char-fork/llama.cpp

git clone https://git.t4t.associates/char-fork/llama.cpp

Charlotte Somenc/dec in server context8300f1411

char/aliceai-t5-moe
4 files

files

CMakeLists.txt724 B
README.md55.6 KiB
completion.cpp37.6 KiB
main.cpp125 B

llama.cpp/tools/completion

This example program allows you to use various LLaMA language models easily and efficiently. It is specifically designed to work with the llama.cpp project, which provides a plain C/C++ implementation with optional 4-bit quantization support for faster, lower memory inference, and is optimized for desktop CPUs. This program can be used to perform various inference tasks with LLaMA models, including generating text based on user-provided prompts and chat-like interactions with reverse prompts.

Table of Contents

  1. Quick Start
  2. Usage
  3. Common Options
  4. Input Prompts
  5. Interaction
  6. Context Management
  7. Generation Flags
  8. Performance Tuning and Memory Options
  9. Additional Options

Quick Start

To get started right away, run the following command, making sure to use the correct path for the model you have:

First, we will need to download a model. In these examples, we will use the Gemma model from the ggml-org repo on Hugging Face. https://huggingface.co/ggml-org/gemma-1.1-7b-it-Q4_K_M-GGUF/resolve/main/gemma-1.1-7b-it.Q4_K_M.gguf?download=true

Once downloaded, place your model in the models folder in llama.cpp.

Unix-based systems (Linux, macOS, etc.):

Input prompt (One-and-done)
./llama-completion -m models/gemma-1.1-7b-it.Q4_K_M.gguf -no-cnv --prompt "Once upon a time"
Conversation mode (Allow for continuous interaction with the model)
./llama-completion -m models/gemma-1.1-7b-it.Q4_K_M.gguf --chat-template gemma
Conversation mode using built-in jinja chat template
./llama-completion -m models/gemma-1.1-7b-it.Q4_K_M.gguf --jinja
One-and-done query using jinja with custom system prompt and a starting prompt
./llama-completion -m models/gemma-1.1-7b-it.Q4_K_M.gguf --jinja --single-turn -sys "You are a helpful assistant" -p "Hello"
Infinite text from a starting prompt (you can use Ctrl-C to stop it):
./llama-completion -m models/gemma-1.1-7b-it.Q4_K_M.gguf --ignore-eos -n -1

Windows:

Input prompt (One-and-done)
./llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf -no-cnv --prompt "Once upon a time"
Conversation mode (Allow for continuous interaction with the model)
./llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --chat-template gemma
Conversation mode using built-in jinja chat template
./llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --jinja
One-and-done query using jinja with custom system prompt and a starting prompt
./llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --jinja --single-turn -sys "You are a helpful assistant" -p "Hello"

Infinite text from a starting prompt (you can use Ctrl-C to stop it):

llama-completion.exe -m models\gemma-1.1-7b-it.Q4_K_M.gguf --ignore-eos -n -1

Usage

<!-- HELP_START --> <!-- IMPORTANT: The list below is auto-generated by llama-gen-docs; do NOT modify it manually -->

Common params

