Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Finetune LORA #2632

Merged
merged 247 commits into from
Sep 28, 2023
Merged

Finetune LORA #2632

merged 247 commits into from
Sep 28, 2023

Conversation

xaedes
Copy link
Collaborator

@xaedes xaedes commented Aug 16, 2023

Based on #2439 I am here implementing LORA finetuning.
It makes sense to merge PR 2439 before this one. Most commits and changes here come from PR 2439.

I am still working on this.
But since finetuning small train-from-scratch models already seems to work I decided to make a draft PR for it.

The resulting lora files can be loaded by main which applies it to the base model and uses it for generation.

Memory allocator with checkpointing does not work yet. Not sure why o0.
Quantizied and bigger models are untested so far.

Finetuning 32-layer models requires more than 8192 graph nodes, so we may need increase GGML_MAX_NODES and GGML_GRAPH_HASHTABLE_SIZE. Otherwise users will have to increase it themselves by changing the code.
This is not yet commited. For reference:
Next prime (for hashtable) after 2*8192 is 16411.
Next prime after 4*8192 is 32771.

Todos:

  • Test whether allocator without checkpointing works
  • Make checkpointing with allocator work
  • Test prediction results of finetuned LORA model, like is it actually finetuned on the new training data? --> Works
  • Test finetuning on quantized small models --> Doesn't work: backward pass creates unsupported operations like mul_mat(F32, Q)
  • Deal with mul_mat(F32, Q), maybe by graph rewriting into transpose(mul_mat(Q, F32)). But changing mul_mat so that it can write into transposed dst would have better performance
  • Test finetuning on bigger quantized models (3B, 7B, etc.)
  • Fix whatever not works according to above tests
  • Remove debugging stuff
  • Use GGUF for checkpointing files
  • Update README
  • Merge master into this PR, because currently it can't automatically merge into master
  • Maybe add option to finetune without LORA, will probably only be reasonable with very small models, like the ones generated by train-from-scratch
  • Maybe refactor to deduplicate common code with train-from-scratch

xaedes added 30 commits July 28, 2023 21:17
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.
reduces memory overhead from O(n_layer) to O(sqrt(n_layer))

as explained in readme of https://github.com/cybertronai/gradient-checkpointing
…ows 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);
…eter

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]
…aking Adam default instead of AdamW

btw: the default weight decay parameter for torch.optim.AdamW is 0.01
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.
the second argument to cross_entropy_loss must sum up to 1 for each row
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)
this helps keeping the loss and gradients in a sane range
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.
--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
… the input

this makes it possible to store other values into the input tensor and then simply recompute the graph without rebuilding it
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
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
…t 2)

this allows to not apply weight decay to bias parameters
…y that adam-min-alpha also applies to warmup
now that each optimizer iteration gets its own batch we need to multiply by number of opt iterations
…of common.h

and clarify what is context for prediction and what are generated tokens
uncomment `// #define GGML_FLASH_ATTN_EXP_FP16` to enable usage of f16 exp in flash attention
@ggerganov
Copy link
Owner

ggerganov commented Oct 6, 2023

@x4080 If you send me a specific command that you are interested in, I can run it on M1 Pro or M2 Ultra

@CoruNethron
Copy link

how fast is it to finetune on apple silicon 16GB

I can mention, that it highly depends on model size, training set size (and quality) and other parameters. I have experience to train (overfit, actually, as I see it) 3B model within 3 hours, using 100KB dataset ( shakespeare.txt ), and to train 13B model along 12 hours with low quality 5KB dataset, and see strong evidence, that model actually become more skewed towards dataset but unable to solve a task, that I thought it would solve. Both trainings was made using M1, 16GB machine.
Also, take a look at comparison table, provided by @PossiblyAnEngineer earlier in this thread it compares how different parameters affect training time.

@generalsvr
Copy link

How can I enable GPU instead of CPU? I am using M2 MAX 38c

@CoruNethron
Copy link

How can I enable GPU instead of CPU? I am using M2 MAX 38c

According to discussion, Metal (GPU) finetuning is under investigation now.

@x4080
Copy link

x4080 commented Oct 6, 2023

@x4080 If you send me a specific command that you are interested in, I can run it on M1 Pro or M2 Ultra

I usually train it on colab using llama2 base model with couple of simple train data - just trying to understand how can I effectively train an LLM, usually the workflow would be after training using qlora - combine it with the base model, then need to convert it to gguf then I can really play around with it with my m2

For about maybe 100 data, need training about 15 mins

So I just wondered if I can skip all that and using this method - and can it be more effectively

@ggerganov do you have experience for how long will it take ? And will it take more than 16gb ?

Thanks

@x4080
Copy link

x4080 commented Oct 6, 2023

how fast is it to finetune on apple silicon 16GB

I can mention, that it highly depends on model size, training set size (and quality) and other parameters. I have experience to train (overfit, actually, as I see it) 3B model within 3 hours, using 100KB dataset ( shakespeare.txt ), and to train 13B model along 12 hours with low quality 5KB dataset, and see strong evidence, that model actually become more skewed towards dataset but unable to solve a task, that I thought it would solve. Both trainings was made using M1, 16GB machine. Also, take a look at comparison table, provided by @PossiblyAnEngineer earlier in this thread it compares how different parameters affect training time.

Thanks for answering, did you tried to train it on colab and how long will it took ? For my training testing, I use 7b shared llama2 for little data (about 100) its about 15 mins but the conversion etc took a long time

@Mihaiii
Copy link
Contributor

Mihaiii commented Oct 6, 2023

@x4080 you can find some time estimates for different scenarios in the unofficial guide made by @PossiblyAnEngineer : https://rentry.org/cpu-lora

Hope this helps.

yusiwen pushed a commit to yusiwen/llama.cpp that referenced this pull request Oct 7, 2023
* 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" (ggerganov#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>
@x4080
Copy link

x4080 commented Oct 7, 2023

@Mihaiii Thanks for the suggestion

@daboe01
Copy link
Contributor

daboe01 commented Oct 22, 2023

any news on metal (GPU) finetuning?

@ggerganov
Copy link
Owner

Low prio atm - hoping for some community help

@ggerganov
Copy link
Owner

Pinging this thread as well - help with testing training examples will be appreciated.
See: #3912

@rayrayraykk
Copy link

I would like to ask if dropout is supported?

@ananarcit
Copy link

I've trained Shakespeare data with a model for 256 iterations but while testing the lora generated model either with main.exe or after merging with base model, the results are not related to Shakespeare data

Files used:
shakespeare.txt
open_llama_3b_v2

