Skip to content

Distribute and run LLMs with a single file.

Add llama-bench command (cpu mode only)

Justine Tunney9206719486ea
diff --git a/llama.cpp/BUILD.mk b/llama.cpp/BUILD.mk
index 22443b02..735488b9 100644
--- a/llama.cpp/BUILD.mk
+++ b/llama.cpp/BUILD.mk
@@ -24,6 +24,7 @@ include llama.cpp/main/BUILD.mk
include llama.cpp/imatrix/BUILD.mk
include llama.cpp/quantize/BUILD.mk
include llama.cpp/perplexity/BUILD.mk
+include llama.cpp/llama-bench/BUILD.mk
$(LLAMA_CPP_OBJS): private \
CCFLAGS += \
@@ -66,4 +67,5 @@ o/$(MODE)/llama.cpp: \
o/$(MODE)/llama.cpp/server \
o/$(MODE)/llama.cpp/imatrix \
o/$(MODE)/llama.cpp/quantize \
- o/$(MODE)/llama.cpp/perplexity
+ o/$(MODE)/llama.cpp/perplexity \
+ o/$(MODE)/llama.cpp/llama-bench
diff --git a/llama.cpp/common.cpp b/llama.cpp/common.cpp
index 1c801035..e1313a8b 100644
--- a/llama.cpp/common.cpp
+++ b/llama.cpp/common.cpp
@@ -162,7 +162,7 @@ static int count_math_cpus(int cpu_count) {
/**
* Returns number of CPUs on system that are useful for math.
*/
-int get_math_cpu_count() {
+int cpu_get_num_math() {
#if defined(__x86_64__) && (defined(__linux__) || defined(__COSMOPOLITAN__)) && !defined(__ANDROID__)
int cpu_count = sysconf(_SC_NPROCESSORS_ONLN);
if (cpu_count < 1) {
diff --git a/llama.cpp/common.h b/llama.cpp/common.h
index e58fb1c4..1fdbc7d3 100644
--- a/llama.cpp/common.h
+++ b/llama.cpp/common.h
@@ -46,7 +46,7 @@ extern char const *LLAMA_BUILD_TARGET;
struct llama_control_vector_load_info;
-int get_math_cpu_count();
+int cpu_get_num_math();
int32_t get_num_physical_cores();
//
@@ -56,7 +56,7 @@ int32_t get_num_physical_cores();
struct gpt_params {
uint32_t seed = LLAMA_DEFAULT_SEED; // RNG seed
- int32_t n_threads = get_math_cpu_count();
+ int32_t n_threads = cpu_get_num_math();
int32_t n_threads_draft = -1;
int32_t n_threads_batch = -1; // number of threads to use for batch processing (-1 = use n_threads)
int32_t n_threads_batch_draft = -1;
diff --git a/llama.cpp/llama-bench/BUILD.mk b/llama.cpp/llama-bench/BUILD.mk
new file mode 100644
index 00000000..e31ff7d7
--- /dev/null
+++ b/llama.cpp/llama-bench/BUILD.mk
@@ -0,0 +1,18 @@
+#-*-mode:makefile-gmake;indent-tabs-mode:t;tab-width:8;coding:utf-8-*-┐
+#── vi: set noet ft=make ts=8 sw=8 fenc=utf-8 :vi ────────────────────┘
+
+PKGS += LLAMA_CPP_LLAMA-BENCH
+
+LLAMA_CPP_LLAMA_BENCH_FILES := $(wildcard llama.cpp/llama-bench/*)
+LLAMA_CPP_LLAMA_BENCH_SRCS = $(filter %.cpp,$(LLAMA_CPP_LLAMA_BENCH_FILES))
+LLAMA_CPP_LLAMA_BENCH_OBJS = $(LLAMA_CPP_LLAMA_BENCH_SRCS:%.cpp=o/$(MODE)/%.o)
+
+o/$(MODE)/llama.cpp/llama-bench/llama-bench: \
+ o/$(MODE)/llama.cpp/llama-bench/llama-bench.o \
+ o/$(MODE)/llama.cpp/llama.cpp.a
+
+$(LLAMA_CPP_LLAMA_BENCH_OBJS): llama.cpp/llama-bench/BUILD.mk
+
+.PHONY: o/$(MODE)/llama.cpp/llama-bench
+o/$(MODE)/llama.cpp/llama-bench: \
+ o/$(MODE)/llama.cpp/llama-bench/llama-bench
diff --git a/llama.cpp/llama-bench/README.md b/llama.cpp/llama-bench/README.md
new file mode 100644
index 00000000..e381ea4c
--- /dev/null
+++ b/llama.cpp/llama-bench/README.md
@@ -0,0 +1,339 @@
+# llama.cpp/example/main
+
+This example program allows you to use various LLaMA language models in an easy and efficient way. It is specifically designed to work with the [llama.cpp](https://github.com/ggerganov/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](#quick-start)
+2. [Common Options](#common-options)
+3. [Input Prompts](#input-prompts)
+4. [Interaction](#interaction)
+5. [Context Management](#context-management)
+6. [Generation Flags](#generation-flags)
+7. [Performance Tuning and Memory Options](#performance-tuning-and-memory-options)
+8. [Additional Options](#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:
+
+#### Unix-based systems (Linux, macOS, etc.):
+
+```bash
+./main -m models/7B/ggml-model.bin --prompt "Once upon a time"
+```
+
+#### Windows:
+
+```powershell
+main.exe -m models\7B\ggml-model.bin --prompt "Once upon a time"
+```
+
+For an interactive experience, try this command:
+
+#### Unix-based systems (Linux, macOS, etc.):
+
+```bash
+./main -m models/7B/ggml-model.bin -n -1 --color -r "User:" --in-prefix " " -i -p \
+'User: Hi
+AI: Hello. I am an AI chatbot. Would you like to talk?
+User: Sure!
+AI: What would you like to talk about?
+User:'
+```
+
+#### Windows:
+
+```powershell
+main.exe -m models\7B\ggml-model.bin -n -1 --color -r "User:" --in-prefix " " -i -e -p "User: Hi\nAI: Hello. I am an AI chatbot. Would you like to talk?\nUser: Sure!\nAI: What would you like to talk about?\nUser:"
+```
+
+The following command generates "infinite" text from a starting prompt (you can use `Ctrl-C` to stop it):
+
+#### Unix-based systems (Linux, macOS, etc.):
+
+```bash
+./main -m models/7B/ggml-model.bin --ignore-eos -n -1 --random-prompt
+```
+
+#### Windows:
+
+```powershell
+main.exe -m models\7B\ggml-model.bin --ignore-eos -n -1 --random-prompt
+```
+
+## Common Options
+
+In this section, we cover the most commonly used options for running the `main` program with the LLaMA models:
+
+- `-m FNAME, --model FNAME`: Specify the path to the LLaMA model file (e.g., `models/7B/ggml-model.bin`).
+- `-i, --interactive`: Run the program in interactive mode, allowing you to provide input directly and receive real-time responses.
+- `-ins, --instruct`: Run the program in instruction mode, which is particularly useful when working with Alpaca models.
+- `-n N, --n-predict N`: Set the number of tokens to predict when generating text. Adjusting this value can influence the length of the generated text.
+- `-c N, --ctx-size N`: Set the size of the prompt context. The default is 512, but LLaMA models were built with a context of 2048, which will provide better results for longer input/inference.
+
+## Input Prompts
+
+The `main` program provides several ways to interact with the LLaMA models using input prompts:
+
+- `--prompt PROMPT`: Provide a prompt directly as a command-line option.
+- `--file FNAME`: Provide a file containing a prompt or multiple prompts.
+- `--interactive-first`: Run the program in interactive mode and wait for input right away. (More on this below.)
+- `--random-prompt`: Start with a randomized prompt.
+
+## Interaction
+
+The `main` 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`, `--interactive-first`, and `--instruct`.
+
+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
+
+- `-i, --interactive`: Run the program in interactive mode, allowing users to engage in real-time conversations or provide specific instructions to the model.
+- `--interactive-first`: Run the program in interactive mode and immediately wait for user input before starting the text generation.
+- `-ins, --instruct`: Run the program in instruction mode, which is specifically designed to work with Alpaca models that excel in completing tasks based on user instructions.
+- `--color`: Enable colorized output to differentiate visually distinguishing between prompts, user input, and generated text.
+
+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:
+
+- `-r PROMPT, --reverse-prompt PROMPT`: Specify one or multiple reverse prompts to pause text generation and switch to interactive mode. For example, `-r "User:"` can be used to jump back into the conversation whenever it's the user's turn to speak. This helps create a more interactive and conversational experience. However, the reverse prompt doesn't work when it ends with a space.
+
+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:
+
+```sh
+./main -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:
+
+```sh
+./main -r "User:" --in-prefix " " --in-suffix "Assistant:"
+```
+
+### Instruction Mode
+
+Instruction mode is particularly useful when working with Alpaca models, which are designed to follow user instructions for specific tasks:
+
+- `-ins, --instruct`: Enable instruction mode to leverage the capabilities of Alpaca models in completing tasks based on user-provided instructions.
+
+Technical detail: the user's input is internally prefixed with the reverse prompt (or `### Instruction:` as the default), and followed by `### Response:` (except if you just press Return without any input, to keep generating a longer response).
+
+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.
+
+## 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
+
+The `--ctx-size` option allows you to set the size of the prompt context
+used by the LLaMA models during text generation. A larger context size
+helps the model to better comprehend and generate responses for longer
+input or conversations.
+
+- `-c N, --ctx-size N`: Set the size of the prompt context (default: 512). The LLaMA models were built with a context of 2048, which will yield the best results on longer input/inference. However, increasing the context size beyond 2048 may lead to unpredictable results.
+
+### Extended Context Size
+
+Some fine-tuned models have extended the context length by scaling RoPE.
+For example, if the original pre-trained model have a context length
+(max sequence length) of 4096 (4k) and the fine-tuned model have 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.
+
+- `--rope-scale N`: Where N is the linear scaling factor used by the fine-tuned model.
+
+### 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.
+
+- `--keep N`: Specify the number of tokens from the initial prompt to
+ retain when the model resets its internal context. By default, this
+ value is set to 0 (meaning no tokens are kept). Use `-1` to retain
+ all tokens from the initial prompt.
+
+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
+
+- `-n N, --n-predict N`: Set the number of tokens to predict when generating text (default: 128, -1 = infinity, -2 = until context filled)
+
+The `--n-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 `--n-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 significant pause in output.
+
+If the pause is undesirable, a value of -2 will stop generation immediately when the context is filled.
+
+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 `n-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
+
+- `--temp N`: Adjust the randomness of the generated text (default: 0.8).
+
+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.5`
+
+### Repeat Penalty
+
+- `--repeat-penalty N`: Control the repetition of token sequences in the generated text (default: 1.1).
+- `--repeat-last-n N`: Last n tokens to consider for penalizing repetition (default: 64, 0 = disabled, -1 = ctx-size).
+- `--no-penalize-nl`: Disable penalization for newline tokens when applying the 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.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, and a value of -1 sets the number of tokens considered equal to the context size (`ctx-size`).
+
+Use the `--no-penalize-nl` option to disable newline penalization when applying the repeat penalty. This option is particularly useful for generating chat conversations, dialogues, code, poetry, or any text where newline tokens play a significant role in structure and formatting. Disabling newline penalization helps maintain the natural flow and intended formatting in these specific use cases.
+
+Example usage: `--repeat-penalty 1.15 --repeat-last-n 128 --no-penalize-nl`
+
+### Top-K Sampling
+
+- `--top-k N`: Limit the next token selection to the K most probable tokens (default: 40).
+
+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 N`: Limit the next token selection to a subset of tokens with a cumulative probability above a threshold P (default: 0.9).
+
+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
+
+- `--min-p N`: Sets a minimum base probability threshold for token selection (default: 0.05).
+
+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`
+
+### Tail Free Sampling (TFS)
+
+- `--tfs N`: Enable tail free sampling with parameter z (default: 1.0, 1.0 = disabled).
+
+Tail free sampling (TFS) is a text generation technique that aims to reduce the impact of less likely tokens, which may be less relevant, less coherent, or nonsensical, on the output. Similar to Top-P it tries to determine the bulk of the most likely tokens dynamically. But TFS filters out logits based on the second derivative of their probabilities. Adding tokens is stopped after the sum of the second derivatives reaches the parameter z. In short: TFS looks how quickly the probabilities of the tokens decrease and cuts off the tail of unlikely tokens using the parameter z. Typical values for z are in the range of 0.9 to 0.95. A value of 1.0 would include all tokens, and thus disables the effect of TFS.
+
+Example usage: `--tfs 0.95`
+
+### Locally Typical Sampling
+
+- `--typical N`: Enable locally typical sampling with parameter p (default: 1.0, 1.0 = disabled).
+
+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 N`: Enable Mirostat sampling, controlling perplexity during text generation (default: 0, 0 = disabled, 1 = Mirostat, 2 = Mirostat 2.0).
+- `--mirostat-lr N`: Set the Mirostat learning rate, parameter eta (default: 0.1).
+- `--mirostat-ent N`: Set the Mirostat target entropy, parameter tau (default: 5.0).
+
+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`
+
+### Logit Bias
+
+- `-l TOKEN_ID(+/-)BIAS, --logit-bias TOKEN_ID(+/-)BIAS`: Modify the likelihood of a token appearing in the generated text completion.
+
+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
+
+- `-s SEED, --seed SEED`: Set the random number generator (RNG) seed (default: -1, -1 = random 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
+
+- `-t N, --threads N`: Set the number of threads to use during generation. For optimal performance, it is recommended to set this value to the number of physical CPU cores your system has (as opposed to the logical number of cores). Using the correct number of threads can greatly improve performance.
+- `-tb N, --threads-batch N`: Set the number of threads to use during batch and prompt processing. In some systems, it is beneficial to use a higher number of threads during batch processing than during generation. If not specified, the number of threads used for batch processing will be the same as the number of threads used for generation.
+
+### Mlock
+
+- `--mlock`: Lock the model in memory, preventing it from being swapped out when memory-mapped. This can improve performance but trades away some of the advantages of memory-mapping by requiring more RAM to run and potentially slowing down load times as the model loads into RAM.
+
+### No Memory Mapping
+
+- `--no-mmap`: Do not memory-map the model. By default, models are mapped into memory, which allows the system to load only the necessary parts of the model as needed. However, if the model is larger than your total amount of RAM or if your system is low on available memory, using mmap might increase the risk of pageouts, negatively impacting performance. Disabling mmap results in slower load times but may reduce pageouts if you're not using `--mlock`. Note that if the model is larger than the total amount of RAM, turning off mmap would prevent the model from loading at all.
+
+### NUMA support
+
+- `--numa`: Attempt optimizations that help on some systems with non-uniform memory access. This currently consists of pinning an equal proportion of the threads to the cores on each NUMA node, 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.
+
+### Memory Float 32
+
+- `--memory-f32`: Use 32-bit floats instead of 16-bit floats for memory key+value. This doubles the context memory requirement and cached prompt file size but does not appear to increase generation quality in a measurable way. Not recommended.
+
+### Batch Size
+
+- `-b N, --batch-size N`: Set the batch size for prompt processing (default: 512). This large batch size benefits users who have BLAS installed and enabled it during the build. If you don't have BLAS enabled ("BLAS=0"), you can use a smaller number, such as 8, to see the prompt progress as it's evaluated in some situations.
+
+### Prompt Caching
+
+- `--prompt-cache FNAME`: Specify a file to cache the model state after the initial prompt. This can significantly speed up the startup time when you're using longer prompts. The file is created during the first run and is reused and updated in subsequent runs. **Note**: Restoring a cached prompt does not imply restoring the exact state of the session at the point it was saved. So even when specifying a specific seed, you are not guaranteed to get the same sequence of tokens as the original generation.
+
+### Grammars
+
+- `--grammar GRAMMAR`, `--grammar-file FILE`: Specify a grammar (defined inline or in a file) to constrain model output to a specific format. For example, you could force the model to output JSON or to speak only in emojis. See the [GBNF guide](../../grammars/README.md) for details on the syntax.
+
+### Quantization
+
+For information about 4-bit quantization, which can significantly improve performance and reduce memory usage, please refer to llama.cpp's primary [README](../../README.md#prepare-data--run).
+
+## Additional Options
+
+These options provide extra functionality and customization when running the LLaMA models:
+
+- `-h, --help`: Display a help message showing all available options and their default values. This is particularly useful for checking the latest options and default values, as they can change frequently, and the information in this document may become outdated.
+- `--verbose-prompt`: Print the prompt before generating text.
+- `-ngl N, --n-gpu-layers N`: When compiled with appropriate support (currently CLBlast or cuBLAS), this option allows offloading some layers to the GPU for computation. Generally results in increased performance.
+- `-mg i, --main-gpu i`: When using multiple GPUs this option controls which GPU is used for small tensors for which the overhead of splitting the computation across all GPUs is not worthwhile. The GPU in question will use slightly more VRAM to store a scratch buffer for temporary results. By default GPU 0 is used. Requires cuBLAS.
+- `-ts SPLIT, --tensor-split SPLIT`: When using multiple GPUs this option controls how large tensors should be split across all GPUs. `SPLIT` is a comma-separated list of non-negative values that assigns the proportion of data that each GPU should get in order. For example, "3,2" will assign 60% of the data to GPU 0 and 40% to GPU 1. By default the data is split in proportion to VRAM but this may not be optimal for performance. Requires cuBLAS.
+- `--lora FNAME`: Apply a LoRA (Low-Rank Adaptation) adapter to the model (implies --no-mmap). This allows you to adapt the pretrained model to specific tasks or domains.
+- `--lora-base FNAME`: Optional model to use as a base for the layers modified by the LoRA adapter. This flag is used in conjunction with the `--lora` flag, and specifies the base model for the adaptation.
diff --git a/llama.cpp/llama-bench/bench-llamafile-zip.py b/llama.cpp/llama-bench/bench-llamafile-zip.py
new file mode 100755
index 00000000..da7ef674
--- /dev/null
+++ b/llama.cpp/llama-bench/bench-llamafile-zip.py
@@ -0,0 +1,39 @@
+#!/usr/bin/env python
+
+import sys
+
+def split(line):
+ return [x.strip() for x in line[1:-1].split('|')]
+
+with open('before') as f:
+ lines = [split(x) for x in f.read().strip().split('\n') if x.startswith('|')]
+ headers = lines[0]
+ bars = lines[1]
+ before = lines[2:]
+
+with open('after') as f:
+ lines = [split(x) for x in f.read().strip().split('\n') if x.startswith('|')]
+ after = lines[2:]
+
+res = []
+
+def print_row(A):
+ res.append('| ')
+ for i, a in enumerate(A):
+ if i:
+ res.append(' | ')
+ res.append(str(a))
+ res.append(' |\n')
+
+last_name = headers[-1]
+headers = headers[:-1]
+headers.append(last_name + ' before')
+headers.append(last_name + ' after')
+headers.append(last_name + ' speedup')
+print_row(headers)
+print_row(["---:" for h in headers])
+
+for B, A in zip(before, after):
+ print_row(B[:] + [A[-1], ('%.2f' % (float(A[-1]) / float(B[-1]))) + 'x'])
+
+print(''.join(res))
diff --git a/llama.cpp/llama-bench/bench-llamafile.sh b/llama.cpp/llama-bench/bench-llamafile.sh
new file mode 100755
index 00000000..a31f5407
--- /dev/null
+++ b/llama.cpp/llama-bench/bench-llamafile.sh
@@ -0,0 +1,9 @@
+#!/bin/sh
+cd ~/llamafile
+make -j16 o//llama.cpp/llama-bench/llama-bench || exit
+o//llama.cpp/llama-bench/llama-bench \
+ $(for f in $(ls -S /weights/TinyLlama-1.1B-Chat-v1.0.*.gguf \
+ /weights/mixtral-8x7b-instruct-v0.1.*.gguf); do
+ echo -m $f
+ done) \
+ "$@"
diff --git a/llama.cpp/llama-bench/embedding.cpp b/llama.cpp/llama-bench/embedding.cpp
new file mode 100644
index 00000000..583f8815
--- /dev/null
+++ b/llama.cpp/llama-bench/embedding.cpp
@@ -0,0 +1,250 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+
+#include "llama.cpp/common.h"
+#include "llama.cpp/llama.h"
+#include "llamafile/llamafile.h"
+
+#include <ctime>
+
+#if defined(_MSC_VER)
+#pragma warning(disable: 4244 4267) // possible loss of data
+#endif
+
+// [jart] dont do the multiline demo unless it's requested
+static std::vector<std::string> split_lines(const std::string & s, bool multiline) {
+ std::vector<std::string> lines;
+ if (multiline) {
+ std::string line;
+ std::stringstream ss(s);
+ while (std::getline(ss, line)) {
+ lines.push_back(line);
+ }
+ } else {
+ lines.push_back(s);
+ }
+ return lines;
+}
+
+static void batch_add_seq(llama_batch & batch, const std::vector<int32_t> & tokens, int seq_id) {
+ for (size_t i = 0; i < tokens.size(); i++) {
+ llama_batch_add(batch, tokens[i], i, { seq_id }, i == tokens.size() - 1);
+ }
+}
+
+static void batch_decode(llama_context * ctx, llama_batch & batch, float * output, int n_seq, int n_embd) {
+ // clear previous kv_cache values (irrelevant for embeddings)
+ llama_kv_cache_clear(ctx);
+
+ // run model
+ LOG("%s: n_tokens = %d, n_seq = %d\n", __func__, batch.n_tokens, n_seq);
+ if (llama_decode(ctx, batch) < 0) {
+ fprintf(stderr, "%s : failed to decode\n", __func__);
+ exit(1);
+ }
+
+ for (int i = 0; i < batch.n_tokens; i++) {
+ if (!batch.logits[i]) {
+ continue;
+ }
+
+ // try to get sequence embeddings - supported only when pooling_type is not NONE
+ const float * embd = llama_get_embeddings_seq(ctx, batch.seq_id[i][0]);
+ if (embd == NULL) {
+ embd = llama_get_embeddings_ith(ctx, i);
+ if (embd == NULL) {
+ LOG("%s: failed to get embeddings for token %d\n", __func__, i);
+ continue;
+ }
+ }
+
+ float * out = output + batch.seq_id[i][0] * n_embd;
+ llama_embd_normalize(embd, out, n_embd);
+ }
+}
+
+static void llama_log_callback_logTee(ggml_log_level level, const char * text, void * user_data) {
+ (void) level;
+ (void) user_data;
+ LOG_TEE("%s", text);
+}
+
+int embedding_cli(int argc, char ** argv) {
+ gpt_params params;
+
+ if (!gpt_params_parse(argc, argv, params)) {
+ return 1;
+ }
+
+#ifndef LOG_DISABLE_LOGS
+ log_set_target(stderr);
+ log_dump_cmdline(argc, argv);
+ llama_log_set(llama_log_callback_logTee, nullptr);
+#endif // LOG_DISABLE_LOGS
+
+ params.embedding = true;
+ // For non-causal models, batch size must be equal to ubatch size
+ params.n_ubatch = params.n_batch;
+
+ print_build_info();
+
+ if (params.seed == LLAMA_DEFAULT_SEED) {
+ params.seed = _rand64();
+ }
+
+ LOG("%s: seed = %u\n", __func__, params.seed);
+
+ std::mt19937 rng(params.seed);
+ if (params.random_prompt) {
+ params.prompt = gpt_random_prompt(rng);
+ }
+
+ llama_backend_init();
+ llama_numa_init(params.numa);
+
+ llama_model * model;
+ llama_context * ctx;
+
+ // load the model
+ std::tie(model, ctx) = llama_init_from_gpt_params(params);
+ if (model == NULL) {
+ fprintf(stderr, "%s: error: unable to load model\n", __func__);
+ return 1;
+ }
+
+ const int n_ctx_train = llama_n_ctx_train(model);
+ const int n_ctx = llama_n_ctx(ctx);
+
+ if (n_ctx > n_ctx_train) {
+ LOG("%s: warning: model was trained on only %d context tokens (%d specified)\n",
+ __func__, n_ctx_train, n_ctx);
+ }
+
+ // print system information
+ {
+ LOG("\n");
+ LOG("%s\n", get_system_info(params).c_str());
+ }
+
+ // split the prompt into lines
+ std::vector<std::string> prompts = split_lines(params.prompt, params.multiline_input);
+
+ // max batch size
+ const uint64_t n_batch = params.n_batch;
+ GGML_ASSERT(params.n_batch >= params.n_ctx);
+
+ // tokenize the prompts and trim
+ std::vector<std::vector<int32_t>> inputs;
+ for (const auto & prompt : prompts) {
+ auto inp = ::llama_tokenize(ctx, prompt, true, false);
+ if (inp.size() > n_batch) {
+ fprintf(stderr, "%s: error: number of tokens in input line (%lld) exceeds batch size (%lld), increase batch size and re-run\n",
+ __func__, (long long int) inp.size(), (long long int) n_batch);
+ return 1;
+ }
+ inputs.push_back(inp);
+ }
+
+ // add SEP if not present
+ for (auto & inp : inputs) {
+ if (inp.empty() || inp.back() != llama_token_sep(model)) {
+ inp.push_back(llama_token_sep(model));
+ }
+ }
+
+ // tokenization stats
+ if (params.verbose_prompt) {
+ for (int i = 0; i < (int) inputs.size(); i++) {
+ LOG("%s: prompt %d: '%s'\n", __func__, i, prompts[i].c_str());
+ LOG("%s: number of tokens in prompt = %zu\n", __func__, inputs[i].size());
+ for (int j = 0; j < (int) inputs[i].size(); j++) {
+ LOG("%6d -> '%s'\n", inputs[i][j], llama_token_to_piece(ctx, inputs[i][j]).c_str());
+ }
+ LOG("\n\n");
+ }
+ }
+
+ // initialize batch
+ const int n_prompts = prompts.size();
+ struct llama_batch batch = llama_batch_init(n_batch, 0, 1);
+
+ // allocate output
+ const int n_embd = llama_n_embd(model);
+ std::vector<float> embeddings(n_prompts * n_embd, 0);
+ float * emb = embeddings.data();
+
+ // break into batches
+ int p = 0; // number of prompts processed already
+ int s = 0; // number of prompts in current batch
+ for (int k = 0; k < n_prompts; k++) {
+ // clamp to n_batch tokens
+ auto & inp = inputs[k];
+
+ const uint64_t n_toks = inp.size();
+
+ // encode if at capacity
+ if (batch.n_tokens + n_toks > n_batch) {
+ float * out = emb + p * n_embd;
+ batch_decode(ctx, batch, out, s, n_embd);
+ llama_batch_clear(batch);
+ p += s;
+ s = 0;
+ }
+
+ // add to batch
+ batch_add_seq(batch, inp, s);
+ s += 1;
+ }
+
+ // final batch
+ float * out = emb + p * n_embd;
+ batch_decode(ctx, batch, out, s, n_embd);
+
+ LOG("\n");
+
+ // [jart] don't truncate data unless we're in interactive mode
+ // [jart] print very carefully so this tool can be shell scriptable
+ // print the first part of the embeddings or for a single prompt, the full embedding
+ bool demo_mode = n_prompts > 1 && params.interactive;
+ for (int j = 0; j < n_prompts; j++) {
+ LOG("embedding %d: ", j);
+ int display_count = n_embd;
+ if (demo_mode) {
+ display_count = std::min(16, display_count);
+ }
+ for (int i = 0; i < (n_prompts > 1 ? std::min(16, n_embd) : n_embd); i++) {
+ if (i) {
+ fprintf(stdout, " ");
+ }
+ if (demo_mode) {
+ fprintf(stdout, "%9.6f", emb[j * n_embd + i]);
+ } else {
+ fprintf(stdout, "%g", emb[j * n_embd + i]);
+ }
+ }
+ fprintf(stdout, "\n");
+ fflush(stdout);
+ }
+
+ // [jart] print very carefully so this tool can be shell scriptable
+ // print cosine similarity matrix
+ if (n_prompts > 1) {
+ LOG("\n");
+ LOG("cosine similarity matrix:\n\n");
+ for (int i = 0; i < n_prompts; i++) {
+ for (int j = 0; j < n_prompts; j++) {
+ float sim = llama_embd_similarity_cos(emb + i * n_embd, emb + j * n_embd, n_embd);
+ LOG("%6.2f ", sim);
+ }
+ LOG("\n");
+ }
+ }
+
+ // clean up
+ llama_print_timings(ctx);
+ llama_free(ctx);
+ llama_free_model(model);
+ llama_backend_free();
+
+ return 0;
+}
diff --git a/llama.cpp/llama-bench/llama-bench.cpp b/llama.cpp/llama-bench/llama-bench.cpp
new file mode 100644
index 00000000..3e045ffb
--- /dev/null
+++ b/llama.cpp/llama-bench/llama-bench.cpp
@@ -0,0 +1,1391 @@
+#include <algorithm>
+#include <array>
+#include <cassert>
+#include <chrono>
+#include <cinttypes>
+#include <clocale>
+#include <cmath>
+#include <cstdio>
+#include <cstring>
+#include <ctime>
+#include <cstdlib>
+#include <iterator>
+#include <map>
+#include <numeric>
+#include <regex>
+#include <sstream>
+#include <string>
+#include <vector>
+#include <cosmo.h>
+#include <libgen.h>
+
+#include "llama.cpp/ggml.h"
+#include "llama.cpp/llama.h"
+#include "llama.cpp/common.h"
+#include "llama.cpp/ggml-cuda.h"
+
+// utils
+static uint64_t get_time_ns() {
+ using clock = std::chrono::high_resolution_clock;
+ return std::chrono::nanoseconds(clock::now().time_since_epoch()).count();
+}
+
+template<class T>
+static std::string join(const std::vector<T> & values, const std::string & delim) {
+ std::ostringstream str;
+ for (size_t i = 0; i < values.size(); i++) {
+ str << values[i];
+ if (i < values.size() - 1) {
+ str << delim;
+ }
+ }
+ return str.str();
+}
+
+template<class T>
+static std::vector<T> split(const std::string & str, char delim) {
+ std::vector<T> values;
+ std::istringstream str_stream(str);
+ std::string token;
+ while (std::getline(str_stream, token, delim)) {
+ T value;
+ std::istringstream token_stream(token);
+ token_stream >> value;
+ values.push_back(value);
+ }
+ return values;
+}
+
+template<typename T, typename F>
+static std::vector<std::string> transform_to_str(const std::vector<T> & values, F f) {
+ std::vector<std::string> str_values;
+ std::transform(values.begin(), values.end(), std::back_inserter(str_values), f);
+ return str_values;
+}
+
+template<typename T>
+static T avg(const std::vector<T> & v) {
+ if (v.empty()) {
+ return 0;
+ }
+ T sum = std::accumulate(v.begin(), v.end(), T(0));
+ return sum / (T)v.size();
+}
+
+template<typename T>
+static T stdev(const std::vector<T> & v) {
+ if (v.size() <= 1) {
+ return 0;
+ }
+ T mean = avg(v);
+ T sq_sum = std::inner_product(v.begin(), v.end(), v.begin(), T(0));
+ T stdev = std::sqrt(sq_sum / (T)(v.size() - 1) - mean * mean * (T)v.size() / (T)(v.size() - 1));
+ return stdev;
+}
+
+static std::string get_cpu_info() {
+ std::string id;
+ if (IsLinux()) {
+ FILE * f = fopen("/proc/cpuinfo", "r");
+ if (f) {
+ char buf[1024];
+ while (fgets(buf, sizeof(buf), f)) {
+ if (strncmp(buf, "model name", 10) == 0) {
+ char * p = strchr(buf, ':');
+ if (p) {
+ p++;
+ while (std::isspace(*p)) {
+ p++;
+ }
+ while (std::isspace(p[strlen(p) - 1])) {
+ p[strlen(p) - 1] = '\0';
+ }
+ id = p;
+ break;
+ }
+ }
+ }
+ fclose(f);
+ }
+ }
+ // TODO: other platforms
+ return id;
+}
+
+static std::string get_gpu_info() {
+ std::string id;
+#ifdef GGML_USE_CUDA
+ int count = ggml_backend_cuda_get_device_count();
+ for (int i = 0; i < count; i++) {
+ char buf[128];
+ ggml_backend_cuda_get_device_description(i, buf, sizeof(buf));
+ id += buf;
+ if (i < count - 1) {
+ id += "/";
+ }
+ }
+#endif
+#ifdef GGML_USE_SYCL
+ int count = ggml_backend_sycl_get_device_count();
+ for (int i = 0; i < count; i++) {
+ char buf[128];
+ ggml_sycl_get_device_description(i, buf, sizeof(buf));
+ id += buf;
+ if (i < count - 1) {
+ id += "/";
+ }
+ }
+#endif
+ // TODO: other backends
+ return id;
+}
+
+// command line params
+enum output_formats {CSV, JSON, MARKDOWN, SQL};
+
+static const char * output_format_str(output_formats format) {
+ switch (format) {
+ case CSV: return "csv";
+ case JSON: return "json";
+ case MARKDOWN: return "md";
+ case SQL: return "sql";
+ default: GGML_ASSERT(!"invalid output format");
+ }
+}
+
+static const char * split_mode_str(llama_split_mode mode) {
+ switch (mode) {
+ case LLAMA_SPLIT_MODE_NONE: return "none";
+ case LLAMA_SPLIT_MODE_LAYER: return "layer";
+ case LLAMA_SPLIT_MODE_ROW: return "row";
+ default: GGML_ASSERT(!"invalid split mode");
+ }
+}
+
+static std::string pair_str(const std::pair<int, int> & p) {
+ static char buf[32];
+ snprintf(buf, sizeof(buf), "%d,%d", p.first, p.second);
+ return buf;
+}
+
+struct cmd_params {
+ std::vector<std::string> model;
+ std::vector<int> n_prompt;
+ std::vector<int> n_gen;
+ std::vector<std::pair<int, int>> n_pg;
+ std::vector<int> n_batch;
+ std::vector<int> n_ubatch;
+ std::vector<ggml_type> type_k;
+ std::vector<ggml_type> type_v;
+ std::vector<int> n_threads;
+ std::vector<int> n_gpu_layers;
+ std::vector<llama_split_mode> split_mode;
+ std::vector<int> main_gpu;
+ std::vector<bool> no_kv_offload;
+ std::vector<bool> flash_attn;
+ std::vector<std::vector<float>> tensor_split;
+ std::vector<bool> use_mmap;
+ std::vector<bool> embeddings;
+ ggml_numa_strategy numa;
+ int reps;
+ bool verbose;
+ output_formats output_format;
+};
+
+static const cmd_params cmd_params_defaults = {
+ /* model */ {"models/7B/ggml-model-q4_0.gguf"},
+ /* n_prompt */ {512},
+ /* n_gen */ {16},
+ /* n_pg */ {},
+ /* n_batch */ {2048},
+ /* n_ubatch */ {512},
+ /* type_k */ {GGML_TYPE_F16},
+ /* type_v */ {GGML_TYPE_F16},
+ /* n_threads */ {cpu_get_num_math()},
+ /* n_gpu_layers */ {0},
+ /* split_mode */ {LLAMA_SPLIT_MODE_LAYER},
+ /* main_gpu */ {0},
+ /* no_kv_offload */ {false},
+ /* flash_attn */ {false},
+ /* tensor_split */ {std::vector<float>(llama_max_devices(), 0.0f)},
+ /* use_mmap */ {true},
+ /* embeddings */ {false},
+ /* numa */ GGML_NUMA_STRATEGY_DISABLED,
+ /* reps */ 1,
+ /* verbose */ false,
+ /* output_format */ MARKDOWN
+};
+
+static void print_usage(int /* argc */, char ** argv) {
+ printf("usage: %s [options]\n", argv[0]);
+ printf("\n");
+ printf("options:\n");
+ printf(" -h, --help\n");
+ printf(" -m, --model <filename> (default: %s)\n", join(cmd_params_defaults.model, ",").c_str());
+ printf(" -p, --n-prompt <n> (default: %s)\n", join(cmd_params_defaults.n_prompt, ",").c_str());
+ printf(" -n, --n-gen <n> (default: %s)\n", join(cmd_params_defaults.n_gen, ",").c_str());
+ printf(" -pg <pp,tg> (default: %s)\n", join(transform_to_str(cmd_params_defaults.n_pg, pair_str), ",").c_str());
+ printf(" -b, --batch-size <n> (default: %s)\n", join(cmd_params_defaults.n_batch, ",").c_str());
+ printf(" -ub, --ubatch-size <n> (default: %s)\n", join(cmd_params_defaults.n_ubatch, ",").c_str());
+ printf(" -ctk, --cache-type-k <t> (default: %s)\n", join(transform_to_str(cmd_params_defaults.type_k, ggml_type_name), ",").c_str());
+ printf(" -ctv, --cache-type-v <t> (default: %s)\n", join(transform_to_str(cmd_params_defaults.type_v, ggml_type_name), ",").c_str());
+ printf(" -t, --threads <n> (default: %s)\n", join(cmd_params_defaults.n_threads, ",").c_str());
+ printf(" -ngl, --n-gpu-layers <n> (default: %s)\n", join(cmd_params_defaults.n_gpu_layers, ",").c_str());
+ printf(" -sm, --split-mode <none|layer|row> (default: %s)\n", join(transform_to_str(cmd_params_defaults.split_mode, split_mode_str), ",").c_str());
+ printf(" -mg, --main-gpu <i> (default: %s)\n", join(cmd_params_defaults.main_gpu, ",").c_str());
+ printf(" -nkvo, --no-kv-offload <0|1> (default: %s)\n", join(cmd_params_defaults.no_kv_offload, ",").c_str());
+ printf(" -fa, --flash-attn <0|1> (default: %s)\n", join(cmd_params_defaults.flash_attn, ",").c_str());
+ printf(" -mmp, --mmap <0|1> (default: %s)\n", join(cmd_params_defaults.use_mmap, ",").c_str());
+ printf(" --numa <distribute|isolate|numactl> (default: disabled)\n");
+ printf(" -embd, --embeddings <0|1> (default: %s)\n", join(cmd_params_defaults.embeddings, ",").c_str());
+ printf(" -ts, --tensor-split <ts0/ts1/..> (default: 0)\n");
+ printf(" -r, --repetitions <n> (default: %d)\n", cmd_params_defaults.reps);
+ printf(" -o, --output <csv|json|md|sql> (default: %s)\n", output_format_str(cmd_params_defaults.output_format));
+ printf(" -v, --verbose (default: %s)\n", cmd_params_defaults.verbose ? "1" : "0");
+ printf("\n");
+ printf("Multiple values can be given for each parameter by separating them with ',' or by specifying the parameter multiple times.\n");
+}
+
+static ggml_type ggml_type_from_name(const std::string & s) {
+ if (s == "f16") {
+ return GGML_TYPE_F16;
+ }
+ if (s == "q8_0") {
+ return GGML_TYPE_Q8_0;
+ }
+ if (s == "q4_0") {
+ return GGML_TYPE_Q4_0;
+ }
+ if (s == "q4_1") {
+ return GGML_TYPE_Q4_1;
+ }
+ if (s == "q5_0") {
+ return GGML_TYPE_Q5_0;
+ }
+ if (s == "q5_1") {
+ return GGML_TYPE_Q5_1;
+ }
+ if (s == "iq4_nl") {
+ return GGML_TYPE_IQ4_NL;
+ }
+
+ return GGML_TYPE_COUNT;
+}
+
+
+static cmd_params parse_cmd_params(int argc, char ** argv) {
+ cmd_params params;
+ std::string arg;
+ bool invalid_param = false;
+ const std::string arg_prefix = "--";
+ const char split_delim = ',';
+
+ params.verbose = cmd_params_defaults.verbose;
+ params.output_format = cmd_params_defaults.output_format;
+ params.reps = cmd_params_defaults.reps;
+
+ for (int i = 1; i < argc; i++) {
+ arg = argv[i];
+ if (arg.compare(0, arg_prefix.size(), arg_prefix) == 0) {
+ std::replace(arg.begin(), arg.end(), '_', '-');
+ }
+
+ if (arg == "-h" || arg == "--help") {
+ print_usage(argc, argv);
+ exit(0);
+ } else if (arg == "-m" || arg == "--model") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<std::string>(argv[i], split_delim);
+ params.model.insert(params.model.end(), p.begin(), p.end());
+ } else if (arg == "-p" || arg == "--n-prompt") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<int>(argv[i], split_delim);
+ params.n_prompt.insert(params.n_prompt.end(), p.begin(), p.end());
+ } else if (arg == "-n" || arg == "--n-gen") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<int>(argv[i], split_delim);
+ params.n_gen.insert(params.n_gen.end(), p.begin(), p.end());
+ } else if (arg == "-pg") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<std::string>(argv[i], ',');
+ if (p.size() != 2) {
+ invalid_param = true;
+ break;
+ }
+ params.n_pg.push_back({std::stoi(p[0]), std::stoi(p[1])});
+ } else if (arg == "-b" || arg == "--batch-size") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<int>(argv[i], split_delim);
+ params.n_batch.insert(params.n_batch.end(), p.begin(), p.end());
+ } else if (arg == "-ub" || arg == "--ubatch-size") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<int>(argv[i], split_delim);
+ params.n_ubatch.insert(params.n_ubatch.end(), p.begin(), p.end());
+ } else if (arg == "-ctk" || arg == "--cache-type-k") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<std::string>(argv[i], split_delim);
+ std::vector<ggml_type> types;
+ for (const auto & t : p) {
+ ggml_type gt = ggml_type_from_name(t);
+ if (gt == GGML_TYPE_COUNT) {
+ invalid_param = true;
+ break;
+ }
+ types.push_back(gt);
+ }
+ params.type_k.insert(params.type_k.end(), types.begin(), types.end());
+ } else if (arg == "-ctv" || arg == "--cache-type-v") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<std::string>(argv[i], split_delim);
+ std::vector<ggml_type> types;
+ for (const auto & t : p) {
+ ggml_type gt = ggml_type_from_name(t);
+ if (gt == GGML_TYPE_COUNT) {
+ invalid_param = true;
+ break;
+ }
+ types.push_back(gt);
+ }
+ params.type_v.insert(params.type_v.end(), types.begin(), types.end());
+ } else if (arg == "-t" || arg == "--threads") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<int>(argv[i], split_delim);
+ params.n_threads.insert(params.n_threads.end(), p.begin(), p.end());
+ } else if (arg == "-ngl" || arg == "--n-gpu-layers") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<int>(argv[i], split_delim);
+ params.n_gpu_layers.insert(params.n_gpu_layers.end(), p.begin(), p.end());
+ } else if (arg == "-sm" || arg == "--split-mode") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<std::string>(argv[i], split_delim);
+ std::vector<llama_split_mode> modes;
+ for (const auto & m : p) {
+ llama_split_mode mode;
+ if (m == "none") {
+ mode = LLAMA_SPLIT_MODE_NONE;
+ } else if (m == "layer") {
+ mode = LLAMA_SPLIT_MODE_LAYER;
+ } else if (m == "row") {
+ mode = LLAMA_SPLIT_MODE_ROW;
+ } else {
+ invalid_param = true;
+ break;
+ }
+ modes.push_back(mode);
+ }
+ params.split_mode.insert(params.split_mode.end(), modes.begin(), modes.end());
+ } else if (arg == "-mg" || arg == "--main-gpu") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ params.main_gpu = split<int>(argv[i], split_delim);
+ } else if (arg == "-nkvo" || arg == "--no-kv-offload") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<bool>(argv[i], split_delim);
+ params.no_kv_offload.insert(params.no_kv_offload.end(), p.begin(), p.end());
+ } else if (arg == "--numa") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ } else {
+ std::string value(argv[i]);
+ /**/ if (value == "distribute" || value == "" ) { params.numa = GGML_NUMA_STRATEGY_DISTRIBUTE; }
+ else if (value == "isolate") { params.numa = GGML_NUMA_STRATEGY_ISOLATE; }
+ else if (value == "numactl") { params.numa = GGML_NUMA_STRATEGY_NUMACTL; }
+ else { invalid_param = true; break; }
+ }
+ } else if (arg == "-fa" || arg == "--flash-attn") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<bool>(argv[i], split_delim);
+ params.flash_attn.insert(params.flash_attn.end(), p.begin(), p.end());
+ } else if (arg == "-mmp" || arg == "--mmap") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<bool>(argv[i], split_delim);
+ params.use_mmap.insert(params.use_mmap.end(), p.begin(), p.end());
+ } else if (arg == "-embd" || arg == "--embeddings") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ auto p = split<bool>(argv[i], split_delim);
+ params.embeddings.insert(params.embeddings.end(), p.begin(), p.end());
+ } else if (arg == "-ts" || arg == "--tensor-split") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ for (auto ts : split<std::string>(argv[i], split_delim)) {
+ // split string by ; and /
+ const std::regex regex{R"([;/]+)"};
+ std::sregex_token_iterator it{ts.begin(), ts.end(), regex, -1};
+ std::vector<std::string> split_arg{it, {}};
+ GGML_ASSERT(split_arg.size() <= llama_max_devices());
+
+ std::vector<float> tensor_split(llama_max_devices());
+ for (size_t i = 0; i < llama_max_devices(); ++i) {
+ if (i < split_arg.size()) {
+ tensor_split[i] = std::stof(split_arg[i]);
+ } else {
+ tensor_split[i] = 0.0f;
+ }
+ }
+ params.tensor_split.push_back(tensor_split);
+ }
+ } else if (arg == "-r" || arg == "--repetitions") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ params.reps = std::stoi(argv[i]);
+ } else if (arg == "-o" || arg == "--output") {
+ if (++i >= argc) {
+ invalid_param = true;
+ break;
+ }
+ if (argv[i] == std::string("csv")) {
+ params.output_format = CSV;
+ } else if (argv[i] == std::string("json")) {
+ params.output_format = JSON;
+ } else if (argv[i] == std::string("md")) {
+ params.output_format = MARKDOWN;
+ } else if (argv[i] == std::string("sql")) {
+ params.output_format = SQL;
+ } else {
+ invalid_param = true;
+ break;
+ }
+ } else if (arg == "-v" || arg == "--verbose") {
+ params.verbose = true;
+ } else {
+ invalid_param = true;
+ break;
+ }
+ }
+ if (invalid_param) {
+ fprintf(stderr, "error: invalid parameter for argument: %s\n", arg.c_str());
+ print_usage(argc, argv);
+ exit(1);
+ }
+
+ // set defaults
+ if (params.model.empty()) { params.model = cmd_params_defaults.model; }
+ if (params.n_prompt.empty()) { params.n_prompt = cmd_params_defaults.n_prompt; }
+ if (params.n_gen.empty()) { params.n_gen = cmd_params_defaults.n_gen; }
+ if (params.n_pg.empty()) { params.n_pg = cmd_params_defaults.n_pg; }
+ if (params.n_batch.empty()) { params.n_batch = cmd_params_defaults.n_batch; }
+ if (params.n_ubatch.empty()) { params.n_ubatch = cmd_params_defaults.n_ubatch; }
+ if (params.type_k.empty()) { params.type_k = cmd_params_defaults.type_k; }
+ if (params.type_v.empty()) { params.type_v = cmd_params_defaults.type_v; }
+ if (params.n_gpu_layers.empty()) { params.n_gpu_layers = cmd_params_defaults.n_gpu_layers; }
+ if (params.split_mode.empty()) { params.split_mode = cmd_params_defaults.split_mode; }
+ if (params.main_gpu.empty()) { params.main_gpu = cmd_params_defaults.main_gpu; }
+ if (params.no_kv_offload.empty()){ params.no_kv_offload = cmd_params_defaults.no_kv_offload; }
+ if (params.flash_attn.empty()) { params.flash_attn = cmd_params_defaults.flash_attn; }
+ if (params.tensor_split.empty()) { params.tensor_split = cmd_params_defaults.tensor_split; }
+ if (params.use_mmap.empty()) { params.use_mmap = cmd_params_defaults.use_mmap; }
+ if (params.embeddings.empty()) { params.embeddings = cmd_params_defaults.embeddings; }
+ if (params.n_threads.empty()) { params.n_threads = cmd_params_defaults.n_threads; }
+
+ return params;
+}
+
+struct cmd_params_instance {
+ std::string model;
+ int n_prompt;
+ int n_gen;
+ int n_batch;
+ int n_ubatch;
+ ggml_type type_k;
+ ggml_type type_v;
+ int n_threads;
+ int n_gpu_layers;
+ llama_split_mode split_mode;
+ int main_gpu;
+ bool no_kv_offload;
+ bool flash_attn;
+ std::vector<float> tensor_split;
+ bool use_mmap;
+ bool embeddings;
+
+ llama_model_params to_llama_mparams() const {
+ llama_model_params mparams = llama_model_default_params();
+
+ mparams.n_gpu_layers = n_gpu_layers;
+ mparams.split_mode = split_mode;
+ mparams.main_gpu = main_gpu;
+ mparams.tensor_split = tensor_split.data();
+ mparams.use_mmap = use_mmap;
+
+ return mparams;
+ }
+
+ bool equal_mparams(const cmd_params_instance & other) const {
+ return model == other.model &&
+ n_gpu_layers == other.n_gpu_layers &&
+ split_mode == other.split_mode &&
+ main_gpu == other.main_gpu &&
+ use_mmap == other.use_mmap &&
+ tensor_split == other.tensor_split;
+ }
+
+ llama_context_params to_llama_cparams() const {
+ llama_context_params cparams = llama_context_default_params();
+
+ cparams.n_ctx = n_prompt + n_gen;
+ cparams.n_batch = n_batch;
+ cparams.n_ubatch = n_ubatch;
+ cparams.type_k = type_k;
+ cparams.type_v = type_v;
+ cparams.offload_kqv = !no_kv_offload;
+ cparams.flash_attn = flash_attn;
+ cparams.embeddings = embeddings;
+
+ return cparams;
+ }
+};
+
+static std::vector<cmd_params_instance> get_cmd_params_instances(const cmd_params & params) {
+ std::vector<cmd_params_instance> instances;
+
+ // this ordering minimizes the number of times that each model needs to be reloaded
+ for (const auto & m : params.model)
+ for (const auto & nl : params.n_gpu_layers)
+ for (const auto & sm : params.split_mode)
+ for (const auto & mg : params.main_gpu)
+ for (const auto & ts : params.tensor_split)
+ for (const auto & mmp : params.use_mmap)
+ for (const auto & embd : params.embeddings)
+ for (const auto & nb : params.n_batch)
+ for (const auto & nub : params.n_ubatch)
+ for (const auto & tk : params.type_k)
+ for (const auto & tv : params.type_v)
+ for (const auto & nkvo : params.no_kv_offload)
+ for (const auto & fa : params.flash_attn)
+ for (const auto & nt : params.n_threads) {
+ for (const auto & n_prompt : params.n_prompt) {
+ if (n_prompt == 0) {
+ continue;
+ }
+ cmd_params_instance instance = {
+ /* .model = */ m,
+ /* .n_prompt = */ n_prompt,
+ /* .n_gen = */ 0,
+ /* .n_batch = */ nb,
+ /* .n_ubatch = */ nub,
+ /* .type_k = */ tk,
+ /* .type_v = */ tv,
+ /* .n_threads = */ nt,
+ /* .n_gpu_layers = */ nl,
+ /* .split_mode = */ sm,
+ /* .main_gpu = */ mg,
+ /* .no_kv_offload= */ nkvo,
+ /* .flash_attn = */ fa,
+ /* .tensor_split = */ ts,
+ /* .use_mmap = */ mmp,
+ /* .embeddings = */ embd,
+ };
+ instances.push_back(instance);
+ }
+
+ for (const auto & n_gen : params.n_gen) {
+ if (n_gen == 0) {
+ continue;
+ }
+ cmd_params_instance instance = {
+ /* .model = */ m,
+ /* .n_prompt = */ 0,
+ /* .n_gen = */ n_gen,
+ /* .n_batch = */ nb,
+ /* .n_ubatch = */ nub,
+ /* .type_k = */ tk,
+ /* .type_v = */ tv,
+ /* .n_threads = */ nt,
+ /* .n_gpu_layers = */ nl,
+ /* .split_mode = */ sm,
+ /* .main_gpu = */ mg,
+ /* .no_kv_offload= */ nkvo,
+ /* .flash_attn = */ fa,
+ /* .tensor_split = */ ts,
+ /* .use_mmap = */ mmp,
+ /* .embeddings = */ embd,
+ };
+ instances.push_back(instance);
+ }
+
+ for (const auto & n_pg : params.n_pg) {
+ if (n_pg.first == 0 && n_pg.second == 0) {
+ continue;
+ }
+ cmd_params_instance instance = {
+ /* .model = */ m,
+ /* .n_prompt = */ n_pg.first,
+ /* .n_gen = */ n_pg.second,
+ /* .n_batch = */ nb,
+ /* .n_ubatch = */ nub,
+ /* .type_k = */ tk,
+ /* .type_v = */ tv,
+ /* .n_threads = */ nt,
+ /* .n_gpu_layers = */ nl,
+ /* .split_mode = */ sm,
+ /* .main_gpu = */ mg,
+ /* .no_kv_offload= */ nkvo,
+ /* .flash_attn = */ fa,
+ /* .tensor_split = */ ts,
+ /* .use_mmap = */ mmp,
+ /* .embeddings = */ embd,
+ };
+ instances.push_back(instance);
+ }
+ }
+
+ return instances;
+}
+
+struct test {
+ static const std::string build_commit;
+ static const int build_number;
+ static const bool cuda;
+ static const bool opencl;
+ static const bool vulkan;
+ static const bool kompute;
+ static const bool metal;
+ static const bool sycl;
+ static const bool gpu_blas;
+ static const bool blas;
+ static const std::string cpu_info;
+ static const std::string gpu_info;
+ std::string model_filename;
+ std::string model_type;
+ uint64_t model_size;
+ uint64_t model_n_params;
+ int n_batch;
+ int n_ubatch;
+ int n_threads;
+ ggml_type type_k;
+ ggml_type type_v;
+ int n_gpu_layers;
+ llama_split_mode split_mode;
+ int main_gpu;
+ bool no_kv_offload;
+ bool flash_attn;
+ std::vector<float> tensor_split;
+ bool use_mmap;
+ bool embeddings;
+ int n_prompt;
+ int n_gen;
+ std::string test_time;
+ std::vector<uint64_t> samples_ns;
+
+ test(const cmd_params_instance & inst, const llama_model * lmodel, const llama_context * ctx) {
+ model_filename = basename(strdup(inst.model.c_str())); // [jart]
+ char buf[128];
+ llama_model_desc(lmodel, buf, sizeof(buf));
+ model_type = buf;
+ model_size = llama_model_size(lmodel);
+ model_n_params = llama_model_n_params(lmodel);
+ n_batch = inst.n_batch;
+ n_ubatch = inst.n_ubatch;
+ n_threads = inst.n_threads;
+ type_k = inst.type_k;
+ type_v = inst.type_v;
+ n_gpu_layers = inst.n_gpu_layers;
+ split_mode = inst.split_mode;
+ main_gpu = inst.main_gpu;
+ no_kv_offload = inst.no_kv_offload;
+ flash_attn = inst.flash_attn;
+ tensor_split = inst.tensor_split;
+ use_mmap = inst.use_mmap;
+ embeddings = inst.embeddings;
+ n_prompt = inst.n_prompt;
+ n_gen = inst.n_gen;
+ // RFC 3339 date-time format
+ time_t t = time(NULL);
+ std::strftime(buf, sizeof(buf), "%FT%TZ", gmtime(&t));
+ test_time = buf;
+
+ (void) ctx;
+ }
+
+ uint64_t avg_ns() const {
+ return ::avg(samples_ns);
+ }
+
+ uint64_t stdev_ns() const {
+ return ::stdev(samples_ns);
+ }
+
+ std::vector<double> get_ts() const {
+ int n_tokens = n_prompt + n_gen;
+ std::vector<double> ts;
+ std::transform(samples_ns.begin(), samples_ns.end(), std::back_inserter(ts), [n_tokens](uint64_t t) { return 1e9 * n_tokens / t; });
+ return ts;
+ }
+
+ double avg_ts() const {
+ return ::avg(get_ts());
+ }
+
+ double stdev_ts() const {
+ return ::stdev(get_ts());
+ }
+
+ static std::string get_backend() {
+ if (cuda) {
+ return GGML_CUDA_NAME;
+ }
+ if (opencl) {
+ return "OpenCL";
+ }
+ if (vulkan) {
+ return "Vulkan";
+ }
+ if (kompute) {
+ return "Kompute";
+ }
+ if (metal) {
+ return "Metal";
+ }
+ // if (sycl) {
+ // return GGML_SYCL_NAME;
+ // }
+ if (gpu_blas) {
+ return "GPU BLAS";
+ }
+ if (blas) {
+ return "BLAS";
+ }
+
+ return "CPU";
+ }
+
+ static const std::vector<std::string> & get_fields() {
+ static const std::vector<std::string> fields = {
+ "build_commit", "build_number",
+ "cuda", "opencl", "vulkan", "kompute", "metal", "sycl", "gpu_blas", "blas",
+ "cpu_info", "gpu_info",
+ "model_filename", "model_type", "model_size", "model_n_params",
+ "n_batch", "n_ubatch",
+ "n_threads", "type_k", "type_v",
+ "n_gpu_layers", "split_mode",
+ "main_gpu", "no_kv_offload", "flash_attn",
+ "tensor_split", "use_mmap", "embeddings",
+ "n_prompt", "n_gen", "test_time",
+ "avg_ns", "stddev_ns",
+ "avg_ts", "stddev_ts"
+ };
+ return fields;
+ }
+
+ enum field_type {STRING, BOOL, INT, FLOAT};
+
+ static field_type get_field_type(const std::string & field) {
+ if (field == "build_number" || field == "n_batch" || field == "n_ubatch" ||
+ field == "n_threads" ||
+ field == "model_size" || field == "model_n_params" ||
+ field == "n_gpu_layers" || field == "main_gpu" ||
+ field == "n_prompt" || field == "n_gen" ||
+ field == "avg_ns" || field == "stddev_ns") {
+ return INT;
+ }
+ if (field == "cuda" || field == "opencl" || field == "vulkan" || field == "kompute" || field == "metal" ||
+ field == "gpu_blas" || field == "blas" || field == "sycl" ||field == "f16_kv" || field == "no_kv_offload" ||
+ field == "flash_attn" || field == "use_mmap" || field == "embeddings") {
+ return BOOL;
+ }
+ if (field == "avg_ts" || field == "stddev_ts") {
+ return FLOAT;
+ }
+ return STRING;
+ }
+
+ std::vector<std::string> get_values() const {
+ std::string tensor_split_str;
+ int max_nonzero = 0;
+ for (size_t i = 0; i < llama_max_devices(); i++) {
+ if (tensor_split[i] > 0) {
+ max_nonzero = i;
+ }
+ }
+ for (int i = 0; i <= max_nonzero; i++) {
+ char buf[32];
+ snprintf(buf, sizeof(buf), "%.2f", tensor_split[i]);
+ tensor_split_str += buf;
+ if (i < max_nonzero) {
+ tensor_split_str += "/";
+ }
+ }
+ std::vector<std::string> values = {
+ build_commit, std::to_string(build_number),
+ std::to_string(cuda), std::to_string(opencl), std::to_string(vulkan), std::to_string(vulkan),
+ std::to_string(metal), std::to_string(sycl), std::to_string(gpu_blas), std::to_string(blas),
+ cpu_info, gpu_info,
+ model_filename, model_type, std::to_string(model_size), std::to_string(model_n_params),
+ std::to_string(n_batch), std::to_string(n_ubatch),
+ std::to_string(n_threads), ggml_type_name(type_k), ggml_type_name(type_v),
+ std::to_string(n_gpu_layers), split_mode_str(split_mode),
+ std::to_string(main_gpu), std::to_string(no_kv_offload), std::to_string(flash_attn),
+ tensor_split_str, std::to_string(use_mmap), std::to_string(embeddings),
+ std::to_string(n_prompt), std::to_string(n_gen), test_time,
+ std::to_string(avg_ns()), std::to_string(stdev_ns()),
+ std::to_string(avg_ts()), std::to_string(stdev_ts())
+ };
+ return values;
+ }
+
+ std::map<std::string, std::string> get_map() const {
+ std::map<std::string, std::string> map;
+ auto fields = get_fields();
+ auto values = get_values();
+ std::transform(fields.begin(), fields.end(), values.begin(),
+ std::inserter(map, map.end()), std::make_pair<const std::string &, const std::string &>);
+ return map;
+ }
+};
+
+const std::string test::build_commit = LLAMA_COMMIT;
+const int test::build_number = LLAMA_BUILD_NUMBER;
+const bool test::cuda = false; // !!ggml_cpu_has_cuda(); // [jart]
+const bool test::opencl = false; // !!ggml_cpu_has_clblast(); // [jart]
+const bool test::vulkan = false; // !!ggml_cpu_has_vulkan(); // [jart]
+const bool test::kompute = false; // !!ggml_cpu_has_kompute(); // [jart]
+const bool test::metal = false; // !!ggml_cpu_has_metal(); // [jart]
+const bool test::gpu_blas = false; // !!ggml_cpu_has_gpublas(); // [jart]
+const bool test::blas = false; // !!ggml_cpu_has_blas(); // [jart]
+const bool test::sycl = false; // !!ggml_cpu_has_sycl(); // [jart]
+const std::string test::cpu_info = get_cpu_info();
+const std::string test::gpu_info = ""; //get_gpu_info(); // [jart]
+
+struct printer {
+ virtual ~printer() {}
+
+ FILE * fout;
+ virtual void print_header(const cmd_params & params) { (void) params; }
+ virtual void print_test(const test & t) = 0;
+ virtual void print_footer() { }
+};
+
+struct csv_printer : public printer {
+ static std::string escape_csv(const std::string & field) {
+ std::string escaped = "\"";
+ for (auto c : field) {
+ if (c == '"') {
+ escaped += "\"";
+ }
+ escaped += c;
+ }
+ escaped += "\"";
+ return escaped;
+ }
+
+ void print_header(const cmd_params & params) override {
+ std::vector<std::string> fields = test::get_fields();
+ fprintf(fout, "%s\n", join(fields, ",").c_str());
+ (void) params;
+ }
+
+ void print_test(const test & t) override {
+ std::vector<std::string> values = t.get_values();
+ std::transform(values.begin(), values.end(), values.begin(), escape_csv);
+ fprintf(fout, "%s\n", join(values, ",").c_str());
+ }
+};
+
+struct json_printer : public printer {
+ bool first = true;
+
+ static std::string escape_json(const std::string & value) {
+ std::string escaped;
+ for (auto c : value) {
+ if (c == '"') {
+ escaped += "\\\"";
+ } else if (c == '\\') {
+ escaped += "\\\\";
+ } else if (c <= 0x1f) {
+ char buf[8];
+ snprintf(buf, sizeof(buf), "\\u%04x", c);
+ escaped += buf;
+ } else {
+ escaped += c;
+ }
+ }
+ return escaped;
+ }
+
+ static std::string format_value(const std::string & field, const std::string & value) {
+ switch (test::get_field_type(field)) {
+ case test::STRING:
+ return "\"" + escape_json(value) + "\"";
+ case test::BOOL:
+ return value == "0" ? "false" : "true";
+ default:
+ return value;
+ }
+ }
+
+ void print_header(const cmd_params & params) override {
+ fprintf(fout, "[\n");
+ (void) params;
+ }
+
+ void print_fields(const std::vector<std::string> & fields, const std::vector<std::string> & values) {
+ assert(fields.size() == values.size());
+ for (size_t i = 0; i < fields.size(); i++) {
+ fprintf(fout, " \"%s\": %s,\n", fields.at(i).c_str(), format_value(fields.at(i), values.at(i)).c_str());
+ }
+ }
+
+ void print_test(const test & t) override {
+ if (first) {
+ first = false;
+ } else {
+ fprintf(fout, ",\n");
+ }
+ fprintf(fout, " {\n");
+ print_fields(test::get_fields(), t.get_values());
+ fprintf(fout, " \"samples_ns\": [ %s ],\n", join(t.samples_ns, ", ").c_str());
+ fprintf(fout, " \"samples_ts\": [ %s ]\n", join(t.get_ts(), ", ").c_str());
+ fprintf(fout, " }");
+ fflush(fout);
+ }
+
+ void print_footer() override {
+ fprintf(fout, "\n]\n");
+ }
+};
+
+struct markdown_printer : public printer {
+ std::vector<std::string> fields;
+
+ static int get_field_width(const std::string & field) {
+ if (field == "model") {
+ return -30;
+ }
+ if (field == "t/s") {
+ return 15; // [jart]
+ }
+ if (field == "cpu_info") {
+ return 48; // [jart]
+ }
+ if (field == "model_filename") {
+ return 35; // [jart]
+ }
+ if (field == "size" || field == "params") {
+ return 10;
+ }
+ if (field == "n_gpu_layers") {
+ return 3;
+ }
+ if (field == "test") {
+ return 13;
+ }
+
+ int width = std::max((int)field.length(), 10);
+
+ if (test::get_field_type(field) == test::STRING) {
+ return -width;
+ }
+ return width;
+ }
+
+ static std::string get_field_display_name(const std::string & field) {
+ if (field == "n_gpu_layers") {
+ return "ngl";
+ }
+ if (field == "split_mode") {
+ return "sm";
+ }
+ if (field == "n_threads") {
+ return "threads";
+ }
+ if (field == "no_kv_offload") {
+ return "nkvo";
+ }
+ if (field == "flash_attn") {
+ return "fa";
+ }
+ if (field == "use_mmap") {
+ return "mmap";
+ }
+ if (field == "embeddings") {
+ return "embd";
+ }
+ if (field == "tensor_split") {
+ return "ts";
+ }
+ return field;
+ }
+
+ void print_header(const cmd_params & params) override {
+ // select fields to print
+ fields.emplace_back("cpu_info"); // [jart]
+ fields.emplace_back("model_filename");
+ // fields.emplace_back("model");
+ // fields.emplace_back("size"); // [jart]
+ // fields.emplace_back("params"); // [jart]
+ // fields.emplace_back("backend"); // [jart]
+ bool is_cpu_backend = test::get_backend() == "CPU" || test::get_backend() == "BLAS";
+ if (!is_cpu_backend) {
+ fields.emplace_back("n_gpu_layers");
+ }
+ // if (params.n_threads.size() > 1 || params.n_threads != cmd_params_defaults.n_threads || is_cpu_backend) {
+ // fields.emplace_back("n_threads");
+ // }
+ if (params.n_batch.size() > 1 || params.n_batch != cmd_params_defaults.n_batch) {
+ fields.emplace_back("n_batch");
+ }
+ if (params.n_ubatch.size() > 1 || params.n_ubatch != cmd_params_defaults.n_ubatch) {
+ fields.emplace_back("n_ubatch");
+ }
+ if (params.type_k.size() > 1 || params.type_k != cmd_params_defaults.type_k) {
+ fields.emplace_back("type_k");
+ }
+ if (params.type_v.size() > 1 || params.type_v != cmd_params_defaults.type_v) {
+ fields.emplace_back("type_v");
+ }
+ if (params.main_gpu.size() > 1 || params.main_gpu != cmd_params_defaults.main_gpu) {
+ fields.emplace_back("main_gpu");
+ }
+ if (params.split_mode.size() > 1 || params.split_mode != cmd_params_defaults.split_mode) {
+ fields.emplace_back("split_mode");
+ }
+ if (params.no_kv_offload.size() > 1 || params.no_kv_offload != cmd_params_defaults.no_kv_offload) {
+ fields.emplace_back("no_kv_offload");
+ }
+ if (params.flash_attn.size() > 1 || params.flash_attn != cmd_params_defaults.flash_attn) {
+ fields.emplace_back("flash_attn");
+ }
+ if (params.tensor_split.size() > 1 || params.tensor_split != cmd_params_defaults.tensor_split) {
+ fields.emplace_back("tensor_split");
+ }
+ if (params.use_mmap.size() > 1 || params.use_mmap != cmd_params_defaults.use_mmap) {
+ fields.emplace_back("use_mmap");
+ }
+ if (params.embeddings.size() > 1 || params.embeddings != cmd_params_defaults.embeddings) {
+ fields.emplace_back("embeddings");
+ }
+ fields.emplace_back("test");
+ fields.emplace_back("t/s");
+
+ fprintf(fout, "|");
+ for (const auto & field : fields) {
+ fprintf(fout, " %*s |", get_field_width(field), get_field_display_name(field).c_str());
+ }
+ fprintf(fout, "\n");
+ fprintf(fout, "|");
+ for (const auto & field : fields) {
+ int width = get_field_width(field);
+ fprintf(fout, " %s%s |", std::string(std::abs(width) - 1, '-').c_str(), width > 0 ? ":" : "-");
+ }
+ fprintf(fout, "\n");
+ }
+
+ void print_test(const test & t) override {
+ std::map<std::string, std::string> vmap = t.get_map();
+
+ fprintf(fout, "|");
+ for (const auto & field : fields) {
+ std::string value;
+ char buf[128];
+ if (field == "model") {
+ value = t.model_type;
+ } else if (field == "size") {
+ if (t.model_size < 1024*1024*1024) {
+ snprintf(buf, sizeof(buf), "%.2f MiB", t.model_size / 1024.0 / 1024.0);
+ } else {
+ snprintf(buf, sizeof(buf), "%.2f GiB", t.model_size / 1024.0 / 1024.0 / 1024.0);
+ }
+ value = buf;
+ } else if (field == "params") {
+ if (t.model_n_params < 1000*1000*1000) {
+ snprintf(buf, sizeof(buf), "%.2f M", t.model_n_params / 1e6);
+ } else {
+ snprintf(buf, sizeof(buf), "%.2f B", t.model_n_params / 1e9);
+ }
+ value = buf;
+ } else if (field == "backend") {
+ value = test::get_backend();
+ } else if (field == "test") {
+ if (t.n_prompt > 0 && t.n_gen == 0) {
+ snprintf(buf, sizeof(buf), "pp%d", t.n_prompt);
+ } else if (t.n_gen > 0 && t.n_prompt == 0) {
+ snprintf(buf, sizeof(buf), "tg%d", t.n_gen);
+ } else {
+ snprintf(buf, sizeof(buf), "pp%d+tg%d", t.n_prompt, t.n_gen);
+ }
+ value = buf;
+ } else if (field == "t/s") {
+ // snprintf(buf, sizeof(buf), "%.2f ± %.2f", t.avg_ts(), t.stdev_ts()); // [jart]
+ snprintf(buf, sizeof(buf), "%.2f", t.avg_ts());
+ value = buf;
+ } else if (vmap.find(field) != vmap.end()) {
+ value = vmap.at(field);
+ } else {
+ assert(false);
+ exit(1);
+ }
+
+ int width = get_field_width(field);
+ if (field == "t/s") {
+ // HACK: the utf-8 character is 2 bytes
+ width += 1;
+ }
+ fprintf(fout, " %*s |", width, value.c_str());
+ }
+ fprintf(fout, "\n");
+ }
+
+ void print_footer() override {
+ // fprintf(fout, "\nbuild: %s (%d)\n", test::build_commit.c_str(), test::build_number); // [jart]
+ }
+};
+
+struct sql_printer : public printer {
+ static std::string get_sql_field_type(const std::string & field) {
+ switch (test::get_field_type(field)) {
+ case test::STRING:
+ return "TEXT";
+ case test::BOOL:
+ case test::INT:
+ return "INTEGER";
+ case test::FLOAT:
+ return "REAL";
+ default:
+ assert(false);
+ exit(1);
+ }
+ }
+
+ void print_header(const cmd_params & params) override {
+ std::vector<std::string> fields = test::get_fields();
+ fprintf(fout, "CREATE TABLE IF NOT EXISTS test (\n");
+ for (size_t i = 0; i < fields.size(); i++) {
+ fprintf(fout, " %s %s%s\n", fields.at(i).c_str(), get_sql_field_type(fields.at(i)).c_str(), i < fields.size() - 1 ? "," : "");
+ }
+ fprintf(fout, ");\n");
+ fprintf(fout, "\n");
+ (void) params;
+ }
+
+ void print_test(const test & t) override {
+ fprintf(fout, "INSERT INTO test (%s) ", join(test::get_fields(), ", ").c_str());
+ fprintf(fout, "VALUES (");
+ std::vector<std::string> values = t.get_values();
+ for (size_t i = 0; i < values.size(); i++) {
+ fprintf(fout, "'%s'%s", values.at(i).c_str(), i < values.size() - 1 ? ", " : "");
+ }
+ fprintf(fout, ");\n");
+ }
+};
+
+static void test_prompt(llama_context * ctx, int n_prompt, int n_past, int n_batch, int n_threads) {
+ llama_set_n_threads(ctx, n_threads, n_threads);
+
+ const llama_model * model = llama_get_model(ctx);
+ const int32_t n_vocab = llama_n_vocab(model);
+
+ std::vector<llama_token> tokens(n_batch);
+
+ int n_processed = 0;
+
+ while (n_processed < n_prompt) {
+ int n_tokens = std::min(n_prompt - n_processed, n_batch);
+ tokens[0] = n_processed == 0 && llama_add_bos_token(model) ? llama_token_bos(model) : std::rand() % n_vocab;
+ for (int i = 1; i < n_tokens; i++) {
+ tokens[i] = std::rand() % n_vocab;
+ }
+ llama_decode(ctx, llama_batch_get_one(tokens.data(), n_tokens, n_past + n_processed, 0));
+ n_processed += n_tokens;
+ }
+
+ llama_synchronize(ctx);
+}
+
+static void test_gen(llama_context * ctx, int n_gen, int n_past, int n_threads) {
+ llama_set_n_threads(ctx, n_threads, n_threads);
+
+ const llama_model * model = llama_get_model(ctx);
+ const int32_t n_vocab = llama_n_vocab(model);
+
+ llama_token token = llama_add_bos_token(model) ? llama_token_bos(model) : std::rand() % n_vocab;
+
+ for (int i = 0; i < n_gen; i++) {
+ llama_decode(ctx, llama_batch_get_one(&token, 1, n_past + i, 0));
+ llama_synchronize(ctx);
+ token = std::rand() % n_vocab;
+ }
+}
+
+static void llama_null_log_callback(enum ggml_log_level level, const char * text, void * user_data) {
+ (void) level;
+ (void) text;
+ (void) user_data;
+}
+
+__attribute__((__constructor__(101))) static void init(void) {
+ FLAG_gpu = LLAMAFILE_GPU_DISABLE; // [jart]
+}
+
+int main(int argc, char ** argv) {
+ // try to set locale for unicode characters in markdown
+ setlocale(LC_CTYPE, ".UTF-8");
+
+#if !defined(NDEBUG)
+ fprintf(stderr, "warning: asserts enabled, performance may be affected\n");
+#endif
+
+#if (defined(_MSC_VER) && defined(_DEBUG)) || (!defined(_MSC_VER) && !defined(__OPTIMIZE__))
+ fprintf(stderr, "warning: debug build, performance may be affected\n");
+#endif
+
+#if defined(__SANITIZE_ADDRESS__) || defined(__SANITIZE_THREAD__)
+ fprintf(stderr, "warning: sanitizer enabled, performance may be affected\n");
+#endif
+
+ cmd_params params = parse_cmd_params(argc, argv);
+
+ // initialize llama.cpp
+ if (!params.verbose) {
+ llama_log_set(llama_null_log_callback, NULL);
+ }
+ llama_backend_init();
+ llama_numa_init(params.numa);
+
+ // initialize printer
+ std::unique_ptr<printer> p;
+ switch (params.output_format) {
+ case CSV:
+ p.reset(new csv_printer());
+ break;
+ case JSON:
+ p.reset(new json_printer());
+ break;
+ case MARKDOWN:
+ p.reset(new markdown_printer());
+ break;
+ case SQL:
+ p.reset(new sql_printer());
+ break;
+ default:
+ assert(false);
+ exit(1);
+ }
+ p->fout = stdout;
+ p->print_header(params);
+
+ std::vector<cmd_params_instance> params_instances = get_cmd_params_instances(params);
+
+ llama_model * lmodel = nullptr;
+ const cmd_params_instance * prev_inst = nullptr;
+
+ for (const auto & inst : params_instances) {
+ // keep the same model between tests when possible
+ if (!lmodel || !prev_inst || !inst.equal_mparams(*prev_inst)) {
+ if (lmodel) {
+ llama_free_model(lmodel);
+ }
+
+ lmodel = llama_load_model_from_file(inst.model.c_str(), inst.to_llama_mparams());
+ if (lmodel == NULL) {
+ fprintf(stderr, "%s: error: failed to load model '%s'\n", __func__, inst.model.c_str());
+ return 1;
+ }
+ prev_inst = &inst;
+ }
+
+ llama_context * ctx = llama_new_context_with_model(lmodel, inst.to_llama_cparams());
+ if (ctx == NULL) {
+ fprintf(stderr, "%s: error: failed to create context with model '%s'\n", __func__, inst.model.c_str());
+ llama_free_model(lmodel);
+ return 1;
+ }
+
+ test t(inst, lmodel, ctx);
+
+ llama_kv_cache_clear(ctx);
+
+ // warmup run
+ if (t.n_prompt > 0) {
+ //test_prompt(ctx, std::min(t.n_batch, std::min(t.n_prompt, 32)), 0, t.n_batch, t.n_threads);
+ test_prompt(ctx, t.n_prompt, 0, t.n_batch, t.n_threads);
+ }
+ if (t.n_gen > 0) {
+ test_gen(ctx, 1, 0, t.n_threads);
+ }
+
+ for (int i = 0; i < params.reps; i++) {
+ llama_kv_cache_clear(ctx);
+
+ uint64_t t_start = get_time_ns();
+
+ if (t.n_prompt > 0) {
+ test_prompt(ctx, t.n_prompt, 0, t.n_batch, t.n_threads);
+ }
+ if (t.n_gen > 0) {
+ test_gen(ctx, t.n_gen, t.n_prompt, t.n_threads);
+ }
+
+ uint64_t t_ns = get_time_ns() - t_start;
+ t.samples_ns.push_back(t_ns);
+ }
+
+ p->print_test(t);
+
+ llama_print_timings(ctx);
+
+ llama_free(ctx);
+
+ // [jart] let cpu cool off
+ sleep(7);
+ }
+
+ llama_free_model(lmodel);
+
+ p->print_footer();
+
+ llama_backend_free();
+
+ return 0;
+}
diff --git a/llama.cpp/llama-bench/main.1 b/llama.cpp/llama-bench/main.1
new file mode 100644
index 00000000..d2f51bfc
--- /dev/null
+++ b/llama.cpp/llama-bench/main.1
@@ -0,0 +1,916 @@
+.Dd January 1, 2024
+.Dt LLAMAFILE 1
+.Os Mozilla Ocho
+.Sh NAME
+.Nm llamafile
+.Nd large language model runner
+.Sh SYNOPSIS
+.Nm
+.Op Fl Fl server
+.Op flags...
+.Fl m Ar model.gguf
+.Op Fl Fl mmproj Ar vision.gguf
+.Nm
+.Op Fl Fl cli
+.Op flags...
+.Fl m Ar model.gguf
+.Fl p Ar prompt
+.Nm
+.Op Fl Fl cli
+.Op flags...
+.Fl m Ar model.gguf
+.Fl Fl mmproj Ar vision.gguf
+.Fl Fl image Ar graphic.png
+.Fl p Ar prompt
+.Sh DESCRIPTION
+.Nm
+is a large language model tool. It has use cases such as:
+.Pp
+.Bl -dash -compact
+.It
+Code completion
+.It
+Prose composition
+.It
+Chatbot that passes the Turing test
+.It
+Text/image summarization and analysis
+.El
+.Sh OPTIONS
+The following options are available:
+.Bl -tag -width indent
+.It Fl Fl version
+Print version and exit.
+.It Fl h , Fl Fl help
+Show help message and exit.
+.It Fl Fl cli
+Puts program in command line interface mode. This flag is implied when a
+prompt is supplied using either the
+.Fl p
+or
+.Fl f
+flags.
+.It Fl Fl server
+Puts program in server mode. This will launch an HTTP server on a local
+port. This server has both a web UI and an OpenAI API compatible
+completions endpoint. When the server is run on a desk system, a tab
+browser tab will be launched automatically that displays the web UI.
+This
+.Fl Fl server
+flag is implied if no prompt is specified, i.e. neither the
+.Fl p
+or
+.Fl f
+flags are passed.
+.It Fl m Ar FNAME , Fl Fl model Ar FNAME
+Model path in the GGUF file format.
+.Pp
+Default:
+.Pa models/7B/ggml-model-f16.gguf
+.It Fl Fl mmproj Ar FNAME
+Specifies path of the LLaVA vision model in the GGUF file format. If
+this flag is supplied, then the
+.Fl Fl model
+and
+.Fl Fl image
+flags should also be supplied.
+.It Fl s Ar SEED , Fl Fl seed Ar SEED
+Random Number Generator (RNG) seed. A random seed is used if this is
+less than zero.
+.Pp
+Default: -1
+.It Fl t Ar N , Fl Fl threads Ar N
+Number of threads to use during generation.
+.Pp
+Default: $(nproc)/2
+.It Fl tb Ar N , Fl Fl threads-batch Ar N
+Set the number of threads to use during batch and prompt processing. In
+some systems, it is beneficial to use a higher number of threads during
+batch processing than during generation. If not specified, the number of
+threads used for batch processing will be the same as the number of
+threads used for generation.
+.Pp
+Default: Same as
+.Fl Fl threads
+.It Fl td Ar N , Fl Fl threads-draft Ar N
+Number of threads to use during generation.
+.Pp
+Default: Same as
+.Fl Fl threads
+.It Fl tbd Ar N , Fl Fl threads-batch-draft Ar N
+Number of threads to use during batch and prompt processing.
+.Pp
+Default: Same as
+.Fl Fl threads-draft
+.It Fl Fl in-prefix-bos
+Prefix BOS to user inputs, preceding the
+.Fl Fl in-prefix
+string.
+.It Fl Fl in-prefix Ar STRING
+This 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
+.Fl Fl in-prefix
+flag in conjunction with the
+.Fl Fl reverse-prompt
+flag:
+.Pp
+.Dl "./main -r \[dq]User:\[dq] --in-prefix \[dq] \[dq]"
+.Pp
+Default: empty
+.It Fl Fl in-suffix Ar STRING
+This flag is used to add a suffix after your input. This is useful for
+adding an \[dq]Assistant:\[dq] prompt after the user's input. It's added
+after the new-line character (\[rs]n) that's automatically added to the
+end of the user's input. Here's an example of how to use the
+.Fl Fl in-suffix
+flag in conjunction with the
+.Fl Fl reverse-prompt
+flag:
+.Pp
+.Dl "./main -r \[dq]User:\[dq] --in-prefix \[dq] \[dq] --in-suffix \[dq]Assistant:\[dq]"
+.Pp
+Default: empty
+.It Fl n Ar N , Fl Fl n-predict Ar N
+Number of tokens to predict.
+.Pp
+.Bl -dash -compact
+.It
+-1 = infinity
+.It
+-2 = until context filled
+.El
+.Pp
+Default: -1
+.It Fl c Ar N , Fl Fl ctx-size Ar N
+Set the size of the prompt context. A larger context size helps the
+model to better comprehend and generate responses for longer input or
+conversations. The LLaMA models were built with a context of 2048, which
+yields the best results on longer input / inference.
+.Pp
+.Bl -dash -compact
+.It
+0 = loaded automatically from model
+.El
+.Pp
+Default: 512
+.It Fl b Ar N , Fl Fl batch-size Ar N
+Batch size for prompt processing.
+.Pp
+Default: 512
+.It Fl Fl top-k Ar N
+Top-k sampling.
+.Pp
+.Bl -dash -compact
+.It
+0 = disabled
+.El
+.Pp
+Default: 40
+.It Fl Fl top-p Ar N
+Top-p sampling.
+.Pp
+.Bl -dash -compact
+.It
+1.0 = disabled
+.El
+.Pp
+Default: 0.9
+.It Fl Fl min-p Ar N
+Min-p sampling.
+.Pp
+.Bl -dash -compact
+.It
+0.0 = disabled
+.El
+.Pp
+Default: 0.1
+.It Fl Fl tfs Ar N
+Tail free sampling, parameter z.
+.Pp
+.Bl -dash -compact
+.It
+1.0 = disabled
+.El
+.Pp
+Default: 1.0
+.It Fl Fl typical Ar N
+Locally typical sampling, parameter p.
+.Pp
+.Bl -dash -compact
+.It
+1.0 = disabled
+.El
+.Pp
+Default: 1.0
+.It Fl Fl repeat-last-n Ar N
+Last n tokens to consider for penalize.
+.Pp
+.Bl -dash -compact
+.It
+0 = disabled
+.It
+-1 = ctx_size
+.El
+.Pp
+Default: 64
+.It Fl Fl repeat-penalty Ar N
+Penalize repeat sequence of tokens.
+.Pp
+.Bl -dash -compact
+.It
+1.0 = disabled
+.El
+.Pp
+Default: 1.1
+.It Fl Fl presence-penalty Ar N
+Repeat alpha presence penalty.
+.Pp
+.Bl -dash -compact
+.It
+0.0 = disabled
+.El
+.Pp
+Default: 0.0
+.It Fl Fl frequency-penalty Ar N
+Repeat alpha frequency penalty.
+.Pp
+.Bl -dash -compact
+.It
+0.0 = disabled
+.El
+.Pp
+Default: 0.0
+.It Fl Fl mirostat Ar N
+Use Mirostat sampling. Top K, Nucleus, Tail Free and Locally Typical samplers are ignored if used..
+.Pp
+.Bl -dash -compact
+.It
+0 = disabled
+.It
+1 = Mirostat
+.It
+2 = Mirostat 2.0
+.El
+.Pp
+Default: 0
+.It Fl Fl mirostat-lr Ar N
+Mirostat learning rate, parameter eta.
+.Pp
+Default: 0.1
+.It Fl Fl mirostat-ent Ar N
+Mirostat target entropy, parameter tau.
+.Pp
+Default: 5.0
+.It Fl l Ar TOKEN_ID(+/-)BIAS , Fl Fl logit-bias Ar TOKEN_ID(+/-)BIAS
+Modifies the likelihood of token appearing in the completion, i.e.
+.Fl Fl logit-bias Ar 15043+1
+to increase likelihood of token
+.Ar ' Hello' ,
+or
+.Fl Fl logit-bias Ar 15043-1
+to decrease likelihood of token
+.Ar ' Hello' .
+.It Fl md Ar FNAME , Fl Fl model-draft Ar FNAME
+Draft model for speculative decoding.
+.Pp
+Default:
+.Pa models/7B/ggml-model-f16.gguf
+.It Fl Fl cfg-negative-prompt Ar PROMPT
+Negative prompt to use for guidance..
+.Pp
+Default: empty
+.It Fl Fl cfg-negative-prompt-file Ar FNAME
+Negative prompt file to use for guidance.
+.Pp
+Default: empty
+.It Fl Fl cfg-scale Ar N
+Strength of guidance.
+.Pp
+.Bl -dash -compact
+.It
+1.0 = disable
+.El
+.Pp
+Default: 1.0
+.It Fl Fl rope-scaling Ar {none,linear,yarn}
+RoPE frequency scaling method, defaults to linear unless specified by the model
+.It Fl Fl rope-scale Ar N
+RoPE context scaling factor, expands context by a factor of
+.Ar N
+where
+.Ar N
+is the linear scaling factor used by the fine-tuned model. Some
+fine-tuned models have extended the context length by scaling RoPE. For
+example, if the original pre-trained model have a context length (max
+sequence length) of 4096 (4k) and the fine-tuned model have 32k. That is
+a scaling factor of 8, and should work by setting the above
+.Fl Fl ctx-size
+to 32768 (32k) and
+.Fl Fl rope-scale
+to 8.
+.It Fl Fl rope-freq-base Ar N
+RoPE base frequency, used by NTK-aware scaling.
+.Pp
+Default: loaded from model
+.It Fl Fl rope-freq-scale Ar N
+RoPE frequency scaling factor, expands context by a factor of 1/N
+.It Fl Fl yarn-orig-ctx Ar N
+YaRN: original context size of model.
+.Pp
+Default: 0 = model training context size
+.It Fl Fl yarn-ext-factor Ar N
+YaRN: extrapolation mix factor.
+.Pp
+.Bl -dash -compact
+.It
+0.0 = full interpolation
+.El
+.Pp
+Default: 1.0
+.It Fl Fl yarn-attn-factor Ar N
+YaRN: scale sqrt(t) or attention magnitude.
+.Pp
+Default: 1.0
+.It Fl Fl yarn-beta-slow Ar N
+YaRN: high correction dim or alpha.
+.Pp
+Default: 1.0
+.It Fl Fl yarn-beta-fast Ar N
+YaRN: low correction dim or beta.
+.Pp
+Default: 32.0
+.It Fl Fl ignore-eos
+Ignore end of stream token and continue generating (implies
+.Fl Fl logit-bias Ar 2-inf )
+.It Fl Fl no-penalize-nl
+Do not penalize newline token.
+.It Fl Fl temp Ar N
+Temperature.
+.Pp
+Default: 0.8
+.It Fl Fl logits-all
+Return logits for all tokens in the batch.
+.Pp
+Default: disabled
+.It Fl Fl hellaswag
+Compute HellaSwag score over random tasks from datafile supplied with -f
+.It Fl Fl hellaswag-tasks Ar N
+Number of tasks to use when computing the HellaSwag score.
+.Pp
+Default: 400
+.It Fl Fl keep Ar N
+This flag 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, where
+.Ar N
+is the number of tokens from the initial prompt to retain when the model
+resets its internal context.
+.Pp
+.Bl -dash -compact
+.It
+0 = no tokens are kept from initial prompt
+.It
+-1 = retain all tokens from initial prompt
+.El
+.Pp
+Default: 0
+.It Fl Fl draft Ar N
+Number of tokens to draft for speculative decoding.
+.Pp
+Default: 16
+.It Fl Fl chunks Ar N
+Max number of chunks to process.
+.Pp
+.Bl -dash -compact
+.It
+-1 = all
+.El
+.Pp
+Default: -1
+.It Fl ns Ar N , Fl Fl sequences Ar N
+Number of sequences to decode.
+.Pp
+Default: 1
+.It Fl pa Ar N , Fl Fl p-accept Ar N
+speculative decoding accept probability.
+.Pp
+Default: 0.5
+.It Fl ps Ar N , Fl Fl p-split Ar N
+Speculative decoding split probability.
+.Pp
+Default: 0.1
+.It Fl Fl mlock
+Force system to keep model in RAM rather than swapping or compressing.
+.It Fl Fl no-mmap
+Do not memory-map model (slower load but may reduce pageouts if not using mlock).
+.It Fl Fl numa
+Attempt optimizations that help on some NUMA systems if run without this previously, it is recommended to drop the system page cache before using this. See https://github.com/ggerganov/llama.cpp/issues/1437.
+.It Fl Fl recompile
+Force GPU support to be recompiled at runtime if possible.
+.It Fl Fl nocompile
+Never compile GPU support at runtime.
+.Pp
+If the appropriate DSO file already exists under
+.Pa ~/.llamafile/
+then it'll be linked as-is without question. If a prebuilt DSO is
+present in the PKZIP content of the executable, then it'll be extracted
+and linked if possible. Otherwise,
+.Nm
+will skip any attempt to compile GPU support and simply fall back to
+using CPU inference.
+.It Fl Fl gpu Ar GPU
+Specifies which brand of GPU should be used. Valid choices are:
+.Pp
+.Bl -dash
+.It
+.Ar AUTO :
+Use any GPU if possible, otherwise fall back to CPU inference (default)
+.It
+.Ar APPLE :
+Use Apple Metal GPU. This is only available on MacOS ARM64. If Metal
+could not be used for any reason, then a fatal error will be raised.
+.It
+.Ar AMD :
+Use AMD GPUs. The AMD HIP ROCm SDK should be installed in which case we
+assume the HIP_PATH environment variable has been defined. The set of
+gfx microarchitectures needed to run on the host machine is determined
+automatically based on the output of the hipInfo command. On Windows,
+.Nm
+release binaries are distributed with a tinyBLAS DLL so it'll work out
+of the box without requiring the HIP SDK to be installed. However,
+tinyBLAS is slower than rocBLAS for batch and image processing, so it's
+recommended that the SDK be installed anyway. If an AMD GPU could not be
+used for any reason, then a fatal error will be raised.
+.It
+.Ar NVIDIA :
+Use NVIDIA GPUs. If an NVIDIA GPU could not be used for any reason, a
+fatal error will be raised. On Windows, NVIDIA GPU support will use our
+tinyBLAS library, since it works on stock Windows installs. However,
+tinyBLAS goes slower for batch and image processing. It's possible to
+use NVIDIA's closed-source cuBLAS library instead. To do that, both MSVC
+and CUDA need to be installed and the
+.Nm
+command should be run once from the x64 MSVC command prompt with the
+.Fl Fl recompile
+flag passed. The GGML library will then be compiled and saved to
+.Pa ~/.llamafile/
+so the special process only needs to happen a single time.
+.It
+.Ar DISABLE :
+Never use GPU and instead use CPU inference. This setting is implied by
+.Fl ngl Ar 0 .
+.El
+.Pp
+.It Fl ngl Ar N , Fl Fl n-gpu-layers Ar N
+Number of layers to store in VRAM.
+.It Fl ngld Ar N , Fl Fl n-gpu-layers-draft Ar N
+Number of layers to store in VRAM for the draft model.
+.It Fl sm Ar SPLIT_MODE , Fl Fl split-mode Ar SPLIT_MODE
+How to split the model across multiple GPUs, one of:
+.Bl -dash -compact
+.It
+none: use one GPU only
+.It
+layer (default): split layers and KV across GPUs
+.It
+row: split rows across GPUs
+.El
+.It Fl ts Ar SPLIT , Fl Fl tensor-split Ar SPLIT
+When using multiple GPUs this option controls how large tensors should
+be split across all GPUs.
+.Ar SPLIT
+is a comma-separated list of non-negative values that assigns the
+proportion of data that each GPU should get in order. For example,
+\[dq]3,2\[dq] will assign 60% of the data to GPU 0 and 40% to GPU 1. By
+default the data is split in proportion to VRAM but this may not be
+optimal for performance. Requires cuBLAS.
+How to split tensors across multiple GPUs, comma-separated list of
+proportions, e.g. 3,1
+.It Fl mg Ar i , Fl Fl main-gpu Ar i
+The GPU to use for scratch and small tensors.
+.It Fl nommq , Fl Fl no-mul-mat-q
+Use cuBLAS instead of custom mul_mat_q CUDA kernels. Not recommended since this is both slower and uses more VRAM.
+.It Fl Fl verbose-prompt
+Print prompt before generation.
+.It Fl Fl simple-io
+Use basic IO for better compatibility in subprocesses and limited consoles.
+.It Fl Fl lora Ar FNAME
+Apply LoRA adapter (implies
+.Fl Fl no-mmap )
+.It Fl Fl lora-scaled Ar FNAME Ar S
+Apply LoRA adapter with user defined scaling S (implies
+.Fl Fl no-mmap )
+.It Fl Fl lora-base Ar FNAME
+Optional model to use as a base for the layers modified by the LoRA adapter
+.It Fl Fl unsecure
+Disables pledge() sandboxing on Linux and OpenBSD.
+.It Fl Fl samplers
+Samplers that will be used for generation in the order, separated by
+semicolon, for example: top_k;tfs;typical;top_p;min_p;temp
+.It Fl Fl samplers-seq
+Simplified sequence for samplers that will be used.
+.It Fl cml , Fl Fl chatml
+Run in chatml mode (use with ChatML-compatible models)
+.It Fl dkvc , Fl Fl dump-kv-cache
+Verbose print of the KV cache.
+.It Fl nkvo , Fl Fl no-kv-offload
+Disable KV offload.
+.It Fl ctk Ar TYPE , Fl Fl cache-type-k Ar TYPE
+KV cache data type for K.
+.It Fl ctv Ar TYPE , Fl Fl cache-type-v Ar TYPE
+KV cache data type for V.
+.It Fl gan Ar N , Fl Fl grp-attn-n Ar N
+Group-attention factor.
+.Pp
+Default: 1
+.It Fl gaw Ar N , Fl Fl grp-attn-w Ar N
+Group-attention width.
+.Pp
+Default: 512
+.It Fl bf Ar FNAME , Fl Fl binary-file Ar FNAME
+Binary file containing multiple choice tasks.
+.It Fl Fl winogrande
+Compute Winogrande score over random tasks from datafile supplied by the
+.Fl f
+flag.
+.It Fl Fl winogrande-tasks Ar N
+Number of tasks to use when computing the Winogrande score.
+.Pp
+Default: 0
+.It Fl Fl multiple-choice
+Compute multiple choice score over random tasks from datafile supplied
+by the
+.Fl f
+flag.
+.It Fl Fl multiple-choice-tasks Ar N
+Number of tasks to use when computing the multiple choice score.
+.Pp
+Default: 0
+.It Fl Fl kl-divergence
+Computes KL-divergence to logits provided via the
+.Fl Fl kl-divergence-base
+flag.
+.It Fl Fl save-all-logits Ar FNAME , Fl Fl kl-divergence-base Ar FNAME
+Save logits to filename.
+.It Fl ptc Ar N , Fl Fl print-token-count Ar N
+Print token count every
+.Ar N
+tokens.
+.Pp
+Default: -1
+.It Fl Fl pooling Ar KIND
+Specifies pooling type for embeddings. This may be one of:
+.Pp
+.Bl -dash -compact
+.It
+none
+.It
+mean
+.It
+cls
+.El
+.Pp
+The model default is used if unspecified.
+.El
+.Sh CLI OPTIONS
+The following options may be specified when
+.Nm
+is running in
+.Fl Fl cli
+mode.
+.Bl -tag -width indent
+.It Fl e , Fl Fl escape
+Process prompt escapes sequences (\[rs]n, \[rs]r, \[rs]t, \[rs]\[aa], \[rs]\[dq], \[rs]\[rs])
+.It Fl p Ar STRING , Fl Fl prompt Ar STRING
+Prompt to start text generation. Your LLM works by auto-completing this
+text. For example:
+.Pp
+.Dl "llamafile -m model.gguf -p \[dq]four score and\[dq]"
+.Pp
+Stands a pretty good chance of printing Lincoln's Gettysburg Address.
+Prompts can take on a structured format too. Depending on how your model
+was trained, it may specify in its docs an instruction notation. With
+some models that might be:
+.Pp
+.Dl "llamafile -p \[dq][INST]Summarize this: $(cat file)[/INST]\[dq]"
+.Pp
+In most cases, simply colons and newlines will work too:
+.Pp
+.Dl "llamafile -e -p \[dq]User: What is best in life?\[rs]nAssistant:\[dq]"
+.Pp
+.It Fl f Ar FNAME , Fl Fl file Ar FNAME
+Prompt file to start generation.
+.It Fl Fl grammar Ar GRAMMAR
+BNF-like grammar to constrain which tokens may be selected when
+generating text. For example, the grammar:
+.Pp
+.Dl "root ::= \[dq]yes\[dq] | \[dq]no\[dq]"
+.Pp
+will force the LLM to only output yes or no before exiting. This is
+useful for shell scripts when the
+.Fl Fl no-display-prompt
+flag is also supplied.
+.It Fl Fl grammar-file Ar FNAME
+File to read grammar from.
+.It Fl Fl fast
+Put llamafile into fast math mode. This disables algorithms that reduce
+floating point rounding, e.g. Kahan summation, and certain functions
+like expf() will be vectorized but handle underflows less gracefully.
+It's unspecified whether llamafile runs in fast or precise math mode
+when neither flag is specified.
+.It Fl Fl precise
+Put llamafile into precise math mode. This enables algorithms that
+reduce floating point rounding, e.g. Kahan summation, and certain
+functions like expf() will always handle subnormals correctly. It's
+unspecified whether llamafile runs in fast or precise math mode when
+neither flag is specified.
+.It Fl Fl trap
+Put llamafile into math trapping mode. When floating point exceptions
+occur, such as NaNs, overflow, and divide by zero, llamafile will print
+a warning to the console. This warning will include a C++ backtrace the
+first time an exception is trapped. The op graph will also be dumped to
+a file, and llamafile will report the specific op where the exception
+occurred. This is useful for troubleshooting when reporting issues.
+USing this feature will disable sandboxing. Math trapping is only
+possible if your CPU supports it. That is generally the case on AMD64,
+however it's less common on ARM64.
+.It Fl Fl prompt-cache Ar FNAME
+File to cache prompt state for faster startup.
+.Pp
+Default: none
+.It Fl fa Ar FNAME , Fl Fl flash-attn
+Enable Flash Attention. This is a mathematical shortcut that can speed
+up inference for certain models. This feature is still under active
+development.
+.It Fl Fl prompt-cache-all
+If specified, saves user input and generations to cache as well. Not supported with
+.Fl Fl interactive
+or other interactive options.
+.It Fl Fl prompt-cache-ro
+If specified, uses the prompt cache but does not update it.
+.It Fl Fl random-prompt
+Start with a randomized prompt.
+.It Fl Fl image Ar IMAGE_FILE
+Path to an image file. This should be used with multimodal models.
+Alternatively, it's possible to embed an image directly into the prompt
+instead; in which case, it must be base64 encoded into an HTML img tag
+URL with the image/jpeg MIME type. See also the
+.Fl Fl mmproj
+flag for supplying the vision model.
+.It Fl i , Fl Fl interactive
+Run the program in interactive mode, allowing users to engage in
+real-time conversations or provide specific instructions to the model.
+.It Fl Fl interactive-first
+Run the program in interactive mode and immediately wait for user input
+before starting the text generation.
+.It Fl ins , Fl Fl instruct
+Run the program in instruction mode, which is specifically designed to
+work with Alpaca models that excel in completing tasks based on user
+instructions.
+.Pp
+Technical details: The user's input is internally prefixed with the
+reverse prompt (or \[dq]### Instruction:\[dq] as the default), and
+followed by \[dq]### Response:\[dq] (except if you just press Return
+without any input, to keep generating a longer response).
+.Pp
+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.
+.It Fl r Ar PROMPT , Fl Fl reverse-prompt Ar PROMPT
+Specify one or multiple reverse prompts to pause text generation and
+switch to interactive mode. For example,
+.Fl r Ar \[dq]User:\[dq]
+can be used to jump back into the conversation whenever it's the user's
+turn to speak. This helps create a more interactive and conversational
+experience. However, the reverse prompt doesn't work when it ends with a
+space. To overcome this limitation, you can use the
+.Fl Fl in-prefix
+flag to add a space or any other characters after the reverse prompt.
+.It Fl Fl color
+Enable colorized output to differentiate visually distinguishing between
+prompts, user input, and generated text.
+.It Fl Fl no-display-prompt , Fl Fl silent-prompt
+Don't echo the prompt itself to standard output.
+.It Fl Fl keep Ar N
+Specifies number of tokens to keep from the initial prompt. The default
+is -1 which means all tokens.
+.It Fl Fl multiline-input
+Allows you to write or paste multiple lines without ending each in '\[rs]'.
+.It Fl Fl cont-batching
+Enables continuous batching, a.k.a. dynamic batching.
+is -1 which means all tokens.
+.It Fl Fl embedding
+In CLI mode, the embedding flag may be use to print embeddings to
+standard output. By default, embeddings are computed over a whole
+prompt. However the
+.Fl Fl multiline
+flag may be passed, to have a separate embeddings array computed for
+each line of text in the prompt. In multiline mode, each embedding array
+will be printed on its own line to standard output, where individual
+floats are separated by space. If both the
+.Fl Fl multiline-input
+and
+.Fl Fl interactive
+flags are passed, then a pretty-printed summary of embeddings along with
+a cosine similarity matrix will be printed to the terminal.
+.El
+.Sh SERVER OPTIONS
+The following options may be specified when
+.Nm
+is running in
+.Fl Fl server
+mode.
+.Bl -tag -width indent
+.It Fl Fl port Ar PORT
+Port to listen
+.Pp
+Default: 8080
+.It Fl Fl host Ar IPADDR
+IP address to listen.
+.Pp
+Default: 127.0.0.1
+.It Fl to Ar N , Fl Fl timeout Ar N
+Server read/write timeout in seconds.
+.Pp
+Default: 600
+.It Fl np Ar N , Fl Fl parallel Ar N
+Number of slots for process requests.
+.Pp
+Default: 1
+.It Fl cb , Fl Fl cont-batching
+Enable continuous batching (a.k.a dynamic batching).
+.Pp
+Default: disabled
+.It Fl spf Ar FNAME , Fl Fl system-prompt-file Ar FNAME
+Set a file to load a system prompt (initial prompt of all slots), this
+is useful for chat applications.
+.It Fl a Ar ALIAS , Fl Fl alias Ar ALIAS
+Set an alias for the model. This will be added as the
+.Ar model
+field in completion responses.
+.It Fl Fl path Ar PUBLIC_PATH
+Path from which to serve static files.
+.Pp
+Default:
+.Pa /zip/llama.cpp/server/public
+.It Fl Fl nobrowser
+Do not attempt to open a web browser tab at startup.
+.It Fl gan Ar N , Fl Fl grp-attn-n Ar N
+Set the group attention factor to extend context size through
+self-extend. The default value is
+.Ar 1
+which means disabled. This flag is used together with
+.Fl Fl grp-attn-w .
+.It Fl gaw Ar N , Fl Fl grp-attn-w Ar N
+Set the group attention width to extend context size through
+self-extend. The default value is
+.Ar 512 .
+This flag is used together with
+.Fl Fl grp-attn-n .
+.El
+.Sh LOG OPTIONS
+The following log options are available:
+.Bl -tag -width indent
+.It Fl ld Ar LOGDIR , Fl Fl logdir Ar LOGDIR
+Path under which to save YAML logs (no logging if unset)
+.It Fl Fl log-test
+Run simple logging test
+.It Fl Fl log-disable
+Disable trace logs
+.It Fl Fl log-enable
+Enable trace logs
+.It Fl Fl log-file
+Specify a log filename (without extension)
+.It Fl Fl log-new
+Create a separate new log file on start. Each log file will have unique name:
+.Fa <name>.<ID>.log
+.It Fl Fl log-append
+Don't truncate the old log file.
+.El
+.Sh EXAMPLES
+Here's an example of how to run llama.cpp's built-in HTTP server. This
+example uses LLaVA v1.5-7B, a multimodal LLM that works with llama.cpp's
+recently-added support for image inputs.
+.Bd -literal -offset indent
+llamafile \[rs]
+ -m llava-v1.5-7b-Q8_0.gguf \[rs]
+ --mmproj llava-v1.5-7b-mmproj-Q8_0.gguf \[rs]
+ --host 0.0.0.0
+.Ed
+.Pp
+Here's an example of how to generate code for a libc function using the
+llama.cpp command line interface, utilizing WizardCoder-Python-13B
+weights:
+.Bd -literal -offset indent
+llamafile \[rs]
+ -m wizardcoder-python-13b-v1.0.Q8_0.gguf --temp 0 -r '}\[rs]n' -r '\`\`\`\[rs]n' \[rs]
+ -e -p '\`\`\`c\[rs]nvoid *memcpy(void *dst, const void *src, size_t size) {\[rs]n'
+.Ed
+.Pp
+Here's a similar example that instead utilizes Mistral-7B-Instruct
+weights for prose composition:
+.Bd -literal -offset indent
+llamafile \[rs]
+ -m mistral-7b-instruct-v0.2.Q5_K_M.gguf \[rs]
+ -p '[INST]Write a story about llamas[/INST]'
+.Ed
+.Pp
+Here's an example of how llamafile can be used as an interactive chatbot
+that lets you query knowledge contained in training data:
+.Bd -literal -offset indent
+llamafile -m llama-65b-Q5_K.gguf -p '
+The following is a conversation between a Researcher and their helpful AI
+assistant Digital Athena which is a large language model trained on the
+sum of human knowledge.
+Researcher: Good morning.
+Digital Athena: How can I help you today?
+Researcher:' --interactive --color --batch_size 1024 --ctx_size 4096 \[rs]
+--keep -1 --temp 0 --mirostat 2 --in-prefix ' ' --interactive-first \[rs]
+--in-suffix 'Digital Athena:' --reverse-prompt 'Researcher:'
+.Ed
+.Pp
+Here's an example of how you can use llamafile to summarize HTML URLs:
+.Bd -literal -offset indent
+(
+ echo '[INST]Summarize the following text:'
+ links -codepage utf-8 \[rs]
+ -force-html \[rs]
+ -width 500 \[rs]
+ -dump https://www.poetryfoundation.org/poems/48860/the-raven |
+ sed 's/ */ /g'
+ echo '[/INST]'
+) | llamafile \[rs]
+ -m mistral-7b-instruct-v0.2.Q5_K_M.gguf \[rs]
+ -f /dev/stdin \[rs]
+ -c 0 \[rs]
+ --temp 0 \[rs]
+ -n 500 \[rs]
+ --no-display-prompt 2>/dev/null
+.Ed
+.Pp
+Here's how you can use llamafile to describe a jpg/png/gif/bmp image:
+.Bd -literal -offset indent
+llamafile --temp 0 \[rs]
+ --image lemurs.jpg \[rs]
+ -m llava-v1.5-7b-Q4_K.gguf \[rs]
+ --mmproj llava-v1.5-7b-mmproj-Q4_0.gguf \[rs]
+ -e -p '### User: What do you see?\[rs]n### Assistant: ' \[rs]
+ --no-display-prompt 2>/dev/null
+.Ed
+.Pp
+If you wanted to write a script to rename all your image files, you
+could use the following command to generate a safe filename:
+.Bd -literal -offset indent
+llamafile --temp 0 \[rs]
+ --image ~/Pictures/lemurs.jpg \[rs]
+ -m llava-v1.5-7b-Q4_K.gguf \[rs]
+ --mmproj llava-v1.5-7b-mmproj-Q4_0.gguf \[rs]
+ --grammar 'root ::= [a-z]+ (" " [a-z]+)+' \[rs]
+ -e -p '### User: The image has...\[rs]n### Assistant: ' \[rs]
+ --no-display-prompt 2>/dev/null |
+ sed -e's/ /_/g' -e's/$/.jpg/'
+three_baby_lemurs_on_the_back_of_an_adult_lemur.jpg
+.Ed
+.Pp
+Here's an example of how to make an API request to the OpenAI API
+compatible completions endpoint when your
+.Nm
+is running in the background in
+.Fl Fl server
+mode.
+.Bd -literal -offset indent
+curl -s http://localhost:8080/v1/chat/completions \[rs]
+ -H "Content-Type: application/json" -d '{
+ "model": "gpt-3.5-turbo",
+ "stream": true,
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are a poetic assistant."
+ },
+ {
+ "role": "user",
+ "content": "Compose a poem that explains FORTRAN."
+ }
+ ]
+}' | python3 -c '
+import json
+import sys
+json.dump(json.load(sys.stdin), sys.stdout, indent=2)
+print()
+'
+.Ed
+.Sh PROTIP
+The
+.Fl ngl Ar 35
+flag needs to be passed in order to use GPUs made by NVIDIA and AMD.
+It's not enabled by default since it sometimes needs to be tuned based
+on the system hardware and model architecture, in order to achieve
+optimal performance, and avoid compromising a shared display.
+.Sh SEE ALSO
+.Xr llamafile-quantize 1 ,
+.Xr llamafile-perplexity 1 ,
+.Xr llava-quantize 1 ,
+.Xr zipalign 1 ,
+.Xr unzip 1
diff --git a/llama.cpp/llama-bench/main.1.asc b/llama.cpp/llama-bench/main.1.asc
new file mode 100644
index 00000000..df24c93c
--- /dev/null
+++ b/llama.cpp/llama-bench/main.1.asc
@@ -0,0 +1,899 @@
+LLAMAFILE(1) General Commands Manual LLAMAFILE(1)
+
+NAME
+ llamafile — large language model runner
+
+SYNOPSIS
+ llamafile [--server] [flags...] -m model.gguf [--mmproj vision.gguf]
+ llamafile [--cli] [flags...] -m model.gguf -p prompt
+ llamafile [--cli] [flags...] -m model.gguf --mmproj vision.gguf --image
+ graphic.png -p prompt
+
+DESCRIPTION
+ llamafile is a large language model tool. It has use cases such as:
+
+ - Code completion
+ - Prose composition
+ - Chatbot that passes the Turing test
+ - Text/image summarization and analysis
+
+OPTIONS
+ The following options are available:
+
+ --version
+ Print version and exit.
+
+ -h, --help
+ Show help message and exit.
+
+ --cli Puts program in command line interface mode. This flag is im‐
+ plied when a prompt is supplied using either the -p or -f
+ flags.
+
+ --server
+ Puts program in server mode. This will launch an HTTP server on
+ a local port. This server has both a web UI and an OpenAI API
+ compatible completions endpoint. When the server is run on a
+ desk system, a tab browser tab will be launched automatically
+ that displays the web UI. This --server flag is implied if no
+ prompt is specified, i.e. neither the -p or -f flags are
+ passed.
+
+ -m FNAME, --model FNAME
+ Model path in the GGUF file format.
+
+ Default: models/7B/ggml‐model‐f16.gguf
+
+ --mmproj FNAME
+ Specifies path of the LLaVA vision model in the GGUF file for‐
+ mat. If this flag is supplied, then the --model and --image
+ flags should also be supplied.
+
+ -s SEED, --seed SEED
+ Random Number Generator (RNG) seed. A random seed is used if
+ this is less than zero.
+
+ Default: ‐1
+
+ -t N, --threads N
+ Number of threads to use during generation.
+
+ Default: $(nproc)/2
+
+ -tb N, --threads‐batch N
+ Set the number of threads to use during batch and prompt pro‐
+ cessing. In some systems, it is beneficial to use a higher num‐
+ ber of threads during batch processing than during generation.
+ If not specified, the number of threads used for batch process‐
+ ing will be the same as the number of threads used for genera‐
+ tion.
+
+ Default: Same as --threads
+
+ -td N, --threads‐draft N
+ Number of threads to use during generation.
+
+ Default: Same as --threads
+
+ -tbd N, --threads‐batch‐draft N
+ Number of threads to use during batch and prompt processing.
+
+ Default: Same as --threads‐draft
+
+ --in‐prefix‐bos
+ Prefix BOS to user inputs, preceding the --in‐prefix string.
+
+ --in‐prefix STRING
+ This 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:
+
+ ./main ‐r "User:" ‐‐in‐prefix " "
+
+ Default: empty
+
+ --in‐suffix STRING
+ This flag is used to add a suffix after your input. This is
+ useful for adding an "Assistant:" prompt after the user’s in‐
+ put. It’s added after the new‐line character (\n) that’s auto‐
+ matically added to the end of the user’s input. Here’s an exam‐
+ ple of how to use the --in‐suffix flag in conjunction with the
+ --reverse‐prompt flag:
+
+ ./main ‐r "User:" ‐‐in‐prefix " " ‐‐in‐suffix
+ "Assistant:"
+
+ Default: empty
+
+ -n N, --n‐predict N
+ Number of tokens to predict.
+
+ - ‐1 = infinity
+ - ‐2 = until context filled
+
+ Default: ‐1
+
+ -c N, --ctx‐size N
+ Set the size of the prompt context. A larger context size helps
+ the model to better comprehend and generate responses for
+ longer input or conversations. The LLaMA models were built with
+ a context of 2048, which yields the best results on longer in‐
+ put / inference.
+
+ - 0 = loaded automatically from model
+
+ Default: 512
+
+ -b N, --batch‐size N
+ Batch size for prompt processing.
+
+ Default: 512
+
+ --top‐k N
+ Top‐k sampling.
+
+ - 0 = disabled
+
+ Default: 40
+
+ --top‐p N
+ Top‐p sampling.
+
+ - 1.0 = disabled
+
+ Default: 0.9
+
+ --min‐p N
+ Min‐p sampling.
+
+ - 0.0 = disabled
+
+ Default: 0.1
+
+ --tfs N
+ Tail free sampling, parameter z.
+
+ - 1.0 = disabled
+
+ Default: 1.0
+
+ --typical N
+ Locally typical sampling, parameter p.
+
+ - 1.0 = disabled
+
+ Default: 1.0
+
+ --repeat‐last‐n N
+ Last n tokens to consider for penalize.
+
+ - 0 = disabled
+ - ‐1 = ctx_size
+
+ Default: 64
+
+ --repeat‐penalty N
+ Penalize repeat sequence of tokens.
+
+ - 1.0 = disabled
+
+ Default: 1.1
+
+ --presence‐penalty N
+ Repeat alpha presence penalty.
+
+ - 0.0 = disabled
+
+ Default: 0.0
+
+ --frequency‐penalty N
+ Repeat alpha frequency penalty.
+
+ - 0.0 = disabled
+
+ Default: 0.0
+
+ --mirostat N
+ Use Mirostat sampling. Top K, Nucleus, Tail Free and Locally
+ Typical samplers are ignored if used..
+
+ - 0 = disabled
+ - 1 = Mirostat
+ - 2 = Mirostat 2.0
+
+ Default: 0
+
+ --mirostat‐lr N
+ Mirostat learning rate, parameter eta.
+
+ Default: 0.1
+
+ --mirostat‐ent N
+ Mirostat target entropy, parameter tau.
+
+ Default: 5.0
+
+ -l TOKEN_ID(+/‐)BIAS, --logit‐bias TOKEN_ID(+/‐)BIAS
+ Modifies the likelihood of token appearing in the completion,
+ i.e. --logit‐bias 15043+1 to increase likelihood of token
+ ’ Hello’, or --logit‐bias 15043‐1 to decrease likelihood of to‐
+ ken ’ Hello’.
+
+ -md FNAME, --model‐draft FNAME
+ Draft model for speculative decoding.
+
+ Default: models/7B/ggml‐model‐f16.gguf
+
+ --cfg‐negative‐prompt PROMPT
+ Negative prompt to use for guidance..
+
+ Default: empty
+
+ --cfg‐negative‐prompt‐file FNAME
+ Negative prompt file to use for guidance.
+
+ Default: empty
+
+ --cfg‐scale N
+ Strength of guidance.
+
+ - 1.0 = disable
+
+ Default: 1.0
+
+ --rope‐scaling {none,linear,yarn}
+ RoPE frequency scaling method, defaults to linear unless speci‐
+ fied by the model
+
+ --rope‐scale N
+ RoPE context scaling factor, expands context by a factor of N
+ where N is the linear scaling factor used by the fine‐tuned
+ model. Some fine‐tuned models have extended the context length
+ by scaling RoPE. For example, if the original pre‐trained model
+ have a context length (max sequence length) of 4096 (4k) and
+ the fine‐tuned model have 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.
+
+ --rope‐freq‐base N
+ RoPE base frequency, used by NTK‐aware scaling.
+
+ Default: loaded from model
+
+ --rope‐freq‐scale N
+ RoPE frequency scaling factor, expands context by a factor of
+ 1/N
+
+ --yarn‐orig‐ctx N
+ YaRN: original context size of model.
+
+ Default: 0 = model training context size
+
+ --yarn‐ext‐factor N
+ YaRN: extrapolation mix factor.
+
+ - 0.0 = full interpolation
+
+ Default: 1.0
+
+ --yarn‐attn‐factor N
+ YaRN: scale sqrt(t) or attention magnitude.
+
+ Default: 1.0
+
+ --yarn‐beta‐slow N
+ YaRN: high correction dim or alpha.
+
+ Default: 1.0
+
+ --yarn‐beta‐fast N
+ YaRN: low correction dim or beta.
+
+ Default: 32.0
+
+ --ignore‐eos
+ Ignore end of stream token and continue generating (implies
+ --logit‐bias 2‐inf)
+
+ --no‐penalize‐nl
+ Do not penalize newline token.
+
+ --temp N
+ Temperature.
+
+ Default: 0.8
+
+ --logits‐all
+ Return logits for all tokens in the batch.
+
+ Default: disabled
+
+ --hellaswag
+ Compute HellaSwag score over random tasks from datafile sup‐
+ plied with ‐f
+
+ --hellaswag‐tasks N
+ Number of tasks to use when computing the HellaSwag score.
+
+ Default: 400
+
+ --keep N
+ This flag 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, where N is the
+ number of tokens from the initial prompt to retain when the
+ model resets its internal context.
+
+ - 0 = no tokens are kept from initial prompt
+ - ‐1 = retain all tokens from initial prompt
+
+ Default: 0
+
+ --draft N
+ Number of tokens to draft for speculative decoding.
+
+ Default: 16
+
+ --chunks N
+ Max number of chunks to process.
+
+ - ‐1 = all
+
+ Default: ‐1
+
+ -ns N, --sequences N
+ Number of sequences to decode.
+
+ Default: 1
+
+ -pa N, --p‐accept N
+ speculative decoding accept probability.
+
+ Default: 0.5
+
+ -ps N, --p‐split N
+ Speculative decoding split probability.
+
+ Default: 0.1
+
+ --mlock
+ Force system to keep model in RAM rather than swapping or com‐
+ pressing.
+
+ --no‐mmap
+ Do not memory‐map model (slower load but may reduce pageouts if
+ not using mlock).
+
+ --numa Attempt optimizations that help on some NUMA systems if run
+ without this previously, it is recommended to drop the system
+ page cache before using this. See
+ https://github.com/ggerganov/llama.cpp/issues/1437.
+
+ --recompile
+ Force GPU support to be recompiled at runtime if possible.
+
+ --nocompile
+ Never compile GPU support at runtime.
+
+ If the appropriate DSO file already exists under ~/.llamafile/
+ then it’ll be linked as‐is without question. If a prebuilt DSO
+ is present in the PKZIP content of the executable, then it’ll
+ be extracted and linked if possible. Otherwise, llamafile will
+ skip any attempt to compile GPU support and simply fall back to
+ using CPU inference.
+
+ --gpu GPU
+ Specifies which brand of GPU should be used. Valid choices are:
+
+ - AUTO: Use any GPU if possible, otherwise fall back to CPU
+ inference (default)
+
+ - APPLE: Use Apple Metal GPU. This is only available on MacOS
+ ARM64. If Metal could not be used for any reason, then a
+ fatal error will be raised.
+
+ - AMD: Use AMD GPUs. The AMD HIP ROCm SDK should be installed
+ in which case we assume the HIP_PATH environment variable
+ has been defined. The set of gfx microarchitectures needed
+ to run on the host machine is determined automatically
+ based on the output of the hipInfo command. On Windows,
+ llamafile release binaries are distributed with a tinyBLAS
+ DLL so it’ll work out of the box without requiring the HIP
+ SDK to be installed. However, tinyBLAS is slower than
+ rocBLAS for batch and image processing, so it’s recommended
+ that the SDK be installed anyway. If an AMD GPU could not
+ be used for any reason, then a fatal error will be raised.
+
+ - NVIDIA: Use NVIDIA GPUs. If an NVIDIA GPU could not be used
+ for any reason, a fatal error will be raised. On Windows,
+ NVIDIA GPU support will use our tinyBLAS library, since it
+ works on stock Windows installs. However, tinyBLAS goes
+ slower for batch and image processing. It’s possible to use
+ NVIDIA’s closed‐source cuBLAS library instead. To do that,
+ both MSVC and CUDA need to be installed and the llamafile
+ command should be run once from the x64 MSVC command prompt
+ with the --recompile flag passed. The GGML library will
+ then be compiled and saved to ~/.llamafile/ so the special
+ process only needs to happen a single time.
+
+ - DISABLE: Never use GPU and instead use CPU inference. This
+ setting is implied by -ngl 0.
+
+ -ngl N, --n‐gpu‐layers N
+ Number of layers to store in VRAM.
+
+ -ngld N, --n‐gpu‐layers‐draft N
+ Number of layers to store in VRAM for the draft model.
+
+ -sm SPLIT_MODE, --split‐mode SPLIT_MODE
+ How to split the model across multiple GPUs, one of:
+ - none: use one GPU only
+ - layer (default): split layers and KV across GPUs
+ - row: split rows across GPUs
+
+ -ts SPLIT, --tensor‐split SPLIT
+ When using multiple GPUs this option controls how large tensors
+ should be split across all GPUs. SPLIT is a comma‐separated
+ list of non‐negative values that assigns the proportion of data
+ that each GPU should get in order. For example, "3,2" will as‐
+ sign 60% of the data to GPU 0 and 40% to GPU 1. By default the
+ data is split in proportion to VRAM but this may not be optimal
+ for performance. Requires cuBLAS. How to split tensors across
+ multiple GPUs, comma‐separated list of proportions, e.g. 3,1
+
+ -mg i, --main‐gpu i
+ The GPU to use for scratch and small tensors.
+
+ -nommq, --no‐mul‐mat‐q
+ Use cuBLAS instead of custom mul_mat_q CUDA kernels. Not recom‐
+ mended since this is both slower and uses more VRAM.
+
+ --verbose‐prompt
+ Print prompt before generation.
+
+ --simple‐io
+ Use basic IO for better compatibility in subprocesses and lim‐
+ ited consoles.
+
+ --lora FNAME
+ Apply LoRA adapter (implies --no‐mmap)
+
+ --lora‐scaled FNAME S
+ Apply LoRA adapter with user defined scaling S (implies
+ --no‐mmap)
+
+ --lora‐base FNAME
+ Optional model to use as a base for the layers modified by the
+ LoRA adapter
+
+ --unsecure
+ Disables pledge() sandboxing on Linux and OpenBSD.
+
+ --samplers
+ Samplers that will be used for generation in the order, sepa‐
+ rated by semicolon, for example: top_k;tfs;typi‐
+ cal;top_p;min_p;temp
+
+ --samplers‐seq
+ Simplified sequence for samplers that will be used.
+
+ -cml, --chatml
+ Run in chatml mode (use with ChatML‐compatible models)
+
+ -dkvc, --dump‐kv‐cache
+ Verbose print of the KV cache.
+
+ -nkvo, --no‐kv‐offload
+ Disable KV offload.
+
+ -ctk TYPE, --cache‐type‐k TYPE
+ KV cache data type for K.
+
+ -ctv TYPE, --cache‐type‐v TYPE
+ KV cache data type for V.
+
+ -gan N, --grp‐attn‐n N
+ Group‐attention factor.
+
+ Default: 1
+
+ -gaw N, --grp‐attn‐w N
+ Group‐attention width.
+
+ Default: 512
+
+ -bf FNAME, --binary‐file FNAME
+ Binary file containing multiple choice tasks.
+
+ --winogrande
+ Compute Winogrande score over random tasks from datafile sup‐
+ plied by the -f flag.
+
+ --winogrande‐tasks N
+ Number of tasks to use when computing the Winogrande score.
+
+ Default: 0
+
+ --multiple‐choice
+ Compute multiple choice score over random tasks from datafile
+ supplied by the -f flag.
+
+ --multiple‐choice‐tasks N
+ Number of tasks to use when computing the multiple choice
+ score.
+
+ Default: 0
+
+ --kl‐divergence
+ Computes KL‐divergence to logits provided via the
+ --kl‐divergence‐base flag.
+
+ --save‐all‐logits FNAME, --kl‐divergence‐base FNAME
+ Save logits to filename.
+
+ -ptc N, --print‐token‐count N
+ Print token count every N tokens.
+
+ Default: ‐1
+
+ --pooling KIND
+ Specifies pooling type for embeddings. This may be one of:
+
+ - none
+ - mean
+ - cls
+
+ The model default is used if unspecified.
+
+CLI OPTIONS
+ The following options may be specified when llamafile is running in
+ --cli mode.
+
+ -e, --escape
+ Process prompt escapes sequences (\n, \r, \t, \´, \", \\)
+
+ -p STRING, --prompt STRING
+ Prompt to start text generation. Your LLM works by auto‐com‐
+ pleting this text. For example:
+
+ llamafile ‐m model.gguf ‐p "four score and"
+
+ Stands a pretty good chance of printing Lincoln’s Gettysburg
+ Address. Prompts can take on a structured format too. Depend‐
+ ing on how your model was trained, it may specify in its docs
+ an instruction notation. With some models that might be:
+
+ llamafile ‐p "[INST]Summarize this: $(cat file)[/INST]"
+
+ In most cases, simply colons and newlines will work too:
+
+ llamafile ‐e ‐p "User: What is best in life?\nAssistant:"
+
+ -f FNAME, --file FNAME
+ Prompt file to start generation.
+
+ --grammar GRAMMAR
+ BNF‐like grammar to constrain which tokens may be selected when
+ generating text. For example, the grammar:
+
+ root ::= "yes" | "no"
+
+ will force the LLM to only output yes or no before exiting.
+ This is useful for shell scripts when the --no‐display‐prompt
+ flag is also supplied.
+
+ --grammar‐file FNAME
+ File to read grammar from.
+
+ --fast Put llamafile into fast math mode. This disables algorithms
+ that reduce floating point rounding, e.g. Kahan summation, and
+ certain functions like expf() will be vectorized but handle un‐
+ derflows less gracefully. It’s unspecified whether llamafile
+ runs in fast or precise math mode when neither flag is speci‐
+ fied.
+
+ --precise
+ Put llamafile into precise math mode. This enables algorithms
+ that reduce floating point rounding, e.g. Kahan summation, and
+ certain functions like expf() will always handle subnormals
+ correctly. It’s unspecified whether llamafile runs in fast or
+ precise math mode when neither flag is specified.
+
+ --trap Put llamafile into math trapping mode. When floating point ex‐
+ ceptions occur, such as NaNs, overflow, and divide by zero,
+ llamafile will print a warning to the console. This warning
+ will include a C++ backtrace the first time an exception is
+ trapped. The op graph will also be dumped to a file, and lla‐
+ mafile will report the specific op where the exception oc‐
+ curred. This is useful for troubleshooting when reporting is‐
+ sues. USing this feature will disable sandboxing. Math trap‐
+ ping is only possible if your CPU supports it. That is gener‐
+ ally the case on AMD64, however it’s less common on ARM64.
+
+ --prompt‐cache FNAME
+ File to cache prompt state for faster startup.
+
+ Default: none
+
+ -fa FNAME, --flash‐attn
+ Enable Flash Attention. This is a mathematical shortcut that
+ can speed up inference for certain models. This feature is
+ still under active development.
+
+ --prompt‐cache‐all
+ If specified, saves user input and generations to cache as
+ well. Not supported with --interactive or other interactive op‐
+ tions.
+
+ --prompt‐cache‐ro
+ If specified, uses the prompt cache but does not update it.
+
+ --random‐prompt
+ Start with a randomized prompt.
+
+ --image IMAGE_FILE
+ Path to an image file. This should be used with multimodal mod‐
+ els. Alternatively, it’s possible to embed an image directly
+ into the prompt instead; in which case, it must be base64 en‐
+ coded into an HTML img tag URL with the image/jpeg MIME type.
+ See also the --mmproj flag for supplying the vision model.
+
+ -i, --interactive
+ Run the program in interactive mode, allowing users to engage
+ in real‐time conversations or provide specific instructions to
+ the model.
+
+ --interactive‐first
+ Run the program in interactive mode and immediately wait for
+ user input before starting the text generation.
+
+ -ins, --instruct
+ Run the program in instruction mode, which is specifically de‐
+ signed to work with Alpaca models that excel in completing
+ tasks based on user instructions.
+
+ Technical details: The user’s input is internally prefixed with
+ the reverse prompt (or "### Instruction:" as the default), and
+ followed by "### Response:" (except if you just press Return
+ without any input, to keep generating a longer response).
+
+ By understanding and utilizing these interaction options, you
+ can create engaging and dynamic experiences with the LLaMA mod‐
+ els, tailoring the text generation process to your specific
+ needs.
+
+ -r PROMPT, --reverse‐prompt PROMPT
+ Specify one or multiple reverse prompts to pause text genera‐
+ tion and switch to interactive mode. For example, -r "User:"
+ can be used to jump back into the conversation whenever it’s
+ the user’s turn to speak. This helps create a more interactive
+ and conversational experience. However, the reverse prompt
+ doesn’t work when it ends with a space. To overcome this limi‐
+ tation, you can use the --in‐prefix flag to add a space or any
+ other characters after the reverse prompt.
+
+ --color
+ Enable colorized output to differentiate visually distinguish‐
+ ing between prompts, user input, and generated text.
+
+ --no‐display‐prompt, --silent‐prompt
+ Don’t echo the prompt itself to standard output.
+
+ --keep N
+ Specifies number of tokens to keep from the initial prompt. The
+ default is ‐1 which means all tokens.
+
+ --multiline‐input
+ Allows you to write or paste multiple lines without ending each
+ in ’\’.
+
+ --cont‐batching
+ Enables continuous batching, a.k.a. dynamic batching. is ‐1
+ which means all tokens.
+
+ --embedding
+ In CLI mode, the embedding flag may be use to print embeddings
+ to standard output. By default, embeddings are computed over a
+ whole prompt. However the --multiline flag may be passed, to
+ have a separate embeddings array computed for each line of text
+ in the prompt. In multiline mode, each embedding array will be
+ printed on its own line to standard output, where individual
+ floats are separated by space. If both the --multiline‐input
+ and --interactive flags are passed, then a pretty‐printed sum‐
+ mary of embeddings along with a cosine similarity matrix will
+ be printed to the terminal.
+
+SERVER OPTIONS
+ The following options may be specified when llamafile is running in
+ --server mode.
+
+ --port PORT
+ Port to listen
+
+ Default: 8080
+
+ --host IPADDR
+ IP address to listen.
+
+ Default: 127.0.0.1
+
+ -to N, --timeout N
+ Server read/write timeout in seconds.
+
+ Default: 600
+
+ -np N, --parallel N
+ Number of slots for process requests.
+
+ Default: 1
+
+ -cb, --cont‐batching
+ Enable continuous batching (a.k.a dynamic batching).
+
+ Default: disabled
+
+ -spf FNAME, --system‐prompt‐file FNAME
+ Set a file to load a system prompt (initial prompt of all
+ slots), this is useful for chat applications.
+
+ -a ALIAS, --alias ALIAS
+ Set an alias for the model. This will be added as the model
+ field in completion responses.
+
+ --path PUBLIC_PATH
+ Path from which to serve static files.
+
+ Default: /zip/llama.cpp/server/public
+
+ --nobrowser
+ Do not attempt to open a web browser tab at startup.
+
+ -gan N, --grp‐attn‐n N
+ Set the group attention factor to extend context size through
+ self‐extend. The default value is 1 which means disabled. This
+ flag is used together with --grp‐attn‐w.
+
+ -gaw N, --grp‐attn‐w N
+ Set the group attention width to extend context size through
+ self‐extend. The default value is 512. This flag is used to‐
+ gether with --grp‐attn‐n.
+
+LOG OPTIONS
+ The following log options are available:
+
+ -ld LOGDIR, --logdir LOGDIR
+ Path under which to save YAML logs (no logging if unset)
+
+ --log‐test
+ Run simple logging test
+
+ --log‐disable
+ Disable trace logs
+
+ --log‐enable
+ Enable trace logs
+
+ --log‐file
+ Specify a log filename (without extension)
+
+ --log‐new
+ Create a separate new log file on start. Each log file will
+ have unique name: <name>.<ID>.log
+
+ --log‐append
+ Don’t truncate the old log file.
+
+EXAMPLES
+ Here’s an example of how to run llama.cpp’s built‐in HTTP server. This
+ example uses LLaVA v1.5‐7B, a multimodal LLM that works with
+ llama.cpp’s recently‐added support for image inputs.
+
+ llamafile \
+ ‐m llava‐v1.5‐7b‐Q8_0.gguf \
+ ‐‐mmproj llava‐v1.5‐7b‐mmproj‐Q8_0.gguf \
+ ‐‐host 0.0.0.0
+
+ Here’s an example of how to generate code for a libc function using the
+ llama.cpp command line interface, utilizing WizardCoder‐Python‐13B
+ weights:
+
+ llamafile \
+ ‐m wizardcoder‐python‐13b‐v1.0.Q8_0.gguf ‐‐temp 0 ‐r ’}\n’ ‐r ’```\n’ \
+ ‐e ‐p ’```c\nvoid *memcpy(void *dst, const void *src, size_t size) {\n’
+
+ Here’s a similar example that instead utilizes Mistral‐7B‐Instruct
+ weights for prose composition:
+
+ llamafile \
+ ‐m mistral‐7b‐instruct‐v0.2.Q5_K_M.gguf \
+ ‐p ’[INST]Write a story about llamas[/INST]’
+
+ Here’s an example of how llamafile can be used as an interactive chat‐
+ bot that lets you query knowledge contained in training data:
+
+ llamafile ‐m llama‐65b‐Q5_K.gguf ‐p ’
+ The following is a conversation between a Researcher and their helpful AI
+ assistant Digital Athena which is a large language model trained on the
+ sum of human knowledge.
+ Researcher: Good morning.
+ Digital Athena: How can I help you today?
+ Researcher:’ ‐‐interactive ‐‐color ‐‐batch_size 1024 ‐‐ctx_size 4096 \
+ ‐‐keep ‐1 ‐‐temp 0 ‐‐mirostat 2 ‐‐in‐prefix ’ ’ ‐‐interactive‐first \
+ ‐‐in‐suffix ’Digital Athena:’ ‐‐reverse‐prompt ’Researcher:’
+
+ Here’s an example of how you can use llamafile to summarize HTML URLs:
+
+ (
+ echo ’[INST]Summarize the following text:’
+ links ‐codepage utf‐8 \
+ ‐force‐html \
+ ‐width 500 \
+ ‐dump https://www.poetryfoundation.org/poems/48860/the‐raven |
+ sed ’s/ */ /g’
+ echo ’[/INST]’
+ ) | llamafile \
+ ‐m mistral‐7b‐instruct‐v0.2.Q5_K_M.gguf \
+ ‐f /dev/stdin \
+ ‐c 0 \
+ ‐‐temp 0 \
+ ‐n 500 \
+ ‐‐no‐display‐prompt 2>/dev/null
+
+ Here’s how you can use llamafile to describe a jpg/png/gif/bmp image:
+
+ llamafile ‐‐temp 0 \
+ ‐‐image lemurs.jpg \
+ ‐m llava‐v1.5‐7b‐Q4_K.gguf \
+ ‐‐mmproj llava‐v1.5‐7b‐mmproj‐Q4_0.gguf \
+ ‐e ‐p ’### User: What do you see?\n### Assistant: ’ \
+ ‐‐no‐display‐prompt 2>/dev/null
+
+ If you wanted to write a script to rename all your image files, you
+ could use the following command to generate a safe filename:
+
+ llamafile ‐‐temp 0 \
+ ‐‐image ~/Pictures/lemurs.jpg \
+ ‐m llava‐v1.5‐7b‐Q4_K.gguf \
+ ‐‐mmproj llava‐v1.5‐7b‐mmproj‐Q4_0.gguf \
+ ‐‐grammar ’root ::= [a‐z]+ (" " [a‐z]+)+’ \
+ ‐e ‐p ’### User: The image has...\n### Assistant: ’ \
+ ‐‐no‐display‐prompt 2>/dev/null |
+ sed ‐e’s/ /_/g’ ‐e’s/$/.jpg/’
+ three_baby_lemurs_on_the_back_of_an_adult_lemur.jpg
+
+ Here’s an example of how to make an API request to the OpenAI API com‐
+ patible completions endpoint when your llamafile is running in the
+ background in --server mode.
+
+ curl ‐s http://localhost:8080/v1/chat/completions \
+ ‐H "Content‐Type: application/json" ‐d ’{
+ "model": "gpt‐3.5‐turbo",
+ "stream": true,
+ "messages": [
+ {
+ "role": "system",
+ "content": "You are a poetic assistant."
+ },
+ {
+ "role": "user",
+ "content": "Compose a poem that explains FORTRAN."
+ }
+ ]
+ }’ | python3 ‐c ’
+ import json
+ import sys
+ json.dump(json.load(sys.stdin), sys.stdout, indent=2)
+ print()
+
+PROTIP
+ The -ngl 35 flag needs to be passed in order to use GPUs made by NVIDIA
+ and AMD. It’s not enabled by default since it sometimes needs to be
+ tuned based on the system hardware and model architecture, in order to
+ achieve optimal performance, and avoid compromising a shared display.
+
+SEE ALSO
+ llamafile‐quantize(1), llamafile‐perplexity(1), llava‐quantize(1),
+ zipalign(1), unzip(1)
+
+Mozilla Ocho January 1, 2024 LLAMAFILE(1)
diff --git a/llama.cpp/llama-bench/main.cpp b/llama.cpp/llama-bench/main.cpp
new file mode 100644
index 00000000..8064b294
--- /dev/null
+++ b/llama.cpp/llama-bench/main.cpp
@@ -0,0 +1,1040 @@
+// -*- mode:c++;indent-tabs-mode:nil;c-basic-offset:4;coding:utf-8 -*-
+// vi: set et ft=cpp ts=4 sts=4 sw=4 fenc=utf-8 :vi
+
+#include <cassert>
+#include <cinttypes>
+#include <cmath>
+#include <cosmo.h>
+#include <cstdio>
+#include <cstring>
+#include <ctime>
+#include <fstream>
+#include <iostream>
+#include <signal.h>
+#include <sstream>
+#include <string>
+#include <unistd.h>
+#include <vector>
+#include <tool/args/args.h>
+#include <sys/auxv.h>
+#include <stdatomic.h>
+#include <third_party/nsync/futex.internal.h>
+
+#include "llamafile/version.h"
+#include "llama.cpp/llama.h"
+#include "llama.cpp/common.h"
+#include "llama.cpp/console.h"
+#include "llama.cpp/ggml-cuda.h"
+#include "llama.cpp/ggml-metal.h"
+#include "llama.cpp/llava/llava.h"
+#include "llama.cpp/server/server.h"
+
+static llama_context ** g_ctx;
+static llama_model ** g_model;
+static gpt_params * g_params;
+static std::vector<llama_token> * g_input_tokens;
+static std::ostringstream * g_output_ss;
+static std::vector<llama_token> * g_output_tokens;
+static bool is_interacting = false;
+
+static bool file_exists(const std::string &path) {
+ std::ifstream f(path.c_str());
+ return f.good();
+}
+
+static bool file_is_empty(const std::string &path) {
+ std::ifstream f;
+ f.exceptions(std::ifstream::failbit | std::ifstream::badbit);
+ f.open(path.c_str(), std::ios::in | std::ios::binary | std::ios::ate);
+ return f.tellg() == 0;
+}
+
+static void write_logfile(
+ const llama_context * ctx, const gpt_params & params, const llama_model * model,
+ const std::vector<llama_token> & input_tokens, const std::string & output,
+ const std::vector<llama_token> & output_tokens
+) {
+ if (params.logdir.empty()) {
+ return;
+ }
+
+ const std::string timestamp = get_sortable_timestamp();
+
+ const bool success = create_directory_with_parents(params.logdir);
+ if (!success) {
+ fprintf(stderr, "%s: warning: failed to create logdir %s, cannot write logfile\n",
+ __func__, params.logdir.c_str());
+ return;
+ }
+
+ const std::string logfile_path = params.logdir + timestamp + ".yml";
+ FILE * logfile = fopen(logfile_path.c_str(), "we");
+
+ if (logfile == NULL) {
+ fprintf(stderr, "%s: failed to open logfile %s\n", __func__, logfile_path.c_str());
+ return;
+ }
+
+ fprintf(logfile, "binary: main\n");
+ char model_desc[128];
+ llama_model_desc(model, model_desc, sizeof(model_desc));
+ dump_non_result_info_yaml(logfile, params, ctx, timestamp, input_tokens, model_desc);
+
+ fprintf(logfile, "\n");
+ fprintf(logfile, "######################\n");
+ fprintf(logfile, "# Generation Results #\n");
+ fprintf(logfile, "######################\n");
+ fprintf(logfile, "\n");
+
+ dump_string_yaml_multiline(logfile, "output", output.c_str());
+ dump_vector_int_yaml(logfile, "output_tokens", output_tokens);
+
+ llama_dump_timing_info_yaml(logfile, ctx);
+ fclose(logfile);
+}
+
+static atomic_int is_killed;
+
+static void *safe_sigint_handler(void *arg) {
+ while (!is_killed)
+ nsync_futex_wait_(&is_killed, 0, 0, 0);
+ console::cleanup();
+ printf("\n");
+ llama_print_timings(*g_ctx);
+ write_logfile(*g_ctx, *g_params, *g_model, *g_input_tokens, g_output_ss->str(), *g_output_tokens);
+ _exit(128 + SIGINT);
+}
+
+static void launch_sigint_thread(void) {
+ pthread_t th;
+ sigset_t block_every_signal;
+ sigfillset(&block_every_signal);
+ pthread_attr_t attr;
+ pthread_attr_init(&attr);
+ pthread_attr_setstacksize(&attr, 65536);
+ pthread_attr_setguardsize(&attr, getauxval(AT_PAGESZ));
+ pthread_attr_setsigmask_np(&attr, &block_every_signal);
+ pthread_create(&th, &attr, safe_sigint_handler, 0);
+ pthread_attr_destroy(&attr);
+}
+
+static void sigint_handler(int signo) {
+ if (signo == SIGINT) {
+ if (g_params->interactive && !is_interacting) {
+ is_interacting = true;
+ } else {
+ is_killed = true;
+ nsync_futex_wake_(&is_killed, 1, 0);
+ for (;;) {
+ }
+ }
+ }
+}
+
+static void llama_log_callback_logTee(ggml_log_level level, const char * text, void * user_data) {
+ (void) level;
+ (void) user_data;
+ LOG_TEE("%s", text);
+}
+
+int main(int argc, char ** argv) {
+
+ if (llamafile_has(argv, "--version")) {
+ puts("llamafile v" LLAMAFILE_VERSION_STRING);
+ return 0;
+ }
+
+ if (llamafile_has(argv, "-h") ||
+ llamafile_has(argv, "-help") ||
+ llamafile_has(argv, "--help")) {
+ llamafile_help("/zip/llama.cpp/main/main.1.asc");
+ __builtin_unreachable();
+ }
+
+ llamafile_check_cpu();
+ ShowCrashReports();
+ LoadZipArgs(&argc, &argv);
+ launch_sigint_thread();
+
+ if (!llamafile_has(argv, "--cli") &&
+ (llamafile_has(argv, "--server") ||
+ (!llamafile_has(argv, "-p") &&
+ !llamafile_has(argv, "-f") &&
+ !llamafile_has(argv, "--random-prompt")))) {
+ return server_cli(argc, argv);
+ }
+
+ if (llamafile_has(argv, "--embedding")) {
+ int embedding_cli(int, char **);
+ return embedding_cli(argc, argv);
+ }
+
+ gpt_params params;
+ g_params = &params;
+
+ if (!gpt_params_parse(argc, argv, params)) {
+ return 1;
+ }
+ llama_sampling_params & sparams = params.sparams;
+
+#ifndef LOG_DISABLE_LOGS
+ log_set_target(log_filename_generator("main", "log"));
+ log_dump_cmdline(argc, argv);
+ llama_log_set(llama_log_callback_logTee, nullptr);
+#endif // LOG_DISABLE_LOGS
+
+ if (!params.image.empty() && params.mmproj.empty()) {
+ fprintf(stderr, "%s: fatal error: --mmproj must also be passed when an --image is specified in cli mode\n", argv[0]);
+ return 1;
+ }
+
+ if (!FLAG_unsecure && !llamafile_has_gpu()) {
+ // Enable pledge() security on Linux and OpenBSD.
+ // - We do this *after* opening the log file for writing.
+ // - We do this *before* loading any weights or graphdefs.
+ // In effect, what this does is:
+ // - We'll no longer be able to talk to the network going forward.
+ // - We'll no longer be able to change the filesystem going forward.
+ // Cosmopolitan Libc implements pledge() on Linux using SECCOMP.
+ const char *promises;
+ if (!params.path_prompt_cache.empty() && !params.prompt_cache_ro) {
+ // TODO(jart): Open prompt cache in RW mode before pledge()
+ promises = "stdio rpath tty cpath wpath";
+ } else {
+ promises = "stdio rpath tty";
+ }
+ __pledge_mode = PLEDGE_PENALTY_RETURN_EPERM;
+ if (pledge(0, 0)) {
+ LOG("warning: this OS doesn't support pledge() security\n");
+ } else if (pledge(promises, 0)) {
+ perror("pledge");
+ exit(1);
+ }
+ }
+
+ if (!params.mmproj.empty() &&
+ (!params.image.empty() ||
+ params.prompt.find("<img src=\"") != std::string::npos)) {
+ return llava_cli(argc, argv, params);
+ }
+
+ // TODO: Dump params ?
+ //LOG("Params perplexity: %s\n", LOG_TOSTR(params.perplexity));
+
+ // save choice to use color for later
+ // (note for later: this is a slightly awkward choice)
+ console::init(!params.interactive || params.simple_io, params.use_color);
+ atexit([]() { console::cleanup(); });
+
+ if (params.logits_all) {
+ printf("\n************\n");
+ printf("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
+ printf("************\n\n");
+
+ return 0;
+ }
+
+ if (params.embedding) {
+ printf("\n************\n");
+ printf("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
+ printf("************\n\n");
+
+ return 0;
+ }
+
+ if (params.n_ctx != 0 && params.n_ctx < 8) {
+ LOG_TEE("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
+ params.n_ctx = 8;
+ }
+
+ if (params.rope_freq_base != 0.0) {
+ LOG_TEE("%s: warning: changing RoPE frequency base to %g.\n", __func__, params.rope_freq_base);
+ }
+
+ if (params.rope_freq_scale != 0.0) {
+ LOG_TEE("%s: warning: scaling RoPE frequency by %g.\n", __func__, params.rope_freq_scale);
+ }
+
+ print_build_info();
+
+ if (params.seed == LLAMA_DEFAULT_SEED) {
+ params.seed = time(NULL);
+ }
+
+ LOG_TEE("%s: seed = %u\n", __func__, params.seed);
+
+ std::mt19937 rng(params.seed);
+ if (params.random_prompt) {
+ params.prompt = gpt_random_prompt(rng);
+ }
+
+ LOG("%s: llama backend init\n", __func__);
+ llama_backend_init();
+ llama_numa_init(params.numa);
+
+ llama_model * model;
+ llama_context * ctx;
+ llama_context * ctx_guidance = NULL;
+ g_model = &model;
+ g_ctx = &ctx;
+
+ // load the model and apply lora adapter, if any
+ LOG("%s: load the model and apply lora adapter, if any\n", __func__);
+ std::tie(model, ctx) = llama_init_from_gpt_params(params);
+ if (sparams.cfg_scale > 1.f) {
+ struct llama_context_params lparams = llama_context_params_from_gpt_params(params);
+ ctx_guidance = llama_new_context_with_model(model, lparams);
+ }
+
+ if (model == NULL) {
+ LOG_TEE("%s: error: unable to load model\n", __func__);
+ return 1;
+ }
+
+ const int n_ctx_train = llama_n_ctx_train(model);
+ const int n_ctx = llama_n_ctx(ctx);
+ LOG("n_ctx: %d\n", n_ctx);
+
+ if (n_ctx > n_ctx_train) {
+ LOG_TEE("%s: warning: model was trained on only %d context tokens (%d specified)\n",
+ __func__, n_ctx_train, n_ctx);
+ }
+
+ // print system information
+ {
+ LOG_TEE("\n");
+ LOG_TEE("%s\n", get_system_info(params).c_str());
+ }
+
+ std::string path_session = params.path_prompt_cache;
+ std::vector<llama_token> session_tokens;
+
+ if (!path_session.empty()) {
+ LOG_TEE("%s: attempting to load saved session from '%s'\n", __func__, path_session.c_str());
+ if (!file_exists(path_session)) {
+ LOG_TEE("%s: session file does not exist, will create.\n", __func__);
+ } else if (file_is_empty(path_session)) {
+ LOG_TEE("%s: The session file is empty. A new session will be initialized.\n", __func__);
+ } else {
+ // The file exists and is not empty
+ session_tokens.resize(n_ctx);
+ size_t n_token_count_out = 0;
+ if (!llama_state_load_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.capacity(), &n_token_count_out)) {
+ LOG_TEE("%s: error: failed to load session file '%s'\n", __func__, path_session.c_str());
+ return 1;
+ }
+ session_tokens.resize(n_token_count_out);
+ LOG_TEE("%s: loaded a session with prompt size of %d tokens\n", __func__, (int)session_tokens.size());
+ }
+ }
+
+ const bool add_bos = llama_should_add_bos_token(model);
+ GGML_ASSERT(llama_add_eos_token(model) != 1);
+ LOG("add_bos: %d\n", add_bos);
+
+ std::vector<llama_token> embd_inp;
+
+ if (params.interactive_first || params.instruct || params.chatml || !params.prompt.empty() || session_tokens.empty()) {
+ LOG("tokenize the prompt\n");
+ if (params.chatml) {
+ params.prompt = "<|im_start|>system\n" + params.prompt + "<|im_end|>";
+ }
+ embd_inp = ::llama_tokenize(ctx, params.prompt, true, true);
+ } else {
+ LOG("use session tokens\n");
+ embd_inp = session_tokens;
+ }
+
+ LOG("prompt: \"%s\"\n", log_tostr(params.prompt));
+ LOG("tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
+
+ // Should not run without any tokens
+ if (embd_inp.empty()) {
+ embd_inp.push_back(llama_token_bos(model));
+ LOG("embd_inp was considered empty and bos was added: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_inp).c_str());
+ }
+
+ // Tokenize negative prompt
+ std::vector<llama_token> guidance_inp;
+ int guidance_offset = 0;
+ int original_prompt_len = 0;
+ if (ctx_guidance) {
+ LOG("cfg_negative_prompt: \"%s\"\n", log_tostr(sparams.cfg_negative_prompt));
+
+ guidance_inp = ::llama_tokenize(ctx_guidance, sparams.cfg_negative_prompt, true, true);
+ LOG("guidance_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx_guidance, guidance_inp).c_str());
+
+ std::vector<llama_token> original_inp = ::llama_tokenize(ctx, params.prompt, true, true);
+ LOG("original_inp tokenized: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, original_inp).c_str());
+
+ original_prompt_len = original_inp.size();
+ guidance_offset = (int)guidance_inp.size() - original_prompt_len;
+ LOG("original_prompt_len: %s", log_tostr(original_prompt_len));
+ LOG("guidance_offset: %s", log_tostr(guidance_offset));
+ }
+
+ if ((int) embd_inp.size() > n_ctx - 4) {
+ LOG_TEE("%s: error: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
+ return 1;
+ }
+
+ // debug message about similarity of saved session, if applicable
+ size_t n_matching_session_tokens = 0;
+ if (!session_tokens.empty()) {
+ for (llama_token id : session_tokens) {
+ if (n_matching_session_tokens >= embd_inp.size() || id != embd_inp[n_matching_session_tokens]) {
+ break;
+ }
+ n_matching_session_tokens++;
+ }
+ if (params.prompt.empty() && n_matching_session_tokens == embd_inp.size()) {
+ LOG_TEE("%s: using full prompt from session file\n", __func__);
+ } else if (n_matching_session_tokens >= embd_inp.size()) {
+ LOG_TEE("%s: session file has exact match for prompt!\n", __func__);
+ } else if (n_matching_session_tokens < (embd_inp.size() / 2)) {
+ LOG_TEE("%s: warning: session file has low similarity to prompt (%zu / %zu tokens); will mostly be reevaluated\n",
+ __func__, n_matching_session_tokens, embd_inp.size());
+ } else {
+ LOG_TEE("%s: session file matches %zu / %zu tokens of prompt\n",
+ __func__, n_matching_session_tokens, embd_inp.size());
+ }
+
+ // remove any "future" tokens that we might have inherited from the previous session
+ llama_kv_cache_seq_rm(ctx, -1, n_matching_session_tokens, -1);
+ }
+
+ LOGLN(
+ "recalculate the cached logits (check): embd_inp.empty() %s, n_matching_session_tokens %zu, embd_inp.size() %zu, session_tokens.size() %zu, embd_inp.size() %zu",
+ log_tostr(embd_inp.empty()), n_matching_session_tokens, embd_inp.size(), session_tokens.size(), embd_inp.size());
+
+ // if we will use the cache for the full prompt without reaching the end of the cache, force
+ // reevaluation of the last token to recalculate the cached logits
+ if (!embd_inp.empty() && n_matching_session_tokens == embd_inp.size() && session_tokens.size() > embd_inp.size()) {
+ LOGLN("recalculate the cached logits (do): session_tokens.resize( %zu )", embd_inp.size() - 1);
+
+ session_tokens.resize(embd_inp.size() - 1);
+ }
+
+ // number of tokens to keep when resetting context
+ if (params.n_keep < 0 || params.n_keep > (int) embd_inp.size() || params.instruct || params.chatml) {
+ params.n_keep = (int)embd_inp.size();
+ } else {
+ params.n_keep += add_bos; // always keep the BOS token
+ }
+
+ // prefix & suffix for instruct mode
+ const auto inp_pfx = ::llama_tokenize(ctx, "\n\n### Instruction:\n\n", true, true);
+ const auto inp_sfx = ::llama_tokenize(ctx, "\n\n### Response:\n\n", false, true);
+
+ LOG("inp_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_pfx).c_str());
+ LOG("inp_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, inp_sfx).c_str());
+
+ // chatml prefix & suffix
+ const auto cml_pfx = ::llama_tokenize(ctx, "\n<|im_start|>user\n", true, true);
+ const auto cml_sfx = ::llama_tokenize(ctx, "<|im_end|>\n<|im_start|>assistant\n", false, true);
+
+ LOG("cml_pfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, cml_pfx).c_str());
+ LOG("cml_sfx: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, cml_sfx).c_str());
+
+ // in instruct mode, we inject a prefix and a suffix to each input by the user
+ if (params.instruct) {
+ params.interactive_first = true;
+ params.antiprompt.emplace_back("### Instruction:\n\n");
+ }
+ // similar for chatml mode
+ else if (params.chatml) {
+ params.interactive_first = true;
+ params.antiprompt.emplace_back("<|im_start|>user\n");
+ }
+ else if (params.conversation) {
+ params.interactive_first = true;
+ }
+
+ // enable interactive mode if interactive start is specified
+ if (params.interactive_first) {
+ params.interactive = true;
+ }
+
+ if (params.verbose_prompt) {
+ LOG_TEE("\n");
+ LOG_TEE("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
+ LOG_TEE("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size());
+ for (int i = 0; i < (int) embd_inp.size(); i++) {
+ LOG_TEE("%6d -> '%s'\n", embd_inp[i], llama_token_to_piece(ctx, embd_inp[i]).c_str());
+ }
+
+ if (ctx_guidance) {
+ LOG_TEE("\n");
+ LOG_TEE("%s: negative prompt: '%s'\n", __func__, sparams.cfg_negative_prompt.c_str());
+ LOG_TEE("%s: number of tokens in negative prompt = %zu\n", __func__, guidance_inp.size());
+ for (int i = 0; i < (int) guidance_inp.size(); i++) {
+ LOG_TEE("%6d -> '%s'\n", guidance_inp[i], llama_token_to_piece(ctx, guidance_inp[i]).c_str());
+ }
+ }
+
+ if (params.n_keep > add_bos) {
+ LOG_TEE("%s: static prompt based on n_keep: '", __func__);
+ for (int i = 0; i < params.n_keep; i++) {
+ LOG_TEE("%s", llama_token_to_piece(ctx, embd_inp[i]).c_str());
+ }
+ LOG_TEE("'\n");
+ }
+ LOG_TEE("\n");
+ }
+
+ struct sigaction sa;
+ sa.sa_handler = sigint_handler;
+ sigemptyset(&sa.sa_mask);
+ sa.sa_flags = 0;
+ sigaction(SIGINT, &sa, NULL);
+
+ if (params.interactive) {
+ LOG_TEE("%s: interactive mode on.\n", __func__);
+
+ if (!params.antiprompt.empty()) {
+ for (const auto & antiprompt : params.antiprompt) {
+ LOG_TEE("Reverse prompt: '%s'\n", antiprompt.c_str());
+ if (params.verbose_prompt) {
+ auto tmp = ::llama_tokenize(ctx, antiprompt, false, true);
+ for (int i = 0; i < (int) tmp.size(); i++) {
+ LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
+ }
+ }
+ }
+ }
+
+ if (params.input_prefix_bos) {
+ LOG_TEE("Input prefix with BOS\n");
+ }
+
+ if (!params.input_prefix.empty()) {
+ LOG_TEE("Input prefix: '%s'\n", params.input_prefix.c_str());
+ if (params.verbose_prompt) {
+ auto tmp = ::llama_tokenize(ctx, params.input_prefix, true, true);
+ for (int i = 0; i < (int) tmp.size(); i++) {
+ LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
+ }
+ }
+ }
+
+ if (!params.input_suffix.empty()) {
+ LOG_TEE("Input suffix: '%s'\n", params.input_suffix.c_str());
+ if (params.verbose_prompt) {
+ auto tmp = ::llama_tokenize(ctx, params.input_suffix, false, true);
+ for (int i = 0; i < (int) tmp.size(); i++) {
+ LOG_TEE("%6d -> '%s'\n", tmp[i], llama_token_to_piece(ctx, tmp[i]).c_str());
+ }
+ }
+ }
+ }
+ LOG_TEE("sampling: \n%s\n", llama_sampling_print(sparams).c_str());
+ LOG_TEE("sampling order: \n%s\n", llama_sampling_order_print(sparams).c_str());
+ LOG_TEE("generate: n_ctx = %d, n_batch = %d, n_predict = %d, n_keep = %d\n", n_ctx, params.n_batch, params.n_predict, params.n_keep);
+
+ // group-attention state
+ // number of grouped KV tokens so far (used only if params.grp_attn_n > 1)
+ int ga_i = 0;
+
+ const int ga_n = params.grp_attn_n;
+ const int ga_w = params.grp_attn_w;
+
+ if (ga_n != 1) {
+ GGML_ASSERT(ga_n > 0 && "grp_attn_n must be positive"); // NOLINT
+ GGML_ASSERT(ga_w % ga_n == 0 && "grp_attn_w must be a multiple of grp_attn_n"); // NOLINT
+ //GGML_ASSERT(n_ctx_train % ga_w == 0 && "n_ctx_train must be a multiple of grp_attn_w"); // NOLINT
+ //GGML_ASSERT(n_ctx >= n_ctx_train * ga_n && "n_ctx must be at least n_ctx_train * grp_attn_n"); // NOLINT
+ LOG_TEE("self-extend: n_ctx_train = %d, grp_attn_n = %d, grp_attn_w = %d\n", n_ctx_train, ga_n, ga_w);
+ }
+ LOG_TEE("\n\n");
+
+ if (params.interactive) {
+ const char *control_message;
+ if (params.multiline_input) {
+ control_message = " - To return control to LLaMa, end your input with '\\'.\n"
+ " - To return control without starting a new line, end your input with '/'.\n";
+ } else {
+ control_message = " - Press Return to return control to LLaMa.\n"
+ " - To return control without starting a new line, end your input with '/'.\n"
+ " - If you want to submit another line, end your input with '\\'.\n";
+ }
+ LOG_TEE("== Running in interactive mode. ==\n");
+#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
+ LOG_TEE( " - Press Ctrl+C to interject at any time.\n");
+#endif
+ LOG_TEE( "%s\n", control_message);
+
+ is_interacting = params.interactive_first;
+ }
+
+ bool is_antiprompt = false;
+ bool input_echo = true;
+ bool display = true;
+ bool need_to_save_session = !path_session.empty() && n_matching_session_tokens < embd_inp.size();
+
+ int n_past = 0;
+ int n_remain = params.n_predict;
+ int n_consumed = 0;
+ int n_session_consumed = 0;
+ int n_past_guidance = 0;
+
+ std::vector<int> input_tokens; g_input_tokens = &input_tokens;
+ std::vector<int> output_tokens; g_output_tokens = &output_tokens;
+ std::ostringstream output_ss; g_output_ss = &output_ss;
+
+ // the first thing we will do is to output the prompt, so set color accordingly
+ console::set_display(console::prompt);
+ display = params.display_prompt;
+
+ std::vector<llama_token> embd;
+ std::vector<llama_token> embd_guidance;
+
+ // tokenized antiprompts
+ std::vector<std::vector<llama_token>> antiprompt_ids;
+
+ antiprompt_ids.reserve(params.antiprompt.size());
+ for (const std::string & antiprompt : params.antiprompt) {
+ antiprompt_ids.emplace_back(::llama_tokenize(ctx, antiprompt, false, true));
+ }
+
+ struct llama_sampling_context * ctx_sampling = llama_sampling_init(sparams);
+ if (!ctx_sampling) {
+ fprintf(stderr, "%s: failed to initialize sampling subsystem\n", __func__);
+ exit(1);
+ }
+
+ while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
+ // predict
+ if (!embd.empty()) {
+ // Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via
+ // --prompt or --file which uses the same value.
+ int max_embd_size = n_ctx - 4;
+
+ // Ensure the input doesn't exceed the context size by truncating embd if necessary.
+ if ((int) embd.size() > max_embd_size) {
+ const int skipped_tokens = (int) embd.size() - max_embd_size;
+ embd.resize(max_embd_size);
+
+ console::set_display(console::error);
+ printf("<<input too long: skipped %d token%s>>", skipped_tokens, skipped_tokens != 1 ? "s" : "");
+ console::set_display(console::reset);
+ fflush(stdout);
+ }
+
+ if (ga_n == 1) {
+ // infinite text generation via context shifting
+ // if we run out of context:
+ // - take the n_keep first tokens from the original prompt (via n_past)
+ // - take half of the last (n_ctx - n_keep) tokens and recompute the logits in batches
+ if (n_past + (int) embd.size() + std::max<int>(0, guidance_offset) >= n_ctx) {
+ if (params.n_predict == -2) {
+ LOG_TEE("\n\n%s: context full and n_predict == -%d => stopping\n", __func__, params.n_predict);
+ break;
+ }
+
+ const int n_left = n_past - params.n_keep;
+ const int n_discard = n_left/2;
+
+ LOG("context full, swapping: n_past = %d, n_left = %d, n_ctx = %d, n_keep = %d, n_discard = %d\n",
+ n_past, n_left, n_ctx, params.n_keep, n_discard);
+
+ llama_kv_cache_seq_rm (ctx, 0, params.n_keep , params.n_keep + n_discard);
+ llama_kv_cache_seq_add(ctx, 0, params.n_keep + n_discard, n_past, -n_discard);
+
+ n_past -= n_discard;
+
+ if (ctx_guidance) {
+ n_past_guidance -= n_discard;
+ }
+
+ LOG("after swap: n_past = %d, n_past_guidance = %d\n", n_past, n_past_guidance);
+
+ LOG("embd: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
+
+ LOG("clear session path\n");
+ path_session.clear();
+ }
+ } else {
+ // context extension via Self-Extend
+ while (n_past >= ga_i + ga_w) {
+ const int ib = (ga_n*ga_i)/ga_w;
+ const int bd = (ga_w/ga_n)*(ga_n - 1);
+ const int dd = (ga_w/ga_n) - ib*bd - ga_w;
+
+ LOG("\n");
+ LOG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i, n_past, ib*bd, ga_i + ib*bd, n_past + ib*bd);
+ LOG("div: [%6d, %6d] / %6d -> [%6d, %6d]\n", ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n, (ga_i + ib*bd)/ga_n, (ga_i + ib*bd + ga_w)/ga_n);
+ LOG("shift: [%6d, %6d] + %6d -> [%6d, %6d]\n", ga_i + ib*bd + ga_w, n_past + ib*bd, dd, ga_i + ib*bd + ga_w + dd, n_past + ib*bd + dd);
+
+ llama_kv_cache_seq_add(ctx, 0, ga_i, n_past, ib*bd);
+ llama_kv_cache_seq_div(ctx, 0, ga_i + ib*bd, ga_i + ib*bd + ga_w, ga_n);
+ llama_kv_cache_seq_add(ctx, 0, ga_i + ib*bd + ga_w, n_past + ib*bd, dd);
+
+ n_past -= bd;
+
+ ga_i += ga_w/ga_n;
+
+ LOG("\nn_past_old = %d, n_past = %d, ga_i = %d\n\n", n_past + bd, n_past, ga_i);
+ }
+ }
+
+ // try to reuse a matching prefix from the loaded session instead of re-eval (via n_past)
+ if (n_session_consumed < (int) session_tokens.size()) {
+ size_t i = 0;
+ for ( ; i < embd.size(); i++) {
+ if (embd[i] != session_tokens[n_session_consumed]) {
+ session_tokens.resize(n_session_consumed);
+ break;
+ }
+
+ n_past++;
+ n_session_consumed++;
+
+ if (n_session_consumed >= (int) session_tokens.size()) {
+ ++i;
+ break;
+ }
+ }
+ if (i > 0) {
+ embd.erase(embd.begin(), embd.begin() + i);
+ }
+ }
+
+ // evaluate tokens in batches
+ // embd is typically prepared beforehand to fit within a batch, but not always
+ if (ctx_guidance) {
+ int input_size = 0;
+ llama_token * input_buf = NULL;
+
+ if (n_past_guidance < (int) guidance_inp.size()) {
+ // Guidance context should have the same data with these modifications:
+ //
+ // * Replace the initial prompt
+ // * Shift everything by guidance_offset
+ embd_guidance = guidance_inp;
+ if (embd.begin() + original_prompt_len < embd.end()) {
+ embd_guidance.insert(
+ embd_guidance.end(),
+ embd.begin() + original_prompt_len,
+ embd.end()
+ );
+ }
+
+ input_buf = embd_guidance.data();
+ input_size = embd_guidance.size();
+
+ LOG("guidance context: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd_guidance).c_str());
+ } else {
+ input_buf = embd.data();
+ input_size = embd.size();
+ }
+
+ for (int i = 0; i < input_size; i += params.n_batch) {
+ int n_eval = std::min(input_size - i, params.n_batch);
+ if (llama_decode(ctx_guidance, llama_batch_get_one(input_buf + i, n_eval, n_past_guidance, 0))) {
+ LOG_TEE("%s : failed to eval\n", __func__);
+ return 1;
+ }
+
+ n_past_guidance += n_eval;
+ }
+ }
+
+ for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
+ int n_eval = (int) embd.size() - i;
+ if (n_eval > params.n_batch) {
+ n_eval = params.n_batch;
+ }
+
+ LOG("eval: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, embd).c_str());
+
+ if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
+ LOG_TEE("%s : failed to eval\n", __func__);
+ return 1;
+ }
+
+ n_past += n_eval;
+
+ LOG("n_past = %d\n", n_past);
+ // Display total tokens alongside total time
+ if (params.n_print > 0 && n_past % params.n_print == 0) {
+ LOG_TEE("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
+ }
+ }
+
+ if (!embd.empty() && !path_session.empty()) {
+ session_tokens.insert(session_tokens.end(), embd.begin(), embd.end());
+ n_session_consumed = session_tokens.size();
+ }
+ }
+
+ embd.clear();
+ embd_guidance.clear();
+
+ if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
+ // optionally save the session on first sample (for faster prompt loading next time)
+ if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
+ need_to_save_session = false;
+ llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
+
+ LOG("saved session to %s\n", path_session.c_str());
+ }
+
+ const llama_token id = llama_sampling_sample(ctx_sampling, ctx, ctx_guidance);
+
+ llama_sampling_accept(ctx_sampling, ctx, id, /* apply_grammar= */ true);
+
+ LOG("last: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, ctx_sampling->prev).c_str());
+
+ embd.push_back(id);
+
+ // echo this to console
+ input_echo = true;
+
+ // decrement remaining sampling budget
+ --n_remain;
+
+ LOG("n_remain: %d\n", n_remain);
+ } else {
+ // some user input remains from prompt or interaction, forward it to processing
+ LOG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
+ while ((int) embd_inp.size() > n_consumed) {
+ embd.push_back(embd_inp[n_consumed]);
+
+ // push the prompt in the sampling context in order to apply repetition penalties later
+ // for the prompt, we don't apply grammar rules
+ llama_sampling_accept(ctx_sampling, ctx, embd_inp[n_consumed], /* apply_grammar= */ false);
+
+ ++n_consumed;
+ if ((int) embd.size() >= params.n_batch) {
+ break;
+ }
+ }
+ }
+
+ // display text
+ if (input_echo && display) {
+ for (auto id : embd) {
+ const std::string token_str = llama_token_to_piece(ctx, id, !params.conversation && sparams.grammar.empty());
+ printf("%s", token_str.c_str());
+
+ if (embd.size() > 1) {
+ input_tokens.push_back(id);
+ } else {
+ output_tokens.push_back(id);
+ output_ss << token_str;
+ }
+ }
+ fflush(stdout);
+ }
+ // reset color to default if there is no pending user input
+ if (input_echo && (int) embd_inp.size() == n_consumed) {
+ console::set_display(console::reset);
+ display = true;
+ }
+
+ // if not currently processing queued inputs;
+ if ((int) embd_inp.size() <= n_consumed) {
+ // check for reverse prompt in the last n_prev tokens
+ if (!params.antiprompt.empty()) {
+ const int n_prev = 32;
+ const std::string last_output = llama_sampling_prev_str(ctx_sampling, ctx, n_prev);
+
+ is_antiprompt = false;
+ // Check if each of the reverse prompts appears at the end of the output.
+ // If we're not running interactively, the reverse prompt might be tokenized with some following characters
+ // so we'll compensate for that by widening the search window a bit.
+ for (std::string & antiprompt : params.antiprompt) {
+ size_t extra_padding = params.interactive ? 0 : 2;
+ size_t search_start_pos = last_output.length() > static_cast<size_t>(antiprompt.length() + extra_padding)
+ ? last_output.length() - static_cast<size_t>(antiprompt.length() + extra_padding)
+ : 0;
+
+ if (last_output.find(antiprompt, search_start_pos) != std::string::npos) {
+ if (params.interactive) {
+ is_interacting = true;
+ }
+ is_antiprompt = true;
+ break;
+ }
+ }
+
+ // check for reverse prompt using special tokens
+ llama_token last_token = llama_sampling_last(ctx_sampling);
+ for (std::vector<llama_token> ids : antiprompt_ids) {
+ if (ids.size() == 1 && last_token == ids[0]) {
+ if (params.interactive) {
+ is_interacting = true;
+ }
+ is_antiprompt = true;
+ break;
+ }
+ }
+
+ if (is_antiprompt) {
+ LOG("found antiprompt: %s\n", last_output.c_str());
+ }
+ }
+
+ // deal with end of generation tokens in interactive mode
+ if (llama_token_is_eog(model, llama_sampling_last(ctx_sampling))) {
+ LOG("found an EOG token\n");
+
+ if (params.interactive) {
+ if (!params.antiprompt.empty()) {
+ // tokenize and inject first reverse prompt
+ const auto first_antiprompt = ::llama_tokenize(ctx, params.antiprompt.front(), false, true);
+ embd_inp.insert(embd_inp.end(), first_antiprompt.begin(), first_antiprompt.end());
+ is_antiprompt = true;
+ }
+
+ is_interacting = true;
+ printf("\n");
+ } else if (params.instruct || params.chatml) {
+ is_interacting = true;
+ }
+ }
+
+ if (n_past > 0 && is_interacting) {
+ LOG("waiting for user input\n");
+
+ if (params.conversation || params.instruct || params.chatml) {
+ printf("\n> ");
+ }
+
+ if (params.input_prefix_bos) {
+ LOG("adding input prefix BOS token\n");
+ embd_inp.push_back(llama_token_bos(model));
+ }
+
+ std::string buffer;
+ if (!params.input_prefix.empty() && !params.conversation) {
+ LOG("appending input prefix: '%s'\n", params.input_prefix.c_str());
+ printf("%s", params.input_prefix.c_str());
+ }
+
+ // color user input only
+ console::set_display(console::user_input);
+ display = params.display_prompt;
+
+ std::string line;
+ bool another_line = true;
+ do {
+ another_line = console::readline(line, params.multiline_input);
+ buffer += line;
+ } while (another_line);
+
+ // done taking input, reset color
+ console::set_display(console::reset);
+ display = true;
+
+ // Add tokens to embd only if the input buffer is non-empty
+ // Entering a empty line lets the user pass control back
+ if (buffer.length() > 1) {
+ // append input suffix if any
+ if (!params.input_suffix.empty() && !params.conversation) {
+ LOG("appending input suffix: '%s'\n", params.input_suffix.c_str());
+ printf("%s", params.input_suffix.c_str());
+ }
+
+ LOG("buffer: '%s'\n", buffer.c_str());
+
+ const size_t original_size = embd_inp.size();
+
+ // instruct mode: insert instruction prefix
+ if (params.instruct && !is_antiprompt) {
+ LOG("inserting instruction prefix\n");
+ n_consumed = embd_inp.size();
+ embd_inp.insert(embd_inp.end(), inp_pfx.begin(), inp_pfx.end());
+ }
+ // chatml mode: insert user chat prefix
+ if (params.chatml && !is_antiprompt) {
+ LOG("inserting chatml prefix\n");
+ n_consumed = embd_inp.size();
+ embd_inp.insert(embd_inp.end(), cml_pfx.begin(), cml_pfx.end());
+ }
+ if (params.escape) {
+ process_escapes(buffer);
+ }
+
+ const auto line_pfx = ::llama_tokenize(ctx, params.input_prefix, false, true);
+ const auto line_inp = ::llama_tokenize(ctx, buffer, false, params.interactive_specials);
+ const auto line_sfx = ::llama_tokenize(ctx, params.input_suffix, false, true);
+
+ LOG("input tokens: %s\n", LOG_TOKENS_TOSTR_PRETTY(ctx, line_inp).c_str());
+
+ embd_inp.insert(embd_inp.end(), line_pfx.begin(), line_pfx.end());
+ embd_inp.insert(embd_inp.end(), line_inp.begin(), line_inp.end());
+ embd_inp.insert(embd_inp.end(), line_sfx.begin(), line_sfx.end());
+
+ // instruct mode: insert response suffix
+ if (params.instruct) {
+ LOG("inserting instruction suffix\n");
+ embd_inp.insert(embd_inp.end(), inp_sfx.begin(), inp_sfx.end());
+ }
+ // chatml mode: insert assistant chat suffix
+ if (params.chatml) {
+ LOG("inserting chatml suffix\n");
+ embd_inp.insert(embd_inp.end(), cml_sfx.begin(), cml_sfx.end());
+ }
+
+ for (size_t i = original_size; i < embd_inp.size(); ++i) {
+ const llama_token token = embd_inp[i];
+ output_tokens.push_back(token);
+ output_ss << llama_token_to_piece(ctx, token);
+ }
+
+ n_remain -= line_inp.size();
+ LOG("n_remain: %d\n", n_remain);
+ } else {
+ LOG("empty line, passing control back\n");
+ }
+
+ input_echo = false; // do not echo this again
+ }
+
+ if (n_past > 0) {
+ if (is_interacting) {
+ llama_sampling_reset(ctx_sampling);
+ }
+ is_interacting = false;
+ }
+ }
+
+ // end of generation
+ if (!embd.empty() && llama_token_is_eog(model, embd.back()) && !(params.instruct || params.interactive || params.chatml)) {
+ LOG_TEE(" [end of text]\n");
+ break;
+ }
+
+ // In interactive mode, respect the maximum number of tokens and drop back to user input when reached.
+ // We skip this logic when n_predict == -1 (infinite) or -2 (stop at context size).
+ if (params.interactive && n_remain <= 0 && params.n_predict >= 0) {
+ n_remain = params.n_predict;
+ is_interacting = true;
+ }
+ }
+
+ // [jart] ensure trailing newline
+ printf("\n");
+
+ if (!path_session.empty() && params.prompt_cache_all && !params.prompt_cache_ro) {
+ LOG_TEE("\n%s: saving final output to session file '%s'\n", __func__, path_session.c_str());
+ llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
+ }
+
+ llama_print_timings(ctx);
+ write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
+
+ if (ctx_guidance) { llama_free(ctx_guidance); }
+ llama_free(ctx);
+ llama_free_model(model);
+
+ llama_sampling_free(ctx_sampling);
+ llama_backend_free();
+
+#ifndef LOG_DISABLE_LOGS
+ LOG_TEE("Log end\n");
+#endif // LOG_DISABLE_LOGS
+
+ return 0;
+}