LLM inference in C/C++
Go to file
xaedes e32089b2c2
train : improved training-from-scratch example (#1652)
* add python wrapper

https://gist.github.com/abetlen/2b90e5f153f6efd00931d098de5c73ce

* fix decoding error. adds errors=ignore parameter

* add python bindings for functions to get and set the whole llama state
(rng, logits, embedding and kv_cache)

* update python bindings

* add text generating baby-llama from scratch example

* fix race condition bug in ggml_compute_forward_diag_mask_f32

* implement ggml_soft_max_back for more performant backward pass of soft_max

avoids creating big intermediate matrices of size n_embd x n_embd for llama layers and n_vocab x n_vocab for cross entropy loss

* improve softmax backward pass

go from quadratic runtime to linear runtime by simplifying the formulas

* fix race condition bug in non-inplace ggml_compute_forward_diag_mask_f32

memcpy needs to be synchronized across threads to avoid race conditions.
=> do it in INIT phase

* fix bug in ggml_compute_forward_soft_max_back_f32 on DEBUG build

* improve performance of mul_mat backward pass

avoid transpose by using mul_mat with swapped arguments

* avoid printing too much newlines in baby-llama-text

* activate threading in baby-llama-text

* add ggml_out_prod and use it for mul_mat backward pass for improved performance

performance stats report improvement from 37 seconds to 16 seconds runtime during my training tests

* better weight initialization improves training convergence at start

* better weight initialization improves training convergence at start

* improve ggml_out_prod performance

- change iteration order (>15s -> 10s runtime)
- parallelize over one more dimension: over dst matrix rows (10s -> <5s runtime)

* add llama sampler, shuffle samples and constrain sampling to tokens occurring in train data

* fix get_samples call, add model tensor names, increase model size, start training samples after newline

* save train trained model to checkpoint and load model to be trained from checkpoint

* use inplace functions where possible

* initialize rng with srand

* use different arguments for input and output checkpoint

* ggml fixes to support backward pass on inplace operations

* remove duplicate include

* fix cross entropy loss

- add target probabilities for each sample which is then used in cross entropy loss

* print used memory before and after optimization

* sample with non-greedy sampling parameters at the end of training

* add cmake target for baby-llama-text

* add ggml_add1_inplace to header

* enable gradient propagation for inplace add1 and scale operations

those functions backward passes don't need the original src0, so they also work when forward is inplace

* implement AdamW in ggml_opt_adam by adding weight decay parameter (default 0.001f)

also add a schedule parameter (default 1.0f) that can be used to scale alpha and decay according to learning schedule.
setting the decay parameter to zero disables AdamW resulting in normal Adam optimizer.

since the difference between Adam and AdamW is minimal it is not implemented as another optimizer, but integrated into the existing Adam optimizer.

* use inplace operations in cross_entropy_loss

* fix random weight initialization scale

* add missing default parameters for adam optimizer

* add ggml_opt_context, so that we can properly resume training

otherwise the optimizer states, tracking statistics about the error function and its derivates,
will reset to zero each time ggml_opt is called, hindering convergence on resumed training.

now the optimizer context and all its memory is stored in a separate struct.

* fix bug in llama_sample_token_mirostat_v2

when all candidates are filtered out through mu threshold, the following soft_max operation will fail.
so keep at least one.

* add forward function without using cache, for more performant training

during training on whole samples no cache is required.
removing the cache and simplifying the remaining code results in performance and memory usage improvement.

* print suppressed newline tokens as string "\n"

printing too much actual newlines is suppressed to avoid flooding the console.

* store optimizer state in training checkpoint and add learning schedule

persistent optimizer state allows to resume training without resetting the optimizer
learning schedule consists of linear warmup ramp followed by cosine decay with restarts

* remove unused functions

* fix bug in get_samples which corrupted training targets

* save checkpoint only when it was trained

* simplify code

* remove trailing whitespace

* simplify backward pass for SQRT

* replace inefficient repeat backward pass with dedicated repeat_back operation

* add ggml_cross_entropy_loss with backward pass for faster training

cross entropy loss can also be implemented using softmax and log, but as dedicated operation it is faster and especially avoids unnecessary memory overhead.

* add tests for cross_entropy_loss backward pass

finite differences regularly results in estimated gradient of zero, despite the backward pass giving non zero gradient.
_probably_ the finite differences fails due to numerical issues

* use ggml_cross_entropy_loss in text training example

* remove trailing whitespace

* slightly improve how cross entropy loss is compute

btw: directly implemented cross entropy loss seems to have way lower magnitudes than when implemented with softmax and log.
probably the input to log gets closer to zero due to float numerics.
maybe the multiplication by (1.0-eps)/sum is more accurate..

* add llama_get_vocab to get the vocabulary as output parameters

* set default model.type for unknown models with few layers

* add export of training checkpoint to llama compatible model file

* get vocabulary for exporting training checkpoint to llama compatible model file

* implement backward pass of flash attention

* bugfixes for backward pass of flash attention

* test flash attention backward pass

need to set loose error bounds to pass.
the finitie differences are close to numeric limits and often return quite different values than the backward pass.
reducing eps further lets the gradients vanish completely.
likewise setting eps to big results in wronger values.
the softmax in the middle of the function is probably the most responsible for the numeric issues using finite differences.

* add option to train with flash attention and move options to the top of the main function

training from scratch also works with flash attention
training convergence and generation results after fix number of iterations are worse than when not using flash attention.
maybe there still lingers a bug in the flash attention backward pass?
but training works, just with slower convergence.

flash attention is still worth to use, because it requires way less memory and is faster with high n_ctx

* add train_params and command line option parser

* remove unnecessary comments

* add train params to specify memory size

* remove python bindings

* rename baby-llama-text to train-text-from-scratch

* replace auto parameters in lambda function

* add #include <climits>

* add explicit cast to fix compile error

"error: non-constant-expression cannot be narrowed from type 'int64_t' (aka 'long long') to 'uint32_t' (aka 'unsigned int') in initializer list [-Wc++11-narrowing]"

* remove trailing whitespace

* add ggml_opt_resume_g which accepts forward and backward cgraphs

* fix formulas in comments

* bug fix for ggml_compute_forward_get_rows_back_f32

the result should be set to zero, not to whatever data is in opt0

* improve training memory usage with scratch buffers

instead of relying on the automatic backward pass, we manually create the graph for the backward pass.
it turns out that all backward pass operations need only temporary memory which can be reused after each layer.

will compute backward pass for ALL model parameters

* add option to use scratch buffers in training or not

make it configurable because currently training with scratch buffers implies flash attention and optimization over all parameters.

* ci : disable temporary

* store view offset and permute axes in opt[0] instead of storing it in padding

use memcpy to store offset, because offset is of type size_t.
when storing it as int32_t offset would have to be smaller than 2^31 which is not necessarily true.

* minor : fix compile warnings + minor style changes

* fix bug in threaded indices calculation of ggml_compute_forward_flash_attn_back_f32

* store view offset like in master branch

* bug fix in forward_batch_wo_cache_flash_attn_train

* scratch buffer bug fixes in forward_batch_wo_cache_flash_attn_train

data of permute and reshape is the same as their input.
if we want to preserve the output of permute/reshape, we also need to preserve their inputs.

replace reshape(src0, src1) with reshape_nd calls so that we don't need src1.

replace (temporary) t03 with ggml_repeat(ctx0, layer.attention_norm, t02).
in the future we could also use the new broadcasting ggml_mul to avoid these repeat calls.
for this we need backward pass of broadcasting ggml_mul.

* remove unnecessary scratch buffer 0

buf 0 is persistent memory, so we can just disable scratch for this by using buf -1

* avoid creating unnecessary grad tensors

previously we need to create grads for model parameters, so that expand(..) correctly populates cgraph->leafs & cgraph->grads
this wasted memory, because unnecessary grad for each op were automatically created:
the automatically generated grad was unnecessary because we later manually set the grad (e.g. t35->grad = expand(gb, ...) ).
this discarded the automatically generated grad resulting in wasted memory.

improved this by changing expand(..) to not use ggml_build_forward_expand.
expand set cgraph->nodes but not the leafs.
cgraph->leafs & cgraph->grads are set in another pass after the last expand call.

* print used training seed

* zero initialize gfbuf and gbbuf

* ci : re-enable workflows + add README for training

---------

Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
2023-06-13 22:04:40 +03:00
.devops Add llama.cpp docker support for non-latin languages (#1673) 2023-06-08 00:58:53 -07:00
.github ci : run when changing only the CUDA sources (#1800) 2023-06-12 20:12:47 +03:00
docs docs : add performance troubleshoot + example benchmark documentation (#1674) 2023-06-05 23:32:36 +03:00
examples train : improved training-from-scratch example (#1652) 2023-06-13 22:04:40 +03:00
media media : add logos and banners 2023-04-05 18:58:31 +03:00
models Make loading weights 10-100x faster 2023-03-30 12:28:25 -07:00
pocs ggml : a faster version for Q4_1 x Q8_0 dot products (#1083) 2023-04-21 18:18:26 +03:00
prompts prompts : model agnostic DAN (#1304) 2023-05-11 18:10:19 +03:00
scripts ggml : remove bit shuffling (#1405) 2023-05-12 00:23:08 +03:00
spm-headers deploy : add a Package.swift for SwiftPM support (#393) 2023-03-28 19:39:01 +03:00
tests train : improved training-from-scratch example (#1652) 2023-06-13 22:04:40 +03:00
.clang-tidy clang-tidy : restore dot file from accidental deletion 2023-06-08 10:09:08 +03:00
.dockerignore Fix whitespace, add .editorconfig, add GitHub workflow (#883) 2023-04-11 19:45:44 +00:00
.ecrc Fix whitespace, add .editorconfig, add GitHub workflow (#883) 2023-04-11 19:45:44 +00:00
.editorconfig do not force the prompt file to end with a new line (#908) 2023-04-13 11:33:16 +02:00
.gitignore ggml : fix builds, add ggml-quants-k.o (close #1712, close #1710) 2023-06-06 10:18:03 +03:00
build.zig zig : update build.zig (#872) 2023-04-13 16:43:22 +03:00
CMakeLists.txt cmake : fix Metal build (close #1791) 2023-06-10 22:56:53 +03:00
convert-lora-to-ggml.py py : cast lora_alpha to int in convert-lora-to-ggml (#1170) 2023-04-25 23:33:08 +02:00
convert-pth-to-ggml.py Docker: change to calling convert.py (#1641) 2023-06-03 15:11:53 +03:00
convert.py convert.py: Support models which are stored in a single pytorch_model.bin (#1469) 2023-05-17 00:04:35 +02:00
flake.lock flake : update to support metal on m1/m2 (#1724) 2023-06-07 07:15:31 +03:00
flake.nix metal : fix issue with ggml-metal.metal path. Closes #1769 (#1782) 2023-06-10 17:47:34 +03:00
ggml-cuda.cu Leverage mmap for offloading tensors to GPU (#1597) 2023-06-12 14:44:16 +02:00
ggml-cuda.h Leverage mmap for offloading tensors to GPU (#1597) 2023-06-12 14:44:16 +02:00
ggml-metal.h llama : Metal inference (#1642) 2023-06-04 23:34:30 +03:00
ggml-metal.m Metal implementation for all k_quants (#1807) 2023-06-12 22:39:21 +03:00
ggml-metal.metal Metal implementation for all k_quants (#1807) 2023-06-12 22:39:21 +03:00
ggml-opencl.cpp Leverage mmap for offloading tensors to GPU (#1597) 2023-06-12 14:44:16 +02:00
ggml-opencl.h Leverage mmap for offloading tensors to GPU (#1597) 2023-06-12 14:44:16 +02:00
ggml.c train : improved training-from-scratch example (#1652) 2023-06-13 22:04:40 +03:00
ggml.h train : improved training-from-scratch example (#1652) 2023-06-13 22:04:40 +03:00
k_quants.c k-quants : GCC12 compilation fix (#1792) 2023-06-10 22:51:36 +03:00
k_quants.h k-quants : allow to optionally disable at compile time (#1734) 2023-06-07 10:59:52 +03:00
LICENSE Add LICENSE (#21) 2023-03-12 08:36:03 +02:00
llama-util.h metal : use shared buffers between CPU and GPU (#1696) 2023-06-05 23:24:04 +03:00
llama.cpp train : improved training-from-scratch example (#1652) 2023-06-13 22:04:40 +03:00
llama.h train : improved training-from-scratch example (#1652) 2023-06-13 22:04:40 +03:00
Makefile Allow "quantizing" to f16 and f32 (#1787) 2023-06-13 04:23:23 -06:00
Package.swift Add Accelerate/BLAS when using Swift (#765) 2023-04-05 06:44:24 -04:00
README.md doc : fix wrong address of BLIS.md (#1772) 2023-06-10 17:08:11 +03:00
requirements.txt py : bump sentencepiece to 0.1.98 to support Python 3.11 (#976) 2023-04-14 19:46:49 +00:00
SHA256SUMS Update SHA256SUMS with current hashes for models quantized using q4_0 (#1798) 2023-06-11 12:38:53 +03:00

llama.cpp

llama

Actions Status License: MIT

Inference of LLaMA model in pure C/C++

Hot topics:

Table of Contents
  1. Description
  2. Usage
  3. Contributing
  4. Coding guidelines
  5. Docs

Description

The main goal of llama.cpp is to run the LLaMA model using 4-bit integer quantization on a MacBook

  • Plain C/C++ implementation without dependencies
  • Apple silicon first-class citizen - optimized via ARM NEON, Accelerate and Metal frameworks
  • AVX, AVX2 and AVX512 support for x86 architectures
  • Mixed F16 / F32 precision
  • 4-bit, 5-bit and 8-bit integer quantization support
  • Supports OpenBLAS/Apple BLAS/ARM Performance Lib/ATLAS/BLIS/Intel MKL/NVHPC/ACML/SCSL/SGIMATH and more in BLAS
  • cuBLAS and CLBlast support

The original implementation of llama.cpp was hacked in an evening. Since then, the project has improved significantly thanks to many contributions. This project is for educational purposes and serves as the main playground for developing new features for the ggml library.

Supported platforms:

  • Mac OS
  • Linux
  • Windows (via CMake)
  • Docker

Supported models:

Bindings:

UI:


Here is a typical run using LLaMA-7B:

make -j && ./main -m ./models/7B/ggml-model-q4_0.bin -p "Building a website can be done in 10 simple steps:" -n 512
I llama.cpp build info:
I UNAME_S:  Darwin
I UNAME_P:  arm
I UNAME_M:  arm64
I CFLAGS:   -I.              -O3 -DNDEBUG -std=c11   -fPIC -pthread -DGGML_USE_ACCELERATE
I CXXFLAGS: -I. -I./examples -O3 -DNDEBUG -std=c++11 -fPIC -pthread
I LDFLAGS:   -framework Accelerate
I CC:       Apple clang version 14.0.0 (clang-1400.0.29.202)
I CXX:      Apple clang version 14.0.0 (clang-1400.0.29.202)

make: Nothing to be done for `default'.
main: seed = 1678486056
llama_model_load: loading model from './models/7B/ggml-model-q4_0.bin' - please wait ...
llama_model_load: n_vocab = 32000
llama_model_load: n_ctx   = 512
llama_model_load: n_embd  = 4096
llama_model_load: n_mult  = 256
llama_model_load: n_head  = 32
llama_model_load: n_layer = 32
llama_model_load: n_rot   = 128
llama_model_load: f16     = 2
llama_model_load: n_ff    = 11008
llama_model_load: ggml ctx size = 4529.34 MB
llama_model_load: memory_size =   512.00 MB, n_mem = 16384
llama_model_load: .................................... done
llama_model_load: model size =  4017.27 MB / num tensors = 291

main: prompt: 'Building a website can be done in 10 simple steps:'
main: number of tokens in prompt = 15
     1 -> ''
  8893 -> 'Build'
   292 -> 'ing'
   263 -> ' a'
  4700 -> ' website'
   508 -> ' can'
   367 -> ' be'
  2309 -> ' done'
   297 -> ' in'
 29871 -> ' '
 29896 -> '1'
 29900 -> '0'
  2560 -> ' simple'
  6576 -> ' steps'
 29901 -> ':'

sampling parameters: temp = 0.800000, top_k = 40, top_p = 0.950000


Building a website can be done in 10 simple steps:
1) Select a domain name and web hosting plan
2) Complete a sitemap
3) List your products
4) Write product descriptions
5) Create a user account
6) Build the template
7) Start building the website
8) Advertise the website
9) Provide email support
10) Submit the website to search engines
A website is a collection of web pages that are formatted with HTML. HTML is the code that defines what the website looks like and how it behaves.
The HTML code is formatted into a template or a format. Once this is done, it is displayed on the user's browser.
The web pages are stored in a web server. The web server is also called a host. When the website is accessed, it is retrieved from the server and displayed on the user's computer.
A website is known as a website when it is hosted. This means that it is displayed on a host. The host is usually a web server.
A website can be displayed on different browsers. The browsers are basically the software that renders the website on the user's screen.
A website can also be viewed on different devices such as desktops, tablets and smartphones.
Hence, to have a website displayed on a browser, the website must be hosted.
A domain name is an address of a website. It is the name of the website.
The website is known as a website when it is hosted. This means that it is displayed on a host. The host is usually a web server.
A website can be displayed on different browsers. The browsers are basically the software that renders the website on the users screen.
A website can also be viewed on different devices such as desktops, tablets and smartphones. Hence, to have a website displayed on a browser, the website must be hosted.
A domain name is an address of a website. It is the name of the website.
A website is an address of a website. It is a collection of web pages that are formatted with HTML. HTML is the code that defines what the website looks like and how it behaves.
The HTML code is formatted into a template or a format. Once this is done, it is displayed on the users browser.
A website is known as a website when it is hosted

main: mem per token = 14434244 bytes
main:     load time =  1332.48 ms
main:   sample time =  1081.40 ms
main:  predict time = 31378.77 ms / 61.41 ms per token
main:    total time = 34036.74 ms

And here is another demo of running both LLaMA-7B and whisper.cpp on a single M1 Pro MacBook:

https://user-images.githubusercontent.com/1991296/224442907-7693d4be-acaa-4e01-8b4f-add84093ffff.mp4

Usage

Here are the steps for the LLaMA-7B model.

Get the Code

git clone https://github.com/ggerganov/llama.cpp
cd llama.cpp

Build

In order to build llama.cpp you have three different options.

  • Using make:

    • On Linux or MacOS:

      make
      
    • On Windows:

      1. Download the latest fortran version of w64devkit.
      2. Extract w64devkit on your pc.
      3. Run w64devkit.exe.
      4. Use the cd command to reach the llama.cpp folder.
      5. From here you can run:
        make
        
  • Using CMake:

    mkdir build
    cd build
    cmake ..
    cmake --build . --config Release
    
  • Using Zig:

    zig build -Drelease-fast
    

Metal Build

Using Metal allows the computation to be executed on the GPU for Apple devices:

  • Using make:

    LLAMA_METAL=1 make
    
  • Using CMake:

    mkdir build-metal
    cd build-metal
    cmake -DLLAMA_METAL=ON ..
    cmake --build . --config Release
    

When built with Metal support, you can enable GPU inference with the --gpu-layers|-ngl command-line argument. Any value larger than 0 will offload the computation to the GPU. For example:

./main -m ./models/7B/ggml-model-q4_0.bin -n 128 -ngl 1

BLAS Build

Building the program with BLAS support may lead to some performance improvements in prompt processing using batch sizes higher than 32 (the default is 512). BLAS doesn't affect the normal generation performance. There are currently three different implementations of it:

  • Accelerate Framework:

    This is only available on Mac PCs and it's enabled by default. You can just build using the normal instructions.

  • OpenBLAS:

    This provides BLAS acceleration using only the CPU. Make sure to have OpenBLAS installed on your machine.

    • Using make:

      • On Linux:

        make LLAMA_OPENBLAS=1
        
      • On Windows:

        1. Download the latest fortran version of w64devkit.

        2. Download the latest version of OpenBLAS for Windows.

        3. Extract w64devkit on your pc.

        4. From the OpenBLAS zip that you just downloaded copy libopenblas.a, located inside the lib folder, inside w64devkit\x86_64-w64-mingw32\lib.

        5. From the same OpenBLAS zip copy the content of the include folder inside w64devkit\x86_64-w64-mingw32\include.

        6. Run w64devkit.exe.

        7. Use the cd command to reach the llama.cpp folder.

        8. From here you can run:

          make LLAMA_OPENBLAS=1
          
    • Using CMake on Linux:

      mkdir build
      cd build
      cmake .. -DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=OpenBLAS
      cmake --build . --config Release
      
  • BLIS

    Check BLIS.md for more information.

  • Intel MKL

    By default, LLAMA_BLAS_VENDOR is set to Generic, so if you already sourced intel environment script and assign -DLLAMA_BLAS=ON in cmake, the mkl version of Blas will automatically been selected. You may also specify it by:

    mkdir build
    cd build
    cmake .. -DLLAMA_BLAS=ON -DLLAMA_BLAS_VENDOR=Intel10_64lp -DCMAKE_C_COMPILER=icx -DCMAKE_CXX_COMPILER=icpx
    cmake --build . --config Release
    
  • cuBLAS

    This provides BLAS acceleration using the CUDA cores of your Nvidia GPU. Make sure to have the CUDA toolkit installed. You can download it from your Linux distro's package manager or from here: CUDA Toolkit.

    • Using make:

      make LLAMA_CUBLAS=1
      
    • Using CMake:

      mkdir build
      cd build
      cmake .. -DLLAMA_CUBLAS=ON
      cmake --build . --config Release
      

    Note: Because llama.cpp uses multiple CUDA streams for matrix multiplication results are not guaranteed to be reproducible. If you need reproducibility, set GGML_CUDA_MAX_STREAMS in the file ggml-cuda.cu to 1.

    The environment variable CUDA_VISIBLE_DEVICES can be used to specify which GPU(s) will be used.

  • CLBlast

    OpenCL acceleration is provided by the matrix multiplication kernels from the CLBlast project and custom kernels for ggml that can generate tokens on the GPU.

    You will need the OpenCL SDK.

    • For Ubuntu or Debian, the packages opencl-headers, ocl-icd may be needed.

    • Installing the OpenCL SDK from source
      git clone --recurse-submodules https://github.com/KhronosGroup/OpenCL-SDK.git
      mkdir OpenCL-SDK/build
      cd OpenCL-SDK/build
      cmake .. -DBUILD_DOCS=OFF \
        -DBUILD_EXAMPLES=OFF \
        -DBUILD_TESTING=OFF \
        -DOPENCL_SDK_BUILD_SAMPLES=OFF \
        -DOPENCL_SDK_TEST_SAMPLES=OFF
      cmake --build . --config Release
      cmake --install . --prefix /some/path
      

    Installing CLBlast: it may be found in your operating system's packages.

    • If not, then installing from source:
      git clone https://github.com/CNugteren/CLBlast.git
      mkdir CLBlast/build
      cd CLBLast/build
      cmake .. -DBUILD_SHARED_LIBS=OFF -DTUNERS=OFF
      cmake --build . --config Release
      cmake --install . --prefix /some/path
      

      Where /some/path is where the built library will be installed (default is /usr/local).

    Building:

    • Build with make:
      make LLAMA_CLBLAST=1
      
    • CMake:
      mkdir build
      cd build
      cmake .. -DLLAMA_CLBLAST=ON -DCLBlast_dir=/some/path
      cmake --build . --config Release
      

    Running:

    The CLBlast build supports --gpu-layers|-ngl like the CUDA version does.

    To select the correct platform (driver) and device (GPU), you can use the environment variables GGML_OPENCL_PLATFORM and GGML_OPENCL_DEVICE. The selection can be a number (starting from 0) or a text string to search:

    GGML_OPENCL_PLATFORM=1 ./main ...
    GGML_OPENCL_DEVICE=2 ./main ...
    GGML_OPENCL_PLATFORM=Intel ./main ...
    GGML_OPENCL_PLATFORM=AMD GGML_OPENCL_DEVICE=1 ./main ...
    

    The default behavior is to find the first GPU device, but when it is an integrated GPU on a laptop, for instance, the selectors are useful. Using the variables it is possible to select a CPU-based driver as well, if so desired.

    You can get a list of platforms and devices from the clinfo -l command, etc.

Prepare Data & Run

# obtain the original LLaMA model weights and place them in ./models
ls ./models
65B 30B 13B 7B tokenizer_checklist.chk tokenizer.model

# install Python dependencies
python3 -m pip install -r requirements.txt

# convert the 7B model to ggml FP16 format
python3 convert.py models/7B/

# quantize the model to 4-bits (using q4_0 method)
./quantize ./models/7B/ggml-model-f16.bin ./models/7B/ggml-model-q4_0.bin q4_0

# run the inference
./main -m ./models/7B/ggml-model-q4_0.bin -n 128

When running the larger models, make sure you have enough disk space to store all the intermediate files.

Memory/Disk Requirements

As the models are currently fully loaded into memory, you will need adequate disk space to save them and sufficient RAM to load them. At the moment, memory and disk requirements are the same.

Model Original size Quantized size (4-bit)
7B 13 GB 3.9 GB
13B 24 GB 7.8 GB
30B 60 GB 19.5 GB
65B 120 GB 38.5 GB

Quantization

Several quantization methods are supported. They differ in the resulting model disk size and inference speed.

Model Measure F16 Q4_0 Q4_1 Q5_0 Q5_1 Q8_0
7B perplexity 5.9066 6.1565 6.0912 5.9862 5.9481 5.9070
7B file size 13.0G 3.5G 3.9G 4.3G 4.7G 6.7G
7B ms/tok @ 4th 127 55 54 76 83 72
7B ms/tok @ 8th 122 43 45 52 56 67
7B bits/weight 16.0 4.5 5.0 5.5 6.0 8.5
13B perplexity 5.2543 5.3860 5.3608 5.2856 5.2706 5.2548
13B file size 25.0G 6.8G 7.6G 8.3G 9.1G 13G
13B ms/tok @ 4th - 103 105 148 160 131
13B ms/tok @ 8th - 73 82 98 105 128
13B bits/weight 16.0 4.5 5.0 5.5 6.0 8.5

Perplexity (measuring model quality)

You can use the perplexity example to measure perplexity over a given prompt (lower perplexity is better). For more information, see https://huggingface.co/docs/transformers/perplexity.

The perplexity measurements in table above are done against the wikitext2 test dataset (https://paperswithcode.com/dataset/wikitext-2), with context length of 512. The time per token is measured on a MacBook M1 Pro 32GB RAM using 4 and 8 threads.

Interactive mode

If you want a more ChatGPT-like experience, you can run in interactive mode by passing -i as a parameter. In this mode, you can always interrupt generation by pressing Ctrl+C and entering one or more lines of text, which will be converted into tokens and appended to the current context. You can also specify a reverse prompt with the parameter -r "reverse prompt string". This will result in user input being prompted whenever the exact tokens of the reverse prompt string are encountered in the generation. A typical use is to use a prompt that makes LLaMa emulate a chat between multiple users, say Alice and Bob, and pass -r "Alice:".

Here is an example of a few-shot interaction, invoked with the command

# default arguments using a 7B model
./examples/chat.sh

# advanced chat with a 13B model
./examples/chat-13B.sh

# custom arguments using a 13B model
./main -m ./models/13B/ggml-model-q4_0.bin -n 256 --repeat_penalty 1.0 --color -i -r "User:" -f prompts/chat-with-bob.txt

Note the use of --color to distinguish between user input and generated text. Other parameters are explained in more detail in the README for the main example program.

image

Persistent Interaction

The prompt, user inputs, and model generations can be saved and resumed across calls to ./main by leveraging --prompt-cache and --prompt-cache-all. The ./examples/chat-persistent.sh script demonstrates this with support for long-running, resumable chat sessions. To use this example, you must provide a file to cache the initial chat prompt and a directory to save the chat session, and may optionally provide the same variables as chat-13B.sh. The same prompt cache can be reused for new chat sessions. Note that both prompt cache and chat directory are tied to the initial prompt (PROMPT_TEMPLATE) and the model file.

# Start a new chat
PROMPT_CACHE_FILE=chat.prompt.bin CHAT_SAVE_DIR=./chat/default ./examples/chat-persistent.sh

# Resume that chat
PROMPT_CACHE_FILE=chat.prompt.bin CHAT_SAVE_DIR=./chat/default ./examples/chat-persistent.sh

# Start a different chat with the same prompt/model
PROMPT_CACHE_FILE=chat.prompt.bin CHAT_SAVE_DIR=./chat/another ./examples/chat-persistent.sh

# Different prompt cache for different prompt/model
PROMPT_TEMPLATE=./prompts/chat-with-bob.txt PROMPT_CACHE_FILE=bob.prompt.bin \
    CHAT_SAVE_DIR=./chat/bob ./examples/chat-persistent.sh

Instruction mode with Alpaca

  1. First, download the ggml Alpaca model into the ./models folder
  2. Run the main tool like this:
./examples/alpaca.sh

Sample run:

== Running in interactive mode. ==
 - Press Ctrl+C to interject at any time.
 - Press Return to return control to LLaMa.
 - If you want to submit another line, end your input in '\'.

 Below is an instruction that describes a task. Write a response that appropriately completes the request.

> How many letters are there in the English alphabet?
There 26 letters in the English Alphabet
> What is the most common way of transportation in Amsterdam?
The majority (54%) are using public transit. This includes buses, trams and metros with over 100 lines throughout the city which make it very accessible for tourists to navigate around town as well as locals who commute by tram or metro on a daily basis
> List 5 words that start with "ca".
cadaver, cauliflower, cabbage (vegetable), catalpa (tree) and Cailleach.
>

Using GPT4All

  • Obtain the tokenizer.model file from LLaMA model and put it to models
  • Obtain the added_tokens.json file from Alpaca model and put it to models
  • Obtain the gpt4all-lora-quantized.bin file from GPT4All model and put it to models/gpt4all-7B
  • It is distributed in the old ggml format which is now obsoleted
  • You have to convert it to the new format using convert.py:
python3 convert.py models/gpt4all-7B/gpt4all-lora-quantized.bin
  • You can now use the newly generated models/gpt4all-7B/ggml-model-q4_0.bin model in exactly the same way as all other models

  • The newer GPT4All-J model is not yet supported!

Using Pygmalion 7B & Metharme 7B

python3 convert.py pygmalion-7b/ --outtype q4_1

The Pygmalion 7B & Metharme 7B weights are saved in bfloat16 precision. If you wish to convert to ggml without quantizating, please specify the --outtype as f32 instead of f16.

Obtaining the Facebook LLaMA original model and Stanford Alpaca model data

  • Under no circumstances should IPFS, magnet links, or any other links to model downloads be shared anywhere in this repository, including in issues, discussions, or pull requests. They will be immediately deleted.
  • The LLaMA models are officially distributed by Facebook and will never be provided through this repository.
  • Refer to Facebook's LLaMA repository if you need to request access to the model data.

Verifying the model files

Please verify the sha256 checksums of all downloaded model files to confirm that you have the correct model data files before creating an issue relating to your model files.

  • The following python script will verify if you have all possible latest files in your self-installed ./models subdirectory:
# run the verification script
python3 .\scripts\verify-checksum-models.py
  • On linux or macOS it is also possible to run the following commands to verify if you have all possible latest files in your self-installed ./models subdirectory:
    • On Linux: sha256sum --ignore-missing -c SHA256SUMS
    • on macOS: shasum -a 256 --ignore-missing -c SHA256SUMS

Seminal papers and background on the models

If your issue is with model generation quality, then please at least scan the following links and papers to understand the limitations of LLaMA models. This is especially important when choosing an appropriate model size and appreciating both the significant and subtle differences between LLaMA models and ChatGPT:

How to run

  1. Download/extract: https://s3.amazonaws.com/research.metamind.io/wikitext/wikitext-2-raw-v1.zip?ref=salesforce-research
  2. Run ./perplexity -m models/7B/ggml-model-q4_0.bin -f wiki.test.raw
  3. Output:
perplexity : calculating perplexity over 655 chunks
24.43 seconds per pass - ETA 4.45 hours
[1]4.5970,[2]5.1807,[3]6.0382,...

And after 4.45 hours, you will have the final perplexity.

Android

You can easily run llama.cpp on Android device with termux. First, obtain the Android NDK and then build with CMake:

$ mkdir build-android
$ cd build-android
$ export NDK=<your_ndk_directory>
$ cmake -DCMAKE_TOOLCHAIN_FILE=$NDK/build/cmake/android.toolchain.cmake -DANDROID_ABI=arm64-v8a -DANDROID_PLATFORM=android-23 -DCMAKE_C_FLAGS=-march=armv8.4a+dotprod ..
$ make

Install termux on your device and run termux-setup-storage to get access to your SD card. Finally, copy the llama binary and the model files to your device storage. Here is a demo of an interactive session running on Pixel 5 phone:

https://user-images.githubusercontent.com/271616/225014776-1d567049-ad71-4ef2-b050-55b0b3b9274c.mp4

Docker

Prerequisites

  • Docker must be installed and running on your system.
  • Create a folder to store big models & intermediate files (ex. /llama/models)

Images

We have two Docker images available for this project:

  1. ghcr.io/ggerganov/llama.cpp:full: This image includes both the main executable file and the tools to convert LLaMA models into ggml and convert into 4-bit quantization.
  2. ghcr.io/ggerganov/llama.cpp:light: This image only includes the main executable file.

Usage

The easiest way to download the models, convert them to ggml and optimize them is with the --all-in-one command which includes the full docker image.

Replace /path/to/models below with the actual path where you downloaded the models.

docker run -v /path/to/models:/models ghcr.io/ggerganov/llama.cpp:full --all-in-one "/models/" 7B

On completion, you are ready to play!

docker run -v /path/to/models:/models ghcr.io/ggerganov/llama.cpp:full --run -m /models/7B/ggml-model-q4_0.bin -p "Building a website can be done in 10 simple steps:" -n 512

or with a light image:

docker run -v /path/to/models:/models ghcr.io/ggerganov/llama.cpp:light -m /models/7B/ggml-model-q4_0.bin -p "Building a website can be done in 10 simple steps:" -n 512

Contributing

  • Contributors can open PRs
  • Collaborators can push to branches in the llama.cpp repo and merge PRs into the master branch
  • Collaborators will be invited based on contributions
  • Any help with managing issues and PRs is very appreciated!
  • Make sure to read this: Inference at the edge
  • A bit of backstory for those who are interested: Changelog podcast

Coding guidelines

  • Avoid adding third-party dependencies, extra files, extra headers, etc.
  • Always consider cross-compatibility with other operating systems and architectures
  • Avoid fancy looking modern STL constructs, use basic for loops, avoid templates, keep it simple
  • There are no strict rules for the code style, but try to follow the patterns in the code (indentation, spaces, etc.). Vertical alignment makes things more readable and easier to batch edit
  • Clean-up any trailing whitespaces, use 4 spaces for indentation, brackets on the same line, void * ptr, int & a
  • See good first issues for tasks suitable for first contributions

Docs