Trained model with below command
`
image

`
Tested with main.exe but doesn't give any output or provides irrelevant response

  1. ![image](https://github.com/ggerganov/llama.cpp/assets/151434487/671ce960-9ecd-483b-9fdb-8efba79fb784)
image

Can someone please provide working example of trained data that provides relevant results

@CoruNethron
Copy link

Trained model with below command

Not sure, but probably the issue is because of --sample-start "\n" - it makes model learn each single line from the poetry as an separate training sample. Try to remove that option.
Also, note the word Thy in your output example. It may be the marker, that model actually learned some Shakespeare.

@ananarcit
Copy link

Great work ! I run my finetuning with my E5-2666 v3 CPU, use the traing data shakespeare.txt

# finetuning
 ./finetune \                                                                                                                                                                                                    
--model-base /home/simpx/llama/llama-2-7b/ggml-model-q8_0.gguf \
--checkpoint-in  chk-lora-llama-2-7b-q8_0-shakespeare-LATEST.gguf \
--checkpoint-out chk-lora-llama-2-7b-q8_0-shakespeare-ITERATION.gguf \
--lora-out lora-llama-2-7b-q8_0-shakespeare-ITERATION.bin \
--train-data "shakespeare.txt" \
--save-every 20 \
--threads 20 --adam-iter 150 --batch 4 --ctx 64 \
--use-checkpointing

After 7.5 hours, the loss value decreased from 2.5 to 0.8, and each iteration takes 3 minutes.

#inference
./main \
   -m /home/simpx/llama/llama-2-7b/ggml-model-f16.gguf \
   --lora lora-llama-2-7b-q8_0-shakespeare-100.bin \
   -t 10 --prompt "To be, or"

 To be, or not to be, that is the question:
As who should say 'to-morrow', that thou gav'st me.
The ende of that day's life, so ends this play:
And then begins a new more beautiful,
Awakened by your sweet breath alone.
Sweet love renewed makes all things well again,
And all ill no sooner hath, but dies,
Or eyes, or tears, or weariness of flesh;
...

a minor issue, finetune will crash when it fails to load model, could add checks just like the main program

diff --git a/examples/finetune/finetune.cpp b/examples/finetune/finetune.cpp                                                                                                                                     
index e5eacd9..a203b37 100644
--- a/examples/finetune/finetune.cpp
+++ b/examples/finetune/finetune.cpp
@@ -1541,6 +1541,10 @@ int main(int argc, char ** argv) {
 
     printf("%s: model base = '%s'\n", __func__, params.fn_model_base);
     struct llama_model * lmodel = llama_load_model_from_file(params.fn_model_base, llama_params);
+    if (lmodel == NULL) {
+        LOG_TEE("%s: error: unable to load model\n", __func__);
+        return 1;
+    }
     struct llama_context * lctx = llama_new_context_with_model(lmodel, llama_params);
 
     struct my_llama_model model;

Hi, How can we identify number of samples in the training data? I read image value to be twice the sample size

@xaedes
Copy link
Collaborator Author

xaedes commented Nov 22, 2023

@rayrayraykk

I would like to ask if dropout is supported?

Sorry - not yet, but I will add it, hopefully before the end of the year^^

@ananarcit, @CoruNethron

Not sure, but probably the issue is because of --sample-start "\n" - it makes model learn each single line from the poetry as an separate training sample. Try to remove that option.

Yep, i think that helps especially for endless generation of text.

It helps because the model training will also see text samples that begin in the middle of a sentence or word.
This is exactly what will happen at inference time; due to context swap the begin of the text, that the model uses for prediction, moves forward.

@ananarcit

How can we identify number of samples in the training data?

The number of training samples as-per-your-command-line-parameters is printed at the begin of training: "number of training tokens: ######"
During training there is also printed a line at each iteration which contains the iteration number, current sample, total number of training samples, learning rate schedule (between 0 and 1) and current loss.

@QueryType
Copy link

Wow! Thanks, using this discussion, I was eventually able to finetune llama-2-7b within 2 hrs, for 150 iterations, and now my model when run with the lora, keeps on spewing Shakespeare style poetry and doesn't seem to stop. I am training on M2 mac mini, with 8 CPU and 10 GPU. Though, GPU use never went up more than 1%, at least my CPUs were not fried and max temperature reached was around 80 deg. C with no artificial air conditioning. Ambient temperature is around 18-20 deg. C. It hit a peak power of 18.08 W, though I failed to note it in my excitement to try the inferencing. The final loss was at ~ 0.7.

@x4080
Copy link

x4080 commented Nov 23, 2023

Wow! Thanks, using this discussion, I was eventually able to finetune llama-2-7b within 2 hrs, for 150 iterations, and now my model when run with the lora, keeps on spewing Shakespeare style poetry and doesn't seem to stop. I am training on M2 mac mini, with 8 CPU and 10 GPU. Though, GPU use never went up more than 1%, at least my CPUs were not fried and max temperature reached was around 80 deg. C with no artificial air conditioning. Ambient temperature is around 18-20 deg. C. It hit a peak power of 18.08 W, though I failed to note it in my excitement to try the inferencing. The final loss was at ~ 0.7.

How many memory do you have ?

@QueryType
Copy link

Wow! Thanks, using this discussion, I was eventually able to finetune llama-2-7b within 2 hrs, for 150 iterations, and now my model when run with the lora, keeps on spewing Shakespeare style poetry and doesn't seem to stop. I am training on M2 mac mini, with 8 CPU and 10 GPU. Though, GPU use never went up more than 1%, at least my CPUs were not fried and max temperature reached was around 80 deg. C with no artificial air conditioning. Ambient temperature is around 18-20 deg. C. It hit a peak power of 18.08 W, though I failed to note it in my excitement to try the inferencing. The final loss was at ~ 0.7.

How many memory do you have ?

24 GB.

@ananarcit
Copy link

@rayrayraykk

I would like to ask if dropout is supported?

Sorry - not yet, but I will add it, hopefully before the end of the year^^

@ananarcit, @CoruNethron

Not sure, but probably the issue is because of --sample-start "\n" - it makes model learn each single line from the poetry as an separate training sample. Try to remove that option.

Yep, i think that helps especially for endless generation of text.

It helps because the model training will also see text samples that begin in the middle of a sentence or word. This is exactly what will happen at inference time; due to context swap the begin of the text, that the model uses for prediction, moves forward.

@ananarcit

How can we identify number of samples in the training data?

The number of training samples as-per-your-command-line-parameters is printed at the begin of training: "number of training tokens: ######" During training there is also printed a line at each iteration which contains the iteration number, current sample, total number of training samples, learning rate schedule (between 0 and 1) and current loss.

@xaedes

Thank you for the clarification . i m able to train the data and the response is shakespear, but what i dont understand is the data returned by the chat is not part of the data i trained. is this expected?

another question i had is when i ran the fine tuning with 256 iterations it behaved like a shakespeare , but when i tried to increase the iteration to 756 and tried , it started giving garbage text as results.

@karayakar
Copy link

karayakar commented Dec 11, 2023

I did experiment shakespeare.txt and output is like this continuously writing and doesn't stop, I tried to load model in LM Studio UI it is throwing error on one model. Other one loads but whenever I type anything it is not stopping. Anyone can tell me what I am missing? why model produce continuous output?

Sorry again, if I am repeating question, if already answered in here, I couldn't able to follow and not clear what I need to do.

train

./bin/train-text-from-scratch
--vocab-model ../models/ggml-vocab-llama.gguf
--ctx 64 --embd 256 --head 8 --layer 16
--checkpoint-in chk-shakespeare-256x16-LATEST.gguf
--checkpoint-out chk-shakespeare-256x16-ITERATION.gguf
--model-out ggml-shakespeare-256x16-f32-ITERATION.gguf
--train-data "shakespeare.txt"
-t 6 -b 16 --seed 1 --adam-iter 256
--no-checkpointing

image

image

image

image

image

image

@xaedes
Copy link
Collaborator Author

xaedes commented Dec 11, 2023

@karayakar

throwing error on one model. Other one loads but whenever I type anything it is not stopping

chk-shakespeare-256x16-ITERATION.gguf is the training save file, it is expected that it does not load as a model for prediction. The other one, (the one that loads) is the actual model.

whenever I type anything it is not stopping
why model produce continuous output?

When you use a model in a chatting workflow, text is probably generated until a stopping text like "User:" is generated.
You only trained it on shakespeare data, which does not contain text in chat format, which is something like

User:
<text>
Assistant:
<other-text>
etc..

So the trained model has no reason to output "User:" which would tell UI that you are using to stop generating text.

To be properly used in a chat-context the training corpus should also include text in the chat format.
You can continue training or lora-finetune the existing model with such a training corpus.

Additionally you may be able to specify a different stop-pattern in the UI, for example ":\n" (colon followed by new-line)

@xaedes
Copy link
Collaborator Author

xaedes commented Dec 11, 2023

@ananarcit

what i dont understand is the data returned by the chat is not part of the data i trained. is this expected?

Not entirely sure what you mean, but I think it is expected that a finetuned model generates text that is not part of the finetune-training-corpus, since it is based on a base-model with pre-existing 'knowledge'.

another question i had is when i ran the fine tuning with 256 iterations it behaved like a shakespeare , but when i tried to increase the iteration to 756 and tried , it started giving garbage text as results.

This sounds like overfitting. Predicting text from the training-corpus should get better - but sampling makes it so, that repetitions etc are avoided, so the sampled text may be different than the text in the training-data. When the model is so strongly overfitted that it absolutely expects to complete text from the training-data it then may produce not-so-good results, because its input is different from training-data due to sampling.

@karayakar
Copy link

@xaedes Thank you for the information.

@williamgomez71
Copy link

@xaedes Thank you in advance for the code made

Do you have any example of a file or dataset with which finetuning can be done for llama2code-instruct or chat models following the prompt currently available for llamacode? My question is that the examples I have seen use Shakespeare-type conversations, but these datasets do not use end-of-conversation and start limiters for the LLM to start responding. Therefore I would like to understand the following regarding the inputs that will be used for finetuning:

  1. I don't see in the code what happens if the context length is exceeded.
  2. How new entries and possible responses are handled, since the examples I have seen have plain text files, I don't know at what point the algorithm you made determines that there is a new entry and its corresponding response.
  3. Does the code handle padding automatically or should the dataset be fixed so that padding is added before sending it to the LLM entry?
  4. Does the tokenizer code automatically add attention masks for paddings [1,1,1,1,1,0,0,0,0]?
  5. Maybe there is a possibility to see the error as a function of cross entropy? or how it is currently calculated
  6. there is the possibility of working with a parquet-type dataset like this https://huggingface.co/datasets/databricks/databricks-dolly-15k?ref=hackernoon.com

example prompt for llama2code:
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<>\n", "\n<>\n\n"

[INST] <>
You are a helpful assistant and only based on the context below you have to answer the user's question
<>

Context:

any context

any user questions.
Answer: [/INST]

without system tags
[INST]
Context:

any context

any user questions.
Answer: [/INST]

@rvs
Copy link

rvs commented Nov 18, 2024

Hey @xaedes -- sorry about this weird way of trying to contact you -- but we (@janchk + myself) are looking into ways of resurrecting some of your work on LORA and would really appreciate if there's a chance to talk to you somehow. Since GH is not really great with DMs -- I'm also trying to contact you on LI.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
high priority Very important issue training Fine-tuning and training stuff
Projects
None yet
Development

Successfully merging this pull request may close these issues.