2023-03-10 19:40:58 +01:00
// Various helper functions and utilities
# pragma once
2023-03-22 06:32:36 +01:00
# include "llama.h"
2023-03-10 19:40:58 +01:00
# include <string>
# include <vector>
2024-09-15 19:46:12 +02:00
# include <sstream>
2023-03-10 19:40:58 +01:00
2023-08-28 17:59:39 +02:00
# ifdef _WIN32
# define DIRECTORY_SEPARATOR '\\'
# else
# define DIRECTORY_SEPARATOR ' / '
# endif // _WIN32
2023-09-15 20:02:01 +02:00
# define die(msg) do { fputs("error: " msg "\n", stderr); exit(1); } while (0)
# define die_fmt(fmt, ...) do { fprintf(stderr, "error: " fmt "\n", __VA_ARGS__); exit(1); } while (0)
2023-09-07 19:22:29 +02:00
2023-11-02 07:50:16 +01:00
# define print_build_info() do { \
2024-05-22 19:04:20 +02:00
fprintf ( stderr , " %s: build = %d (%s) \n " , __func__ , LLAMA_BUILD_NUMBER , LLAMA_COMMIT ) ; \
2023-11-02 07:50:16 +01:00
fprintf ( stderr , " %s: built with %s for %s \n " , __func__ , LLAMA_COMPILER , LLAMA_BUILD_TARGET ) ; \
2023-09-15 22:59:49 +02:00
} while ( 0 )
2024-04-30 01:52:50 +02:00
# define DEFAULT_MODEL_PATH "models / 7B / ggml-model-f16.gguf"
2024-10-10 22:57:42 +02:00
struct common_lora_adapter_info {
2024-08-06 17:33:39 +02:00
std : : string path ;
float scale ;
} ;
2024-10-10 22:57:42 +02:00
struct common_lora_adapter_container : common_lora_adapter_info {
2024-08-06 17:33:39 +02:00
struct llama_lora_adapter * adapter ;
} ;
2024-11-25 08:58:41 +01:00
using llama_tokens = std : : vector < llama_token > ;
2023-11-02 07:50:16 +01:00
// build info
extern int LLAMA_BUILD_NUMBER ;
2024-12-13 19:34:25 +01:00
extern const char * LLAMA_COMMIT ;
extern const char * LLAMA_COMPILER ;
extern const char * LLAMA_BUILD_TARGET ;
2023-11-02 07:50:16 +01:00
2024-10-10 22:57:42 +02:00
struct common_control_vector_load_info ;
2024-03-15 21:43:02 +01:00
2024-05-22 19:04:20 +02:00
//
// CPU utils
//
2024-09-09 23:36:09 +02:00
struct cpu_params {
int n_threads = - 1 ;
bool cpumask [ GGML_MAX_N_THREADS ] = { false } ; // CPU affinity mask.
bool mask_valid = false ; // Default: any CPU
enum ggml_sched_priority priority = GGML_SCHED_PRIO_NORMAL ; // Scheduling prio : (0 - normal, 1 - medium, 2 - high, 3 - realtime)
bool strict_cpu = false ; // Use strict CPU placement
uint32_t poll = 50 ; // Polling (busywait) level (0 - no polling, 100 - mostly polling)
} ;
2024-05-22 19:04:20 +02:00
int32_t cpu_get_num_physical_cores ( ) ;
int32_t cpu_get_num_math ( ) ;
2024-03-15 21:43:02 +01:00
2023-03-10 19:40:58 +01:00
//
2024-09-09 23:36:09 +02:00
// Common params
2023-03-10 19:40:58 +01:00
//
2024-09-07 20:43:51 +02:00
enum llama_example {
LLAMA_EXAMPLE_COMMON ,
LLAMA_EXAMPLE_SPECULATIVE ,
LLAMA_EXAMPLE_MAIN ,
LLAMA_EXAMPLE_INFILL ,
LLAMA_EXAMPLE_EMBEDDING ,
LLAMA_EXAMPLE_PERPLEXITY ,
LLAMA_EXAMPLE_RETRIEVAL ,
LLAMA_EXAMPLE_PASSKEY ,
LLAMA_EXAMPLE_IMATRIX ,
LLAMA_EXAMPLE_BENCH ,
LLAMA_EXAMPLE_SERVER ,
LLAMA_EXAMPLE_CVECTOR_GENERATOR ,
LLAMA_EXAMPLE_EXPORT_LORA ,
LLAMA_EXAMPLE_LLAVA ,
2024-09-09 23:36:09 +02:00
LLAMA_EXAMPLE_LOOKUP ,
LLAMA_EXAMPLE_PARALLEL ,
2024-09-07 20:43:51 +02:00
LLAMA_EXAMPLE_COUNT ,
} ;
2024-10-10 22:57:42 +02:00
enum common_sampler_type {
COMMON_SAMPLER_TYPE_NONE = 0 ,
2024-10-25 18:07:34 +02:00
COMMON_SAMPLER_TYPE_DRY = 1 ,
COMMON_SAMPLER_TYPE_TOP_K = 2 ,
COMMON_SAMPLER_TYPE_TOP_P = 3 ,
COMMON_SAMPLER_TYPE_MIN_P = 4 ,
2024-10-29 09:42:05 +01:00
//COMMON_SAMPLER_TYPE_TFS_Z = 5,
2024-10-25 18:07:34 +02:00
COMMON_SAMPLER_TYPE_TYPICAL_P = 6 ,
COMMON_SAMPLER_TYPE_TEMPERATURE = 7 ,
COMMON_SAMPLER_TYPE_XTC = 8 ,
COMMON_SAMPLER_TYPE_INFILL = 9 ,
2024-12-16 11:31:14 +01:00
COMMON_SAMPLER_TYPE_PENALTIES = 10 ,
2024-09-09 23:36:09 +02:00
} ;
2024-06-25 13:59:54 +02:00
// dimensionality reduction methods, used by cvector-generator
enum dimre_method {
DIMRE_METHOD_PCA ,
DIMRE_METHOD_MEAN ,
} ;
2024-11-25 08:58:41 +01:00
// sampling parameters
struct common_params_sampling {
2024-09-09 23:36:09 +02:00
uint32_t seed = LLAMA_DEFAULT_SEED ; // the seed used to initialize llama_sampler
2024-10-25 18:07:34 +02:00
int32_t n_prev = 64 ; // number of previous tokens to remember
int32_t n_probs = 0 ; // if greater than 0, output the probabilities of top n_probs tokens.
int32_t min_keep = 0 ; // 0 = disabled, otherwise samplers should return at least min_keep tokens
int32_t top_k = 40 ; // <= 0 to use vocab size
float top_p = 0.95f ; // 1.0 = disabled
float min_p = 0.05f ; // 0.0 = disabled
float xtc_probability = 0.00f ; // 0.0 = disabled
float xtc_threshold = 0.10f ; // > 0.5 disables XTC
float typ_p = 1.00f ; // typical_p, 1.0 = disabled
float temp = 0.80f ; // <= 0.0 to sample greedily, 0.0 to not output probabilities
float dynatemp_range = 0.00f ; // 0.0 = disabled
float dynatemp_exponent = 1.00f ; // controls how entropy maps to temperature in dynamic temperature sampler
int32_t penalty_last_n = 64 ; // last n tokens to penalize (0 = disable penalty, -1 = context size)
float penalty_repeat = 1.00f ; // 1.0 = disabled
float penalty_freq = 0.00f ; // 0.0 = disabled
float penalty_present = 0.00f ; // 0.0 = disabled
float dry_multiplier = 0.0f ; // 0.0 = disabled; DRY repetition penalty for tokens extending repetition:
float dry_base = 1.75f ; // 0.0 = disabled; multiplier * base ^ (length of sequence before token - allowed length)
int32_t dry_allowed_length = 2 ; // tokens extending repetitions beyond this receive penalty
int32_t dry_penalty_last_n = - 1 ; // how many tokens to scan for repetitions (0 = disable penalty, -1 = context size)
int32_t mirostat = 0 ; // 0 = disabled, 1 = mirostat, 2 = mirostat 2.0
float mirostat_tau = 5.00f ; // target entropy
float mirostat_eta = 0.10f ; // learning rate
bool ignore_eos = false ;
bool no_perf = false ; // disable performance metrics
2024-12-02 14:45:54 +01:00
bool timing_per_token = false ;
2024-10-25 18:07:34 +02:00
std : : vector < std : : string > dry_sequence_breakers = { " \n " , " : " , " \" " , " * " } ; // default sequence breakers for DRY
2024-09-09 23:36:09 +02:00
2024-10-15 12:54:55 +02:00
2024-10-10 22:57:42 +02:00
std : : vector < enum common_sampler_type > samplers = {
2024-12-16 11:31:14 +01:00
COMMON_SAMPLER_TYPE_PENALTIES ,
2024-10-25 18:07:34 +02:00
COMMON_SAMPLER_TYPE_DRY ,
2024-10-10 22:57:42 +02:00
COMMON_SAMPLER_TYPE_TOP_K ,
COMMON_SAMPLER_TYPE_TYPICAL_P ,
COMMON_SAMPLER_TYPE_TOP_P ,
COMMON_SAMPLER_TYPE_MIN_P ,
2024-10-15 12:54:55 +02:00
COMMON_SAMPLER_TYPE_XTC ,
2024-10-15 15:35:33 +02:00
COMMON_SAMPLER_TYPE_TEMPERATURE ,
2024-09-09 23:36:09 +02:00
} ;
std : : string grammar ; // optional BNF-like grammar to constrain sampling
std : : vector < llama_logit_bias > logit_bias ; // logit biases to apply
// print the parameters into a string
std : : string print ( ) const ;
Threadpool: take 2 (#8672)
* Introduce ggml_compute_threadpool
- OpenMP functional: check
- Vanilla ggml functional: Check
- ggml w/threadpool functional: Check
- OpenMP no regression: No glaring problems
- Vanilla ggml no regression: No glaring problems
- ggml w/threadpool no regression: No glaring problems
* Minor fixes
* fixed use after release bug
* fixed a harmless race condition
* Fix Android bulid issue
* fix more race conditions
* fix deadlock for cases where cgraph.n_nodes == 1
and fix --poll case
* threadpool: use cpu_get_num_math to set the default number of threadpool threads
This way we avoid using E-Cores and Hyperthreaded siblings.
* bench: create fresh threadpool for each test
For benchmarking it's better to start a fresh pool for each test with the exact number of threads
needed for that test. Having larger pools is suboptimal (causes more load, etc).
* atomics: always use stdatomics with clang and use relaxed memory order when polling in ggml_barrier
This also removes sched_yield() calls from ggml_barrier() to match OpenMP behavior.
* threadpool: make polling the default to match openmp behavior
All command line args now allow for setting poll to 0 (false).
* threadpool: do not wakeup threads in already paused threadpool
* fix potential race condition in check_for_work
* threadpool: do not create two threadpools if their params are identical
* threadpool: reduce pause/resume/wakeup overhead in common cases
We now start threadpool in paused state only if we have two.
The resume is now implicit (ie new work) which allows for reduced locking and context-switch overhead.
* threadpool: add support for hybrid polling
poll params (--poll, ...) now specify "polling level", i.e. how aggresively we poll before waiting on cond.var.
poll=0 means no polling, 1 means poll for 128K rounds then wait, 2 for 256K rounds, ...
The default value of 50 (ie 50x128K rounds) seems like a decent default across modern platforms.
We can tune this further as things evolve.
* threadpool: reduce the number of barrier required
New work is now indicated with an atomic counter that is incremented for
each new graph that needs to be computed.
This removes the need for extra barrier for clearing the "new_work" and
removes the special case for trivial graphs.
* threadpool: remove special-casing for disposable threadpools
With the efficient hybrid polling there is no need to make disposable pools any different.
This simplifies the overall logic and reduces branching.
Include n_threads in debug print for disposable threadpool.
Declare pause and stop flags as atomic_bool
This doesn't actually generate any memory barriers and simply informs
the thread sanitizer that these flags can be written & read by different
threads without locking.
* threadpool: do not clear barrier counters between graphs computes (fixes race with small graphs)
This fixes the race condition with very small graphs where the main thread happens to
start a new graph while the workers are just about to exit from barriers.
* threadpool: use relaxed order for chunk sync
Full memory barrier is an overkill for this since each thread works on different chunk
* threadpool: remove abort_callback from threadpool state
* threadpool: better naming for thread/cpumask releated functions
* threadpool: consistent use of int type for n_threads params
* threadpool: add support for ggml_threadpool_params_default/init
Also removes the need for explicit mask_specified param.
all-zero cpumask means use default (usually inherited) cpu affinity mask.
* threadpool: move typedef into ggml.h
* threadpool: fix apply_priority() function name
* threadpool: fix swift wrapper errors due to n_threads int type cleanup
* threadpool: enable --cpu-mask and other threadpool related options only if threadpool is enabled
* threadpool: replace checks for compute_thread ret code with proper status check
* threadpool: simplify threadpool init logic and fix main thread affinity application
Most of the init code is now exactly the same between threadpool and openmp.
* threadpool: update threadpool resume/pause function names
* threadpool: enable openmp by default for now
* threadpool: don't forget to free workers state when omp is enabled
* threadpool: avoid updating process priority on the platforms that do not require it
On Windows we need to change overall process priority class in order to set thread priorities,
but on Linux, Mac, etc we do not need to touch the overall process settings.
* threadpool: update calling thread prio and affinity only at start/resume
This avoids extra syscalls for each graph_compute()
* llama-bench: turn threadpool params into vectors, add output headers, etc
* llama-bench: add support for cool off between tests --delay
This helps for long running tests on platforms that are thermally limited (phones, laptops, etc).
--delay (disabled by default) introduces the sleep for N seconds before starting each test.
* threadpool: move process priority setting into the apps (bench and cli)
This avoids changing the overall process priority on Windows for the apps
that use ggml/llama.cpp directy.
* threadpool: move all pause/resume logic into ggml
* threadpool: futher api cleanup and prep for future refactoring
All threadpool related functions and structs use ggml_threadpool prefix.
* threadpool: minor indent fixes
* threadpool: improve setprioty error message
* Update examples/llama-bench/llama-bench.cpp
Co-authored-by: slaren <slarengh@gmail.com>
* threadpool: fix indent in set_threadpool call
* use int32_t for n_thread type in public llama.cpp API
* threadpool: use _new and _free instead of _create and _release
* fix two more public APIs to use int32_t for n_threads
* build: set _GNU_SOURCE for Adroid
---------
Co-authored-by: Max Krasnyansky <quic_maxk@quicinc.com>
Co-authored-by: fmz <quic_fzaghlou@quic.com>
Co-authored-by: Max Krasnyansky <max.krasnyansky@gmail.com>
Co-authored-by: slaren <slarengh@gmail.com>
2024-08-30 01:20:53 +02:00
} ;
2024-11-25 08:58:41 +01:00
struct common_params_speculative {
2024-11-25 19:30:06 +01:00
std : : vector < ggml_backend_dev_t > devices ; // devices to use for offloading
2024-11-25 08:58:41 +01:00
int32_t n_ctx = 0 ; // draft context size
int32_t n_max = 16 ; // maximum number of tokens to draft during speculative decoding
int32_t n_min = 5 ; // minimum number of draft tokens to use for speculative decoding
int32_t n_gpu_layers = - 1 ; // number of layers to store in VRAM for the draft model (-1 - use default)
float p_split = 0.1f ; // speculative decoding split probability
float p_min = 0.9f ; // minimum speculative decoding probability (greedy)
struct cpu_params cpuparams ;
struct cpu_params cpuparams_batch ;
std : : string model = " " ; // draft model for speculative decoding // NOLINT
} ;
2024-10-10 22:57:42 +02:00
struct common_params {
2024-06-06 15:30:58 +02:00
int32_t n_predict = - 1 ; // new tokens to predict
2024-11-02 14:18:56 +01:00
int32_t n_ctx = 4096 ; // context size
2024-06-06 15:30:58 +02:00
int32_t n_batch = 2048 ; // logical batch size for prompt processing (must be >=32 to use BLAS)
int32_t n_ubatch = 512 ; // physical batch size for prompt processing (must be >=32 to use BLAS)
int32_t n_keep = 0 ; // number of tokens to keep from initial prompt
int32_t n_chunks = - 1 ; // max number of chunks to process (-1 = unlimited)
int32_t n_parallel = 1 ; // number of parallel sequences to decode
int32_t n_sequences = 1 ; // number of sequences to decode
int32_t grp_attn_n = 1 ; // group-attention factor
int32_t grp_attn_w = 512 ; // group-attention width
int32_t n_print = - 1 ; // print token count every n tokens (-1 = disabled)
float rope_freq_base = 0.0f ; // RoPE base frequency
float rope_freq_scale = 0.0f ; // RoPE frequency scaling factor
2024-01-31 16:30:17 +01:00
float yarn_ext_factor = - 1.0f ; // YaRN extrapolation mix factor
2024-06-06 15:30:58 +02:00
float yarn_attn_factor = 1.0f ; // YaRN magnitude scaling factor
2024-01-31 16:30:17 +01:00
float yarn_beta_fast = 32.0f ; // YaRN low correction dim
2024-06-06 15:30:58 +02:00
float yarn_beta_slow = 1.0f ; // YaRN high correction dim
int32_t yarn_orig_ctx = 0 ; // YaRN original context length
2024-11-11 07:38:43 +01:00
float defrag_thold = 0.1f ; // KV cache defragmentation threshold
2024-03-03 11:40:27 +01:00
2024-11-25 19:30:06 +01:00
// offload params
2024-12-16 11:31:14 +01:00
std : : vector < ggml_backend_dev_t > devices ; // devices to use for offloading
int32_t n_gpu_layers = - 1 ; // number of layers to store in VRAM (-1 - use default)
int32_t main_gpu = 0 ; // the GPU that is used for scratch and small tensors
float tensor_split [ 128 ] = { 0 } ; // how split tensors should be distributed across GPUs
enum llama_split_mode split_mode = LLAMA_SPLIT_MODE_LAYER ; // how to split the model across GPUs
2024-11-25 19:30:06 +01:00
Threadpool: take 2 (#8672)
* Introduce ggml_compute_threadpool
- OpenMP functional: check
- Vanilla ggml functional: Check
- ggml w/threadpool functional: Check
- OpenMP no regression: No glaring problems
- Vanilla ggml no regression: No glaring problems
- ggml w/threadpool no regression: No glaring problems
* Minor fixes
* fixed use after release bug
* fixed a harmless race condition
* Fix Android bulid issue
* fix more race conditions
* fix deadlock for cases where cgraph.n_nodes == 1
and fix --poll case
* threadpool: use cpu_get_num_math to set the default number of threadpool threads
This way we avoid using E-Cores and Hyperthreaded siblings.
* bench: create fresh threadpool for each test
For benchmarking it's better to start a fresh pool for each test with the exact number of threads
needed for that test. Having larger pools is suboptimal (causes more load, etc).
* atomics: always use stdatomics with clang and use relaxed memory order when polling in ggml_barrier
This also removes sched_yield() calls from ggml_barrier() to match OpenMP behavior.
* threadpool: make polling the default to match openmp behavior
All command line args now allow for setting poll to 0 (false).
* threadpool: do not wakeup threads in already paused threadpool
* fix potential race condition in check_for_work
* threadpool: do not create two threadpools if their params are identical
* threadpool: reduce pause/resume/wakeup overhead in common cases
We now start threadpool in paused state only if we have two.
The resume is now implicit (ie new work) which allows for reduced locking and context-switch overhead.
* threadpool: add support for hybrid polling
poll params (--poll, ...) now specify "polling level", i.e. how aggresively we poll before waiting on cond.var.
poll=0 means no polling, 1 means poll for 128K rounds then wait, 2 for 256K rounds, ...
The default value of 50 (ie 50x128K rounds) seems like a decent default across modern platforms.
We can tune this further as things evolve.
* threadpool: reduce the number of barrier required
New work is now indicated with an atomic counter that is incremented for
each new graph that needs to be computed.
This removes the need for extra barrier for clearing the "new_work" and
removes the special case for trivial graphs.
* threadpool: remove special-casing for disposable threadpools
With the efficient hybrid polling there is no need to make disposable pools any different.
This simplifies the overall logic and reduces branching.
Include n_threads in debug print for disposable threadpool.
Declare pause and stop flags as atomic_bool
This doesn't actually generate any memory barriers and simply informs
the thread sanitizer that these flags can be written & read by different
threads without locking.
* threadpool: do not clear barrier counters between graphs computes (fixes race with small graphs)
This fixes the race condition with very small graphs where the main thread happens to
start a new graph while the workers are just about to exit from barriers.
* threadpool: use relaxed order for chunk sync
Full memory barrier is an overkill for this since each thread works on different chunk
* threadpool: remove abort_callback from threadpool state
* threadpool: better naming for thread/cpumask releated functions
* threadpool: consistent use of int type for n_threads params
* threadpool: add support for ggml_threadpool_params_default/init
Also removes the need for explicit mask_specified param.
all-zero cpumask means use default (usually inherited) cpu affinity mask.
* threadpool: move typedef into ggml.h
* threadpool: fix apply_priority() function name
* threadpool: fix swift wrapper errors due to n_threads int type cleanup
* threadpool: enable --cpu-mask and other threadpool related options only if threadpool is enabled
* threadpool: replace checks for compute_thread ret code with proper status check
* threadpool: simplify threadpool init logic and fix main thread affinity application
Most of the init code is now exactly the same between threadpool and openmp.
* threadpool: update threadpool resume/pause function names
* threadpool: enable openmp by default for now
* threadpool: don't forget to free workers state when omp is enabled
* threadpool: avoid updating process priority on the platforms that do not require it
On Windows we need to change overall process priority class in order to set thread priorities,
but on Linux, Mac, etc we do not need to touch the overall process settings.
* threadpool: update calling thread prio and affinity only at start/resume
This avoids extra syscalls for each graph_compute()
* llama-bench: turn threadpool params into vectors, add output headers, etc
* llama-bench: add support for cool off between tests --delay
This helps for long running tests on platforms that are thermally limited (phones, laptops, etc).
--delay (disabled by default) introduces the sleep for N seconds before starting each test.
* threadpool: move process priority setting into the apps (bench and cli)
This avoids changing the overall process priority on Windows for the apps
that use ggml/llama.cpp directy.
* threadpool: move all pause/resume logic into ggml
* threadpool: futher api cleanup and prep for future refactoring
All threadpool related functions and structs use ggml_threadpool prefix.
* threadpool: minor indent fixes
* threadpool: improve setprioty error message
* Update examples/llama-bench/llama-bench.cpp
Co-authored-by: slaren <slarengh@gmail.com>
* threadpool: fix indent in set_threadpool call
* use int32_t for n_thread type in public llama.cpp API
* threadpool: use _new and _free instead of _create and _release
* fix two more public APIs to use int32_t for n_threads
* build: set _GNU_SOURCE for Adroid
---------
Co-authored-by: Max Krasnyansky <quic_maxk@quicinc.com>
Co-authored-by: fmz <quic_fzaghlou@quic.com>
Co-authored-by: Max Krasnyansky <max.krasnyansky@gmail.com>
Co-authored-by: slaren <slarengh@gmail.com>
2024-08-30 01:20:53 +02:00
struct cpu_params cpuparams ;
struct cpu_params cpuparams_batch ;
2024-04-11 14:51:07 +02:00
ggml_backend_sched_eval_callback cb_eval = nullptr ;
void * cb_eval_user_data = nullptr ;
2024-03-03 11:40:27 +01:00
ggml_numa_strategy numa = GGML_NUMA_STRATEGY_DISABLED ;
2024-04-24 15:10:07 +02:00
enum llama_rope_scaling_type rope_scaling_type = LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED ;
enum llama_pooling_type pooling_type = LLAMA_POOLING_TYPE_UNSPECIFIED ; // pooling type for embeddings
2024-07-05 09:05:56 +02:00
enum llama_attention_type attention_type = LLAMA_ATTENTION_TYPE_UNSPECIFIED ; // attention type for embeddings
2023-03-17 20:46:46 +01:00
2024-11-25 08:58:41 +01:00
struct common_params_sampling sampling ;
struct common_params_speculative speculative ;
2023-07-11 18:18:43 +02:00
2024-09-09 23:36:09 +02:00
std : : string model = " " ; // model path // NOLINT
2024-12-06 11:14:32 +01:00
std : : string model_alias = " " ; // model alias // NOLINT
2024-09-09 23:36:09 +02:00
std : : string model_url = " " ; // model url to download // NOLINT
std : : string hf_token = " " ; // HF token // NOLINT
std : : string hf_repo = " " ; // HF repo // NOLINT
std : : string hf_file = " " ; // HF file // NOLINT
std : : string prompt = " " ; // NOLINT
std : : string prompt_file = " " ; // store the external prompt file name // NOLINT
std : : string path_prompt_cache = " " ; // path to file for saving/loading prompt eval state // NOLINT
std : : string input_prefix = " " ; // string to prefix user inputs with // NOLINT
std : : string input_suffix = " " ; // string to suffix user inputs with // NOLINT
std : : string lookup_cache_static = " " ; // path of static ngram cache file for lookup decoding // NOLINT
std : : string lookup_cache_dynamic = " " ; // path of dynamic ngram cache file for lookup decoding // NOLINT
std : : string logits_file = " " ; // file for saving *all* logits // NOLINT
std : : string rpc_servers = " " ; // comma separated list of RPC servers // NOLINT
2023-03-12 22:13:28 +01:00
2024-06-06 15:30:58 +02:00
std : : vector < std : : string > in_files ; // all input files
2024-06-04 20:23:39 +02:00
std : : vector < std : : string > antiprompt ; // strings upon which more user input is prompted (a.k.a. reverse prompts)
2023-12-05 18:19:18 +01:00
std : : vector < llama_model_kv_override > kv_overrides ;
2024-08-06 17:33:39 +02:00
bool lora_init_without_apply = false ; // only load lora to memory, but do not apply it to ctx (user can manually apply lora later using llama_lora_adapter_apply)
2024-10-10 22:57:42 +02:00
std : : vector < common_lora_adapter_info > lora_adapters ; // lora adapter path with user defined scale
2023-04-17 17:28:55 +02:00
2024-10-10 22:57:42 +02:00
std : : vector < common_control_vector_load_info > control_vectors ; // control vector with user defined scale
2024-03-15 21:43:02 +01:00
2024-06-06 15:30:58 +02:00
int32_t verbosity = 0 ;
2024-03-15 21:43:02 +01:00
int32_t control_vector_layer_start = - 1 ; // layer range for control vector
int32_t control_vector_layer_end = - 1 ; // layer range for control vector
2024-06-06 15:30:58 +02:00
int32_t ppl_stride = 0 ; // stride for perplexity calculations. If left at 0, the pre-existing approach will be used.
int32_t ppl_output_type = 0 ; // = 0 -> ppl output is as usual, = 1 -> ppl output is num_tokens, ppl, one per line
// (which is more convenient to use for plotting)
//
bool hellaswag = false ; // compute HellaSwag score over random tasks from datafile supplied in prompt
size_t hellaswag_tasks = 400 ; // number of tasks to use when computing the HellaSwag score
2023-07-28 20:25:36 +02:00
2024-06-06 15:30:58 +02:00
bool winogrande = false ; // compute Winogrande score over random tasks from datafile supplied in prompt
size_t winogrande_tasks = 0 ; // number of tasks to use when computing the Winogrande score. If 0, all tasks will be computed
2024-01-18 12:46:27 +01:00
2024-06-06 15:30:58 +02:00
bool multiple_choice = false ; // compute TruthfulQA score over random tasks from datafile supplied in prompt
size_t multiple_choice_tasks = 0 ; // number of tasks to use when computing the TruthfulQA score. If 0, all tasks will be computed
2024-01-21 13:42:44 +01:00
2024-06-06 15:30:58 +02:00
bool kl_divergence = false ; // compute KL divergence
2024-01-22 15:10:14 +01:00
2024-06-04 20:23:39 +02:00
bool usage = false ; // print usage
2023-03-21 16:32:14 +01:00
bool use_color = false ; // use color to distinguish generations and inputs
2024-05-26 16:10:17 +02:00
bool special = false ; // enable special token output
2024-06-04 20:23:39 +02:00
bool interactive = false ; // interactive mode
bool interactive_first = false ; // wait for user input immediately
2024-05-08 16:32:32 +02:00
bool conversation = false ; // conversation mode (does not print special tokens and suffix/prefix)
2023-05-10 17:37:14 +02:00
bool prompt_cache_all = false ; // save user input and generations to prompt cache
2023-06-07 04:10:17 +02:00
bool prompt_cache_ro = false ; // open the prompt cache read-only and do not update it
2023-03-24 16:05:13 +01:00
2024-06-04 20:23:39 +02:00
bool escape = true ; // escape "\n", "\r", "\t", "\'", "\"", and "\\"
2023-05-09 04:45:48 +02:00
bool multiline_input = false ; // reverse the usage of `\`
2023-08-04 17:20:12 +02:00
bool simple_io = false ; // improves compatibility with subprocesses and limited consoles
2024-03-22 12:08:28 +01:00
bool cont_batching = true ; // insert new sequences for decoding on-the-fly
ggml : add Flash Attention (#5021)
* ggml : add ggml_flash_attn_ext API
* ggml : fix GQA support in ggml_flash_attn_ext
* ggml : online attention (CPU)
* metal : initial implementation
* metal : f16 precision
* metal : reduce branches
* metal : specialize for head size
* wip : 8 rows per simd group
* wip : 4 rows per simd group
* wip : template for rows per warp
* metal : parallelize across KV size
* metal : parallel reduce across heads
* metal : efficient flash_attn_f16 implementation
* metal : avoid redundant loads of the attention
* metal : scale and mask in matrix form
* metal : fix comment
* llama : avoid ggml_cast, use F32 query
* metal : add parallel reduce version (disabled)
* metal : move output into local memory + optimize
- the result from each simdgroup now stays in the registers
- significantly reduced SRAM usage
- more efficient skipping of -INF blocks
- avoid simdgroup barrier in hot loop
- add comments
* metal : add tests, fix scaling, support C > 32
* metal : improve precision
* ggml : fix f16 mad
* metal : minor
* metal : support Q > 8
* tests : add ATTN tests
* metal : disable buffer allocation logs
* tests : more
* metal : faster inner loop for C == 32
* metal : fix array initialization
* tests : ifdef
* ggml : switch to padded F16 mask for ggml_soft_max, ggml_flash_attn_ext
* ggml : fix ggml_soft_max mask requirement
* cuda : fix soft_max to use correct mask size
* cuda : add flash_attn kernel (wip)
* metal : optimize softmax for C > 32
* metal : optimize softmax
* tests : minor fix
* cuda : avoid zeroing fragments
* tests : update dims
* cuda : fix __hisinf() result check
* cuda : avoid warp_reduce for smax
* cuda : use int instead of int64_t
Noticeably improves performance (thanks to Johannes)
* cuda : make loops use the same loop values
Thanks Johannes again for the tip
* cuda : unroll some of the loops
* cuda : avoid __hisinf branches
* cuda : use half2 in softmax
* cuda : switch to 1 warp for bs > 16
* cuda : speed-up reduce part of the kernel
* cuda : unroll Q*K^T loop
* cuda : fix -INF block check
* cuda : simplify softmax
* cuda : fix matrix names
* cuda : minor
* llama : adapt to F16 KQ_pos
* llama : adapt new models to F16 KQ_mask
* ggml : fix F16 store (ARM NEON)
* llama : fix type of KQ_mask and KQ_pos
* ggml : fix CPU soft_max
* tests : add hs=256
* cuda : fix build
* metal : improve perf via smaller int registers
* cuda : adapt soft_max to F16 mask and pos
* CUDA: faster FlashAttention, kernel for bs == 1
* 16 cols for Phi-2
* no vec for hs, no hs==256 ncols==32 for Volta
* adjust kernel selection logic
* 4 warps, 256 stride for all D
* no ncols == 64
* Multiple parallel blocks for batch size 1
* fix compile warnings
* fix excessive KQ_b loads
* fix cmake build
* fix KV cache padding, NaN from INFINITY (#6438)
* llama : flash_attn cparam + fix defrag
* server: support flash_attn param
* server: bench: enable flash_attn param
* CUDA: refactor host code, dyn. par. blocks
* fix flash_attn_vec_f16 race condition
* flush softmax exp below threshold to 0
* store temp KQ in registers
* Calculate KQ as FP32 if KQV has GGML_PREC_F32
* Add __hgt2_mask implementation for CUDA 11
* fix KQ FP32 precision fpr parallel_blocks > 1
* llama-bench : add -fa,--flash-attn arg
* metal : add BS=1 kernel for flash attention (#6508)
* metal : add BS=1 kernel for flash attention (wip)
* metal : support more than 1 warps
* metal : opts
* metal : opt
* metal : switch to parallel reduce
* metal : reduce registers
* metal : simplify
* metal : initial FA vec kernel
* metal : use F32 attention accumulators
* batched-bench : add fattn arg
* llama : simplify llama_build_kv_store
ggml-ci
* llama : adapt build_olmo to changes
* ggml : fix arm fp16 store on windows
* metal : clean-up
* metal : clean-up kernel code
* metal : minor
* tests : remove benchmarks
ggml-ci
* ggml : fix avx512 const correctness
ggml-ci
* ggml : fix soft_max with bias on CPU
ggml-ci
* common : print --flash-attn in help
* ggml : fix num dimensions in ggml_flash_attn_ext
* llama : force disable flash attention for incompatible models
* ggml : ggml_soft_max support F16/F32 mask/pos
ggml-ci
* cuda : uint -> uint32_t
* cuda : "constexpr dim3" -> "const dim3"
ggml-ci
* cuda : try to fix __hgt2_mask
ggml-ci
* ggml : add TODO's for F16/F32 mask/pos support in other backends
* llama : replace bool need_kq_pos with use_alibi
* llama : prep ALiBi support for BERT models
ggml-ci
* llama : fix n_batch requirements
ggml-ci
* cont
* server : add help for --flash-attn arg
* llama : disable FA for AMD
* tests : remove TMP_ATTN_BENCH
ggml-ci
* llama : support save/load state with FA enabled
ggml-ci
* ci : add CUDA save-load-state tests
ggml-ci
* llama : llama_kv_cache_clear zeroes data + fix save-load seq
ggml-ci
* llama : fix copy-paste errors, add TODO
* llama : disallow incompatible states
* llama : update llama_state_get_size after v_trans field
* metal : remove tmp log
* llama : add static reminder for llama_state_get_size
* metal : fix max nsg
ggml-ci
* ci : fix arg order
ggml-ci
---------
Co-authored-by: Johannes Gäßler <johannesg@5d6.de>
Co-authored-by: Pierrick HYMBERT <pierrick.hymbert@gmail.com>
2024-04-30 11:16:08 +02:00
bool flash_attn = false ; // flash attention
2024-09-13 08:53:38 +02:00
bool no_perf = false ; // disable performance metrics
2024-09-16 08:20:01 +02:00
bool ctx_shift = true ; // context shift on inifinite text generation
2023-03-24 16:05:13 +01:00
2023-07-25 14:19:11 +02:00
bool input_prefix_bos = false ; // prefix BOS to user inputs, preceding input_prefix
2023-09-28 18:04:36 +02:00
bool logits_all = false ; // return logits for all tokens in the batch
Rewrite loading code to try to satisfy everyone:
- Support all three formats (ggml, ggmf, ggjt). (However, I didn't
include the hack needed to support GPT4All files without conversion.
Those can still be used after converting them with convert.py from my
other PR.)
- Support both mmap and read (mmap is used by default, but can be
disabled with `--no-mmap`, and is automatically disabled for pre-ggjt
files or on platforms where mmap is not supported).
- Support multi-file models like before, but automatically determine the
number of parts rather than requiring `--n_parts`.
- Improve validation and error checking.
- Stop using the per-file type field (f16) entirely in favor of just
relying on the per-tensor type/size fields. This has no immediate
benefit, but makes it easier to experiment with different formats, and
should make it easier to support the new GPTQ-for-LLaMa models in the
future (I have some work in progress on that front).
- Support VirtualLock on Windows (using the same `--mlock` option as on
Unix).
- Indicate loading progress when using mmap + mlock. (Which led me
to the interesting observation that on my Linux machine, with a
warm file cache, mlock actually takes some time, whereas mmap
without mlock starts almost instantly...)
- To help implement this, move mlock support from ggml to the
loading code.
- madvise/PrefetchVirtualMemory support (based on #740)
- Switch from ifstream to the `fopen` family of functions to avoid
unnecessary copying and, when mmap is enabled, allow reusing the same
file descriptor for both metadata reads and mmap (whereas the existing
implementation opens the file a second time to mmap).
- Quantization now produces a single-file output even with multi-file
inputs (not really a feature as much as 'it was easier this way').
Implementation notes:
I tried to factor the code into more discrete pieces than before.
Regarding code style: I tried to follow the code style, but I'm naughty
and used a few advanced C++ features repeatedly:
- Destructors to make it easier to ensure everything gets cleaned up.
- Exceptions. I don't even usually use exceptions when writing C++, and
I can remove them if desired... but here they make the loading code
much more succinct while still properly handling a variety of errors,
ranging from API calls failing to integer overflow and allocation
failure. The exceptions are converted to error codes at the
API boundary.)
Co-authored-by: Pavol Rusnak <pavol@rusnak.io> (for the bit I copied from #740)
2023-04-08 21:24:37 +02:00
bool use_mmap = true ; // use mmap for faster loads
2023-03-24 16:19:05 +01:00
bool use_mlock = false ; // use mlock to keep model in memory
2023-03-25 16:16:50 +01:00
bool verbose_prompt = false ; // print prompt tokens before generation
2024-01-13 17:09:08 +01:00
bool display_prompt = true ; // print prompt before generation
2023-11-23 18:07:56 +01:00
bool dump_kv_cache = false ; // dump the KV cache contents for debugging purposes
2023-12-07 12:03:17 +01:00
bool no_kv_offload = false ; // disable KV offloading
2024-04-11 14:51:07 +02:00
bool warmup = true ; // warmup run
2024-04-26 18:39:58 +02:00
bool check_tensors = false ; // validate tensor data
2023-12-07 12:03:17 +01:00
2024-12-12 22:53:05 +01:00
ggml_type cache_type_k = GGML_TYPE_F16 ; // KV cache data type for the K
ggml_type cache_type_v = GGML_TYPE_F16 ; // KV cache data type for the V
2023-10-12 17:23:18 +02:00
// multimodal models (see examples/llava)
2024-09-09 23:36:09 +02:00
std : : string mmproj = " " ; // path to multimodal projector // NOLINT
2024-04-29 16:34:24 +02:00
std : : vector < std : : string > image ; // path to image file(s)
2024-06-04 20:23:39 +02:00
2024-06-24 07:30:24 +02:00
// embedding
bool embedding = false ; // get only sentence embedding
2024-10-22 09:40:02 +02:00
int32_t embd_normalize = 2 ; // normalisation for embeddings (-1=none, 0=max absolute int16, 1=taxicab, 2=euclidean, >2=p-norm)
2024-06-24 07:30:24 +02:00
std : : string embd_out = " " ; // empty = default, "array" = [[],[]...], "json" = openai style, "json+" = same "json" + cosine similarity matrix
2024-10-22 09:40:02 +02:00
std : : string embd_sep = " \n " ; // separator of embeddings
2024-09-28 16:42:03 +02:00
bool reranking = false ; // enable reranking support on server
2024-06-24 07:30:24 +02:00
2024-06-04 20:23:39 +02:00
// server params
2024-06-06 15:30:58 +02:00
int32_t port = 8080 ; // server listens on this network port
int32_t timeout_read = 600 ; // http read timeout in seconds
int32_t timeout_write = timeout_read ; // http write timeout in seconds
2024-10-13 17:52:48 +02:00
int32_t n_threads_http = - 1 ; // number of threads to process HTTP requests (TODO: support threadpool)
int32_t n_cache_reuse = 0 ; // min chunk size to reuse from the cache via KV shifting
2024-06-04 20:23:39 +02:00
std : : string hostname = " 127.0.0.1 " ;
2024-09-09 23:36:09 +02:00
std : : string public_path = " " ; // NOLINT
std : : string chat_template = " " ; // NOLINT
2024-06-30 20:27:13 +02:00
bool enable_chat_template = true ;
2024-06-04 20:23:39 +02:00
std : : vector < std : : string > api_keys ;
2024-09-09 23:36:09 +02:00
std : : string ssl_file_key = " " ; // NOLINT
std : : string ssl_file_cert = " " ; // NOLINT
2024-06-04 20:23:39 +02:00
2024-10-08 13:27:04 +02:00
// "advanced" endpoints are disabled by default for better security
bool webui = true ;
bool endpoint_slots = false ;
bool endpoint_props = false ; // only control POST requests, not GET
2024-06-04 20:23:39 +02:00
bool endpoint_metrics = false ;
bool log_json = false ;
std : : string slot_save_path ;
2024-06-08 09:50:31 +02:00
float slot_prompt_similarity = 0.5f ;
2024-06-04 20:23:39 +02:00
// batched-bench params
bool is_pp_shared = false ;
std : : vector < int32_t > n_pp ;
std : : vector < int32_t > n_tg ;
std : : vector < int32_t > n_pl ;
// retrieval params
std : : vector < std : : string > context_files ; // context files to embed
int32_t chunk_size = 64 ; // chunk size for context embedding
std : : string chunk_separator = " \n " ; // chunk separator for context embedding
// passkey params
int32_t n_junk = 250 ; // number of times to repeat the junk text
int32_t i_pos = - 1 ; // position of the passkey in the junk text
2024-06-06 15:30:58 +02:00
// imatrix params
std : : string out_file = " imatrix.dat " ; // save the resulting imatrix to this file
int32_t n_out_freq = 10 ; // output the imatrix every n_out_freq iterations
int32_t n_save_freq = 0 ; // save the imatrix every n_save_freq iterations
int32_t i_chunk = 0 ; // start processing from this chunk
bool process_output = false ; // collect data for the output tensor
bool compute_ppl = true ; // whether to compute perplexity
2024-06-15 18:53:40 +02:00
// cvector-generator params
2024-06-25 13:59:54 +02:00
int n_pca_batch = 100 ;
2024-06-15 18:53:40 +02:00
int n_pca_iterations = 1000 ;
2024-06-25 13:59:54 +02:00
dimre_method cvector_dimre_method = DIMRE_METHOD_PCA ;
std : : string cvector_outfile = " control_vector.gguf " ;
std : : string cvector_positive_file = " examples/cvector-generator/positive.txt " ;
std : : string cvector_negative_file = " examples/cvector-generator/negative.txt " ;
2024-06-28 12:53:43 +02:00
bool spm_infill = false ; // suffix/prefix/middle pattern for infill
2024-07-23 23:48:37 +02:00
std : : string lora_outfile = " ggml-lora-merged-f16.gguf " ;
2024-09-06 17:59:58 +02:00
// batched-bench params
bool batched_bench_output_jsonl = false ;
2023-03-10 19:40:58 +01:00
} ;
2024-09-15 19:46:12 +02:00
// call once at the start of a program if it uses libcommon
// initializes the logging system and prints info about the build
2024-10-10 22:57:42 +02:00
void common_init ( ) ;
2024-09-15 19:46:12 +02:00
2024-10-10 22:57:42 +02:00
std : : string common_params_get_system_info ( const common_params & params ) ;
2023-03-10 19:40:58 +01:00
2024-10-12 07:21:51 +02:00
bool parse_cpu_range ( const std : : string & range , bool ( & boolmask ) [ GGML_MAX_N_THREADS ] ) ;
bool parse_cpu_mask ( const std : : string & mask , bool ( & boolmask ) [ GGML_MAX_N_THREADS ] ) ;
void postprocess_cpu_params ( cpu_params & cpuparams , const cpu_params * role_model = nullptr ) ;
Threadpool: take 2 (#8672)
* Introduce ggml_compute_threadpool
- OpenMP functional: check
- Vanilla ggml functional: Check
- ggml w/threadpool functional: Check
- OpenMP no regression: No glaring problems
- Vanilla ggml no regression: No glaring problems
- ggml w/threadpool no regression: No glaring problems
* Minor fixes
* fixed use after release bug
* fixed a harmless race condition
* Fix Android bulid issue
* fix more race conditions
* fix deadlock for cases where cgraph.n_nodes == 1
and fix --poll case
* threadpool: use cpu_get_num_math to set the default number of threadpool threads
This way we avoid using E-Cores and Hyperthreaded siblings.
* bench: create fresh threadpool for each test
For benchmarking it's better to start a fresh pool for each test with the exact number of threads
needed for that test. Having larger pools is suboptimal (causes more load, etc).
* atomics: always use stdatomics with clang and use relaxed memory order when polling in ggml_barrier
This also removes sched_yield() calls from ggml_barrier() to match OpenMP behavior.
* threadpool: make polling the default to match openmp behavior
All command line args now allow for setting poll to 0 (false).
* threadpool: do not wakeup threads in already paused threadpool
* fix potential race condition in check_for_work
* threadpool: do not create two threadpools if their params are identical
* threadpool: reduce pause/resume/wakeup overhead in common cases
We now start threadpool in paused state only if we have two.
The resume is now implicit (ie new work) which allows for reduced locking and context-switch overhead.
* threadpool: add support for hybrid polling
poll params (--poll, ...) now specify "polling level", i.e. how aggresively we poll before waiting on cond.var.
poll=0 means no polling, 1 means poll for 128K rounds then wait, 2 for 256K rounds, ...
The default value of 50 (ie 50x128K rounds) seems like a decent default across modern platforms.
We can tune this further as things evolve.
* threadpool: reduce the number of barrier required
New work is now indicated with an atomic counter that is incremented for
each new graph that needs to be computed.
This removes the need for extra barrier for clearing the "new_work" and
removes the special case for trivial graphs.
* threadpool: remove special-casing for disposable threadpools
With the efficient hybrid polling there is no need to make disposable pools any different.
This simplifies the overall logic and reduces branching.
Include n_threads in debug print for disposable threadpool.
Declare pause and stop flags as atomic_bool
This doesn't actually generate any memory barriers and simply informs
the thread sanitizer that these flags can be written & read by different
threads without locking.
* threadpool: do not clear barrier counters between graphs computes (fixes race with small graphs)
This fixes the race condition with very small graphs where the main thread happens to
start a new graph while the workers are just about to exit from barriers.
* threadpool: use relaxed order for chunk sync
Full memory barrier is an overkill for this since each thread works on different chunk
* threadpool: remove abort_callback from threadpool state
* threadpool: better naming for thread/cpumask releated functions
* threadpool: consistent use of int type for n_threads params
* threadpool: add support for ggml_threadpool_params_default/init
Also removes the need for explicit mask_specified param.
all-zero cpumask means use default (usually inherited) cpu affinity mask.
* threadpool: move typedef into ggml.h
* threadpool: fix apply_priority() function name
* threadpool: fix swift wrapper errors due to n_threads int type cleanup
* threadpool: enable --cpu-mask and other threadpool related options only if threadpool is enabled
* threadpool: replace checks for compute_thread ret code with proper status check
* threadpool: simplify threadpool init logic and fix main thread affinity application
Most of the init code is now exactly the same between threadpool and openmp.
* threadpool: update threadpool resume/pause function names
* threadpool: enable openmp by default for now
* threadpool: don't forget to free workers state when omp is enabled
* threadpool: avoid updating process priority on the platforms that do not require it
On Windows we need to change overall process priority class in order to set thread priorities,
but on Linux, Mac, etc we do not need to touch the overall process settings.
* threadpool: update calling thread prio and affinity only at start/resume
This avoids extra syscalls for each graph_compute()
* llama-bench: turn threadpool params into vectors, add output headers, etc
* llama-bench: add support for cool off between tests --delay
This helps for long running tests on platforms that are thermally limited (phones, laptops, etc).
--delay (disabled by default) introduces the sleep for N seconds before starting each test.
* threadpool: move process priority setting into the apps (bench and cli)
This avoids changing the overall process priority on Windows for the apps
that use ggml/llama.cpp directy.
* threadpool: move all pause/resume logic into ggml
* threadpool: futher api cleanup and prep for future refactoring
All threadpool related functions and structs use ggml_threadpool prefix.
* threadpool: minor indent fixes
* threadpool: improve setprioty error message
* Update examples/llama-bench/llama-bench.cpp
Co-authored-by: slaren <slarengh@gmail.com>
* threadpool: fix indent in set_threadpool call
* use int32_t for n_thread type in public llama.cpp API
* threadpool: use _new and _free instead of _create and _release
* fix two more public APIs to use int32_t for n_threads
* build: set _GNU_SOURCE for Adroid
---------
Co-authored-by: Max Krasnyansky <quic_maxk@quicinc.com>
Co-authored-by: fmz <quic_fzaghlou@quic.com>
Co-authored-by: Max Krasnyansky <max.krasnyansky@gmail.com>
Co-authored-by: slaren <slarengh@gmail.com>
2024-08-30 01:20:53 +02:00
bool set_process_priority ( enum ggml_sched_priority prio ) ;
2024-05-22 19:04:20 +02:00
//
// String utils
//
2023-09-28 21:42:38 +02:00
2024-10-12 07:21:51 +02:00
# ifdef __GNUC__
# ifdef __MINGW32__
# define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(gnu_printf, __VA_ARGS__)))
# else
# define LLAMA_COMMON_ATTRIBUTE_FORMAT(...) __attribute__((format(printf, __VA_ARGS__)))
# endif
# else
# define LLAMA_COMMON_ATTRIBUTE_FORMAT(...)
# endif
LLAMA_COMMON_ATTRIBUTE_FORMAT ( 1 , 2 )
std : : string string_format ( const char * fmt , . . . ) ;
2024-05-22 19:04:20 +02:00
std : : string string_strip ( const std : : string & str ) ;
std : : string string_get_sortable_timestamp ( ) ;
2024-06-04 20:23:39 +02:00
2024-08-09 17:23:52 +02:00
void string_replace_all ( std : : string & s , const std : : string & search , const std : : string & replace ) ;
2024-06-04 20:23:39 +02:00
template < class T >
static std : : vector < T > string_split ( const std : : string & str , char delim ) {
2024-10-25 17:57:54 +02:00
static_assert ( ! std : : is_same < T , std : : string > : : value , " Please use the specialized version for std::string " ) ;
2024-06-04 20:23:39 +02:00
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 ;
}
train : finetune LORA (#2632)
* fix track_max_mem in forward_batch_wo_cache_flash_attn_train
* remove unnecessary Adam(W) optimizer tensors.
reduces optimizer memory overhead from 7*modelsize to 2*modelsize.
additionally allows to optimize models with more than 2^31 parameters by replacing int with int64_t.
bumps training checkpoint file version, but old checkpoints can still be read.
new version with less tensors is saved.
* add gradient clipping to AdamW
* Fix reset of unused g->nodes and g->grads to NULL
* implement gradient checkpointing for training
reduces memory overhead from O(n_layer) to O(sqrt(n_layer))
as explained in readme of https://github.com/cybertronai/gradient-checkpointing
* remove unused compute buffer 3
* add and use function ggml_build_backward_expand to avoid stack overflows with large maximum number of nodes
GGML_API void ggml_build_backward_expand(struct ggml_context * ctx, struct ggml_cgraph * gf, struct ggml_cgraph * gb, bool keep);
* change AdamW decay parameter to work like the torch AdamW decay parameter
It is now relative to Adam learning rate `alpha*sched`.
Before that it was relative to `sched` only.
`alpha` being the maximum learning rate and `sched` being a scaling parameter in [0..1]
* change default AdamW weight decay parameter used in training to 0.1 as used in nanoGPT
* change default AdamW weight decay parameter defined in ggml to 0.0, making Adam default instead of AdamW
btw: the default weight decay parameter for torch.optim.AdamW is 0.01
* bug fixes for cross entropy loss
ggml_cross_entropy_loss: sums where not correctly added in workload of each thread
ggml_cross_entropy_loss_back: simplify backward process, reducing numerical issues
guard usage of exp f16 lookup in cross entropy by #define GGML_CROSS_ENTROPY_EXP_FP16
cross entropy loss is only used once during training, but it is quite sensitive to numerical errors introduced by exp-f16-lookup.
so exp-f16-lookup for cross entropy loss is disabled by default, trading better gradients for very slightly worse runtime performance.
* fix test-grad0 for cross_entropy_loss
the second argument to cross_entropy_loss must sum up to 1 for each row
* fix test-grad0 for soft_max
dont use only sum as aggregation, because sum of softmax is always 1 -> finite differences should not work
instead use sum(log(soft_max()*(1-eps)+eps)); use eps to avoid log(0)
* improve finite differences of test-grad0 by using double instead of float
* change cross_entropy_loss to output average over all rows
this helps keeping the loss and gradients in a sane range
* improve gradient checkpointing
sqrt(n_layers) is only the best checkpoint step when mem size of checkpoints and mem size of layers are equal.
since layers require more memory than the single-tensor-checkpoint we use, the optimal values are compute different:
```
given: n, u, v
objective: minimize(a*u+b*v) where a*b=n, a>0, b>0
b=n/a
minimize(a*u+v*n/a)
diff(a*u+v*n/a, a) = u - (v*n/a)/a
diff(a*u+v*n/a, a) == 0
u - (v*n/a)/a == 0
u == v*n/(a*a)
u*a*a = v*n
a*a = v*n/u
a = sqrt(n*v/u)
```
this change results in more checkpoints, requiring less layers to store between checkpoints, overall improving memory usage.
* disable gradient checkpointing debug output
* llama : fix rope usage in train-text-from-scratch after ChatGLM change
* add more training parameters:
--enable-restart N Only for Adam optimizer. Enable restarts of cos-decay
--disable-restart N Only for Adam optimizer. Disable restarts of cos-decay
--opt-past N Number of optimization iterations to track for delta convergence test. Disabled when zero.
--opt-delta N Maximum delta for delta convergence test. Disabled when <= zero.
--opt-max-no-improvement N Maximum number of optimization iterations with no improvement. Disabled when <= zero.
--adam-epsf N AdamW epsilon for convergence test. Disabled when <= zero.
--adam-min-alpha N Adam minimum learning rate alpha, usually 0.1 * alpha
* replace memcpy with reshape operation so that the graph is not cut at the input
this makes it possible to store other values into the input tensor and then simply recompute the graph without rebuilding it
* remove unused function argument from get_example_targets_batch
* measure and print total training time
* add optimization callback to ggml_opt_resume_g
this callback is called before each iteration with custom data and pointer to learning schedule parameter (only used in Adam(W)).
can be used for dynamic learning schedule and setting input data for batches before each iteration
* use optimization callback in training
allows dynamic learning schedule and different batch data for each iteration without relying on low n_iter and high n_examples parameters
reduces runtime by avoiding restart of optimization function and improves training convergence by providing a different batch for each iteration
* add minimum number of tensor dimensions to apply weight decay (default 2)
this allows to not apply weight decay to bias parameters
* rename training parameter cos-decay-alpha to cos-decay-min and clarify that adam-min-alpha also applies to warmup
* fix increase of model.train_samples and model.train_tokens
now that each optimizer iteration gets its own batch we need to multiply by number of opt iterations
* change sampling parameters for prediction after training to defaults of common.h
and clarify what is context for prediction and what are generated tokens
* tighten abs error bounds for cross_entropy_loss in test-grad0
* add conditional compilation of using F16 exp in flash attention
uncomment `// #define GGML_FLASH_ATTN_EXP_FP16` to enable usage of f16 exp in flash attention
* tighten abs error bounds for flash_attn in test-grad0
* tighten abs error bounds for sqrt in test-grad0
* remove out-commented vectorized code of opt_adam
the vectorized code might be bit faster for low number of parameters, but it had a big memory usage overhead
* ggml : update ggml_rms_norm_back with configurable eps
* llama training : fix ggml_rms_norm_back calls to pass configurable eps
* remove trailing whitespace
* add train function using automatic gradient checkpointing backward pass and allocator
* in train function replace add_inplace by regular add
because using add_inplace seems to result in different gradients
* don't use allocate hash_map on context
because the context has no_alloc=True when using memory allocator resulting in NULL data pointers
* correctly clone reshape and permute operations by also cloning tensor->nb values
* fix variable name and add missing type cast
* terminate recursive tensor cloning when reaching tensor without src tensors
* correctly clone view tensors by setting data pointers
without this the checkpointing would only work when being used together with memory allocator
* fix variable names
* swap arguments to commutative ops to be the same as in `forward_batch_wo_cache_flash_attn`
* add input tensors as checkpoints
so that recursive tensor cloning of gradient checkpointing terminates on input tensors
* fix variable name and add missing boolean negation
* make sure some tensors are not reallocated by inserting new temporary nodes depending on them:
output and parameter gradient tensors need to be available at the end of the graph execution
parameter gradient tensors also need to be available before the graph execution because they are set to zero before each optimizer iteration
checkpoint tensors are allocated all together to reduce memory allocator fragmentation
afterwards, in addition to the temporary nodes, we also need to reset the temporary leafs
* fix ASSERT to work with zero layers
* add training options whether to use allocator and/or unified training function
* integrate unified training function which may use memory allocator
the unified training function also supports arguments whether to use flash attention and/or gradient checkpointing
* format name of cloned tensors with " (clone)" suffix
* set names for tensors in unified train function for easier debugging
* allocate graph on context using ggml_new_graph
* remove handwritten training functions
* remove unused training parameters "use_scratch" and "use_unified"
* remove trailing whitespace
* remove unused train params: mem_compute1_gb & mem_compute2_gb
mem_compute_gb is used for compute when automatic memory allocator is not enabled, otherwise it can be very small to only hold the tensor definitions
mem_compute0_gb is used for automatic memory allocator (as long as measurement of max required size is not implemented)
* remove unused forward_batch function
* add debug asserts in ggml_allocr_alloc to some common pitfalls when using this function directly
* only use ggml_allocr_alloc when tensor has NULL data and is no view
* fix test when to create temporary backward graph
temporary backward graph is only necessary when using checkpointing
* fix memory "leak" in optimizers
each iteration a new cplan with new memory for work data was allocated.
now cplan creation only happens at the start of optimization, with each iteration reusing the cplan and its work data.
* reverse order of for loop in ggml_build_backward_expand to save memory when using gradient checkpointing and allocator
with this loop order gradient checkpointing with allocator on 16 layer model saves 13% memory; 2 layer memory it saves 2% memory.
the computation results are the same
* add API functions to access llama model tensors
* add stub example for finetuning, based on train-text-from-scratch
* move and remove code
* add API functions to access remaining model parameters:
mult, head and rot
* first draft for LORA finetune training
* remove const model and layer arguments in API functions for accessing model tensors
* bug fixes to make finetune compile
automatic allocator does not work yet
* add debug prints for training memory improvements
* fix names of lora tensors
* avoid stack overflow resulting from big ggml_cgraph
replace stack allocation and ggml_build_forward by ggml_new_graph in combination with ggml_build_forward_expand
* replace llama API functions to get model tensors by one function to get model tensor by name
LLAMA_API struct ggml_tensor * llama_get_model_tensor(struct llama_model * model, const char * name);
* remove unused call to not existing llama_get_layer_from_model
* implement ggml_compute_forward_out_prod_q_f32
* remove trailing whitespace
* add lora finetune support on quantized base model tensors
* add ggml_add_cast API function
this function works like ggml_add, but accepts a data type for the resulting tensor.
only supported for quantized src0 input.
* use ggml_add_cast in finetuning
lora-applied weights will now have data type F32, which improves gradients when finetuning quantized base models
* bug fix: actually use result type passed to ggml_add_cast
* make sure base model tensors data cannot be used in viewable operations
memory allocator would try to make lora application inplace on base model tensors.
since those are memory mapped this will result in memory access violations
* fix bug in ggml_out_prod which resulted in wrong n_dims of result tensors
* avoid keeping in memory ALL of the gradients
The problem here stems from ggml_graph_reset. This function is called in the optimization function, before each graph computation, to reset the gradients to zero. This required a unique memory slot for each gradient: allocating memory from a previosly freed memory location might lead to non-zero input gradients.
During ggml_compute_backward the gradients are build stepwise by adding or substracting new values, starting from a OP_NONE tensor which needs to contain zero-values. This requires the graph reset.
To avoid this I now remember in ggml_build_backward_expand the original OP_NONE gradient tensors in a hash table, which is passed to ggml_compute_backward. There instead of using add (or sub or similar) I test whether the existing gradient to be changed is a zero-valued-tensor by looking up its existence in the hash table. When it is such a zero-tensor it will not be modified, but replaced by the value to be added, otherwise the regular add (not inplace, allocator will take care of this) will be used. This way none of those zero-tensor values will be necessary in the final backward graph and more importantly they won't need a unique memory slot, just to make them zero.
* remove trailing whitespace
* remove debug prints and function to compute tensor data hash
* improve optimization iteration prints
* adjust maximal values to support finetuning 3B models
* change default finetune params lora_r and lora_alpha to match the n_rank parameters of 4
* bug fix: make sure finetune input gradient is allocated at begin and kept until end
* remove unnecessary src tensor from ggml_get_rows_back
we don't need data of src[2] for computation, only to setup the correct output shape.
remove dependency on src[2], so that allocator can work more freely.
the computational graph is still completely determined, because the output shape is naturally included.
this is similar to how ggml_reshape does it.
* remove unnecessary src tensor from ggml_repeat & ggml_repeat_back
we don't need data of src[1] for computation, only to setup the correct output shape.
remove dependency on src[1], so that allocator can work more freely.
the computational graph is still completely determined, because the output shape is naturally included
* resolve todo
allocator will only make it inplace when they are of the same type
* mixing multiple LORA adapters is now possible
pass more than one '--lora FNAME' argument to apply more than one LORA.
use '--lora-scaled FNAME S' when you want to specify a user-defined scale for an adapter.
* add option to save finetune output every N iterations
* also save latest finetune output with ITERATION="LATEST" and print where files are saved
saving with LATEST makes it easier to resume training from the latest checkpoint
the string "LATEST" can be configured with command line option "--fn-latest STR"
* update checkpoint train stats before saving via "--save-every"
* add command line option `--rank-wo N` for rank of wo tensor
* update finetune README
* fix dump_non_result_info_yaml to output multiple lora adapters
* bug fix: replace GGML_TYPE_SIZE[t] by ggml_type_size(t)
* replace llama_n_mult by llama_n_ff
* finetune bug fixes to compile with merged in code from master
* remove prediction related code to reduce duplicated code with main
use main instead
* reduce large memory overhead in train-text-from-scratch
all gradients had to be pinned so that graph_reset works correctly.
this is no longer necessary with the changes to ggml_compute_backward introduced in this PR.
* add comment explaining why finetune checkpoints are allocated in one block
* make default value of float member a float literal
* handle rms_norm and rope parameters the same as in train-text-from-scratch
* remove unused code
* remove vocab related code as it is unnecessary
* add LLM_KV_TRAINING_TYPE to train-text-from-scratch checkpoints
so that they can be differentiated from lora finetune checkpoints
* add gguf constants and load/save functions from train-text-from-scratch
* add load & save lora finetune checkpoints via gguf
* add python script to convert old finetune checkpoint files to gguf
* remove old checkpoint save & load code
* remove code to print data checksums which was used to verify correctness of new gguf code
* omit tokenization when training is disabled, only save llama lora adapter
training can be disabled by passing '-n 0' to finetune
* remove trailing whitespace
* update README.md
* implement ggml_compute_forward_repeat_f16
* avoid stack overflow of large cgraphs in test-grad0
* add ggml API functions ggml_unravel_index, ggml_get_i32_nd and its analogs for set and for f32
ggml_get_i32_1d, ggml_set_i32_1d, ggml_get_f32_1d, ggml_set_f32_1d now support non-contiguous tensors.
in case of non-contiguous tensor, the 1d index is unraveled into a multi index using ggml_unravel_index to be passed to '_nd' function equivalent.
this fixes a bug in test-grad0 which happens due to ggml_build_backward not building purely contiguous tensors anymore
* increase test-grad0 context mem size to accommodate for bigger cgraph
* add sanity check to ggml_compute_backward, asserting the correct shape of gradients
* fix ggml_acc_or_set to return tensor of correct shape
* remove unused 'inplace' argument from ggml_compute_backward function
inplace operations to add gradients are no longer created by ggml_compute_backward
use allocator to automatically make inplace operations
* add missing argument 'int i0' to ggml_get_i32_nd & ggml_set_i32_nd header declarations
* fix error message in ggml_allocr_alloc to display actual max_avail
* fix check_gradient
ggml_build_backward_expand was previously replaced by ggml_build_backward, but the assignment of forward graph to backward graph missing
* use tensor->view_src instead of ggml_is_view and get_view_source
* move gradient checkpointing code into ggml, new API function:
// build gradient checkpointing backward graph gb for gf using provided checkpoints
// gb_tmp will contain original backward graph with rewritten backward process nodes,
// but without the second forward pass nodes.
GGML_API void ggml_build_backward_gradient_checkpointing(
struct ggml_context * ctx,
struct ggml_cgraph * gf,
struct ggml_cgraph * gb,
struct ggml_cgraph * gb_tmp,
struct ggml_tensor * * checkpoints,
int n_checkpoints);
* replace custom data getters and setters by ggml functions
* train-text-from-scratch can train (full finetune) gguf models
just pass the gguf model via `--checkpoint-in FN`.
after this, to continue training, pass the generated checkpoint instead of the original gguf model.
tested with smaller models, bigger models may exceed available memory.
use (LORA) finetune for those.
* remove trailing whitespace
* add option to save train-text-from-scratch output every N iterations
* update README.md
* fix warnings
* fix warnings
* remove finetune option to disable allocator
the allocator should always be used.
by making sure that it is always used it gets easier to implement automatic memory requirements computation
* add tensor checkpoints only when gradient checkpointing is enabled
* initialize opt ggml context if none was provided
* add ggml-alloc API function 'ggml_allocr_max_size' to get max size of alloc
GGML_API size_t ggml_allocr_max_size(struct ggml_allocr * alloc);
* finetune: automatically allocate all memory and changes to command line options
remove '--n_examples N' parameter, as it no longer makes sense to call optimization process multiple times in a loop.
add '--only_write_lora' command line option: will skip tokenization and training, to only write a llama.cpp comptabile LORA adapter.
remove memory buffer related command line options.
improve iteration console output.
* add finetune to Makefile
* update README.md
* print time per iteration and estimate remaining time
* increase measured alloc size by tensor_alignment
ggml_allocr_reset will reduce the given size by up to tensor_alignment-1
* fix README.md
* add some more allocator debug prints
* bug fix, probably solves the 'ggml_allocr_alloc: not enough space in the buffer' issue
* revert last commit
"bug fix, probably solves the 'ggml_allocr_alloc: not enough space in the buffer' issue"
"alloc was freeing an externally allocated tensor, because it calculated the end of allocator memory as alloc->data + alloc->max_size instead of alloc->data + alloc->size."
This is intentional to reduce the risk of freeing external tensors when measuring. Unless max_size is not properly calculated, I don't see why this is an issue.
* remove unnecessary "0x" before "%p" output
* move measurement memory segment to upper region of the address space
* update README.md
* fix printf format warnings
* add missing gguf_free in load_checkpoint_lora_file
* load default rms_norm and rope parameters from base model
* add gradient accumulation
specify number accumulation steps with '--grad-acc N'.
this will simulate a bigger batch size of grad_acc*batch.
* fix tracking of train_samples and train_tokens
* build : fix compile warnings
* ggml : fix L-BFGS linesearch loop
* improve finetune time measurement
fix printf warnings on system where int64_t is (long int).
change time datatypes to double because values get big with long training times.
exclude file saving from time measurement.
converge faster to actual time per iteration by removing very small first duration before first iteration was performed.
fix bug in output of total training time, the reported value was 1000 times to small.
* specify default lora rank with '--lora-r N'
'--lora-r N' will specify default rank for all tensors
'--rank-wq N', etc. will override this default rank for specific tensor types.
* fix gradient accumulation bug where the same batch was used for each microstep
* fix gradient accumulation bug where the same batch was used for each microstep
* support grouped-query-attention in ggml_flash_attn and ggml_flash_attn_back
k and v can now be repeated in q along ne[2]
in forward pass just use modulo to compute k and v indices, like ik2 = iq2 % nek2.
in backard pass this won't work as easy, because multiple threads will compete to accumulate to the same k->grad[:,ik1,ik2,ik3] and v->grad[:,iv1,iv2,iv3].
so we change the parallelization over q rows to be over k rows. this ensures non-overlapping (ik2,ik3) across threads.
in each thread we then iterate over the number of repetitions of k/v in q to compute iq2 as iq2 = ik2 + irep*nek2.
since ne2 is not the same for q,k and v we also change how the gradients are concatenated into the result tensor.
additionally the offsets of gradq, gradk and gradv in the result tensor are now memory aligned.
we also simplify the compute_backward part of flash_attn to use ggml_reshape instead of switching over the number of dimensions.
this needs a small change to ggml_reshape, removing the assertion of second argument to be contiguous.
since only the shape (ne) of the second reshape argument is of relevance, its memory layout (nb) is irrelevant -> it can very well be non-contiguous.
change test-grad0 to also test for repeated k/v in q.
this changes the rng and now results in small gradient differences in softmax. these solely come from using f16 exp table lookup in forward softmax: when temporarily changing softmax to use actual exp function, the reported gradient differences go away. gradient differences coming solely from f16 table lookup are acceptable.
added a note to explain this.
* add llama API functions to get grouped-query-attention n_head parameter 'n_head_kv'.
* fix finetune to support grouped-query-attention (using flash-attention)
note: ggml changes to ggml_out_prod are necessary to support grouped-query-attention without flash-attention.
* support broadcastable a in out_prod(a, b) and backward pass of broadcasting mul_mat(a, b)
* test broadcasting mul_mat backward pass
* decouple random number generator of each operation test
when changing one test the rng of others tests is not influenced anymore
* add comment briefly describing what ggml_repeat_back does
* simplify broadcasting mul_mat backward using ggml_repeat_back
* add cgraph evaluation order member and corresponding enum type
this controls in which order ggml_build_forward visits source nodes.
by default the nodes are visited left to right, i.e. src[0] first.
in some cases it is beneficial for ggml-alloc to visit in a different order.
two possible orders are supported: left-to-right (src[0] first) and right-to-left (src[0] last).
* measure max compute size for each cgraph eval order and use best order
this can bring huge memory savings:
e.g. codellama-34b with n_ctx=64, n_batch=1 goes from 92927.8mb down to 4627.6 MB
* remove unused command line options
* add sample start patterns and options to force new or by default resume last shuffling
* update shuffle rng state on reshuffle
* exclude known zero values from computations in flash_attn_f32 & flash_attn_back_f32
* remove probably unnecessary exception type flags from stringstream
* pass correct max number of tokens to llama_tokenize
* account for possible leading whitespace that will be added by tokenizer
e.g. '\t' will be tokenized by llama spm tokenizer to [29871, 12]
* use unrolled vec_mad in out_prod
y is vec_mad result vec.
x is vec_mad input vec.
v is vec_mad input scalar.
ggml_vec_mad_f32_unroll will internally loop over x and v with same y.
GGML_VEC_MAD_UNROLL is by default defined to 32.
This value is empirical optimized using performance test runs of out-prod in openllama-3b finetune with 256 context length and batch size 1. It gives 23% performance boost for out_prod.
Full measurements of out-prod runtime in ms:
unroll_xv unroll_yv
1 67014.643 87826.469
2 77117.552 89077.656
4 72091.311 109121.657
8 61077.543 88678.334
16 56914.67 79514.947
24 59024.595 84350.254
28 55952.446 83368.73
32 51476.658 85177.745
36 55973.792 84659.92
40 55139.616 93844.738
48 60736.392 93330.267
64 99856.878 116994.99
Second column is when unrollying yv instead of xv
* set lora_alpha to value of lora_r if it is not set via command line
otherwise only changing lora_r will change scaling of lora adapter used in prediction
* reshuffle original sample order instead of the previous shuffled order
otherwise resumed reshuffle will not result in same sample order
* block tiling for out-prod inspired by mul-mat
block sizes are empirically optimized
roughly doubles the flops of out-prod
* exclude some more known zero values from computations in flash_attn_f32 & flash_attn_back_f32
* add static keywords
* remove outcommented old code
* update train-text-from-scratch with tokenization, sample selection and shuffling from finetune
* remove lbfgs related train parameters
* move common train functions into common/train.[h|cpp]
* move train state into struct train_state
* move train data saving code into callback to unify code of opt_callback
train_params are still different in finetune and train-text-from-scratch, so it can't yet be moved to train.h|cpp
* move common train params into common/train
* move common opt_callback into common/train
* fix consume_common_train_arg
* save and load head_count_kv in lora checkpoints
* increase train_samples by used_samples instead of number of batches
on batch can contain more than one sample when option "fill_with_next_samples" is used
* fix usage of llama_tokenize
* remove static from process_escape since we need it exposed in header
* fix code formating of long function declarations
* fix condition in load_train_state_gguf
* use die("msg") instead of replace GGML_ASSERT(!"msg") or throw std::runtime_error("msg")
* fix saving and loading of training type
* remove terminating '\0' from tokenization
(llama_tokenize is now passed the string length instead of relying on terminating '\0')
* fix compile warnings
* fix compile warnings
* use new/delete for train_state instead of malloc/free
using malloc may result in seg faults when trying to assign string fields
* assert that sample_count > 0, avoiding division by zero
* fix frand to return value in interval [0,1)
* add train option "--sample-random-offsets"
Use samples beginning at random offsets.
The offset is only applied to the first sample in each batch context window.
Together with "--fill-with-next-samples" this may help for training endless text generation.
For example given a dataset containing samples "abcd", "ABCD", "0123".
With context size of 8 and options "--fill-with-next-samples", "--no-separate-with-eos", "--no-separate-with-bos",
the context windows of batches could only be filled with "abcdABCD", "ABCDabcd", "0123abcd", etc.
With "--sample-random-offsets" it can also be filled with "23abcdAB", "bcd0123A", etc.
* deduplicate code into function
* remove n_rot hparam, as it must always be hparam.n_embd_head()
* align code
* assert correct base model tensor shapes
* move some params from lora hparams into model hparams and load model params from gguf
this equalizes the model definition in finetune and text-from-scratch and removes the need for additional llama api functions to get model parameters
* remove now unnecessary llama API functions to get model params that where added by this PR
* train-text-from-scratch: automatically allocate model tensors, remove option '--mem-model N'
* train-text-from-scratch: automatically allocate opt context
* train-text-from-scratch: automatically allocate input tensors
* train-text-from-scratch: automatically allocate compute memory
* remove unused options and equalize train-text-from-scratch with finetune
* initialize opt->loss_after with zero
* add export-lora program
* remove trailing whitespace
* add export-lora build in Makefile
* remove unused struct tensor_info from export-lora
* add export-lora build dependency to llama
because it depends on common, which depends on llama
* update finetune README.md
* cancel optimization when specified number of epochs is completed
* improve handling of export-lora arguments
print errors and warnings when files could not be read or created
* Fix export-lora.cpp "not enough space in the context's memory pool" (#1)
* Fix export-lora.cpp "not enough space in the context's memory pool"
Without this patch, export-lora would sometimes error with "not enough space in the context's memory pool (needed 656784, available 656800)".
* increase required context size by 5*GGML_MEM_ALIGN instead of plain 16
---------
Co-authored-by: xaedes <xaedes@gmail.com>
* improve handling of not yet supported tensor types
---------
Co-authored-by: Georgi Gerganov <ggerganov@gmail.com>
Co-authored-by: meatbag-18a <145869052+meatbag-18a@users.noreply.github.com>
2023-09-28 20:40:11 +02:00
2024-10-25 17:57:54 +02:00
template < >
std : : vector < std : : string > string_split < std : : string > ( const std : : string & input , char separator )
{
std : : vector < std : : string > parts ;
size_t begin_pos = 0 ;
size_t separator_pos = input . find ( separator ) ;
while ( separator_pos ! = std : : string : : npos ) {
std : : string part = input . substr ( begin_pos , separator_pos - begin_pos ) ;
parts . emplace_back ( part ) ;
begin_pos = separator_pos + 1 ;
separator_pos = input . find ( separator , begin_pos ) ;
}
parts . emplace_back ( input . substr ( begin_pos , separator_pos - begin_pos ) ) ;
return parts ;
}
2024-12-13 19:34:25 +01:00
static bool string_starts_with ( const std : : string & str ,
const std : : string & prefix ) { // While we wait for C++20's std::string::starts_with...
return str . rfind ( prefix , 0 ) = = 0 ;
}
2024-05-22 19:04:20 +02:00
bool string_parse_kv_override ( const char * data , std : : vector < llama_model_kv_override > & overrides ) ;
void string_process_escapes ( std : : string & input ) ;
2024-04-08 14:43:30 +02:00
2024-09-15 19:46:12 +02:00
std : : string string_from ( bool value ) ;
std : : string string_from ( const std : : vector < int > & values ) ;
std : : string string_from ( const struct llama_context * ctx , const std : : vector < llama_token > & tokens ) ;
std : : string string_from ( const struct llama_context * ctx , const struct llama_batch & batch ) ;
2023-12-05 11:05:51 +01:00
//
2024-05-22 19:04:20 +02:00
// Filesystem utils
2023-12-05 11:05:51 +01:00
//
2024-05-22 19:04:20 +02:00
bool fs_validate_filename ( const std : : string & filename ) ;
bool fs_create_directory_with_parents ( const std : : string & path ) ;
std : : string fs_get_cache_directory ( ) ;
2024-06-08 21:21:08 +02:00
std : : string fs_get_cache_file ( const std : : string & filename ) ;
2023-12-05 11:05:51 +01:00
2023-03-10 19:40:58 +01:00
//
2023-08-21 22:07:43 +02:00
// Model utils
2023-03-10 19:40:58 +01:00
//
2024-10-10 22:57:42 +02:00
struct common_init_result {
2024-08-06 17:33:39 +02:00
struct llama_model * model = nullptr ;
2024-08-05 18:14:10 +02:00
struct llama_context * context = nullptr ;
2024-10-10 22:57:42 +02:00
std : : vector < common_lora_adapter_container > lora_adapters ;
2024-08-05 18:14:10 +02:00
} ;
2024-10-10 22:57:42 +02:00
struct common_init_result common_init_from_params ( common_params & params ) ;
2023-10-18 15:21:57 +02:00
2024-11-25 19:30:06 +01:00
struct llama_model_params common_model_params_to_llama ( common_params & params ) ;
2024-10-10 22:57:42 +02:00
struct llama_context_params common_context_params_to_llama ( const common_params & params ) ;
Threadpool: take 2 (#8672)
* Introduce ggml_compute_threadpool
- OpenMP functional: check
- Vanilla ggml functional: Check
- ggml w/threadpool functional: Check
- OpenMP no regression: No glaring problems
- Vanilla ggml no regression: No glaring problems
- ggml w/threadpool no regression: No glaring problems
* Minor fixes
* fixed use after release bug
* fixed a harmless race condition
* Fix Android bulid issue
* fix more race conditions
* fix deadlock for cases where cgraph.n_nodes == 1
and fix --poll case
* threadpool: use cpu_get_num_math to set the default number of threadpool threads
This way we avoid using E-Cores and Hyperthreaded siblings.
* bench: create fresh threadpool for each test
For benchmarking it's better to start a fresh pool for each test with the exact number of threads
needed for that test. Having larger pools is suboptimal (causes more load, etc).
* atomics: always use stdatomics with clang and use relaxed memory order when polling in ggml_barrier
This also removes sched_yield() calls from ggml_barrier() to match OpenMP behavior.
* threadpool: make polling the default to match openmp behavior
All command line args now allow for setting poll to 0 (false).
* threadpool: do not wakeup threads in already paused threadpool
* fix potential race condition in check_for_work
* threadpool: do not create two threadpools if their params are identical
* threadpool: reduce pause/resume/wakeup overhead in common cases
We now start threadpool in paused state only if we have two.
The resume is now implicit (ie new work) which allows for reduced locking and context-switch overhead.
* threadpool: add support for hybrid polling
poll params (--poll, ...) now specify "polling level", i.e. how aggresively we poll before waiting on cond.var.
poll=0 means no polling, 1 means poll for 128K rounds then wait, 2 for 256K rounds, ...
The default value of 50 (ie 50x128K rounds) seems like a decent default across modern platforms.
We can tune this further as things evolve.
* threadpool: reduce the number of barrier required
New work is now indicated with an atomic counter that is incremented for
each new graph that needs to be computed.
This removes the need for extra barrier for clearing the "new_work" and
removes the special case for trivial graphs.
* threadpool: remove special-casing for disposable threadpools
With the efficient hybrid polling there is no need to make disposable pools any different.
This simplifies the overall logic and reduces branching.
Include n_threads in debug print for disposable threadpool.
Declare pause and stop flags as atomic_bool
This doesn't actually generate any memory barriers and simply informs
the thread sanitizer that these flags can be written & read by different
threads without locking.
* threadpool: do not clear barrier counters between graphs computes (fixes race with small graphs)
This fixes the race condition with very small graphs where the main thread happens to
start a new graph while the workers are just about to exit from barriers.
* threadpool: use relaxed order for chunk sync
Full memory barrier is an overkill for this since each thread works on different chunk
* threadpool: remove abort_callback from threadpool state
* threadpool: better naming for thread/cpumask releated functions
* threadpool: consistent use of int type for n_threads params
* threadpool: add support for ggml_threadpool_params_default/init
Also removes the need for explicit mask_specified param.
all-zero cpumask means use default (usually inherited) cpu affinity mask.
* threadpool: move typedef into ggml.h
* threadpool: fix apply_priority() function name
* threadpool: fix swift wrapper errors due to n_threads int type cleanup
* threadpool: enable --cpu-mask and other threadpool related options only if threadpool is enabled
* threadpool: replace checks for compute_thread ret code with proper status check
* threadpool: simplify threadpool init logic and fix main thread affinity application
Most of the init code is now exactly the same between threadpool and openmp.
* threadpool: update threadpool resume/pause function names
* threadpool: enable openmp by default for now
* threadpool: don't forget to free workers state when omp is enabled
* threadpool: avoid updating process priority on the platforms that do not require it
On Windows we need to change overall process priority class in order to set thread priorities,
but on Linux, Mac, etc we do not need to touch the overall process settings.
* threadpool: update calling thread prio and affinity only at start/resume
This avoids extra syscalls for each graph_compute()
* llama-bench: turn threadpool params into vectors, add output headers, etc
* llama-bench: add support for cool off between tests --delay
This helps for long running tests on platforms that are thermally limited (phones, laptops, etc).
--delay (disabled by default) introduces the sleep for N seconds before starting each test.
* threadpool: move process priority setting into the apps (bench and cli)
This avoids changing the overall process priority on Windows for the apps
that use ggml/llama.cpp directy.
* threadpool: move all pause/resume logic into ggml
* threadpool: futher api cleanup and prep for future refactoring
All threadpool related functions and structs use ggml_threadpool prefix.
* threadpool: minor indent fixes
* threadpool: improve setprioty error message
* Update examples/llama-bench/llama-bench.cpp
Co-authored-by: slaren <slarengh@gmail.com>
* threadpool: fix indent in set_threadpool call
* use int32_t for n_thread type in public llama.cpp API
* threadpool: use _new and _free instead of _create and _release
* fix two more public APIs to use int32_t for n_threads
* build: set _GNU_SOURCE for Adroid
---------
Co-authored-by: Max Krasnyansky <quic_maxk@quicinc.com>
Co-authored-by: fmz <quic_fzaghlou@quic.com>
Co-authored-by: Max Krasnyansky <max.krasnyansky@gmail.com>
Co-authored-by: slaren <slarengh@gmail.com>
2024-08-30 01:20:53 +02:00
struct ggml_threadpool_params ggml_threadpool_params_from_cpu_params ( const cpu_params & params ) ;
2023-03-28 16:09:55 +02:00
2024-11-27 22:30:52 +01:00
struct llama_model * common_load_model_from_url (
const std : : string & model_url ,
const std : : string & local_path ,
const std : : string & hf_token ,
const struct llama_model_params & params ) ;
struct llama_model * common_load_model_from_hf (
const std : : string & repo ,
const std : : string & remote_path ,
const std : : string & local_path ,
const std : : string & hf_token ,
const struct llama_model_params & params ) ;
2024-03-17 19:12:37 +01:00
2024-08-06 17:33:39 +02:00
// clear LoRA adapters from context, then apply new list of adapters
2024-10-10 22:57:42 +02:00
void common_lora_adapters_apply ( struct llama_context * ctx , std : : vector < common_lora_adapter_container > & lora_adapters ) ;
2024-08-06 17:33:39 +02:00
2024-11-25 08:58:41 +01:00
//
2023-10-18 15:21:57 +02:00
// Batch utils
2024-11-25 08:58:41 +01:00
//
2023-10-18 15:21:57 +02:00
2024-10-10 22:57:42 +02:00
void common_batch_clear ( struct llama_batch & batch ) ;
2023-10-18 15:21:57 +02:00
2024-10-10 22:57:42 +02:00
void common_batch_add (
2023-10-18 15:21:57 +02:00
struct llama_batch & batch ,
llama_token id ,
llama_pos pos ,
const std : : vector < llama_seq_id > & seq_ids ,
bool logits ) ;
2024-11-25 08:58:41 +01:00
//
// Token utils
//
// longest common prefix
size_t common_lcp ( const llama_tokens & a , const llama_tokens & b ) ;
// longet common subsequence
size_t common_lcs ( const llama_tokens & a , const llama_tokens & b ) ;
2023-05-02 22:39:51 +02:00
//
2023-08-21 22:07:43 +02:00
// Vocab utils
2023-05-02 22:39:51 +02:00
//
2023-08-27 13:19:19 +02:00
// tokenizes a string into a vector of tokens
// should work similar to Python's `tokenizer.encode`
2024-10-10 22:57:42 +02:00
std : : vector < llama_token > common_tokenize (
2023-09-28 21:42:38 +02:00
const struct llama_context * ctx ,
const std : : string & text ,
2024-04-09 19:44:08 +02:00
bool add_special ,
bool parse_special = false ) ;
2023-09-28 21:42:38 +02:00
2024-10-10 22:57:42 +02:00
std : : vector < llama_token > common_tokenize (
2023-09-28 21:42:38 +02:00
const struct llama_model * model ,
2023-08-21 22:07:43 +02:00
const std : : string & text ,
2024-04-09 19:44:08 +02:00
bool add_special ,
bool parse_special = false ) ;
2023-08-21 22:07:43 +02:00
2024-04-24 12:15:29 +02:00
// tokenizes a token into a piece, optionally renders special/control tokens
2023-08-27 13:19:19 +02:00
// should work similar to Python's `tokenizer.id_to_piece`
2024-10-10 22:57:42 +02:00
std : : string common_token_to_piece (
2023-08-21 22:07:43 +02:00
const struct llama_context * ctx ,
2024-04-24 12:15:29 +02:00
llama_token token ,
bool special = true ) ;
2023-08-27 13:19:19 +02:00
// detokenizes a vector of tokens into a string
// should work similar to Python's `tokenizer.decode`
2024-07-05 19:01:35 +02:00
// optionally renders special/control tokens
2024-10-10 22:57:42 +02:00
std : : string common_detokenize (
2023-08-27 13:19:19 +02:00
llama_context * ctx ,
2024-07-05 19:01:35 +02:00
const std : : vector < llama_token > & tokens ,
bool special = true ) ;
2023-08-28 17:59:39 +02:00
2024-06-04 20:23:39 +02:00
//
// Chat template utils
//
2024-06-25 13:56:49 +02:00
// same with llama_chat_message, but uses std::string
2024-10-10 22:57:42 +02:00
struct common_chat_msg {
2024-06-25 13:56:49 +02:00
std : : string role ;
std : : string content ;
} ;
2024-06-04 20:23:39 +02:00
// Check if the template supplied via "--chat-template" is supported or not. Returns true if it's valid
2024-10-10 22:57:42 +02:00
bool common_chat_verify_template ( const std : : string & tmpl ) ;
2024-06-04 20:23:39 +02:00
2024-06-25 13:56:49 +02:00
// CPP wrapper for llama_chat_apply_template
2024-06-27 18:14:19 +02:00
// If the built-in template is not supported, we default to chatml
// If the custom "tmpl" is not supported, we throw an error
2024-10-10 22:57:42 +02:00
std : : string common_chat_apply_template ( const struct llama_model * model ,
2024-06-25 13:56:49 +02:00
const std : : string & tmpl ,
2024-10-10 22:57:42 +02:00
const std : : vector < common_chat_msg > & chat ,
2024-06-25 13:56:49 +02:00
bool add_ass ) ;
// Format single message, while taking into account the position of that message in chat history
2024-10-10 22:57:42 +02:00
std : : string common_chat_format_single ( const struct llama_model * model ,
2024-06-25 13:56:49 +02:00
const std : : string & tmpl ,
2024-10-10 22:57:42 +02:00
const std : : vector < common_chat_msg > & past_msg ,
const common_chat_msg & new_msg ,
2024-06-25 13:56:49 +02:00
bool add_ass ) ;
// Returns an example of formatted chat
2024-10-10 22:57:42 +02:00
std : : string common_chat_format_example ( const struct llama_model * model ,
2024-06-25 13:56:49 +02:00
const std : : string & tmpl ) ;
2023-11-23 18:07:56 +01:00
//
// KV cache utils
//
// Dump the KV cache view with the number of sequences per cell.
2024-10-10 22:57:42 +02:00
void common_kv_cache_dump_view ( const llama_kv_cache_view & view , int row_size = 80 ) ;
2023-11-23 18:07:56 +01:00
// Dump the KV cache view showing individual sequences in each cell (long output).
2024-10-10 22:57:42 +02:00
void common_kv_cache_dump_view_seqs ( const llama_kv_cache_view & view , int row_size = 40 ) ;
2024-03-09 13:27:58 +01:00
//
// Embedding utils
//
2024-12-18 12:01:41 +01:00
// TODO: repace embd_norm with an enum
void common_embd_normalize ( const float * inp , float * out , int n , int embd_norm ) ;
2024-03-09 13:27:58 +01:00
2024-10-10 22:57:42 +02:00
float common_embd_similarity_cos ( const float * embd1 , const float * embd2 , int n ) ;
2024-03-15 21:43:02 +01:00
//
// Control vector utils
//
2024-10-10 22:57:42 +02:00
struct common_control_vector_data {
2024-03-15 21:43:02 +01:00
int n_embd ;
// stores data for layers [1, n_layer] where n_layer = data.size() / n_embd
std : : vector < float > data ;
} ;
2024-10-10 22:57:42 +02:00
struct common_control_vector_load_info {
2024-03-15 21:43:02 +01:00
float strength ;
std : : string fname ;
} ;
// Load control vectors, scale each by strength, and add them together.
// On error, returns {-1, empty}
2024-10-10 22:57:42 +02:00
common_control_vector_data common_control_vector_load ( const std : : vector < common_control_vector_load_info > & load_infos ) ;
2024-03-23 18:07:00 +01:00
//
// Split utils
//
2024-05-22 19:04:20 +02:00
2024-03-23 18:07:00 +01:00
static const char * const LLM_KV_SPLIT_NO = " split.no " ;
static const char * const LLM_KV_SPLIT_COUNT = " split.count " ;
static const char * const LLM_KV_SPLIT_TENSORS_COUNT = " split.tensors.count " ;