ArgumentExplanation
-h, --help, --usageprint usage and exit
--versionshow version and build info
-cl, --cache-listshow list of models in cache
--completion-bashprint source-able bash completion script for llama.cpp
-t, --threads Nnumber of CPU threads to use during generation (default: -1)<br/>(env: LLAMA_ARG_THREADS)
-tb, --threads-batch Nnumber of threads to use during batch and prompt processing (default: same as --threads)
-C, --cpu-mask MCPU affinity mask: arbitrarily long hex. Complements cpu-range (default: "")
-Cr, --cpu-range lo-hirange of CPUs for affinity. Complements --cpu-mask
--cpu-strict <0|1>use strict CPU placement (default: 0)
--prio Nset process/thread priority : low(-1), normal(0), medium(1), high(2), realtime(3) (default: 0)
--poll <0...100>use polling level to wait for work (0 - no polling, default: 50)
-Cb, --cpu-mask-batch MCPU affinity mask: arbitrarily long hex. Complements cpu-range-batch (default: same as --cpu-mask)
-Crb, --cpu-range-batch lo-hiranges of CPUs for affinity. Complements --cpu-mask-batch
--cpu-strict-batch <0|1>use strict CPU placement (default: same as --cpu-strict)
--prio-batch Nset process/thread priority : 0-normal, 1-medium, 2-high, 3-realtime (default: 0)
--poll-batch <0|1>use polling to wait for work (default: same as --poll)
-c, --ctx-size Nsize of the prompt context (default: 0, 0 = loaded from model)<br/>(env: LLAMA_ARG_CTX_SIZE)
-n, --predict, --n-predict Nnumber of tokens to predict (default: -1, -1 = infinity, -2 = until context filled)<br/>(env: LLAMA_ARG_N_PREDICT)
-b, --batch-size Nlogical maximum batch size (default: 2048)<br/>(env: LLAMA_ARG_BATCH)
-ub, --ubatch-size Nphysical maximum batch size (default: 512)<br/>(env: LLAMA_ARG_UBATCH)
--keep Nnumber of tokens to keep from the initial prompt (default: 0, -1 = all)
--swa-fulluse full-size SWA cache (default: false)<br/>(more info)<br/>(env: LLAMA_ARG_SWA_FULL)
-fa, --flash-attn [on|off|auto]set Flash Attention use ('on', 'off', or 'auto', default: 'auto')<br/>(env: LLAMA_ARG_FLASH_ATTN)
-p, --prompt PROMPTprompt to start generation with; for system message, use -sys
--perf, --no-perfwhether to enable internal libllama performance timings (default: false)<br/>(env: LLAMA_ARG_PERF)
-f, --file FNAMEa file containing the prompt (default: none)
-bf, --binary-file FNAMEbinary file containing the prompt (default: none)
-e, --escape, --no-escapewhether to process escapes sequences (\n, \r, \t, ', ", \) (default: true)
--rope-scaling {none,linear,yarn}RoPE frequency scaling method, defaults to linear unless specified by the model<br/>(env: LLAMA_ARG_ROPE_SCALING_TYPE)
--rope-scale NRoPE context scaling factor, expands context by a factor of N<br/>(env: LLAMA_ARG_ROPE_SCALE)
--rope-freq-base NRoPE base frequency, used by NTK-aware scaling (default: loaded from model)<br/>(env: LLAMA_ARG_ROPE_FREQ_BASE)
--rope-freq-scale NRoPE frequency scaling factor, expands context by a factor of 1/N<br/>(env: LLAMA_ARG_ROPE_FREQ_SCALE)
--yarn-orig-ctx NYaRN: original context size of model (default: 0 = model training context size)<br/>(env: LLAMA_ARG_YARN_ORIG_CTX)
--yarn-ext-factor NYaRN: extrapolation mix factor (default: -1.00, 0.0 = full interpolation)<br/>(env: LLAMA_ARG_YARN_EXT_FACTOR)
--yarn-attn-factor NYaRN: scale sqrt(t) or attention magnitude (default: -1.00)<br/>(env: LLAMA_ARG_YARN_ATTN_FACTOR)
--yarn-beta-slow NYaRN: high correction dim or alpha (default: -1.00)<br/>(env: LLAMA_ARG_YARN_BETA_SLOW)
--yarn-beta-fast NYaRN: low correction dim or beta (default: -1.00)<br/>(env: LLAMA_ARG_YARN_BETA_FAST)
-kvo, --kv-offload, -nkvo, --no-kv-offloadwhether to enable KV cache offloading (default: enabled)<br/>(env: LLAMA_ARG_KV_OFFLOAD)
--repack, -nr, --no-repackwhether to enable weight repacking (default: enabled)<br/>(env: LLAMA_ARG_REPACK)
--no-hostbypass host buffer allowing extra buffers to be used<br/>(env: LLAMA_ARG_NO_HOST)
-ctk, --cache-type-k TYPEKV cache data type for K<br/>allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1<br/>(default: f16)<br/>(env: LLAMA_ARG_CACHE_TYPE_K)
-ctv, --cache-type-v TYPEKV cache data type for V<br/>allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1<br/>(default: f16)<br/>(env: LLAMA_ARG_CACHE_TYPE_V)
-dt, --defrag-thold NKV cache defragmentation threshold (DEPRECATED)<br/>(env: LLAMA_ARG_DEFRAG_THOLD)
-np, --parallel Nnumber of parallel sequences to decode (default: 1)<br/>(env: LLAMA_ARG_N_PARALLEL)
--rpc SERVERScomma-separated list of RPC servers (host:port)<br/>(env: LLAMA_ARG_RPC)
-lm, --load-mode MODEmodel loading mode (default: auto)<br/>- auto: mmap, unless a device does not support it<br/>- none: no special loading mode<br/>- mmap: memory-map model (if mmap disabled, slower load but may reduce pageouts if not using mlock)<br/>- mlock: force system to keep model in RAM rather than swapping or compressing<br/>- mmap+mlock: mmap + force system to keep model in RAM rather than swapping or compressing<br/>- dio: use DirectIO if available<br/><br/>(env: LLAMA_ARG_LOAD_MODE)
-lzm, --lazy-mode MODEon-demand reading of certain tensors, for example per-layer embeddings (default: auto)<br/>- on: read the rows of such tensors from disk on demand instead of keeping them resident (requires mmap)<br/>- auto: on, but only for tensors larger than 4 GiB<br/>- off: always keep them resident<br/>(env: LLAMA_ARG_LAZY_MODE)
--numa TYPEattempt optimizations that help on some NUMA systems<br/>- distribute: spread execution evenly over all nodes<br/>- isolate: only spawn threads on CPUs on the node that execution started on<br/>- numactl: use the CPU map provided by numactl<br/>if run without this previously, it is recommended to drop the system page cache before using this<br/>see https://github.com/ggml-org/llama.cpp/issues/1437<br/>(env: LLAMA_ARG_NUMA)
-dev, --device <dev1,dev2,..>comma-separated list of devices to use for offloading (none = don't offload)<br/>use --list-devices to see a list of available devices<br/>(env: LLAMA_ARG_DEVICE)
--list-devicesprint list of available devices and exit
-ot, --override-tensor <tensor name pattern>=<buffer type>,...override tensor buffer type<br/>(env: LLAMA_ARG_OVERRIDE_TENSOR)
-cmoe, --cpu-moekeep all Mixture of Experts (MoE) weights in the CPU<br/>(env: LLAMA_ARG_CPU_MOE)
-ncmoe, --n-cpu-moe Nkeep the Mixture of Experts (MoE) weights of the first N layers in the CPU<br/>(env: LLAMA_ARG_N_CPU_MOE)
-ncffn, --n-cpu-ffn Nkeep the dense FFN weights of the first N layers in the CPU<br/>(dense models; for MoE expert weights use --n-cpu-moe)<br/>(env: LLAMA_ARG_N_CPU_FFN)
-ngl, --gpu-layers, --n-gpu-layers Nmax. number of layers to store in VRAM, either an exact number, 'auto', or 'all' (default: auto)<br/>(env: LLAMA_ARG_N_GPU_LAYERS)
-sm, --split-mode {none,layer,row,tensor}how to split the model across multiple GPUs, one of:<br/>- none: use one GPU only<br/>- layer (default): split layers and KV across GPUs (pipelined)<br/>- row: split weight across GPUs by rows (parallelized)<br/>- tensor: split weights and KV across GPUs (parallelized, EXPERIMENTAL)<br/>(env: LLAMA_ARG_SPLIT_MODE)
-ts, --tensor-split N0,N1,N2,...fraction of the model to offload to each GPU, comma-separated list of proportions, e.g. 3,1<br/>(env: LLAMA_ARG_TENSOR_SPLIT)
-mg, --main-gpu INDEXthe GPU to use for the model (with split-mode = none), or for intermediate results and KV (with split-mode = row) (default: 0)<br/>(env: LLAMA_ARG_MAIN_GPU)
-fit, --fit [on|off]whether to adjust unset arguments to fit in device memory ('on' or 'off', default: 'on')<br/>(env: LLAMA_ARG_FIT)
-fitt, --fit-target MiB0,MiB1,MiB2,...target margin per device for --fit, comma-separated list of values, single value is broadcast across all devices, default: 1024<br/>(env: LLAMA_ARG_FIT_TARGET)
-fitc, --fit-ctx Nminimum ctx size that can be set by --fit option, default: 4096<br/>(env: LLAMA_ARG_FIT_CTX)
--check-tensorscheck model tensor data for invalid values (default: false)
--override-kv KEY=TYPE:VALUE,...advanced option to override model metadata by key. to specify multiple overrides, either use comma-separated values.<br/>types: int, float, bool, str. example: --override-kv tokenizer.ggml.add_bos_token=bool:false,tokenizer.ggml.add_eos_token=bool:false
--op-offload, --no-op-offloadwhether to offload host tensor operations to device (default: true)
--lora FNAMEpath to LoRA adapter (use comma-separated values to load multiple adapters)
--lora-scaled FNAME:SCALE,...path to LoRA adapter with user defined scaling (format: FNAME:SCALE,...)<br/>note: use comma-separated values
--control-vector FNAMEadd a control vector<br/>note: use comma-separated values to add multiple control vectors
--control-vector-scaled FNAME:SCALE,...add a control vector with user defined scaling SCALE<br/>note: use comma-separated values (format: FNAME:SCALE,...)
--control-vector-layer-range START ENDlayer range to apply the control vector(s) to, start and end inclusive
-m, --model FNAMEmodel path to load<br/>(env: LLAMA_ARG_MODEL)
-mu, --model-url MODEL_URLmodel download url (default: unused)<br/>(env: LLAMA_ARG_MODEL_URL)
-dr, --docker-repo [<repo>/]<model>[:quant]Docker Hub model repository. repo is optional, default to ai/. quant is optional, default to :latest.<br/>example: gemma3<br/>(default: unused)<br/>(env: LLAMA_ARG_DOCKER_REPO)
-hf, -hfr, --hf-repo <user>/<model>[:quant]Hugging Face model repository; quant is optional, case-insensitive, default to Q4_K_M, or falls back to the first file in the repo if Q4_K_M doesn't exist.<br/>mmproj is also downloaded automatically if available. to disable, add --no-mmproj<br/>example: ggml-org/GLM-4.7-Flash-GGUF:Q4_K_M<br/>(default: unused)<br/>(env: LLAMA_ARG_HF_REPO)
-hff, --hf-file FILEHugging Face model file. If specified, it will override the quant in --hf-repo (default: unused)<br/>(env: LLAMA_ARG_HF_FILE)
-hft, --hf-token TOKENHugging Face access token (default: value from HF_TOKEN environment variable)<br/>(env: HF_TOKEN)
--log-disableLog disable
--log-file FNAMELog to file<br/>(env: LLAMA_ARG_LOG_FILE)
--log-jsonl, --no-log-jsonlLog as JSONL (one JSON object per line) to stdout, this also disables colored logging (default: disabled)<br/>(env: LLAMA_ARG_LOG_JSONL)
--log-colors [on|off|auto]Set colored logging ('on', 'off', or 'auto', default: 'auto')<br/>'auto' enables colors when output is to a terminal<br/>(env: LLAMA_ARG_LOG_COLORS)
-v, --verbose, --log-verboseSet verbosity level to infinity (i.e. log all messages, useful for debugging)
--offlineOffline mode: forces use of cache, prevents network access<br/>(env: LLAMA_ARG_OFFLINE)
-lv, --verbosity, --log-verbosity NSet the verbosity threshold. Messages with a higher verbosity will be ignored. Values:<br/> - 0: generic output<br/> - 1: error<br/> - 2: warning<br/> - 3: info<br/> - 4: trace (more info)<br/> - 5: debug<br/>(default: 3)<br/><br/>(env: LLAMA_ARG_LOG_VERBOSITY)
--log-prefix, --no-log-prefixEnable prefix in log messages<br/>(env: LLAMA_ARG_LOG_PREFIX)
--log-timestamps, --no-log-timestampsEnable timestamps in log messages<br/>(env: LLAMA_ARG_LOG_TIMESTAMPS)
--spec-draft-type-k, -ctkd, --cache-type-k-draft TYPEKV cache data type for K for the draft model<br/>allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1<br/>(default: f16)<br/>(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_K)
--spec-draft-type-v, -ctvd, --cache-type-v-draft TYPEKV cache data type for V for the draft model<br/>allowed values: f32, f16, bf16, q8_0, q4_0, q4_1, iq4_nl, q5_0, q5_1<br/>(default: f16)<br/>(env: LLAMA_ARG_SPEC_DRAFT_CACHE_TYPE_V)

Sampling params

ArgumentExplanation
--samplers SAMPLERSsamplers that will be used for generation in the order, separated by ';'<br/>(default: penalties;dry;top_n_sigma;top_k;typ_p;top_p;min_p;xtc;temperature)
-s, --seed SEEDRNG seed (default: -1, use random seed for -1)
--sampler-seq, --sampling-seq SEQUENCEsimplified sequence for samplers that will be used (default: edskypmxt)
--ignore-eosignore end of stream token and continue generating (implies --logit-bias EOS-inf)
--temp, --temperature Ntemperature (default: 0.80)
--top-k Ntop-k sampling (default: 40, 0 = disabled)<br/>(env: LLAMA_ARG_TOP_K)
--top-p Ntop-p sampling (default: 0.95, 1.0 = disabled)
--min-p Nmin-p sampling (default: 0.05, 0.0 = disabled)
--top-nsigma, --top-n-sigma Ntop-n-sigma sampling (default: -1.00, -1.0 = disabled)
--xtc-probability Nxtc probability (default: 0.00, 0.0 = disabled)
--xtc-threshold Nxtc threshold (default: 0.10, 1.0 = disabled)
--typical, --typical-p Nlocally typical sampling, parameter p (default: 1.00, 1.0 = disabled)
--repeat-last-n Nlast n tokens to consider for penalize (default: 64, 0 = disabled)
--repeat-penalty Npenalize repeat sequence of tokens (default: 1.00, 1.0 = disabled)
--presence-penalty Nrepeat alpha presence penalty (default: 0.00, 0.0 = disabled)
--frequency-penalty Nrepeat alpha frequency penalty (default: 0.00, 0.0 = disabled)
--dry-multiplier Nset DRY sampling multiplier (default: 0.00, 0.0 = disabled)
--dry-base Nset DRY sampling base value (default: 1.75)
--dry-allowed-length Nset allowed length for DRY sampling (default: 2)
--dry-penalty-last-n Nset DRY penalty for the last n tokens (default: 64, 0 = disable)
--dry-sequence-breaker STRINGadd sequence breaker for DRY sampling, clearing out default breakers ('\n', ':', '"', '*') in the process; use "none" to not use any sequence breakers
--adaptive-target Nadaptive-p: select tokens near this probability (valid range 0.0 to 1.0; negative = disabled) (default: -1.00)<br/>(more info)
--adaptive-decay Nadaptive-p: decay rate for target adaptation over time. lower values are more reactive, higher values are more stable.<br/>(valid range 0.0 to 0.99) (default: 0.90)
--dynatemp-range Ndynamic temperature range (default: 0.00, 0.0 = disabled)
--dynatemp-exp Ndynamic temperature exponent (default: 1.00)
--mirostat Nuse Mirostat sampling.<br/>Top K, Nucleus and Locally Typical samplers are ignored if used.<br/>(default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0)
--mirostat-lr NMirostat learning rate, parameter eta (default: 0.10)
--mirostat-ent NMirostat target entropy, parameter tau (default: 5.00)
-l, --logit-bias TOKEN_ID(+/-)BIASmodifies the likelihood of token appearing in the completion,<br/>i.e. --logit-bias 15043+1 to increase likelihood of token ' Hello',<br/>or --logit-bias 15043-1 to decrease likelihood of token ' Hello'
--grammar GRAMMARBNF-like grammar to constrain generations (see samples in grammars/ dir)
--grammar-file FNAMEfile to read grammar from
-j, --json-schema SCHEMAJSON schema to constrain generations (https://json-schema.org/), e.g. {"type": "object"} for any JSON object
-jf, --json-schema-file FILEFile containing a JSON schema to constrain generations (https://json-schema.org/), e.g. {"type": "object"} for any JSON object
-bs, --backend-samplingenable backend sampling (experimental) (default: disabled)<br/>(env: LLAMA_ARG_BACKEND_SAMPLING)

Completion-specific params

ArgumentExplanation
--verbose-promptprint a verbose prompt before generation (default: false)
--display-prompt, --no-display-promptwhether to print prompt at generation (default: true)
-co, --color [on|off|auto]Colorize output to distinguish prompt and user input from generations ('on', 'off', or 'auto', default: 'auto')<br/>'auto' enables colors when output is to a terminal
--context-shift, --no-context-shiftwhether to use context shift on infinite text generation (default: disabled)<br/>(env: LLAMA_ARG_CONTEXT_SHIFT)
-sys, --system-prompt PROMPTsystem prompt to use with model (if applicable, depending on chat template)
-sysf, --system-prompt-file FNAMEa file containing the system prompt (default: none)
-ptc, --print-token-count Nprint token count every N tokens (default: -1)
--prompt-cache FNAMEfile to cache prompt state for faster startup (default: none)
--prompt-cache-allif specified, saves user input and generations to cache as well
--prompt-cache-roif specified, uses the prompt cache but does not update it
-r, --reverse-prompt PROMPThalt generation at PROMPT, return control in interactive mode
-sp, --specialspecial tokens output enabled (default: false)
-cnv, --conversation, -no-cnv, --no-conversationwhether to run in conversation mode:<br/>- does not print special tokens and suffix/prefix<br/>- interactive mode is also enabled<br/>(default: auto enabled if chat template is available)
-st, --single-turnrun conversation for a single turn only, then exit when done<br/>will not be interactive if first turn is predefined with --prompt<br/>(default: false)
-i, --interactiverun in interactive mode (default: false)
-if, --interactive-firstrun in interactive mode and wait for input right away (default: false)
-mli, --multiline-inputallows you to write or paste multiple lines without ending each in ''
--in-prefix-bosprefix BOS to user inputs, preceding the --in-prefix string
--in-prefix STRINGstring to prefix user inputs with (default: empty)
--in-suffix STRINGstring to suffix after user inputs with (default: empty)
--warmup, --no-warmupwhether to perform warmup with an empty run (default: enabled)
-gan, --grp-attn-n Ngroup-attention factor (default: 1)<br/>(env: LLAMA_ARG_GRP_ATTN_N)
-gaw, --grp-attn-w Ngroup-attention width (default: 512)<br/>(env: LLAMA_ARG_GRP_ATTN_W)
--jinja, --no-jinjawhether to use jinja template engine for chat (default: disabled)<br/>(env: LLAMA_ARG_JINJA)
--reasoning-format FORMATcontrols whether thought tags are allowed and/or extracted from the response, and in which format they're returned; one of:<br/>- none: leaves thoughts unparsed in message.content<br/>- deepseek: puts thoughts in message.reasoning_content<br/>- deepseek-legacy: keeps <think> tags in message.content while also populating message.reasoning_content<br/>(default: auto)<br/>(env: LLAMA_ARG_THINK)
-rea, --reasoning [on|off|auto]Use reasoning/thinking in the chat ('on', 'off', or 'auto', default: 'auto' (detect from template))<br/>(env: LLAMA_ARG_REASONING)
--reasoning-effort LEVELreasoning effort level given to the chat template: 'default' to keep the template default,<br/>or a level such as 'minimal', 'low', 'medium', 'high', 'xhigh' or 'max' (default: default)<br/>(env: LLAMA_ARG_REASONING_EFFORT)
--reasoning-budget Ntoken budget for thinking: -1 for unrestricted, 0 for immediate end, N>0 for token budget (default: -1)<br/>(env: LLAMA_ARG_THINK_BUDGET)
--reasoning-budget-message MESSAGEmessage injected before the end-of-thinking tag when reasoning budget is exhausted (default: none)<br/>(env: LLAMA_ARG_THINK_BUDGET_MESSAGE)
--reasoning-preserve, --no-reasoning-preservepreserve reasoning trace in the full history, not just the last assistant message (default: enabled)<br/>compatible with certain templates having 'supports_preserve_reasoning' capability<br/>example: https://docs.z.ai/guides/capabilities/thinking-mode#preserved-thinking<br/>(env: LLAMA_ARG_REASONING_PRESERVE)
--chat-template JINJA_TEMPLATEset custom jinja chat template (default: template taken from model's metadata)<br/>if suffix/prefix are specified, template will be disabled<br/>only commonly used templates are accepted (unless --jinja is set before this flag):<br/>list of built-in templates:<br/>bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr<br/>(env: LLAMA_ARG_CHAT_TEMPLATE)
--chat-template-file JINJA_TEMPLATE_FILEset custom jinja chat template file (default: template taken from model's metadata)<br/>if suffix/prefix are specified, template will be disabled<br/>only commonly used templates are accepted (unless --jinja is set before this flag):<br/>list of built-in templates:<br/>bailing, bailing-think, bailing2, chatglm3, chatglm4, chatml, command-r, deepseek, deepseek-ocr, deepseek2, deepseek3, exaone-moe, exaone3, exaone4, falcon3, gemma, gigachat, glmedge, gpt-oss, granite, granite-4.0, granite-4.1, grok-2, hunyuan-dense, hunyuan-moe, hunyuan-vl, kimi-k2, llama2, llama2-sys, llama2-sys-bos, llama2-sys-strip, llama3, llama4, megrez, minicpm, mistral-v1, mistral-v3, mistral-v3-tekken, mistral-v7, mistral-v7-tekken, monarch, openchat, orion, pangu-embedded, phi3, phi4, rwkv-world, seed_oss, smolvlm, solar-open, vicuna, vicuna-orca, yandex, zephyr<br/>(env: LLAMA_ARG_CHAT_TEMPLATE_FILE)
--skip-chat-parsing, --no-skip-chat-parsingforce a pure content parser, even if a Jinja template is specified; model will output everything in the content section, including any reasoning and/or tool calls (default: disabled)<br/>(env: LLAMA_ARG_SKIP_CHAT_PARSING)
--simple-iouse basic IO for better compatibility in subprocesses and limited consoles
<!-- HELP_END -->

Common Options

In this section, we cover the most commonly used options for running the llama-completion program with the LLaMA models:

Input Prompts

The llama-completion program provides several ways to interact with the LLaMA models using input prompts:

Interaction

The llama-completion program offers a seamless way to interact with LLaMA models, allowing users to engage in real-time conversations or provide instructions for specific tasks. The interactive mode can be triggered using various options, including --interactive and --interactive-first.

In interactive mode, users can participate in text generation by injecting their input during the process. Users can press Ctrl+C at any time to interject and type their input, followed by pressing Return to submit it to the LLaMA model. To submit additional lines without finalizing input, users can end the current line with a backslash (\) and continue typing.

Interaction Options

By understanding and utilizing these interaction options, you can create engaging and dynamic experiences with the LLaMA models, tailoring the text generation process to your specific needs.

Reverse Prompts

Reverse prompts are a powerful way to create a chat-like experience with a LLaMA model by pausing the text generation when specific text strings are encountered:

To overcome this limitation, you can use the --in-prefix flag to add a space or any other characters after the reverse prompt.

In-Prefix

The --in-prefix flag is used to add a prefix to your input, primarily, this is used to insert a space after the reverse prompt. Here's an example of how to use the --in-prefix flag in conjunction with the --reverse-prompt flag:

./llama-completion -r "User:" --in-prefix " "

In-Suffix

The --in-suffix flag is used to add a suffix after your input. This is useful for adding an "Assistant:" prompt after the user's input. It's added after the new-line character (\n) that's automatically added to the end of the user's input. Here's an example of how to use the --in-suffix flag in conjunction with the --reverse-prompt flag:

./llama-completion -r "User:" --in-prefix " " --in-suffix "Assistant:"

When --in-prefix or --in-suffix options are enabled the chat template ( --chat-template ) is disabled

Chat templates

--chat-template JINJA_TEMPLATE: This option sets a custom jinja chat template. It accepts a string, not a file name. Default: template taken from model's metadata. Llama.cpp only supports some pre-defined templates. These include llama2, llama3, gemma, monarch, chatml, orion, vicuna, vicuna-orca, deepseek, command-r, zephyr. When --in-prefix or --in-suffix options are enabled the chat template ( --chat-template ) is disabled.

Example usage: --chat-template gemma

--chat-template-file FNAME: Load a custom jinja chat template from an external file, useful if the model contains outdated or incompatible template, some examples can be found in models/templates. Up-to-date chat templates can be downloaded from Hugging Face using scripts/get_chat_template.py

Context Management

During text generation, LLaMA models have a limited context size, which means they can only consider a certain number of tokens from the input and generated text. When the context fills up, the model resets internally, potentially losing some information from the beginning of the conversation or instructions. Context management options help maintain continuity and coherence in these situations.

Context Size

Extended Context Size

Some fine-tuned models have extended the context length by scaling RoPE. For example, if the original pre-trained model has a context length (max sequence length) of 4096 (4k) and the fine-tuned model has 32k. That is a scaling factor of 8, and should work by setting the above --ctx-size to 32768 (32k) and --rope-scale to 8.

Keep Prompt

The --keep option allows users to retain the original prompt when the model runs out of context, ensuring a connection to the initial instruction or conversation topic is maintained.

By utilizing context management options like --ctx-size and --keep, you can maintain a more coherent and consistent interaction with the LLaMA models, ensuring that the generated text remains relevant to the original prompt or conversation.

Generation Flags

The following options allow you to control the text generation process and fine-tune the diversity, creativity, and quality of the generated text according to your needs. By adjusting these options and experimenting with different combinations of values, you can find the best settings for your specific use case.

Number of Tokens to Predict

The --predict option controls the number of tokens the model generates in response to the input prompt. By adjusting this value, you can influence the length of the generated text. A higher value will result in longer text, while a lower value will produce shorter text.

A value of -1 will enable infinite text generation, even though we have a finite context window. When the context window is full, some of the earlier tokens (half of the tokens after --keep) will be discarded. The context must then be re-evaluated before generation can resume. On large models and/or large context windows, this will result in a significant pause in output.

If the pause is undesirable, a value of -2 will stop generation immediately when the context is filled.

The --no-context-shift option allows you to stop the infinite text generation once the finite context window is full.

It is important to note that the generated text may be shorter than the specified number of tokens if an End-of-Sequence (EOS) token or a reverse prompt is encountered. In interactive mode, text generation will pause and control will be returned to the user. In non-interactive mode, the program will end. In both cases, the text generation may stop before reaching the specified --predict value. If you want the model to keep going without ever producing End-of-Sequence on its own, you can use the --ignore-eos parameter.

Temperature

Temperature is a hyperparameter that controls the randomness of the generated text. It affects the probability distribution of the model's output tokens. A higher temperature (e.g., 1.5) makes the output more random and creative, while a lower temperature (e.g., 0.5) makes the output more focused, deterministic, and conservative. The default value is 0.8, which provides a balance between randomness and determinism. At the extreme, a temperature of 0 will always pick the most likely next token, leading to identical outputs in each run.

Example usage: --temp 0

Repeat Penalty

The repeat-penalty option helps prevent the model from generating repetitive or monotonous text. A higher value (e.g., 1.5) will penalize repetitions more strongly, while a lower value (e.g., 0.9) will be more lenient. The default value is 1.

The repeat-last-n option controls the number of tokens in the history to consider for penalizing repetition. A larger value will look further back in the generated text to prevent repetitions, while a smaller value will only consider recent tokens. A value of 0 disables the penalty.

DRY Repetition Penalty

DRY (Don't Repeat Yourself) sampling is an effective technique for reducing repetition in generated text even across long contexts by penalizing tokens based on their recent usage patterns (original PR link).

The dry-multiplier option controls the strength of the DRY sampling effect. A value of 0.0 disables DRY sampling, while higher values increase its influence. A typical recommended value is 0.8.

The dry-base option sets the base value for the exponential penalty calculation in DRY sampling. Higher values lead to more aggressive penalization of repetitions.

The dry-allowed-length option sets the maximum length of repeated sequences that will not be penalized. Repetitions shorter than or equal to this length are not penalized, allowing for natural repetitions of short phrases or common words.

The dry-penalty-last-n option controls how many recent tokens to consider when applying the DRY penalty. A value of 0 disables the penalty. Use a positive value to limit the consideration to a specific number of recent tokens.

The dry-sequence-breaker option adds a single sequence breaker and can be used more than once to specify multiple sequence breakers. Sequence breakers interrupt sequence matching and break the input into parts where matching can be applied.

DRY sampling provides more nuanced control over text generation, particularly for reducing long-range repetitions and maintaining global coherence.

Example usage: --dry-multiplier 0.8 --dry-base 1.75 --dry-allowed-length 2 --dry-penalty-last-n 64 --dry-sequence-breaker "—" --dry-sequence-breaker "##"

Top-K Sampling

Top-k sampling is a text generation method that selects the next token only from the top k most likely tokens predicted by the model. It helps reduce the risk of generating low-probability or nonsensical tokens, but it may also limit the diversity of the output. A higher value for top-k (e.g., 100) will consider more tokens and lead to more diverse text, while a lower value (e.g., 10) will focus on the most probable tokens and generate more conservative text. The default value is 40.

Example usage: --top-k 30

Top-P Sampling

Top-p sampling, also known as nucleus sampling, is another text generation method that selects the next token from a subset of tokens that together have a cumulative probability of at least p. This method provides a balance between diversity and quality by considering both the probabilities of tokens and the number of tokens to sample from. A higher value for top-p (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text. The default value is 0.9.

Example usage: --top-p 0.95

Min-P Sampling

The Min-P sampling method was designed as an alternative to Top-P, and aims to ensure a balance of quality and variety. The parameter p represents the minimum probability for a token to be considered, relative to the probability of the most likely token. For example, with p=0.05 and the most likely token having a probability of 0.9, logits with a value less than 0.045 are filtered out.

Example usage: --min-p 0.05

Adaptive-P Sampling

Adaptive-P: Select tokens near a configurable target probability over time.

The adaptive-p sampler transforms the token probability distribution to favor tokens that fall near a user-configurable probability target. Internally, the sampler maintains an exponential moving average of the ORIGINAL probabilities of selected tokens at each sampling step. It uses this EMA to compute an adapted target probability at each sampling step, thus maintaining the desired target probability over time. Only mild truncation before this sampler is recommended. It is suggested to apply min-p before adaptive-p as the only other active sampler.

Recommended starting values: --adaptive-target 0.55 --adaptive-decay 0.9

For more info, refer to: llama.cpp#17927

Locally Typical Sampling

Locally typical sampling promotes the generation of contextually coherent and diverse text by sampling tokens that are typical or expected based on the surrounding context. By setting the parameter p between 0 and 1, you can control the balance between producing text that is locally coherent and diverse. A value closer to 1 will promote more contextually coherent tokens, while a value closer to 0 will promote more diverse tokens. A value equal to 1 disables locally typical sampling.

Example usage: --typical 0.9

Mirostat Sampling

Mirostat is an algorithm that actively maintains the quality of generated text within a desired range during text generation. It aims to strike a balance between coherence and diversity, avoiding low-quality output caused by excessive repetition (boredom traps) or incoherence (confusion traps).

The --mirostat-lr option sets the Mirostat learning rate (eta). The learning rate influences how quickly the algorithm responds to feedback from the generated text. A lower learning rate will result in slower adjustments, while a higher learning rate will make the algorithm more responsive. The default value is 0.1.

The --mirostat-ent option sets the Mirostat target entropy (tau), which represents the desired perplexity value for the generated text. Adjusting the target entropy allows you to control the balance between coherence and diversity in the generated text. A lower value will result in more focused and coherent text, while a higher value will lead to more diverse and potentially less coherent text. The default value is 5.0.

Example usage: --mirostat 2 --mirostat-lr 0.05 --mirostat-ent 3.0

XTC Sampling

Exclude Top Choices (XTC) is a unique sampler that is designed to remove top tokens from consideration and avoid more obvious and repetitive outputs. With a chance of xtc-probability it searches for tokens with probabilities of xtc-threshold and above, then removes all such tokens except the least probable one.

By removing top tokens XTC can improve the variety of answers, break writing clichés and inhibit repetition, since clichés and repeated phrases are usually more likely to appear. By keeping the last token above the threshold, XTC ensures that the answer is still coherent. XTC is meant to be used for creative tasks, but feel free to experiment with different settings for different models.

Being experimental and unique, XTC is disabled by default. The recommended combination of samplers is Min-P followed by XTC on its default settings: --sampling-seq mx --min-p 0.02 --xtc-probability 0.5.

Example usage: --xtc-probability 0.5 --xtc-threshold 0.1

Top-nσ Sampling

Top-nσ sampling is a text generation method that selects tokens based on a statistical threshold in pre-softmax logits. It works by only sampling from tokens with logits that are within n * σ of the maximum logit. This method helps maintain a stable sampling space regardless of temperature scaling, allowing it to perform well on reasoning tasks even in high temperatures. Without complex probability manipulation, it efficiently filters tokens directly on the pre-softmax logits. A higher value for top-nsigma (e.g., 5) will take more noisy tokens into consideration, while a lower value (e.g., 1) will focous on the more informative region of the sampling space.

Example usage: --top-nsigma 1

Logit Bias

The logit bias option allows you to manually adjust the likelihood of specific tokens appearing in the generated text. By providing a token ID and a positive or negative bias value, you can increase or decrease the probability of that token being generated.

For example, use --logit-bias 15043+1 to increase the likelihood of the token 'Hello', or --logit-bias 15043-1 to decrease its likelihood. Using a value of negative infinity, --logit-bias 15043-inf ensures that the token Hello is never produced.

A more practical use case might be to prevent the generation of \code{begin} and \code{end} by setting the \ token (29905) to negative infinity with -l 29905-inf. (This is due to the prevalence of LaTeX codes that show up in LLaMA model inference.)

Example usage: --logit-bias 29905-inf

RNG Seed

The RNG seed is used to initialize the random number generator that influences the text generation process. By setting a specific seed value, you can obtain consistent and reproducible results across multiple runs with the same input and settings. This can be helpful for testing, debugging, or comparing the effects of different options on the generated text to see when they diverge. If the seed is set to a value less than 0, a random seed will be used, which will result in different outputs on each run.

Performance Tuning and Memory Options

These options help improve the performance and memory usage of the LLaMA models. By adjusting these settings, you can fine-tune the model's behavior to better suit your system's capabilities and achieve optimal performance for your specific use case.

Number of Threads

Model Loading Mode

NUMA support

These flags attempt optimizations that help on some systems with non-uniform memory access. This currently consists of one of the above strategies, and disabling prefetch and readahead for mmap. The latter causes mapped pages to be faulted in on first access instead of all at once, and in combination with pinning threads to NUMA nodes, more of the pages end up on the NUMA node where they are used. Note that if the model is already in the system page cache, for example because of a previous run without this option, this will have little effect unless you drop the page cache first. This can be done by rebooting the system or on Linux by writing '3' to '/proc/sys/vm/drop_caches' as root.

Batch Size

Prompt Caching

Grammars & JSON schemas

Quantization

For information about 4-bit quantization, which can significantly improve performance and reduce memory usage, please refer to llama.cpp's primary README.

LoRA (Low-Rank Adaptation) adapters

You can add LoRA adapters using --lora or --lora-scaled. For example: --lora my_adapter_1.gguf --lora my_adapter_2.gguf ... or --lora-scaled lora_task_A.gguf 0.5 --lora-scaled lora_task_B.gguf 0.5.

LoRA adapters should be in GGUF format. To convert from Hugging Face format use the convert-lora-to-gguf.py script. LoRA adapters are loaded separately and applied during inference - they are not merged with the main model. This means that mmap model loading is fully supported when using LoRA adapters. The old --lora-base flag has been removed now that merging is no longer performed.

Additional Options

These options provide extra functionality and customization when running the LLaMA models: