diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-bat/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-bat/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..a3267da039aad22dcc2d70006dccc34c8759d359 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-bat/adapter_config.json @@ -0,0 +1,18 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "exclude_modules": null, + "inference_mode": false, + "init_weights": "bat", + "layers_pattern": null, + "layers_to_transform": null, + "mini_r": 1, + "miss_dropout": 0.0, + "modules_to_save": null, + "peft_type": "MISS", + "r": 64, + "revision": null, + "target_modules": null, + "task_type": null +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..02ee9f74396d7372104f2adf9f462e1ac4653d93 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,18 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "exclude_modules": null, + "inference_mode": false, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "mini_r": 1, + "miss_dropout": 0.0, + "modules_to_save": null, + "peft_type": "MISS", + "r": 64, + "revision": null, + "target_modules": null, + "task_type": null +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-mini/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-mini/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..d732e181b21e0961029723bc640c25d5917d217e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/miss/llama-3.2-3B-mini/adapter_config.json @@ -0,0 +1,18 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "exclude_modules": null, + "inference_mode": false, + "init_weights": "mini", + "layers_pattern": null, + "layers_to_transform": null, + "mini_r": 64, + "miss_dropout": 0.0, + "modules_to_save": null, + "peft_type": "MISS", + "r": 64, + "revision": null, + "target_modules": null, + "task_type": null +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/oft/llama-3.2-3B-rank32/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/oft/llama-3.2-3B-rank32/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..e8cdb86ecd110a0176dd42b34e25b3c133cbab4a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/oft/llama-3.2-3B-rank32/adapter_config.json @@ -0,0 +1,27 @@ +{ + "alpha_pattern": {}, + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "block_share": false, + "coft": false, + "eps": 6e-05, + "exclude_modules": null, + "fan_in_fan_out": false, + "inference_mode": false, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "module_dropout": 0.0, + "modules_to_save": null, + "oft_block_size": 0, + "peft_type": "OFT", + "r": 32, + "rank_pattern": {}, + "revision": null, + "target_modules": [ + "q_proj", + "v_proj" + ], + "task_type": null +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/osf/llama-3.2-3B-rank128/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/osf/llama-3.2-3B-rank128/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..34d7bf1858cf07e62aa0e31d85d3ad96f083ad63 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/osf/llama-3.2-3B-rank128/adapter_config.json @@ -0,0 +1,28 @@ +{ + "task_type": null, + "peft_type": "OSF", + "auto_mapping": null, + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "effective_rank": null, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "rank_pattern": { + "q_proj": 2944, + "o_proj": 2944, + "k_proj": 896, + "v_proj": 896, + "gate_proj": 2944, + "down_proj": 2944, + "up_proj": 2944 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/osf/llama-3.2-3B-rank128/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/osf/llama-3.2-3B-rank128/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..51f64313245dcc58f7e87b6e548e9abfda811ed5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/osf/llama-3.2-3B-rank128/training_params.json @@ -0,0 +1,7 @@ +{ + "autocast_adapter_dtype": false, + "optimizer_kwargs": { + "lr": 5e-5 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prefixtuning/llama-3.2-3B-lr_0.001/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prefixtuning/llama-3.2-3B-lr_0.001/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..77bff7fd16cd3f675655221218e69a55eaead91f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prefixtuning/llama-3.2-3B-lr_0.001/adapter_config.json @@ -0,0 +1,15 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "encoder_hidden_size": 3072, + "inference_mode": false, + "num_attention_heads": 24, + "num_layers": 28, + "num_transformer_submodules": 1, + "num_virtual_tokens": 200, + "peft_type": "PREFIX_TUNING", + "prefix_projection": false, + "revision": null, + "task_type": "CAUSAL_LM", + "token_dim": 3072 +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prefixtuning/llama-3.2-3B-lr_0.001/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prefixtuning/llama-3.2-3B-lr_0.001/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..8a120ad9a80c36dc3666f4da481a5292a7dc8072 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prefixtuning/llama-3.2-3B-lr_0.001/training_params.json @@ -0,0 +1,6 @@ +{ + "optimizer_kwargs": { + "lr": 1e-3 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..efa055b03d6f3a6c6d0f7df76f11550891919b0a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,17 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "inference_mode": false, + "num_attention_heads": 24, + "num_layers": 28, + "num_transformer_submodules": 1, + "num_virtual_tokens": 200, + "peft_type": "PROMPT_TUNING", + "prompt_tuning_init": "RANDOM", + "prompt_tuning_init_text": null, + "revision": null, + "task_type": "CAUSAL_LM", + "token_dim": 3072, + "tokenizer_kwargs": null, + "tokenizer_name_or_path": null +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-lr_0.001/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-lr_0.001/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..efa055b03d6f3a6c6d0f7df76f11550891919b0a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-lr_0.001/adapter_config.json @@ -0,0 +1,17 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "inference_mode": false, + "num_attention_heads": 24, + "num_layers": 28, + "num_transformer_submodules": 1, + "num_virtual_tokens": 200, + "peft_type": "PROMPT_TUNING", + "prompt_tuning_init": "RANDOM", + "prompt_tuning_init_text": null, + "revision": null, + "task_type": "CAUSAL_LM", + "token_dim": 3072, + "tokenizer_kwargs": null, + "tokenizer_name_or_path": null +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-lr_0.001/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-lr_0.001/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..8a120ad9a80c36dc3666f4da481a5292a7dc8072 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-lr_0.001/training_params.json @@ -0,0 +1,6 @@ +{ + "optimizer_kwargs": { + "lr": 1e-3 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-sample_vocab-lr_0.001/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-sample_vocab-lr_0.001/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..8b9f14279798195477b8a188feb12dfcd9605e00 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-sample_vocab-lr_0.001/adapter_config.json @@ -0,0 +1,17 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "inference_mode": false, + "num_attention_heads": 24, + "num_layers": 28, + "num_transformer_submodules": 1, + "num_virtual_tokens": 200, + "peft_type": "PROMPT_TUNING", + "prompt_tuning_init": "SAMPLE_VOCAB", + "prompt_tuning_init_text": null, + "revision": null, + "task_type": "CAUSAL_LM", + "token_dim": 3072, + "tokenizer_kwargs": null, + "tokenizer_name_or_path": null +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-sample_vocab-lr_0.001/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-sample_vocab-lr_0.001/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..8a120ad9a80c36dc3666f4da481a5292a7dc8072 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/prompt_tuning/llama-3.2-3B-sample_vocab-lr_0.001/training_params.json @@ -0,0 +1,6 @@ +{ + "optimizer_kwargs": { + "lr": 1e-3 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/psoft/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/psoft/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..fb70b83d7f8a2a2de113fc6a77bb50e36919a4eb --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/psoft/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,26 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "r": 256, + "psoft_alpha": 256, + "psoft_dropout": 0.0, + "exclude_modules": null, + "fan_in_fan_out": false, + "ab_svd_init": "psoft_init", + "psoft_svd": "full", + "psoft_svd_lowrank_niter": 10, + "psoft_orth": true, + "psoft_mag_a": true, + "psoft_mag_b": true, + "use_cayley_neumann": false, + "num_cayley_neumann_terms": 5, + "cayley_neumann_eps": null, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "modules_to_save": null, + "peft_type": "PSOFT", + "revision": null, + "target_modules": null, + "task_type": null +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/psoft/llama-3.2-3B-fast/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/psoft/llama-3.2-3B-fast/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..290234d40949b5c10ccff4926aa808b5972ac0de --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/psoft/llama-3.2-3B-fast/adapter_config.json @@ -0,0 +1,26 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "r": 256, + "psoft_alpha": 256, + "psoft_dropout": 0.0, + "exclude_modules": null, + "fan_in_fan_out": false, + "ab_svd_init": "psoft_init", + "psoft_svd": "lowrank", + "psoft_svd_lowrank_niter": 10, + "psoft_orth": true, + "psoft_mag_a": true, + "psoft_mag_b": true, + "use_cayley_neumann": true, + "num_cayley_neumann_terms": 5, + "cayley_neumann_eps": null, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "modules_to_save": null, + "peft_type": "PSOFT", + "revision": null, + "target_modules": null, + "task_type": null +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/ptuning/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/ptuning/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..54469edf776f3de255d054c317887b1312aa7791 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/ptuning/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,17 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "encoder_dropout": 0.0, + "encoder_hidden_size": 3072, + "encoder_num_layers": 2, + "encoder_reparameterization_type": "MLP", + "inference_mode": false, + "num_attention_heads": 24, + "num_layers": 28, + "num_transformer_submodules": 1, + "num_virtual_tokens": 20, + "peft_type": "P_TUNING", + "revision": null, + "task_type": "CAUSAL_LM", + "token_dim": 3072 +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/pvera/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/pvera/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..4fd7ce5a7d1a7705408ac2797062de993922014e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/pvera/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,20 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "d_initial": 0.1, + "fan_in_fan_out": false, + "inference_mode": false, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "modules_to_save": null, + "peft_type": "PVERA", + "projection_prng_key": 0, + "r": 256, + "revision": null, + "save_projection": true, + "target_modules": null, + "task_type": null, + "pvera_dropout": 0.0 +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/pvera/llama-3.2-3B-default/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/pvera/llama-3.2-3B-default/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..8bed6db65eff25a98c541f42c663cf0bb33b2669 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/pvera/llama-3.2-3B-default/training_params.json @@ -0,0 +1,6 @@ +{ + "optimizer_kwargs": { + "lr": 3e-3 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/randlora/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/randlora/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..3dbdfaa6b123a057774dc5c46d86bfe4d4e35b55 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/randlora/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,22 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "fan_in_fan_out": false, + "inference_mode": false, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "modules_to_save": null, + "peft_type": "RANDLORA", + "projection_prng_key": 0, + "r": 32, + "randlora_alpha": 640, + "randlora_dropout": 0.0, + "revision": null, + "save_projection": true, + "sparse": false, + "target_modules": null, + "task_type": null, + "very_sparse": false +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/road/llama-3.2-3B-lr_0.001/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/road/llama-3.2-3B-lr_0.001/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..d0f74c40761246f57831661e4a86dae1d28399d8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/road/llama-3.2-3B-lr_0.001/adapter_config.json @@ -0,0 +1,12 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "group_size": 64, + "inference_mode": false, + "init_weights": true, + "peft_type": "ROAD", + "revision": null, + "target_modules": null, + "task_type": null, + "variant": "road_2" +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/road/llama-3.2-3B-lr_0.001/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/road/llama-3.2-3B-lr_0.001/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..52d87e3ef6d143c29d2ba640028909a31befffa6 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/road/llama-3.2-3B-lr_0.001/training_params.json @@ -0,0 +1,5 @@ +{ + "optimizer_kwargs": { + "lr": 1e-3 + } +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/shira/llama-3.2-3B-lr_0.0003-random_seed_42/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/shira/llama-3.2-3B-lr_0.0003-random_seed_42/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..0d4565eef10746dd8c02364f737fb7a7143955d0 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/shira/llama-3.2-3B-lr_0.0003-random_seed_42/adapter_config.json @@ -0,0 +1,15 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "fan_in_fan_out": false, + "inference_mode": false, + "init_weights": true, + "mask_type": "random", + "modules_to_save": null, + "peft_type": "SHIRA", + "r": 32, + "random_seed": 42, + "revision": null, + "target_modules": null, + "task_type": null +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/shira/llama-3.2-3B-lr_0.0003-random_seed_42/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/shira/llama-3.2-3B-lr_0.0003-random_seed_42/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..92f18b8a3c5adb57d1d25314d50f1c8df85eb570 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/shira/llama-3.2-3B-lr_0.0003-random_seed_42/training_params.json @@ -0,0 +1,6 @@ +{ + "optimizer_kwargs": { + "lr": 3e-4 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/trainable_tokens/llama-3.2-3B-sos+eos/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/trainable_tokens/llama-3.2-3B-sos+eos/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..bce0cd5b129fe4281eb46c7d17f05bb0fca3935d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/trainable_tokens/llama-3.2-3B-sos+eos/adapter_config.json @@ -0,0 +1,7 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "peft_type": "TRAINABLE_TOKENS", + "token_indices": [128000, 128001], + "task_type": "CAUSAL_LM" +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/trainable_tokens/llama-3.2-3B-sos+eos/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/trainable_tokens/llama-3.2-3B-sos+eos/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..92e546e6cfeadce2db2ab6dbd124790a4fb0dbf4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/trainable_tokens/llama-3.2-3B-sos+eos/training_params.json @@ -0,0 +1,5 @@ +{ + "optimizer_kwargs": { + "lr": 0.2 + } +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vblora/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vblora/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..b6cbc59e57c07e6b883ff34ed98090d51916d652 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vblora/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,26 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "exclude_modules": null, + "fan_in_fan_out": false, + "inference_mode": false, + "init_logits_std": 0.1, + "init_vector_bank_bound": 0.02, + "layers_pattern": null, + "layers_to_transform": null, + "modules_to_save": null, + "num_vectors": 256, + "peft_type": "VBLORA", + "r": 4, + "revision": null, + "save_only_topk_weights": false, + "target_modules": [ + "v_proj", + "q_proj" + ], + "task_type": null, + "topk": 2, + "vblora_dropout": 0.0, + "vector_length": 256 +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vera/llama-3.2-3B-default/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vera/llama-3.2-3B-default/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..f4962c1b4fa1266ba29f31559fa3260483d8fac7 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vera/llama-3.2-3B-default/adapter_config.json @@ -0,0 +1,20 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "d_initial": 0.1, + "fan_in_fan_out": false, + "inference_mode": false, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "modules_to_save": null, + "peft_type": "VERA", + "projection_prng_key": 0, + "r": 256, + "revision": null, + "save_projection": true, + "target_modules": null, + "task_type": null, + "vera_dropout": 0.0 +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vera/llama-3.2-3B-default/training_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vera/llama-3.2-3B-default/training_params.json new file mode 100644 index 0000000000000000000000000000000000000000..8a120ad9a80c36dc3666f4da481a5292a7dc8072 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/vera/llama-3.2-3B-default/training_params.json @@ -0,0 +1,6 @@ +{ + "optimizer_kwargs": { + "lr": 1e-3 + } +} + diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/waveft/llama-3.2-3B-n_frequency-5000/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/waveft/llama-3.2-3B-n_frequency-5000/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..6aad104d0f1dec10bf97eee02c9d22b2b49dbeb2 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/experiments/waveft/llama-3.2-3B-n_frequency-5000/adapter_config.json @@ -0,0 +1,26 @@ +{ + "auto_mapping": null, + "base_model_name_or_path": null, + "bias": "none", + "exclude_modules": null, + "fan_in_fan_out": false, + "inference_mode": false, + "init_weights": true, + "layers_pattern": null, + "layers_to_transform": null, + "modules_to_save": null, + "n_frequency": 5000, + "n_frequency_pattern": {}, + "peft_type": "WAVEFT", + "proportional_parameters": false, + "random_loc_seed": 777, + "revision": null, + "scaling": 25.0, + "target_modules": [ + "q_proj", + "v_proj" + ], + "task_type": "CAUSAL_LM", + "use_idwt": true, + "wavelet_family": "db1" +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/requirements.txt b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..ee25a1ced129a9c13938c22922aa0514230af60b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/requirements.txt @@ -0,0 +1,4 @@ +bitsandbytes +datasets +numpy +tqdm diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/.gitkeep b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/adalora--llama-3.2-3B-rank32.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/adalora--llama-3.2-3B-rank32.json new file mode 100644 index 0000000000000000000000000000000000000000..edfa5dc8b49b17ed1a6e989c065e3af838bb0908 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/adalora--llama-3.2-3B-rank32.json @@ -0,0 +1,4080 @@ +{ + "run_info": { + "created_at": "2026-01-09T17:02:52+00:00", + "total_time": 1339.9807203459786, + "experiment_name": "adalora/llama-3.2-3B-rank32", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "ADALORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 8, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "lora_alpha": 8, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": false, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": { + "model.layers.0.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.0.self_attn.v_proj.lora_E": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "model.layers.1.self_attn.q_proj.lora_E": [ + false, + false, + false, + true, + false, + true, + true, + false, + false, + false, + false, + true, + true, + false, + true, + true, + true, + true, + false, + false, + false, + false, + false, + false, + true, + false, + true, + true, + false, + false, + true, + true, + true, + false, + true, + false, + false, + false, + true, + true, + true, + false, + false, + false, + true, + false, + true, + true, + true, + true, + false, + true, + true, + true, + false, + false, + true, + true, + false, + false, + true, + true, + false, + false + ], + "model.layers.1.self_attn.v_proj.lora_E": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true + ], + "model.layers.2.self_attn.q_proj.lora_E": [ + true, + false, + true, + false, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + false, + false, + true, + false, + false, + true, + false, + false, + true, + false, + true, + true, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + true, + true, + true, + false, + false, + false, + true, + true, + false, + false, + false, + true, + false, + true, + true, + false, + true, + false, + false, + false, + false, + true, + false, + true, + true, + false, + false + ], + "model.layers.2.self_attn.v_proj.lora_E": [ + false, + false, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + true, + false, + false, + true, + true, + false, + false, + true, + true, + true, + false, + false, + true, + true, + true, + false, + false, + false, + true, + true, + false, + true, + false, + true, + true + ], + "model.layers.3.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.3.self_attn.v_proj.lora_E": [ + false, + false, + false, + false, + false, + true, + false, + true, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + false, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + true, + false, + false, + false, + false, + true, + false, + true, + true, + false, + true, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + true, + true + ], + "model.layers.4.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + false, + true, + false, + false, + true, + true, + false, + true, + false, + false, + false, + false, + false, + false, + false, + true, + true, + false, + true, + false, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + true, + true, + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false + ], + "model.layers.4.self_attn.v_proj.lora_E": [ + true, + false, + true, + true, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + false, + true, + false, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + false, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false, + false, + true, + true, + true, + true, + true, + false, + false, + false, + false, + false, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + true, + true, + true + ], + "model.layers.5.self_attn.q_proj.lora_E": [ + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.5.self_attn.v_proj.lora_E": [ + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + false, + true, + false, + false, + true, + false, + true, + false, + false, + false, + false, + true, + true, + false, + false, + false, + false, + true, + false, + true, + false, + true, + true, + false, + false, + true, + true, + true, + true, + false, + false, + true, + false, + true, + false, + false, + true, + true, + true, + false, + true, + true, + false, + false, + true, + true, + true, + true, + false, + false, + false, + true, + true + ], + "model.layers.6.self_attn.q_proj.lora_E": [ + false, + false, + true, + true, + false, + false, + true, + true, + false, + false, + false, + true, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + true, + true, + false, + true, + false, + true, + false, + true, + false, + false, + false, + true, + true, + false, + false, + false, + false, + true, + true, + false, + false, + false, + true, + false, + true, + false, + false, + true, + true, + false, + false, + false, + true, + false, + false, + true, + false, + false, + false, + true, + false, + false + ], + "model.layers.6.self_attn.v_proj.lora_E": [ + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + false, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + true + ], + "model.layers.7.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.7.self_attn.v_proj.lora_E": [ + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + false, + true, + false, + false, + true, + true, + true, + true, + false, + false, + false, + true, + false, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + false, + false, + true, + true, + true, + true + ], + "model.layers.8.self_attn.q_proj.lora_E": [ + false, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + false, + false, + true, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true + ], + "model.layers.8.self_attn.v_proj.lora_E": [ + false, + true, + false, + false, + false, + true, + false, + false, + false, + false, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + false, + true, + false, + false, + false, + true, + false, + true, + false, + true, + true, + false, + true, + false, + true, + true, + false, + false, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + false, + false, + true + ], + "model.layers.9.self_attn.q_proj.lora_E": [ + true, + false, + true, + true, + false, + false, + true, + true, + false, + true, + true, + false, + false, + false, + true, + true, + false, + true, + false, + true, + false, + false, + false, + true, + false, + true, + false, + true, + false, + true, + false, + true, + true, + false, + false, + true, + true, + false, + false, + false, + false, + true, + true, + true, + false, + false, + false, + false, + true, + true, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false, + false, + true, + false, + false + ], + "model.layers.9.self_attn.v_proj.lora_E": [ + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + true, + true, + true, + false, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false + ], + "model.layers.10.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.10.self_attn.v_proj.lora_E": [ + true, + true, + false, + false, + false, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + false, + false, + true, + true, + true, + true, + false, + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + true + ], + "model.layers.11.self_attn.q_proj.lora_E": [ + true, + false, + false, + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + true, + true, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + true, + false, + false, + false, + true, + false, + true, + false, + true, + false, + false, + false, + true, + true, + false, + false, + false, + false, + true, + true, + false, + true, + false, + true, + true, + false, + false, + false + ], + "model.layers.11.self_attn.v_proj.lora_E": [ + false, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + false, + true, + true, + true, + true, + false, + false, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + false, + false, + false, + true, + false, + false, + true, + true, + false, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + false + ], + "model.layers.12.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + true, + true, + false, + true, + false, + false, + false, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.12.self_attn.v_proj.lora_E": [ + true, + true, + true, + true, + false, + true, + true, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + false, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + false, + true, + true, + true, + false, + true, + false, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + true, + true, + false + ], + "model.layers.13.self_attn.q_proj.lora_E": [ + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + false, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + false, + false, + false, + true, + false, + false, + true, + false, + true, + false, + true, + true, + true, + false, + false, + false, + false, + true, + true, + true, + true, + false, + true, + false, + true, + true, + true, + false, + true, + false, + true, + true, + false, + false, + false, + true, + false + ], + "model.layers.13.self_attn.v_proj.lora_E": [ + true, + false, + true, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + false, + true, + true, + false, + false, + true, + false, + false, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + false, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + true + ], + "model.layers.14.self_attn.q_proj.lora_E": [ + false, + true, + false, + true, + true, + false, + false, + false, + true, + false, + false, + true, + false, + false, + true, + true, + true, + true, + false, + true, + false, + false, + false, + true, + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + false, + false, + true, + true, + false, + true, + true, + false, + false, + false, + false, + false, + false, + true, + false, + true, + true, + true, + false, + true, + true, + true, + false, + false, + true, + false, + true, + true, + true + ], + "model.layers.14.self_attn.v_proj.lora_E": [ + true, + true, + true, + false, + false, + false, + true, + false, + false, + false, + false, + true, + true, + false, + false, + true, + false, + false, + true, + true, + false, + true, + false, + false, + true, + false, + true, + false, + true, + true, + false, + true, + false, + true, + false, + false, + true, + false, + false, + true, + false, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false + ], + "model.layers.15.self_attn.q_proj.lora_E": [ + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + false, + true, + true, + true, + false, + true, + false, + false, + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + false, + false, + true, + true, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true + ], + "model.layers.15.self_attn.v_proj.lora_E": [ + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + true, + true, + false, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + false, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true + ], + "model.layers.16.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + false, + false, + false, + true, + true, + false, + true, + false, + true, + false, + true, + true, + true, + false, + true, + false, + false, + true, + true, + false, + false, + false, + true, + true, + false, + false, + true, + false, + true, + true, + true, + true, + false, + true, + false, + false, + true, + true, + false, + true, + true, + true, + true, + false, + true, + true, + false, + true, + true, + false, + true, + false, + false, + true, + true, + true, + false, + false, + true, + true + ], + "model.layers.16.self_attn.v_proj.lora_E": [ + true, + false, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + false, + true, + true, + true, + true, + false, + true, + false, + true, + true, + true, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + true, + false, + false, + true, + false, + false, + true, + true, + false, + true, + false, + true, + true, + true, + false, + true, + true, + false, + false, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + false, + false + ], + "model.layers.17.self_attn.q_proj.lora_E": [ + true, + true, + true, + true, + false, + true, + false, + true, + false, + true, + true, + true, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + true, + true, + false, + true, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true + ], + "model.layers.17.self_attn.v_proj.lora_E": [ + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + false, + false, + false, + true, + false, + true, + true, + false, + false, + true, + true, + false, + false, + false, + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true + ], + "model.layers.18.self_attn.q_proj.lora_E": [ + false, + true, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + false, + false, + true, + false, + true, + true, + false, + false, + true, + false, + false, + true, + false, + true, + false, + false, + true, + false, + true, + true, + true, + true + ], + "model.layers.18.self_attn.v_proj.lora_E": [ + true, + true, + true, + false, + true, + true, + true, + true, + false, + true, + true, + false, + false, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + false, + false, + true + ], + "model.layers.19.self_attn.q_proj.lora_E": [ + false, + true, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + false, + true, + false, + true, + true, + false, + true, + false, + true, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + false, + false, + false, + false, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + false, + true, + true + ], + "model.layers.19.self_attn.v_proj.lora_E": [ + false, + true, + false, + false, + true, + true, + false, + true, + false, + false, + false, + false, + false, + true, + true, + false, + true, + false, + false, + false, + false, + false, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + true, + true, + false, + false, + false, + true, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + true, + true + ], + "model.layers.20.self_attn.q_proj.lora_E": [ + false, + true, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + true, + false, + true, + true, + false, + false, + false, + false, + true, + false, + true, + false, + true, + false, + false, + false, + false, + false, + true, + false, + false, + true, + true, + false, + false, + false, + false, + false, + true, + false, + false + ], + "model.layers.20.self_attn.v_proj.lora_E": [ + true, + false, + true, + true, + false, + false, + false, + true, + true, + false, + false, + true, + true, + true, + false, + true, + false, + true, + false, + false, + false, + false, + true, + false, + false, + false, + true, + false, + true, + false, + true, + true, + true, + false, + false, + false, + true, + false, + true, + false, + true, + true, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false, + true, + false, + false, + true, + true, + false, + true, + true + ], + "model.layers.21.self_attn.q_proj.lora_E": [ + false, + true, + true, + true, + true, + true, + false, + true, + true, + false, + false, + true, + true, + true, + true, + true, + false, + false, + false, + false, + true, + true, + false, + true, + true, + true, + true, + false, + false, + false, + false, + false, + false, + false, + true, + true, + true, + false, + true, + false, + true, + false, + true, + false, + false, + false, + true, + false, + true, + true, + true, + true, + true, + false, + false, + true, + true, + false, + true, + true, + true, + false, + true, + true + ], + "model.layers.21.self_attn.v_proj.lora_E": [ + true, + true, + true, + true, + true, + false, + true, + true, + false, + true, + true, + false, + false, + true, + true, + false, + true, + true, + false, + true, + true, + true, + true, + false, + false, + false, + true, + false, + true, + true, + true, + false, + true, + true, + false, + true, + true, + false, + true, + true, + false, + false, + false, + true, + true, + false, + true, + false, + true, + true, + false, + true, + true, + false, + false, + false, + false, + true, + true, + false, + false, + false, + false, + false + ], + "model.layers.22.self_attn.q_proj.lora_E": [ + false, + true, + false, + true, + true, + false, + true, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + true, + true, + false, + false, + false, + false, + true, + true, + true, + false, + false, + true, + false, + false, + false, + false, + true, + true, + false, + false, + false, + false, + true, + false, + false, + false, + true, + false, + true, + false, + false, + false, + true, + false, + true, + true, + true, + false, + false, + true, + false, + false, + true, + true, + false, + true + ], + "model.layers.22.self_attn.v_proj.lora_E": [ + false, + true, + true, + true, + true, + false, + false, + true, + true, + false, + true, + false, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + false, + true, + true, + false, + true, + false, + false, + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + false, + true, + true, + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + false, + true, + true + ], + "model.layers.23.self_attn.q_proj.lora_E": [ + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + true, + true, + false, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + false, + true, + true + ], + "model.layers.23.self_attn.v_proj.lora_E": [ + false, + true, + false, + true, + false, + false, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + false, + false, + false, + true, + false, + true, + true, + false, + true, + false, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + false, + true, + true, + false, + false, + true, + false, + true, + true, + false, + true, + false, + false, + true + ], + "model.layers.24.self_attn.q_proj.lora_E": [ + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + true, + false, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + false, + true, + true, + true, + true, + true, + true, + true, + true, + true, + false, + true, + true, + true, + false, + false, + true, + true, + true, + false, + true, + false, + true, + true, + true, + true, + false, + false, + false, + true, + true, + true, + true, + false, + false, + true + ], + "model.layers.24.self_attn.v_proj.lora_E": [ + true, + true, + true, + false, + true, + false, + false, + true, + true, + true, + false, + true, + true, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + false, + false, + true, + false, + true, + false, + true, + false, + true, + true, + false, + true, + true, + false, + false, + false, + true, + false, + false, + true, + true, + true, + true, + true, + false, + false, + true, + true, + true, + true, + false, + false, + true, + true, + true, + false, + true, + false, + true, + true, + true + ], + "model.layers.25.self_attn.q_proj.lora_E": [ + false, + false, + false, + false, + true, + true, + false, + true, + true, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + true, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.25.self_attn.v_proj.lora_E": [ + false, + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + true, + false, + true, + true, + true, + false, + false, + false, + false, + true, + false, + false, + false, + true, + true, + true, + true, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false + ], + "model.layers.26.self_attn.q_proj.lora_E": [ + true, + false, + false, + true, + false, + false, + false, + false, + false, + false, + true, + false, + true, + false, + true, + true, + true, + false, + false, + true, + true, + true, + false, + false, + true, + true, + false, + false, + true, + false, + true, + true, + false, + false, + false, + true, + true, + false, + true, + false, + false, + true, + false, + false, + true, + false, + false, + false, + true, + false, + true, + true, + false, + true, + false, + false, + true, + true, + true, + false, + true, + true, + true, + true + ], + "model.layers.26.self_attn.v_proj.lora_E": [ + false, + false, + true, + false, + true, + false, + false, + false, + true, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + true, + false, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false, + false, + false, + false, + false, + false, + true, + true, + true, + false, + false, + false, + true, + false, + true, + false, + true, + false, + false, + false, + true, + false, + false + ], + "model.layers.27.self_attn.q_proj.lora_E": [ + true, + false, + false, + true, + true, + false, + false, + true, + true, + false, + false, + false, + true, + true, + false, + true, + false, + false, + true, + false, + false, + true, + true, + true, + true, + false, + false, + true, + true, + false, + false, + false, + false, + true, + true, + true, + true, + false, + false, + false, + false, + false, + false, + true, + true, + true, + false, + false, + false, + true, + true, + true, + true, + true, + false, + false, + false, + false, + false, + false, + false, + false, + true, + false + ], + "model.layers.27.self_attn.v_proj.lora_E": [ + false, + false, + true, + true, + true, + true, + true, + true, + true, + true, + false, + false, + true, + false, + false, + false, + true, + true, + false, + false, + false, + true, + false, + true, + true, + true, + true, + true, + false, + true, + false, + false, + true, + false, + true, + true, + false, + true, + true, + false, + false, + true, + false, + true, + true, + false, + false, + true, + false, + true, + true, + true, + false, + false, + false, + false, + false, + true, + true, + true, + true, + true, + false, + true + ] + }, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": false, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": null, + "arrow_config": null, + "ensure_weight_tying": false, + "target_r": 32, + "init_r": 64, + "tinit": 200, + "tfinal": 500, + "deltaT": 1, + "beta1": 0.85, + "beta2": 0.85, + "orth_reg_weight": 0.5, + "total_step": 5000 + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14915761654, + "accelerator_memory_max": 22796042240, + "accelerator_memory_reserved_99th": 20617101312, + "train_time": 1097.5522341161268, + "file_size": 35131056, + "num_trainable_params": 18353664, + "num_total_params": 3231103544, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.3241328690052032, + "train samples": 1000, + "train time": 33.437529707327485, + "eval time": 12.192411294032354, + "tokens / sec": 6331.777552143872, + "mem allocated avg": 7294713141.248, + "mem reserved avg": 15068431384.576, + "elapsed time": 71.46285747201182 + }, + { + "step": 500, + "valid accuracy": 0.42, + "train loss": 1.0195916182994842, + "train samples": 2000, + "train time": 35.78730485920096, + "eval time": 12.20008662098553, + "tokens / sec": 5811.977203042275, + "mem allocated avg": 7287517972.48, + "mem reserved avg": 14679560683.52, + "elapsed time": 123.03286996803945 + }, + { + "step": 750, + "valid accuracy": 0.3, + "train loss": 0.788285866856575, + "train samples": 3000, + "train time": 36.553958278673235, + "eval time": 12.192845579993445, + "tokens / sec": 5865.329230982038, + "mem allocated avg": 7297823625.216, + "mem reserved avg": 14887958872.064, + "elapsed time": 175.27128310705302 + }, + { + "step": 1000, + "valid accuracy": 0.34, + "train loss": 0.7407853524684906, + "train samples": 4000, + "train time": 36.186631593853235, + "eval time": 12.179883008997422, + "tokens / sec": 5757.264238857439, + "mem allocated avg": 7288626950.144, + "mem reserved avg": 14961325637.632, + "elapsed time": 227.3045465090545 + }, + { + "step": 1250, + "valid accuracy": 0.32, + "train loss": 0.7283406076431275, + "train samples": 5000, + "train time": 35.77542787248967, + "eval time": 12.210806805000175, + "tokens / sec": 5829.084721034463, + "mem allocated avg": 7289293629.44, + "mem reserved avg": 14984788574.208, + "elapsed time": 278.867415188055 + }, + { + "step": 1500, + "valid accuracy": 0.38, + "train loss": 0.7160038756132125, + "train samples": 6000, + "train time": 35.90073716780171, + "eval time": 12.185589247965254, + "tokens / sec": 5830.827345454697, + "mem allocated avg": 7291158284.288, + "mem reserved avg": 14897169563.648, + "elapsed time": 330.540843091032 + }, + { + "step": 1750, + "valid accuracy": 0.34, + "train loss": 0.7057664946317673, + "train samples": 7000, + "train time": 35.91021893679863, + "eval time": 12.154321324953344, + "tokens / sec": 5829.95610158939, + "mem allocated avg": 7292672542.72, + "mem reserved avg": 15298061139.968, + "elapsed time": 382.3315215060138 + }, + { + "step": 2000, + "valid accuracy": 0.34, + "train loss": 0.7058077181577682, + "train samples": 8000, + "train time": 35.90797309036134, + "eval time": 12.198829908971675, + "tokens / sec": 5784.119295103047, + "mem allocated avg": 7288192765.952, + "mem reserved avg": 14933509013.504, + "elapsed time": 434.1038082460291 + }, + { + "step": 2250, + "valid accuracy": 0.36, + "train loss": 0.6997898343801499, + "train samples": 9000, + "train time": 36.599770584725775, + "eval time": 12.184865101007745, + "tokens / sec": 5872.932987446225, + "mem allocated avg": 7298940741.632, + "mem reserved avg": 15212841271.296, + "elapsed time": 486.43084904103307 + }, + { + "step": 2500, + "valid accuracy": 0.36, + "train loss": 0.6983125779628754, + "train samples": 10000, + "train time": 35.72843996837037, + "eval time": 7.310388852027245, + "tokens / sec": 5764.791303016259, + "mem allocated avg": 7285925011.456, + "mem reserved avg": 14699911446.528, + "elapsed time": 533.0108368530055 + }, + { + "step": 2750, + "valid accuracy": 0.32, + "train loss": 0.6912899543046951, + "train samples": 11000, + "train time": 36.1996374403825, + "eval time": 12.285541804973036, + "tokens / sec": 5853.124920075475, + "mem allocated avg": 7295115497.472, + "mem reserved avg": 15075444260.864, + "elapsed time": 585.0133225410245 + }, + { + "step": 3000, + "valid accuracy": 0.36, + "train loss": 0.6850721148252488, + "train samples": 12000, + "train time": 35.86890918528661, + "eval time": 12.206184039998334, + "tokens / sec": 5819.2737036347135, + "mem allocated avg": 7291246731.264, + "mem reserved avg": 15016489123.84, + "elapsed time": 636.763230385026 + }, + { + "step": 3250, + "valid accuracy": 0.34, + "train loss": 0.6939100304841995, + "train samples": 13000, + "train time": 36.13155907928012, + "eval time": 12.18468267400749, + "tokens / sec": 5837.030157963555, + "mem allocated avg": 7293795069.952, + "mem reserved avg": 14881256374.272, + "elapsed time": 688.5670087640174 + }, + { + "step": 3500, + "valid accuracy": 0.36, + "train loss": 0.6824952847957612, + "train samples": 14000, + "train time": 35.909013247233815, + "eval time": 12.309029697033111, + "tokens / sec": 5841.151873371449, + "mem allocated avg": 7290872406.016, + "mem reserved avg": 14875896053.76, + "elapsed time": 740.3315773730283 + }, + { + "step": 3750, + "valid accuracy": 0.32, + "train loss": 0.6794799867868423, + "train samples": 15000, + "train time": 36.30529697693419, + "eval time": 12.151031351007987, + "tokens / sec": 5968.908617871319, + "mem allocated avg": 7301860868.096, + "mem reserved avg": 15216507092.992, + "elapsed time": 792.3454526530113 + }, + { + "step": 4000, + "valid accuracy": 0.3, + "train loss": 0.6966380437612534, + "train samples": 16000, + "train time": 35.68916123179952, + "eval time": 12.212951252993662, + "tokens / sec": 5726.472490418209, + "mem allocated avg": 7282899265.536, + "mem reserved avg": 14899249938.432, + "elapsed time": 843.872047640034 + }, + { + "step": 4250, + "valid accuracy": 0.32, + "train loss": 0.6774853245019913, + "train samples": 17000, + "train time": 36.08229462581221, + "eval time": 12.197503683972172, + "tokens / sec": 5858.524303739224, + "mem allocated avg": 7294883461.12, + "mem reserved avg": 14887791099.904, + "elapsed time": 895.6108071450144 + }, + { + "step": 4500, + "valid accuracy": 0.32, + "train loss": 0.6867766143083572, + "train samples": 18000, + "train time": 35.802349225094076, + "eval time": 12.20918653300032, + "tokens / sec": 5804.591165049559, + "mem allocated avg": 7287909275.648, + "mem reserved avg": 14847987154.944, + "elapsed time": 947.2645250619971 + }, + { + "step": 4750, + "valid accuracy": 0.32, + "train loss": 0.6804986503124237, + "train samples": 19000, + "train time": 32.32421511563007, + "eval time": 12.151784093992319, + "tokens / sec": 6494.790337491783, + "mem allocated avg": 7071402708.992, + "mem reserved avg": 14653581164.544, + "elapsed time": 995.2198103830451 + }, + { + "step": 5000, + "valid accuracy": 0.34, + "train loss": 0.6861251518726349, + "train samples": 20000, + "train time": 31.86748417984927, + "eval time": 12.234077127010096, + "tokens / sec": 6535.815592612781, + "mem allocated avg": 7067250501.632, + "mem reserved avg": 14337473249.28, + "elapsed time": 1042.8103677670006 + }, + { + "step": 5000, + "test accuracy": 0.38362395754359363, + "train loss": 0.6861251518726349, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.0754537582397461 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/adaptionprompt--llama-3.2-3B-lr_0.0005.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/adaptionprompt--llama-3.2-3B-lr_0.0005.json new file mode 100644 index 0000000000000000000000000000000000000000..2e673d84976140dc447c0a3503461c8d7e5f62e2 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/adaptionprompt--llama-3.2-3B-lr_0.0005.json @@ -0,0 +1,343 @@ +{ + "run_info": { + "created_at": "2026-01-09T17:25:16+00:00", + "total_time": 1466.8854283409892, + "experiment_name": "adaptionprompt/llama-3.2-3B-lr_0.0005", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0005 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "ADAPTION_PROMPT", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "target_modules": "self_attn", + "adapter_len": 100, + "adapter_layers": 28 + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14458868570, + "accelerator_memory_max": 22445817856, + "accelerator_memory_reserved_99th": 20222836736, + "train_time": 1180.5937879550038, + "file_size": 17210384, + "num_trainable_params": 8601628, + "num_total_params": 3221351452, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.3200566630363464, + "train samples": 1000, + "train time": 34.53835600853199, + "eval time": 14.21398706396576, + "tokens / sec": 6129.967504756138, + "mem allocated avg": 6848584845.312, + "mem reserved avg": 14547960201.216, + "elapsed time": 71.65906680002809 + }, + { + "step": 500, + "valid accuracy": 0.08, + "train loss": 1.1533236474990844, + "train samples": 2000, + "train time": 34.522620833537076, + "eval time": 14.150563488015905, + "tokens / sec": 6024.890201787426, + "mem allocated avg": 6841784819.712, + "mem reserved avg": 14164156219.392, + "elapsed time": 123.70079839800019 + }, + { + "step": 750, + "valid accuracy": 0.2, + "train loss": 0.9019568083286286, + "train samples": 3000, + "train time": 35.55624677182641, + "eval time": 14.130223647051025, + "tokens / sec": 6029.910900772695, + "mem allocated avg": 6852599943.168, + "mem reserved avg": 14414614888.448, + "elapsed time": 176.709548267012 + }, + { + "step": 1000, + "valid accuracy": 0.18, + "train loss": 0.8574914336204529, + "train samples": 4000, + "train time": 35.06597913411679, + "eval time": 14.383076103986241, + "tokens / sec": 5941.2571713220295, + "mem allocated avg": 6843962202.112, + "mem reserved avg": 14454611771.392, + "elapsed time": 229.6261993580265 + }, + { + "step": 1250, + "valid accuracy": 0.22, + "train loss": 0.8493955388069153, + "train samples": 5000, + "train time": 35.032775730942376, + "eval time": 14.193959789990913, + "tokens / sec": 5952.6542116333285, + "mem allocated avg": 6843453933.568, + "mem reserved avg": 14489709707.264, + "elapsed time": 282.2174852700555 + }, + { + "step": 1500, + "valid accuracy": 0.2, + "train loss": 0.8379271342754364, + "train samples": 6000, + "train time": 35.1143401027075, + "eval time": 14.287394939980004, + "tokens / sec": 5961.410619926743, + "mem allocated avg": 6845303027.712, + "mem reserved avg": 14413767639.04, + "elapsed time": 335.0856573909987 + }, + { + "step": 1750, + "valid accuracy": 0.24, + "train loss": 0.8321145892143249, + "train samples": 7000, + "train time": 34.62294518906856, + "eval time": 14.048951104981825, + "tokens / sec": 6046.712631081982, + "mem allocated avg": 6846216781.824, + "mem reserved avg": 14785382973.44, + "elapsed time": 387.15798614604864 + }, + { + "step": 2000, + "valid accuracy": 0.24, + "train loss": 0.836554151058197, + "train samples": 8000, + "train time": 34.390015198267065, + "eval time": 14.16389181703562, + "tokens / sec": 6039.427397824062, + "mem allocated avg": 6842828976.128, + "mem reserved avg": 14449343725.568, + "elapsed time": 439.18930962705053 + }, + { + "step": 2250, + "valid accuracy": 0.2, + "train loss": 0.8322268238067627, + "train samples": 9000, + "train time": 35.45279946445953, + "eval time": 14.172650399035774, + "tokens / sec": 6062.934471944297, + "mem allocated avg": 6854121762.816, + "mem reserved avg": 14755116875.776, + "elapsed time": 492.21291138301603 + }, + { + "step": 2500, + "valid accuracy": 0.24, + "train loss": 0.8304620375633239, + "train samples": 10000, + "train time": 35.034967973362654, + "eval time": 14.244871944014449, + "tokens / sec": 5878.897910127911, + "mem allocated avg": 6840198320.128, + "mem reserved avg": 14230501720.064, + "elapsed time": 544.8923244239995 + }, + { + "step": 2750, + "valid accuracy": 0.22, + "train loss": 0.8325318789482117, + "train samples": 11000, + "train time": 35.15703216131078, + "eval time": 14.128618655027822, + "tokens / sec": 6026.703250371868, + "mem allocated avg": 6849819580.416, + "mem reserved avg": 14618449674.24, + "elapsed time": 597.5583866710076 + }, + { + "step": 3000, + "valid accuracy": 0.16, + "train loss": 0.8273461208343506, + "train samples": 12000, + "train time": 35.226769833650906, + "eval time": 14.172337282972876, + "tokens / sec": 5925.3516852574585, + "mem allocated avg": 6844943210.496, + "mem reserved avg": 14524555984.896, + "elapsed time": 650.4424432980013 + }, + { + "step": 3250, + "valid accuracy": 0.16, + "train loss": 0.832145271062851, + "train samples": 13000, + "train time": 34.82297695695888, + "eval time": 14.088282125012483, + "tokens / sec": 6056.374797039126, + "mem allocated avg": 6846756392.96, + "mem reserved avg": 14383988080.64, + "elapsed time": 702.644515115011 + }, + { + "step": 3500, + "valid accuracy": 0.2, + "train loss": 0.8267167332172394, + "train samples": 14000, + "train time": 35.251085491792765, + "eval time": 14.197126877959818, + "tokens / sec": 5950.171379795793, + "mem allocated avg": 6845619677.184, + "mem reserved avg": 14408566702.08, + "elapsed time": 755.514794363 + }, + { + "step": 3750, + "valid accuracy": 0.24, + "train loss": 0.8225111892223358, + "train samples": 15000, + "train time": 35.429980689892545, + "eval time": 14.131252312974539, + "tokens / sec": 6116.373641203281, + "mem allocated avg": 6856933664.768, + "mem reserved avg": 14748112388.096, + "elapsed time": 808.5010599610396 + }, + { + "step": 4000, + "valid accuracy": 0.18, + "train loss": 0.8426167027950286, + "train samples": 16000, + "train time": 34.42210436682217, + "eval time": 14.11721703200601, + "tokens / sec": 5937.260483033845, + "mem allocated avg": 6838090446.848, + "mem reserved avg": 14423599087.616, + "elapsed time": 860.4732752880082 + }, + { + "step": 4250, + "valid accuracy": 0.22, + "train loss": 0.8195950338840484, + "train samples": 17000, + "train time": 35.29558803292457, + "eval time": 14.072754080989398, + "tokens / sec": 5989.105488278345, + "mem allocated avg": 6848445681.664, + "mem reserved avg": 14423037050.88, + "elapsed time": 913.1631882850197 + }, + { + "step": 4500, + "valid accuracy": 0.22, + "train loss": 0.8332238008975983, + "train samples": 18000, + "train time": 34.60890661936719, + "eval time": 14.16370828700019, + "tokens / sec": 6004.754853587451, + "mem allocated avg": 6843256502.272, + "mem reserved avg": 14372839620.608, + "elapsed time": 965.424148318998 + }, + { + "step": 4750, + "valid accuracy": 0.2, + "train loss": 0.8247757973670959, + "train samples": 19000, + "train time": 34.65050247934414, + "eval time": 14.110966334003024, + "tokens / sec": 6058.7577373560125, + "mem allocated avg": 6846388692.992, + "mem reserved avg": 14453437366.272, + "elapsed time": 1017.51672834903 + }, + { + "step": 5000, + "valid accuracy": 0.24, + "train loss": 0.8316655712127685, + "train samples": 20000, + "train time": 34.58433834684547, + "eval time": 14.152012452017516, + "tokens / sec": 6022.379202723645, + "mem allocated avg": 6842473314.304, + "mem reserved avg": 14115619733.504, + "elapsed time": 1069.6098215640523 + }, + { + "step": 5000, + "test accuracy": 0.21228203184230476, + "train loss": 0.8316655712127685, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": -0.9543380737304688 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/boft--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/boft--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..913c12e3abac6b4d00c71f29a1e4e501f30a173e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/boft--llama-3.2-3B-default.json @@ -0,0 +1,356 @@ +{ + "run_info": { + "created_at": "2026-01-09T17:49:47+00:00", + "total_time": 10059.440659368003, + "experiment_name": "boft/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "BOFT", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "boft_block_size": 4, + "boft_block_num": 0, + "boft_n_butterfly_factor": 1, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "boft_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "modules_to_save": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 17188165936, + "accelerator_memory_max": 24410849280, + "accelerator_memory_reserved_99th": 22345154560, + "train_time": 7190.453845723998, + "file_size": 3225360, + "num_trainable_params": 802816, + "num_total_params": 3213552640, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.2914534993171691, + "train samples": 1000, + "train time": 168.16101133066695, + "eval time": 142.30593162897276, + "tokens / sec": 1259.025491846513, + "mem allocated avg": 6795307169.792, + "mem reserved avg": 17261339344.896, + "elapsed time": 344.37489816197194 + }, + { + "step": 500, + "valid accuracy": 0.12, + "train loss": 1.065816521883011, + "train samples": 2000, + "train time": 169.6081039829878, + "eval time": 143.82841559901135, + "tokens / sec": 1226.3270157236266, + "mem allocated avg": 6787530438.656, + "mem reserved avg": 16960280592.384, + "elapsed time": 662.5959406199981 + }, + { + "step": 750, + "valid accuracy": 0.42, + "train loss": 0.8761289038658142, + "train samples": 3000, + "train time": 170.50346154812723, + "eval time": 143.55063587299082, + "tokens / sec": 1257.4583416271698, + "mem allocated avg": 6797964732.416, + "mem reserved avg": 17119546703.872, + "elapsed time": 981.3382467220072 + }, + { + "step": 1000, + "valid accuracy": 0.44, + "train loss": 0.8187025270462036, + "train samples": 4000, + "train time": 170.603982186527, + "eval time": 143.48508089897223, + "tokens / sec": 1221.1672748190563, + "mem allocated avg": 6789360863.232, + "mem reserved avg": 17173468676.096, + "elapsed time": 1300.2320007149829 + }, + { + "step": 1250, + "valid accuracy": 0.38, + "train loss": 0.7968714184761048, + "train samples": 5000, + "train time": 170.08946738566738, + "eval time": 143.52085828600684, + "tokens / sec": 1226.0488741913275, + "mem allocated avg": 6788928741.376, + "mem reserved avg": 17237641527.296, + "elapsed time": 1618.561195612012 + }, + { + "step": 1500, + "valid accuracy": 0.42, + "train loss": 0.7768479048013687, + "train samples": 6000, + "train time": 171.03791188867763, + "eval time": 142.4387985090143, + "tokens / sec": 1223.8865505809376, + "mem allocated avg": 6790983270.4, + "mem reserved avg": 17204464582.656, + "elapsed time": 1936.8438452039845 + }, + { + "step": 1750, + "valid accuracy": 0.34, + "train loss": 0.7638826340436935, + "train samples": 7000, + "train time": 169.5759706167737, + "eval time": 142.81106396700488, + "tokens / sec": 1234.5793996551745, + "mem allocated avg": 6792170039.296, + "mem reserved avg": 17521872732.16, + "elapsed time": 2253.9779722079984 + }, + { + "step": 2000, + "valid accuracy": 0.3, + "train loss": 0.7574314765930176, + "train samples": 8000, + "train time": 169.80084089771844, + "eval time": 142.94605548703112, + "tokens / sec": 1223.1741545090943, + "mem allocated avg": 6788512305.152, + "mem reserved avg": 17193743941.632, + "elapsed time": 2571.564919157012 + }, + { + "step": 2250, + "valid accuracy": 0.4, + "train loss": 0.747995015501976, + "train samples": 9000, + "train time": 169.89184381318046, + "eval time": 142.61838847299805, + "tokens / sec": 1265.2049396577568, + "mem allocated avg": 6799572060.16, + "mem reserved avg": 17437013573.632, + "elapsed time": 2888.81089515402 + }, + { + "step": 2500, + "valid accuracy": 0.3, + "train loss": 0.7451818664073944, + "train samples": 10000, + "train time": 169.05202275590273, + "eval time": 142.17101406800793, + "tokens / sec": 1218.3645995020095, + "mem allocated avg": 6785213417.472, + "mem reserved avg": 17006149500.928, + "elapsed time": 3204.817744602973 + }, + { + "step": 2750, + "valid accuracy": 0.26, + "train loss": 0.7368416948318481, + "train samples": 11000, + "train time": 169.79861720540794, + "eval time": 142.90656082698843, + "tokens / sec": 1247.837017092338, + "mem allocated avg": 6795389593.6, + "mem reserved avg": 17333305212.928, + "elapsed time": 3522.2434823570075 + }, + { + "step": 3000, + "valid accuracy": 0.42, + "train loss": 0.7283624488115311, + "train samples": 12000, + "train time": 169.40914075018372, + "eval time": 142.4628674259875, + "tokens / sec": 1232.1117920537804, + "mem allocated avg": 6790662739.968, + "mem reserved avg": 17229924007.936, + "elapsed time": 3838.9266921749804 + }, + { + "step": 3250, + "valid accuracy": 0.4, + "train loss": 0.7360379147529602, + "train samples": 13000, + "train time": 169.2894103731378, + "eval time": 142.70766545902006, + "tokens / sec": 1245.8014918661738, + "mem allocated avg": 6792828252.16, + "mem reserved avg": 17116644245.504, + "elapsed time": 4155.603474072996 + }, + { + "step": 3500, + "valid accuracy": 0.38, + "train loss": 0.7245079389810563, + "train samples": 14000, + "train time": 169.62816236459184, + "eval time": 142.80769011599477, + "tokens / sec": 1236.528162989657, + "mem allocated avg": 6790204116.992, + "mem reserved avg": 17182729699.328, + "elapsed time": 4472.8496758749825 + }, + { + "step": 3750, + "valid accuracy": 0.32, + "train loss": 0.7198032699823379, + "train samples": 15000, + "train time": 169.99743940570625, + "eval time": 143.21545482298825, + "tokens / sec": 1274.742729993885, + "mem allocated avg": 6802659770.368, + "mem reserved avg": 17454201831.424, + "elapsed time": 4790.820539581007 + }, + { + "step": 4000, + "valid accuracy": 0.36, + "train loss": 0.7386080088615418, + "train samples": 16000, + "train time": 169.4405590199167, + "eval time": 142.85203308903147, + "tokens / sec": 1206.1633954829977, + "mem allocated avg": 6782729986.048, + "mem reserved avg": 17107366445.056, + "elapsed time": 5107.90697863797 + }, + { + "step": 4250, + "valid accuracy": 0.4, + "train loss": 0.7167673094272613, + "train samples": 17000, + "train time": 169.4217613734072, + "eval time": 142.6639407540206, + "tokens / sec": 1247.7086667402577, + "mem allocated avg": 6793673689.088, + "mem reserved avg": 17128346353.664, + "elapsed time": 5424.600868158974 + }, + { + "step": 4500, + "valid accuracy": 0.36, + "train loss": 0.7279775400161743, + "train samples": 18000, + "train time": 169.55897833802737, + "eval time": 142.51284795097308, + "tokens / sec": 1225.6384299845254, + "mem allocated avg": 6789383653.376, + "mem reserved avg": 17117466329.088, + "elapsed time": 5741.48882275197 + }, + { + "step": 4750, + "valid accuracy": 0.4, + "train loss": 0.7207833558321, + "train samples": 19000, + "train time": 169.6458221563953, + "eval time": 142.71257099701324, + "tokens / sec": 1237.513528664789, + "mem allocated avg": 6791604719.616, + "mem reserved avg": 17139536756.736, + "elapsed time": 6058.54882254597 + }, + { + "step": 5000, + "valid accuracy": 0.36, + "train loss": 0.7267992464303971, + "train samples": 20000, + "train time": 169.51394822495058, + "eval time": 142.66391144797672, + "tokens / sec": 1228.6894511099795, + "mem allocated avg": 6788474263.552, + "mem reserved avg": 16838276677.632, + "elapsed time": 6375.395246869011 + }, + { + "step": 5000, + "test accuracy": 0.36239575435936316, + "train loss": 0.7267992464303971, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.3084230422973633 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/bone--llama-3.2-3B-bat.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/bone--llama-3.2-3B-bat.json new file mode 100644 index 0000000000000000000000000000000000000000..16c710e0bbc2805f2edcbb3dce5dc97f5dac3da8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/bone--llama-3.2-3B-bat.json @@ -0,0 +1,352 @@ +{ + "run_info": { + "created_at": "2026-01-09T20:37:31+00:00", + "total_time": 1743.6652406350477, + "experiment_name": "bone/llama-3.2-3B-bat", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "BONE", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 64, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "init_weights": "bat", + "layers_to_transform": null, + "layers_pattern": null, + "bias": "none", + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 17289858514, + "accelerator_memory_max": 25209864192, + "accelerator_memory_reserved_99th": 23320330240, + "train_time": 1432.8082630151184, + "file_size": 29367552, + "num_trainable_params": 7340032, + "num_total_params": 3220089856, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.38, + "train loss": 0.8741573710441589, + "train samples": 1000, + "train time": 47.08210420422256, + "eval time": 17.23298390500713, + "tokens / sec": 4496.804116520603, + "mem allocated avg": 6899156936.704, + "mem reserved avg": 17432425005.056, + "elapsed time": 92.3484000210301 + }, + { + "step": 500, + "valid accuracy": 0.44, + "train loss": 0.694805077791214, + "train samples": 2000, + "train time": 45.921670439012814, + "eval time": 10.156194142997265, + "tokens / sec": 4529.343075100717, + "mem allocated avg": 6892228743.168, + "mem reserved avg": 17057630388.224, + "elapsed time": 153.09530606598128 + }, + { + "step": 750, + "valid accuracy": 0.46, + "train loss": 0.6675743660926818, + "train samples": 3000, + "train time": 46.44820640789112, + "eval time": 9.883839346992318, + "tokens / sec": 4615.915588154449, + "mem allocated avg": 6902447476.736, + "mem reserved avg": 17196562513.92, + "elapsed time": 213.98306120501366 + }, + { + "step": 1000, + "valid accuracy": 0.38, + "train loss": 0.6475769439935685, + "train samples": 4000, + "train time": 46.272512987605296, + "eval time": 11.084571123996284, + "tokens / sec": 4502.370555405226, + "mem allocated avg": 6893826957.312, + "mem reserved avg": 17298584764.416, + "elapsed time": 276.0952120529837 + }, + { + "step": 1250, + "valid accuracy": 0.42, + "train loss": 0.6444406238794327, + "train samples": 5000, + "train time": 45.26340117654763, + "eval time": 8.693854385986924, + "tokens / sec": 4607.210120746516, + "mem allocated avg": 6894148816.896, + "mem reserved avg": 17275818082.304, + "elapsed time": 334.61537264700746 + }, + { + "step": 1500, + "valid accuracy": 0.52, + "train loss": 0.6367908464670181, + "train samples": 6000, + "train time": 45.64225660829106, + "eval time": 12.539341575000435, + "tokens / sec": 4586.342033798003, + "mem allocated avg": 6895285663.744, + "mem reserved avg": 17295631974.4, + "elapsed time": 397.52763449802296 + }, + { + "step": 1750, + "valid accuracy": 0.38, + "train loss": 0.6280897797346116, + "train samples": 7000, + "train time": 46.028662396303844, + "eval time": 17.17660208797315, + "tokens / sec": 4548.361588209252, + "mem allocated avg": 6897027553.28, + "mem reserved avg": 17636528226.304, + "elapsed time": 465.4344937889837 + }, + { + "step": 2000, + "valid accuracy": 0.4, + "train loss": 0.6281794626712799, + "train samples": 8000, + "train time": 46.304100580571685, + "eval time": 17.161395469971467, + "tokens / sec": 4485.477471667926, + "mem allocated avg": 6892820834.304, + "mem reserved avg": 17282487025.664, + "elapsed time": 533.6705477859941 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6160554866790772, + "train samples": 9000, + "train time": 47.66154300532071, + "eval time": 14.93811830598861, + "tokens / sec": 4509.883366050575, + "mem allocated avg": 6904737810.432, + "mem reserved avg": 17579468914.688, + "elapsed time": 600.9623893949902 + }, + { + "step": 2500, + "valid accuracy": 0.48, + "train loss": 0.6119242373704911, + "train samples": 10000, + "train time": 45.28331206360599, + "eval time": 17.183108089026064, + "tokens / sec": 4548.408466913683, + "mem allocated avg": 6890091653.12, + "mem reserved avg": 17013791522.816, + "elapsed time": 668.064512034005 + }, + { + "step": 2750, + "valid accuracy": 0.48, + "train loss": 0.6009454892873765, + "train samples": 11000, + "train time": 46.55525783565827, + "eval time": 17.103973756020423, + "tokens / sec": 4551.172302555977, + "mem allocated avg": 6899537018.88, + "mem reserved avg": 17462959538.176, + "elapsed time": 736.392622578016 + }, + { + "step": 3000, + "valid accuracy": 0.42, + "train loss": 0.5898327060937881, + "train samples": 12000, + "train time": 45.69055778736947, + "eval time": 17.16533613699721, + "tokens / sec": 4568.361825902261, + "mem allocated avg": 6895349350.4, + "mem reserved avg": 17354150903.808, + "elapsed time": 804.0024728610297 + }, + { + "step": 3250, + "valid accuracy": 0.5, + "train loss": 0.5984167819023132, + "train samples": 13000, + "train time": 46.50175124424277, + "eval time": 17.302273807988968, + "tokens / sec": 4535.334570353648, + "mem allocated avg": 6898310023.168, + "mem reserved avg": 17226862166.016, + "elapsed time": 872.4092298070318 + }, + { + "step": 3500, + "valid accuracy": 0.48, + "train loss": 0.5800097153186798, + "train samples": 14000, + "train time": 45.426418964751065, + "eval time": 17.125486647011712, + "tokens / sec": 4617.357141067116, + "mem allocated avg": 6895650811.904, + "mem reserved avg": 17232507699.2, + "elapsed time": 939.6246801590314 + }, + { + "step": 3750, + "valid accuracy": 0.42, + "train loss": 0.577217645406723, + "train samples": 15000, + "train time": 47.63793423282914, + "eval time": 17.120611401973292, + "tokens / sec": 4548.958797013947, + "mem allocated avg": 6907398975.488, + "mem reserved avg": 17587723304.96, + "elapsed time": 1009.0847758559976 + }, + { + "step": 4000, + "valid accuracy": 0.5, + "train loss": 0.5854997953176498, + "train samples": 16000, + "train time": 44.550334901490714, + "eval time": 17.11661865498172, + "tokens / sec": 4587.462708235699, + "mem allocated avg": 6887509987.328, + "mem reserved avg": 17280842858.496, + "elapsed time": 1075.4839722960023 + }, + { + "step": 4250, + "valid accuracy": 0.48, + "train loss": 0.5725951849222183, + "train samples": 17000, + "train time": 45.552318896050565, + "eval time": 17.120852815976832, + "tokens / sec": 4640.576048002853, + "mem allocated avg": 6898683543.552, + "mem reserved avg": 17244771844.096, + "elapsed time": 1142.6874302860233 + }, + { + "step": 4500, + "valid accuracy": 0.48, + "train loss": 0.5793783943653107, + "train samples": 18000, + "train time": 46.363164163019974, + "eval time": 17.14258968201466, + "tokens / sec": 4482.394671538814, + "mem allocated avg": 6894085709.824, + "mem reserved avg": 17169358258.176, + "elapsed time": 1210.9217723699985 + }, + { + "step": 4750, + "valid accuracy": 0.46, + "train loss": 0.5683046000003815, + "train samples": 19000, + "train time": 45.238315581926145, + "eval time": 17.115985165000893, + "tokens / sec": 4640.7342382101415, + "mem allocated avg": 6896364773.376, + "mem reserved avg": 17282084372.48, + "elapsed time": 1277.8335477730143 + }, + { + "step": 5000, + "valid accuracy": 0.46, + "train loss": 0.5765521181821823, + "train samples": 20000, + "train time": 44.84296027891105, + "eval time": 17.095471853972413, + "tokens / sec": 4644.653223260795, + "mem allocated avg": 6893230526.464, + "mem reserved avg": 16886980935.68, + "elapsed time": 1344.3281179019832 + }, + { + "step": 5000, + "test accuracy": 0.5064442759666414, + "train loss": 0.5765521181821823, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.3088569641113281 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/bone--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/bone--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..efa8bd2bb209869cbe61e6a1442c92d878168db0 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/bone--llama-3.2-3B-default.json @@ -0,0 +1,352 @@ +{ + "run_info": { + "created_at": "2026-01-09T21:06:39+00:00", + "total_time": 1113.975204212009, + "experiment_name": "bone/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "BONE", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 64, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "bias": "none", + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 13443749694, + "accelerator_memory_max": 20275265536, + "accelerator_memory_reserved_99th": 18498977792, + "train_time": 931.1479183980846, + "file_size": 29367496, + "num_trainable_params": 7340032, + "num_total_params": 3220089856, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.36, + "train loss": 0.8770946979522705, + "train samples": 1000, + "train time": 28.682230734440964, + "eval time": 8.853944770002272, + "tokens / sec": 7381.538833580775, + "mem allocated avg": 6897714161.664, + "mem reserved avg": 13519852404.736, + "elapsed time": 59.13298718299484 + }, + { + "step": 500, + "valid accuracy": 0.4, + "train loss": 0.6949568554162979, + "train samples": 2000, + "train time": 28.45853918744251, + "eval time": 6.328033077006694, + "tokens / sec": 7308.702622788837, + "mem allocated avg": 6890609534.976, + "mem reserved avg": 13203794821.12, + "elapsed time": 96.60603074397659 + }, + { + "step": 750, + "valid accuracy": 0.44, + "train loss": 0.6667997059822083, + "train samples": 3000, + "train time": 29.355493688082788, + "eval time": 6.721548973000608, + "tokens / sec": 7303.607368287546, + "mem allocated avg": 6900360769.536, + "mem reserved avg": 13417939206.144, + "elapsed time": 135.35112743999343 + }, + { + "step": 1000, + "valid accuracy": 0.42, + "train loss": 0.6474654762744904, + "train samples": 4000, + "train time": 29.110337335790973, + "eval time": 7.787894255015999, + "tokens / sec": 7156.770380116902, + "mem allocated avg": 6891688468.48, + "mem reserved avg": 13453288800.256, + "elapsed time": 175.05626158800442 + }, + { + "step": 1250, + "valid accuracy": 0.4, + "train loss": 0.6438281389474869, + "train samples": 5000, + "train time": 28.465142201224808, + "eval time": 6.192574144050013, + "tokens / sec": 7326.0831976812315, + "mem allocated avg": 6892015517.696, + "mem reserved avg": 13493218574.336, + "elapsed time": 212.38757716899272 + }, + { + "step": 1500, + "valid accuracy": 0.5, + "train loss": 0.6369395072460174, + "train samples": 6000, + "train time": 28.41225368680898, + "eval time": 7.941400229989085, + "tokens / sec": 7367.630963297592, + "mem allocated avg": 6894076573.696, + "mem reserved avg": 13404207054.848, + "elapsed time": 251.46505238697864 + }, + { + "step": 1750, + "valid accuracy": 0.46, + "train loss": 0.6280212769508362, + "train samples": 7000, + "train time": 28.603689649200533, + "eval time": 11.7747625039774, + "tokens / sec": 7319.1606596057245, + "mem allocated avg": 6895286140.928, + "mem reserved avg": 13746437095.424, + "elapsed time": 294.6126683760085 + }, + { + "step": 2000, + "valid accuracy": 0.48, + "train loss": 0.6282699835300446, + "train samples": 8000, + "train time": 28.49381335376529, + "eval time": 6.387318613997195, + "tokens / sec": 7289.161244279513, + "mem allocated avg": 6891065575.424, + "mem reserved avg": 13428383023.104, + "elapsed time": 332.2536138329888 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6164305354356766, + "train samples": 9000, + "train time": 29.641954794351477, + "eval time": 7.702494629949797, + "tokens / sec": 7251.478571209485, + "mem allocated avg": 6901582643.2, + "mem reserved avg": 13693672751.104, + "elapsed time": 372.30250247899676 + }, + { + "step": 2500, + "valid accuracy": 0.52, + "train loss": 0.6126096348762512, + "train samples": 10000, + "train time": 28.804422622197308, + "eval time": 9.238736133964267, + "tokens / sec": 7150.533885073516, + "mem allocated avg": 6888456951.808, + "mem reserved avg": 13231275900.928, + "elapsed time": 413.07279076898703 + }, + { + "step": 2750, + "valid accuracy": 0.46, + "train loss": 0.6011255930662155, + "train samples": 11000, + "train time": 28.807400498830248, + "eval time": 7.274331616004929, + "tokens / sec": 7355.089189967128, + "mem allocated avg": 6897535533.056, + "mem reserved avg": 13570335047.68, + "elapsed time": 451.849644197966 + }, + { + "step": 3000, + "valid accuracy": 0.5, + "train loss": 0.5905841100215912, + "train samples": 12000, + "train time": 28.54119487659773, + "eval time": 7.517624335014261, + "tokens / sec": 7313.323808007365, + "mem allocated avg": 6893574338.56, + "mem reserved avg": 13508544561.152, + "elapsed time": 490.6727877999656 + }, + { + "step": 3250, + "valid accuracy": 0.5, + "train loss": 0.5996895109415055, + "train samples": 13000, + "train time": 28.56189932534471, + "eval time": 11.817645783012267, + "tokens / sec": 7383.99773760335, + "mem allocated avg": 6896400535.552, + "mem reserved avg": 13368513527.808, + "elapsed time": 533.6943597999634 + }, + { + "step": 3500, + "valid accuracy": 0.48, + "train loss": 0.580611946105957, + "train samples": 14000, + "train time": 28.992627491941676, + "eval time": 6.298771312984172, + "tokens / sec": 7234.597832097099, + "mem allocated avg": 6893331273.728, + "mem reserved avg": 13393645797.376, + "elapsed time": 571.7360254359664 + }, + { + "step": 3750, + "valid accuracy": 0.46, + "train loss": 0.577835813999176, + "train samples": 15000, + "train time": 29.917891803139355, + "eval time": 8.922266290988773, + "tokens / sec": 7243.257694289169, + "mem allocated avg": 6904537260.032, + "mem reserved avg": 13701608374.272, + "elapsed time": 613.3215442419751 + }, + { + "step": 4000, + "valid accuracy": 0.46, + "train loss": 0.5866445735692978, + "train samples": 16000, + "train time": 28.4423630858073, + "eval time": 11.81282829795964, + "tokens / sec": 7185.514065179128, + "mem allocated avg": 6885427052.544, + "mem reserved avg": 13412377559.04, + "elapsed time": 656.3323608639766 + }, + { + "step": 4250, + "valid accuracy": 0.46, + "train loss": 0.5731088873147965, + "train samples": 17000, + "train time": 28.676882747968193, + "eval time": 11.7569903130061, + "tokens / sec": 7371.407898753475, + "mem allocated avg": 6897404037.12, + "mem reserved avg": 13391523479.552, + "elapsed time": 699.4078589889687 + }, + { + "step": 4500, + "valid accuracy": 0.42, + "train loss": 0.5799848650693893, + "train samples": 18000, + "train time": 28.678615707845893, + "eval time": 11.924760186986532, + "tokens / sec": 7246.444602385225, + "mem allocated avg": 6891705860.096, + "mem reserved avg": 13364461830.144, + "elapsed time": 742.7912658689893 + }, + { + "step": 4750, + "valid accuracy": 0.44, + "train loss": 0.5690632259845734, + "train samples": 19000, + "train time": 29.26655402261531, + "eval time": 11.802604599972256, + "tokens / sec": 7173.34196016971, + "mem allocated avg": 6894110355.456, + "mem reserved avg": 13432342446.08, + "elapsed time": 786.5075720959576 + }, + { + "step": 5000, + "valid accuracy": 0.42, + "train loss": 0.5775251245498657, + "train samples": 20000, + "train time": 28.85452529176837, + "eval time": 11.805582064029295, + "tokens / sec": 7218.278515897755, + "mem allocated avg": 6891173048.32, + "mem reserved avg": 13139571638.272, + "elapsed time": 829.8449935640092 + }, + { + "step": 5000, + "test accuracy": 0.49128127369219105, + "train loss": 0.5775251245498657, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.2672872543334961 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/c3a--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/c3a--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..2072a27d5dc677f8af5241753cca4d551f79d358 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/c3a--llama-3.2-3B-default.json @@ -0,0 +1,352 @@ +{ + "run_info": { + "created_at": "2026-01-09T21:25:18+00:00", + "total_time": 1366.5376071679639, + "experiment_name": "c3a/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.3, + "weight_decay": 1e-05 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "C3A", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "block_size": 64, + "target_modules": [ + "v_proj", + "q_proj" + ], + "bias": "none", + "modules_to_save": null, + "layers_to_transform": null, + "layers_pattern": null, + "block_size_pattern": {}, + "init_weights": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14377058251, + "accelerator_memory_max": 22166896640, + "accelerator_memory_reserved_99th": 20061356032, + "train_time": 1153.291345822101, + "file_size": 22027512, + "num_trainable_params": 5505024, + "num_total_params": 3218254848, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.38, + "train loss": 0.8909596583843231, + "train samples": 1000, + "train time": 37.80949870531913, + "eval time": 11.432839135988615, + "tokens / sec": 5599.624624756394, + "mem allocated avg": 6869184182.272, + "mem reserved avg": 14482872991.744, + "elapsed time": 72.47078875597799 + }, + { + "step": 500, + "valid accuracy": 0.42, + "train loss": 0.7013351047039031, + "train samples": 2000, + "train time": 37.42838709271746, + "eval time": 8.331702384981327, + "tokens / sec": 5557.1456895739475, + "mem allocated avg": 6862181789.696, + "mem reserved avg": 14091510874.112, + "elapsed time": 121.3354702090146 + }, + { + "step": 750, + "valid accuracy": 0.46, + "train loss": 0.674084732890129, + "train samples": 3000, + "train time": 38.329594842216466, + "eval time": 9.41572032001568, + "tokens / sec": 5593.615087312568, + "mem allocated avg": 6872815554.56, + "mem reserved avg": 14353973641.216, + "elapsed time": 172.14090229501016 + }, + { + "step": 1000, + "valid accuracy": 0.44, + "train loss": 0.6545811468362808, + "train samples": 4000, + "train time": 37.05278595397249, + "eval time": 13.860594167024828, + "tokens / sec": 5622.681119276645, + "mem allocated avg": 6864588425.216, + "mem reserved avg": 14391965646.848, + "elapsed time": 226.19000285398215 + }, + { + "step": 1250, + "valid accuracy": 0.38, + "train loss": 0.6509714391231537, + "train samples": 5000, + "train time": 36.79460979660507, + "eval time": 8.696108918986283, + "tokens / sec": 5667.62363163425, + "mem allocated avg": 6863943450.624, + "mem reserved avg": 14405840404.48, + "elapsed time": 274.7266224689665 + }, + { + "step": 1500, + "valid accuracy": 0.52, + "train loss": 0.6443188463449478, + "train samples": 6000, + "train time": 37.157257698476315, + "eval time": 9.571486864006147, + "tokens / sec": 5633.650408183485, + "mem allocated avg": 6865824692.224, + "mem reserved avg": 14339352297.472, + "elapsed time": 324.5449085899745 + }, + { + "step": 1750, + "valid accuracy": 0.46, + "train loss": 0.6351410290002822, + "train samples": 7000, + "train time": 37.588308651640546, + "eval time": 13.673957422957756, + "tokens / sec": 5569.6839658376775, + "mem allocated avg": 6866604124.16, + "mem reserved avg": 14722149646.336, + "elapsed time": 378.88215018698247 + }, + { + "step": 2000, + "valid accuracy": 0.42, + "train loss": 0.6367183820009231, + "train samples": 8000, + "train time": 37.49864329502452, + "eval time": 9.148618383973371, + "tokens / sec": 5538.760385700621, + "mem allocated avg": 6862256517.12, + "mem reserved avg": 14371757490.176, + "elapsed time": 428.6968064419925 + }, + { + "step": 2250, + "valid accuracy": 0.4, + "train loss": 0.6258963789939881, + "train samples": 9000, + "train time": 38.2491970359697, + "eval time": 13.646375201002229, + "tokens / sec": 5619.673526685071, + "mem allocated avg": 6874371139.584, + "mem reserved avg": 14650997473.28, + "elapsed time": 483.6756669579772 + }, + { + "step": 2500, + "valid accuracy": 0.48, + "train loss": 0.6206584950685501, + "train samples": 10000, + "train time": 37.62900273769628, + "eval time": 13.673765863000881, + "tokens / sec": 5473.623668311165, + "mem allocated avg": 6859448377.344, + "mem reserved avg": 14140047360.0, + "elapsed time": 538.0801370120025 + }, + { + "step": 2750, + "valid accuracy": 0.5, + "train loss": 0.6105827242136002, + "train samples": 11000, + "train time": 37.365518155740574, + "eval time": 9.94396861596033, + "tokens / sec": 5670.495431560023, + "mem allocated avg": 6870005147.648, + "mem reserved avg": 14540318179.328, + "elapsed time": 588.4858504809672 + }, + { + "step": 3000, + "valid accuracy": 0.48, + "train loss": 0.5981686524152756, + "train samples": 12000, + "train time": 36.890319129568525, + "eval time": 9.116078838997055, + "tokens / sec": 5658.151106442905, + "mem allocated avg": 6865474818.048, + "mem reserved avg": 14431375327.232, + "elapsed time": 637.5967296099989 + }, + { + "step": 3250, + "valid accuracy": 0.58, + "train loss": 0.6065964109897614, + "train samples": 13000, + "train time": 36.91873880266212, + "eval time": 13.868325658957474, + "tokens / sec": 5712.573257914012, + "mem allocated avg": 6867266957.312, + "mem reserved avg": 14327809572.864, + "elapsed time": 691.4201774260146 + }, + { + "step": 3500, + "valid accuracy": 0.54, + "train loss": 0.5876260681152343, + "train samples": 14000, + "train time": 37.31881154741859, + "eval time": 13.723029766988475, + "tokens / sec": 5620.4898093682405, + "mem allocated avg": 6864456710.144, + "mem reserved avg": 14320821862.4, + "elapsed time": 745.5659840449807 + }, + { + "step": 3750, + "valid accuracy": 0.52, + "train loss": 0.5839207136631012, + "train samples": 15000, + "train time": 38.572791439597495, + "eval time": 8.601323624025099, + "tokens / sec": 5618.027420684421, + "mem allocated avg": 6877443866.624, + "mem reserved avg": 14659335749.632, + "elapsed time": 795.8486898440169 + }, + { + "step": 4000, + "valid accuracy": 0.56, + "train loss": 0.5916516542434692, + "train samples": 16000, + "train time": 36.93544478120748, + "eval time": 8.182845938019454, + "tokens / sec": 5533.248650737345, + "mem allocated avg": 6857094844.416, + "mem reserved avg": 14323103563.776, + "elapsed time": 844.0624020369723 + }, + { + "step": 4250, + "valid accuracy": 0.56, + "train loss": 0.5781249686479568, + "train samples": 17000, + "train time": 37.122223554353695, + "eval time": 9.616572241007816, + "tokens / sec": 5694.405662163205, + "mem allocated avg": 6869011593.216, + "mem reserved avg": 14312148041.728, + "elapsed time": 893.7695867909933 + }, + { + "step": 4500, + "valid accuracy": 0.56, + "train loss": 0.5846204442977905, + "train samples": 18000, + "train time": 37.07799867092399, + "eval time": 8.460158887959551, + "tokens / sec": 5604.887195893012, + "mem allocated avg": 6863795603.456, + "mem reserved avg": 14295052058.624, + "elapsed time": 942.4601713569718 + }, + { + "step": 4750, + "valid accuracy": 0.52, + "train loss": 0.5748073060512543, + "train samples": 19000, + "train time": 37.64343991095666, + "eval time": 8.636093506007455, + "tokens / sec": 5577.040793737192, + "mem allocated avg": 6865605898.24, + "mem reserved avg": 14353235443.712, + "elapsed time": 991.785048523976 + }, + { + "step": 5000, + "valid accuracy": 0.5, + "train loss": 0.5811544748544692, + "train samples": 20000, + "train time": 37.4456382485223, + "eval time": 8.431857075018343, + "tokens / sec": 5562.1965532452705, + "mem allocated avg": 6862668220.416, + "mem reserved avg": 14027497406.464, + "elapsed time": 1040.7068556279992 + }, + { + "step": 5000, + "test accuracy": 0.5026535253980288, + "train loss": 0.5811544748544692, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.4295167922973633 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/delora--llama-3.2-3B-rank32.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/delora--llama-3.2-3B-rank32.json new file mode 100644 index 0000000000000000000000000000000000000000..5320f2eaaa02eb52a9264e6722c4e1ab4bcad546 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/delora--llama-3.2-3B-rank32.json @@ -0,0 +1,355 @@ +{ + "run_info": { + "created_at": "2026-01-09T21:48:09+00:00", + "total_time": 1277.7959856730304, + "experiment_name": "delora/llama-3.2-3B-rank32", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.001 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "DELORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "delora_lambda": 15, + "module_dropout": 0.0, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "bias": "none", + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "lambda_pattern": {}, + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14449004406, + "accelerator_memory_max": 22353543168, + "accelerator_memory_reserved_99th": 20126367744, + "train_time": 1058.4298028770136, + "file_size": 37417520, + "num_trainable_params": 9175096, + "num_total_params": 3221924920, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.36, + "train loss": 0.7511726866960525, + "train samples": 1000, + "train time": 33.47864836757071, + "eval time": 13.131931535026524, + "tokens / sec": 6324.000828094447, + "mem allocated avg": 6927743098.88, + "mem reserved avg": 14590045847.552, + "elapsed time": 69.13025180797558 + }, + { + "step": 500, + "valid accuracy": 0.46, + "train loss": 0.7057771706581115, + "train samples": 2000, + "train time": 33.688454272574745, + "eval time": 13.079983315023128, + "tokens / sec": 6174.073714308867, + "mem allocated avg": 6921407948.8, + "mem reserved avg": 14192392273.92, + "elapsed time": 119.17276985396165 + }, + { + "step": 750, + "valid accuracy": 0.38, + "train loss": 0.6696414754390717, + "train samples": 3000, + "train time": 33.589053718489595, + "eval time": 11.759635296999477, + "tokens / sec": 6383.061630640097, + "mem allocated avg": 6930950647.808, + "mem reserved avg": 14421644541.952, + "elapsed time": 167.67709576297784 + }, + { + "step": 1000, + "valid accuracy": 0.36, + "train loss": 0.6491379799842835, + "train samples": 4000, + "train time": 33.53858558466891, + "eval time": 9.152838472975418, + "tokens / sec": 6211.830235775778, + "mem allocated avg": 6922103914.496, + "mem reserved avg": 14461423321.088, + "elapsed time": 213.7067174440017 + }, + { + "step": 1250, + "valid accuracy": 0.36, + "train loss": 0.6447645363807678, + "train samples": 5000, + "train time": 33.239838396781124, + "eval time": 13.123246687988285, + "tokens / sec": 6273.736878943261, + "mem allocated avg": 6922382727.168, + "mem reserved avg": 14487830659.072, + "elapsed time": 263.2440371370176 + }, + { + "step": 1500, + "valid accuracy": 0.46, + "train loss": 0.6379029039144516, + "train samples": 6000, + "train time": 33.83518080448266, + "eval time": 9.2000446600141, + "tokens / sec": 6186.78532293425, + "mem allocated avg": 6924438607.872, + "mem reserved avg": 14402577235.968, + "elapsed time": 309.58903181599453 + }, + { + "step": 1750, + "valid accuracy": 0.5, + "train loss": 0.6294291808605194, + "train samples": 7000, + "train time": 33.638763133611064, + "eval time": 13.089110154949594, + "tokens / sec": 6223.623596636268, + "mem allocated avg": 6925751805.952, + "mem reserved avg": 14803384926.208, + "elapsed time": 359.6268992089899 + }, + { + "step": 2000, + "valid accuracy": 0.42, + "train loss": 0.6335482016801834, + "train samples": 8000, + "train time": 33.628849623783026, + "eval time": 9.815332075988408, + "tokens / sec": 6176.125627952288, + "mem allocated avg": 6921476399.104, + "mem reserved avg": 14434068070.4, + "elapsed time": 406.38412045896985 + }, + { + "step": 2250, + "valid accuracy": 0.42, + "train loss": 0.6242709509134292, + "train samples": 9000, + "train time": 33.97552239638753, + "eval time": 13.092339784023352, + "tokens / sec": 6326.55467345675, + "mem allocated avg": 6932143722.496, + "mem reserved avg": 14720891355.136, + "elapsed time": 456.67317382100737 + }, + { + "step": 2500, + "valid accuracy": 0.46, + "train loss": 0.6215527185201645, + "train samples": 10000, + "train time": 33.24377211777028, + "eval time": 13.087968986015767, + "tokens / sec": 6195.656716401972, + "mem allocated avg": 6919181907.968, + "mem reserved avg": 14204631252.992, + "elapsed time": 506.2042880220106 + }, + { + "step": 2750, + "valid accuracy": 0.44, + "train loss": 0.6135006090402603, + "train samples": 11000, + "train time": 33.8344249399961, + "eval time": 11.559464724035934, + "tokens / sec": 6262.290562814704, + "mem allocated avg": 6928519376.896, + "mem reserved avg": 14587529265.152, + "elapsed time": 554.7988454389852 + }, + { + "step": 3000, + "valid accuracy": 0.5, + "train loss": 0.6046421718597412, + "train samples": 12000, + "train time": 33.518839641998056, + "eval time": 13.07255553000141, + "tokens / sec": 6227.274041386164, + "mem allocated avg": 6924324909.056, + "mem reserved avg": 14517383725.056, + "elapsed time": 604.7252621700172 + }, + { + "step": 3250, + "valid accuracy": 0.5, + "train loss": 0.6123787004947663, + "train samples": 13000, + "train time": 33.85599415731849, + "eval time": 12.407609467976727, + "tokens / sec": 6229.354808487008, + "mem allocated avg": 6927248498.688, + "mem reserved avg": 14381471498.24, + "elapsed time": 654.1598190389923 + }, + { + "step": 3500, + "valid accuracy": 0.46, + "train loss": 0.5954382091760635, + "train samples": 14000, + "train time": 33.584031070175115, + "eval time": 8.71236887795385, + "tokens / sec": 6245.52780938415, + "mem allocated avg": 6924072755.2, + "mem reserved avg": 14376438333.44, + "elapsed time": 699.7364873759798 + }, + { + "step": 3750, + "valid accuracy": 0.52, + "train loss": 0.5923196750879288, + "train samples": 15000, + "train time": 34.014798398071434, + "eval time": 8.587440980016254, + "tokens / sec": 6370.844755977933, + "mem allocated avg": 6935308263.424, + "mem reserved avg": 14727753236.48, + "elapsed time": 745.567757465993 + }, + { + "step": 4000, + "valid accuracy": 0.5, + "train loss": 0.6026594350337983, + "train samples": 16000, + "train time": 33.61519722332014, + "eval time": 10.390929970017169, + "tokens / sec": 6079.779887717532, + "mem allocated avg": 6916062009.344, + "mem reserved avg": 14388383711.232, + "elapsed time": 792.880163897993 + }, + { + "step": 4250, + "valid accuracy": 0.46, + "train loss": 0.5877031481266022, + "train samples": 17000, + "train time": 33.592281938006636, + "eval time": 8.453822323994245, + "tokens / sec": 6292.784764968063, + "mem allocated avg": 6928201375.744, + "mem reserved avg": 14382436188.16, + "elapsed time": 838.0397840199876 + }, + { + "step": 4500, + "valid accuracy": 0.5, + "train loss": 0.5929731521606445, + "train samples": 18000, + "train time": 33.91169841529336, + "eval time": 8.1252419599914, + "tokens / sec": 6128.20972441413, + "mem allocated avg": 6921858213.888, + "mem reserved avg": 14347757682.688, + "elapsed time": 883.4076476009795 + }, + { + "step": 4750, + "valid accuracy": 0.52, + "train loss": 0.583827891588211, + "train samples": 19000, + "train time": 33.430834216298535, + "eval time": 8.106015269993804, + "tokens / sec": 6279.801414517154, + "mem allocated avg": 6925002395.648, + "mem reserved avg": 14434042904.576, + "elapsed time": 928.1137036280124 + }, + { + "step": 5000, + "valid accuracy": 0.5, + "train loss": 0.591714503645897, + "train samples": 20000, + "train time": 33.46077763434732, + "eval time": 8.106805060000625, + "tokens / sec": 6224.601301142554, + "mem allocated avg": 6921049147.392, + "mem reserved avg": 14118002098.176, + "elapsed time": 972.8581771000172 + }, + { + "step": 5000, + "test accuracy": 0.5026535253980288, + "train loss": 0.591714503645897, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.515233039855957 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/fourierft--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/fourierft--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..857526394e0c79463de043700c8bc1e7bc740f63 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/fourierft--llama-3.2-3B-default.json @@ -0,0 +1,356 @@ +{ + "run_info": { + "created_at": "2026-01-09T22:09:31+00:00", + "total_time": 2139.03748531203, + "experiment_name": "fourierft/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "FOURIERFT", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "n_frequency": 1000, + "scaling": 300, + "random_loc_seed": 777, + "fan_in_fan_out": false, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "bias": "none", + "modules_to_save": null, + "layers_to_transform": null, + "layers_pattern": null, + "n_frequency_pattern": {}, + "init_weights": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 15762228825, + "accelerator_memory_max": 23651680256, + "accelerator_memory_reserved_99th": 21596471296, + "train_time": 1726.894935239805, + "file_size": 231416, + "num_trainable_params": 56000, + "num_total_params": 3212805824, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.3261459288597106, + "train samples": 1000, + "train time": 54.26436190091772, + "eval time": 20.152891070989426, + "tokens / sec": 3901.62148016375, + "mem allocated avg": 6780939091.968, + "mem reserved avg": 15867958001.664, + "elapsed time": 99.62701734097209 + }, + { + "step": 500, + "valid accuracy": 0.0, + "train loss": 1.3400139141082763, + "train samples": 2000, + "train time": 53.535696760285646, + "eval time": 20.12735749600688, + "tokens / sec": 3885.16471414073, + "mem allocated avg": 6773629601.792, + "mem reserved avg": 15486259560.448, + "elapsed time": 176.75905558397062 + }, + { + "step": 750, + "valid accuracy": 0.0, + "train loss": 1.3044390759468079, + "train samples": 3000, + "train time": 53.646198650298174, + "eval time": 20.156346999981906, + "tokens / sec": 3996.573949211373, + "mem allocated avg": 6783680942.08, + "mem reserved avg": 15731836059.648, + "elapsed time": 253.90234332997352 + }, + { + "step": 1000, + "valid accuracy": 0.0, + "train loss": 1.311077395439148, + "train samples": 4000, + "train time": 52.92571030347608, + "eval time": 20.228597007051576, + "tokens / sec": 3936.3855261535678, + "mem allocated avg": 6776640890.88, + "mem reserved avg": 15724596690.944, + "elapsed time": 330.55366935697384 + }, + { + "step": 1250, + "valid accuracy": 0.0, + "train loss": 1.2998026401996612, + "train samples": 5000, + "train time": 53.52640636928845, + "eval time": 20.14151435403619, + "tokens / sec": 3895.9835741868837, + "mem allocated avg": 6775686537.216, + "mem reserved avg": 15805932634.112, + "elapsed time": 407.61837184696924 + }, + { + "step": 1500, + "valid accuracy": 0.0, + "train loss": 1.2868368306159974, + "train samples": 6000, + "train time": 53.88665995717747, + "eval time": 20.14792396198027, + "tokens / sec": 3884.6534590629794, + "mem allocated avg": 6777282525.184, + "mem reserved avg": 15735241834.496, + "elapsed time": 485.17054163996363 + }, + { + "step": 1750, + "valid accuracy": 0.0, + "train loss": 1.2805588779449464, + "train samples": 7000, + "train time": 53.43724203767488, + "eval time": 20.139051661011763, + "tokens / sec": 3917.773298487193, + "mem allocated avg": 6777839691.776, + "mem reserved avg": 16100456660.992, + "elapsed time": 562.2017202629941 + }, + { + "step": 2000, + "valid accuracy": 0.0, + "train loss": 1.2766080429553985, + "train samples": 8000, + "train time": 53.74037380289519, + "eval time": 20.10542684403481, + "tokens / sec": 3864.8037834975135, + "mem allocated avg": 6774405505.024, + "mem reserved avg": 15730795872.256, + "elapsed time": 639.6445371389855 + }, + { + "step": 2250, + "valid accuracy": 0.0, + "train loss": 1.2596942813396454, + "train samples": 9000, + "train time": 55.60716101707658, + "eval time": 20.199656157987192, + "tokens / sec": 3865.473368330941, + "mem allocated avg": 6785559302.144, + "mem reserved avg": 16046719238.144, + "elapsed time": 718.9049943919526 + }, + { + "step": 2500, + "valid accuracy": 0.0, + "train loss": 1.2683517651557923, + "train samples": 10000, + "train time": 53.73305493139196, + "eval time": 20.08102407801198, + "tokens / sec": 3833.152614586777, + "mem allocated avg": 6771125086.208, + "mem reserved avg": 15553687191.552, + "elapsed time": 796.1963960899739 + }, + { + "step": 2750, + "valid accuracy": 0.0, + "train loss": 1.254921770811081, + "train samples": 11000, + "train time": 55.10060942819109, + "eval time": 20.137201737961732, + "tokens / sec": 3845.347668543126, + "mem allocated avg": 6781653977.088, + "mem reserved avg": 15920974004.224, + "elapsed time": 874.8866917559644 + }, + { + "step": 3000, + "valid accuracy": 0.0, + "train loss": 1.2537723093032838, + "train samples": 12000, + "train time": 53.60143480350962, + "eval time": 20.126665371004492, + "tokens / sec": 3894.130833720389, + "mem allocated avg": 6776695320.576, + "mem reserved avg": 15812299587.584, + "elapsed time": 952.1623955519754 + }, + { + "step": 3250, + "valid accuracy": 0.0, + "train loss": 1.2485535402297974, + "train samples": 13000, + "train time": 54.74126313335728, + "eval time": 20.236808118002955, + "tokens / sec": 3852.6878615536516, + "mem allocated avg": 6778833948.672, + "mem reserved avg": 15685539332.096, + "elapsed time": 1030.4662453850033 + }, + { + "step": 3500, + "valid accuracy": 0.0, + "train loss": 1.247687777519226, + "train samples": 14000, + "train time": 53.67239992291434, + "eval time": 20.154386248032097, + "tokens / sec": 3907.9676016210988, + "mem allocated avg": 6776816490.496, + "mem reserved avg": 15717592203.264, + "elapsed time": 1107.7825586889521 + }, + { + "step": 3750, + "valid accuracy": 0.0, + "train loss": 1.2286142303943635, + "train samples": 15000, + "train time": 55.43350543506676, + "eval time": 20.094228011963423, + "tokens / sec": 3909.2422227174457, + "mem allocated avg": 6788307730.432, + "mem reserved avg": 16017065508.864, + "elapsed time": 1186.77993246197 + }, + { + "step": 4000, + "valid accuracy": 0.0, + "train loss": 1.2608506062030793, + "train samples": 16000, + "train time": 53.14804647688288, + "eval time": 20.161071109992918, + "tokens / sec": 3845.353000676958, + "mem allocated avg": 6769206956.032, + "mem reserved avg": 15759719792.64, + "elapsed time": 1263.6211953659658 + }, + { + "step": 4250, + "valid accuracy": 0.0, + "train loss": 1.2272750456333161, + "train samples": 17000, + "train time": 54.87057439738419, + "eval time": 20.140905109001324, + "tokens / sec": 3852.502043610417, + "mem allocated avg": 6780253456.384, + "mem reserved avg": 15731970277.376, + "elapsed time": 1341.9455141729559 + }, + { + "step": 4500, + "valid accuracy": 0.0, + "train loss": 1.2504476809501648, + "train samples": 18000, + "train time": 53.83008128858637, + "eval time": 20.128594986046664, + "tokens / sec": 3860.629503527497, + "mem allocated avg": 6775227097.088, + "mem reserved avg": 15675707883.52, + "elapsed time": 1419.423019112961 + }, + { + "step": 4750, + "valid accuracy": 0.0, + "train loss": 1.234989553451538, + "train samples": 19000, + "train time": 53.29879065020941, + "eval time": 20.26173467701301, + "tokens / sec": 3938.9073830547627, + "mem allocated avg": 6777659713.536, + "mem reserved avg": 15754426580.992, + "elapsed time": 1496.3555859409971 + }, + { + "step": 5000, + "valid accuracy": 0.0, + "train loss": 1.2481540043354034, + "train samples": 20000, + "train time": 53.355687880772166, + "eval time": 20.13233814504929, + "tokens / sec": 3903.6138089985725, + "mem allocated avg": 6774096742.4, + "mem reserved avg": 15385797591.04, + "elapsed time": 1573.2050500559853 + }, + { + "step": 5000, + "test accuracy": 0.000758150113722517, + "train loss": 1.2481540043354034, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": -0.012529373168945312 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/fourierft--llama-3.2-3B-n_frequency-5000.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/fourierft--llama-3.2-3B-n_frequency-5000.json new file mode 100644 index 0000000000000000000000000000000000000000..11949352d05d67d6aa55e1992bf94dc70540d32e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/fourierft--llama-3.2-3B-n_frequency-5000.json @@ -0,0 +1,356 @@ +{ + "run_info": { + "created_at": "2026-01-09T22:45:14+00:00", + "total_time": 2150.229806937976, + "experiment_name": "fourierft/llama-3.2-3B-n_frequency-5000", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "FOURIERFT", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "n_frequency": 5000, + "scaling": 300, + "random_loc_seed": 777, + "fan_in_fan_out": false, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "bias": "none", + "modules_to_save": null, + "layers_to_transform": null, + "layers_pattern": null, + "n_frequency_pattern": {}, + "init_weights": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 15765951270, + "accelerator_memory_max": 23674748928, + "accelerator_memory_reserved_99th": 21602762752, + "train_time": 1735.5117494451115, + "file_size": 1127472, + "num_trainable_params": 280000, + "num_total_params": 3213029824, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.3799961261749267, + "train samples": 1000, + "train time": 54.63538205990335, + "eval time": 20.25719825399574, + "tokens / sec": 3875.126191446176, + "mem allocated avg": 6784255385.6, + "mem reserved avg": 15879072907.264, + "elapsed time": 99.3786606270005 + }, + { + "step": 500, + "valid accuracy": 0.0, + "train loss": 1.370254718542099, + "train samples": 2000, + "train time": 54.05832158756675, + "eval time": 20.27056284097489, + "tokens / sec": 3847.6037341092406, + "mem allocated avg": 6777261156.352, + "mem reserved avg": 15501593935.872, + "elapsed time": 177.16174678102834 + }, + { + "step": 750, + "valid accuracy": 0.0, + "train loss": 1.3024464647769929, + "train samples": 3000, + "train time": 54.38698652503081, + "eval time": 20.305425599042792, + "tokens / sec": 3942.1378844243395, + "mem allocated avg": 6787271151.616, + "mem reserved avg": 15726962278.4, + "elapsed time": 255.17251890699845 + }, + { + "step": 1000, + "valid accuracy": 0.0, + "train loss": 1.2703465101718903, + "train samples": 4000, + "train time": 54.011514401237946, + "eval time": 20.39393692498561, + "tokens / sec": 3857.251593656943, + "mem allocated avg": 6780041570.304, + "mem reserved avg": 15735644487.68, + "elapsed time": 333.0673065180308 + }, + { + "step": 1250, + "valid accuracy": 0.0, + "train loss": 1.2236051378250121, + "train samples": 5000, + "train time": 54.131226874596905, + "eval time": 20.295763457019348, + "tokens / sec": 3852.452863909948, + "mem allocated avg": 6779091253.248, + "mem reserved avg": 15815420149.76, + "elapsed time": 410.88266454002587 + }, + { + "step": 1500, + "valid accuracy": 0.0, + "train loss": 1.1791759724617004, + "train samples": 6000, + "train time": 54.805071563867386, + "eval time": 20.344787555979565, + "tokens / sec": 3819.5552715601325, + "mem allocated avg": 6781132302.336, + "mem reserved avg": 15728438673.408, + "elapsed time": 489.5477928170003 + }, + { + "step": 1750, + "valid accuracy": 0.0, + "train loss": 1.1484073193073272, + "train samples": 7000, + "train time": 54.526441418449394, + "eval time": 20.204474157013465, + "tokens / sec": 3839.5133545092, + "mem allocated avg": 6781927921.664, + "mem reserved avg": 16101270355.968, + "elapsed time": 567.73078815802 + }, + { + "step": 2000, + "valid accuracy": 0.06, + "train loss": 1.1230360004901887, + "train samples": 8000, + "train time": 53.57974702503998, + "eval time": 20.231831898970995, + "tokens / sec": 3876.390082673128, + "mem allocated avg": 6778186371.072, + "mem reserved avg": 15751582842.88, + "elapsed time": 645.0985403700033 + }, + { + "step": 2250, + "valid accuracy": 0.06, + "train loss": 1.0939874126911164, + "train samples": 9000, + "train time": 55.8729160525254, + "eval time": 20.28473745501833, + "tokens / sec": 3847.087554870596, + "mem allocated avg": 6789467377.664, + "mem reserved avg": 16052515766.272, + "elapsed time": 724.6561014120234 + }, + { + "step": 2500, + "valid accuracy": 0.08, + "train loss": 1.077495297908783, + "train samples": 10000, + "train time": 52.74528944323538, + "eval time": 20.17585710203275, + "tokens / sec": 3904.93638719458, + "mem allocated avg": 6774599432.192, + "mem reserved avg": 15540391247.872, + "elapsed time": 801.0244456710061 + }, + { + "step": 2750, + "valid accuracy": 0.08, + "train loss": 1.0567093884944916, + "train samples": 11000, + "train time": 53.79716244636802, + "eval time": 20.35781637695618, + "tokens / sec": 3938.516277902769, + "mem allocated avg": 6785299869.696, + "mem reserved avg": 15918188986.368, + "elapsed time": 878.562464024988 + }, + { + "step": 3000, + "valid accuracy": 0.12, + "train loss": 1.0359035170078277, + "train samples": 12000, + "train time": 53.633092043863144, + "eval time": 20.22181941999588, + "tokens / sec": 3891.8323006492337, + "mem allocated avg": 6780504604.672, + "mem reserved avg": 15821015351.296, + "elapsed time": 955.9252954589901 + }, + { + "step": 3250, + "valid accuracy": 0.1, + "train loss": 1.0238903017044068, + "train samples": 13000, + "train time": 54.95394577109255, + "eval time": 20.251423412002623, + "tokens / sec": 3837.7771976282793, + "mem allocated avg": 6782707699.712, + "mem reserved avg": 15711476908.032, + "elapsed time": 1034.4340154950041 + }, + { + "step": 3500, + "valid accuracy": 0.22, + "train loss": 1.0096496410369873, + "train samples": 14000, + "train time": 54.10011919972021, + "eval time": 20.23786943597952, + "tokens / sec": 3877.0709400042274, + "mem allocated avg": 6780696848.384, + "mem reserved avg": 15717843861.504, + "elapsed time": 1112.2632181590307 + }, + { + "step": 3750, + "valid accuracy": 0.26, + "train loss": 0.9940191543102265, + "train samples": 15000, + "train time": 55.7427657317603, + "eval time": 20.346782680018805, + "tokens / sec": 3887.5537866706554, + "mem allocated avg": 6792103485.44, + "mem reserved avg": 16009381543.936, + "elapsed time": 1191.7781133620301 + }, + { + "step": 4000, + "valid accuracy": 0.16, + "train loss": 1.0120926787853242, + "train samples": 16000, + "train time": 53.314123046409804, + "eval time": 20.31927741097752, + "tokens / sec": 3833.3745042020823, + "mem allocated avg": 6772785229.824, + "mem reserved avg": 15762924240.896, + "elapsed time": 1268.9340723860078 + }, + { + "step": 4250, + "valid accuracy": 0.16, + "train loss": 0.9847111780643463, + "train samples": 17000, + "train time": 54.80445172073087, + "eval time": 20.269200723967515, + "tokens / sec": 3857.1501650483247, + "mem allocated avg": 6784316258.304, + "mem reserved avg": 15734939844.608, + "elapsed time": 1347.3028064740356 + }, + { + "step": 4500, + "valid accuracy": 0.16, + "train loss": 0.9993657054901123, + "train samples": 18000, + "train time": 54.06312520604115, + "eval time": 20.218144676997326, + "tokens / sec": 3843.9879161254607, + "mem allocated avg": 6778886414.336, + "mem reserved avg": 15662697152.512, + "elapsed time": 1425.0894955290132 + }, + { + "step": 4750, + "valid accuracy": 0.2, + "train loss": 0.9890022552013398, + "train samples": 19000, + "train time": 54.60328221245436, + "eval time": 20.21068259398453, + "tokens / sec": 3844.8055042397323, + "mem allocated avg": 6781246834.688, + "mem reserved avg": 15759325528.064, + "elapsed time": 1503.2603250180255 + }, + { + "step": 5000, + "valid accuracy": 0.24, + "train loss": 0.9977171268463135, + "train samples": 20000, + "train time": 53.51452894380782, + "eval time": 20.269856880011503, + "tokens / sec": 3892.0271580583562, + "mem allocated avg": 6777745672.192, + "mem reserved avg": 15388339339.264, + "elapsed time": 1580.3933992580278 + }, + { + "step": 5000, + "test accuracy": 0.11675511751326763, + "train loss": 0.9977171268463135, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.40204334259033203 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/full-finetuning--llama-3.2-3B-lr_0.00001.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/full-finetuning--llama-3.2-3B-lr_0.00001.json new file mode 100644 index 0000000000000000000000000000000000000000..d04a0854a0cb666aa251eca523b26abbed7ec58f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/full-finetuning--llama-3.2-3B-lr_0.00001.json @@ -0,0 +1,332 @@ +{ + "run_info": { + "created_at": "2026-01-09T23:21:09+00:00", + "total_time": 2347.218174619018, + "experiment_name": "full-finetuning/llama-3.2-3B-lr_0.00001", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 1e-05 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": null, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 34309618532, + "accelerator_memory_max": 38549848064, + "accelerator_memory_reserved_99th": 37237492285, + "train_time": 2154.846133010811, + "file_size": 6425499648, + "num_trainable_params": 3212749824, + "num_total_params": 3212749824, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.3, + "train loss": 1.0749022269248962, + "train samples": 1000, + "train time": 91.49652248725761, + "eval time": 11.212762297014706, + "tokens / sec": 2313.956795784073, + "mem allocated avg": 26068575909.888, + "mem reserved avg": 34185951576.064, + "elapsed time": 124.61640950996662 + }, + { + "step": 500, + "valid accuracy": 0.4, + "train loss": 0.7238605138063431, + "train samples": 2000, + "train time": 91.91453206090955, + "eval time": 11.141172014991753, + "tokens / sec": 2262.917466219234, + "mem allocated avg": 26061334226.944, + "mem reserved avg": 34147850518.528, + "elapsed time": 230.16530759999296 + }, + { + "step": 750, + "valid accuracy": 0.42, + "train loss": 0.6648618532419205, + "train samples": 3000, + "train time": 92.5216026121634, + "eval time": 6.087067044980358, + "tokens / sec": 2317.3074606017867, + "mem allocated avg": 26070816337.92, + "mem reserved avg": 34269409837.056, + "elapsed time": 331.3244165930082 + }, + { + "step": 1000, + "valid accuracy": 0.4, + "train loss": 0.6407386429309845, + "train samples": 4000, + "train time": 91.41802564635873, + "eval time": 11.26410798204597, + "tokens / sec": 2278.9378629322678, + "mem allocated avg": 26063015718.912, + "mem reserved avg": 34418341183.488, + "elapsed time": 436.4462315859855 + }, + { + "step": 1250, + "valid accuracy": 0.46, + "train loss": 0.6343499521017074, + "train samples": 5000, + "train time": 91.51783608621918, + "eval time": 9.06717514997581, + "tokens / sec": 2278.6596462304447, + "mem allocated avg": 26061503963.136, + "mem reserved avg": 34260576632.832, + "elapsed time": 539.5919883140014 + }, + { + "step": 1500, + "valid accuracy": 0.58, + "train loss": 0.624906349182129, + "train samples": 6000, + "train time": 91.87651025888044, + "eval time": 11.171614417049568, + "tokens / sec": 2278.395200363706, + "mem allocated avg": 26064701278.208, + "mem reserved avg": 34224690167.808, + "elapsed time": 645.2011065029656 + }, + { + "step": 1750, + "valid accuracy": 0.54, + "train loss": 0.6175477323532105, + "train samples": 7000, + "train time": 90.95103025593562, + "eval time": 11.160093326005153, + "tokens / sec": 2301.843084249583, + "mem allocated avg": 26063144126.464, + "mem reserved avg": 34362062012.416, + "elapsed time": 749.8216157860006 + }, + { + "step": 2000, + "valid accuracy": 0.42, + "train loss": 0.6184427078962326, + "train samples": 8000, + "train time": 90.84291155746905, + "eval time": 11.153122653020546, + "tokens / sec": 2286.3203792032505, + "mem allocated avg": 26060605181.952, + "mem reserved avg": 34304549715.968, + "elapsed time": 854.322792426974 + }, + { + "step": 2250, + "valid accuracy": 0.46, + "train loss": 0.6107840378284455, + "train samples": 9000, + "train time": 92.96169786009705, + "eval time": 11.16127427702304, + "tokens / sec": 2312.221107702729, + "mem allocated avg": 26073147115.52, + "mem reserved avg": 34312711831.552, + "elapsed time": 960.9334694420104 + }, + { + "step": 2500, + "valid accuracy": 0.54, + "train loss": 0.6089447345733643, + "train samples": 10000, + "train time": 90.26249368820572, + "eval time": 11.146873010031413, + "tokens / sec": 2281.8669370189687, + "mem allocated avg": 26057948864.512, + "mem reserved avg": 34399810748.416, + "elapsed time": 1064.9780696959933 + }, + { + "step": 2750, + "valid accuracy": 0.56, + "train loss": 0.6021645392179489, + "train samples": 11000, + "train time": 91.39197911316296, + "eval time": 11.157545586000197, + "tokens / sec": 2318.376317659624, + "mem allocated avg": 26068202784.768, + "mem reserved avg": 34373529239.552, + "elapsed time": 1170.0117728059995 + }, + { + "step": 3000, + "valid accuracy": 0.48, + "train loss": 0.5950663160085679, + "train samples": 12000, + "train time": 91.94340823084349, + "eval time": 6.359558377007488, + "tokens / sec": 2270.2116879976475, + "mem allocated avg": 26062483675.136, + "mem reserved avg": 34305480851.456, + "elapsed time": 1270.7611719949637 + }, + { + "step": 3250, + "valid accuracy": 0.5, + "train loss": 0.6067559220790864, + "train samples": 13000, + "train time": 91.35254304017872, + "eval time": 6.207320767978672, + "tokens / sec": 2308.649469202422, + "mem allocated avg": 26064313700.352, + "mem reserved avg": 34178494103.552, + "elapsed time": 1370.8038186989725 + }, + { + "step": 3500, + "valid accuracy": 0.46, + "train loss": 0.5922972733974456, + "train samples": 14000, + "train time": 91.81345162418438, + "eval time": 7.237666736007668, + "tokens / sec": 2284.523632316533, + "mem allocated avg": 26062809985.024, + "mem reserved avg": 34401211645.952, + "elapsed time": 1472.3757120459923 + }, + { + "step": 3750, + "valid accuracy": 0.5, + "train loss": 0.5926397043466568, + "train samples": 15000, + "train time": 92.5030986299389, + "eval time": 11.144441604032181, + "tokens / sec": 2342.6566591777223, + "mem allocated avg": 26074840416.256, + "mem reserved avg": 34314205003.776, + "elapsed time": 1578.5238473899662 + }, + { + "step": 4000, + "valid accuracy": 0.52, + "train loss": 0.6050900548696518, + "train samples": 16000, + "train time": 90.88473943283316, + "eval time": 11.175483218976296, + "tokens / sec": 2248.7053522449546, + "mem allocated avg": 26056039493.632, + "mem reserved avg": 34580459421.696, + "elapsed time": 1683.2547346790088 + }, + { + "step": 4250, + "valid accuracy": 0.52, + "train loss": 0.5931364653110505, + "train samples": 17000, + "train time": 91.31777060282184, + "eval time": 7.878185064007994, + "tokens / sec": 2314.8725445720397, + "mem allocated avg": 26067197499.392, + "mem reserved avg": 34410673995.776, + "elapsed time": 1785.080884763971 + }, + { + "step": 4500, + "valid accuracy": 0.48, + "train loss": 0.6010294594764709, + "train samples": 18000, + "train time": 91.71872854570393, + "eval time": 6.507075314002577, + "tokens / sec": 2265.8185879282355, + "mem allocated avg": 26062461708.288, + "mem reserved avg": 34202108035.072, + "elapsed time": 1885.7456577859703 + }, + { + "step": 4750, + "valid accuracy": 0.5, + "train loss": 0.5937523410320282, + "train samples": 19000, + "train time": 91.9850392206572, + "eval time": 6.368945363035891, + "tokens / sec": 2282.31679606496, + "mem allocated avg": 26063243161.6, + "mem reserved avg": 34250082484.224, + "elapsed time": 1986.7437554029748 + }, + { + "step": 5000, + "valid accuracy": 0.46, + "train loss": 0.5987640290260315, + "train samples": 20000, + "train time": 90.72794272896135, + "eval time": 11.154609176970553, + "tokens / sec": 2295.654389764034, + "mem allocated avg": 26061294045.184, + "mem reserved avg": 34290171641.856, + "elapsed time": 2091.1681218339945 + }, + { + "step": 5000, + "test accuracy": 0.49507202426080366, + "train loss": 0.5987640290260315, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.5911064147949219 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/gralora--llama-3.2-3B-rank32.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/gralora--llama-3.2-3B-rank32.json new file mode 100644 index 0000000000000000000000000000000000000000..22f9af64912e22c89c04348e688254c1dd3c276f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/gralora--llama-3.2-3B-rank32.json @@ -0,0 +1,355 @@ +{ + "run_info": { + "created_at": "2026-01-10T00:00:21+00:00", + "total_time": 1289.217340779025, + "experiment_name": "gralora/llama-3.2-3B-rank32", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0002 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "GRALORA", + "auto_mapping": null, + "peft_version": "0.17.2.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "hybrid_r": 0, + "target_modules": [ + "q_proj", + "v_proj" + ], + "alpha": 64, + "gralora_dropout": 0.0, + "gralora_k": 2, + "fan_in_fan_out": false, + "bias": "none", + "modules_to_save": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14431023425, + "accelerator_memory_max": 22307405824, + "accelerator_memory_reserved_99th": 20126367744, + "train_time": 1078.0007609191234, + "file_size": 36714960, + "num_trainable_params": 9175040, + "num_total_params": 3221924864, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.36, + "train loss": 0.942215921163559, + "train samples": 1000, + "train time": 34.042564845993184, + "eval time": 13.884479815023951, + "tokens / sec": 6219.243495835461, + "mem allocated avg": 6927297665.024, + "mem reserved avg": 14540712443.904, + "elapsed time": 70.35818397701951 + }, + { + "step": 500, + "valid accuracy": 0.48, + "train loss": 0.707061094880104, + "train samples": 2000, + "train time": 33.86772509320872, + "eval time": 13.81671311397804, + "tokens / sec": 6141.392710244596, + "mem allocated avg": 6920123852.8, + "mem reserved avg": 14167075454.976, + "elapsed time": 121.25836294901092 + }, + { + "step": 750, + "valid accuracy": 0.42, + "train loss": 0.6730556710958481, + "train samples": 3000, + "train time": 34.94966330617899, + "eval time": 13.804657173983287, + "tokens / sec": 6134.5655356312, + "mem allocated avg": 6930530816.0, + "mem reserved avg": 14409984376.832, + "elapsed time": 173.17440196697135 + }, + { + "step": 1000, + "valid accuracy": 0.38, + "train loss": 0.6534032428264618, + "train samples": 4000, + "train time": 34.35864242265234, + "eval time": 13.949590890028048, + "tokens / sec": 6063.56902689048, + "mem allocated avg": 6921228693.504, + "mem reserved avg": 14450920783.872, + "elapsed time": 224.78821431397228 + }, + { + "step": 1250, + "valid accuracy": 0.4, + "train loss": 0.6493164491653443, + "train samples": 5000, + "train time": 33.983851948869415, + "eval time": 11.309890707023442, + "tokens / sec": 6136.3850193838225, + "mem allocated avg": 6921922877.44, + "mem reserved avg": 14466959802.368, + "elapsed time": 273.25096270401264 + }, + { + "step": 1500, + "valid accuracy": 0.34, + "train loss": 0.6408532521724701, + "train samples": 6000, + "train time": 34.35372261068551, + "eval time": 9.27557178097777, + "tokens / sec": 6093.400775579672, + "mem allocated avg": 6923754981.376, + "mem reserved avg": 14382721400.832, + "elapsed time": 320.11889754998265 + }, + { + "step": 1750, + "valid accuracy": 0.4, + "train loss": 0.6322305067777634, + "train samples": 7000, + "train time": 34.57727349648485, + "eval time": 9.888179413974285, + "tokens / sec": 6054.699484078268, + "mem allocated avg": 6925341489.152, + "mem reserved avg": 14776876924.928, + "elapsed time": 367.8946221729857 + }, + { + "step": 2000, + "valid accuracy": 0.52, + "train loss": 0.6344789278507232, + "train samples": 8000, + "train time": 33.59021200949792, + "eval time": 8.374654100975022, + "tokens / sec": 6183.229803410356, + "mem allocated avg": 6920861077.504, + "mem reserved avg": 14419908100.096, + "elapsed time": 413.12702070496744 + }, + { + "step": 2250, + "valid accuracy": 0.42, + "train loss": 0.6251693757772445, + "train samples": 9000, + "train time": 34.35726486198837, + "eval time": 13.802904761978425, + "tokens / sec": 6256.260527822477, + "mem allocated avg": 6931583428.608, + "mem reserved avg": 14699693342.72, + "elapsed time": 464.4872953959857 + }, + { + "step": 2500, + "valid accuracy": 0.46, + "train loss": 0.6212710882425309, + "train samples": 10000, + "train time": 33.39420525066089, + "eval time": 13.795758826017845, + "tokens / sec": 6167.746722941514, + "mem allocated avg": 6918615058.432, + "mem reserved avg": 14201795903.488, + "elapsed time": 514.8732995300088 + }, + { + "step": 2750, + "valid accuracy": 0.48, + "train loss": 0.6123416483402252, + "train samples": 11000, + "train time": 34.10195262962952, + "eval time": 7.583350939967204, + "tokens / sec": 6213.163284260355, + "mem allocated avg": 6927684456.448, + "mem reserved avg": 14572228444.16, + "elapsed time": 559.7389343840186 + }, + { + "step": 3000, + "valid accuracy": 0.46, + "train loss": 0.6028379487991333, + "train samples": 12000, + "train time": 34.35880611848552, + "eval time": 7.6943675089860335, + "tokens / sec": 6075.036463147065, + "mem allocated avg": 6923840229.376, + "mem reserved avg": 14495858556.928, + "elapsed time": 605.0798396450118 + }, + { + "step": 3250, + "valid accuracy": 0.54, + "train loss": 0.6112224916219712, + "train samples": 13000, + "train time": 34.423862263094634, + "eval time": 10.099462785990909, + "tokens / sec": 6126.593186671682, + "mem allocated avg": 6926499131.392, + "mem reserved avg": 14352186867.712, + "elapsed time": 652.7459372479934 + }, + { + "step": 3500, + "valid accuracy": 0.5, + "train loss": 0.5940833052396775, + "train samples": 14000, + "train time": 34.00928645499516, + "eval time": 7.006814954045694, + "tokens / sec": 6167.433129700158, + "mem allocated avg": 6923424174.08, + "mem reserved avg": 14361095569.408, + "elapsed time": 696.9908059639856 + }, + { + "step": 3750, + "valid accuracy": 0.52, + "train loss": 0.5911667649745941, + "train samples": 15000, + "train time": 34.607924775453284, + "eval time": 8.789539379009511, + "tokens / sec": 6261.6583168749585, + "mem allocated avg": 6934536548.352, + "mem reserved avg": 14719675006.976, + "elapsed time": 743.6320169619867 + }, + { + "step": 4000, + "valid accuracy": 0.52, + "train loss": 0.601644613146782, + "train samples": 16000, + "train time": 33.85560346476268, + "eval time": 7.726654959958978, + "tokens / sec": 6036.607801503638, + "mem allocated avg": 6915689891.84, + "mem reserved avg": 14388962525.184, + "elapsed time": 788.4833239429863 + }, + { + "step": 4250, + "valid accuracy": 0.6, + "train loss": 0.5881835660934448, + "train samples": 17000, + "train time": 34.50086922443006, + "eval time": 10.961278792994563, + "tokens / sec": 6127.063020496756, + "mem allocated avg": 6927453581.312, + "mem reserved avg": 14375817576.448, + "elapsed time": 837.071181916981 + }, + { + "step": 4500, + "valid accuracy": 0.58, + "train loss": 0.5937378851175308, + "train samples": 18000, + "train time": 33.85475521400804, + "eval time": 9.431811225018464, + "tokens / sec": 6138.517283209049, + "mem allocated avg": 6921458198.528, + "mem reserved avg": 14334059085.824, + "elapsed time": 883.6634952509776 + }, + { + "step": 4750, + "valid accuracy": 0.58, + "train loss": 0.586182700753212, + "train samples": 19000, + "train time": 34.06897705892334, + "eval time": 9.29696652397979, + "tokens / sec": 6162.1750379209825, + "mem allocated avg": 6924237260.8, + "mem reserved avg": 14424924487.68, + "elapsed time": 930.1821659649722 + }, + { + "step": 5000, + "valid accuracy": 0.6, + "train loss": 0.592198490023613, + "train samples": 20000, + "train time": 34.439023942220956, + "eval time": 7.703576382948086, + "tokens / sec": 6047.7904469486575, + "mem allocated avg": 6920309841.92, + "mem reserved avg": 14079011848.192, + "elapsed time": 975.4882056199713 + }, + { + "step": 5000, + "test accuracy": 0.5011372251705838, + "train loss": 0.592198490023613, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.49779701232910156 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ia3--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ia3--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..5c70c5691bf2868ac5cacd0540dffed04cf828b0 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ia3--llama-3.2-3B-default.json @@ -0,0 +1,353 @@ +{ + "run_info": { + "created_at": "2026-01-10T00:21:54+00:00", + "total_time": 1252.7159106170293, + "experiment_name": "ia3/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "IA3", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "target_modules": [ + "k_proj", + "down_proj", + "v_proj" + ], + "exclude_modules": null, + "feedforward_modules": [ + "down_proj" + ], + "fan_in_fan_out": false, + "modules_to_save": null, + "init_ia3_weights": true + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14786832524, + "accelerator_memory_max": 23240638464, + "accelerator_memory_reserved_99th": 20933771264, + "train_time": 1015.700665248034, + "file_size": 1157064, + "num_trainable_params": 286720, + "num_total_params": 3213036544, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.3155594708919525, + "train samples": 1000, + "train time": 29.70507554640062, + "eval time": 11.724285421019886, + "tokens / sec": 7127.367835482717, + "mem allocated avg": 6782600361.984, + "mem reserved avg": 14885492621.312, + "elapsed time": 63.95026855904143 + }, + { + "step": 500, + "valid accuracy": 0.0, + "train loss": 1.2050744531154634, + "train samples": 2000, + "train time": 29.590323601732962, + "eval time": 11.715296942042187, + "tokens / sec": 7029.155976780827, + "mem allocated avg": 6775425632.256, + "mem reserved avg": 14480272523.264, + "elapsed time": 108.9384753460181 + }, + { + "step": 750, + "valid accuracy": 0.12, + "train loss": 1.0194114191532135, + "train samples": 3000, + "train time": 30.585519072716124, + "eval time": 11.650421504979022, + "tokens / sec": 7009.885936225842, + "mem allocated avg": 6785668968.448, + "mem reserved avg": 14756492607.488, + "elapsed time": 154.82391193299554 + }, + { + "step": 1000, + "valid accuracy": 0.3, + "train loss": 0.9196182670593261, + "train samples": 4000, + "train time": 29.49092253309209, + "eval time": 11.840653097024187, + "tokens / sec": 7064.411083316362, + "mem allocated avg": 6777244168.192, + "mem reserved avg": 14776985976.832, + "elapsed time": 199.8590077710105 + }, + { + "step": 1250, + "valid accuracy": 0.3, + "train loss": 0.8686861591339111, + "train samples": 5000, + "train time": 29.44121315999655, + "eval time": 11.64985877397703, + "tokens / sec": 7083.1999641696975, + "mem allocated avg": 6777135923.2, + "mem reserved avg": 14839564992.512, + "elapsed time": 244.56394972099224 + }, + { + "step": 1500, + "valid accuracy": 0.3, + "train loss": 0.8333434355258942, + "train samples": 6000, + "train time": 29.930749938997906, + "eval time": 11.69840682001086, + "tokens / sec": 6993.844137772663, + "mem allocated avg": 6779035060.224, + "mem reserved avg": 14722384527.36, + "elapsed time": 289.89695524802664 + }, + { + "step": 1750, + "valid accuracy": 0.3, + "train loss": 0.8170836737155914, + "train samples": 7000, + "train time": 30.3804316627793, + "eval time": 11.654387208051048, + "tokens / sec": 6891.113408914859, + "mem allocated avg": 6779937654.784, + "mem reserved avg": 15161679151.104, + "elapsed time": 335.59190371102886 + }, + { + "step": 2000, + "valid accuracy": 0.3, + "train loss": 0.8073079003095627, + "train samples": 8000, + "train time": 29.52141359890811, + "eval time": 11.679582766955718, + "tokens / sec": 7035.435457863099, + "mem allocated avg": 6776053977.088, + "mem reserved avg": 14763992023.04, + "elapsed time": 380.5167595850071 + }, + { + "step": 2250, + "valid accuracy": 0.28, + "train loss": 0.795267580151558, + "train samples": 9000, + "train time": 30.315992950985674, + "eval time": 11.681108721997589, + "tokens / sec": 7090.25102187891, + "mem allocated avg": 6787896084.48, + "mem reserved avg": 15088715038.72, + "elapsed time": 426.1353191550006 + }, + { + "step": 2500, + "valid accuracy": 0.3, + "train loss": 0.7891060090065003, + "train samples": 10000, + "train time": 29.285075834020972, + "eval time": 11.683325350983068, + "tokens / sec": 7033.17284091594, + "mem allocated avg": 6772744847.36, + "mem reserved avg": 14541761019.904, + "elapsed time": 470.7990039800061 + }, + { + "step": 2750, + "valid accuracy": 0.3, + "train loss": 0.7823175694942475, + "train samples": 11000, + "train time": 30.584478964097798, + "eval time": 11.64602530299453, + "tokens / sec": 6927.729592801655, + "mem allocated avg": 6783104911.36, + "mem reserved avg": 14943508234.24, + "elapsed time": 516.6453109350405 + }, + { + "step": 3000, + "valid accuracy": 0.26, + "train loss": 0.7710221862792969, + "train samples": 12000, + "train time": 29.543955663975794, + "eval time": 11.677449156995863, + "tokens / sec": 7065.099960683823, + "mem allocated avg": 6778547337.216, + "mem reserved avg": 14865569677.312, + "elapsed time": 561.5630381150404 + }, + { + "step": 3250, + "valid accuracy": 0.3, + "train loss": 0.7756292035579682, + "train samples": 13000, + "train time": 29.600664581230376, + "eval time": 11.676535067963414, + "tokens / sec": 7124.873815628153, + "mem allocated avg": 6780569153.536, + "mem reserved avg": 14715774304.256, + "elapsed time": 606.3470957170357 + }, + { + "step": 3500, + "valid accuracy": 0.32, + "train loss": 0.7658540964126587, + "train samples": 14000, + "train time": 29.628978170803748, + "eval time": 11.7645476309699, + "tokens / sec": 7079.218148896091, + "mem allocated avg": 6778699649.024, + "mem reserved avg": 14727702904.832, + "elapsed time": 651.4321867520339 + }, + { + "step": 3750, + "valid accuracy": 0.36, + "train loss": 0.7585025093555451, + "train samples": 15000, + "train time": 30.480809888918884, + "eval time": 11.652502680022735, + "tokens / sec": 7109.489570314241, + "mem allocated avg": 6790036742.144, + "mem reserved avg": 15097195921.408, + "elapsed time": 697.2096698190435 + }, + { + "step": 4000, + "valid accuracy": 0.34, + "train loss": 0.7766863429546356, + "train samples": 16000, + "train time": 29.984013571229298, + "eval time": 11.786360332975164, + "tokens / sec": 6816.065484845664, + "mem allocated avg": 6770827464.704, + "mem reserved avg": 14748657647.616, + "elapsed time": 742.6605575150461 + }, + { + "step": 4250, + "valid accuracy": 0.32, + "train loss": 0.7541669148206711, + "train samples": 17000, + "train time": 30.13022418995388, + "eval time": 11.657879816018976, + "tokens / sec": 7015.845573113327, + "mem allocated avg": 6782400247.808, + "mem reserved avg": 14721461780.48, + "elapsed time": 787.9822572360281 + }, + { + "step": 4500, + "valid accuracy": 0.3, + "train loss": 0.7659742934703827, + "train samples": 18000, + "train time": 30.020536605035886, + "eval time": 11.697008132992778, + "tokens / sec": 6922.527826006246, + "mem allocated avg": 6776485750.784, + "mem reserved avg": 14703325609.984, + "elapsed time": 833.4761402930017 + }, + { + "step": 4750, + "valid accuracy": 0.32, + "train loss": 0.7579846435785293, + "train samples": 19000, + "train time": 30.37128037889488, + "eval time": 11.668571799993515, + "tokens / sec": 6912.4184881546, + "mem allocated avg": 6779605635.072, + "mem reserved avg": 14800801234.944, + "elapsed time": 879.1311652210425 + }, + { + "step": 5000, + "valid accuracy": 0.34, + "train loss": 0.7657218432426453, + "train samples": 20000, + "train time": 29.584271008439828, + "eval time": 11.69853776000673, + "tokens / sec": 7040.227556750738, + "mem allocated avg": 6776251918.336, + "mem reserved avg": 14395312701.44, + "elapsed time": 924.0385756980395 + }, + { + "step": 5000, + "test accuracy": 0.35178165276724793, + "train loss": 0.7657218432426453, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.1822957992553711 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ia3--llama-3.2-3B-lr_0.001.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ia3--llama-3.2-3B-lr_0.001.json new file mode 100644 index 0000000000000000000000000000000000000000..cdaec6ec9d25f44acdf4bdfe4f05839d941c7e29 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ia3--llama-3.2-3B-lr_0.001.json @@ -0,0 +1,352 @@ +{ + "run_info": { + "created_at": "2026-01-10T00:42:51+00:00", + "total_time": 1158.928240164998, + "experiment_name": "ia3/llama-3.2-3B-lr_0.001", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.001 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "IA3", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "target_modules": [ + "down_proj", + "k_proj", + "v_proj" + ], + "exclude_modules": null, + "feedforward_modules": [ + "down_proj" + ], + "fan_in_fan_out": false, + "modules_to_save": null, + "init_ia3_weights": true + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14786832524, + "accelerator_memory_max": 23240638464, + "accelerator_memory_reserved_99th": 20933771264, + "train_time": 969.7345388169051, + "file_size": 1157064, + "num_trainable_params": 286720, + "num_total_params": 3213036544, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.2, + "train loss": 1.16681476187706, + "train samples": 1000, + "train time": 29.673775453935377, + "eval time": 11.714410117012449, + "tokens / sec": 7134.885829700566, + "mem allocated avg": 6782600361.984, + "mem reserved avg": 14885492621.312, + "elapsed time": 64.35547732701525 + }, + { + "step": 500, + "valid accuracy": 0.34, + "train loss": 0.8284487807750702, + "train samples": 2000, + "train time": 29.442405258771032, + "eval time": 11.714618961967062, + "tokens / sec": 7064.470384532775, + "mem allocated avg": 6775425632.256, + "mem reserved avg": 14480272523.264, + "elapsed time": 109.20030425902223 + }, + { + "step": 750, + "valid accuracy": 0.34, + "train loss": 0.7387913703918457, + "train samples": 3000, + "train time": 30.728236329741776, + "eval time": 7.293018446012866, + "tokens / sec": 6977.328529346211, + "mem allocated avg": 6785668968.448, + "mem reserved avg": 14756492607.488, + "elapsed time": 150.8779634690145 + }, + { + "step": 1000, + "valid accuracy": 0.36, + "train loss": 0.7031073143482208, + "train samples": 4000, + "train time": 29.568247662391514, + "eval time": 6.950251807982568, + "tokens / sec": 7045.936654034017, + "mem allocated avg": 6777244168.192, + "mem reserved avg": 14776985976.832, + "elapsed time": 191.10305509302998 + }, + { + "step": 1250, + "valid accuracy": 0.3, + "train loss": 0.6952721246480942, + "train samples": 5000, + "train time": 29.136579907499254, + "eval time": 7.7922670019906946, + "tokens / sec": 7157.257326084655, + "mem allocated avg": 6777135923.2, + "mem reserved avg": 14839564992.512, + "elapsed time": 231.62949198303977 + }, + { + "step": 1500, + "valid accuracy": 0.28, + "train loss": 0.6860846598148346, + "train samples": 6000, + "train time": 29.309486759477295, + "eval time": 8.780186134041287, + "tokens / sec": 7142.0902630549235, + "mem allocated avg": 6779035060.224, + "mem reserved avg": 14722384527.36, + "elapsed time": 273.4239038110245 + }, + { + "step": 1750, + "valid accuracy": 0.34, + "train loss": 0.677450892329216, + "train samples": 7000, + "train time": 29.44055196386762, + "eval time": 9.34235847304808, + "tokens / sec": 7111.109881939079, + "mem allocated avg": 6779937654.784, + "mem reserved avg": 15161679151.104, + "elapsed time": 315.85002974100644 + }, + { + "step": 2000, + "valid accuracy": 0.32, + "train loss": 0.6783282169103623, + "train samples": 8000, + "train time": 29.261146096221637, + "eval time": 8.788515535998158, + "tokens / sec": 7098.013157687588, + "mem allocated avg": 6776053977.088, + "mem reserved avg": 14763992023.04, + "elapsed time": 357.609911208041 + }, + { + "step": 2250, + "valid accuracy": 0.48, + "train loss": 0.6720160303115845, + "train samples": 9000, + "train time": 30.398827165656257, + "eval time": 10.552425866015255, + "tokens / sec": 7070.930691788078, + "mem allocated avg": 6787896084.48, + "mem reserved avg": 15088715038.72, + "elapsed time": 402.1721519330167 + }, + { + "step": 2500, + "valid accuracy": 0.44, + "train loss": 0.6704732036590576, + "train samples": 10000, + "train time": 29.788877881946974, + "eval time": 8.030864721979015, + "tokens / sec": 6914.224859903927, + "mem allocated avg": 6772744847.36, + "mem reserved avg": 14541761019.904, + "elapsed time": 443.68974046903895 + }, + { + "step": 2750, + "valid accuracy": 0.44, + "train loss": 0.6629449647665023, + "train samples": 11000, + "train time": 30.050681999477092, + "eval time": 8.138099809992127, + "tokens / sec": 7050.7883982029725, + "mem allocated avg": 6783104911.36, + "mem reserved avg": 14943508234.24, + "elapsed time": 485.477781796013 + }, + { + "step": 3000, + "valid accuracy": 0.38, + "train loss": 0.6557633522748947, + "train samples": 12000, + "train time": 29.61273902398534, + "eval time": 10.074375847005285, + "tokens / sec": 7048.689411369032, + "mem allocated avg": 6778547337.216, + "mem reserved avg": 14865569677.312, + "elapsed time": 528.8621876270045 + }, + { + "step": 3250, + "valid accuracy": 0.48, + "train loss": 0.6654598761796952, + "train samples": 13000, + "train time": 29.63859097607201, + "eval time": 7.940114627999719, + "tokens / sec": 7115.756621840281, + "mem allocated avg": 6780569153.536, + "mem reserved avg": 14715774304.256, + "elapsed time": 569.9359965579933 + }, + { + "step": 3500, + "valid accuracy": 0.46, + "train loss": 0.6528869969844818, + "train samples": 14000, + "train time": 30.20164098625537, + "eval time": 11.715904708020389, + "tokens / sec": 6944.986866622787, + "mem allocated avg": 6778699649.024, + "mem reserved avg": 14727702904.832, + "elapsed time": 615.5466552060097 + }, + { + "step": 3750, + "valid accuracy": 0.48, + "train loss": 0.6514250497817993, + "train samples": 15000, + "train time": 31.03051795932697, + "eval time": 9.986055641958956, + "tokens / sec": 6983.544402450578, + "mem allocated avg": 6790036742.144, + "mem reserved avg": 15097195921.408, + "elapsed time": 660.206704717013 + }, + { + "step": 4000, + "valid accuracy": 0.42, + "train loss": 0.6659475769996643, + "train samples": 16000, + "train time": 29.327483134518843, + "eval time": 11.69795022701146, + "tokens / sec": 6968.651181643686, + "mem allocated avg": 6770827464.704, + "mem reserved avg": 14748657647.616, + "elapsed time": 704.8852831150289 + }, + { + "step": 4250, + "valid accuracy": 0.42, + "train loss": 0.6488557003736496, + "train samples": 17000, + "train time": 29.780065669328906, + "eval time": 11.67279983102344, + "tokens / sec": 7098.338947509905, + "mem allocated avg": 6782400247.808, + "mem reserved avg": 14721461780.48, + "elapsed time": 749.8611966730095 + }, + { + "step": 4500, + "valid accuracy": 0.4, + "train loss": 0.6574098072052001, + "train samples": 18000, + "train time": 29.94875920598861, + "eval time": 7.102646674029529, + "tokens / sec": 6939.11886534666, + "mem allocated avg": 6776485750.784, + "mem reserved avg": 14703325609.984, + "elapsed time": 790.6740298850345 + }, + { + "step": 4750, + "valid accuracy": 0.44, + "train loss": 0.6505107415914535, + "train samples": 19000, + "train time": 30.134280904079787, + "eval time": 7.6594287430052646, + "tokens / sec": 6966.783135401682, + "mem allocated avg": 6779605635.072, + "mem reserved avg": 14800801234.944, + "elapsed time": 832.055415440991 + }, + { + "step": 5000, + "valid accuracy": 0.38, + "train loss": 0.6568637717962265, + "train samples": 20000, + "train time": 29.94096938223811, + "eval time": 9.314888863998931, + "tokens / sec": 6956.354596974339, + "mem allocated avg": 6776251918.336, + "mem reserved avg": 14395312701.44, + "elapsed time": 874.9385239290423 + }, + { + "step": 5000, + "test accuracy": 0.41243366186504926, + "train loss": 0.6568637717962265, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.2050151824951172 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ln_tuning--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ln_tuning--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..b52e20dffcd00b2ef74a222dc2b70d62f199062d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ln_tuning--llama-3.2-3B-default.json @@ -0,0 +1,348 @@ +{ + "run_info": { + "created_at": "2026-01-10T01:02:15+00:00", + "total_time": 1158.007769990014, + "experiment_name": "ln_tuning/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "LN_TUNING", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "target_modules": [ + "norm", + "input_layernorm", + "post_attention_layernorm" + ], + "exclude_modules": null, + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 13811999938, + "accelerator_memory_max": 21179138048, + "accelerator_memory_reserved_99th": 19146997760, + "train_time": 933.4248713181005, + "file_size": 358288, + "num_trainable_params": 175104, + "num_total_params": 3212924928, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.3265766797065734, + "train samples": 1000, + "train time": 27.05523074005032, + "eval time": 11.134952866006643, + "tokens / sec": 7825.436864102909, + "mem allocated avg": 6781727356.928, + "mem reserved avg": 13917774413.824, + "elapsed time": 59.58366395003395 + }, + { + "step": 500, + "valid accuracy": 0.0, + "train loss": 1.3412033476829528, + "train samples": 2000, + "train time": 27.19167830166407, + "eval time": 11.076495647954289, + "tokens / sec": 7649.215237563, + "mem allocated avg": 6774720333.824, + "mem reserved avg": 13569009647.616, + "elapsed time": 100.96434171200963 + }, + { + "step": 750, + "valid accuracy": 0.0, + "train loss": 1.2789963104724884, + "train samples": 3000, + "train time": 27.539981623878703, + "eval time": 11.047948513005394, + "tokens / sec": 7785.081447334822, + "mem allocated avg": 6784869052.416, + "mem reserved avg": 13769388326.912, + "elapsed time": 142.60399866703665 + }, + { + "step": 1000, + "valid accuracy": 0.0, + "train loss": 1.2634205253124238, + "train samples": 4000, + "train time": 26.802510203735437, + "eval time": 11.213655479019508, + "tokens / sec": 7773.00329022781, + "mem allocated avg": 6775999932.416, + "mem reserved avg": 13779588874.24, + "elapsed time": 183.79537835903466 + }, + { + "step": 1250, + "valid accuracy": 0.0, + "train loss": 1.2484288651943207, + "train samples": 5000, + "train time": 26.859816205396783, + "eval time": 11.04810167697724, + "tokens / sec": 7763.939946770734, + "mem allocated avg": 6776329017.344, + "mem reserved avg": 13803437686.784, + "elapsed time": 224.77404374204343 + }, + { + "step": 1500, + "valid accuracy": 0.0, + "train loss": 1.231340999364853, + "train samples": 6000, + "train time": 27.544580540037714, + "eval time": 11.118913470010739, + "tokens / sec": 7599.716383254584, + "mem allocated avg": 6778265929.728, + "mem reserved avg": 13820894380.032, + "elapsed time": 266.58437842602143 + }, + { + "step": 1750, + "valid accuracy": 0.0, + "train loss": 1.2306929278373717, + "train samples": 7000, + "train time": 27.029298119421583, + "eval time": 11.036927138979081, + "tokens / sec": 7745.484143725154, + "mem allocated avg": 6779571120.128, + "mem reserved avg": 14093188595.712, + "elapsed time": 307.76138371700654 + }, + { + "step": 2000, + "valid accuracy": 0.0, + "train loss": 1.2307198526859284, + "train samples": 8000, + "train time": 26.702352902852, + "eval time": 11.090556368988473, + "tokens / sec": 7778.1909615094855, + "mem allocated avg": 6775307636.736, + "mem reserved avg": 13810257625.088, + "elapsed time": 348.7669416820281 + }, + { + "step": 2250, + "valid accuracy": 0.0, + "train loss": 1.2245776391029357, + "train samples": 9000, + "train time": 27.69884210533928, + "eval time": 11.05135836795671, + "tokens / sec": 7760.179980901304, + "mem allocated avg": 6785839908.864, + "mem reserved avg": 14071948640.256, + "elapsed time": 390.5765162970056 + }, + { + "step": 2500, + "valid accuracy": 0.0, + "train loss": 1.2369521839618682, + "train samples": 10000, + "train time": 27.172044244071003, + "eval time": 11.106051086972002, + "tokens / sec": 7580.10689773341, + "mem allocated avg": 6772880177.152, + "mem reserved avg": 13577423421.44, + "elapsed time": 431.9964616240468 + }, + { + "step": 2750, + "valid accuracy": 0.0, + "train loss": 1.2313981459140777, + "train samples": 11000, + "train time": 27.588061350223143, + "eval time": 11.063589482975658, + "tokens / sec": 7680.1699586725845, + "mem allocated avg": 6782132961.28, + "mem reserved avg": 13968802316.288, + "elapsed time": 473.7305173620116 + }, + { + "step": 3000, + "valid accuracy": 0.0, + "train loss": 1.2322822377681732, + "train samples": 12000, + "train time": 27.48076619656058, + "eval time": 11.10096250998322, + "tokens / sec": 7595.53057971594, + "mem allocated avg": 6777935728.64, + "mem reserved avg": 13851705737.216, + "elapsed time": 515.4748477530084 + }, + { + "step": 3250, + "valid accuracy": 0.0, + "train loss": 1.231231040239334, + "train samples": 13000, + "train time": 27.788235317741055, + "eval time": 11.049090766988229, + "tokens / sec": 7589.578740372652, + "mem allocated avg": 6780943562.752, + "mem reserved avg": 13802355556.352, + "elapsed time": 557.366414040036 + }, + { + "step": 3500, + "valid accuracy": 0.0, + "train loss": 1.2321618583202363, + "train samples": 14000, + "train time": 27.022960201604292, + "eval time": 11.094650793995243, + "tokens / sec": 7761.917955515015, + "mem allocated avg": 6777875570.688, + "mem reserved avg": 13817966755.84, + "elapsed time": 598.6570834580343 + }, + { + "step": 3750, + "valid accuracy": 0.0, + "train loss": 1.215895681142807, + "train samples": 15000, + "train time": 27.39095462608384, + "eval time": 11.043718303029891, + "tokens / sec": 7911.4803758478065, + "mem allocated avg": 6788866940.928, + "mem reserved avg": 14072342904.832, + "elapsed time": 640.2053242530092 + }, + { + "step": 4000, + "valid accuracy": 0.0, + "train loss": 1.2472150621414184, + "train samples": 16000, + "train time": 26.27257864776766, + "eval time": 11.109217509045266, + "tokens / sec": 7778.947119732583, + "mem allocated avg": 6769699028.992, + "mem reserved avg": 13815643111.424, + "elapsed time": 680.7284473860054 + }, + { + "step": 4250, + "valid accuracy": 0.0, + "train loss": 1.21587810254097, + "train samples": 17000, + "train time": 26.962625220243353, + "eval time": 11.047069397987798, + "tokens / sec": 7840.074854480067, + "mem allocated avg": 6782053310.464, + "mem reserved avg": 13778800345.088, + "elapsed time": 721.68619730504 + }, + { + "step": 4500, + "valid accuracy": 0.0, + "train loss": 1.241484440803528, + "train samples": 18000, + "train time": 26.840785892680287, + "eval time": 11.098841341969091, + "tokens / sec": 7742.61978881452, + "mem allocated avg": 6775733297.152, + "mem reserved avg": 13672147582.976, + "elapsed time": 762.8068605409935 + }, + { + "step": 4750, + "valid accuracy": 0.0, + "train loss": 1.2253197972774506, + "train samples": 19000, + "train time": 27.470003902097233, + "eval time": 11.055242774018552, + "tokens / sec": 7642.481622799185, + "mem allocated avg": 6778600820.736, + "mem reserved avg": 13782675881.984, + "elapsed time": 804.4074719570344 + }, + { + "step": 5000, + "valid accuracy": 0.0, + "train loss": 1.2366444897651672, + "train samples": 20000, + "train time": 26.569939231791068, + "eval time": 11.095670820039231, + "tokens / sec": 7838.93399917121, + "mem allocated avg": 6775143475.2, + "mem reserved avg": 13464646975.488, + "elapsed time": 845.1059082580032 + }, + { + "step": 5000, + "test accuracy": 0.0, + "train loss": 1.2366444897651672, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": -0.032855987548828125 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/loha--llama-3.2-3B-rank32.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/loha--llama-3.2-3B-rank32.json new file mode 100644 index 0000000000000000000000000000000000000000..85e8cbd259e0604c24126aae74d6641a8ee75d7b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/loha--llama-3.2-3B-rank32.json @@ -0,0 +1,357 @@ +{ + "run_info": { + "created_at": "2026-01-10T01:21:37+00:00", + "total_time": 1723.7877959029865, + "experiment_name": "loha/llama-3.2-3B-rank32", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "LOHA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "rank_pattern": {}, + "alpha_pattern": {}, + "r": 32, + "alpha": 64, + "rank_dropout": 0.0, + "module_dropout": 0.0, + "use_effective_conv2d": false, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 16069747225, + "accelerator_memory_max": 23907532800, + "accelerator_memory_reserved_99th": 21843935232, + "train_time": 1444.0684821169707, + "file_size": 73429560, + "num_trainable_params": 18350080, + "num_total_params": 3231099904, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.2914833612442016, + "train samples": 1000, + "train time": 48.783409356023185, + "eval time": 15.048279424023349, + "tokens / sec": 4339.979570818157, + "mem allocated avg": 7075144325.12, + "mem reserved avg": 16180198768.64, + "elapsed time": 89.06116562400712 + }, + { + "step": 500, + "valid accuracy": 0.36, + "train loss": 0.9051123208999634, + "train samples": 2000, + "train time": 49.313777334056795, + "eval time": 14.961491579946596, + "tokens / sec": 4217.786818296632, + "mem allocated avg": 7068229634.048, + "mem reserved avg": 15816938487.808, + "elapsed time": 157.51611204899382 + }, + { + "step": 750, + "valid accuracy": 0.32, + "train loss": 0.7515957379341125, + "train samples": 3000, + "train time": 49.29726693738485, + "eval time": 10.4420769319986, + "tokens / sec": 4349.1457705418525, + "mem allocated avg": 7078224801.792, + "mem reserved avg": 16001924071.424, + "elapsed time": 221.30589306500042 + }, + { + "step": 1000, + "valid accuracy": 0.44, + "train loss": 0.7083757585287094, + "train samples": 4000, + "train time": 48.992843332118355, + "eval time": 15.014163143991027, + "tokens / sec": 4252.376180490441, + "mem allocated avg": 7069774227.456, + "mem reserved avg": 16085097119.744, + "elapsed time": 289.58009328099433 + }, + { + "step": 1250, + "valid accuracy": 0.36, + "train loss": 0.6994501632452012, + "train samples": 5000, + "train time": 48.87461844785139, + "eval time": 15.003678467997815, + "tokens / sec": 4266.795457902294, + "mem allocated avg": 7069489561.6, + "mem reserved avg": 16102310543.36, + "elapsed time": 357.60247106896713 + }, + { + "step": 1500, + "valid accuracy": 0.34, + "train loss": 0.688896736741066, + "train samples": 6000, + "train time": 48.57590564060956, + "eval time": 10.066342948994134, + "tokens / sec": 4309.358667417182, + "mem allocated avg": 7071214790.656, + "mem reserved avg": 16085852094.464, + "elapsed time": 420.47844035195885 + }, + { + "step": 1750, + "valid accuracy": 0.4, + "train loss": 0.6796333414316177, + "train samples": 7000, + "train time": 49.9453335700091, + "eval time": 11.371492591046263, + "tokens / sec": 4191.682886781486, + "mem allocated avg": 7073070399.488, + "mem reserved avg": 16412395438.08, + "elapsed time": 485.994160362985 + }, + { + "step": 2000, + "valid accuracy": 0.42, + "train loss": 0.6801165891885758, + "train samples": 8000, + "train time": 48.455957927857526, + "eval time": 15.107590888044797, + "tokens / sec": 4286.2840583860325, + "mem allocated avg": 7068561985.536, + "mem reserved avg": 16088888770.56, + "elapsed time": 553.8159226219868 + }, + { + "step": 2250, + "valid accuracy": 0.38, + "train loss": 0.6730777739286423, + "train samples": 9000, + "train time": 50.08038655488053, + "eval time": 15.016238837968558, + "tokens / sec": 4292.059522432988, + "mem allocated avg": 7080170047.488, + "mem reserved avg": 16375955324.928, + "elapsed time": 623.1283458310063 + }, + { + "step": 2500, + "valid accuracy": 0.44, + "train loss": 0.6711871980428695, + "train samples": 10000, + "train time": 48.26023929938674, + "eval time": 8.185648262035102, + "tokens / sec": 4267.840420812362, + "mem allocated avg": 7066054148.096, + "mem reserved avg": 15799381131.264, + "elapsed time": 683.6707712119678 + }, + { + "step": 2750, + "valid accuracy": 0.44, + "train loss": 0.6645230972766876, + "train samples": 11000, + "train time": 50.41757245978806, + "eval time": 11.489728196000215, + "tokens / sec": 4202.522843974521, + "mem allocated avg": 7075331424.256, + "mem reserved avg": 16211597328.384, + "elapsed time": 749.7390187569545 + }, + { + "step": 3000, + "valid accuracy": 0.4, + "train loss": 0.6566754117012024, + "train samples": 12000, + "train time": 48.205230054212734, + "eval time": 14.944865885016043, + "tokens / sec": 4330.048830080392, + "mem allocated avg": 7070783477.76, + "mem reserved avg": 16134405357.568, + "elapsed time": 817.0802311009611 + }, + { + "step": 3250, + "valid accuracy": 0.42, + "train loss": 0.6666845008134842, + "train samples": 13000, + "train time": 48.50475694506895, + "eval time": 14.985318146995269, + "tokens / sec": 4348.047764445925, + "mem allocated avg": 7073913442.304, + "mem reserved avg": 16018088919.04, + "elapsed time": 884.7171556460089 + }, + { + "step": 3500, + "valid accuracy": 0.44, + "train loss": 0.6538506431579589, + "train samples": 14000, + "train time": 48.627094919618685, + "eval time": 14.961251400003675, + "tokens / sec": 4313.438842001972, + "mem allocated avg": 7070698022.912, + "mem reserved avg": 16014808973.312, + "elapsed time": 952.4853859379655 + }, + { + "step": 3750, + "valid accuracy": 0.44, + "train loss": 0.6510264467000961, + "train samples": 15000, + "train time": 50.97888733900618, + "eval time": 15.012431181967258, + "tokens / sec": 4250.838166767737, + "mem allocated avg": 7083094827.008, + "mem reserved avg": 16354790866.944, + "elapsed time": 1022.6562416799716 + }, + { + "step": 4000, + "valid accuracy": 0.46, + "train loss": 0.6674902982711792, + "train samples": 16000, + "train time": 48.719796552322805, + "eval time": 15.030813960998785, + "tokens / sec": 4194.865628810926, + "mem allocated avg": 7063056650.24, + "mem reserved avg": 16042550099.968, + "elapsed time": 1090.629200581985 + }, + { + "step": 4250, + "valid accuracy": 0.48, + "train loss": 0.6494669053554535, + "train samples": 17000, + "train time": 50.06373492471175, + "eval time": 15.01842499698978, + "tokens / sec": 4222.397715989367, + "mem allocated avg": 7074535757.824, + "mem reserved avg": 15991052435.456, + "elapsed time": 1159.7775298539782 + }, + { + "step": 4500, + "valid accuracy": 0.5, + "train loss": 0.658131462097168, + "train samples": 18000, + "train time": 49.55814389558509, + "eval time": 14.973931148997508, + "tokens / sec": 4193.417744576054, + "mem allocated avg": 7069541146.624, + "mem reserved avg": 15961180602.368, + "elapsed time": 1228.5485400629696 + }, + { + "step": 4750, + "valid accuracy": 0.48, + "train loss": 0.6511208745241165, + "train samples": 19000, + "train time": 50.09447881835513, + "eval time": 14.996958026022185, + "tokens / sec": 4190.861048005878, + "mem allocated avg": 7071928455.168, + "mem reserved avg": 16052733870.08, + "elapsed time": 1297.7279399959953 + }, + { + "step": 5000, + "valid accuracy": 0.44, + "train loss": 0.6570172024965286, + "train samples": 20000, + "train time": 48.30597296968335, + "eval time": 14.95854680496268, + "tokens / sec": 4311.682121188528, + "mem allocated avg": 7068810864.64, + "mem reserved avg": 15664794304.512, + "elapsed time": 1365.0393339970033 + }, + { + "step": 5000, + "test accuracy": 0.4184988627748294, + "train loss": 0.6570172024965286, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.07485389709472656 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lokr--llama-3.2-3B-rank32.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lokr--llama-3.2-3B-rank32.json new file mode 100644 index 0000000000000000000000000000000000000000..5e69d757926d8262ca4bbeb60a308b7b847ede75 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lokr--llama-3.2-3B-rank32.json @@ -0,0 +1,360 @@ +{ + "run_info": { + "created_at": "2026-01-10T01:50:25+00:00", + "total_time": 1535.4195199839887, + "experiment_name": "lokr/llama-3.2-3B-rank32", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "LOKR", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "rank_pattern": {}, + "alpha_pattern": {}, + "r": 32, + "alpha": 64, + "rank_dropout": 0.0, + "module_dropout": 0.0, + "use_effective_conv2d": false, + "decompose_both": false, + "decompose_factor": -1, + "rank_dropout_scale": false, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 15792361544, + "accelerator_memory_max": 23571988480, + "accelerator_memory_reserved_99th": 21346910208, + "train_time": 1317.615543427004, + "file_size": 1131984, + "num_trainable_params": 279552, + "num_total_params": 3213029376, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.2610098366737366, + "train samples": 1000, + "train time": 44.917080010229256, + "eval time": 13.230089190998115, + "tokens / sec": 4713.552171062408, + "mem allocated avg": 6785872599.04, + "mem reserved avg": 15919304671.232, + "elapsed time": 85.93055745301535 + }, + { + "step": 500, + "valid accuracy": 0.36, + "train loss": 0.9418223905563354, + "train samples": 2000, + "train time": 44.39176498691086, + "eval time": 13.134529082977679, + "tokens / sec": 4685.441096143134, + "mem allocated avg": 6778738747.392, + "mem reserved avg": 15563761909.76, + "elapsed time": 147.61094936099835 + }, + { + "step": 750, + "valid accuracy": 0.4, + "train loss": 0.7931550116539001, + "train samples": 3000, + "train time": 45.546711406088434, + "eval time": 13.15151729201898, + "tokens / sec": 4707.2772848171, + "mem allocated avg": 6788886910.976, + "mem reserved avg": 15770750812.16, + "elapsed time": 210.37875085603446 + }, + { + "step": 1000, + "valid accuracy": 0.38, + "train loss": 0.7486971822977067, + "train samples": 4000, + "train time": 44.15514894755324, + "eval time": 13.2610618310282, + "tokens / sec": 4718.271933528252, + "mem allocated avg": 6779705090.048, + "mem reserved avg": 15782125764.608, + "elapsed time": 272.00523140100995 + }, + { + "step": 1250, + "valid accuracy": 0.34, + "train loss": 0.7329185563325882, + "train samples": 5000, + "train time": 44.73619283729931, + "eval time": 13.166668922000099, + "tokens / sec": 4661.505299711804, + "mem allocated avg": 6780468045.824, + "mem reserved avg": 15823901032.448, + "elapsed time": 333.9785253200098 + }, + { + "step": 1500, + "valid accuracy": 0.32, + "train loss": 0.7207690758705139, + "train samples": 6000, + "train time": 44.514215660397895, + "eval time": 13.139724303036928, + "tokens / sec": 4702.565166979489, + "mem allocated avg": 6781829281.792, + "mem reserved avg": 15757807190.016, + "elapsed time": 395.81570798699977 + }, + { + "step": 1750, + "valid accuracy": 0.3, + "train loss": 0.7103254743814469, + "train samples": 7000, + "train time": 45.324679988552816, + "eval time": 13.146416853996925, + "tokens / sec": 4619.006688031214, + "mem allocated avg": 6783828615.168, + "mem reserved avg": 16158497439.744, + "elapsed time": 458.46547377400566 + }, + { + "step": 2000, + "valid accuracy": 0.36, + "train loss": 0.7092406690120697, + "train samples": 8000, + "train time": 43.866437830845825, + "eval time": 13.131515079992823, + "tokens / sec": 4734.735945528569, + "mem allocated avg": 6779261771.776, + "mem reserved avg": 15762227986.432, + "elapsed time": 519.6737852150109 + }, + { + "step": 2250, + "valid accuracy": 0.4, + "train loss": 0.7017901630401612, + "train samples": 9000, + "train time": 46.34161411313107, + "eval time": 9.606278705003206, + "tokens / sec": 4638.336495471652, + "mem allocated avg": 6790719053.824, + "mem reserved avg": 16063865552.896, + "elapsed time": 579.7241231160006 + }, + { + "step": 2500, + "valid accuracy": 0.34, + "train loss": 0.7000315390825271, + "train samples": 10000, + "train time": 43.55846684699645, + "eval time": 13.126351199985947, + "tokens / sec": 4728.5181253849005, + "mem allocated avg": 6776950829.056, + "mem reserved avg": 15558267371.52, + "elapsed time": 640.5660474800388 + }, + { + "step": 2750, + "valid accuracy": 0.36, + "train loss": 0.6941497979164124, + "train samples": 11000, + "train time": 45.54542878107168, + "eval time": 7.833579002006445, + "tokens / sec": 4652.080475923768, + "mem allocated avg": 6786488795.136, + "mem reserved avg": 15941710643.2, + "elapsed time": 698.0084676230326 + }, + { + "step": 3000, + "valid accuracy": 0.38, + "train loss": 0.6868689198493958, + "train samples": 12000, + "train time": 44.477772765094414, + "eval time": 13.114933934004512, + "tokens / sec": 4692.928333043902, + "mem allocated avg": 6781943875.584, + "mem reserved avg": 15848840364.032, + "elapsed time": 759.7957223660196 + }, + { + "step": 3250, + "valid accuracy": 0.36, + "train loss": 0.6960364075899124, + "train samples": 13000, + "train time": 45.38897958409507, + "eval time": 8.616416077013128, + "tokens / sec": 4646.524375134943, + "mem allocated avg": 6784858740.736, + "mem reserved avg": 15725200670.72, + "elapsed time": 817.8723878910532 + }, + { + "step": 3500, + "valid accuracy": 0.4, + "train loss": 0.6833818035125733, + "train samples": 14000, + "train time": 43.60606637201272, + "eval time": 7.672805098001845, + "tokens / sec": 4810.110552292832, + "mem allocated avg": 6782173394.944, + "mem reserved avg": 15725863370.752, + "elapsed time": 873.291599542019 + }, + { + "step": 3750, + "valid accuracy": 0.36, + "train loss": 0.6804632662534714, + "train samples": 15000, + "train time": 44.50026800244814, + "eval time": 8.241878828965127, + "tokens / sec": 4869.70100917321, + "mem allocated avg": 6793631014.912, + "mem reserved avg": 16037810536.448, + "elapsed time": 930.1443349370384 + }, + { + "step": 4000, + "valid accuracy": 0.36, + "train loss": 0.6991109738349914, + "train samples": 16000, + "train time": 42.83764784556115, + "eval time": 7.653670433035586, + "tokens / sec": 4770.8735254747935, + "mem allocated avg": 6774149611.52, + "mem reserved avg": 15730233835.52, + "elapsed time": 984.7777602920542 + }, + { + "step": 4250, + "valid accuracy": 0.38, + "train loss": 0.6788504232168198, + "train samples": 17000, + "train time": 44.51924567105016, + "eval time": 7.663433300971519, + "tokens / sec": 4748.261045614738, + "mem allocated avg": 6785154426.88, + "mem reserved avg": 15703524507.648, + "elapsed time": 1040.9056276420015 + }, + { + "step": 4500, + "valid accuracy": 0.38, + "train loss": 0.6892099533081054, + "train samples": 18000, + "train time": 44.30832453438779, + "eval time": 9.274187314964365, + "tokens / sec": 4690.269880069872, + "mem allocated avg": 6780451182.592, + "mem reserved avg": 15700773044.224, + "elapsed time": 1098.7072390830144 + }, + { + "step": 4750, + "valid accuracy": 0.4, + "train loss": 0.6815461959838868, + "train samples": 19000, + "train time": 43.495211453642696, + "eval time": 7.511790357995778, + "tokens / sec": 4826.715240222559, + "mem allocated avg": 6782852112.384, + "mem reserved avg": 15813943754.752, + "elapsed time": 1153.775285233045 + }, + { + "step": 5000, + "valid accuracy": 0.36, + "train loss": 0.6875366779565811, + "train samples": 20000, + "train time": 43.26518003502861, + "eval time": 9.198009185027331, + "tokens / sec": 4814.032897387025, + "mem allocated avg": 6779266990.08, + "mem reserved avg": 15458820423.68, + "elapsed time": 1210.3138140790397 + }, + { + "step": 5000, + "test accuracy": 0.379833206974981, + "train loss": 0.6875366779565811, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.3052024841308594 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank10-target-mlp.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank10-target-mlp.json new file mode 100644 index 0000000000000000000000000000000000000000..d5362fe9be6bc272369ffbc20b67f2c555dfe6ec --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank10-target-mlp.json @@ -0,0 +1,375 @@ +{ + "run_info": { + "created_at": "2026-01-10T02:16:05+00:00", + "total_time": 1280.0792806840036, + "experiment_name": "lora/llama-3.2-3B-rank10-target-mlp", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "LORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 10, + "target_modules": [ + "up_proj", + "gate_proj", + "down_proj" + ], + "exclude_modules": null, + "lora_alpha": 20, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": false, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": false, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": null, + "arrow_config": null, + "ensure_weight_tying": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 15498352577, + "accelerator_memory_max": 24693964800, + "accelerator_memory_reserved_99th": 22066233344, + "train_time": 1084.286043549073, + "file_size": 37868984, + "num_trainable_params": 9461760, + "num_total_params": 3222211584, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.28, + "train loss": 0.956905131816864, + "train samples": 1000, + "train time": 34.45501961914124, + "eval time": 8.187887417967431, + "tokens / sec": 6144.794063108907, + "mem allocated avg": 6931928963.072, + "mem reserved avg": 15621727191.04, + "elapsed time": 66.55439633503556 + }, + { + "step": 500, + "valid accuracy": 0.34, + "train loss": 0.6960876834392548, + "train samples": 2000, + "train time": 34.311293395468965, + "eval time": 12.610760554962326, + "tokens / sec": 6061.998234886334, + "mem allocated avg": 6925043042.304, + "mem reserved avg": 15157191245.824, + "elapsed time": 116.78655780700501 + }, + { + "step": 750, + "valid accuracy": 0.4, + "train loss": 0.6628184849023819, + "train samples": 3000, + "train time": 34.70101865468314, + "eval time": 7.451941114966758, + "tokens / sec": 6178.5217930789795, + "mem allocated avg": 6935014987.776, + "mem reserved avg": 15434812227.584, + "elapsed time": 162.2516898770118 + }, + { + "step": 1000, + "valid accuracy": 0.42, + "train loss": 0.6416039798259735, + "train samples": 4000, + "train time": 34.48607983236434, + "eval time": 6.998231331992429, + "tokens / sec": 6041.162144630941, + "mem allocated avg": 6926214045.696, + "mem reserved avg": 15482434355.2, + "elapsed time": 207.0800661740359 + }, + { + "step": 1250, + "valid accuracy": 0.38, + "train loss": 0.6370971938371658, + "train samples": 5000, + "train time": 34.169997635355685, + "eval time": 7.873161940020509, + "tokens / sec": 6102.956231528264, + "mem allocated avg": 6926345869.312, + "mem reserved avg": 15533814579.2, + "elapsed time": 252.415388560039 + }, + { + "step": 1500, + "valid accuracy": 0.5, + "train loss": 0.6280006822347641, + "train samples": 6000, + "train time": 34.276999980502296, + "eval time": 8.087436428992078, + "tokens / sec": 6107.039709399109, + "mem allocated avg": 6927777204.224, + "mem reserved avg": 15449374851.072, + "elapsed time": 298.10151039704215 + }, + { + "step": 1750, + "valid accuracy": 0.42, + "train loss": 0.6198004070520401, + "train samples": 7000, + "train time": 34.87267060915474, + "eval time": 12.61192423501052, + "tokens / sec": 6003.411735981022, + "mem allocated avg": 6928959924.224, + "mem reserved avg": 15878183714.816, + "elapsed time": 348.9116879070061 + }, + { + "step": 2000, + "valid accuracy": 0.36, + "train loss": 0.62178213763237, + "train samples": 8000, + "train time": 34.02151767432224, + "eval time": 7.202711585967336, + "tokens / sec": 6104.842293874464, + "mem allocated avg": 6924543111.168, + "mem reserved avg": 15504924213.248, + "elapsed time": 393.50626342202304 + }, + { + "step": 2250, + "valid accuracy": 0.52, + "train loss": 0.6131408748626709, + "train samples": 9000, + "train time": 34.81766810180852, + "eval time": 10.382788593007717, + "tokens / sec": 6173.532339141203, + "mem allocated avg": 6936508715.008, + "mem reserved avg": 15821845823.488, + "elapsed time": 441.9828996449942 + }, + { + "step": 2500, + "valid accuracy": 0.48, + "train loss": 0.6092700402736664, + "train samples": 10000, + "train time": 33.81983969331486, + "eval time": 12.668855660012923, + "tokens / sec": 6090.123485733533, + "mem allocated avg": 6922254147.584, + "mem reserved avg": 15216221880.32, + "elapsed time": 491.83312584704254 + }, + { + "step": 2750, + "valid accuracy": 0.52, + "train loss": 0.599810087800026, + "train samples": 11000, + "train time": 34.98453600978246, + "eval time": 12.589807912008837, + "tokens / sec": 6056.418754296279, + "mem allocated avg": 6932940275.712, + "mem reserved avg": 15688190132.224, + "elapsed time": 542.6733375560143 + }, + { + "step": 3000, + "valid accuracy": 0.38, + "train loss": 0.5911425656080246, + "train samples": 12000, + "train time": 34.17171706445515, + "eval time": 10.20739641803084, + "tokens / sec": 6108.297092776719, + "mem allocated avg": 6927596806.144, + "mem reserved avg": 15592476114.944, + "elapsed time": 590.4343665740453 + }, + { + "step": 3250, + "valid accuracy": 0.48, + "train loss": 0.5990802057981491, + "train samples": 13000, + "train time": 34.13041735702427, + "eval time": 9.451952209987212, + "tokens / sec": 6179.268123030882, + "mem allocated avg": 6930062843.904, + "mem reserved avg": 15432622800.896, + "elapsed time": 637.2517090940382 + }, + { + "step": 3500, + "valid accuracy": 0.54, + "train loss": 0.5822520101070404, + "train samples": 14000, + "train time": 34.94589354854543, + "eval time": 12.59894744300982, + "tokens / sec": 6002.135836321477, + "mem allocated avg": 6928036900.864, + "mem reserved avg": 15451773992.96, + "elapsed time": 688.1364196360228 + }, + { + "step": 3750, + "valid accuracy": 0.62, + "train loss": 0.5812049109935761, + "train samples": 15000, + "train time": 35.20199201494688, + "eval time": 12.605403171968646, + "tokens / sec": 6155.986851766434, + "mem allocated avg": 6939365515.264, + "mem reserved avg": 15827197755.392, + "elapsed time": 739.258546972007 + }, + { + "step": 4000, + "valid accuracy": 0.48, + "train loss": 0.5900991085767746, + "train samples": 16000, + "train time": 33.90330129902577, + "eval time": 8.236152897006832, + "tokens / sec": 6028.115026245918, + "mem allocated avg": 6919923267.584, + "mem reserved avg": 15453300719.616, + "elapsed time": 784.7485570590361 + }, + { + "step": 4250, + "valid accuracy": 0.52, + "train loss": 0.5774198567867279, + "train samples": 17000, + "train time": 34.68033379589906, + "eval time": 7.178619690006599, + "tokens / sec": 6095.356556948615, + "mem allocated avg": 6930677893.12, + "mem reserved avg": 15433386164.224, + "elapsed time": 829.8555172120105 + }, + { + "step": 4500, + "valid accuracy": 0.5, + "train loss": 0.5839589636325836, + "train samples": 18000, + "train time": 33.97633226803737, + "eval time": 7.210191433026921, + "tokens / sec": 6116.551909150627, + "mem allocated avg": 6925906124.8, + "mem reserved avg": 15420786475.008, + "elapsed time": 874.4303943190025 + }, + { + "step": 4750, + "valid accuracy": 0.52, + "train loss": 0.575189305305481, + "train samples": 19000, + "train time": 34.245364292524755, + "eval time": 10.291229791007936, + "tokens / sec": 6130.435588498806, + "mem allocated avg": 6928215662.592, + "mem reserved avg": 15476939816.96, + "elapsed time": 922.2494909689995 + }, + { + "step": 5000, + "valid accuracy": 0.5, + "train loss": 0.5811728711128235, + "train samples": 20000, + "train time": 34.228812442102935, + "eval time": 8.269593706994783, + "tokens / sec": 6084.932112450577, + "mem allocated avg": 6926067277.824, + "mem reserved avg": 15089847500.8, + "elapsed time": 968.0756093530217 + }, + { + "step": 5000, + "test accuracy": 0.5109931766489765, + "train loss": 0.5811728711128235, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.4244680404663086 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank14-target-mlp-bdlora.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank14-target-mlp-bdlora.json new file mode 100644 index 0000000000000000000000000000000000000000..a25edbdaa24c5865567ff3cc3f87e852d80cb952 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank14-target-mlp-bdlora.json @@ -0,0 +1,388 @@ +{ + "run_info": { + "created_at": "2026-01-10T02:37:29+00:00", + "total_time": 1449.8443840030232, + "experiment_name": "lora/llama-3.2-3B-rank14-target-mlp-bdlora", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "LORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 14, + "target_modules": [ + "gate_proj", + "up_proj", + "down_proj" + ], + "exclude_modules": null, + "lora_alpha": 28, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": false, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": false, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": { + "target_modules_bd_a": [ + "o_proj", + "down_proj" + ], + "target_modules_bd_b": [ + "q_proj", + "v_proj", + "k_proj", + "up_proj", + "gate_proj" + ], + "nblocks": 2 + }, + "arrow_config": null, + "ensure_weight_tying": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 15486387067, + "accelerator_memory_max": 24685576192, + "accelerator_memory_reserved_99th": 22066233344, + "train_time": 1247.0251060129958, + "file_size": 33740152, + "num_trainable_params": 8429568, + "num_total_params": 3221179392, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.38, + "train loss": 0.9585020205974579, + "train samples": 1000, + "train time": 40.947455714514945, + "eval time": 9.724019955960102, + "tokens / sec": 5170.504401448084, + "mem allocated avg": 6915241809.92, + "mem reserved avg": 15587350675.456, + "elapsed time": 76.15033562999452 + }, + { + "step": 500, + "valid accuracy": 0.34, + "train loss": 0.6961374168395996, + "train samples": 2000, + "train time": 40.97218767303275, + "eval time": 12.660414524958469, + "tokens / sec": 5076.492416266536, + "mem allocated avg": 6908625721.344, + "mem reserved avg": 15151772205.056, + "elapsed time": 133.12352299899794 + }, + { + "step": 750, + "valid accuracy": 0.32, + "train loss": 0.6627170724868774, + "train samples": 3000, + "train time": 41.68421668821247, + "eval time": 8.807691658032127, + "tokens / sec": 5143.45757301057, + "mem allocated avg": 6919140038.656, + "mem reserved avg": 15427161817.088, + "elapsed time": 186.93488279398298 + }, + { + "step": 1000, + "valid accuracy": 0.44, + "train loss": 0.6412999538183213, + "train samples": 4000, + "train time": 40.972820968716405, + "eval time": 15.062458469008561, + "tokens / sec": 5084.736541793616, + "mem allocated avg": 6909692874.752, + "mem reserved avg": 15471554330.624, + "elapsed time": 246.33008374396013 + }, + { + "step": 1250, + "valid accuracy": 0.4, + "train loss": 0.6367096021175385, + "train samples": 5000, + "train time": 40.94994170789141, + "eval time": 14.975786323018838, + "tokens / sec": 5092.510301664554, + "mem allocated avg": 6909957285.888, + "mem reserved avg": 15508665532.416, + "elapsed time": 305.5784399929689 + }, + { + "step": 1500, + "valid accuracy": 0.5, + "train loss": 0.6278209384679795, + "train samples": 6000, + "train time": 40.83828021842055, + "eval time": 9.454851284972392, + "tokens / sec": 5125.852481554279, + "mem allocated avg": 6911538085.888, + "mem reserved avg": 15441019797.504, + "elapsed time": 359.22269572195364 + }, + { + "step": 1750, + "valid accuracy": 0.42, + "train loss": 0.6189806928634644, + "train samples": 7000, + "train time": 41.167949416907504, + "eval time": 8.857150142022874, + "tokens / sec": 5085.388098393329, + "mem allocated avg": 6912511498.24, + "mem reserved avg": 15868285157.376, + "elapsed time": 412.59175090299686 + }, + { + "step": 2000, + "valid accuracy": 0.4, + "train loss": 0.6215936172008515, + "train samples": 8000, + "train time": 39.99366526392987, + "eval time": 8.554796635988168, + "tokens / sec": 5193.222442338142, + "mem allocated avg": 6908099178.496, + "mem reserved avg": 15486578327.552, + "elapsed time": 464.5223481360008 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6134832800626755, + "train samples": 9000, + "train time": 40.83385715901386, + "eval time": 9.429859316034708, + "tokens / sec": 5263.965124895172, + "mem allocated avg": 6920264648.704, + "mem reserved avg": 15807736184.832, + "elapsed time": 518.1040934349876 + }, + { + "step": 2500, + "valid accuracy": 0.42, + "train loss": 0.6091812270879745, + "train samples": 10000, + "train time": 39.71863999107154, + "eval time": 9.170394071028568, + "tokens / sec": 5185.650869372664, + "mem allocated avg": 6906021558.272, + "mem reserved avg": 15211985633.28, + "elapsed time": 570.3839986599633 + }, + { + "step": 2750, + "valid accuracy": 0.52, + "train loss": 0.6002322329282761, + "train samples": 11000, + "train time": 40.94364706269698, + "eval time": 9.519503901014104, + "tokens / sec": 5174.942028870724, + "mem allocated avg": 6916685307.904, + "mem reserved avg": 15683366682.624, + "elapsed time": 624.1543187929783 + }, + { + "step": 3000, + "valid accuracy": 0.44, + "train loss": 0.5916472736597062, + "train samples": 12000, + "train time": 41.149513348413166, + "eval time": 9.368373601988424, + "tokens / sec": 5072.50227317814, + "mem allocated avg": 6910862186.496, + "mem reserved avg": 15584163004.416, + "elapsed time": 678.0904719049577 + }, + { + "step": 3250, + "valid accuracy": 0.52, + "train loss": 0.6005176463127136, + "train samples": 13000, + "train time": 41.157697485759854, + "eval time": 9.39710839802865, + "tokens / sec": 5124.217652675289, + "mem allocated avg": 6913147236.352, + "mem reserved avg": 15416206295.04, + "elapsed time": 731.8966049049632 + }, + { + "step": 3500, + "valid accuracy": 0.54, + "train loss": 0.5828959219455719, + "train samples": 14000, + "train time": 40.61929137952393, + "eval time": 8.772685625997838, + "tokens / sec": 5163.802540034817, + "mem allocated avg": 6912162123.776, + "mem reserved avg": 15441204346.88, + "elapsed time": 784.6333682870027 + }, + { + "step": 3750, + "valid accuracy": 0.54, + "train loss": 0.5827477180957794, + "train samples": 15000, + "train time": 41.78944715799298, + "eval time": 8.540672906965483, + "tokens / sec": 5185.591452806565, + "mem allocated avg": 6922672640.0, + "mem reserved avg": 15820361039.872, + "elapsed time": 838.2750829259749 + }, + { + "step": 4000, + "valid accuracy": 0.56, + "train loss": 0.5919854927062989, + "train samples": 16000, + "train time": 40.357097996922676, + "eval time": 8.853416519996244, + "tokens / sec": 5064.115363686059, + "mem allocated avg": 6903590129.664, + "mem reserved avg": 15445197324.288, + "elapsed time": 890.848429523001 + }, + { + "step": 4250, + "valid accuracy": 0.56, + "train loss": 0.5791787240505218, + "train samples": 17000, + "train time": 40.23014218133176, + "eval time": 8.847462174016982, + "tokens / sec": 5254.492988048452, + "mem allocated avg": 6914294579.2, + "mem reserved avg": 15425500872.704, + "elapsed time": 943.1942599099712 + }, + { + "step": 4500, + "valid accuracy": 0.5, + "train loss": 0.585926919221878, + "train samples": 18000, + "train time": 39.97698019299423, + "eval time": 8.84911245398689, + "tokens / sec": 5198.441678104017, + "mem allocated avg": 6909213696.0, + "mem reserved avg": 15410191663.104, + "elapsed time": 995.4117041879799 + }, + { + "step": 4750, + "valid accuracy": 0.52, + "train loss": 0.5774390150308609, + "train samples": 19000, + "train time": 40.493067349656485, + "eval time": 8.984108597971499, + "tokens / sec": 5184.566488559207, + "mem allocated avg": 6911982841.856, + "mem reserved avg": 15462503022.592, + "elapsed time": 1048.1989943929948 + }, + { + "step": 5000, + "valid accuracy": 0.52, + "train loss": 0.5829407849311828, + "train samples": 20000, + "train time": 40.788713948684745, + "eval time": 11.74522749998141, + "tokens / sec": 5106.314463898809, + "mem allocated avg": 6909793161.216, + "mem reserved avg": 15076937433.088, + "elapsed time": 1104.0808472170029 + }, + { + "step": 5000, + "test accuracy": 0.513267626990144, + "train loss": 0.5829407849311828, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.38550758361816406 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32-dora.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32-dora.json new file mode 100644 index 0000000000000000000000000000000000000000..e0683ebf010b202d101376a9d20ead6816601903 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32-dora.json @@ -0,0 +1,374 @@ +{ + "run_info": { + "created_at": "2026-01-10T03:21:22+00:00", + "total_time": 1503.135829265986, + "experiment_name": "lora/llama-3.2-3B-rank32-dora", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "LORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "lora_alpha": 64, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": false, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": true, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": null, + "arrow_config": null, + "ensure_weight_tying": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 15412689371, + "accelerator_memory_max": 24547164160, + "accelerator_memory_reserved_99th": 22162702336, + "train_time": 1216.6712898398982, + "file_size": 37181760, + "num_trainable_params": 9289728, + "num_total_params": 3222039552, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.26, + "train loss": 0.9799610931873322, + "train samples": 1000, + "train time": 35.417795918125194, + "eval time": 17.352634231036063, + "tokens / sec": 5977.757636003882, + "mem allocated avg": 6925407713.28, + "mem reserved avg": 15541154611.2, + "elapsed time": 75.89598628797103 + }, + { + "step": 500, + "valid accuracy": 0.44, + "train loss": 0.7162615118026734, + "train samples": 2000, + "train time": 35.72266378562199, + "eval time": 17.35569141904125, + "tokens / sec": 5822.494124408378, + "mem allocated avg": 6918067554.304, + "mem reserved avg": 15118301659.136, + "elapsed time": 132.76655074994778 + }, + { + "step": 750, + "valid accuracy": 0.46, + "train loss": 0.6789851016998291, + "train samples": 3000, + "train time": 36.546013267710805, + "eval time": 11.214822898968123, + "tokens / sec": 5866.60433873995, + "mem allocated avg": 6928052195.328, + "mem reserved avg": 15356437463.04, + "elapsed time": 184.19187769596465 + }, + { + "step": 1000, + "valid accuracy": 0.4, + "train loss": 0.6588249838352204, + "train samples": 4000, + "train time": 36.061139613215346, + "eval time": 13.717305009020492, + "tokens / sec": 5777.299393046663, + "mem allocated avg": 6919732948.992, + "mem reserved avg": 15453527212.032, + "elapsed time": 237.84873885498382 + }, + { + "step": 1250, + "valid accuracy": 0.36, + "train loss": 0.6543591912984849, + "train samples": 5000, + "train time": 35.93075305066304, + "eval time": 17.338175220997073, + "tokens / sec": 5803.886150283504, + "mem allocated avg": 6919911497.728, + "mem reserved avg": 15469197131.776, + "elapsed time": 294.79154046898475 + }, + { + "step": 1500, + "valid accuracy": 0.4, + "train loss": 0.6470256053209305, + "train samples": 6000, + "train time": 36.02197089209221, + "eval time": 17.308061218995135, + "tokens / sec": 5811.203407694546, + "mem allocated avg": 6921449252.864, + "mem reserved avg": 15339878350.848, + "elapsed time": 351.9409700029646 + }, + { + "step": 1750, + "valid accuracy": 0.46, + "train loss": 0.6376578369140625, + "train samples": 7000, + "train time": 36.077694381529, + "eval time": 12.42961401498178, + "tokens / sec": 5802.892994935542, + "mem allocated avg": 6922675496.96, + "mem reserved avg": 15837507354.624, + "elapsed time": 404.2594750869903 + }, + { + "step": 2000, + "valid accuracy": 0.38, + "train loss": 0.6405653357505798, + "train samples": 8000, + "train time": 36.009058863681275, + "eval time": 11.470333072997164, + "tokens / sec": 5767.881931773622, + "mem allocated avg": 6919334260.736, + "mem reserved avg": 15421482729.472, + "elapsed time": 455.6199949949514 + }, + { + "step": 2250, + "valid accuracy": 0.46, + "train loss": 0.6328598493337632, + "train samples": 9000, + "train time": 36.205427291512024, + "eval time": 17.303009946015663, + "tokens / sec": 5936.899964453458, + "mem allocated avg": 6930608842.752, + "mem reserved avg": 15744427360.256, + "elapsed time": 512.8717058099573 + }, + { + "step": 2500, + "valid accuracy": 0.42, + "train loss": 0.629319528579712, + "train samples": 10000, + "train time": 34.97963203344261, + "eval time": 17.334575710003264, + "tokens / sec": 5888.1980177230935, + "mem allocated avg": 6915153993.728, + "mem reserved avg": 15108914806.784, + "elapsed time": 568.9176407279447 + }, + { + "step": 2750, + "valid accuracy": 0.34, + "train loss": 0.6210904417037963, + "train samples": 11000, + "train time": 35.76373431546381, + "eval time": 14.790576178987976, + "tokens / sec": 5924.4652175034535, + "mem allocated avg": 6926034331.648, + "mem reserved avg": 15580086140.928, + "elapsed time": 623.1745745909866 + }, + { + "step": 3000, + "valid accuracy": 0.42, + "train loss": 0.6132080693244935, + "train samples": 12000, + "train time": 35.911868128867354, + "eval time": 14.77954756503459, + "tokens / sec": 5812.312499338176, + "mem allocated avg": 6920991168.512, + "mem reserved avg": 15530618519.552, + "elapsed time": 677.7459287579986 + }, + { + "step": 3250, + "valid accuracy": 0.48, + "train loss": 0.6221653089523316, + "train samples": 13000, + "train time": 35.66093143681064, + "eval time": 17.444324638985563, + "tokens / sec": 5914.063135835525, + "mem allocated avg": 6923086110.72, + "mem reserved avg": 15357922246.656, + "elapsed time": 734.5032512069447 + }, + { + "step": 3500, + "valid accuracy": 0.5, + "train loss": 0.6054375174045563, + "train samples": 14000, + "train time": 35.69942569779232, + "eval time": 10.496662761026528, + "tokens / sec": 5875.444657726555, + "mem allocated avg": 6920997902.336, + "mem reserved avg": 15300158291.968, + "elapsed time": 784.4919563499861 + }, + { + "step": 3750, + "valid accuracy": 0.54, + "train loss": 0.6029420564174652, + "train samples": 15000, + "train time": 36.43003757862607, + "eval time": 12.152991220995318, + "tokens / sec": 5948.47039430841, + "mem allocated avg": 6933233727.488, + "mem reserved avg": 15711619514.368, + "elapsed time": 836.8070459629525 + }, + { + "step": 4000, + "valid accuracy": 0.46, + "train loss": 0.616380462884903, + "train samples": 16000, + "train time": 35.82399892428657, + "eval time": 10.243308471050113, + "tokens / sec": 5704.918661703261, + "mem allocated avg": 6913596911.616, + "mem reserved avg": 15358928879.616, + "elapsed time": 886.7407023639535 + }, + { + "step": 4250, + "valid accuracy": 0.5, + "train loss": 0.6010915513038635, + "train samples": 17000, + "train time": 36.03616644133581, + "eval time": 17.357441558968276, + "tokens / sec": 5866.023522344573, + "mem allocated avg": 6924514760.704, + "mem reserved avg": 15282240225.28, + "elapsed time": 943.718220997951 + }, + { + "step": 4500, + "valid accuracy": 0.48, + "train loss": 0.6073519963026047, + "train samples": 18000, + "train time": 36.01844966417411, + "eval time": 10.97284383297665, + "tokens / sec": 5769.765271343896, + "mem allocated avg": 6919068428.288, + "mem reserved avg": 15324342648.832, + "elapsed time": 994.5949146979838 + }, + { + "step": 4750, + "valid accuracy": 0.48, + "train loss": 0.59943410551548, + "train samples": 19000, + "train time": 36.32360130321467, + "eval time": 11.35271465400001, + "tokens / sec": 5779.685726850554, + "mem allocated avg": 6921889050.624, + "mem reserved avg": 15411919716.352, + "elapsed time": 1045.9306690069498 + }, + { + "step": 5000, + "valid accuracy": 0.5, + "train loss": 0.6067105796337128, + "train samples": 20000, + "train time": 35.769867127528414, + "eval time": 10.729407122998964, + "tokens / sec": 5822.778129352014, + "mem allocated avg": 6918440036.352, + "mem reserved avg": 15005122560.0, + "elapsed time": 1096.1181151779601 + }, + { + "step": 5000, + "test accuracy": 0.4799090219863533, + "train loss": 0.6067105796337128, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.42719078063964844 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32-lorafa.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32-lorafa.json new file mode 100644 index 0000000000000000000000000000000000000000..77839d718ac7cd67c8a6c6e353855fd376f864be --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32-lorafa.json @@ -0,0 +1,376 @@ +{ + "run_info": { + "created_at": "2026-01-10T03:46:29+00:00", + "total_time": 1342.1041010030312, + "experiment_name": "lora/llama-3.2-3B-rank32-lorafa", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "lora-fa", + "optimizer_kwargs": { + "r": 32, + "lora_alpha": 64, + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "LORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "lora_alpha": 64, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": false, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": false, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": null, + "arrow_config": null, + "ensure_weight_tying": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 13388834091, + "accelerator_memory_max": 20206059520, + "accelerator_memory_reserved_99th": 18423480320, + "train_time": 1120.0941248898162, + "file_size": 36715216, + "num_trainable_params": 3670016, + "num_total_params": 3221924864, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.26, + "train loss": 1.1382666566371917, + "train samples": 1000, + "train time": 38.28122999728657, + "eval time": 12.03737130900845, + "tokens / sec": 5530.6216653698675, + "mem allocated avg": 6860955803.648, + "mem reserved avg": 13463397072.896, + "elapsed time": 74.45199455297552 + }, + { + "step": 500, + "valid accuracy": 0.34, + "train loss": 0.8058973848819733, + "train samples": 2000, + "train time": 38.396226758370176, + "eval time": 12.014686524984427, + "tokens / sec": 5417.068747638286, + "mem allocated avg": 6853930907.648, + "mem reserved avg": 13148698443.776, + "elapsed time": 127.58669048099546 + }, + { + "step": 750, + "valid accuracy": 0.34, + "train loss": 0.7258100744485855, + "train samples": 3000, + "train time": 38.67140380904311, + "eval time": 12.018376077001449, + "tokens / sec": 5544.174218724985, + "mem allocated avg": 6863542669.312, + "mem reserved avg": 13364780597.248, + "elapsed time": 181.01454636198469 + }, + { + "step": 1000, + "valid accuracy": 0.36, + "train loss": 0.6959180034399033, + "train samples": 4000, + "train time": 38.689740434405394, + "eval time": 12.171833780012093, + "tokens / sec": 5384.786707298101, + "mem allocated avg": 6854990675.968, + "mem reserved avg": 13398603464.704, + "elapsed time": 234.65134076797403 + }, + { + "step": 1250, + "valid accuracy": 0.4, + "train loss": 0.6883955686092377, + "train samples": 5000, + "train time": 37.8607366749784, + "eval time": 11.988320239004679, + "tokens / sec": 5508.028060579701, + "mem allocated avg": 6855320889.344, + "mem reserved avg": 13438013145.088, + "elapsed time": 287.2428716639988 + }, + { + "step": 1500, + "valid accuracy": 0.36, + "train loss": 0.6802743972539902, + "train samples": 6000, + "train time": 37.84619458694942, + "eval time": 12.051020699029323, + "tokens / sec": 5531.097704395993, + "mem allocated avg": 6857234538.496, + "mem reserved avg": 13349186174.976, + "elapsed time": 339.8987459249911 + }, + { + "step": 1750, + "valid accuracy": 0.44, + "train loss": 0.6713488042354584, + "train samples": 7000, + "train time": 38.03005455125822, + "eval time": 6.861379031033721, + "tokens / sec": 5504.9881592419, + "mem allocated avg": 6858592649.216, + "mem reserved avg": 13688270487.552, + "elapsed time": 387.54206994600827 + }, + { + "step": 2000, + "valid accuracy": 0.34, + "train loss": 0.6732557244300842, + "train samples": 8000, + "train time": 37.907950733962934, + "eval time": 9.611344902019482, + "tokens / sec": 5478.956155071674, + "mem allocated avg": 6854296047.616, + "mem reserved avg": 13373387309.056, + "elapsed time": 437.8645573030226 + }, + { + "step": 2250, + "valid accuracy": 0.4, + "train loss": 0.6658673313856125, + "train samples": 9000, + "train time": 39.20586472720606, + "eval time": 12.025575989042409, + "tokens / sec": 5482.54710094027, + "mem allocated avg": 6864924219.392, + "mem reserved avg": 13638182109.184, + "elapsed time": 491.79203153197886 + }, + { + "step": 2500, + "valid accuracy": 0.4, + "train loss": 0.6645902947187424, + "train samples": 10000, + "train time": 37.9725074750022, + "eval time": 12.050091590033844, + "tokens / sec": 5424.108485213697, + "mem allocated avg": 6851850416.128, + "mem reserved avg": 13178209566.72, + "elapsed time": 544.5313534020097 + }, + { + "step": 2750, + "valid accuracy": 0.48, + "train loss": 0.6584658966064453, + "train samples": 11000, + "train time": 38.62057857518084, + "eval time": 12.022568356012926, + "tokens / sec": 5486.220243633619, + "mem allocated avg": 6860907974.656, + "mem reserved avg": 13517839138.816, + "elapsed time": 597.8993249600171 + }, + { + "step": 3000, + "valid accuracy": 0.44, + "train loss": 0.6503710049390793, + "train samples": 12000, + "train time": 38.213741579907946, + "eval time": 12.023225912998896, + "tokens / sec": 5462.197402563343, + "mem allocated avg": 6856872128.512, + "mem reserved avg": 13452542214.144, + "elapsed time": 650.9364468560088 + }, + { + "step": 3250, + "valid accuracy": 0.48, + "train loss": 0.6599701564311982, + "train samples": 13000, + "train time": 37.91452166024828, + "eval time": 11.357707492948975, + "tokens / sec": 5562.538857535435, + "mem allocated avg": 6859697266.688, + "mem reserved avg": 13314373451.776, + "elapsed time": 702.8724391320138 + }, + { + "step": 3500, + "valid accuracy": 0.46, + "train loss": 0.646973167181015, + "train samples": 14000, + "train time": 37.81747335771797, + "eval time": 11.383261173032224, + "tokens / sec": 5546.377940587435, + "mem allocated avg": 6856628082.688, + "mem reserved avg": 13340680126.464, + "elapsed time": 754.8501812759787 + }, + { + "step": 3750, + "valid accuracy": 0.38, + "train loss": 0.6448353365659714, + "train samples": 15000, + "train time": 38.43758335191524, + "eval time": 11.972405905020423, + "tokens / sec": 5637.7894004411255, + "mem allocated avg": 6867760596.992, + "mem reserved avg": 13645018824.704, + "elapsed time": 808.0009117710288 + }, + { + "step": 4000, + "valid accuracy": 0.42, + "train loss": 0.6610955271720886, + "train samples": 16000, + "train time": 37.65237786894431, + "eval time": 11.012930686993059, + "tokens / sec": 5427.890921294691, + "mem allocated avg": 6848820500.48, + "mem reserved avg": 13351971192.832, + "elapsed time": 859.4539053810295 + }, + { + "step": 4250, + "valid accuracy": 0.44, + "train loss": 0.6431050715446472, + "train samples": 17000, + "train time": 38.30668486945797, + "eval time": 8.816615463001654, + "tokens / sec": 5518.331871326748, + "mem allocated avg": 6860700841.984, + "mem reserved avg": 13334833266.688, + "elapsed time": 909.1930963720079 + }, + { + "step": 4500, + "valid accuracy": 0.44, + "train loss": 0.6520027537345886, + "train samples": 18000, + "train time": 38.130526454304345, + "eval time": 9.092709565011319, + "tokens / sec": 5450.173898045947, + "mem allocated avg": 6855184822.272, + "mem reserved avg": 13305347309.568, + "elapsed time": 959.1735217869864 + }, + { + "step": 4750, + "valid accuracy": 0.44, + "train loss": 0.6446634820699692, + "train samples": 19000, + "train time": 38.61787147738505, + "eval time": 9.569177008001134, + "tokens / sec": 5436.317227451079, + "mem allocated avg": 6857516408.832, + "mem reserved avg": 13386364485.632, + "elapsed time": 1010.02847156598 + }, + { + "step": 5000, + "valid accuracy": 0.46, + "train loss": 0.6510778307914734, + "train samples": 20000, + "train time": 38.292791458952706, + "eval time": 8.873381062003318, + "tokens / sec": 5439.143819621041, + "mem allocated avg": 6854407677.952, + "mem reserved avg": 13086983454.72, + "elapsed time": 1059.891814726987 + }, + { + "step": 5000, + "test accuracy": 0.42532221379833207, + "train loss": 0.6510778307914734, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.33704090118408203 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32.json new file mode 100644 index 0000000000000000000000000000000000000000..15d77e1544b24988e1e62cdc32834b9925c3116c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank32.json @@ -0,0 +1,374 @@ +{ + "run_info": { + "created_at": "2026-01-10T03:01:44+00:00", + "total_time": 1173.714544863964, + "experiment_name": "lora/llama-3.2-3B-rank32", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "LORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "lora_alpha": 64, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": false, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": false, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": null, + "arrow_config": null, + "ensure_weight_tying": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14427567318, + "accelerator_memory_max": 22286434304, + "accelerator_memory_reserved_99th": 20122173440, + "train_time": 958.3276851720293, + "file_size": 36715216, + "num_trainable_params": 9175040, + "num_total_params": 3221924864, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.34, + "train loss": 0.9826480431556701, + "train samples": 1000, + "train time": 29.567459934856743, + "eval time": 12.036156770016532, + "tokens / sec": 7160.5406912349235, + "mem allocated avg": 6927427098.624, + "mem reserved avg": 14540435619.84, + "elapsed time": 63.864961831015535 + }, + { + "step": 500, + "valid accuracy": 0.46, + "train loss": 0.7163139179944992, + "train samples": 2000, + "train time": 29.46686314494582, + "eval time": 12.008591033983976, + "tokens / sec": 7058.606780670357, + "mem allocated avg": 6920238368.768, + "mem reserved avg": 14166437920.768, + "elapsed time": 108.54651641799137 + }, + { + "step": 750, + "valid accuracy": 0.36, + "train loss": 0.679160294175148, + "train samples": 3000, + "train time": 30.308068415150046, + "eval time": 9.108271537988912, + "tokens / sec": 7074.056883573211, + "mem allocated avg": 6930467016.704, + "mem reserved avg": 14381723156.48, + "elapsed time": 151.1071816039621 + }, + { + "step": 1000, + "valid accuracy": 0.42, + "train loss": 0.6593781963586808, + "train samples": 4000, + "train time": 30.217666860786267, + "eval time": 12.128453835961409, + "tokens / sec": 6894.50978991232, + "mem allocated avg": 6921353275.392, + "mem reserved avg": 14449670881.28, + "elapsed time": 196.77825986297103 + }, + { + "step": 1250, + "valid accuracy": 0.42, + "train loss": 0.6545941867828369, + "train samples": 5000, + "train time": 29.99424036074197, + "eval time": 11.980647846998181, + "tokens / sec": 6952.601482548144, + "mem allocated avg": 6922116595.712, + "mem reserved avg": 14466657812.48, + "elapsed time": 241.93410539499018 + }, + { + "step": 1500, + "valid accuracy": 0.38, + "train loss": 0.647283132314682, + "train samples": 6000, + "train time": 30.01751733769197, + "eval time": 11.991809643048327, + "tokens / sec": 6973.628020101123, + "mem allocated avg": 6923839727.616, + "mem reserved avg": 14383426043.904, + "elapsed time": 287.2019039680017 + }, + { + "step": 1750, + "valid accuracy": 0.42, + "train loss": 0.6378610955476761, + "train samples": 7000, + "train time": 30.147432959987782, + "eval time": 8.299405578000005, + "tokens / sec": 6944.372354285015, + "mem allocated avg": 6925383284.736, + "mem reserved avg": 14772699398.144, + "elapsed time": 328.93911194999237 + }, + { + "step": 2000, + "valid accuracy": 0.36, + "train loss": 0.6409116793870926, + "train samples": 8000, + "train time": 30.117346432991326, + "eval time": 11.998839316016529, + "tokens / sec": 6896.225086167764, + "mem allocated avg": 6921043718.144, + "mem reserved avg": 14419597721.6, + "elapsed time": 374.35504649899667 + }, + { + "step": 2250, + "valid accuracy": 0.42, + "train loss": 0.633124389886856, + "train samples": 9000, + "train time": 30.76248943991959, + "eval time": 11.96315730799688, + "tokens / sec": 6987.340878890907, + "mem allocated avg": 6931688802.304, + "mem reserved avg": 14696019132.416, + "elapsed time": 420.3003967599943 + }, + { + "step": 2500, + "valid accuracy": 0.42, + "train loss": 0.6295496643781662, + "train samples": 10000, + "train time": 29.52961014426546, + "eval time": 12.078024981019553, + "tokens / sec": 6974.931229831966, + "mem allocated avg": 6918595411.968, + "mem reserved avg": 14198885056.512, + "elapsed time": 465.105449871975 + }, + { + "step": 2750, + "valid accuracy": 0.4, + "train loss": 0.6213833647966385, + "train samples": 11000, + "train time": 30.2069385854993, + "eval time": 8.256086013978347, + "tokens / sec": 7014.3155818416, + "mem allocated avg": 6927818975.232, + "mem reserved avg": 14563151970.304, + "elapsed time": 506.76149754499784 + }, + { + "step": 3000, + "valid accuracy": 0.48, + "train loss": 0.6133703490495682, + "train samples": 12000, + "train time": 30.294824214477558, + "eval time": 12.005937494977843, + "tokens / sec": 6889.988815325418, + "mem allocated avg": 6924054609.92, + "mem reserved avg": 14496630308.864, + "elapsed time": 552.3840983010014 + }, + { + "step": 3250, + "valid accuracy": 0.44, + "train loss": 0.6224808418750762, + "train samples": 13000, + "train time": 29.94148239895003, + "eval time": 7.373289940995164, + "tokens / sec": 7043.772822931297, + "mem allocated avg": 6926655715.328, + "mem reserved avg": 14371212230.656, + "elapsed time": 592.8639876859961 + }, + { + "step": 3500, + "valid accuracy": 0.5, + "train loss": 0.6059285970926285, + "train samples": 14000, + "train time": 30.129387284861878, + "eval time": 11.973128407029435, + "tokens / sec": 6961.6417359202715, + "mem allocated avg": 6923676155.904, + "mem reserved avg": 14364719448.064, + "elapsed time": 638.2131494429777 + }, + { + "step": 3750, + "valid accuracy": 0.5, + "train loss": 0.6033647983074188, + "train samples": 15000, + "train time": 30.893273340305313, + "eval time": 7.364776138972957, + "tokens / sec": 7014.569081524799, + "mem allocated avg": 6934723543.04, + "mem reserved avg": 14704281911.296, + "elapsed time": 679.7110908210161 + }, + { + "step": 4000, + "valid accuracy": 0.42, + "train loss": 0.6165854910612106, + "train samples": 16000, + "train time": 29.51253367715981, + "eval time": 12.00497411499964, + "tokens / sec": 6924.956096133736, + "mem allocated avg": 6915841265.664, + "mem reserved avg": 14385749688.32, + "elapsed time": 724.5038471769658 + }, + { + "step": 4250, + "valid accuracy": 0.48, + "train loss": 0.601499475479126, + "train samples": 17000, + "train time": 29.835361877689138, + "eval time": 8.425500162993558, + "tokens / sec": 7085.183041070353, + "mem allocated avg": 6927651903.488, + "mem reserved avg": 14371388391.424, + "elapsed time": 765.8859701670008 + }, + { + "step": 4500, + "valid accuracy": 0.48, + "train loss": 0.6076976944208146, + "train samples": 18000, + "train time": 29.980451503419317, + "eval time": 11.977038996003103, + "tokens / sec": 6931.7835315554885, + "mem allocated avg": 6921458522.112, + "mem reserved avg": 14316107464.704, + "elapsed time": 811.13678931701 + }, + { + "step": 4750, + "valid accuracy": 0.54, + "train loss": 0.5996475745439529, + "train samples": 19000, + "train time": 30.189162221679, + "eval time": 7.3034177150111645, + "tokens / sec": 6954.11811889373, + "mem allocated avg": 6924435124.224, + "mem reserved avg": 14412157026.304, + "elapsed time": 851.8043771950179 + }, + { + "step": 5000, + "valid accuracy": 0.5, + "train loss": 0.6068337166309357, + "train samples": 20000, + "train time": 29.628619944676757, + "eval time": 12.001391948957462, + "tokens / sec": 7029.689549796961, + "mem allocated avg": 6920384235.52, + "mem reserved avg": 14090395189.248, + "elapsed time": 896.6036795430118 + }, + { + "step": 5000, + "test accuracy": 0.49052312357846856, + "train loss": 0.6068337166309357, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.4156990051269531 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank64-rslora.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank64-rslora.json new file mode 100644 index 0000000000000000000000000000000000000000..4e07d97de1bde4b9fcd4a7b9445199bfc003043e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank64-rslora.json @@ -0,0 +1,374 @@ +{ + "run_info": { + "created_at": "2026-01-10T04:28:43+00:00", + "total_time": 1177.140506102005, + "experiment_name": "lora/llama-3.2-3B-rank64-rslora", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "LORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 64, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "lora_alpha": 64, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": true, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": false, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": null, + "arrow_config": null, + "ensure_weight_tying": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14681817219, + "accelerator_memory_max": 22554869760, + "accelerator_memory_reserved_99th": 20363345920, + "train_time": 982.3692580849747, + "file_size": 73415408, + "num_trainable_params": 18350080, + "num_total_params": 3231099904, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.32, + "train loss": 0.8665798449516297, + "train samples": 1000, + "train time": 30.42884735291591, + "eval time": 12.067878839967307, + "tokens / sec": 6957.838315216747, + "mem allocated avg": 7074216630.272, + "mem reserved avg": 14794627219.456, + "elapsed time": 65.52868704096181 + }, + { + "step": 500, + "valid accuracy": 0.36, + "train loss": 0.6969451537132263, + "train samples": 2000, + "train time": 30.028659706760664, + "eval time": 6.849575296975672, + "tokens / sec": 6926.549570681369, + "mem allocated avg": 7067057743.872, + "mem reserved avg": 14420780515.328, + "elapsed time": 106.05690014996799 + }, + { + "step": 750, + "valid accuracy": 0.42, + "train loss": 0.6719447268247605, + "train samples": 3000, + "train time": 30.664972058671992, + "eval time": 12.004266217991244, + "tokens / sec": 6991.723311855027, + "mem allocated avg": 7077370155.008, + "mem reserved avg": 14632534147.072, + "elapsed time": 152.2843752449844 + }, + { + "step": 1000, + "valid accuracy": 0.36, + "train loss": 0.652460936665535, + "train samples": 4000, + "train time": 30.48696271161316, + "eval time": 12.170594627968967, + "tokens / sec": 6833.609565200806, + "mem allocated avg": 7068219230.208, + "mem reserved avg": 14705993187.328, + "elapsed time": 198.70327374298358 + }, + { + "step": 1250, + "valid accuracy": 0.4, + "train loss": 0.6479703410863876, + "train samples": 5000, + "train time": 30.378673091356177, + "eval time": 12.018067600030918, + "tokens / sec": 6864.618456931107, + "mem allocated avg": 7068962146.304, + "mem reserved avg": 14721814102.016, + "elapsed time": 244.72620570997242 + }, + { + "step": 1500, + "valid accuracy": 0.46, + "train loss": 0.6393348515033722, + "train samples": 6000, + "train time": 30.843879525607917, + "eval time": 12.084749042987823, + "tokens / sec": 6786.792168157847, + "mem allocated avg": 7070648739.84, + "mem reserved avg": 14638833991.68, + "elapsed time": 291.3573861339828 + }, + { + "step": 1750, + "valid accuracy": 0.48, + "train loss": 0.6295465973615646, + "train samples": 7000, + "train time": 31.083455514337402, + "eval time": 6.925516706018243, + "tokens / sec": 6735.255026695277, + "mem allocated avg": 7072147429.376, + "mem reserved avg": 15031110467.584, + "elapsed time": 333.1081438650144 + }, + { + "step": 2000, + "valid accuracy": 0.48, + "train loss": 0.629354835152626, + "train samples": 8000, + "train time": 30.73974690376781, + "eval time": 11.996038755984046, + "tokens / sec": 6756.594341853298, + "mem allocated avg": 7067883671.552, + "mem reserved avg": 14674275860.48, + "elapsed time": 379.59074820997193 + }, + { + "step": 2250, + "valid accuracy": 0.48, + "train loss": 0.6158513882160187, + "train samples": 9000, + "train time": 31.485766681085806, + "eval time": 12.010253109037876, + "tokens / sec": 6826.8307447353345, + "mem allocated avg": 7078482102.272, + "mem reserved avg": 14951896842.24, + "elapsed time": 426.7389918650151 + }, + { + "step": 2500, + "valid accuracy": 0.54, + "train loss": 0.6116750190258026, + "train samples": 10000, + "train time": 30.16659908008296, + "eval time": 12.012144456035458, + "tokens / sec": 6827.650656052461, + "mem allocated avg": 7065497255.936, + "mem reserved avg": 14441743646.72, + "elapsed time": 472.54497441998683 + }, + { + "step": 2750, + "valid accuracy": 0.52, + "train loss": 0.5988917994499207, + "train samples": 11000, + "train time": 30.42298925470095, + "eval time": 8.22808063303819, + "tokens / sec": 6964.503002191352, + "mem allocated avg": 7074708860.928, + "mem reserved avg": 14816605372.416, + "elapsed time": 514.8220539310132 + }, + { + "step": 3000, + "valid accuracy": 0.46, + "train loss": 0.5868005758523941, + "train samples": 12000, + "train time": 30.30703110230388, + "eval time": 7.013154852029402, + "tokens / sec": 6887.213706133448, + "mem allocated avg": 7070749229.056, + "mem reserved avg": 14752096976.896, + "elapsed time": 555.8788702209713 + }, + { + "step": 3250, + "valid accuracy": 0.62, + "train loss": 0.5923758454322815, + "train samples": 13000, + "train time": 30.638515021419153, + "eval time": 7.016375864041038, + "tokens / sec": 6883.525518536415, + "mem allocated avg": 7073382963.2, + "mem reserved avg": 14626209136.64, + "elapsed time": 597.1164690629812 + }, + { + "step": 3500, + "valid accuracy": 0.54, + "train loss": 0.5735730677843094, + "train samples": 14000, + "train time": 30.935304028331302, + "eval time": 12.06780532200355, + "tokens / sec": 6780.279250137832, + "mem allocated avg": 7070430666.752, + "mem reserved avg": 14618080575.488, + "elapsed time": 643.7984791700146 + }, + { + "step": 3750, + "valid accuracy": 0.54, + "train loss": 0.5689221447706223, + "train samples": 15000, + "train time": 31.092261793499347, + "eval time": 9.570651119982358, + "tokens / sec": 6969.676295640462, + "mem allocated avg": 7081445613.568, + "mem reserved avg": 14958674837.504, + "elapsed time": 688.1187267049681 + }, + { + "step": 4000, + "valid accuracy": 0.64, + "train loss": 0.5762798600196838, + "train samples": 16000, + "train time": 30.104006341425702, + "eval time": 7.257788410002831, + "tokens / sec": 6788.897055165882, + "mem allocated avg": 7062573928.448, + "mem reserved avg": 14642197823.488, + "elapsed time": 729.1823095660075 + }, + { + "step": 4250, + "valid accuracy": 0.66, + "train loss": 0.5624099019765854, + "train samples": 17000, + "train time": 30.637119862483814, + "eval time": 7.486830469977576, + "tokens / sec": 6899.767372025493, + "mem allocated avg": 7074448791.552, + "mem reserved avg": 14627375153.152, + "elapsed time": 770.8080390199902 + }, + { + "step": 4500, + "valid accuracy": 0.64, + "train loss": 0.568421840429306, + "train samples": 18000, + "train time": 30.23169072222663, + "eval time": 7.723167017975356, + "tokens / sec": 6874.177230425627, + "mem allocated avg": 7068260964.352, + "mem reserved avg": 14572748537.856, + "elapsed time": 812.4831150689861 + }, + { + "step": 4750, + "valid accuracy": 0.7, + "train loss": 0.5584498722553253, + "train samples": 19000, + "train time": 30.594949091493618, + "eval time": 7.525550253980327, + "tokens / sec": 6861.88427286417, + "mem allocated avg": 7071199416.32, + "mem reserved avg": 14665811755.008, + "elapsed time": 854.1516887749895 + }, + { + "step": 5000, + "valid accuracy": 0.64, + "train loss": 0.5659015461206436, + "train samples": 20000, + "train time": 30.757398171175737, + "eval time": 7.549682089011185, + "tokens / sec": 6771.704122723533, + "mem allocated avg": 7067111507.968, + "mem reserved avg": 14342934233.088, + "elapsed time": 896.06547770201 + }, + { + "step": 5000, + "test accuracy": 0.5322213798332069, + "train loss": 0.5659015461206436, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.6632366180419922 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank64.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank64.json new file mode 100644 index 0000000000000000000000000000000000000000..f81de427cab0b4e6091a60f2679128051722eb8e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/lora--llama-3.2-3B-rank64.json @@ -0,0 +1,374 @@ +{ + "run_info": { + "created_at": "2026-01-10T04:08:56+00:00", + "total_time": 1182.5466393660172, + "experiment_name": "lora/llama-3.2-3B-rank64", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "LORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 64, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "lora_alpha": 128, + "lora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "use_rslora": false, + "modules_to_save": null, + "init_lora_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "rank_pattern": {}, + "alpha_pattern": {}, + "megatron_config": null, + "megatron_core": "megatron.core", + "trainable_token_indices": null, + "loftq_config": {}, + "eva_config": null, + "corda_config": null, + "use_dora": false, + "alora_invocation_tokens": null, + "use_qalora": false, + "qalora_group_size": 16, + "layer_replication": null, + "lora_bias": false, + "target_parameters": null, + "use_bdlora": null, + "arrow_config": null, + "ensure_weight_tying": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14680829879, + "accelerator_memory_max": 22554869760, + "accelerator_memory_reserved_99th": 20369637376, + "train_time": 983.3214389311033, + "file_size": 73415408, + "num_trainable_params": 18350080, + "num_total_params": 3231099904, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.38, + "train loss": 0.9425716633796692, + "train samples": 1000, + "train time": 30.139569386141375, + "eval time": 7.757456969993655, + "tokens / sec": 7024.619273338111, + "mem allocated avg": 7074216630.272, + "mem reserved avg": 14794627219.456, + "elapsed time": 61.089543453999795 + }, + { + "step": 500, + "valid accuracy": 0.4, + "train loss": 0.707941146492958, + "train samples": 2000, + "train time": 30.18722614523722, + "eval time": 12.01657494698884, + "tokens / sec": 6890.166025831305, + "mem allocated avg": 7067018012.672, + "mem reserved avg": 14421703262.208, + "elapsed time": 106.94860831601545 + }, + { + "step": 750, + "valid accuracy": 0.46, + "train loss": 0.672982994556427, + "train samples": 3000, + "train time": 31.17097897437634, + "eval time": 8.986971779959276, + "tokens / sec": 6878.22478005087, + "mem allocated avg": 7077317242.88, + "mem reserved avg": 14631695286.272, + "elapsed time": 150.70241837605136 + }, + { + "step": 1000, + "valid accuracy": 0.4, + "train loss": 0.6524584344625473, + "train samples": 4000, + "train time": 30.163662555685733, + "eval time": 12.034879773971625, + "tokens / sec": 6906.853556506502, + "mem allocated avg": 7068152137.728, + "mem reserved avg": 14705372430.336, + "elapsed time": 196.66190933802864 + }, + { + "step": 1250, + "valid accuracy": 0.32, + "train loss": 0.6483220961093903, + "train samples": 5000, + "train time": 30.15837659779936, + "eval time": 11.979068343993276, + "tokens / sec": 6914.762116712108, + "mem allocated avg": 7068966111.232, + "mem reserved avg": 14721310785.536, + "elapsed time": 242.42918774002464 + }, + { + "step": 1500, + "valid accuracy": 0.42, + "train loss": 0.6400836319923401, + "train samples": 6000, + "train time": 30.463665828632656, + "eval time": 12.046926526003517, + "tokens / sec": 6871.497382407956, + "mem allocated avg": 7070724999.168, + "mem reserved avg": 14636988497.92, + "elapsed time": 288.6348234670004 + }, + { + "step": 1750, + "valid accuracy": 0.44, + "train loss": 0.6306325042247772, + "train samples": 7000, + "train time": 30.8206563887652, + "eval time": 6.342445521964692, + "tokens / sec": 6792.684664441944, + "mem allocated avg": 7072154179.584, + "mem reserved avg": 15031026581.504, + "elapsed time": 329.53624591004336 + }, + { + "step": 2000, + "valid accuracy": 0.36, + "train loss": 0.633572401881218, + "train samples": 8000, + "train time": 30.76832819468109, + "eval time": 12.006199798022863, + "tokens / sec": 6750.318011620285, + "mem allocated avg": 7067827228.672, + "mem reserved avg": 14674108088.32, + "elapsed time": 376.048165582004 + }, + { + "step": 2250, + "valid accuracy": 0.48, + "train loss": 0.6247809824943542, + "train samples": 9000, + "train time": 31.255851800669916, + "eval time": 11.957888349017594, + "tokens / sec": 6877.048220307755, + "mem allocated avg": 7078532499.456, + "mem reserved avg": 14951896842.24, + "elapsed time": 422.90829164604656 + }, + { + "step": 2500, + "valid accuracy": 0.46, + "train loss": 0.6205553900003433, + "train samples": 10000, + "train time": 30.488378216978163, + "eval time": 12.01241706701694, + "tokens / sec": 6755.590557627709, + "mem allocated avg": 7065481543.68, + "mem reserved avg": 14441408102.4, + "elapsed time": 469.04079198202817 + }, + { + "step": 2750, + "valid accuracy": 0.4, + "train loss": 0.6116848350763321, + "train samples": 11000, + "train time": 30.81134812964592, + "eval time": 12.024563168000896, + "tokens / sec": 6876.719548539758, + "mem allocated avg": 7074637836.288, + "mem reserved avg": 14815430967.296, + "elapsed time": 515.5033730530413 + }, + { + "step": 3000, + "valid accuracy": 0.48, + "train loss": 0.6029672604799271, + "train samples": 12000, + "train time": 30.93273847439559, + "eval time": 6.518992024997715, + "tokens / sec": 6747.899161038586, + "mem allocated avg": 7070744289.28, + "mem reserved avg": 14750754799.616, + "elapsed time": 556.7073722220375 + }, + { + "step": 3250, + "valid accuracy": 0.5, + "train loss": 0.6111509243249893, + "train samples": 13000, + "train time": 30.533708127739374, + "eval time": 12.115831910981797, + "tokens / sec": 6907.153206472158, + "mem allocated avg": 7073456336.896, + "mem reserved avg": 14612535705.6, + "elapsed time": 602.9381153370487 + }, + { + "step": 3500, + "valid accuracy": 0.56, + "train loss": 0.593697448015213, + "train samples": 14000, + "train time": 30.537241372454446, + "eval time": 9.105283900978975, + "tokens / sec": 6868.662347123506, + "mem allocated avg": 7070424858.624, + "mem reserved avg": 14616318967.808, + "elapsed time": 646.2546505310456 + }, + { + "step": 3750, + "valid accuracy": 0.56, + "train loss": 0.5907982959747314, + "train samples": 15000, + "train time": 31.559637603582814, + "eval time": 8.497839941002894, + "tokens / sec": 6866.460341591462, + "mem allocated avg": 7081439485.952, + "mem reserved avg": 14958674837.504, + "elapsed time": 689.9719419340254 + }, + { + "step": 4000, + "valid accuracy": 0.58, + "train loss": 0.6027647771835327, + "train samples": 16000, + "train time": 29.910713088989723, + "eval time": 7.624095275008585, + "tokens / sec": 6832.769228602266, + "mem allocated avg": 7062505238.528, + "mem reserved avg": 14642030051.328, + "elapsed time": 731.2170849570539 + }, + { + "step": 4250, + "valid accuracy": 0.52, + "train loss": 0.5883516261577606, + "train samples": 17000, + "train time": 30.172428335470613, + "eval time": 11.343407000007574, + "tokens / sec": 7006.0320518349445, + "mem allocated avg": 7074408183.808, + "mem reserved avg": 14628214013.952, + "elapsed time": 776.2375028960523 + }, + { + "step": 4500, + "valid accuracy": 0.54, + "train loss": 0.5942763085365296, + "train samples": 18000, + "train time": 30.16442324745003, + "eval time": 7.2430568499839865, + "tokens / sec": 6889.506830453588, + "mem allocated avg": 7068303734.784, + "mem reserved avg": 14573755170.816, + "elapsed time": 817.3560434450046 + }, + { + "step": 4750, + "valid accuracy": 0.54, + "train loss": 0.5860209344625473, + "train samples": 19000, + "train time": 30.54188258619979, + "eval time": 7.178718408977147, + "tokens / sec": 6873.806793261001, + "mem allocated avg": 7071201742.848, + "mem reserved avg": 14665811755.008, + "elapsed time": 858.6104542890098 + }, + { + "step": 5000, + "valid accuracy": 0.54, + "train loss": 0.5927872058153153, + "train samples": 20000, + "train time": 30.322970695851836, + "eval time": 7.213035533030052, + "tokens / sec": 6868.720155723152, + "mem allocated avg": 7067111507.968, + "mem reserved avg": 14342934233.088, + "elapsed time": 899.7537731120246 + }, + { + "step": 5000, + "test accuracy": 0.48142532221379836, + "train loss": 0.5927872058153153, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.5590972900390625 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-bat.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-bat.json new file mode 100644 index 0000000000000000000000000000000000000000..5a415051ac36e53257dc36a7cc4036b7b3161ae1 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-bat.json @@ -0,0 +1,354 @@ +{ + "run_info": { + "created_at": "2026-01-10T04:48:24+00:00", + "total_time": 1721.4078567399993, + "experiment_name": "miss/llama-3.2-3B-bat", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "MISS", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 64, + "miss_dropout": 0.0, + "mini_r": 1, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "init_weights": "bat", + "layers_to_transform": null, + "layers_pattern": null, + "bias": "none", + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 17293963899, + "accelerator_memory_max": 25209864192, + "accelerator_memory_reserved_99th": 23326621696, + "train_time": 1423.5636942129931, + "file_size": 29367552, + "num_trainable_params": 7340032, + "num_total_params": 3220089856, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.36, + "train loss": 0.8741254634857177, + "train samples": 1000, + "train time": 46.8061858395813, + "eval time": 14.096318043011706, + "tokens / sec": 4523.312382803929, + "mem allocated avg": 6899013533.696, + "mem reserved avg": 17451592974.336, + "elapsed time": 86.06038647796959 + }, + { + "step": 500, + "valid accuracy": 0.38, + "train loss": 0.6947710816860199, + "train samples": 2000, + "train time": 46.26122461789055, + "eval time": 9.15796463796869, + "tokens / sec": 4496.098011196235, + "mem allocated avg": 6892333068.288, + "mem reserved avg": 17059224223.744, + "elapsed time": 146.15365184500115 + }, + { + "step": 750, + "valid accuracy": 0.42, + "train loss": 0.6673551234006881, + "train samples": 3000, + "train time": 47.344122322043404, + "eval time": 9.78604631399503, + "tokens / sec": 4528.5663665196935, + "mem allocated avg": 6902329288.704, + "mem reserved avg": 17203441172.48, + "elapsed time": 207.85480376699707 + }, + { + "step": 1000, + "valid accuracy": 0.38, + "train loss": 0.6479887133836746, + "train samples": 4000, + "train time": 45.87445053498959, + "eval time": 15.653570670983754, + "tokens / sec": 4541.438590988614, + "mem allocated avg": 6893856186.368, + "mem reserved avg": 17297435525.12, + "elapsed time": 274.1509896569769 + }, + { + "step": 1250, + "valid accuracy": 0.38, + "train loss": 0.643939706325531, + "train samples": 5000, + "train time": 46.59595572971739, + "eval time": 9.941779709013645, + "tokens / sec": 4475.4527884273275, + "mem allocated avg": 6894185762.816, + "mem reserved avg": 17293979418.624, + "elapsed time": 335.32179716200335 + }, + { + "step": 1500, + "valid accuracy": 0.42, + "train loss": 0.636546324968338, + "train samples": 6000, + "train time": 46.49660485459026, + "eval time": 10.256375792028848, + "tokens / sec": 4502.070649129005, + "mem allocated avg": 6895291287.552, + "mem reserved avg": 17267370754.048, + "elapsed time": 396.81466775399167 + }, + { + "step": 1750, + "valid accuracy": 0.46, + "train loss": 0.6276157149076462, + "train samples": 7000, + "train time": 45.90664244216168, + "eval time": 17.122960125969257, + "tokens / sec": 4560.451143073005, + "mem allocated avg": 6897185751.04, + "mem reserved avg": 17666676883.456, + "elapsed time": 464.545704477001 + }, + { + "step": 2000, + "valid accuracy": 0.4, + "train loss": 0.6279411467313767, + "train samples": 8000, + "train time": 46.310828003275674, + "eval time": 17.158595203014556, + "tokens / sec": 4484.825881007983, + "mem allocated avg": 6892809709.568, + "mem reserved avg": 17283250388.992, + "elapsed time": 532.7772233400028 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6160788837671279, + "train samples": 9000, + "train time": 46.55647217790829, + "eval time": 17.279317434004042, + "tokens / sec": 4616.930577957234, + "mem allocated avg": 6904810153.984, + "mem reserved avg": 17565350887.424, + "elapsed time": 601.2993231709697 + }, + { + "step": 2500, + "valid accuracy": 0.46, + "train loss": 0.6119984414577484, + "train samples": 10000, + "train time": 45.34805366815999, + "eval time": 17.203243199037388, + "tokens / sec": 4541.914885855721, + "mem allocated avg": 6890310887.424, + "mem reserved avg": 17000260698.112, + "elapsed time": 668.4959828169667 + }, + { + "step": 2750, + "valid accuracy": 0.46, + "train loss": 0.6004733507633209, + "train samples": 11000, + "train time": 46.389391683624126, + "eval time": 9.513812761986628, + "tokens / sec": 4567.44510566186, + "mem allocated avg": 6899632867.328, + "mem reserved avg": 17449630040.064, + "elapsed time": 729.0607163279783 + }, + { + "step": 3000, + "valid accuracy": 0.54, + "train loss": 0.5900258921384811, + "train samples": 12000, + "train time": 45.66193583566928, + "eval time": 17.152980474988, + "tokens / sec": 4571.22538017645, + "mem allocated avg": 6895528245.248, + "mem reserved avg": 17372186411.008, + "elapsed time": 796.6476987909991 + }, + { + "step": 3250, + "valid accuracy": 0.5, + "train loss": 0.5992479181289673, + "train samples": 13000, + "train time": 46.438706652319524, + "eval time": 17.12707888399018, + "tokens / sec": 4541.491682337064, + "mem allocated avg": 6898141349.888, + "mem reserved avg": 17236685225.984, + "elapsed time": 864.8241676180041 + }, + { + "step": 3500, + "valid accuracy": 0.5, + "train loss": 0.580125424861908, + "train samples": 14000, + "train time": 45.41073746327311, + "eval time": 10.362589209980797, + "tokens / sec": 4618.951633842981, + "mem allocated avg": 6895632789.504, + "mem reserved avg": 17228648939.52, + "elapsed time": 925.2799343459774 + }, + { + "step": 3750, + "valid accuracy": 0.46, + "train loss": 0.5769485214948654, + "train samples": 15000, + "train time": 47.041211065487005, + "eval time": 17.174327873974107, + "tokens / sec": 4606.662862023757, + "mem allocated avg": 6907387170.816, + "mem reserved avg": 17589401026.56, + "elapsed time": 994.1755958849681 + }, + { + "step": 4000, + "valid accuracy": 0.48, + "train loss": 0.5861251219511032, + "train samples": 16000, + "train time": 44.97431876306655, + "eval time": 17.113029053027276, + "tokens / sec": 4544.2155794883, + "mem allocated avg": 6887367462.912, + "mem reserved avg": 17309741613.056, + "elapsed time": 1061.0027105140034 + }, + { + "step": 4250, + "valid accuracy": 0.52, + "train loss": 0.5727652524709701, + "train samples": 17000, + "train time": 45.65709007618716, + "eval time": 17.11248146300204, + "tokens / sec": 4629.927129548971, + "mem allocated avg": 6898684106.752, + "mem reserved avg": 17259015700.48, + "elapsed time": 1128.2974988719798 + }, + { + "step": 4500, + "valid accuracy": 0.48, + "train loss": 0.5792552961111068, + "train samples": 18000, + "train time": 46.35413060814608, + "eval time": 17.145976198022254, + "tokens / sec": 4483.268206598161, + "mem allocated avg": 6893984632.832, + "mem reserved avg": 17174450143.232, + "elapsed time": 1196.5402560840012 + }, + { + "step": 4750, + "valid accuracy": 0.44, + "train loss": 0.5682005435228348, + "train samples": 19000, + "train time": 45.35197045758832, + "eval time": 17.11697928601643, + "tokens / sec": 4629.1042678361255, + "mem allocated avg": 6896390144.0, + "mem reserved avg": 17273217613.824, + "elapsed time": 1263.6123683289625 + }, + { + "step": 5000, + "valid accuracy": 0.44, + "train loss": 0.5761626448631286, + "train samples": 20000, + "train time": 45.72992003214313, + "eval time": 17.19783457898302, + "tokens / sec": 4554.567334769052, + "mem allocated avg": 6893206769.664, + "mem reserved avg": 16897718353.92, + "elapsed time": 1331.1372104339534 + }, + { + "step": 5000, + "test accuracy": 0.5163002274450341, + "train loss": 0.5761626448631286, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.2831449508666992 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..97d85d587381d2a508029bc1b275ddcf81c4e7f4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-default.json @@ -0,0 +1,354 @@ +{ + "run_info": { + "created_at": "2026-01-10T05:17:10+00:00", + "total_time": 1145.4119831069838, + "experiment_name": "miss/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "MISS", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 64, + "miss_dropout": 0.0, + "mini_r": 1, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "bias": "none", + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 13443749694, + "accelerator_memory_max": 20275265536, + "accelerator_memory_reserved_99th": 18498977792, + "train_time": 930.4467204429675, + "file_size": 29367496, + "num_trainable_params": 7340032, + "num_total_params": 3220089856, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.4, + "train loss": 0.8770495002269745, + "train samples": 1000, + "train time": 29.581142008537427, + "eval time": 11.88444348500343, + "tokens / sec": 7157.228748602595, + "mem allocated avg": 6897714161.664, + "mem reserved avg": 13519852404.736, + "elapsed time": 63.32356589497067 + }, + { + "step": 500, + "valid accuracy": 0.42, + "train loss": 0.6948347247838974, + "train samples": 2000, + "train time": 28.6214671752532, + "eval time": 11.315816484973766, + "tokens / sec": 7267.097760097966, + "mem allocated avg": 6890609534.976, + "mem reserved avg": 13203794821.12, + "elapsed time": 105.93744991498534 + }, + { + "step": 750, + "valid accuracy": 0.4, + "train loss": 0.6675079126358032, + "train samples": 3000, + "train time": 28.836697526625358, + "eval time": 8.011410179024097, + "tokens / sec": 7435.005336586838, + "mem allocated avg": 6900360769.536, + "mem reserved avg": 13417939206.144, + "elapsed time": 145.43328489601845 + }, + { + "step": 1000, + "valid accuracy": 0.36, + "train loss": 0.6478000595569611, + "train samples": 4000, + "train time": 28.465044133423362, + "eval time": 7.135868438985199, + "tokens / sec": 7319.0120142963, + "mem allocated avg": 6891700822.016, + "mem reserved avg": 13453288800.256, + "elapsed time": 183.82717936398694 + }, + { + "step": 1250, + "valid accuracy": 0.34, + "train loss": 0.644065090060234, + "train samples": 5000, + "train time": 28.294503198412713, + "eval time": 6.2051020989893, + "tokens / sec": 7370.265473037135, + "mem allocated avg": 6892015517.696, + "mem reserved avg": 13493218574.336, + "elapsed time": 220.99409208400175 + }, + { + "step": 1500, + "valid accuracy": 0.5, + "train loss": 0.6371824450492859, + "train samples": 6000, + "train time": 28.5445017926977, + "eval time": 7.893026220030151, + "tokens / sec": 7333.496360183501, + "mem allocated avg": 6894076573.696, + "mem reserved avg": 13404207054.848, + "elapsed time": 260.1458303320105 + }, + { + "step": 1750, + "valid accuracy": 0.46, + "train loss": 0.6281298241615295, + "train samples": 7000, + "train time": 28.726283402822446, + "eval time": 11.832006459997501, + "tokens / sec": 7287.925035907368, + "mem allocated avg": 6895286140.928, + "mem reserved avg": 13746437095.424, + "elapsed time": 303.4682386519853 + }, + { + "step": 2000, + "valid accuracy": 0.4, + "train loss": 0.6284154652357101, + "train samples": 8000, + "train time": 28.592419658671133, + "eval time": 11.856868351984303, + "tokens / sec": 7264.023208928129, + "mem allocated avg": 6891065575.424, + "mem reserved avg": 13428383023.104, + "elapsed time": 346.6774228439899 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6165187916755677, + "train samples": 9000, + "train time": 29.799386566970497, + "eval time": 11.83944596600486, + "tokens / sec": 7213.168617311317, + "mem allocated avg": 6901582643.2, + "mem reserved avg": 13693672751.104, + "elapsed time": 391.026491408993 + }, + { + "step": 2500, + "valid accuracy": 0.5, + "train loss": 0.6125160049200058, + "train samples": 10000, + "train time": 28.65632294554962, + "eval time": 8.679996104969177, + "tokens / sec": 7187.488792311613, + "mem allocated avg": 6888456951.808, + "mem reserved avg": 13231275900.928, + "elapsed time": 431.072143708996 + }, + { + "step": 2750, + "valid accuracy": 0.46, + "train loss": 0.6009856187105179, + "train samples": 11000, + "train time": 28.90840060118353, + "eval time": 11.810368279984687, + "tokens / sec": 7329.391996571593, + "mem allocated avg": 6897535533.056, + "mem reserved avg": 13570335047.68, + "elapsed time": 474.47477067 + }, + { + "step": 3000, + "valid accuracy": 0.44, + "train loss": 0.5904879401922226, + "train samples": 12000, + "train time": 28.64282536803512, + "eval time": 11.851109263021499, + "tokens / sec": 7287.374667756766, + "mem allocated avg": 6893574338.56, + "mem reserved avg": 13508544561.152, + "elapsed time": 517.7344847109634 + }, + { + "step": 3250, + "valid accuracy": 0.52, + "train loss": 0.5999962613582611, + "train samples": 13000, + "train time": 28.622812291316222, + "eval time": 11.942176382988691, + "tokens / sec": 7368.283656179534, + "mem allocated avg": 6896400535.552, + "mem reserved avg": 13368513527.808, + "elapsed time": 560.9433922549943 + }, + { + "step": 3500, + "valid accuracy": 0.54, + "train loss": 0.581193753361702, + "train samples": 14000, + "train time": 28.940197857038584, + "eval time": 8.767924475017935, + "tokens / sec": 7247.704422621507, + "mem allocated avg": 6893331273.728, + "mem reserved avg": 13393645797.376, + "elapsed time": 601.3920295889839 + }, + { + "step": 3750, + "valid accuracy": 0.52, + "train loss": 0.5779475719928742, + "train samples": 15000, + "train time": 30.048772321257275, + "eval time": 11.848424528026953, + "tokens / sec": 7211.708940491347, + "mem allocated avg": 6904537260.032, + "mem reserved avg": 13701608374.272, + "elapsed time": 646.0380702709663 + }, + { + "step": 4000, + "valid accuracy": 0.5, + "train loss": 0.5872079440355301, + "train samples": 16000, + "train time": 28.764328929479234, + "eval time": 11.874075043015182, + "tokens / sec": 7105.084930055418, + "mem allocated avg": 6885427052.544, + "mem reserved avg": 13412377559.04, + "elapsed time": 689.4377979059936 + }, + { + "step": 4250, + "valid accuracy": 0.5, + "train loss": 0.5736851218938828, + "train samples": 17000, + "train time": 29.44270641100593, + "eval time": 11.804472424963024, + "tokens / sec": 7179.672855107539, + "mem allocated avg": 6897404037.12, + "mem reserved avg": 13391523479.552, + "elapsed time": 733.3348887860193 + }, + { + "step": 4500, + "valid accuracy": 0.48, + "train loss": 0.5799340176582336, + "train samples": 18000, + "train time": 28.752423408732284, + "eval time": 11.81368973600911, + "tokens / sec": 7227.842921125195, + "mem allocated avg": 6891705860.096, + "mem reserved avg": 13364461830.144, + "elapsed time": 776.6694126090151 + }, + { + "step": 4750, + "valid accuracy": 0.46, + "train loss": 0.569597121834755, + "train samples": 19000, + "train time": 28.624554165056907, + "eval time": 11.791828219022136, + "tokens / sec": 7334.2277678609435, + "mem allocated avg": 6894110355.456, + "mem reserved avg": 13432342446.08, + "elapsed time": 819.7075462730136 + }, + { + "step": 5000, + "valid accuracy": 0.5, + "train loss": 0.5774972836971283, + "train samples": 20000, + "train time": 28.596162587520666, + "eval time": 11.84556078800233, + "tokens / sec": 7283.49474732995, + "mem allocated avg": 6891173048.32, + "mem reserved avg": 13139571638.272, + "elapsed time": 862.8139132329961 + }, + { + "step": 5000, + "test accuracy": 0.5072024260803639, + "train loss": 0.5774972836971283, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.2503843307495117 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-mini.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-mini.json new file mode 100644 index 0000000000000000000000000000000000000000..a96fd993678c6c9188b815d8abfe723743467232 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/miss--llama-3.2-3B-mini.json @@ -0,0 +1,354 @@ +{ + "run_info": { + "created_at": "2026-01-10T05:36:20+00:00", + "total_time": 1164.9662163450266, + "experiment_name": "miss/llama-3.2-3B-mini", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "MISS", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 64, + "miss_dropout": 0.0, + "mini_r": 64, + "target_modules": [ + "v_proj", + "q_proj" + ], + "exclude_modules": null, + "init_weights": "mini", + "layers_to_transform": null, + "layers_pattern": null, + "bias": "none", + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 13360508698, + "accelerator_memory_max": 20208156672, + "accelerator_memory_reserved_99th": 18419286016, + "train_time": 965.1716879240121, + "file_size": 924568, + "num_trainable_params": 229376, + "num_total_params": 3212979200, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.36, + "train loss": 1.020440380334854, + "train samples": 1000, + "train time": 29.14442138321465, + "eval time": 12.024983258976135, + "tokens / sec": 7264.477726839923, + "mem allocated avg": 6783826952.192, + "mem reserved avg": 13450990321.664, + "elapsed time": 63.706338621035684 + }, + { + "step": 500, + "valid accuracy": 0.36, + "train loss": 0.7482323343753815, + "train samples": 2000, + "train time": 29.259688968246337, + "eval time": 11.94900638400577, + "tokens / sec": 7108.58547490794, + "mem allocated avg": 6776902322.176, + "mem reserved avg": 13124723802.112, + "elapsed time": 107.86160998500418 + }, + { + "step": 750, + "valid accuracy": 0.32, + "train loss": 0.7063661125898362, + "train samples": 3000, + "train time": 29.166292658483144, + "eval time": 7.974753042974044, + "tokens / sec": 7350.985691273331, + "mem allocated avg": 6786654785.536, + "mem reserved avg": 13338851409.92, + "elapsed time": 147.86676333699143 + }, + { + "step": 1000, + "valid accuracy": 0.42, + "train loss": 0.688511967420578, + "train samples": 4000, + "train time": 28.6978243496269, + "eval time": 12.130904801015276, + "tokens / sec": 7259.644405855755, + "mem allocated avg": 6777901023.232, + "mem reserved avg": 13356089999.36, + "elapsed time": 191.68146110099042 + }, + { + "step": 1250, + "valid accuracy": 0.3, + "train loss": 0.6866365925073624, + "train samples": 5000, + "train time": 28.645599797542673, + "eval time": 11.464701619988773, + "tokens / sec": 7279.931349801555, + "mem allocated avg": 6778335270.912, + "mem reserved avg": 13394157502.464, + "elapsed time": 234.6450296450057 + }, + { + "step": 1500, + "valid accuracy": 0.36, + "train loss": 0.6822218251228332, + "train samples": 6000, + "train time": 29.08336391224293, + "eval time": 11.949963599035982, + "tokens / sec": 7197.619939414231, + "mem allocated avg": 6780129107.968, + "mem reserved avg": 13321201778.688, + "elapsed time": 278.6094037120347 + }, + { + "step": 1750, + "valid accuracy": 0.24, + "train loss": 0.6754459946155548, + "train samples": 7000, + "train time": 29.193349240114912, + "eval time": 11.136245816014707, + "tokens / sec": 7171.325163072516, + "mem allocated avg": 6781609465.856, + "mem reserved avg": 13660596469.76, + "elapsed time": 321.90487952699186 + }, + { + "step": 2000, + "valid accuracy": 0.34, + "train loss": 0.67962717461586, + "train samples": 8000, + "train time": 29.31439256318845, + "eval time": 7.02683376398636, + "tokens / sec": 7085.120373969961, + "mem allocated avg": 6777150697.472, + "mem reserved avg": 13345998503.936, + "elapsed time": 361.2144933200325 + }, + { + "step": 2250, + "valid accuracy": 0.4, + "train loss": 0.6712153544425964, + "train samples": 9000, + "train time": 29.861825554224197, + "eval time": 8.035724240005948, + "tokens / sec": 7198.086386570357, + "mem allocated avg": 6787852380.16, + "mem reserved avg": 13611019796.48, + "elapsed time": 401.98816647101194 + }, + { + "step": 2500, + "valid accuracy": 0.32, + "train loss": 0.6712795463800431, + "train samples": 10000, + "train time": 28.831970324506983, + "eval time": 7.130053625965957, + "tokens / sec": 7143.701858798371, + "mem allocated avg": 6774711887.872, + "mem reserved avg": 13150376165.376, + "elapsed time": 440.8588270440232 + }, + { + "step": 2750, + "valid accuracy": 0.4, + "train loss": 0.663529386639595, + "train samples": 11000, + "train time": 29.773301075445488, + "eval time": 11.953038807027042, + "tokens / sec": 7116.476586290984, + "mem allocated avg": 6783670095.872, + "mem reserved avg": 13488831332.352, + "elapsed time": 485.4690147790243 + }, + { + "step": 3000, + "valid accuracy": 0.3, + "train loss": 0.6546721721887588, + "train samples": 12000, + "train time": 29.324858280131593, + "eval time": 6.814812419994269, + "tokens / sec": 7117.886061240441, + "mem allocated avg": 6779918237.696, + "mem reserved avg": 13427518996.48, + "elapsed time": 524.5932486919919 + }, + { + "step": 3250, + "valid accuracy": 0.38, + "train loss": 0.6654119681119919, + "train samples": 13000, + "train time": 29.492643706209492, + "eval time": 12.11322735704016, + "tokens / sec": 7150.969648597359, + "mem allocated avg": 6782518890.496, + "mem reserved avg": 13282119254.016, + "elapsed time": 569.0096655500238 + }, + { + "step": 3500, + "valid accuracy": 0.38, + "train loss": 0.6504700319766998, + "train samples": 14000, + "train time": 29.362759083742276, + "eval time": 10.022665730968583, + "tokens / sec": 7143.402273669011, + "mem allocated avg": 6779553323.008, + "mem reserved avg": 13312653787.136, + "elapsed time": 611.3592632650398 + }, + { + "step": 3750, + "valid accuracy": 0.34, + "train loss": 0.6487009708881378, + "train samples": 15000, + "train time": 29.566806230286602, + "eval time": 11.986386795993894, + "tokens / sec": 7329.2664182992285, + "mem allocated avg": 6790642272.256, + "mem reserved avg": 13618812813.312, + "elapsed time": 655.834033236024 + }, + { + "step": 4000, + "valid accuracy": 0.32, + "train loss": 0.6651566809415818, + "train samples": 16000, + "train time": 28.500502578506712, + "eval time": 6.6941377419861965, + "tokens / sec": 7170.856002873622, + "mem allocated avg": 6771731691.52, + "mem reserved avg": 13326276886.528, + "elapsed time": 693.9715984800132 + }, + { + "step": 4250, + "valid accuracy": 0.32, + "train loss": 0.6470119653940201, + "train samples": 17000, + "train time": 28.92905807477655, + "eval time": 9.46098636800889, + "tokens / sec": 7307.15115070793, + "mem allocated avg": 6783692464.128, + "mem reserved avg": 13309684219.904, + "elapsed time": 735.1370009399834 + }, + { + "step": 4500, + "valid accuracy": 0.36, + "train loss": 0.655580215215683, + "train samples": 18000, + "train time": 29.20642664108891, + "eval time": 8.954324702965096, + "tokens / sec": 7115.48874341349, + "mem allocated avg": 6777984110.592, + "mem reserved avg": 13275827798.016, + "elapsed time": 776.2690268270089 + }, + { + "step": 4750, + "valid accuracy": 0.34, + "train loss": 0.6466742227077484, + "train samples": 19000, + "train time": 29.03275447653141, + "eval time": 9.065798953990452, + "tokens / sec": 7231.108580128142, + "mem allocated avg": 6780332462.08, + "mem reserved avg": 13353162375.168, + "elapsed time": 817.2261539060273 + }, + { + "step": 5000, + "valid accuracy": 0.3, + "train loss": 0.6535704051256179, + "train samples": 20000, + "train time": 28.70540242100833, + "eval time": 8.94265478203306, + "tokens / sec": 7255.777046608071, + "mem allocated avg": 6777309382.656, + "mem reserved avg": 13061280759.808, + "elapsed time": 857.7239665249945 + }, + { + "step": 5000, + "test accuracy": 0.39423805913570886, + "train loss": 0.6535704051256179, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.1832265853881836 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/oft--llama-3.2-3B-rank32.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/oft--llama-3.2-3B-rank32.json new file mode 100644 index 0000000000000000000000000000000000000000..059b29da21ab6cbcf335fb5edff04533fa2fbe0d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/oft--llama-3.2-3B-rank32.json @@ -0,0 +1,360 @@ +{ + "run_info": { + "created_at": "2026-01-10T05:55:49+00:00", + "total_time": 1348.0078762479825, + "experiment_name": "oft/llama-3.2-3B-rank32", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "OFT", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "oft_block_size": 0, + "module_dropout": 0.0, + "target_modules": [ + "v_proj", + "q_proj" + ], + "fan_in_fan_out": false, + "bias": "none", + "exclude_modules": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null, + "modules_to_save": null, + "coft": false, + "eps": 6e-05, + "block_share": false, + "use_cayley_neumann": true, + "num_cayley_neumann_terms": 5 + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14570148069, + "accelerator_memory_max": 22315794432, + "accelerator_memory_reserved_99th": 20145242112, + "train_time": 1118.0740923878038, + "file_size": 32693568, + "num_trainable_params": 8171520, + "num_total_params": 3220921344, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.36, + "train loss": 0.9629777348041535, + "train samples": 1000, + "train time": 34.88295750680845, + "eval time": 14.028832973039243, + "tokens / sec": 6069.410827871367, + "mem allocated avg": 6910183786.496, + "mem reserved avg": 14692730798.08, + "elapsed time": 71.68712687701918 + }, + { + "step": 500, + "valid accuracy": 0.32, + "train loss": 0.71439142203331, + "train samples": 2000, + "train time": 34.68627706926782, + "eval time": 8.79689448804129, + "tokens / sec": 5996.463661540789, + "mem allocated avg": 6902787000.32, + "mem reserved avg": 14280673984.512, + "elapsed time": 118.46906502003549 + }, + { + "step": 750, + "valid accuracy": 0.48, + "train loss": 0.6710897196531296, + "train samples": 3000, + "train time": 35.380497081787325, + "eval time": 12.356959308963269, + "tokens / sec": 6059.863983945164, + "mem allocated avg": 6913287290.88, + "mem reserved avg": 14527609438.208, + "elapsed time": 169.46450086700497 + }, + { + "step": 1000, + "valid accuracy": 0.46, + "train loss": 0.6509144109487534, + "train samples": 4000, + "train time": 35.38656886102399, + "eval time": 14.169413066993002, + "tokens / sec": 5887.431494650181, + "mem allocated avg": 6904497004.544, + "mem reserved avg": 14534924304.384, + "elapsed time": 222.43686137301847 + }, + { + "step": 1250, + "valid accuracy": 0.36, + "train loss": 0.645386314868927, + "train samples": 5000, + "train time": 34.42120103741763, + "eval time": 14.01571749499999, + "tokens / sec": 6058.417304303483, + "mem allocated avg": 6905021065.216, + "mem reserved avg": 14595632660.48, + "elapsed time": 274.1503414300387 + }, + { + "step": 1500, + "valid accuracy": 0.46, + "train loss": 0.6368236445188522, + "train samples": 6000, + "train time": 34.666979860921856, + "eval time": 9.192593308980577, + "tokens / sec": 6038.339677693329, + "mem allocated avg": 6905748031.488, + "mem reserved avg": 14529454931.968, + "elapsed time": 321.3953521400108 + }, + { + "step": 1750, + "valid accuracy": 0.5, + "train loss": 0.6279961000680924, + "train samples": 7000, + "train time": 34.723764617112465, + "eval time": 11.785299010982271, + "tokens / sec": 6029.15617901713, + "mem allocated avg": 6907708614.656, + "mem reserved avg": 14900634058.752, + "elapsed time": 371.2769475780078 + }, + { + "step": 2000, + "valid accuracy": 0.4, + "train loss": 0.6302493048906326, + "train samples": 8000, + "train time": 34.55560137151042, + "eval time": 14.030101582000498, + "tokens / sec": 6010.487207762393, + "mem allocated avg": 6903469649.92, + "mem reserved avg": 14548564180.992, + "elapsed time": 423.27879621402826 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6211440742015839, + "train samples": 9000, + "train time": 35.52928709477419, + "eval time": 14.005440895038191, + "tokens / sec": 6049.882155716418, + "mem allocated avg": 6915304634.368, + "mem reserved avg": 14843717353.472, + "elapsed time": 476.20078854600433 + }, + { + "step": 2500, + "valid accuracy": 0.42, + "train loss": 0.6180904031991958, + "train samples": 10000, + "train time": 35.02202940842835, + "eval time": 14.004316847014707, + "tokens / sec": 5881.069814601671, + "mem allocated avg": 6900778860.544, + "mem reserved avg": 14355215155.2, + "elapsed time": 528.5787644560332 + }, + { + "step": 2750, + "valid accuracy": 0.46, + "train loss": 0.6097299265861511, + "train samples": 11000, + "train time": 35.6146717875381, + "eval time": 9.144496340013575, + "tokens / sec": 5949.261620716075, + "mem allocated avg": 6911029626.88, + "mem reserved avg": 14734220853.248, + "elapsed time": 576.7091627839836 + }, + { + "step": 3000, + "valid accuracy": 0.42, + "train loss": 0.600579794883728, + "train samples": 12000, + "train time": 35.16766768670641, + "eval time": 14.045691164967138, + "tokens / sec": 5935.309724247127, + "mem allocated avg": 6906340362.24, + "mem reserved avg": 14634706796.544, + "elapsed time": 629.347200824006 + }, + { + "step": 3250, + "valid accuracy": 0.56, + "train loss": 0.6099310213327408, + "train samples": 13000, + "train time": 35.43659597542137, + "eval time": 11.369511878991034, + "tokens / sec": 5951.502795197366, + "mem allocated avg": 6908234280.96, + "mem reserved avg": 14499599876.096, + "elapsed time": 679.4317268640152 + }, + { + "step": 3500, + "valid accuracy": 0.5, + "train loss": 0.5943480662107468, + "train samples": 14000, + "train time": 34.85756022395799, + "eval time": 8.693275505036581, + "tokens / sec": 6017.345983263524, + "mem allocated avg": 6906331211.776, + "mem reserved avg": 14555694497.792, + "elapsed time": 726.3931989329867 + }, + { + "step": 3750, + "valid accuracy": 0.52, + "train loss": 0.5926959769725799, + "train samples": 15000, + "train time": 35.249166297202464, + "eval time": 11.4140949450084, + "tokens / sec": 6147.748238153325, + "mem allocated avg": 6917726124.032, + "mem reserved avg": 14819759489.024, + "elapsed time": 776.4263785420335 + }, + { + "step": 4000, + "valid accuracy": 0.52, + "train loss": 0.603757186293602, + "train samples": 16000, + "train time": 34.53601357748266, + "eval time": 8.989645537047181, + "tokens / sec": 5917.677775446856, + "mem allocated avg": 6898480144.384, + "mem reserved avg": 14544931913.728, + "elapsed time": 823.3236909009865 + }, + { + "step": 4250, + "valid accuracy": 0.52, + "train loss": 0.5904598969221115, + "train samples": 17000, + "train time": 34.97911310993368, + "eval time": 9.157656271010637, + "tokens / sec": 6043.292159399201, + "mem allocated avg": 6909286631.424, + "mem reserved avg": 14509322272.768, + "elapsed time": 870.700260128011 + }, + { + "step": 4500, + "valid accuracy": 0.54, + "train loss": 0.5976542398929596, + "train samples": 18000, + "train time": 35.34081694687484, + "eval time": 9.293714377039578, + "tokens / sec": 5880.396039299176, + "mem allocated avg": 6904009969.664, + "mem reserved avg": 14498240921.6, + "elapsed time": 918.7880094650318 + }, + { + "step": 4750, + "valid accuracy": 0.52, + "train loss": 0.5886972019672394, + "train samples": 19000, + "train time": 35.23478025314398, + "eval time": 9.220501197036356, + "tokens / sec": 5958.288897836031, + "mem allocated avg": 6907173064.704, + "mem reserved avg": 14554260045.824, + "elapsed time": 966.5027436820092 + }, + { + "step": 5000, + "valid accuracy": 0.54, + "train loss": 0.5947221873998642, + "train samples": 20000, + "train time": 35.268570395885035, + "eval time": 9.204281533020549, + "tokens / sec": 5905.541326514927, + "mem allocated avg": 6903379494.912, + "mem reserved avg": 14243067854.848, + "elapsed time": 1014.2827233370044 + }, + { + "step": 5000, + "test accuracy": 0.5034116755117514, + "train loss": 0.5947221873998642, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.5187549591064453 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/osf--llama-3.2-3B-rank128.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/osf--llama-3.2-3B-rank128.json new file mode 100644 index 0000000000000000000000000000000000000000..0f28e1354ff419a5aae7e9a760f7486b5c80ae6d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/osf--llama-3.2-3B-rank128.json @@ -0,0 +1,362 @@ +{ + "run_info": { + "created_at": "2026-01-10T13:52:04+00:00", + "total_time": 3564.558626318001, + "experiment_name": "osf/llama-3.2-3B-rank128", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 5e-05 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": false, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "OSF", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "effective_rank": null, + "target_modules": [ + "q_proj", + "k_proj", + "v_proj", + "o_proj", + "gate_proj", + "down_proj", + "up_proj" + ], + "rank_pattern": { + "q_proj": 2944, + "o_proj": 2944, + "k_proj": 896, + "v_proj": 896, + "gate_proj": 2944, + "down_proj": 2944, + "up_proj": 2944 + }, + "init_weights": null, + "modules_to_save": null, + "target_svd_config": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 30265093547, + "accelerator_memory_max": 38600179712, + "accelerator_memory_reserved_99th": 36574330880, + "train_time": 2726.1649636220536, + "file_size": 389155304, + "num_trainable_params": 194535936, + "num_total_params": 3407285760, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.36, + "train loss": 1.1346645681858063, + "train samples": 1000, + "train time": 76.96098467695992, + "eval time": 44.08565193996765, + "tokens / sec": 2750.9913092806755, + "mem allocated avg": 16402297032.704, + "mem reserved avg": 30341083430.912, + "elapsed time": 154.4344606329687 + }, + { + "step": 500, + "valid accuracy": 0.4, + "train loss": 0.7762473058700562, + "train samples": 2000, + "train time": 75.26524780492764, + "eval time": 43.51324718899559, + "tokens / sec": 2763.4931932873073, + "mem allocated avg": 16396203208.704, + "mem reserved avg": 29951977848.832, + "elapsed time": 278.9545994399814 + }, + { + "step": 750, + "valid accuracy": 0.32, + "train loss": 0.6953379583358764, + "train samples": 3000, + "train time": 76.63530880311737, + "eval time": 42.7298935810104, + "tokens / sec": 2797.679077027202, + "mem allocated avg": 16407247548.416, + "mem reserved avg": 30196337999.872, + "elapsed time": 403.9367217730032 + }, + { + "step": 1000, + "valid accuracy": 0.36, + "train loss": 0.6674225121736527, + "train samples": 4000, + "train time": 74.17853219044628, + "eval time": 43.0046770980116, + "tokens / sec": 2808.575390318014, + "mem allocated avg": 16398045169.664, + "mem reserved avg": 30316370591.744, + "elapsed time": 527.0352661089855 + }, + { + "step": 1250, + "valid accuracy": 0.36, + "train loss": 0.6617556363344193, + "train samples": 5000, + "train time": 75.8016281768214, + "eval time": 43.36838999501197, + "tokens / sec": 2751.101856460739, + "mem allocated avg": 16396343963.648, + "mem reserved avg": 30267557281.792, + "elapsed time": 651.8875343019608 + }, + { + "step": 1500, + "valid accuracy": 0.4, + "train loss": 0.6529131004810333, + "train samples": 6000, + "train time": 75.09193942596903, + "eval time": 30.097449911991134, + "tokens / sec": 2787.662718531506, + "mem allocated avg": 16399491280.896, + "mem reserved avg": 30184493285.376, + "elapsed time": 762.9776720659574 + }, + { + "step": 1750, + "valid accuracy": 0.42, + "train loss": 0.6453723709583282, + "train samples": 7000, + "train time": 75.4158672678168, + "eval time": 29.512030549987685, + "tokens / sec": 2776.00732557432, + "mem allocated avg": 16399573282.816, + "mem reserved avg": 30614921150.464, + "elapsed time": 873.7585097869742 + }, + { + "step": 2000, + "valid accuracy": 0.5, + "train loss": 0.6473421185016632, + "train samples": 8000, + "train time": 74.86789236118784, + "eval time": 32.70745619904483, + "tokens / sec": 2774.166514505374, + "mem allocated avg": 16395882827.776, + "mem reserved avg": 30363908833.28, + "elapsed time": 987.328368842951 + }, + { + "step": 2250, + "valid accuracy": 0.46, + "train loss": 0.6403058428764343, + "train samples": 9000, + "train time": 76.38718391134171, + "eval time": 43.59695099998498, + "tokens / sec": 2813.927533308179, + "mem allocated avg": 16407910541.312, + "mem reserved avg": 30658625798.144, + "elapsed time": 1113.1452908439678 + }, + { + "step": 2500, + "valid accuracy": 0.48, + "train loss": 0.6393621402978897, + "train samples": 10000, + "train time": 75.52950381772825, + "eval time": 34.47939619596582, + "tokens / sec": 2726.974090774518, + "mem allocated avg": 16392402880.512, + "mem reserved avg": 29978301300.736, + "elapsed time": 1228.9517676229589 + }, + { + "step": 2750, + "valid accuracy": 0.46, + "train loss": 0.6332201733589172, + "train samples": 11000, + "train time": 76.26470051467186, + "eval time": 27.436079355014954, + "tokens / sec": 2778.2315877479673, + "mem allocated avg": 16403186505.728, + "mem reserved avg": 30425330221.056, + "elapsed time": 1338.4403797709965 + }, + { + "step": 3000, + "valid accuracy": 0.48, + "train loss": 0.6263919055461884, + "train samples": 12000, + "train time": 74.40951175126247, + "eval time": 29.06353580096038, + "tokens / sec": 2805.1655640175404, + "mem allocated avg": 16398444703.744, + "mem reserved avg": 30332476719.104, + "elapsed time": 1447.7839398179785 + }, + { + "step": 3250, + "valid accuracy": 0.48, + "train loss": 0.6381742950677872, + "train samples": 13000, + "train time": 74.72798433422577, + "eval time": 43.305307837959845, + "tokens / sec": 2822.2492802258867, + "mem allocated avg": 16399888216.064, + "mem reserved avg": 30181515329.536, + "elapsed time": 1571.4769958669785 + }, + { + "step": 3500, + "valid accuracy": 0.48, + "train loss": 0.6243305860757827, + "train samples": 14000, + "train time": 76.08441733068321, + "eval time": 42.96766831201967, + "tokens / sec": 2756.806286474804, + "mem allocated avg": 16400161828.864, + "mem reserved avg": 30211395551.232, + "elapsed time": 1696.4063137219637 + }, + { + "step": 3750, + "valid accuracy": 0.48, + "train loss": 0.6249194881916046, + "train samples": 15000, + "train time": 76.11614000686677, + "eval time": 29.9355729019735, + "tokens / sec": 2847.0045903595515, + "mem allocated avg": 16410507460.608, + "mem reserved avg": 30531127345.152, + "elapsed time": 1808.269276439969 + }, + { + "step": 4000, + "valid accuracy": 0.5, + "train loss": 0.6388201580047608, + "train samples": 16000, + "train time": 76.0119633852737, + "eval time": 30.01086129399482, + "tokens / sec": 2688.695185573835, + "mem allocated avg": 16392468033.536, + "mem reserved avg": 30200129650.688, + "elapsed time": 1920.24236187496 + }, + { + "step": 4250, + "valid accuracy": 0.48, + "train loss": 0.6239535554647445, + "train samples": 17000, + "train time": 75.46739184868056, + "eval time": 29.885257655987516, + "tokens / sec": 2801.064073127841, + "mem allocated avg": 16401088077.824, + "mem reserved avg": 30233021382.656, + "elapsed time": 2031.23209467798 + }, + { + "step": 4500, + "valid accuracy": 0.48, + "train loss": 0.6330795180797577, + "train samples": 18000, + "train time": 75.55658065743046, + "eval time": 43.05317433399614, + "tokens / sec": 2750.4950355315286, + "mem allocated avg": 16396156147.712, + "mem reserved avg": 30183100776.448, + "elapsed time": 2155.806646246987 + }, + { + "step": 4750, + "valid accuracy": 0.5, + "train loss": 0.6253060162067413, + "train samples": 19000, + "train time": 75.05370855727233, + "eval time": 30.0452861750382, + "tokens / sec": 2797.1835640846284, + "mem allocated avg": 16399268433.92, + "mem reserved avg": 30276214325.248, + "elapsed time": 2266.6352769299992 + }, + { + "step": 5000, + "valid accuracy": 0.46, + "train loss": 0.6309190951585769, + "train samples": 20000, + "train time": 75.36505703715375, + "eval time": 29.40401862899307, + "tokens / sec": 2763.6149720860867, + "mem allocated avg": 16396532787.2, + "mem reserved avg": 29853982130.176, + "elapsed time": 2377.1134240519605 + }, + { + "step": 5000, + "test accuracy": 0.44579226686884005, + "train loss": 0.6309190951585769, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.3507108688354492 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "261366de2e40cde64b702d6b9c527081ad850549", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prefixtuning--llama-3.2-3B-lr_0.001.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prefixtuning--llama-3.2-3B-lr_0.001.json new file mode 100644 index 0000000000000000000000000000000000000000..6797029b3a377bcdb5bb568a2e09e87b3aeec690 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prefixtuning--llama-3.2-3B-lr_0.001.json @@ -0,0 +1,348 @@ +{ + "run_info": { + "created_at": "2026-01-10T06:21:07+00:00", + "total_time": 1331.180568004027, + "experiment_name": "prefixtuning/llama-3.2-3B-lr_0.001", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.001 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "PREFIX_TUNING", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "num_virtual_tokens": 200, + "token_dim": 1024, + "num_transformer_submodules": 1, + "num_attention_heads": 8, + "num_layers": 28, + "modules_to_save": null, + "encoder_hidden_size": 3072, + "prefix_projection": false + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 13976940104, + "accelerator_memory_max": 21969764352, + "accelerator_memory_reserved_99th": 19153289216, + "train_time": 1064.3996377468575, + "file_size": 45875328, + "num_trainable_params": 11468800, + "num_total_params": 3224218624, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 7.371234140396118, + "train samples": 1000, + "train time": 28.751766396977473, + "eval time": 16.065947165014222, + "tokens / sec": 7363.686706297703, + "mem allocated avg": 7055800627.2, + "mem reserved avg": 14144568819.712, + "elapsed time": 65.96332754800096 + }, + { + "step": 500, + "valid accuracy": 0.02, + "train loss": 3.85315430355072, + "train samples": 2000, + "train time": 28.732399038621224, + "eval time": 15.995644349022768, + "tokens / sec": 7239.0404894634585, + "mem allocated avg": 7047734953.984, + "mem reserved avg": 13747594723.328, + "elapsed time": 113.22562833898701 + }, + { + "step": 750, + "valid accuracy": 0.0, + "train loss": 1.7292076191902161, + "train samples": 3000, + "train time": 28.82316682342207, + "eval time": 15.999323514988646, + "tokens / sec": 7438.495614082733, + "mem allocated avg": 7058484809.728, + "mem reserved avg": 13879262314.496, + "elapsed time": 160.49658835295122 + }, + { + "step": 1000, + "valid accuracy": 0.06, + "train loss": 1.1542455520629882, + "train samples": 4000, + "train time": 28.307557759340852, + "eval time": 15.991954815981444, + "tokens / sec": 7359.730633464974, + "mem allocated avg": 7050851307.52, + "mem reserved avg": 13934467743.744, + "elapsed time": 207.3751138979569 + }, + { + "step": 1250, + "valid accuracy": 0.12, + "train loss": 1.011209780216217, + "train samples": 5000, + "train time": 28.492442497052252, + "eval time": 16.001330196973868, + "tokens / sec": 7319.063643686383, + "mem allocated avg": 7049989021.696, + "mem reserved avg": 13963450384.384, + "elapsed time": 254.30183131998638 + }, + { + "step": 1500, + "valid accuracy": 0.1, + "train loss": 0.9543534135818481, + "train samples": 6000, + "train time": 29.00675484893145, + "eval time": 9.917582978028804, + "tokens / sec": 7216.629405467993, + "mem allocated avg": 7052174501.888, + "mem reserved avg": 13851756068.864, + "elapsed time": 295.813073428988 + }, + { + "step": 1750, + "valid accuracy": 0.18, + "train loss": 0.9020170977115631, + "train samples": 7000, + "train time": 28.937920498428866, + "eval time": 15.994958859984763, + "tokens / sec": 7234.624893359789, + "mem allocated avg": 7052584257.536, + "mem reserved avg": 14313834151.936, + "elapsed time": 343.2948918819893 + }, + { + "step": 2000, + "valid accuracy": 0.12, + "train loss": 0.8851030931472779, + "train samples": 8000, + "train time": 28.514948888856452, + "eval time": 16.008299834036734, + "tokens / sec": 7283.7584527870895, + "mem allocated avg": 7048941596.672, + "mem reserved avg": 13972795293.696, + "elapsed time": 390.4364310989622 + }, + { + "step": 2250, + "valid accuracy": 0.16, + "train loss": 0.8607603459358215, + "train samples": 9000, + "train time": 29.902237092261203, + "eval time": 10.535748619004153, + "tokens / sec": 7188.358494275642, + "mem allocated avg": 7059749308.416, + "mem reserved avg": 14222314438.656, + "elapsed time": 433.4298671329743 + }, + { + "step": 2500, + "valid accuracy": 0.12, + "train loss": 0.8404140145778656, + "train samples": 10000, + "train time": 28.107242401398253, + "eval time": 16.000201146001928, + "tokens / sec": 7327.8978086357465, + "mem allocated avg": 7045691678.72, + "mem reserved avg": 13735917780.992, + "elapsed time": 480.0712110779714 + }, + { + "step": 2750, + "valid accuracy": 0.16, + "train loss": 0.825820200920105, + "train samples": 11000, + "train time": 28.787353610619903, + "eval time": 16.014024466043338, + "tokens / sec": 7360.211114433085, + "mem allocated avg": 7056392456.192, + "mem reserved avg": 14160037412.864, + "elapsed time": 527.3567257059622 + }, + { + "step": 3000, + "valid accuracy": 0.16, + "train loss": 0.8098397166728973, + "train samples": 12000, + "train time": 28.65236609155545, + "eval time": 9.67730041500181, + "tokens / sec": 7284.948102820664, + "mem allocated avg": 7051615287.296, + "mem reserved avg": 14045272866.816, + "elapsed time": 568.3316111429594 + }, + { + "step": 3250, + "valid accuracy": 0.22, + "train loss": 0.8175026917457581, + "train samples": 13000, + "train time": 29.403707249381114, + "eval time": 16.004016032034997, + "tokens / sec": 7172.59895873977, + "mem allocated avg": 7053057355.776, + "mem reserved avg": 13961034465.28, + "elapsed time": 616.2441388620064 + }, + { + "step": 3500, + "valid accuracy": 0.22, + "train loss": 0.7965447254180908, + "train samples": 14000, + "train time": 29.196881618758198, + "eval time": 10.013400638010353, + "tokens / sec": 7183.986383848656, + "mem allocated avg": 7052398039.04, + "mem reserved avg": 13956026466.304, + "elapsed time": 658.0585781059926 + }, + { + "step": 3750, + "valid accuracy": 0.26, + "train loss": 0.7888746349811554, + "train samples": 15000, + "train time": 30.024835704127327, + "eval time": 16.018790416012052, + "tokens / sec": 7217.458311360924, + "mem allocated avg": 7062534557.696, + "mem reserved avg": 14256909058.048, + "elapsed time": 706.6880692789564 + }, + { + "step": 4000, + "valid accuracy": 0.22, + "train loss": 0.8037197089195252, + "train samples": 16000, + "train time": 28.532692203647457, + "eval time": 11.774339078983758, + "tokens / sec": 7162.766083947526, + "mem allocated avg": 7044319064.064, + "mem reserved avg": 13979053195.264, + "elapsed time": 749.5904883489711 + }, + { + "step": 4250, + "valid accuracy": 0.2, + "train loss": 0.7834680559635162, + "train samples": 17000, + "train time": 29.28171190287685, + "eval time": 8.626789060013834, + "tokens / sec": 7219.147592912134, + "mem allocated avg": 7055146299.392, + "mem reserved avg": 13931238129.664, + "elapsed time": 789.9725718589616 + }, + { + "step": 4500, + "valid accuracy": 0.22, + "train loss": 0.7825182939767837, + "train samples": 18000, + "train time": 28.710874950978905, + "eval time": 9.622777467011474, + "tokens / sec": 7238.302571928913, + "mem allocated avg": 7049707819.008, + "mem reserved avg": 13845691105.28, + "elapsed time": 830.868794028007 + }, + { + "step": 4750, + "valid accuracy": 0.24, + "train loss": 0.780375949382782, + "train samples": 19000, + "train time": 29.437492316938005, + "eval time": 8.954141772992443, + "tokens / sec": 7131.687636286989, + "mem allocated avg": 7052297474.048, + "mem reserved avg": 13998388936.704, + "elapsed time": 871.7168849699665 + }, + { + "step": 5000, + "valid accuracy": 0.22, + "train loss": 0.7886579229831695, + "train samples": 20000, + "train time": 28.385062363231555, + "eval time": 8.572692813992035, + "tokens / sec": 7337.662230039503, + "mem allocated avg": 7048989648.896, + "mem reserved avg": 13639188742.144, + "elapsed time": 911.1826199819916 + }, + { + "step": 5000, + "test accuracy": 0.20090978013646701, + "train loss": 0.7886579229831695, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.5536785125732422 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..bfd3cbb73e5fbd3dea4aaa0ba253bce92d795c2c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-default.json @@ -0,0 +1,351 @@ +{ + "run_info": { + "created_at": "2026-01-10T06:43:22+00:00", + "total_time": 1838.2831721020048, + "experiment_name": "prompt_tuning/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "PROMPT_TUNING", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "num_virtual_tokens": 200, + "token_dim": 3072, + "num_transformer_submodules": 1, + "num_attention_heads": 24, + "num_layers": 28, + "modules_to_save": null, + "prompt_tuning_init": "RANDOM", + "prompt_tuning_init_text": null, + "tokenizer_name_or_path": null, + "tokenizer_kwargs": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 17625765642, + "accelerator_memory_max": 24427626496, + "accelerator_memory_reserved_99th": 22968008704, + "train_time": 1505.838819740049, + "file_size": 2457728, + "num_trainable_params": 614400, + "num_total_params": 3213364224, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 3.462650680541992, + "train samples": 1000, + "train time": 48.139625351293944, + "eval time": 16.530633710033726, + "tokens / sec": 4398.019271130643, + "mem allocated avg": 7084412407.808, + "mem reserved avg": 17769940647.936, + "elapsed time": 87.74912454502191 + }, + { + "step": 500, + "valid accuracy": 0.0, + "train loss": 2.2589459805488588, + "train samples": 2000, + "train time": 48.43768710020231, + "eval time": 16.48010197596159, + "tokens / sec": 4294.073735802535, + "mem allocated avg": 7076015853.568, + "mem reserved avg": 17322089644.032, + "elapsed time": 155.9924284190056 + }, + { + "step": 750, + "valid accuracy": 0.0, + "train loss": 1.7582932782173157, + "train samples": 3000, + "train time": 48.9170593819581, + "eval time": 16.461432596028317, + "tokens / sec": 4382.94948038264, + "mem allocated avg": 7086598868.992, + "mem reserved avg": 17347867836.416, + "elapsed time": 224.63146157900337 + }, + { + "step": 1000, + "valid accuracy": 0.0, + "train loss": 1.6029385833740235, + "train samples": 4000, + "train time": 48.4513027088251, + "eval time": 16.587105787999462, + "tokens / sec": 4299.905025299824, + "mem allocated avg": 7080125773.824, + "mem reserved avg": 17638306611.2, + "elapsed time": 293.0906825060374 + }, + { + "step": 1250, + "valid accuracy": 0.0, + "train loss": 1.5049201951026916, + "train samples": 5000, + "train time": 47.84065633546561, + "eval time": 16.44257097603986, + "tokens / sec": 4359.012103381303, + "mem allocated avg": 7076596897.792, + "mem reserved avg": 17677858897.92, + "elapsed time": 360.6927552940324 + }, + { + "step": 1500, + "valid accuracy": 0.0, + "train loss": 1.4373888688087464, + "train samples": 6000, + "train time": 48.565593625826295, + "eval time": 16.451919412997086, + "tokens / sec": 4310.273680844737, + "mem allocated avg": 7079910084.608, + "mem reserved avg": 17610313826.304, + "elapsed time": 429.08035932003986 + }, + { + "step": 1750, + "valid accuracy": 0.0, + "train loss": 1.3829970264434814, + "train samples": 7000, + "train time": 47.46174641727703, + "eval time": 16.44140770897502, + "tokens / sec": 4411.026053685007, + "mem allocated avg": 7081518635.008, + "mem reserved avg": 17944507580.416, + "elapsed time": 496.28030893800315 + }, + { + "step": 2000, + "valid accuracy": 0.0, + "train loss": 1.333943516254425, + "train samples": 8000, + "train time": 47.37612354574958, + "eval time": 16.461310581013095, + "tokens / sec": 4383.980462213941, + "mem allocated avg": 7076895195.136, + "mem reserved avg": 17455510454.272, + "elapsed time": 563.4433135589934 + }, + { + "step": 2250, + "valid accuracy": 0.0, + "train loss": 1.2829430739879608, + "train samples": 9000, + "train time": 49.185617247305345, + "eval time": 16.46588272700319, + "tokens / sec": 4370.139321811113, + "mem allocated avg": 7088224200.704, + "mem reserved avg": 17821908074.496, + "elapsed time": 632.4641255650204 + }, + { + "step": 2500, + "valid accuracy": 0.0, + "train loss": 1.246446587562561, + "train samples": 10000, + "train time": 48.255648160818964, + "eval time": 16.453739245946053, + "tokens / sec": 4268.246471658303, + "mem allocated avg": 7075521802.24, + "mem reserved avg": 17499282210.816, + "elapsed time": 700.5415165220038 + }, + { + "step": 2750, + "valid accuracy": 0.0, + "train loss": 1.2048211748600006, + "train samples": 11000, + "train time": 48.75862841651542, + "eval time": 16.46915528498357, + "tokens / sec": 4345.507797923046, + "mem allocated avg": 7083802673.152, + "mem reserved avg": 18024199356.416, + "elapsed time": 769.1840648030047 + }, + { + "step": 3000, + "valid accuracy": 0.06, + "train loss": 1.1679602472782136, + "train samples": 12000, + "train time": 48.22104389790911, + "eval time": 16.46740536397556, + "tokens / sec": 4328.6288128045, + "mem allocated avg": 7078835648.512, + "mem reserved avg": 17764907483.136, + "elapsed time": 837.2026147870347 + }, + { + "step": 3250, + "valid accuracy": 0.04, + "train loss": 1.131537829875946, + "train samples": 13000, + "train time": 48.137974261830095, + "eval time": 16.45086403901223, + "tokens / sec": 4381.177297841325, + "mem allocated avg": 7080606814.208, + "mem reserved avg": 17735715127.296, + "elapsed time": 905.0784538229927 + }, + { + "step": 3500, + "valid accuracy": 0.04, + "train loss": 1.1094365301132203, + "train samples": 14000, + "train time": 48.85280603397405, + "eval time": 16.464311491989065, + "tokens / sec": 4293.509770024922, + "mem allocated avg": 7081026895.872, + "mem reserved avg": 17464184274.944, + "elapsed time": 973.75803008402 + }, + { + "step": 3750, + "valid accuracy": 0.02, + "train loss": 1.079718291759491, + "train samples": 15000, + "train time": 49.39224000740796, + "eval time": 16.467753204982728, + "tokens / sec": 4387.389597384091, + "mem allocated avg": 7091974598.656, + "mem reserved avg": 17988463886.336, + "elapsed time": 1042.9676414930145 + }, + { + "step": 4000, + "valid accuracy": 0.02, + "train loss": 1.0901593000888825, + "train samples": 16000, + "train time": 48.37513752095401, + "eval time": 16.4682428810047, + "tokens / sec": 4224.752847709724, + "mem allocated avg": 7072683055.104, + "mem reserved avg": 17487336833.024, + "elapsed time": 1111.1566645530402 + }, + { + "step": 4250, + "valid accuracy": 0.04, + "train loss": 1.0608918931484221, + "train samples": 17000, + "train time": 48.56447010586271, + "eval time": 16.604359342018142, + "tokens / sec": 4352.750056557934, + "mem allocated avg": 7082847784.96, + "mem reserved avg": 17545067233.28, + "elapsed time": 1179.6303421389894 + }, + { + "step": 4500, + "valid accuracy": 0.06, + "train loss": 1.068639324426651, + "train samples": 18000, + "train time": 48.767977151903324, + "eval time": 16.501046893012244, + "tokens / sec": 4261.36190460976, + "mem allocated avg": 7077102155.776, + "mem reserved avg": 17491698909.184, + "elapsed time": 1248.2997376249987 + }, + { + "step": 4750, + "valid accuracy": 0.02, + "train loss": 1.0587589330673217, + "train samples": 19000, + "train time": 48.74695514619816, + "eval time": 16.455141162965447, + "tokens / sec": 4306.710016458811, + "mem allocated avg": 7080302989.312, + "mem reserved avg": 17688931860.48, + "elapsed time": 1316.8433299760218 + }, + { + "step": 5000, + "valid accuracy": 0.04, + "train loss": 1.0654818024635315, + "train samples": 20000, + "train time": 48.002736268914305, + "eval time": 16.48369751899736, + "tokens / sec": 4338.91932395692, + "mem allocated avg": 7078423576.576, + "mem reserved avg": 17237222096.896, + "elapsed time": 1384.6823478980223 + }, + { + "step": 5000, + "test accuracy": 0.053828658074298714, + "train loss": 1.0654818024635315, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 2.5893402099609375 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-lr_0.001.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-lr_0.001.json new file mode 100644 index 0000000000000000000000000000000000000000..62aeb977db3c7a4ba2c39650bc55af9fe8f3ee6a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-lr_0.001.json @@ -0,0 +1,350 @@ +{ + "run_info": { + "created_at": "2026-01-10T07:14:05+00:00", + "total_time": 1832.84551787097, + "experiment_name": "prompt_tuning/llama-3.2-3B-lr_0.001", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.001 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "PROMPT_TUNING", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "num_virtual_tokens": 200, + "token_dim": 3072, + "num_transformer_submodules": 1, + "num_attention_heads": 24, + "num_layers": 28, + "modules_to_save": null, + "prompt_tuning_init": "RANDOM", + "prompt_tuning_init_text": null, + "tokenizer_name_or_path": null, + "tokenizer_kwargs": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 17625765642, + "accelerator_memory_max": 24427626496, + "accelerator_memory_reserved_99th": 22968008704, + "train_time": 1500.144346723042, + "file_size": 2457728, + "num_trainable_params": 614400, + "num_total_params": 3213364224, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 2.454541881084442, + "train samples": 1000, + "train time": 48.05059277405962, + "eval time": 16.54681792098563, + "tokens / sec": 4406.168327527848, + "mem allocated avg": 7084412407.808, + "mem reserved avg": 17769940647.936, + "elapsed time": 87.42315325996606 + }, + { + "step": 500, + "valid accuracy": 0.0, + "train loss": 1.4034946029186248, + "train samples": 2000, + "train time": 47.981591070012655, + "eval time": 16.47515737899812, + "tokens / sec": 4334.891681613949, + "mem allocated avg": 7076015853.568, + "mem reserved avg": 17322089644.032, + "elapsed time": 155.20469547994435 + }, + { + "step": 750, + "valid accuracy": 0.14, + "train loss": 1.0518241834640503, + "train samples": 3000, + "train time": 48.23318296362413, + "eval time": 16.460273437958676, + "tokens / sec": 4445.093332565138, + "mem allocated avg": 7086598868.992, + "mem reserved avg": 17347867836.416, + "elapsed time": 223.13227264099987 + }, + { + "step": 1000, + "valid accuracy": 0.14, + "train loss": 0.9424336891174316, + "train samples": 4000, + "train time": 48.76682744745631, + "eval time": 16.60897780803498, + "tokens / sec": 4272.084343080777, + "mem allocated avg": 7080125773.824, + "mem reserved avg": 17638306611.2, + "elapsed time": 291.9349672459648 + }, + { + "step": 1250, + "valid accuracy": 0.2, + "train loss": 0.9085311102867126, + "train samples": 5000, + "train time": 47.41566651139874, + "eval time": 16.448816249030642, + "tokens / sec": 4398.082223517145, + "mem allocated avg": 7076596897.792, + "mem reserved avg": 17677858897.92, + "elapsed time": 359.1130418909597 + }, + { + "step": 1500, + "valid accuracy": 0.18, + "train loss": 0.8753406238555909, + "train samples": 6000, + "train time": 48.10185396374436, + "eval time": 16.48715262202313, + "tokens / sec": 4351.828105373616, + "mem allocated avg": 7079910084.608, + "mem reserved avg": 17610313826.304, + "elapsed time": 427.0594008389744 + }, + { + "step": 1750, + "valid accuracy": 0.24, + "train loss": 0.8501061711311341, + "train samples": 7000, + "train time": 48.353323488729075, + "eval time": 16.45508589997189, + "tokens / sec": 4329.692043790943, + "mem allocated avg": 7081518635.008, + "mem reserved avg": 17944507580.416, + "elapsed time": 495.1906558799674 + }, + { + "step": 2000, + "valid accuracy": 0.3, + "train loss": 0.8353028309345245, + "train samples": 8000, + "train time": 47.772918620554265, + "eval time": 16.471650794963352, + "tokens / sec": 4347.567743341495, + "mem allocated avg": 7076895195.136, + "mem reserved avg": 17455510454.272, + "elapsed time": 562.7745764599531 + }, + { + "step": 2250, + "valid accuracy": 0.26, + "train loss": 0.8205564830303193, + "train samples": 9000, + "train time": 49.30290105647873, + "eval time": 16.451010891993064, + "tokens / sec": 4359.743451075368, + "mem allocated avg": 7088224200.704, + "mem reserved avg": 17821908074.496, + "elapsed time": 631.8972226959886 + }, + { + "step": 2500, + "valid accuracy": 0.3, + "train loss": 0.8072783839702606, + "train samples": 10000, + "train time": 47.070282332773786, + "eval time": 16.457994004013017, + "tokens / sec": 4375.73326082624, + "mem allocated avg": 7075521802.24, + "mem reserved avg": 17499282210.816, + "elapsed time": 698.7572857749765 + }, + { + "step": 2750, + "valid accuracy": 0.22, + "train loss": 0.8001595716476441, + "train samples": 11000, + "train time": 49.0196822991129, + "eval time": 16.485916983976495, + "tokens / sec": 4322.365834750307, + "mem allocated avg": 7083802673.152, + "mem reserved avg": 18024199356.416, + "elapsed time": 767.6797842659871 + }, + { + "step": 3000, + "valid accuracy": 0.26, + "train loss": 0.7877968080043792, + "train samples": 12000, + "train time": 48.047267597168684, + "eval time": 16.470330245036166, + "tokens / sec": 4344.284502294987, + "mem allocated avg": 7078835648.512, + "mem reserved avg": 17764907483.136, + "elapsed time": 835.5052842849982 + }, + { + "step": 3250, + "valid accuracy": 0.28, + "train loss": 0.7942508835792541, + "train samples": 13000, + "train time": 48.499368979479186, + "eval time": 16.475236736994702, + "tokens / sec": 4348.5308043747, + "mem allocated avg": 7080606814.208, + "mem reserved avg": 17735715127.296, + "elapsed time": 903.7694554779446 + }, + { + "step": 3500, + "valid accuracy": 0.32, + "train loss": 0.780822759628296, + "train samples": 14000, + "train time": 48.17758794862311, + "eval time": 16.458987591962796, + "tokens / sec": 4353.684128472325, + "mem allocated avg": 7081026895.872, + "mem reserved avg": 17464184274.944, + "elapsed time": 971.7567571739783 + }, + { + "step": 3750, + "valid accuracy": 0.26, + "train loss": 0.7757164461612701, + "train samples": 15000, + "train time": 48.30266001843847, + "eval time": 16.458310062997043, + "tokens / sec": 4486.357478393083, + "mem allocated avg": 7091974598.656, + "mem reserved avg": 17988463886.336, + "elapsed time": 1039.8424308019457 + }, + { + "step": 4000, + "valid accuracy": 0.34, + "train loss": 0.7912626936435699, + "train samples": 16000, + "train time": 47.030636349343695, + "eval time": 16.47025357297389, + "tokens / sec": 4345.529124503372, + "mem allocated avg": 7072683055.104, + "mem reserved avg": 17487336833.024, + "elapsed time": 1106.6578654039768 + }, + { + "step": 4250, + "valid accuracy": 0.32, + "train loss": 0.7665636780261993, + "train samples": 17000, + "train time": 48.857000946998596, + "eval time": 16.620428661990445, + "tokens / sec": 4326.688005866765, + "mem allocated avg": 7082847784.96, + "mem reserved avg": 17545067233.28, + "elapsed time": 1175.4323937539593 + }, + { + "step": 4500, + "valid accuracy": 0.32, + "train loss": 0.7785143363475799, + "train samples": 18000, + "train time": 47.66669207031373, + "eval time": 16.471256715012714, + "tokens / sec": 4359.815858282028, + "mem allocated avg": 7077102155.776, + "mem reserved avg": 17491698909.184, + "elapsed time": 1242.9420014299685 + }, + { + "step": 4750, + "valid accuracy": 0.38, + "train loss": 0.7709136388301849, + "train samples": 19000, + "train time": 49.014523516292684, + "eval time": 16.465405926981475, + "tokens / sec": 4283.199854635232, + "mem allocated avg": 7080302989.312, + "mem reserved avg": 17688931860.48, + "elapsed time": 1311.757940771 + }, + { + "step": 5000, + "valid accuracy": 0.34, + "train loss": 0.7789487948417664, + "train samples": 20000, + "train time": 47.309582717716694, + "eval time": 16.467871464032214, + "tokens / sec": 4402.490743635378, + "mem allocated avg": 7078423576.576, + "mem reserved avg": 17237222096.896, + "elapsed time": 1378.8721237509744 + }, + { + "step": 5000, + "test accuracy": 0.2517058377558757, + "train loss": 0.7789487948417664, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 3.673459053039551 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-sample_vocab-lr_0.001.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-sample_vocab-lr_0.001.json new file mode 100644 index 0000000000000000000000000000000000000000..def3b78b2ec9e30ce3ff96b4be4b12006737d18b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/prompt_tuning--llama-3.2-3B-sample_vocab-lr_0.001.json @@ -0,0 +1,350 @@ +{ + "run_info": { + "created_at": "2026-01-10T07:44:42+00:00", + "total_time": 1716.5059452480054, + "experiment_name": "prompt_tuning/llama-3.2-3B-sample_vocab-lr_0.001", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.001 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "PROMPT_TUNING", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "num_virtual_tokens": 200, + "token_dim": 3072, + "num_transformer_submodules": 1, + "num_attention_heads": 24, + "num_layers": 28, + "modules_to_save": null, + "prompt_tuning_init": "SAMPLE_VOCAB", + "prompt_tuning_init_text": null, + "tokenizer_name_or_path": null, + "tokenizer_kwargs": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 17586373997, + "accelerator_memory_max": 24423432192, + "accelerator_memory_reserved_99th": 22726102220, + "train_time": 1432.4597771912813, + "file_size": 2457728, + "num_trainable_params": 614400, + "num_total_params": 3213364224, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.28, + "train loss": 1.231001257419586, + "train samples": 1000, + "train time": 49.07237136311596, + "eval time": 16.56022824399406, + "tokens / sec": 4314.423658750133, + "mem allocated avg": 7084323387.392, + "mem reserved avg": 17684527841.28, + "elapsed time": 88.38586634700187 + }, + { + "step": 500, + "valid accuracy": 0.28, + "train loss": 0.7781594865322113, + "train samples": 2000, + "train time": 48.241733307542745, + "eval time": 16.490848871006165, + "tokens / sec": 4311.515895874316, + "mem allocated avg": 7075966793.728, + "mem reserved avg": 17277822959.616, + "elapsed time": 156.45012381998822 + }, + { + "step": 750, + "valid accuracy": 0.4, + "train loss": 0.741938561797142, + "train samples": 3000, + "train time": 49.612739670265, + "eval time": 16.47905260400148, + "tokens / sec": 4321.490839347853, + "mem allocated avg": 7086541828.096, + "mem reserved avg": 17510808158.208, + "elapsed time": 225.8728333899635 + }, + { + "step": 1000, + "valid accuracy": 0.42, + "train loss": 0.7171692438125611, + "train samples": 4000, + "train time": 48.20866126095643, + "eval time": 10.150423899991438, + "tokens / sec": 4321.547094458078, + "mem allocated avg": 7080115116.032, + "mem reserved avg": 17537341325.312, + "elapsed time": 287.67958221398294 + }, + { + "step": 1250, + "valid accuracy": 0.26, + "train loss": 0.7132015836238861, + "train samples": 5000, + "train time": 48.86127889546333, + "eval time": 16.462877204001416, + "tokens / sec": 4267.960330022437, + "mem allocated avg": 7076709810.176, + "mem reserved avg": 17610590650.368, + "elapsed time": 356.37783604400465 + }, + { + "step": 1500, + "valid accuracy": 0.38, + "train loss": 0.7038432757854461, + "train samples": 6000, + "train time": 47.56107051449362, + "eval time": 11.72161501395749, + "tokens / sec": 4401.309679020136, + "mem allocated avg": 7079892111.36, + "mem reserved avg": 17553254514.688, + "elapsed time": 418.98402368696406 + }, + { + "step": 1750, + "valid accuracy": 0.28, + "train loss": 0.6960202144384384, + "train samples": 7000, + "train time": 47.92567691701697, + "eval time": 16.476755581970792, + "tokens / sec": 4368.326405957645, + "mem allocated avg": 7081680021.504, + "mem reserved avg": 17797270732.8, + "elapsed time": 486.68094182398636 + }, + { + "step": 2000, + "valid accuracy": 0.36, + "train loss": 0.6972298842668533, + "train samples": 8000, + "train time": 48.42164681700524, + "eval time": 16.48074709100183, + "tokens / sec": 4289.321277835165, + "mem allocated avg": 7076841058.304, + "mem reserved avg": 17448875065.344, + "elapsed time": 554.9344664419768 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6904777873754502, + "train samples": 9000, + "train time": 48.16334705770714, + "eval time": 16.464009888994042, + "tokens / sec": 4462.895814579892, + "mem allocated avg": 7088048144.384, + "mem reserved avg": 17760679624.704, + "elapsed time": 622.9242907789885 + }, + { + "step": 2500, + "valid accuracy": 0.3, + "train loss": 0.6871954158544541, + "train samples": 10000, + "train time": 47.13648067950271, + "eval time": 10.590642432973254, + "tokens / sec": 4369.58799279991, + "mem allocated avg": 7075573088.256, + "mem reserved avg": 17511076593.664, + "elapsed time": 684.0204358329647 + }, + { + "step": 2750, + "valid accuracy": 0.4, + "train loss": 0.6794538542032241, + "train samples": 11000, + "train time": 49.06664197781356, + "eval time": 16.50549652200425, + "tokens / sec": 4318.229074975339, + "mem allocated avg": 7083983587.328, + "mem reserved avg": 17821639639.04, + "elapsed time": 752.9455686199944 + }, + { + "step": 3000, + "valid accuracy": 0.4, + "train loss": 0.6709245092868805, + "train samples": 12000, + "train time": 48.61840220115846, + "eval time": 11.749490908987354, + "tokens / sec": 4293.2509204308335, + "mem allocated avg": 7078543196.16, + "mem reserved avg": 17548003246.08, + "elapsed time": 816.6363624369842 + }, + { + "step": 3250, + "valid accuracy": 0.34, + "train loss": 0.6784907094240189, + "train samples": 13000, + "train time": 49.01847082650056, + "eval time": 16.607726505957544, + "tokens / sec": 4302.480196627877, + "mem allocated avg": 7080616044.544, + "mem reserved avg": 17588226621.44, + "elapsed time": 885.5438669619616 + }, + { + "step": 3500, + "valid accuracy": 0.42, + "train loss": 0.6641751153469085, + "train samples": 14000, + "train time": 47.80453353270423, + "eval time": 10.248818032967392, + "tokens / sec": 4387.659171624487, + "mem allocated avg": 7081103153.152, + "mem reserved avg": 17553304846.336, + "elapsed time": 946.9957575129811 + }, + { + "step": 3750, + "valid accuracy": 0.42, + "train loss": 0.6602498284578323, + "train samples": 15000, + "train time": 49.44991112826392, + "eval time": 16.504967942018993, + "tokens / sec": 4382.272789892635, + "mem allocated avg": 7091858644.992, + "mem reserved avg": 17967123267.584, + "elapsed time": 1016.2674351629685 + }, + { + "step": 4000, + "valid accuracy": 0.42, + "train loss": 0.6744856735467911, + "train samples": 16000, + "train time": 47.36242724902695, + "eval time": 16.486980255984236, + "tokens / sec": 4315.087124344937, + "mem allocated avg": 7072767692.8, + "mem reserved avg": 17510019629.056, + "elapsed time": 1083.4467996029998 + }, + { + "step": 4250, + "valid accuracy": 0.36, + "train loss": 0.6564534237384796, + "train samples": 17000, + "train time": 48.728701793181244, + "eval time": 11.983494354994036, + "tokens / sec": 4338.079863017822, + "mem allocated avg": 7083052060.672, + "mem reserved avg": 17659378794.496, + "elapsed time": 1147.4254322479828 + }, + { + "step": 4500, + "valid accuracy": 0.42, + "train loss": 0.6627028694152832, + "train samples": 18000, + "train time": 47.626907504571136, + "eval time": 9.85688041697722, + "tokens / sec": 4363.457778148918, + "mem allocated avg": 7077199714.304, + "mem reserved avg": 17402955825.152, + "elapsed time": 1208.2546821089927 + }, + { + "step": 4750, + "valid accuracy": 0.4, + "train loss": 0.655256854891777, + "train samples": 19000, + "train time": 47.39932202390628, + "eval time": 11.606938865967095, + "tokens / sec": 4429.1561785233, + "mem allocated avg": 7080305192.96, + "mem reserved avg": 17739850711.04, + "elapsed time": 1270.5360992229544 + }, + { + "step": 5000, + "valid accuracy": 0.4, + "train loss": 0.6607183293104172, + "train samples": 20000, + "train time": 47.21705101500265, + "eval time": 11.613721745961811, + "tokens / sec": 4411.118346502019, + "mem allocated avg": 7078454282.24, + "mem reserved avg": 17244729901.056, + "elapsed time": 1332.6370788229979 + }, + { + "step": 5000, + "test accuracy": 0.3555724033358605, + "train loss": 0.6607183293104172, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 2.631608009338379 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ptuning--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ptuning--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..6af724b8f689b0bda8bfa041dd0b28a415177ea4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/ptuning--llama-3.2-3B-default.json @@ -0,0 +1,351 @@ +{ + "run_info": { + "created_at": "2026-01-10T08:13:23+00:00", + "total_time": 1162.917062154971, + "experiment_name": "ptuning/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "P_TUNING", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "num_virtual_tokens": 20, + "token_dim": 3072, + "num_transformer_submodules": 1, + "num_attention_heads": 24, + "num_layers": 28, + "modules_to_save": null, + "encoder_reparameterization_type": "MLP", + "encoder_hidden_size": 3072, + "encoder_num_layers": 2, + "encoder_dropout": 0.0 + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14104160475, + "accelerator_memory_max": 20950548480, + "accelerator_memory_reserved_99th": 19218300928, + "train_time": 959.7272375969915, + "file_size": 245880, + "num_trainable_params": 28382208, + "num_total_params": 3241132032, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.12, + "train loss": 0.9454967255592346, + "train samples": 1000, + "train time": 29.694366472947877, + "eval time": 11.680081729020458, + "tokens / sec": 7129.938272731966, + "mem allocated avg": 7266438576.128, + "mem reserved avg": 14210964652.032, + "elapsed time": 62.83816469996236 + }, + { + "step": 500, + "valid accuracy": 0.36, + "train loss": 0.7915761218070984, + "train samples": 2000, + "train time": 30.064934794034343, + "eval time": 11.6559070070507, + "tokens / sec": 6918.192286958545, + "mem allocated avg": 7258846287.872, + "mem reserved avg": 13882106052.608, + "elapsed time": 107.20484153198777 + }, + { + "step": 750, + "valid accuracy": 0.32, + "train loss": 0.7556082547903061, + "train samples": 3000, + "train time": 30.023478755319957, + "eval time": 11.630144803028088, + "tokens / sec": 7141.111186591247, + "mem allocated avg": 7269281730.56, + "mem reserved avg": 14078433034.24, + "elapsed time": 151.32677704497473 + }, + { + "step": 1000, + "valid accuracy": 0.28, + "train loss": 0.7297289679050446, + "train samples": 4000, + "train time": 29.457952680124436, + "eval time": 11.804060328984633, + "tokens / sec": 7072.317695063931, + "mem allocated avg": 7260512626.688, + "mem reserved avg": 14043024719.872, + "elapsed time": 195.22547230595956 + }, + { + "step": 1250, + "valid accuracy": 0.38, + "train loss": 0.7234208507537842, + "train samples": 5000, + "train time": 29.54452143079834, + "eval time": 11.626074030995369, + "tokens / sec": 7058.43215258894, + "mem allocated avg": 7259926929.408, + "mem reserved avg": 14128538189.824, + "elapsed time": 238.97390070999973 + }, + { + "step": 1500, + "valid accuracy": 0.36, + "train loss": 0.7123123975992203, + "train samples": 6000, + "train time": 30.126697142142802, + "eval time": 8.240376622998156, + "tokens / sec": 6948.355440768741, + "mem allocated avg": 7261799639.04, + "mem reserved avg": 14042739507.2, + "elapsed time": 279.96362110297196 + }, + { + "step": 1750, + "valid accuracy": 0.42, + "train loss": 0.7047000522613526, + "train samples": 7000, + "train time": 29.664779813203495, + "eval time": 11.633714700001292, + "tokens / sec": 7057.358973108514, + "mem allocated avg": 7263532308.48, + "mem reserved avg": 14314966614.016, + "elapsed time": 323.87410058197565 + }, + { + "step": 2000, + "valid accuracy": 0.44, + "train loss": 0.7051602005958557, + "train samples": 8000, + "train time": 29.419329382071737, + "eval time": 11.648401496990118, + "tokens / sec": 7059.848214166664, + "mem allocated avg": 7259382927.36, + "mem reserved avg": 14145265074.176, + "elapsed time": 367.623096796975 + }, + { + "step": 2250, + "valid accuracy": 0.44, + "train loss": 0.6980359296798706, + "train samples": 9000, + "train time": 30.83813531260239, + "eval time": 11.641796185984276, + "tokens / sec": 6970.20094830957, + "mem allocated avg": 7271977609.216, + "mem reserved avg": 14313431498.752, + "elapsed time": 412.71304436796345 + }, + { + "step": 2500, + "valid accuracy": 0.5, + "train loss": 0.6962304570674896, + "train samples": 10000, + "train time": 29.281850074534304, + "eval time": 7.721943242009729, + "tokens / sec": 7033.947632261268, + "mem allocated avg": 7256155267.072, + "mem reserved avg": 13909410971.648, + "elapsed time": 452.32350523298373 + }, + { + "step": 2750, + "valid accuracy": 0.4, + "train loss": 0.6884069440364837, + "train samples": 11000, + "train time": 29.80504708213266, + "eval time": 11.643363915965892, + "tokens / sec": 7108.8966716317345, + "mem allocated avg": 7266777749.504, + "mem reserved avg": 14297912573.952, + "elapsed time": 496.34979761595605 + }, + { + "step": 3000, + "valid accuracy": 0.34, + "train loss": 0.6823657184839249, + "train samples": 12000, + "train time": 29.4866174882045, + "eval time": 11.663472635962535, + "tokens / sec": 7078.838394519087, + "mem allocated avg": 7261770512.384, + "mem reserved avg": 14176470695.936, + "elapsed time": 540.1913515449851 + }, + { + "step": 3250, + "valid accuracy": 0.32, + "train loss": 0.6892943847179412, + "train samples": 13000, + "train time": 30.05981874052668, + "eval time": 9.359989358054008, + "tokens / sec": 7016.043636872069, + "mem allocated avg": 7263956414.464, + "mem reserved avg": 14069599830.016, + "elapsed time": 582.1699139429838 + }, + { + "step": 3500, + "valid accuracy": 0.34, + "train loss": 0.6757683880329132, + "train samples": 14000, + "train time": 29.95969556894852, + "eval time": 11.67419690900715, + "tokens / sec": 7001.072474761515, + "mem allocated avg": 7262049505.28, + "mem reserved avg": 14046656987.136, + "elapsed time": 626.462889155955 + }, + { + "step": 3750, + "valid accuracy": 0.32, + "train loss": 0.6726086636781693, + "train samples": 15000, + "train time": 30.04007897916017, + "eval time": 11.621128266968299, + "tokens / sec": 7213.795947418589, + "mem allocated avg": 7273184010.24, + "mem reserved avg": 14348948865.024, + "elapsed time": 670.6827715289546 + }, + { + "step": 4000, + "valid accuracy": 0.36, + "train loss": 0.687798623919487, + "train samples": 16000, + "train time": 28.8626030132873, + "eval time": 6.513009499001782, + "tokens / sec": 7080.892873934969, + "mem allocated avg": 7255382544.384, + "mem reserved avg": 14072502288.384, + "elapsed time": 708.7366754019749 + }, + { + "step": 4250, + "valid accuracy": 0.34, + "train loss": 0.6694162834882736, + "train samples": 17000, + "train time": 29.575119761226233, + "eval time": 6.9559804140008055, + "tokens / sec": 7147.528115072473, + "mem allocated avg": 7265205653.504, + "mem reserved avg": 14095831007.232, + "elapsed time": 747.7560498069506 + }, + { + "step": 4500, + "valid accuracy": 0.42, + "train loss": 0.6779570702314377, + "train samples": 18000, + "train time": 29.56798030581558, + "eval time": 6.977328688022681, + "tokens / sec": 7028.4814130211425, + "mem allocated avg": 7259650541.568, + "mem reserved avg": 14029410009.088, + "elapsed time": 786.97692555096 + }, + { + "step": 4750, + "valid accuracy": 0.32, + "train loss": 0.6683919057846069, + "train samples": 19000, + "train time": 30.30186787992716, + "eval time": 6.962075466988608, + "tokens / sec": 6928.252767515686, + "mem allocated avg": 7262556618.752, + "mem reserved avg": 14063425814.528, + "elapsed time": 826.7863181569846 + }, + { + "step": 5000, + "valid accuracy": 0.38, + "train loss": 0.6739522596597671, + "train samples": 20000, + "train time": 29.33842807688052, + "eval time": 7.4907851399620995, + "tokens / sec": 7099.221521146537, + "mem allocated avg": 7259827462.144, + "mem reserved avg": 13813571125.248, + "elapsed time": 866.1968886919785 + }, + { + "step": 5000, + "test accuracy": 0.3821076573161486, + "train loss": 0.6739522596597671, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 3.1548709869384766 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/randlora--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/randlora--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..c4676423cea2bd9fc80f4bbf1954fae53294d2ed --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/randlora--llama-3.2-3B-default.json @@ -0,0 +1,358 @@ +{ + "run_info": { + "created_at": "2026-01-10T08:32:50+00:00", + "total_time": 1712.8715220090235, + "experiment_name": "randlora/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "RANDLORA", + "auto_mapping": null, + "peft_version": null, + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "target_modules": [ + "v_proj", + "q_proj" + ], + "projection_prng_key": 0, + "save_projection": true, + "sparse": false, + "very_sparse": false, + "randlora_dropout": 0.0, + "fan_in_fan_out": false, + "randlora_alpha": 640, + "bias": "none", + "modules_to_save": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 15193692176, + "accelerator_memory_max": 22791847936, + "accelerator_memory_reserved_99th": 20508049408, + "train_time": 1465.4105980930617, + "file_size": 2211281240, + "num_trainable_params": 9289728, + "num_total_params": 3222039552, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.38, + "train loss": 0.9159073839187623, + "train samples": 1000, + "train time": 51.456300139427185, + "eval time": 8.755500879022293, + "tokens / sec": 4114.539899416034, + "mem allocated avg": 6994605942.784, + "mem reserved avg": 15311281586.176, + "elapsed time": 84.91182701400248 + }, + { + "step": 500, + "valid accuracy": 0.34, + "train loss": 0.7010563344955444, + "train samples": 2000, + "train time": 52.27174317778554, + "eval time": 14.115188423951622, + "tokens / sec": 3979.1096939807776, + "mem allocated avg": 6986201692.16, + "mem reserved avg": 14981995167.744, + "elapsed time": 154.25366032699822 + }, + { + "step": 750, + "valid accuracy": 0.36, + "train loss": 0.6810104308128357, + "train samples": 3000, + "train time": 52.0417874493869, + "eval time": 8.199473799031693, + "tokens / sec": 4119.785474480774, + "mem allocated avg": 6997675347.968, + "mem reserved avg": 15224560156.672, + "elapsed time": 217.4881883119815 + }, + { + "step": 1000, + "valid accuracy": 0.28, + "train loss": 0.6662307423353195, + "train samples": 4000, + "train time": 51.765757714165375, + "eval time": 7.892937373020686, + "tokens / sec": 4024.5909496846825, + "mem allocated avg": 6988936497.152, + "mem reserved avg": 15255941939.2, + "elapsed time": 280.21508718596306 + }, + { + "step": 1250, + "valid accuracy": 0.38, + "train loss": 0.6655746358633041, + "train samples": 5000, + "train time": 52.88386500120396, + "eval time": 14.099892683967482, + "tokens / sec": 3943.3199520355106, + "mem allocated avg": 6988741001.216, + "mem reserved avg": 15194075955.2, + "elapsed time": 350.0570412139641 + }, + { + "step": 1500, + "valid accuracy": 0.38, + "train loss": 0.6581832259893418, + "train samples": 6000, + "train time": 52.76923948794138, + "eval time": 14.133205129997805, + "tokens / sec": 3966.9133387422708, + "mem allocated avg": 6991358814.208, + "mem reserved avg": 15142125305.856, + "elapsed time": 419.9533305739751 + }, + { + "step": 1750, + "valid accuracy": 0.36, + "train loss": 0.6510355799198151, + "train samples": 7000, + "train time": 53.25456840818515, + "eval time": 13.085501310008112, + "tokens / sec": 3931.212030399676, + "mem allocated avg": 6991980468.224, + "mem reserved avg": 15527758004.224, + "elapsed time": 489.19832555996254 + }, + { + "step": 2000, + "valid accuracy": 0.46, + "train loss": 0.6502977329492569, + "train samples": 8000, + "train time": 53.048176583775785, + "eval time": 14.269489981001243, + "tokens / sec": 3915.2335362931512, + "mem allocated avg": 6987123507.2, + "mem reserved avg": 15160764792.832, + "elapsed time": 559.521614014986 + }, + { + "step": 2250, + "valid accuracy": 0.46, + "train loss": 0.6383942588567734, + "train samples": 9000, + "train time": 54.19255740486551, + "eval time": 14.067514252034016, + "tokens / sec": 3966.374910011196, + "mem allocated avg": 6999139655.68, + "mem reserved avg": 15462352027.648, + "elapsed time": 630.752589983982 + }, + { + "step": 2500, + "valid accuracy": 0.42, + "train loss": 0.6331259000301361, + "train samples": 10000, + "train time": 51.30145365791395, + "eval time": 14.185831039969344, + "tokens / sec": 4014.837500968684, + "mem allocated avg": 6985442590.72, + "mem reserved avg": 15002463371.264, + "elapsed time": 699.3249540069955 + }, + { + "step": 2750, + "valid accuracy": 0.5, + "train loss": 0.6209538959264755, + "train samples": 11000, + "train time": 52.28545083821518, + "eval time": 8.485180826974101, + "tokens / sec": 4052.3892708817802, + "mem allocated avg": 6994917660.672, + "mem reserved avg": 15347461652.48, + "elapsed time": 763.0090306919883 + }, + { + "step": 3000, + "valid accuracy": 0.42, + "train loss": 0.608346626996994, + "train samples": 12000, + "train time": 50.35002116265241, + "eval time": 7.221828919020481, + "tokens / sec": 4145.599051998574, + "mem allocated avg": 6990200410.112, + "mem reserved avg": 15265429454.848, + "elapsed time": 823.5788191119791 + }, + { + "step": 3250, + "valid accuracy": 0.5, + "train loss": 0.6135392972230911, + "train samples": 13000, + "train time": 50.94754268962424, + "eval time": 14.057202987954952, + "tokens / sec": 4139.571584145337, + "mem allocated avg": 6993134067.712, + "mem reserved avg": 15059187138.56, + "elapsed time": 891.3881165689672 + }, + { + "step": 3500, + "valid accuracy": 0.52, + "train loss": 0.5913569860458374, + "train samples": 14000, + "train time": 51.22462305892259, + "eval time": 10.398285192961339, + "tokens / sec": 4094.710462949216, + "mem allocated avg": 6989725995.008, + "mem reserved avg": 15092934508.544, + "elapsed time": 955.9796246159822 + }, + { + "step": 3750, + "valid accuracy": 0.46, + "train loss": 0.586094471335411, + "train samples": 15000, + "train time": 54.32701862248359, + "eval time": 7.748301387007814, + "tokens / sec": 3988.8623652599267, + "mem allocated avg": 7002481041.408, + "mem reserved avg": 15310149124.096, + "elapsed time": 1020.95719456597 + }, + { + "step": 4000, + "valid accuracy": 0.48, + "train loss": 0.5912544637918472, + "train samples": 16000, + "train time": 51.06255231570685, + "eval time": 14.150051894015633, + "tokens / sec": 4002.4047120953414, + "mem allocated avg": 6982720993.28, + "mem reserved avg": 15162954219.52, + "elapsed time": 1089.1380827649846 + }, + { + "step": 4250, + "valid accuracy": 0.5, + "train loss": 0.5755240997076034, + "train samples": 17000, + "train time": 52.308833500603214, + "eval time": 14.18892294500256, + "tokens / sec": 4041.1721281752975, + "mem allocated avg": 6993589919.744, + "mem reserved avg": 15129659834.368, + "elapsed time": 1158.4711514469818 + }, + { + "step": 4500, + "valid accuracy": 0.56, + "train loss": 0.5807081238031387, + "train samples": 18000, + "train time": 50.61249336565379, + "eval time": 9.862378416000865, + "tokens / sec": 4106.0612939695175, + "mem allocated avg": 6988681547.776, + "mem reserved avg": 15200375799.808, + "elapsed time": 1221.9246637789765 + }, + { + "step": 4750, + "valid accuracy": 0.52, + "train loss": 0.5690834984779358, + "train samples": 19000, + "train time": 51.20076460047858, + "eval time": 8.214846904971637, + "tokens / sec": 4100.309861349955, + "mem allocated avg": 6991610628.096, + "mem reserved avg": 15140388864.0, + "elapsed time": 1284.1992750130012 + }, + { + "step": 5000, + "valid accuracy": 0.5, + "train loss": 0.5778189089298248, + "train samples": 20000, + "train time": 51.87798086879775, + "eval time": 8.667530598992016, + "tokens / sec": 4014.8054436958814, + "mem allocated avg": 6988335155.2, + "mem reserved avg": 14901984624.64, + "elapsed time": 1347.629596157989 + }, + { + "step": 5000, + "test accuracy": 0.49962092494313876, + "train loss": 0.5778189089298248, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.46999263763427734 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/road--llama-3.2-3B-lr_0.001.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/road--llama-3.2-3B-lr_0.001.json new file mode 100644 index 0000000000000000000000000000000000000000..5b291e29e818428ebc52c791f5e73551547aa320 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/road--llama-3.2-3B-lr_0.001.json @@ -0,0 +1,348 @@ +{ + "run_info": { + "created_at": "2026-01-10T09:01:28+00:00", + "total_time": 1209.8416560290498, + "experiment_name": "road/llama-3.2-3B-lr_0.001", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.001 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "ROAD", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "variant": "road_2", + "group_size": 64, + "init_weights": true, + "target_modules": [ + "v_proj", + "q_proj" + ], + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14529478839, + "accelerator_memory_max": 22806528000, + "accelerator_memory_reserved_99th": 20495466496, + "train_time": 986.1049144260469, + "file_size": 931480, + "num_trainable_params": 229376, + "num_total_params": 3212979200, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.22, + "train loss": 1.1801395919322968, + "train samples": 1000, + "train time": 30.463671060162596, + "eval time": 12.11280647298554, + "tokens / sec": 6949.88465381854, + "mem allocated avg": 6785091975.168, + "mem reserved avg": 14651240742.912, + "elapsed time": 66.61390974500682 + }, + { + "step": 500, + "valid accuracy": 0.3, + "train loss": 0.8728977775573731, + "train samples": 2000, + "train time": 30.350360362324864, + "eval time": 12.122786874999292, + "tokens / sec": 6853.1311495791215, + "mem allocated avg": 6777472542.72, + "mem reserved avg": 14239108431.872, + "elapsed time": 112.51008765597362 + }, + { + "step": 750, + "valid accuracy": 0.42, + "train loss": 0.7738239982128143, + "train samples": 3000, + "train time": 31.060686238168273, + "eval time": 12.105645439994987, + "tokens / sec": 6902.648523474598, + "mem allocated avg": 6787427880.96, + "mem reserved avg": 14477940490.24, + "elapsed time": 159.04484326101374 + }, + { + "step": 1000, + "valid accuracy": 0.36, + "train loss": 0.7328966956138611, + "train samples": 4000, + "train time": 31.1341793507454, + "eval time": 12.271532059996389, + "tokens / sec": 6691.552639077739, + "mem allocated avg": 6779240853.504, + "mem reserved avg": 14547599491.072, + "elapsed time": 205.96491558500566 + }, + { + "step": 1250, + "valid accuracy": 0.32, + "train loss": 0.7226412436962127, + "train samples": 5000, + "train time": 30.673152873758227, + "eval time": 12.08470779901836, + "tokens / sec": 6798.714199948135, + "mem allocated avg": 6779142604.8, + "mem reserved avg": 14559075106.816, + "elapsed time": 252.09245199902216 + }, + { + "step": 1500, + "valid accuracy": 0.38, + "train loss": 0.7143599749803543, + "train samples": 6000, + "train time": 31.072990959743038, + "eval time": 12.123655039002188, + "tokens / sec": 6736.750905994249, + "mem allocated avg": 6781227952.128, + "mem reserved avg": 14496538034.176, + "elapsed time": 298.79225073900307 + }, + { + "step": 1750, + "valid accuracy": 0.38, + "train loss": 0.7038573758602142, + "train samples": 7000, + "train time": 30.712441952317022, + "eval time": 12.087091822992079, + "tokens / sec": 6816.618500249399, + "mem allocated avg": 6782587774.976, + "mem reserved avg": 14888504131.584, + "elapsed time": 345.02615644899197 + }, + { + "step": 2000, + "valid accuracy": 0.3, + "train loss": 0.7051438037157058, + "train samples": 8000, + "train time": 30.437189053802285, + "eval time": 12.269888009992428, + "tokens / sec": 6823.757595777529, + "mem allocated avg": 6778266038.272, + "mem reserved avg": 14524782477.312, + "elapsed time": 391.30238440597896 + }, + { + "step": 2250, + "valid accuracy": 0.4, + "train loss": 0.697867576956749, + "train samples": 9000, + "train time": 31.4548720899038, + "eval time": 12.078225647972431, + "tokens / sec": 6833.535974511012, + "mem allocated avg": 6789062723.584, + "mem reserved avg": 14819180675.072, + "elapsed time": 438.25679710297845 + }, + { + "step": 2500, + "valid accuracy": 0.38, + "train loss": 0.6966045496463775, + "train samples": 10000, + "train time": 30.316960251017008, + "eval time": 12.1344860860263, + "tokens / sec": 6793.78797526677, + "mem allocated avg": 6775575060.48, + "mem reserved avg": 14285396770.816, + "elapsed time": 484.1519402990234 + }, + { + "step": 2750, + "valid accuracy": 0.4, + "train loss": 0.6900997126102447, + "train samples": 11000, + "train time": 31.133579084766097, + "eval time": 12.133857114997227, + "tokens / sec": 6805.545852056406, + "mem allocated avg": 6784651790.336, + "mem reserved avg": 14683520106.496, + "elapsed time": 530.7991969200084 + }, + { + "step": 3000, + "valid accuracy": 0.38, + "train loss": 0.6820800434350968, + "train samples": 12000, + "train time": 31.004261121852323, + "eval time": 6.647833172988612, + "tokens / sec": 6732.332668069386, + "mem allocated avg": 6781542193.152, + "mem reserved avg": 14604935626.752, + "elapsed time": 571.967426163028 + }, + { + "step": 3250, + "valid accuracy": 0.4, + "train loss": 0.6917668293714523, + "train samples": 13000, + "train time": 30.61097677750513, + "eval time": 8.696813674003351, + "tokens / sec": 6889.718075085513, + "mem allocated avg": 6783328645.12, + "mem reserved avg": 14447456288.768, + "elapsed time": 614.5629294660175 + }, + { + "step": 3500, + "valid accuracy": 0.44, + "train loss": 0.6792756502628327, + "train samples": 14000, + "train time": 30.631839248526376, + "eval time": 8.344476633996237, + "tokens / sec": 6847.450402773009, + "mem allocated avg": 6780746895.36, + "mem reserved avg": 14468931125.248, + "elapsed time": 657.0185567580047 + }, + { + "step": 3750, + "valid accuracy": 0.4, + "train loss": 0.6768034971952438, + "train samples": 15000, + "train time": 31.22799357509939, + "eval time": 7.472214682027698, + "tokens / sec": 6939.3827521725525, + "mem allocated avg": 6791758675.968, + "mem reserved avg": 14830622736.384, + "elapsed time": 699.1621996440226 + }, + { + "step": 4000, + "valid accuracy": 0.4, + "train loss": 0.693776785492897, + "train samples": 16000, + "train time": 30.5784999235766, + "eval time": 7.540951641974971, + "tokens / sec": 6683.552185711522, + "mem allocated avg": 6772682035.2, + "mem reserved avg": 14486186491.904, + "elapsed time": 740.7859192459728 + }, + { + "step": 4250, + "valid accuracy": 0.42, + "train loss": 0.674255707025528, + "train samples": 17000, + "train time": 31.011587454471737, + "eval time": 12.230024265998509, + "tokens / sec": 6816.452086186856, + "mem allocated avg": 6784054867.968, + "mem reserved avg": 14463939903.488, + "elapsed time": 787.3081514210207 + }, + { + "step": 4500, + "valid accuracy": 0.44, + "train loss": 0.6836280490159988, + "train samples": 18000, + "train time": 30.32553677726537, + "eval time": 12.078615510021336, + "tokens / sec": 6852.904254469726, + "mem allocated avg": 6778766051.328, + "mem reserved avg": 14435452190.72, + "elapsed time": 833.2261762300041 + }, + { + "step": 4750, + "valid accuracy": 0.4, + "train loss": 0.676575911641121, + "train samples": 19000, + "train time": 30.607126664719544, + "eval time": 12.086251140979584, + "tokens / sec": 6859.154153859013, + "mem allocated avg": 6781519785.984, + "mem reserved avg": 14521225707.52, + "elapsed time": 879.2816601090017 + }, + { + "step": 5000, + "valid accuracy": 0.42, + "train loss": 0.6835739253759384, + "train samples": 20000, + "train time": 30.988149417680688, + "eval time": 12.111999842978548, + "tokens / sec": 6721.279066802329, + "mem allocated avg": 6777674483.712, + "mem reserved avg": 14157940260.864, + "elapsed time": 925.7869706979836 + }, + { + "step": 5000, + "test accuracy": 0.3866565579984837, + "train loss": 0.6835739253759384, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.1559743881225586 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/shira--llama-3.2-3B-lr_0.0003-random_seed_42.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/shira--llama-3.2-3B-lr_0.0003-random_seed_42.json new file mode 100644 index 0000000000000000000000000000000000000000..7f57aca19b2259362458bedaeae2fbe24cee5b6e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/shira--llama-3.2-3B-lr_0.0003-random_seed_42.json @@ -0,0 +1,350 @@ +{ + "run_info": { + "created_at": "2026-01-10T09:21:42+00:00", + "total_time": 1266.219620509015, + "experiment_name": "shira/llama-3.2-3B-lr_0.0003-random_seed_42", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0003 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "SHIRA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 32, + "mask_type": "random", + "random_seed": 42, + "target_modules": [ + "q_proj", + "v_proj" + ], + "fan_in_fan_out": false, + "init_weights": true, + "modules_to_save": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14575737398, + "accelerator_memory_max": 21678260224, + "accelerator_memory_reserved_99th": 19818086400, + "train_time": 1026.581762216112, + "file_size": 110115520, + "num_trainable_params": 9175040, + "num_total_params": 3221924864, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.38, + "train loss": 0.9357188229560852, + "train samples": 1000, + "train time": 31.005053431203123, + "eval time": 13.649991136044264, + "tokens / sec": 6828.5320155884165, + "mem allocated avg": 6998764658.688, + "mem reserved avg": 14655091113.984, + "elapsed time": 66.7176694990485 + }, + { + "step": 500, + "valid accuracy": 0.4, + "train loss": 0.7031368371248246, + "train samples": 2000, + "train time": 31.183240320475306, + "eval time": 8.634114325977862, + "tokens / sec": 6670.089376934567, + "mem allocated avg": 6991483916.288, + "mem reserved avg": 14325804695.552, + "elapsed time": 109.90105467604008 + }, + { + "step": 750, + "valid accuracy": 0.46, + "train loss": 0.6644203888177872, + "train samples": 3000, + "train time": 31.103451813396532, + "eval time": 13.64413362799678, + "tokens / sec": 6893.157752595665, + "mem allocated avg": 7001957066.752, + "mem reserved avg": 14535368900.608, + "elapsed time": 157.93175754504045 + }, + { + "step": 1000, + "valid accuracy": 0.4, + "train loss": 0.6444325144290924, + "train samples": 4000, + "train time": 30.684549567697104, + "eval time": 13.796387184003834, + "tokens / sec": 6789.605939639536, + "mem allocated avg": 6993408995.328, + "mem reserved avg": 14586304528.384, + "elapsed time": 205.7778243360226 + }, + { + "step": 1250, + "valid accuracy": 0.42, + "train loss": 0.6387022986412049, + "train samples": 5000, + "train time": 30.919842153030913, + "eval time": 13.635492319008335, + "tokens / sec": 6744.471688047026, + "mem allocated avg": 6993185427.456, + "mem reserved avg": 14606370078.72, + "elapsed time": 253.6162872450077 + }, + { + "step": 1500, + "valid accuracy": 0.5, + "train loss": 0.6296824035644532, + "train samples": 6000, + "train time": 31.136358544055838, + "eval time": 13.624358916946221, + "tokens / sec": 6723.040515602067, + "mem allocated avg": 6995184592.896, + "mem reserved avg": 14538120364.032, + "elapsed time": 301.7656091070385 + }, + { + "step": 1750, + "valid accuracy": 0.5, + "train loss": 0.6209747047424317, + "train samples": 7000, + "train time": 31.68197686993517, + "eval time": 13.656035805994179, + "tokens / sec": 6608.0156822117015, + "mem allocated avg": 6995961063.424, + "mem reserved avg": 14895399567.36, + "elapsed time": 350.47537555603776 + }, + { + "step": 2000, + "valid accuracy": 0.46, + "train loss": 0.6227067719697952, + "train samples": 8000, + "train time": 30.87618053384358, + "eval time": 13.635997612960637, + "tokens / sec": 6726.738748412974, + "mem allocated avg": 6992352337.92, + "mem reserved avg": 14571960008.704, + "elapsed time": 398.4335696240305 + }, + { + "step": 2250, + "valid accuracy": 0.42, + "train loss": 0.6115854290723801, + "train samples": 9000, + "train time": 31.98190122464439, + "eval time": 13.636252279975452, + "tokens / sec": 6720.926266708837, + "mem allocated avg": 7003833470.976, + "mem reserved avg": 14827611226.112, + "elapsed time": 447.4371414630441 + }, + { + "step": 2500, + "valid accuracy": 0.48, + "train loss": 0.6084150255918502, + "train samples": 10000, + "train time": 31.10554581769975, + "eval time": 13.639432755007874, + "tokens / sec": 6621.552349767809, + "mem allocated avg": 6989386164.224, + "mem reserved avg": 14371598106.624, + "elapsed time": 495.53728479502024 + }, + { + "step": 2750, + "valid accuracy": 0.48, + "train loss": 0.598827944278717, + "train samples": 11000, + "train time": 31.166906193597242, + "eval time": 10.745618918037508, + "tokens / sec": 6798.268608500117, + "mem allocated avg": 6999211896.832, + "mem reserved avg": 14710699196.416, + "elapsed time": 540.7916241060011 + }, + { + "step": 3000, + "valid accuracy": 0.5, + "train loss": 0.5887291294336319, + "train samples": 12000, + "train time": 30.795661959215067, + "eval time": 12.80061661900254, + "tokens / sec": 6777.9351610118865, + "mem allocated avg": 6994559866.88, + "mem reserved avg": 14628163682.304, + "elapsed time": 587.7743918690248 + }, + { + "step": 3250, + "valid accuracy": 0.58, + "train loss": 0.597461501955986, + "train samples": 13000, + "train time": 31.37682155967923, + "eval time": 9.411147411970887, + "tokens / sec": 6721.553985283782, + "mem allocated avg": 6997160384.512, + "mem reserved avg": 14501202100.224, + "elapsed time": 631.8334740100545 + }, + { + "step": 3500, + "valid accuracy": 0.56, + "train loss": 0.5807107644081115, + "train samples": 14000, + "train time": 31.556804033578373, + "eval time": 9.451412087015342, + "tokens / sec": 6646.74406751752, + "mem allocated avg": 6994673545.216, + "mem reserved avg": 14552573935.616, + "elapsed time": 676.2394572110497 + }, + { + "step": 3750, + "valid accuracy": 0.56, + "train loss": 0.5781861733198166, + "train samples": 15000, + "train time": 31.661963078950066, + "eval time": 8.377148772997316, + "tokens / sec": 6844.269240654614, + "mem allocated avg": 7006026270.72, + "mem reserved avg": 14834229837.824, + "elapsed time": 719.6216589460382 + }, + { + "step": 4000, + "valid accuracy": 0.52, + "train loss": 0.5876536679267883, + "train samples": 16000, + "train time": 30.703147317806724, + "eval time": 13.655890587018803, + "tokens / sec": 6656.418571182472, + "mem allocated avg": 6986944800.768, + "mem reserved avg": 14532718100.48, + "elapsed time": 767.4079029310378 + }, + { + "step": 4250, + "valid accuracy": 0.54, + "train loss": 0.5748379683494568, + "train samples": 17000, + "train time": 31.318038100958802, + "eval time": 8.131663441017736, + "tokens / sec": 6749.752309469485, + "mem allocated avg": 6997509144.576, + "mem reserved avg": 14515999604.736, + "elapsed time": 810.1378366760327 + }, + { + "step": 4500, + "valid accuracy": 0.54, + "train loss": 0.5816982330083847, + "train samples": 18000, + "train time": 30.432493349188007, + "eval time": 9.551053533970844, + "tokens / sec": 6828.819368017539, + "mem allocated avg": 6992803389.44, + "mem reserved avg": 14505589342.208, + "elapsed time": 853.5443232820253 + }, + { + "step": 4750, + "valid accuracy": 0.6, + "train loss": 0.5723524678945542, + "train samples": 19000, + "train time": 30.418727806943934, + "eval time": 8.29991272703046, + "tokens / sec": 6901.6364304386025, + "mem allocated avg": 6995412983.808, + "mem reserved avg": 14580717715.456, + "elapsed time": 895.5305709300446 + }, + { + "step": 5000, + "valid accuracy": 0.56, + "train loss": 0.5786988343000412, + "train samples": 20000, + "train time": 30.267178804264404, + "eval time": 8.313903974951245, + "tokens / sec": 6881.38135856438, + "mem allocated avg": 6992403818.496, + "mem reserved avg": 14239225872.384, + "elapsed time": 937.4194786970038 + }, + { + "step": 5000, + "test accuracy": 0.5276724791508719, + "train loss": 0.5786988343000412, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.3599224090576172 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/trainable_tokens--llama-3.2-3B-sos+eos.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/trainable_tokens--llama-3.2-3B-sos+eos.json new file mode 100644 index 0000000000000000000000000000000000000000..6a60214223244f4cf5921ff9e7bd5573a9216b3c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/trainable_tokens--llama-3.2-3B-sos+eos.json @@ -0,0 +1,346 @@ +{ + "run_info": { + "created_at": "2026-01-10T09:42:53+00:00", + "total_time": 1247.7475435149972, + "experiment_name": "trainable_tokens/llama-3.2-3B-sos+eos", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.2 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "TRAINABLE_TOKENS", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "token_indices": [ + 128000, + 128001 + ], + "target_modules": "model.embed_tokens", + "init_weights": true + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14425538114, + "accelerator_memory_max": 20967325696, + "accelerator_memory_reserved_99th": 18897436672, + "train_time": 997.0611474359757, + "file_size": 49424, + "num_trainable_params": 6144, + "num_total_params": 3212755968, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.1, + "train loss": 0.9905012159347534, + "train samples": 1000, + "train time": 29.634983344411012, + "eval time": 12.536395390983671, + "tokens / sec": 7144.225375106512, + "mem allocated avg": 6778851835.904, + "mem reserved avg": 14544495706.112, + "elapsed time": 65.80975040997146 + }, + { + "step": 500, + "valid accuracy": 0.3, + "train loss": 0.9729812822341919, + "train samples": 2000, + "train time": 29.16309229255421, + "eval time": 12.553540614026133, + "tokens / sec": 7132.131185316872, + "mem allocated avg": 6772151279.616, + "mem reserved avg": 14197677096.96, + "elapsed time": 110.11175278900191 + }, + { + "step": 750, + "valid accuracy": 0.04, + "train loss": 1.0480547146797181, + "train samples": 3000, + "train time": 29.716528838151135, + "eval time": 12.526994656014722, + "tokens / sec": 7214.873620257571, + "mem allocated avg": 6781906634.752, + "mem reserved avg": 14420948287.488, + "elapsed time": 154.87282191601116 + }, + { + "step": 1000, + "valid accuracy": 0.22, + "train loss": 0.9436001698970795, + "train samples": 4000, + "train time": 29.420189953991212, + "eval time": 12.568019258033019, + "tokens / sec": 7081.395474529784, + "mem allocated avg": 6773335566.336, + "mem reserved avg": 14408482816.0, + "elapsed time": 199.46210629702546 + }, + { + "step": 1250, + "valid accuracy": 0.14, + "train loss": 0.9967188131809235, + "train samples": 5000, + "train time": 29.337331054673996, + "eval time": 12.49918926099781, + "tokens / sec": 7108.281241104102, + "mem allocated avg": 6773163264.0, + "mem reserved avg": 14396453552.128, + "elapsed time": 243.82226993597578 + }, + { + "step": 1500, + "valid accuracy": 0.24, + "train loss": 0.9018084218502045, + "train samples": 6000, + "train time": 29.38388642319478, + "eval time": 12.539064191980287, + "tokens / sec": 7124.006572349131, + "mem allocated avg": 6775546910.72, + "mem reserved avg": 14435041148.928, + "elapsed time": 288.2892293820041 + }, + { + "step": 1750, + "valid accuracy": 0.08, + "train loss": 0.9539130289554596, + "train samples": 7000, + "train time": 28.713767355075106, + "eval time": 12.493294921994675, + "tokens / sec": 7291.101770489092, + "mem allocated avg": 6776510859.264, + "mem reserved avg": 14674661736.448, + "elapsed time": 332.0281024390133 + }, + { + "step": 2000, + "valid accuracy": 0.28, + "train loss": 0.8857205002307892, + "train samples": 8000, + "train time": 28.366790932661388, + "eval time": 12.514002014009748, + "tokens / sec": 7321.8010628357615, + "mem allocated avg": 6772300070.912, + "mem reserved avg": 14436005838.848, + "elapsed time": 375.5168060029973 + }, + { + "step": 2250, + "valid accuracy": 0.12, + "train loss": 0.8438295316696167, + "train samples": 9000, + "train time": 29.40557757782517, + "eval time": 12.504264893999789, + "tokens / sec": 7309.769700360958, + "mem allocated avg": 6783270096.896, + "mem reserved avg": 14682664468.48, + "elapsed time": 419.90326115401695 + }, + { + "step": 2500, + "valid accuracy": 0.28, + "train loss": 0.9853150990009308, + "train samples": 10000, + "train time": 28.319882539799437, + "eval time": 12.528796100988984, + "tokens / sec": 7272.876210222398, + "mem allocated avg": 6769575254.016, + "mem reserved avg": 14188315410.432, + "elapsed time": 463.3294100689818 + }, + { + "step": 2750, + "valid accuracy": 0.38, + "train loss": 0.8659319682121277, + "train samples": 11000, + "train time": 29.408809582469985, + "eval time": 12.51743244897807, + "tokens / sec": 7204.677884218004, + "mem allocated avg": 6779202121.728, + "mem reserved avg": 14528272138.24, + "elapsed time": 507.77231002697954 + }, + { + "step": 3000, + "valid accuracy": 0.2, + "train loss": 0.8670841429233551, + "train samples": 12000, + "train time": 29.205915787781123, + "eval time": 12.515230823017191, + "tokens / sec": 7146.873993498494, + "mem allocated avg": 6774948583.424, + "mem reserved avg": 14482512281.6, + "elapsed time": 552.1565157959703 + }, + { + "step": 3250, + "valid accuracy": 0.24, + "train loss": 0.8831028847694397, + "train samples": 13000, + "train time": 28.957690052688122, + "eval time": 12.505934452987276, + "tokens / sec": 7283.074016479509, + "mem allocated avg": 6777873250.304, + "mem reserved avg": 14402812116.992, + "elapsed time": 596.0801243850146 + }, + { + "step": 3500, + "valid accuracy": 0.24, + "train loss": 0.8406728208065033, + "train samples": 14000, + "train time": 28.88564268813934, + "eval time": 12.525049041956663, + "tokens / sec": 7261.392874811295, + "mem allocated avg": 6774829201.408, + "mem reserved avg": 14323296501.76, + "elapsed time": 640.1019531330094 + }, + { + "step": 3750, + "valid accuracy": 0.22, + "train loss": 0.8314566104412079, + "train samples": 15000, + "train time": 29.845886443858035, + "eval time": 12.519134696980473, + "tokens / sec": 7260.732577255891, + "mem allocated avg": 6787227551.744, + "mem reserved avg": 14711236067.328, + "elapsed time": 685.0585421550204 + }, + { + "step": 4000, + "valid accuracy": 0.26, + "train loss": 0.8273813252449036, + "train samples": 16000, + "train time": 29.003598894923925, + "eval time": 12.54185038903961, + "tokens / sec": 7046.470361847695, + "mem allocated avg": 6767122819.072, + "mem reserved avg": 14423137714.176, + "elapsed time": 729.2252393189701 + }, + { + "step": 4250, + "valid accuracy": 0.34, + "train loss": 0.7995920785665512, + "train samples": 17000, + "train time": 29.465179357444867, + "eval time": 9.66559061704902, + "tokens / sec": 7174.196954161389, + "mem allocated avg": 6778672529.408, + "mem reserved avg": 14360768413.696, + "elapsed time": 770.7659295659978 + }, + { + "step": 4500, + "valid accuracy": 0.36, + "train loss": 0.7986028344631195, + "train samples": 18000, + "train time": 28.988296278985217, + "eval time": 12.561084756976925, + "tokens / sec": 7169.031184169855, + "mem allocated avg": 6773402359.808, + "mem reserved avg": 14380808798.208, + "elapsed time": 814.9140880479827 + }, + { + "step": 4750, + "valid accuracy": 0.32, + "train loss": 0.7896175284385681, + "train samples": 19000, + "train time": 28.64752666564891, + "eval time": 12.497469249996357, + "tokens / sec": 7328.34643807965, + "mem allocated avg": 6775494619.136, + "mem reserved avg": 14341474615.296, + "elapsed time": 858.5426965900115 + }, + { + "step": 5000, + "valid accuracy": 0.3, + "train loss": 0.7938800511360169, + "train samples": 20000, + "train time": 28.41598576674005, + "eval time": 12.515183010022156, + "tokens / sec": 7329.67709477757, + "mem allocated avg": 6772489893.888, + "mem reserved avg": 14171697577.984, + "elapsed time": 901.9474186989828 + }, + { + "step": 5000, + "test accuracy": 0.2721758908263836, + "train loss": 0.7938800511360169, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.20132732391357422 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/vblora--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/vblora--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..fae961d111bd1b1c11191b6521f7f451f42ba5cd --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/vblora--llama-3.2-3B-default.json @@ -0,0 +1,359 @@ +{ + "run_info": { + "created_at": "2026-01-10T10:03:45+00:00", + "total_time": 1442.0607667469885, + "experiment_name": "vblora/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "VBLORA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 4, + "num_vectors": 256, + "vector_length": 256, + "topk": 2, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "save_only_topk_weights": false, + "vblora_dropout": 0.0, + "fan_in_fan_out": false, + "bias": "none", + "modules_to_save": null, + "init_vector_bank_bound": 0.02, + "init_logits_std": 0.1, + "layers_to_transform": null, + "layers_pattern": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 14315209883, + "accelerator_memory_max": 22168993792, + "accelerator_memory_reserved_99th": 20019412992, + "train_time": 1188.2950591499684, + "file_size": 4864912, + "num_trainable_params": 1212416, + "num_total_params": 3213962240, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.3084168200492858, + "train samples": 1000, + "train time": 38.33692664222326, + "eval time": 13.785690262040589, + "tokens / sec": 5522.586668875496, + "mem allocated avg": 6799863355.392, + "mem reserved avg": 14422449848.32, + "elapsed time": 74.86309108795831 + }, + { + "step": 500, + "valid accuracy": 0.38, + "train loss": 1.0353211274147034, + "train samples": 2000, + "train time": 38.09402504004538, + "eval time": 13.701952785020694, + "tokens / sec": 5460.042612492392, + "mem allocated avg": 6792844609.536, + "mem reserved avg": 14055465025.536, + "elapsed time": 129.952204842004 + }, + { + "step": 750, + "valid accuracy": 0.3, + "train loss": 0.8149400570392609, + "train samples": 3000, + "train time": 38.48971955140587, + "eval time": 13.7833748270059, + "tokens / sec": 5570.344562101877, + "mem allocated avg": 6803264000.0, + "mem reserved avg": 14282477535.232, + "elapsed time": 185.41029871697538 + }, + { + "step": 1000, + "valid accuracy": 0.3, + "train loss": 0.7666769211292267, + "train samples": 4000, + "train time": 38.318057818338275, + "eval time": 13.802792146976572, + "tokens / sec": 5437.018780745575, + "mem allocated avg": 6793968019.456, + "mem reserved avg": 14342078595.072, + "elapsed time": 240.8755328389816 + }, + { + "step": 1250, + "valid accuracy": 0.34, + "train loss": 0.7546750259399414, + "train samples": 5000, + "train time": 38.47422462084796, + "eval time": 10.539507273002528, + "tokens / sec": 5420.200200395978, + "mem allocated avg": 6794672488.448, + "mem reserved avg": 14357513633.792, + "elapsed time": 293.10720169899287 + }, + { + "step": 1500, + "valid accuracy": 0.34, + "train loss": 0.7437419641017914, + "train samples": 6000, + "train time": 38.40448851091787, + "eval time": 13.719243174011353, + "tokens / sec": 5450.691002966751, + "mem allocated avg": 6796510103.552, + "mem reserved avg": 14279759626.24, + "elapsed time": 348.5309307149728 + }, + { + "step": 1750, + "valid accuracy": 0.4, + "train loss": 0.7351079850196839, + "train samples": 7000, + "train time": 38.52799471229082, + "eval time": 13.719382153009064, + "tokens / sec": 5433.8410696784495, + "mem allocated avg": 6797950621.696, + "mem reserved avg": 14646685728.768, + "elapsed time": 404.0734379639616 + }, + { + "step": 2000, + "valid accuracy": 0.34, + "train loss": 0.7361109793186188, + "train samples": 8000, + "train time": 38.6812528463779, + "eval time": 13.746708846010733, + "tokens / sec": 5369.422775029082, + "mem allocated avg": 6793576230.912, + "mem reserved avg": 14290614484.992, + "elapsed time": 459.8579424939817 + }, + { + "step": 2250, + "valid accuracy": 0.42, + "train loss": 0.7294788275957107, + "train samples": 9000, + "train time": 38.70111024065409, + "eval time": 9.169133496005088, + "tokens / sec": 5554.052549484873, + "mem allocated avg": 6804150888.448, + "mem reserved avg": 14586505854.976, + "elapsed time": 510.9330796489958 + }, + { + "step": 2500, + "valid accuracy": 0.42, + "train loss": 0.7272682936191559, + "train samples": 10000, + "train time": 38.18993485230021, + "eval time": 13.75650224700803, + "tokens / sec": 5393.22732014544, + "mem allocated avg": 6791362646.016, + "mem reserved avg": 14089313058.816, + "elapsed time": 566.1566062810016 + }, + { + "step": 2750, + "valid accuracy": 0.34, + "train loss": 0.7220834786891938, + "train samples": 11000, + "train time": 38.772894190915395, + "eval time": 13.813729731016792, + "tokens / sec": 5464.668150814606, + "mem allocated avg": 6800614600.704, + "mem reserved avg": 14463805685.76, + "elapsed time": 621.9531869380153 + }, + { + "step": 3000, + "valid accuracy": 0.32, + "train loss": 0.7162344917058945, + "train samples": 12000, + "train time": 38.64312012627488, + "eval time": 13.718790433020331, + "tokens / sec": 5401.504829784076, + "mem allocated avg": 6796550658.048, + "mem reserved avg": 14397560848.384, + "elapsed time": 677.6688264649711 + }, + { + "step": 3250, + "valid accuracy": 0.3, + "train loss": 0.7240759524106979, + "train samples": 13000, + "train time": 38.53601192642236, + "eval time": 8.802515299990773, + "tokens / sec": 5472.828906184632, + "mem allocated avg": 6799288741.888, + "mem reserved avg": 14244904960.0, + "elapsed time": 728.1590657840134 + }, + { + "step": 3500, + "valid accuracy": 0.34, + "train loss": 0.7126485753059387, + "train samples": 14000, + "train time": 38.67533435986843, + "eval time": 10.104931714013219, + "tokens / sec": 5423.353242361304, + "mem allocated avg": 6796233105.408, + "mem reserved avg": 14249518694.4, + "elapsed time": 780.2666325760074 + }, + { + "step": 3750, + "valid accuracy": 0.34, + "train loss": 0.7088012579679489, + "train samples": 15000, + "train time": 39.28342586872168, + "eval time": 13.906550085986964, + "tokens / sec": 5516.397697191264, + "mem allocated avg": 6807167205.376, + "mem reserved avg": 14590800822.272, + "elapsed time": 836.7359555650037 + }, + { + "step": 4000, + "valid accuracy": 0.38, + "train loss": 0.7263217406272888, + "train samples": 16000, + "train time": 38.43631436518626, + "eval time": 13.765814298996702, + "tokens / sec": 5317.185150954824, + "mem allocated avg": 6788341315.584, + "mem reserved avg": 14278853656.576, + "elapsed time": 892.29195685999 + }, + { + "step": 4250, + "valid accuracy": 0.34, + "train loss": 0.7048129771947861, + "train samples": 17000, + "train time": 38.582715313415974, + "eval time": 10.130817791970912, + "tokens / sec": 5478.85233796637, + "mem allocated avg": 6800143554.56, + "mem reserved avg": 14243218849.792, + "elapsed time": 944.1107314319815 + }, + { + "step": 4500, + "valid accuracy": 0.28, + "train loss": 0.7155517739057541, + "train samples": 18000, + "train time": 38.19235976098571, + "eval time": 9.205565118987579, + "tokens / sec": 5441.3500841676305, + "mem allocated avg": 6793989150.72, + "mem reserved avg": 14201930121.216, + "elapsed time": 994.8280632529641 + }, + { + "step": 4750, + "valid accuracy": 0.4, + "train loss": 0.7085129739046097, + "train samples": 19000, + "train time": 38.29387024784228, + "eval time": 13.80606703099329, + "tokens / sec": 5482.313452290169, + "mem allocated avg": 6796964847.616, + "mem reserved avg": 14314161307.648, + "elapsed time": 1050.1360529760132 + }, + { + "step": 5000, + "valid accuracy": 0.38, + "train loss": 0.714538745880127, + "train samples": 20000, + "train time": 38.23504033399513, + "eval time": 13.824080880964175, + "tokens / sec": 5447.359233326512, + "mem allocated avg": 6793035892.736, + "mem reserved avg": 13966579335.168, + "elapsed time": 1105.3972024219693 + }, + { + "step": 5000, + "test accuracy": 0.354814253222138, + "train loss": 0.714538745880127, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": -0.010824203491210938 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/vera--llama-3.2-3B-default.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/vera--llama-3.2-3B-default.json new file mode 100644 index 0000000000000000000000000000000000000000..8af5ac5a5e4619aa8063594db0173d42028fbe0c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/vera--llama-3.2-3B-default.json @@ -0,0 +1,355 @@ +{ + "run_info": { + "created_at": "2026-01-10T10:27:51+00:00", + "total_time": 1263.101585368975, + "experiment_name": "vera/llama-3.2-3B-default", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.001 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": null, + "peft_type": "VERA", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "r": 256, + "target_modules": [ + "q_proj", + "v_proj" + ], + "projection_prng_key": 0, + "save_projection": true, + "vera_dropout": 0.0, + "d_initial": 0.1, + "fan_in_fan_out": false, + "bias": "none", + "modules_to_save": null, + "init_weights": true, + "layers_to_transform": null, + "layers_pattern": null + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 13999608640, + "accelerator_memory_max": 21617442816, + "accelerator_memory_reserved_99th": 19627245568, + "train_time": 1015.8542694449425, + "file_size": 6821968, + "num_trainable_params": 129024, + "num_total_params": 3212878848, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.0, + "train loss": 1.301754014492035, + "train samples": 1000, + "train time": 31.943585795292165, + "eval time": 12.187114808009937, + "tokens / sec": 6627.903371800015, + "mem allocated avg": 6789185892.352, + "mem reserved avg": 14110276190.208, + "elapsed time": 66.61339723097626 + }, + { + "step": 500, + "valid accuracy": 0.28, + "train loss": 1.0202444262504577, + "train samples": 2000, + "train time": 31.78171904978808, + "eval time": 12.214804693008773, + "tokens / sec": 6544.48551615986, + "mem allocated avg": 6782031269.888, + "mem reserved avg": 13716204552.192, + "elapsed time": 113.8828261839808 + }, + { + "step": 750, + "valid accuracy": 0.32, + "train loss": 0.8039965138435364, + "train samples": 3000, + "train time": 31.674388502840884, + "eval time": 12.142891115974635, + "tokens / sec": 6768.90731389401, + "mem allocated avg": 6791776645.12, + "mem reserved avg": 13949500129.28, + "elapsed time": 160.88182786101243 + }, + { + "step": 1000, + "valid accuracy": 0.32, + "train loss": 0.7543835270404816, + "train samples": 4000, + "train time": 31.252004174282774, + "eval time": 12.184918653976638, + "tokens / sec": 6666.324464766307, + "mem allocated avg": 6783568500.736, + "mem reserved avg": 14006072901.632, + "elapsed time": 207.57197764096782 + }, + { + "step": 1250, + "valid accuracy": 0.42, + "train loss": 0.7379774446487427, + "train samples": 5000, + "train time": 31.04683574225055, + "eval time": 12.13903358601965, + "tokens / sec": 6716.884185276503, + "mem allocated avg": 6783591102.464, + "mem reserved avg": 14041858703.36, + "elapsed time": 253.9649221689906 + }, + { + "step": 1500, + "valid accuracy": 0.42, + "train loss": 0.725366308093071, + "train samples": 6000, + "train time": 31.466947606997564, + "eval time": 12.193409828003496, + "tokens / sec": 6652.408826379123, + "mem allocated avg": 6785737506.816, + "mem reserved avg": 13954449408.0, + "elapsed time": 300.88531206996413 + }, + { + "step": 1750, + "valid accuracy": 0.38, + "train loss": 0.7149190576076507, + "train samples": 7000, + "train time": 32.161987620871514, + "eval time": 12.206813755037729, + "tokens / sec": 6509.392468770777, + "mem allocated avg": 6786781550.592, + "mem reserved avg": 14342623854.592, + "elapsed time": 348.52885854797205 + }, + { + "step": 2000, + "valid accuracy": 0.42, + "train loss": 0.7139762370586396, + "train samples": 8000, + "train time": 31.66324118396733, + "eval time": 12.41653193399543, + "tokens / sec": 6559.530617641469, + "mem allocated avg": 6782663055.36, + "mem reserved avg": 13990637862.912, + "elapsed time": 395.93328011297854 + }, + { + "step": 2250, + "valid accuracy": 0.38, + "train loss": 0.7068367917537689, + "train samples": 9000, + "train time": 32.87184925627662, + "eval time": 12.149466416973155, + "tokens / sec": 6538.968900843246, + "mem allocated avg": 6793174691.84, + "mem reserved avg": 14273040351.232, + "elapsed time": 444.18720530200517 + }, + { + "step": 2500, + "valid accuracy": 0.4, + "train loss": 0.7048668594360351, + "train samples": 10000, + "train time": 31.740153488412034, + "eval time": 12.253064631018788, + "tokens / sec": 6489.162066440422, + "mem allocated avg": 6780151590.912, + "mem reserved avg": 13770160078.848, + "elapsed time": 491.48139633599203 + }, + { + "step": 2750, + "valid accuracy": 0.36, + "train loss": 0.6994699697494506, + "train samples": 11000, + "train time": 31.831262842926662, + "eval time": 12.147469694027677, + "tokens / sec": 6656.380585512423, + "mem allocated avg": 6789358209.024, + "mem reserved avg": 14143369248.768, + "elapsed time": 538.6766653700033 + }, + { + "step": 3000, + "valid accuracy": 0.38, + "train loss": 0.6912990446090699, + "train samples": 12000, + "train time": 31.59112943575019, + "eval time": 12.194770312984474, + "tokens / sec": 6607.266144900441, + "mem allocated avg": 6785734909.952, + "mem reserved avg": 14090034479.104, + "elapsed time": 585.7846582700149 + }, + { + "step": 3250, + "valid accuracy": 0.42, + "train loss": 0.7005903688669205, + "train samples": 13000, + "train time": 32.01279983797576, + "eval time": 12.153572589973919, + "tokens / sec": 6588.021074926875, + "mem allocated avg": 6787881736.192, + "mem reserved avg": 13914804846.592, + "elapsed time": 633.0662019159645 + }, + { + "step": 3500, + "valid accuracy": 0.4, + "train loss": 0.6888112008571625, + "train samples": 14000, + "train time": 31.394535964296665, + "eval time": 12.198143090994563, + "tokens / sec": 6681.098909649039, + "mem allocated avg": 6784882763.776, + "mem reserved avg": 13954659123.2, + "elapsed time": 680.0055505509954 + }, + { + "step": 3750, + "valid accuracy": 0.36, + "train loss": 0.6853219895362854, + "train samples": 15000, + "train time": 32.20891197276069, + "eval time": 12.149777695012745, + "tokens / sec": 6728.044715800003, + "mem allocated avg": 6795943520.256, + "mem reserved avg": 14263871602.688, + "elapsed time": 727.6112716209609 + }, + { + "step": 4000, + "valid accuracy": 0.38, + "train loss": 0.7033915517330169, + "train samples": 16000, + "train time": 31.605115150858182, + "eval time": 12.220193530025426, + "tokens / sec": 6466.453263165871, + "mem allocated avg": 6777292670.976, + "mem reserved avg": 13970463260.672, + "elapsed time": 774.7509838030091 + }, + { + "step": 4250, + "valid accuracy": 0.34, + "train loss": 0.6845373644828796, + "train samples": 17000, + "train time": 31.9817577842623, + "eval time": 12.144686578016263, + "tokens / sec": 6609.6742219722855, + "mem allocated avg": 6788761931.776, + "mem reserved avg": 13960019443.712, + "elapsed time": 821.9710977289942 + }, + { + "step": 4500, + "valid accuracy": 0.4, + "train loss": 0.6940178046226502, + "train samples": 18000, + "train time": 31.950214379117824, + "eval time": 12.20877941895742, + "tokens / sec": 6504.4320997053055, + "mem allocated avg": 6783152502.784, + "mem reserved avg": 13920844644.352, + "elapsed time": 869.4368790709996 + }, + { + "step": 4750, + "valid accuracy": 0.36, + "train loss": 0.6864041843414307, + "train samples": 19000, + "train time": 31.99477967567509, + "eval time": 12.149096956010908, + "tokens / sec": 6561.664187974136, + "mem allocated avg": 6785828032.512, + "mem reserved avg": 13979548123.136, + "elapsed time": 916.7890869269613 + }, + { + "step": 5000, + "valid accuracy": 0.38, + "train loss": 0.6927255519628525, + "train samples": 20000, + "train time": 30.892451956111472, + "eval time": 12.215222013997845, + "tokens / sec": 6742.099989210984, + "mem allocated avg": 6782438621.184, + "mem reserved avg": 13639734001.664, + "elapsed time": 963.0640164369834 + }, + { + "step": 5000, + "test accuracy": 0.37604245640636846, + "train loss": 0.6927255519628525, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": 0.1016998291015625 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/waveft--llama-3.2-3B-n_frequency-5000.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/waveft--llama-3.2-3B-n_frequency-5000.json new file mode 100644 index 0000000000000000000000000000000000000000..28066dd76988354ac6b4adc6f587de10042d8e01 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/results/waveft--llama-3.2-3B-n_frequency-5000.json @@ -0,0 +1,359 @@ +{ + "run_info": { + "created_at": "2026-01-10T10:48:59+00:00", + "total_time": 2531.969072496984, + "experiment_name": "waveft/llama-3.2-3B-n_frequency-5000", + "peft_branch": "main", + "train_config": { + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "bfloat16", + "max_seq_length": 768, + "batch_size": 4, + "batch_size_eval": 50, + "max_steps": 5000, + "eval_steps": 250, + "compile": false, + "query_template": "Question: {query} Think step by step.\nAnswer:", + "seed": 0, + "grad_norm_clip": 1.0, + "optimizer_type": "AdamW", + "optimizer_kwargs": { + "lr": 0.0001, + "weight_decay": 0.1 + }, + "lr_scheduler": "cosine", + "use_amp": false, + "autocast_adapter_dtype": true, + "generation_kwargs": { + "max_length": 800, + "max_new_tokens": 300 + }, + "attn_implementation": null + }, + "peft_config": { + "task_type": "CAUSAL_LM", + "peft_type": "WAVEFT", + "auto_mapping": null, + "peft_version": "0.18.1.dev0@UNKNOWN", + "base_model_name_or_path": "meta-llama/Llama-3.2-3B", + "revision": null, + "inference_mode": false, + "n_frequency": 5000, + "scaling": 25.0, + "wavelet_family": "db1", + "use_idwt": true, + "random_loc_seed": 777, + "fan_in_fan_out": false, + "target_modules": [ + "q_proj", + "v_proj" + ], + "exclude_modules": null, + "bias": "none", + "modules_to_save": null, + "layers_to_transform": null, + "layers_pattern": null, + "n_frequency_pattern": {}, + "proportional_parameters": false, + "init_weights": true + }, + "error_msg": "" + }, + "train_info": { + "accelerator_memory_reserved_avg": 17216480005, + "accelerator_memory_max": 24895291392, + "accelerator_memory_reserved_99th": 23207084032, + "train_time": 2067.484345029923, + "file_size": 1127304, + "num_trainable_params": 280000, + "num_total_params": 3213029824, + "status": "success", + "metrics": [ + { + "step": 250, + "valid accuracy": 0.34, + "train loss": 1.0574276540279388, + "train samples": 1000, + "train time": 64.88644388166722, + "eval time": 29.24885773198912, + "tokens / sec": 3262.915754577488, + "mem allocated avg": 6785503729.664, + "mem reserved avg": 17346156560.384, + "elapsed time": 119.97641712299082 + }, + { + "step": 500, + "valid accuracy": 0.36, + "train loss": 0.7510680348873139, + "train samples": 2000, + "train time": 64.65898592909798, + "eval time": 29.2429800920072, + "tokens / sec": 3216.79959886902, + "mem allocated avg": 6777740601.344, + "mem reserved avg": 16956279226.368, + "elapsed time": 217.2935731979669 + }, + { + "step": 750, + "valid accuracy": 0.36, + "train loss": 0.696870755314827, + "train samples": 3000, + "train time": 65.85057329281699, + "eval time": 22.638891860027798, + "tokens / sec": 3255.87142645859, + "mem allocated avg": 6787450871.808, + "mem reserved avg": 17161649127.424, + "elapsed time": 309.1054733619676 + }, + { + "step": 1000, + "valid accuracy": 0.38, + "train loss": 0.6762536237239838, + "train samples": 4000, + "train time": 64.82745491992682, + "eval time": 26.79089952702634, + "tokens / sec": 3213.700125314671, + "mem allocated avg": 6780707246.08, + "mem reserved avg": 17234697125.888, + "elapsed time": 404.1986583190155 + }, + { + "step": 1250, + "valid accuracy": 0.42, + "train loss": 0.6723555997610092, + "train samples": 5000, + "train time": 64.86200350278523, + "eval time": 29.28087447199505, + "tokens / sec": 3215.102660081186, + "mem allocated avg": 6779905163.264, + "mem reserved avg": 17208071684.096, + "elapsed time": 501.6932976419921 + }, + { + "step": 1500, + "valid accuracy": 0.44, + "train loss": 0.668335919380188, + "train samples": 6000, + "train time": 65.25852178613422, + "eval time": 29.221144348965026, + "tokens / sec": 3207.718996241155, + "mem allocated avg": 6780988528.64, + "mem reserved avg": 17179751743.488, + "elapsed time": 599.6254665869637 + }, + { + "step": 1750, + "valid accuracy": 0.52, + "train loss": 0.6587805707454681, + "train samples": 7000, + "train time": 65.32939753873507, + "eval time": 20.71052837802563, + "tokens / sec": 3204.606316411679, + "mem allocated avg": 6782190442.496, + "mem reserved avg": 17551023144.96, + "elapsed time": 689.0983284820104 + }, + { + "step": 2000, + "valid accuracy": 0.34, + "train loss": 0.6639124175310135, + "train samples": 8000, + "train time": 64.99063060310436, + "eval time": 19.205011637997814, + "tokens / sec": 3195.783731787319, + "mem allocated avg": 6778450325.504, + "mem reserved avg": 17222315540.48, + "elapsed time": 776.8548289329628 + }, + { + "step": 2250, + "valid accuracy": 0.42, + "train loss": 0.6567040872573853, + "train samples": 9000, + "train time": 65.94732432649471, + "eval time": 18.143796648015268, + "tokens / sec": 3259.389250363315, + "mem allocated avg": 6790019246.08, + "mem reserved avg": 17537441988.608, + "elapsed time": 864.3628261939739 + }, + { + "step": 2500, + "valid accuracy": 0.5, + "train loss": 0.6553765784502029, + "train samples": 10000, + "train time": 64.10474358743522, + "eval time": 26.53317212499678, + "tokens / sec": 3212.975958933097, + "mem allocated avg": 6775553220.608, + "mem reserved avg": 16962285469.696, + "elapsed time": 958.4253370200167 + }, + { + "step": 2750, + "valid accuracy": 0.4, + "train loss": 0.6487860177755356, + "train samples": 11000, + "train time": 65.63589023012901, + "eval time": 21.08229285199195, + "tokens / sec": 3228.1271611783477, + "mem allocated avg": 6786175535.104, + "mem reserved avg": 17393409589.248, + "elapsed time": 1048.5621143350145 + }, + { + "step": 3000, + "valid accuracy": 0.42, + "train loss": 0.6410797102451324, + "train samples": 12000, + "train time": 64.99408569413936, + "eval time": 29.25125474098604, + "tokens / sec": 3211.5383695415485, + "mem allocated avg": 6781518624.768, + "mem reserved avg": 17271095296.0, + "elapsed time": 1146.3423907670076 + }, + { + "step": 3250, + "valid accuracy": 0.4, + "train loss": 0.6509387036561965, + "train samples": 13000, + "train time": 65.00038516824134, + "eval time": 18.81445889500901, + "tokens / sec": 3244.611542748896, + "mem allocated avg": 6782426165.248, + "mem reserved avg": 17123514515.456, + "elapsed time": 1233.4203302449896 + }, + { + "step": 3500, + "valid accuracy": 0.44, + "train loss": 0.6376135617494583, + "train samples": 14000, + "train time": 64.8011383570265, + "eval time": 18.342268240987323, + "tokens / sec": 3236.8258539590365, + "mem allocated avg": 6781259872.256, + "mem reserved avg": 17207123771.392, + "elapsed time": 1320.0369267839706 + }, + { + "step": 3750, + "valid accuracy": 0.4, + "train loss": 0.635018677353859, + "train samples": 15000, + "train time": 66.17575967306038, + "eval time": 19.382110312988516, + "tokens / sec": 3274.6582898423158, + "mem allocated avg": 6792251662.336, + "mem reserved avg": 17455057469.44, + "elapsed time": 1409.0309616610175 + }, + { + "step": 4000, + "valid accuracy": 0.42, + "train loss": 0.6503389171361923, + "train samples": 16000, + "train time": 64.66550021909643, + "eval time": 17.806172358978074, + "tokens / sec": 3160.464224471373, + "mem allocated avg": 6773483292.672, + "mem reserved avg": 17174861185.024, + "elapsed time": 1494.9754901370034 + }, + { + "step": 4250, + "valid accuracy": 0.4, + "train loss": 0.6333471950292587, + "train samples": 17000, + "train time": 64.98916661646217, + "eval time": 20.801376049988903, + "tokens / sec": 3252.680577480337, + "mem allocated avg": 6783976222.72, + "mem reserved avg": 17191504183.296, + "elapsed time": 1583.9985767480102 + }, + { + "step": 4500, + "valid accuracy": 0.46, + "train loss": 0.6411651639938355, + "train samples": 18000, + "train time": 64.85606565064518, + "eval time": 20.16082675504731, + "tokens / sec": 3204.295510607074, + "mem allocated avg": 6779666743.296, + "mem reserved avg": 17107123175.424, + "elapsed time": 1672.4678985319915 + }, + { + "step": 4750, + "valid accuracy": 0.42, + "train loss": 0.6345895240306855, + "train samples": 19000, + "train time": 65.05685202759923, + "eval time": 18.8133876810316, + "tokens / sec": 3227.0082774822404, + "mem allocated avg": 6781692170.24, + "mem reserved avg": 17216258965.504, + "elapsed time": 1759.7040043339948 + }, + { + "step": 5000, + "valid accuracy": 0.44, + "train loss": 0.63977869784832, + "train samples": 20000, + "train time": 64.65817459212849, + "eval time": 19.78138606599532, + "tokens / sec": 3221.24775890837, + "mem allocated avg": 6778381412.352, + "mem reserved avg": 16829980344.32, + "elapsed time": 1847.474526909995 + }, + { + "step": 5000, + "test accuracy": 0.4200151630022744, + "train loss": 0.63977869784832, + "train samples": 20000, + "train total tokens": 4198051, + "forgetting": -0.13996505737304688 + } + ] + }, + "meta_info": { + "model_info": { + "sha": "13afe5124825b4f3751f836b40dafda64c1ed062", + "created_at": "2024-09-18T15:23:48+00:00" + }, + "dataset_info": { + "metamath": { + "sha": "aa4f34d3d2d3231299b5b03d9b3e5a20da45aa18", + "created_at": "2023-09-21T17:22:46+00:00" + }, + "gsm8k": { + "sha": "cc7b047b6e5bb11b4f1af84efc572db110a51b3c", + "created_at": "2022-04-12T10:22:10+00:00" + } + }, + "package_info": { + "transformers-version": "4.57.1", + "transformers-commit-hash": null, + "peft-version": "0.18.1.dev0", + "peft-commit-hash": "8be1a16f5e06ca5e197d2af74bdfc5b3c8072d26", + "datasets-version": "4.2.0", + "datasets-commit-hash": null, + "bitsandbytes-version": "0.46.0", + "bitsandbytes-commit-hash": null, + "torch-version": "2.9.0+cu128", + "torch-commit-hash": null + }, + "system_info": { + "system": "Linux", + "release": "6.14.0-1016-aws", + "version": "#16~24.04.1-Ubuntu SMP Tue Oct 14 02:15:09 UTC 2025", + "machine": "x86_64", + "processor": "x86_64", + "accelerator": "NVIDIA L40S" + }, + "pytorch_info": "PyTorch built with:\n - GCC 13.3\n - C++ Version: 201703\n - Intel(R) oneAPI Math Kernel Library Version 2024.2-Product Build 20240605 for Intel(R) 64 architecture applications\n - Intel(R) MKL-DNN v3.7.1 (Git Hash 8d263e693366ef8db40acc569cc7d8edf644556d)\n - OpenMP 201511 (a.k.a. OpenMP 4.5)\n - LAPACK is enabled (usually provided by MKL)\n - NNPACK is enabled\n - CPU capability usage: AVX2\n - CUDA Runtime 12.8\n - NVCC architecture flags: -gencode;arch=compute_70,code=sm_70;-gencode;arch=compute_75,code=sm_75;-gencode;arch=compute_80,code=sm_80;-gencode;arch=compute_86,code=sm_86;-gencode;arch=compute_90,code=sm_90;-gencode;arch=compute_100,code=sm_100;-gencode;arch=compute_120,code=sm_120\n - CuDNN 90.7.1\n - Built with CuDNN 90.8\n - Magma 2.6.1\n - Build settings: BLAS_INFO=mkl, BUILD_TYPE=Release, COMMIT_SHA=0fabc3ba44823f257e70ce397d989c8de5e362c1, CUDA_VERSION=12.8, CUDNN_VERSION=9.8.0, CXX_COMPILER=/opt/rh/gcc-toolset-13/root/usr/bin/c++, CXX_FLAGS= -fvisibility-inlines-hidden -DUSE_PTHREADPOOL -DNDEBUG -DUSE_KINETO -DLIBKINETO_NOROCTRACER -DLIBKINETO_NOXPUPTI=ON -DUSE_FBGEMM -DUSE_PYTORCH_QNNPACK -DUSE_XNNPACK -DSYMBOLICATE_MOBILE_DEBUG_HANDLE -O2 -fPIC -DC10_NODEPRECATED -Wall -Wextra -Werror=return-type -Werror=non-virtual-dtor -Werror=range-loop-construct -Werror=bool-operation -Wnarrowing -Wno-missing-field-initializers -Wno-unknown-pragmas -Wno-unused-parameter -Wno-strict-overflow -Wno-strict-aliasing -Wno-stringop-overflow -Wsuggest-override -Wno-psabi -Wno-error=old-style-cast -faligned-new -Wno-maybe-uninitialized -fno-math-errno -fno-trapping-math -Werror=format -Wno-dangling-reference -Wno-error=dangling-reference -Wno-stringop-overflow, LAPACK_INFO=mkl, PERF_WITH_AVX=1, PERF_WITH_AVX2=1, TORCH_VERSION=2.9.0, USE_CUDA=ON, USE_CUDNN=ON, USE_CUSPARSELT=1, USE_GFLAGS=OFF, USE_GLOG=OFF, USE_GLOO=ON, USE_MKL=ON, USE_MKLDNN=ON, USE_MPI=OFF, USE_NCCL=1, USE_NNPACK=ON, USE_OPENMP=ON, USE_ROCM=OFF, USE_ROCM_KERNEL_ASSERT=OFF, USE_XCCL=OFF, USE_XPU=OFF, \n" + } +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/run.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/run.py new file mode 100644 index 0000000000000000000000000000000000000000..806ec0d69382082e81d54df4957252e0e3c1b8aa --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/run.py @@ -0,0 +1,513 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Main entry point to run the experiments. Contains general setup and the proper training code. +""" + +import argparse +import datetime as dt +import json +import os +import random +import sys +import textwrap +import time +from collections.abc import Callable +from contextlib import AbstractContextManager, nullcontext +from functools import partial +from typing import Any, Literal, Optional + +import torch +from torch import nn +from torch.amp import GradScaler, autocast +from tqdm import tqdm +from transformers import GenerationConfig, set_seed +from utils import ( + FILE_NAME_TRAIN_PARAMS, + BucketIterator, + TrainResult, + TrainStatus, + get_accuracy, + get_base_model_info, + get_dataset_info, + get_file_size, + get_model, + get_optimizer_and_scheduler, + get_peft_branch, + get_tokenizer, + get_train_config, + init_accelerator, + log_results, + validate_experiment_path, +) + +from data import get_train_valid_test_datasets, get_wiki_small +from peft import AdaLoraConfig, PeftConfig +from peft.utils import CONFIG_NAME, infer_device + + +# number of batches per bucket, increasing this further has diminishing returns +BUCKET_FACTOR = 20 +# empty device cache every N steps; 10 is a good compromise between keeping memory down while lowering runtime overhead +ACCELERATOR_EMPTY_CACHE_SCHEDULE = 10 + +# disable torch inductor caching to keep total runtime numbers comparable when torch.compile is used +os.environ["TORCHINDUCTOR_FORCE_DISABLE_CACHES"] = "1" + + +def get_generation_config(*, seq_len, generate_kwargs) -> GenerationConfig: + # filter out None values so that we don't depend on setting correct defaults in the config + generate_kwargs = {k: v for k, v in generate_kwargs.items() if v is not None} + if ("max_length" in generate_kwargs) and ("max_new_tokens" in generate_kwargs): + # transformers does not support setting both max_length and max_new_tokens, but what we want in this case is to + # take the smaller of the two values + new_max_length = min(generate_kwargs["max_new_tokens"] + seq_len, generate_kwargs["max_length"]) + del generate_kwargs["max_new_tokens"] + generate_kwargs["max_length"] = new_max_length + generation_config = GenerationConfig(**generate_kwargs) + return generation_config + + +def evaluate(model, tokenizer, ds, batch_size, generate_kwargs, use_tqdm: bool = False) -> tuple[list[str], list[str]]: + generate_kwargs = generate_kwargs.copy() + generate_kwargs["pad_token_id"] = tokenizer.eos_token_id + with torch.inference_mode(): + predictions = [] + responses = [] + pbar = range(0, len(ds), batch_size) + if use_tqdm: + pbar = tqdm(pbar) + for j in pbar: + sliced = ds[j : j + batch_size] + responses += sliced.pop("response") + batch = tokenizer.pad(sliced, return_tensors="pt", padding_side="left").to(model.device) + seq_len = batch["input_ids"].shape[1] + generation_config = get_generation_config(seq_len=seq_len, generate_kwargs=generate_kwargs) + outputs = model.generate(**batch, generation_config=generation_config) + predictions += tokenizer.batch_decode(outputs, skip_special_tokens=True) + return predictions, responses + + +@torch.inference_mode # type: ignore +def calculate_mean_per_token_loss(model, tokenizer, rows: list[str], batch_size: int, max_length: int) -> float: + """Calculate the mean loss per token on the given dataset. + + Useful to determine general model performance before and after training to get an estimate of the magnitude of + 'forgetting'. Note that for Wikipedia data, since the information density is quite high, the loss can be + surprisingly large. + + """ + losses: list[float] = [] + for j in range(0, len(rows), batch_size): + sliced = rows[j : j + batch_size] + batch = tokenizer(sliced, truncation=True, max_length=max_length) + batch = tokenizer.pad(batch, return_tensors="pt", padding_side="left").to(model.device) + outputs = model(**batch, pad_token_id=tokenizer.eos_token_id) + logits = outputs.logits + for logit, target, mask in zip(logits, batch["input_ids"], batch["attention_mask"]): + # calculate loss per token so that the mean is not skewed by sequence length of sample, padding from left + num_tokens = mask.sum() + token_losses = torch.nn.functional.cross_entropy(logit[-num_tokens:], target[-num_tokens:], reduction="none") + losses.extend(loss.item() for loss in token_losses) + return torch.tensor(losses).mean().item() + + +class DummyGradScaler: + # if no mixed precision is being used + def scale(self, loss): + return loss + + def unscale_(self, optimizer): + pass + + def step(self, optimizer): + optimizer.step() + + def update(self): + pass + + +def train( + *, + model: nn.Module, + max_steps: int, + batch_size: int, + batch_size_eval: int, + tokenizer: Any, + accelerator_memory_init: int, + eval_steps: int, + generation_kwargs: dict[str, Any], + grad_norm_clip: float, + optimizer_type: str, + optimizer_kwargs: dict[str, Any], + query_template: str, + lr_scheduler_arg: Optional[Literal["cosine"]], + use_amp: bool, + is_adalora: bool, +) -> TrainResult: + accelerator_memory_allocated_log = [] + accelerator_memory_reserved_log = [] + losses = [] + durations = [] + metrics = [] + sample = 0 # keep count of the current sample + total_samples = 0 # total number of samples over all epochs + total_tokens = [] # total number of tokens over all epochs + + device_type = infer_device() + torch_accelerator_module = getattr(torch, device_type, torch.cuda) + if use_amp: + grad_scaler: GradScaler | DummyGradScaler = GradScaler(device=device_type) + autocast_ctx: Callable[[], AbstractContextManager[Any]] = partial(autocast, device_type=device_type) + else: + grad_scaler = DummyGradScaler() + autocast_ctx = nullcontext + + optimizer, lr_scheduler = get_optimizer_and_scheduler( + model, + optimizer_type=optimizer_type, + max_steps=max_steps, + lr_scheduler_arg=lr_scheduler_arg, + **optimizer_kwargs, + ) + # print this after getting the optimizer, in case it modifies requires_gard + if hasattr(model, "get_nb_trainable_parameters"): + num_trainable_params, num_params = model.get_nb_trainable_parameters() + else: + num_params = model.num_parameters() + num_trainable_params = num_params + print_verbose( + f"trainable params: {num_trainable_params:,d} || all params: {num_params:,d} || " + f"trainable: {100 * num_trainable_params / num_params:.4f}%" + ) + + status = TrainStatus.FAILED + tic_train = time.perf_counter() + eval_time = 0.0 + error_msg = "" + + rows_wiki = get_wiki_small() + model.eval() + # use small batch_size, not batch_size_eval, to prevent this from taking too much memory and affecting the max memory metric + wiki_loss_before = calculate_mean_per_token_loss( + model=model, tokenizer=tokenizer, rows=rows_wiki, batch_size=batch_size, max_length=768 + ) + model.train() + + ds_train, ds_valid, ds_test = get_train_valid_test_datasets( + tokenizer=tokenizer, query_template=query_template, print_fn=print_verbose + ) + # note: bucketing by length is only really worth it for the train dataset, since it's length is big compared to the + # batch size + iterator_train = BucketIterator( + ds_train, + batch_size=batch_size, + bucket_factor=BUCKET_FACTOR, + delete_cols=["response"], + ) + try: + pbar = tqdm(range(1, max_steps + 1)) + for step, batch in zip(pbar, iterator_train): + tic = time.perf_counter() + + # create the batch + tokens_per_sample = [len(i) for i in batch["input_ids"]] + total_tokens.append(sum(tokens_per_sample) + len(tokens_per_sample)) # add EOS token + batch = tokenizer.pad(batch, return_tensors="pt").to(model.device) + actual_batch_size = len(batch["input_ids"]) + total_samples += actual_batch_size + sample += batch_size + if sample >= len(ds_train): # new epoch + sample = 0 + + # add labels, they are automatically shifted by transformers + labels = batch["input_ids"].clone() + # We want to ignore the padding tokens except for the first EOS token; if we don't ignore them, the loss + # will be dominated by padding tokens; if we ignore all, the model will not learn to predict the EOS token. + # TODO: Note that the longest sequence in the batch won't have any PAD/EOS token at the end, this is fine if + # the batch size is > 1 but should still be fixed eventually. + for i, num_tokens in enumerate(tokens_per_sample): + labels[i, num_tokens + 1 :] = -100 + batch["labels"] = labels + num_items_in_batch = batch["attention_mask"].sum().item() + + # train step + optimizer.zero_grad() + with autocast_ctx(): + outputs = model(**batch, num_items_in_batch=num_items_in_batch) + loss = outputs.loss + grad_scaler.scale(loss).backward() + if grad_norm_clip: + grad_scaler.unscale_(optimizer) + torch.nn.utils.clip_grad_norm_(model.parameters(), grad_norm_clip) + grad_scaler.step(optimizer) + grad_scaler.update() + lr_scheduler.step() + + if is_adalora: + model.base_model.update_and_allocate(step) + + losses.append(loss.item()) + pbar.set_postfix({"loss": loss.item()}) + accelerator_memory_allocated_log.append( + torch_accelerator_module.memory_allocated() - accelerator_memory_init + ) + accelerator_memory_reserved_log.append( + torch_accelerator_module.memory_reserved() - accelerator_memory_init + ) + toc = time.perf_counter() + durations.append(toc - tic) + + # every couple of steps, evaluate; this can be slow due to generation + if step % eval_steps == 0: + tic_eval = time.perf_counter() + loss_avg = sum(losses[-eval_steps:]) / eval_steps + memory_allocated_avg = sum(accelerator_memory_allocated_log[-eval_steps:]) / eval_steps + memory_reserved_avg = sum(accelerator_memory_reserved_log[-eval_steps:]) / eval_steps + token_sum = sum(total_tokens[-eval_steps:]) + dur_train = sum(durations[-eval_steps:]) + tokens_per_sec = token_sum / dur_train + + model.eval() + predictions, responses = evaluate( + model=model, + tokenizer=tokenizer, + ds=ds_valid, + batch_size=batch_size_eval, + generate_kwargs={**generation_kwargs}, + ) + model.train() + + example = random.choice(predictions) + example = textwrap.shorten(example, width=750) + example = textwrap.indent(example, " ") + print_verbose(f"\nExample prediction:\n{example}\n") + accuracy = get_accuracy(predictions=predictions, responses=responses) + num_tokens_generated = sum(sum(mask) for mask in tokenizer(predictions)["attention_mask"]) + + toc_eval = time.perf_counter() + dur_eval = toc_eval - tic_eval + eval_time += toc_eval - tic_eval + elapsed = time.perf_counter() - tic_train + + metrics.append( + { + "step": step, + "valid accuracy": accuracy, + "train loss": loss_avg, + "train samples": total_samples, + "train time": dur_train, + "eval time": dur_eval, + "tokens / sec": tokens_per_sec, + "mem allocated avg": memory_allocated_avg, + "mem reserved avg": memory_reserved_avg, + "elapsed time": elapsed, + } + ) + + log_dict = { + "step": f"{step:5d}", + "samples": f"{total_samples:7d}", + "lr": f"{lr_scheduler.get_last_lr()[0]:.2e}", + "loss avg": f"{loss_avg:.4f}", + "valid acc": f"{accuracy:.3f}", + "gen valid tokens": num_tokens_generated, + "train time": f"{dur_train:.1f}s", + "eval time": f"{dur_eval:.1f}s", + "train tokens / sec": f"{tokens_per_sec:.0f}", + "mem allocated": f"{memory_allocated_avg:.0f}", + "mem reserved": f"{memory_reserved_avg:.0f}", + "elapsed time": f"{elapsed // 60:.0f}min {elapsed % 60:.0f}s", + } + print_verbose(json.dumps(log_dict)) + + if step % ACCELERATOR_EMPTY_CACHE_SCHEDULE == 0: + torch_accelerator_module.empty_cache() + + print_verbose(f"Training finished after {max_steps} steps, evaluation on test set follows.") + # test set evaluation + model.eval() + predictions, responses = evaluate( + model=model, + tokenizer=tokenizer, + ds=ds_test, + batch_size=batch_size_eval, + generate_kwargs={**generation_kwargs, "pad_token_id": tokenizer.eos_token_id}, + use_tqdm=len(ds_test) > 100, + ) + accuracy = get_accuracy(predictions=predictions, responses=responses) + # use small batch_size, not batch_size_eval, to prevent this from taking too much memory and affecting the max memory metric + wiki_loss_after = calculate_mean_per_token_loss( + model=model, tokenizer=tokenizer, rows=rows_wiki, batch_size=batch_size, max_length=768 + ) + forgetting = wiki_loss_after - wiki_loss_before + metrics.append( + { + "step": step, + "test accuracy": accuracy, + "train loss": sum(losses[-eval_steps:]) / eval_steps, + "train samples": total_samples, + "train total tokens": sum(total_tokens), + "forgetting": forgetting, + } + ) + print_verbose(f"Test accuracy: {accuracy:.3f}") + + except KeyboardInterrupt: + print_verbose("canceled training") + status = TrainStatus.CANCELED + error_msg = "manually canceled" + except torch.OutOfMemoryError as exc: + # ouch, still let's try to log some results + print_verbose("out of memory error encountered") + status = TrainStatus.CANCELED + error_msg = str(exc) + except Exception as exc: + print_verbose(f"encountered an error: {exc}") + status = TrainStatus.CANCELED + error_msg = str(exc) + + toc_train = time.perf_counter() + train_time = toc_train - tic_train - eval_time + + if status != TrainStatus.CANCELED: + status = TrainStatus.SUCCESS + train_result = TrainResult( + status=status, + train_time=train_time, + accelerator_memory_reserved_log=accelerator_memory_reserved_log, + losses=losses, + metrics=metrics, + error_msg=error_msg, + num_trainable_params=num_trainable_params, + num_total_params=num_params, + ) + return train_result + + +def main(*, path_experiment: str, experiment_name: str, clean: bool) -> None: + tic_total = time.perf_counter() + start_date = dt.datetime.now(tz=dt.timezone.utc).replace(microsecond=0).isoformat() + + peft_branch = get_peft_branch() + if peft_branch == "main": + print_verbose("===== This experiment is categorized as a MAIN run because the PEFT branch is 'main' ======") + else: + print_verbose( + f"===== This experiment is categorized as a TEST run because the PEFT branch is '{peft_branch}' ======" + ) + + # load configs + peft_config: Optional[PeftConfig] = None + if os.path.exists(os.path.join(path_experiment, CONFIG_NAME)): + peft_config = PeftConfig.from_pretrained(path_experiment) + else: + print_verbose(f"Could not find PEFT config at {path_experiment}, performing FULL FINETUNING") + path_train_config = os.path.join(path_experiment, FILE_NAME_TRAIN_PARAMS) + train_config = get_train_config(path_train_config) + set_seed(train_config.seed) + + # initialize objects + accelerator_memory_init = init_accelerator() + tokenizer = get_tokenizer(model_id=train_config.model_id, max_seq_length=train_config.max_seq_length) + + model_info = get_base_model_info(train_config.model_id) + metamath_info = get_dataset_info("meta-math/MetaMathQA") + gsm8k_info = get_dataset_info("openai/gsm8k") + model = get_model( + model_id=train_config.model_id, + dtype=train_config.dtype, + compile=train_config.compile, + attn_implementation=train_config.attn_implementation, + peft_config=peft_config, + autocast_adapter_dtype=train_config.autocast_adapter_dtype, + ) + print_verbose(model) + + # train model + train_result = train( + model=model, + max_steps=train_config.max_steps, + batch_size=train_config.batch_size, + batch_size_eval=train_config.batch_size_eval, + tokenizer=tokenizer, + accelerator_memory_init=accelerator_memory_init, + eval_steps=train_config.eval_steps, + generation_kwargs=train_config.generation_kwargs, + grad_norm_clip=train_config.grad_norm_clip, + optimizer_type=train_config.optimizer_type, + optimizer_kwargs=train_config.optimizer_kwargs, + query_template=train_config.query_template, + lr_scheduler_arg=train_config.lr_scheduler, + use_amp=train_config.use_amp, + is_adalora=isinstance(peft_config, AdaLoraConfig), + ) + + if train_result.status == TrainStatus.FAILED: + print_verbose("Training failed, not logging results") + sys.exit(1) + + file_size = get_file_size( + model, + peft_config=peft_config, + clean=clean, + print_fn=print_verbose, + ) + + time_total = time.perf_counter() - tic_total + # log results: print and save to file + log_results( + experiment_name=experiment_name, + train_result=train_result, + accelerator_memory_init=accelerator_memory_init, + time_total=time_total, + file_size=file_size, + model_info=model_info, + datasets_info={"metamath": metamath_info, "gsm8k": gsm8k_info}, + start_date=start_date, + train_config=train_config, + peft_config=peft_config, + print_fn=print_verbose, + ) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("-v", "--verbose", action="store_true", help="Enable verbose output") + parser.add_argument("path_experiment", type=str, help="Path to the experiment directory") + parser.add_argument( + "--clean", + action="store_true", + help="Delete training artifacts after run finishes (logs are still saved)", + ) + args = parser.parse_args() + + experiment_name = validate_experiment_path(args.path_experiment) + + if args.verbose: + + def print_verbose(*args, **kwargs) -> None: + kwargs["file"] = sys.stderr + print(*args, **kwargs) + else: + + def print_verbose(*args, **kwargs) -> None: + pass + + main( + path_experiment=args.path_experiment, + experiment_name=experiment_name, + clean=args.clean, + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/temporary_results/.gitkeep b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/temporary_results/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..2b75bdf37c270774c05bb8c1de77a1525dd8d7fa --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/MetaMathQA/utils.py @@ -0,0 +1,710 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +All utilities not related to data handling. +""" + +import enum +import json +import os +import platform +import subprocess +import tempfile +import warnings +from collections.abc import Callable +from dataclasses import asdict, dataclass +from decimal import Decimal, DivisionByZero, InvalidOperation +from typing import Any, Literal, Optional + +import bitsandbytes +import datasets +import huggingface_hub +import numpy as np +import torch +import transformers +from torch import nn +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + BitsAndBytesConfig, + PreTrainedModel, + get_cosine_schedule_with_warmup, +) + +import peft +from peft import PeftConfig, get_peft_model, prepare_model_for_kbit_training +from peft.optimizers import create_lorafa_optimizer, create_loraplus_optimizer +from peft.utils import SAFETENSORS_WEIGHTS_NAME, infer_device + + +device = infer_device() + +if device not in ["cuda", "xpu"]: + raise RuntimeError("CUDA or XPU is not available, currently only CUDA or XPU is supported") + +ACCELERATOR_MEMORY_INIT_THRESHOLD = 500 * 2**20 # 500MB +FILE_NAME_DEFAULT_TRAIN_PARAMS = os.path.join(os.path.dirname(__file__), "default_training_params.json") +FILE_NAME_TRAIN_PARAMS = "training_params.json" # specific params for this experiment +# main results +RESULT_PATH = os.path.join(os.path.dirname(__file__), "results") +# testing results +RESULT_PATH_TEST = os.path.join(os.path.dirname(__file__), "temporary_results") +# cancelled results +RESULT_PATH_CANCELLED = os.path.join(os.path.dirname(__file__), "cancelled_results") +hf_api = huggingface_hub.HfApi() +WARMUP_STEP_RATIO = 0.1 + + +@dataclass +class TrainConfig: + """All configuration parameters associated with training the model + + Args: + model_id: The model identifier + dtype: The data type to use for the model + max_seq_length: The maximum sequence length + batch_size: The batch size for training + batch_size_eval: The batch size for eval/test, can be much higher than for training + max_steps: The maximum number of steps to train for + eval_steps: The number of steps between evaluations + compile: Whether to compile the model + query_template: The template for the query + seed: The random seed + grad_norm_clip: The gradient norm clipping value (set to 0 to skip) + optimizer_type: The name of a torch optimizer (e.g. AdamW) or a PEFT method ("lora+", "lora-fa") + optimizer_kwargs: The optimizer keyword arguments (lr etc.) + lr_scheduler: The learning rate scheduler (currently only None or 'cosine' are supported) + use_amp: Whether to use automatic mixed precision + autocast_adapter_dtype: Whether to cast adapter dtype to float32, same argument as in PEFT + generation_kwargs: Arguments passed to transformers GenerationConfig (used in evaluation) + attn_implementation: The attention implementation to use (if any), see transformers docs + """ + + model_id: str + dtype: Literal["float32", "float16", "bfloat16", "int8", "int4"] + max_seq_length: int + batch_size: int + batch_size_eval: int + max_steps: int + eval_steps: int + compile: bool + query_template: str + seed: int + grad_norm_clip: float # set to 0 to skip + optimizer_type: str + optimizer_kwargs: dict[str, Any] + lr_scheduler: Optional[Literal["cosine"]] + use_amp: bool + autocast_adapter_dtype: bool + generation_kwargs: dict[str, Any] + attn_implementation: Optional[str] + + def __post_init__(self) -> None: + if not isinstance(self.model_id, str): + raise ValueError(f"Invalid model_id: {self.model_id}") + if self.dtype not in ["float32", "float16", "bfloat16", "int8", "int4"]: + raise ValueError(f"Invalid dtype: {self.dtype}") + if self.max_seq_length < 0: + raise ValueError(f"Invalid max_seq_length: {self.max_seq_length}") + if self.batch_size <= 0: + raise ValueError(f"Invalid batch_size: {self.batch_size}") + if self.batch_size_eval <= 0: + raise ValueError(f"Invalid eval batch_size: {self.batch_size_eval}") + if self.max_steps <= 0: + raise ValueError(f"Invalid max_steps: {self.max_steps}") + if self.eval_steps <= 0: + raise ValueError(f"Invalid eval_steps: {self.eval_steps}") + if self.eval_steps > self.max_steps: + raise ValueError(f"Invalid eval_steps: {self.eval_steps} > max_steps: {self.max_steps}") + if self.grad_norm_clip < 0: + raise ValueError(f"Invalid grad_norm_clip: {self.grad_norm_clip}") + if self.optimizer_type not in ["lora+", "lora-fa"] and not hasattr(torch.optim, self.optimizer_type): + raise ValueError(f"Invalid optimizer_type: {self.optimizer_type}") + if self.lr_scheduler not in [None, "cosine"]: + raise ValueError(f"Invalid lr_scheduler: {self.lr_scheduler}, must be None or 'cosine'") + if "{query}" not in self.query_template: + raise ValueError("Invalid query_template, must contain '{query}'") + + +def validate_experiment_path(path: str) -> str: + # the experiment path should take the form of ./experiments// + # e.g. ./experiments/lora/rank32 + # it should contain: + # - adapter_config.json + # - optional: training_params.json + if not os.path.exists(FILE_NAME_DEFAULT_TRAIN_PARAMS): + raise FileNotFoundError( + f"Missing default training params file '{FILE_NAME_DEFAULT_TRAIN_PARAMS}' in the ./experiments directory" + ) + if not os.path.exists(path): + raise FileNotFoundError(f"Path {path} does not exist") + + # check path structure + path_parts = path.rstrip(os.path.sep).split(os.path.sep) + if (len(path_parts) != 3) or (path_parts[-3] != "experiments"): + raise ValueError( + f"Path {path} does not have the correct structure, should be ./experiments//" + ) + + experiment_name = os.path.join(*path_parts[-2:]) + return experiment_name + + +def get_train_config(path: str) -> TrainConfig: + # first, load the default params, then update with experiment-specific params + with open(FILE_NAME_DEFAULT_TRAIN_PARAMS) as f: + default_config_kwargs = json.load(f) + + config_kwargs = {} + if os.path.exists(path): + with open(path) as f: + config_kwargs = json.load(f) + + config_kwargs = {**default_config_kwargs, **config_kwargs} + return TrainConfig(**config_kwargs) + + +def init_accelerator() -> int: + torch_accelerator_module = getattr(torch, device, torch.cuda) + torch.manual_seed(0) + torch_accelerator_module.reset_peak_memory_stats() + torch_accelerator_module.manual_seed_all(0) + # might not be necessary, but just to be sure + nn.Linear(1, 1).to(device) + + accelerator_memory_init = torch_accelerator_module.max_memory_reserved() + if accelerator_memory_init > ACCELERATOR_MEMORY_INIT_THRESHOLD: + raise RuntimeError( + f"{device} memory usage at start is too high: {accelerator_memory_init // 2**20}MB, please ensure that no other " + f"processes are running on {device}." + ) + + torch_accelerator_module.reset_peak_memory_stats() + accelerator_memory_init = torch_accelerator_module.max_memory_reserved() + return accelerator_memory_init + + +def get_tokenizer(*, model_id: str, max_seq_length: int): + tokenizer = AutoTokenizer.from_pretrained(model_id) + tokenizer.model_max_length = max_seq_length + if not tokenizer.pad_token: + tokenizer.pad_token = tokenizer.eos_token + return tokenizer + + +def get_base_model( + *, + model_id: str, + dtype: Literal["float32", "float16", "bfloat16", "int8", "int4"], + attn_implementation: Optional[str], +) -> PreTrainedModel: + kwargs: dict[str, Any] = { + "pretrained_model_name_or_path": model_id, + "device_map": device, + "attn_implementation": attn_implementation, + } + if dtype == "int4": + quant_config = BitsAndBytesConfig(load_in_4bit=True) + kwargs["quantization_config"] = quant_config + elif dtype == "int8": + quant_config = BitsAndBytesConfig(load_in_8bit=True) + kwargs["quantization_config"] = quant_config + elif dtype == "bfloat16": + kwargs["dtype"] = torch.bfloat16 + elif dtype == "float16": + kwargs["dtype"] = torch.float16 + elif dtype != "float32": + raise ValueError(f"Invalid dtype: {dtype}") + + model = AutoModelForCausalLM.from_pretrained(**kwargs) + + if dtype in ["int8", "int4"]: + model = prepare_model_for_kbit_training(model) + + return model + + +def get_model( + *, + model_id: str, + dtype: Literal["float32", "float16", "bfloat16", "int8", "int4"], + compile: bool, + attn_implementation: Optional[str], + peft_config: Optional[PeftConfig], + autocast_adapter_dtype: bool, +) -> nn.Module: + base_model = get_base_model(model_id=model_id, dtype=dtype, attn_implementation=attn_implementation) + if peft_config is None: + model = base_model + else: + model = get_peft_model(base_model, peft_config, autocast_adapter_dtype=autocast_adapter_dtype) + + if compile: + model = torch.compile(model, dynamic=True) + + return model + + +class DummyScheduler: + # if no lr scheduler is being used + def __init__(self, lr): + self.lr = lr + + def get_last_lr(self): + return [self.lr] + + def step(self): + pass + + +def get_optimizer_and_scheduler( + model, *, optimizer_type: str, max_steps: int, lr_scheduler_arg: Optional[Literal["cosine"]], **optimizer_kwargs +) -> tuple[torch.optim.Optimizer, Any]: + if optimizer_type == "lora+": + optimizer = create_loraplus_optimizer(model, optimizer_cls=torch.optim.AdamW, **optimizer_kwargs) + elif optimizer_type == "lora-fa": + optimizer = create_lorafa_optimizer(model, **optimizer_kwargs) + else: + cls = getattr(torch.optim, optimizer_type) + optimizer = cls(model.parameters(), **optimizer_kwargs) + + if lr_scheduler_arg == "cosine": + warmup_steps = int(WARMUP_STEP_RATIO * max_steps) + lr_scheduler = get_cosine_schedule_with_warmup( + optimizer, num_warmup_steps=warmup_steps, num_training_steps=max_steps + ) + elif lr_scheduler_arg is None: + lr_scheduler = DummyScheduler(optimizer_kwargs["lr"]) + else: + raise ValueError(f"Invalid lr_scheduler argument: {lr_scheduler_arg}") + + return optimizer, lr_scheduler + + +class BucketIterator: + """ + Iterator that yields batches of data from a torch Dataset, grouped in buckets by sequence length + + The iterator will yield batches of size `batch_size`, where the samples in each batch are sorted by sequence length. + This is done to minimize the amount of padding required for each batch. To avoid sorting the entire dataset and thus + introducing a bias, the dataset is first split into buckets of size `batch_size * bucket_factor`. + + Args: + ds: The torch Dataset to iterate over + batch_size: The batch size + bucket_factor: The factor by which to multiply the batch size to determine the bucket size + delete_cols: The columns to delete from the dataset before yielding a batch + """ + + def __init__(self, ds, *, batch_size: int, bucket_factor: int, delete_cols: list[str]) -> None: + self.ds = ds + self.batch_size = batch_size + self.bucket_factor = bucket_factor + self.delete_cols = set(delete_cols) + + assert self.bucket_factor > 0, "bucket_factor must be greater than 0" + + def _batch_iterator(self, bucket): + tokens_per_sample_bucket = torch.tensor([len(i) for i in bucket["input_ids"]]) + # sort long to short instead to encounter possible OOM errors as early as possible + sorted = torch.argsort(tokens_per_sample_bucket, descending=True) + cls = type(bucket) # conserve the type returned by the ds + bucket = {k: [v[i] for i in sorted] for k, v in bucket.items() if k not in self.delete_cols} + num_samples = len(bucket["input_ids"]) + for j in range(0, num_samples, self.batch_size): + batch = {k: v[j : j + self.batch_size] for k, v in bucket.items()} + yield cls(batch) + + def __iter__(self): + bucket_size = self.batch_size * self.bucket_factor + for i in range(0, len(self.ds), bucket_size): + bucket = self.ds[i : i + bucket_size] + yield from self._batch_iterator(bucket) + + # if there is a remainder, we yield the last batch + if len(self.ds) % bucket_size != 0: + bucket = self.ds[-(len(self.ds) % bucket_size) :] + yield from self._batch_iterator(bucket) + + +def get_file_size( + model: nn.Module, *, peft_config: Optional[PeftConfig], clean: bool, print_fn: Callable[..., None] +) -> int: + file_size = 99999999 # set a default dummy value + if peft_config is not None: + try: + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True, delete=clean) as tmp_dir: + model.save_pretrained(tmp_dir) + stat = os.stat(os.path.join(tmp_dir, SAFETENSORS_WEIGHTS_NAME)) + file_size = stat.st_size + if not clean: + print_fn(f"Saved PEFT checkpoint to {tmp_dir}") + except Exception as exc: + print(f"Failed to save PEFT checkpoint due to the following error: {exc}") + else: + print_fn("Not saving the fully fine-tuned model because it's too big, estimating the size instead") + try: + num_params = model.num_parameters() + dtype_size = next(model.parameters()).element_size() + file_size = num_params * dtype_size + except Exception as exc: + print(f"Failed to determine file size for fully finetuned model because of: {exc}") + return file_size + + +################## +# ANSWER PARSING # +################## + + +def parse_answer(text: str) -> Optional[str]: + """ + A label/prediction can look like this: + + Question: If the magnitude of vector v is equal to 4, what is the dot product of vector v with itself?. Think step + by step + Answer: The dot product of a vector with itself is equal to the square of its magnitude. So, the dot product of + vector v with itself is equal to $4^2 = \boxed{16}$.The answer is: 16 + + We want to extract '16' from this string. + + """ + # This implementation is based on sampling meta-llama/Llama-3.1-8B-Instruct. It may not work for other models. + candidate_delimiters = [ + # MetaMath: + "The answer is: ", + "The answer is ", + "The final answer is: ", + "The final answer is ", + # GSM8K: + "#### ", + ] + text = text.strip() + text = text.rstrip(".!?") + for delimiter in candidate_delimiters: + if delimiter in text: + break + else: # no match + return None + + text = text.rpartition(delimiter)[-1].strip() + # if a new paragraph follows after the final answer, we want to remove it + text = text.split("\n", 1)[0] + # note: we can just remove % here since the GSM8K dataset just omits it, i.e. 50% -> 50, no need to divide by 100 + text = text.strip(" .!?$%") + return text + + +def convert_to_decimal(s: Optional[str]) -> Optional[Decimal]: + """ + Converts a string representing a number to a Decimal. + + The string may be: + - A simple number (e.g., "13", "65.33") + - A fraction (e.g., "20/14") + """ + if s is None: + return None + + try: + s = s.strip() + # Check if the string represents a fraction. + if "/" in s: + parts = s.split("/") + if len(parts) != 2: + return None + numerator = Decimal(parts[0].strip()) + denominator = Decimal(parts[1].strip()) + if denominator == 0: + return None + value = numerator / denominator + else: + # Parse as a regular decimal or integer string. + value = Decimal(s) + return value + except (DivisionByZero, InvalidOperation, ValueError): + return None + + +def get_accuracy(*, predictions: list[str], responses: list[str]) -> float: + if len(predictions) != len(responses): + raise ValueError(f"Prediction length mismatch: {len(predictions)} != {len(responses)}") + + y_true: list[str | float | None] = [] + y_pred: list[str | float | None] = [] + + for prediction, response in zip(predictions, responses): + parsed_prediction = parse_answer(prediction) + parsed_response = parse_answer(response) + if parsed_response is None: + raise ValueError(f"Error encountered while trying to parse response: {response}") + + decimal_prediction = convert_to_decimal(parsed_prediction) + decimal_answer = convert_to_decimal(parsed_response) + if decimal_prediction is not None: + y_pred.append(float(decimal_prediction)) + elif parsed_prediction is not None: + y_pred.append(parsed_prediction) + else: + y_pred.append(None) + + # we convert decimals to float so that stuff like this works: + # float(convert_to_decimal('20/35')) == float(convert_to_decimal('0.5714285714285714')) + if decimal_answer is not None: + y_true.append(float(decimal_answer)) + elif parsed_prediction is not None: + y_true.append(parsed_response) + else: + y_true.append(None) + + correct: list[bool] = [] + for true, pred in zip(y_true, y_pred): + if (true is not None) and (pred is not None): + correct.append(true == pred) + else: + correct.append(False) + + accuracy = sum(correct) / len(correct) + return accuracy + + +########### +# LOGGING # +########### + + +def get_base_model_info(model_id: str) -> Optional[huggingface_hub.ModelInfo]: + try: + return hf_api.model_info(model_id) + except Exception as exc: + warnings.warn(f"Could not retrieve model info, failed with error {exc}") + return None + + +def get_dataset_info(dataset_id: str) -> Optional[huggingface_hub.DatasetInfo]: + try: + return hf_api.dataset_info(dataset_id) + except Exception as exc: + warnings.warn(f"Could not retrieve dataset info, failed with error {exc}") + return None + + +def get_git_hash(module) -> Optional[str]: + if "site-packages" in module.__path__[0]: + return None + + return subprocess.check_output("git rev-parse HEAD".split(), cwd=os.path.dirname(module.__file__)).decode().strip() + + +def get_package_info() -> dict[str, Optional[str]]: + """Get the package versions and commit hashes of transformers, peft, datasets, bnb, and torch""" + package_info = { + "transformers-version": transformers.__version__, + "transformers-commit-hash": get_git_hash(transformers), + "peft-version": peft.__version__, + "peft-commit-hash": get_git_hash(peft), + "datasets-version": datasets.__version__, + "datasets-commit-hash": get_git_hash(datasets), + "bitsandbytes-version": bitsandbytes.__version__, + "bitsandbytes-commit-hash": get_git_hash(bitsandbytes), + "torch-version": torch.__version__, + "torch-commit-hash": get_git_hash(torch), + } + return package_info + + +def get_system_info() -> dict[str, str]: + device = infer_device() + torch_accelerator_module = getattr(torch, device, torch.cuda) + system_info = { + "system": platform.system(), + "release": platform.release(), + "version": platform.version(), + "machine": platform.machine(), + "processor": platform.processor(), + "accelerator": torch_accelerator_module.get_device_name(0), + } + return system_info + + +@dataclass +class MetaInfo: + package_info: dict[str, Optional[str]] + system_info: dict[str, str] + pytorch_info: str + + +def get_meta_info() -> MetaInfo: + meta_info = MetaInfo( + package_info=get_package_info(), + system_info=get_system_info(), + pytorch_info=torch.__config__.show(), + ) + return meta_info + + +def get_peft_branch() -> str: + return ( + subprocess.check_output("git rev-parse --abbrev-ref HEAD".split(), cwd=os.path.dirname(peft.__file__)) + .decode() + .strip() + ) + + +class TrainStatus(enum.Enum): + FAILED = "failed" + SUCCESS = "success" + CANCELED = "canceled" + + +@dataclass +class TrainResult: + status: TrainStatus + train_time: float + accelerator_memory_reserved_log: list[int] + losses: list[float] + metrics: list[Any] # TODO + error_msg: str + num_trainable_params: int + num_total_params: int + + +def log_to_console(log_data: dict[str, Any], print_fn: Callable[..., None]) -> None: + accelerator_memory_max = log_data["train_info"]["accelerator_memory_max"] + accelerator_memory_avg = log_data["train_info"]["accelerator_memory_reserved_avg"] + accelerator_memory_reserved_99th = log_data["train_info"]["accelerator_memory_reserved_99th"] + time_train = log_data["train_info"]["train_time"] + time_total = log_data["run_info"]["total_time"] + file_size = log_data["train_info"]["file_size"] + + print_fn(f"accelerator memory max: {accelerator_memory_max // 2**20}MB") + print_fn(f"accelerator memory reserved avg: {accelerator_memory_avg // 2**20}MB") + print_fn(f"accelerator memory reserved 99th percentile: {accelerator_memory_reserved_99th // 2**20}MB") + print_fn(f"train time: {time_train}s") + print_fn(f"total time: {time_total:.2f}s") + print_fn(f"file size of checkpoint: {file_size / 2**20:.1f}MB") + + +def log_to_file( + *, log_data: dict, save_dir: str, experiment_name: str, timestamp: str, print_fn: Callable[..., None] +) -> None: + if save_dir.endswith(RESULT_PATH): + file_name = f"{experiment_name.replace(os.path.sep, '--')}.json" + else: + # For cancelled and temporary runs, we want to include the timestamp, as these runs are not tracked in git, thus + # we need unique names to avoid losing history. + file_name = f"{experiment_name.replace(os.path.sep, '--')}--{timestamp.replace(':', '-')}.json" + file_name = os.path.join(save_dir, file_name) + with open(file_name, "w") as f: + json.dump(log_data, f, indent=2) + print_fn(f"Saved log to: {file_name}") + + +def log_results( + *, + experiment_name: str, + train_result: TrainResult, + accelerator_memory_init: int, + time_total: float, + file_size: int, + model_info: Optional[huggingface_hub.ModelInfo], + datasets_info: dict[str, Optional[huggingface_hub.DatasetInfo]], + start_date: str, + train_config: TrainConfig, + peft_config: Optional[PeftConfig], + print_fn: Callable[..., None], +) -> None: + # collect results + device = infer_device() + torch_accelerator_module = getattr(torch, device, torch.cuda) + accelerator_memory_final = torch_accelerator_module.max_memory_reserved() + accelerator_memory_avg = int( + sum(train_result.accelerator_memory_reserved_log) / len(train_result.accelerator_memory_reserved_log) + ) + accelerator_memory_reserved_99th = int(np.percentile(train_result.accelerator_memory_reserved_log, 99)) + + meta_info = get_meta_info() + if model_info is not None: + model_sha = model_info.sha + model_created_at = model_info.created_at.isoformat() + else: + model_sha = None + model_created_at = None + + dataset_info_log = {} + for key, dataset_info in datasets_info.items(): + if dataset_info is not None: + dataset_sha = dataset_info.sha + dataset_created_at = dataset_info.created_at.isoformat() + else: + dataset_sha = None + dataset_created_at = None + dataset_info_log[key] = {"sha": dataset_sha, "created_at": dataset_created_at} + + peft_branch = get_peft_branch() + + if train_result.status == TrainStatus.CANCELED: + save_dir = RESULT_PATH_CANCELLED + print_fn("Experiment run was categorized as canceled") + elif peft_branch != "main": + save_dir = RESULT_PATH_TEST + print_fn(f"Experiment run was categorized as a test run on branch {peft_branch}") + elif train_result.status == TrainStatus.SUCCESS: + save_dir = RESULT_PATH + print_fn("Experiment run was categorized as successful run") + else: + save_dir = tempfile.mkdtemp() + print_fn(f"Experiment could not be categorized, writing results to {save_dir}. Please open an issue on PEFT.") + + if peft_config is None: + peft_config_dict: Optional[dict[str, Any]] = None + else: + peft_config_dict = peft_config.to_dict() + for key, value in peft_config_dict.items(): + if isinstance(value, set): + peft_config_dict[key] = list(value) + + log_data = { + "run_info": { + "created_at": start_date, + "total_time": time_total, + "experiment_name": experiment_name, + "peft_branch": peft_branch, + "train_config": asdict(train_config), + "peft_config": peft_config_dict, + "error_msg": train_result.error_msg, + }, + "train_info": { + "accelerator_memory_reserved_avg": accelerator_memory_avg, + "accelerator_memory_max": (accelerator_memory_final - accelerator_memory_init), + "accelerator_memory_reserved_99th": accelerator_memory_reserved_99th, + "train_time": train_result.train_time, + "file_size": file_size, + "num_trainable_params": train_result.num_trainable_params, + "num_total_params": train_result.num_total_params, + "status": train_result.status.value, + "metrics": train_result.metrics, + }, + "meta_info": { + "model_info": {"sha": model_sha, "created_at": model_created_at}, + "dataset_info": dataset_info_log, + **asdict(meta_info), + }, + } + + log_to_console(log_data, print_fn=print) # use normal print to be able to redirect if so desired + log_to_file( + log_data=log_data, save_dir=save_dir, experiment_name=experiment_name, timestamp=start_date, print_fn=print_fn + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/README.md b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/README.md new file mode 100644 index 0000000000000000000000000000000000000000..c34fec0f9d0ef4de9342c539ca1e29642f4f6133 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/README.md @@ -0,0 +1,116 @@ +--- +title: PEFT Method Comparison +sdk: gradio +app_file: app.py +pinned: false +emoji: ⚖️ +--- + +# Comparison of PEFT Methods + +The goal of this project is to provide replicable experiments that produce outcomes allowing us to compare different PEFT methods with one another. This gives you more information to make an informed decision about which methods best fit your use case and what trade-offs to expect. + +Visit our [Gradio Space](https://huggingface.co/spaces/peft-internal-testing/PEFT-method-comparison) to check the results. + +## Community Contributions + +We envision the PEFT method comparison project as an ongoing endeavor with heavy involvement from the community. As maintainers, it is impossible for us to know all the perfect hyperparameters for each method or to predict all the use cases that PEFT users may have. As a consequence, community contributions are very welcome. + +Below, we outline all the ways you can contribute to this project. + +### Creating New Experiments + +Creating a new experiment requires setting up a new PEFT configuration for us to test. This will result in one more data point being added to the total comparison. + +Working on this is especially relevant if: + +1. You are the author of a paper whose method is introduced in PEFT, or worked on the PEFT integration, and know what hyperparameters work best. +2. You have experience with a specific method and want to share your knowledge with the community. + +Of course, you can contribute even without meeting these criteria. Please follow the instructions below. + +#### How to Add New Experiments + +Start by navigating to one of the existing experiment folders, e.g. `peft/method_comparison/MetaMathQA`, if your experiment involves using the [MetaMathQA dataset](https://huggingface.co/datasets/meta-math/MetaMathQA). There, create a new directory inside the `experiments/` folder using a descriptive name. For example, if you want to test LoRA with rank 123 using Llama-3.2 3B as the base model, you could name the folder `experiments/lora/llama-3.2-3B-rank123`. + +Inside this directory, you will find a default configuration file called `default_training_params.json`, which contains the default parameters used in the `run.py` training script. Create a new JSON file containing all the parameters you want to modify compared to the defaults, and save it as `training_params.json` in the newly created folder. If you are satisfied with all the default training parameters, you can skip this step. + +Finally, you need to create a PEFT configuration file for the PEFT method you want to add. This should be a JSON file called `adapter_config.json`, placed in the same directory. Below is an example of how this could look: + +```python +from peft import LoraConfig +config = LoraConfig(r=123) +config.save_pretrained("experiments/lora/llama-3.2-3B-rank123/") +``` + +Once you've created the configuration files for your experiment, please [create a PR on PEFT](https://github.com/huggingface/peft/pulls). After it is reviewed and merged, we will run it on our hardware to ensure that the results are comparable. Of course, it is best if you run the experiment at least once on your hardware to verify that the proposed settings work well. + +#### Considerations When Adding New Experiments + +When adding a new experiment, please consider the following points: + +1. Avoid changing too many training parameters at once, as this would make it difficult to compare results with existing ones. For example, if all existing results were created with 5000 training steps but your result uses 10000 steps, it would be unclear whether an improvement in the test score is due to the PEFT method itself or simply due to longer training. Similarly, using a completely different base model, especially if it is significantly more capable, does not contribute to a fair comparison. +2. Avoid suggesting configurations that are very close to existing ones. For example, if there is already an experiment with LoRA and rank 123, do not add an experiment with LoRA and rank 124. +3. Experiments for less-tested methods are more valuable than additional experiments for widely tested methods. +4. Do not edit existing experiments, always create new ones. +5. If you found hyper parameters that work especially well with a given method but are not trivial to find out, consider updating the PEFT documentation of that method so that other users can benefit from your findings. + +### Updating the Training Script + +We provide a training script that includes features typically useful for improving training outcomes, such as AMP support, a cosine learning rate schedule, etc. However, there is always room for improvement. For example, at the time of writing, the script does not support gradient accumulation. Therefore, PRs that extend the training script are welcome. + +#### How to Update the Training Script + +Follow the same process as when contributing to PEFT in general (see the [contribution guidelines](https://huggingface.co/docs/peft/developer_guides/contributing)). If the same training script is used across multiple datasets, please ensure that all relevant scripts are updated accordingly. + +#### Considerations When Updating the Training Script + +1. Updates should be backward-compatible. By default, any new features should be disabled to ensure that existing results remain valid. For example, if you add gradient accumulation, ensure it is disabled by default so that new experiments must opt in. +2. Before adding a bug fix that could invalidate existing results, consider whether the trade-off is worthwhile. If we already have many experimental results, rerunning all of them can be expensive. If the bug fix is not critical, it may not be worth invalidating previous results. However, if you discover a significant bug that could meaningfully impact outcomes, it should be addressed. +3. Avoid unnecessary complexity. While we could add support for DeepSpeed, FSDP, etc., doing so would add significant complexity, exclude users with limited hardware, and is unlikely to alter the relative performance of different PEFT methods. +4. Minimize reliance on specific training frameworks. For example, we deliberately avoid using the `Trainer` class from transformers or PyTorch Lightning. This ensures transparency, making it easier to understand the training process and replicate results over time. If a training framework were used, we would have to pin the version or risk future incompatibilities. + +### Adding a New Dataset + +Adding a new dataset increases the breadth and usefulness of the PEFT method comparison. The goal is not necessarily to outperform benchmarks or replicate paper results, but to fairly compare different PEFT methods in a way that is useful for PEFT users. If this involves replicating an experiment from a paper, that is great, but it is not a requirement. + +#### How to Add a New Dataset + +The easiest way to add support for a new dataset is to copy an existing setup, such as `method_comparison/MetaMathQA`, rename it, and modify `data.py`, as well as any other necessary parts of the code. Ideally, as much existing code as possible should be reused. The general folder structure and experiment logging format should remain consistent. + +After adding the dataset, ensure it functions correctly and produces meaningful results by running at least one experimental setup, such as using LoRA with default settings. + +#### Considerations When Adding a New Dataset + +1. Before beginning, it is best to open an [issue on PEFT](https://github.com/huggingface/peft/issues) to share your plans. This allows for early feedback and prevents wasted effort on impractical ideas. +2. The most valuable new datasets are those that test different capabilities than those already present. Bonus points if the task is similar to what users may face in the real world. Task ideas that would be great to add: + - A task involving both language and image modalities. + - An image generation task (like stable diffusion) + - A task involving audio (like whisper) + - A task that requires knowledge preservation (checked, for instance, via an auxiliary test set) + - Learning something completely new (e.g. a new language) + - A reinforcement learning task (e.g. using [trl](https://github.com/huggingface/trl)) +3. Training should be reasonably fast. Running dozens of experiments is impractical if each one takes multiple days and incurs high costs. Ideally, training should take a few hours at most on high-end consumer hardware. +4. The chosen base model should not be too large, to avoid VRAM constraints. Morevoer, if the base model is too powerful, there is little room for improvement through further fine-tuning. +5. Test scores should be informative and have a broad range: + - Besides loss, there should ideally be at least one additional metric, such as accuracy. + - Comparisons are not meaningful if all methods score near 0% or near 100%. The dataset should yield a range of scores to facilitate meaningful differentiation between methods. +6. The dataset should be publicly available and have a track record as a useful dataset. The license should permit the intended usage. + +## Result dashboard + +For convenience, we included a [Gradio](https://www.gradio.app/) app that shows the results of the experiments. It allows you to filter down the task and base model and show the experiment results for this selection. Give it a try [here](https://huggingface.co/spaces/peft-internal-testing/PEFT-method-comparison). + +### Local deployment + +This app requires additional packages to be installed, please install the packages listed in `requirements-app.txt`, e.g. via: + +```sh +python -m pip install -r requirements-app.txt +``` + +To launch the demo, run: + +```sh +python app.py +``` diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/app.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/app.py new file mode 100644 index 0000000000000000000000000000000000000000..9929d24bb46548c5bda4fcfb42ee4fa66999e844 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/app.py @@ -0,0 +1,385 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Gradio app to show the results""" + +import os +import tempfile + +import gradio as gr +import plotly.express as px +import plotly.graph_objects as go +from processing import load_df +from sanitizer import parse_and_filter + + +metric_preferences = { + "accelerator_memory_reserved_avg": "lower", + "accelerator_memory_max": "lower", + "accelerator_memory_reserved_99th": "lower", + "total_time": "lower", + "train_time": "lower", + "file_size": "lower", + "test_accuracy": "higher", + "train_loss": "lower", + "num_trainable_params": "lower", + "forgetting*": "lower", +} + + +def get_model_ids(task_name, df): + filtered = df[df["task_name"] == task_name] + return sorted(filtered["model_id"].unique()) + + +def filter_data(task_name, model_id, df): + filtered = df[(df["task_name"] == task_name) & (df["model_id"] == model_id)] + return filtered + + +# Compute the Pareto frontier for two selected metrics. +def compute_pareto_frontier(df, metric_x, metric_y): + if df.empty: + return df + + df = df.copy() + points = df[[metric_x, metric_y]].values + selected_indices = [] + + def dominates(a, b, metric_x, metric_y): + # Check for each metric whether b is as good or better than a + if metric_preferences[metric_x] == "higher": + cond_x = b[0] >= a[0] + better_x = b[0] > a[0] + else: + cond_x = b[0] <= a[0] + better_x = b[0] < a[0] + if metric_preferences[metric_y] == "higher": + cond_y = b[1] >= a[1] + better_y = b[1] > a[1] + else: + cond_y = b[1] <= a[1] + better_y = b[1] < a[1] + return cond_x and cond_y and (better_x or better_y) + + for i, point in enumerate(points): + dominated = False + for j, other_point in enumerate(points): + if i == j: + continue + if dominates(point, other_point, metric_x, metric_y): + dominated = True + break + if not dominated: + selected_indices.append(i) + pareto_df = df.iloc[selected_indices] + return pareto_df + + +def generate_pareto_plot(df, metric_x, metric_y): + if df.empty: + return {} + + # Compute Pareto frontier and non-frontier points. + pareto_df = compute_pareto_frontier(df, metric_x, metric_y) + non_pareto_df = df.drop(pareto_df.index) + + # Create an empty figure. + fig = go.Figure() + + # Draw the line connecting Pareto frontier points. + if not pareto_df.empty: + # Sort the Pareto frontier points by metric_x for a meaningful connection. + pareto_sorted = pareto_df.sort_values(by=metric_x) + line_trace = go.Scatter( + x=pareto_sorted[metric_x], + y=pareto_sorted[metric_y], + mode="lines", + line={"color": "rgba(0,0,255,0.3)", "width": 4}, + name="Pareto Frontier", + ) + fig.add_trace(line_trace) + + # Add non-frontier points in gray with semi-transparency. + if not non_pareto_df.empty: + non_frontier_trace = go.Scatter( + x=non_pareto_df[metric_x], + y=non_pareto_df[metric_y], + mode="markers", + marker={"color": "rgba(128,128,128,0.5)", "size": 12}, + hoverinfo="text", + text=non_pareto_df.apply( + lambda row: f"experiment_name: {row['experiment_name']}
" + f"peft_type: {row['peft_type']}
" + f"{metric_x}: {row[metric_x]}
" + f"{metric_y}: {row[metric_y]}", + axis=1, + ), + showlegend=False, + ) + fig.add_trace(non_frontier_trace) + + # Add Pareto frontier points with legend + if not pareto_df.empty: + pareto_scatter = px.scatter( + pareto_df, + x=metric_x, + y=metric_y, + color="experiment_name", + hover_data={"experiment_name": True, "peft_type": True, metric_x: True, metric_y: True}, + ) + for trace in pareto_scatter.data: + trace.marker = {"size": 12} + fig.add_trace(trace) + + # Update layout with axes labels. + fig.update_layout( + title=f"Pareto Frontier for {metric_x} vs {metric_y}", + template="seaborn", + height=700, + autosize=True, + xaxis_title=metric_x, + yaxis_title=metric_y, + ) + + return fig + + +def compute_pareto_summary(filtered, pareto_df, metric_x, metric_y): + if filtered.empty: + return "No data available." + + stats = filtered[[metric_x, metric_y]].agg(["min", "max", "mean"]).to_string() + total_points = len(filtered) + pareto_points = len(pareto_df) + excluded_points = total_points - pareto_points + summary_text = ( + f"{stats}\n\n" + f"Total points: {total_points}\n" + f"Pareto frontier points: {pareto_points}\n" + f"Excluded points: {excluded_points}" + ) + return summary_text + + +def export_csv(df): + if df.empty: + return None + csv_data = df.to_csv(index=False) + with tempfile.NamedTemporaryFile(delete=False, suffix=".csv", mode="w", encoding="utf-8") as tmp: + tmp.write(csv_data) + tmp_path = tmp.name + return tmp_path + + +def format_df(df): + return df.style.format(precision=3, thousands=",", decimal=".") + + +def build_app(df): + with gr.Blocks() as demo: + gr.Markdown("# PEFT method comparison") + gr.Markdown( + "Find more information [on the PEFT GitHub repo](https://github.com/huggingface/peft/tree/main/method_comparison)" + ) + + # Hidden state to store the current filter query. + filter_state = gr.State("") + + gr.Markdown("## Choose the task and base model") + with gr.Row(): + task_dropdown = gr.Dropdown( + label="Select Task", + choices=sorted(df["task_name"].unique()), + value=sorted(df["task_name"].unique())[0], + ) + model_dropdown = gr.Dropdown( + label="Select Model ID", choices=get_model_ids(sorted(df["task_name"].unique())[0], df) + ) + + # Make dataframe columns all equal in width so that they are good enough for numbers but don't + # get hugely extended by columns like `train_config`. + column_widths = ["150px" for _ in df.columns] + column2index = dict(zip(df.columns, range(len(df.columns)))) + column_widths[column2index['experiment_name']] = '300px' + + data_table = gr.DataFrame( + label="Results", + value=format_df(df), + interactive=False, + max_chars=100, + wrap=False, + column_widths=column_widths, + ) + + with gr.Row(): + filter_textbox = gr.Textbox( + label="Filter DataFrame", + placeholder="Enter filter (e.g.: peft_type=='LORA')", + interactive=True, + ) + apply_filter_button = gr.Button("Apply Filter") + reset_filter_button = gr.Button("Reset Filter") + + gr.Markdown( + "*forgetting: This is the reduction in CE loss on a sample of Wikipedia data and reflects how much the " + "model 'forgot' during training. The lower the number, the better." + ) + + gr.Markdown("## Pareto plot") + gr.Markdown( + "Select 2 criteria to plot the Pareto frontier. This will show the best PEFT methods along this axis and " + "the trade-offs with the other axis. The PEFT methods that Pareto-dominate are shown in colors. All other " + "methods are inferior with regard to these two metrics. Hover over a point to show details." + ) + + with gr.Row(): + x_default = ( + "accelerator_memory_max" + if "accelerator_memory_max" in metric_preferences + else list(metric_preferences.keys())[0] + ) + y_default = ( + "test_accuracy" if "test_accuracy" in metric_preferences else list(metric_preferences.keys())[1] + ) + metric_x_dropdown = gr.Dropdown( + label="1st metric for Pareto plot", + choices=list(metric_preferences.keys()), + value=x_default, + ) + metric_y_dropdown = gr.Dropdown( + label="2nd metric for Pareto plot", + choices=list(metric_preferences.keys()), + value=y_default, + ) + + pareto_plot = gr.Plot(label="Pareto Frontier Plot") + summary_box = gr.Textbox(label="Summary Statistics", lines=6) + csv_output = gr.File(label="Export Filtered Data as CSV") + + def update_on_task(task_name, current_filter): + new_models = get_model_ids(task_name, df) + filtered = filter_data(task_name, new_models[0] if new_models else "", df) + if current_filter.strip(): + try: + mask = parse_and_filter(filtered, current_filter) + df_queried = filtered[mask] + if not df_queried.empty: + filtered = df_queried + except Exception: + # invalid filter query + pass + return gr.update(choices=new_models, value=new_models[0] if new_models else None), format_df(filtered) + + task_dropdown.change( + fn=update_on_task, inputs=[task_dropdown, filter_state], outputs=[model_dropdown, data_table] + ) + + def update_on_model(task_name, model_id, current_filter): + filtered = filter_data(task_name, model_id, df) + if current_filter.strip(): + try: + mask = parse_and_filter(filtered, current_filter) + filtered = filtered[mask] + except Exception: + pass + return format_df(filtered) + + model_dropdown.change( + fn=update_on_model, inputs=[task_dropdown, model_dropdown, filter_state], outputs=data_table + ) + + def update_pareto_plot_and_summary(task_name, model_id, metric_x, metric_y, current_filter): + filtered = filter_data(task_name, model_id, df) + if current_filter.strip(): + try: + mask = parse_and_filter(filtered, current_filter) + filtered = filtered[mask] + except Exception as e: + return generate_pareto_plot(filtered, metric_x, metric_y), f"Filter error: {e}" + + pareto_df = compute_pareto_frontier(filtered, metric_x, metric_y) + fig = generate_pareto_plot(filtered, metric_x, metric_y) + summary = compute_pareto_summary(filtered, pareto_df, metric_x, metric_y) + return fig, summary + + for comp in [model_dropdown, metric_x_dropdown, metric_y_dropdown]: + comp.change( + fn=update_pareto_plot_and_summary, + inputs=[task_dropdown, model_dropdown, metric_x_dropdown, metric_y_dropdown, filter_state], + outputs=[pareto_plot, summary_box], + ) + + def apply_filter(filter_query, task_name, model_id, metric_x, metric_y): + filtered = filter_data(task_name, model_id, df) + if filter_query.strip(): + try: + mask = parse_and_filter(filtered, filter_query) + filtered = filtered[mask] + except Exception as e: + # Update the table, plot, and summary even if there is a filter error. + return ( + filter_query, + filtered, + generate_pareto_plot(filtered, metric_x, metric_y), + f"Filter error: {e}", + ) + + pareto_df = compute_pareto_frontier(filtered, metric_x, metric_y) + fig = generate_pareto_plot(filtered, metric_x, metric_y) + summary = compute_pareto_summary(filtered, pareto_df, metric_x, metric_y) + return filter_query, format_df(filtered), fig, summary + + apply_filter_button.click( + fn=apply_filter, + inputs=[filter_textbox, task_dropdown, model_dropdown, metric_x_dropdown, metric_y_dropdown], + outputs=[filter_state, data_table, pareto_plot, summary_box], + ) + + def reset_filter(task_name, model_id, metric_x, metric_y): + filtered = filter_data(task_name, model_id, df) + pareto_df = compute_pareto_frontier(filtered, metric_x, metric_y) + fig = generate_pareto_plot(filtered, metric_x, metric_y) + summary = compute_pareto_summary(filtered, pareto_df, metric_x, metric_y) + # Return empty strings to clear the filter state and textbox. + return "", "", format_df(filtered), fig, summary + + reset_filter_button.click( + fn=reset_filter, + inputs=[task_dropdown, model_dropdown, metric_x_dropdown, metric_y_dropdown], + outputs=[filter_state, filter_textbox, data_table, pareto_plot, summary_box], + ) + + gr.Markdown("## Export data") + # Export button for CSV download. + export_button = gr.Button("Export Filtered Data") + export_button.click( + fn=lambda task, model: export_csv(filter_data(task, model, df)), + inputs=[task_dropdown, model_dropdown], + outputs=csv_output, + ) + + demo.load( + fn=update_pareto_plot_and_summary, + inputs=[task_dropdown, model_dropdown, metric_x_dropdown, metric_y_dropdown, filter_state], + outputs=[pareto_plot, summary_box], + ) + + return demo + + +path = os.path.join(os.path.dirname(__file__), "MetaMathQA", "results") +df = load_df(path, task_name="MetaMathQA") +demo = build_app(df) +demo.launch(theme=gr.themes.Soft()) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/processing.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/processing.py new file mode 100644 index 0000000000000000000000000000000000000000..ea2b8caf40ed016b25b3981127be62e9771f4ab4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/processing.py @@ -0,0 +1,150 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Data processing used for analyzing and presenting the results""" + +import json +import os + +import pandas as pd + + +def preprocess(rows, task_name: str, print_fn=print): + results = [] + skipped = 0 + for row in rows: + run_info = row["run_info"] + train_info = row["train_info"] + meta_info = row["meta_info"] + if run_info["peft_config"]: + peft_type = run_info["peft_config"]["peft_type"] + else: + peft_type = "full-finetuning" + if train_info["status"] != "success": + skipped += 1 + continue + + train_metrics = train_info["metrics"][-1] + + # extract the fields that make most sense + dct = { + "task_name": task_name, + "experiment_name": run_info["experiment_name"], + "model_id": run_info["train_config"]["model_id"], + "train_config": run_info["train_config"], + "peft_type": peft_type, + "peft_config": run_info["peft_config"], + "accelerator_memory_reserved_avg": train_info["accelerator_memory_reserved_avg"], + "accelerator_memory_max": train_info["accelerator_memory_max"], + "accelerator_memory_reserved_99th": train_info["accelerator_memory_reserved_99th"], + "total_time": run_info["total_time"], + "train_time": train_info["train_time"], + "file_size": train_info["file_size"], + "num_trainable_params": train_info["num_trainable_params"], + "test_accuracy": train_metrics["test accuracy"], + "train_loss": train_metrics["train loss"], + "train_samples": train_metrics["train samples"], + "train_total_tokens": train_metrics["train total tokens"], + "forgetting*": train_metrics.get("forgetting", 123), + "peft_version": meta_info["package_info"]["peft-version"], + "peft_branch": run_info["peft_branch"], + "transformers_version": meta_info["package_info"]["transformers-version"], + "datasets_version": meta_info["package_info"]["datasets-version"], + "torch_version": meta_info["package_info"]["torch-version"], + "bitsandbytes_version": meta_info["package_info"]["bitsandbytes-version"], + "package_info": meta_info["package_info"], + "system_info": meta_info["system_info"], + "created_at": run_info["created_at"], + } + results.append(dct) + + if skipped: + print_fn(f"Skipped {skipped} of {len(rows)} entries because the train status != success") + + return results + + +def load_jsons(path): + results = [] + for fn in os.listdir(path): + if fn.endswith(".json"): + with open(os.path.join(path, fn)) as f: + row = json.load(f) + results.append(row) + return results + + +def load_df(path, task_name, print_fn=print): + jsons = load_jsons(path) + preprocessed = preprocess(jsons, task_name=task_name, print_fn=print_fn) + dtype_dict = { + "task_name": "string", + "experiment_name": "string", + "model_id": "string", + "train_config": "string", + "peft_type": "string", + "peft_config": "string", + "accelerator_memory_reserved_avg": int, + "accelerator_memory_max": int, + "accelerator_memory_reserved_99th": int, + "total_time": float, + "train_time": float, + "file_size": int, + "test_accuracy": float, + "train_loss": float, + "train_samples": int, + "train_total_tokens": int, + "forgetting*": float, + "num_trainable_params": int, + "peft_version": "string", + "peft_branch": "string", + "transformers_version": "string", + "datasets_version": "string", + "torch_version": "string", + "bitsandbytes_version": "string", + "package_info": "string", + "system_info": "string", + "created_at": "string", + } + df = pd.DataFrame(preprocessed) + df = df.astype(dtype_dict) + df["created_at"] = pd.to_datetime(df["created_at"]) + # round training time to nearest second + df["train_time"] = df["train_time"].round().astype(int) + df["total_time"] = df["total_time"].round().astype(int) + + # reorder columns for better viewing, pinned_columns arg in Gradio seems not to work correctly + important_columns = [ + "experiment_name", + "peft_type", + "total_time", + "train_time", + "test_accuracy", + "train_loss", + "accelerator_memory_max", + "accelerator_memory_reserved_99th", + "accelerator_memory_reserved_avg", + "num_trainable_params", + "file_size", + "created_at", + "task_name", + "forgetting*", + ] + other_columns = [col for col in df if col not in important_columns] + df = df[important_columns + other_columns] + + columns = ["experiment_name", "model_id", "peft_type", "created_at"] + # we want to keep only the most recent run for each experiment + df = df.sort_values("created_at").drop_duplicates(columns, keep="last") + return df diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/requirements-app.txt b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/requirements-app.txt new file mode 100644 index 0000000000000000000000000000000000000000..01f489ea23e3993a576fdf01ff72f289ed890134 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/requirements-app.txt @@ -0,0 +1,3 @@ +dash +gradio>=6.0.2 +pandas diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/sanitizer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/sanitizer.py new file mode 100644 index 0000000000000000000000000000000000000000..7659d650c0fb293806d314f7334950ebaffbda33 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/sanitizer.py @@ -0,0 +1,100 @@ +import ast + +import pandas as pd + + +def _evaluate_node(df, node): + """ + Recursively evaluates an AST node to generate a pandas boolean mask. + """ + # Base Case: A simple comparison like 'price > 100' + if isinstance(node, ast.Compare): + if not isinstance(node.left, ast.Name): + raise ValueError("Left side of comparison must be a column name.") + col = node.left.id + if col not in df.columns: + raise ValueError(f"Column '{col}' not found in DataFrame.") + + if len(node.ops) > 1: + raise ValueError("Chained comparisons like '10 < price < 100' are not supported.") + + op_node = node.ops[0] + val_node = node.comparators[0] + try: + value = ast.literal_eval(val_node) + except ValueError: + raise ValueError("Right side of comparison must be a literal (number, string, list).") + + operator_map = { + ast.Gt: lambda c, v: df[c] > v, + ast.GtE: lambda c, v: df[c] >= v, + ast.Lt: lambda c, v: df[c] < v, + ast.LtE: lambda c, v: df[c] <= v, + ast.Eq: lambda c, v: df[c] == v, + ast.NotEq: lambda c, v: df[c] != v, + ast.In: lambda c, v: df[c].isin(v), + ast.NotIn: lambda c, v: ~df[c].isin(v) + } + op_type = type(op_node) + if op_type not in operator_map: + raise ValueError(f"Unsupported operator '{op_type.__name__}'.") + return operator_map[op_type](col, value) + + # Recursive Step: "Bitwise" operation & and | (the same as boolean operations) + elif isinstance(node, ast.BinOp): + if isinstance(node.op, ast.BitOr): + return _evaluate_node(df, node.left) | _evaluate_node(df, node.right) + elif isinstance(node.op, ast.BitAnd): + return _evaluate_node(df, node.left) & _evaluate_node(df, node.right) + + # Recursive Step: A boolean operation like '... and ...' or '... or ...' + elif isinstance(node, ast.BoolOp): + op_type = type(node.op) + # Evaluate the first value in the boolean expression + result = _evaluate_node(df, node.values[0]) + # Combine it with the rest of the values based on the operator + for i in range(1, len(node.values)): + if op_type is ast.And or op_type is ast.BitAnd: + result &= _evaluate_node(df, node.values[i]) + elif op_type is ast.Or or op_type is ast.BitOr: + result |= _evaluate_node(df, node.values[i]) + return result + + elif isinstance(node, ast.UnaryOp): + if not isinstance(node.op, ast.Not): + raise ValueError("Only supported unary op is negation.") + return ~_evaluate_node(df, node.operand) + + # If the node is not a comparison or boolean op, it's an unsupported expression type + else: + raise ValueError(f"Unsupported expression type: {type(node).__name__}") + + +def parse_and_filter(df, filter_str): + """ + Filters a pandas DataFrame using a string expression parsed by AST. + This is done to avoid the security vulnerables that `DataFrame.query` + brings (arbitrary code execution). + + Args: + df (pd.DataFrame): The DataFrame to filter. + filter_str (str): A string representing a filter expression. + e.g., "price > 100 and stock < 50" + Supported operators: >, >=, <, <=, ==, !=, in, not in, and, or. + + Returns: + pd.Series: A boolean Series representing the filter mask. + """ + if not filter_str: + return pd.Series([True] * len(df), index=df.index) + + try: + # 'eval' mode ensures the source is a single expression. + tree = ast.parse(filter_str, mode='eval') + expression_node = tree.body + except (SyntaxError, ValueError) as e: + raise ValueError(f"Invalid filter syntax: {e}") + + # The recursive evaluation starts here + mask = _evaluate_node(df, expression_node) + return mask diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/test_sanitizer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/test_sanitizer.py new file mode 100644 index 0000000000000000000000000000000000000000..59c0dd191e887aaeebbfce9dff9e88e6be0e2152 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/test_sanitizer.py @@ -0,0 +1,38 @@ +import pandas as pd +import pytest + +from .sanitizer import parse_and_filter + + +@pytest.fixture +def df_products(): + data = { + 'product_id': [101, 102, 103, 104, 105, 106], + 'category': ['Electronics', 'Books', 'Electronics', 'Home Goods', 'Books', 'Electronics'], + 'price': [799.99, 19.99, 49.50, 120.00, 24.99, 150.00], + 'stock': [15, 300, 50, 25, 150, 0] + } + return pd.DataFrame(data) + + +def test_exploit_fails(df_products): + with pytest.raises(ValueError) as e: + mask1 = parse_and_filter(df_products, + """price < 50 and @os.system("/bin/echo password")""") + assert 'Invalid filter syntax' in str(e) + + +@pytest.mark.parametrize('expression,ids', [ + ("price < 50", [102, 103, 105]), + ("product_id in [101, 102]", [101, 102]), + ("price < 50 and category == 'Electronics'", [103]), + ("stock < 100 or category == 'Home Goods'", [101, 103, 104, 106]), + ("(price > 100 and stock < 20) or category == 'Books'", [101, 102, 105, 106]), + ("not (price > 50 or stock > 100)", [103]), + ("not price > 50", [102, 103, 105]), + ("(price < 50) & (category == 'Electronics')", [103]), + ("(stock < 100) | (category == 'Home Goods')", [101, 103, 104, 106]), +]) +def test_operations(df_products, expression, ids): + mask1 = parse_and_filter(df_products, expression) + assert sorted(df_products[mask1].product_id) == sorted(ids) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/README.md b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9f727fbf7276fa42501d65fca364b6201d1e0c57 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/README.md @@ -0,0 +1,179 @@ +## Base Model Inference Caching + +The benchmarking suite uses a separate script, `run_base.py`, to measure base model inference times and save results for reuse. This should be run once per model configuration to avoid redundant computations and ensure consistent baseline metrics for all PEFT experiments. + +**Usage:** +```bash +python run_base.py +``` +This will cache the base model inference results for the specified configuration. Subsequent runs of `run.py` will automatically load these cached results. + +# PEFT Benchmarking Suite + +This directory contains a comprehensive benchmarking framework for Parameter-Efficient Fine-Tuning (PEFT) methods. For the task of text generation, the suite measures inference performance, memory usage, and other key metrics across different PEFT configurations. + +## Overview + +The benchmarking suite provides: +- **Inference time measurement** across different prompt categories +- **Memory usage during inference** (RAM and GPU) +- **Parameter efficiency metrics** (trainable vs total parameters) +- **Time per token analysis** for fair comparison across different generation lengths +- **Structured result logging** with detailed metadata + +## Architecture + +The suite follows a clean separation between: +1. **Default benchmark configuration** - shared settings for consistent comparison +2. **Individual adapter configurations** - PEFT-specific parameters for each experiment + +This ensures that all experiments are comparable while allowing flexibility in adapter parameters. + +## Quick Start + +### Running a Single Experiment + +```bash +# From the peft_bench directory +python run.py experiments/lora/lora_r8 --verbose +``` + +## Configuration Structure + +The benchmarking suite uses a hierarchical configuration system: + +1. **Default benchmark parameters** (`default_benchmark_params.json`) - Base configuration shared by all experiments +2. **Experiment-specific overrides** (`benchmark_params.json` in each experiment) - Optional overrides for specific experiments +3. **Adapter configuration** (`adapter_config.json` in each experiment) - PEFT method parameters + +This structure ensures consistent comparison while allowing flexibility where needed. + +### Default Configuration (`default_benchmark_params.json`) + +Contains shared benchmark settings that apply to all experiments. Here are the key configuration fields: + +- `model_id`: The Hugging Face model ID to use as the base model (e.g., "facebook/opt-350m") +- `dtype`: Model precision ("float16", "float32", or "bfloat16") +- `seed`: Random seed for reproducibility +- `max_new_tokens`: Maximum number of tokens to generate during inference +- `num_inference_runs`: Number of inference runs per prompt for statistical reliability +- `use_4bit`: Whether to use 4-bit quantization (bool) +- `use_8bit`: Whether to use 8-bit quantization (bool) + +Each experiment can override these settings by providing its own `benchmark_params.json` file. + +### Experiment Structure + +Each experiment directory should contain: + +1. `adapter_config.json`: PEFT adapter configuration. For details on available parameters and their meanings, refer to the [PEFT documentation](https://huggingface.co/docs/peft/main/en/developer_guides/adapters). + +2. (Optional) `benchmark_params.json`: Override specific benchmark parameters for this experiment. + +Example directory structure: +``` +experiments/ +└── lora/ + ├── lora_r8/ # LoRA rank 8 experiment + │ ├── adapter_config.json # PEFT adapter configuration + │ └── benchmark_params.json # Optional benchmark overrides + └── lora_r16/ # LoRA rank 16 experiment + └── adapter_config.json +``` + +### Experiment-Specific Overrides Example + +If an experiment needs different benchmark settings, create `benchmark_params.json`: +```json +{ + "_comment": "Override settings for this specific experiment", + "max_new_tokens": 50, + "num_inference_runs": 15, + "num_prompt_samples": 2 +} +``` + +These parameters will override the defaults from `default_benchmark_params.json`. However, the defaults should generally not be changed to keep the results from the individual experiments comparable. + +### Create a New Experiment Adapter Configuration + +To create a new experiment, follow these steps: + +1. **Create the experiment directory** + ```bash + mkdir -p experiments/lora/lora_r8 + ``` + +2. **Generate the adapter configuration programmatically** + Use the PEFT library to create and save your adapter config: + + ```python + from peft import LoraConfig + + config = LoraConfig( + lora_alpha=16, + lora_dropout=0.1, + r=8, + target_modules=["q_proj", "v_proj"], + task_type="CAUSAL_LM" + ) + config.save_pretrained("experiments/lora/lora_r8") + ``` + + This will create an `adapter_config.json` in your experiment directory. Adjust parameters as needed for your experiment. + +3. **(Optional) Add benchmark overrides** + If you need to override default benchmark settings, create a `benchmark_params.json` in the same directory. + +4. **Run the benchmark** + ```bash + python run.py experiments/lora/lora_r8 --verbose + ``` + +## Prompt Categories + +The benchmark automatically runs across all prompt categories for consistent comparison: +- **short** - Brief prompts (1-2 sentences) +- **medium** - Moderate length prompts (paragraph-level) +- **long** - Extended prompts (multiple paragraphs) + +Results are tracked separately for each category, allowing analysis of how different PEFT methods perform across varying input lengths. + +## Results Structure + +Results are saved in a structured JSON format with three main sections: + +### `run_info` +- Execution metadata (timestamp, duration, status) +- Hardware information (GPU type, CUDA version, etc.) +- Error information (if applicable) +- PEFT and benchmark configurations + +### `generation_info` +- Memory usage logs at different stages +- Per-category metrics (inference time, time per token, etc.) +- Overall aggregated metrics +- Individual sample results for detailed analysis + +### `meta_info` +- Model information (ID, PEFT method) +- Parameter counts (adapter, total, ratio) +- Model size information (base model, adapter) +- System and package information + +## Key Metrics + +### Inference Performance +- **Inference Time**: Total time for generation per category +- **Time Per Token**: Normalized time accounting for different generation lengths +- **Inference Overhead**: Percentage increase compared to base model + +### Memory Usage +- **Peak GPU Memory**: Maximum GPU memory during benchmark +- **Peak RAM Memory**: Maximum RAM usage +- **Memory Logs**: Detailed tracking at each stage + +### Parameter Efficiency +- **Adapter Parameters**: Number of parameters in the PEFT adapter +- **Parameter Ratio**: Percentage of total model parameters that are in the adapter +- **Adapter Size**: Memory footprint of the adapter in MB diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/cancelled_results/.gitkeep b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/cancelled_results/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/configs/prompts.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/configs/prompts.json new file mode 100644 index 0000000000000000000000000000000000000000..7768b420a0ff49511be9e689e659fb2c97022207 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/configs/prompts.json @@ -0,0 +1,23 @@ +{ + "short": [ + "Explain quantum computing in one paragraph.", + "Write a haiku about machine learning.", + "What's the difference between supervised and unsupervised learning?", + "Define parameter-efficient fine-tuning in one sentence.", + "List three applications of natural language processing." + ], + "medium": [ + "Explain the concept of low-rank adaptation (LoRA) for large language models. Include its benefits and limitations.", + "Compare and contrast prompt tuning and prefix tuning approaches for adapting large language models.", + "What are the key differences between full fine-tuning and parameter-efficient methods? Explain with examples.", + "Describe the process of quantization for neural networks and how it affects model size and inference speed.", + "Explain how sparse expert models like Mixture of Experts work and their advantages over dense models." + ], + "long": [ + "Analyze the evolution of parameter-efficient fine-tuning methods from 2020 to present. Include a detailed comparison of at least five different approaches, their theoretical foundations, and practical implications for deploying large language models.", + "Provide a comprehensive tutorial on implementing LoRA for a transformer-based language model. Include code examples, hyperparameter selection guidance, and best practices for training and deployment.", + "Compare the computational efficiency, parameter count, and performance characteristics of different PEFT methods (LoRA, Prefix Tuning, Prompt Tuning, IA3, AdaLoRA) across various downstream tasks. Include a discussion of when each method is most appropriate.", + "Explain the mathematical foundations of various parameter-efficient fine-tuning techniques. Discuss how each technique modifies the original neural network architecture and the optimization challenges involved.", + "Discuss the ethical implications of parameter-efficient fine-tuning methods in democratizing access to large language models. Include considerations about computational resources, environmental impact, and accessibility for researchers in resource-constrained settings." + ] +} \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/data.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/data.py new file mode 100644 index 0000000000000000000000000000000000000000..ce3343f1ca63a74908395d8789da6d58491efc4f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/data.py @@ -0,0 +1,119 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Data handling utilities for PEFT benchmarking. +""" + +import json +import os +from typing import Optional + +from transformers import PreTrainedTokenizer +from utils import BenchmarkConfig + + +DEFAULT_PROMPTS_PATH = os.path.join(os.path.dirname(__file__), "configs", "prompts.json") + + +def load_test_prompts(config: dict) -> dict[str, list[str]]: + """ + Load prompts from JSON file. + + Args: + config: Configuration containing prompts file path + + Returns: + dictionary with prompts by category + """ + prompts_file = getattr(config, "prompts_file", DEFAULT_PROMPTS_PATH) + + with open(prompts_file) as f: + prompts = json.load(f) + + return prompts + + +def truncate_prompt_for_model( + prompt: str, + tokenizer: PreTrainedTokenizer, + max_length: Optional[int] = None, + reserve_output_tokens: int = 50, +) -> str: + """ + Truncate a prompt to fit within the model's context window. + + Args: + prompt: Input prompt + tokenizer: Model tokenizer + max_length: Maximum sequence length (if None, uses model's max_length) + reserve_output_tokens: Number of tokens to reserve for response + + Returns: + Truncated prompt + """ + if max_length is None: + if hasattr(tokenizer, "model_max_length"): + max_length = tokenizer.model_max_length + else: + max_length = 2048 + + max_prompt_length = max_length - reserve_output_tokens + input_ids = tokenizer.encode(prompt, return_tensors="pt")[0] + + if len(input_ids) <= max_prompt_length: + return prompt + + truncated_ids = input_ids[:max_prompt_length] + truncated_prompt = tokenizer.decode(truncated_ids, skip_special_tokens=True) + + return truncated_prompt + + +def prepare_benchmark_prompts( + config: BenchmarkConfig, + tokenizer: PreTrainedTokenizer, + max_input_length: Optional[int] = None, + seed: int = 42, +) -> dict[str, list[str]]: + """ + Prepare prompts for benchmarking, ensuring appropriate length and variety. + Always returns all prompt categories for consistent benchmarking. + + Args: + config: Benchmark configuration + tokenizer: Model tokenizer + max_input_length: Maximum input length (overrides model default if provided) + seed: Random seed (kept for backwards compatibility) + + Returns: + Dictionary with processed prompts by category (all categories included) + """ + all_prompts = load_test_prompts(config) + + processed_prompts = {} + for category, prompts in all_prompts.items(): + truncated_prompts = [ + truncate_prompt_for_model( + prompt, + tokenizer, + max_length=max_input_length, + reserve_output_tokens=getattr(config, "reserve_output_tokens", 50), + ) + for prompt in prompts + ] + + processed_prompts[category] = truncated_prompts + + return processed_prompts diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/default_benchmark_params.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/default_benchmark_params.json new file mode 100644 index 0000000000000000000000000000000000000000..c7d9a148e53d5975b66c641e3f6269519cc7bb82 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/default_benchmark_params.json @@ -0,0 +1,12 @@ +{ + "model_id": "meta-llama/Llama-3.2-3B", + "dtype": "float16", + "seed": 42, + "num_inference_runs": 10, + "max_new_tokens": 20, + "category_generation_params": { + "short": {"max_new_tokens": 20}, + "medium": {"max_new_tokens": 50}, + "long": {"max_new_tokens": 100} + } +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/experiments/lora/lora_r8/adapter_config.json b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/experiments/lora/lora_r8/adapter_config.json new file mode 100644 index 0000000000000000000000000000000000000000..f3fd26121a544399ccc14f9cbb017a7ba3abeac2 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/experiments/lora/lora_r8/adapter_config.json @@ -0,0 +1,17 @@ +{ + "base_model_name_or_path": null, + "bias": "none", + "fan_in_fan_out": false, + "inference_mode": false, + "init_lora_weights": true, + "lora_alpha": 16, + "lora_dropout": 0.1, + "modules_to_save": null, + "peft_type": "LORA", + "r": 8, + "target_modules": [ + "q_proj", + "v_proj" + ], + "task_type": "CAUSAL_LM" +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/results/.gitkeep b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/results/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/run.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/run.py new file mode 100644 index 0000000000000000000000000000000000000000..1cfba8931f29cf8571a89253859781a16e2203a8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/run.py @@ -0,0 +1,358 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Main entry point to run the experiments. Contains general setup and the proper inference code. +""" + +import argparse +import gc +import json +import os +import sys +import time +from typing import Optional + +import bitsandbytes +import torch +import transformers +from data import prepare_benchmark_prompts +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, set_seed +from utils import ( + BenchmarkConfig, + BenchmarkResult, + BenchmarkStatus, + get_memory_usage, + init_accelerator, + log_results, + validate_experiment_path, +) + +import peft +from peft import PeftConfig, get_peft_model + + +def load_base_results(model_id: str) -> Optional[dict]: + """Load base model results if they exist.""" + base_results_dir = os.path.join(os.path.dirname(__file__), "base_results") + model_name = model_id.replace("/", "_").replace("-", "_") + filename = f"base_{model_name}.json" + filepath = os.path.join(base_results_dir, filename) + + if os.path.exists(filepath): + with open(filepath) as f: + return json.load(f) + return None + + +def measure_inference_time(model, tokenizer, prompts, max_new_tokens, num_runs, print_fn, category_generation_params): + """Measure inference time for each prompt category.""" + inference_times = {} + time_per_token = {} + generated_tokens = {} + individual_samples = {} + + for category, category_prompts in prompts.items(): + print_fn(f"\nMeasuring inference time for {category} prompts...") + category_times = [] + category_tokens = [] + category_time_per_token = [] + category_samples = [] + + for prompt in category_prompts: + prompt_times = [] + prompt_tokens = [] + prompt_time_per_token = [] + + inputs = tokenizer(prompt, return_tensors="pt").to(model.device) + + cat_max_new_tokens = category_generation_params.get(category, {}).get("max_new_tokens", max_new_tokens) + + for _ in range(num_runs): + start_time = time.perf_counter() + outputs = model.generate( + **inputs, + max_new_tokens=cat_max_new_tokens, + min_new_tokens=cat_max_new_tokens, + pad_token_id=tokenizer.pad_token_id, + ) + end_time = time.perf_counter() + + # Calculate metrics + inference_time = end_time - start_time + num_tokens = len(outputs[0]) - len(inputs["input_ids"][0]) + time_per_token_val = inference_time / num_tokens if num_tokens > 0 else 0 + + prompt_times.append(inference_time) + prompt_tokens.append(num_tokens) + prompt_time_per_token.append(time_per_token_val) + + # Calculate averages for this prompt + avg_time = sum(prompt_times) / len(prompt_times) + avg_tokens = sum(prompt_tokens) / len(prompt_tokens) + avg_time_per_token = sum(prompt_time_per_token) / len(prompt_time_per_token) + + sample_result = { + "inference_time": avg_time, + "generated_tokens": avg_tokens, + "time_per_token": avg_time_per_token, + "individual_runs": [ + {"inference_time": t, "generated_tokens": tok, "time_per_token": tpt} + for t, tok, tpt in zip(prompt_times, prompt_tokens, prompt_time_per_token) + ], + } + category_samples.append(sample_result) + + category_times.append(avg_time) + category_tokens.append(avg_tokens) + category_time_per_token.append(avg_time_per_token) + + if category_times: + avg_category_time = sum(category_times) / len(category_times) + avg_category_tokens = sum(category_tokens) / len(category_tokens) + avg_category_time_per_token = sum(category_time_per_token) / len(category_time_per_token) + + inference_times[category] = avg_category_time + generated_tokens[category] = avg_category_tokens + time_per_token[category] = avg_category_time_per_token + individual_samples[category] = category_samples + + return { + "inference_times": inference_times, + "time_per_token": time_per_token, + "generated_tokens": generated_tokens, + "individual_samples": individual_samples, + } + + +def run_benchmark( + benchmark_config: BenchmarkConfig, experiment_name: str, experiment_path: str, print_fn=print +) -> BenchmarkResult: + """Run benchmarks for the specified PEFT method configuration.""" + result = BenchmarkResult( + experiment_name=experiment_name, + status=BenchmarkStatus.RUNNING, + model_id=benchmark_config.model_id, + ) + + result.save() + + start_time = time.perf_counter() + e_main_benchmark: Optional[Exception] = None + + try: + print_fn("Initializing accelerator...") + accelerator_allocated_init, accelerator_reserved_init = init_accelerator() + set_seed(benchmark_config.seed) + + print_fn(f"Loading base model: {benchmark_config.model_id}") + tokenizer = AutoTokenizer.from_pretrained(benchmark_config.model_id) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + model_kwargs = { + "device_map": "auto" if (torch.cuda.is_available() or torch.xpu.is_available()) else None, + } + + if benchmark_config.dtype == "float32": + model_kwargs["torch_dtype"] = torch.float32 + elif benchmark_config.dtype == "float16": + model_kwargs["torch_dtype"] = torch.float16 + elif benchmark_config.dtype == "bfloat16": + model_kwargs["torch_dtype"] = torch.bfloat16 + else: + raise ValueError(f"Unsupported dtype: {benchmark_config.dtype}") + + if benchmark_config.use_8bit: + model_kwargs["quantization_config"] = BitsAndBytesConfig( + load_in_8bit=True, llm_int8_enable_fp32_cpu_offload=True + ) + elif benchmark_config.use_4bit: + model_kwargs["quantization_config"] = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=model_kwargs.get("torch_dtype", torch.float16), + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + ) + + base_model = AutoModelForCausalLM.from_pretrained(benchmark_config.model_id, **model_kwargs) + + base_results = load_base_results(benchmark_config.model_id) + + print_fn("Preparing benchmark prompts...") + prompts = prepare_benchmark_prompts( + config=benchmark_config, + tokenizer=tokenizer, + max_input_length=None, + seed=benchmark_config.seed, + ) + + if base_results: + print_fn("Using cached base model results...") + base_inference_times = base_results["inference_results"] + else: + raise FileNotFoundError( + "No cached base results found. Please run `python run_base.py` first to generate base model results." + ) + + try: + print_fn(f"Loading PEFT config from {experiment_path}") + peft_config = PeftConfig.from_pretrained(experiment_path) + print_fn(f"Loaded PEFT config: {peft_config.peft_type}, with parameters: {vars(peft_config)}") + model = get_peft_model(base_model, peft_config) + except Exception as exc: + error_msg = f"Error loading PEFT config: {str(exc)}" + print_fn(error_msg) + + del base_model + gc.collect() + if torch.cuda.is_available(): + torch.cuda.empty_cache() + elif torch.xpu.is_available(): + torch.xpu.empty_cache() + + ram, accelerator_allocated, accelerator_reserved = get_memory_usage() + result.add_memory_log("peft_model_loaded", ram, accelerator_allocated, accelerator_reserved) + + # Calculate PEFT model metrics + trainable_params = model.get_nb_trainable_parameters()[0] + total_params = sum(p.numel() for p in model.parameters()) + base_params = sum(p.numel() for p in model.base_model.parameters()) + dtype_bytes = 2 if benchmark_config.dtype in ["float16", "bfloat16"] else 4 + adapter_size_mb = trainable_params * dtype_bytes / (1024 * 1024) + base_model_size_mb = base_params * dtype_bytes / (1024 * 1024) + param_ratio = trainable_params / total_params if total_params > 0 else 0 + + result.update_meta_info( + param_counts={ + "base_params": base_params, + "trainable_params": trainable_params, + "total_params": total_params, + "param_ratio": param_ratio, + }, + size_info={"base_model_size_mb": base_model_size_mb, "adapter_size_mb": adapter_size_mb}, + package_info={ + "transformers-version": transformers.__version__, + "peft-version": peft.__version__, + "bitsandbytes-version": bitsandbytes.__version__ if hasattr(bitsandbytes, "__version__") else None, + }, + ) + + print_fn("Measuring PEFT model inference times...") + peft_inference_times = measure_inference_time( + model, + tokenizer, + prompts, + max_new_tokens=benchmark_config.max_new_tokens, + num_runs=benchmark_config.num_inference_runs, + print_fn=print_fn, + category_generation_params=benchmark_config.category_generation_params, + ) + + # Calculate inference overhead for each category + inference_overhead = { + k: (peft_inference_times["inference_times"][k] - base_inference_times["inference_times"][k]) + / base_inference_times["inference_times"][k] + * 100 + for k in base_inference_times["inference_times"] + } + + for category in prompts: + category_metrics = { + "inference_time": peft_inference_times["inference_times"][category], + "base_inference_time": base_inference_times["inference_times"][category], + "inference_overhead_pct": inference_overhead[category], + "time_per_token": peft_inference_times["time_per_token"][category], + "generated_tokens": peft_inference_times["generated_tokens"][category], + } + result.add_metrics_for_category( + category, category_metrics, individual_samples=peft_inference_times["individual_samples"][category] + ) + + result.update_generation_info( + memory_data={ + "peak_accelerator_memory_mb": max( + (log["accelerator_allocated_mb"] for log in result.generation_info["memory"]["memory_logs"]), default=0 + ), + "peak_ram_memory_mb": max( + (log["ram_mb"] for log in result.generation_info["memory"]["memory_logs"]), default=0 + ), + } + ) + + ram, accelerator_allocated, accelerator_reserved = get_memory_usage() + result.add_memory_log("benchmark_complete", ram, accelerator_allocated, accelerator_reserved) + + result.status = BenchmarkStatus.SUCCESS + + except Exception as exc: + print_fn(f"Benchmark failed with error: {exc}") + result.status = BenchmarkStatus.FAILED + e_main_benchmark = exc + end_time = time.perf_counter() + error_message = str(e_main_benchmark) if e_main_benchmark is not None else None + + peft_config_dict = peft_config.to_dict() if "peft_config" in locals() else None + if peft_config_dict: + for key, value in peft_config_dict.items(): + if isinstance(value, set): + peft_config_dict[key] = list(value) + + result.update_run_info( + duration=end_time - start_time, + status=result.status, + error=error_message, + peft_config=peft_config_dict, + benchmark_config=benchmark_config.to_dict(), + ) + + return result + + +def main() -> None: + """Main entry point for the benchmark runner.""" + parser = argparse.ArgumentParser(description="Run PEFT method benchmarks") + parser.add_argument("experiment_path", help="Path to experiment directory") + parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose output") + args = parser.parse_args() + + print_fn = print if args.verbose else lambda *args, **kwargs: None + + experiment_path = args.experiment_path + allowed_root = os.path.abspath(os.path.join(os.path.dirname(__file__))) + abs_experiment_path = os.path.abspath(experiment_path) + if not abs_experiment_path.startswith(allowed_root): + print(f"Experiment path must be inside {allowed_root}, got: {abs_experiment_path}. Skipping execution.") + return 0 + if not os.path.exists(abs_experiment_path): + print(f"Experiment path not found: {abs_experiment_path}. Skipping execution.") + return 0 + experiment_path = abs_experiment_path + + experiment_name, benchmark_config = validate_experiment_path(experiment_path) + + print_fn(f"Running benchmark for experiment: {experiment_name}") + + result = run_benchmark( + benchmark_config=benchmark_config, + experiment_name=experiment_name, + experiment_path=experiment_path, + print_fn=print_fn, + ) + + log_results(experiment_name, result, print_fn=print) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/run_base.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/run_base.py new file mode 100644 index 0000000000000000000000000000000000000000..1489cff08786e76473bcdcd237afd365594d9a63 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/run_base.py @@ -0,0 +1,185 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import json +import os +import sys +import time + +import torch +from data import prepare_benchmark_prompts +from run import measure_inference_time +from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig, set_seed +from utils import ( + BenchmarkConfig, + get_memory_usage, + init_accelerator, +) + + +def run_base_model_benchmark(benchmark_config: BenchmarkConfig, print_fn=print) -> dict: + """Run benchmark for base model only and return results.""" + + print_fn(f"Running base model benchmark for: {benchmark_config.model_id}") + + print_fn("Initializing accelerator...") + init_accelerator() + + set_seed(benchmark_config.seed) + + print_fn(f"Loading base model: {benchmark_config.model_id}") + tokenizer = AutoTokenizer.from_pretrained(benchmark_config.model_id) + if tokenizer.pad_token is None: + tokenizer.pad_token = tokenizer.eos_token + + model_kwargs = { + "device_map": "auto" if (torch.cuda.is_available() or torch.xpu.is_available()) else None, + } + + if benchmark_config.dtype == "float32": + model_kwargs["torch_dtype"] = torch.float32 + elif benchmark_config.dtype == "float16": + model_kwargs["torch_dtype"] = torch.float16 + elif benchmark_config.dtype == "bfloat16": + model_kwargs["torch_dtype"] = torch.bfloat16 + + if benchmark_config.use_8bit: + model_kwargs["quantization_config"] = BitsAndBytesConfig( + load_in_8bit=True, llm_int8_enable_fp32_cpu_offload=True + ) + elif benchmark_config.use_4bit: + model_kwargs["quantization_config"] = BitsAndBytesConfig( + load_in_4bit=True, + bnb_4bit_compute_dtype=model_kwargs.get("torch_dtype", torch.float16), + bnb_4bit_use_double_quant=True, + bnb_4bit_quant_type="nf4", + ) + + model = AutoModelForCausalLM.from_pretrained(benchmark_config.model_id, **model_kwargs) + + ram, accelerator_allocated, accelerator_reserved = get_memory_usage() + print_fn(f"Memory after model load - RAM: {ram:.2f}MB, {model.device.type.upper()}: {accelerator_allocated:.2f}MB") + + print_fn("Preparing benchmark prompts...") + prompts = prepare_benchmark_prompts( + config=benchmark_config.to_dict(), + tokenizer=tokenizer, + max_input_length=None, + seed=benchmark_config.seed, + ) + + # Measure base model inference for each prompt category + print_fn("Measuring base model inference times...") + base_inference_results = measure_inference_time( + model, + tokenizer, + prompts, + max_new_tokens=benchmark_config.max_new_tokens, + num_runs=benchmark_config.num_inference_runs, + print_fn=print_fn, + category_generation_params=benchmark_config.category_generation_params, + ) + + result = { + "model_id": benchmark_config.model_id, + "benchmark_config": benchmark_config.to_dict(), + "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), + "inference_results": base_inference_results, + "memory_info": { + "ram_mb": ram, + "accelerator_allocated_mb": accelerator_allocated, + "accelerator_reserved_mb": accelerator_reserved, + }, + } + + return result + + +def save_base_results(result: dict, model_id: str) -> str: + """Save base model results with a filename based on model and config.""" + base_results_dir = os.path.join(os.path.dirname(__file__), "base_results") + os.makedirs(base_results_dir, exist_ok=True) + + model_name = model_id.replace("/", "_").replace("-", "_") + filename = f"base_{model_name}.json" + filepath = os.path.join(base_results_dir, filename) + + with open(filepath, "w") as f: + json.dump(result, f, indent=2) + + return filepath + + +def main(): + """Main entry point for the base model benchmark runner.""" + parser = argparse.ArgumentParser(description="Run base model benchmarks") + parser.add_argument("--verbose", "-v", action="store_true", help="Enable verbose output") + parser.add_argument("--force", "-f", action="store_true", help="Force re-run even if results exist") + args = parser.parse_args() + + print_fn = print if args.verbose else lambda *args, **kwargs: None + + default_config_path = os.path.join(os.path.dirname(__file__), "default_benchmark_params.json") + benchmark_config = BenchmarkConfig.from_json(default_config_path) + + model_name = benchmark_config.model_id.replace("/", "_").replace("-", "_") + base_results_dir = os.path.join(os.path.dirname(__file__), "base_results") + filename = f"base_{model_name}.json" + filepath = os.path.join(base_results_dir, filename) + + if os.path.exists(filepath) and not args.force: + print(f"Base results already exist at: {filepath}") + print("Use --force to re-run the benchmark") + return 0 + + print_fn(f"Running base model benchmark for: {benchmark_config.model_id}") + + result = run_base_model_benchmark(benchmark_config, print_fn=print_fn) + + saved_path = save_base_results(result, benchmark_config.model_id) + device_type = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" + print(f"Base model results saved to: {saved_path}") + + print("\nBase Model Benchmark Summary:") + print(f"Model: {result['model_id']}") + print( + f"Memory Usage - RAM: {result['memory_info']['ram_mb']:.2f}MB, {device_type.upper()}: {result['memory_info']['accelerator_allocated_mb']:.2f}MB" + ) + + print("\nInference Times by Category:") + for category, time_val in result["inference_results"]["inference_times"].items(): + time_per_token = result["inference_results"]["time_per_token"][category] + tokens = result["inference_results"]["generated_tokens"][category] + print(f" {category}: {time_val:.4f}s ({time_per_token:.6f}s/token, {tokens:.1f} tokens)") + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/temporary_results/.gitkeep b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/temporary_results/.gitkeep new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..de58427fa696a04065fb56d7a677d262600f07da --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/method_comparison/text_generation_benchmark/utils.py @@ -0,0 +1,457 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Utilities for PEFT benchmarking. +""" + +import datetime +import json +import os +import platform +import subprocess +from dataclasses import asdict, dataclass, field +from enum import Enum +from typing import Any, Callable, Optional + +import psutil +import torch + +from peft.utils import infer_device + + +FILE_NAME_BENCHMARK_PARAMS = "benchmark_params.json" +FILE_NAME_DEFAULT_CONFIG = "default_benchmark_params.json" + +RESULT_PATH = os.path.join(os.path.dirname(__file__), "results") +RESULT_PATH_TEMP = os.path.join(os.path.dirname(__file__), "temporary_results") +RESULT_PATH_CANCELLED = os.path.join(os.path.dirname(__file__), "cancelled_results") + + +class BenchmarkStatus(Enum): + """Status of a benchmark run.""" + + SUCCESS = "success" + FAILED = "failed" + CANCELLED = "cancelled" + RUNNING = "running" + + +@dataclass +class BenchmarkResult: + """Container for benchmark results.""" + + experiment_name: str + status: BenchmarkStatus + + model_id: str + + run_info: dict = field(default_factory=dict) + generation_info: dict = field(default_factory=dict) + meta_info: dict = field(default_factory=dict) + + def __post_init__(self): + """Initialize structured data format.""" + device = infer_device() + torch_accelerator_module = getattr(torch, device, torch.cuda) + self.run_info = { + "timestamp": datetime.datetime.now(tz=datetime.timezone.utc).isoformat(), + "duration": 0.0, + "status": self.status.value, + "hardware": { + "num_accelerators": torch_accelerator_module.device_count() if torch_accelerator_module.is_available() else 0, + "accelerator_type": torch_accelerator_module.get_device_name(0) if torch_accelerator_module.is_available() else "N/A", + "cuda_version": torch.version.cuda if torch.cuda.is_available() else "N/A", + "pytorch_version": torch.__version__, + }, + } + + self.meta_info = { + "model_id": self.model_id, + "parameters": { + "base_params": 0, + "trainable_params": 0, + "total_params": 0, + "param_ratio": 0.0, + }, + "model_size": { + "base_model_size_mb": 0.0, + "adapter_size_mb": 0.0, + }, + "package_info": { + "transformers-version": None, + "transformers-commit-hash": None, + "peft-version": None, + "peft-commit-hash": None, + "datasets-version": None, + "datasets-commit-hash": None, + "bitsandbytes-version": None, + "bitsandbytes-commit-hash": None, + "torch-version": torch.__version__, + "torch-commit-hash": None, + }, + "system_info": { + "system": platform.system(), + "release": platform.release(), + "version": platform.version(), + "machine": platform.machine(), + "processor": platform.processor(), + "accelerator": torch_accelerator_module.get_device_name(0) if torch_accelerator_module.is_available() else "N/A", + }, + } + + self.generation_info = { + "memory": { + "peak_accelerator_memory_mb": 0.0, + "peak_ram_memory_mb": 0.0, + "memory_logs": [], + }, + "by_category": {}, + "overall": {}, + } + + def update_meta_info(self, param_counts: dict, size_info: dict, package_info: Optional[dict] = None): + """Update model metadata information.""" + self.meta_info["parameters"].update(param_counts) + self.meta_info["model_size"].update(size_info) + if package_info: + self.meta_info["package_info"].update(package_info) + + def update_generation_info(self, memory_data: Optional[dict] = None, performance_metrics: Optional[dict] = None): + """Update generation performance information, primarily for memory and high-level performance.""" + if memory_data: + self.generation_info["memory"].update(memory_data) + if performance_metrics: # For things like overall tokens/sec if calculated + self.generation_info.update(performance_metrics) + + def add_memory_log(self, stage: str, ram_mb: float, accelerator_allocated_mb: float, accelerator_reserved_mb: float): + """Add a memory usage log entry to generation_info.""" + self.generation_info["memory"]["memory_logs"].append( + { + "stage": stage, + "ram_mb": ram_mb, + "accelerator_allocated_mb": accelerator_allocated_mb, + "accelerator_reserved_mb": accelerator_reserved_mb, + } + ) + + def add_metrics_for_category(self, category: str, metrics: dict, individual_samples: list = None): + """Add metrics for a specific prompt category under generation_info.""" + category_data = {"metrics": metrics, "samples": individual_samples if individual_samples is not None else []} + self.generation_info["by_category"][category] = category_data + + def update_run_info( + self, + duration: float, + status: BenchmarkStatus, + error: Optional[str] = None, + peft_config: Optional[dict] = None, + benchmark_config: Optional[dict] = None, + ): + """Update run information.""" + self.run_info["duration"] = duration + self.run_info["status"] = status.value + if error: + self.run_info["error"] = error + if peft_config: + self.run_info["peft_config"] = peft_config + if benchmark_config: + self.run_info["benchmark_config"] = benchmark_config + + def compute_overall_metrics(self): + """Compute overall metrics across all categories within generation_info.""" + if not self.generation_info["by_category"]: + return + + categories = self.generation_info["by_category"] + key_metrics = [ + "inference_time", + "base_inference_time", + "inference_overhead_pct", + "time_per_token", + "generated_tokens", + ] + + for metric in key_metrics: + values = [] + for category_data in categories.values(): + if "metrics" in category_data and metric in category_data["metrics"]: + values.append(category_data["metrics"][metric]) + + if values: + self.generation_info["overall"][metric] = sum(values) / len(values) + + def to_dict(self) -> dict[str, Any]: + """Convert result to dictionary.""" + self.compute_overall_metrics() + return { + "run_info": self.run_info, + "generation_info": self.generation_info, + "meta_info": self.meta_info, + } + + def save(self, path: Optional[str] = None): + """Save result to JSON file.""" + if path is None: + peft_branch = get_peft_branch() + if self.status == BenchmarkStatus.CANCELLED: + base_path = RESULT_PATH_CANCELLED + elif peft_branch != "main": + base_path = RESULT_PATH_TEMP + elif self.status == BenchmarkStatus.SUCCESS: + base_path = RESULT_PATH + elif self.status == BenchmarkStatus.FAILED: + base_path = RESULT_PATH_CANCELLED + else: + base_path = RESULT_PATH_TEMP + + filename = f"{self.experiment_name}.json" + path = os.path.join(base_path, filename) + + os.makedirs(os.path.dirname(path), exist_ok=True) + + with open(path, "w") as f: + json.dump(self.to_dict(), f, indent=2) + + return path + + +@dataclass +class BenchmarkConfig: + """Configuration for benchmarking PEFT methods.""" + + model_id: str + + seed: int + num_inference_runs: int + max_new_tokens: int + + dtype: str = "float16" + use_4bit: bool = False + use_8bit: bool = False + + category_generation_params: Optional[dict] = None + + def __post_init__(self) -> None: + """Validate configuration.""" + if not isinstance(self.model_id, str): + raise ValueError(f"Invalid model_id: {self.model_id}") + + if self.seed < 0: + raise ValueError(f"Invalid seed: {self.seed}") + + if self.num_inference_runs <= 0: + raise ValueError(f"Invalid num_inference_runs: {self.num_inference_runs}") + + if self.max_new_tokens <= 0: + raise ValueError(f"Invalid max_new_tokens: {self.max_new_tokens}") + + @classmethod + def from_dict(cls, config_dict: dict) -> "BenchmarkConfig": + """Create config from dictionary.""" + valid_keys = set(cls.__dataclass_fields__.keys()) + filtered_dict = {k: v for k, v in config_dict.items() if k in valid_keys} + + return cls(**filtered_dict) + + @classmethod + def from_json(cls, json_path: str) -> "BenchmarkConfig": + """Load config from JSON file.""" + with open(json_path) as f: + config_dict = json.load(f) + return cls.from_dict(config_dict) + + def to_dict(self) -> dict[str, Any]: + """Convert config to dictionary.""" + result = asdict(self) + return result + + def save(self, path: str) -> None: + """Save config to JSON file.""" + with open(path, "w") as f: + json.dump(self.to_dict(), f, indent=2) + + def merge_from_dict(self, config_dict: dict) -> None: + """Merge settings from a dictionary into this config object. + Keys in config_dict will override existing attributes. + """ + for key, value in config_dict.items(): + if hasattr(self, key): + setattr(self, key, value) + + +def validate_experiment_path(path: str) -> tuple[str, "BenchmarkConfig"]: + """Validate experiment path, load and merge configs, and return them.""" + if not os.path.exists(path): + raise FileNotFoundError(f"Experiment path not found: {path}") + + path_parts = os.path.normpath(path).split(os.sep) + + try: + experiments_idx = path_parts.index("experiments") + except ValueError: + experiment_name = os.path.basename(path.rstrip(os.sep)) + else: + if experiments_idx + 1 < len(path_parts): + method_name = path_parts[experiments_idx + 1] + remaining_parts = path_parts[experiments_idx + 2 :] + if remaining_parts: + remaining_name = "-".join(remaining_parts) + experiment_name = f"{method_name}--{remaining_name}" + else: + experiment_name = method_name + else: + experiment_name = os.path.basename(path.rstrip(os.sep)) + + default_config_path = os.path.join(os.path.dirname(__file__), FILE_NAME_DEFAULT_CONFIG) + experiment_benchmark_params_path = os.path.join(path, FILE_NAME_BENCHMARK_PARAMS) + + if not os.path.exists(default_config_path): + raise FileNotFoundError(f"Default configuration file not found: {default_config_path}. This is required.") + benchmark_config = BenchmarkConfig.from_json(default_config_path) + print(f"Loaded default configuration from {default_config_path}") + + if os.path.exists(experiment_benchmark_params_path): + with open(experiment_benchmark_params_path) as f: + experiment_specific_params = json.load(f) + + benchmark_config.merge_from_dict(experiment_specific_params) + print(f"Loaded and merged experiment-specific parameters from {experiment_benchmark_params_path}") + else: + print(f"No {FILE_NAME_BENCHMARK_PARAMS} found in {path}. Using only default configuration.") + + return experiment_name, benchmark_config + + +def get_memory_usage() -> tuple[float, float, float]: + """Get current memory usage (RAM and accelerator).""" + process = psutil.Process(os.getpid()) + ram_usage_bytes = process.memory_info().rss + ram_usage_mb = ram_usage_bytes / (1024 * 1024) + + if torch.cuda.is_available(): + accelerator_allocated = torch.cuda.memory_allocated() + accelerator_reserved = torch.cuda.memory_reserved() + accelerator_allocated_mb = accelerator_allocated / (1024 * 1024) + accelerator_reserved_mb = accelerator_reserved / (1024 * 1024) + elif torch.xpu.is_available(): + accelerator_allocated = torch.xpu.memory_allocated() + accelerator_reserved = torch.xpu.memory_reserved() + accelerator_allocated_mb = accelerator_allocated / (1024 * 1024) + accelerator_reserved_mb = accelerator_reserved / (1024 * 1024) + else: + accelerator_allocated_mb = 0.0 + accelerator_reserved_mb = 0.0 + + return ram_usage_mb, accelerator_allocated_mb, accelerator_reserved_mb + + +def init_accelerator() -> tuple[float, float]: + """Initialize accelerator and return initial memory usage.""" + if torch.cuda.is_available(): + torch.cuda.init() + torch.cuda.empty_cache() + _, accelerator_allocated, accelerator_reserved = get_memory_usage() + elif torch.xpu.is_available(): + torch.xpu.init() + torch.xpu.empty_cache() + _, accelerator_allocated, accelerator_reserved = get_memory_usage() + else: + accelerator_allocated = 0.0 + accelerator_reserved = 0.0 + return accelerator_allocated, accelerator_reserved + + +def get_model_size_mb(model: torch.nn.Module, dtype_bytes: int = 4) -> float: + """Calculate model size in MB.""" + return sum(p.numel() * dtype_bytes for p in model.parameters()) / (1024 * 1024) + + +def get_peft_branch() -> str: + repo_root = os.path.dirname(__file__) + return subprocess.check_output("git rev-parse --abbrev-ref HEAD".split(), cwd=repo_root).decode().strip() + + +def log_results( + experiment_name: str, + benchmark_result: BenchmarkResult, + print_fn: Callable = print, +) -> None: + """Log benchmark results to console.""" + print_fn("\n" + "=" * 50) + print_fn(f"Benchmark Results: {experiment_name}") + print_fn("=" * 50) + + print_fn(f"Status: {benchmark_result.run_info.get('status', 'N/A')}") + print_fn(f"Duration: {benchmark_result.run_info.get('duration', 0):.2f} seconds") + + if benchmark_result.run_info.get("status") != BenchmarkStatus.SUCCESS.value: + print_fn(f"Error: {benchmark_result.run_info.get('error', 'Unknown error')}") + print_fn("=" * 50) + return + + print_fn("\nModel Information:") + print_fn(f" Base Model: {benchmark_result.meta_info.get('model_id', 'N/A')}") + + print_fn("\nParameter Counts:") + params = benchmark_result.meta_info.get("parameters", {}) + print_fn(f" Base Parameters: {params.get('base_params', 0):,}") + print_fn(f" Trainable Parameters: {params.get('trainable_params', 0):,}") + print_fn(f" Parameter Ratio: {params.get('param_ratio', 0):.5%}") + + print_fn("\nModel Size:") + size_info = benchmark_result.meta_info.get("model_size", {}) + print_fn(f" Base Model: {size_info.get('base_model_size_mb', 0):.2f} MB") + print_fn(f" Adapter: {size_info.get('adapter_size_mb', 0):.2f} MB") + + print_fn("\nMemory Usage (from generation_info):") + memory_data = benchmark_result.generation_info.get("memory", {}) + print_fn(f" Peak Accelerator Memory: {memory_data.get('peak_accelerator_memory_mb', 0):.2f} MB") + print_fn(f" Peak RAM Memory: {memory_data.get('peak_ram_memory_mb', 0):.2f} MB") + + print_fn("\nDetailed Metrics (from generation_info.by_category):") + if benchmark_result.generation_info.get("by_category"): + for category, cat_data in benchmark_result.generation_info["by_category"].items(): + print_fn(f" Category: {category}") + metrics = cat_data.get("metrics", {}) + print_fn(f" Inference Time: {metrics.get('inference_time', 0):.4f} seconds") + print_fn(f" Base Inference Time: {metrics.get('base_inference_time', 0):.4f} seconds") + print_fn(f" Inference Overhead: {metrics.get('inference_overhead_pct', 0):.2f}%") + print_fn(f" Time Per Token: {metrics.get('time_per_token', 0):.6f} seconds/token") + print_fn(f" Generated Tokens: {metrics.get('generated_tokens', 0):.1f}") + + samples = cat_data.get("samples", []) + if samples: + print_fn(f" Number of Samples: {len(samples)}") + print_fn( + f" Average Generated Tokens: {sum(s.get('generated_tokens', 0) for s in samples) / len(samples):.1f}" + ) + else: + print_fn(" No per-category metrics available.") + + benchmark_result.compute_overall_metrics() + + print_fn("\nOverall Metrics (from generation_info.overall):") + overall = benchmark_result.generation_info.get("overall") + if overall: + print_fn(f" Inference Time: {overall.get('inference_time', 0):.4f} seconds") + print_fn(f" Base Inference Time: {overall.get('base_inference_time', 0):.4f} seconds") + print_fn(f" Inference Overhead: {overall.get('inference_overhead_pct', 0):.2f}%") + print_fn(f" Time Per Token: {overall.get('time_per_token', 0):.6f} seconds/token") + print_fn(f" Generated Tokens: {overall.get('generated_tokens', 0):.1f}") + else: + print_fn(" No overall metrics computed.") + + print_fn("\nSaved results to:", benchmark_result.save()) + print_fn("=" * 50) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/pyproject.toml b/tasks/tasksmith-f71b564d1bc2/tests/source/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..c1ed90e74f7477091e224a872d74297573037817 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/pyproject.toml @@ -0,0 +1,58 @@ +[tool.black] +# Only used by `hf-doc-builder´. +line-length = 119 +target-version = ['py310'] + +[tool.ruff] +target-version = "py310" +line-length = 119 +extend-exclude = ["*.ipynb"] + +[tool.ruff.lint] +preview = true +explicit-preview-rules = true +extend-select = [ + "C", # Complexity + "E", # PEP8 errors + "F", # PEP8 formatting + "I", # Import sorting + "UP", # Pyupgrade upgrades + "W", # PEP8 warnings + "PT009", # Pytest assertions + "RUF022", # Sorting of __all__ +] +ignore = [ + "C901", # Function too complex + "E501", # Line length (handled by ruff-format) + "F841", # unused variable + "UP007", # X | Y style Unions + "C420", # dict.fromkeys + "UP045", # don't force replacing Optional[X] with X | None +] + +[tool.ruff.lint.isort] +lines-after-imports = 2 +known-first-party = ["peft"] + +[tool.pytest] +doctest_optionflags = [ + "NORMALIZE_WHITESPACE", + "ELLIPSIS", + "NUMBER", +] + +addopts = ["--cov=src/peft", "--cov-report=term-missing", "--durations=10"] + +markers = [ + "single_gpu_tests: tests that run on a single GPU", + "multi_gpu_tests: tests that run on multiple GPUs", + "regression: whether to run regression suite test", + "bitsandbytes: select bitsandbytes integration tests", +] + +filterwarnings = [ + "error::DeprecationWarning:transformers", + # in sync with tests/conftest.py regarding BPE deprecation + "ignore:.*BPE.__init__ will not create from files anymore.*:DeprecationWarning:transformers", + "error::FutureWarning:transformers", +] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/requirements.txt b/tasks/tasksmith-f71b564d1bc2/tests/source/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..dca857de3249b60ea3786b49156d14166cd57ac0 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/requirements.txt @@ -0,0 +1,15 @@ +accelerate +torch +safetensors +bitsandbytes +scipy +peft +transformers +tqdm +packaging +pytest +numpy +pyyaml +datasets +psutil +setuptools \ No newline at end of file diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/ci_clean_cache.py b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/ci_clean_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..8e4bfbaa0abc8fee26098d1b6496d3891ac7bc3f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/ci_clean_cache.py @@ -0,0 +1,67 @@ +""" +Utility to clean cache files that exceed a specific time in days according to their +last access time recorded in the cache. + +Exit code: +- 1 if no candidates are found +- 0 if candidates are found + +Deletion can be enabled by passing `-d` parameter, otherwise it will only list the candidates. +""" + +import sys +from datetime import datetime as dt + +from huggingface_hub import scan_cache_dir + + +def find_old_revisions(scan_results, max_age_days=30): + """Find commit hashes of objects in the cache. These objects need a last access time that + is above the passed `max_age_days` parameter. Returns an empty list if no objects are found. + Time measurement is based of the current time and the recorded last access tiem in the cache. + """ + now = dt.now() + revisions = [(i.revisions, i.last_accessed) for i in scan_results.repos] + revisions_ages = [(rev, (now - dt.fromtimestamp(ts_access)).days) for rev, ts_access in revisions] + delete_candidates = [rev for rev, age in revisions_ages if age > max_age_days] + hashes = [n.commit_hash for rev in delete_candidates for n in rev] + + return hashes + + +def delete_old_revisions(scan_results, delete_candidates, do_delete=False): + delete_operation = scan_results.delete_revisions(*delete_candidates) + print(f"Would free {delete_operation.expected_freed_size_str}") + print(f"Candidates: {delete_candidates}") + + if do_delete: + print("Deleting now.") + delete_operation.execute() + else: + print("Not deleting, pass the -d flag.") + + +if __name__ == "__main__": + from argparse import ArgumentParser + + parser = ArgumentParser() + parser.add_argument("-a", "--max-age", type=int, default=30, help="Max. age in days items in the cache may have.") + parser.add_argument( + "-d", + "--delete", + action="store_true", + help=( + "Delete mode; Really delete items if there are candidates. Exit code = 0 when we found something to delete, 1 " + "otherwise." + ), + ) + args = parser.parse_args() + + scan_results = scan_cache_dir() + + delete_candidates = find_old_revisions(scan_results, args.max_age) + if not delete_candidates: + print("No delete candidates found, not deleting anything.") + sys.exit(1) + + delete_old_revisions(scan_results, delete_candidates, do_delete=args.delete) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/convert-bone-to-miss.py b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/convert-bone-to-miss.py new file mode 100644 index 0000000000000000000000000000000000000000..e709410fa806bb0fa35e6f01160084c9dc2d4652 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/convert-bone-to-miss.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +# Copyright (c) 2025 Your Organization/Project. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Convert Bone checkpoint to MiSS format.""" + +import argparse +import json +import os +from pathlib import Path + +from safetensors import safe_open +from safetensors.torch import save_file + +from peft.utils import CONFIG_NAME, SAFETENSORS_WEIGHTS_NAME + + +def convert_bone_to_miss(bone_dir: Path, miss_dir: Path) -> None: + """Convert Bone checkpoint files to MiSS format.""" + bone_config_path = bone_dir / CONFIG_NAME + miss_config_path = miss_dir / CONFIG_NAME + if not os.path.exists(miss_dir): + os.makedirs(miss_dir, exist_ok=True) + with open(bone_config_path, encoding="utf-8") as f: + config = json.load(f) + + config["peft_type"] = "MISS" + + with open(miss_config_path, "w", encoding="utf-8") as f: + json.dump(config, f, indent=2, ensure_ascii=False) + + bone_weight_path = bone_dir / SAFETENSORS_WEIGHTS_NAME + miss_weight_path = miss_dir / SAFETENSORS_WEIGHTS_NAME + + new_data = {} + + with safe_open(bone_weight_path, framework="pt") as f: + for old_key in f.keys(): + tensor = f.get_tensor(old_key) + new_key = old_key.replace(".bone_", ".miss_") + new_data[new_key] = tensor + + save_file(new_data, miss_weight_path) + + print(f"Converted checkpoint saved at {miss_weight_path}") + + +def main() -> None: + parser = argparse.ArgumentParser(description="Convert Bone checkpoint to MiSS format.") + parser.add_argument("bone_dir", type=Path, help="Directory containing Bone checkpoint files") + parser.add_argument("miss_dir", type=Path, help="Directory to save MiSS checkpoint files") + args = parser.parse_args() + + args.miss_dir.mkdir(parents=True, exist_ok=True) + convert_bone_to_miss(args.bone_dir, args.miss_dir) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/evaluate-lora-conversion.py b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/evaluate-lora-conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..0096af13780729c3702a594e04fbf378c3215d1a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/evaluate-lora-conversion.py @@ -0,0 +1,157 @@ +#!/usr/bin/env python3 +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Script to evaluate a PEFT checkpoint converted into a LoRA on GSM8K + +To run this script, first train a PEFT model on MetaMathQA as described here: + +https://github.com/huggingface/peft/tree/main/method_comparison/MetaMathQA + +Call the script with the `-v` (verbose) option. When that run finishes, it will save a checkpoint of that model and +print a message like this: "Saved PEFT checkpoint to ...". Use this path as the `--path` argument to this script. + +Example usage: + +```bash +# Convert to LoRA with rank 8 and evaluate it +python evaluate-lora-conversion.py --path /path/to/peft/checkpoint --rank 8 +# Convert to LoRA with dynamic rank (50% singular value threshold) and evaluate it +python evaluate-lora-conversion.py --path /path/to/peft/checkpoint --rank 0.5 +# Evaluate the original PEFT model without LoRA conversion +python evaluate-lora-conversion.py --path /path/to/peft/checkpoint +``` + +The script will report the evaluation accuracy, maximum CUDA memory reserved, and evaluation time for the converted LoRA +model. + +""" + +import argparse +import importlib.util +import os +import sys +import time + +import torch +from transformers import AutoModelForCausalLM + +from peft import PeftModel, convert_to_lora, get_peft_model, set_peft_model_state_dict + + +root = os.path.abspath(os.path.join(os.path.dirname(__file__), "..")) + +spec = importlib.util.spec_from_file_location("data", os.path.join(root, "method_comparison", "MetaMathQA", "data.py")) +mm_data = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mm_data) +sys.modules["data"] = mm_data + +spec = importlib.util.spec_from_file_location( + "utils", os.path.join(root, "method_comparison", "MetaMathQA", "utils.py") +) +mm_utils = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mm_utils) +sys.modules["utils"] = mm_utils + +spec = importlib.util.spec_from_file_location("run", os.path.join(root, "method_comparison", "MetaMathQA", "run.py")) +mm_run = importlib.util.module_from_spec(spec) +spec.loader.exec_module(mm_run) + + +def noop(*args, **kwargs): + pass + + +def evaluate_model(model, tokenizer, ds_test): + torch.cuda.empty_cache() + torch.cuda.reset_peak_memory_stats() + tic = time.perf_counter() + predictions, responses = mm_run.evaluate( + model=model, + tokenizer=tokenizer, + ds=ds_test, + batch_size=50, + generate_kwargs={"max_length": 800, "max_new_tokens": 300, "pad_token_id": tokenizer.eos_token_id}, + use_tqdm=True, + ) + toc = time.perf_counter() + accuracy_peft = mm_utils.get_accuracy(predictions=predictions, responses=responses) + cuda_mem_reserved_max = torch.cuda.memory_reserved(0) + print(f"Evaluation Accuracy: {100 * accuracy_peft:.2f}%") + print(f"Max CUDA Memory Reserved: {cuda_mem_reserved_max / (1024**3):.2f} GB") + print(f"Evaluation Time: {toc - tic:.0f} seconds".format(toc - tic)) + + +def main(path_peft_model: str, rank: int | float | None) -> None: + model_id = "meta-llama/Llama-3.2-3B" + tokenizer = mm_utils.get_tokenizer(model_id=model_id, max_seq_length=768) + _, _, ds_test = mm_data.get_train_valid_test_datasets( + tokenizer=tokenizer, query_template="Question: {query} Think step by step.\nAnswer:", print_fn=noop + ) + + model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).to(0) + model = PeftModel.from_pretrained(model, path_peft_model) + if rank is None: + print("Evaluating the original PEFT model without LoRA conversion...") + model.set_adapter("default") + model.print_trainable_parameters() + model.eval() + evaluate_model(model, tokenizer, ds_test) + return + + print(f"Converting PEFT model to LoRA with rank={rank}...") + tic = time.perf_counter() + lora_config, lora_state_dict = convert_to_lora(model, rank=rank, progressbar=True) + toc = time.perf_counter() + print(f"Conversion completed in {toc - tic:.0f} seconds.".format(toc - tic)) + + del model + torch.cuda.empty_cache() + model = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16).to(0) + + model = get_peft_model(model, lora_config) + model.print_trainable_parameters() + + load_result = set_peft_model_state_dict(model, lora_state_dict) + assert not load_result.unexpected_keys, ( + f"Unexpected keys when loading LoRA state dict: {load_result.unexpected_keys}" + ) + + del lora_state_dict + model.eval() + evaluate_model(model, tokenizer, ds_test) + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Evaluate a PEFT checkpoint converted into a LoRA on GSM8K") + parser.add_argument( + "--path", + type=str, + required=True, + help="Path to the input PEFT checkpoint", + ) + parser.add_argument( + "--rank", + required=False, + default=None, + help="Rank for the LoRA decomposition (int, float, or None for no conversion)", + ) + + args = parser.parse_args() + if args.rank is not None: + if "." in str(args.rank): + args.rank = float(args.rank) + else: + args.rank = int(args.rank) + main(args.path, args.rank) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/launch_notebook_mp.py b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/launch_notebook_mp.py new file mode 100644 index 0000000000000000000000000000000000000000..ce5439afa82a4220cdecbd73e545c58cd14f8442 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/launch_notebook_mp.py @@ -0,0 +1,47 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This is a minimal example of launching PEFT with Accelerate. This used to cause issues because PEFT would eagerly +# import bitsandbytes, which initializes CUDA, resulting in: +# > RuntimeError: Cannot re-initialize CUDA in forked subprocess. To use CUDA with multiprocessing, you must use the +# > 'spawn' start method +# This script exists to ensure that this issue does not reoccur. + +import torch +from accelerate import notebook_launcher + +import peft +from peft.utils import infer_device + + +def init(): + class MyModule(torch.nn.Module): + def __init__(self): + super().__init__() + self.linear = torch.nn.Linear(1, 2) + + def forward(self, x): + return self.linear(x) + + device = infer_device() + model = MyModule().to(device) + peft.get_peft_model(model, peft.LoraConfig(target_modules=["linear"])) + + +def main(): + notebook_launcher(init, (), num_processes=2) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/log_reports.py b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/log_reports.py new file mode 100644 index 0000000000000000000000000000000000000000..c8191ee8f5a2d79c83b266e4a60d2f280fa9d376 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/log_reports.py @@ -0,0 +1,144 @@ +import argparse +import json +import os +from datetime import date +from pathlib import Path + +from tabulate import tabulate + + +MAX_LEN_MESSAGE = 2900 # slack endpoint has a limit of 3001 characters + +parser = argparse.ArgumentParser() +parser.add_argument( + "--slack_channel_name", + default="peft-ci-daily", +) + + +def main(slack_channel_name=None): + failed = [] + passed = [] + + group_info = [] + + total_num_failed = 0 + empty_file = False or len(list(Path().glob("*.log"))) == 0 + + total_empty_files = [] + + for log in Path().glob("*.log"): + section_num_failed = 0 + i = 0 + with open(log) as f: + for line in f: + line = json.loads(line) + i += 1 + if line.get("nodeid", "") != "": + test = line["nodeid"] + if line.get("duration", None) is not None: + duration = f"{line['duration']:.4f}" + if line.get("outcome", "") == "failed": + section_num_failed += 1 + failed.append([test, duration, log.name.split("_")[0]]) + total_num_failed += 1 + else: + passed.append([test, duration, log.name.split("_")[0]]) + empty_file = i == 0 + group_info.append([str(log), section_num_failed, failed]) + total_empty_files.append(empty_file) + os.remove(log) + failed = [] + text = ( + "🌞 There were no failures!" + if not any(total_empty_files) + else "Something went wrong there is at least one empty file - please check GH action results." + ) + no_error_payload = { + "type": "section", + "text": { + "type": "plain_text", + "text": text, + "emoji": True, + }, + } + + message = "" + payload = [ + { + "type": "header", + "text": { + "type": "plain_text", + "text": "🤗 Results of the {} PEFT scheduled tests.".format(os.environ.get("TEST_TYPE", "")), + }, + }, + ] + if total_num_failed > 0: + for i, (name, num_failed, failed_tests) in enumerate(group_info): + if num_failed > 0: + if num_failed == 1: + message += f"*{name}: {num_failed} failed test*\n" + else: + message += f"*{name}: {num_failed} failed tests*\n" + failed_table = [] + for test in failed_tests: + failed_table.append(test[0].split("::")) + failed_table = tabulate( + failed_table, + headers=["Test Location", "Test Case", "Test Name"], + showindex="always", + tablefmt="grid", + maxcolwidths=[12, 12, 12], + ) + message += "\n```\n" + failed_table + "\n```" + + if total_empty_files[i]: + message += f"\n*{name}: Warning! Empty file - please check the GitHub action job *\n" + print(f"### {message}") + else: + payload.append(no_error_payload) + + if os.environ.get("TEST_TYPE", "") != "": + from slack_sdk import WebClient + + if len(message) > MAX_LEN_MESSAGE: + print(f"Truncating long message from {len(message)} to {MAX_LEN_MESSAGE}") + message = message[:MAX_LEN_MESSAGE] + "..." + + if len(message) != 0: + md_report = { + "type": "section", + "text": {"type": "mrkdwn", "text": message}, + } + payload.append(md_report) + action_button = { + "type": "section", + "text": {"type": "mrkdwn", "text": "*For more details:*"}, + "accessory": { + "type": "button", + "text": {"type": "plain_text", "text": "Check Action results", "emoji": True}, + "url": f"https://github.com/huggingface/peft/actions/runs/{os.environ['GITHUB_RUN_ID']}", + }, + } + payload.append(action_button) + + date_report = { + "type": "context", + "elements": [ + { + "type": "plain_text", + "text": f"Nightly {os.environ.get('TEST_TYPE')} test results for {date.today()}", + }, + ], + } + payload.append(date_report) + + print(payload) + + client = WebClient(token=os.environ.get("SLACK_API_TOKEN")) + client.chat_postMessage(channel=f"#{slack_channel_name}", text=message, blocks=payload) + + +if __name__ == "__main__": + args = parser.parse_args() + main(args.slack_channel_name) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/stale.py b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/stale.py new file mode 100644 index 0000000000000000000000000000000000000000..794ec8451282c69ae9cff18c15329b14816d707a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/stale.py @@ -0,0 +1,65 @@ +# Copyright 2023 The HuggingFace Team, the AllenNLP library authors. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Script to close stale issue. Taken in part from the AllenNLP repository. +https://github.com/allenai/allennlp. +""" + +import os +from datetime import datetime as dt +from datetime import timezone + +from github import Github + + +LABELS_TO_EXEMPT = [ + "good first issue", + "good second issue", + "good difficult issue", + "feature request", + "new model", + "wip", + "PRs welcome to address this", +] + + +def main(): + g = Github(os.environ["GITHUB_TOKEN"]) + repo = g.get_repo("huggingface/peft") + open_issues = repo.get_issues(state="open") + + for issue in open_issues: + comments = sorted(issue.get_comments(), key=lambda i: i.created_at, reverse=True) + last_comment = comments[0] if len(comments) > 0 else None + if ( + (last_comment is not None and last_comment.user.login == "github-actions[bot]") + and (dt.now(timezone.utc) - issue.updated_at).days > 7 + and (dt.now(timezone.utc) - issue.created_at).days >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + issue.edit(state="closed") + elif ( + (dt.now(timezone.utc) - issue.updated_at).days > 23 + and (dt.now(timezone.utc) - issue.created_at).days >= 30 + and not any(label.name.lower() in LABELS_TO_EXEMPT for label in issue.get_labels()) + ): + issue.create_comment( + "This issue has been automatically marked as stale because it has not had " + "recent activity. If you think this still needs to be addressed " + "please comment on this thread.\n\n" + ) + + +if __name__ == "__main__": + main() diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/train_memory.py b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/train_memory.py new file mode 100644 index 0000000000000000000000000000000000000000..c764fe84ae095ee65b923b517fc438b412ad10ed --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/scripts/train_memory.py @@ -0,0 +1,276 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""This script trains a model on a small text dataset and measures the memory consumption, as well as a few other +useful metrics. + +Example: + +Get help: + +```bash +python train_memory.py --help +``` + +Train the google/gemma-2-2b model with a LoRA config json at the indicated location. + +```bash +python train_memory.py "google/gemma-2-2b" --max_seq_length 256 --batch_size 1 --rank 32 --dtype bfloat16 --path_config +``` + +Fully fine-tune the model (i.e. without LoRA) by setting the rank to 0: + +```bash +python train_memory.py "google/gemma-2-2b" --rank 0 +``` + +Get an estimate of the size of the hidden states by passing `--monitor_tensors`. This trains just for a single epoch. For realistic estimates, the batch size for this: + +```bash +python train_memory.py "google/gemma-2-2b" --max_seq_length 256 --batch_size 32 --rank 32 --dtype bfloat16 --path_config configs/lora_rank-32_embedding-lora/ --monitor_tensors +``` + +""" + +import argparse +import gc +import os +import sys +import tempfile +import time +import warnings +from collections import Counter +from contextlib import nullcontext +from functools import partial + +import torch +from datasets import load_dataset +from torch import nn +from transformers import ( + AutoModelForCausalLM, + AutoTokenizer, + BitsAndBytesConfig, +) + +from peft import LoraConfig, get_peft_model, prepare_model_for_kbit_training +from peft.utils import CONFIG_NAME, SAFETENSORS_WEIGHTS_NAME + + +# suppress all warnings +warnings.filterwarnings("ignore") + +device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda" +dtype_to_bytes_linear = {"float32": 4, "float16": 2, "bfloat16": 2, "int8": 1, "int4": 0.5} + + +def init_accelerator(): + torch.manual_seed(0) + if device == "cpu": + return + + device_module = getattr(torch, device, torch.cuda) + device_module.reset_peak_memory_stats() + device_module.manual_seed_all(0) + # might not be necessary, but just to be sure + nn.Linear(1, 1).to(device) + + +def get_data(tokenizer): + def tokenize(samples): + # For some reason, the max sequence length is not honored by the tokenizer, resulting in IndexErrors. Thus, + # manually ensure that sequences are not too long. + tokenized = tokenizer(samples["quote"]) + tokenized["input_ids"] = [input_ids[: tokenizer.model_max_length] for input_ids in tokenized["input_ids"]] + tokenized["attention_mask"] = [ + input_ids[: tokenizer.model_max_length] for input_ids in tokenized["attention_mask"] + ] + return tokenized + + data = load_dataset("ybelkada/english_quotes_copy") + data = data.map(tokenize, batched=True) + # We need to manually remove unused columns. This is because we cannot use remove_unused_columns=True in the + # Trainer, as this leads to errors with torch.compile. We also cannot just leave them in, as they contain + # strings. Therefore, manually remove all unused columns. + data = data.remove_columns(["quote", "author", "tags"]) + return data + + +def train(model_id, rank, dtype, monitor_tensors, max_seq_length, batch_size, max_steps, path_config): + init_accelerator() + device_module = getattr(torch, device, torch.cuda) + accelerator_memory_init = device_module.max_memory_allocated() + accelerator_memory_log = [] + + tokenizer = AutoTokenizer.from_pretrained(model_id) + tokenizer.model_max_length = max_seq_length + if not tokenizer.pad_token: + tokenizer.pad_token = tokenizer.eos_token + data = get_data(tokenizer) + + if dtype == "int4": + quant_config = BitsAndBytesConfig(load_in_4bit=True) + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, quantization_config=quant_config) + model = prepare_model_for_kbit_training(model) + elif dtype == "int8": + quant_config = BitsAndBytesConfig(load_in_8bit=True) + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, quantization_config=quant_config) + model = prepare_model_for_kbit_training(model) + elif dtype == "bfloat16": + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, torch_dtype=torch.bfloat16) + elif dtype == "float16": + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device, torch_dtype=torch.float16) + elif dtype == "float32": + model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device) + else: + raise ValueError(f"Invalid dtype: {dtype}") + + if rank > 0: + if path_config is None: + raise RuntimeError("LoRA rank > 0 requires a path to a LoRA config") + if path_config.endswith(CONFIG_NAME): + path_config = path_config.removesuffix(CONFIG_NAME) + config = LoraConfig.from_pretrained(path_config) + model = get_peft_model(model, config) + model.print_trainable_parameters() + else: + print("Not using LoRA") + + model.config.use_cache = False + storage = [] + + def pack(x): + storage.append(x) + return len(storage) - 1 + + def unpack(x): + return storage[x] + + train_ctx = partial(torch.autograd.graph.saved_tensors_hooks, pack, unpack) if monitor_tensors else nullcontext + + optimizer = torch.optim.AdamW(model.parameters(), lr=1e-5) + losses = [] + sample = 0 + tic_total = time.perf_counter() + for i in range(0, max_steps): + storage.clear() + tic = time.perf_counter() + try: + batch = tokenizer.pad(data["train"][sample : sample + batch_size], return_tensors="pt").to(model.device) + sample += batch_size + + # add targets + batch["labels"] = batch["input_ids"].clone() + optimizer.zero_grad() + + with train_ctx(): + outputs = model(**batch) + loss = outputs.loss + loss.backward() + optimizer.step() + losses.append(loss.item()) + accelerator_memory_log.append(device_module.memory_allocated() - accelerator_memory_init) + device_module.empty_cache() + gc.collect() + toc = time.perf_counter() + print(f"step {i:3d} loss {loss.item():.6f} time {toc - tic:.2f}s", file=sys.stderr) + except KeyboardInterrupt: + print("canceled training") + break + + if monitor_tensors: + break + + toc_total = time.perf_counter() + + accelerator_memory_final = device_module.max_memory_allocated() + accelerator_memory_avg = int(sum(accelerator_memory_log) / len(accelerator_memory_log)) + print(f"{model.device.type} memory avg: {accelerator_memory_avg // 2**20}MB") + print(f"{model.device.type} memory max: {(accelerator_memory_final - accelerator_memory_init) // 2**20}MB") + print(f"total time: {toc_total - tic_total:.2f}s") + + with tempfile.TemporaryDirectory() as tmp_dir: + model.save_pretrained(tmp_dir) + stat = os.stat(os.path.join(tmp_dir, SAFETENSORS_WEIGHTS_NAME)) + file_size = stat.st_size + print(f"file size: {file_size / 2**20:.1f}MB") + + if monitor_tensors: + dtype_counts = Counter(t.dtype for t in storage) + shape_counts = Counter(t.shape for t in storage) + param_shape_counts = Counter(p.shape for p in model.parameters()) + param_shape_counts_copy = dict(param_shape_counts).copy() + + # shape counts includes the params, so we need to subtract them; note that they can be transposed + # this is an approximation + diff_shape_counts = {} + for shape, count in shape_counts.items(): + if shape in param_shape_counts_copy: + diff_count = count - param_shape_counts[shape] + if diff_count > 0: + diff_shape_counts[shape] = diff_count + param_shape_counts_copy[shape] = max(0, param_shape_counts_copy[shape] - diff_count) + elif shape[::-1] in param_shape_counts: + diff_count = count - param_shape_counts[shape[::-1]] + if diff_count > 0: + diff_shape_counts[shape] = diff_count + param_shape_counts_copy[shape[::-1]] = max(0, param_shape_counts_copy[shape[::-1]] - diff_count) + else: + diff_shape_counts[shape] = count + + total_size = sum(t.numel() * t.element_size() for t in storage) + total_size_mb = f"{total_size // 2**20}MB" + diff_size = 0 + for shape, count in diff_shape_counts.items(): + diff_size += count * torch.zeros(shape).numel() * dtype_to_bytes_linear[dtype] + param_size = total_size - diff_size + + diff_size_mb = f"{diff_size // 2**20}MB" + param_size_mb = f"{param_size // 2**20}MB" + + print(f"Dtype counts: {dtype_counts.most_common()}") + print(f"Total size of tensors: {total_size_mb: >12}") + print(f"Total size of activations: {diff_size_mb: >12}") + print(f"Total size of parameters: {param_size_mb: >12}") + + +if __name__ == "__main__": + parser = argparse.ArgumentParser() + parser.add_argument("model_id", type=str, help="Model name on Hugging Face Hub") + parser.add_argument("--rank", type=int, default=8, help="Rank of LoRA, 0 => no LoRA, default 8") + parser.add_argument( + "--dtype", + type=str, + default="float32", + help="Data type, one of float32, float16, bfloat16, int8, int4, default float32", + ) + parser.add_argument( + "--monitor_tensors", + action="store_true", + help="Monitor tensor sizes during training for a single training step, off by default", + ) + parser.add_argument("--max_seq_length", type=int, default=128, help="Maximum sequence length, default 128") + parser.add_argument("--batch_size", type=int, default=1, help="Batch size, default 1") + parser.add_argument("--max_steps", type=int, default=50, help="Maximum number of training steps, default 50") + parser.add_argument("--path_config", type=str, default=None, help="Path to LoRA config") + args = parser.parse_args() + train( + model_id=args.model_id, + rank=args.rank, + dtype=args.dtype, + monitor_tensors=args.monitor_tensors, + max_seq_length=args.max_seq_length, + batch_size=args.batch_size, + max_steps=args.max_steps, + path_config=args.path_config, + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/setup.py b/tasks/tasksmith-f71b564d1bc2/tests/source/setup.py new file mode 100644 index 0000000000000000000000000000000000000000..168b4e4aedc74bdb1a64fa2f27303751387ebb3d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/setup.py @@ -0,0 +1,111 @@ +# Copyright 2023 The HuggingFace Team. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from setuptools import find_packages, setup + + +VERSION = "0.18.2.dev0" + +extras = {} +extras["quality"] = [ + "black", # doc-builder has an implicit dependency on Black, see huggingface/doc-builder#434 + "hf-doc-builder", + "ruff~=0.12.8", +] +extras["docs_specific"] = [ + "black", # doc-builder has an implicit dependency on Black, see huggingface/doc-builder#434 + "requests", # doc-builder has an implicit dependency on requests (setup.py doesn't mention it, pyproject does) + "hf-doc-builder", +] +extras["dev"] = extras["quality"] + extras["docs_specific"] +extras["test"] = extras["dev"] + [ + "pytest", + "pytest-cov", + "pytest-xdist", + "parameterized", + "datasets", + "diffusers", + "scipy", + "protobuf", + "sentencepiece", +] + +setup( + name="peft", + version=VERSION, + description="Parameter-Efficient Fine-Tuning (PEFT)", + license_files=["LICENSE"], + long_description=open("README.md", encoding="utf-8").read(), + long_description_content_type="text/markdown", + keywords="deep learning", + license="Apache", + author="The HuggingFace team", + author_email="benjamin@huggingface.co", + url="https://github.com/huggingface/peft", + package_dir={"": "src"}, + packages=find_packages("src"), + package_data={"peft": ["py.typed", "tuners/boft/fbd/fbd_cuda.cpp", "tuners/boft/fbd/fbd_cuda_kernel.cu"]}, + entry_points={}, + python_requires=">=3.10.0", + install_requires=[ + "numpy>=1.17", + "packaging>=20.0", + "psutil", + "pyyaml", + "torch>=1.13.0", + "transformers", + "tqdm", + "accelerate>=0.21.0", + "safetensors", + "huggingface_hub>=0.25.0", + ], + extras_require=extras, + classifiers=[ + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "Intended Audience :: Education", + "Intended Audience :: Science/Research", + "License :: OSI Approved :: Apache Software License", + "Operating System :: OS Independent", + "Programming Language :: Python :: 3", + "Programming Language :: Python :: 3.10", + "Programming Language :: Python :: 3.11", + "Programming Language :: Python :: 3.12", + "Programming Language :: Python :: 3.13", + "Topic :: Scientific/Engineering :: Artificial Intelligence", + ], +) + +# Release checklist +# 1. Change the version in __init__.py and setup.py to the release version, e.g. from "0.6.1.dev0" to "0.7.0" +# 2. Check if there are any deprecations that need to be addressed for this release by searching for "# TODO" in the code +# 3. Commit these changes with the message: "Release: VERSION", create a PR and merge it. +# 4. Add a tag in git to mark the release: "git tag -a v -m 'Adds tag for pypi' " +# Push the tag to git: +# git push --tags origin main +# It is necessary to work on the original repository, not on a fork. +# 5. Run the following commands in the top-level directory: +# python setup.py bdist_wheel +# python setup.py sdist +# Ensure that you are on the clean and up-to-date main branch (git status --untracked-files=no should not list any +# files and show the main branch) +# 6. Upload the package to the pypi test server first: +# twine upload dist/* -r pypitest +# 7. Check that you can install it in a virtualenv by running: +# pip install -i https://testpypi.python.org/pypi --extra-index-url https://pypi.org/simple peft +# 8. Upload the final version to actual pypi: +# twine upload dist/* -r pypi +# 9. Add release notes to the tag on https://github.com/huggingface/peft/releases once everything is looking hunky-dory. +# Check the notes here: https://docs.google.com/document/d/1k-sOIfykuKjWcOIALqjhFKz4amFEp-myeJUJEzNgjoU/edit?usp=sharing +# 10. Update the version in __init__.py, setup.py to the bumped patch version + ".dev0" (e.g. from "0.7.0" to "0.7.1.dev0") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..404dd9742b7a94cacb72ae1e86e2a1660a432bc3 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/__init__.py @@ -0,0 +1,280 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +__version__ = "0.18.2.dev0" + +from .auto import ( + MODEL_TYPE_TO_PEFT_MODEL_MAPPING, + AutoPeftModel, + AutoPeftModelForCausalLM, + AutoPeftModelForFeatureExtraction, + AutoPeftModelForQuestionAnswering, + AutoPeftModelForSeq2SeqLM, + AutoPeftModelForSequenceClassification, + AutoPeftModelForTokenClassification, +) +from .config import PeftConfig, PromptLearningConfig +from .mapping import ( + PEFT_TYPE_TO_CONFIG_MAPPING, + PEFT_TYPE_TO_MIXED_MODEL_MAPPING, + PEFT_TYPE_TO_TUNER_MAPPING, + get_peft_config, + inject_adapter_in_model, +) +from .mapping_func import get_peft_model +from .mixed_model import PeftMixedModel +from .peft_model import ( + PeftModel, + PeftModelForCausalLM, + PeftModelForFeatureExtraction, + PeftModelForQuestionAnswering, + PeftModelForSeq2SeqLM, + PeftModelForSequenceClassification, + PeftModelForTokenClassification, + get_layer_status, + get_model_status, +) +from .tuners import ( + AdaLoraConfig, + AdaLoraModel, + AdaptionPromptConfig, + AdaptionPromptModel, + ArrowConfig, + BdLoraConfig, + BOFTConfig, + BOFTModel, + C3AConfig, + C3AModel, + CartridgeConfig, + CartridgeEncoder, + CPTConfig, + CPTEmbedding, + DeloraConfig, + DeloraModel, + EvaConfig, + FourierFTConfig, + FourierFTModel, + GraloraConfig, + GraloraModel, + HRAConfig, + HRAModel, + IA3Config, + IA3Model, + LilyConfig, + LilyModel, + LNTuningConfig, + LNTuningModel, + LoftQConfig, + LoHaConfig, + LoHaModel, + LoKrConfig, + LoKrModel, + LoraConfig, + LoraGAConfig, + LoraModel, + LoraRuntimeConfig, + MissConfig, + MissModel, + MultitaskPromptTuningConfig, + MultitaskPromptTuningInit, + OFTConfig, + OFTModel, + OSFConfig, + OSFModel, + PolyConfig, + PolyModel, + PrefixEncoder, + PrefixTuningConfig, + PromptEmbedding, + PromptEncoder, + PromptEncoderConfig, + PromptEncoderReparameterizationType, + PromptTuningConfig, + PromptTuningInit, + PsoftConfig, + PsoftModel, + PveraConfig, + PveraModel, + RandLoraConfig, + RandLoraModel, + RoadConfig, + RoadModel, + ShiraConfig, + ShiraModel, + TrainableTokensConfig, + TrainableTokensModel, + VBLoRAConfig, + VBLoRAModel, + VeraConfig, + VeraModel, + WaveFTConfig, + WaveFTModel, + XLoraConfig, + XLoraModel, + convert_to_lora, + create_arrow_model, + get_eva_state_dict, + initialize_lora_eva_weights, + preprocess_loraga, + save_as_lora, +) +from .tuners.cartridge.utils import ( + compose_cartridge_adapters, + initialize_kv_prefix_from_past_key_values, + initialize_kv_prefix_from_text, + prompt_embeddings_from_past_key_values, +) +from .utils import ( + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + PeftType, + PeftWarning, + TaskType, + bloom_model_postprocess_past_key_value, + cast_mixed_precision_params, + get_peft_model_state_dict, + load_peft_weights, + prepare_model_for_kbit_training, + replace_lora_weights_loftq, + set_peft_model_state_dict, + shift_tokens_right, +) + + +__all__ = [ + "MODEL_TYPE_TO_PEFT_MODEL_MAPPING", + "PEFT_TYPE_TO_CONFIG_MAPPING", + "PEFT_TYPE_TO_MIXED_MODEL_MAPPING", + "PEFT_TYPE_TO_TUNER_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "AdaLoraConfig", + "AdaLoraModel", + "AdaptionPromptConfig", + "AdaptionPromptModel", + "ArrowConfig", + "AutoPeftModel", + "AutoPeftModelForCausalLM", + "AutoPeftModelForFeatureExtraction", + "AutoPeftModelForQuestionAnswering", + "AutoPeftModelForSeq2SeqLM", + "AutoPeftModelForSequenceClassification", + "AutoPeftModelForTokenClassification", + "BOFTConfig", + "BOFTModel", + "BdLoraConfig", + "C3AConfig", + "C3AModel", + "CPTConfig", + "CPTEmbedding", + "CartridgeConfig", + "CartridgeEncoder", + "DeloraConfig", + "DeloraModel", + "EvaConfig", + "FourierFTConfig", + "FourierFTModel", + "GraloraConfig", + "GraloraModel", + "HRAConfig", + "HRAModel", + "IA3Config", + "IA3Model", + "LNTuningConfig", + "LNTuningModel", + "LilyConfig", + "LilyModel", + "LoHaConfig", + "LoHaModel", + "LoKrConfig", + "LoKrModel", + "LoftQConfig", + "LoraConfig", + "LoraGAConfig", + "LoraModel", + "LoraRuntimeConfig", + "MissConfig", + "MissModel", + "MultitaskPromptTuningConfig", + "MultitaskPromptTuningInit", + "OFTConfig", + "OFTModel", + "OSFConfig", + "OSFModel", + "PeftConfig", + "PeftMixedModel", + "PeftModel", + "PeftModelForCausalLM", + "PeftModelForFeatureExtraction", + "PeftModelForQuestionAnswering", + "PeftModelForSeq2SeqLM", + "PeftModelForSequenceClassification", + "PeftModelForTokenClassification", + "PeftType", + "PeftWarning", + "PolyConfig", + "PolyModel", + "PrefixEncoder", + "PrefixTuningConfig", + "PromptEmbedding", + "PromptEncoder", + "PromptEncoderConfig", + "PromptEncoderReparameterizationType", + "PromptLearningConfig", + "PromptTuningConfig", + "PromptTuningInit", + "PsoftConfig", + "PsoftModel", + "PveraConfig", + "PveraModel", + "RandLoraConfig", + "RandLoraModel", + "RoadConfig", + "RoadModel", + "ShiraConfig", + "ShiraModel", + "TaskType", + "TrainableTokensConfig", + "TrainableTokensModel", + "VBLoRAConfig", + "VBLoRAConfig", + "VBLoRAModel", + "VeraConfig", + "VeraModel", + "WaveFTConfig", + "WaveFTModel", + "XLoraConfig", + "XLoraModel", + "bloom_model_postprocess_past_key_value", + "cast_mixed_precision_params", + "compose_cartridge_adapters", + "convert_to_lora", + "create_arrow_model", + "get_eva_state_dict", + "get_layer_status", + "get_model_status", + "get_peft_config", + "get_peft_model", + "get_peft_model_state_dict", + "initialize_kv_prefix_from_past_key_values", + "initialize_kv_prefix_from_text", + "initialize_lora_eva_weights", + "inject_adapter_in_model", + "load_peft_weights", + "prepare_model_for_kbit_training", + "preprocess_loraga", + "prompt_embeddings_from_past_key_values", + "replace_lora_weights_loftq", + "save_as_lora", + "set_peft_model_state_dict", + "shift_tokens_right", +] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/auto.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/auto.py new file mode 100644 index 0000000000000000000000000000000000000000..613f67c707e344eab1a5281565fb0fdb3d827d01 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/auto.py @@ -0,0 +1,184 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import importlib +import os +from typing import Optional + +from transformers import ( + AutoModel, + AutoModelForCausalLM, + AutoModelForQuestionAnswering, + AutoModelForSeq2SeqLM, + AutoModelForSequenceClassification, + AutoModelForTokenClassification, + AutoTokenizer, +) + +from .config import PeftConfig +from .peft_model import ( + PeftModel, + PeftModelForCausalLM, + PeftModelForFeatureExtraction, + PeftModelForQuestionAnswering, + PeftModelForSeq2SeqLM, + PeftModelForSequenceClassification, + PeftModelForTokenClassification, +) +from .utils.constants import TOKENIZER_CONFIG_NAME +from .utils.other import check_file_exists_on_hf_hub + + +MODEL_TYPE_TO_PEFT_MODEL_MAPPING: dict[str, type[PeftModel]] = { + "SEQ_CLS": PeftModelForSequenceClassification, + "SEQ_2_SEQ_LM": PeftModelForSeq2SeqLM, + "CAUSAL_LM": PeftModelForCausalLM, + "TOKEN_CLS": PeftModelForTokenClassification, + "QUESTION_ANS": PeftModelForQuestionAnswering, + "FEATURE_EXTRACTION": PeftModelForFeatureExtraction, +} + + +class _BaseAutoPeftModel: + _target_class = None + _target_peft_class = None + + def __init__(self, *args, **kwargs): + # For consistency with transformers: https://github.com/huggingface/transformers/blob/91d7df58b6537d385e90578dac40204cb550f706/src/transformers/models/auto/auto_factory.py#L400 + raise EnvironmentError( # noqa: UP024 + f"{self.__class__.__name__} is designed to be instantiated " + f"using the `{self.__class__.__name__}.from_pretrained(pretrained_model_name_or_path)` or " + f"`{self.__class__.__name__}.from_config(config)` methods." + ) + + @classmethod + def from_pretrained( + cls, + pretrained_model_name_or_path, + adapter_name: str = "default", + is_trainable: bool = False, + config: Optional[PeftConfig] = None, + revision: Optional[str] = None, + **kwargs, + ): + r""" + A wrapper around all the preprocessing steps a user needs to perform in order to load a PEFT model. The kwargs + are passed along to `PeftConfig` that automatically takes care of filtering the kwargs of the Hub methods and + the config object init. + """ + peft_config = PeftConfig.from_pretrained(pretrained_model_name_or_path, revision=revision, **kwargs) + base_model_path = peft_config.base_model_name_or_path + base_model_revision = peft_config.revision + + task_type = getattr(peft_config, "task_type", None) + + if cls._target_class is not None: + target_class = cls._target_class + elif cls._target_class is None and task_type is not None: + # this is only in the case where we use `AutoPeftModel` + raise ValueError( + "Cannot use `AutoPeftModel` with a task type, please use a specific class for your task type. (e.g. `AutoPeftModelForCausalLM` for `task_type='CAUSAL_LM'`)" + ) + + if task_type is not None: + expected_target_class = MODEL_TYPE_TO_PEFT_MODEL_MAPPING[task_type] + if cls._target_peft_class.__name__ != expected_target_class.__name__: + raise ValueError( + f"Expected target PEFT class: {expected_target_class.__name__}, but you have asked for: {cls._target_peft_class.__name__}" + " make sure that you are loading the correct model for your task type." + ) + elif task_type is None and getattr(peft_config, "auto_mapping", None) is not None: + auto_mapping = getattr(peft_config, "auto_mapping", None) + base_model_class = auto_mapping["base_model_class"] + parent_library_name = auto_mapping["parent_library"] + + parent_library = importlib.import_module(parent_library_name) + target_class = getattr(parent_library, base_model_class) + else: + raise ValueError( + "Cannot infer the auto class from the config, please make sure that you are loading the correct model for your task type." + ) + + base_model = target_class.from_pretrained(base_model_path, revision=base_model_revision, **kwargs) + + tokenizer_exists = False + if os.path.exists(os.path.join(pretrained_model_name_or_path, TOKENIZER_CONFIG_NAME)): + tokenizer_exists = True + else: + token = kwargs.get("token", None) + if token is None: + token = kwargs.get("use_auth_token", None) + + tokenizer_exists = check_file_exists_on_hf_hub( + repo_id=pretrained_model_name_or_path, + filename=TOKENIZER_CONFIG_NAME, + revision=revision, + repo_type=kwargs.get("repo_type", None), + token=token, + ) + + if tokenizer_exists and hasattr(base_model, "get_input_embeddings"): + tokenizer = AutoTokenizer.from_pretrained( + pretrained_model_name_or_path, trust_remote_code=kwargs.get("trust_remote_code", False) + ) + embedding_size = base_model.get_input_embeddings().weight.shape[0] + if len(tokenizer) > embedding_size: + # only resize if the tokenizer has a larger vocab size than there are embeddings + base_model.resize_token_embeddings(len(tokenizer)) + + return cls._target_peft_class.from_pretrained( + base_model, + pretrained_model_name_or_path, + adapter_name=adapter_name, + is_trainable=is_trainable, + config=config, + **kwargs, + ) + + +class AutoPeftModel(_BaseAutoPeftModel): + _target_class = None + _target_peft_class = PeftModel + + +class AutoPeftModelForCausalLM(_BaseAutoPeftModel): + _target_class = AutoModelForCausalLM + _target_peft_class = PeftModelForCausalLM + + +class AutoPeftModelForSeq2SeqLM(_BaseAutoPeftModel): + _target_class = AutoModelForSeq2SeqLM + _target_peft_class = PeftModelForSeq2SeqLM + + +class AutoPeftModelForSequenceClassification(_BaseAutoPeftModel): + _target_class = AutoModelForSequenceClassification + _target_peft_class = PeftModelForSequenceClassification + + +class AutoPeftModelForTokenClassification(_BaseAutoPeftModel): + _target_class = AutoModelForTokenClassification + _target_peft_class = PeftModelForTokenClassification + + +class AutoPeftModelForQuestionAnswering(_BaseAutoPeftModel): + _target_class = AutoModelForQuestionAnswering + _target_peft_class = PeftModelForQuestionAnswering + + +class AutoPeftModelForFeatureExtraction(_BaseAutoPeftModel): + _target_class = AutoModel + _target_peft_class = PeftModelForFeatureExtraction diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..60a5c20c74bc2b8b97a5e0262e99cc10a79be481 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/config.py @@ -0,0 +1,408 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import importlib.metadata +import inspect +import json +import os +import warnings +from dataclasses import asdict, dataclass, field +from typing import Optional, Union + +import packaging.version +from huggingface_hub import hf_hub_download +from transformers.utils import PushToHubMixin, http_user_agent + +from peft import __version__ + +from .utils import CONFIG_NAME, PeftType, TaskType + + +# we expect at least these keys to be present in a PEFT adapter_config.json +MIN_EXPECTED_CONFIG_KEYS = {"peft_type"} + + +def _check_and_remove_unused_kwargs(cls, kwargs): + """Make PEFT configs forward-compatible by removing unused kwargs that were added in later PEFT versions. + + This assumes that removing the unused kwargs will not affect the default behavior. + + Returns the filtered kwargs and the set of removed keys. + """ + # it's not pretty but eh + signature_parameters = inspect.signature(cls.__init__).parameters + unexpected_kwargs = set(kwargs.keys()) - set(signature_parameters.keys()) + for key in unexpected_kwargs: + del kwargs[key] + return kwargs, unexpected_kwargs + + +def _is_dev_version(version: str) -> bool: + # check if the given version is a dev version + return packaging.version.Version(version).dev is not None + + +def _get_commit_hash(pkg_name: str) -> str | None: + # If PEFT was installed from a specific commit hash, try to get it. This works e.g. when installing PEFT with `pip + # install git+https://github.com/huggingface/peft.git@`. This works not for other means, like editable + # installs. + try: + dist = importlib.metadata.distribution(pkg_name) + except importlib.metadata.PackageNotFoundError: + return None + + # See: https://packaging.python.org/en/latest/specifications/direct-url/ + for path in dist.files or []: + if path.name == "direct_url.json": + direct_url = json.loads((dist.locate_file(path)).read_text()) + vcs_info = direct_url.get("vcs_info") + if vcs_info and "commit_id" in vcs_info: + return vcs_info["commit_id"] + return None + + +@dataclass +class PeftConfigMixin(PushToHubMixin): + r""" + This is the base configuration class for PEFT adapter models. It contains all the methods that are common to all + PEFT adapter models. This class inherits from [`~transformers.utils.PushToHubMixin`] which contains the methods to + push your model to the Hub. The method `save_pretrained` will save the configuration of your adapter model in a + directory. The method `from_pretrained` will load the configuration of your adapter model from a directory. + + Args: + peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use. + """ + + task_type: Optional[TaskType] = field(default=None, metadata={"help": "The type of task."}) + peft_type: Optional[PeftType] = field(default=None, metadata={"help": "The type of PEFT model."}) + auto_mapping: Optional[dict] = field( + default=None, metadata={"help": "An auto mapping dict to help retrieve the base model class if needed."} + ) + peft_version: Optional[str] = field(default=None, metadata={"help": "PEFT version, leave empty to auto-fill."}) + + def __post_init__(self): + # check for invalid task type + if (self.task_type is not None) and (self.task_type not in list(TaskType)): + raise ValueError( + f"Invalid task type: '{self.task_type}'. Must be one of the following task types: {', '.join(TaskType)}." + ) + if self.peft_version is None: + self.peft_version = self._get_peft_version() + + @staticmethod + def _get_peft_version() -> str: + # gets the current peft version; if it's a dev version, try to get the commit hash too, as the dev version is + # ambiguous + version = __version__ + if not _is_dev_version(version): + return version + + try: + git_hash = _get_commit_hash("peft") + if git_hash is None: + git_hash = "UNKNOWN" + except Exception: + # Broad exception: We never want to break user code just because the git_hash could not be determined + warnings.warn( + "A dev version of PEFT is used but there was an error while trying to determine the commit hash. " + "Please open an issue: https://github.com/huggingface/peft/issues" + ) + git_hash = "UNKNOWN" + version = version + f"@{git_hash}" + return version + + def to_dict(self) -> dict: + r""" + Returns the configuration for your adapter model as a dictionary. + """ + return asdict(self) + + def save_pretrained(self, save_directory: str, **kwargs) -> None: + r""" + This method saves the configuration of your adapter model in a directory. + + Args: + save_directory (`str`): + The directory where the configuration will be saved. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the [`~transformers.utils.PushToHubMixin.push_to_hub`] + method. + """ + if os.path.isfile(save_directory): + raise AssertionError(f"Provided path ({save_directory}) should be a directory, not a file") + + os.makedirs(save_directory, exist_ok=True) + auto_mapping_dict = kwargs.pop("auto_mapping_dict", None) + + output_dict = self.to_dict() + # converting set type to list + for key, value in output_dict.items(): + if isinstance(value, set): + output_dict[key] = list(value) + + output_path = os.path.join(save_directory, CONFIG_NAME) + + # Add auto mapping details for custom models. + if auto_mapping_dict is not None: + output_dict["auto_mapping"] = auto_mapping_dict + + # save it + with open(output_path, "w") as writer: + writer.write(json.dumps(output_dict, indent=2, sort_keys=True)) + + @classmethod + def from_peft_type(cls, **kwargs): + r""" + This method loads the configuration of your adapter model from a set of kwargs. + + The appropriate configuration type is determined by the `peft_type` argument. If `peft_type` is not provided, + the calling class type is instantiated. + + Args: + kwargs (configuration keyword arguments): + Keyword arguments passed along to the configuration initialization. + """ + # Avoid circular dependency .. TODO: fix this with a larger refactor + from peft.mapping import PEFT_TYPE_TO_CONFIG_MAPPING + + # TODO: this hack is needed to fix the following issue (on commit 702f937): + # if someone saves a default config and loads it back with `PeftConfig` class it yields to + # not loading the correct config class. + # + # from peft import AdaLoraConfig, PeftConfig + # peft_config = AdaLoraConfig() + # print(peft_config) + # >>> AdaLoraConfig(peft_type=, auto_mapping=None, base_model_name_or_path=None, + # revision=None, task_type=None, inference_mode=False, r=8, target_modules=None, lora_alpha=8, lora_dropout=0.0, ... + # + # peft_config.save_pretrained("./test_config") + # peft_config = PeftConfig.from_pretrained("./test_config") + # print(peft_config) + # >>> PeftConfig(peft_type='ADALORA', auto_mapping=None, base_model_name_or_path=None, revision=None, task_type=None, inference_mode=False) + + if "peft_type" in kwargs: + peft_type = kwargs["peft_type"] + config_cls = PEFT_TYPE_TO_CONFIG_MAPPING[peft_type] + else: + config_cls = cls + + try: + config = config_cls(**kwargs) + except TypeError as exc: + # Here we potentially handle forward compatibility. Sometimes new keywords are added to configs, which makes + # new configs incompatible with older PEFT versions. We catch these and remove them to allow the program to + # continue, but warn the user about it. + + # First check if the error is due to unexpected keyword arguments, we don't want to accidentally catch + # other TypeErrors. + if "got an unexpected keyword argument" not in str(exc): + raise exc + + filtered_kwargs, unexpected_kwargs = _check_and_remove_unused_kwargs(config_cls, kwargs) + if not MIN_EXPECTED_CONFIG_KEYS.issubset(set(filtered_kwargs.keys())): + raise TypeError( + f"The {cls.__name__} config that is trying to be loaded is missing required keys: " + f"{MIN_EXPECTED_CONFIG_KEYS}." + ) + + warnings.warn( + f"Unexpected keyword arguments {sorted(unexpected_kwargs)} for class {config_cls.__name__}, these are " + "ignored. This probably means that you're loading a configuration file that was saved using a " + "higher version of the library and additional parameters have been introduced since. It is " + "highly recommended to upgrade the PEFT version before continuing (e.g. by running `pip install " + "-U peft`)." + ) + config = config_cls.from_peft_type(**filtered_kwargs) + return config + + @classmethod + def from_pretrained(cls, pretrained_model_name_or_path: str, subfolder: Optional[str] = None, **kwargs): + r""" + This method loads the configuration of your adapter model from a directory. + + Args: + pretrained_model_name_or_path (`str`): + The directory or the Hub repository id where the configuration is saved. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the child class initialization. + """ + path = ( + os.path.join(pretrained_model_name_or_path, subfolder) + if subfolder is not None + else pretrained_model_name_or_path + ) + + hf_hub_download_kwargs, class_kwargs, _ = cls._split_kwargs(kwargs) + if "user_agent" not in hf_hub_download_kwargs: + hf_hub_download_kwargs["user_agent"] = http_user_agent() + + if os.path.isfile(os.path.join(path, CONFIG_NAME)): + config_file = os.path.join(path, CONFIG_NAME) + else: + try: + config_file = hf_hub_download( + pretrained_model_name_or_path, CONFIG_NAME, subfolder=subfolder, **hf_hub_download_kwargs + ) + except Exception as exc: + raise ValueError(f"Can't find '{CONFIG_NAME}' at '{pretrained_model_name_or_path}'") from exc + + loaded_attributes = cls.from_json_file(config_file) + kwargs = {**class_kwargs, **loaded_attributes} + kwargs = cls.check_kwargs(**kwargs) + return cls.from_peft_type(**kwargs) + + @classmethod + def from_json_file(cls, path_json_file: str, **kwargs): + r""" + Loads a configuration file from a json file. + + Args: + path_json_file (`str`): + The path to the json file. + """ + with open(path_json_file) as file: + json_object = json.load(file) + + # Sanity check that config does not contain a runtime_config + if "runtime_config" in json_object: + warnings.warn( + "The configuration file contains a `runtime_config` key. This is ignored. Runtime configurations are only valid at runtime." + ) + del json_object["runtime_config"] + + return json_object + + @classmethod + def _split_kwargs(cls, kwargs): + hf_hub_download_kwargs = {} + class_kwargs = {} + other_kwargs = {} + + for key, value in kwargs.items(): + if key in inspect.signature(hf_hub_download).parameters: + hf_hub_download_kwargs[key] = value + elif key in list(cls.__annotations__): + class_kwargs[key] = value + else: + other_kwargs[key] = value + + return hf_hub_download_kwargs, class_kwargs, other_kwargs + + @classmethod + def _get_peft_type( + cls, + model_id: str, + **hf_hub_download_kwargs, + ): + subfolder = hf_hub_download_kwargs.get("subfolder", None) + + path = os.path.join(model_id, subfolder) if subfolder is not None else model_id + + if os.path.isfile(os.path.join(path, CONFIG_NAME)): + config_file = os.path.join(path, CONFIG_NAME) + else: + try: + config_file = hf_hub_download( + model_id, + CONFIG_NAME, + **hf_hub_download_kwargs, + ) + except Exception: + raise ValueError(f"Can't find '{CONFIG_NAME}' at '{model_id}'") + + loaded_attributes = cls.from_json_file(config_file) + return loaded_attributes["peft_type"] + + @classmethod + def check_kwargs(cls, **kwargs): + """Check kwargs before initializing the config instance. + + Subclasses can override this method to add specific checks. + + """ + return kwargs + + @property + def is_prompt_learning(self) -> bool: + r""" + Utility method to check if the configuration is for prompt learning. + """ + return False + + @property + def is_adaption_prompt(self) -> bool: + """Return True if this is an adaption prompt config.""" + return False + + +@dataclass +class PeftConfig(PeftConfigMixin): + """ + This is the base configuration class to store the configuration of a [`PeftModel`]. + + Args: + peft_type (Union[[`~peft.utils.config.PeftType`], `str`]): The type of Peft method to use. + task_type (Union[[`~peft.utils.config.TaskType`], `str`]): The type of task to perform. + inference_mode (`bool`, defaults to `False`): Whether to use the Peft model in inference mode. + """ + + base_model_name_or_path: Optional[str] = field( + default=None, metadata={"help": "The name of the base model to use."} + ) + revision: Optional[str] = field(default=None, metadata={"help": "The specific base model version to use."}) + peft_type: Optional[Union[str, PeftType]] = field(default=None, metadata={"help": "Peft type"}) + task_type: Optional[Union[str, TaskType]] = field(default=None, metadata={"help": "Task type"}) + inference_mode: bool = field(default=False, metadata={"help": "Whether to use inference mode"}) + + +@dataclass +class PromptLearningConfig(PeftConfig): + """ + This is the base configuration class to store the configuration of [`PrefixTuning`], [`PromptEncoder`], or + [`PromptTuning`]. + + Args: + num_virtual_tokens (`int`): The number of virtual tokens to use. + token_dim (`int`): The hidden embedding dimension of the base transformer model. + num_transformer_submodules (`int`): The number of transformer submodules in the base transformer model. + num_attention_heads (`int`): The number of attention heads in the base transformer model. + num_layers (`int`): The number of layers in the base transformer model. + """ + + num_virtual_tokens: int = field(default=None, metadata={"help": "Number of virtual tokens"}) + token_dim: int = field( + default=None, metadata={"help": "The hidden embedding dimension of the base transformer model"} + ) + num_transformer_submodules: Optional[int] = field( + default=None, metadata={"help": "Number of transformer submodules"} + ) + num_attention_heads: Optional[int] = field(default=None, metadata={"help": "Number of attention heads"}) + num_layers: Optional[int] = field(default=None, metadata={"help": "Number of transformer layers"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of extra modules to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved. " + "The module(s) will be fully fine-tuned." + }, + ) + + @property + def is_prompt_learning(self) -> bool: + r""" + Utility method to check if the configuration is for prompt learning. + """ + return True diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/functional.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/functional.py new file mode 100644 index 0000000000000000000000000000000000000000..60df690cafe1e9a3b5c8ff09d550f82110afe593 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/functional.py @@ -0,0 +1,34 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Functions that are useful for integration with non-PeftModel models, e.g. transformers or diffusers. + +The functions provided here can be considered "public API" of PEFT and hence are safe to be used by packages that +provide PEFT integrations. +""" + +from peft.mapping import inject_adapter_in_model +from peft.tuners.tuners_utils import cast_adapter_dtype, delete_adapter, set_adapter, set_requires_grad +from peft.utils import get_peft_model_state_dict, set_peft_model_state_dict + + +__all__ = [ + "cast_adapter_dtype", + "delete_adapter", + "get_peft_model_state_dict", + "inject_adapter_in_model", + "set_adapter", + "set_peft_model_state_dict", + "set_requires_grad", +] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/helpers.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/helpers.py new file mode 100644 index 0000000000000000000000000000000000000000..612952841455beaaf257d066b9859c58339df63e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/helpers.py @@ -0,0 +1,295 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import inspect +from contextlib import contextmanager +from copy import deepcopy +from functools import update_wrapper +from types import MethodType + +from torch import nn + +from .peft_model import PeftConfig, PeftModel +from .tuners.lora import LoraLayer, dora +from .tuners.tuners_utils import BaseTunerLayer + + +def update_forward_signature(model: PeftModel) -> None: + """ + Updates the forward signature of the PeftModel to include parents class signature + model (`PeftModel`): Peft model to update the forward signature + + Example: + + ```python + >>> from transformers import WhisperForConditionalGeneration + >>> from peft import get_peft_model, LoraConfig, update_forward_signature + + >>> model = WhisperForConditionalGeneration.from_pretrained("openai/whisper-tiny.en") + >>> peft_config = LoraConfig(r=8, lora_alpha=32, lora_dropout=0.1, target_modules=["q_proj", "v_proj"]) + + >>> peft_model = get_peft_model(model, peft_config) + >>> update_forward_signature(peft_model) + ``` + """ + + # Only update signature when the current forward signature only has *args and **kwargs + current_signature = inspect.signature(model.forward) + if ( + len(current_signature.parameters) == 2 + and "args" in current_signature.parameters + and "kwargs" in current_signature.parameters + ): + forward = deepcopy(model.forward.__func__) + update_wrapper( + forward, type(model.get_base_model()).forward, assigned=("__doc__", "__name__", "__annotations__") + ) + model.forward = MethodType(forward, model) + + +def update_generate_signature(model: PeftModel) -> None: + """ + Updates the generate signature of a PeftModel with overriding generate to include parents class signature + model (`PeftModel`): Peft model to update the generate signature + + Example: + + ```python + >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + >>> from peft import get_peft_model, LoraConfig, TaskType, update_generate_signature + + >>> model_name_or_path = "bigscience/mt0-large" + >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) + >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path) + + >>> peft_config = LoraConfig( + ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1 + ... ) + >>> peft_model = get_peft_model(model, peft_config) + >>> update_generate_signature(peft_model) + >>> help(peft_model.generate) + ``` + """ + if not hasattr(model, "generate"): + return + current_signature = inspect.signature(model.generate) + if ( + len(current_signature.parameters) == 2 + and "args" in current_signature.parameters + and "kwargs" in current_signature.parameters + ) or (len(current_signature.parameters) == 1 and "kwargs" in current_signature.parameters): + generate = deepcopy(model.generate.__func__) + update_wrapper( + generate, + type(model.get_base_model()).generate, + assigned=("__doc__", "__name__", "__annotations__"), + ) + model.generate = MethodType(generate, model) + + +def update_signature(model: PeftModel, method: str = "all") -> None: + """ + Updates the signature of a PeftModel include parents class signature for forward or generate method + model (`PeftModel`): Peft model to update generate or forward signature method (`str`): method to update + signature choose one of "forward", "generate", "all" + + Example: + ```python + >>> from transformers import AutoModelForSeq2SeqLM, AutoTokenizer + >>> from peft import get_peft_model, LoraConfig, TaskType, update_signature + + >>> model_name_or_path = "bigscience/mt0-large" + >>> tokenizer = AutoTokenizer.from_pretrained(model_name_or_path) + >>> model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path) + + >>> peft_config = LoraConfig( + ... task_type=TaskType.SEQ_2_SEQ_LM, inference_mode=False, r=8, lora_alpha=32, lora_dropout=0.1 + ... ) + >>> peft_model = get_peft_model(model, peft_config) + >>> update_signature(peft_model) + >>> help(peft_model.generate) + ``` + """ + if method == "forward": + update_forward_signature(model) + elif method == "generate": + update_generate_signature(model) + elif method == "all": + update_forward_signature(model) + update_generate_signature(model) + else: + raise ValueError(f"method {method} is not supported please choose one of ['forward', 'generate', 'all']") + + +def check_if_peft_model(model_name_or_path: str) -> bool: + """ + Check if the model is a PEFT model. + + Args: + model_name_or_path (`str`): + Model id to check, can be local or on the Hugging Face Hub. + + Returns: + `bool`: True if the model is a PEFT model, False otherwise. + """ + is_peft_model = True + try: + PeftConfig.from_pretrained(model_name_or_path) + except Exception: + # allow broad exceptions so that this works even if new exceptions are added on HF Hub side + is_peft_model = False + + return is_peft_model + + +@contextmanager +def rescale_adapter_scale(model, multiplier): + """ + Context manager to temporarily rescale the scaling of the LoRA adapter in a model. + + The original scaling values are restored when the context manager exits. This context manager works with the + transformers and diffusers models that have directly loaded LoRA adapters. + + For LoRA, applying this context manager with multiplier in [0, 1] is strictly equivalent to applying + [wise-ft](https://huggingface.co/papers/2109.01903) (see [#1940](https://github.com/huggingface/peft/issues/1940) + for details). It can improve the performances of the model if there is a distribution shiftbetween the training + data used for fine-tuning, and the test data used during inference. + + Warning: It has been reported that when using Apple's MPS backend for PyTorch, it is necessary to add a short sleep + time after exiting the context before the scales are fully restored. + + Args: + model: The model containing `LoraLayer` modules whose scaling is to be adjusted. + multiplier (float or int): + The multiplier that rescales the `scaling` attribute. Must be of type float or int. + + Raises: + ValueError: If the model does not contain any `LoraLayer` + instances, indicating that the model does not support scaling. + + Example: + + ```python + >>> model = ModelWithLoraLayer() + >>> multiplier = 0.5 + >>> with rescale_adapter_scale(model, multiplier): + ... outputs = model(**inputs) # Perform operations with the scaled model + >>> outputs = model(**inputs) # The original scaling values are restored here + ``` + """ + # check if multiplier has a valid data type + if not isinstance(multiplier, (float, int)): + raise TypeError(f"Argument multiplier should be of type float, got {type(multiplier)}") + + # iterate on the model's modules and grab the original scaling attribute + # from the lora layers if present + original_scaling = {} + for module in model.modules(): + if isinstance(module, LoraLayer): + original_scaling[module] = module.scaling.copy() + module.scaling = {k: v * multiplier for k, v in module.scaling.items()} + + # check whether scaling is prohibited on model + # the original scaling dictionary should be empty + # if there were no lora layers + if not original_scaling: + raise ValueError("scaling is only supported for models with `LoraLayer`s") + try: + yield + + finally: + # restore original scaling values after exiting the context + for module, scaling in original_scaling.items(): + module.scaling = scaling + + +@contextmanager +def disable_input_dtype_casting(model: nn.Module, active: bool = True): + """ + Context manager disables input dtype casting to the dtype of the weight. + + Parameters: + model (nn.Module): + The model containing PEFT modules whose input dtype casting is to be adjusted. + active (bool): + Whether the context manager is active (default) or inactive. + + """ + # Additional info: Normally, the dtype of the weight and input need to match, which is why the dtype is cast. + # However, in certain circumustances, this is handled by forward hooks, e.g. when using layerwise casting in + # diffusers. In that case, PEFT casting the dtype interferes with the layerwise casting, which is why the option to + # disable it is given. + if not active: + yield + return + + original_values = {} + for name, module in model.named_modules(): + if not isinstance(module, BaseTunerLayer): + continue + original_values[name] = module.cast_input_dtype_enabled + module.cast_input_dtype_enabled = False + + try: + yield + finally: + for name, module in model.named_modules(): + if not isinstance(module, BaseTunerLayer): + continue + if name in original_values: + module.cast_input_dtype_enabled = original_values[name] + + +class DoraCaching: + """Context manager to enable DoRA caching, which improves speed of DoRA inference at the expense of memory. + + With active caching, the materialized LoRA weight (B @ A) and the weight norm (base weight + LoRA weight) are + cached. + + Even within the caching context, if the model is in training mode, caching is disabled. When the model switches to + training mode, the cache will be cleared. + + Example: + + ```py + >>> from peft.helpers import enable_dora_scaling + + >>> model.eval() # put in eval model for caching to work + + >>> with DoraCaching(): # use as a context manager + ... output = model(inputs) + + >>> dora_caching = DoraCaching() + >>> dora_caching(enabled=True) # permanently enable caching + >>> output = model(inputs) + >>> dora_caching(enabled=False) # permanently disable caching + >>> output = model(inputs) + ``` + + """ + + def __init__(self, enabled: bool = True) -> None: + self.enabled = enabled + self.prev_value = None + + def __enter__(self): + self.prev_value = dora.ENABLE_DORA_CACHING + dora.ENABLE_DORA_CACHING = self.enabled + + def __exit__(self, type, value, traceback): + dora.ENABLE_DORA_CACHING = self.prev_value + self.prev_value = None + + def __call__(self, enabled: bool = True): + dora.ENABLE_DORA_CACHING = enabled diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/import_utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/import_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..02b59c1ad7f09823f6d3276f01b40bb560b05444 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/import_utils.py @@ -0,0 +1,166 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import importlib +import importlib.metadata as importlib_metadata +import platform +from functools import lru_cache + +import packaging.version +import torch +import transformers + + +is_transformers_ge_v5 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.0.0.dev0") + +is_transformers_ge_v5_1_0 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("5.1.0") + +is_transformers_le_4_53 = packaging.version.parse(transformers.__version__) < packaging.version.parse("4.54.0.dev0") + + +@lru_cache +def is_bnb_available() -> bool: + return importlib.util.find_spec("bitsandbytes") is not None + + +@lru_cache +def is_bnb_4bit_available() -> bool: + if not is_bnb_available(): + return False + + import bitsandbytes as bnb + + return hasattr(bnb.nn, "Linear4bit") + + +@lru_cache +def is_gptqmodel_available(): + if importlib.util.find_spec("gptqmodel") is not None: + GPTQMODEL_MINIMUM_VERSION = packaging.version.parse("5.6.12") + OPTIMUM_MINIMUM_VERSION = packaging.version.parse("1.24.0") + version_gptqmodel = packaging.version.parse(importlib_metadata.version("gptqmodel")) + if GPTQMODEL_MINIMUM_VERSION <= version_gptqmodel: + if is_optimum_available(): + version_optimum = packaging.version.parse(importlib_metadata.version("optimum")) + if OPTIMUM_MINIMUM_VERSION <= version_optimum: + return True + else: + raise ImportError( + f"gptqmodel requires optimum version `{OPTIMUM_MINIMUM_VERSION}` or higher. Found version `{version_optimum}`, " + f"but only versions above `{OPTIMUM_MINIMUM_VERSION}` are supported" + ) + else: + raise ImportError( + f"gptqmodel requires optimum version `{OPTIMUM_MINIMUM_VERSION}` or higher to be installed." + ) + else: + raise ImportError( + f"Found an incompatible version of gptqmodel. Found version `{version_gptqmodel}`, " + f"but only versions above `{GPTQMODEL_MINIMUM_VERSION}` are supported" + ) + + +@lru_cache +def is_optimum_available() -> bool: + return importlib.util.find_spec("optimum") is not None + + +@lru_cache +def is_torch_tpu_available(check_device=True): + "Checks if `torch_xla` is installed and potentially if a TPU is in the environment" + if importlib.util.find_spec("torch_xla") is not None: + if check_device: + # We need to check if `xla_device` can be found, will raise a RuntimeError if not + try: + import torch_xla.core.xla_model as xm + + _ = xm.xla_device() + return True + except RuntimeError: + return False + return True + return False + + +@lru_cache +def is_aqlm_available(): + return importlib.util.find_spec("aqlm") is not None + + +@lru_cache +def is_eetq_available(): + return importlib.util.find_spec("eetq") is not None + + +@lru_cache +def is_hqq_available(): + return importlib.util.find_spec("hqq") is not None + + +@lru_cache +def is_inc_available(): + return importlib.util.find_spec("neural_compressor") is not None + + +@lru_cache +def is_torchao_available(): + if importlib.util.find_spec("torchao") is None: + return False + + TORCHAO_MINIMUM_VERSION = packaging.version.parse("0.4.0") + try: + torchao_version = packaging.version.parse(importlib_metadata.version("torchao")) + except importlib_metadata.PackageNotFoundError: + # Same idea as in diffusers: + # https://github.com/huggingface/diffusers/blob/9f06a0d1a4a998ac6a463c5be728c892f95320a8/src/diffusers/utils/import_utils.py#L351-L357 + # It's not clear under what circumstances `importlib_metadata.version("torchao")` can raise an error even + # though `importlib.util.find_spec("torchao") is not None` but it has been observed, so adding this for + # precaution. + return False + + if torchao_version < TORCHAO_MINIMUM_VERSION: + raise ImportError( + f"Found an incompatible version of torchao. Found version {torchao_version}, " + f"but only versions above {TORCHAO_MINIMUM_VERSION} are supported" + ) + return True + + +@lru_cache +def is_xpu_available(check_device=False): + """ + Checks if XPU acceleration is available and potentially if a XPU is in the environment + """ + + system = platform.system() + if system == "Darwin": + return False + else: + if check_device: + try: + # Will raise a RuntimeError if no XPU is found + _ = torch.xpu.device_count() + return torch.xpu.is_available() + except RuntimeError: + return False + return hasattr(torch, "xpu") and torch.xpu.is_available() + + +@lru_cache +def is_diffusers_available(): + return importlib.util.find_spec("diffusers") is not None + + +@lru_cache +def is_te_available(): + return importlib.util.find_spec("transformer_engine") is not None diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mapping.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mapping.py new file mode 100644 index 0000000000000000000000000000000000000000..82c6ec1e40bb7b06f505b82346245b8bf00d789c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mapping.py @@ -0,0 +1,92 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any, Optional + +import torch + +from .utils import PeftType + + +if TYPE_CHECKING: + from .config import PeftConfig + from .tuners.tuners_utils import BaseTuner + + +# these will be filled by the register_peft_method function +PEFT_TYPE_TO_CONFIG_MAPPING: dict[PeftType, type[PeftConfig]] = {} +PEFT_TYPE_TO_TUNER_MAPPING: dict[PeftType, type[BaseTuner]] = {} +PEFT_TYPE_TO_MIXED_MODEL_MAPPING: dict[PeftType, type[BaseTuner]] = {} +PEFT_TYPE_TO_PREFIX_MAPPING: dict[PeftType, str] = {} + + +def get_peft_config(config_dict: dict[str, Any]) -> PeftConfig: + """ + Returns a Peft config object from a dictionary. + + Args: + config_dict (`Dict[str, Any]`): Dictionary containing the configuration parameters. + """ + + return PEFT_TYPE_TO_CONFIG_MAPPING[config_dict["peft_type"]](**config_dict) + + +def inject_adapter_in_model( + peft_config: PeftConfig, + model: torch.nn.Module, + adapter_name: str = "default", + low_cpu_mem_usage: bool = False, + state_dict: Optional[dict[str, torch.Tensor]] = None, +) -> torch.nn.Module: + r""" + Create PEFT layers and inject them into the model in-place. + + Currently the API does not support prompt learning methods and adaption prompt. + + This function is similar to [`get_peft_model`] but it does not return a [`PeftModel`] instance. Instead, it returns + the original, mutated instance of the passed model. + + Args: + peft_config (`PeftConfig`): + Configuration object containing the parameters of the PEFT model. + model (`torch.nn.Module`): + The input model where the adapter will be injected. + adapter_name (`str`, `optional`, defaults to `"default"`): + The name of the adapter to be injected, if not provided, the default adapter name is used ("default"). + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + state_dict (`dict`, *optional*, defaults to `None`) + If a `state_dict` is passed here, the adapters will be injected based on the entries of the state_dict. + This can be useful when the exact `target_modules` of the PEFT method is unknown, for instance because the + checkpoint was created without meta data. Note that the values from the `state_dict` are not used, only the + keys are used to determine the correct layers that should be adapted. + """ + if peft_config.is_prompt_learning or peft_config.is_adaption_prompt: + raise ValueError("`create_and_replace` does not support prompt learning and adaption prompt yet.") + + if peft_config.peft_type not in PEFT_TYPE_TO_TUNER_MAPPING.keys(): + raise ValueError( + f"`inject_adapter_in_model` does not support {peft_config.peft_type} yet. Please use `get_peft_model`." + ) + + tuner_cls = PEFT_TYPE_TO_TUNER_MAPPING[peft_config.peft_type] + + # By instantiating a peft model we are injecting randomly initialized LoRA layers into the model's modules. + peft_model = tuner_cls( + model, peft_config, adapter_name=adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict + ) + + return peft_model.model diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mapping_func.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mapping_func.py new file mode 100644 index 0000000000000000000000000000000000000000..fae671819eb037e3a14f51dd2b94bffaaffaa819 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mapping_func.py @@ -0,0 +1,128 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import Optional + +from transformers import PreTrainedModel + +from .auto import MODEL_TYPE_TO_PEFT_MODEL_MAPPING +from .config import PeftConfig +from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING +from .mixed_model import PeftMixedModel +from .peft_model import PeftModel +from .tuners.tuners_utils import BaseTuner, BaseTunerLayer + + +def get_peft_model( + model: PreTrainedModel, + peft_config: PeftConfig, + adapter_name: str = "default", + mixed: bool = False, + autocast_adapter_dtype: bool = True, + revision: Optional[str] = None, + low_cpu_mem_usage: bool = False, +) -> PeftModel | PeftMixedModel: + """ + Returns a Peft model object from a model and a config, where the model will be modified in-place. + + Args: + model ([`transformers.PreTrainedModel`]): + Model to be wrapped. + peft_config ([`PeftConfig`]): + Configuration object containing the parameters of the Peft model. + adapter_name (`str`, `optional`, defaults to `"default"`): + The name of the adapter to be injected, if not provided, the default adapter name is used ("default"). + mixed (`bool`, `optional`, defaults to `False`): + Whether to allow mixing different (compatible) adapter types. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 or bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. + revision (`str`, `optional`, defaults to `main`): + The revision of the base model. If this isn't set, the saved peft model will load the `main` revision for + the base model + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. Leave this setting as + False if you intend on training the model, unless the adapter weights will be replaced by different weights + before training starts. + """ + model_config = BaseTuner.get_model_config(model) + old_name = peft_config.base_model_name_or_path + new_name = model.__dict__.get("name_or_path", None) + peft_config.base_model_name_or_path = new_name + + # Especially in notebook environments there could be a case that a user wants to experiment with different + # configuration values. However, it is likely that there won't be any changes for new configs on an already + # initialized PEFT model. The best we can do is warn the user about it. + if any(isinstance(module, BaseTunerLayer) for module in model.modules()): + warnings.warn( + "You are trying to modify a model with PEFT for a second time. If you want to reload the model with a " + "different config, make sure to call `.unload()` before." + ) + + if (old_name is not None) and (old_name != new_name): + warnings.warn( + f"The PEFT config's `base_model_name_or_path` was renamed from '{old_name}' to '{new_name}'. " + "Please ensure that the correct base model is loaded when loading this checkpoint." + ) + + if revision is not None: + if peft_config.revision is not None and peft_config.revision != revision: + warnings.warn( + f"peft config has already set base model revision to {peft_config.revision}, overwriting with revision {revision}" + ) + peft_config.revision = revision + + if ( + (isinstance(peft_config, PEFT_TYPE_TO_CONFIG_MAPPING["LORA"])) + and (peft_config.init_lora_weights == "eva") + and not low_cpu_mem_usage + ): + warnings.warn( + "lora with eva initialization used with low_cpu_mem_usage=False. " + "Setting low_cpu_mem_usage=True can improve the maximum batch size possible for eva initialization." + ) + + prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(peft_config.peft_type) + if prefix and adapter_name in prefix: + warnings.warn( + f"Adapter name '{adapter_name}' should not be contained in the prefix '{prefix}'. " + "This may lead to reinitialization of the adapter weights during loading." + ) + + if mixed: + # note: PeftMixedModel does not support autocast_adapter_dtype, so don't pass it + return PeftMixedModel(model, peft_config, adapter_name=adapter_name) + + # We explicitly exclude prompt learning here since prompt learning is specific to the task and needs special + # handling in the PEFT model's forward method. + if peft_config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys() and not peft_config.is_prompt_learning: + return PeftModel( + model, + peft_config, + adapter_name=adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + + return MODEL_TYPE_TO_PEFT_MODEL_MAPPING[peft_config.task_type]( + model, + peft_config, + adapter_name=adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mixed_model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mixed_model.py new file mode 100644 index 0000000000000000000000000000000000000000..26409a6ed77f645b0296c44661b67ea0fdf159d2 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/mixed_model.py @@ -0,0 +1,473 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import os +from contextlib import contextmanager +from typing import Any, Optional, Union + +import torch +from accelerate.hooks import remove_hook_from_submodules +from torch import nn +from transformers.utils import PushToHubMixin + +from peft.utils.constants import DUMMY_MODEL_CONFIG + +from .config import PeftConfig +from .peft_model import PeftModel +from .tuners import MixedModel +from .utils import _set_adapter, _set_trainable + + +def _prepare_model_for_gradient_checkpointing(model: nn.Module) -> None: + r""" + Prepares the model for gradient checkpointing if necessary + """ + # Note: same as PeftModel._prepare_model_for_gradient_checkpointing + if not getattr(model, "is_gradient_checkpointing", True): + return model + + if not ( + getattr(model, "is_loaded_in_8bit", False) + or getattr(model, "is_loaded_in_4bit", False) + or getattr(model, "is_quantized", False) + ): + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + elif hasattr(model, "get_input_embeddings"): + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + +def _check_config_compatible(peft_config: PeftConfig) -> None: + from .tuners.mixed import COMPATIBLE_TUNER_TYPES + + if peft_config.peft_type not in COMPATIBLE_TUNER_TYPES: + raise ValueError( + f"The provided `peft_type` '{peft_config.peft_type.value}' is not compatible with the `PeftMixedModel`. " + f"Compatible types are: {COMPATIBLE_TUNER_TYPES}" + ) + + +class PeftMixedModel(PushToHubMixin, torch.nn.Module): + """ + PeftMixedModel for loading mixing different types of adapters for inference. + + This class does not support loading/saving, and it shouldn't usually be initialized directly. Instead, use + `get_peft_model` with the argument `mixed=True`. + + > [!TIP] > Read the [Mixed adapter types](https://huggingface.co/docs/peft/en/developer_guides/mixed_models) guide + to learn > more about using different adapter types. + + Example: + + ```py + >>> base_model = ... # load the base model, e.g. from transformers + >>> peft_model = PeftMixedModel.from_pretrained(base_model, path_to_adapter1, "adapter1").eval() + >>> peft_model.load_adapter(path_to_adapter2, "adapter2") + >>> peft_model.set_adapter(["adapter1", "adapter2"]) # activate both adapters + >>> peft_model(data) # forward pass using both adapters + ``` + + Args: + model (`torch.nn.Module`): + The model to be tuned. + config (`PeftConfig`): + The config of the model to be tuned. The adapter type must be compatible. + adapter_name (`str`, `optional`, defaults to `"default"`): + The name of the first adapter. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + """ + + def __init__(self, model: nn.Module, peft_config: PeftConfig, adapter_name: str = "default") -> None: + super().__init__() + _check_config_compatible(peft_config) + _prepare_model_for_gradient_checkpointing(model) + self.modules_to_save = None + self.base_model = MixedModel(model, {adapter_name: peft_config}, adapter_name) + self.set_modules_to_save(peft_config, adapter_name) + + self.config = getattr(model, "config", DUMMY_MODEL_CONFIG) + + # the `pretraining_tp` is set for some models to simulate Tensor Parallelism during inference to avoid + # numerical differences, https://github.com/pytorch/pytorch/issues/76232 - to avoid any unexpected + # behavior we disable that in this line. + if hasattr(self.base_model, "config") and hasattr(self.base_model.config, "pretraining_tp"): + self.base_model.config.pretraining_tp = 1 + + @property + def peft_config(self) -> dict[str, PeftConfig]: + return self.base_model.peft_config + + @property + def active_adapter(self) -> str: + return self.base_model.active_adapter + + @property + def active_adapters(self) -> list[str]: + return self.base_model.active_adapters + + def get_nb_trainable_parameters(self): + r""" + Returns the number of trainable parameters and number of all parameters in the model. + """ + # note: same as PeftModel.get_nb_trainable_parameters + trainable_params = 0 + all_param = 0 + for _, param in self.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + num_params = param.ds_numel + + # Due to the design of 4bit linear layers from bitsandbytes + # one needs to multiply the number of parameters by 2 to get + # the correct number of parameters + if param.__class__.__name__ == "Params4bit": + num_params = num_params * 2 + + all_param += num_params + if param.requires_grad: + trainable_params += num_params + + return trainable_params, all_param + + def print_trainable_parameters(self): + """ + Prints the number of trainable parameters in the model. + + Note: print_trainable_parameters() uses get_nb_trainable_parameters() which is different from + num_parameters(only_trainable=True) from huggingface/transformers. get_nb_trainable_parameters() returns + (trainable parameters, all parameters) of the Peft Model which includes modified backbone transformer model. + For techniques like LoRA, the backbone transformer model is modified in place with LoRA modules. However, for + prompt tuning, the backbone transformer model is unmodified. num_parameters(only_trainable=True) returns number + of trainable parameters of the backbone transformer model which can be different. + """ + # note: same as PeftModel.print_trainable_parameters + trainable_params, all_param = self.get_nb_trainable_parameters() + + print( + f"trainable params: {trainable_params:,d} || " + f"all params: {all_param:,d} || " + f"trainable%: {100 * trainable_params / all_param:.4f}" + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "base_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.base_model, name) + + def forward(self, *args: Any, **kwargs: Any): + """ + Forward pass of the model. + """ + return self.base_model(*args, **kwargs) + + def generate(self, *args: Any, **kwargs: Any): + """ + Generate output. + """ + return self.base_model.generate(*args, **kwargs) + + @contextmanager + def disable_adapter(self): + """ + Disables the adapter module. + """ + try: + self.base_model.disable_adapter_layers() + yield + finally: + self.base_model.enable_adapter_layers() + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. + + > [!TIP] > Don't use `low_cpu_mem_usage=True` when creating a new PEFT adapter for training (training + is untested > and discouraged for PeftMixedModel in general). + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + """ + _check_config_compatible(peft_config) + + try: + self.peft_config[adapter_name] = peft_config + self.base_model.inject_adapter(self, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage) + except Exception: # something went wrong, roll back + if adapter_name in self.peft_config: + del self.peft_config[adapter_name] + raise + + self.base_model._cast_adapter_dtype(adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + self.set_modules_to_save(peft_config, adapter_name) + + def set_modules_to_save(self, peft_config: PeftConfig, adapter_name: str) -> None: + if (modules_to_save := getattr(peft_config, "modules_to_save", None)) is None: + return + + if self.modules_to_save is None: + self.modules_to_save = set(modules_to_save) + else: + self.modules_to_save.update(modules_to_save) + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def set_adapter(self, adapter_name: Union[str, list[str]], inference_mode: bool = False) -> None: + """ + Sets the active adapter(s) for the model. + + Note that the order in which the adapters are applied during the forward pass may not be the same as the order + in which they are passed to this function. Instead, the order during the forward pass is determined by the + order in which the adapters were loaded into the model. The active adapters only determine which adapters are + active during the forward pass, but not the order in which they are applied. + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_name (str, list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_name, str): + adapter_name = [adapter_name] + + mismatched = set(adapter_name) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + self.base_model.set_adapter(adapter_name, inference_mode=inference_mode) + _set_adapter(self, adapter_name, inference_mode=inference_mode) + + def delete_adapter(self, adapter_name: Union[str, list[str]]) -> None: + if isinstance(adapter_name, str): + adapter_name = [adapter_name] + + mismatched = set(adapter_name) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + self.base_model.delete_adapter(adapter_name) + + def merge_and_unload(self, *args: Any, **kwargs: Any): + r""" + This method merges the adapter layers into the base model. This is needed if someone wants to use the base + model as a standalone model. + + Args: + progressbar (`bool`): + whether to show a progressbar indicating the unload and merge process + safe_merge (`bool`): + whether to activate the safe merging check to check if there is any potential Nan in the adapter + weights + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + return self.base_model.merge_and_unload(*args, **kwargs) + + def unload(self, *args: Any, **kwargs: Any): + """ + Gets back the base model by removing all the adapter modules without merging. This gives back the original base + model. + """ + return self.base_model.unload(*args, **kwargs) + + def get_layer_status(self): + raise TypeError(f"get_layer_status is not supported for {self.__class__.__name__}.") + + def get_model_status(self): + raise TypeError(f"get_model_status is not supported for {self.__class__.__name__}.") + + @classmethod + def _split_kwargs(cls, kwargs: dict[str, Any]): + return PeftModel._split_kwargs(kwargs) + + def _check_new_adapter_config(self, peft_config: PeftConfig, is_trainable: bool) -> None: + return PeftModel._check_new_adapter_config(self, peft_config, is_trainable=is_trainable) + + def load_adapter(self, model_id: str, adapter_name: str, *args: Any, **kwargs: Any): + """ + Load a trained adapter into the model. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be + used for inference. + torch_device (`str`, *optional*, defaults to None): + The device to load the adapter on. If `None`, the device will be inferred. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + kwargs: (`optional`): + Additional arguments to modify the way the adapter is loaded, e.g. the token for Hugging Face Hub. + """ + # the low_cpu_mem_usage option is handled through kwargs + output = PeftModel.load_adapter(self, model_id, adapter_name, *args, **kwargs) + # TODO: not quite clear why this is necessary but tests fail without it + self.set_adapter(self.active_adapters) + return output + + def create_or_update_model_card(self, output_dir: str): + raise NotImplementedError(f"Model card creation is not supported for {self.__class__.__name__} (yet).") + + def save_pretrained( + self, + save_directory: str, + safe_serialization: bool = False, + selected_adapters: Optional[list[str]] = None, + **kwargs: Any, + ): + raise NotImplementedError(f"Saving is not supported for {self.__class__.__name__} (yet).") + + @classmethod + def from_pretrained( + cls, + model: nn.Module, + model_id: str | os.PathLike, + adapter_name: str = "default", + is_trainable: bool = False, + config: Optional[PeftConfig] = None, + **kwargs: Any, + ): + r""" + Instantiate a PEFT mixed model from a pretrained model and loaded PEFT weights. + + Note that the passed `model` may be modified inplace. + + Args: + model (`nn.Module`): + The model to be adapted. + model_id (`str` or `os.PathLike`): + The name of the PEFT configuration to use. Can be either: + - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face + Hub. + - A path to a directory containing a PEFT configuration file saved using the `save_pretrained` + method (`./my_peft_config_directory/`). + adapter_name (`str`, *optional*, defaults to `"default"`): + The name of the adapter to be loaded. This is useful for loading multiple adapters. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and use for + inference + config ([`~peft.PeftConfig`], *optional*): + The configuration object to use instead of an automatically loaded configuration. This configuration + object is mutually exclusive with `model_id` and `kwargs`. This is useful when configuration is already + loaded before calling `from_pretrained`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + kwargs: (`optional`): + Additional keyword arguments passed along to the specific PEFT configuration class. + """ + # note: adapted from PeftModel.from_pretrained + from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_MIXED_MODEL_MAPPING + + # load the config + if config is None: + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_id, **hf_kwargs)].from_pretrained( + model_id, **kwargs + ) + elif isinstance(config, PeftConfig): + config.inference_mode = not is_trainable + else: + raise ValueError(f"The input config must be a PeftConfig, got {config.__class__}") + + # note: this is different from PeftModel.from_pretrained + if config.peft_type not in PEFT_TYPE_TO_MIXED_MODEL_MAPPING: + raise ValueError(f"Adapter of type {config.peft_type} is not supported for mixed models.") + + if (getattr(model, "hf_device_map", None) is not None) and len( + set(model.hf_device_map.values()).intersection({"cpu", "disk"}) + ) > 0: + remove_hook_from_submodules(model) + + if config.is_prompt_learning and is_trainable: + # note: should not be possible to reach, but just in case + raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.") + else: + config.inference_mode = not is_trainable + + # note: this is different from PeftModel.from_pretrained, we always return a PeftMixedModel + model = cls(model, config, adapter_name) + # the low_cpu_mem_usage option is handled through kwargs + model.load_adapter(model_id, adapter_name, is_trainable=is_trainable, **kwargs) + return model diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..0e8821f45db8e2dcf8f26fd8b38f8f90a28f5c09 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .lorafa import create_lorafa_optimizer +from .loraplus import create_loraplus_optimizer + + +__all__ = ["create_lorafa_optimizer", "create_loraplus_optimizer"] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/lorafa.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/lorafa.py new file mode 100644 index 0000000000000000000000000000000000000000..4d3d64843595348f4b528804f72d6e2a8203a5d8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/lorafa.py @@ -0,0 +1,256 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This module contains the implementation of the LoRA-FA optimizer. +""" + +from __future__ import annotations + +import math +from collections.abc import Callable, Iterable + +import torch +import torch.nn as nn +from accelerate.utils.imports import is_bf16_available +from torch import autocast +from torch.optim import Optimizer + +from ..peft_model import PeftModel +from ..utils.other import infer_device + + +class LoraFAOptimizer(Optimizer): + """ + Implements the LoRA-FA optimizer designed specifically for training Low-Rank Adaptation (LoRA) parameters + efficiently. Note that LoraFAOptimizer is based on adamw-hf in transformers, with only LoRA part modified. Without + LoRA it will fall back to adamw-hf. + + Args: + params (Iterable[nn.parameter.Parameter]): Parameters to optimize. + lr (float, optional): Learning rate (default: 1e-3). + betas (Tuple[float, float], optional): + Coefficients for computing running averages of gradient and squared gradient (default: (0.9, 0.999)). + eps (float, optional): Term added to denominator to improve numerical stability (default: 1e-6). + weight_decay (float, optional): Weight decay (L2 penalty) (default: 0.0). + correct_bias (bool, optional): Whether to apply bias correction as in original Adam (default: True). + + Args in sub-function step: + closure (Callable, optional): A closure that reevaluates the model and returns the loss. + + Reference: + - LoRA-FA: https://huggingface.co/papers/2308.03303 + """ + + def __init__( + self, + params: Iterable[nn.parameter.Parameter], + lr: float = 1e-3, + betas: tuple[float, float] = (0.9, 0.999), + eps: float = 1e-6, + weight_decay: float = 0.0, + correct_bias: bool = True, + ): + if lr < 0.0: + raise ValueError(f"Invalid learning rate: {lr} - should be >= 0.0") + if not 0.0 <= betas[0] < 1.0: + raise ValueError(f"Invalid beta parameter: {betas[0]} - should be in [0.0, 1.0)") + if not 0.0 <= betas[1] < 1.0: + raise ValueError(f"Invalid beta parameter: {betas[1]} - should be in [0.0, 1.0)") + if not 0.0 <= eps: + raise ValueError(f"Invalid epsilon value: {eps} - should be >= 0.0") + defaults = { + "lr": lr, + "betas": betas, + "eps": eps, + "weight_decay": weight_decay, + "correct_bias": correct_bias, + } + super().__init__(params, defaults) + + @torch.no_grad() + def step(self, closure: Callable = None): + """ + Performs a single optimization step. + + Arguments: + closure (`Callable`, *optional*): A closure that reevaluates the model and returns the loss. + """ + loss = None + if closure is not None: + loss = closure() + + for group in self.param_groups: + scaling_factor = group["scaling_factor"] + param_list = [] + name_list = [] + for p, n in zip(group["params"], group["names"]): + # Skip non-lora no-grad module, since we need lora_A which is no-grad. + if "lora" not in n and p.grad is None: + continue + grad = p.grad + + if "lora" in n: + param_list.append(p) + name_list.append(n) + if len(param_list) == 2: + name = n[: n.find("lora")] + "lora" + elif len(param_list) == 1: + continue + else: + name = n + # param_list contains a pair of A and B adapters + # i.e., param_list -> [A,B] + + state = self.state[name] + # State initialization + if len(state) == 0: + if len(param_list) == 2: + state["step"] = 0 + # Exponential moving average of gradient values + state["exp_avg_B"] = torch.zeros_like(param_list[1]) + # Exponential moving average of squared gradient values + state["exp_avg_sq_B"] = torch.zeros_like(param_list[1]) + else: + state["step"] = 0 + # Exponential moving average of gradient values + state["exp_avg"] = torch.zeros_like(p) + # Exponential moving average of squared gradient values + state["exp_avg_sq"] = torch.zeros_like(p) + + # Below is the LoRA-FA part + # 1. In this part, we optimize the gradient of B as: + # g^B = \left(\frac{r}{\alpha}\right)^2 (A^\top A)^{-1} g_{\text{LoRA-FA}}^B + # to min the func as described below: + # \min_{g^B} \|\hat{g}_\text{LoRA-FA} - g\|_F^2 + # 2. After the gradient of B is ready, update the optimizer state + if len(param_list) == 2: + A = param_list[0] + B = param_list[1] + grad_B_orin = B.grad + + # projection + delta = 1e-8 + + # computing the inverse matrix + AA_T = A @ A.T + AA_T_inv = torch.linalg.pinv(AA_T + delta * torch.eye(A.shape[0]).to(A.device)) + + device_type = infer_device() + + if is_bf16_available(): + with autocast(device_type=device_type, dtype=torch.bfloat16): + grad_B = (1 / scaling_factor**2) * (grad_B_orin @ AA_T_inv) + else: + grad_B = (1 / scaling_factor**2) * (grad_B_orin @ AA_T_inv) + + if grad_B.dtype != B.grad.dtype: + grad_B = grad_B.to(B.grad.dtype) + + exp_avg_B, exp_avg_sq_B = state["exp_avg_B"], state["exp_avg_sq_B"] + beta1, beta2 = group["betas"] + state["step"] += 1 + exp_avg_B.mul_(beta1).add_(grad_B, alpha=(1.0 - beta1)) + exp_avg_sq_B.mul_(beta2).addcmul_(grad_B, grad_B, value=1.0 - beta2) + + denom_B = exp_avg_sq_B.sqrt().add_(group["eps"]) + step_size = group["lr"] + if group["correct_bias"]: # No bias correction for Bert + bias_correction1 = 1.0 - beta1 ** state["step"] + bias_correction2 = 1.0 - beta2 ** state["step"] + step_size = step_size * math.sqrt(bias_correction2) / bias_correction1 + B.addcdiv_(exp_avg_B, denom_B, value=-step_size) + if group["weight_decay"] > 0.0: + B.add_(B, alpha=(-group["lr"] * group["weight_decay"])) + param_list = [] + name_list = [] + + # Below is the original AdamW + else: + exp_avg, exp_avg_sq = state["exp_avg"], state["exp_avg_sq"] + beta1, beta2 = group["betas"] + + state["step"] += 1 + + # Decay the first and second moment running average coefficient + # In-place operations to update the averages at the same time + exp_avg.mul_(beta1).add_(grad, alpha=(1.0 - beta1)) + exp_avg_sq.mul_(beta2).addcmul_(grad, grad, value=1.0 - beta2) + denom = exp_avg_sq.sqrt().add_(group["eps"]) + + step_size = group["lr"] + if group["correct_bias"]: # No bias correction for Bert + bias_correction1 = 1.0 - beta1 ** state["step"] + bias_correction2 = 1.0 - beta2 ** state["step"] + step_size = step_size * math.sqrt(bias_correction2) / bias_correction1 + + p.addcdiv_(exp_avg, denom, value=-step_size) + + # Just adding the square of the weights to the loss function is *not* + # the correct way of using L2 regularization/weight decay with Adam, + # since that will interact with the m and v parameters in strange ways. + # + # Instead we want to decay the weights in a manner that doesn't interact + # with the m/v parameters. This is equivalent to adding the square + # of the weights to the loss with plain (non-momentum) SGD. + # Add weight decay at the end (fixed version) + if group["weight_decay"] > 0.0: + p.add_(p, alpha=(-group["lr"] * group["weight_decay"])) + + return loss + + +def create_lorafa_optimizer( + model: PeftModel, r: int, lora_alpha: int, lr: float, weight_decay: float = 0.0, use_rslora: bool = False +) -> Optimizer: + """ + Helper function to instantiate a lorafa optimizer specifically configured for a given model using the LoRA method. + + This function will: + - Disable gradient updates for the "lora_A" parameters (these are typically frozen during LoRA training). + - Compute the scaling factor based on provided `lora_alpha` and rank `r` for proper gradient projection. + - Create and configure parameter groups for the optimizer including specified learning rate, weight decay, and + additional optimizer options. + + For hyper-params, LoRA-FA uses the same hyper-params as AdamW, except for the LoRA hyper-params (r, lora_alpha, + use_rslora). One can always use the same hyper-params such as lr and weight_decay, as AdamW in LoRA tuning. + + Args: + model (PeftModel): The model containing LoRA-adapted parameters. + r (int): Rank of the LoRA decomposition. + lora_alpha (int): Scaling factor for LoRA parameterization. + lr (float): Learning rate for optimizer updates. + weight_decay (float): Weight decay for AdamW. + use_rslora (bool): + whether to use rslora. In rslora, the lora scaling factor becomes to lora_alpha / math.sqrt(r) instead of + lora_alpha / r. + + Returns: + Optimizer: Configured lorafa optimizer instance ready for training. + """ + for name, param in model.named_parameters(): + if "lora_A" in name: + param.requires_grad_(False) + lora_scaling = lora_alpha / math.sqrt(r) if use_rslora else lora_alpha / r + param_groups = [ + { + "params": model.parameters(), + "lr": lr, + "names": [name for name, _ in model.named_parameters()], + "scaling_factor": lora_scaling, + "betas": (0.9, 0.999), + "weight_decay": weight_decay, + } + ] + return LoraFAOptimizer(param_groups) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/loraplus.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/loraplus.py new file mode 100644 index 0000000000000000000000000000000000000000..e4ecae770d5acab4215479141f2db1d17e42da81 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/optimizers/loraplus.py @@ -0,0 +1,121 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This module contains the implementation of the LoraPlus optimizer. +""" + +from __future__ import annotations + +from operator import attrgetter + +import torch.nn as nn +from torch.optim import Optimizer +from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS +from transformers.trainer_pt_utils import get_parameter_names + +from ..peft_model import PeftModel +from ..tuners.lora.layer import Embedding + + +def create_loraplus_optimizer( + model: PeftModel, optimizer_cls: type[Optimizer], *, lr: float, loraplus_lr_ratio: float, **kwargs +) -> Optimizer: + """ + Creates a LoraPlus optimizer. + + Efficient Low Rank Adaptation of Large Models: https://huggingface.co/papers/2402.12354 + + Reference: https://github.com/nikhil-ghosh-berkeley/loraplus/ + + Args: + model (`torch.nn.Module`): The model to be optimized. + optimizer_cls (`torch.optim.Optimizer`): The optimizer class to be used. + lr (`float`): The learning rate to be used for the optimizer. + loraplus_lr_ratio (`float`): + The ratio of learning ηB/ηA where ηA (lr) is passed in as the optimizer learning rate. Should be ≥1. Should + be set in tandem with the optimizer learning rate (lr); should be larger when the task is more difficult + and the model needs to update its features to learn well. In this case, it helps to make the learning rate + slightly smaller (e.g., by a factor of 2) than typical vanilla LoRA learning rates + loraplus_lr_embedding (optional `float`): + If LoRA modules are added to embedding layers your can specify a different learning rate for them. Default + value 1e-6. + kwargs (`dict`): Additional keyword arguments to be passed to the optimizer. + + Returns: + `torch.optim.Optimizer`: An instance of the specified optimizer class configured with the model's parameters + organized into groups with custom learning rates. + """ + + decay_parameters = get_parameter_names(model, ALL_LAYERNORM_LAYERS) + decay_parameters = [name for name in decay_parameters if "bias" not in name] + param_groups = { + "groupA": {}, + "groupB": {}, + "groupB_no_decay": {}, + "embedding": {}, + } + + for name, param in model.named_parameters(): + if not param.requires_grad: + continue + + module = attrgetter(name)(model) + if isinstance(module, Embedding): + param_groups["embedding"][name] = param + elif "lora_B" in name or param.ndim == 1: + if name in decay_parameters: + param_groups["groupB"][name] = param + else: + param_groups["groupB_no_decay"][name] = param + else: + param_groups["groupA"][name] = param + + kwargs["lr"] = lr + loraplus_weight_decay = kwargs.pop("loraplus_weight_decay", 0.0) + loraplus_lr_embedding = kwargs.pop("loraplus_lr_embedding", 1e-6) + + optimizer_grouped_parameters = [ + { + "params": list(param_groups["groupA"].values()), + "weight_decay": loraplus_weight_decay, + "lr": lr, + }, + { + "params": list(param_groups["embedding"].values()), + "weight_decay": loraplus_weight_decay, + "lr": loraplus_lr_embedding, + }, + { + "params": list(param_groups["groupB"].values()), + "weight_decay": loraplus_weight_decay, + "lr": lr * loraplus_lr_ratio, + }, + { + "params": list(param_groups["groupB_no_decay"].values()), + "weight_decay": 0.0, + "lr": lr * loraplus_lr_ratio, + }, + ] + + optimizer = optimizer_cls(optimizer_grouped_parameters, **kwargs) + eight_bit_names = ["Adam8bit", "AdamW8bit", "PagedAdam8bit", "PagedAdamW8bit"] + if optimizer_cls.__name__ in eight_bit_names: + import bitsandbytes + + manager = bitsandbytes.optim.GlobalOptimManager.get_instance() + for module in model.modules(): + if isinstance(module, nn.Embedding): + manager.register_module_override(module, "weight", {"optim_bits": 32}) + return optimizer diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/peft_model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/peft_model.py new file mode 100644 index 0000000000000000000000000000000000000000..a2870e006deb986a53086200283572753f8a698d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/peft_model.py @@ -0,0 +1,3447 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import collections +import copy +import inspect +import os +import warnings +from collections.abc import Sequence +from contextlib import contextmanager, nullcontext +from copy import deepcopy +from dataclasses import dataclass +from typing import Any, Literal, Optional, Union + +import packaging.version +import torch +import transformers +from accelerate import dispatch_model, infer_auto_device_map +from accelerate.hooks import AlignDevicesHook, add_hook_to_module, remove_hook_from_submodules +from accelerate.utils import get_balanced_memory, named_module_tensors +from huggingface_hub import HfFileSystem, ModelCard, ModelCardData, hf_hub_download +from safetensors import safe_open +from safetensors.torch import save_file as safe_save_file +from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss +from transformers import Cache, DynamicCache, EncoderDecoderCache, PreTrainedModel +from transformers.modeling_outputs import QuestionAnsweringModelOutput, SequenceClassifierOutput, TokenClassifierOutput +from transformers.utils import PushToHubMixin + +from peft.tuners.lora.variants import get_alora_offsets_for_forward, get_alora_offsets_for_generate +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import AuxiliaryTrainingWrapper +from peft.utils.constants import DUMMY_MODEL_CONFIG +from peft.utils.integrations import init_empty_weights +from peft.utils.other import TrainableTokensWrapper, create_attention_mask, set_additional_trainable_modules + +from . import __version__ +from .config import PeftConfig +from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING, PEFT_TYPE_TO_TUNER_MAPPING +from .utils import ( + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + WEIGHTS_NAME, + PeftType, + TaskType, + _get_batch_size, + _prepare_prompt_learning_config, + _set_adapter, + _set_trainable, + get_peft_model_state_dict, + id_tensor_storage, + infer_device, + load_peft_weights, + map_cache_to_layer_device_map, + set_peft_model_state_dict, + shift_tokens_right, +) + + +class PeftModel(PushToHubMixin, torch.nn.Module): + """ + Base model encompassing various Peft methods. + + Args: + model ([`~transformers.PreTrainedModel`]): The base transformer model used for Peft. + peft_config ([`PeftConfig`]): The configuration of the Peft model. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading loading process. + + > [!TIP] > Don't use `low_cpu_mem_usage=True` when creating a new PEFT adapter for training. + + **Attributes**: + - **base_model** ([`torch.nn.Module`]) -- The base transformer model used for Peft. + - **peft_config** ([`PeftConfig`]) -- The configuration of the Peft model. + - **modules_to_save** (`list` of `str`) -- The list of sub-module names to save when + saving the model. + - **prompt_encoder** ([`PromptEncoder`]) -- The prompt encoder used for Peft if + using [`PromptLearningConfig`]. + - **prompt_tokens** (`torch.Tensor`) -- The virtual prompt tokens used for Peft if + using [`PromptLearningConfig`]. + - **transformer_backbone_name** (`str`) -- The name of the transformer + backbone in the base model if using [`PromptLearningConfig`]. + - **word_embeddings** (`torch.nn.Embedding`) -- The word embeddings of the transformer backbone + in the base model if using [`PromptLearningConfig`]. + """ + + def __init__( + self, + model: PreTrainedModel, + peft_config: PeftConfig, + adapter_name: str = "default", + autocast_adapter_dtype: bool = True, + low_cpu_mem_usage: bool = False, + ) -> None: + super().__init__() + self.active_adapter = adapter_name + self.peft_type = peft_config.peft_type + # These args are special PEFT arguments that users can pass. They need to be removed before passing them to + # forward. + self.special_peft_forward_args = {"adapter_names", "alora_offsets"} + + self._is_prompt_learning = peft_config.is_prompt_learning + if self._is_prompt_learning: + self._peft_config = {adapter_name: peft_config} + self.base_model = model + self.add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + else: + self._peft_config = None + cls = PEFT_TYPE_TO_TUNER_MAPPING[peft_config.peft_type] + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self.base_model = cls(model, {adapter_name: peft_config}, adapter_name) + + if hasattr(self.base_model, "_cast_adapter_dtype"): + self.base_model._cast_adapter_dtype( + adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype + ) + + if getattr(model, "is_gradient_checkpointing", True): + model = self.prepare_model_for_gradient_checkpointing(model) + + # the `pretraining_tp` is set for some models to simulate Tensor Parallelism during inference to avoid + # numerical differences, https://github.com/pytorch/pytorch/issues/76232 - to avoid any unexpected + # behavior we disable that in this line. + if hasattr(self.base_model, "config") and hasattr(self.base_model.config, "pretraining_tp"): + self.base_model.config.pretraining_tp = 1 + + self._adapters_disabled = False + + @property + def peft_config(self) -> dict[str, PeftConfig]: + if self._is_prompt_learning: + return self._peft_config + return self.base_model.peft_config + + @property + def active_adapters(self) -> list[str]: + try: + adapters = self.base_model.active_adapters + if not isinstance(adapters, list): + # Base model is probably a transformers model, see: + # https://github.com/huggingface/transformers/pull/30790#issuecomment-2253808249 + # Unfortunately, transformers models also have an active_adapters method but it's 1) not a property and + # 2) calling it fails because the base model (usually) has no loaded adapter. The base model can be a + # transformers model for prompt learning, where the base model is not wrapped in a LoraModel or similar. + adapters = self.active_adapter + if isinstance(adapters, str): + adapters = [adapters] + except AttributeError: + adapters = self.active_adapter + if isinstance(adapters, str): + adapters = [adapters] + return adapters + + @property + def has_active_enabled_adapter(self) -> bool: + """Reflects whether the adapters are purposefully disabled (via disable_adapter) or if there + are no active adapters (enabled but inactive). They are two separate mechanisms but sometimes it is helpful to + know whether the model has any active/enabled adapter at all. + """ + if self.peft_config[self.active_adapter].is_prompt_learning: + return not self._adapters_disabled + + return not self._adapters_disabled or not self.active_adapters + + @peft_config.setter + def peft_config(self, value: dict[str, PeftConfig]): + if self._is_prompt_learning: + self._peft_config = value + else: + self.base_model.peft_config = value + + def save_pretrained( + self, + save_directory: str, + safe_serialization: bool = True, + selected_adapters: Optional[list[str]] = None, + save_embedding_layers: Union[str, bool] = "auto", + is_main_process: bool = True, + path_initial_model_for_weight_conversion: Optional[str] = None, + **kwargs: Any, + ) -> None: + r""" + This function saves the adapter model and the adapter configuration files to a directory, so that it can be + reloaded using the [`PeftModel.from_pretrained`] class method, and also used by the [`PeftModel.push_to_hub`] + method. + + Args: + save_directory (`str`): + Directory where the adapter model and configuration files will be saved (will be created if it does not + exist). + safe_serialization (`bool`, *optional*): + Whether to save the adapter files in safetensors format, defaults to `True`. + selected_adapters (`List[str]`, *optional*): + A list of adapters to be saved. If `None`, will default to all adapters. + save_embedding_layers (`Union[bool, str]`, *optional*, defaults to `"auto"`): + If `True`, save the embedding layers in addition to adapter weights. If `auto`, checks the common + embedding layers `peft.utils.other.EMBEDDING_LAYER_NAMES` in config's `target_modules` when available. + and automatically sets the boolean flag. This only works for 🤗 transformers models. + is_main_process (`bool`, *optional*): + Whether the process calling this is the main process or not. Will default to `True`. Will not save the + checkpoint if not on the main process, which is important for multi device setups (e.g. DDP). + path_initial_model_for_weight_conversion (`str, *optional*`): + The path to the initialized adapter, which is obtained after initializing the model with + PiSSA/CorDA/OLoRA and before performing any training. When `path_initial_model_for_weight_conversion` + is not None, the difference in adapter before and after fine-tuning is calculated. This difference can + be represented as the parameters of a standard LoRA adapter. Using this converted adapter does not + require changes to the base model, thus conveniently allowing the use of multiple PiSSA/CorDA/OLoRA + adapters with LoRA adapters, and the activation or deactivation of any adapters. Note that this + conversion is not supported if `rslora` is used in combination with `rank_pattern` or `alpha_pattern`. + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the `push_to_hub` method. + + """ + if os.path.isfile(save_directory): + raise ValueError(f"Provided path ({save_directory}) should be a directory, not a file") + + if selected_adapters is None: + selected_adapters = list(self.peft_config.keys()) + else: + if any( + selected_adapter_name not in list(self.peft_config.keys()) + for selected_adapter_name in selected_adapters + ): + raise ValueError( + f"You passed an invalid `selected_adapters` arguments, current supported adapter names are" + f" {list(self.peft_config.keys())} - got {selected_adapters}." + ) + + def save_mutated_as_lora(peft_config, path_initial_model_for_weight_conversion, output_state_dict, kwargs): + if peft_config.use_rslora and (peft_config.rank_pattern or peft_config.alpha_pattern): + msg = ( + "Passing `path_initial_model_for_weight_conversion` to `save_pretrained` is not supported when " + "using `rank_pattern` or `alpha_pattern` at the same time as `use_rslora=True`." + ) + raise ValueError(msg) + + if not any( + str(peft_config.init_lora_weights).lower().startswith(prefix) + for prefix in ["pissa", "corda", "olora", "lora_ga", "true"] + ): + warnings.warn( + "`path_initial_model_for_weight_conversion` only works for converting a PiSSA/CorDA/OLoRA/LoRA-GA adapter to " + "a LoRA adapter" + ) + initial_adapter_name = os.path.basename(path_initial_model_for_weight_conversion) + try: + self.load_adapter( + os.path.dirname(path_initial_model_for_weight_conversion), + subfolder=initial_adapter_name, + adapter_name=initial_adapter_name, + ) + is_pissa = str(self.peft_config[initial_adapter_name].init_lora_weights).lower().startswith("pissa") + is_corda = str(self.peft_config[initial_adapter_name].init_lora_weights).lower() == "corda" + is_olora = str(self.peft_config[initial_adapter_name].init_lora_weights).lower() == "olora" + is_lora_ga = str(self.peft_config[initial_adapter_name].init_lora_weights).lower() == "lora_ga" + if is_pissa or is_corda or is_olora or is_lora_ga: + raise ValueError( + "The `init_lora_weights` parameter of the initial adapter should be set to `True`. " + "Otherwise, `self.load_adapter` will subtract the decomposed values again based on the " + "residual model." + ) + output_state_dict = self.base_model.subtract_mutated_init( + output_state_dict, initial_adapter_name, kwargs + ) + finally: + self.delete_adapter(initial_adapter_name) + return output_state_dict + + if is_main_process: + os.makedirs(save_directory, exist_ok=True) + self.create_or_update_model_card(save_directory) + + for adapter_name in selected_adapters: + peft_config = self.peft_config[adapter_name] + # save only the trainable weights + output_state_dict = get_peft_model_state_dict( + self, + state_dict=kwargs.get("state_dict", None), + adapter_name=adapter_name, + save_embedding_layers=save_embedding_layers, + ) + output_dir = os.path.join(save_directory, adapter_name) if adapter_name != "default" else save_directory + os.makedirs(output_dir, exist_ok=True) + + if is_main_process and safe_serialization: + # Section copied from: https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_utils.py#L2111-L2134 + # Safetensors does not allow tensor aliasing. + # We're going to remove aliases before saving + ptrs = collections.defaultdict(list) + for name, tensor in output_state_dict.items(): + # Sometimes in the state_dict we have non-tensor objects. + # e.g. in bitsandbytes we have some `str` objects in the state_dict + if isinstance(tensor, torch.Tensor): + ptrs[id_tensor_storage(tensor)].append(name) + else: + # In the non-tensor case, fall back to the pointer of the object itself + ptrs[id(tensor)].append(name) + + # These are all the pointers of shared tensors. + shared_ptrs = {ptr: names for ptr, names in ptrs.items() if len(names) > 1} + + for _, names in shared_ptrs.items(): + # Here we just clone the shared tensors to avoid tensor aliasing which is + # not supported in safetensors. + for shared_tensor_name in names[1:]: + output_state_dict[shared_tensor_name] = output_state_dict[shared_tensor_name].clone() + if path_initial_model_for_weight_conversion is not None: + peft_config = copy.deepcopy(peft_config) + peft_config.init_lora_weights = True + peft_config.save_pretrained(path_initial_model_for_weight_conversion) + output_state_dict = save_mutated_as_lora( + peft_config, path_initial_model_for_weight_conversion, output_state_dict, kwargs + ) + + # Before exporting the parameters we need to make sure all the tensors are contigious as saving + # non-contiguous parameters is not supported. Tensors can become non contigiuous + # if they are a transpose view of another tensor. This can happen + # during adapter tying or parameter sharing. + for k, v in output_state_dict.items(): + if not v.is_contiguous(): + output_state_dict[k] = v.contiguous() + + safe_save_file( + output_state_dict, + os.path.join(output_dir, SAFETENSORS_WEIGHTS_NAME), + metadata={"format": "pt"}, + ) + elif is_main_process: + if path_initial_model_for_weight_conversion is not None: + peft_config = copy.deepcopy(peft_config) + peft_config.init_lora_weights = True + peft_config.save_pretrained(path_initial_model_for_weight_conversion) + output_state_dict = save_mutated_as_lora( + peft_config, path_initial_model_for_weight_conversion, output_state_dict, kwargs + ) + torch.save(output_state_dict, os.path.join(output_dir, WEIGHTS_NAME)) + + # save the config and change the inference mode to `True` + if peft_config.base_model_name_or_path is None: + peft_config.base_model_name_or_path = ( + self.base_model.__dict__.get("name_or_path", None) + if peft_config.is_prompt_learning + else self.base_model.model.__dict__.get("name_or_path", None) + ) + inference_mode = peft_config.inference_mode + peft_config.inference_mode = True + + if peft_config.task_type is None: + # deal with auto mapping + base_model_class = self._get_base_model_class( + is_prompt_tuning=peft_config.is_prompt_learning, + ) + parent_library = base_model_class.__module__ + + auto_mapping_dict = { + "base_model_class": base_model_class.__name__, + "parent_library": parent_library, + } + else: + auto_mapping_dict = None + + if is_main_process: + if path_initial_model_for_weight_conversion is not None: + peft_config.init_lora_weights = True + peft_config.r *= 2 + if not peft_config.use_rslora: + peft_config.lora_alpha *= 2 + else: + # with rslora, we have scaling = alpha / sqrt(r), we thus adjust alpha to keep the same scaling + peft_config.lora_alpha *= 2**0.5 + + if peft_config.rank_pattern: + peft_config.rank_pattern = {key: 2 * val for key, val in peft_config.rank_pattern.items()} + if peft_config.alpha_pattern: + peft_config.alpha_pattern = {key: 2 * val for key, val in peft_config.alpha_pattern.items()} + + peft_config.save_pretrained(output_dir, auto_mapping_dict=auto_mapping_dict) + peft_config.inference_mode = inference_mode + + @classmethod + def from_pretrained( + cls, + model: torch.nn.Module, + model_id: Union[str, os.PathLike], + adapter_name: str = "default", + is_trainable: bool = False, + config: Optional[PeftConfig] = None, + autocast_adapter_dtype: bool = True, + ephemeral_gpu_offload: bool = False, + low_cpu_mem_usage: bool = False, + key_mapping: Optional[dict[str, str]] = None, + **kwargs: Any, + ) -> PeftModel: + r""" + Instantiate a PEFT model from a pretrained model and loaded PEFT weights. + + Note that the passed `model` may be modified inplace. + + Args: + model ([`torch.nn.Module`]): + The model to be adapted. For 🤗 Transformers models, the model should be initialized with the + [`~transformers.PreTrainedModel.from_pretrained`]. + model_id (`str` or `os.PathLike`): + The name of the PEFT configuration to use. Can be either: + - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face + Hub. + - A path to a directory containing a PEFT configuration file saved using the `save_pretrained` + method (`./my_peft_config_directory/`). + adapter_name (`str`, *optional*, defaults to `"default"`): + The name of the adapter to be loaded. This is useful for loading multiple adapters. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be + used for inference. + config ([`~peft.PeftConfig`], *optional*): + The configuration object to use instead of an automatically loaded configuration. This configuration + object is mutually exclusive with `model_id` and `kwargs`. This is useful when configuration is already + loaded before calling `from_pretrained`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + ephemeral_gpu_offload (`bool`, *optional*): + Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`. This is + useful when parts of the model and/or components (such as adapters) are kept in CPU memory until they + are needed. Rather than perform expensive operations on small data, the data is transferred to the GPU + on-demand, the operation(s) performed, and the results moved back to CPU memory. This brings a slight + momentary VRAM overhead but gives orders of magnitude speedup in certain cases. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + torch_device (`str`, *optional*, defaults to None): + The device to load the adapter on. If `None`, the device will be inferred. + key_mapping (dict, *optional*, defaults to None) + Extra mapping of PEFT `state_dict` keys applied before loading the `state_dict`. When this mapping is + applied, the PEFT-specific `"base_model.model"` prefix is removed beforehand and the adapter name (e.g. + `"default"`) is not inserted yet. Only pass this argument if you know what you're doing. + kwargs: (`optional`): + Additional keyword arguments passed along to the specific PEFT configuration class. + + """ + from .auto import MODEL_TYPE_TO_PEFT_MODEL_MAPPING + from .tuners import XLoraConfig, XLoraModel + + # load the config + if config is None: + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_id, **hf_kwargs)].from_pretrained( + model_id, **kwargs + ) + elif isinstance(config, PeftConfig): + config.inference_mode = not is_trainable + else: + raise ValueError(f"The input config must be a PeftConfig, got {config.__class__}") + + # See discussion in https://github.com/huggingface/transformers/pull/38627 + # Some transformers models can have a _checkpoint_conversion_mapping dict that is used to map state_dicts + # stemming from updated model architectures so that they still correspond to the initial architecture. When + # loading a PEFT state_dict created with the initial architecture on a model with the new architecture, we need + # to map it too according to the same rules. Note that we skip prompt learning methods. This is because they + # don't have the "base_model.model." prefix, which we need to remove before mapping. Instead just using + # "base_model.". This could be fine, we could only remove "base_model.", However, the subsequent sub-module + # could also be called "model", resulting in what looks like "base_model.model.". To avoid this confusion, we + # skip prompt learning. Since it applies itself directly to the pre-trained model (unlike LoRA et al that target + # sub-modules), skipping should be fine. + if (key_mapping is None) and (not config.is_prompt_learning): + key_mapping = getattr(model, "_checkpoint_conversion_mapping", {}) + + # Runtime configuration, if supported + if hasattr(config, "runtime_config"): + config.runtime_config.ephemeral_gpu_offload = ephemeral_gpu_offload + else: + if ephemeral_gpu_offload: + warnings.warn("Ephemeral GPU offloading is not supported for this model. Ignoring.") + + if hasattr(model, "hf_device_map"): + weight_map = dict(named_module_tensors(model, recurse=True)) + + # recreate the offload_index for disk-offloaded modules: we need to know the location in storage of each weight + # before the offload hook is removed from the model + disk_modules = set() + index = None + for name, module in model.named_modules(): + if hasattr(module, "_hf_hook") and hasattr(module._hf_hook, "original_devices"): + if hasattr(module._hf_hook.weights_map, "dataset"): + index = module._hf_hook.weights_map.dataset.index + for key in module._hf_hook.original_devices.keys(): + if module._hf_hook.original_devices[key] == torch.device("meta"): + disk_modules.add(str(name) + "." + str(key)) + + if disk_modules and not kwargs.get("use_safetensors", True): + raise ValueError("Disk offloading currently only supported for safetensors") + + if index: + offload_index = { + p: { + "safetensors_file": index[p]["safetensors_file"], + "weight_name": p, + "dtype": str(weight_map[p].dtype).replace("torch.", ""), + } + for p in weight_map.keys() + if p in disk_modules + } + kwargs["offload_index"] = offload_index + + if (getattr(model, "hf_device_map", None) is not None) and len( + set(model.hf_device_map.values()).intersection({"cpu", "disk"}) + ) > 0: + remove_hook_from_submodules(model) + + if config.is_prompt_learning and is_trainable: + raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.") + else: + config.inference_mode = not is_trainable + if isinstance(getattr(model, "base_model", None), XLoraModel): + if not isinstance(config, XLoraConfig): + raise TypeError(f"Expected 'XLoraConfig', got '{type(config)}' instead.") + if "adapters" in kwargs: + config.adapters = kwargs["adapters"] + else: + # If the path is on HF hub, then we get the adapter names to create a subfolders list which tells + # `load_adapter` where the adapters are. + if not os.path.exists(model_id): + s = HfFileSystem() + + # The names of the adapters which must be in folders + adapter_names = [ + file["name"][len(model_id) + 1 :] for file in s.ls(model_id) if file["type"] == "directory" + ] + # Prepare a dict of adapter paths, which really just point to the hf id; we will use the subfolders + adapter_paths = {} + for adapter_name in adapter_names: + adapter_paths[adapter_name] = os.path.join(model_id, model_id) + config.adapters = adapter_paths + config._subfolders = adapter_names + else: + if "adapters" not in kwargs: + raise ValueError("If model_id is a local path, then `adapters` must be passed in kwargs.") + + if config.task_type not in MODEL_TYPE_TO_PEFT_MODEL_MAPPING.keys(): + model = cls( + model, + config, + adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + else: + model = MODEL_TYPE_TO_PEFT_MODEL_MAPPING[config.task_type]( + model, + config, + adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + + load_result = model.load_adapter( + model_id, + adapter_name, + is_trainable=is_trainable, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + key_mapping=key_mapping, + **kwargs, + ) + + # 1. Remove VB-LoRA vector bank, since it's a shared parameter set via the VBLoRAModel + # 2. Remove the prompt encoder, as it does not need to be part of the checkpoint + missing_keys = [ + k for k in load_result.missing_keys if "vblora_vector_bank" not in k and "prompt_encoder" not in k + ] + if missing_keys: + # Let's warn here since (in contrast to load_adapter) we don't return the load result, so it could be quite + # difficult for users to even notice that something might have gone wrong here. As we filter out non PEFT + # keys from the missing keys, this gives no false positives. + + # careful: if the wording of the warning is changed, adjust the unit tests accordingly! + warn_message = f"Found missing adapter keys while loading the checkpoint: {missing_keys}." + + prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(config.peft_type) + if prefix and adapter_name in prefix: + warn_message = ( + f"Adapter name '{adapter_name}' should not be contained in the prefix '{prefix}'. " + "This could be the potential reason for missing adapter keys. " + ) + warn_message + + warnings.warn(warn_message) + + return model + + def _setup_prompt_encoder(self, adapter_name: str): + config = self.peft_config[adapter_name] + if not hasattr(self, "prompt_encoder"): + self.prompt_encoder = torch.nn.ModuleDict({}) + self.prompt_tokens = {} + transformer_backbone = None + for name, module in self.base_model.named_children(): + for param in module.parameters(): + param.requires_grad = False + if isinstance(module, PreTrainedModel): + # Make sure to freeze Tranformers model + if transformer_backbone is None: + transformer_backbone = module + self.transformer_backbone_name = name + if transformer_backbone is None: + transformer_backbone = self.base_model + + if config.num_transformer_submodules is None: + config.num_transformer_submodules = 2 if config.task_type == TaskType.SEQ_2_SEQ_LM else 1 + + # determine the word embeddings + word_embeddings = None + try: + # First try to find the word embeddings based on the module name, this should work for models like Bert, + # Roberta, Deberta, etc. + word_embeddings = self.base_model.get_submodule("embeddings.word_embeddings") + except AttributeError: + pass + + if word_embeddings is None: + # Word embeddings could not be determined. Next try to guess them by checking which parameter has the size + # of the vocab. + for named_param, value in list(transformer_backbone.named_parameters()): + # for ZeRO-3, the tensor is sharded across accelerators and deepspeed modifies it to a tensor with shape + # [0] the actual unsharded shape is stored in "ds_shape" attribute special handling is needed in case + # the model is initialized in deepspeed.zero.Init() context or HfDeepSpeedConfig has been called before + # For reference refer to issue: https://github.com/huggingface/peft/issues/996 + deepspeed_distributed_tensor_shape = getattr(value, "ds_shape", None) + + # Handle VLM case with separate text and vision configs + if hasattr(self.base_model.config, "get_text_config"): + vocab_size = self.base_model.config.get_text_config().vocab_size + # below: for older transformers versions before get_text_config was added + elif "text_config" in self.base_model.config: + vocab_size = self.base_model.config.text_config.vocab_size + else: + vocab_size = self.base_model.config.vocab_size + + if value.shape[0] == vocab_size or ( + deepspeed_distributed_tensor_shape is not None + and deepspeed_distributed_tensor_shape[0] == vocab_size + ): + word_embeddings = transformer_backbone.get_submodule(named_param.replace(".weight", "")) + break + + self.word_embeddings = word_embeddings + model_cls = PEFT_TYPE_TO_TUNER_MAPPING[config.peft_type] + + if config.peft_type in (PeftType.PROMPT_TUNING, PeftType.MULTITASK_PROMPT_TUNING, PeftType.CPT): + prompt_encoder = model_cls(config, self.word_embeddings) + elif config.peft_type == PeftType.P_TUNING: + prompt_encoder = model_cls(config) + elif config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # prefix tuning now uses Cache but that won't work with gradient checkpointing + if any(getattr(module, "gradient_checkpointing", False) for module in self.get_base_model().modules()): + raise ValueError(f"{config.peft_type.value} does not work with gradient checkpointing.") + prompt_encoder = model_cls(config) + else: + raise ValueError("Not supported") + + prompt_encoder = prompt_encoder.to(self.device) + self.prompt_encoder.update(torch.nn.ModuleDict({adapter_name: prompt_encoder})) + self.prompt_tokens[adapter_name] = torch.arange( + config.num_virtual_tokens * config.num_transformer_submodules + ).long() + + def prepare_model_for_gradient_checkpointing(self, model: PreTrainedModel): + r""" + Prepares the model for gradient checkpointing if necessary + """ + self._prepare_model_for_gradient_checkpointing(model) + + def _prepare_model_for_gradient_checkpointing(self, model: PreTrainedModel): + if not ( + getattr(model, "is_loaded_in_8bit", False) + or getattr(model, "is_loaded_in_4bit", False) + or getattr(model, "is_quantized", False) + ): + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + elif hasattr(model, "get_input_embeddings"): + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + return model + + def get_prompt_embedding_to_save(self, adapter_name: str) -> torch.Tensor: + """ + Returns the prompt embedding to save when saving the model. Only applicable when using a prompt learning + method. + """ + prompt_encoder = self.prompt_encoder[adapter_name] + prompt_tokens = ( + self.prompt_tokens[adapter_name].unsqueeze(0).expand(1, -1).to(prompt_encoder.embedding.weight.device) + ) + peft_type = self.peft_config[adapter_name].peft_type + if self.peft_config[adapter_name].peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + prompt_tokens = prompt_tokens[:, : self.peft_config[adapter_name].num_virtual_tokens] + + if self.peft_config[adapter_name].peft_type == PeftType.MULTITASK_PROMPT_TUNING: + prompt_embedding_cls = PEFT_TYPE_TO_TUNER_MAPPING[peft_type] + prompt_embeddings = super(prompt_embedding_cls, prompt_encoder).forward(prompt_tokens) + else: + prompt_embeddings = prompt_encoder(prompt_tokens) + + return prompt_embeddings[0].detach().cpu() + + def get_prompt( + self, batch_size: int, task_ids: Optional[torch.Tensor] = None, max_cache_len: Optional[int] = None + ) -> torch.Tensor: + """ + Returns the virtual prompts to use for Peft. Only applicable when using a prompt learning method. + """ + peft_config = self.active_peft_config + prompt_encoder = self.prompt_encoder[self.active_adapter] + prompt_tokens = ( + self.prompt_tokens[self.active_adapter] + .unsqueeze(0) + .expand(batch_size, -1) + .to(prompt_encoder.embedding.weight.device) + ) + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + prompt_tokens = prompt_tokens[:, : peft_config.num_virtual_tokens] + if peft_config.inference_mode: + past_key_values = prompt_encoder.embedding.weight.repeat(batch_size, 1, 1) + else: + past_key_values = prompt_encoder(prompt_tokens) + if self.base_model_torch_dtype is not None: + past_key_values = past_key_values.to(self.base_model_torch_dtype) + past_key_values = past_key_values.view( + batch_size, + peft_config.num_virtual_tokens, + peft_config.num_layers * 2, + peft_config.num_attention_heads, + peft_config.token_dim // peft_config.num_attention_heads, + ) + if peft_config.num_transformer_submodules == 2: + past_key_values = torch.cat([past_key_values, past_key_values], dim=2) + + # Transpose: 2 x [num_layers, batch_size, num_heads, num_virtual_tokens, head_dim] + past_key_values = past_key_values.permute([2, 0, 3, 1, 4]).split( + peft_config.num_transformer_submodules * 2 + ) + + base_model = self.get_base_model() + model_config = getattr(base_model, "config", None) + model_type = getattr(model_config, "model_type", "") + if TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING.get(self.config.model_type, None) is not None: + post_process_fn = TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING[self.config.model_type] + past_key_values = post_process_fn(past_key_values) + elif ("gemma2" in model_type) or ("gemma3_text" in model_type): + # TODO: remove this logic once transformers < 4.56 is dropped + transformers_lt_4_56 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.56.0.dev0" + ) + # Gemma2 and Gemma3 only support HybridCache (which does not have the from_legacy_cache method) + if transformers_lt_4_56 and ((max_cache_len is None) or (max_cache_len == -1)): + raise ValueError( + "max_cache_len is missing but it should have been passed. Something went wrong, please open an " + "issue on GitHub with a reproducer: https://github.com/huggingface/peft/issues" + ) + base_config = base_model.config + if hasattr(base_config, "get_text_config"): + base_config = base_config.get_text_config() + if transformers_lt_4_56: + # HybridCache is deprecated, and will be removed in 4.60.0 + # see https://github.com/huggingface/transformers/pull/40276 + from transformers import HybridCache + + new_cache = HybridCache( + config=base_config, + max_batch_size=batch_size, + max_cache_len=max_cache_len, + dtype=past_key_values[0].dtype, + device=past_key_values[0].device, + ) + else: + # transformers 4.56+ uses DynamicCache for gemma + new_cache = DynamicCache(config=base_config) + cache_position = torch.arange(peft_config.num_virtual_tokens, device=past_key_values[0].device) + for layer_idx in range(peft_config.num_layers): + key_states, value_states = past_key_values[0][layer_idx], past_key_values[1][layer_idx] + new_cache.update( + key_states, value_states, layer_idx, cache_kwargs={"cache_position": cache_position} + ) + past_key_values = new_cache + elif peft_config.num_transformer_submodules == 1: + # Dont' apply this to encoder-decoder models and not to models requiring special processing. + # TODO: remove from_legacy_cache once transformers < 4.56 is dropped + transformers_lt_4_56 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.56.0.dev0" + ) + if transformers_lt_4_56: + past_key_values = DynamicCache.from_legacy_cache(past_key_values) + else: + past_key_values = DynamicCache(past_key_values) + + elif (peft_config.num_transformer_submodules == 2) and getattr( + self.base_model, "_supports_cache_class", True + ): + # Dont' apply this to encoder-decoder models that don't support new Cache format yet + # If we don't apply this, prefix-tuning fails to update cross-attn cache + # TODO: remove check for _supports_cache_class once transformers 4.53 is no longer supported + # TODO: remove from_legacy_cache once transformers < 4.56 is dropped + transformers_lt_4_56 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.56.0.dev0" + ) + if transformers_lt_4_56: + past_key_values = EncoderDecoderCache.from_legacy_cache(past_key_values) + else: + past_key_values = EncoderDecoderCache(past_key_values) + + past_key_values.cross_attention_cache = DynamicCache() + # invalidate the cross attention cache, since we add virtual tokens to the encoder + for key in past_key_values.is_updated.keys(): + past_key_values.is_updated[key] = False + map_cache_to_layer_device_map(self.get_base_model(), past_key_values) # no-op if not a Cache instance + return past_key_values + else: + if peft_config.peft_type == PeftType.MULTITASK_PROMPT_TUNING: + prompts = prompt_encoder(prompt_tokens, task_ids) + else: + if peft_config.inference_mode: + prompts = prompt_encoder.embedding.weight + else: + # Take only one prompt token sample and expand the output instead of expanding the input, see: + # https://github.com/huggingface/peft/issues/2043#issuecomment-2321522577 + prompt_tokens = prompt_tokens[:1] + prompts = prompt_encoder(prompt_tokens) + prompts = prompts.repeat(batch_size, 1, 1) + return prompts + + def get_nb_trainable_parameters(self) -> tuple[int, int]: + r""" + Returns the number of trainable parameters and the number of all parameters in the model. + """ + trainable_params = 0 + all_param = 0 + for _, param in self.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + num_params = param.ds_numel + + # Due to the design of 4bit linear layers from bitsandbytes + # one needs to multiply the number of parameters by 2 to get + # the correct number of parameters + if param.__class__.__name__ == "Params4bit": + if hasattr(param, "element_size"): + num_bytes = param.element_size() + elif not hasattr(param, "quant_storage"): + num_bytes = 1 + else: + num_bytes = param.quant_storage.itemsize + num_params = num_params * 2 * num_bytes + + all_param += num_params + if param.requires_grad: + trainable_params += num_params + + return trainable_params, all_param + + def print_trainable_parameters(self) -> None: + """ + Prints the number of trainable parameters in the model. + + Note: print_trainable_parameters() uses get_nb_trainable_parameters() which is different from + num_parameters(only_trainable=True) from huggingface/transformers. get_nb_trainable_parameters() returns + (trainable parameters, all parameters) of the Peft Model which includes modified backbone transformer model. + For techniques like LoRA, the backbone transformer model is modified in place with LoRA modules. However, for + prompt tuning, the backbone transformer model is unmodified. num_parameters(only_trainable=True) returns number + of trainable parameters of the backbone transformer model which can be different. + """ + trainable_params, all_param = self.get_nb_trainable_parameters() + + print( + f"trainable params: {trainable_params:,d} || all params: {all_param:,d} || trainable%: {100 * trainable_params / all_param:.4f}" + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "base_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.base_model, name) + + @contextmanager + def _enable_peft_forward_hooks(self, *args, **kwargs): + # If the base model has a method called _enable_peft_forward_hooks, it is invoked as a context. Otherwise, this + # runs without any changes + if hasattr(self.base_model, "_enable_peft_forward_hooks") and self.has_active_enabled_adapter: + with self.base_model._enable_peft_forward_hooks(*args, **kwargs): + yield + return + else: + # nothing to enable + yield + return + + def forward(self, *args: Any, **kwargs: Any): + """ + Forward pass of the model. + """ + with self._enable_peft_forward_hooks(*args, **kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.get_base_model()(*args, **kwargs) + + def generate(self, *args, **kwargs): + with self._enable_peft_forward_hooks(*args, **kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.get_base_model().generate(*args, **kwargs) + + def _get_base_model_class(self, is_prompt_tuning=False): + """ + Returns the base model class. + """ + if not is_prompt_tuning: + return self.base_model.model.__class__ + return self.base_model.__class__ + + @contextmanager + def disable_adapter(self): + """ + Context manager that disables the adapter module. Use this to run inference on the base model. + + Example: + + ```py + >>> with model.disable_adapter(): + ... model(inputs) + ``` + """ + if self.peft_config[self.active_adapter].is_prompt_learning: + try: + # TODO: consider replacing this patching of methods with a more robust mechanism: setting a flag and + # letting the underlying methods deal with it, same as how LoRA does it. + old_forward = self.forward + self.forward = self.base_model.forward + old_prepare_inputs_for_generation = self.prepare_inputs_for_generation + self.prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation + self._adapters_disabled = True + yield + finally: + self.forward = old_forward + self.prepare_inputs_for_generation = old_prepare_inputs_for_generation + self._adapters_disabled = False + + elif self.peft_config[self.active_adapter].is_adaption_prompt: + try: + self.base_model.disable_adapter_layers() + self._adapters_disabled = True + yield + finally: + self.base_model.enable_adapter_layers() + self._adapters_disabled = False + + else: # LoRA, LoHa, etc. + model_status = self.get_model_status() + if model_status.enabled == "irregular": + warnings.warn( + "The model contains some adapter layers that are enabled and others that are disabled. " + "This is most likely unintentional. After exiting the disable_adapter context, all adapters " + "will be enabled" + ) + try: + self.base_model.disable_adapter_layers() + self._adapters_disabled = True + yield + finally: + if model_status.enabled is not False: + # model_status.enabled is `True` or `"irregular"` + self.base_model.enable_adapter_layers() + self._adapters_disabled = False + + def get_base_model(self) -> torch.nn.Module: + """ + Returns the base model. + """ + return self.base_model if self.active_peft_config.is_prompt_learning else self.base_model.model + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + """ + prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(peft_config.peft_type) + if prefix and adapter_name in prefix: + warnings.warn( + f"Adapter name '{adapter_name}' should not be contained in the prefix '{prefix}'. " + "This may lead to reinitialization of the adapter weights during loading." + ) + + if peft_config.peft_type != self.peft_type: + raise ValueError( + f"Cannot combine adapters with different peft types. " + f"Found {self.peft_type} and {peft_config.peft_type}." + ) + + try: + if peft_config.is_prompt_learning: + self.peft_config[adapter_name] = peft_config + if hasattr(self.config, "to_dict"): + dict_config = self.config.to_dict() + else: + dict_config = self.config + + peft_config = _prepare_prompt_learning_config(peft_config, dict_config) + self._setup_prompt_encoder(adapter_name) + set_additional_trainable_modules( + model=self.base_model, + peft_config=peft_config, + model_config=BaseTuner.get_model_config(self), + adapter_name=adapter_name, + ) + elif peft_config.is_adaption_prompt: + self.base_model.add_adapter(adapter_name, peft_config) + set_additional_trainable_modules( + model=self.base_model, + peft_config=peft_config, + model_config=BaseTuner.get_model_config(self), + adapter_name=adapter_name, + ) + else: + self.peft_config[adapter_name] = peft_config + self.base_model.inject_adapter( + self.base_model.model, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage + ) + except Exception: # something went wrong, roll back + if adapter_name in self.peft_config: + del self.peft_config[adapter_name] + raise + + if hasattr(self.base_model, "_cast_adapter_dtype"): + self.base_model._cast_adapter_dtype( + adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype + ) + + def delete_adapter(self, adapter_name: str) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (str): Name of the adapter to be deleted. + """ + if adapter_name not in self.peft_config: + raise ValueError(f"Adapter {adapter_name} does not exist") + + self.base_model.delete_adapter(adapter_name=adapter_name) + new_active_adapters = self.active_adapters + num_adapters = len(new_active_adapters) + # Note: PeftModel assumes that there is exactly one active adapter, so we should theoretically raise if + # num_adapters != 1. However, we have allowed this in the past (maybe inadvertently), so we let it slip and + # don't introduce a backwards incompatibility by raising an error. + if num_adapters == 1: + self.active_adapter = new_active_adapters[0] + + @property + def modules_to_save(self) -> Optional[set[str]]: + modules: set[str] = set() + for config in self.peft_config.values(): + if getattr(config, "modules_to_save", None) is not None: + # modules_to_save can only be a sequence of str, not a str + modules.update(config.modules_to_save) + + if not modules: + # for backwards compatibility, as modules_to_save was initialized as None + return None + return modules + + def get_layer_status(self) -> list[TunerLayerStatus]: + """Get the status of each adapter layer in the model. + + This method returns a list of `TunerLayerStatus` dataclass instances, each of which contains the following + attributes: + + - `name` (`str`): + The name of the adapter layer, e.g. `model.encoder.block.0.layer.0.SelfAttention.q`. + - `module_type` (`str`): + The type of the adapter layer, e.g. `lora.Linear`. + - `enabled` (`bool`): + Whether the adapter layer is enabled. + - `active_adapters` (`list[str]`): + The names of the active adapters, if any, e.g. `["default"]`. + - `merged_adapters` (`list[str]`): + The names of the merged adapters, if any, e.g. `["default"]`. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + + Args: + model ([`~PeftModel`]): + The model to get the adapter layer status from. + + Returns: + list[`peft.peft_model.TunerLayerStatus`]: + A list of dataclasses, each containing the status of the corresponding adapter layer. + + """ + return get_layer_status(self) + + def get_model_status(self) -> TunerModelStatus: + """Get the status of tuners of the model. + + This method returns a `TunerModelStatus` dataclass instance, which contains the following attributes: + + - `base_model_type` (`str`): + The type of the base model, e.g. `T5Model`. + - `adapter_model_type` (`str`): + The type of the adapter model, e.g. `LoraModel`. + - `peft_types` (`dict[str, str]`): + The mapping of adapter name to adapter type, e.g. `{"default": "LORA"}`. + - `trainable_params` (`int`): + The number of trainable parameters in the model. + - `total_params` (`int`): + The total number of parameters in the model. + - `num_adapter_layers` (`int`): + The number of adapter layers in the model. + - `enabled` (`bool`, `Literal["irregular"]`): + Whether all adapter layers are enabled. If some are enabled and some are not, this will be `"irregular"`. + This means that your model is in an inconsistent state and might not work as expected. + - `active_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the active adapters. If the active adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `merged_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the merged adapters. If the merged adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + + Args: + model ([`~PeftModel`]): + The model to get the adapter layer status from. + + Returns: + `peft.peft_model.TunerModelStatus`: + A dataclass containing the status of the model. + + """ + return get_model_status(self) + + @classmethod + def _split_kwargs(cls, kwargs: dict[str, Any]): + _kwargs_not_in_hf_hub_download_signature = ("use_auth_token",) + hf_hub_download_kwargs = {} + other_kwargs = {} + + for key, value in kwargs.items(): + if key in inspect.signature(hf_hub_download).parameters or key in _kwargs_not_in_hf_hub_download_signature: + hf_hub_download_kwargs[key] = value + else: + other_kwargs[key] = value + + return hf_hub_download_kwargs, other_kwargs + + def _update_offload(self, offload_index: dict[str, dict[str, str]], adapters_weights: dict[str, torch.tensor]): + """ + Update the offload_index and safetensors files for loading and mergine PeftModels with disk-offloaded modules. + + Args: + offload_index (Dict[str: str]): + Dictionary of disk-offloaded modules with their metadata and safetensors filenames + adapters_weights (Dict[str: torch.tensor]): + Dictionary of Peft adapter module names and weights + """ + + if not offload_index: + return offload_index + + prefix = "base_model.model." + # rename offload index weight and model names + adapter_names = list(self.peft_config.keys()) + for adapter_name in adapter_names: + keys = list(offload_index.keys()) + block_id = keys[0].split(".")[0] + "." # for writing safetensors key, + + # replace original offload index keys with PeftModel keys + for key in keys: + suffix_pos = key.rfind(".") + extended_prefix = prefix + key[:suffix_pos] + module = dict(self.named_modules())[extended_prefix] + if isinstance(module, BaseTunerLayer): + new_key = prefix + key[:suffix_pos] + ".base_layer" + key[suffix_pos:] + else: + new_key = prefix + key + offload_index[key]["weight_name"] = new_key + offload_index[new_key] = offload_index[key] + del offload_index[key] + + files_seen = set() + # rename safetensors for dispatch + for new_key in list(offload_index.keys()): + fname = offload_index[new_key]["safetensors_file"] + + # make a new file name + new_fname_list = list(fname.split(os.sep)) + for i, name in enumerate(new_fname_list): + if "--" in name: + new_fname_list[i] += "-peft" + break + new_fname = os.path.join(*new_fname_list) + + if fname in files_seen: + continue + safe_dict = {} + with safe_open(fname, framework="pt") as f: + for safe_key in f.keys(): + safe_tensor = f.get_tensor(safe_key) + metadata = f.metadata() + suffix_pos = safe_key.rfind(".") + extended_prefix = prefix + block_id + safe_key[:suffix_pos] + safe_module = dict(self.named_modules())[extended_prefix] + if isinstance(safe_module, BaseTunerLayer): + final_key = extended_prefix + ".base_layer" + safe_key[suffix_pos:] + lora_dict = {key: val for key, val in adapters_weights.items() if extended_prefix in key} + + # add LoRA keys and values to disk offload + for lora_key, lora_val in lora_dict.items(): + divide = lora_key.rfind(".") + new_key = lora_key[:divide] + f".{adapter_name}" + lora_key[divide:] + safe_dict[new_key] = lora_val + else: + final_key = prefix + block_id + safe_key + safe_dict[final_key] = safe_tensor + files_seen.add(new_fname) + + # avoid overwriting original safetensors + for key in safe_dict.keys(): + offload_index[key] = {"safetensors_file": new_fname, "weight_name": key} + + base_name = os.path.dirname(new_fname) + if not os.path.exists(base_name): + os.makedirs(base_name) + safe_save_file(safe_dict, new_fname, metadata=metadata) + + def _check_new_adapter_config(self, peft_config: PeftConfig, is_trainable: bool) -> None: + """Perform checks on newly added PEFT configs to ensure integrity.""" + if peft_config.is_prompt_learning and is_trainable: + raise ValueError("Cannot set a prompt learning adapter to trainable when loading pretrained adapter.") + + # Since PiSSA/CorDA/OLoRA modifies the base weights, it should not be combined with other adapters. + all_configs = [peft_config] + list(self.peft_config.values()) + if len(all_configs) > 1: + if any(getattr(config, "init_lora_weights", None) == "pissa" for config in all_configs): + msg = ( + "PiSSA changes the base weights of the model and should thus not be used with other adapters. " + "Consider converting the PiSSA adapter into a normal LoRA adapter: " + "https://github.com/huggingface/peft/tree/main/examples/pissa_finetuning#convert-pissa-to-lora" + ) + warnings.warn(msg) + elif any(getattr(config, "init_lora_weights", None) == "corda" for config in all_configs): + msg = ( + "CorDA changes the base weights of the model and should thus not be used with other adapters. " + "Consider converting the CorDA adapter into a normal LoRA adapter: " + "https://github.com/huggingface/peft/tree/main/examples/corda_finetuning#convert-corda-to-lora" + ) + warnings.warn(msg) + elif any(getattr(config, "init_lora_weights", None) == "olora" for config in all_configs): + msg = ( + "OLoRA changes the base weights of the model and should thus not be used with other adapters. " + "Consider converting the OLoRA adapter into a normal LoRA adapter: " + "https://github.com/huggingface/peft/tree/main/examples/olora_finetuning#olora-and-lora" + ) + warnings.warn(msg) + + def load_adapter( + self, + model_id: Union[str, os.PathLike], + adapter_name: str, + is_trainable: bool = False, + torch_device: Optional[str] = None, + autocast_adapter_dtype: bool = True, + ephemeral_gpu_offload: bool = False, + low_cpu_mem_usage: bool = False, + key_mapping: Optional[dict[str, str]] = None, + **kwargs: Any, + ): + """ + Load a trained adapter into the model. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + model_id (`str` or `os.PathLike`): + The name of the PEFT configuration to use. Can be either: + - A string, the `model id` of a PEFT configuration hosted inside a model repo on the Hugging Face + Hub. + - A path to a directory containing a PEFT configuration file saved using the `save_pretrained` + method (`./my_peft_config_directory/`). + adapter_name (`str`): + The name of the adapter to be added. + is_trainable (`bool`, *optional*, defaults to `False`): + Whether the adapter should be trainable or not. If `False`, the adapter will be frozen and can only be + used for inference. + torch_device (`str`, *optional*, defaults to None): + The device to load the adapter on. If `None`, the device will be inferred. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + Whether to use ephemeral GPU offloading for partially loaded modules. Defaults to `False`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device before loading the saved weights. Useful to speed up the + process. + key_mapping (dict, *optional*, defaults to None) + Extra mapping of PEFT `state_dict` keys applied before loading the `state_dict`. When this mapping is + applied, the PEFT-specific `"base_model.model"` prefix is removed beforehand and the adapter name (e.g. + `"default"`) is not inserted yet. Only pass this argument if you know what you're doing. + kwargs: (`optional`): + Additional arguments to modify the way the adapter is loaded, e.g. the token for Hugging Face Hub. + """ + from .mapping import PEFT_TYPE_TO_CONFIG_MAPPING + + hf_hub_download_kwargs, kwargs = self._split_kwargs(kwargs) + if torch_device is None: + torch_device = infer_device() + + if adapter_name not in self.peft_config: + # load the config + peft_config = PEFT_TYPE_TO_CONFIG_MAPPING[ + PeftConfig._get_peft_type( + model_id, + **hf_hub_download_kwargs, + ) + ].from_pretrained( + model_id, + ephemeral_gpu_offload=ephemeral_gpu_offload, + **hf_hub_download_kwargs, + ) + self._check_new_adapter_config(peft_config, is_trainable=is_trainable) + peft_config.inference_mode = not is_trainable + self.add_adapter( + adapter_name, + peft_config, + low_cpu_mem_usage=low_cpu_mem_usage, + autocast_adapter_dtype=autocast_adapter_dtype, + ) + + adapters_weights = load_peft_weights( + model_id, device=torch_device, key_mapping=key_mapping, **hf_hub_download_kwargs + ) + + # load the weights into the model + ignore_mismatched_sizes = kwargs.get("ignore_mismatched_sizes", False) + load_result = set_peft_model_state_dict( + self, + adapters_weights, + adapter_name=adapter_name, + ignore_mismatched_sizes=ignore_mismatched_sizes, + low_cpu_mem_usage=low_cpu_mem_usage, + ) + + tuner = self.peft_config[adapter_name].peft_type + tuner_prefix = PEFT_TYPE_TO_PREFIX_MAPPING.get(tuner, "") + adapter_missing_keys = [] + + # Filter missing keys specific to the current adapter and tuner prefix. + for key in load_result.missing_keys: + if tuner_prefix in key and adapter_name in key: + adapter_missing_keys.append(key) + + load_result.missing_keys.clear() + load_result.missing_keys.extend(adapter_missing_keys) + + if ( + (getattr(self, "hf_device_map", None) is not None) + and (len(set(self.hf_device_map.values()).intersection({"cpu", "disk"})) > 0) + and len(self.peft_config) == 1 + ): + device_map = kwargs.get("device_map", "auto") + max_memory = kwargs.get("max_memory", None) + offload_folder = kwargs.get("offload_folder", None) + offload_dir = kwargs.get("offload_dir", None) + offload_index = kwargs.get("offload_index", None) + + if offload_dir is not None and offload_folder is not None: + # see https://github.com/huggingface/peft/issues/2541 + raise ValueError("Cannot use `offload_folder` when `offload_dir` is specified.") + elif offload_dir is None: + # to keep backwards compatibility + offload_dir = offload_folder + + dispatch_model_kwargs = {} + # Safety checker for previous `accelerate` versions + # `offload_index` was introduced in https://github.com/huggingface/accelerate/pull/873/ + if "offload_index" in inspect.signature(dispatch_model).parameters: + dispatch_model_kwargs["offload_index"] = offload_index + + no_split_module_classes = self._no_split_modules + if isinstance(no_split_module_classes, set): + no_split_module_classes = list(no_split_module_classes) + + if device_map != "sequential": + max_memory = get_balanced_memory( + self, + max_memory=max_memory, + no_split_module_classes=no_split_module_classes, + low_zero=(device_map == "balanced_low_0"), + ) + + if isinstance(device_map, str): + device_map = infer_auto_device_map( + self, max_memory=max_memory, no_split_module_classes=no_split_module_classes + ) + + self._update_offload(offload_index, adapters_weights) + dispatch_model_kwargs["offload_index"] = offload_index + + dispatch_model( + self, + device_map=device_map, + offload_dir=offload_dir, + **dispatch_model_kwargs, + ) + + hook = AlignDevicesHook(io_same_device=True) + if self.peft_config[adapter_name].is_prompt_learning: + remove_hook_from_submodules(self.prompt_encoder) + add_hook_to_module(self.get_base_model(), hook) + + if hasattr(self.base_model, "_cast_adapter_dtype"): + self.base_model._cast_adapter_dtype( + adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype + ) + + # Set model in evaluation mode to deactivate Dropout modules by default + if not is_trainable: + self.eval() + return load_result + + def set_adapter(self, adapter_name: str, inference_mode: bool = False) -> None: + """ + Sets the active adapter. + + Only one adapter can be active at a time. + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_name (`str`): + The name of the adapter to be set as active. The adapter must be loaded first. + inference_mode (`bool`, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if adapter_name not in self.peft_config: + raise ValueError(f"Adapter {adapter_name} not found.") + self.active_adapter = adapter_name + if not self.peft_config[adapter_name].is_prompt_learning: + # _set_adapter does not need to be called, since it's called through the BaseTuner class. + self.base_model.set_adapter(adapter_name, inference_mode=inference_mode) + else: + # handle auxiliary modules + _set_adapter(self, adapter_name, inference_mode=inference_mode) + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Note: Not supported for prompt learning methods like prompt tuning. + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + if self.active_peft_config.is_prompt_learning: + raise TypeError( + "Setting `requires_grad` is not supported for prompt learning methods like " + f"{self.active_peft_config.peft_type.value}." + ) + + self.base_model.set_requires_grad(adapter_names=adapter_names, requires_grad=requires_grad) + + @property + def base_model_torch_dtype(self): + return getattr(self.base_model, "dtype", None) + + @property + def active_peft_config(self): + return self.peft_config[self.active_adapter] + + def _get_peft_specific_model_tags(self): + """Derive tags for the model card from the adapter's config. For example, setting the + base model is important for enabling support for HF inference providers but it also makes models more + searchable on the HF hub. + """ + peft_method = self.active_peft_config.peft_type + if not isinstance(peft_method, str): + peft_method = peft_method.value + + tags = [] + + if hasattr(self.base_model, "model") and isinstance(self.base_model.model, transformers.PreTrainedModel): + tags.append("transformers") + + if peft_method == "LORA": + tags.append("lora") + + if hasattr(self.base_model, "name_or_path"): + tags.append(f"base_model:adapter:{self.base_model.name_or_path}") + + return tags + + def create_or_update_model_card(self, output_dir: str): + """ + Updates or create model card to include information about peft: + 1. Adds `peft` library tag + 2. Adds peft version + 3. Adds base model info + 4. Adds quantization information if it was used + """ + + filename = os.path.join(output_dir, "README.md") + + card = ModelCard.load(filename) if os.path.exists(filename) else ModelCard.from_template(ModelCardData()) + + card.data["library_name"] = "peft" + + tags = set() + base_model = self.get_base_model() + if hasattr(base_model, "model_tags"): + tags = tags.union(base_model.model_tags or []) + + tags = tags.union(self._get_peft_specific_model_tags()) + if tags: + card.data["tags"] = sorted(tags) + + # One of the rare moments where we can select the pipeline tag with certainty, so let's do that. + # Makes it easier to deploy an adapter with auto inference since the user doesn't have to add any tags. + if not card.data.pipeline_tag and isinstance(self, PeftModelForCausalLM): + card.data.pipeline_tag = "text-generation" + + model_config = BaseTuner.get_model_config(self) + model_config = None if model_config == DUMMY_MODEL_CONFIG else model_config + if model_config is not None and "_name_or_path" in model_config: + card.data["base_model"] = model_config["_name_or_path"] + + lines = card.text.splitlines() + + quantization_config = None + if hasattr(model_config, "quantization_config"): + quantization_config = self.config.quantization_config.to_dict() + training_config_text = "" + quantization_prefix = "The following `bitsandbytes` quantization config was used during training:" + # Adds quantization information if it was used + if quantization_config is not None: + training_config_text += f"\n{quantization_prefix}\n" + training_config_text += "\n".join([f"- {name}: {value}" for name, value in quantization_config.items()]) + training_config_text += "\n" + + training_procedure_heading = "## Training procedure" + if quantization_prefix not in lines and bool(training_config_text): + if training_procedure_heading in lines: + lines.insert(lines.index(training_procedure_heading) + 2, training_config_text) + else: + lines.append(f"{training_procedure_heading}\n{training_config_text}") + + # Adds peft version + framework_block_heading = "### Framework versions" + if f"- PEFT {__version__}" not in lines: + if framework_block_heading in lines: + lines.insert(lines.index(framework_block_heading) + 2, f"- PEFT {__version__}") + else: + lines.append(f"{framework_block_heading}\n\n- PEFT {__version__}") + + card.text = "\n".join(lines) + card.save(filename) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + """ + Whether it is possible for the adapter of this model to be converted to LoRA. + + Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight. + """ + peft_config = self.active_peft_config + if peft_config.is_prompt_learning: + return False + + if not hasattr(self.base_model, "supports_lora_conversion"): + return False + + return self.base_model.supports_lora_conversion() + + +class PeftModelForSequenceClassification(PeftModel): + """ + Peft model for sequence classification tasks. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + - **cls_layer_name** (`str`) -- The name of the classification layer. + + Example: + + ```py + >>> from transformers import AutoModelForSequenceClassification + >>> from peft import PeftModelForSequenceClassification, get_peft_config + + >>> config = { + ... "peft_type": "PREFIX_TUNING", + ... "task_type": "SEQ_CLS", + ... "inference_mode": False, + ... "num_virtual_tokens": 20, + ... "token_dim": 768, + ... "num_transformer_submodules": 1, + ... "num_attention_heads": 12, + ... "num_layers": 12, + ... "encoder_hidden_size": 768, + ... "prefix_projection": False, + ... "postprocess_past_key_value_function": None, + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForSequenceClassification(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 370178 || all params: 108680450 || trainable%: 0.3406113979101117 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + classifier_module_names = ["classifier", "score"] + + if hasattr(peft_config, "modules_to_save"): + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + # The modification of peft_config must happen before the init call as the `modules_to_save` information + # will be used to guard the target layer matching against matching `modules_to_save` layers. Only the + # config is relevant for this, the `modules_to_save` attribute can follow later. + super().__init__(model, peft_config, adapter_name, **kwargs) + + if hasattr(peft_config, "modules_to_save"): + for name, _ in self.base_model.named_children(): + if any(module_name in name for module_name in self.modules_to_save): + self.cls_layer_name = name + break + + # to make sure classifier layer is trainable; this may add a new ModulesToSaveWrapper + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + """ + # ensure that additional adapters also add the classifier layer to modules_to_save + if hasattr(peft_config, "modules_to_save"): + classifier_module_names = ["classifier", "score"] + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + return super().add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + peft_config = self.active_peft_config + if not peft_config.is_prompt_learning: + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + return self._prefix_tuning_forward(input_ids=input_ids, **kwargs) + else: + if kwargs.get("token_type_ids", None) is not None: + kwargs["token_type_ids"] = torch.cat( + ( + torch.zeros(batch_size, peft_config.num_virtual_tokens).to(self.word_embeddings.weight.device), + kwargs["token_type_ids"], + ), + dim=1, + ).long() + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _prefix_tuning_forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + **kwargs, + ): + batch_size = _get_batch_size(input_ids, inputs_embeds) + past_key_values = self.get_prompt(batch_size) + fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys()) + kwargs.update( + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "inputs_embeds": inputs_embeds, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + "past_key_values": past_key_values, + } + ) + if "past_key_values" in fwd_params: + return self.base_model(labels=labels, **kwargs) + else: + transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name) + fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys()) + if "past_key_values" not in fwd_params: + raise ValueError("Model does not support past key values which are required for prefix tuning.") + outputs = transformer_backbone_name(**kwargs) + pooled_output = outputs[1] if len(outputs) > 1 else outputs[0] + if "dropout" in [name for name, _ in list(self.base_model.named_children())]: + pooled_output = self.base_model.dropout(pooled_output) + logits = self.base_model.get_submodule(self.cls_layer_name)(pooled_output) + + loss = None + if labels is not None: + if self.config.problem_type is None: + if self.base_model.num_labels == 1: + self.config.problem_type = "regression" + elif self.base_model.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int): + self.config.problem_type = "single_label_classification" + else: + self.config.problem_type = "multi_label_classification" + + if self.config.problem_type == "regression": + loss_fct = MSELoss() + if self.base_model.num_labels == 1: + loss = loss_fct(logits.squeeze(), labels.squeeze()) + else: + loss = loss_fct(logits, labels) + elif self.config.problem_type == "single_label_classification": + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.base_model.num_labels), labels.view(-1)) + elif self.config.problem_type == "multi_label_classification": + loss_fct = BCEWithLogitsLoss() + loss = loss_fct(logits, labels) + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return SequenceClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class PeftModelForCausalLM(PeftModel): + """ + Peft model for causal language modeling. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import PeftModelForCausalLM, get_peft_config + + >>> config = { + ... "peft_type": "PREFIX_TUNING", + ... "task_type": "CAUSAL_LM", + ... "inference_mode": False, + ... "num_virtual_tokens": 20, + ... "token_dim": 1280, + ... "num_transformer_submodules": 1, + ... "num_attention_heads": 20, + ... "num_layers": 36, + ... "encoder_hidden_size": 1280, + ... "prefix_projection": False, + ... "postprocess_past_key_value_function": None, + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForCausalLM.from_pretrained("gpt2-large") + >>> peft_model = PeftModelForCausalLM(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 1843200 || all params: 775873280 || trainable%: 0.23756456724479544 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + self.base_model_prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + + if not peft_config.is_prompt_learning: + # Adds alora_offsets to kwargs if relevant. No other modifications. + kwargs = get_alora_offsets_for_forward(self, input_ids, inputs_embeds, **kwargs) + if self.base_model.config.model_type == "mpt": + if inputs_embeds is not None: + raise AssertionError("forward in MPTForCausalLM does not support inputs_embeds") + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids") + kwargs["token_type_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # overwrite past_kv in kwargs + # some archs require max_cache_len to re-initialize the cache + if input_ids is not None: + max_cache_len = input_ids.shape[1] + peft_config.num_virtual_tokens + else: + max_cache_len = inputs_embeds.shape[1] + peft_config.num_virtual_tokens + kwargs["past_key_values"] = self.get_prompt(batch_size, max_cache_len=max_cache_len) + return self.base_model(input_ids=input_ids, inputs_embeds=inputs_embeds, **kwargs) + elif peft_config.peft_type == PeftType.CPT: + return self._cpt_forward(input_ids, inputs_embeds, peft_config, task_ids, batch_size, **kwargs) + else: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + # concat prompt labels + if labels is not None: + prefix_labels = torch.full((batch_size, peft_config.num_virtual_tokens), -100).to(labels.device) + kwargs["labels"] = torch.cat((prefix_labels, labels), dim=1) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _cpt_forward(self, input_ids, inputs_embeds, peft_config, task_ids, batch_size, **kwargs): + # Extract labels from kwargs + labels = kwargs.pop("labels") + device = [i.device for i in [input_ids, inputs_embeds, labels] if i is not None][0] + # Extract input_type_mask from kwargs and move it to the same device as labels + if "input_type_mask" in kwargs.keys(): + input_type_mask = kwargs.pop("input_type_mask").to(device) + else: + if input_ids is None: + N_tokens = inputs_embeds.shape[1] + else: + N_tokens = input_ids.shape[1] + input_type_mask = torch.ones((batch_size, N_tokens)).to(device) * 4 + + cpt_token_ids = peft_config.cpt_token_ids + cpt_tokens_type_mask = peft_config.cpt_tokens_type_mask + + # Generate embeddings if not provided + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + # Get prompt and concatenate with input embeddings + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + # If labels are provided, generate prefix labels and type mask + cpt_labels = None + if labels is not None: + # Generate prefix labels and concatenate with the input labels + prefix_labels = torch.Tensor(cpt_token_ids).long().view(1, -1) + prefix_labels = prefix_labels.repeat(batch_size, 1).to(labels.device) + cpt_labels = torch.cat((prefix_labels, labels), dim=1) + # Generate prefix type mask and shift input type mask values to avoid conflicts + prefix_type_mask = torch.Tensor(cpt_tokens_type_mask).long().view(1, -1) + prefix_type_mask = prefix_type_mask.repeat(batch_size, 1).to(labels.device) + adjusted_input_type_mask = input_type_mask + adjusted_input_type_mask[adjusted_input_type_mask > 0] += prefix_type_mask.max() + # Concatenate prefix and shifted input type masks + cpt_type_mask = torch.cat((prefix_type_mask, adjusted_input_type_mask), dim=1) + # Identify valid label positions and mask invalid ones with -100 + labels_idx = (cpt_type_mask > 0) & (cpt_type_mask % 4 == 0) + cpt_labels[~labels_idx] = -100 + # Update kwargs with the modified labels + + kwargs["labels"] = cpt_labels + # Pass the modified inputs to the base model + base_model_output = self.base_model(inputs_embeds=inputs_embeds, **kwargs) + if labels is None: + return base_model_output + else: + # Calculate the loss using the custom CPT loss function + cpt_embedding = PEFT_TYPE_TO_TUNER_MAPPING[peft_config.peft_type] + base_model_output = cpt_embedding.calculate_loss( + base_model_output, cpt_labels, cpt_type_mask, self.peft_config["default"] + ) + return base_model_output + + def generate(self, *args, **kwargs): + peft_config = self.active_peft_config + self.base_model.prepare_inputs_for_generation = self.prepare_inputs_for_generation + if hasattr(self.base_model, "model"): + self.base_model.model.generation_config = self.generation_config + else: + self.base_model.generation_config = self.generation_config + try: + if not peft_config.is_prompt_learning: + # Adds alora_offsets to kwargs if relevant. No other changes. + kwargs = get_alora_offsets_for_generate(self, *args, **kwargs) + with self._enable_peft_forward_hooks(*args, **kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + outputs = self.base_model.generate(*args, **kwargs) + else: + outputs = self.base_model.generate(*args, **kwargs) + except: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + raise + else: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + return outputs + + def prepare_inputs_for_generation(self, *args, task_ids: Optional[torch.Tensor] = None, **kwargs): + peft_config = self.active_peft_config + model_kwargs = self.base_model_prepare_inputs_for_generation(*args, **kwargs) + + # https://github.com/huggingface/transformers/pull/26681/ introduced new cache format + # for some architectures which requires a special fix for prompt tuning etc. + # TODO: starting with transformers 4.38, all architectures should support caching. + uses_transformers_4_38 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.38.0") + uses_transformers_4_36 = packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.36.0") + transformers_new_cache_archs = ["llama", "mistral", "persimmon", "phi"] + if packaging.version.parse(transformers.__version__) > packaging.version.parse("4.43.3"): + # https://github.com/huggingface/transformers/pull/31445 + transformers_new_cache_archs.append("bloom") + + uses_cache = uses_transformers_4_38 or ( + uses_transformers_4_36 and self.base_model.config.model_type in transformers_new_cache_archs + ) + + # heuristic to determine if we're in 'prefill stage' (when the KV cache is filled with the values from the + # initial input) + is_prefill = (model_kwargs.get("cache_position") is not None) and (model_kwargs["cache_position"][0] == 0) + + if peft_config.peft_type == PeftType.POLY: + model_kwargs["task_ids"] = task_ids + if peft_config.is_prompt_learning: + if uses_cache and (model_kwargs.get("past_key_values", None) is not None): + # change in the logic of `prepare_inputs_for_generation` makes the below code necessary + # In prompt learning methods, past key values are longer when compared to the `input_ids`. + # As such only consider the last input ids in the autogressive generation phase. + past_key_values = model_kwargs["past_key_values"] + if isinstance(past_key_values, (tuple, list)): + seq_len = past_key_values[0][0].shape[-2] + else: # using transformers kv cache + seq_len = past_key_values.get_seq_length() + if seq_len >= model_kwargs["input_ids"].shape[1]: + model_kwargs["input_ids"] = model_kwargs["input_ids"][:, -1:] + + if (attention_mask := model_kwargs.get("attention_mask", None)) is not None: + if isinstance(attention_mask, dict): + # see: https://github.com/huggingface/transformers/pull/37866 + # For now, just deal with the case of a single attention mask + if len(attention_mask) != 1: + raise ValueError( + f"Expected a single attention mask, got {len(attention_mask)} instead, please open an " + "issue (https://github.com/huggingface/peft/issues) and report the error." + ) + attention_mask = list(attention_mask.values())[0] + + size = model_kwargs["input_ids"].shape[0], peft_config.num_virtual_tokens + prefix_attention_mask = torch.ones(size).to(model_kwargs["input_ids"].device) + if attention_mask.dim() == 4: + # Transform the 4d attention mask to 2d, leave it up to the model to deal with it instead of trying + # to create a 4d attention mask here. + # from [batch_size, heads, input_ids_length, total_sequence_length] + # to [batch_size, total_sequence_length] + bs = attention_mask.shape[0] + total_seq_len = prefix_attention_mask.shape[1] + attention_mask.shape[2] + attention_mask_2d = torch.ones((bs, total_seq_len), dtype=attention_mask.dtype) + + if is_prefill and (peft_config.peft_type not in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE)): + # if in prefill stage, for prompt learning methods that are not prefix tuning, new tokens + # (embeddings) are inserted, thus set cache_position to correspond to these tokens + cache_position_ = torch.arange(total_seq_len, device=model_kwargs["input_ids"].device) + else: + # prefix tuning acts directly on the cache, no need to upate cache_position + cache_position_ = model_kwargs["cache_position"] + + attention_mask_new = create_attention_mask( + self.get_base_model(), + model_input=None, + attention_mask=attention_mask_2d, + past_key_values=model_kwargs.get("past_key_values"), + cache_position=cache_position_, + batch_size=bs, + sequence_length=total_seq_len, + position_ids=model_kwargs.get("position_ids", None), + ) + model_kwargs["attention_mask"] = attention_mask_new + else: + # 2d attention mask + model_kwargs["attention_mask"] = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + if model_kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + model_kwargs["position_ids"] = model_kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn( + "Position ids are not supported for parameter efficient tuning. Ignoring position ids." + ) + model_kwargs["position_ids"] = None + + if kwargs.get("token_type_ids", None) is not None: + warnings.warn( + "Token type ids are not supported for parameter efficient tuning. Ignoring token type ids" + ) + kwargs["token_type_ids"] = None + + cache: transformers.Cache | None = model_kwargs.get("past_key_values", None) + # no past_key_values or past_key_values empty cache + requires_prompt_injection = (cache is None) or ( + isinstance(cache, transformers.Cache) and not cache.get_seq_length() + ) + + if requires_prompt_injection and peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # some archs require max_cache_len to re-initialize the cache, but DynamicCache has no max len + if isinstance(cache, transformers.Cache) and not isinstance(cache, transformers.DynamicCache): + max_cache_len = cache.max_cache_len + else: + max_cache_len = -1 # -1 means no max length + new_past_key_values = self.get_prompt( + batch_size=model_kwargs["input_ids"].shape[0], + max_cache_len=max_cache_len, + ) + model_kwargs["past_key_values"] = new_past_key_values + elif requires_prompt_injection: + inputs_embeds = self.word_embeddings(model_kwargs["input_ids"]) + prompts = self.get_prompt(batch_size=model_kwargs["input_ids"].shape[0], task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + model_kwargs["inputs_embeds"] = torch.cat((prompts, inputs_embeds), dim=1) + model_kwargs["input_ids"] = None + + # if we're in the prefill stage + if is_prefill and (peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE)): + # for prefix tuning, the past_key_values have been prefilled + model_kwargs["cache_position"] += peft_config.num_virtual_tokens + elif peft_config.peft_type not in ( + PeftType.PREFIX_TUNING, + PeftType.CARTRIDGE, + ): # prefix-style needs cache_position + # For transformers>=4.38.0 - for some architectures such as Llama, `cache_position` is passed in the forward + # pass to keep track of the position ids of the cache. We have to pop that from `model_kwargs` as + # `cache_position` is properly created by the model, using the passed `inputs_embeds`: + # https://github.com/huggingface/transformers/blob/593230f0a1150ea9c0477b9d859f25daf73c8c33/src/transformers/models/llama/modeling_llama.py#L956 + _ = model_kwargs.pop("cache_position", None) + + return model_kwargs + + +class PeftModelForSeq2SeqLM(PeftModel): + """ + Peft model for sequence-to-sequence language modeling. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import PeftModelForSeq2SeqLM, get_peft_config + + >>> config = { + ... "peft_type": "LORA", + ... "task_type": "SEQ_2_SEQ_LM", + ... "inference_mode": False, + ... "r": 8, + ... "target_modules": ["q", "v"], + ... "lora_alpha": 32, + ... "lora_dropout": 0.1, + ... "fan_in_fan_out": False, + ... "enable_lora": None, + ... "bias": "none", + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> peft_model = PeftModelForSeq2SeqLM(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 884736 || all params: 223843584 || trainable%: 0.3952474242013566 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + self.base_model_prepare_inputs_for_generation = self.base_model.prepare_inputs_for_generation + self.base_model_prepare_encoder_decoder_kwargs_for_generation = ( + self.base_model._prepare_encoder_decoder_kwargs_for_generation + ) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + decoder_input_ids=None, + decoder_attention_mask=None, + decoder_inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + if not peft_config.is_prompt_learning: + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + decoder_input_ids=decoder_input_ids, + decoder_attention_mask=decoder_attention_mask, + decoder_inputs_embeds=decoder_inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if decoder_attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + decoder_attention_mask.device + ) + if peft_config.peft_type not in [PeftType.PROMPT_TUNING, PeftType.P_TUNING]: + decoder_attention_mask = torch.cat((prefix_attention_mask, decoder_attention_mask), dim=1) + + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids") + kwargs["token_type_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "decoder_attention_mask": decoder_attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # overwrite past_kv in kwargs + kwargs["past_key_values"] = self.get_prompt(batch_size) + return self.base_model( + input_ids=input_ids, + decoder_input_ids=decoder_input_ids, + decoder_inputs_embeds=decoder_inputs_embeds, + **kwargs, + ) + elif peft_config.peft_type in [PeftType.PROMPT_TUNING, PeftType.P_TUNING]: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + attention_mask.device + ) + kwargs["attention_mask"] = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + prompts = self.get_prompt(batch_size=batch_size) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts[:, : peft_config.num_virtual_tokens], inputs_embeds), dim=1) + + return self.base_model( + inputs_embeds=inputs_embeds, + decoder_input_ids=decoder_input_ids, + decoder_inputs_embeds=decoder_inputs_embeds, + **kwargs, + ) + else: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + if decoder_inputs_embeds is None and decoder_input_ids is None: + decoder_input_ids = shift_tokens_right( + labels, self.config.pad_token_id, self.config.decoder_start_token_id + ) + decoder_inputs_embeds = self.word_embeddings(decoder_input_ids) + + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + attention_mask.device + ) + kwargs["attention_mask"] = torch.cat((prefix_attention_mask, attention_mask), dim=1) + # concat prompt labels + if labels is not None: + if peft_config.num_transformer_submodules == 1: + kwargs["labels"] = labels + elif peft_config.num_transformer_submodules == 2: + prefix_labels = torch.full((batch_size, peft_config.num_virtual_tokens), -100).to(labels.device) + kwargs["labels"] = torch.cat((prefix_labels, labels), dim=1) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts[:, : peft_config.num_virtual_tokens], inputs_embeds), dim=1) + if peft_config.num_transformer_submodules == 1: + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + elif peft_config.num_transformer_submodules == 2: + decoder_inputs_embeds = torch.cat( + (prompts[:, peft_config.num_virtual_tokens :], decoder_inputs_embeds), dim=1 + ) + return self.base_model( + inputs_embeds=inputs_embeds, decoder_inputs_embeds=decoder_inputs_embeds, **kwargs + ) + + def generate(self, **kwargs): + peft_config = self.active_peft_config + self.base_model.prepare_inputs_for_generation = self.prepare_inputs_for_generation + self.base_model._prepare_encoder_decoder_kwargs_for_generation = ( + self._prepare_encoder_decoder_kwargs_for_generation + ) + try: + if not peft_config.is_prompt_learning: + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + outputs = self.base_model.generate(**kwargs) + else: + if "input_ids" not in kwargs: + raise ValueError("input_ids must be provided for Peft model generation") + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn( + "Position ids are not supported for parameter efficient tuning. Ignoring position ids." + ) + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn( + "Token type ids are not supported for parameter efficient tuning. Ignoring token type ids" + ) + kwargs["token_type_ids"] = None + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + outputs = self.base_model.generate(**kwargs) + elif peft_config.peft_type in [ + PeftType.PROMPT_TUNING, + PeftType.P_TUNING, + PeftType.MULTITASK_PROMPT_TUNING, + ]: + kwargs = deepcopy(kwargs) + + if "encoder_outputs" in kwargs: + del kwargs["encoder_outputs"] + warnings.warn( + "`encoder_outputs` should not be passed to `generate` when using prompt tuning. Ignoring it." + ) + + input_ids = kwargs.pop("input_ids") + inputs_embeds = self.word_embeddings(input_ids) + batch_size = inputs_embeds.shape[0] + prompts = self.get_prompt(batch_size=batch_size, task_ids=kwargs.pop("task_ids", None)) + prompts = prompts.to(inputs_embeds.dtype) + + inputs_embeds = torch.cat((prompts[:, : peft_config.num_virtual_tokens], inputs_embeds), dim=1) + kwargs["inputs_embeds"] = inputs_embeds + + if "attention_mask" in kwargs: + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to( + kwargs["attention_mask"].device + ) + kwargs["attention_mask"] = torch.cat((prefix_attention_mask, kwargs["attention_mask"]), dim=1) + + return self.base_model.generate(**kwargs) + else: + raise NotImplementedError + except: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + self.base_model._prepare_encoder_decoder_kwargs_for_generation = ( + self.base_model_prepare_encoder_decoder_kwargs_for_generation + ) + raise + else: + self.base_model.prepare_inputs_for_generation = self.base_model_prepare_inputs_for_generation + self.base_model._prepare_encoder_decoder_kwargs_for_generation = ( + self.base_model_prepare_encoder_decoder_kwargs_for_generation + ) + return outputs + + def prepare_inputs_for_generation(self, *args, task_ids: torch.Tensor = None, **kwargs): + peft_config = self.active_peft_config + model_kwargs = self.base_model_prepare_inputs_for_generation(*args, **kwargs) + if peft_config.peft_type == PeftType.POLY: + model_kwargs["task_ids"] = task_ids + elif peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + past_key_values = model_kwargs.get("past_key_values", None) + cache_position = model_kwargs.get("cache_position", [None]) + # check prefill stage + is_prefill_stage = ( + # old cache implementation + (past_key_values is None) + # new cache implementation + or (isinstance(past_key_values, Cache) and (cache_position[0] == 0)) + ) + if is_prefill_stage: + batch_size = model_kwargs["decoder_input_ids"].shape[0] + new_past_key_values = self.get_prompt(batch_size) + model_kwargs["past_key_values"] = new_past_key_values + + return model_kwargs + + +class PeftModelForTokenClassification(PeftModel): + """ + Peft model for token classification tasks. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + - **cls_layer_name** (`str`) -- The name of the classification layer. + + Example: + + ```py + >>> from transformers import AutoModelForSequenceClassification + >>> from peft import PeftModelForTokenClassification, get_peft_config + + >>> config = { + ... "peft_type": "PREFIX_TUNING", + ... "task_type": "TOKEN_CLS", + ... "inference_mode": False, + ... "num_virtual_tokens": 20, + ... "token_dim": 768, + ... "num_transformer_submodules": 1, + ... "num_attention_heads": 12, + ... "num_layers": 12, + ... "encoder_hidden_size": 768, + ... "prefix_projection": False, + ... "postprocess_past_key_value_function": None, + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForTokenClassification.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForTokenClassification(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 370178 || all params: 108680450 || trainable%: 0.3406113979101117 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig = None, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + + classifier_module_names = ["classifier", "score"] + if hasattr(peft_config, "modules_to_save"): + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + for name, _ in self.base_model.named_children(): + if any(module_name in name for module_name in self.modules_to_save): + self.cls_layer_name = name + break + + # to make sure classifier layer is trainable; this may add a new ModulesToSaveWrapper + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + + """ + # ensure that additional adapters also add the classifier layer to modules_to_save + if hasattr(peft_config, "modules_to_save"): + classifier_module_names = ["classifier", "score"] + if peft_config.modules_to_save is None: + peft_config.modules_to_save = classifier_module_names[:] + else: + peft_config.modules_to_save.extend(classifier_module_names) + + return super().add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if not peft_config.is_prompt_learning: + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + labels=labels, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "labels": labels, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + return self._prefix_tuning_forward(input_ids=input_ids, **kwargs) + else: + if kwargs.get("token_type_ids", None) is not None: + kwargs["token_type_ids"] = torch.cat( + ( + torch.zeros(batch_size, peft_config.num_virtual_tokens).to(self.word_embeddings.weight.device), + kwargs["token_type_ids"], + ), + dim=1, + ).long() + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size, task_ids=task_ids) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _prefix_tuning_forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + labels=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + **kwargs, + ): + batch_size = _get_batch_size(input_ids, inputs_embeds) + past_key_values = self.get_prompt(batch_size) + fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys()) + kwargs.update( + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "inputs_embeds": inputs_embeds, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + "past_key_values": past_key_values, + } + ) + if "past_key_values" in fwd_params: + return self.base_model(labels=labels, **kwargs) + else: + transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name) + fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys()) + if "past_key_values" not in fwd_params: + raise ValueError("Model does not support past key values which are required for prefix tuning.") + outputs = transformer_backbone_name(**kwargs) + sequence_output = outputs[0] + if "dropout" in [name for name, _ in list(self.base_model.named_children())]: + sequence_output = self.base_model.dropout(sequence_output) + logits = self.base_model.get_submodule(self.cls_layer_name)(sequence_output) + + loss = None + if labels is not None: + loss_fct = CrossEntropyLoss() + loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1)) + + if not return_dict: + output = (logits,) + outputs[2:] + return ((loss,) + output) if loss is not None else output + + return TokenClassifierOutput( + loss=loss, + logits=logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class PeftModelForQuestionAnswering(PeftModel): + """ + Peft model for extractive question answering. + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + - **cls_layer_name** (`str`) -- The name of the classification layer. + + Example: + + ```py + >>> from transformers import AutoModelForQuestionAnswering + >>> from peft import PeftModelForQuestionAnswering, get_peft_config + + >>> config = { + ... "peft_type": "LORA", + ... "task_type": "QUESTION_ANS", + ... "inference_mode": False, + ... "r": 16, + ... "target_modules": ["query", "value"], + ... "lora_alpha": 32, + ... "lora_dropout": 0.05, + ... "fan_in_fan_out": False, + ... "bias": "none", + ... } + + >>> peft_config = get_peft_config(config) + >>> model = AutoModelForQuestionAnswering.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForQuestionAnswering(model, peft_config) + >>> peft_model.print_trainable_parameters() + trainable params: 592900 || all params: 108312580 || trainable%: 0.5473971721475013 + ``` + """ + + def __init__( + self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs + ) -> None: + super().__init__(model, peft_config, adapter_name, **kwargs) + + qa_module_names = ["qa_outputs"] + if hasattr(peft_config, "modules_to_save"): + if peft_config.modules_to_save is None: + peft_config.modules_to_save = qa_module_names[:] + else: + peft_config.modules_to_save.extend(qa_module_names) + + for name, _ in self.base_model.named_children(): + if any(module_name in name for module_name in self.modules_to_save): + self.cls_layer_name = name + break + + # to make sure classifier layer is trainable; this may add a new ModulesToSaveWrapper + _set_trainable( + self, + adapter_name, + module_names=getattr(peft_config, "modules_to_save", None), + inference_mode=peft_config.inference_mode, + ) + + def add_adapter( + self, + adapter_name: str, + peft_config: PeftConfig, + low_cpu_mem_usage: bool = False, + autocast_adapter_dtype: bool = True, + ) -> None: + """ + Add an adapter to the model based on the passed configuration. + + This adapter is not trained. To load a trained adapter, check out [`PeftModel.load_adapter`]. + + The name for the new adapter should be unique. + + The new adapter is not automatically set as the active adapter. Use [`PeftModel.set_adapter`] to set the active + adapter. + + Args: + adapter_name (`str`): + The name of the adapter to be added. + peft_config ([`PeftConfig`]): + The configuration of the adapter to be added. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the process when loading saved + adapters. Don't use this option when creating a new PEFT adapter for training. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter + weights using float16 and bfloat16 to float32, as this is typically required for stable training, and + only affect select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the + corresponding layer. + + """ + # ensure that additional adapters also add the classifier layer to modules_to_save + if hasattr(peft_config, "modules_to_save"): + qa_module_names = ["qa_outputs"] + if peft_config.modules_to_save is None: + peft_config.modules_to_save = qa_module_names[:] + else: + peft_config.modules_to_save.extend(qa_module_names) + + return super().add_adapter(adapter_name, peft_config, low_cpu_mem_usage=low_cpu_mem_usage) + + def forward( + self, + input_ids=None, + attention_mask=None, + token_type_ids=None, + position_ids=None, + inputs_embeds=None, + start_positions=None, + end_positions=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + return_dict = return_dict if return_dict is not None else self.config.use_return_dict + + if not peft_config.is_prompt_learning: + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + start_positions=start_positions, + end_positions=end_positions, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "start_positions": start_positions, + "end_positions": end_positions, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + return self._prefix_tuning_forward(input_ids=input_ids, **kwargs) + else: + if kwargs.get("token_type_ids", None) is not None: + kwargs["token_type_ids"] = torch.cat( + ( + torch.zeros(batch_size, peft_config.num_virtual_tokens).to(self.word_embeddings.weight.device), + kwargs["token_type_ids"], + ), + dim=1, + ).long() + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + def _prefix_tuning_forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + start_positions=None, + end_positions=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + **kwargs, + ): + batch_size = _get_batch_size(input_ids, inputs_embeds) + past_key_values = self.get_prompt(batch_size) + fwd_params = list(inspect.signature(self.base_model.forward).parameters.keys()) + kwargs.update( + { + "input_ids": input_ids, + "attention_mask": attention_mask, + "inputs_embeds": inputs_embeds, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + "past_key_values": past_key_values, + } + ) + if "past_key_values" in fwd_params: + return self.base_model(start_positions=start_positions, end_positions=end_positions, **kwargs) + else: + transformer_backbone_name = self.base_model.get_submodule(self.transformer_backbone_name) + fwd_params = list(inspect.signature(transformer_backbone_name.forward).parameters.keys()) + if "past_key_values" not in fwd_params: + raise ValueError("Model does not support past key values which are required for prefix tuning.") + outputs = transformer_backbone_name(**kwargs) + sequence_output = outputs[0] + if "dropout" in [name for name, _ in list(self.base_model.named_children())]: + sequence_output = self.base_model.dropout(sequence_output) + logits = self.base_model.get_submodule(self.cls_layer_name)(sequence_output) + start_logits, end_logits = logits.split(1, dim=-1) + start_logits = start_logits.squeeze(-1).contiguous() + end_logits = end_logits.squeeze(-1).contiguous() + + total_loss = None + if start_positions is not None and end_positions is not None: + # If we are on multi-GPU, split add a dimension + if len(start_positions.size()) > 1: + start_positions = start_positions.squeeze(-1) + if len(end_positions.size()) > 1: + end_positions = end_positions.squeeze(-1) + # sometimes the start/end positions are outside our model inputs, we ignore these terms + ignored_index = start_logits.size(1) + start_positions = start_positions.clamp(0, ignored_index) + end_positions = end_positions.clamp(0, ignored_index) + + loss_fct = CrossEntropyLoss(ignore_index=ignored_index) + start_loss = loss_fct(start_logits, start_positions) + end_loss = loss_fct(end_logits, end_positions) + total_loss = (start_loss + end_loss) / 2 + + if not return_dict: + output = (start_logits, end_logits) + outputs[2:] + return ((total_loss,) + output) if total_loss is not None else output + + return QuestionAnsweringModelOutput( + loss=total_loss, + start_logits=start_logits, + end_logits=end_logits, + hidden_states=outputs.hidden_states, + attentions=outputs.attentions, + ) + + +class PeftModelForFeatureExtraction(PeftModel): + """ + Peft model for extracting features/embeddings from transformer models + + Args: + model ([`~transformers.PreTrainedModel`]): Base transformer model. + peft_config ([`PeftConfig`]): Peft config. + adapter_name (`str`, *optional*): The name of the adapter, defaults to `"default"`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + Whether to autocast the adapter dtype. Defaults to `True`. Right now, this will only cast adapter weights + using float16 and bfloat16 to float32, as this is typically required for stable training, and only affect + select PEFT tuners. If set to `False`, the dtypes will stay the same as those of the corresponding layer. + + **Attributes**: + - **config** ([`~transformers.PretrainedConfig`]) -- The configuration object of the base model. + + Example: + + ```py + >>> from transformers import AutoModel + >>> from peft import PeftModelForFeatureExtraction, get_peft_config + + >>> config = { + ... "peft_type": "LORA", + ... "task_type": "FEATURE_EXTRACTION", + ... "inference_mode": False, + ... "r": 16, + ... "target_modules": ["query", "value"], + ... "lora_alpha": 32, + ... "lora_dropout": 0.05, + ... "fan_in_fan_out": False, + ... "bias": "none", + ... } + >>> peft_config = get_peft_config(config) + >>> model = AutoModel.from_pretrained("bert-base-cased") + >>> peft_model = PeftModelForFeatureExtraction(model, peft_config) + >>> peft_model.print_trainable_parameters() + ``` + """ + + def __init__(self, model: torch.nn.Module, peft_config: PeftConfig, adapter_name: str = "default", **kwargs): + super().__init__(model, peft_config, adapter_name, **kwargs) + + def forward( + self, + input_ids=None, + attention_mask=None, + inputs_embeds=None, + output_attentions=None, + output_hidden_states=None, + return_dict=None, + task_ids=None, + **kwargs, + ): + peft_config = self.active_peft_config + if not peft_config.is_prompt_learning: + if peft_config.peft_type == PeftType.POLY: + kwargs["task_ids"] = task_ids + + with self._enable_peft_forward_hooks(**kwargs): + kwargs = {k: v for k, v in kwargs.items() if k not in self.special_peft_forward_args} + return self.base_model( + input_ids=input_ids, + attention_mask=attention_mask, + inputs_embeds=inputs_embeds, + output_attentions=output_attentions, + output_hidden_states=output_hidden_states, + return_dict=return_dict, + **kwargs, + ) + + batch_size = _get_batch_size(input_ids, inputs_embeds) + if attention_mask is not None: + # concat prompt attention mask + prefix_attention_mask = torch.ones(batch_size, peft_config.num_virtual_tokens).to(attention_mask.device) + attention_mask = torch.cat((prefix_attention_mask, attention_mask), dim=1) + + if kwargs.get("position_ids", None) is not None: + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # Offset position_ids by num_virtual_tokens to account for the KV cache prefix + kwargs["position_ids"] = kwargs["position_ids"] + peft_config.num_virtual_tokens + else: + warnings.warn("Position ids are not supported for parameter efficient tuning. Ignoring position ids.") + kwargs["position_ids"] = None + if kwargs.get("token_type_ids", None) is not None: + warnings.warn("Token type ids are not supported for parameter efficient tuning. Ignoring token type ids") + kwargs["token_type_ids"] = None + kwargs.update( + { + "attention_mask": attention_mask, + "output_attentions": output_attentions, + "output_hidden_states": output_hidden_states, + "return_dict": return_dict, + } + ) + + if peft_config.peft_type in (PeftType.PREFIX_TUNING, PeftType.CARTRIDGE): + # overwrite past_kv in kwargs + kwargs["past_key_values"] = self.get_prompt(batch_size) + return self.base_model(input_ids=input_ids, **kwargs) + else: + if inputs_embeds is None: + inputs_embeds = self.word_embeddings(input_ids) + prompts = self.get_prompt(batch_size=batch_size) + prompts = prompts.to(inputs_embeds.dtype) + inputs_embeds = torch.cat((prompts, inputs_embeds), dim=1) + return self.base_model(inputs_embeds=inputs_embeds, **kwargs) + + +@dataclass +class TunerLayerStatus: + name: str + module_type: str + enabled: bool + active_adapters: list[str] + merged_adapters: list[str] + requires_grad: dict[str, bool | Literal["irregular"]] + available_adapters: list[str] + devices: dict[str, list[str]] + + +def get_layer_status(model: torch.nn.Module) -> list[TunerLayerStatus]: + """Get the status of each adapter layer in the model. + + This function returns a list of `TunerLayerStatus` dataclass instances, each of which contains the following + attributes: + + - `name` (`str`): + The name of the adapter layer, e.g. `model.encoder.block.0.layer.0.SelfAttention.q`. + - `module_type` (`str`): + The type of the adapter layer, e.g. `lora.Linear`. + - `enabled` (`bool`): + Whether the adapter layer is enabled. + - `active_adapters` (`list[str]`): + The names of the active adapters, if any, e.g. `["default"]`. + - `merged_adapters` (`list[str]`): + The names of the merged adapters, if any, e.g. `["default"]`. + - requires_grad : dict[str, bool | Literal["irregular"]] + The requires_grad status of the parameters for each adapter module. Ideally, it should be either `True` or + `False`. If the requires_grad status is not consistent across all parameters, the value will be set to + `"irregular"`. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + - `devices` (`dict[str, list[str]]`): + The devices where the parameters of the given adapter are stored, e.g. `["cuda"]`. + + Args: + model ([Union[`~PeftModel`, `~transformers.PreTrainedModel`, `nn.Module`]]): + The model to get the adapter layer status from. + + Returns: + list[`peft.peft_model.TunerLayerStatus`]: + A list of dataclasses, each containing the status of the corresponding adapter layer. + + """ + if isinstance(model, PeftModel): + base_model = model.base_model + if not isinstance(base_model, BaseTuner): + raise TypeError( + "get_layer_status() got an invalid PeftModel instance; prefix tuning and adaption prompt are not " + "supported." + ) + else: + base_model = model + + layer_status: list[TunerLayerStatus] = [] + for name, module in base_model.named_modules(): + if not isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)): + continue + if isinstance(module, TrainableTokensWrapper): + # Skip TrainableTokensWrapper, since it wraps TrainableTokensLayer, which is the actual PEFT layer we're + # interested in. + continue + + # determine if all submodules/parameters if this module require grad or not + mapping_requires_grad_list: dict[str, list[bool]] = collections.defaultdict(list) + for adapter_module_name in module.adapter_layer_names: + adapter_module = getattr(module, adapter_module_name) + if isinstance(adapter_module, torch.nn.ModuleDict): + for key, submodule in adapter_module.items(): + for param in submodule.parameters(): + mapping_requires_grad_list[key].append(param.requires_grad) + elif isinstance(adapter_module, torch.nn.ParameterDict): + for key, param in adapter_module.items(): + mapping_requires_grad_list[key].append(param.requires_grad) + else: + # strange, we don't know how to handle this, ignore for now + pass + + def check_irrgular(vals: list[bool]) -> bool | Literal["irregular"]: + if all(vals): + return True + if not any(vals): + return False + return "irregular" + + requires_grad = {key: check_irrgular(vals) for key, vals in mapping_requires_grad_list.items()} + + devices_dd = collections.defaultdict(list) + for adapter_module_name in module.adapter_layer_names + module.other_param_names: + adapter_module = getattr(module, adapter_module_name) + if isinstance(adapter_module, torch.nn.ModuleDict): + for key, submodule in adapter_module.items(): + devices_dd[key].extend([param.device.type for param in submodule.parameters()]) + elif isinstance(adapter_module, torch.nn.ParameterDict) or ( + adapter_module.__class__.__name__ == "BufferDict" + ): # VeRA + for key, param in adapter_module.items(): + devices_dd[key].append(param.device.type) + devices = {key: sorted(set(val)) for key, val in devices_dd.items()} + + status = TunerLayerStatus( + name=name, + module_type=repr(module).partition("(")[0], + enabled=not module.disable_adapters, + active_adapters=module.active_adapters, + merged_adapters=module.merged_adapters, + requires_grad=requires_grad, + available_adapters=sorted(module._get_available_adapters()), + devices=devices, + ) + layer_status.append(status) + + if not layer_status: + raise ValueError( + "No adapter layers found in the model, please ensure that it's a PEFT model or that you have PEFT adapters " + "injected in the model." + ) + + return layer_status + + +@dataclass +class TunerModelStatus: + base_model_type: str + adapter_model_type: str + peft_types: dict[str, str] + trainable_params: int + total_params: int + num_adapter_layers: int + enabled: bool | Literal["irregular"] + active_adapters: list[str] | Literal["irregular"] + merged_adapters: list[str] | Literal["irregular"] + requires_grad: dict[str, bool | Literal["irregular"]] + available_adapters: list[str] + devices: dict[str, list[str]] + + +def get_model_status(model: torch.nn.Module) -> TunerModelStatus: + """Get the status of tuners of the model. + + This function returns a `TunerModelStatus` dataclass instance, which contains the following attributes: + + - `base_model_type` (`str`): + The type of the base model, e.g. `T5Model`. + - `adapter_model_type` (`str`): + The type of the adapter model, e.g. `LoraModel`. + - `peft_types` (`dict[str, str]`): + The mapping of adapter name to adapter type, e.g. `{"default": "LORA"}`. + - `trainable_params` (`int`): + The number of trainable parameters in the model. + - `total_params` (`int`): + The total number of parameters in the model. + - `num_adapter_layers` (`int`): + The number of adapter layers in the model. + - `enabled` (`bool`, `Literal["irregular"]`): + Whether all adapter layers are enabled. If some are enabled and some are not, this will be `"irregular"`. This + means that your model is in an inconsistent state and might not work as expected. + - `active_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the active adapters. If the active adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `merged_adapters` (`list[str]`, `Literal["irregular"]`): + The names of the merged adapters. If the merged adapters are not consistent across all layers, this will be + `"irregular"`, which means that your model is in an inconsistent state and might not work as expected. + - `requires_grad` (`dict[str, bool | Literal["irregular"]]`): + Whether for the given adapter, all adapter layers have `requires_grad` set to `True` or `False`. If there is a + mix, this will be set to `"irregular"`, which means that your model is in an inconsistent state and might not + work as expected. + - `available_adapters` (`list[str]`): + The names of the available adapters, e.g. `["default"]`. + - `devices` (`dict[str, list[str]]`): + The devices where the parameters of the given adapter are stored, e.g. `["cuda"]`. + + Args: + model ([Union[`~PeftModel`, `~transformers.PreTrainedModel`, `nn.Module`]]): + The model to get the adapter layer status from. + + Returns: + `peft.peft_model.TunerModelStatus`: + A dataclass containing the status of the model. + + """ + if isinstance(model, PeftModel): + if not isinstance(model.base_model, BaseTuner): + raise TypeError( + "get_model_status() got an invalid PeftModel instance; prefix tuning and adaption prompt are not " + "supported." + ) + base_model_type = model.get_base_model().__class__.__name__ + trainable_params, total_params = model.get_nb_trainable_parameters() + base_model = model.base_model + peft_types = {key: str(config.peft_type).partition(".")[-1] for key, config in base_model.peft_config.items()} + adapter_model_type = base_model.__class__.__name__ + elif isinstance(model, PreTrainedModel): + base_model_type = model.__class__.__name__ + trainable_params, total_params = PeftModel.get_nb_trainable_parameters(model) + base_model = model + peft_types = {} + adapter_model_type = "None" + else: + base_model_type = "other" + trainable_params, total_params = PeftModel.get_nb_trainable_parameters(model) + base_model = model + peft_types = {} + adapter_model_type = "None" + + layer_status = get_layer_status(model) + num_adapter_layers = len(layer_status) + + enabled_set: set[bool] = {status.enabled for status in layer_status} # must be {True}, {False}, or {True, False} + enabled: bool | Literal["irregular"] + if len(enabled_set) == 1: + enabled = enabled_set.pop() + else: + enabled = "irregular" + + available_adapters: list[str] = sorted(set().union(*(status.available_adapters for status in layer_status))) + + # ideally, active adapters should be consistent across all layers of the model, but we cannot guarantee it + all_active_adapters: set[tuple[str, ...]] = {tuple(status.active_adapters) for status in layer_status} + active_adapters: list[str] | Literal["irregular"] + if not all_active_adapters: + active_adapters = [] + elif len(all_active_adapters) == 1: + active_adapters = list(all_active_adapters.pop()) + else: + active_adapters = "irregular" + + # Here we determine what adapters are merged. This is not trivial because multiple adapters can be merged or not at + # the same time. Some layers may only have adapter A, some only adapter B, so it's not as easy as just checking + # which adapters are merged on each layer. + + # First, determine all adapters that are merged on at least on module. + merged_all: set[str] = set() + for status in layer_status: + merged_all.update(status.merged_adapters) + + # Next, check if on any layer, on of these adapters is not merged. + merged_adapters: list[str] | Literal["irregular"] = sorted(merged_all) + for status in layer_status: + unmerged = set(status.available_adapters) - set(status.merged_adapters) + if unmerged & merged_all: + # there is overlap between unmerged adapters and adapters that should be merged + merged_adapters = "irregular" + break + + # check status of requires_grad + # first, merge the values for all layers + requires_grad_all: dict[str, list[bool | Literal["irregular"]]] = collections.defaultdict(list) + for status in layer_status: + for key, val in status.requires_grad.items(): + requires_grad_all[key].append(val) + + # then, check if the values are consistent + def check_irrgular(vals: list[bool | Literal["irregular"]]) -> bool | Literal["irregular"]: + if all(val is True for val in vals): + return True + if all(val is False for val in vals): + return False + return "irregular" + + requires_grad = {key: check_irrgular(vals) for key, vals in requires_grad_all.items()} + + devices_dd = collections.defaultdict(list) + for status in layer_status: + for key, val in status.devices.items(): + devices_dd[key].extend(val) + devices = {key: sorted(set(val)) for key, val in devices_dd.items()} + + adapter_model_status = TunerModelStatus( + base_model_type=base_model_type, + adapter_model_type=adapter_model_type, + peft_types=peft_types, + trainable_params=trainable_params, + total_params=total_params, + num_adapter_layers=num_adapter_layers, + enabled=enabled, + active_adapters=active_adapters, + merged_adapters=merged_adapters, + requires_grad=requires_grad, + available_adapters=available_adapters, + devices=devices, + ) + return adapter_model_status + + +def __getattr__(name): + if name == "PEFT_TYPE_TO_MODEL_MAPPING": + # This is for backwards compatibility: In #2282, PEFT_TYPE_TO_MODEL_MAPPING was removed as it was redundant with + # PEFT_TYPE_TO_TUNER_MAPPING. However, third party code could still use this mapping, e.g.: + # https://github.com/AutoGPTQ/AutoGPTQ/blob/6689349625de973b9ee3016c28c11f32acf7f02c/auto_gptq/utils/peft_utils.py#L8 + # TODO: Remove after 2026-01 + msg = ( + "PEFT_TYPE_TO_MODEL_MAPPING is deprecated, please use `from peft import PEFT_TYPE_TO_TUNER_MAPPING` instead. " + "The deprecated variable will be removed in 2026." + ) + warnings.warn(msg, category=DeprecationWarning) + return PEFT_TYPE_TO_TUNER_MAPPING + + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/py.typed b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/py.typed new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e5239da068ec3139756f13218a07e0918a495535 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/__init__.py @@ -0,0 +1,152 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .adalora import AdaLoraConfig, AdaLoraModel +from .adaption_prompt import AdaptionPromptConfig, AdaptionPromptModel +from .boft import BOFTConfig, BOFTModel +from .c3a import C3AConfig, C3AModel +from .cartridge import CartridgeConfig, CartridgeEncoder +from .cpt import CPTConfig, CPTEmbedding +from .delora import DeloraConfig, DeloraModel +from .fourierft import FourierFTConfig, FourierFTModel +from .gralora import GraloraConfig, GraloraModel +from .hra import HRAConfig, HRAModel +from .ia3 import IA3Config, IA3Model +from .lily import LilyConfig, LilyModel +from .ln_tuning import LNTuningConfig, LNTuningModel +from .loha import LoHaConfig, LoHaModel +from .lokr import LoKrConfig, LoKrModel +from .lora import ( + ArrowConfig, + BdLoraConfig, + EvaConfig, + LoftQConfig, + LoraConfig, + LoraGAConfig, + LoraModel, + LoraRuntimeConfig, + convert_to_lora, + create_arrow_model, + get_eva_state_dict, + initialize_lora_eva_weights, + preprocess_loraga, + save_as_lora, +) +from .miss import MissConfig, MissModel +from .mixed import MixedModel +from .multitask_prompt_tuning import MultitaskPromptEmbedding, MultitaskPromptTuningConfig, MultitaskPromptTuningInit +from .oft import OFTConfig, OFTModel +from .osf import OSFConfig, OSFModel +from .p_tuning import PromptEncoder, PromptEncoderConfig, PromptEncoderReparameterizationType +from .poly import PolyConfig, PolyModel +from .prefix_tuning import PrefixEncoder, PrefixTuningConfig +from .prompt_tuning import PromptEmbedding, PromptTuningConfig, PromptTuningInit +from .psoft import PsoftConfig, PsoftModel +from .pvera import PveraConfig, PveraModel +from .randlora import RandLoraConfig, RandLoraModel +from .road import RoadConfig, RoadModel +from .shira import ShiraConfig, ShiraModel +from .trainable_tokens import TrainableTokensConfig, TrainableTokensModel +from .vblora import VBLoRAConfig, VBLoRAModel +from .vera import VeraConfig, VeraModel +from .waveft import WaveFTConfig, WaveFTModel +from .xlora import XLoraConfig, XLoraModel + + +__all__ = [ + "AdaLoraConfig", + "AdaLoraModel", + "AdaptionPromptConfig", + "AdaptionPromptModel", + "ArrowConfig", + "BOFTConfig", + "BOFTModel", + "BdLoraConfig", + "C3AConfig", + "C3AModel", + "CPTConfig", + "CPTEmbedding", + "CartridgeConfig", + "CartridgeEncoder", + "DeloraConfig", + "DeloraModel", + "EvaConfig", + "FourierFTConfig", + "FourierFTModel", + "GraloraConfig", + "GraloraModel", + "HRAConfig", + "HRAModel", + "IA3Config", + "IA3Model", + "LNTuningConfig", + "LNTuningModel", + "LilyConfig", + "LilyModel", + "LoHaConfig", + "LoHaModel", + "LoKrConfig", + "LoKrModel", + "LoftQConfig", + "LoraConfig", + "LoraGAConfig", + "LoraModel", + "LoraRuntimeConfig", + "MissConfig", + "MissModel", + "MixedModel", + "MultitaskPromptEmbedding", + "MultitaskPromptTuningConfig", + "MultitaskPromptTuningInit", + "OFTConfig", + "OFTModel", + "OSFConfig", + "OSFModel", + "PolyConfig", + "PolyModel", + "PrefixEncoder", + "PrefixTuningConfig", + "PromptEmbedding", + "PromptEncoder", + "PromptEncoderConfig", + "PromptEncoderReparameterizationType", + "PromptTuningConfig", + "PromptTuningInit", + "PsoftConfig", + "PsoftModel", + "PveraConfig", + "PveraModel", + "RandLoraConfig", + "RandLoraModel", + "RoadConfig", + "RoadModel", + "ShiraConfig", + "ShiraModel", + "TrainableTokensConfig", + "TrainableTokensModel", + "VBLoRAConfig", + "VBLoRAModel", + "VeraConfig", + "VeraModel", + "WaveFTConfig", + "WaveFTModel", + "XLoraConfig", + "XLoraModel", + "convert_to_lora", + "create_arrow_model", + "get_eva_state_dict", + "initialize_lora_eva_weights", + "preprocess_loraga", + "save_as_lora", +] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/_buffer_dict.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/_buffer_dict.py new file mode 100644 index 0000000000000000000000000000000000000000..16e8fae5ac164ee952780fefc1e247f08ff54909 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/_buffer_dict.py @@ -0,0 +1,159 @@ +# Copyright (c) Meta Platforms, Inc. and affiliates. +# +# This source code is licensed under the MIT license found in the +# LICENSE file in the root directory of this source tree. + +# Adapted from https://botorch.org/api/_modules/botorch/utils/torch.html + +# TODO: To be removed once (if) https://github.com/pytorch/pytorch/pull/37385 lands + +from __future__ import annotations + +import collections +from collections import OrderedDict + +import torch +from torch.nn import Module + + +class BufferDict(Module): + r""" + Holds buffers in a dictionary. + + BufferDict can be indexed like a regular Python dictionary, but buffers it contains are properly registered, and + will be visible by all Module methods. `torch.nn.BufferDict` is an **ordered** dictionary that respects + + * the order of insertion, and + * in `torch.nn.BufferDict.update`, the order of the merged `OrderedDict` or another `torch.nn.BufferDict` (the + argument to `torch.nn.BufferDict.update`). + + Note that `torch.nn.BufferDict.update` with other unordered mapping types (e.g., Python's plain `dict`) does not + preserve the order of the merged mapping. + + Args: + buffers (iterable, optional): + a mapping (dictionary) of (string : `torch.Tensor`) or an iterable of key-value pairs of type (string, + `torch.Tensor`) + + ```python + class MyModule(nn.Module): + def __init__(self): + super().__init__() + self.buffers = nn.BufferDict({"left": torch.randn(5, 10), "right": torch.randn(5, 10)}) + + def forward(self, x, choice): + x = self.buffers[choice].mm(x) + return x + ``` + """ + + def __init__(self, buffers=None, persistent: bool = False): + r""" + Args: + buffers (`dict`): + A mapping (dictionary) from string to `torch.Tensor`, or an iterable of key-value pairs of type + (string, `torch.Tensor`). + """ + super().__init__() + self.persistent = persistent + + if buffers is not None: + self.update(buffers) + + def __getitem__(self, key): + return self._buffers[key] + + def __setitem__(self, key, buffer): + self.register_buffer(key, buffer, persistent=self.persistent) + + def __delitem__(self, key): + del self._buffers[key] + + def __len__(self): + return len(self._buffers) + + def __iter__(self): + return iter(self._buffers.keys()) + + def __contains__(self, key): + return key in self._buffers + + def clear(self): + """Remove all items from the BufferDict.""" + self._buffers.clear() + + def pop(self, key): + r"""Remove key from the BufferDict and return its buffer. + + Args: + key (`str`): + Key to pop from the BufferDict + """ + v = self[key] + del self[key] + return v + + def keys(self): + r"""Return an iterable of the BufferDict keys.""" + return self._buffers.keys() + + def items(self): + r"""Return an iterable of the BufferDict key/value pairs.""" + return self._buffers.items() + + def values(self): + r"""Return an iterable of the BufferDict values.""" + return self._buffers.values() + + def update(self, buffers): + r""" + Update the `torch.nn.BufferDict` with the key-value pairs from a mapping or an iterable, overwriting existing + keys. + + Note: + If `buffers` is an `OrderedDict`, a `torch.nn.BufferDict`, or an iterable of key-value pairs, the order of + new elements in it is preserved. + + Args: + buffers (iterable): + a mapping (dictionary) from string to `torch.Tensor`, or an iterable of key-value pairs of type + (string, `torch.Tensor`). + """ + if not isinstance(buffers, collections.abc.Iterable): + raise TypeError( + "BuffersDict.update should be called with an " + "iterable of key/value pairs, but got " + type(buffers).__name__ + ) + + if isinstance(buffers, (OrderedDict, BufferDict)): + for key, buffer in buffers.items(): + self[key] = buffer + elif isinstance(buffers, collections.abc.Mapping): + for key, buffer in sorted(buffers.items()): + self[key] = buffer + else: + for j, p in enumerate(buffers): + if not isinstance(p, collections.abc.Iterable): + raise TypeError( + "BufferDict update sequence element #" + str(j) + " should be Iterable; is" + type(p).__name__ + ) + if not len(p) == 2: + raise ValueError( + "BufferDict update sequence element " + "#" + str(j) + " has length " + str(len(p)) + "; 2 is required" + ) + self[p[0]] = p[1] + + def extra_repr(self): + child_lines = [] + for k, p in self._buffers.items(): + size_str = "x".join(str(size) for size in p.size()) + device_type = p.device.type + device_str = "" if device_type == "cpu" else f" ({device_type.upper()} {p.get_device()})" + parastr = f"Buffer containing: [{torch.typename(p)} of size {size_str}{device_str}]" + child_lines.append(" (" + k + "): " + parastr) + tmpstr = "\n".join(child_lines) + return tmpstr + + def __call__(self, input): + raise RuntimeError("BufferDict should not be called.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..64d5f3e5ce6ba3c5873f01ee88f4c4766e1fde75 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/__init__.py @@ -0,0 +1,43 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.utils import register_peft_method + +from .config import AdaLoraConfig +from .gptq import SVDQuantLinear +from .layer import AdaLoraLayer, RankAllocator, SVDLinear +from .model import AdaLoraModel + + +__all__ = ["AdaLoraConfig", "AdaLoraLayer", "AdaLoraModel", "RankAllocator", "SVDLinear", "SVDQuantLinear"] + + +register_peft_method( + name="adalora", config_cls=AdaLoraConfig, model_cls=AdaLoraModel, prefix="lora_", is_mixed_compatible=True +) + + +def __getattr__(name): + if (name == "SVDLinear8bitLt") and is_bnb_available(): + from .bnb import SVDLinear8bitLt + + return SVDLinear8bitLt + + if (name == "SVDLinear4bit") and is_bnb_4bit_available(): + from .bnb import SVDLinear4bit + + return SVDLinear4bit + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..52b43f0dff0e62785e216d8736088098f87a9857 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/bnb.py @@ -0,0 +1,142 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available + +from .config import AdaLoraConfig +from .layer import AdaLoraLayer + + +if is_bnb_available(): + + class SVDLinear8bitLt(torch.nn.Module, AdaLoraLayer): + # Low-rank matrix for SVD-based adaptation + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha, config=config) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + result = self.base_layer(x) + + if self.disable_adapters: + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + if x.dtype != torch.float32: + x = x.float() + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + output = dropout(x) @ (lora_A * lora_E).T @ lora_B.T + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling / ranknum + # inplace operation on view is forbidden for MatMul8bitLtBackward, so avoid it + result = result + output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep + + +if is_bnb_4bit_available(): + + class SVDLinear4bit(torch.nn.Module, AdaLoraLayer): + # Low-rank matrix for SVD-based adaptation + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha, config=config) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + result = self.base_layer(x, *args, **kwargs) + + if self.disable_adapters: + return result + + # As per Tim Dettmers, for 4bit, we need to defensively clone here. + # The reason is that in some cases, an error can occur that backprop + # does not work on a manipulated view. This issue may be solved with + # newer PyTorch versions but this would need extensive testing to be + # sure. + result = result.clone() + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.dtype) + + output = dropout(x) @ (lora_A * lora_E).T @ lora_B.T + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling / ranknum + result += output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..004c26b0fe5ecf88212bd11de062baec2f10de83 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/config.py @@ -0,0 +1,108 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Optional + +from peft.tuners.lora import LoraConfig +from peft.utils import PeftType + + +@dataclass +class AdaLoraConfig(LoraConfig): + """ + This is the configuration class to store the configuration of a [`~peft.AdaLora`]. + + AdaLoRA has three phases defined by `tinit`, `tfinal` and `total_step`. + + The initial phase can be understood as a step for pre-training the adapters so that when reducing their rank, there + is already some information encoded that can be reduced instead of random matrices. This phase is defined by + supplying `tinit`. + + After the initial phase is over (`tinit` steps have passed) and the final phase has not begun, AdaLoRA reduces the + budget of how much rank each layer is allowed to have with each step. This is where the reduction of rank is + happening. This goes on until `total_step - tfinal` steps are reached. + + The last phase, beginning once `total_step - tfinal` steps are reached, does not change the layer ranks anymore but + fine-tunes the reduced-rank layers that resulted from the previous phase. + + A practical example: `tinit` is 10, `tfinal` is 20, `total_step` is 100. We spend 10 steps doing pre-training + without rank reduction because our budget is constant (init phase), then we spend 80 (100-20) steps in the + reduction phase where our budget decreases step-wise and, finally, 20 steps in the final fine-tuning stage without + reduction. + + Args: + target_r (`int`): The target average rank of incremental matrix. + init_r (`int`): The initial rank for each incremental matrix. + tinit (`int`): The steps of initial fine-tuning warmup. + tfinal (`int`): The number of steps of final fine-tuning. + deltaT (`int`): The time internval between two budget allocations. + beta1 (`float`): The hyperparameter of EMA for sensitivity smoothing. + beta2 (`float`): The hyperparameter of EMA for undertainty quantification. + orth_reg_weight (`float`): The coefficient of orthogonal regularization. + total_step (`int`): The total training steps that should be specified before training. + rank_pattern (`list`): The allocated rank for each weight matrix by RankAllocator. + """ + + target_r: int = field(default=8, metadata={"help": "Target Lora matrix dimension."}) + init_r: int = field(default=12, metadata={"help": "Initial Lora matrix dimension."}) + tinit: int = field(default=0, metadata={"help": "The steps of initial warmup."}) + tfinal: int = field(default=0, metadata={"help": "The steps of final warmup."}) + deltaT: int = field(default=1, metadata={"help": "Step interval of rank allocation."}) + beta1: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."}) + beta2: float = field(default=0.85, metadata={"help": "Hyperparameter of EMA."}) + orth_reg_weight: float = field(default=0.5, metadata={"help": "The orthogonal regularization coefficient."}) + total_step: Optional[int] = field(default=None, metadata={"help": "The total training steps."}) + rank_pattern: Optional[dict] = field(default=None, metadata={"help": "The saved rank pattern."}) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.ADALORA + + if self.use_dora: + raise ValueError(f"{self.peft_type} does not support DoRA.") + + if self.loftq_config: + raise ValueError(f"{self.peft_type} does not support LOFTQ.") + + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + + # Check if 'r' has been set to a non-default value + if self.r != 8: # 8 is the default value for 'r' in LoraConfig + warnings.warn( + "Note that `r` is not used in AdaLora and will be ignored." + "If you intended to set the initial rank, use `init_r` instead." + ) + + if self.total_step is None or self.total_step <= 0: + raise ValueError("AdaLoRA does not work when `total_step` is None, supply a value > 0.") + + if self.tinit >= (self.total_step - self.tfinal): + raise ValueError( + "The supplied schedule values don't allow for a budgeting phase. Decrease `tfinal`/`tinit` or " + "increase `total_step`." + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/gptq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..c1708c7bfc7114f49a9a29d2df196e2cea840541 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/gptq.py @@ -0,0 +1,71 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch + +from .config import AdaLoraConfig +from .layer import AdaLoraLayer + + +class SVDQuantLinear(torch.nn.Module, AdaLoraLayer): + def __init__( + self, + base_layer, + adapter_name, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha=lora_alpha, config=config) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + result = self.quant_linear_module(x) + + if self.disable_adapters: + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, torch.float32) + + output = (dropout(x) @ (lora_A * lora_E).T @ lora_B.T) * scaling / ranknum + # TODO: here, the dtype conversion is applied on the *whole expression*, + # not the intermediate result, unlike for SVDLinear8bitLT and + # SVDLinear4bit, is that correct? + if requires_conversion: + output = output.to(expected_dtype) + result += output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..0a0035682cb0fa11079d9af6ad8c152737570c2a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/layer.py @@ -0,0 +1,361 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Any, Optional + +import packaging +import torch +import transformers +from torch import nn + +from peft.tuners.lora import LoraLayer +from peft.tuners.tuners_utils import check_adapters_to_merge +from peft.utils import transpose + +from .config import AdaLoraConfig + + +if packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.33.0"): + from transformers.integrations import deepspeed_config +else: + from transformers.deepspeed import deepspeed_config + + +class AdaLoraLayer(LoraLayer): + # List all names of layers that may contain adapter weights + # Note: ranknum doesn't need to be included as it is not an nn.Module + adapter_layer_names = ("lora_A", "lora_B", "lora_E", "lora_embedding_A", "lora_embedding_B") + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("r", "lora_alpha", "scaling", "lora_dropout", "ranknum") + + def __init__(self, base_layer: nn.Module) -> None: + super().__init__(base_layer) + self.lora_E = nn.ParameterDict({}) + self.lora_A = nn.ParameterDict({}) + self.lora_B = nn.ParameterDict({}) + self.ranknum = nn.ParameterDict({}) + + def update_layer(self, adapter_name: str, r: int, lora_alpha: int, config: AdaLoraConfig, **kwargs) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + inference_mode = config.inference_mode + if r < 0: + # note: r == 0 is allowed for AdaLora, see #1539 + raise ValueError(f"`r` should be a positive integer or 0, but the value passed is {r}") + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + # Actual trainable parameters + # Right singular vectors + self.lora_A[adapter_name] = nn.Parameter(torch.randn(r, self.in_features)) + # Singular values + self.lora_E[adapter_name] = nn.Parameter(torch.randn(r, 1)) + # Left singular vectors + self.lora_B[adapter_name] = nn.Parameter(torch.randn(self.out_features, r)) + # The current rank + self.ranknum[adapter_name] = nn.Parameter(torch.randn(1), requires_grad=False) + self.ranknum[adapter_name].data.fill_(float(r)) + self.ranknum[adapter_name].requires_grad = False + self.scaling[adapter_name] = lora_alpha if lora_alpha > 0 else float(r) + if init_lora_weights: + self.reset_lora_parameters(adapter_name) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_lora_parameters(self, adapter_name): + if adapter_name in self.lora_A.keys(): + nn.init.zeros_(self.lora_E[adapter_name]) + nn.init.normal_(self.lora_A[adapter_name], mean=0.0, std=0.02) + nn.init.normal_(self.lora_B[adapter_name], mean=0.0, std=0.02) + + +class SVDLinear(nn.Module, AdaLoraLayer): + # SVD-based adaptation by a dense layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: AdaLoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + AdaLoraLayer.__init__(self, base_layer) + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha, config=config) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + base_layer = self.get_base_layer() + if active_adapter in self.lora_A.keys(): + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += self.get_delta_weight(active_adapter) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def get_delta_weight(self, adapter) -> torch.Tensor: + return ( + transpose(self.lora_B[adapter] @ (self.lora_A[adapter] * self.lora_E[adapter]), self.fan_in_fan_out) + * self.scaling[adapter] + / (self.ranknum[adapter] + 1e-5) + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + lora_E = self.lora_E[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + ranknum = self.ranknum[active_adapter] + 1e-5 + + x = self._cast_input_dtype(x, lora_A.dtype) + result += (dropout(x) @ (lora_A * lora_E).T @ lora_B.T) * scaling / ranknum + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "adalora." + rep + + +class RankAllocator: + """ + The RankAllocator for AdaLoraModel. Paper: https://openreview.net/pdf?id=lq62uWRJjiY + + Args: + config ([`AdaLoraConfig`]): The configuration of the AdaLora model. + model: the model that we apply AdaLoRA to. + + """ + + def __init__(self, model, peft_config, adapter_name): + self.peft_config = peft_config + self.adapter_name = adapter_name + self.beta1 = peft_config.beta1 + self.beta2 = peft_config.beta2 + assert self.beta1 > 0 and self.beta1 < 1 + assert self.beta2 > 0 and self.beta2 < 1 + + self.reset_ipt() + self._set_budget_scheduler(model) + + def set_total_step(self, total_step): + self.peft_config.total_step = total_step + + def reset_ipt(self): + self.ipt = {} + self.exp_avg_ipt = {} + self.exp_avg_unc = {} + + def _set_budget_scheduler(self, model): + self.init_bgt = 0 + self.name_set = set() + for n, p in model.named_parameters(): + if f"lora_A.{self.adapter_name}" in n: + self.init_bgt += p.size(0) + self.name_set.add(n.replace("lora_A", "%s")) + self.name_set = sorted(self.name_set) + # The total final rank budget + self.target_bgt = self.peft_config.target_r * len(self.name_set) + + def budget_schedule(self, step: int): + tinit = self.peft_config.tinit + tfinal = self.peft_config.tfinal + total_step = self.peft_config.total_step + # Initial warmup + if step <= tinit: + budget = self.init_bgt + mask_ind = False + # Final fine-tuning + elif step > total_step - tfinal: + budget = self.target_bgt + mask_ind = True + else: + # Budget decreasing with a cubic scheduler + mul_coeff = 1 - (step - tinit) / (total_step - tfinal - tinit) + budget = int((self.init_bgt - self.target_bgt) * (mul_coeff**3) + self.target_bgt) + mask_ind = True if step % self.peft_config.deltaT == 0 else False + return budget, mask_ind + + def update_ipt(self, model): + # Update the sensitivity and uncertainty for every weight + for n, p in model.named_parameters(): + if "lora_" in n and self.adapter_name in n: + if n not in self.ipt: + self.ipt[n] = torch.zeros_like(p) + self.exp_avg_ipt[n] = torch.zeros_like(p) + self.exp_avg_unc[n] = torch.zeros_like(p) + with torch.no_grad(): + if deepspeed_config() is not None: + import deepspeed + + grad = deepspeed.utils.safe_get_full_grad(p) + self.ipt[n] = (p * grad).abs().detach() + else: + self.ipt[n] = (p * p.grad).abs().detach() + # Sensitivity smoothing + self.exp_avg_ipt[n] = self.beta1 * self.exp_avg_ipt[n] + (1 - self.beta1) * self.ipt[n] + # Uncertainty quantification + self.exp_avg_unc[n] = ( + self.beta2 * self.exp_avg_unc[n] + (1 - self.beta2) * (self.ipt[n] - self.exp_avg_ipt[n]).abs() + ) + + def _element_score(self, n): + return self.exp_avg_ipt[n] * self.exp_avg_unc[n] + + def _combine_ipt(self, ipt_E, ipt_AB): + ipt_AB = ipt_AB.sum(dim=1, keepdim=False) + sum_ipt = ipt_E.view(-1) + ipt_AB.view(-1) + return sum_ipt + + def mask_to_budget(self, model, budget): + value_ipt = {} + vector_ipt = {} + triplet_ipt = {} + # Get the importance score for A, E, B + for n, p in model.named_parameters(): + if f"lora_A.{self.adapter_name}" in n: + entry_ipt = self._element_score(n) + comb_ipt = torch.mean(entry_ipt, dim=1, keepdim=True) + name_m = n.replace("lora_A", "%s") + if name_m not in vector_ipt: + vector_ipt[name_m] = [comb_ipt] + else: + vector_ipt[name_m].append(comb_ipt) + if f"lora_B.{self.adapter_name}" in n: + entry_ipt = self._element_score(n) + comb_ipt = torch.mean(entry_ipt, dim=0, keepdim=False).view(-1, 1) + name_m = n.replace("lora_B", "%s") + if name_m not in vector_ipt: + vector_ipt[name_m] = [comb_ipt] + else: + vector_ipt[name_m].append(comb_ipt) + if f"lora_E.{self.adapter_name}" in n: + entry_ipt = self._element_score(n) + name_m = n.replace("lora_E", "%s") + value_ipt[name_m] = entry_ipt + + all_score = [] + # Calculate the score for each triplet + for name_m in vector_ipt: + ipt_E = value_ipt[name_m] + ipt_AB = torch.cat(vector_ipt[name_m], dim=1) + sum_ipt = self._combine_ipt(ipt_E, ipt_AB) + name_E = name_m % "lora_E" + triplet_ipt[name_E] = sum_ipt.view(-1, 1) + all_score.append(sum_ipt.view(-1)) + + # Get the threshold by ranking ipt + mask_threshold = torch.kthvalue( + torch.cat(all_score), + k=self.init_bgt - budget, + )[0].item() + + rank_pattern = {} + # Mask the unimportant triplets + with torch.no_grad(): + for n, p in model.named_parameters(): + if f"lora_E.{self.adapter_name}" in n: + p.masked_fill_(triplet_ipt[n] <= mask_threshold, 0.0) + rank_pattern[n] = (~(triplet_ipt[n] <= mask_threshold)).view(-1).tolist() + return rank_pattern + + def update_and_allocate(self, model, global_step, force_mask=False): + # # Update the importance score and allocate the budget + if global_step < self.peft_config.total_step - self.peft_config.tfinal: + self.update_ipt(model) + budget, mask_ind = self.budget_schedule(global_step) + # Allocate the budget according to importance scores + if mask_ind or force_mask: + rank_pattern = self.mask_to_budget(model, budget) + else: + rank_pattern = None + return budget, rank_pattern + + def mask_using_rank_pattern(self, model, rank_pattern): + # Mask the unimportant triplets + is_adapter_name_truncated = False + if self.adapter_name not in next(iter(rank_pattern.keys())): + is_adapter_name_truncated = True + + with torch.no_grad(): + for n, p in model.named_parameters(): + if f"lora_E.{self.adapter_name}" in n: + key = n if not is_adapter_name_truncated else n.replace(f".{self.adapter_name}", "") + mask = torch.Tensor(rank_pattern[key]).unsqueeze(-1).to(p.device) + p.masked_fill_(~mask.bool(), 0.0) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..4b170461b427df0b2507002681521eed370782a9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adalora/model.py @@ -0,0 +1,338 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings + +import torch +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.lora import LoraConfig, LoraModel +from peft.tuners.tuners_utils import BaseTunerLayer, get_device_map +from peft.utils import ( + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + _freeze_adapter, + _get_submodules, + get_gptqmodel_quant_linear, + get_quantization_config, +) +from peft.utils.integrations import gather_params_ctx + +from .gptq import SVDQuantLinear +from .layer import AdaLoraLayer, RankAllocator, SVDLinear + + +class AdaLoraModel(LoraModel): + """ + Creates AdaLoRA (Adaptive LoRA) model from a pretrained transformers model. Paper: + https://openreview.net/forum?id=lq62uWRJjiY + + Args: + model ([`transformers.PreTrainedModel`]): The model to be adapted. + config ([`AdaLoraConfig`]): The configuration of the AdaLora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The AdaLora model. + + Example:: + + >>> from transformers import AutoModelForSeq2SeqLM >>> from peft import LoraConfig, AdaLoraModel, AdaLoraConfig + >>> config = AdaLoraConfig( + peft_type="ADALORA", task_type="SEQ_2_SEQ_LM", init_r=12, lora_alpha=32, target_modules=["q", "v"], + lora_dropout=0.01, + ) + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") >>> model = AdaLoraModel(model, config, "default") + + **Attributes**: + - **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`AdaLoraConfig`]): The configuration of the AdaLora model. + """ + + # Note: don't redefine prefix or tuner_layer_cls here, it should be inherited from LoraModel + target_module_mapping = TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING + + def __init__(self, model, config, adapter_name, **kwargs): + super().__init__(model, config, adapter_name, **kwargs) + + traininable_mode_counter = 0 + for config in self.peft_config.values(): + if not config.inference_mode: + traininable_mode_counter += 1 + + if traininable_mode_counter > 1: + raise ValueError( + "AdaLoraModel supports only 1 trainable adapter. " + "When using multiple adapters, set inference_mode to True for all adapters except the one you want to train." + ) + + if self.peft_config[adapter_name].inference_mode: + _freeze_adapter(self.model, adapter_name) + else: + self.trainable_adapter_name = adapter_name + self.rankallocator = RankAllocator(self.model, self.peft_config[adapter_name], self.trainable_adapter_name) + + def _check_new_adapter_config(self, config: LoraConfig) -> None: + """ + A helper method to check the config when a new adapter is being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + super()._check_new_adapter_config(config) + + traininable_mode_counter = 0 + for config_ in self.peft_config.values(): + if not config_.inference_mode: + traininable_mode_counter += 1 + + if traininable_mode_counter > 1: + raise ValueError( + f"{self.__class__.__name__} supports only 1 trainable adapter. " + "When using multiple adapters, set inference_mode to True for all adapters except the one " + "you want to train." + ) + + def _create_and_replace( + self, + lora_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + kwargs = { + "r": lora_config.init_r, + "lora_alpha": lora_config.lora_alpha, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + if (kwargs["loaded_in_8bit"] or kwargs["loaded_in_4bit"]) and not is_bnb_available(): + raise ImportError( + "To use AdaLora with 8-bit quantization, please install the `bitsandbytes` package. " + "You can install it with `pip install bitsandbytes`." + ) + + quantization_config = get_quantization_config(self.model, method="gptq") + if quantization_config is not None: + kwargs["gptq_quantization_config"] = quantization_config + + # If it is not an AdaLoraLayer, create a new module, else update it with new adapters + if not isinstance(target, AdaLoraLayer): + device_map = get_device_map(self.model) + new_module = self._create_new_module(lora_config, adapter_name, target, device_map=device_map, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + else: + target.update_layer( + adapter_name, + lora_config.init_r, + lora_config.lora_alpha, + config=lora_config, + ) + + @staticmethod + def _create_new_module(lora_config, adapter_name, target, device_map=None, **kwargs): + # avoid eager bnb import + if is_bnb_available(): + import bitsandbytes as bnb + + from .bnb import SVDLinear8bitLt + if is_bnb_4bit_available(): + from .bnb import SVDLinear4bit + + gptq_quantization_config = kwargs.get("gptq_quantization_config", None) + + QuantLinear = get_gptqmodel_quant_linear(gptq_quantization_config, device_map=device_map) + + loaded_in_8bit = kwargs.pop("loaded_in_8bit", False) + loaded_in_4bit = kwargs.pop("loaded_in_4bit", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + kwargs.update( + { + "has_fp16_weights": target_base_layer.state.has_fp16_weights, + "threshold": target_base_layer.state.threshold, + "index": target_base_layer.index, + } + ) + new_module = SVDLinear8bitLt(target, adapter_name, config=lora_config, **kwargs) + elif loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + new_module = SVDLinear4bit(target, adapter_name, config=lora_config, **fourbit_kwargs) + elif QuantLinear is not None and isinstance(target, QuantLinear): + new_module = SVDQuantLinear(target, adapter_name, config=lora_config, **kwargs) + else: + if isinstance(target_base_layer, torch.nn.Linear): + if lora_config.fan_in_fan_out: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + lora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + if not lora_config.fan_in_fan_out: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. " + "Setting fan_in_fan_out to True." + ) + lora_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. " + f"Currently, only `torch.nn.Linear` and `Conv1D` are supported." + ) + new_module = SVDLinear(target, adapter_name, config=lora_config, **kwargs) + + return new_module + + def forward(self, *args, **kwargs): + outputs = self.model.forward(*args, **kwargs) + + if (getattr(outputs, "loss", None) is not None) and isinstance(outputs.loss, torch.Tensor): + # Calculate the orthogonal regularization + orth_reg_weight = self.peft_config[self.trainable_adapter_name].orth_reg_weight + + if orth_reg_weight <= 0: + raise ValueError("orth_reg_weight should be greater than 0. ") + + regu_loss = 0 + num_param = 0 + for n, p in self.model.named_parameters(): + if ("lora_A" in n or "lora_B" in n) and self.trainable_adapter_name in n: + if p.shape == torch.Size([0]): + with gather_params_ctx(p, fwd_module=self): + para_cov = p @ p.T if "lora_A" in n else p.T @ p + else: + para_cov = p @ p.T if "lora_A" in n else p.T @ p + I = torch.eye(*para_cov.size(), out=torch.empty_like(para_cov)) # noqa: E741 + I.requires_grad = False + num_param += 1 + regu_loss += torch.norm(para_cov - I, p="fro") + if num_param > 0: + regu_loss = regu_loss / num_param + else: + regu_loss = 0 + outputs.loss += orth_reg_weight * regu_loss + return outputs + + def resize_modules_by_rank_pattern(self, rank_pattern, adapter_name): + lora_config = self.peft_config[adapter_name] + for name, rank_idx in rank_pattern.items(): + if isinstance(rank_idx, list): + rank = sum(rank_idx) + elif isinstance(rank_idx, torch.Tensor): + rank_idx = rank_idx.view(-1) + rank = rank_idx.sum().item() + else: + raise ValueError("Unexpected type of rank_idx") + key = ".".join(name.split(".")[0:-2]) if adapter_name in name else ".".join(name.split(".")[0:-1]) + _, target, _ = _get_submodules(self.model, key) + lora_E_weights = target.lora_E[adapter_name][rank_idx] + lora_A_weights = target.lora_A[adapter_name][rank_idx] + lora_B_weights = target.lora_B[adapter_name][:, rank_idx] + ranknum = target.ranknum[adapter_name] + target.update_layer( + adapter_name, + rank, + lora_config.lora_alpha, + lora_config.lora_dropout, + lora_config.init_lora_weights, + ) + with torch.no_grad(): + if rank > 0: + target.lora_E[adapter_name].copy_(lora_E_weights) + target.lora_A[adapter_name].copy_(lora_A_weights) + target.lora_B[adapter_name].copy_(lora_B_weights) + # The scaling is exactly as the previous + target.ranknum[adapter_name].copy_(ranknum) + + def resize_state_dict_by_rank_pattern(self, rank_pattern, state_dict, adapter_name): + for name, rank_idx in rank_pattern.items(): + rank = sum(rank_idx) + prefix = ".".join(name.split(".")[0:-2]) if adapter_name in name else ".".join(name.split(".")[0:-1]) + for layer in ["lora_E", "lora_A", "lora_B"]: + key = f"base_model.model.{prefix}.{layer}.{adapter_name}" + if layer != "lora_B": + state_dict[key] = ( + state_dict[key][rank_idx] if rank != state_dict[key].shape[0] else state_dict[key] + ) + else: + state_dict[key] = ( + state_dict[key][:, rank_idx] if rank != state_dict[key].shape[1] else state_dict[key] + ) + return state_dict + + def update_and_allocate(self, global_step): + """ + This method updates Adalora budget and mask. + + This should be called in every training step after `loss.backward()` and before `zero_grad()`. + + `tinit`, `tfinal` and `deltaT` are handled with in the method. + + Args: + global_step (`int`): The current training step, it is used to calculate adalora budget. + + Example: + + ```python + >>> loss = model(**input).loss + >>> loss.backward() + >>> optimizer.step() + >>> model.base_model.update_and_allocate(i_step) + >>> optimizer.zero_grad() + ``` + """ + lora_config = self.peft_config[self.trainable_adapter_name] + # Update the importance score and allocate the budget + if global_step < lora_config.total_step - lora_config.tfinal: + _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step) + if rank_pattern: + lora_config.rank_pattern = rank_pattern + # Finalize the budget allocation + elif global_step == lora_config.total_step - lora_config.tfinal: + _, rank_pattern = self.rankallocator.update_and_allocate(self.model, global_step, force_mask=True) + # for some reason, this freezes the trainable parameters and nothing gets updates + # self.resize_modules_by_rank_pattern(rank_pattern, self.trainable_adapter_name) + lora_config.rank_pattern = rank_pattern + self.rankallocator.reset_ipt() + # Currently using inefficient way to mask the unimportant weights using the rank pattern + # due to problem mentioned above + elif global_step > lora_config.total_step - lora_config.tfinal: + self.rankallocator.mask_using_rank_pattern(self.model, lora_config.rank_pattern) + # Pass the function and do forward propagation + else: + return None + + def add_weighted_adapter(self, *args, **kwargs): + """This method is not supported for AdaLoRA, use LoRA instead.""" + raise TypeError(f"{self.__class__.__name__} does not support add_weighted_adapter method.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..68882a222625eedc770d28816a3a0646964739bb --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from peft.utils import register_peft_method + +from .config import AdaptionPromptConfig +from .layer import AdaptedAttention +from .model import AdaptionPromptModel + + +__all__ = ["AdaptedAttention", "AdaptionPromptConfig", "AdaptionPromptModel"] + +register_peft_method(name="adaption_prompt", config_cls=AdaptionPromptConfig, model_cls=AdaptionPromptModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/config.py new file mode 100644 index 0000000000000000000000000000000000000000..4a9f780383d425fb551e2635017de9eaac3c2b81 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/config.py @@ -0,0 +1,88 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from collections import namedtuple +from dataclasses import dataclass, field + +from peft.config import PeftConfig +from peft.utils import PeftType + +from .utils import gpt2_compute_query_states, llama_compute_query_states + + +@dataclass +class AdaptionPromptConfig(PeftConfig): + """Stores the configuration of an [`AdaptionPromptModel`].""" + + target_modules: str = field( + default=None, metadata={"help": "Name of the attention submodules to insert adaption prompts into."} + ) + adapter_len: int = field(default=None, metadata={"help": "Number of adapter tokens to insert"}) + adapter_layers: int = field(default=None, metadata={"help": "Number of adapter layers (from the top)"}) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.ADAPTION_PROMPT + + @property + def is_adaption_prompt(self) -> bool: + """Return True if this is an adaption prompt config.""" + return True + + +# Contains the config that is specific to a transformers model type. +ModelTypeConfig = namedtuple( + "ModelTypeConfig", ["compute_query_states", "target_modules", "k_proj_layer", "v_proj_layer", "o_proj_layer"] +) + +# Mapping of transformers model types to their specific configuration. +TRANSFORMERS_MODEL_CONFIG = { + "llama": ModelTypeConfig( + compute_query_states=llama_compute_query_states, + target_modules="self_attn", + k_proj_layer="k_proj", + v_proj_layer="v_proj", + o_proj_layer="o_proj", + ), + "mistral": ModelTypeConfig( # same as llama, + compute_query_states=llama_compute_query_states, + target_modules="self_attn", + k_proj_layer="k_proj", + v_proj_layer="v_proj", + o_proj_layer="o_proj", + ), + "gpt2": ModelTypeConfig( # piggybacking of off the prior definitions, GPTs attention calculation is different + compute_query_states=gpt2_compute_query_states, + target_modules="attn", + k_proj_layer="c_attn", + v_proj_layer=None, + o_proj_layer=None, + ), +} + + +def prepare_config( + peft_config: AdaptionPromptConfig, + model, +) -> AdaptionPromptConfig: + """Prepare the config based on the llama model type.""" + if model.config.model_type not in TRANSFORMERS_MODEL_CONFIG: + raise ValueError(f"Unsupported model type for adaption prompt: '{model.config.model_type}'.") + + model_config = TRANSFORMERS_MODEL_CONFIG[model.config.model_type] + + if peft_config.target_modules is None: + peft_config.target_modules = model_config.target_modules + + return peft_config diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..4dd877841f176b1688d5c0fc224c79f3b089ceff --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/layer.py @@ -0,0 +1,236 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from .config import TRANSFORMERS_MODEL_CONFIG + + +class _BaseAdaptedAttention(nn.Module): + """Base module, which defines adaption prompts for multiple model types.""" + + def __init__(self, model_type: str, adapter_len: int, model, target_dtype=torch.float32): + """ + Initialize object. + + Args: + model_type: The transformer model type. This is used to retrieve the right method to + compute query states. + adapter_len: The length of the adaption prompt to insert. + model: The original transformer attention module that is being wrapped. + """ + if isinstance(model, _BaseAdaptedAttention): + raise ValueError("Unable to stack multiple adaption prompts") + super().__init__() + self.model_type = model_type + self.model = model + self.adapter_len = adapter_len + # Assume all parameters of the attention model we are wrapping are on the same device. + + device = next(model.parameters()).device + # Don't think this was specified in the paper, but we follow the official repo which used an Embedding + # which initializes the tokens with standard normal values. + # https://github.com/ZrrSkywalker/LLaMA-Adapter/blob/41c3546fe1997ab8a65809dc8d8f9252b19d9faf/llama/model.py#L234 + # (bsz, adapter_len, hidden_size) + + if hasattr(self.model, "hidden_size"): + # TODO: remove this clause after 2026-01-01 + hidden_size = self.model.hidden_size + else: # changed in https://github.com/huggingface/transformers/pull/35235 + hidden_size = self.model.config.hidden_size + + if hasattr(self.model, "num_heads"): + # TODO: remove this clause after 2026-01-01 + self.num_heads = self.model.num_heads + else: # changed in https://github.com/huggingface/transformers/pull/35235 + self.num_heads = self.model.config.num_attention_heads + + self.adaption_prompt = nn.Parameter( + torch.empty(1, adapter_len, hidden_size, device=device, dtype=target_dtype).normal_() + ) + # Initialize the gate to 0 as this is "zero-init". + self.adaption_gate = nn.Parameter(torch.zeros(1, device=device, dtype=target_dtype)) + + +class AdaptedAttentionGPT(_BaseAdaptedAttention): + """This module wraps a GPT2Attention module and injects adaption prompts""" + + def __init__(self, model_type, adapter_len, model): + target_dtype = ( + model.c_proj.weight.dtype if model.c_proj.weight.dtype not in [torch.int8, torch.uint8] else torch.float32 + ) + super().__init__(model_type, adapter_len, model, target_dtype=target_dtype) + + def forward( + self, + hidden_states: Optional[tuple[torch.FloatTensor]], + layer_past: Optional[tuple[torch.Tensor]] = None, + attention_mask: Optional[torch.FloatTensor] = None, + head_mask: Optional[torch.FloatTensor] = None, + encoder_hidden_states: Optional[torch.Tensor] = None, + encoder_attention_mask: Optional[torch.FloatTensor] = None, + use_cache: Optional[bool] = False, + output_attentions: Optional[bool] = False, + **kwargs, + ) -> tuple[Union[torch.Tensor, tuple[torch.Tensor]], ...]: + attn_outputs = self.model( + hidden_states=hidden_states, + attention_mask=attention_mask, + head_mask=head_mask, + encoder_hidden_states=encoder_hidden_states, + encoder_attention_mask=encoder_attention_mask, + use_cache=use_cache, + output_attentions=output_attentions, + **kwargs, + ) + """ + Forward pass for the adapter which wraps the GPT2Attention module + """ + + attn_output = attn_outputs[0] + add_outputs = attn_outputs[1:] + + c_attn_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].k_proj_layer + + bsz = attn_output.shape[0] + q_len = attn_output.shape[1] + embed_dim = attn_output.shape[2] + + _, key, value = getattr(self.model, c_attn_layer)(self.adaption_prompt).split(embed_dim, dim=2) + + adapter_k = ( + key.view(1, self.adapter_len, self.num_heads, self.model.head_dim).repeat(bsz, 1, 1, 1).transpose(1, 2) + ) + adapter_v = ( + value.view(1, self.adapter_len, self.num_heads, self.model.head_dim).repeat(bsz, 1, 1, 1).transpose(1, 2) + ) + # recompute query state since it is not returned by GPT2 forward + compute_query_states = TRANSFORMERS_MODEL_CONFIG[self.model_type].compute_query_states + query_states = compute_query_states( + self.model, hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states + ) + + previous_dtype = query_states.dtype + + scores = torch.matmul(query_states, adapter_k.transpose(2, 3).to(previous_dtype)) / math.sqrt( + self.model.head_dim + ) + # Upcast attention to fp32 + # (bsz, num_heads, q_len, adapter_len) + scores = self.adaption_gate * F.softmax(scores, dim=-1, dtype=torch.float32).to(previous_dtype) + # (bsz, q_len, num_heads * head_dim) + adapter_output = torch.matmul(scores, adapter_v).transpose(1, 2).reshape(bsz, q_len, -1) + + # Add adaption prompt output to original output. + hidden_state = attn_output + adapter_output + + # Restore original dtype. + hidden_state = hidden_state.to(previous_dtype) + + # add additional attention outputs (attention and cross attention) + output = (hidden_state,) + add_outputs + return output + + +class AdaptedAttention(_BaseAdaptedAttention): + """This module wraps a LLamaAttention module and injects adaption prompts.""" + + def __init__(self, model_type, adapter_len, model): + target_dtype = ( + model.q_proj.weight.dtype if model.q_proj.weight.dtype not in [torch.int8, torch.uint8] else torch.float32 + ) + super().__init__(model_type, adapter_len, model, target_dtype=target_dtype) + + def forward(self, **kwargs): + """ + Forward pass for the adapter which wraps the original LlamaAttention module. + + "Official" paper implementation: + https://github.com/ZrrSkywalker/LLaMA-Adapter/blob/41c3546fe1997ab8a65809dc8d8f9252b19d9faf/llama/model.py#L141 + + Args: + kwargs: See the original LlamaAttention module. + """ + if kwargs.get("output_attention", False): + raise NotImplementedError("output_attention is not currently supported.") + + output, *_ = self.model(**kwargs) + bsz = output.shape[0] + q_len = output.shape[1] + embed_dim = output.shape[2] + k_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].k_proj_layer + v_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].v_proj_layer + o_proj_layer = TRANSFORMERS_MODEL_CONFIG[self.model_type].o_proj_layer + factor = ( + self.model.k_proj.in_features // self.model.k_proj.out_features + ) # Mistral has different input and output dimension for k_proj and v_proj layers + + if k_proj_layer == v_proj_layer: + _, key, value = getattr(self.model, k_proj_layer)(self.adaption_prompt).split(embed_dim, dim=2) + else: + key = getattr(self.model, k_proj_layer)(self.adaption_prompt) + value = getattr(self.model, v_proj_layer)(self.adaption_prompt) + + if hasattr(self.model, "num_heads"): + # TODO: remove this clause after 2026-01-01 + num_heads = self.model.num_heads + else: # changed in https://github.com/huggingface/transformers/pull/35235 + num_heads = self.model.config.num_attention_heads + # (bsz, num_key_value_heads, adapter_len, head_dim) + adapter_k = ( + key.view(1, self.adapter_len, (num_heads // factor), self.model.head_dim) + .repeat(bsz, 1, 1, 1) + .transpose(1, 2) + ) + adapter_v = ( + value.view(1, self.adapter_len, (num_heads // factor), self.model.head_dim) + .repeat(bsz, 1, 1, 1) + .transpose(1, 2) + ) + # Below is taken from https://github.com/huggingface/transformers/blob/e547458c43dfdbbb8f6a7757237e234c44e20a8f/src/transformers/models/mistral/modeling_mistral.py#L181 + # (bsz, num_heads, adapter_len, head_dim) + adapter_k = torch.repeat_interleave(adapter_k, repeats=factor, dim=1) + adapter_v = torch.repeat_interleave(adapter_v, repeats=factor, dim=1) + # Recompute query states. + compute_query_states = TRANSFORMERS_MODEL_CONFIG[self.model_type].compute_query_states + # (bsz, num_heads, q_len, head_dim) + query_states = compute_query_states(model=self.model, **kwargs) + + previous_dtype = query_states.dtype + + # (bsz, num_heads, q_len, adapter_len) + scores = torch.matmul(query_states, adapter_k.transpose(2, 3).to(previous_dtype)) / math.sqrt( + self.model.head_dim + ) + # Upcast attention to fp32 + # (bsz, num_heads, q_len, adapter_len) + scores = self.adaption_gate * F.softmax(scores, dim=-1, dtype=torch.float32).to(previous_dtype) + # (bsz, q_len, num_heads * head_dim) + adapter_output = torch.matmul(scores, adapter_v).transpose(1, 2).reshape(bsz, q_len, -1) + + # (bsz, q_len, hidden_size) + if o_proj_layer is not None: + adapter_output = getattr(self.model, o_proj_layer)(adapter_output) + + # Add adaption prompt output to original output. + output = output + adapter_output + + # Restore original dtype. + output = output.to(previous_dtype) + return output, *_ diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/model.py new file mode 100644 index 0000000000000000000000000000000000000000..15bfa92fe897a887259c77b5ec1578c0dd47b082 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/model.py @@ -0,0 +1,171 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch.nn as nn + +from peft.utils import _freeze_adapter, _get_submodules + +from .config import AdaptionPromptConfig, prepare_config +from .layer import AdaptedAttention, AdaptedAttentionGPT +from .utils import is_adaption_prompt_trainable + + +class AdaptionPromptModel(nn.Module): + """ + Implements adaption prompts as described in https://huggingface.co/papers/2303.16199. + + The top L attention modules are replaced with AdaptedAttention modules that wrap the original ones, but insert + trainable prompts with gates (for zero init). + + Notes on the multi-adapter pattern: + - We store the states of different adapters by keeping a dictionary of AdaptedAttention modules indexed by adapter + name. + - Every time we switch adapters, we remove the modules of the currently active adapter from the model, store them + in the dictionary, and replace them with the modules of the new adapter. + - To avoid duplicated and potentially inconsistent state, the currently active adapter is always removed from the + dictionary. + - Disabling the adapter would also result in the modules being removed from the model. + """ + + def __init__(self, model, configs: dict, adapter_name: str): + super().__init__() + self.model = model + # Store adapter configs by name. + self.peft_config: dict[str, AdaptionPromptConfig] = {} + # Store lists of the parents of the affected attention modules by adapter name. + # We keep references to the parents so we can swap the adapters in-and-out of the model. + self._parents: dict[str, list[nn.Module]] = {} + # Store lists of cached AdaptedAttention modules by name. + self._cached_adapters: dict[str, list] = {} + # The name of the currently active adapter. + self._active_adapter = None + # Whether the adapter is enabled. + self._enabled = True + self.forward = self.model.forward + self.add_adapter(adapter_name, configs[adapter_name]) + self._mark_only_adaption_prompts_as_trainable(self.model) + + def add_adapter(self, adapter_name: str, config: AdaptionPromptConfig) -> None: + """Add an adapter with the given name and config.""" + config = prepare_config(config, self.model) + if adapter_name in self.peft_config: + raise ValueError(f"Adapter with name '{adapter_name}' already exists.") + + parents = [] + for name, _ in self.model.named_modules(): + if name.endswith(f".{config.target_modules}"): + par, _, _ = _get_submodules(self.model, name) + parents.append(par) + if len(parents) < config.adapter_layers: + raise ValueError( + f"Config specifies more adapter layers '{config.adapter_layers}' than the model has '{len(parents)}'." + ) + # Note that if the target modules are not in Sequential, ModuleList, or + # some other PyTorch ordered container, the behavior is undefined as we + # assume here that the order of the modules is the same as the order of + # the transformer decoder layers. + parents = parents[-config.adapter_layers :] + self._parents[adapter_name] = parents + + # It is only None during initialization. + # If it is disabled, we don't have to remove the modules. + if self._active_adapter is not None and self._enabled: + self._remove_adapted_attentions(self._active_adapter) + self._active_adapter = adapter_name + self.peft_config[adapter_name] = config + self._create_adapted_attentions(config, parents) + if not self._enabled: + self._remove_adapted_attentions(self._active_adapter) + + if config.inference_mode: + _freeze_adapter(self.model, adapter_name) + + def set_adapter(self, adapter_name: str, inference_mode: bool = False) -> None: + """Set the model to use the adapter with the given name.""" + if inference_mode: + raise ValueError("inference_mode is not supported for AdaptionPromptModel.") + if self._active_adapter == adapter_name: + return + if adapter_name not in self.peft_config: + raise ValueError(f"Adapter with name '{adapter_name}' does not exist.") + + if self._enabled: + self._remove_adapted_attentions(self._active_adapter) + self._set_adapted_attentions(adapter_name) + + self._active_adapter = adapter_name + + def enable_adapter_layers(self): + """Enable adapter layers by swapping in cached AdaptedAttention modules.""" + self._enabled = True + self._set_adapted_attentions(self._active_adapter) + + def disable_adapter_layers(self): + """Disable adapter layers by swapping out AdaptedAttention modules.""" + self._enabled = False + self._remove_adapted_attentions(self._active_adapter) + + def _create_adapted_attentions(self, config: AdaptionPromptConfig, parents: list[nn.Module]) -> None: + """Wrap LlamaAttention modules with newly created AdaptedAttention modules.""" + for par in parents: + if self.model.config.model_type == "gpt2": + attn = AdaptedAttentionGPT( + model_type=self.model.config.model_type, + adapter_len=config.adapter_len, + model=getattr(par, config.target_modules), + ) + + else: + attn = AdaptedAttention( + model_type=self.model.config.model_type, + adapter_len=config.adapter_len, + model=getattr(par, config.target_modules), + ) + setattr(par, config.target_modules, attn) + + def _set_adapted_attentions(self, adapter_name: str) -> None: + """Replace LlamaAttention modules with cached AdaptedAttention modules.""" + cached = self._cached_adapters[adapter_name] + del self._cached_adapters[adapter_name] + config = self.peft_config[adapter_name] + for i, par in enumerate(self._parents[adapter_name]): + setattr(par, config.target_modules, cached[i]) + + def _remove_adapted_attentions(self, adapter_name: str) -> None: + """Remove AdaptedAttention modules from the model and store them in the cache.""" + config = self.peft_config[adapter_name] + adapted_attentions = [] + for par in self._parents[adapter_name]: + attn = getattr(par, config.target_modules) + adapted_attentions.append(attn) + setattr(par, config.target_modules, attn.model) + self._cached_adapters[adapter_name] = adapted_attentions + + def _mark_only_adaption_prompts_as_trainable(self, model: nn.Module) -> None: + """Freeze all parameters of the model except the adaption prompts.""" + for n, p in model.named_parameters(): + if not is_adaption_prompt_trainable(n): + p.requires_grad = False + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + # This is necessary as e.g. causal models have various methods that we + # don't want to re-implement here. + if name == "model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.model, name) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..967dabf47c2af6973c4b3c8a0ba67cb957c0fceb --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/adaption_prompt/utils.py @@ -0,0 +1,158 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import inspect +from typing import Optional + +import torch +import torch.nn as nn + + +def llama_rotate_half(x: torch.Tensor) -> torch.Tensor: + """ + Rotate half the hidden dims of the input. + + This function was duplicated verbatim from: + https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/modeling_llama.py#L126 + + This was done to eliminate the Llama transformers implementation as a dependency of this file. Note that some other + functions were also adapted from the transformers implementation but were modified. + """ + x1 = x[..., : x.shape[-1] // 2] + x2 = x[..., x.shape[-1] // 2 :] + return torch.cat((-x2, x1), dim=-1) + + +def llama_apply_rotary_pos_emb(q, cos, sin, position_ids): + """ + Apply rotary position embedding to query states in the Llama model. + + This function was adapted from: + https://github.com/huggingface/transformers/blob/1de8ce9ee1191ba761a593ac15d9ccbf5851bfc5/src/transformers/models/llama/modeling_llama.py#L133 + + It was modified to remove unnecessary processing of key states. The method is compatible with transformers <= + 4.34.2 and also with the latest version (>=4.35). + """ + # In previous transformers version cos/sin cached had a shape of 4D + if len(cos.shape) == 4: + gather_indices = position_ids[:, None, :, None] # [bs, 1, seq_len, 1] + gather_indices = gather_indices.repeat(1, cos.shape[1], 1, cos.shape[3]) + cos = torch.gather(cos.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices) + sin = torch.gather(sin.repeat(gather_indices.shape[0], 1, 1, 1), 2, gather_indices) + # In the new version, it is 2D so we fall back to the new implementation + # https://github.com/huggingface/transformers/blame/eef7ea98c31a333bacdc7ae7a2372bde772be8e4/src/transformers/models/llama/modeling_llama.py#L222-L226 + else: + cos = cos[position_ids].unsqueeze(1) + sin = sin[position_ids].unsqueeze(1) + q_embed = (q * cos) + (llama_rotate_half(q) * sin) + return q_embed + + +def llama_compute_query_states(model: nn.Module, **kwargs) -> torch.Tensor: + """ + Compute query states for Llama models specifically. They need to be recomputed as the forward() method of the + original LlamaModel in the transformers library does not return them. See the related discussion in the PR: + https://github.com/huggingface/peft/pull/268 + """ + hidden_states = kwargs.get("hidden_states") + position_ids = kwargs.get("position_ids") + past_key_value = kwargs.get("past_key_value") + bsz, q_len, _ = hidden_states.size() + if hasattr(model, "num_heads"): + # TODO: remove this clause after 2026-01-01 + num_heads = model.num_heads + else: # changed in https://github.com/huggingface/transformers/pull/35235 + num_heads = model.config.num_attention_heads + query_states = model.q_proj(hidden_states).view(bsz, q_len, num_heads, model.head_dim).transpose(1, 2) + + factor = model.k_proj.in_features // model.k_proj.out_features + value_states = model.v_proj(hidden_states).view(bsz, q_len, (num_heads // factor), model.head_dim).transpose(1, 2) + + seq_len = q_len + + if past_key_value is not None: + if isinstance(past_key_value, tuple): + # for transformers <= 4.35 + seq_len += past_key_value[0].shape[-2] + else: + # since transformers 4.36, this is a DynamicCache instance + seq_len += past_key_value.get_seq_length(model.layer_idx) + + # model.rotary_emb is deprecated and will be removed in transformers > 4.47.0. Instead, the position embeddings are + # passed via the kwargs + if "position_embeddings" in kwargs: + cos, sin = kwargs["position_embeddings"] + cos = cos.unsqueeze(1) + sin = sin.unsqueeze(1) + return (query_states * cos) + (llama_rotate_half(query_states) * sin) + + # For transformers > 4.37.2 `position_ids` became a required arguments in the rotary embedding's forward pass. + if "position_ids" not in inspect.signature(model.rotary_emb.forward).parameters: + # TODO we assume that position_ids is not None here, not sure if that is safe but the old code also did that + cos, sin = model.rotary_emb(value_states, seq_len=seq_len) + return llama_apply_rotary_pos_emb(query_states, cos, sin, position_ids) + + past_seen_tokens = 0 + if position_ids is None: + # Compute position_ids, since they are required for transformers > 4.37.2 + if past_key_value is None: + new_cache_positions = torch.arange(q_len, q_len + q_len, device=value_states.device) + else: + past_seen_tokens = past_key_value.get_usable_length(q_len, model.layer_idx) + new_cache_positions = torch.arange(past_seen_tokens, past_seen_tokens + q_len, device=value_states.device) + position_ids = new_cache_positions.unsqueeze(0) + + rotary_emb_kwargs = {"position_ids": position_ids} + # The `seq_len` argument has been officially removed in transformers >= 4.39.0 + if "seq_len" in inspect.signature(model.rotary_emb.forward).parameters: + rotary_emb_kwargs["seq_len"] = q_len + past_seen_tokens + + cos, sin = model.rotary_emb(value_states, **rotary_emb_kwargs) + + # For batched inference unsqueeze it on the correct dim + # since: https://github.com/huggingface/transformers/pull/29109 + if len(cos.shape) == 3: + cos = cos.unsqueeze(1) + sin = sin.unsqueeze(1) + + return (query_states * cos) + (llama_rotate_half(query_states) * sin) + + +def gpt2_compute_query_states( + model: nn.Module, + hidden_states: Optional[tuple[torch.FloatTensor]], + encoder_hidden_states: Optional[torch.Tensor] = None, +) -> torch.Tensor: + """ + Compute query states for GPT2 models. They need to be recomputed as the forward() method of the GPT@ in the + transformers library does not return them. See the related discussion in the PR: + """ + if encoder_hidden_states is not None: + if not hasattr(model, "q_attn"): + raise ValueError( + f"If `{model.__class__.__name__}` is used as cross attention, the weights `q_attn` must be defined. " + f"Please make sure to instantiate it with `GPT2Attention(..., is_cross_attention=True)`." + ) + query_states = model.q_attn(hidden_states) + else: + query_states, _, _ = model.c_attn(hidden_states).split(model.split_size, dim=2) + + shape_q = (*query_states.shape[:-1], -1, model.head_dim) + query_states = query_states.view(shape_q).transpose(1, 2) + + return query_states + + +def is_adaption_prompt_trainable(params: str) -> bool: + """Return True if module is trainable under adaption prompt fine-tuning.""" + return params.split(".")[-1].startswith("adaption_") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c84b8358da8fc52d3f332c195f22b8b9620c665f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import BOFTConfig +from .layer import BOFTLayer +from .model import BOFTModel + + +__all__ = ["BOFTConfig", "BOFTLayer", "BOFTModel"] + +register_peft_method(name="boft", config_cls=BOFTConfig, model_cls=BOFTModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1715cc5bc65c190d3ba4dd160707d3fb0c93307a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/config.py @@ -0,0 +1,160 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# The implementation is based on "Parameter-Efficient Orthogonal Finetuning +# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class BOFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`BOFTModel`]. + + Args: + boft_block_size (`int`): BOFT block size across different layers. + boft_block_num (`int`): Number of BOFT blocks per injected layer. + boft_n_butterfly_factor (`int`): Number of butterfly factors across different layers. + target_modules (`Union[List[str],str]`): The names of the modules to apply the adapter to. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + boft_dropout (`float`): + The multiplicative dropout probability, by setting OFT blocks to identity during training, similar to the + dropout layer in LoRA. + fan_in_fan_out (`bool`): Set this to True if the layer to replace stores weight like (fan_in, fan_out). + For example, gpt-2 uses `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set + to `True`. + bias (`str`): Bias type for BOFT. Can be 'none', 'all' or 'boft_only'. If 'all' or 'boft_only', the + corresponding biases will be updated during training. Be aware that this means that, even when disabling + the adapters, the model will not produce the same output as the base model would have without adaptation. + modules_to_save (`List[str]`):List of modules apart from BOFT layers to be set as trainable + and saved in the final checkpoint. + layers_to_transform (`Union[List[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply the BOFT transformations on + the layer indexes that are specified in this list. If a single integer is passed, it will apply the BOFT + transformations on the layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None` and if the layer + pattern is not in the common layers pattern. This should target the `nn.ModuleList` of the model, which is + often called `'layers'` or `'h'`. + """ + + boft_block_size: int = field( + default=4, + metadata={ + "help": "BOFT block size across different layers.", + "note": "You can only specify either boft_block_size or boft_block_num, but not both simultaneously, because boft_block_size x boft_block_num = layer dimension.", + }, + ) + boft_block_num: int = field( + default=0, + metadata={ + "help": "Number of BOFT blocks per injected layer.", + "note": "You can only specify either boft_block_size or boft_block_num, but not both simultaneously, because boft_block_size x boft_block_num = layer dimension.", + }, + ) + boft_n_butterfly_factor: int = field( + default=1, + metadata={ + "help": "Number of butterfly factors.", + "note": ( + "for example, boft_n_butterfly_factor=2, the effective block size of OFT becomes twice as big and the number of blocks become half.", + "note: for boft_n_butterfly_factor=1, BOFT is the same as vanilla OFT.", + ), + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with BOFT.", + "example": "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' ", + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from BOFT."}, + ) + boft_dropout: float = field( + default=0.0, + metadata={ + "help": "BOFT multiplicative dropout, randomly setting blocks of OFT to be identity matrix, similar to the dropout layer in LoRA." + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + bias: str = field(default="none", metadata={"help": "Bias type for BOFT. Can be 'none', 'all' or 'boft_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from BOFT layers to be set as trainable and saved in the final checkpoint. ", + "note": ( + "For example, in Sequence Classification or Token Classification tasks, ", + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved.", + ), + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the BOFT layers with their default initialization. Don't change ", + "this setting, except if you know exactly what you're doing.", + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. " + "This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.BOFT + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + if self.boft_block_size == 0 and self.boft_block_num == 0: + raise ValueError( + f"Either `boft_block_size` or `boft_block_num` must be non-zero. Currently, boft_block_size = {self.boft_block_size} and boft_block_num = {self.boft_block_num}." + ) + if not (self.boft_block_size != 0) ^ (self.boft_block_num != 0): + raise ValueError( + f"You can only specify either boft_block_size ({self.boft_block_size}) or boft_block_num ({self.boft_block_num}), but not both simultaneously, because boft_block_size x boft_block_num == in_features." + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/fbd_cuda.cpp b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/fbd_cuda.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d63111b04083f3b1359aba0a9de9656060a4d515 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/fbd_cuda.cpp @@ -0,0 +1,28 @@ +#include +#include +#include +#include + +std::vector forward_fast_block_diag_cuda( + at::Tensor input); + +std::vector forward_fast_block_diag( + at::Tensor input + ) { + return forward_fast_block_diag_cuda(input); +} + +std::vector backward_fast_block_diag_cuda( + at::Tensor grad_output, + at::Tensor input); +std::vector backward_fast_block_diag( + at::Tensor grad_output, + at::Tensor input + ) { + return backward_fast_block_diag_cuda(grad_output, input); +} + +PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { + m.def("forward", &forward_fast_block_diag, "FAST BLOCK DIAG (CUDA)"); + m.def("backward", &backward_fast_block_diag, "FAST BLOCK DIAG backward (CUDA)"); +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/fbd_cuda_kernel.cu b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/fbd_cuda_kernel.cu new file mode 100644 index 0000000000000000000000000000000000000000..9f307455349e6ea8067d47ebf8a39b98ba452d09 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/fbd/fbd_cuda_kernel.cu @@ -0,0 +1,109 @@ +// Author: Yao Feng +// Date: 2023/08 +// Description: cuda kernel for fast block diag + +#include + +#include +#include +#include + +namespace{ +template +__global__ void forward_fast_block_diag_cuda_kernel( + const scalar_t* __restrict__ input, //[z, N, b, b] + scalar_t* output, //[z, Nxb, Nxb] + int z, int N, int b + ) { + + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= z*N*b*b) { + return; + } + const int zi = i/(N*b*b); + const int Ni = (i%(N*b*b))/(b*b); + const int x = ((i%(N*b*b))%(b*b))/b; + const int y = ((i%(N*b*b))%(b*b))%b; + + output[zi*N*b*N*b + (Ni*b+x)*N*b + Ni*b + y] = input[zi*N*b*b + Ni*b*b + x*b + y]; + +} + +template +__global__ void backward_fast_block_diag_cuda_kernel( + const scalar_t* __restrict__ grad_output, + scalar_t* grad_input, + int z, int N, int b + ) { + + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= z*N*b*b) { + return; + } + const int zi = i/(N*b*b); + const int Ni = (i%(N*b*b))/(b*b); + const int x = ((i%(N*b*b))%(b*b))/b; + const int y = ((i%(N*b*b))%(b*b))%b; + + grad_input[zi*N*b*b + Ni*b*b + x*b + y] = grad_output[zi*N*b*N*b + (Ni*b+x)*N*b + Ni*b + y]; + +} // namespace +} + +std::vector forward_fast_block_diag_cuda( + at::Tensor input + ){ + const auto z = input.size(0); + const auto N = input.size(1); + const auto b = input.size(2); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((z*N*b*b - 1) / threads +1); + // initlaize output + auto output = at::zeros({z, N*b, N*b}, input.options()); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(input.type(), "forward_fast_block_diag1", ([&] { + forward_fast_block_diag_cuda_kernel<<>>( + input.data_ptr(), + output.data_ptr(), + z, N, b); + })); + + + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in forward_fast_block_diag_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {output}; +} + +std::vector backward_fast_block_diag_cuda( + at::Tensor grad_output, + at::Tensor input + ){ + + const auto z = input.size(0); + const auto N = input.size(1); + const auto b = input.size(2); + + // print(channel_size) + const int threads = 512; + const dim3 blocks_1 ((z*N*b*b - 1) / threads +1); + + // initialize grad input + auto grad_input = at::zeros_like(input); + + AT_DISPATCH_FLOATING_TYPES_AND_HALF(grad_output.type(), "backward_fast_block_diag", ([&] { + backward_fast_block_diag_cuda_kernel<<>>( + grad_output.data_ptr(), + grad_input.data_ptr(), + z, N, b); + })); + + cudaError_t err = cudaGetLastError(); + if (err != cudaSuccess) + printf("Error in backward_fast_block_diag_cuda_kernel: %s\n", cudaGetErrorString(err)); + + return {grad_input}; +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..470ce123120f9fa849a1c6d44ba8a8248c8bdd10 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/layer.py @@ -0,0 +1,1011 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# The implementation is based on "Parameter-Efficient Orthogonal Finetuning +# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024. + +from __future__ import annotations + +import math +import os +import warnings +from contextlib import contextmanager +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch.autograd import Function + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + + +_FBD_CUDA = None + + +# this function is a 1:1 copy from accelerate +@contextmanager +def patch_environment(**kwargs): + """ + A context manager that will add each keyword argument passed to `os.environ` and remove them when exiting. + + Will convert the values in `kwargs` to strings and upper-case all the keys. + + Example: + + ```python + >>> import os + >>> from accelerate.utils import patch_environment + + >>> with patch_environment(FOO="bar"): + ... print(os.environ["FOO"]) # prints "bar" + >>> print(os.environ["FOO"]) # raises KeyError + ``` + """ + existing_vars = {} + for key, value in kwargs.items(): + key = key.upper() + if key in os.environ: + existing_vars[key] = os.environ[key] + os.environ[key] = str(value) + + yield + + for key in kwargs: + key = key.upper() + if key in existing_vars: + # restore previous value + os.environ[key] = existing_vars[key] + else: + os.environ.pop(key, None) + + +def get_fbd_cuda(): + global _FBD_CUDA + + if _FBD_CUDA is not None: + return _FBD_CUDA + + # This import initializes cuda context and should thus be local, see issue 1877 + from torch.utils.cpp_extension import load + + curr_dir = os.path.dirname(__file__) + # need ninja to build the extension + try: + with patch_environment(CC="gcc", CXX="gcc"): + fbd_cuda = load( + name="fbd_cuda", + sources=[f"{curr_dir}/fbd/fbd_cuda.cpp", f"{curr_dir}/fbd/fbd_cuda_kernel.cu"], + verbose=True, + # build_directory='/tmp/' # for debugging + ) + # extra_cuda_cflags = ['-std=c++14', '-ccbin=$$(which gcc-7)']) # cuda10.2 is not compatible with gcc9. Specify gcc 7 + except Exception as e: + warnings.warn(f"Failed to load the CUDA extension: {e}, check if ninja is available.") + warnings.warn("Setting boft_n_butterfly_factor to 1 to speed up the finetuning process.") + fbd_cuda = None + + _FBD_CUDA = fbd_cuda + return _FBD_CUDA + + +class FastBlockDiag(Function): + """ + Implements a custom autograd Function for a fast block diagonal operation using CUDA. + + This function is optimized for 4D tensors where the last two dimensions are equal, representing block diagonal + matrices for efficient computation on CUDA devices. + """ + + @staticmethod + def forward(ctx, input): + """ + The forward method for FastBlockDiag. + + Computes the block diagonal operation on the input tensor using a CUDA-optimized function. This method assumes + that the input is a 4D tensor where the last two dimensions are equal, which represent the blocks to be + diagonalized. + + Parameters: + ctx: A context object that can be used to stash information for backward computation. + input (Tensor): The input tensor of shape (N, D, H, H), where `N` is the batch size, + `D` represents one additional dimension (In BOFT, the number of BOFT blocks), and `H` is the + size of the square blocks along the last two dimensions (In BOFT, the block size). + + Returns: + Tensor: The resulting tensor after applying the block diagonal operation, + will have the shape (N, DxH, DxH). + """ + output = get_fbd_cuda().forward(input)[0] + ctx.save_for_backward(input) + return output + + @staticmethod + def backward(ctx, grad_output): + (input,) = ctx.saved_tensors + grad_input = get_fbd_cuda().backward(grad_output, input)[0] + return grad_input + + +class MultiplicativeDropoutLayer(nn.Module): + """ + Implements the multiplicative dropout layer for BOFT. + """ + + def __init__(self, p=0.0): + """ + Initializes the multiplicative dropout layer. + + Parameters: + p (float): The probability of dropping out a block. Defaults to 0.0. + """ + super().__init__() + self.p = p + + def forward(self, x): + """ + Applies multiplicative dropout to the input tensor. + + Parameters: + x (Tensor): The input tensor of shape (N, D, H, H), where `N` is the batch size, `D` represents + one additional dimension (In BOFT, the number of BOFT blocks), and `H` is the size of the square + blocks along the last two dimensions (In BOFT, the block size). + """ + if self.training: + # Ensure the last two dimensions are the same + if x.shape[-1] != x.shape[-2]: + raise ValueError("The last two dimensions of input should be the same!") + + N, D, H, _ = x.shape + + # Randomly select one from N + n_random = torch.randint(0, N, (1,)).item() + + # Create a mask with 1s for matrices to be replaced with identity and 0s otherwise + num_to_replace = int(self.p * D) + num_zeros = D - num_to_replace + + # Generate a flat tensor with desired number of 1s and 0s + mask = torch.cat([torch.ones(num_to_replace, device=x.device), torch.zeros(num_zeros, device=x.device)]) + + # Shuffle and reshape the mask + mask = mask[torch.randperm(D)].view(1, D, 1, 1) + + full_mask = torch.zeros(N, D, 1, 1, device=x.device) + full_mask[n_random] = mask + + # Use the mask to combine original matrices and identity matrices + eye_matrix = torch.eye(H, device=x.device).repeat(N, D, 1, 1) + x = (1 - full_mask) * x + full_mask * eye_matrix + return x + + +class BOFTLayer(BaseTunerLayer): + """ + Implements the BOFT layer. + """ + + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("boft_R", "boft_s") + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("boft_block_size", "boft_block_num", "boft_dropout") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + """ + Initializes the BOFT layer. + + Note, currently only support linear layer and convolutional layer, with further support for other layers to be + added soon. + + Parameters: + base_layer: the pretrained model layer + """ + self.base_layer = base_layer + self.boft_block_size = {} + self.boft_block_num = {} + self.boft_dropout = nn.ModuleDict({}) + self.boft_R = nn.ParameterDict({}) + self.boft_s = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + self.kwargs = kwargs + + base_layer = self.get_base_layer() + + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, nn.Conv2d): + in_features, out_features = base_layer.in_channels, base_layer.out_channels + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + self.in_features = in_features + self.out_features = out_features + + def set_scale(self, adapter, scale): + if adapter not in self.scaling: + # Ignore the case where the adapter is not in the layer + return + + warnings.warn("Scaling operation for BOFT not supported! Automatically set scale to 1.") + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.boft_R.keys(): + continue + + warnings.warn("Scaling operation for BOFT not supported! Automatically set scale to 1.") + + def unscale_layer(self, scale=None) -> None: + for active_adapter in self.active_adapters: + if active_adapter not in self.boft_R.keys(): + continue + + warnings.warn("Unscaling operation for BOFT not supported! Keeping scale to 1.") + + def update_layer( + self, + adapter_name, + boft_block_size, + boft_block_num, + boft_n_butterfly_factor, + boft_dropout, + init_weights, + inference_mode: bool = False, + **kwargs, + ): + """ + Update the linear layer with trainable BOFT weights. Override for other layer types. + """ + # Attempt to load the CUDA extension during model initialization + if not get_fbd_cuda(): + self.fbd_cuda_available = False + # If the CUDA extension is not available, set the butterfly factor to 1 to speed up the finetuning process + boft_n_butterfly_factor = 1 + else: + self.fbd_cuda_available = True + + # to be consistent with the paper notation + boft_n_butterfly_factor = boft_n_butterfly_factor - 1 + if boft_n_butterfly_factor < 0: + raise ValueError( + f"You can only specify boft_n_butterfly_factor {boft_n_butterfly_factor + 1} to be a positive integer number." + ) + + # Initialize the MultiplicativeDropoutLayer for boft_dropout > 0.0. + if boft_dropout > 0.0: + boft_dropout_layer = MultiplicativeDropoutLayer(p=boft_dropout) + else: + boft_dropout_layer = nn.Identity() + self.boft_dropout.update(nn.ModuleDict({adapter_name: boft_dropout_layer})) + + if boft_block_size == 0 and boft_block_num != 0: + if self.in_features % boft_block_num != 0: + raise ValueError( + f"in_features ({self.in_features}) must be divisible by boft_block_num ({boft_block_num})!" + ) + + if boft_n_butterfly_factor != 0: + if boft_n_butterfly_factor > int(math.log2(boft_block_num)): + raise ValueError( + f"Invalid combination of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_num ({boft_block_num})!" + ) + if boft_block_num % (2**boft_n_butterfly_factor) != 0: + raise ValueError( + f"boft_block_num ({boft_block_num}) must be a multiple of 2 raised to the power of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1})!" + ) + + boft_block_size = int(self.in_features // boft_block_num) + + elif boft_block_size != 0 and boft_block_num == 0: + if self.in_features % boft_block_size != 0: + raise ValueError( + f"in_features ({self.in_features}) must be divisible by boft_block_size ({boft_block_size})!" + ) + + if boft_n_butterfly_factor != 0: + if self.in_features < (boft_block_size * (2**boft_n_butterfly_factor)): + raise ValueError( + f"Invalid combination of in_features ({self.in_features}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + if self.in_features % (boft_block_size * (2**boft_n_butterfly_factor)) != 0: + raise ValueError( + f"Invalid combination of in_features ({self.in_features}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + + boft_block_num = int(self.in_features // boft_block_size) + + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # In OFT you can specify the number of blocks to be 1 + if boft_n_butterfly_factor != 0: + if boft_block_num % 2 != 0: + raise ValueError(f"boft_block_num ({boft_block_num}) must be an even number!") + + if boft_block_size % 2 != 0: + raise ValueError(f"boft_block_size ({boft_block_size}) must be an even number!") + + # If there is no butterfly factor, then permutation matrix P will be an identity matrix. + P = torch.empty((boft_n_butterfly_factor + 1, self.in_features, self.in_features)) + for i in range(boft_n_butterfly_factor + 1): + perm = self.block_butterfly_perm( + self.in_features, int(boft_block_num / (2 ** (i))), int(boft_block_size / 2), boft_n_butterfly_factor + ) + perm_mat = self.perm2mat(perm) + P[i] = perm_mat + + self.register_buffer("boft_P", P, persistent=False) + + self.boft_R[adapter_name] = nn.Parameter( + torch.zeros(boft_n_butterfly_factor + 1, boft_block_num, boft_block_size, boft_block_size) + ) + self.boft_s[adapter_name] = nn.Parameter(torch.ones(int(self.out_features), 1)) + + self.reset_boft_parameters(adapter_name, init_weights) + + # set the boft block size and number + self.boft_block_size[adapter_name] = boft_block_size + self.boft_block_num[adapter_name] = boft_block_num + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_boft_parameters(self, adapter_name, init_weights): + """ + Reset the BOFT parameters. + """ + if init_weights is False: + nn.init.normal_(self.boft_R[adapter_name], mean=0.0, std=0.1) + nn.init.normal_(self.boft_s[adapter_name], mean=1.0, std=0.1) + return + + if adapter_name in self.boft_R.keys(): + if init_weights is True: + # initialize R to zero + nn.init.zeros_(self.boft_R[adapter_name]) + nn.init.ones_(self.boft_s[adapter_name]) + else: + raise ValueError(f"Unknown initialization {init_weights=}") + + def perm2mat(self, indices): + """ + Convert permutation indices to permutation matrix. + + Args: + indices: A list of indices representing the permutation. + """ + # Number of indices determines the size of the square matrix + n = len(indices) + + # Initialize a matrix of zeros + perm_mat = torch.zeros((n, n)) + + # Set the 1s according to the indices + for i, idx in enumerate(indices): + perm_mat[i, idx] = 1 + + return perm_mat + + def block_butterfly_perm(self, n, b, r=3, n_butterfly_factor=1): + """ + Define the permutation matrix for the block butterfly permutation. + + Args: + n: size of the permutation matrix + b: desired number of blocks after multiplying with the permutation matrix + r: base block size of the block diagonal matrix, e.g. 2x2, 3x3, 5x5 etc. + """ + + if n_butterfly_factor == 0: + return torch.arange(n) + + if b * r * 2 > n: + raise ValueError("Invalid number of blocks!") + + block_size = int(n // b) + indices = torch.arange(n) + + def sort_block(b, r): + step = b / r + initial_order = torch.arange(b) + sorted_order = torch.empty(b, dtype=torch.long) + + evens = torch.arange(0, step, 2) + odds = torch.arange(1, step, 2) + sorted_seq = torch.cat((evens, odds), dim=0) + for i, pos in enumerate(sorted_seq): + sorted_order[int(i * r) : int(i * r + r)] = initial_order[int(pos * r) : int(pos * r + r)] + return sorted_order + + sorted_order = sort_block(block_size, r) + + for i in range(0, n, block_size): + block_end = i + block_size + tmp_indices = indices[i:block_end] + indices[i:block_end] = tmp_indices[sorted_order] + return indices + + def cayley_batch(self, data): + """ + Perform the Cayley parametrization on a batch of skew-symmetric matrices. + + Args: + data: A batch of skew-symmetric matrices of shape (b, r, c). + """ + b, r, c = data.shape + # Ensure the input matrix is skew-symmetric + skew_mat = 0.5 * (data - data.transpose(1, 2)) + id_mat = torch.eye(r, device=data.device).unsqueeze(0).expand(b, r, c) + + # Perform the Cayley parametrization, must be in float32 + Q = torch.linalg.solve(id_mat + skew_mat, id_mat - skew_mat, left=False) + + return Q.to(data.dtype) + + +class Linear(nn.Module, BOFTLayer): + """ + BOFT implemented in a dense layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + boft_block_size: int = 8, + boft_block_num: int = 0, + boft_n_butterfly_factor: int = 0, + boft_dropout: float = 0.1, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: Union[bool, str] = True, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + super().__init__() + BOFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + + self.update_layer( + adapter_name, boft_block_size, boft_block_num, boft_n_butterfly_factor, boft_dropout, init_weights + ) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.boft_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + else: + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + orig_weight = base_layer.weight.data.clone() + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + + self.base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if active_adapter in self.boft_R.keys(): + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = base_layer.weight.data.clone() + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat.t(), orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + + base_layer.weight.data = (orig_weight * (1 / boft_s)).to(orig_dtype) + + def get_delta_weight(self, adapter) -> tuple[torch.Tensor, torch.Tensor]: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + boft_R = self.boft_R[adapter] + boft_s = self.boft_s[adapter] + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + boft_P = self.boft_P.to(block_diagonal_butterfly.device, block_diagonal_butterfly.dtype) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + return butterfly_oft_mat, boft_s + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + boft_rotation = torch.eye(self.in_features, device=x.device, dtype=previous_dtype) + boft_scale = torch.ones((int(self.out_features), 1), device=x.device, dtype=previous_dtype) + + for active_adapter in self.active_adapters: + if active_adapter not in self.boft_R.keys(): + continue + boft_R = self.boft_R[active_adapter] + boft_s = self.boft_s[active_adapter] + dropout = self.boft_dropout[active_adapter] + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + orth_rotate_butterfly = dropout(orth_rotate_butterfly) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + # The BOFT author's cayley_batch, dropout and FastBlockDiag ONLY return fp32 outputs. + boft_P = self.boft_P.to(x) + block_diagonal_butterfly = block_diagonal_butterfly.to(x) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + boft_rotation = butterfly_oft_mat @ boft_rotation + boft_scale = boft_s * boft_scale + + x = x.to(self.get_base_layer().weight.data.dtype) + + orig_weight = self.get_base_layer().weight.data + orig_weight = torch.transpose(orig_weight, 0, 1) + boft_rotation = boft_rotation.to(previous_dtype) + orig_weight = orig_weight.to(previous_dtype) + rotated_weight = torch.mm(boft_rotation, orig_weight) + rotated_weight = torch.transpose(rotated_weight, 0, 1) + + scaled_rotated_weight = rotated_weight * boft_scale + + scaled_rotated_weight = scaled_rotated_weight.to(previous_dtype) + if self.base_layer.bias is not None: + self.base_layer.bias = self.base_layer.bias.to(previous_dtype) + result = F.linear(input=x, weight=scaled_rotated_weight, bias=self.base_layer.bias) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "boft." + rep + + +class Conv2d(nn.Module, BOFTLayer): + """ + BOFT implemented in a Conv2d layer. + """ + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + boft_block_size: int = 8, + boft_block_num: int = 0, + boft_n_butterfly_factor: int = 0, + boft_dropout: float = 0.1, + init_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + super().__init__() + BOFTLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, boft_block_size, boft_block_num, boft_n_butterfly_factor, boft_dropout, init_weights + ) + + def update_layer( + self, + adapter_name, + boft_block_size, + boft_block_num, + boft_n_butterfly_factor, + boft_dropout, + init_weights, + inference_mode: bool = False, + **kwargs, + ): + """ + Update the conv2d layer with trainable BOFT weights. + """ + + # Attempt to load the CUDA extension during model initialization + if not get_fbd_cuda(): + self.fbd_cuda_available = False + # If the CUDA extension is not available, set the butterfly factor to 1 to speed up the finetuning process + boft_n_butterfly_factor = 1 + else: + self.fbd_cuda_available = True + + # to be consistent with the paper notation + boft_n_butterfly_factor = boft_n_butterfly_factor - 1 + if boft_n_butterfly_factor < 0: + raise ValueError( + f"You can only specify boft_n_butterfly_factor {boft_n_butterfly_factor + 1} to be a positive integer number." + ) + + # Initialize the MultiplicativeDropoutLayer for boft_dropout > 0.0. + if boft_dropout > 0.0: + boft_dropout_layer = MultiplicativeDropoutLayer(p=boft_dropout) + else: + boft_dropout_layer = nn.Identity() + self.boft_dropout.update(nn.ModuleDict({adapter_name: boft_dropout_layer})) + + # layer information from the base layer + base_layer = self.get_base_layer() + conv_filter_dim = self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + + # Initialize the BOFT parameters. + if boft_block_size == 0 and boft_block_num != 0: + if conv_filter_dim % boft_block_num != 0: + raise ValueError( + f"Convolutional kernel dimension ({conv_filter_dim}) must be divisible by boft_block_num ({boft_block_num})!" + ) + + if boft_n_butterfly_factor != 0: + if boft_n_butterfly_factor > int(math.log2(boft_block_num)): + raise ValueError( + f"Invalid combination of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_num ({boft_block_num})!" + ) + if boft_block_num % (2**boft_n_butterfly_factor) != 0: + raise ValueError( + f"boft_block_num ({boft_block_num}) must be a multiple of 2 raised to the power of boft_n_butterfly_factor ({boft_n_butterfly_factor + 1})!" + ) + + boft_block_size = int(conv_filter_dim // boft_block_num) + + elif boft_block_size != 0 and boft_block_num == 0: + if conv_filter_dim % boft_block_size != 0: + raise ValueError( + f"Convolutional kernel dimension ({conv_filter_dim}) must be divisible by boft_block_size ({boft_block_size})!" + ) + + if boft_n_butterfly_factor != 0: + if conv_filter_dim < (boft_block_size * (2**boft_n_butterfly_factor)): + raise ValueError( + f"Invalid combination of convolutional kernel dimension ({conv_filter_dim}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + if conv_filter_dim % (boft_block_size * (2**boft_n_butterfly_factor)) != 0: + raise ValueError( + f"Invalid combination of convolutional kernel dimension ({conv_filter_dim}), boft_n_butterfly_factor ({boft_n_butterfly_factor + 1}) and boft_block_size ({boft_block_size})!" + ) + + boft_block_num = int(conv_filter_dim // boft_block_size) + + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # In OFT you can specify the number of blocks to be 1 + if boft_n_butterfly_factor != 0: + if boft_block_num % 2 != 0: + raise ValueError(f"boft_block_num ({boft_block_num}) must be an even number!") + + if boft_block_size % 2 != 0: + raise ValueError(f"boft_block_size ({boft_block_size}) must be an even number!") + + # If there is no butterfly factor, then permutation matrix P will be an identity matrix. + P = torch.empty((boft_n_butterfly_factor + 1, conv_filter_dim, conv_filter_dim)) + for i in range(boft_n_butterfly_factor + 1): + perm = self.block_butterfly_perm( + conv_filter_dim, int(boft_block_num / (2 ** (i))), int(boft_block_size / 2), boft_n_butterfly_factor + ) + perm_mat = self.perm2mat(perm) + P[i] = perm_mat + + self.register_buffer("boft_P", P, persistent=False) + + self.boft_R[adapter_name] = nn.Parameter( + torch.zeros(boft_n_butterfly_factor + 1, boft_block_num, boft_block_size, boft_block_size) + ) + self.boft_s[adapter_name] = nn.Parameter(torch.ones(1, int(self.out_features))) + + self.reset_boft_parameters(adapter_name, init_weights) + + # set the boft block size and number + self.boft_block_size[adapter_name] = boft_block_size + self.boft_block_num[adapter_name] = boft_block_num + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.boft_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = orig_weight.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + orig_weight = orig_weight.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + self.base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + else: + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = base_layer.weight.data.clone() + orig_weight = orig_weight.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat, orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * boft_s + orig_weight = orig_weight.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + self.base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if active_adapter in self.boft_R.keys(): + butterfly_oft_mat, boft_s = self.get_delta_weight(active_adapter) + + orig_weight = base_layer.weight.data.clone() + orig_weight = orig_weight.view( + self.out_features, + self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0], + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = torch.mm(butterfly_oft_mat.t(), orig_weight.to(butterfly_oft_mat.dtype)) + orig_weight = torch.transpose(orig_weight, 0, 1) + orig_weight = orig_weight * (1 / boft_s) + orig_weight = orig_weight.view( + self.out_features, + self.in_features, + base_layer.kernel_size[0], + base_layer.kernel_size[0], + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + + def get_delta_weight(self, adapter) -> tuple[torch.Tensor, torch.Tensor]: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + boft_R = self.boft_R[adapter] + boft_s = self.boft_s[adapter].transpose(0, 1) + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + boft_P = self.boft_P.to(block_diagonal_butterfly.device, block_diagonal_butterfly.dtype) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + return butterfly_oft_mat, boft_s + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + boft_rotation = torch.eye( + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + device=x.device, + dtype=x.dtype, + ) + boft_scale = torch.ones((int(self.out_features), 1), device=x.device, dtype=x.dtype) + + for active_adapter in self.active_adapters: + if active_adapter not in self.boft_R.keys(): + continue + boft_R = self.boft_R[active_adapter] + boft_s = self.boft_s[active_adapter].transpose(0, 1) + dropout = self.boft_dropout[active_adapter] + + N, D, H, _ = boft_R.shape + boft_R = boft_R.view(N * D, H, H) + orth_rotate_butterfly = self.cayley_batch(boft_R) + orth_rotate_butterfly = orth_rotate_butterfly.view(N, D, H, H) + orth_rotate_butterfly = dropout(orth_rotate_butterfly) + if self.fbd_cuda_available: + block_diagonal_butterfly = FastBlockDiag.apply(orth_rotate_butterfly) + else: + orth_rotate_butterfly = orth_rotate_butterfly.squeeze(0) + block_diagonal_butterfly = torch.block_diag(*torch.unbind(orth_rotate_butterfly)) + block_diagonal_butterfly = block_diagonal_butterfly.unsqueeze(0) + + boft_P = self.boft_P.to(x) + block_diagonal_butterfly = block_diagonal_butterfly.to(x) + butterfly_oft_mat_batch = torch.bmm(block_diagonal_butterfly, boft_P.permute(0, 2, 1)) + butterfly_oft_mat_batch = torch.bmm(boft_P, butterfly_oft_mat_batch) + butterfly_oft_mat = butterfly_oft_mat_batch[0] + + for i in range(1, butterfly_oft_mat_batch.shape[0]): + butterfly_oft_mat = butterfly_oft_mat_batch[i] @ butterfly_oft_mat + + boft_rotation = butterfly_oft_mat @ boft_rotation + boft_scale = boft_s * boft_scale + + x = x.to(self.base_layer.weight.data.dtype) + + orig_weight = self.base_layer.weight.data + orig_weight = orig_weight.view( + self.out_features, + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + orig_weight = torch.transpose(orig_weight, 0, 1) + rotated_weight = torch.mm(boft_rotation, orig_weight) + rotated_weight = torch.transpose(rotated_weight, 0, 1) + + scaled_rotated_weight = rotated_weight * boft_scale + + scaled_rotated_weight = scaled_rotated_weight.view( + self.out_features, self.in_features, self.base_layer.kernel_size[0], self.base_layer.kernel_size[0] + ) + x = self._cast_input_dtype(x, scaled_rotated_weight.dtype) + bias = self._cast_input_dtype(self.base_layer.bias, scaled_rotated_weight.dtype) + result = F.conv2d( + input=x, + weight=scaled_rotated_weight, + bias=bias, + padding=self.base_layer.padding[0], + stride=self.base_layer.stride[0], + ) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "boft." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..11bfa45ccb898fa5df101121892325a2ef54dc71 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/boft/model.py @@ -0,0 +1,131 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# The implementation is based on "Parameter-Efficient Orthogonal Finetuning +# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024. + +import warnings + +import torch + +from peft.tuners.tuners_utils import ( + BaseTuner, + BaseTunerLayer, +) +from peft.utils import TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING + +from .layer import BOFTLayer, Conv2d, Linear + + +class BOFTModel(BaseTuner): + """ + Creates BOFT and OFT model from a pretrained transformers model. Paper: https://huggingface.co/papers/2311.06243 + https://huggingface.co/papers/2306.07280 + + Args: + model ([`transformers.PreTrainedModel`]): The model to be adapted. + config ([`BOFTConfig`]): The configuration of the BOFT model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The BOFT model. + + Example:: + + >>> import transformers >>> from transformers import AutoModelForSeq2SeqLM, BOFTConfig >>> from peft import + BOFTConfig, get_peft_model + + >>> config = BOFTConfig( ... boft_block_size=8, ... boft_n_butterfly_factor=1, ... target_modules=["query", + "value", "key", "output.dense", "mlp.fc1", "mlp.fc2"], ... boft_dropout=0.1, ... bias="boft_only", ... + modules_to_save=["classifier"], ... ) + + >>> model = transformers.Dinov2ForImageClassification.from_pretrained( ... "facebook/dinov2-large", ... + num_labels=100, ... ) >>> boft_model = get_peft_model(model, config) + + **Attributes**: + - **model** ([`transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`BOFTConfig`]): The configuration of the BOFT model. + """ + + prefix: str = "boft_" + tuner_layer_cls = BOFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + boft_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "boft_block_size": boft_config.boft_block_size, + "boft_block_num": boft_config.boft_block_num, + "boft_n_butterfly_factor": boft_config.boft_n_butterfly_factor, + "boft_dropout": boft_config.boft_dropout, + "fan_in_fan_out": boft_config.fan_in_fan_out, + "init_weights": boft_config.init_weights, + } + kwargs["bias"] = bias + + # If it is not a BOFTLayer, create a new module, else update it with new adapters + if not isinstance(target, BOFTLayer): + new_module = self._create_new_module(boft_config, adapter_name, target, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + else: + target.update_layer( + adapter_name, + boft_block_size=boft_config.boft_block_size, + boft_block_num=boft_config.boft_block_num, + boft_n_butterfly_factor=boft_config.boft_n_butterfly_factor, + boft_dropout=boft_config.boft_dropout, + init_weights=boft_config.init_weights, + ) + + @staticmethod + def _create_new_module(boft_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = boft_config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, **kwargs) + elif isinstance(target_base_layer, torch.nn.Conv2d): + new_module = Conv2d(target, adapter_name, **kwargs) + else: + raise ValueError( + f"Target module {target} is not supported. " + "Currently, only `torch.nn.Linear` and `torch.nn.Conv2d` are supported." + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ba8a7cbf61845f934737e11be277a7e2f48e7b34 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from peft.utils import register_peft_method + +from .config import C3AConfig +from .layer import C3ALayer, C3ALinear +from .model import C3AModel + + +__all__ = ["C3AConfig", "C3ALayer", "C3ALinear", "C3AModel"] + +register_peft_method(name="c3a", model_cls=C3AModel, config_cls=C3AConfig) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/config.py new file mode 100644 index 0000000000000000000000000000000000000000..2059c77a417f9f4eaa54f9d1f73943836646d328 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/config.py @@ -0,0 +1,137 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class C3AConfig(PeftConfig): + """This is the configuration class to store the configuration of a [`C3AModel`]. + + Args: + block_size (`int`): + block size for C3A, must be divisible by both the input size and the output size of the target layer. If + you have no idea what block_size you should use, set it to the greatest common divisor of all input & + output sizes of your target layers. Increasing this would result in less parameters. + target_modules (`Union[list[str],str]`): The names of the modules to apply C3A to. + bias (`str`): Bias type for C3A. Can be 'none', 'all' or 'c3a_only'. If 'all' or 'c3a_only', the + corresponding biases will be updated during training. Be aware that this means that, even when disabling + the adapters, the model will not produce the same output as the base model would have without adaptation. + modules_to_save (`list[str]`):list of modules apart from C3A layers to be set as trainable + and saved in the final checkpoint. + layers_to_transform (`Union[list[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply C3A on the layer indexes that + are specified in this list. If a single integer is passed, it will apply C3A on the layer at this index. + layers_pattern (`str`): + The layer pattern name, used only if `layers_to_transform` is different from `None` and if the layer + pattern is not in the common layers pattern. + block_size_pattern (`dict`): + The mapping from layer names or regexp expression to block_size which are different from the default + specified. For example, `{"model.decoder.layers.0.encoder_attn.k_proj": 1280`} + init_weights (`Union[bool, Literal["gaussian", "kaiming_uniform", "xavier_uniform"]]`): + Defaults to 'xavier_uniform'. Setting this to `False` also uses 'xavier_uniform'. To set the weights to + zeros (thus making C3A a no-op), set the value to `True`. + """ + + block_size: int = field( + default=256, + metadata={ + "help": ( + "block size for C3A, must be divisible by both the input size and the output size of the target layer." + " If you have no idea what block_size you should use, set it to the greatest common divisor of all" + " input & output sizes of your target layers. Increasing this would result in less parameters." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "list of module names or regex expression of the module names to replace with C3A." + " For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + ) + }, + ) + bias: str = field(default="none", metadata={"help": "Bias type for C3A. Can be 'none', 'all' or 'c3a_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "list of modules apart from C3A layers to be set as trainable and saved in the final checkpoint." + " For example, in Sequence Classification or Token Classification tasks," + " the final layer `classifier/score` are randomly initialized" + " and as such need to be trainable and saved." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, is this argument is specified," + " PEFT will transform only the layers indexes that are specified inside this list." + " If a single integer is passed, PEFT will transform only the layer at this index." + " This only works when target_modules is a list of str." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different to None" + " and if the layer pattern is not in the common layers pattern." + " This only works when target_modules is a list of str." + ) + }, + ) + block_size_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to block_size" + " which are different from the default specified." + " For example, `{model.decoder.layers.0.encoder_attn.k_proj: 1280`}" + ) + }, + ) + init_weights: Optional[Union[bool, Literal["gaussian", "kaiming_uniform", "xavier_uniform"]]] = field( + default="xavier_uniform", + metadata={ + "help": ( + "Defaults to 'xavier_uniform'. Setting this to `False` also uses 'xavier_uniform'. To set the weights " + "to zeros (thus making C3A a no-op), set the value to `True`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.C3A + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..15b1e503d02b0f0501dbf8862c3be6f6e9cafc43 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/layer.py @@ -0,0 +1,205 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import math +import warnings +from typing import Any, Literal, Optional + +import torch +import torch.nn as nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .utils import BlockCircularConvolution, get_circulant_fast + + +class C3ALayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("c3a_kernel",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("block_size",) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.block_size = {} + self.c3a_kernel = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + def get_delta_weight(self, adapter) -> torch.Tensor: + if adapter not in self.c3a_kernel.keys(): + raise ValueError(f"Adapter {adapter} not found.") + base_layer_weight = self.get_base_layer().weight + base_layer_weight_dtype = base_layer_weight.dtype + c3a_kernel = self.c3a_kernel[adapter] + + delta_weight = get_circulant_fast(c3a_kernel.to(torch.float32)).to(base_layer_weight_dtype) + return delta_weight / base_layer_weight.size(-1) + + def update_layer(self, adapter_name, block_size, init_weights, inference_mode: bool = False, **kwargs): + if block_size <= 0: + raise ValueError(f"`block_size` should be a positive integer value but the value passed is {block_size}") + if self.in_features % block_size != 0: + raise ValueError( + f"The block size should be a factor of the input size. However, the input size is {self.in_features} and the block size is {block_size}" + ) + if self.out_features % block_size != 0: + raise ValueError( + f"The block size should be a factor of the output size. However, the output size is {self.out_features} and the block size is {block_size}" + ) + + self.block_size[adapter_name] = block_size + + weight = self.get_base_layer().weight + self.c3a_kernel[adapter_name] = nn.Parameter( + torch.zeros( + self.out_features // block_size, + self.in_features // block_size, + block_size, + # Currently, only fp32 is widely supported for FFT (fp16 is only supported on GPU with shapes of powers + # of 2, bf16 lacks FFT support) + dtype=torch.float32, + device=weight.device, + ) + ) + + self.reset_c3a_parameters(adapter_name, init_weights) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + @torch.no_grad() + def reset_c3a_parameters(self, adapter_name, init_weights): + if init_weights is True: + return + + if adapter_name in self.c3a_kernel.keys(): + if init_weights == "gaussian": + nn.init.normal_(self.c3a_kernel[adapter_name]) + elif init_weights in ["xavier_uniform", False]: + fan_in, fan_out = self.in_features, self.out_features + std = 1.0 * math.sqrt(2.0 / float(fan_in + fan_out)) + a = math.sqrt(3.0) * std + nn.init.uniform_(self.c3a_kernel[adapter_name], -a, a) + elif init_weights == "kaiming_uniform": + fan_in = self.in_features + a = 1.0 * math.sqrt(1.0 / float(fan_in)) + nn.init.uniform_(self.c3a_kernel[adapter_name], -a, a) + else: + raise ValueError(f"Unknown init_weights: {init_weights}") + + +class C3ALinear(nn.Module, C3ALayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + block_size: int, + init_weights: bool | Literal["gaussian", "kaiming_uniform", "xavier_uniform"], + **kwargs, + ) -> None: + super().__init__() + C3ALayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, block_size, init_weights) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.c3a_kernel.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights = orig_weights + delta_weight + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data = base_layer.weight.data + delta_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.c3a_kernel.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + x = x.to(torch.float32) + for active_adapter in self.active_adapters: + if active_adapter not in self.c3a_kernel.keys(): + continue + c3a_kernel = self.c3a_kernel[active_adapter].to(torch.float32) + x = BlockCircularConvolution.apply(x, c3a_kernel) / x.size(-1) + result += x.to(result.dtype) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "c3a." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f6408808e920fb24d1fb6684be9a4042f14aa5b4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/model.py @@ -0,0 +1,101 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import re +from itertools import chain + +import torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, +) + +from .layer import C3ALayer, C3ALinear + + +class C3AModel(BaseTuner): + """ + Creates C3A model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2407.19342. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`C3AConfig`]): The configuration of the C3A model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The C3A model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`C3AConfig`]): The configuration of the C3A model. + """ + + prefix: str = "c3a_" + tuner_layer_cls = C3ALayer + target_module_mapping = TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + c3a_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + # Regexp matching - Find key which matches current target_name in patterns provided + pattern_keys = list(chain(c3a_config.block_size_pattern.keys())) + target_name_key = next(filter(lambda key: re.match(rf".*\.{key}$", current_key), pattern_keys), current_key) + + block_size = c3a_config.block_size_pattern.get(target_name_key, c3a_config.block_size) + kwargs = { + "block_size": block_size, + "init_weights": c3a_config.init_weights, + } + + if isinstance(target, C3ALinear): + target.update_layer( + adapter_name, + block_size, + c3a_config.init_weights, + ) + else: + new_module = self._create_new_module(c3a_config, adapter_name, target, **kwargs) + if adapter_name != self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(c3a_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + new_module = C3ALinear(target, adapter_name, **kwargs) + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` is supported." + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..89b80ec5797a514a368c9138405871cb620602d6 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/c3a/utils.py @@ -0,0 +1,48 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +import torch +from torch.autograd import Function +from torch.fft import fft, ifft + + +def get_circulant_fast(w): + m, n, b = w.shape + x = torch.eye(n * b, dtype=w.dtype, device=w.device) + x = x.reshape(*x.shape[:-1], n, b) + x = torch.einsum("...nb,mnb->...mb", ifft(x), fft(w)) + x = fft(x).real.flatten(start_dim=1).T + return x + + +class BlockCircularConvolution(Function): + @staticmethod + def forward(ctx, x, w): + m, n, b = w.shape + x = x.reshape(*x.shape[:-1], n, b) + ctx.save_for_backward(x, w) + x = torch.einsum("...nb,mnb->...mb", ifft(x), fft(w)) + x = fft(x).real + x = x.reshape(*x.shape[:-2], -1) + return x + + @staticmethod + def backward(ctx, grad_output): + x, w = ctx.saved_tensors + m, n, b = w.shape + grad_output = grad_output.reshape(*grad_output.shape[:-1], m, b) + grad_output_fft = fft(grad_output) + x_grad = fft(torch.einsum("...mb,mnb->...nb", grad_output_fft, ifft(w))).real + x_grad = x_grad.reshape(*x_grad.shape[:-2], -1) + w_grad = fft(torch.einsum("...mb,...nb->mnb", grad_output_fft, ifft(x))).real + return x_grad, w_grad diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..78ecfa0c3a14d56a936fc5db391ff3f9c8537b3a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import CartridgeConfig +from .model import CartridgeEncoder + + +__all__ = ["CartridgeConfig", "CartridgeEncoder"] + +register_peft_method(name="cartridge", config_cls=CartridgeConfig, model_cls=CartridgeEncoder) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1eba07f0b8c0f53b78b0044eae076ff0dde0b99e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/config.py @@ -0,0 +1,74 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +@dataclass +class CartridgeConfig(PromptLearningConfig): + """ + Configuration for CARTRIDGE, a KV-cache-parameterized prefix adapter. + + This is similar to prefix-tuning in how it is served (as `past_key_values`), but it stores the KV cache directly as + trainable parameters instead of learning it via an MLP projection. + + Initialization: + The Cartridges paper discusses multiple initialization options. In PEFT, initialization is a *separate* step + from constructing the adapter config: + + - **Random KV initialization (paper option 2)**: Create the adapter via `get_peft_model(...)`. The CARTRIDGE + prompt encoder parameters are randomly initialized by PyTorch. + + - **KV derived from the first tokens of a prompt/corpus (paper option 3)**: Run a no-grad prefill on the *base + model* and copy the first `num_virtual_tokens` cached KV tokens into the adapter. PEFT provides utilities for + this (importable from `peft` or from `peft.tuners.cartridge.utils`): + + - `initialize_kv_prefix_from_text(model, tokenizer, text=...)` + - `initialize_kv_prefix_from_past_key_values(model, past_key_values=...)` + + If you already have a flattened KV-prefix tensor, you can load it directly via the prompt encoder’s + `load_prompt_embeddings(...)` method. + + Args: + num_frozen_tokens (`int`, defaults to 1): + Number of *prefix* tokens at the start of the cartridge to keep frozen (no gradients). The Cartridges paper + recommends freezing the first token as an attention sink for stability (set this to `1`), as many LLMs use + early tokens as attention sinks and changing them can harm training. + """ + + num_frozen_tokens: int = field( + default=1, + metadata={ + "help": ( + "Number of initial virtual tokens to freeze (no gradients). The paper recommends freezing the first " + "token as an attention sink for stability." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + if self.num_frozen_tokens < 0: + raise ValueError(f"`num_frozen_tokens` must be >= 0, got {self.num_frozen_tokens}.") + # `num_virtual_tokens` is required for prompt-learning configs. Validate the relationship early for a clearer + # error, even if the encoder also checks it. + if (self.num_virtual_tokens is not None) and (self.num_frozen_tokens > self.num_virtual_tokens): + raise ValueError( + f"`num_frozen_tokens` must be <= `num_virtual_tokens`, got num_frozen_tokens={self.num_frozen_tokens} " + f"and num_virtual_tokens={self.num_virtual_tokens}." + ) + self.peft_type = PeftType.CARTRIDGE diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/model.py new file mode 100644 index 0000000000000000000000000000000000000000..bd0ad07ffeb9980759c16240b7d8ed51ad826da8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/model.py @@ -0,0 +1,116 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch + + +class CartridgeEncoder(torch.nn.Module): + """ + A parameterized prefix KV cache. + + The parameters are stored in the same flattened layout as `PrefixEncoder` output: `[num_virtual_tokens, num_layers + * 2 * token_dim]`, where `token_dim` is per-head hidden size times number of heads (after any GQA adjustment + performed by `_prepare_prompt_learning_config`). + + If `num_frozen_tokens > 0`, the first `num_frozen_tokens` virtual tokens are stored as a non-trainable parameter, + and the remaining tokens are trainable. + """ + + def __init__(self, config): + super().__init__() + self.config = config + + num_virtual_tokens = config.num_virtual_tokens + hidden = config.num_layers * 2 * config.token_dim + num_frozen_tokens = int(config.num_frozen_tokens) + if num_frozen_tokens < 0 or num_frozen_tokens > num_virtual_tokens: + raise ValueError( + f"`num_frozen_tokens` must be in [0, num_virtual_tokens], got {num_frozen_tokens} for " + f"num_virtual_tokens={num_virtual_tokens}." + ) + + self.num_frozen_tokens = num_frozen_tokens + self.num_trainable_tokens = num_virtual_tokens - num_frozen_tokens + + if self.num_frozen_tokens: + frozen = torch.empty(self.num_frozen_tokens, hidden) + self.frozen_embedding = torch.nn.Parameter(frozen, requires_grad=False) + else: + self.frozen_embedding = None + + trainable = torch.empty(self.num_trainable_tokens, hidden) + self.trainable_embedding = torch.nn.Parameter(trainable, requires_grad=not config.inference_mode) + + self.reset_parameters() + + @property + def embedding(self): + """ + Expose a prefix-encoder compatible interface (`.embedding.weight`) for PEFT internals. + """ + + class _Proxy(torch.nn.Module): + def __init__(self, parent: CartridgeEncoder): + super().__init__() + self._parent = parent + + @property + def weight(self): + return self._parent.weight + + return _Proxy(self) + + @property + def weight(self) -> torch.Tensor: + if self.frozen_embedding is None: + return self.trainable_embedding + return torch.cat([self.frozen_embedding, self.trainable_embedding], dim=0) + + def reset_parameters(self): + # Match `torch.nn.Embedding` initialization (normal with std=1). + with torch.no_grad(): + if self.frozen_embedding is not None: + torch.nn.init.normal_(self.frozen_embedding) + torch.nn.init.normal_(self.trainable_embedding) + + def load_prompt_embeddings(self, prompt_embeddings: torch.Tensor) -> None: + """ + Load the flattened prompt embeddings saved by PEFT (`prompt_embeddings`). + + PEFT saves prompt-learning adapters as a single `prompt_embeddings` tensor. For CARTRIDGE, we split that tensor + into frozen and trainable segments according to `self.num_frozen_tokens`. + """ + if prompt_embeddings.ndim != 2 or prompt_embeddings.shape[0] != ( + self.num_frozen_tokens + self.num_trainable_tokens + ): + raise ValueError( + "Invalid `prompt_embeddings` shape. Expected " + f"({self.num_frozen_tokens + self.num_trainable_tokens}, hidden), got {tuple(prompt_embeddings.shape)}." + ) + with torch.no_grad(): + if self.frozen_embedding is not None: + self.frozen_embedding.copy_( + prompt_embeddings[: self.num_frozen_tokens].to(self.frozen_embedding.device) + ) + trainable_part = prompt_embeddings[self.num_frozen_tokens :] + else: + trainable_part = prompt_embeddings + self.trainable_embedding.copy_(trainable_part.to(self.trainable_embedding.device)) + + def forward(self, prefix_tokens: torch.Tensor) -> torch.Tensor: + batch_size = prefix_tokens.shape[0] + # Ignore token ids; they exist for prompt-learning uniformity. + return self.weight.unsqueeze(0).expand(batch_size, -1, -1) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..cb0f08136c4f6a8973846e5e45654ed296d5f082 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cartridge/utils.py @@ -0,0 +1,237 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from collections.abc import Sequence +from dataclasses import replace +from pathlib import Path +from typing import Any, Optional + +import torch +from safetensors.torch import save_file + +from peft.config import PeftConfig +from peft.utils import PeftType +from peft.utils.constants import SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME +from peft.utils.save_and_load import load_peft_weights + + +def _to_legacy_past_key_values(past_key_values: Any): + # Support both legacy tuples and transformers.Cache-like objects. + if isinstance(past_key_values, (tuple, list)): + return past_key_values + to_legacy = getattr(past_key_values, "to_legacy_cache", None) + if callable(to_legacy): + return to_legacy() + if hasattr(past_key_values, "__iter__"): + legacy = list(past_key_values) + if legacy and isinstance(legacy[0], (tuple, list)) and len(legacy[0]) >= 2: + return [(layer[0], layer[1]) for layer in legacy] + raise TypeError( + "Unsupported `past_key_values` type. Expected a legacy tuple/list, an object with `to_legacy_cache()`, or an " + "iterable of (key, value) tuples." + ) + + +def prompt_embeddings_from_past_key_values( + past_key_values: Any, + *, + num_virtual_tokens: int, +) -> torch.Tensor: + """ + Convert a (legacy) `past_key_values` cache into the flattened prompt embeddings tensor saved by PEFT. + + The output matches the layout expected by `PeftModel.get_prompt()` for prefix-style prompt learning: shape + `[num_virtual_tokens, num_layers * 2 * token_dim]`. + """ + legacy = _to_legacy_past_key_values(past_key_values) + if len(legacy) == 0: + raise ValueError("Empty `past_key_values`.") + + # Each layer: (key, value), where key/value are [batch, num_heads, seq_len, head_dim] + num_layers = len(legacy) + key0, value0 = legacy[0] + if key0.ndim != 4: + raise ValueError(f"Expected key/value tensors with rank 4, got key.ndim={key0.ndim}.") + if key0.shape[0] != 1: + raise ValueError( + "This helper expects `past_key_values` from a single-sequence prefill (batch=1). " + f"Got batch={key0.shape[0]}." + ) + num_heads = key0.shape[1] + seq_len = key0.shape[2] + head_dim = key0.shape[3] + if seq_len < num_virtual_tokens: + raise ValueError(f"Need at least {num_virtual_tokens} cached tokens, got {seq_len}.") + + packed = torch.empty( + num_virtual_tokens, + num_layers * 2, + num_heads, + head_dim, + device=key0.device, + dtype=key0.dtype, + ) + for layer_idx, (k, v) in enumerate(legacy): + if k.shape[:2] != (1, num_heads) or v.shape[:2] != (1, num_heads): + raise ValueError("Inconsistent head shapes across layers in `past_key_values`.") + if k.shape[2] < num_virtual_tokens or v.shape[2] < num_virtual_tokens: + raise ValueError("Not enough cached tokens in `past_key_values` for the requested cartridge length.") + if k.shape[3] != head_dim or v.shape[3] != head_dim: + raise ValueError("Inconsistent head_dim across layers in `past_key_values`.") + packed[:, 2 * layer_idx] = k[0, :, :num_virtual_tokens, :].transpose(0, 1).contiguous() + packed[:, 2 * layer_idx + 1] = v[0, :, :num_virtual_tokens, :].transpose(0, 1).contiguous() + + return packed.reshape(num_virtual_tokens, -1) + + +@torch.no_grad() +def initialize_kv_prefix_from_past_key_values( + model, + *, + adapter_name: Optional[str] = None, + past_key_values: Any, + num_virtual_tokens: Optional[int] = None, +) -> torch.Tensor: + """ + Initialize a KV-prefix prompt-learning adapter from an existing cached prefix (`past_key_values`). + + Returns the prompt embeddings tensor that was loaded into the adapter. + """ + if adapter_name is None: + adapter_name = model.active_adapter + config = model.peft_config[adapter_name] + if config.peft_type not in (PeftType.CARTRIDGE, PeftType.PREFIX_TUNING): + raise ValueError( + f"Adapter '{adapter_name}' must be a CARTRIDGE or PREFIX_TUNING adapter (got {config.peft_type})." + ) + if getattr(config, "prefix_projection", False): + raise ValueError( + "Initialization from KV cache is not supported for prefix tuning with `prefix_projection=True`." + ) + if num_virtual_tokens is None: + num_virtual_tokens = config.num_virtual_tokens + + prompt_embeddings = prompt_embeddings_from_past_key_values(past_key_values, num_virtual_tokens=num_virtual_tokens) + model.prompt_encoder[adapter_name].load_prompt_embeddings(prompt_embeddings) + return prompt_embeddings + + +@torch.no_grad() +def initialize_kv_prefix_from_text( + model, + tokenizer, + *, + text: str, + adapter_name: Optional[str] = None, + num_virtual_tokens: Optional[int] = None, + use_chat_template: bool = True, + max_length: Optional[int] = None, +) -> torch.Tensor: + """ + Convenience initializer: prefill the base model on `text` and load the resulting cache prefix into the adapter. + """ + if adapter_name is None: + adapter_name = model.active_adapter + config = model.peft_config[adapter_name] + if config.peft_type not in (PeftType.CARTRIDGE, PeftType.PREFIX_TUNING): + raise ValueError( + f"Adapter '{adapter_name}' must be a CARTRIDGE or PREFIX_TUNING adapter (got {config.peft_type})." + ) + if getattr(config, "prefix_projection", False): + raise ValueError( + "Initialization from KV cache is not supported for prefix tuning with `prefix_projection=True`." + ) + if num_virtual_tokens is None: + num_virtual_tokens = config.num_virtual_tokens + + def _tokenize_plain(): + toks = tokenizer(text, return_tensors="pt", truncation=max_length is not None, max_length=max_length) + return toks["input_ids"] + + if use_chat_template and hasattr(tokenizer, "apply_chat_template"): + try: + input_ids = tokenizer.apply_chat_template( + [{"role": "system", "content": text}], + tokenize=True, + add_generation_prompt=False, + return_dict=False, + return_tensors="pt", + ) + except (TypeError, ValueError): + # Some tokenizers don't support the full signature or do not define a chat template. + input_ids = _tokenize_plain() + else: + if max_length is not None and input_ids.shape[1] > max_length: + input_ids = input_ids[:, :max_length] + else: + input_ids = _tokenize_plain() + + input_ids = input_ids.to(model.device) + attention_mask = torch.ones_like(input_ids) + with model.disable_adapter(): + outputs = model(input_ids=input_ids, attention_mask=attention_mask, use_cache=True) + return initialize_kv_prefix_from_past_key_values( + model, + adapter_name=adapter_name, + past_key_values=outputs.past_key_values, + num_virtual_tokens=num_virtual_tokens, + ) + + +def compose_cartridge_adapters( + adapter_paths: Sequence[str | Path], + *, + output_path: str | Path, + safe_serialization: bool = True, +) -> None: + """ + Compose multiple CARTRIDGE adapters by concatenating their prompt embeddings. + + This implements the paper's "composition via concatenation" behavior at the adapter level (no runtime + multi-adapter). + """ + adapter_paths = [Path(p) for p in adapter_paths] + if len(adapter_paths) < 2: + raise ValueError("Need at least 2 adapters to compose.") + + configs = [PeftConfig.from_pretrained(str(p)) for p in adapter_paths] + for p, cfg in zip(adapter_paths, configs): + if cfg.peft_type != PeftType.CARTRIDGE: + raise ValueError(f"Adapter at '{p}' is not a CARTRIDGE adapter (got {cfg.peft_type}).") + + base = configs[0] + for cfg in configs[1:]: + for attr in ("task_type", "token_dim", "num_layers", "num_attention_heads", "num_transformer_submodules"): + if getattr(cfg, attr, None) != getattr(base, attr, None): + raise ValueError(f"Incompatible CARTRIDGE configs for attribute '{attr}'.") + + weights = [load_peft_weights(str(p), device="cpu") for p in adapter_paths] + prompt_embeddings = [w["prompt_embeddings"] for w in weights] + composed = torch.cat(prompt_embeddings, dim=0) + + num_virtual_tokens = composed.shape[0] + # Preserve the "frozen prefix tokens" count of the first adapter only (matches a single attention-sink prefix). + num_frozen_tokens = base.num_frozen_tokens + out_cfg = replace(base, num_virtual_tokens=num_virtual_tokens, num_frozen_tokens=num_frozen_tokens) + + output_path = Path(output_path) + output_path.mkdir(parents=True, exist_ok=True) + out_cfg.save_pretrained(str(output_path)) + + if safe_serialization: + save_file({"prompt_embeddings": composed}, str(output_path / SAFETENSORS_WEIGHTS_NAME)) + else: + torch.save({"prompt_embeddings": composed}, str(output_path / WEIGHTS_NAME)) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fcd4de85989168ad6834712679c805cba39c1df1 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from peft.utils import register_peft_method + +from .config import CPTConfig +from .model import CPTEmbedding + + +__all__ = ["CPTConfig", "CPTEmbedding"] + +register_peft_method(name="cpt", config_cls=CPTConfig, model_cls=CPTEmbedding) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d23b0acc650ed1aae04d43cdcb53a4f7613389f4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/config.py @@ -0,0 +1,99 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Literal, Optional + +from peft.config import PromptLearningConfig +from peft.utils import PeftType, TaskType + + +@dataclass +class CPTConfig(PromptLearningConfig): + """ + CPT Configuration class extending PeftConfig for Context-aware Prompt Tuning (CPT). + + This class introduces additional parameters required for CPT, such as: + - Token type masks + - Prompt tuning initialization + - Loss weighting + - Projection settings + + For more details, see the paper: https://huggingface.co/papers/2410.17222 + """ + + # Token-related configurations + cpt_token_ids: Optional[list[int]] = field( + default=None, metadata={"help": "Tensor of token IDs used for CPT prompts."} + ) + cpt_mask: Optional[list[int]] = field(default=None, metadata={"help": "Tensor mask applied to CPT tokens."}) + cpt_tokens_type_mask: Optional[list[int]] = field( + default=None, metadata={"help": "Mask indicating the type of each CPT token."} + ) + + # Loss-related configurations + opt_weighted_loss_type: Optional[Literal["none", "decay"]] = field( + default="none", metadata={"help": "Type of weighted loss: 'none' or 'decay'."} + ) + opt_loss_decay_factor: Optional[float] = field( + default=1.0, metadata={"help": "Factor for exponential decay in loss weighting."} + ) + + # Projection-related configurations + opt_projection_epsilon: Optional[float] = field( + default=0.1, metadata={"help": "Epsilon value for input projection."} + ) + opt_projection_format_epsilon: Optional[float] = field( + default=0.1, metadata={"help": "Epsilon value for format projection."} + ) + + # Tokenizer configuration + tokenizer_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": "The tokenizer to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`" + }, + ) + # Neet to define CPT-specific static attributes + is_prompt_learning = True # Indicates that CPT is a prompt-learning method. + + def __post_init__(self): + """ + Post-initialization hook to set additional attributes after the config is initialized. + """ + # CPT-specific static attributes + self.is_prompt_learning = True # Indicates that CPT is a prompt-learning method. + self.num_layers = None # Number of layers (optional, not always required). + self.token_dim = None # Dimension of token embeddings. + self.num_attention_heads = None # Number of attention heads (if applicable). + self.num_transformer_submodules = 1 # Number of transformer submodules used. + self.peft_type = PeftType.CPT # Specifies that the PEFT type is CPT. + if self.task_type != TaskType.CAUSAL_LM: + raise ValueError(f"{self.__class__.__name__} only supports task_type = {TaskType.CAUSAL_LM.value}.") + + if self.cpt_token_ids is None: + self.cpt_token_ids = [0] + + self.num_virtual_tokens = len(self.cpt_token_ids) + + if self.cpt_mask is None: + self.cpt_mask = [1 for _ in self.cpt_token_ids] + + if self.cpt_tokens_type_mask is None: + self.cpt_tokens_type_mask = [1 for _ in self.cpt_token_ids] + + if not ( + len(self.cpt_token_ids) == len(self.cpt_mask) == len(self.cpt_tokens_type_mask) == self.num_virtual_tokens + ): + raise ValueError("cpt_token_ids, cpt_mask and cpt_tokens_type_mask must have the same length.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/model.py new file mode 100644 index 0000000000000000000000000000000000000000..6c4dc08e5153b38827e638691f315abc432cd5dc --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/cpt/model.py @@ -0,0 +1,202 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy + +import torch +from torch.nn import CrossEntropyLoss + +from peft.utils.integrations import gather_params_ctx + + +class CPTEmbedding(torch.nn.Module): + """ + CPTEmbedding is a custom embedding layer designed for Context-aware Prompt Tuning (CPT) in PEFT. It initializes + embeddings, applies prompt-specific projections, and computes loss using label masks. + """ + + def __init__(self, config, word_embeddings): + """ + Initializes the CPTEmbedding module. + + Args: + config (Namespace): + Configuration object containing model hyperparameters and CPT-specific settings. + word_embeddings (torch.nn.Embedding): + The base word embedding layer used to initialize CPT embeddings. + """ + super().__init__() + self.config = copy.deepcopy(config) + num_virtual_tokens = config.num_virtual_tokens + + # Initialize embeddings with virtual token dimensions + self.embedding = torch.nn.Embedding(num_virtual_tokens, config.token_dim) + + # Initialize embeddings using text-based prompt tuning, if configured + if not config.inference_mode: + assert config.num_virtual_tokens == len(config.cpt_token_ids) + + init_token_ids = torch.LongTensor(config.cpt_token_ids).to(word_embeddings.weight.device) + with gather_params_ctx(word_embeddings.parameters()): + word_embedding_weights = word_embeddings(init_token_ids).detach().clone() + word_embedding_weights = word_embedding_weights.to(torch.float32) + self.embedding.weight = torch.nn.Parameter(word_embedding_weights) + + self.embedding.requires_grad_(False) + + # Initialize delta embedding with zero weights + self.delta_embedding = torch.nn.Embedding(num_virtual_tokens, config.token_dim) + self.delta_embedding.weight.data = torch.zeros_like(self.delta_embedding.weight).to(torch.float32) + + # Apply hook for backward gradient updates + self.set_updated_tokens() + + def forward(self, indices): + """ + Computes the prompt embeddings and applies delta adjustments. + + Args: + indices (torch.Tensor): + Indices of the tokens to be embedded. + + Returns: + torch.Tensor: + Sum of prompt embeddings and delta embeddings. + """ + with torch.no_grad(): + prompt_embeddings = self.embedding(indices) + + self.delta_embedding.weight.data = self.get_projection() # Apply epsilon-based projection + + delta_prompt_embeddings = self.delta_embedding(indices) + + return prompt_embeddings + delta_prompt_embeddings + + def set_updated_tokens(self): + """ + Sets up a backward hook to selectively update token gradients based on the CPT token type mask. + """ + tensor_ICL_mask = torch.Tensor(self.config.cpt_tokens_type_mask).long() + mask_input_template = torch.remainder(tensor_ICL_mask, 4) == 1 + mask_input = torch.remainder(tensor_ICL_mask, 4) == 2 + mask_output_template = torch.remainder(tensor_ICL_mask, 4) == 3 + mask = mask_input_template | mask_input | mask_output_template + mask = mask.view(-1, 1) + + def backward_hook(grad): + grad = grad * mask.to(grad.device) # Apply mask to gradients + return grad + + self.delta_embedding.weight.register_hook(backward_hook) + + def get_epsilon(self): + cpt_tokens_type_mask = self.config.cpt_tokens_type_mask + + MIN_VALUE = 1e-10 + + # Calculate normalized epsilon values for input, output, and format tokens + normalized_format_eps = self.config.opt_projection_format_epsilon * torch.sqrt( + torch.Tensor([self.config.token_dim / 2048]) + ) + normalized_input_eps = self.config.opt_projection_epsilon * torch.sqrt( + torch.Tensor([self.config.token_dim / 2048]) + ) + + epsilon = torch.ones_like(torch.Tensor(cpt_tokens_type_mask)).to(torch.float32) * MIN_VALUE + cpt_tokens_type_mask = torch.Tensor(cpt_tokens_type_mask).long() + + epsilon[(cpt_tokens_type_mask > 0) & (torch.remainder(cpt_tokens_type_mask, 4) == 1)] = normalized_format_eps + epsilon[(cpt_tokens_type_mask > 0) & (torch.remainder(cpt_tokens_type_mask, 4) == 3)] = normalized_format_eps + epsilon[(cpt_tokens_type_mask > 0) & (torch.remainder(cpt_tokens_type_mask, 4) == 2)] = normalized_input_eps + + return epsilon + + def get_projection(self): + """ + Applies epsilon-based projection to the delta embeddings to control their norm. + """ + + # Apply projection to control delta embedding norm + with torch.no_grad(): + new_embeddings_weights = self.delta_embedding.weight.clone().to(self.delta_embedding.weight.device) + token_norm = torch.norm(new_embeddings_weights, p=2, dim=1) + + projection_mask = token_norm > 0 + if torch.any(projection_mask): + epsilon = self.get_epsilon().to(self.delta_embedding.weight.device) + new_embeddings_weights[projection_mask] *= ( + epsilon[projection_mask] / (token_norm[projection_mask].clamp(min=epsilon[projection_mask])) + ).view(-1, 1) + return new_embeddings_weights + + @staticmethod + def calculate_loss(base_model_output, labels, cpt_type_mask, config): + """ + Computes the loss for CPT models with optional exponential decay. + + Args: + base_model_output (ModelOutput): + Output from the base model containing logits. + labels (torch.Tensor): + Ground-truth labels for the input tokens. + cpt_type_mask (torch.Tensor): + Token type mask used for filtering valid loss terms. + config (Namespace): + Configuration object containing loss-related hyperparameters. + + Returns: + ModelOutput: + The base model output with computed loss. + """ + + device = base_model_output.logits.device + + lm_logits = base_model_output.logits + labels = labels.to(device) + + # Shift logits and labels for token prediction + shift_logits = lm_logits[..., :-1, :].contiguous() + shift_labels = labels[..., 1:].contiguous() + shift_cpt_type_mask = cpt_type_mask[..., 1:].contiguous() + + shift_labels_bool = (shift_labels.clone().detach() != -100).bool() + batch_size, seq_length, vocab_size = shift_logits.shape + + # Compute cross-entropy loss + loss_fct = CrossEntropyLoss(reduction="none", ignore_index=-100) + loss = loss_fct( + shift_logits.view(batch_size * seq_length, vocab_size), shift_labels.view(batch_size * seq_length) + ) + loss = loss.view(batch_size, seq_length) + # Apply exponential decay weights to the loss + shift_labels_weights = shift_labels_bool.clone().detach().float() + + for i in range(batch_size): + idx_labels = (shift_cpt_type_mask[i] > 0) & (shift_cpt_type_mask[i] % 4 == 0) + labels_ids = shift_cpt_type_mask[i][idx_labels].unique() + + exponential_decay = torch.ones_like(shift_cpt_type_mask[i]).to(device=device).float() + decay_value = 1 + for label_mask_idx in torch.flip(labels_ids, [0]): + exponential_decay[shift_cpt_type_mask[i] == label_mask_idx] = decay_value + decay_value *= config.opt_loss_decay_factor + if config.opt_weighted_loss_type == "decay": + shift_labels_weights[i] *= exponential_decay + + # Compute the weighted mean loss + loss = (loss[shift_labels_bool] * shift_labels_weights[shift_labels_bool]).mean() + + base_model_output.loss = loss + + return base_model_output diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..982801ca5665621e50cda5c6540203fdaa29f34c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from peft.utils import register_peft_method + +from .config import DeloraConfig +from .layer import DeloraLayer, DeloraLinear +from .model import DeloraModel + + +__all__ = ["DeloraConfig", "DeloraLayer", "DeloraLinear", "DeloraModel"] + +register_peft_method(name="delora", model_cls=DeloraModel, config_cls=DeloraConfig) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..0a28cc94befe12ea8c30bece2c69f96dcef30006 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/config.py @@ -0,0 +1,154 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class DeloraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`DeloraModel`]. + + Args: + r (`int`): + The rank of the DeLoRA adapter. + delora_lambda (`int`): + The initial value of the boundary of the DeLoRA adapter. This variable sets an upper bound to the Frobenius + norm of the weight change, avoiding the finetuned model to deviate too much from the original model. + module_dropout (`float`): + The dropout probability for disabling DeLoRA modules during training. + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen, + excluding the output layer. If this is not specified, modules will be chosen according to the model + architecture. If the architecture is not known, an error will be raised -- in this case, you should specify + the target modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + bias (`str`): + Bias type for DeLoRA. Can be 'none', 'all' or 'delora_only'. If 'all' or 'delora_only', the corresponding + biases will be updated during training. Be aware that this means that, even when disabling the adapters, + the model will not produce the same output as the base model would have without adaptation. + init_weights (`bool`): + Whether to perform initialization of adapter weights. If `True` (default): A is initialized with kaiming + uniform initialization, while B is initialized with zeros. If `False`: A and B are both initialized with + kaiming uniform, immediately contributing a non-zero delta. This is generally discouraged for normal use. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + lambda_pattern (`dict`): + The mapping from layer names or regexp expression to lambdas which are different from the default lambda + specified by `delora_lambda`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field(default=8, metadata={"help": "DeLoRA rank"}) + delora_lambda: int = field( + default=15, + metadata={ + "help": "The initial value of the boundary of the DeLoRA adapter. This variable sets an upper bound to the " + "Frobenius norm of the weight change, avoiding the finetuned model to deviate too much from the original model." + }, + ) + module_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for disabling DeLoRA modules during training"} + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with DeLoRA." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + "This can also be a wildcard 'all-linear' which matches all linear layers except the output layer." + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from DeLoRA."}, + ) + bias: str = field(default="none", metadata={"help": "Bias type for DeLoRA. Can be 'none' or 'all'"}) + init_weights: bool = field( + default=True, + metadata={ + "help": "Whether to perform initialization of adapter weights. If `True` (default): A is initialized with kaiming uniform " + "initialization, while B is initialized with zeros. If `False`: A and B are both initialized with kaiming uniform, " + "immediately contributing a non-zero delta. This is generally discouraged for normal use." + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that " + "are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the " + "common layers pattern. This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + }, + ) + rank_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": "The mapping from layer names or regexp expression to ranks which are different from the default rank specified " + "by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + }, + ) + lambda_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": "The mapping from layer names or regexp expression to lambdas which are different from the default lambda specified by `delora_lambda`." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from DeLoRA layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, the final layer `classifier/score` " + "are randomly initialized and as such need to be trainable and saved." + }, + ) + + def __post_init__(self): + super().__post_init__() + # PeftType enum members are uppercase; use DELORA + self.peft_type = PeftType.DELORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..b5e26d2946b1c219d21340293246e1974feb971a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/layer.py @@ -0,0 +1,272 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import math +import warnings +from typing import Any, Optional + +import torch +import torch.nn as nn + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + + +class DeloraLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ( + "delora_A", + "delora_B", + "delora_lambda", + ) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ( + "r", + "delora_dropout", + "delora_w_norm", + ) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.delora_dropout = nn.ModuleDict({}) + self.delora_A = nn.ParameterDict({}) + self.delora_B = nn.ParameterDict({}) + self.delora_lambda = nn.ParameterDict({}) + # Use persistent buffers so they are included in state_dict and saved. + self.delora_w_norm = BufferDict({}, persistent=True) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer_mod = self.get_base_layer() + if isinstance(base_layer_mod, nn.Linear): + self.in_features, self.out_features = base_layer_mod.in_features, base_layer_mod.out_features + else: + raise ValueError(f"Unsupported layer type {type(base_layer_mod)}") + + @staticmethod + def _compute_delta( + A: torch.Tensor, B: torch.Tensor, delora_lambda: torch.Tensor, r: int, w_norm: torch.Tensor + ) -> torch.Tensor: + """Compute delta = B @ diag(delora_lambda/r / (||A_i||*||B^j||)) @ A, scaled by provided w_norm (per-input channel)""" + An = torch.clamp(A.norm(dim=1), min=1e-4) + Bn = torch.clamp(B.norm(dim=0), min=1e-4) + diag = torch.diag_embed(delora_lambda / r / (An * Bn)) + delta = B @ diag @ A + delta = delta * w_norm.unsqueeze(0) + return delta + + def get_delta_weight(self, adapter: str) -> torch.Tensor: + if adapter not in self.delora_A or adapter not in self.delora_B: + raise ValueError(f"Adapter {adapter} not found.") + + delta = self._compute_delta( + self.delora_A[adapter], + self.delora_B[adapter], + self.delora_lambda[adapter], + self.r[adapter], + self.delora_w_norm[adapter], + ) + return delta + + def update_layer( + self, + adapter_name: str, + r: int, + delora_lambda: float, + module_dropout: float, + init_weights: bool = True, + inference_mode: bool = False, + **kwargs: Any, + ) -> None: + """Internal function to create delora adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + delora_lambda (`float`): Boundary for the adapter's norm. + module_dropout (`float`): The dropout probability for disabling adapter during training. + init_weights (`bool`): Whether to initialize weights. + """ + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.r[adapter_name] = r + self.delora_A[adapter_name] = nn.Parameter(torch.empty(r, self.in_features)) + self.delora_B[adapter_name] = nn.Parameter(torch.empty(self.out_features, r)) + self.delora_lambda[adapter_name] = nn.Parameter(torch.empty(1)) + if module_dropout > 0.0: + module_dropout_layer = nn.Dropout(p=module_dropout) + else: + module_dropout_layer = nn.Identity() + self.delora_dropout.update(nn.ModuleDict({adapter_name: module_dropout_layer})) + + # Initialize weights + self.reset_delora_parameters(adapter_name, init_weights, delora_lambda) + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_delora_parameters( + self, + adapter_name: str, + init_weights: bool = True, + delora_lambda: float = 15.0, + ) -> None: + if adapter_name not in self.delora_A.keys(): + return + + if init_weights is True: + nn.init.kaiming_uniform_(self.delora_A[adapter_name], a=math.sqrt(5)) + nn.init.zeros_(self.delora_B[adapter_name]) + else: + nn.init.kaiming_uniform_(self.delora_A[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.delora_B[adapter_name], a=math.sqrt(5)) + + self.delora_lambda[adapter_name].data.fill_(float(delora_lambda)) + + # capture a fixed norm for this adapter to use for future delta computations + with torch.no_grad(): + w = self.get_base_layer().weight + if w.device.type != "meta": + w_norm = torch.norm(w.data, dim=0).detach() + else: + # For meta tensors, we can't compute the norm, so use a default value + w_norm = torch.ones(w.shape[1], device=w.device) + self.delora_w_norm[adapter_name] = w_norm + + +class DeloraLinear(nn.Module, DeloraLayer): + # DeLoRA implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + r: int, + delora_lambda: float, + module_dropout: float, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + DeloraLayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, delora_lambda, module_dropout, init_weights) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter in self.delora_A.keys(): + base_layer = self.get_base_layer() + delta_weight = ( + self.get_delta_weight(active_adapter) + .detach() + .to(dtype=base_layer.weight.dtype, device=base_layer.weight.device) + ) + with torch.no_grad(): + if safe_merge: + orig_weights = base_layer.weight.data.clone() + orig_weights = orig_weights + delta_weight + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data.add_(delta_weight) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + Unmerge all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.delora_A.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + if not self.active_adapters: + return self.base_layer(x, *args, **kwargs).to(previous_dtype) + + base_out = self.base_layer(x, *args, **kwargs) + add_out = torch.zeros_like(base_out) + + for adapter in self.active_adapters: + if adapter not in self.delora_A: + continue + + x_d = self.delora_dropout[adapter](x) + + # Decomposed delta calculation + # 1. (x * w_norm) @ A.T + h = nn.functional.linear(x_d * self.delora_w_norm[adapter], self.delora_A[adapter]) + + # 2. h @ diag + An = torch.clamp(self.delora_A[adapter].norm(dim=1), min=1e-4) + Bn = torch.clamp(self.delora_B[adapter].norm(dim=0), min=1e-4) + scaling = (self.delora_lambda[adapter] / self.r[adapter]) / (An * Bn) + + h = h * scaling + + # 3. h @ B.T + h = nn.functional.linear(h, self.delora_B[adapter]) + + add_out += h + + result = base_out + add_out.to(base_out.dtype) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "delora." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..04492c351c72660ebac4f9c2288004907ee6f1c4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/delora/model.py @@ -0,0 +1,105 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, +) +from peft.utils.other import get_pattern_key + +from .config import DeloraConfig +from .layer import DeloraLayer, DeloraLinear + + +class DeloraModel(BaseTuner): + """ + Creates DeLoRA model from a pretrained transformers model. + + The method is described in detail in [TODO]. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`DeloraConfig`]): The configuration of the DeLoRA model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The DeLoRA model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`DeloraConfig`]): The configuration of the DeLoRA model. + """ + + prefix: str = "delora_" + tuner_layer_cls = DeloraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING + + def _check_new_adapter_config(self, config: DeloraConfig) -> None: + """ + A helper method to check the config when a new adapter is being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + super()._check_new_adapter_config(config) + + def _create_and_replace( + self, + delora_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Regexp matching - Find key which matches current target_name in patterns provided + r_key = get_pattern_key(delora_config.rank_pattern.keys(), current_key) + lambda_key = get_pattern_key(delora_config.lambda_pattern.keys(), current_key) + r = delora_config.rank_pattern.get(r_key, delora_config.r) + delora_lambda = delora_config.lambda_pattern.get(lambda_key, delora_config.delora_lambda) + + kwargs = { + "r": r, + "delora_lambda": delora_lambda, + "module_dropout": delora_config.module_dropout, + "init_weights": delora_config.init_weights, + } + + if isinstance(target, DeloraLinear): + target.update_layer(adapter_name, **kwargs) + else: + new_module = self._create_new_module(delora_config, adapter_name, target, **kwargs) + if adapter_name != self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(delora_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + new_module = DeloraLinear(target, adapter_name, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dfe3f5d89e36123eefef7fc6e675c6b80bd8d44c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import FourierFTConfig +from .layer import FourierFTLayer, FourierFTLinear +from .model import FourierFTModel + + +__all__ = ["FourierFTConfig", "FourierFTLayer", "FourierFTLinear", "FourierFTModel"] + +register_peft_method(name="fourierft", model_cls=FourierFTModel, config_cls=FourierFTConfig) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..dbbb80d8e080e9237b711473b44d55f6ff186239 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/config.py @@ -0,0 +1,206 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class FourierFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`FourierFTModel`]. + + Args: + n_frequency (`int`): + Num of learnable frequencies for the Discrete Fourier Transform. 'n_frequency' is an integer that is + greater than 0 and less than or equal to d^2 (assuming the weight W has dimensions of d by d). + Additionally, it is the number of trainable parameters required to update each delta W weight. + 'n_frequency' will affect the performance and efficiency for PEFT. Specifically, it has little impact on + training speed, but higher values of it (typically) result in larger GPU memory costs and better accuracy. + With the same `target_modules`, the number of parameters of LoRA is (2*d*r/n_frequency) times that of + FourierFT. The following examples of settings regarding 'n_frequency' can be used as reference for users. + For NLU tasks with the RoBERTa-large model, adopting 'n_frequency': 1000 can almost achieve similar results + as 'r': 8 in LoRA. At this time, the number of parameters of LoRA is about 16 times that of FourierFT. For + image classification tasks with Vit-large models, adopting 'n_frequency': 3000 can almost achieve similar + results as 'r': 16 in LoRA, where the number of parameters of LoRA is about 11 times that of FourierFT. + scaling (`float`): + The scaling value for the delta W matrix. This is an important hyperparameter used for scaling, similar to + the 'lora_alpha' parameter in the LoRA method. 'scaling' can be determined during the hyperparameter search + process. However, if users want to skip this process, one can refer to the settings in the following + scenarios. This parameter can be set to 100.0 or 150.0 for both RoBERTa-base and RoBERTa-large models + across all NLU (GLUE) tasks. This parameter can be set to 300.0 for both LLaMA family models for all + instruction tuning. This parameter can be set to 300.0 for both ViT-base and ViT-large models across all + image classification tasks. + random_loc_seed (`int`): + Seed for the random location of the frequencies, i.e., the spectral entry matrix. + target_modules (`Union[list[str],str]`): + List of module names or regex expression of the module names to replace with FourierFT. For example, ['q', + 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. Only linear layers are supported. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). + bias (`str`): + Bias type for FourierFT. Can be 'none', 'all' or 'fourier_only'. + modules_to_save (`list[str]`): + List of modules apart from FourierFT layers to be set as trainable and saved in the final checkpoint. For + example, in Sequence Classification or Token Classification tasks, the final layer `classifier/score` are + randomly initialized and as such need to be trainable and saved. + layers_to_transform (`Union[list[int],int]`): + The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes + that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at + this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is + not in the common layers pattern. This should target the `nn.ModuleList` of the model, which is often + called `'layers'` or `'h'`. + n_frequency_pattern (`dict`): + The mapping from layer names or regexp expression to n_frequency which are different from the default + specified. For example, `{model.decoder.layers.0.encoder_attn.k_proj: 1000`}. + init_weights (`bool`): + The initialization of the Fourier weights. Set this to False (the default) if the spectrum are initialized + to a standard normal distribution. Set this to True if the spectrum are initialized to zeros. + """ + + n_frequency: int = field( + default=1000, + metadata={ + "help": ( + "Num of learnable frequencies for the Discrete Fourier Transform. 'n_frequency' is an integer that is" + "greater than 0 and less than or equal to d^2 (assuming the weight W has dimensions of d by d)." + "Additionally, it is the number of trainable parameters required to update each delta W weight." + "'n_frequency' will affect the performance and efficiency for PEFT. Specifically, it has little impact on" + "training speed, but higher values of it (typically) result in larger GPU memory costs and better accuracy." + "With the same `target_modules`, the number of parameters of LoRA is (2*d*r/n_frequency) times that of FourierFT." + "The following examples of settings regarding 'n_frequency' can be used as reference for users. For NLU" + "tasks with the RoBERTa-large model, adopting 'n_frequency': 1000 can almost achieve similar results as" + "'r': 8 in LoRA. At this time, the number of parameters of LoRA is about 16 times that of FourierFT." + "For image classification tasks with Vit-large models, adopting 'n_frequency': 3000 can almost achieve" + "similar results as 'r': 16 in LoRA, where the number of parameters of LoRA is about 11 times that of FourierFT." + ) + }, + ) + scaling: float = field( + default=150.0, + metadata={ + "help": ( + "The scaling value for the delta W matrix. This is an important hyperparameter used for scaling, similar to the" + "'lora_alpha' parameter in the LoRA method. 'scaling' can be determined during the hyperparameter search process." + "However, if users want to skip this process, one can refer to the settings in the following scenarios." + "This parameter can be set to 100.0 or 150.0 for both RoBERTa-base and RoBERTa-large models across all NLU (GLUE) tasks." + "This parameter can be set to 300.0 for both LLaMA family models for all instruction tuning." + "This parameter can be set to 300.0 for both ViT-base and ViT-large models across all image classification tasks." + ) + }, + ) + random_loc_seed: Optional[int] = field( + default=777, metadata={"help": "Seed for the random location of the frequencies."} + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with FourierFT." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from fourierft."}, + ) + bias: str = field( + default="none", metadata={"help": "Bias type for FourierFT. Can be 'none', 'all' or 'fourier_only'."} + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from FourierFT layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers" + " indexes that are specified inside this list. If a single integer is passed, PEFT will transform only" + " the layer at this index." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer" + " pattern is not in the common layers pattern. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + ) + }, + ) + n_frequency_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to n_frequency which are different from the default specified." + "For example, `{model.decoder.layers.0.encoder_attn.k_proj: 500`}." + ) + }, + ) + init_weights: bool = field( + default=False, + metadata={ + "help": ( + "The initialization of the Fourier weights. Set this to False (the default) if the spectrum should be " + "initialized to a standard normal distribution. Set this to True if the spectrum should be initialized " + "to zeros." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.FOURIERFT + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..774595eeb6418eb0db0dae1643457a9a2a06bef5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/layer.py @@ -0,0 +1,200 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + + +class FourierFTLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("fourierft_spectrum",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("fourierft_n_frequency", "fourierft_scaling", "fourierft_random_loc_seed") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.fourierft_n_frequency = {} + self.fourierft_scaling = {} + self.fourierft_spectrum = nn.ParameterDict({}) + self.indices = {} + self.fourierft_random_loc_seed = {} + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + self.in_features, self.out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + def update_layer( + self, adapter_name, n_frequency, scaling, init_weights, random_loc_seed, inference_mode: bool = False, **kwargs + ): + if n_frequency <= 0: + raise ValueError(f"`n_frequency` should be a positive integer value but the value passed is {n_frequency}") + if n_frequency > self.in_features * self.out_features: + raise ValueError( + f"`n_frequency` should be less than or equal to the product of the input and output dimensions " + f"but the value passed is {n_frequency} and the product is {self.in_features * self.out_features}" + ) + self.fourierft_n_frequency[adapter_name] = n_frequency + self.fourierft_random_loc_seed[adapter_name] = random_loc_seed + self.indices[adapter_name] = torch.randperm( + self.out_features * self.in_features, + generator=torch.Generator().manual_seed(self.fourierft_random_loc_seed[adapter_name]), + )[:n_frequency] + self.indices[adapter_name] = torch.stack( + [self.indices[adapter_name] // self.in_features, self.indices[adapter_name] % self.in_features], dim=0 + ) + self.fourierft_scaling[adapter_name] = scaling + # Actual trainable parameters + self.fourierft_spectrum[adapter_name] = nn.Parameter(torch.randn(n_frequency), requires_grad=True) + + if init_weights: + self.reset_fourier_parameters(adapter_name) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + @torch.no_grad() + def reset_fourier_parameters(self, adapter_name): + if adapter_name in self.fourierft_spectrum.keys(): + nn.init.zeros_(self.fourierft_spectrum[adapter_name]) + + def get_delta_weight(self, adapter) -> torch.Tensor: + # careful: ifft2 does not work with float16 or bfloat16 + spectrum = self.fourierft_spectrum[adapter] + indices = self.indices[adapter].to(spectrum.device) + dense_spectrum = torch.zeros(self.out_features, self.in_features, device=spectrum.device) + dense_spectrum[indices[0, :], indices[1, :]] = spectrum.float() + delta_weight = torch.fft.ifft2(dense_spectrum).real * self.fourierft_scaling[adapter] + return delta_weight.to(spectrum.dtype) + + +class FourierFTLinear(nn.Module, FourierFTLayer): + # FourierFT implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + n_frequency: int = 1000, + scaling: float = 150.0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: Union[bool, str] = False, + random_loc_seed: int = 777, + **kwargs, + ) -> None: + super().__init__() + FourierFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, n_frequency, scaling, init_weights, random_loc_seed) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.fourierft_spectrum.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + orig_weights += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.fourierft_spectrum.keys(): + self.get_base_layer().weight.data -= transpose( + self.get_delta_weight(active_adapter), self.fan_in_fan_out + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.fourierft_spectrum.keys(): + continue + + delta_w = self.get_delta_weight(active_adapter) + x = x.to(delta_w.dtype) + result = result + F.linear(x, delta_w) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + if isinstance(self.get_base_layer(), Conv1D): + # get_delta_weight does not transpose Conv1D because it is used in forward, therefore, it has the wrong + # shape for conversion + return False + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "fourierft." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..5347d90b1777fcef235215c15999d6b39fd09ede --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/fourierft/model.py @@ -0,0 +1,128 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import re +import warnings +from itertools import chain + +import torch +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, +) + +from .layer import FourierFTLayer, FourierFTLinear + + +class FourierFTModel(BaseTuner): + """ + Creates FourierFT model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2405.03003. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`FourierFTConfig`]): The configuration of the FourierFT model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The FourierFT model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`FourierFTConfig`]): The configuration of the Fourier model. + """ + + prefix: str = "fourierft_" + tuner_layer_cls = FourierFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + fourierft_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + # Regexp matching - Find key which matches current target_name in patterns provided + pattern_keys = list(chain(fourierft_config.n_frequency_pattern.keys())) + target_name_key = next(filter(lambda key: re.match(rf".*\.{key}$", current_key), pattern_keys), current_key) + + n_frequency = fourierft_config.n_frequency_pattern.get(target_name_key, fourierft_config.n_frequency) + scaling = fourierft_config.scaling + random_loc_seed = fourierft_config.random_loc_seed + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "n_frequency": n_frequency, + "scaling": scaling, + "fan_in_fan_out": fourierft_config.fan_in_fan_out, + "init_weights": fourierft_config.init_weights, + "random_loc_seed": fourierft_config.random_loc_seed, + } + kwargs["bias"] = bias + if isinstance(target, FourierFTLayer): + target.update_layer( + adapter_name, + n_frequency, + scaling, + fourierft_config.init_weights, + random_loc_seed, + ) + else: + new_module = self._create_new_module(fourierft_config, adapter_name, target, **kwargs) + if adapter_name != self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(fourierft_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = fourierft_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = fourierft_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + new_module = FourierFTLinear(target, adapter_name, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..830e0a477c45632ebe83b0be2b15c816e9087160 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import GraloraConfig +from .layer import GraloraLayer +from .model import GraloraModel + + +__all__ = ["GraloraConfig", "GraloraLayer", "GraloraModel"] + +register_peft_method(name="gralora", config_cls=GraloraConfig, model_cls=GraloraModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..39f6c1b0b91ebb7051a834caa9a33e1930435f27 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/config.py @@ -0,0 +1,182 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class GraloraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`GraloraModel`]. + + Args: + r (`int`): + GraLoRA attention dimension determines the rank of the GraLoRA adapter. The total parameter count of the + GraLoRA adapter is same as LoRA with same rank r, while the expressivitiy is multiplied by gralora_k. + hybrid_r (`int`): + Hybrid GraLoRA rank determines the rank allocated to vanilla LoRA method when using Hybrid GraLoRA method. + Hybrid GraLoRA, a combination of GraLoRA and vanilla LoRA, becomes available when hybrid_r > 0. The + parameter count of the GraLoRA adapter is r + hybrid_r. + target_modules (`Union[List[str], str]`): + List of module names or regex expression of the module names to replace with GraLoRA. " For example, ['q', + 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " This can also be a wildcard 'all-linear' + which matches all linear/Conv1D " "(if the model is a PreTrainedModel, the output layer excluded). " If not + specified, modules will be chosen according to the model architecture, If the architecture is " not known, + an error will be raised -- in this case, you should specify the target modules manually. " To avoid + targeting any modules (because you want to apply `target_parameters`), set " `target_modules=[]`. + alpha (`int`): GraLoRA alpha. + GraLoRA alpha is the scaling factor for the GraLoRA adapter. Scale becomes alpha / (r + hybrid_r). + gralora_dropout (`float`): + GraLoRA dropout is the dropout probability for the GraLoRA adapter. It is used to prevent overfitting and + improve the generalization of the GraLoRA adapter. + gralora_k (`int`): + GraLoRA k determines the number of subblocks in the GraLoRA adapter. The rank r must be divisible by + gralora_k for the GraLoRA adapter to be valid. The total parameter count is preserved regardles of + gralora_k. The entire rank of the GraLoRA adapter is increased by gralora_k, while the rank of each + subblock is reduced by gralora_k. gralora_k=2 is recommended for rank 32 or lower, and gralora_k=4 is + recommended for rank 64 or higher. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + bias (`str`): + Bias type for gralora. Can be 'none', 'all' or 'gralora_only'. If 'all' or 'gralora_only', the + corresponding biases will be updated during training. Be aware that this means that, even when disabling + the adapters, the model will not produce the same output as the base model would have without adaptation. + init_weights (`bool`): + Whether to initialize the weights of the GraLoRA layers with their default initialization. Don't change + this setting, except if you know exactly what you're doing. + layers_to_transform (`Union[List[int], int]`): + The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes + that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at + this index. This only works when target_modules is a list of str. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is + not in the common layers pattern. This only works when target_modules is a list of str. This should target + the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "GraLoRA attention dimension determines the rank of the GraLoRA adapter. " + "The total parameter count of the GraLoRA adapter is same as LoRA with same rank r, while the expressivitiy is multiplied by gralora_k." + ) + }, + ) + hybrid_r: int = field( + default=0, + metadata={ + "help": ( + "hybrid_r is the rank allocated to vanilla LoRA method when using Hybrid GraLoRA method. " + "Hybrid GraLoRA, a combination of GraLoRA and vanilla LoRA, becomes available when hybrid_r > 0. " + "r + hybrid_r determines the parameter count of the GraLoRA adapter." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with LoRA. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded). " + "If not specified, modules will be chosen according to the model architecture, If the architecture is " + "not known, an error will be raised -- in this case, you should specify the target modules manually. " + "To avoid targeting any modules (because you want to apply `target_parameters`), set " + "`target_modules=[]`." + ) + }, + ) + alpha: int = field( + default=64, + metadata={ + "help": ( + "gralora alpha is the scaling factor for the GraLoRA adapter. Scale becomes alpha / (r + hybrid_r). " + ) + }, + ) + gralora_dropout: float = field(default=0.0, metadata={"help": "gralora dropout"}) + gralora_k: int = field( + default=2, + metadata={ + "help": ( + "gralora_k determines the number of subblocks in the GraLoRA adapter. " + "The rank r must be divisible by gralora_k for the GraLoRA adapter to be valid. " + "The total parameter count is preserved regardles of gralora_k. " + "The entire rank of the GraLoRA adapter is increased by gralora_k, while the rank of each subblock is reduced by gralora_k. " + "gralora_k=2 is recommended for rank 32 or lower, and gralora_k=4 is recommended for rank 64 or higher. " + ) + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + bias: str = field( + default="none", metadata={"help": "Bias type for gralora. Can be 'none', 'all' or 'gralora_only'"} + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from gralora layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the GraLoRA layers with their default initialization. " + "Don't change this setting, except if you know exactly what you're doing." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. " + "If a single integer is passed, PEFT will transform only the layer at this index. " + "This only works when target_modules is a list of str." + ) + }, + ) + layers_pattern: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. " + "This only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.GRALORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + if self.r % self.gralora_k != 0: + raise ValueError(f"r should be divisible by gralora_k, but got {self.r} and {self.gralora_k}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..fef1750a7db57a0931b30131f967093bb4f9ba93 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/layer.py @@ -0,0 +1,395 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import warnings +from typing import Optional + +import torch +import torch.nn as nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer +from peft.utils.other import transpose + + +class GraloraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weight + adapter_layer_names = ("gralora_A", "gralora_B", "gralora_A_general", "gralora_B_general") + other_param_names = ("r", "hybrid_r", "alpha", "scaling", "gralora_dropout") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.alpha = {} + self.gralora_k = {} + self.hybrid_r = {} + self.scaling = {} + self.gralora_dropout = nn.ModuleDict({}) + + self.gralora_A = nn.ParameterDict({}) + self.gralora_B = nn.ParameterDict({}) + self.gralora_A_general = nn.ModuleDict({}) + self.gralora_B_general = nn.ModuleDict({}) + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + in_features, out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + else: + raise NotImplementedError(f"Unsupported layer type {type(base_layer)}") + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + def update_layer( + self, + adapter_name, + module_name, + r, + alpha, + gralora_dropout, + gralora_k: int = 2, + hybrid_r: int = 0, + init_weights: bool = True, + ): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + elif hybrid_r < 0: + raise ValueError(f"`hybrid_r` should be a non-negative integer value but the value passed is {hybrid_r}") + + self.r[adapter_name] = r + self.alpha[adapter_name] = alpha + self.gralora_k[adapter_name] = gralora_k + self.hybrid_r[adapter_name] = hybrid_r + + if gralora_dropout > 0.0: + gralora_dropout_layer = nn.Dropout(p=gralora_dropout) + else: + gralora_dropout_layer = nn.Identity() + + self.gralora_dropout.update(nn.ModuleDict({adapter_name: gralora_dropout_layer})) + + # Actual trainable parameters + if self.in_features % gralora_k != 0: + raise ValueError( + f"in_features should be divisible by gralora_k, but got {self.in_features} and {gralora_k}" + ) + if self.out_features % gralora_k != 0: + raise ValueError( + f"out_features should be divisible by gralora_k, but got {self.out_features} and {gralora_k}" + ) + subblock_in_features = self.in_features // gralora_k + subblock_out_features = self.out_features // gralora_k + + # gralora_r is the rank allocated to GraLoRA method; hybrid_r is the rank allocated to vanilla LoRA + gralora_r = r + + gralora_A = [] + gralora_B = [] + for _ in range(gralora_k): + new_A = nn.Parameter(torch.empty(gralora_r, subblock_in_features)) + new_B = nn.Parameter(torch.empty(subblock_out_features, gralora_r)) + if init_weights: + # Initialize to identity: A is random, B is zero + nn.init.kaiming_uniform_(new_A, a=math.sqrt(5)) + nn.init.zeros_(new_B) + else: + # Initialize to random: both A and B are random (for testing) + nn.init.kaiming_uniform_(new_A, a=math.sqrt(5)) + nn.init.kaiming_uniform_(new_B, a=math.sqrt(5)) + gralora_A.append(new_A) + gralora_B.append(new_B) + # stack A and B and transpose to get the final shape + gralora_A = torch.stack(tuple(gralora_A), dim=0) # [N, gralora_r, in_features//N] + gralora_A = gralora_A.transpose(1, 2).contiguous() # [N, in_features//N, gralora_r] + + gralora_B = torch.stack(tuple(gralora_B), dim=0) # [N, out_features//N, gralora_r] + gralora_B = gralora_B.transpose(1, 2).contiguous() # [N, gralora_r, out_features//N] + + if hybrid_r > 0: + general_gralora_A = nn.Linear(self.in_features, hybrid_r, bias=False) + general_gralora_B = nn.Linear(hybrid_r, self.out_features, bias=False) + if init_weights: + # Initialize to identity: A is random, B is zero + nn.init.kaiming_uniform_(general_gralora_A.weight, a=math.sqrt(5)) + nn.init.zeros_(general_gralora_B.weight) + else: + # Initialize to random: both A and B are random (for testing) + nn.init.kaiming_uniform_(general_gralora_A.weight, a=math.sqrt(5)) + nn.init.kaiming_uniform_(general_gralora_B.weight, a=math.sqrt(5)) + else: + general_gralora_A = nn.Identity() + general_gralora_B = nn.Identity() + + self.gralora_A[adapter_name] = gralora_A + self.gralora_B[adapter_name] = gralora_B + self.gralora_A_general[adapter_name] = general_gralora_A + self.gralora_B_general[adapter_name] = general_gralora_B + + self.module_name = module_name + + self.scaling[adapter_name] = alpha / (gralora_r + hybrid_r) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters) + + +class Linear(nn.Linear, GraloraLayer): + # Gralora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + module_name, + r: int = 0, + alpha: int = 1, + gralora_dropout: float = 0.0, + gralora_k: int = 2, + hybrid_r: int = 0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: bool = True, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called + super(nn.Linear, self).__init__() + GraloraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer(adapter_name, module_name, r, alpha, gralora_dropout, gralora_k, hybrid_r, init_weights) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + from peft.tuners.tuners_utils import check_adapters_to_merge + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.gralora_A.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights += delta_weight + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.gralora_A.keys(): + delta_weight = self.get_delta_weight(active_adapter) + self.get_base_layer().weight.data -= delta_weight + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for GraLoRA adapter. + + GraLoRA applies block-wise low-rank adaptation with information exchange. This method computes the equivalent + weight matrix that would be added to the base weight during merge. + + Args: + adapter (str): The name of the adapter + + Returns: + torch.Tensor: The delta weight matrix with shape [out_features, in_features] + """ + gralora_A = self.gralora_A[adapter] # [N, in_features//N, rank] + gralora_B = self.gralora_B[adapter] # [N, rank, out_features//N] + gralora_A_general = self.gralora_A_general[adapter] + gralora_B_general = self.gralora_B_general[adapter] + + device = gralora_A.device + dtype = gralora_A.dtype + + gralora_k = self.gralora_k[adapter] + hybrid_r = self.hybrid_r[adapter] + r = self.r[adapter] + + # Handle CPU fp16/bf16 casting + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + if cast_to_fp32: + gralora_A = gralora_A.float() + gralora_B = gralora_B.float() + + # Get dimensions + in_features = self.in_features + out_features = self.out_features + gralora_rank = r + subblock_gralora_rank = gralora_rank // gralora_k + + # scatter gralora_A to get the scattered weight matrix + l_indices = torch.arange(in_features, device=device) + n_indices = l_indices // (in_features // gralora_k) + i_indices = l_indices % (in_features // gralora_k) + gralora_A_scattered = torch.zeros( + in_features, gralora_k, gralora_rank, device=device, dtype=torch.float32 if cast_to_fp32 else dtype + ) + gralora_A_scattered.scatter_( + 1, + n_indices.unsqueeze(1).unsqueeze(2).expand(-1, 1, gralora_rank), + gralora_A[n_indices, i_indices, :].unsqueeze(1), + ) + + # compute the delta weight + delta_weight = ( + torch.einsum( + "ikr, kro -> iko", + gralora_A_scattered.view(in_features, gralora_k, gralora_k, subblock_gralora_rank) + .permute(0, 2, 1, 3) + .reshape(in_features, gralora_k, gralora_rank), + gralora_B, + ) + .reshape(in_features, out_features) + .T + ) + + # Add hybrid LoRA component if present + if hybrid_r > 0: + weight_A_general = gralora_A_general.weight # [hybrid_r, in_features] + weight_B_general = gralora_B_general.weight # [out_features, hybrid_r] + + if cast_to_fp32: + weight_A_general = weight_A_general.float() + weight_B_general = weight_B_general.float() + + # Compute delta for hybrid part: [out_features, hybrid_r] @ [hybrid_r, in_features] + delta_weight += weight_B_general @ weight_A_general + + # Apply scaling and transpose if needed + delta_weight = transpose(delta_weight, self.fan_in_fan_out) * self.scaling[adapter] + + # Cast back if needed + if cast_to_fp32: + delta_weight = delta_weight.to(dtype=dtype) + + return delta_weight + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + # Handle 2D input: [batch, features] -> [batch, 1, features] + # This is common for MLPs and other non-sequence models + x_is_2d = x.ndim == 2 + if x_is_2d: + x = x.unsqueeze(1) # [B, F] -> [B, 1, F] + + for active_adapter in self.active_adapters: + if active_adapter not in self.gralora_A.keys(): + continue + gralora_A = self.gralora_A[active_adapter] + gralora_B = self.gralora_B[active_adapter] + + gralora_A_general = self.gralora_A_general[active_adapter] + gralora_B_general = self.gralora_B_general[active_adapter] + + r = self.r[active_adapter] + gralora_rank = r + gralora_k = self.gralora_k[active_adapter] + hybrid_r = self.hybrid_r[active_adapter] + + dropout = self.gralora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + gralora_dtype = gralora_A.dtype + + B, L, in_features = x.shape + N = gralora_k + subblock_gralora_rank = gralora_rank // N + + output = torch.einsum( + "bljr, jro -> bljo", + torch.einsum( + "blni, nir -> blnr", + dropout(x.to(gralora_dtype)).view(B, L, N, in_features // N), + gralora_A, + ) + .view(B, L, N, N, subblock_gralora_rank) + .permute(0, 1, 3, 2, 4) + .reshape(B, L, N, N * subblock_gralora_rank), + gralora_B, + ).reshape(B, L, -1) + + # Squeeze back to 2D if input was 2D + if x_is_2d: + output = output.squeeze(1) # [B, 1, F] -> [B, F] + + result += scaling * output.to(torch_result_dtype) + if hybrid_r > 0: + hybrid_output = gralora_B_general(gralora_A_general(dropout(x.to(gralora_dtype)))) + if x_is_2d: + hybrid_output = hybrid_output.squeeze(1) + result += scaling * hybrid_output.to(torch_result_dtype) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "gralora." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7ce04df17f96aa4280be163e411d29bcab7c267d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/gralora/model.py @@ -0,0 +1,142 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings + +import torch +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, +) + +from .layer import GraloraLayer, Linear + + +class GraloraModel(BaseTuner): + """ + Creates Vector-based Random Matrix Adaptation (Gralora) model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`GraloraConfig`]): The configuration of the Gralora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The Gralora model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import GraloraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = GraloraConfig(r=128) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`GraloraConfig`]): The configuration of the Gralora model. + """ + + # The unique prefix for GraLoRA method + prefix: str = "gralora_" + # The class of tuner layer for GraLoRA method + tuner_layer_cls = GraloraLayer + + target_module_mapping = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + gralora_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + r = gralora_config.r + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": r, + "alpha": gralora_config.alpha, + "gralora_dropout": gralora_config.gralora_dropout, + "gralora_k": gralora_config.gralora_k, + "fan_in_fan_out": gralora_config.fan_in_fan_out, + "hybrid_r": gralora_config.hybrid_r, + "init_weights": gralora_config.init_weights, + } + kwargs["bias"] = bias + + if isinstance(target, Linear): + target.update_layer( + adapter_name, + current_key, + r, + gralora_config.alpha, + gralora_config.gralora_dropout, + gralora_config.gralora_k, + gralora_config.hybrid_r, + gralora_config.init_weights, + ) + else: + new_module = self._create_new_module(gralora_config, adapter_name, target, current_key, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(gralora_config, adapter_name, target, module_name, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = gralora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = gralora_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`." + ) + new_module = Linear( + target, + adapter_name, + module_name, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f5f6a54435d0fcaa1bd275c623168b5491f2d9e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import HRAConfig +from .layer import HRAConv2d, HRALayer, HRALinear +from .model import HRAModel + + +__all__ = ["HRAConfig", "HRAConv2d", "HRALayer", "HRALinear", "HRAModel"] + +register_peft_method(name="hra", config_cls=HRAConfig, model_cls=HRAModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9e6d87cc17c3ba003eac963467bb1253725ebe10 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/config.py @@ -0,0 +1,133 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class HRAConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`HRAModel`]. + + Args: + r (`int`): + The rank of HRA across different layers. It is best to set 'r' to an even number; otherwise, the default + initialization method will not work. + apply_GS (`bool`): + Whether to apply Gram-Schmidt orthogonalization. + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear modules are chosen, excluding + the output layer. If this is not specified, modules will be chosen according to the model architecture. If + the architecture is not known, an error will be raised -- in this case, you should specify the target + modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + init_weights (`bool`): + Whether to perform initialization of HRA weights. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field( + default=8, + metadata={ + "help": "The rank of HRA across different layers.", + "note": "It is best to set 'r' to an even number; otherwise, the default initialization method will not work.", + }, + ) + apply_GS: bool = field( + default=False, + metadata={"help": "Whether to apply Gram-Schmidt orthogonalization or not."}, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with HRA.", + "example": "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' ", + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from HRA."}, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the HRA layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. " + "This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + }, + ) + bias: str = field(default="none", metadata={"help": "Bias type for HRA. Can be 'none', 'all' or 'hra_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from HRA layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.HRA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..55ab6db69a6730f0ef3b4e46ee46071426091269 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/layer.py @@ -0,0 +1,461 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import warnings +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + + +class HRALayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("hra_u",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("hra_r", "hra_apply_GS") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.hra_r = {} + self.hra_apply_GS = {} + self.hra_u = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, nn.Conv2d): + self.in_features, self.out_features = base_layer.in_channels, base_layer.out_channels + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + def update_layer( + self, + adapter_name: str, + r: int, + apply_GS: bool, + init_weights: bool, + inference_mode: bool = False, + **kwargs, + ) -> None: + """Internal function to create hra adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + init_weights (`bool`): Whether to initialize weights. + apply_GS (`bool`): Whether to apply Gram-Schmidt orthogonalization or not. + """ + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.hra_r[adapter_name] = r + self.hra_apply_GS[adapter_name] = apply_GS + + # Determine shape of HRA weights + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.hra_u[adapter_name] = nn.Parameter(torch.empty(self.in_features, r), requires_grad=True) + elif isinstance(base_layer, nn.Conv2d): + self.hra_u[adapter_name] = nn.Parameter( + torch.empty(self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0], r), + requires_grad=True, + ) + else: + raise TypeError(f"HRA is not implemented for base layers of type {type(base_layer).__name__}") + + # Initialize weights + if init_weights: + self.reset_hra_parameters(adapter_name) + else: + self.reset_hra_parameters_random(adapter_name) + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_hra_parameters(self, adapter_name: str): + if self.hra_r[adapter_name] % 2 != 0: + warnings.warn("The symmetric initialization can NOT be performed when r is odd!") + nn.init.kaiming_uniform_(self.hra_u[adapter_name], a=math.sqrt(5)) + else: + shape = self.hra_u[adapter_name].shape + half_u = torch.zeros(shape[0], shape[1] // 2) + nn.init.kaiming_uniform_(half_u, a=math.sqrt(5)) + self.hra_u[adapter_name] = nn.Parameter(torch.repeat_interleave(half_u, 2, dim=1)) + + def reset_hra_parameters_random(self, adapter_name: str): + nn.init.kaiming_uniform_(self.hra_u[adapter_name], a=math.sqrt(5)) + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.hra_u.keys(): + continue + + warnings.warn("Scaling operation for HRA not supported! Automatically set scale to 1.") + + def unscale_layer(self, scale=None) -> None: + for active_adapter in self.active_adapters: + if active_adapter not in self.hra_u.keys(): + continue + + warnings.warn("Unscaling operation for HRA not supported! Keeping scale at 1.") + + +class HRALinear(nn.Module, HRALayer): + """ + HRA implemented in a dense layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 0, + apply_GS: bool = False, + init_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + super().__init__() + HRALayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, apply_GS, init_weights, **kwargs) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.hra_u.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + else: + delta_weight = self.get_delta_weight(active_adapter) + new_weight = torch.mm(base_layer.weight.data.to(delta_weight.dtype), delta_weight) + base_layer.weight.data = new_weight.to(orig_dtype) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if active_adapter in self.hra_u.keys(): + orig_weight = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter, reverse=True) + new_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + base_layer.weight.data = new_weight.to(orig_dtype) + + def get_delta_weight(self, adapter_name: str, reverse: bool = False) -> torch.Tensor: + rank = self.hra_r[adapter_name] + apply_GS = self.hra_apply_GS[adapter_name] + opt_u = self.hra_u[adapter_name] + shape = opt_u.shape + + if apply_GS: + weight = [(opt_u[:, 0] / opt_u[:, 0].norm()).view(-1, 1)] + for i in range(1, rank): + ui = opt_u[:, i].view(-1, 1) + for j in range(i): + ui = ui - (weight[j].t() @ ui) * weight[j] + weight.append((ui / ui.norm()).view(-1, 1)) + weight = torch.cat(weight, dim=1) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) - 2 * weight @ weight.t() + + else: + opt_u = opt_u / opt_u.norm(dim=0) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) + if reverse: + indices = range(rank - 1, -1, -1) + else: + indices = range(rank) + + for i in indices: + ui = opt_u[:, i].view(-1, 1) + weight = weight - 2 * weight @ ui @ ui.t() + + return weight + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + new_weight = torch.eye(self.in_features, device=x.device) + + for active_adapter in self.active_adapters: + if active_adapter not in self.hra_u.keys(): + continue + delta_weight = self.get_delta_weight(active_adapter) + new_weight = torch.mm(new_weight.to(delta_weight.dtype), delta_weight) + + orig_weight = self.get_base_layer().weight.data + orig_weight = self._cast_input_dtype(orig_weight, new_weight.dtype) + new_weight = torch.mm(orig_weight, new_weight) + bias = self._cast_input_dtype(self.base_layer.bias, new_weight.dtype) + + if self.cast_input_dtype_enabled: + x = self._cast_input_dtype(x, new_weight.dtype) + else: + x = x.to(self.get_base_layer().weight.data.dtype) + result = F.linear(input=x, weight=new_weight, bias=bias) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "hra." + rep + + +class HRAConv2d(nn.Module, HRALayer): + """HRA implemented in Conv2d layer""" + + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 0, + apply_GS: bool = False, + init_weights: Union[bool, str] = True, + **kwargs, + ): + super().__init__() + HRALayer.__init__(self, base_layer) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, apply_GS, init_weights, **kwargs) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.hra_u.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + orig_weight = orig_weight.view( + self.out_features, + self.in_features * base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + delta_weight = self.get_delta_weight(active_adapter) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + orig_weight = orig_weight.view( + self.out_features, + self.in_features, + base_layer.kernel_size[0], + base_layer.kernel_size[0], + ) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + else: + orig_weight = base_layer.weight.data + orig_weight = orig_weight.view( + self.out_features, + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + delta_weight = self.get_delta_weight(active_adapter) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + orig_weight = orig_weight.view( + self.out_features, + self.in_features, + base_layer.kernel_size[0], + base_layer.kernel_size[0], + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if active_adapter in self.hra_u.keys(): + orig_weight = base_layer.weight.data.clone() + orig_weight = orig_weight.view( + self.out_features, + self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0], + ) + delta_weight = self.get_delta_weight(active_adapter, reverse=True) + orig_weight = torch.mm(orig_weight.to(delta_weight.dtype), delta_weight) + orig_weight = orig_weight.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + + def get_delta_weight(self, adapter_name: str, reverse: bool = False) -> torch.Tensor: + rank = self.hra_r[adapter_name] + apply_GS = self.hra_apply_GS[adapter_name] + opt_u = self.hra_u[adapter_name] + shape = opt_u.shape + + if apply_GS: + weight = [(opt_u[:, 0] / opt_u[:, 0].norm()).view(-1, 1)] + for i in range(1, rank): + ui = opt_u[:, i].view(-1, 1) + for j in range(i): + ui = ui - (weight[j].t() @ ui) * weight[j] + weight.append((ui / ui.norm()).view(-1, 1)) + weight = torch.cat(weight, dim=1) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) - 2 * weight @ weight.t() + + else: + opt_u = opt_u / opt_u.norm(dim=0) + weight = torch.eye(shape[0], device=opt_u.device, dtype=opt_u.dtype) + if reverse: + indices = range(rank - 1, -1, -1) + else: + indices = range(rank) + + for i in indices: + ui = opt_u[:, i].view(-1, 1) + weight = weight - 2 * weight @ ui @ ui.t() + + return weight + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + new_weight = torch.eye( + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + device=x.device, + ) + for active_adapter in self.active_adapters: + if active_adapter not in self.hra_u.keys(): + continue + delta_weight = self.get_delta_weight(active_adapter) + new_weight = torch.mm(new_weight.to(delta_weight.dtype), delta_weight) + + orig_weight = self.base_layer.weight.data + orig_weight = orig_weight.view( + self.out_features, + self.in_features * self.base_layer.kernel_size[0] * self.base_layer.kernel_size[0], + ) + orig_weight = self._cast_input_dtype(orig_weight, new_weight.dtype) + bias = self._cast_input_dtype(self.base_layer.bias, new_weight.dtype) + + new_weight = torch.mm(orig_weight, new_weight) + new_weight = new_weight.view( + self.out_features, + self.in_features, + self.base_layer.kernel_size[0], + self.base_layer.kernel_size[0], + ) + + if self.cast_input_dtype_enabled: + x = self._cast_input_dtype(x, new_weight.dtype) + else: + x = x.to(self.get_base_layer().weight.data.dtype) + result = F.conv2d( + input=x, + weight=new_weight, + bias=bias, + padding=self.base_layer.padding[0], + stride=self.base_layer.stride[0], + ) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "hra." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/model.py new file mode 100644 index 0000000000000000000000000000000000000000..e210d226b5294053788188b9d3b307b73c7d9457 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/hra/model.py @@ -0,0 +1,131 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING + +from .layer import HRAConv2d, HRALayer, HRALinear + + +class HRAModel(BaseTuner): + """ + Creates Householder reflection adaptation (HRA) model from a pretrained model. The method is described in + https://huggingface.co/papers/2405.17484 + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`HRAConfig`]): The configuration of the HRA model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The HRA model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import HRAModel, HRAConfig + + >>> config_te = HRAConfig( + ... r=8, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... init_weights=True, + ... ) + >>> config_unet = HRAConfig( + ... r=8, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... init_weights=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = HRAModel(model.text_encoder, config_te, "default") + >>> model.unet = HRAModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`HRAConfig`]): The configuration of the HRA model. + """ + + prefix: str = "hra_" + tuner_layer_cls = HRALayer + target_module_mapping = TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + hra_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": hra_config.r, + "apply_GS": hra_config.apply_GS, + "init_weights": hra_config.init_weights, + } + kwargs["bias"] = bias + + # If it is not a HRALayer, create a new module, else update it with new adapters + if not isinstance(target, HRALayer): + new_module = self._create_new_module(hra_config, adapter_name, target, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + else: + target.update_layer( + adapter_name, + r=hra_config.r, + apply_GS=hra_config.apply_GS, + init_weights=hra_config.init_weights, + ) + + @staticmethod + def _create_new_module(hra_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + new_module = HRALinear(target, adapter_name, **kwargs) + elif isinstance(target_base_layer, torch.nn.Conv2d): + new_module = HRAConv2d(target, adapter_name, **kwargs) + else: + raise ValueError( + f"Target module {target} is not supported. " + "Currently, only `torch.nn.Linear` and `torch.nn.Conv2d` are supported." + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..21cab4d6d8a6437766f395e90079ce6ecd9e4f26 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/__init__.py @@ -0,0 +1,39 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.utils import register_peft_method + +from .config import IA3Config +from .layer import Conv2d, Conv3d, IA3Layer, Linear +from .model import IA3Model + + +__all__ = ["Conv2d", "Conv3d", "IA3Config", "IA3Layer", "IA3Model", "Linear"] + +register_peft_method(name="ia3", config_cls=IA3Config, model_cls=IA3Model, is_mixed_compatible=True) + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..628e3ce7229528a0b3157da349b2b34153573c51 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/bnb.py @@ -0,0 +1,129 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any + +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available + +from .layer import IA3Layer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, IA3Layer): + # (IA)^3 implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + is_feedforward: bool, + init_ia3_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + self._active_adapter = adapter_name + self.update_layer(adapter_name, init_ia3_weights) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + if self.disable_adapters: + return self.base_layer(x) + + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + ia3_scaling *= self.ia3_l[active_adapter].flatten() + + requires_conversion = (not torch.is_autocast_enabled()) and (x.dtype != torch.float32) + if requires_conversion: + x = x.float() + if self.is_feedforward: + result = self.base_layer(x * ia3_scaling) + expected_dtype = result.dtype + else: + result = self.base_layer(x) + expected_dtype = result.dtype + result = result * ia3_scaling + + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "ia3." + rep + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, IA3Layer): + # IA3 implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + is_feedforward: bool, + init_ia3_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + + # Freezing the pre-trained weight matrix + self.get_base_layer().weight.requires_grad = False + self._active_adapter = adapter_name + self.update_layer(adapter_name, init_ia3_weights) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # note: no check for self.merged because merging is not supported (yet) + if self.disable_adapters: + return self.base_layer(x) + + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + ia3_scaling *= self.ia3_l[active_adapter].flatten() + + requires_conversion = (not torch.is_autocast_enabled()) and (x.dtype != torch.float32) + if requires_conversion: + x = x.float() + if self.is_feedforward: + result = self.base_layer(x * ia3_scaling) + expected_dtype = result.dtype + else: + result = self.base_layer(x) + expected_dtype = result.dtype + result = result * ia3_scaling + + result = result.clone() + # adalora.py and lora.py both suggest that this is necessary for 4-bit training on older versions of Pytorch. + # This has been duplicated here. + + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "ia3." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/config.py new file mode 100644 index 0000000000000000000000000000000000000000..1c4161e5ed97998017b800535d4315c66c9d14cd --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/config.py @@ -0,0 +1,112 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class IA3Config(PeftConfig): + """ + This is the configuration class to store the configuration of a [`IA3Model`]. + + Args: + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen, + excluding the output layer. If this is not specified, modules will be chosen according to the model + architecture. If the architecture is not known, an error will be raised -- in this case, you should specify + the target modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + feedforward_modules (`Optional[Union[List[str], str]]`): + The names of the modules to be treated as feedforward modules, as in the original paper. These modules will + have (IA)³ vectors multiplied to the input, instead of the output. `feedforward_modules` must be a name or + a subset of names present in `target_modules`. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from (IA)³ layers to be set as trainable and saved in the final checkpoint. + init_ia3_weights (`bool`): + Whether to initialize the vectors in the (IA)³ layers, defaults to `True`. Setting this to `False` is + discouraged. + """ + + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with (IA)³." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'." + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer." + "If not specified, modules will be chosen according to the model architecture, If the architecture is " + "not known, an error will be raised -- in this case, you should specify the target modules manually." + ), + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from (IA)³."}, + ) + feedforward_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or a regex expression of module names which are feedforward" + "For example, ['output.dense']" + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from (IA)^3 layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + init_ia3_weights: bool = field( + default=True, + metadata={"help": "Whether to initialize the vectors in the (IA)^3 layers."}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.IA3 + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + self.feedforward_modules = ( + set(self.feedforward_modules) if isinstance(self.feedforward_modules, list) else self.feedforward_modules + ) + + # check if feedforward_modules is a subset of target_modules. run the check only if both are sets + if isinstance(self.feedforward_modules, set) and isinstance(self.target_modules, set): + if not self.feedforward_modules.issubset(self.target_modules): + raise ValueError("`feedforward_modules` should be a subset of `target_modules`") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..48cb08ba46aa7af05f1d891507e39ee6300f10dc --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/layer.py @@ -0,0 +1,330 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Any, Optional + +import torch +import torch.nn as nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils import transpose + + +class IA3Layer(BaseTunerLayer): + # All names of layers that may contain adapter weights + adapter_layer_names = ("ia3_l",) + + def __init__(self, base_layer: nn.Module, is_feedforward: bool, **kwargs) -> None: + self.base_layer = base_layer + self.ia3_l = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.is_feedforward = is_feedforward + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, (nn.Conv2d, nn.Conv3d)): + in_features, out_features = base_layer.in_channels, base_layer.out_channels + elif isinstance(base_layer, nn.Embedding): + in_features, out_features = base_layer.num_embeddings, base_layer.embedding_dim + elif isinstance(base_layer, Conv1D): + in_features, out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name, init_ia3_weights, inference_mode: bool = False, **kwargs): + # This code works for linear layers, override for other layer types + # Actual trainable parameters + if self.is_feedforward: + weight = torch.randn((1, self.in_features)) + else: + weight = torch.randn((self.out_features, 1)) + self.ia3_l[adapter_name] = nn.Parameter(weight) + if init_ia3_weights: + self.reset_ia3_parameters(adapter_name) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_ia3_parameters(self, adapter_name): + if adapter_name in self.ia3_l.keys(): + # initialize learned vector with torch.ones + nn.init.constant_(self.ia3_l[adapter_name], 1.0) + + +class Linear(nn.Module, IA3Layer): + # (IA)^3 implemented in a dense layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + is_feedforward: bool = False, # Set to True if the layer is treated as a feedforward layer + is_target_conv_1d_layer: bool = False, # whether target module is a conv1d layer. useful while unloading later + init_ia3_weights: bool = True, # whether to initialize IA3 weights + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + self.fan_in_fan_out = fan_in_fan_out + self.is_target_conv_1d_layer = is_target_conv_1d_layer + self._active_adapter = adapter_name + self.update_layer(adapter_name, init_ia3_weights) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.ia3_l.keys(): + base_layer = self.get_base_layer() + ia3_l = transpose(self.ia3_l[active_adapter].data, self.fan_in_fan_out) + orig_dtype = base_layer.weight.data.dtype + if safe_merge: + orig_weights = base_layer.weight.data + orig_weights = torch.mul(orig_weights, ia3_l) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + base_layer.weight.data = orig_weights.to(orig_dtype) + else: + base_layer.weight.data = torch.mul(base_layer.weight.data, ia3_l).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + orig_dtype = base_layer.bias.data.dtype + base_layer.bias.data = torch.mul(base_layer.bias.data, scaling.data).to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + warnings.warn("Unmerge result can be inaccurate for (IA)^3.") + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.ia3_l.keys(): + base_layer = self.get_base_layer() + # Add tolerace to avoid division by zero + ia3_l = transpose(self.ia3_l[active_adapter].data, self.fan_in_fan_out) + 1e-8 + orig_dtype = base_layer.weight.data.dtype + base_layer.weight.data = torch.div(base_layer.weight.data, ia3_l).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + orig_dtype = base_layer.bias.data.dtype + base_layer.bias.data = torch.div(base_layer.bias.data, scaling.data + 1e-8).to(orig_dtype) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + dtype = previous_dtype = x.dtype + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + dtype = self.ia3_l[active_adapter].dtype + ia3_scaling *= self.ia3_l[active_adapter].flatten() + + if self.is_feedforward: + x = x.to(dtype) + # TODO: weight.dtype can be != self.ia3_l[self.active_adapters].dtype + # e.g. bf16 vs fp32. Is that okay? + interm = (x * ia3_scaling).to(previous_dtype) + result = self.base_layer(interm, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result_dtype = result.dtype + result = (result * ia3_scaling).to(result_dtype) + + return result + + +class _ConvNd(nn.Module, IA3Layer): + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + is_feedforward: bool = False, # Set to True if the layer is treated as a feedforward layer + init_ia3_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + IA3Layer.__init__(self, base_layer, is_feedforward=is_feedforward) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self._kernel_dim = base_layer.weight.dim() + + self.update_layer(adapter_name, init_ia3_weights) + + def update_layer(self, adapter_name, init_ia3_weights, inference_mode: bool = False, **kwargs): + # Actual trainable parameters + num_features = self.in_features if self.is_feedforward else self.out_features + weights_size = (1, num_features) + (1,) * (self._kernel_dim - 2) + weight = torch.randn(weights_size) + self.ia3_l[adapter_name] = nn.Parameter(weight) + if init_ia3_weights: + self.reset_ia3_parameters(adapter_name) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.ia3_l.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.data.dtype + ia3_scaling = self.ia3_l[active_adapter].data + if not self.is_feedforward: + ia3_scaling = ia3_scaling.transpose(0, 1) + + if safe_merge: + output_weight = torch.mul(base_layer.weight.data, ia3_scaling).clone() + + if not torch.isfinite(output_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = output_weight.to(orig_dtype) + else: + base_layer.weight.data = torch.mul(base_layer.weight.data, ia3_scaling).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + base_layer.bias.data = torch.mul(base_layer.bias.data, scaling.data).to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + warnings.warn("Unmerge result can be inaccurate for (IA)^3.") + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.ia3_l.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.data.dtype + # divide by (IA)^3 vector. Add tolerace to avoid division by zero + ia3_scaling = self.ia3_l[active_adapter].data + if not self.is_feedforward: + ia3_scaling = ia3_scaling.transpose(0, 1) + base_layer.weight.data = torch.div(base_layer.weight.data, ia3_scaling + 1e-8).to(orig_dtype) + + if not self.is_feedforward and (base_layer.bias is not None): + scaling = self.ia3_l[active_adapter].reshape(base_layer.bias.shape) + orig_dtype = base_layer.bias.data.dtype + base_layer.bias.data = torch.mul(base_layer.bias.data, scaling.data).to(orig_dtype) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + dtype = previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + ia3_scaling = 1 + for active_adapter in self.active_adapters: + if active_adapter not in self.ia3_l.keys(): + continue + dtype = self.ia3_l[active_adapter].dtype + ia3_scaling *= self.ia3_l[active_adapter] + + if self.is_feedforward: + x = x.to(dtype) + # TODO: weight.dtype can be != self.ia3_l[self.active_adapters].dtype + # e.g. bf16 vs fp32. Is that okay? + interm = (x * ia3_scaling).to(self.get_base_layer().weight.dtype) + result = self.base_layer(interm, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result = result.to(dtype) * ia3_scaling + + result = result.to(previous_dtype) + return result + + +class Conv2d(_ConvNd): + # IA3 implemented in a 2D convolutional layer + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 4: + raise ValueError(f"Conv2d layer kernel must have 4 dimensions, not {self._kernel_dim}") + + +class Conv3d(_ConvNd): + # IA3 implemented in a 3D convolutional layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 5: + raise ValueError(f"Conv2d layer kernel must have 5 dimensions, not {self._kernel_dim}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/model.py new file mode 100644 index 0000000000000000000000000000000000000000..e322b167fc53f4dadc8ba068c36a6e65d3e22f37 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ia3/model.py @@ -0,0 +1,315 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import re +import warnings +from dataclasses import replace + +import torch +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + ModulesToSaveWrapper, + _freeze_adapter, + _get_submodules, +) + +from .layer import Conv2d, Conv3d, IA3Layer, Linear + + +class IA3Model(BaseTuner): + """ + Creates a Infused Adapter by Inhibiting and Amplifying Inner Activations ((IA)^3) model from a pretrained + transformers model. The method is described in detail in https://huggingface.co/papers/2205.05638 + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`IA3Config`]): The configuration of the (IA)^3 model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The (IA)^3 model. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM, ia3Config + >>> from peft import IA3Model, IA3Config + + >>> config = IA3Config( + ... peft_type="IA3", + ... task_type="SEQ_2_SEQ_LM", + ... target_modules=["k", "v", "w0"], + ... feedforward_modules=["w0"], + ... ) + + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> ia3_model = IA3Model(config, model) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`ia3Config`]): The configuration of the (IA)^3 model. + """ + + prefix: str = "ia3_" + tuner_layer_cls = IA3Layer + + @staticmethod + def _create_new_module(ia3_config, adapter_name, target, **kwargs): + # avoid eager bnb import + if is_bnb_available(): + import bitsandbytes as bnb + + from .bnb import Linear8bitLt + + if is_bnb_4bit_available(): + from .bnb import Linear4bit + + loaded_in_8bit = kwargs.pop("loaded_in_8bit", False) + loaded_in_4bit = kwargs.pop("loaded_in_4bit", False) + is_feedforward = kwargs.pop("is_feedforward", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target_base_layer.state.has_fp16_weights, + "threshold": target_base_layer.state.threshold, + "index": target_base_layer.index, + } + ) + new_module = Linear8bitLt(target, adapter_name, is_feedforward=is_feedforward, **eightbit_kwargs) + elif loaded_in_4bit and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + new_module = Linear4bit(target, adapter_name, is_feedforward=is_feedforward, **fourbit_kwargs) + elif isinstance(target, torch.nn.Conv2d): + new_module = Conv2d(target, adapter_name, is_feedforward=is_feedforward, **kwargs) + elif isinstance(target, torch.nn.Conv3d): + new_module = Conv3d(target, adapter_name, is_feedforward=is_feedforward, **kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = ia3_config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, is_feedforward=is_feedforward, **kwargs) + elif isinstance(target_base_layer, Conv1D): + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = ia3_config.fan_in_fan_out = True + new_module = Linear( + target, adapter_name, is_feedforward=is_feedforward, is_target_conv_1d_layer=True, **kwargs + ) + else: + raise ValueError( + f"Target module {target} is not supported. " + f"Currently, only `torch.nn.Linear`, `torch.nn.Conv2d`, and `Conv1D` are supported." + ) + return new_module + + def _create_and_replace( + self, + ia3_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + # check if target module is in feedforward_modules + is_feedforward = self._check_target_module_feedforward(ia3_config, current_key) + + kwargs = { + "fan_in_fan_out": ia3_config.fan_in_fan_out, + "init_ia3_weights": ia3_config.init_ia3_weights, + "is_feedforward": is_feedforward, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + + if isinstance(target, IA3Layer): + target.update_layer( + adapter_name, + ia3_config.init_ia3_weights, + ) + else: + new_module = self._create_new_module(ia3_config, adapter_name, target, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _check_target_module_feedforward(ia3_config, key) -> bool: + """ + A helper private method that checks if the target module `key` matches with a feedforward module specified in + `ia3_config` + """ + if isinstance(ia3_config.feedforward_modules, str): + is_feedforward = bool(re.fullmatch(ia3_config.feedforward_modules, key)) + else: + is_feedforward = any(key.endswith(target_key) for target_key in ia3_config.feedforward_modules) + return is_feedforward + + @staticmethod + def _prepare_adapter_config(peft_config, model_config): + if peft_config.target_modules is None: + if model_config["model_type"] not in TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING: + raise ValueError("Please specify `target_modules` in `peft_config`") + peft_config.target_modules = set( + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING[model_config["model_type"]] + ) + if peft_config.feedforward_modules is None: + if model_config["model_type"] not in TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING: + raise ValueError("Please specify `feedforward_modules` in `peft_config`") + peft_config.feedforward_modules = set( + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING[model_config["model_type"]] + ) + return peft_config + + def _unload_and_optionally_merge(self, *args, **kwargs): + r""" + This method merges the (IA)^3 layers into the base model. This is needed if someone wants to use the base model + as a standalone model. + + Args: + safe_merge (`bool`, `optional`, defaults to `False`): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + if getattr(self.model, "is_loaded_in_8bit", False): + raise ValueError("Cannot merge ia3 layers when the model is loaded in 8-bit mode") + + if getattr(self.model, "is_loaded_in_4bit", False): + raise ValueError("Cannot merge ia3 layers when the model is loaded in 4-bit mode") + + return super()._unload_and_optionally_merge(*args, **kwargs) + + def _check_add_weighted_adapter(self, adapters: list[str]) -> tuple[str, str]: + """ + Helper function to check if the arguments to add_weighted_adapter are valid and compatible with the underlying + model. + """ + # Validate existence of adapters + for adapter in adapters: + if adapter not in self.peft_config: + raise ValueError(f"Adapter {adapter} does not exist") + + # Check for conflicting modules_to_save + modules_to_save_wrappers = [module for module in self.modules() if isinstance(module, ModulesToSaveWrapper)] + if any( + sum(adapter in wrapper.modules_to_save for adapter in adapters) > 1 for wrapper in modules_to_save_wrappers + ): + raise ValueError("Cannot add weighted adapters targeting the same module with modules_to_save.") + + # Ensure all adapters have compatible target and feedforward module types + target_module_types = {type(self.peft_config[adapter].target_modules) for adapter in adapters} + feedforward_module_types = {type(self.peft_config[adapter].feedforward_modules) for adapter in adapters} + if len(target_module_types) > 1 or len(feedforward_module_types) > 1: + raise ValueError("All adapter configs should have the same type for target and feedforward modules.") + + # Combine target and feedforward modules + if str in target_module_types: + new_target_modules = "|".join(f"({self.peft_config[adapter].target_modules})" for adapter in adapters) + else: + new_target_modules = set.union(*(self.peft_config[adapter].target_modules for adapter in adapters)) + + if str in feedforward_module_types: + new_feedforward_modules = "|".join( + f"({self.peft_config[adapter].feedforward_modules})" for adapter in adapters + ) + else: + new_feedforward_modules = set.union( + *(self.peft_config[adapter].feedforward_modules for adapter in adapters) + ) + + return new_target_modules, new_feedforward_modules + + def add_weighted_adapter( + self, + adapters: list[str], + weights: list[float], + adapter_name: str, + ) -> None: + """ + This method adds a new adapter by merging the given adapters with the given weights. + + Args: + adapters (`list`): + List of adapter names to be merged. + weights (`list`): + List of weights for each adapter. + adapter_name (`str`): + Name of the new adapter. + """ + if adapter_name in list(self.peft_config.keys()): + return + + new_target_modules, new_feedforward_modules = self._check_add_weighted_adapter( + adapters=adapters, + ) + + self.peft_config[adapter_name] = replace( + self.peft_config[adapters[0]], + target_modules=new_target_modules, + feedforward_modules=new_feedforward_modules, + ) + self.inject_adapter(self.model, adapter_name) + + # Do we really need that? + _freeze_adapter(self.model, adapter_name) + + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + for key in key_list: + _, target, _ = _get_submodules(self.model, key) + if isinstance(target, IA3Layer): + if adapter_name in target.ia3_l: + target_ia3_l = target.ia3_l[adapter_name] + else: + continue + + target_ia3_l.data = target_ia3_l.data.zero_() + for adapter, weight in zip(adapters, weights): + if adapter in target.ia3_l: + current_adapter_ia3_l = target.ia3_l[adapter] + else: + continue + target_ia3_l.data += current_adapter_ia3_l.data * weight diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..df75b8a01874305e354689694fe675a344105984 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/__init__.py @@ -0,0 +1,26 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import LilyConfig +from .layer import LilyLayer, Linear +from .model import LilyModel + + +__all__ = ["LilyConfig", "LilyLayer", "LilyModel", "Linear"] + +register_peft_method( + name="lily", config_cls=LilyConfig, model_cls=LilyModel, prefix="lily_", is_mixed_compatible=False +) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/config.py new file mode 100644 index 0000000000000000000000000000000000000000..97db3f8aaef9abac69422a23cd8c4316d11a385b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/config.py @@ -0,0 +1,237 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class LilyConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`LilyModel`]. + + Args: + r (`int`): + Lily's rank. Determines the inner hidden dimension of each adapter and the rank of the weight update `A @ + B`. In Lily, since the number of adapters is typically smaller than in LoRA, each adapter needs to carry + more capacity, so it is recommended to use a larger `r` than in LoRA — typically `2x`, `3x`, or `4x` the + LoRA rank you would normally use. The total number of trainable parameters scales with `r * (total_layers / + stride_A + num_B)`, so increasing `r` while keeping `stride_A` large and `num_B` small is the recommended + trade-off. + stride_A (`int`): + The number of consecutive layers that share one A adapter. For example, if `stride_A=4`, every 4 adjacent + layers share the same A adapter, resulting in `total_layers / stride_A` distinct A adapters in total. The A + adapter compresses the input into a low-rank representation of size `r`. `stride_A` should be no less than + 1. Suggested values: `2`, `3`, or `4` (i.e. sharing every 2, 3, or 4 layers). Keeping `stride_A` large + (fewer distinct A adapters) and increasing `r` instead leads to better performance than the opposite + trade-off (small `stride_A`, small `r`). Setting `stride_A=1` means every layer has its own A adapter. + NOTE: the A sharing happens within each target (layers with the same target suffix). For example, if your + target_modules are `['q_proj', 'v_proj']` and you set `stride_A=2`, then every 2 adjacent q_proj layers + will share an A adapter, and every 2 adjacent v_proj layers will share another A adapter, but the q_proj + and v_proj layers will not share A adapters with each other since they have different suffixes. + num_B (`int`): + The number of shared B adapters. Unlike A adapters (which are grouped by layer), all B adapters are shared + globally across every layer. For each forward pass, a router computes a weighted combination of all `num_B` + B adapters (using softmax-normalized weights) to produce a single combined B adapter, which then projects + the low-rank representation back to the original dimension. It is recommended to set `num_B` to a similar + order as `total_layers / stride_A`. Suggested values: `total_layers / 2`, `total_layers / 3`, or + `total_layers / 4`. Similar to `stride_A`, prefer smaller `num_B` with larger `r` over larger `num_B` with + smaller `r`. NOTE: to train the router, you need at least 2 B adapters (i.e. `num_B >= 2`), since the + router learns to compute a weighted combination of the B adapters. NOTE: the B sharing happens within each + target (layers with the same target suffix). For example, if your target_modules are `['q_proj', 'v_proj']` + and you set `num_B=4`, then there will be 4 B adapters shared across all q_proj layers, and another 4 B + adapters shared across all v_proj layers, but the q_proj and v_proj layers will not share B adapters with + each other since they have different suffixes. + target_modules (`Union[List[str], str]`, *optional*): + The names of the modules to apply Lily to. Can be a list of module name strings (e.g. `['q_proj', + 'v_proj']`) or a regex pattern (e.g. `'.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'`). If not + specified, Lily will be applied to all supported linear layers. + scaling (`float`): + A scalar multiplier applied to the combined adapter output (`scaling * A @ combined_B`) before adding it to + the frozen weight's forward pass. Unlike LoRA, Lily does not use an `alpha / r` formulation; instead, + `scaling` is a direct multiplier. This design makes it straightforward to sweep over values on a log scale + (e.g. `0.01`, `0.1`, `1.0`, `10.0`). The optimal value is task-dependent and should be treated as a + hyperparameter. We recommend starting with `1.0`. + modules_to_save (`List[str]`, *optional*): + List of modules apart from Lily layers to be set as trainable and saved in the final checkpoint. For + example, in Sequence Classification or Token Classification tasks, the final layer `classifier/score` are + randomly initialized and as such need to be trainable and saved. + exclude_modules (`Union[List[str], str]`, *optional*): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + layers_to_transform (`Union[list[int], int]`, *optional*): + The layer indexes to transform, if this argument is specified, PEFT will transform only the layers indexes + that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at + this index. + layers_pattern (`Optional[Union[List[str], str]]`, *optional*): + The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is + not in the common layers pattern. This should target the `nn.ModuleList` of the model, which is often + called `'layers'` or `'h'`. + init_weights (`bool`): + Whether to initialize Lily adapter weights using the default initialization scheme: A matrices are + initialized with Kaiming uniform, and B matrices are initialized to zero, ensuring that the adapter output + is zero at the start of training and does not disturb the pretrained model. It is strongly recommended to + keep this as `True` unless you have a specific reason to change it. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "Lily's rank. Determines the inner hidden dimension of each adapter and the rank of the " + "weight update `A @ B`. In Lily, since the number of adapters is typically smaller than in LoRA, " + "each adapter needs to carry more capacity, so it is recommended to use a larger `r` than " + "in LoRA — typically `2x`, `3x`, or `4x` the LoRA rank you would normally use. " + "The total number of trainable parameters scales with `r * (total_layers / stride_A + num_B)`, " + "so increasing `r` while keeping `stride_A` large and `num_B` small is the recommended trade-off." + ) + }, + ) + stride_A: int = field( + default=1, + metadata={ + "help": ( + "The number of consecutive layers that share one A adapter. For example, if `stride_A=4`, " + "every 4 adjacent layers share the same A adapter, resulting in `total_layers / stride_A` " + "distinct A adapters in total." + "The A adapter compresses the input into a low-rank representation of size `r`. " + "`stride_A` should be no less than 1." + "Suggested values: `2`, `3`, or `4` (i.e. sharing every 2, 3, or 4 layers). " + "Keeping `stride_A` large (fewer distinct A adapters) and increasing `r` instead leads to " + "better performance than the opposite trade-off (small `stride_A`, small `r`). " + "Setting `stride_A=1` means every layer has its own A adapter." + "Note: A sharing happens within each target module type independently. For example, if " + "`target_modules=['q_proj', 'v_proj']` and `stride_A=2`, then every 2 adjacent `q_proj` " + "layers share one A adapter and every 2 adjacent `v_proj` layers share another A adapter, " + "but `q_proj` and `v_proj` layers never share A adapters with each other." + ) + }, + ) + num_B: int = field( + default=2, + metadata={ + "help": ( + "The number of shared B adapters. Unlike A adapters (which are grouped by layer), " + "all B adapters are shared globally across every layer. For each forward pass, a router " + "computes a weighted combination of all `num_B` B adapters (using softmax-normalized " + "weights) to produce a single combined B adapter, which then projects the low-rank " + "representation back to the original dimension. It is recommended to set `num_B` to a " + "similar order as `total_layers / stride_A`. Suggested values: `total_layers / 2`, " + "`total_layers / 3`, or `total_layers / 4`. Similar to `stride_A`, prefer smaller `num_B` " + "with larger `r` over larger `num_B` with smaller `r`. " + "NOTE: to train the router, you need at least 2 B adapters (i.e. `num_B >= 2`), since the " + "router learns to compute a weighted combination of the B adapters." + "Note: B sharing happens within each target module type independently. For example, if " + "`target_modules=['q_proj', 'v_proj']` and `num_B=4`, then there will be 4 B adapters " + "shared across all `q_proj` layers and another 4 B adapters shared across all `v_proj` " + "layers, but `q_proj` and `v_proj` layers never share B adapters with each other." + ) + }, + ) + scaling: float = field( + default=1.0, + metadata={ + "help": ( + "A scalar multiplier applied to the combined adapter output (`scaling * A @ combined_B`) " + "before adding it to the frozen weight's forward pass. Unlike LoRA, Lily does not use an " + "`alpha / r` formulation; instead, `scaling` is a direct multiplier. This design " + "makes it straightforward to sweep over values on a log scale (e.g. `0.01`, `0.1`, " + "`1.0`, `10.0`). The optimal value is task-dependent and should be treated as a " + "hyperparameter. We recommend starting with `1.0`." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with Lily. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "If not specified, Lily will be applied to all supported linear layers." + ) + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to exclude from Lily. " + "When passing a string, a regex match will be performed. When passing a list of strings, " + "either an exact match will be performed or it is checked if the name of the module ends " + "with any of the passed strings." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from Lily layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, if this argument is specified, PEFT will transform only the layers " + "indexes that are specified inside this list. If a single integer is passed, PEFT will transform only " + "the layer at this index." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer " + "pattern is not in the common layers pattern. This should target the `nn.ModuleList` of the model, " + "which is often called `'layers'` or `'h'`." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize Lily adapter weights using the default initialization scheme: A matrices are " + "initialized with Kaiming uniform, and B matrices are initialized to zero, ensuring that the adapter " + "output is zero at the start of training and does not disturb the pretrained model. It is strongly " + "recommended to keep this as `True` unless you have a specific reason to change it." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.LILY + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified.") + if self.stride_A < 1: + raise ValueError("`stride_A` must be at least 1.") + if self.num_B < 2: + raise ValueError("`num_B` must be at least 2 for the router to be trained.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..e52ddb6cec204a80a0300376e7f262ba6bf0efa4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/layer.py @@ -0,0 +1,188 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +import warnings +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.tuners.tuners_utils import BaseTunerLayer + + +class LilyLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("lily_A", "lily_B", "lily_router") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "scaling", "stride_A", "num_B") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.scaling = {} + self.stride_A = {} + self.num_B = {} + self.lily_A = nn.ModuleDict({}) + self.lily_B = nn.ModuleDict({}) + self.lily_router = nn.ModuleDict({}) + self.kwargs = kwargs + + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + # possibly support user provided custom layer types using dynamic dispatch + if hasattr(base_layer, "in_features") and hasattr(base_layer, "out_features"): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + in_features, out_features = None, None + warnings.warn( + f"Unsupported layer type '{type(base_layer)}' encountered, proceed at your own risk.", UserWarning + ) + + self.in_features = in_features + self.out_features = out_features + + def update_layer( + self, + adapter_name, + r, + scaling, + stride_A, + num_B, + lily_A: Optional[nn.Linear] = None, + lily_B: Optional[nn.Linear] = None, + init_weights: bool = True, + inference_mode: bool = False, + ): + # collect the kwargs + kwargs = locals().copy() + del kwargs["self"] + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.r[adapter_name] = r + self.scaling[adapter_name] = scaling + + # Actual trainble parameters + self.lily_A[adapter_name] = lily_A if lily_A is not None else nn.Linear(self.in_features, r, bias=False) + self.lily_B[adapter_name] = ( + lily_B if lily_B is not None else nn.Linear(self.out_features, num_B * r, bias=False) + ) + self.lily_router[adapter_name] = nn.Linear(r, num_B, bias=False) + + self.stride_A[adapter_name] = stride_A + self.num_B[adapter_name] = num_B + self.reset_lily_parameters(adapter_name, init_weights=init_weights) # initialize the parameters + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_lily_parameters(self, adapter_name, init_weights: bool = True): + if adapter_name in self.lily_A: + nn.init.kaiming_uniform_(self.lily_A[adapter_name].weight, a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lily_router[adapter_name].weight, a=math.sqrt(5)) + if not init_weights: + nn.init.kaiming_uniform_(self.lily_B[adapter_name].weight, a=math.sqrt(5)) + else: + nn.init.zeros_(self.lily_B[adapter_name].weight) + + +class Linear(nn.Module, LilyLayer): + # Lily implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 32, + scaling: float = 1.0, + stride_A: int = 1, + num_B: int = 2, + lily_A: nn.Linear = None, + lily_B: nn.Linear = None, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + LilyLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + + self.update_layer( + adapter_name, + r, + scaling=scaling, + lily_A=lily_A, + lily_B=lily_B, + stride_A=stride_A, + num_B=num_B, + init_weights=init_weights, + ) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + raise NotImplementedError("This method is not supported for Lily.") + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + raise NotImplementedError("This method is not supported for Lily.") + + def unmerge(self) -> None: + raise NotImplementedError("This method is not supported for Lily.") + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + result = self.base_layer(x, *args, **kwargs) + + if self.disable_adapters or not self.active_adapters: + return result + + torch_result_dtype = result.dtype + + lily_A_keys = self.lily_A.keys() + + for active_adapter in self.active_adapters: + if active_adapter not in lily_A_keys: + continue + + lily_A = self.lily_A[active_adapter] + lily_B = self.lily_B[active_adapter] + router = self.lily_router[active_adapter] + num_B = self.num_B[active_adapter] + B = lily_B.weight.reshape(num_B, -1, lily_B.weight.shape[1]) + scaling = self.scaling[active_adapter] + x = self._cast_input_dtype(x, lily_A.weight.dtype) + hidden = lily_A(x) + router_logits = router(hidden) # [B, N, num_of_experts] + router_probability = F.softmax(router_logits, dim=-1) # [B, N, num_of_experts] + expert_probabilities = router_probability.reshape(-1, num_B).mean(dim=0) + combined_B = torch.einsum("e,eio->io", expert_probabilities, B) + delta = torch.matmul(hidden, combined_B) + result = result + (delta * scaling).to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lily." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f0814797b4ac569bd8812647c9855f403232cc75 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lily/model.py @@ -0,0 +1,169 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch +from torch import nn + +from peft.tuners.tuners_utils import ( + BaseTuner, + BaseTunerLayer, +) +from peft.utils import TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING + +from .config import LilyConfig +from .layer import LilyLayer, Linear + + +class LilyModel(BaseTuner): + """ + Creates a Low-Rank Interconnected Adaptation Across Layers (Lily) model from a pretrained transformers model. + + The method is described in detail in https://arxiv.org/abs/2407.09946. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LilyConfig`]): The configuration of the Lily model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The Lily PEFT model. + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`LilyConfig`]): The configuration of the Lily model. + """ + + prefix: str = "lily_" + tuner_layer_cls = LilyLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + lily_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + """ + Create a new Lily layer with independent A and B for each layer. Sharing of A/B across layers is deferred to + _post_injection_hook. + """ + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + if isinstance(target, LilyLayer): + target.update_layer( + adapter_name, + lily_config.r, + scaling=lily_config.scaling, + stride_A=lily_config.stride_A, + num_B=lily_config.num_B, + init_weights=lily_config.init_weights, + ) + else: + new_module = self._create_new_module(lily_config, adapter_name, target) + if adapter_name not in self.active_adapters: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(lily_config, adapter_name, target): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + return Linear( + target, + adapter_name, + r=lily_config.r, + scaling=lily_config.scaling, + stride_A=lily_config.stride_A, + num_B=lily_config.num_B, + init_weights=lily_config.init_weights, + ) + + raise NotImplementedError(f"Lily does not support target modules of type {type(target_base_layer)} yet.") + + def _post_injection_hook(self, model: nn.Module, config: LilyConfig, adapter_name: str) -> None: + """ + After all layers have been independently initialized, apply A/B sharing across layers. + + A sharing: for each (target_module_suffix, weight_shape) group, consecutive blocks of `stride_A` layers share + the same A. The first layer in each block keeps its own A; subsequent layers in the block have their lily_A + replaced by the group leader's. + + B sharing: all layers in the same (target_module_suffix, weight_shape) group share the B from the very first + layer in that group. + + Both lily_A and lily_B are nn.Linear modules, so they move correctly with model.to(device) via standard + nn.Module parameter propagation. + + Note: (target_module_suffix, weight_shape) is used as the group key rather than target_module_suffix alone, to + correctly handle architectures like UNet where the same target key can appear with different shapes across + layers. + """ + stride_A = config.stride_A + + # Collect all adapted LilyLayer modules in traversal order, grouped by + # (target_module_suffix, weight_shape). + # Maps (target_suffix, weight_shape) -> list of LilyLayer in traversal order. + target_to_layers: dict[tuple[str, torch.Size], list[LilyLayer]] = {} + + for key, module in model.named_modules(): + if not isinstance(module, LilyLayer): + continue + if adapter_name not in module.lily_A: + continue + + base = module.get_base_layer() + shape = base.weight.shape # (out_features, in_features) + + # Find the longest matching target suffix for this key + matched_suffix = None + if isinstance(config.target_modules, str): + matched_suffix = config.target_modules + else: + for suffix in config.target_modules: + if key.endswith(suffix): + matched_suffix = suffix + + if matched_suffix is None: + # Should not happen since inject_adapter already matched this layer + continue + + group_key = (matched_suffix, shape) + if group_key not in target_to_layers: + target_to_layers[group_key] = [] + target_to_layers[group_key].append(module) + + # Apply A and B sharing for each (target_suffix, shape) group. + for (target_suffix, shape), layers in target_to_layers.items(): + # B sharing: all layers share the first layer's B + shared_B = layers[0].lily_B[adapter_name] + for i, layer in enumerate(layers): + if i != 0: + layer.lily_B[adapter_name] = shared_B + + # A sharing: layers within the same stride_A block share the group leader's A. + # Group leader is the first layer in each block of stride_A consecutive layers. + group_idx = (i // stride_A) * stride_A + if i != group_idx: + layer.lily_A[adapter_name] = layers[group_idx].lily_A[adapter_name] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8f90a8fb058cf75450b89166bf2e562f07b835fd --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import LNTuningConfig +from .model import LNTuningModel + + +__all__ = ["LNTuningConfig", "LNTuningModel"] + +register_peft_method(name="ln_tuning", config_cls=LNTuningConfig, model_cls=LNTuningModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..127ee9017333bce22706b58b13701049244b1da9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/config.py @@ -0,0 +1,70 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class LNTuningConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a :class:`~peft.tuners.LNTuningModel`. + + Args: + target_modules (`Optional[Union[List[str], str]]`): + List of module names or regex expression of the module names to replace with LNTuning. For example, + '.*decoder.*' or '.*encoder.*'. If this is not specified, modules will be chosen according to the model + architecture. If the architecture is not known, an error will be raised -- in this case, you should specify + the target modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + modules_to_save (`Optional[Union[List[str], str]]`): + List of modules to be set as trainable and saved in the final checkpoint. For example, in Sequence + Classification or Token Classification tasks, the final layer `classifier/score` are randomly initialized + and as such need to be trainable and saved. + """ + + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with LNTuning." + "For example, '.*decoder.*' or '.*encoder.*'. " + "If not specified, modules will be chosen according to the model architecture, If the architecture is " + "not known, an error will be raised -- in this case, you shoud specify the target modules manually." + ), + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from LNTuning."}, + ) + modules_to_save: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of modules to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.LN_TUNING diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..4000e992a791c02f59398ced7c2fa24e8c15c342 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/layer.py @@ -0,0 +1,123 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from copy import deepcopy +from typing import Optional + +import torch +import torch.nn as nn + +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge + + +class LNTuningLayer(nn.Module, BaseTunerLayer): + """ + Selects a layer from the model. + """ + + adapter_layer_names = ("ln_tuning_layers",) + + def __init__(self, base_layer: nn.Module, adapter_name: str): + super().__init__() + self.base_layer = base_layer + self.ln_tuning_layers = nn.ModuleDict({}) + self.update_layer(self.base_layer, adapter_name) + self._active_adapter = adapter_name + self.merged_adapters = [] + + in_features, out_features = _get_in_out_features(self.get_base_layer()) + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, layer: nn.Module, adapter_name: str, inference_mode: bool = False, **kwargs): + self.ln_tuning_layers[adapter_name] = deepcopy(layer) + self.set_adapter(adapter_name, inference_mode=inference_mode) + + def enable_adapters(self, enabled: bool) -> None: + """Toggle the enabling and disabling of adapters + + Takes care of setting the requires_grad flag for the adapter weights. + + Args: + enabled (bool): True to enable adapters, False to disable adapters + """ + if enabled: + self.set_adapter(self.active_adapters) + self._disable_adapters = False + else: + if self.merged: + self.unmerge() + # disable grads on all adapter layers + for layer_name in self.adapter_layer_names: + layer = getattr(self, layer_name) + layer.requires_grad_(False) + self._disable_adapters = True + + def merge(self, adapter_names: Optional[list[str]] = None, safe_merge: bool = False): + # note that there is no actual merging, so whether safe_merge is True or False is irrelevant + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + if len(adapter_names) > 1: + raise ValueError( + f"Trying to merge {len(adapter_names)} adapters, but LN " + f"tuning does not allow merging more than one adapter at a time" + ) + merged_adapters = set(self.merged_adapters) + if merged_adapters: + warnings.warn(f"Already merged with {merged_adapters}. Unmerging first.") + self.unmerge() + + self.base_layer, self.ln_tuning_layers[adapter_names[0]] = ( + self.ln_tuning_layers[adapter_names[0]], + self.base_layer, + ) + self.merged_adapters.append(adapter_names[0]) + + def unmerge(self): + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + # popping one element is sufficient because LN + # tuning does not allow merging more than one adapter at a time. + merged_name = self.merged_adapters.pop() + self.base_layer, self.ln_tuning_layers[merged_name] = ( + self.ln_tuning_layers[merged_name], + self.base_layer, + ) + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged or (len(self.active_adapters) == 0): + result = self.base_layer(x, *args, **kwargs) + else: + if len(self.active_adapters) != 1: + raise ValueError( + f"Trying to run forward with {len(self.active_adapters)} active " + f"adapters, but LN tuning does not allow inference with more than one adapter at a time" + ) + active_adapter = self.active_adapters[0] + result = self.ln_tuning_layers[active_adapter](x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "ln_tuning." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..10d4551afbf44ad3eb3f9a9adfcc5cad160bef5c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/ln_tuning/model.py @@ -0,0 +1,137 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from typing import Optional + +from torch.nn.modules import Module +from tqdm import tqdm + +from peft.config import PeftConfig +from peft.tuners.tuners_utils import BaseTuner, _get_submodules +from peft.utils import TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING + +from .layer import LNTuningLayer + + +class LNTuningModel(BaseTuner): + """ + Creates LayerNorm tuning from a pretrained transformer model. + + The method is described in detail in https://huggingface.co/papers/2312.11420. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LNTuningConfig`]): The configuration of the Lora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + This option has no effect on LN tuning but exists for consistency with other PEFT methods. + + Returns: + 'torch.nn.Module': The adapted model with LayerNorm tuned on. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import get_peft_model, TaskType, LNTuningConfig + + >>> peft_config = LNTuningConfig( + ... task_type=TaskType.CAUSAL_LM, + ... ) + + >>> model = AutoModelForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf") + >>> model = get_peft_model(model, peft_config) + >>> model.print_trainable_parameters() + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`LNTuningConfig`]): The configuration of the Lora model. + """ + + prefix: str = "ln_tuning_" + tuner_layer_cls = LNTuningLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + peft_config: PeftConfig, + adapter_name: str, + target: Module, + target_name: str, + parent: Module, + current_key: str, + ) -> None: + # replace the original module with a same new module + new_module = self._create_new_module(peft_config, target, adapter_name) + if adapter_name != self.active_adapter: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + def _create_new_module( + self, + peft_config: PeftConfig, + target: Module, + adapter_name: str, + ) -> Module: + if not isinstance(target, LNTuningLayer): + new_module = LNTuningLayer(target, adapter_name) + else: + new_module = target + new_module.update_layer(target.base_layer, adapter_name) + return new_module + + def _unloading_checks(self, adapter_names: Optional[list[str]]): + adapters_to_consider = adapter_names or self.active_adapters + is_modules_to_save_available = any( + self.peft_config[adapter].modules_to_save for adapter in adapters_to_consider + ) + if is_modules_to_save_available and len(adapters_to_consider) > 1: + raise ValueError("Cannot unload multiple adapters that specify `modules_to_save`.") + + def _unload_and_optionally_merge( + self, + merge=True, + progressbar: bool = False, + safe_merge: bool = False, + adapter_names: Optional[list[str]] = None, + ): + self._unloading_checks(adapter_names) + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + desc = "Unloading adapters " + ("and merging " if merge else "") + "model" + + for key in tqdm(key_list, disable=not progressbar, desc=desc): + try: + parent, target, target_name = _get_submodules(self.model, key) + except AttributeError: + continue + + if hasattr(target, "base_layer"): + if merge: + target.merge(adapter_names) + self._replace_module(parent, target_name, target.get_base_layer(), target) + + # Clean up peft_config from the model since all PEFT modules have been removed. + # This prevents spurious warnings when re-wrapping the model with get_peft_model(). + if hasattr(self.model, "peft_config"): + del self.model.peft_config + + return self.model + + def _cast_adapter_dtype(self, adapter_name: str, autocast_adapter_dtype: bool = True) -> None: + # Note: LN Tuning does not add adapter layers, instead it creates copies of the original layer. For this reason, + # we need to skip adapter autocasting, otherwise we would change the dtype of copies of the original layer, + # resulting in dtype errors down the line. + pass diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..70dd1545bbd49b0aaa5eafbde05f82b6a04c3d74 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import LoHaConfig +from .layer import Conv2d, Linear, LoHaLayer +from .model import LoHaModel + + +__all__ = ["Conv2d", "Linear", "LoHaConfig", "LoHaLayer", "LoHaModel"] + +register_peft_method(name="loha", config_cls=LoHaConfig, model_cls=LoHaModel, prefix="hada_", is_mixed_compatible=True) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/config.py new file mode 100644 index 0000000000000000000000000000000000000000..79c1f630130133c393c18e09a2624795f9353157 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/config.py @@ -0,0 +1,143 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.tuners.lycoris_utils import LycorisConfig +from peft.utils import PeftType + + +@dataclass +class LoHaConfig(LycorisConfig): + """ + This is the configuration class to store the configuration of a [`LoHaModel`]. + + Args: + r (`int`): + LoHa rank. + alpha (`int`): + The alpha parameter for LoHa scaling. + rank_dropout (`float`): + The dropout probability for rank dimension during training. + module_dropout (`float`): + The dropout probability for disabling LoHa modules during training. + use_effective_conv2d (`bool`): + Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 ("Proposition 3" from FedPara + paper). + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen, + excluding the output layer. If this is not specified, modules will be chosen according to the model + architecture. If the architecture is not known, an error will be raised -- in this case, you should specify + the target modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + init_weights (`bool`): + Whether to perform initialization of adapter weights. This defaults to `True`, passing `False` is + discouraged. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + alpha_pattern (`dict`): + The mapping from layer names or regexp expression to alphas which are different from the default alpha + specified by `alpha`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field(default=8, metadata={"help": "LoHa rank"}) + alpha: int = field(default=8, metadata={"help": "LoHa alpha"}) + rank_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for rank dimension during training"} + ) + module_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for disabling LoHa modules during training"} + ) + use_effective_conv2d: bool = field( + default=False, + metadata={ + "help": ( + "Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 " + '("Proposition 3" from FedPara paper)' + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with LoHa." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer." + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from LoHa."}, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the LoHa layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. " + "This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from LoHA layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.LOHA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..dd250b6c48ded1a392db5d2fc33223b169cc7a3b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/layer.py @@ -0,0 +1,447 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Any + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.lycoris_utils import LycorisLayer + + +class LoHaLayer(nn.Module, LycorisLayer): + # All names of layers that may contain adapter weights + adapter_layer_names = ("hada_w1_a", "hada_w1_b", "hada_w2_a", "hada_w2_b", "hada_t1", "hada_t2") + # other_param_names is defined on parent class + + def __init__(self, base_layer: nn.Module): + super().__init__() + LycorisLayer.__init__(self, base_layer) + + # LoHa info + self.hada_w1_a = nn.ParameterDict({}) + self.hada_w1_b = nn.ParameterDict({}) + self.hada_w2_a = nn.ParameterDict({}) + self.hada_w2_b = nn.ParameterDict({}) + self.hada_t1 = nn.ParameterDict({}) + self.hada_t2 = nn.ParameterDict({}) + + @property + def _available_adapters(self) -> set[str]: + return {*self.hada_w1_a, *self.hada_w1_b, *self.hada_w2_a, *self.hada_w2_b, *self.hada_t1, *self.hada_t2} + + def create_adapter_parameters(self, adapter_name: str, r: int, shape: tuple[int, ...]): + # https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L130C9-L143C75 + if len(shape) == 4: # Conv2d + self.hada_t1[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], shape[3])) + self.hada_w1_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + + self.hada_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], shape[3])) + self.hada_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + elif len(shape) == 3: # Conv1d + self.hada_t1[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], 1)) + self.hada_w1_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + + self.hada_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], 1)) + self.hada_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0])) # out_dim, 1-mode + self.hada_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) # in_dim , 2-mode + else: # Linear + self.hada_w1_a[adapter_name] = nn.Parameter(torch.empty(shape[0], r)) + self.hada_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) + + self.hada_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0], r)) + self.hada_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1])) + + def reset_adapter_parameters(self, adapter_name: str): + # Original implementation performs initialization with normal distribution + # https://github.com/KohakuBlueleaf/LyCORIS/blob/3549fdef8f564761d68b695a08ef88b1122fdedc/lycoris/modules/loha.py#L158 + + # FedPara paper proposes to perform He initialization, let's stick with it + # It is enough to initialize only single matrix with zeros to make adapter do nothing after initialization + if adapter_name in self.hada_w1_a.keys(): + nn.init.kaiming_uniform_(self.hada_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w1_b[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.zeros_(self.hada_w2_b[adapter_name]) + if adapter_name in self.hada_t1.keys(): + nn.init.kaiming_uniform_(self.hada_t1[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_t2[adapter_name], a=math.sqrt(5)) + + def reset_adapter_parameters_random(self, adapter_name: str): + # Original implementation performs initialization with normal distribution + # https://github.com/KohakuBlueleaf/LyCORIS/blob/3549fdef8f564761d68b695a08ef88b1122fdedc/lycoris/modules/loha.py#L158 + + # FedPara paper proposes to perform He initialization, let's stick with it + # It is enough to initialize only single matrix with zeros to make adapter do nothing after initialization + if adapter_name in self.hada_w1_a.keys(): + nn.init.kaiming_uniform_(self.hada_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w1_b[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_w2_b[adapter_name], a=math.sqrt(5)) + if adapter_name in self.hada_t1.keys(): + nn.init.kaiming_uniform_(self.hada_t1[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.hada_t2[adapter_name], a=math.sqrt(5)) + + def update_layer( + self, + adapter_name: str, + r: int, + alpha: float, + rank_dropout: float, + module_dropout: float, + init_weights: bool, + use_effective_conv2d: bool = False, + inference_mode: bool = False, + **kwargs, + ) -> None: + """Internal function to create loha adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + alpha (`float`): Alpha for the added adapter. + rank_dropout (`float`): The dropout probability for rank dimension during training. + module_dropout (`float`): The dropout probability for disabling adapter during training. + init_weights (`bool`): Whether to initialize weights. + use_effective_conv2d (`bool`, *optional*, defaults to `False`): + Use parameter effective decomposition for Conv2d with ksize > 1. + """ + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.r[adapter_name] = r + self.alpha[adapter_name] = alpha + self.scaling[adapter_name] = alpha / r + self.rank_dropout[adapter_name] = rank_dropout + self.module_dropout[adapter_name] = module_dropout + + # Determine shape of LoHa weights + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + shape = tuple(base_layer.weight.shape) + elif isinstance(base_layer, nn.Conv2d): + # For 1x1 convolutions, disable effective_conv2d to avoid unnecessary tensor reshaping overhead. + # Since 1x1 convolutions are essentially pointwise operations (matrix multiplications), + # they can be more efficiently handled with the flattened weight representation, + # similar to how Linear layers work. This optimization reduces computational cost + # without affecting the mathematical equivalence of the operation. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size != (1, 1) + if use_effective_conv2d: + shape = (base_layer.out_channels, base_layer.in_channels, *base_layer.kernel_size) + else: + shape = ( + base_layer.out_channels, + base_layer.in_channels * base_layer.kernel_size[0] * base_layer.kernel_size[1], + ) + elif isinstance(base_layer, nn.Conv1d): + # For Conv1d with kernel_size=1, disable effective_conv2d for the same optimization reasons + # as 1x1 Conv2d. Kernel size 1 means no spatial/temporal context, making it equivalent + # to a Linear layer applied across the channel dimension. Using flattened representation + # avoids unnecessary reshaping and improves computational efficiency. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size[0] != 1 + if use_effective_conv2d: + shape = (base_layer.out_channels, base_layer.in_channels, base_layer.kernel_size[0]) + else: + shape = ( + base_layer.out_channels, + base_layer.in_channels * base_layer.kernel_size[0], + ) + else: + raise TypeError(f"LoHa is not implemented for base layers of type {type(base_layer).__name__}") + + # Create weights with provided shape + self.create_adapter_parameters(adapter_name, r, shape) + + # Initialize weights + if init_weights: + self.reset_adapter_parameters(adapter_name) + else: + self.reset_adapter_parameters_random(adapter_name) + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: + # https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L178 + if adapter_name in self.hada_t1.keys(): + weight = make_weight_cp( + self.hada_t1[adapter_name], + self.hada_w1_a[adapter_name], + self.hada_w1_b[adapter_name], + self.hada_t2[adapter_name], + self.hada_w2_a[adapter_name], + self.hada_w2_b[adapter_name], + scale=torch.tensor(self.scaling[adapter_name]), + ) + else: + weight = make_weight( + self.hada_w1_a[adapter_name], + self.hada_w1_b[adapter_name], + self.hada_w2_a[adapter_name], + self.hada_w2_b[adapter_name], + scale=torch.tensor(self.scaling[adapter_name]), + ) + + base_layer = self.get_base_layer() + + # Reshape to match base layer shape + weight = weight.reshape(base_layer.weight.shape) + + # Perform rank dropout during training - drop rows of addition weights + rank_dropout = self.rank_dropout[adapter_name] + if self.training and rank_dropout: + drop = (torch.rand(weight.size(0)) > rank_dropout).to(weight.dtype) + drop = drop.view(-1, *[1] * len(weight.shape[1:])).to(weight.device) + # TODO: Investigate if there should be a scaler like in normal dropout during training + # Original implementation doesn't have it + # https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L193 + drop /= drop.mean() + weight *= drop + + return weight + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + + # Execute all the adapters + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + module_dropout = self.module_dropout[active_adapter] + + # Modify current execution weights + if (not self.training) or (self.training and torch.rand(1) > module_dropout): + result = result + self._get_delta_activations(active_adapter, x, *args, **kwargs) + + result = result.to(previous_dtype) + return result + + +class Linear(LoHaLayer): + """LoHa implemented in Linear layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str = "default", + r: int = 0, + alpha: float = 0.0, + rank_dropout: float = 0.0, + module_dropout: float = 0.0, + init_weights: bool = True, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, rank_dropout, module_dropout, init_weights, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + return F.linear(input, delta_weight) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "loha." + rep + + +class Conv2d(LoHaLayer): + """LoHa implemented in Conv2d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str = "default", + r: int = 0, + alpha: float = 0.0, + rank_dropout: float = 0.0, + module_dropout: float = 0.0, + use_effective_conv2d: bool = False, + init_weights: bool = True, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer( + adapter_name, r, alpha, rank_dropout, module_dropout, init_weights, use_effective_conv2d, **kwargs + ) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv2d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "loha." + rep + + +class Conv1d(LoHaLayer): + """LoHa implemented in Conv1d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str = "default", + r: int = 0, + alpha: float = 0.0, + rank_dropout: float = 0.0, + module_dropout: float = 0.0, + use_effective_conv2d: bool = False, + init_weights: bool = True, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer( + adapter_name, r, alpha, rank_dropout, module_dropout, init_weights, use_effective_conv2d, **kwargs + ) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv1d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "loha." + rep + + +# Below code is a direct copy from https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py#L9 + + +class HadaWeight(torch.autograd.Function): + @staticmethod + def forward(ctx, w1a, w1b, w2a, w2b, scale=torch.tensor(1)): + ctx.save_for_backward(w1a, w1b, w2a, w2b, scale) + diff_weight = ((w1a @ w1b) * (w2a @ w2b)) * scale + return diff_weight + + @staticmethod + def backward(ctx, grad_out): + (w1a, w1b, w2a, w2b, scale) = ctx.saved_tensors + grad_out = grad_out * scale + temp = grad_out * (w2a @ w2b) + grad_w1a = temp @ w1b.T + grad_w1b = w1a.T @ temp + + temp = grad_out * (w1a @ w1b) + grad_w2a = temp @ w2b.T + grad_w2b = w2a.T @ temp + + del temp + return grad_w1a, grad_w1b, grad_w2a, grad_w2b, None + + +class HadaWeightCP(torch.autograd.Function): + @staticmethod + def forward(ctx, t1, w1a, w1b, t2, w2a, w2b, scale=torch.tensor(1)): + ctx.save_for_backward(t1, w1a, w1b, t2, w2a, w2b, scale) + + rebuild1 = torch.einsum("i j k l, j r, i p -> p r k l", t1, w1b, w1a) + rebuild2 = torch.einsum("i j k l, j r, i p -> p r k l", t2, w2b, w2a) + + return rebuild1 * rebuild2 * scale + + @staticmethod + def backward(ctx, grad_out): + (t1, w1a, w1b, t2, w2a, w2b, scale) = ctx.saved_tensors + grad_out = grad_out * scale + + temp = torch.einsum("i j k l, j r -> i r k l", t2, w2b) + rebuild = torch.einsum("i j k l, i r -> r j k l", temp, w2a) + + grad_w = rebuild * grad_out + del rebuild + + grad_w1a = torch.einsum("r j k l, i j k l -> r i", temp, grad_w) + grad_temp = torch.einsum("i j k l, i r -> r j k l", grad_w, w1a.T) + del grad_w, temp + + grad_w1b = torch.einsum("i r k l, i j k l -> r j", t1, grad_temp) + grad_t1 = torch.einsum("i j k l, j r -> i r k l", grad_temp, w1b.T) + del grad_temp + + temp = torch.einsum("i j k l, j r -> i r k l", t1, w1b) + rebuild = torch.einsum("i j k l, i r -> r j k l", temp, w1a) + + grad_w = rebuild * grad_out + del rebuild + + grad_w2a = torch.einsum("r j k l, i j k l -> r i", temp, grad_w) + grad_temp = torch.einsum("i j k l, i r -> r j k l", grad_w, w2a.T) + del grad_w, temp + + grad_w2b = torch.einsum("i r k l, i j k l -> r j", t2, grad_temp) + grad_t2 = torch.einsum("i j k l, j r -> i r k l", grad_temp, w2b.T) + del grad_temp + return grad_t1, grad_w1a, grad_w1b, grad_t2, grad_w2a, grad_w2b, None + + +def make_weight(w1a, w1b, w2a, w2b, scale): + return HadaWeight.apply(w1a, w1b, w2a, w2b, scale) + + +def make_weight_cp(t1, w1a, w1b, t2, w2a, w2b, scale): + return HadaWeightCP.apply(t1, w1a, w1b, t2, w2a, w2b, scale) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c39be6434d90fe47a8bdc7aae990d0ca4aaab230 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/loha/model.py @@ -0,0 +1,116 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +import torch +from torch import nn + +from peft.tuners.lycoris_utils import LycorisConfig, LycorisTuner +from peft.utils import TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING +from peft.utils.other import get_pattern_key + +from .layer import Conv1d, Conv2d, Linear, LoHaLayer + + +class LoHaModel(LycorisTuner): + """ + Creates Low-Rank Hadamard Product model from a pretrained model. The method is partially described in + https://huggingface.co/papers/2108.06098 Current implementation heavily borrows from + https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/loha.py + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`LoHaConfig`]): The configuration of the LoHa model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The LoHa model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import LoHaModel, LoHaConfig + + >>> config_te = LoHaConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... ) + >>> config_unet = LoHaConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... use_effective_conv2d=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = LoHaModel(model.text_encoder, config_te, "default") + >>> model.unet = LoHaModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`LoHaConfig`]): The configuration of the LoHa model. + """ + + prefix: str = "hada_" + tuner_layer_cls = LoHaLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING + layers_mapping: dict[type[torch.nn.Module], type[LoHaLayer]] = { + torch.nn.Conv2d: Conv2d, + torch.nn.Conv1d: Conv1d, + torch.nn.Linear: Linear, + } + + def _create_and_replace( + self, + config: LycorisConfig, + adapter_name: str, + target: Union[LoHaLayer, nn.Module], + target_name: str, + parent: nn.Module, + current_key: str, + ) -> None: + """ + A private method to create and replace the target module with the adapter module. + """ + r_key = get_pattern_key(config.rank_pattern.keys(), current_key) + alpha_key = get_pattern_key(config.alpha_pattern.keys(), current_key) + kwargs = config.to_dict() + kwargs["r"] = config.rank_pattern.get(r_key, config.r) + kwargs["alpha"] = config.alpha_pattern.get(alpha_key, config.alpha) + + if isinstance(target, LoHaLayer): + target.update_layer(adapter_name, **kwargs) + else: + new_module = self._create_new_module(config, adapter_name, target, **kwargs) + self._replace_module(parent, target_name, new_module, target) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f4fe0e92c6eacd0cc276ad3584230ea58ee4a8a6 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import LoKrConfig +from .layer import Conv2d, Linear, LoKrLayer +from .model import LoKrModel + + +__all__ = ["Conv2d", "Linear", "LoKrConfig", "LoKrLayer", "LoKrModel"] + +register_peft_method(name="lokr", config_cls=LoKrConfig, model_cls=LoKrModel, is_mixed_compatible=True) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6d25dc5c129f711b59e848a38a63fac766d78754 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/config.py @@ -0,0 +1,155 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.tuners.lycoris_utils import LycorisConfig +from peft.utils import PeftType + + +@dataclass +class LoKrConfig(LycorisConfig): + """ + Configuration class of [`LoKrModel`]. + + Args: + r (`int`): + LoKr rank. + alpha (`int`): + The alpha parameter for LoKr scaling. + rank_dropout (`float`): + The dropout probability for rank dimension during training. + module_dropout (`float`): + The dropout probability for disabling LoKr modules during training. + use_effective_conv2d (`bool`): + Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 ("Proposition 3" from FedPara + paper). + decompose_both (`bool`): + Perform rank decomposition of left kronecker product matrix. + decompose_factor (`int`): + Kronecker product decomposition factor. + rank_dropout_scale ('bool) + Whether to scale the rank dropout while training, defaults to `False`. + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen, + excluding the output layer. If this is not specified, modules will be chosen according to the model + architecture. If the architecture is not known, an error will be raised -- in this case, you should specify + the target modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + init_weights (`bool`): + Whether to perform initialization of adapter weights. This defaults to `True`. Use "lycoris" to initialize + weights in the style of the LYCORIS repository. Passing `False` is discouraged. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + alpha_pattern (`dict`): + The mapping from layer names or regexp expression to alphas which are different from the default alpha + specified by `alpha`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + modules_to_save (`Optional[List[str]]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field(default=8, metadata={"help": "LoKr rank"}) + alpha: int = field(default=8, metadata={"help": "LoKr alpha"}) + rank_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for rank dimension during training"} + ) + module_dropout: float = field( + default=0.0, metadata={"help": "The dropout probability for disabling LoKr modules during training"} + ) + use_effective_conv2d: bool = field( + default=False, + metadata={ + "help": ( + "Use parameter effective decomposition for Conv2d (and Conv1d) with ksize > 1 " + '("Proposition 3" from FedPara paper)' + ) + }, + ) + decompose_both: bool = field( + default=False, + metadata={"help": "Perform rank decomposition of left kronecker product matrix."}, + ) + decompose_factor: int = field(default=-1, metadata={"help": "Kronecker product decomposition factor."}) + rank_dropout_scale: bool = field(default=False, metadata={"help": "Rank dropout scale"}) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with LoKr." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer." + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from LoKr."}, + ) + init_weights: Union[bool, Literal["lycoris"]] = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the LoKr layers with their default initialization. Can be True, False or 'lycoris'." + "Default is True. Don't change this setting to False, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. " + "This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from LoKr layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.LOKR + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..f6221592562f204921de705ffc7dc96ac0fa7f2d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/layer.py @@ -0,0 +1,514 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.lycoris_utils import LycorisLayer + + +class LoKrLayer(nn.Module, LycorisLayer): + # All names of layers that may contain adapter weights + adapter_layer_names = ( + "lokr_w1", + "lokr_w1_a", + "lokr_w1_b", + "lokr_w2", + "lokr_w2_a", + "lokr_w2_b", + "lokr_t2", + ) + # other_param_names is defined on parent class + + def __init__(self, base_layer: nn.Module) -> None: + super().__init__() + LycorisLayer.__init__(self, base_layer) + + # LoKr info + self.lokr_w1 = nn.ParameterDict({}) + self.lokr_w1_a = nn.ParameterDict({}) + self.lokr_w1_b = nn.ParameterDict({}) + self.lokr_w2 = nn.ParameterDict({}) + self.lokr_w2_a = nn.ParameterDict({}) + self.lokr_w2_b = nn.ParameterDict({}) + self.lokr_t2 = nn.ParameterDict({}) + + @property + def _available_adapters(self) -> set[str]: + return { + *self.lokr_w1, + *self.lokr_w1_a, + *self.lokr_w1_b, + *self.lokr_w2, + *self.lokr_w2_a, + *self.lokr_w2_b, + *self.lokr_t2, + } + + def create_adapter_parameters( + self, + adapter_name: str, + r: int, + shape, + use_w1: bool, + use_w2: bool, + use_effective_conv2d: bool, + ): + if use_w1: + self.lokr_w1[adapter_name] = nn.Parameter(torch.empty(shape[0][0], shape[1][0])) + else: + self.lokr_w1_a[adapter_name] = nn.Parameter(torch.empty(shape[0][0], r)) + self.lokr_w1_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][0])) + + # Handle both Conv2d and Conv1d + if len(shape) == 4: # Conv2d + if use_w2: + self.lokr_w2[adapter_name] = nn.Parameter(torch.empty(shape[0][1], shape[1][1], *shape[2:])) + elif use_effective_conv2d: + self.lokr_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], shape[3])) + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0][1])) # b, 1-mode + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1])) # d, 2-mode + else: + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0][1], r)) + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1] * shape[2] * shape[3])) + elif len(shape) == 3: # Conv1d + if use_w2: + self.lokr_w2[adapter_name] = nn.Parameter(torch.empty(shape[0][1], shape[1][1], shape[2])) + elif use_effective_conv2d: # Even for Conv1d, use the effective parameter for kernel dimension + # We pass (r, r, kernel_size, 1) in order to be compatible with the 2d assumptions made + # in make_weight_cp (only relevant for the effective conv2d case). + self.lokr_t2[adapter_name] = nn.Parameter(torch.empty(r, r, shape[2], 1)) + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(r, shape[0][1])) # b, 1-mode + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1])) # d, 2-mode + else: + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0][1], r)) + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1] * shape[2])) + else: + # Linear + if use_w2: + self.lokr_w2[adapter_name] = nn.Parameter(torch.empty(shape[0][1], shape[1][1])) + else: + self.lokr_w2_a[adapter_name] = nn.Parameter(torch.empty(shape[0][1], r)) + self.lokr_w2_b[adapter_name] = nn.Parameter(torch.empty(r, shape[1][1])) + + def reset_adapter_parameters(self, adapter_name: str): + if adapter_name in self.lokr_w1: + nn.init.zeros_(self.lokr_w1[adapter_name]) + else: + nn.init.zeros_(self.lokr_w1_a[adapter_name]) + nn.init.kaiming_uniform_(self.lokr_w1_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_w2: + nn.init.kaiming_uniform_(self.lokr_w2[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w2_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_t2: + nn.init.kaiming_uniform_(self.lokr_t2[adapter_name], a=math.sqrt(5)) + + def reset_adapter_parameters_random(self, adapter_name: str): + if adapter_name in self.lokr_w1: + nn.init.kaiming_uniform_(self.lokr_w1[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w1_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_w2: + nn.init.kaiming_uniform_(self.lokr_w2[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w2_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w2_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_t2: + nn.init.kaiming_uniform_(self.lokr_t2[adapter_name], a=math.sqrt(5)) + + # Initializes weight matrices similar to the way initialized in the LyCORIS repository. + def reset_adapter_parameters_lycoris_way(self, adapter_name): + if adapter_name in self.lokr_w1: + nn.init.kaiming_uniform_(self.lokr_w1[adapter_name], a=math.sqrt(5)) + else: + nn.init.kaiming_uniform_(self.lokr_w1_a[adapter_name], a=math.sqrt(5)) + nn.init.kaiming_uniform_(self.lokr_w1_b[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_w2: + nn.init.zeros_(self.lokr_w2[adapter_name]) + else: + nn.init.zeros_(self.lokr_w2_b[adapter_name]) + nn.init.kaiming_uniform_(self.lokr_w2_a[adapter_name], a=math.sqrt(5)) + + if adapter_name in self.lokr_t2: + nn.init.kaiming_uniform_(self.lokr_t2[adapter_name], a=math.sqrt(5)) + + def update_layer( + self, + adapter_name: str, + r: int, + alpha: float, + rank_dropout: float, + module_dropout: float, + init_weights: bool, + use_effective_conv2d: bool, + decompose_both: bool, + decompose_factor: int, + inference_mode: bool = False, + **kwargs, + ) -> None: + """Internal function to create lokr adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + alpha (`float`): Alpha for the added adapter. + rank_dropout (`float`): The dropout probability for rank dimension during training + module_dropout (`float`): The dropout probability for disabling adapter during training. + init_weights (`bool`): Whether to initialize adapter weights. + use_effective_conv2d (`bool`): Use parameter effective decomposition for Conv2d with ksize > 1. + decompose_both (`bool`): Perform rank decomposition of left kronecker product matrix. + decompose_factor (`int`): Kronecker product decomposition factor. + """ + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.r[adapter_name] = r + self.alpha[adapter_name] = alpha + self.scaling[adapter_name] = alpha / r + self.rank_dropout[adapter_name] = rank_dropout + self.module_dropout[adapter_name] = module_dropout + self.rank_dropout_scale[adapter_name] = kwargs["rank_dropout_scale"] + base_layer = self.get_base_layer() + + # Determine shape of LoKr weights + if isinstance(base_layer, nn.Linear): + in_dim, out_dim = base_layer.in_features, base_layer.out_features + + in_m, in_n = factorization(in_dim, decompose_factor) + out_l, out_k = factorization(out_dim, decompose_factor) + shape = ((out_l, out_k), (in_m, in_n)) # ((a, b), (c, d)), out_dim = a*c, in_dim = b*d + + use_w1 = not (decompose_both and r < max(shape[0][0], shape[1][0]) / 2) + use_w2 = not (r < max(shape[0][1], shape[1][1]) / 2) + use_effective_conv2d = False + elif isinstance(base_layer, nn.Conv2d): + in_dim, out_dim = base_layer.in_channels, base_layer.out_channels + k_size = base_layer.kernel_size + + in_m, in_n = factorization(in_dim, decompose_factor) + out_l, out_k = factorization(out_dim, decompose_factor) + shape = ((out_l, out_k), (in_m, in_n), *k_size) # ((a, b), (c, d), *k_size) + + use_w1 = not (decompose_both and r < max(shape[0][0], shape[1][0]) / 2) + use_w2 = r >= max(shape[0][1], shape[1][1]) / 2 + # For 1x1 convolutions, disable effective_conv2d to avoid unnecessary tensor reshaping overhead. + # Since 1x1 convolutions are essentially pointwise operations (matrix multiplications), + # they can be more efficiently handled with the flattened weight representation, + # similar to how Linear layers work. This optimization reduces computational cost + # without affecting the mathematical equivalence of the operation. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size != (1, 1) + elif isinstance(base_layer, nn.Conv1d): + in_dim, out_dim = base_layer.in_channels, base_layer.out_channels + k_size = (base_layer.kernel_size[0],) # Convert to a tuple with single element + + in_m, in_n = factorization(in_dim, decompose_factor) + out_l, out_k = factorization(out_dim, decompose_factor) + shape = ((out_l, out_k), (in_m, in_n), *k_size) # ((a, b), (c, d), k) + + use_w1 = not (decompose_both and r < max(shape[0][0], shape[1][0]) / 2) + use_w2 = r >= max(shape[0][1], shape[1][1]) / 2 + # For Conv1d with kernel_size=1, disable effective_conv2d for the same optimization reasons + # as 1x1 Conv2d. Kernel size 1 means no spatial/temporal context, making it equivalent + # to a Linear layer applied across the channel dimension. Using flattened representation + # avoids unnecessary reshaping and improves computational efficiency. + use_effective_conv2d = use_effective_conv2d and base_layer.kernel_size[0] != 1 + else: + raise TypeError(f"LoKr is not implemented for base layers of type {type(base_layer).__name__}") + + # Create weights with provided shape + self.create_adapter_parameters(adapter_name, r, shape, use_w1, use_w2, use_effective_conv2d) + + # Initialize weights + if init_weights: + if init_weights == "lycoris": + self.reset_adapter_parameters_lycoris_way(adapter_name) + else: + self.reset_adapter_parameters(adapter_name) + else: + self.reset_adapter_parameters_random(adapter_name) + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: + # https://github.com/KohakuBlueleaf/LyCORIS/blob/e4259b870d3354a9615a96be61cb5d07455c58ea/lycoris/modules/lokr.py#L224 + if adapter_name in self.lokr_w1: + w1 = self.lokr_w1[adapter_name] + else: + w1 = self.lokr_w1_a[adapter_name] @ self.lokr_w1_b[adapter_name] + + if adapter_name in self.lokr_w2: + w2 = self.lokr_w2[adapter_name] + elif adapter_name in self.lokr_t2: + w2 = make_weight_cp(self.lokr_t2[adapter_name], self.lokr_w2_a[adapter_name], self.lokr_w2_b[adapter_name]) + else: + w2 = self.lokr_w2_a[adapter_name] @ self.lokr_w2_b[adapter_name] + + # Make weights with Kronecker product + weight = make_kron(w1, w2, self.scaling[adapter_name]) + + # Get base layer for reshaping + base_layer = self.get_base_layer() + + # Regular reshape to match base layer shape + weight = weight.reshape(base_layer.weight.shape) + + # Perform rank dropout during training - drop rows of addition weights + rank_dropout = self.rank_dropout[adapter_name] + if self.training and rank_dropout: + drop = (torch.rand(weight.size(0)) > rank_dropout).float() + drop = drop.view(-1, *[1] * len(weight.shape[1:])).to(weight.device) + if self.rank_dropout_scale[adapter_name]: + drop /= drop.mean() + weight *= drop + + return weight + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + + # Execute all the adapters + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + module_dropout = self.module_dropout[active_adapter] + + # Modify current execution weights + if (not self.training) or (self.training and torch.rand(1) > module_dropout): + result = result + self._get_delta_activations(active_adapter, x, *args, **kwargs) + + result = result.to(previous_dtype) + return result + + +class Linear(LoKrLayer): + """LoKr implemented in Linear layer""" + + def __init__( + self, + base_layer: nn.Module, + device: Optional[Union[str, torch.device]] = None, + dtype: Optional[torch.dtype] = None, + adapter_name: str = "default", + r: int = 0, + alpha: float = 0.0, + rank_dropout: float = 0.0, + module_dropout: float = 0.0, + init_weights: bool = True, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, alpha, rank_dropout, module_dropout, init_weights, **kwargs) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + return F.linear(input, delta_weight) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "lokr." + rep + + +class Conv2d(LoKrLayer): + """LoKr implemented in Conv2d layer""" + + def __init__( + self, + base_layer: nn.Module, + device: Optional[Union[str, torch.device]] = None, + dtype: Optional[torch.dtype] = None, + adapter_name: str = "default", + r: int = 0, + alpha: float = 0.0, + rank_dropout: float = 0.0, + module_dropout: float = 0.0, + use_effective_conv2d: bool = False, + init_weights: bool = True, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer( + adapter_name, r, alpha, rank_dropout, module_dropout, init_weights, use_effective_conv2d, **kwargs + ) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv2d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "lokr." + rep + + +class Conv1d(LoKrLayer): + """LoKr implemented in Conv1d layer""" + + def __init__( + self, + base_layer: nn.Module, + device: Optional[Union[str, torch.device]] = None, + dtype: Optional[torch.dtype] = None, + adapter_name: str = "default", + r: int = 0, + alpha: float = 0.0, + rank_dropout: float = 0.0, + module_dropout: float = 0.0, + use_effective_conv2d: bool = False, + init_weights: bool = True, + **kwargs, + ): + super().__init__(base_layer) + + # Create adapter and set it active + self._active_adapter = adapter_name + self.update_layer( + adapter_name, r, alpha, rank_dropout, module_dropout, init_weights, use_effective_conv2d, **kwargs + ) + + def _get_delta_activations( + self, adapter_name: str, input: torch.Tensor, *args: Any, **kwargs: Any + ) -> torch.Tensor: + delta_weight = self.get_delta_weight(adapter_name) + input = self._cast_input_dtype(input, delta_weight.dtype) + # don't add bias here, because the bias is already included in the output of the base_layer + base_layer = self.get_base_layer() + return F.conv1d( + input, + delta_weight, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + + def __repr__(self) -> str: + rep = super().__repr__() + return "lokr." + rep + + +# Below code is a direct copy from https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/lokr.py#L11 + + +def factorization(dimension: int, factor: int = -1) -> tuple[int, int]: + """Factorizes the provided number into the product of two numbers + + Args: + dimension (`int`): The number that needs to be factorized. + factor (`int`, optional): + Factorization divider. The algorithm will try to output two numbers, one of each will be as close to the + factor as possible. If -1 is provided, the decomposition algorithm would try to search dividers near the + square root of the dimension. Defaults to -1. + + Returns: + Tuple[`int`, `int`]: A tuple of two numbers, whose product is equal to the provided number. The first number is + always less than or equal to the second. + + Example: + ```py + >>> factorization(256, factor=-1) + (16, 16) + + >>> factorization(128, factor=-1) + (8, 16) + + >>> factorization(127, factor=-1) + (1, 127) + + >>> factorization(128, factor=4) + (4, 32) + ``` + """ + + if factor > 0 and (dimension % factor) == 0: + m = factor + n = dimension // factor + return m, n + if factor == -1: + factor = dimension + m, n = 1, dimension + length = m + n + while m < n: + new_m = m + 1 + while dimension % new_m != 0: + new_m += 1 + new_n = dimension // new_m + if new_m + new_n > length or new_m > factor: + break + else: + m, n = new_m, new_n + if m > n: + n, m = m, n + return m, n + + +def make_weight_cp(t, wa, wb): + rebuild2 = torch.einsum("i j k l, i p, j r -> p r k l", t, wa, wb) # [c, d, k1, k2] + return rebuild2 + + +def make_kron(w1, w2, scale=1.0): + if len(w2.shape) == 4: + w1 = w1.unsqueeze(2).unsqueeze(2) + w2 = w2.contiguous() + rebuild = torch.kron(w1, w2) + + return rebuild * scale diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/model.py new file mode 100644 index 0000000000000000000000000000000000000000..10e187a4bf2272af72481f261d92601ee67112fb --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lokr/model.py @@ -0,0 +1,118 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Union + +import torch +from torch import nn + +from peft.tuners.lycoris_utils import LycorisConfig, LycorisTuner +from peft.utils import TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING +from peft.utils.other import get_pattern_key + +from .layer import Conv1d, Conv2d, Linear, LoKrLayer + + +class LoKrModel(LycorisTuner): + """ + Creates Low-Rank Kronecker Product model from a pretrained model. The original method is partially described in + https://huggingface.co/papers/2108.06098 and in https://huggingface.co/papers/2309.14859 Current implementation + heavily borrows from + https://github.com/KohakuBlueleaf/LyCORIS/blob/eb460098187f752a5d66406d3affade6f0a07ece/lycoris/modules/lokr.py + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`LoKrConfig`]): The configuration of the LoKr model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The LoKr model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import LoKrModel, LoKrConfig + + >>> config_te = LoKrConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... ) + >>> config_unet = LoKrConfig( + ... r=8, + ... lora_alpha=32, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... rank_dropout=0.0, + ... module_dropout=0.0, + ... init_weights=True, + ... use_effective_conv2d=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = LoKrModel(model.text_encoder, config_te, "default") + >>> model.unet = LoKrModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`LoKrConfig`]): The configuration of the LoKr model. + """ + + prefix: str = "lokr_" + tuner_layer_cls = LoKrLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING + layers_mapping: dict[type[torch.nn.Module], type[LoKrLayer]] = { + torch.nn.Conv2d: Conv2d, + torch.nn.Conv1d: Conv1d, + torch.nn.Linear: Linear, + } + + def _create_and_replace( + self, + config: LycorisConfig, + adapter_name: str, + target: Union[LoKrLayer, nn.Module], + target_name: str, + parent: nn.Module, + current_key: str, + ) -> None: + """ + A private method to create and replace the target module with the adapter module. + """ + r_key = get_pattern_key(config.rank_pattern.keys(), current_key) + alpha_key = get_pattern_key(config.alpha_pattern.keys(), current_key) + kwargs = config.to_dict() + kwargs["r"] = config.rank_pattern.get(r_key, config.r) + kwargs["alpha"] = config.alpha_pattern.get(alpha_key, config.alpha) + kwargs["rank_dropout_scale"] = config.rank_dropout_scale + + if isinstance(target, LoKrLayer): + target.update_layer(adapter_name, **kwargs) + else: + new_module = self._create_new_module(config, adapter_name, target, **kwargs) + self._replace_module(parent, target_name, new_module, target) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..26b6fbfa246fffa43044b7f078dc8905bde1e30c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/__init__.py @@ -0,0 +1,71 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_eetq_available +from peft.utils import register_peft_method + +from .arrow import create_arrow_model +from .config import ArrowConfig, BdLoraConfig, EvaConfig, LoftQConfig, LoraConfig, LoraGAConfig, LoraRuntimeConfig +from .conversion import convert_to_lora, save_as_lora +from .eva import get_eva_state_dict, initialize_lora_eva_weights +from .gptq import GPTQLoraLinear +from .layer import Conv2d, Conv3d, Embedding, Linear, LoraLayer, ParamWrapper +from .loraga import preprocess_loraga +from .model import LoraModel + + +__all__ = [ + "ArrowConfig", + "BdLoraConfig", + "Conv2d", + "Conv3d", + "Embedding", + "EvaConfig", + "GPTQLoraLinear", + "Linear", + "LoftQConfig", + "LoraConfig", + "LoraGAConfig", + "LoraLayer", + "LoraModel", + "LoraRuntimeConfig", + "ParamWrapper", + "convert_to_lora", + "create_arrow_model", + "get_eva_state_dict", + "initialize_lora_eva_weights", + "preprocess_loraga", + "save_as_lora", +] + +register_peft_method(name="lora", config_cls=LoraConfig, model_cls=LoraModel, is_mixed_compatible=True) + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + if (name == "EetqLoraLinear") and is_eetq_available(): + from .eetq import EetqLoraLinear + + return EetqLoraLinear + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/aqlm.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/aqlm.py new file mode 100644 index 0000000000000000000000000000000000000000..fd7dec3991db18c5845a9b14151f70b79aa79a2b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/aqlm.py @@ -0,0 +1,109 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional + +import torch + +from peft.import_utils import is_aqlm_available +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +if is_aqlm_available(): + from aqlm import QuantizedLinear + + +class AqlmLoraLinear(torch.nn.Module, LoraLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + result = self.base_layer(x) + + if self.disable_adapters: + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + output = lora_B(lora_A(dropout(x))) + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling + result += output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + # TODO: Check if it is better as suggested by users https://github.com/PanQiWei/AutoGPTQ/pull/102 + # def reset_lora_parameters(self, adapter_name): + # if adapter_name in self.lora_A.keys(): + # torch.nn.init.xavier_uniform_(self.lora_A[adapter_name].weight) + # torch.nn.init.zeros_(self.lora_B[adapter_name].weight) + + +def dispatch_aqlm( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_aqlm_available() and isinstance(target_base_layer, QuantizedLinear): + new_module = AqlmLoraLinear(target, adapter_name, config=config, **kwargs) + target.qweight = target_base_layer.codes + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/arrow.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/arrow.py new file mode 100644 index 0000000000000000000000000000000000000000..8a6e7056eb3c08c863b31ce39b58ebc60e5d8e24 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/arrow.py @@ -0,0 +1,476 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import os +from typing import Any + +import torch +from torch import nn +from transformers import PreTrainedModel + +from .config import ArrowConfig + + +TASK_ADAPTER_PREFIX = "task_" +GKS_ADAPTER_PREFIX = "gks_" + + +class ArrowLoraLinearLayer(nn.Module): + """ + This class represent the main logic of the arrow routing algorithm for linear layers. + """ + + def __init__(self, in_features, arrow_config): + super().__init__() + # extra parameters needed for arrow + self.in_features = in_features + self._protos_ready = False + self.top_k = arrow_config.top_k + self.temperature = arrow_config.router_temperature + self.rng_seed = arrow_config.rng_seed + self.task_adapter_names = ( + arrow_config.task_adapter_names.copy() + ) # Set in create_arrow_model() with this format: task_0, task_1, ... + self.gks_adapter_names = ( + arrow_config.gks_adapter_names + ) # Set in create_arrow_model() with this format: gks_0, gks_1, ... + self.use_gks = arrow_config.use_gks + self.gks_done = False + self.gks_added_adapter_names = [] + self.in_features = in_features + self.cast_input_dtype_enabled = True + + @torch.no_grad() + def on_adapter_change(self, lora_A, lora_B): + """ + Called when adapters are added/removed/renamed so Arrow can refresh its internal state before the next forward + pass. + """ + all_ts_adapter_names = [ + k + for k in lora_A.keys() + if k in lora_B and k != "arrow_router" and not (k.startswith("gks_") and k[len("gks_") :].isdigit()) + ] + + if sorted(self.task_adapter_names) == sorted(all_ts_adapter_names): # No changes in the ts_adapters + return + + # Getting the name(s) of added adapter(s) + if len(self.task_adapter_names) < len(all_ts_adapter_names): # Adapter(s) are added. + self.gks_added_adapter_names = [x for x in all_ts_adapter_names if x not in self.task_adapter_names] + + # Updating the task_adapter_names + self.task_adapter_names = all_ts_adapter_names.copy() + # Invalidate caches so they’ll be rebuilt lazily on next forward() + self._protos_ready = False + # GKS will be handled by self.gks_added_adapter_names + + def top_right_singular_vec_from_BA(self, A, B, iters=15, eps=1e-8): + """ + Computes the top *right* singular vector of ΔW = B @ A without forming ΔW. + + Theory: + For any matrix M, the right singular vectors are the eigenvectors of Mᵀ M. If ΔW = B @ A (with A ∈ + ℝ^{r×in}, B ∈ ℝ^{out×r}), then + ΔWᵀ ΔW = (B @ A)ᵀ (B @ A) = Aᵀ (Bᵀ B) A ∈ ℝ^{in×in}. + Therefore, the dominant right singular vector of ΔW is the dominant eigenvector of M := Aᵀ (Bᵀ B) A. We + find it by *power iteration* on the linear operator + v ↦ Aᵀ (Bᵀ B) (A v), + which avoids materializing ΔW (out×in) or M (in×in). The result lives in the input/token space (size = + in_features), which is exactly what Arrow needs. (Right singular vectors ≡ eigenvectors of MᵀM; power + iteration converges to the dominant eigenvector under mild conditions.) + =============================== Practical notes: + - We perform all iteration in float32 for numerical stability, then cast back + to the LoRA dtype/device before storing/using the prototype. + - Convergence is checked with a simple fixed-iter cap (`iters`) and/or + `allclose` tolerance (`tol`). + - The returned vector is unique up to sign (±), as with any singular vector. + Downstream code should be sign-invariant. + """ + + # A: (r, in), B: (out, r) + A32 = A.to(torch.float32) + B32 = B.to(torch.float32) + C = B32.T @ B32 # (r, r) + + # Private RNG on A's device + gen = None + if self.rng_seed is not None: + gen = torch.Generator(device=A32.device.type) + gen.manual_seed(int(self.rng_seed)) + + # init vector in input space + v = torch.randn(A32.size(1), dtype=A32.dtype, device=A32.device, generator=gen) + v = v / (v.norm() + eps) + + for _ in range(iters): + # w = (ΔWᵀΔW) v = Aᵀ (BᵀB) (A v) + w = A32.T @ (C @ (A32 @ v)) + v = w / (w.norm() + eps) + + return v # fp32 + + @torch.no_grad() + def build_prototypes(self, lora_A, lora_B): + """ + Computes a prototype vector for each LoRA module in every layer by applying Singular Value Decomposition (SVD) + to the `lora_A` matrix and extracting the top right singular vector. + + These prototypes are later used to calculate the cosine similarity between each input token and each expert. + The resulting similarity scores serve as coefficients to compute a weighted average of the corresponding LoRA + modules, effectively routing each token through its most relevant experts. + + ** This prototype computation is done is done once for all experts and is re-done on newly added adapters.** + + Args: + lora_A : Matrices A in LoRA layer. + lora_B (optional): Matrices B in LoRA layer. Defaults to None. + """ + + if self._protos_ready: + return + protos = [] + for name in self.task_adapter_names: + A = lora_A[name].weight # (r, in_features) + B = lora_B[name].weight # (out_features, r) + + # Efficiently computing right singular vector of A @ B + proto32 = self.top_right_singular_vec_from_BA(A, B) + + proto = proto32.to(dtype=A.dtype, device=A.device) + protos.append(proto) + + proto_stack = torch.stack(protos, dim=0) # (E, in_features) + + # Register the prototypes buffer with correct dtype/device consistent with A and B weights + self.register_buffer("prototypes", proto_stack, persistent=False) + self._protos_ready = True + + @torch.no_grad() + def gen_know_sub(self, lora_A, lora_B): + """ + This function performs General Knowledge Subtraction. It takes an average of provided general_adapters, and + subtract it from each task_adapter. This subtraction tries to purify the task adapters, based on + "forgetting-via-negation" principle. Forgetting-via-negation is a task-arithmetic operation, explained in: + https://huggingface.co/papers/2212.04089 The task adapters will be more focused and isolated, enhancing the + performance on new tasks. + + Args: + lora_A : Matrices A in LoRA layer. + lora_B : Matrices A in LoRA layer. + """ + if not self.use_gks: + return + elif self.gks_done and not self.gks_added_adapter_names: + return + else: + # 1) compute average A/B over gks_adapter_names + avg_A = torch.stack([lora_A[n].weight for n in self.gks_adapter_names], dim=0).mean( + 0 + ) # shape (r, in_features) + avg_B = torch.stack([lora_B[n].weight for n in self.gks_adapter_names], dim=0).mean( + 0 + ) # shape (out_features, r) + + # 2) Subtract the average from task-specific experts + if self.gks_done is False: # GKS is done for all the experts, since it hasn't been done yet. + for name in self.task_adapter_names: + lora_A[name].weight.data.sub_(avg_A) + lora_B[name].weight.data.sub_(avg_B) + else: # GKS is only done on new added experts, since GKS has been done previously. + for name in self.gks_added_adapter_names: + lora_A[name].weight.data.sub_(avg_A) + lora_B[name].weight.data.sub_(avg_B) + + # 3) Set gks_done flag as true, so we won't do it again in ArrowLinearVariant.forward(). + self.gks_done = True + # Clearing the self.gks_added_adapter_names + self.gks_added_adapter_names = [] + + def _cast_input_dtype(self, x, dtype: torch.dtype): + """ + Whether to cast the dtype of the input of the forward method. + + Usually, we want to enable this to align the input dtype with the dtype of the weight, but by setting + layer.cast_input_dtype=False, this can be disabled if necessary. + + Enabling or disabling can be managed via the peft.helpers.disable_lora_input_dtype_casting context manager. + """ + if x is None: # useful e.g. if x is the bias, which can be None + return None + + cast_input_dtype_enabled = getattr(self, "cast_input_dtype_enabled", True) + if (not cast_input_dtype_enabled) or (x.dtype == dtype): + return x + return x.to(dtype=dtype) + + def forward(self, x, lora_A, lora_B, dropout, scaling): + """ + Applies Arrow routing inside a LoRA layer. + + Steps: + 1. Compute cosine similarity between each token representation and all adapter prototypes. + 2. Select the top-k experts per token and normalize their scores with a softmax. + 3. Project tokens into each selected expert’s low-rank space (A weights). + 4. Map back to the output space (B weights). + 5. Aggregate expert outputs via the weighted sum of their contributions. + 6. Apply dropout, scaling, and return the reshaped delta. + + - Conceptually, this is a Mixture-of-Experts (MoE) over LoRA adapters, + where coefficients are derived from prototype similarity. + + Returns: + delta: LoRA output adjustment computed by Arrow routing. + """ + x = self._cast_input_dtype(x, lora_A[self.task_adapter_names[0]].weight.dtype) + B, *rest, F_in = x.shape + tok = x.view(-1, F_in) # (t, F_in) + t, E = tok.size(0), self.prototypes.size(0) + + # We now turn scaling, which is a dict, to tensors in order to use them later + scales_tens = torch.tensor( + [scaling[n] for n in self.task_adapter_names], + device=tok.device, + dtype=tok.dtype, + ) # shape (E,) + + # 1) similarity — sign-agnostic + sim = torch.abs(tok @ self.prototypes.T) # (t, E) + + # 2) top-k + softmax over full E (non-top-k = -inf) + top_v, idx = torch.topk(sim, self.top_k, dim=1) + full_score = tok.new_full((t, E), float("-inf")) + full_score.scatter_(1, idx, top_v) + coeff = torch.softmax(full_score / self.temperature, dim=1) # (t, E) + + # 3) stack all A and B weights once + # A_stack: (E, r, in_features), B_stack: (E, out_features, r) + A_stack = torch.stack([lora_A[n].weight for n in self.task_adapter_names], dim=0) + B_stack = torch.stack([lora_B[n].weight for n in self.task_adapter_names], dim=0) + + # 4) project tokens into each expert’s low‑rank space: + # z[e] = tok @ A_e.T → shape (t, E, r) + z = torch.einsum("tf, erf -> ter", tok, A_stack) + + # 5) lift back each expert’s output: + # y[e] = z[e] @ B_e.T → shape (t, E, out_features) + y = torch.einsum("ter, eor -> teo", z, B_stack) + + # 6) apply per-expert scaling before the weighted sum + # y_scaled[t, e, o] = scales[e] * y[t, e, o] + y = y * scales_tens.view(1, -1, 1) + + # 6) weighted sum over experts: + # delta_flat[t,o] = Σ_e coeff[t,e] * y[t,e,o] + delta_flat = torch.einsum("te, teo -> to", coeff, y) # (t, out_features) + + # 7) dropout, scale, and reshape + delta = dropout(delta_flat) + out_dim = delta_flat.size(-1) + return delta.view(B, *rest, out_dim) + + +def check_loaded_lora_compatibility_arrow(model, adapter_names: list[str]): + """ + After loading all adapters into `model`, check they share: + - the same LoRA rank (r) + - identical weight shapes + - identical sets of target_modules + Returns (sorted list of target module names, agreed rank r). + """ + reference = None # {'r':…, 'shapes':(Ashape,Bshape), 'modules':set([...])} + + for name in adapter_names: + curr_modules = set() + curr_r = None + curr_shapes = None + + for full_name, module in model.named_modules(): + if hasattr(module, "lora_A") and name in module.lora_A: + A = module.lora_A[name].weight + B = module.lora_B[name].weight + mod_name = full_name.split(".")[-1] + curr_modules.add(mod_name) + # A has shape (r, in_features); B has shape (out_features, r) + curr_r = A.shape[0] + curr_shapes = (A.shape, B.shape) + + if reference is None: + reference = {"r": curr_r, "shapes": curr_shapes, "modules": curr_modules} + else: + if curr_r != reference["r"]: + raise ValueError(f"[{name}] rank mismatch: {curr_r} != {reference['r']}") + if curr_shapes != reference["shapes"]: + raise ValueError(f"[{name}] shape mismatch: {curr_shapes} != {reference['shapes']}") + if curr_modules != reference["modules"]: + raise ValueError( + f"[{name}] target_modules mismatch:\n" + f" this adapter -> {sorted(curr_modules)}\n" + f" reference -> {sorted(reference['modules'])}" + ) + + agreed_modules = sorted(reference["modules"]) + return agreed_modules, int(reference["r"]) + + +def ensure_adapters_target_linear_layers_only(model, adapter_names: list[str]): + """ + Validate that every module holding LoRA weights for any of `adapter_names` is Linear-like: nn.Linear, + bitsandbytes.nn.Linear4bit, nn.Conv1d, or transformers.models.gpt2.modeling_gpt2.Conv1D. If not, raise. + """ + import torch.nn as nn + + Linear4bit = None + try: + import bitsandbytes as bnb # type: ignore + + Linear4bit = bnb.nn.Linear4bit + except ImportError: + pass + + HFConv1D = None + try: + from transformers.models.gpt2.modeling_gpt2 import Conv1D as HFConv1D # type: ignore + except ImportError: + pass + + allowed_types = (nn.Linear, nn.Conv1d) + if Linear4bit is not None: + allowed_types = allowed_types + (Linear4bit,) + if HFConv1D is not None: + allowed_types = allowed_types + (HFConv1D,) + + offenders = [] + + for full_name, module in model.named_modules(): + if hasattr(module, "lora_A"): + for name in adapter_names: + if name in getattr(module, "lora_A", {}): + base = getattr(module, "base_layer", None) or getattr(module, "original_module", None) + layer_to_check = base if base is not None else module + + if not isinstance(layer_to_check, allowed_types): + offenders.append((name, full_name, type(layer_to_check).__name__)) + + if offenders: + lines = [ + "LoRA adapters must only target Linear-like layers " + "(nn.Linear, nn.Conv1d, HF Conv1D, or bitsandbytes.nn.Linear4bit). Found:" + ] + for name, full_name, tname in offenders: + lines.append(f" - adapter '{name}' on module '{full_name}' of type {tname}") + raise TypeError("\n".join(lines)) + + +def _resolve_adapter_source(path: str) -> tuple[str, str | None]: + """ + Resolve a user-provided adapter `path` into (model_id, subfolder). + + Supports: + - Local path to a folder that contains `adapter_config.json` + - Hub path with subfolder, e.g. "user/repo/ts_expert_0[/more/...]", which becomes: + model_id="user/repo", subfolder="ts_expert_0[/more/...]" + - Plain Hub repo id "user/repo" (no subfolder) + """ + if os.path.isdir(path): + if not os.path.isfile(os.path.join(path, "adapter_config.json")): + raise ValueError(f"Local adapter path '{path}' does not contain 'adapter_config.json'.") + return path, None + + parts = path.strip("/").split("/") + if len(parts) >= 2: + model_id = "/".join(parts[:2]) + if len(parts) > 2: + subfolder = "/".join(parts[2:]) + return model_id, subfolder + return model_id, None + + return path, None + + +def create_arrow_model( + base_model: PreTrainedModel, + task_specific_adapter_paths: list[str], + arrow_config: ArrowConfig, + general_adapter_paths: list[str] | None = None, + **adapter_kwargs: Any, +): + if task_specific_adapter_paths is None or len(task_specific_adapter_paths) == 0: + raise ValueError("`task_specific_adapter_paths` should contain at least one adapter path") + + from peft import LoraConfig, PeftModel + + model_id0, sub0 = _resolve_adapter_source(task_specific_adapter_paths[0]) + initial_ts_expert_name = f"{TASK_ADAPTER_PREFIX}0" + + first_kwargs = dict(adapter_kwargs) + if sub0 is not None and "subfolder" not in first_kwargs: + first_kwargs["subfolder"] = sub0 + + model = PeftModel.from_pretrained( + base_model, + model_id=model_id0, + adapter_name=initial_ts_expert_name, + **first_kwargs, + ) + + for i in range(1, len(task_specific_adapter_paths)): + ts_expert_name = f"{TASK_ADAPTER_PREFIX}{i}" + mid, sub = _resolve_adapter_source(task_specific_adapter_paths[i]) + more_kwargs = dict(adapter_kwargs) + if sub is not None and "subfolder" not in more_kwargs: + more_kwargs["subfolder"] = sub + model.load_adapter( + model_id=mid, + adapter_name=ts_expert_name, + **more_kwargs, + ) + arrow_config.task_adapter_names = [f"{TASK_ADAPTER_PREFIX}{i}" for i in range(len(task_specific_adapter_paths))] + + if arrow_config.use_gks: + if general_adapter_paths is None or len(general_adapter_paths) == 0: + raise ValueError("You should provide general LoRA paths if you want to use GenKnowSub.") + for i in range(len(general_adapter_paths)): + gen_expert_name = f"{GKS_ADAPTER_PREFIX}{i}" + mid, sub = _resolve_adapter_source(general_adapter_paths[i]) + gks_kwargs = dict(adapter_kwargs) + if sub is not None and "subfolder" not in gks_kwargs: + gks_kwargs["subfolder"] = sub + model.load_adapter( + model_id=mid, + adapter_name=gen_expert_name, + **gks_kwargs, + ) + arrow_config.gks_adapter_names = [f"{GKS_ADAPTER_PREFIX}{i}" for i in range(len(general_adapter_paths))] + else: + arrow_config.gks_adapter_names = [] + + target_modules, r = check_loaded_lora_compatibility_arrow( + model, adapter_names=arrow_config.task_adapter_names + arrow_config.gks_adapter_names + ) + + ensure_adapters_target_linear_layers_only( + model, adapter_names=arrow_config.task_adapter_names + arrow_config.gks_adapter_names + ) + + router_cfg = LoraConfig( + arrow_config=arrow_config, + target_modules=target_modules, + r=r, + ) + model.add_adapter(adapter_name="arrow_router", peft_config=router_cfg) + model.set_adapter("arrow_router") + + return model diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/awq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/awq.py new file mode 100644 index 0000000000000000000000000000000000000000..3311bba9358aecc72561c8c44f0493a0cd59688b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/awq.py @@ -0,0 +1,104 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_gptqmodel_available +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +class AwqLoraLinear(torch.nn.Module, LoraLayer): + def __init__( + self, + base_layer, + adapter_name, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def forward(self, x: torch.Tensor): + result = self.quant_linear_module(x) + + if self.disable_adapters: + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + output = lora_B(lora_A(dropout(x))) + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling + result = result + output + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_awq( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_gptqmodel_available(): + from gptqmodel.nn_modules.qlinear.gemm_awq import AwqGEMMQuantLinear + + if isinstance(target_base_layer, AwqGEMMQuantLinear): + new_module = AwqLoraLinear(target, adapter_name, config=config, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..c6f4e769584fcee809ad5e44afb7217897165c82 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/bnb.py @@ -0,0 +1,587 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Any, Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight +from peft.utils.other import transpose + +from .config import LoraConfig +from .layer import LoraLayer, LoraVariant + + +VARIANT_KWARG_KEYS = ["alora_offsets"] + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config, **kwargs) -> Optional[LoraVariant]: + if config.arrow_config is not None: + from .variants import ArrowLinearVariant + + return ArrowLinearVariant() + + use_alora = config.alora_invocation_tokens is not None + if not config.use_dora and not use_alora: + return None + + from .variants import ALoraLinearVariant, DoraLinearVariant + + if use_alora: + return ALoraLinearVariant() + else: + return DoraLinearVariant() + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + warnings.warn( + "Merge lora module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8 + # dequantization directly + output = dequantize_bnb_weight(weight, state=state) + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output.to(lora_data.dtype).to(lora_data.device) + lora_data + else: + w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + if self.lora_bias[active_adapter]: + bias_data = self.get_base_layer().bias.data + self.lora_B[active_adapter].bias + if safe_merge and not torch.isfinite(bias_data): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + self.get_base_layer().bias.data = bias_data + + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + warnings.warn( + "Unmerge lora module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output.to(lora_data.dtype).to(lora_data.device) - lora_data + else: + w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias + state.reset_grads() + + def get_delta_weight(self, adapter): + return ( + transpose( + self.lora_B[adapter].weight @ self.lora_A[adapter].weight, + False, + ) + * self.scaling[adapter] + ) + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + result = self.base_layer(x, *args, **kwargs) + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + if active_adapter not in self.lora_variant: # vanilla LoRA: + output = lora_B(lora_A(dropout(sub_batch))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] += output + else: + alora_offsets = variant_kwargs.get("alora_offsets", None) + if alora_offsets is not None: + variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]] + output = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=sub_batch, + result=result[sub_batch_indices_list[i]], + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] = output + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **variant_kwargs, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + output = lora_B(lora_A(dropout(x))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result = result + output + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target.state.has_fp16_weights, + "threshold": target.state.threshold, + "index": target.index, + } + ) + new_module = Linear8bitLt(target, adapter_name, config=config, **eightbit_kwargs) + + return new_module + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.arrow_config is not None: + from .variants import ArrowLinearVariant + + return ArrowLinearVariant() + + use_alora = config.alora_invocation_tokens is not None + if not config.use_dora and not use_alora: + return None + + from .variants import ALoraLinearVariant, DoraLinearVariant + + if use_alora: + return ALoraLinearVariant() + else: + return DoraLinearVariant() + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + warnings.warn( + "Merge lora module to 4-bit linear may get different generations due to rounding errors." + ) + # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930 + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + + output = dequantize_bnb_weight(weight, state=weight.quant_state) + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output + lora_data + else: + w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + if self.lora_bias[active_adapter]: + bias_data = self.get_base_layer().bias.data + self.lora_B[active_adapter].bias + if safe_merge and not torch.isfinite(bias_data): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + self.get_base_layer().bias.data = bias_data + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + warnings.warn( + "Unmerge lora module to 4-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output - lora_data + else: + w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias + + def get_delta_weight(self, adapter): + return ( + transpose( + self.lora_B[adapter].weight @ self.lora_A[adapter].weight, + False, + ) + * self.scaling[adapter] + ) + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + result = self.base_layer(x, *args, **kwargs) + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + if active_adapter not in self.lora_variant: # vanilla LoRA + output = lora_B(lora_A(dropout(sub_batch))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] += output + else: + alora_offsets = variant_kwargs.get("alora_offsets", None) + if alora_offsets is not None: + variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]] + output = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=sub_batch, + result=result[sub_batch_indices_list[i]], + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] = output + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **variant_kwargs, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + # As per Tim Dettmers, for 4bit, we need to defensively clone here. + # The reason is that in some cases, an error can occur that backprop + # does not work on a manipulated view. This issue may be solved with + # newer PyTorch versions but this would need extensive testing to be + # sure. + result = result.clone() + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + output = lora_B(lora_A(dropout(x))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result = result + output + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + new_module = Linear4bit(target, adapter_name, config=config, **fourbit_kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..73cb43343c222656cb305789f5fdb0cd9dff591c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/config.py @@ -0,0 +1,933 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import importlib +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from torch import nn + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class LoraRuntimeConfig: + """ + This is the sub-configuration class to store the runtime configurations for the model. + + Args: + ephemeral_gpu_offload (`bool`): + Whether to use ephemeral GPU offloading for models partially kept in CPU memory. + """ + + ephemeral_gpu_offload: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use ephemeral GPU offloading for models partially kept in CPU memory. Ephemeral GPU offloading result in " + "the data involved in intense operations being momentarily copied over to the GPU, and the results copied " + "back to CPU. There is a momentary VRAM overhead, but operations are generally orders of magnitude faster " + "compared to performing them on the CPU. This is useful when parts of the model and/or components (such " + "as adapters) are kept in CPU memory until they are needed. Rather than perform expensive operations on " + "small data, the data is transferred to the GPU on-demand, the operation(s) performed, and the results " + "moved back to CPU memory. Currently only affects DoRA initialization." + ) + }, + ) + + +@dataclass +class LoftQConfig: + """ + This is the sub-configuration class to store the configuration of a [`LoraModel`]. + + Args: + bits_pattern (`dict`): The mapping from layer names or regexp expression to bits which are different from the + default bits specified by `bits`. For example, `{model.decoder.layers.0.encoder_attn.k_proj: 2`}. + bits (`int`): Quantization bits for LoftQ. + iter (`int`): Alternating iterations for LoftQ. + fake (`bool`): True: use fp16/fp32; used for first time to save weights. False: use bitsandbytes 4bit linear + models. weights can't be saved. Recommend to set to True, save the weights and load the saved weights in 4 + bits. + """ + + loftq_bits: int = field(default=4, metadata={"help": "Quantization bits for LoftQ"}) + loftq_iter: int = field(default=1, metadata={"help": "Alternating iterations for LoftQ"}) + + +@dataclass +class ArrowConfig: + """ + This is the sub-configuration class to store the configuration for Arrow and GenKnowSub algorithm. Arrow is a + routing algorithm to combine the trained LoRA modules to solve new tasks, proposed in + 'https://huggingface.co/papers/2405.11157'. GenKnowSub is a refinement on the trained modules before being combined + via Arrow, introduced in 'https://aclanthology.org/2025.acl-short.54/' + """ + + top_k: int = field( + default=3, + metadata={"help": "Number of top LoRA modules to combine in Arrow routing."}, + ) + + router_temperature: float = field( + default=1.0, + metadata={"help": "Softmax temperature for computing Arrow expert coefficients."}, + ) + + use_gks: bool = field( + default=False, + metadata={"help": "Enable GenKnowSub."}, + ) + + task_adapter_names: Optional[list[str]] = field( + default=None, + init=False, + metadata={"help": "list of task-specific LoRA adapter names. It will be set in create_arrow_model()."}, + ) + + gks_adapter_names: Optional[list[str]] = field( + default=None, + init=False, + metadata={ + "help": "list of general LoRA adapter names for GenKnowSub. It will be set in create_arrow_model()." + }, + ) + + rng_seed: Optional[int] = field( + default=None, + metadata={"help": "Optional RNG seed for reproducibility. If None, sampling is non-deterministic."}, + ) + + def __post_init__(self): + if self.top_k <= 0: + raise ValueError("top_k cannot be negative.") + if self.router_temperature <= 0: + raise ValueError("router_temperature must be greater than 0.") + + +@dataclass +class BdLoraConfig: + """ + Configuration for BD-LoRA (Block-Diagonal LoRA). BD-LoRA is a LoRA variant that can be used for efficient + multi-LoRA serving in inference engines. The speedup results from reduced inter-GPU communication by setting + certain LoRA modules to be block-diagonal. + + To determine which LoRA factors should be set as block-diagonal, follow these guidelines: + - For attention, set + - Q,K,V projections to be LoRA-B block-diagonal + - Out projection to be LoRA-A block-diagonal + - For MLPs, set + - Up, Gate projection to be LoRA-B block-diagonal + - Down projection to be LoRA-A block-diagonal + + For other modules and/or architectures, look into the code of your target inference engine. Modules that are + row-sharded should have LoRA-A block-diagonal, modules that are column-sharded should have LoRA-B block-diagonal. + + Args: + target_modules_bd_a: + Modules where the LoRA-A is block-diagonal. Matches each pattern in the list against the module name via + `pattern is in target_name`. Example: ['up_proj', 'q_proj', 'v_proj', 'k_proj'] + target_modules_bd_b: + Modules where the LoRA-B is block-diagonal. Matches each pattern in the list against the module name via + `pattern is in target_name`. Example: ['out_proj', 'down_proj'] + nblocks: Number of blocks in block-diagonal matrices + """ + + target_modules_bd_a: Optional[list[str]] = field( + default=None, + metadata={ + "help": "Modules where the LoRA-A is block-diagonal. Matches each pattern in the list against the " + "module name via `pattern is in target_name`. " + "Usually one should specify the q,k,v,up and gate projections here. " + "Example: ['up_proj', 'q_proj', 'v_proj', 'k_proj']" + }, + ) + target_modules_bd_b: Optional[list[str]] = field( + default=None, + metadata={ + "help": "Modules where the LoRA-B is block-diagonal. Matches each pattern in the list against the module " + "name via `pattern is in target_name`. Usually, one should specify out and down projections here. " + "Example: ['out_proj', 'down_proj']" + }, + ) + nblocks: int = ( + field( + default=1, + metadata={ + "help": "Number of blocks each block-diagonal matrix has. If using BD-LoRA to speed up inference, " + "set it to be equal to the desired sharding degree during serving." + }, + ), + ) + match_strict: bool = field( + default=True, + metadata={ + "help": "If set to true, requires each target_module to have either a block-diagonal LoRA-A or LoRA-B, " + "and raises an error otherwise. You can set this to False to mix LoRA and BD-LoRA training, " + "e.g. if some layers in your module do not benefit from BD-LoRA." + }, + ) + + def __post_init__(self): + overlap = set(self.target_modules_bd_a or []) & set(self.target_modules_bd_b or []) + if overlap: + raise ValueError( + "Found overlapping modules in target_modules_bd lists:" + f"{self.target_modules_bd_a} (A) and {self.target_modules_bd_b} (B)." + ) + + +@dataclass +class EvaConfig: + """ + This is the sub-configuration class to store the configuration for a data-driven initialization via EVA. EVA was + introduced in Explained Variance Adaptation. + + Args: + rho (`float`): + Rho value for EVA redistribution (>= 1.0). The maximum rank for a layer is lora_r * rho. Default is 2.0, + meaning the maximum rank allowed for a layer is 2r. Increasing rho will allow for a higher degree of + redistribution of ranks across layers. Some pre-trained models might be more sensitive to a rank + redistribution. It can therefore be beneficial to try rho=1.0 (no redistribution) if the performance is + lower than expected. + tau (`float`): + Cosine similarity threshold for early stopping. Compares the cosine similarity of right-singular vectors + between two consecutive SVD steps. If the cosine similarity is above this threshold, the SVD iteration is + stopped. Default is 0.99. + use_label_mask (`bool`): + Use label mask for EVA initialization. This means that positions where labels=label_mask_value are ignored + for the SVD computation. Setting use_label_mask=True is preferred in most cases and can be especially + beneficial for multi-turn conversations. The default value is True. Filtering out items based on the label + mask can sometimes lead to a small batch size and as a result instabilities in the SVD computation. For + cases where a large share of batch items would be filtered out, set use_label_mask=False. + label_mask_value (`int`): + If use_label_mask=True the value to look for to mask out ignored tokens. Default is -100. + whiten (`bool`): Apply whitening to singular vectors. Default is False. + Whitening has been shown to be beneficial for EVA in the vision domain. + adjust_scaling_factors (`bool`): + Adjust LoRA scaling factors after the rank redistribution. Setting this to True means the scaling factors + are adjusted so that all LoRA gradients have the same scale regardless of their rank. Default is True. + """ + + rho: float = field(default=2.0, metadata={"help": "Rho value for EVA redistribution"}) + tau: float = field(default=0.99, metadata={"help": "Cosine similarity threshold for early stopping"}) + use_label_mask: bool = field(default=True, metadata={"help": "Use label mask for EVA initialization"}) + label_mask_value: int = field( + default=-100, metadata={"help": "if use_label_mask=True the value to look for to mask out ignored tokens"} + ) + whiten: bool = field(default=False, metadata={"help": "Apply whitening to singular vectors"}) + adjust_scaling_factors: bool = field( + default=True, + metadata={"help": "Adjust LoRA scaling factors after the rank redistribution"}, + ) + + def __post_init__(self): + if self.rho < 1.0: + raise ValueError("`rho` must be >= 1.0") + if self.tau < 0.0 or self.tau > 1.0: + raise ValueError("`tau` must be between 0.0 and 1.0.") + + +@dataclass +class CordaConfig: + """ + This is the sub-configuration class to store the configuration of a [`LoraModel`]. + + Args: + cache_file (`Optional[str]`): + File to store the SVD cache. The SVD cache is much smaller than the residual model (for example, residual + model of Llama-3-8b is 15GB, while SVD cache is 1.4GB), but with SVD cache and original model weights, + residual model weights can be built quickly. If you need to reuse residual model weights with limited + storage, you can store the SVD cache instead. + covariance_file (`Optional[str]`): + File to store the covariance matrix. If you wish to train multiple models with different ranks, but they + sample from the same dataset, you can store the covariance matrix and reuse it for different ranks. Note + that covariance file is usually large (comparable to model size), so you will need sufficient storage. + corda_method (`Literal["ipm", "kpm"]`): + Method to build adapter. The KPM (Knowledge-Preserved Mode) not only achieves better performance than LoRA + on fine-tuning tasks, but also mitigates the catastrophic forgetting of pre-trained world knowledge. When + preserving pre-trained knowledge is not a concern, the IPM (Instruction-Previewed Mode) is favored because + it can further accelerate convergence and enhance the fine-tuning performance. Defaults to `'ipm'`. + verbose (`bool`): + If true, prints the progress of CorDA initialization. Defaults to `False`. + use_float16_for_covariance (`bool`): + If true, uses float16 for the covariance matrix. This can reduce the memory usage of the covariance matrix + by half, but may lead to numerical instability. Defaults to `False`. + prune_temporary_fields (`bool`): + If true, temporary fields generated in CorDA preprocessing will be pruned. Defaults to `True`. + """ + + cache_file: Optional[str] = field( + default=None, + metadata={ + "help": ( + "File to store the SVD cache. The SVD cache is much smaller than the residual model (for example, " + "residual model of Llama-3-8b is 15GB, while SVD cache is 1.4GB), but with SVD cache and original model " + "weights, residual model weights can be built quickly. If you need to reuse residual model weights with " + "limited storage, you can store the SVD cache instead." + ) + }, + ) + covariance_file: Optional[str] = field( + default=None, + metadata={ + "help": ( + "File to store the covariance matrix. If you wish to train multiple models with different ranks, but " + "they sample from the same dataset, you can store the covariance matrix and reuse it for different ranks. " + "Note that covariance file is usually large (comparable to model size), so you will need sufficient storage." + ) + }, + ) + corda_method: Literal["ipm", "kpm"] = field( + default="ipm", + metadata={ + "help": ( + "Method to build adapter. The KPM not only achieves better performance than LoRA on fine-tuning tasks, but " + "also mitigates the catastrophic forgetting of pre-trained world knowledge. When preserving pre-trained " + "knowledge is not a concern, the IPM is favored because it can further accelerate convergence and enhance " + "the fine-tuning performance." + ) + }, + ) + verbose: bool = field(default=False, metadata={"help": "If true, prints the progress of CorDA initialization."}) + use_float16_for_covariance: bool = field( + default=False, + metadata={ + "help": ( + "If true, uses float16 for the covariance matrix. This can reduce the memory usage of the covariance matrix " + "by half, but may lead to numerical instability." + ) + }, + ) + prune_temporary_fields: bool = field( + default=True, metadata={"help": "If true, temporary fields generated in CorDA preprocessing will be pruned."} + ) + + +@dataclass +class LoraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`LoraModel`]. + + Args: + r (`int`): + Lora attention dimension (the "rank"). + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen (if + the model is a PreTrainedModel, the output layer excluded). If this is not specified, modules will be + chosen according to the model architecture. If the architecture is not known, an error will be raised -- in + this case, you should specify the target modules manually. To avoid targeting any modules (because you want + to apply `target_parameters`), set `target_modules=[]`. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + lora_alpha (`int`): + The alpha parameter for Lora scaling. + lora_dropout (`float`): + The dropout probability for Lora layers. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + bias (`str`): + Bias type for LoRA. Can be 'none', 'all' or 'lora_only'. If 'all' or 'lora_only', the corresponding biases + will be updated during training. Be aware that this means that, even when disabling the adapters, the model + will not produce the same output as the base model would have without adaptation. + use_rslora (`bool`): + When set to True, uses [Rank-Stabilized LoRA](https://huggingface.co/papers/2312.03732) which sets the + adapter scaling factor to `lora_alpha/math.sqrt(r)`, since it was proven to work better. Otherwise, it will + use the original default value of `lora_alpha/r`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + init_lora_weights (`bool` | `Literal["gaussian", "eva", "olora", "pissa", "pissa_niter_[number of iters]", "corda", "loftq", "orthogonal"]`): + How to initialize the weights of the adapter layers. Passing True (default) results in the default + initialization from the reference implementation from Microsoft, with the LoRA B weight being set to 0. + This means that without further training, the LoRA adapter will be a no-op. Setting the initialization to + False leads to random initialization of LoRA A and B, meaning that LoRA is not a no-op before training; + this setting is intended for debugging purposes. Passing 'gaussian' results in Gaussian initialization + scaled by the LoRA rank for linear and layers. Pass `'loftq'` to use LoftQ initialization. Passing `'eva'` + results in a data-driven initialization of Explained + Variance Adaptation. EVA initializes LoRA based on the SVD of layer input activations and achieves SOTA + performance due to its ability to adapt to the finetuning data. Pass `'olora'` to use OLoRA initialization. + Passing `'pissa'` results in the initialization of Principal Singular values and Singular vectors Adaptation (PiSSA), which converges more rapidly than + LoRA and ultimately achieves superior performance. Moreover, PiSSA reduces the quantization error compared + to QLoRA, leading to further enhancements. Passing `'pissa_niter_[number of iters]'` initiates + Fast-SVD-based PiSSA initialization, where `[number of iters]` indicates the number of subspace iterations + to perform FSVD, and must be a nonnegative integer. When `[number of iters]` is set to 16, it can complete + the initialization of a 7B model within seconds, and the training effect is approximately equivalent to + using SVD. Passing `'corda'` results in the initialization of Context-Oriented Decomposition Adaptation, which + converges even more rapidly than PiSSA in Instruction-Previewed Mode, and preserves world knowledge better + than LoRA in Knowledge-Preserved Mode. Passing `"orthogonal"` results in LoRA A and B being intialized + orthogonally; in this, it resembles `"olora"`, but the base weights are left untouched (requires `r` to be + even, only supported for linear layers for now). + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + rank_pattern (`dict`): + The mapping from layer names or regexp expression to ranks which are different from the default rank + specified by `r`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + alpha_pattern (`dict`): + The mapping from layer names or regexp expression to alphas which are different from the default alpha + specified by `lora_alpha`. For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`. + megatron_config (`Optional[dict]`): + The TransformerConfig arguments for Megatron. It is used to create LoRA's parallel linear layer. You can + get it like this, `core_transformer_config_from_args(get_args())`, these two functions being from Megatron. + The arguments will be used to initialize the TransformerConfig of Megatron. You need to specify this + parameter when you want to apply LoRA to the ColumnParallelLinear and RowParallelLinear layers of megatron. + megatron_core (`Optional[str]`): + The core module from Megatron to use, defaults to `"megatron.core"`. + trainable_token_indices (`Optional[Union[List[int], dict[str, List[int]]]]`) + Lets you specify which token indices to selectively fine-tune without requiring to re-train the whole + embedding matrix using the `peft.TrainableTokensModel` method. You can specify token indices in two ways. + Either you specify a list of indices which will then target the model's input embedding layer (or, if not + found, `embed_tokens`). Alternatively, you can specify a dictionary where the key is the name of the + embedding module and the values are the list of token indices, e.g. `{'embed_tokens': [0, 1, ...]}`. Note + that training with FSDP requires `use_orig_params=True` to avoid issues with non-uniform `requires_grad`. + loftq_config (`Optional[LoftQConfig]`): + The configuration of LoftQ. If this is not None, then LoftQ will be used to quantize the backbone weights + and initialize Lora layers. Also pass `init_lora_weights='loftq'`. Note that you should not pass a + quantized model in this case, as LoftQ will quantize the model itself. + eva_config (`Optional[EvaConfig]`): + The configuration of EVA. At a minimum the dataset argument needs to be set (use the same dataset as for + finetuning). + corda_config (`Optional[CordaConfig]`): + The configuration of CorDA. If this is not None, then CorDA will be used to build the adapter layers. Also + pass `init_lora_weights='corda'`. + use_dora (`bool`): + Enable 'Weight-Decomposed Low-Rank Adaptation' (DoRA). This technique decomposes the updates of the weights + into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the magnitude is + handled by a separate learnable parameter. This can improve the performance of LoRA especially at low + ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a bigger overhead than pure + LoRA, so it is recommended to merge weights for inference. For more information, see + https://huggingface.co/papers/2402.09353. + alora_invocation_tokens (`List[int]`): + If not None, enable 'Activated LoRA' (aLoRA), with + alora_invocation_tokens being the tokenized invocation string for the adapter (must be present in all model + input strings). This technique selectively activates the adapter weights only on tokens during and after + the alora_invocation_tokens. When used in a CausalLM, this means that the KV cache prior to invocation is + interchangeable with that of the base model (and other aLoRA adapters operating this way). As a result, in + inference pipelines involving switching between base model inference and adapter inference (e.g. agentic + pipelines, see paper for examples), significant savings are realized (relative to LoRA) by saving prefill + operations. Overall adapter inference speedups of an order of magnitude or more can occur on vLLM, + depending on the length of the shared context. Note that merging is not possible due to the selective + application of the weights. + layer_replication (`List[Tuple[int, int]]`): + Build a new stack of layers by stacking the original model layers according to the ranges specified. This + allows expanding (or shrinking) the model without duplicating the base model weights. The new layers will + all have separate LoRA adapters attached to them. + runtime_config (`LoraRuntimeConfig`): + Runtime configurations (which are not saved or restored). + lora_bias (`bool`): + Defaults to `False`. Whether to enable the bias term for the LoRA B parameter. Typically, this should be + disabled. The main use case for this is when the LoRA weights were extracted from fully fine-tuned + parameters so the bias of those parameters can be taken into account. + target_parameters (`List[str]`, *optional*) + List of parameter names or regex expression of the parameter names to replace with LoRA. This argument + behaves similarly to `target_modules`, except that the parameter name should be passed. Generally, you + should use `target_modules` to target the module (e.g. `nn.Linear`). However, in some circumstances, this + is not possible. E.g., in many mixture of expert (MoE) layers in HF Transformers, instead of using + `nn.Linear`, an `nn.Parameter` is used. PEFT normally overwrites the `forward` method for LoRA, but for + `nn.Parameter`, there is none. Therefore, to apply LoRA to that parameter, it needs to be targeted with + `target_parameters`. As an example, for Llama4, you can pass: + `target_parameters=['feed_forward.experts.gate_up_proj', 'feed_forward.experts.down_proj]`. Passing a + string for regex matching is not implemented yet. + ensure_weight_tying (`bool`, *optional*) + Whether to tie weights or not after peft initialization. This will ensure that the adapters added to the + tied layers are also tied. This is only applicable for layers passed via `modules_to_save` and + `target_modules`. + + """ + + r: int = field(default=8, metadata={"help": "Lora attention dimension"}) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with LoRA. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded). " + "If not specified, modules will be chosen according to the model architecture, If the architecture is " + "not known, an error will be raised -- in this case, you should specify the target modules manually. " + "To avoid targeting any modules (because you want to apply `target_parameters`), set " + "`target_modules=[]`." + ), + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from Lora."}, + ) + lora_alpha: int = field(default=8, metadata={"help": "Lora alpha"}) + lora_dropout: float = field(default=0.0, metadata={"help": "Lora dropout"}) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + bias: Literal["none", "all", "lora_only"] = field( + default="none", metadata={"help": "Bias type for Lora. Can be 'none', 'all' or 'lora_only'"} + ) + use_rslora: bool = field( + default=False, + metadata={ + "help": ( + "When set to True, uses [Rank-Stabilized LoRA](https://huggingface.co/papers/2312.03732)" + " which sets the adapter scaling factor to `lora_alpha/math.sqrt(r)`, since it" + " was proven to work better. Otherwise, it will use the original default" + " value of `lora_alpha/r`." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from LoRA layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + init_lora_weights: ( + bool + | Literal["gaussian", "eva", "olora", "pissa", "pissa_niter_[number of iters]", "corda", "loftq", "orthogonal"] + ) = field( + default=True, + metadata={ + "help": ( + "How to initialize the weights of the LoRA layers. " + "Passing True (default) results in the default initialization from the reference implementation from " + "Microsoft, with the LoRA B weight being set to 0. This means that without further training, the LoRA " + "adapter will be a no-op. " + "Setting the initialization to False leads to random initialization of LoRA A and B, meaning that LoRA " + "is not a no-op before training; this setting is intended for debugging purposes. " + "Passing `'gaussian'` results in Gaussian initialization scaled by the LoRA rank for linear and layers. " + "Passing `'eva'` results in a data-driven initialization of Explained Variance Adaptation. " + "Passing `'olora'` results in OLoRA initialization. " + "Passing `'pissa'` results in PiSSA initialization. " + "Passing `'pissa_niter_[number of iters]'` initiates Fast-SVD-based PiSSA initialization, where " + "[number of iters] indicates the number of subspace iterations to perform fsvd, and must be a " + "nonnegative integer. " + "Passing `'corda'` results in CorDA initialization. " + "Pass `'loftq'` to use LoftQ initialization. " + "Pass `'orthogonal'` for orthogonal initialization of LoRA A and B." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index. " + "This only works when target_modules is a list of str." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern." + "This only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + }, + ) + rank_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to ranks which are different from the default rank specified by `r`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + alpha_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to alphas which are different from the default alpha specified by `lora_alpha`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + megatron_config: Optional[dict] = field( + default=None, + metadata={ + "help": ( + "The TransformerConfig from Megatron. It is used to create LoRA's parallel linear layer." + "You can get it like this, `core_transformer_config_from_args(get_args())`, " + "these two functions being from Megatron." + "You need to specify this parameter when you want to apply LoRA to the ColumnParallelLinear and " + "RowParallelLinear layers of megatron." + "It should be noted that we may not be able to use the `save_pretrained` and `from_pretrained` " + "functions, because TransformerConfig may not necessarily be serialized." + "But when using megatron, we can use `get_peft_model_state_dict` function and " + "megatron's framework, they can also save and load models and configurations." + ) + }, + ) + megatron_core: Optional[str] = field( + default="megatron.core", + metadata={ + "help": ( + "The core module from Megatron, it is used to create LoRA's parallel linear layer. " + "It only needs to be passed in when you need to use your own modified megatron core module. " + "Otherwise, it will use the default value `megatron.core`. " + ) + }, + ) + trainable_token_indices: Optional[Union[list[int], dict[str, list[int]]]] = field( + default=None, + metadata={ + "help": ( + "Lets you specify which token indices to selectively fine-tune without requiring to re-train the " + "whole embedding matrix using the `peft.TrainableTokensModel` method. You can specify token indices " + "in two ways. Either you specify a list of indices which will then target the model's input embedding " + "layer (or, if not found, `embed_tokens`). Alternatively, you can specify a dictionary where the key " + "is the name of the embedding module and the values are the list of token indices, e.g. " + "`{'embed_tokens': [0, 1, ...]}`. Note that training with FSDP requires `use_orig_params=True` to " + "avoid issues with non-uniform `requires_grad`." + ) + }, + ) + # dict type is used when loading config.json + loftq_config: Union[LoftQConfig, dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The configuration of LoftQ. If this is passed, then LoftQ will be used to quantize the backbone " + "weights and initialize Lora layers. Also set `init_lora_weights='loftq'` in this case." + ) + }, + ) + eva_config: Optional[EvaConfig] = field( + default=None, + metadata={ + "help": ( + "The configuration of EVA. If this is passed, then EVA will be used to initialize the LoRA layers. " + "Also set `init_lora_weights='eva'` in this case. " + ) + }, + ) + corda_config: Optional[CordaConfig] = field( + default=None, + metadata={ + "help": ( + "The configuration of CorDA. If this is passed, then CorDA will be used to build the adapter layers. " + "Also set `init_lora_weights='corda'` in this case." + ) + }, + ) + lora_ga_config: Optional[LoraGAConfig] = field( + default=None, + metadata={ + "help": ( + "The configuration of LoRA-GA. If this is passed, then LoRA-GA will be used to initialize the adapter layers. " + "Also set `init_lora_weights='lora_ga'` in this case." + ) + }, + ) + use_dora: bool = field( + default=False, + metadata={ + "help": ( + "Enable 'Weight-Decomposed Low-Rank Adaptation' (DoRA). This technique decomposes the updates of the " + "weights into two parts, magnitude and direction. Direction is handled by normal LoRA, whereas the " + "magnitude is handled by a separate learnable parameter. This can improve the performance of LoRA, " + "especially at low ranks. Right now, DoRA only supports linear and Conv2D layers. DoRA introduces a bigger" + "overhead than pure LoRA, so it is recommended to merge weights for inference." + ) + }, + ) + alora_invocation_tokens: Optional[list[int]] = field( + default=None, + metadata={ + "help": ( + "If not None, enable 'Activated LoRA' (aLoRA), with " + "alora_invocation_tokens being the tokenized invocation string for the adapter (must be present in all model " + "input strings). This technique selectively activates the adapter weights only on tokens during and after " + "the alora_invocation_tokens. When used in a CausalLM, this means that the KV cache prior to invocation is " + "interchangeable with that of the base model (and other aLoRA adapters operating this way). As a result, in " + "inference pipelines involving switching between base model inference and adapter inference (e.g. agentic " + "pipelines, see paper for examples), significant savings are realized (relative to LoRA) by saving prefill " + "operations. Overall adapter inference speedups of an order of magnitude or more can occur on vLLM, " + "depending on the length of the shared context. Note that merging is not possible due to the selective " + "application of the weights." + ) + }, + ) + use_qalora: bool = field( + default=False, + metadata={ + "help": ( + "It is only implemented in GPTQ for now. Enable Quantization-Aware Low-Rank Adaptation (QALoRA)." + "This technique combines quantization-aware training " + "with LoRA to improve performance for quantized models. This can improve the performance of LoRA, " + "especially at low ranks. Right now, QALoRA only supports linear layers." + ) + }, + ) + qalora_group_size: int = field( + default=16, + metadata={ + "help": ( + "Group size parameter for QALoRA pooling, controlling the dimension reduction factor. " + "Input dimensions are pooled into groups of this size, reducing the computational cost. " + "Higher values provide more compression but may reduce model quality. " + "This parameter determines how many original features are averaged together to create " + "one pooled feature. Only used when `use_qalora=True`." + ) + }, + ) + # Enables replicating layers in a model to expand it to a larger model. + layer_replication: Optional[list[tuple[int, int]]] = field( + default=None, + metadata={ + "help": ( + "This enables using LoRA to effectively expand a transformer model to a larger size by repeating some layers. " + "The transformation handles models (currently Llama, Bert or Falcon compatible architectures) with " + "a module list in the model which it modifies to expand the number of modules. " + "Base weights are shared so the memory usage is close to the original model. The intended use is these base weights " + "remain fixed during finetuning but each layer has a separate LoRA adapter so the layers can be specialed via " + "the adapter layers fit during fine tuning." + "The format is a list of [start, end) pairs which specify the layer ranges to stack. For example:\n" + " Original model has 5 layers labelled by their position in the model: `[0, 1, 2, 3, 4]`\n" + " layer_replication: `[[0, 4], [2, 5]]`\n" + " Final model will have this arrangement of original layers: `[0, 1, 2, 3, 2, 3, 4]`\n" + "This format is based on what is used for pass-through merges in mergekit. It makes it simple to select sequential " + "ranges of a model and stack them while reusing layers at either end of each sequence." + ) + }, + ) + runtime_config: LoraRuntimeConfig = field( + default_factory=LoraRuntimeConfig, metadata={"help": "Runtime configurations"} + ) + lora_bias: bool = field( + default=False, + metadata={ + "help": ( + "Whether to enable the bias term for the LoRA B parameter. Typically, this should be disabled. The " + "main use case for this is when the LoRA weights were extracted from fully fine-tuned parameters so " + "the bias of those parameters can be taken into account." + ) + }, + ) + target_parameters: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of parameter names or regex expression of the parameter names to replace with LoRA. " + "This argument behaves similarly to `target_modules`, except that the parameter name should be passed. " + "Generally, you should use `target_modules` to target the module (e.g. `nn.Linear`). However, in some " + "circumstances, this is not possible. E.g., in many mixture of expert (MoE) layers in HF Transformers, " + "instead of using `nn.Linear`, an `nn.Parameter` is used. PEFT normally overwrites the `forward` " + "method for LoRA, but for `nn.Parameter`, there is none. Therefore, to apply LoRA to that parameter, " + "it needs to be targeted with `target_parameters`. As an example, for Llama4, you can pass: " + "`target_parameters=['feed_forward.experts.gate_up_proj', 'feed_forward.experts.down_proj]`. Passing a " + "string for regex matching is not implemented yet." + ) + }, + ) + use_bdlora: Optional[BdLoraConfig] = field( + default=None, + metadata={ + "help": ( + "Enable BD-LoRA (Block-Diagonal LoRA) by providing a BdLoraConfig. This technique uses block-diagonal matrices for LoRA-A or LoRA-B " + "factors to enable faster multi-LoRA serving by eliminating communication overheads in distributed settings." + ) + }, + ) + arrow_config: Optional[ArrowConfig] = field( + default=None, metadata={"help": "The necessary config to apply arrow routing on the model."} + ) + ensure_weight_tying: bool = field( + default=False, + metadata={ + "help": ( + "Whether to tie weights or not after peft initialization. " + "This will ensure that the adapters added to the tied layers " + "are also tied. This is only applicable for layers passed via " + "`modules_to_save`, `target_modules` and `trainable_token_indices`." + ) + }, + ) + + def to_dict(self): + """ + Returns the configuration for your adapter model as a dictionary. Removes runtime configurations. + """ + rv = super().to_dict() + rv.pop("runtime_config") + return rv + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.LORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + + if self.ensure_weight_tying: + self.modules_to_tie = None + self.target_modules_to_tie = None + + if isinstance(self.target_parameters, str): + raise TypeError("`target_parameters` must be a list of strings or None.") + + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + + if self.use_dora and self.megatron_config: + raise ValueError("DoRA does not support megatron_core, please set `use_dora=False`.") + + # handle init_lora_weights and loftq_config + if self.init_lora_weights == "loftq": + if not importlib.util.find_spec("scipy"): + raise ImportError("The required package 'scipy' is not installed. Please install it to continue.") + if not self.loftq_config: + raise ValueError("`loftq_config` must be specified when `init_lora_weights` is 'loftq'.") + if not isinstance(self.loftq_config, dict): + # convert loftq_config to dict + self.loftq_config = vars(self.loftq_config) + elif self.loftq_config: + self.loftq_config = {} + warnings.warn("`loftq_config` specified but will be ignored when `init_lora_weights` is not 'loftq'.") + + elif self.init_lora_weights == "eva" and self.eva_config is None: + warnings.warn("`init_lora_weights` is 'eva' but `eva_config` is not specified. Using default EVA config.") + self.eva_config = EvaConfig() + elif self.init_lora_weights != "eva" and self.eva_config is not None: + warnings.warn("`eva_config` specified but will be ignored when `init_lora_weights` is not 'eva'.") + + elif self.init_lora_weights == "corda" and self.corda_config is None: + warnings.warn( + "`init_lora_weights` is 'corda' but `corda_config` is not specified. Using default CorDA config." + ) + self.corda_config = CordaConfig() + elif self.init_lora_weights != "corda" and self.corda_config is not None: + warnings.warn("`corda_config` specified but will be ignored when `init_lora_weights` is not 'corda'.") + + if self.lora_bias: + if self.init_lora_weights not in (True, False): + raise ValueError( + f"The argument lora_bias=True is only supported with init_lora_weights=True or False, got " + f"init_lora_weights={self.init_lora_weights} instead." + ) + if self.use_dora: + raise ValueError("The argument lora_bias=True is not supported for DoRA, please pass use_dora=False") + + if self.alora_invocation_tokens is not None and self.task_type != "CAUSAL_LM": + warnings.warn("aLoRA is currently only supported for CAUSAL_LM task.") + + # Using post training conversion of modified base weights to restore their initial values PiSSA/CorDA/OLoRA/LoRA-GA cannot + # be correctly done when using rslora + rank_pattern/alpha_pattern. We can't really know if the user intends + # this when they'll eventually call save_pretrained (i.e. if they'll pass + # path_initial_model_for_weight_conversionl). Therefore, we only warn but don't raise an error here. + if ( + self.use_rslora + and (self.rank_pattern or self.alpha_pattern) + and ( + (isinstance(self.init_lora_weights, str) and (self.init_lora_weights.startswith("pissa"))) + or (self.init_lora_weights == "olora") + or (self.init_lora_weights == "corda") + or (self.init_lora_weights == "lora_ga") + ) + ): + msg = ( + "Using Rank-Stabilized LoRA with rank_pattern/alpha_pattern and post-training conversion of modified " + "base weights PiSSA/CorDA/OLoRA/LoRA-GA means that you won't be able to pass " + "`path_initial_model_for_weight_conversion` to `save_pretrained` to restore the initial values of the " + "base weights; if you intend to do this, please ensure not to use rslora or rank_pattern/alpha_pattern." + ) + warnings.warn(msg) + + self._custom_modules: Optional[dict[type[nn.Module], type[nn.Module]]] = None + + def _register_custom_module(self, mapping: dict[type[nn.Module], type[nn.Module]]) -> None: + """ + Experimental API to support providing custom LoRA layers. + + This API is subject to change, you should carefully read the docs before deciding to use it: + + https://huggingface.co/docs/peft/developer_guides/custom_models + + To register custom LoRA module types, call this method with a `mapping` argument that is a dict that maps from + the target layer type to the custom LoRA layer type. The dict can contain multiple items if you wish to target + multiple layer types. The target layer type can be any nn.Module that we currently don't support in PEFT, + whether that is an official PyTorch layer type or a custom layer type. The custom LoRA module class has to be + implemented by the user and follow the PEFT conventions for LoRA layers. + + """ + if self._custom_modules is None: + self._custom_modules = {} + self._custom_modules.update(mapping) + + +@dataclass +class LoraGAConfig: + """ + This is the sub-configuration class to store the configuration for LoRA-GA initialization. + + LoRA-GA (Low-Rank Adaptation with Gradient Approximation) uses gradient information during initialization to + achieve faster convergence (2-4x speedup) by aligning the initial adapter weights with the direction of full + fine-tuning gradients. + + Reference: https://arxiv.org/abs/2407.05000 + + Args: + direction (`Literal["ArBr", "A2rBr", "ArB2r", "random"]`): + Strategy for distributing gradient SVD components to lora_A and lora_B matrices. + - "ArBr": Alternating indices (A takes odd, B takes even) + - "A2rBr": A takes indices [r:2r], B takes indices [:r] + - "ArB2r": A takes indices [:r], B takes indices [r:2r] (recommended) + - "random": Random selection of indices + Default: "ArB2r" + scale (`Literal["stable", "weight_svd", "gd_scale", "unit"]`): + Scaling strategy for adapter initialization. + - "stable": Stable scaling with gamma parameter + - "weight_svd": Scale based on weight matrix singular values + - "gd_scale": Gradient descent based scaling + - "unit": No additional scaling + Default: "stable" + stable_gamma (`int`): + Gamma parameter for stable scaling method. Default: 16 + """ + + direction: Literal["ArBr", "A2rBr", "ArB2r", "random"] = field( + default="ArB2r", metadata={"help": "Component distribution strategy from gradient SVD"} + ) + scale: Literal["stable", "weight_svd", "gd_scale", "unit"] = field( + default="stable", metadata={"help": "Scaling strategy for initialization"} + ) + stable_gamma: int = field(default=16, metadata={"help": "Gamma parameter for stable scaling"}) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/conversion.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/conversion.py new file mode 100644 index 0000000000000000000000000000000000000000..48f4420de786c3fa81ea89899204f2787855f495 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/conversion.py @@ -0,0 +1,375 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import os +import pathlib +import warnings + +import torch +from safetensors.torch import save_file +from tqdm import tqdm +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer +from peft.utils import SAFETENSORS_WEIGHTS_NAME +from peft.utils.other import ModulesToSaveWrapper + +from .config import LoraConfig + + +def _find_cutoff_index(S: torch.Tensor, threshold: float) -> int: + # assumes that the singular values are sorted + if S.dim() != 1: + raise ValueError("Input vector must be 1d.") + + energy = S**2 + cs = torch.cumsum(energy, dim=0) + total = cs[-1] + + cutoff = threshold * total + # smallest index i with cs[i] >= cutoff + k = torch.searchsorted(cs, cutoff).item() + # k is the index of the first item that surpasses the threshold; since we want to include it, add + 1 + return k + 1 + + +@torch.no_grad() +def _convert_module_to_lora( + module: BaseTunerLayer, rank: int | float, adapter_name: str = "default" +) -> tuple[torch.Tensor, torch.Tensor, int]: + """Convert a single BaseTunerLayer's adapter weight to a LoRA weight, return A, B, and the effective rank.""" + delta_weight = module.get_delta_weight(adapter_name) + # Note: Explore different algorithms (truncated, randomized, ...) to see if they are more efficient + + orig_dtype = delta_weight.dtype + delta_weight = delta_weight.float() # SVD not implemented for half-precision types + U, S, V = torch.linalg.svd(delta_weight, full_matrices=False) + if isinstance(rank, int): + effective_rank = rank + else: + # float => interpret as threshold + effective_rank = _find_cutoff_index(S, threshold=rank) + + if effective_rank > U.shape[1]: + raise ValueError( + f"The chosen rank {effective_rank} is larger than the weight shape ({U.shape[1]}), please choose a lower " + "rank." + ) + + lora_B = U[:, :effective_rank] * S[:effective_rank] + lora_A = V[:effective_rank] + lora_A, lora_B = lora_A.to(orig_dtype), lora_B.to(orig_dtype) + + if isinstance(module.get_base_layer(), Conv1D): + # Conv1D => original weight is transposed compared to Linear + return lora_B.T.contiguous(), lora_A.T.contiguous(), effective_rank + return lora_A.contiguous(), lora_B.contiguous(), effective_rank + + +def convert_to_lora( + model: torch.nn.Module, + rank: int | float, + adapter_name: str = "default", + progressbar: bool = False, + compile_kwargs=None, +) -> tuple[LoraConfig, dict[str, torch.Tensor]]: + """ + Convert a non-LoRA model with PEFT layers to a LoRA checkpoint. + + This is only supported for some specific PEFT methods that allow an equivalent conversion. Essentially, this comes + down to PEFT methods that work by updating the base weight with a delta weight. Also, right now, only linear layers + are supported. + + The LoRA adapter will try to approximate the initial adapter as close as possible. The higher the rank, the better + the approximation. It is expected that the approximation will never reach the full performance of the original + adapter, and that the parameter efficiency of the LoRA adapter will be less than that of the original adapter (i.e. + for a similar performance, it will require more parameters). The conversion can still be useful in many situations: + + - In PEFT, LoRA supports more features than most other methods, e.g. mixed adapter batches. Thus the converted + adapter can be used with those features. + - Some downstream packages support LoRA adapters, but not other PEFT methods, e.g. Diffusers. The conversion allows + to use a non-LoRA adapter with those packages. + + The LoRA scaling factor is already baked into the LoRA weights, thus the scaling will always be one (i.e. rank and + alpha are chosen to be identical). + + Note: This function does not support sharded models (yet). + + Args: + model: + The model to be converted. Should be a model that has PEFT layers that support conversion. + rank (`int` or `float`): + The desired rank for the returned LoRA adapter. A higher rank results in a LoRA adapter that more + accurately mirrors the original adapter. It will, however, also require more memory, compute, and disk + space. Therefore, choose a value that represents the best trade off for your use case and validate the + final adapter. If a float is passed, it is interpreted as an explained variance / energy threshold: we pick + the smallest rank k such that the top k singular values account for at least that fraction of the total + squared singular values. This effectively results in lower ranks being assigned if a few singular can + capture the adaptation of this layer. A lower float means the rank is lower and vice versa. Be aware that + dynamic ranks can lead to very unequal ranks per layer, which means that some layers may require a + disproportionally high amount of memory for activations. Choosing a fixed (int) rank is better to achieve + predictable memory requirement. + adapter_name (`str`, *optional*): + The name of the adapter to be converted. Can only convert a single adapter at a time. Defaults to + `"default"`. + progressbar (`bool`): + whether to show a progressbar indicating the progress of the conversion (it can take a few minutes for big + models). + compile_kwargs (`dict`, *optional*): + If provided, the compile the function to convert individual modules to LoRA with the given kwargs being + passed to `torch.compile`. This can potentially speed up the conversion on large models. + + Returns: + lora_config (`LoraConfig`) + The `LoraConfig` that corresponds to the converted LoRA adapter. + state_dict (`dict[str, torch.Tensor]`) + The `state_dict` containing the LoRA weights. + + Raises + TypeError: + If the provided model does not have any layers that can be converted to LoRA, a `TypeError` is raised. + ValueError: + If an invalid rank was chosen (too high or too low). + """ + from peft import PeftType # local to avoid circular import + + ########## + # CHECKS # + ########## + + if isinstance(rank, float) and not (0 < rank <= 1): + raise ValueError( + f"If rank is a float, it is interpreted as a threshold. It must be between 0 and 1 but got {rank}." + ) + elif rank == 0: + raise ValueError("Passing a rank of 0 doesn't make sense, please pass a valid value.") + + # check if LoRA conversion is supported at all + modules_not_supporting_lora = [] + num_modules_with_support = 0 + num_modules_total = 0 + for module in model.modules(): + num_modules_total += 1 + if not isinstance(module, BaseTunerLayer): + continue + + if module.supports_lora_conversion(adapter_name): + num_modules_with_support += 1 + else: + modules_not_supporting_lora.append(module) + + unsupported = {repr(type(module)) for module in modules_not_supporting_lora} + if unsupported: + raise TypeError(f"Some module types on this model do not support LoRA conversion: {', '.join(unsupported)}.") + + if num_modules_with_support == 0: + raise TypeError("Could not detect any layer that supports LoRA conversion.") + + peft_config = getattr(model, "peft_config", {}).get(adapter_name) + if (peft_config is not None) and (peft_config.peft_type == PeftType.LORA): + warnings.warn( + "Converting a PEFT adapter to LoRA that is already a LoRA adapter. There is typically no need for that." + ) + + config_bias = getattr(peft_config, "bias", getattr(peft_config, "lora_bias", "none")) + if config_bias != "none": + # TODO: remove if/when we remove support for bias completely + raise ValueError(f"The adapter's config sets bias={config_bias}, this is not supported right now.") + + ############### + # PREPARATION # + ############### + + peft_prefix = "base_model.model." + config_kwargs = { + "rank_pattern": {}, + "alpha_pattern": {}, + "exclude_modules": set(), + } + + if peft_config is not None: + # use the model's PEFT config, if it exists, to initialize the new LoraConfig + peft_config = model.peft_config[adapter_name] + config_kwargs["target_modules"] = copy.copy(peft_config.target_modules) + config_kwargs["base_model_name_or_path"] = peft_config.base_model_name_or_path + if hasattr(peft_config, "layers_pattern"): + # those two go hand in hand + config_kwargs["layers_pattern"] = peft_config.layers_pattern + config_kwargs["layers_to_transform"] = peft_config.layers_to_transform + if isinstance(rank, int): + # hard-coded rank + lora_config = LoraConfig(r=rank, lora_alpha=rank, **config_kwargs) + else: + # r and lora_alpha shouldn't matter, as the rank will be determined by rank/alpha pattern + lora_config = LoraConfig(r=1, lora_alpha=1, **config_kwargs) + else: + # create a new LoraConfig from scratch, inferring the target modules from the model + lora_config = LoraConfig( + r=rank if isinstance(rank, int) else 1, # 1 is a dummy value, actual values will come from rank_pattern + target_modules=[], + **config_kwargs, + ) + + if compile_kwargs is not None: + convert_module_to_lora = torch.compile(_convert_module_to_lora, **compile_kwargs) + else: + convert_module_to_lora = _convert_module_to_lora + + ############## + # CONVERSION # + ############## + + state_dict = {} + for name, module in tqdm( + model.named_modules(), disable=not progressbar, desc="Converting to LoRA", total=num_modules_total + ): + if not isinstance(module, BaseTunerLayer): + continue + if not hasattr(module, "get_delta_weight"): + # if we arrive here, it means that the layer actually does not support LoRA conversion, which should not + # happen + raise TypeError( + f"Module of type {type(module)} does not have a get_delta_weight method, which is required for " + "conversion. Please open an issue: https://github.com/huggingface/peft/issues" + ) + + lora_A, lora_B, effective_rank = convert_module_to_lora(module, rank=rank, adapter_name=adapter_name) + if effective_rank == 0: + # This shouldn't really happen, as we ensure that the rank is greater than 0 (int) or, for thresholds + # (float), at least one SV is included. But better be safe than sorry, as, in principle, it is fine to + # exclude some layers. Also makes this more future proof. + lora_config.exclude_modules.add(name.removeprefix(peft_prefix)) + continue + + # the rank was dynamically adjusted, store it in rank and alpha pattern + if (effective_rank != rank) or isinstance(lora_config.target_modules, str): + # we need to add an entry to rank/alpha pattern iff: + # 1) The effective rank differs from the general rank + # 2) target modules is a string, as we cannot simply append the name to target_modules regex + lora_config.rank_pattern[name.removeprefix(peft_prefix)] = effective_rank + lora_config.alpha_pattern[name.removeprefix(peft_prefix)] = effective_rank + else: + # effective rank is the same and target_modules are a set, just add the name + lora_config.target_modules.add(name.removeprefix(peft_prefix)) + + # don't include adapter_name in key + state_dict[f"{name}.lora_A.weight"] = lora_A + state_dict[f"{name}.lora_B.weight"] = lora_B + + if not state_dict: + # no layer was converted, which should not happen + raise ValueError( + "Did not convert a single layer, this means that something went wrong. Please open an issue: " + "https://github.com/huggingface/peft/issues" + ) + + ################## + # NON-LORA PARTS # + ################## + + if (peft_config is not None) and getattr(peft_config, "modules_to_save", None): + # logic to take care of modules_to_save; might not cover all edge cases, like sharded model + lora_config.modules_to_save = copy.copy(peft_config.modules_to_save) + + for module_name, module in model.named_modules(): + if isinstance(module, ModulesToSaveWrapper): + for param_name, param in module.modules_to_save.named_parameters(): + # it is expected that '.modules_to_save.' is not part of the key + prefix, _, _ = module_name.partition(".modules_to_save.") + # remove the adapter name + _, _, suffix = param_name.rpartition(".") + state_dict[f"{prefix}.{suffix}"] = param.data + + return lora_config, state_dict + + +def save_as_lora( + path: str | os.PathLike, + model: torch.nn.Module, + rank: int | float, + adapter_name: str = "default", + progressbar: bool = False, + compile_kwargs=None, +) -> None: + """ + Convert a non-LoRA model with PEFT layers to a LoRA, then save the checkpoint file and PEFT config. + + This is only supported for some specific PEFT methods that allow an equivalent conversion. Essentially, this comes + down to PEFT methods that work by updating the base weight with a delta weight. Also, right now, only linear layers + are supported. + + The LoRA adapter will try to approximate the initial adapter as close as possible. The higher the rank, the better + the approximation. It is expected that the approximation will never reach the full performance of the original + adapter, and that the parameter efficiency of the LoRA adapter will be less than that of the original adapter (i.e. + for a similar performance, it will require more parameters). The conversion can still be useful in many situations: + + - In PEFT, LoRA supports more features than most other methods, e.g. mixed adapter batches. Thus the converted + adapter can be used with those features. + - Some downstream packages support LoRA adapters, but not other PEFT methods, e.g. Diffusers. The conversion allows + to use a non-LoRA adapter with those packages. + + The LoRA scaling factor is already baked into the LoRA weights, thus the scaling will always be one (i.e. rank and + alpha are chosen to be identical). + + You can load the converted LoRA weight like this: + + ```py + >>> lora_path = ... + >>> save_as_lora(lora_path, model, rank=...) + >>> base_model = AutoModel.from_pretrained(...) + >>> lora_model = PeftModel.from_pretrained(base_model, lora_path) + ``` + + Note: This function does not support sharded models (yet). + + Args: + model: + The model to be converted. Should be a model that has PEFT layers that support conversion. + rank (`int` or `float`): + The desired rank for the returned LoRA adapter. A higher rank results in a LoRA adapter that more + accurately mirrors the original adapter. It will, however, also require more memory, compute, and disk + space. Therefore, choose a value that represents the best trade off for your use case and validate the + final adapter. If a float is passed, it is interpreted as an explained variance / energy threshold: we pick + the smallest rank k such that the top k singular values account for at least that fraction of the total + squared singular values. This effectively results in lower ranks being assigned if a few singular can + capture the adaptation of this layer. A lower float means the rank is lower and vice versa. Be aware that + dynamic ranks can lead to very unequal ranks per layer, which means that some layers may require a + disproportionally high amount of memory for activations. Choosing a fixed (int) rank is better to achieve + predictable memory requirement. + adapter_name (`str`, *optional*): + The name of the adapter to be converted. Can only convert a single adapter at a time. Defaults to + `"default"`. + progressbar (`bool`): + whether to show a progressbar indicating the progress of the conversion (it can take a few minutes for big + models). + compile_kwargs (`dict`, *optional*): + If provided, the compile the function to convert individual modules to LoRA with the given kwargs being + passed to `torch.compile`. This can potentially speed up the conversion on large models. + + Raises + TypeError: + If the provided model does not have any layers that can be converted to LoRA, a `TypeError` is raised. + ValueError: + If an invalid rank was chosen (too high or too low). + """ + path = pathlib.Path(path) + if not path.exists(): + os.makedirs(path) + + lora_config, state_dict = convert_to_lora( + model, rank=rank, adapter_name=adapter_name, progressbar=progressbar, compile_kwargs=compile_kwargs + ) + save_file(state_dict, path / SAFETENSORS_WEIGHTS_NAME) + lora_config.save_pretrained(str(path)) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/corda.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/corda.py new file mode 100644 index 0000000000000000000000000000000000000000..0b71007187705da6c66c9b75603eef201df3ca00 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/corda.py @@ -0,0 +1,370 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Reference code: https://github.com/iboing/CorDA/blob/main/cordalib/decomposition.py +# Reference paper: https://huggingface.co/papers/2406.05223 + +import os +from collections.abc import Callable, Iterable +from typing import Any, Optional + +import torch +import torch.nn as nn +from attr import dataclass +from tqdm import tqdm +from transformers.pytorch_utils import Conv1D + +from peft.tuners.lora.config import LoraConfig +from peft.tuners.lora.model import LoraModel +from peft.utils.other import get_pattern_key + + +@dataclass +class CordaEigens: + S_WC: torch.Tensor + U_WC: torch.Tensor + V_WC: torch.Tensor + + +def target_modules(model: nn.Module, config: LoraConfig) -> Iterable[nn.Module]: + """ + Iterate over CorDA target name and modules of a model. A module is a target if its name is in + `config.target_modules` and is `nn.Linear` or `Conv1D`. + """ + for name, module in model.named_modules(): + if LoraModel._check_target_module_exists(config, name) and isinstance(module, (nn.Linear, Conv1D)): + yield name, module + + +def get_model_device(model: nn.Module) -> str: + if hasattr(model, "module"): # Handle DeepSpeed/DataParallel + model = model.module + return next(iter(model.parameters())).device.type + + +@torch.no_grad() +def preprocess_corda( + model: nn.Module, + lora_config: LoraConfig, + run_model: Optional[Callable[[], None]] = None, + hooked_model: Optional[nn.Module] = None, +): + """ + Build necessary CorDA fields for a model. + + For each `M * N` linear layer, a `M * M` covariance matrix will be built temporarily during the preprocessing + process, consuming roughly another `2 * MODEL_SIZE` memory for typical LLMs if model weight is FP16 and covariance + is FP32. If that's too much, consider specifying `use_float16_for_covariance` in `lora_config.corda_config`. + + Args: + model (`nn.Module`): + Model to preprocess. + lora_config (`LoraConfig`): + Lora configuration of the model. `lora_config.corda_config` should be set. + run_model (`Optional[Callable[[], None]]`): + Callback to run the model when building covariance. Typically you should run model inference on your sample + dataset in this callback. Experiments have shown that when token count per sample is 2048, hidden dimension + is 4096, collecting 256 distinct samples is enough. If you collect too few or too repetitive samples, the + covariance matrix may be low-ranked and unstabilize preprocessing. You can estimate sample count as + `HIDDEN_DIM / TOKEN_PER_SAMPLE * 128`. `run_model` can be `None` only if covariance file in + `lora_config.corda_config` is already created. + hooked_model (`Optional[nn.Module]`): + Model to hook when building covariance. If none, original model will be hooked. This is only useful when + you want to hook a different model than the one you are training, typically you should leave this `None`. + + Upon completion, the following fields are set for each target module: + eigens.S_WC (`torch.Tensor`): + Singular values of the weight matrix. + eigens.U_WC (`torch.Tensor`): + Left singular vectors of the weight matrix. + eigens.V_WC (`torch.Tensor`): + Right singular vectors of the weight matrix, multiplied by inverse of covariance matrix. + """ + cache_file = lora_config.corda_config.cache_file + covariance_file = lora_config.corda_config.covariance_file + corda_method = lora_config.corda_config.corda_method + verbose = lora_config.corda_config.verbose + prune_temporary_fields = lora_config.corda_config.prune_temporary_fields + + # If cache exists, skip building + if cache_file is not None and os.path.exists(cache_file) and os.path.getsize(cache_file) > 0: + cache = torch.load(cache_file, map_location=get_model_device(model)) + for name, module in target_modules(model, lora_config): + module.eigens = CordaEigens( + S_WC=cache[f"{name}.eigens.S_WC"], + U_WC=cache[f"{name}.eigens.U_WC"], + V_WC=cache[f"{name}.eigens.V_WC"], + ) + else: + # Specify CorDA method for each layer + if corda_method is None: + raise ValueError("corda_method is required when cache_file is not provided.") + for name, module in target_modules(model, lora_config): + module.corda_method = corda_method + + # Specify CorDA rank for each layer + for name, module in target_modules(model, lora_config): + r_key = get_pattern_key(lora_config.rank_pattern.keys(), name) + module.rank = lora_config.rank_pattern.get(r_key, lora_config.r) + + # Calculate covariance matrix + calib_cov_distribution(model, lora_config, run_model, hooked_model, covariance_file) + + # Calculate eigens + collect_eigens(model, lora_config, verbose) + + # Crop CorDA eigens so that there's less to save + crop_corda_eigens(model, lora_config) + + # Remove redundant fields if exist + if prune_temporary_fields: + for name, module in target_modules(model, lora_config): + if hasattr(module, "sample_count"): + del module.sample_count + if hasattr(module, "covariance_matrix"): + del module.covariance_matrix + if hasattr(module, "corda_method"): + del module.corda_method + if hasattr(module, "rank"): + del module.rank + + # Save cache to disk + if cache_file is not None: + cache: dict[str, Any] = {} + for name, module in target_modules(model, lora_config): + cache[f"{name}.eigens.S_WC"] = module.eigens.S_WC + cache[f"{name}.eigens.U_WC"] = module.eigens.U_WC + cache[f"{name}.eigens.V_WC"] = module.eigens.V_WC + + os.makedirs(os.path.dirname(cache_file), exist_ok=True) + torch.save(cache, cache_file) + + +@torch.no_grad() +def calib_cov_distribution( + model: nn.Module, + config: LoraConfig, + run_model: Optional[Callable[[], None]], + hooked_model: Optional[nn.Module], + covariance_file: Optional[str], +): + if covariance_file is not None and os.path.exists(covariance_file) and os.path.getsize(covariance_file) > 0: + all_covariance_matrix = torch.load(covariance_file, map_location=get_model_device(model)) + for name, module in target_modules(model, config): + module.covariance_matrix = all_covariance_matrix[name] + return + + if run_model is None: + raise ValueError("run_model must be specified when covariance file and cache file aren't built.") + if hooked_model is None: + hooked_model = model + hooked_model.eval() + + def hook(module, input, output): + input = input[0].detach().squeeze(0).data ## (context_length = 2048, dim) + if not config.corda_config.use_float16_for_covariance: + input = input.float() + input = input / torch.max(input).abs() + + # check if input is valid + if torch.isnan(input).any() or torch.isinf(input).any(): + raise ValueError("Invalid value found in input, please check your input data.") + + # calculate covariance and check if it's valid + covariance = input.t().matmul(input) + if torch.isnan(covariance).any() or torch.isinf(covariance).any(): + raise ValueError( + "Invalid value found in covariance. Please file an issue at https://github.com/huggingface/peft/issues." + ) + + # add to module + module.sample_count += 1 + module.covariance_matrix += covariance + + # free memory + del covariance, input + + handles = [] + for name, module in target_modules(hooked_model, config): + module.sample_count = 0 + module.covariance_matrix = 0 + handles.append(module.register_forward_hook(hook)) + + run_model() + + # Clear the hooks + for handle in handles: + handle.remove() + + # In some edge cases you might need to hook a model different from the model to add adapters, + # this case you would specify `hooked_model` and set it to a different model from `model`. + if hooked_model is not model: + targets = {} + for name, module in target_modules(model, config): + targets[name] = module + for name, module in target_modules(hooked_model, config): + # There can be modules used only in inference, but not training + # Exclude modules not in target model to prevent KeyError in this case + if name in targets: + targets[name].sample_count = module.sample_count + targets[name].covariance_matrix = module.covariance_matrix + + # Divide by sample count + for name, module in target_modules(model, config): + module.covariance_matrix /= module.sample_count + + # Save covariance to disk + if covariance_file is not None: + all_covariance_matrix = {} + for name, module in target_modules(model, config): + all_covariance_matrix[name] = module.covariance_matrix + os.makedirs(os.path.dirname(covariance_file), exist_ok=True) + torch.save(all_covariance_matrix, covariance_file) + + +@torch.no_grad() +def collect_eigens( + model: nn.Module, + config: LoraConfig, + verbose: bool, +): + """Call collect_eigens_for_layer and store result in key `eigens` of each layer.""" + linear_modules = [] + for name, module in target_modules(model, config): + linear_modules.append((name, module)) + if verbose: + linear_modules = tqdm(linear_modules, desc="Collecting eigens") + for name, module in linear_modules: + module.eigens = collect_eigens_for_layer(module, config) + + +@torch.no_grad() +def collect_eigens_for_layer( + linear: nn.Module, + config: LoraConfig, +) -> CordaEigens: + w = linear.weight.data.float() + # Conv1D stores weights as (in_features, out_features), transposed compared to Linear + # We need to transpose it to match Linear's (out_features, in_features) layout for SVD + if isinstance(linear, Conv1D): + w = w.T + out_dim = w.size(0) + in_dim = w.size(1) + min_dim = min(in_dim, out_dim) + + if not hasattr(linear, "covariance_matrix"): + raise ValueError( + "Covariance matrix not found in linear module. Please do not call this function directly, " + "instead call `preprocess_corda`. If your usage is correct but this error still encounters, " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + covariance_matrix = linear.covariance_matrix.float() + + damp = 0.01 + while True: + compensate = torch.diag( + torch.ones(covariance_matrix.size(0)).to(covariance_matrix.device) + * torch.mean(torch.diag(covariance_matrix)) + * damp + ) + fix_covariance_matrix = covariance_matrix + compensate + cov_inv = torch.linalg.inv(fix_covariance_matrix) + inv_error = torch.dist( + fix_covariance_matrix @ cov_inv, torch.eye(covariance_matrix.size(0)).to(get_model_device(linear)) + ).item() + if inv_error < 0.05: + break + else: + damp = damp * 2 + w = w @ fix_covariance_matrix ## w: out_dim, in_dim; covariance_matrix: in_dim, in_dim + + U, S, Vh = torch.linalg.svd(w, full_matrices=False) + V = (Vh @ cov_inv).transpose(0, 1) + + # Sanity check, temporarily U and V are large, they will be crop after rank search + r = min_dim + if U.size(0) != out_dim or U.size(1) != r: + raise ValueError( + f"Matrix U size mismatch: {U.size()} vs. ({out_dim}, {r}), " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if S.size(0) != r: + raise ValueError( + f"Matrix S size mismatch: {S.size()} vs. ({r},), " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if V.size(0) != in_dim or V.size(1) != r: + raise ValueError( + f"Matrix V size mismatch: {V.size()} vs. ({in_dim}, {r}), " + "please file an issue at https://github.com/huggingface/peft/issues." + ) + + # Offload U and V to CPU, they consume too much memory + U = U.cpu() + V = V.cpu() + return CordaEigens( + S_WC=S, + U_WC=U, + V_WC=V, + ) + + +@torch.no_grad() +def crop_corda_eigens(model: nn.Module, config: LoraConfig): + for name, module in target_modules(model, config): + # We don't expect saving sliced tensor writes the whole tensor to disk, + # so it's necessary to copy the tensors. + # Reference: https://github.com/pytorch/pytorch/issues/40157 + if module.corda_method == "ipm": + module.eigens.S_WC = module.eigens.S_WC[: module.rank].clone() + module.eigens.U_WC = module.eigens.U_WC[:, : module.rank].clone().to(get_model_device(model)) + module.eigens.V_WC = module.eigens.V_WC[:, : module.rank].clone().to(get_model_device(model)) + elif module.corda_method == "kpm": + module.eigens.S_WC = module.eigens.S_WC[-module.rank :].clone() + module.eigens.U_WC = module.eigens.U_WC[:, -module.rank :].clone().to(get_model_device(model)) + module.eigens.V_WC = module.eigens.V_WC[:, -module.rank :].clone().to(get_model_device(model)) + else: + raise ValueError(f"Invalid corda_method found: {module.corda_method}, it should be 'ipm' or 'kpm'.") + + # Sanity check + # For Conv1D, weight is stored as (in_features, out_features), transposed compared to Linear + # But U and V are computed on the transposed weight, so we need to account for this + weight_out_dim = module.weight.size(1) if isinstance(module, Conv1D) else module.weight.size(0) + weight_in_dim = module.weight.size(0) if isinstance(module, Conv1D) else module.weight.size(1) + + if module.eigens.S_WC.size(0) != module.rank: + raise ValueError( + f"rank mismatch: {module.eigens.S_WC.size(0)} vs. {module.rank}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.U_WC.size(0) != weight_out_dim: + raise ValueError( + f"U size mismatch: {module.eigens.U_WC.size(0)} vs. {weight_out_dim}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.U_WC.size(1) != module.rank: + raise ValueError( + f"U size mismatch: {module.eigens.U_WC.size(1)} vs. {module.rank}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.V_WC.size(0) != weight_in_dim: + raise ValueError( + f"V size mismatch: {module.eigens.V_WC.size(0)} vs. {weight_in_dim}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) + if module.eigens.V_WC.size(1) != module.rank: + raise ValueError( + f"V size mismatch: {module.eigens.V_WC.size(1)} vs. {module.rank}," + "please file an issue at https://github.com/huggingface/peft/issues." + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/dora.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/dora.py new file mode 100644 index 0000000000000000000000000000000000000000..f7a397fe51b5c6959c93d57e06660e40fafa0d8d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/dora.py @@ -0,0 +1,287 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from copy import deepcopy +from functools import wraps +from typing import Any, Optional + +import torch +import torch.nn.functional as F +from torch import nn + +from peft.utils.integrations import dequantize_module_weight, gather_params_ctx +from peft.utils.other import transpose + + +ENABLE_DORA_CACHING = False +"""Whether to enable DoRA caching, which makes it faster at inference but requires more memory""" + + +def cache_decorator(cache_key: str): + """Caching decorator for DoRA + + Caching is only enabled if ENABLE_DORA_CACHING is set to True (default: False), when in eval mode, and when the + adapter_name is passed (e.g. not during layer initialization). + + """ + + def cache_value(func): + @wraps(func) + def wrapper(self, *args, **kwargs): + # if adapter_name is not passed, no caching + adapter_name = kwargs.get("adapter_name") + if (not ENABLE_DORA_CACHING) or self.training or (adapter_name is None): + self._cache_clear() + return func(self, *args, **kwargs) + + cache_key_adapter = f"{cache_key}-{adapter_name}" + output = self._cache_get(cache_key_adapter, None) + if output is not None: + return output + + output = func(self, *args, **kwargs) + self._cache_store(cache_key_adapter, output) + return output + + return wrapper + + return cache_value + + +class DoraLinearLayer(nn.Module): + def __init__(self, fan_in_fan_out): + super().__init__() + self.fan_in_fan_out = fan_in_fan_out + self._dora_cache: dict[str, Any] = {} # small ad hoc cache; values are not part of the state_dict + + def _cache_store(self, key: str, value: Any) -> None: + # cache intermediate values, e.g. weight norm of DoRA + self._dora_cache[key] = value + + def _cache_get(self, key: str, default: Optional[Any]) -> Optional[Any]: + # retrieve from ad hoc cache + return self._dora_cache.get(key, default) + + def _cache_clear(self) -> None: + self._dora_cache.clear() + + def train(self, mode: bool = True): + if mode: + self._cache_clear() + super().train(mode=mode) + return self + + @cache_decorator("weight-norm") + def get_weight_norm(self, weight, lora_weight, scaling, adapter_name: Optional[str] = None) -> torch.Tensor: + # calculate L2 norm of weight matrix, column-wise + weight = transpose(weight, self.fan_in_fan_out) + weight = weight + scaling * lora_weight + weight_norm = torch.linalg.norm(weight, dim=1).to(weight.dtype) + return weight_norm + + @cache_decorator("lora-weight") + def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None): + # Don't use `lora_weight = lora_B.weight @ lora_A.weight` because this causes errors with FSDP. Instead, + # calculate the same but using forward. + x_eye = torch.eye(lora_A.weight.shape[1], device=lora_A.weight.device, dtype=lora_A.weight.dtype) + lora_weight = lora_B(lora_A(x_eye)).T + return lora_weight + + def update_layer(self, *, base_layer, lora_A, lora_B, scaling, place_on_cpu=False) -> None: + # temporarily convert fp16 to fp32, as fp16 can cause trouble on CPU with PyTorch < 2.2 + dtype_is_fp16 = lora_A.dtype == torch.float16 + if dtype_is_fp16: + lora_A = lora_A.float() + lora_B = lora_B.float() + + with gather_params_ctx(base_layer.parameters()): + if base_layer.__class__.__name__ == "Linear4bit": + # We have to create a copy of the base layer, otherwise, FSDP will throw an error. 8bit does not work + # yet because Int8Params cannot be correctly deep-copied (attributes vanish) + base_layer = deepcopy(base_layer) + + weight = dequantize_module_weight(base_layer) + if weight.data.ndim >= 3: # For handling LoRAs applied to Conv layers. + r = lora_A.shape[0] + lora_weight = torch.mm(lora_B.view([-1, r]), lora_A.view([r, -1])) + lora_weight = lora_weight.reshape(weight.shape) + else: + lora_weight = lora_B @ lora_A + + if dtype_is_fp16: + lora_weight = lora_weight.half() + weight_norm = self.get_weight_norm( + weight=weight.to(lora_A.device), lora_weight=lora_weight, scaling=scaling + ) + + if place_on_cpu: + weight_norm = weight_norm.to("cpu") + self.weight = nn.Parameter(weight_norm, requires_grad=True) + + def forward(self, x, *, lora_A, lora_B, scaling, base_layer, base_result=None, adapter_name="default"): + """ + For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer + output. + """ + lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name) + lora_weight = lora_weight.to(x.dtype) + + magnitude = self.weight + weight = dequantize_module_weight(base_layer) + weight = weight.to(x.dtype) + weight_norm = self.get_weight_norm( + weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name + ) + # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353) + # "[...] we suggest treating ||V +∆V ||_c in + # Eq. (5) as a constant, thereby detaching it from the gradient + # graph. This means that while ||V + ∆V ||_c dynamically + # reflects the updates of ∆V , it won’t receive any gradient + # during backpropagation" + weight_norm = weight_norm.detach() + mag_norm_scale = (magnitude / weight_norm).view(1, -1) + + lora_result = lora_B(lora_A(x)) + + bias = None + if base_result is not None: + bias = base_layer.bias + if bias is not None: + base_result = base_result - bias + else: + base_result = F.linear(x, transpose(weight, self.fan_in_fan_out)) + + result_dora = (mag_norm_scale - 1) * base_result + mag_norm_scale * lora_result * scaling + return result_dora + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora.dora." + rep + + +class DoraEmbeddingLayer(DoraLinearLayer): + @cache_decorator("lora-weight") + def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None): + return (lora_A @ lora_B).T + + def forward(self, x, *, lora_A, lora_B, scaling, base_layer, embed_fn, adapter_name="default"): + """ + For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer + output. + """ + lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name) + magnitude = self.weight + weight = base_layer.weight + weight_norm = self.get_weight_norm( + weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name + ) + # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353) + # "[...] we suggest treating ||V +∆V ||_c in + # Eq. (5) as a constant, thereby detaching it from the gradient + # graph. This means that while ||V + ∆V ||_c dynamically + # reflects the updates of ∆V , it won’t receive any gradient + # during backpropagation" + weight_norm = weight_norm.detach() + mag_norm_scale = magnitude / weight_norm + result_dora = mag_norm_scale * (embed_fn(x, lora_A) @ lora_B) * scaling + return mag_norm_scale, result_dora + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora.dora." + rep + + +class _DoraConvNdLayer(DoraLinearLayer): + @cache_decorator("weight-norm") + def get_weight_norm(self, weight, lora_weight, scaling, adapter_name: Optional[str] = None) -> torch.Tensor: + # calculate L2 norm of weight matrix, column-wise + weight = weight + scaling * lora_weight + # the following is needed to have compatibility with the 4/5D weight tensors of Conv2D/3D + dim = tuple(range(1, weight.dim())) + weight_norm = weight.norm(p=2, dim=dim, keepdim=True).transpose(1, 0) + return weight_norm + + @cache_decorator("lora-weight") + def get_lora_weight(self, lora_A, lora_B, adapter_name: Optional[str] = None) -> torch.Tensor: + # Don't use `lora_weight = lora_B.weight @ lora_A.weight` because this causes errors with FSDP. Instead, + # calculate the same but using forward. + r = lora_A.weight.shape[0] + lora_weight = torch.mm(lora_B.weight.view([-1, r]), lora_A.weight.view([r, -1])) + return lora_weight + + def forward( + self, x, *, lora_A, lora_B, scaling, base_layer, base_result=None, adapter_name: str = "default" + ) -> torch.Tensor: + """ + For DoRA, calculate the extra output from LoRA with DoRA applied. This should be added on top of the base layer + output. + """ + weight = base_layer.weight + lora_weight = self.get_lora_weight(lora_A=lora_A, lora_B=lora_B, adapter_name=adapter_name).reshape( + weight.shape + ) + magnitude = self.weight + weight_norm = self.get_weight_norm( + weight=weight, lora_weight=lora_weight.detach(), scaling=scaling, adapter_name=adapter_name + ) + # see section 4.3 of DoRA (https://huggingface.co/papers/2402.09353) + # "[...] we suggest treating ||V +∆V ||_c in + # Eq. (5) as a constant, thereby detaching it from the gradient + # graph. This means that while ||V + ∆V ||_c dynamically + # reflects the updates of ∆V , it won’t receive any gradient + # during backpropagation" + weight_norm = weight_norm.detach() + mag_norm_scale = magnitude / weight_norm + + if base_result is None: + base_result = self.conv_fn( + x, + weight, + bias=None, + stride=base_layer.stride, + padding=base_layer.padding, + dilation=base_layer.dilation, + groups=base_layer.groups, + ) + else: + bias = base_layer.bias + if bias is not None: + # reshape bias to (1, -1, 1, ...) + bias_shape = (1, -1) + (1,) * (base_result.dim() - 2) + base_result = base_result - bias.view(*bias_shape) + + result_dora = (mag_norm_scale - 1) * base_result + mag_norm_scale * lora_B(lora_A(x)) * scaling + return result_dora + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora.dora." + rep + + +class DoraConv1dLayer(_DoraConvNdLayer): + def __init__(self, fan_in_fan_out): + super().__init__(fan_in_fan_out) + self.conv_fn = F.conv1d + + +class DoraConv2dLayer(_DoraConvNdLayer): + def __init__(self, fan_in_fan_out): + super().__init__(fan_in_fan_out) + self.conv_fn = F.conv2d + + +class DoraConv3dLayer(_DoraConvNdLayer): + def __init__(self, fan_in_fan_out): + super().__init__(fan_in_fan_out) + self.conv_fn = F.conv3d diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/eetq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/eetq.py new file mode 100644 index 0000000000000000000000000000000000000000..e25578617450954efd83030c01d17ebc0fa4c89a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/eetq.py @@ -0,0 +1,113 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_eetq_available +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +if is_eetq_available(): + from eetq import EetqLinear + + class EetqLoraLinear(torch.nn.Module, LoraLayer): + def __init__( + self, + base_layer, + adapter_name, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def forward(self, x: torch.Tensor): + result = self.quant_linear_module(x) + + if self.disable_adapters: + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + output = lora_B(lora_A(dropout(x))) + if requires_conversion: + output = output.to(expected_dtype) + output = output * scaling + result = result + output + return result + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + raise AttributeError("Merging LoRA layers is not supported for Eetq layers.") + + def unmerge(self) -> None: + raise AttributeError("Unmerging LoRA layers is not supported for Eetq layers.") + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_eetq( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_eetq_available() and isinstance(target_base_layer, EetqLinear): + new_module = EetqLoraLinear(target, adapter_name, config=config, **kwargs) + target.weight = target_base_layer.weight + + if hasattr(target, "bias"): + target.bias = target_base_layer.bias + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/eva.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/eva.py new file mode 100644 index 0000000000000000000000000000000000000000..c7be0c86cec4c4f3b81ade57987a2d2c94aa4ee6 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/eva.py @@ -0,0 +1,734 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from collections import Counter, defaultdict +from collections.abc import Iterable, Mapping +from contextlib import nullcontext +from copy import copy, deepcopy +from functools import partial +from itertools import cycle +from typing import Optional, Union + +import torch +import torch.distributed as dist +from tqdm import tqdm +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import _find_minimal_target_modules, check_target_module_exists +from peft.utils.constants import MIN_TARGET_MODULES_FOR_OPTIMIZATION +from peft.utils.incremental_pca import IncrementalPCA +from peft.utils.other import _get_submodules, get_pattern_key + +from .config import LoraConfig +from .layer import Embedding, LoraLayer, MultiheadAttention, _ConvNd + + +UNSUPPORTED_LORA_MODULES = (Embedding, MultiheadAttention, _ConvNd) + + +class _Hook: + """ + A base class for hooks that prepares layer inputs for EVA. + """ + + def __init__( + self, + name: str, + prepare_layer_inputs_fn: Optional[callable] = None, + gather_distributed_inputs: bool = True, + ): + self.name = name + self.gather_distributed_inputs = gather_distributed_inputs + if prepare_layer_inputs_fn is None: + self._prepare_layer_inputs_fn = self._prepare_layer_inputs_fn_default + else: + self._prepare_layer_inputs_fn = prepare_layer_inputs_fn + self.model_input = None + + @staticmethod + def _prepare_layer_inputs_fn_default(layer_input, model_input, layer_name) -> torch.Tensor: + if isinstance(layer_input, torch.Tensor): + pass + elif isinstance(layer_input, (tuple, list)): + layer_input = layer_input[0] + else: + raise ValueError( + f"unsupported input type {type(layer_input)} for prepare_layer_inputs_fn in layer {layer_name}, " + "please provide a custom prepare_layer_inputs_fn" + ) + # if the input has more than 2 dimensions, we flatten all but the last dimension + if layer_input.ndim > 2: + layer_input = layer_input.view(-1, layer_input.size(-1)) + return layer_input + + @torch.no_grad() + def prepare_layer_inputs(self, layer_input): + return self._prepare_layer_inputs_fn(layer_input, self.model_input, self.name) + + def gather_layer_inputs(self, layer_input): + if dist.is_initialized() and self.gather_distributed_inputs: + world_size = dist.get_world_size() + + # First gather sizes from all processes more efficiently + local_size = torch.tensor([layer_input.shape[0]], device=layer_input.device) + all_sizes = torch.empty(world_size, dtype=local_size.dtype, device=layer_input.device) + dist.all_gather_into_tensor(all_sizes, local_size) + all_sizes = all_sizes.tolist() + + # Find maximum size and pad tensors + padded_input = layer_input.new_zeros((max(all_sizes), *layer_input.shape[1:])) + padded_input[: layer_input.shape[0]] = layer_input + + # Gather padded tensors + gathered_inputs = [torch.zeros_like(padded_input) for _ in range(world_size)] + dist.all_gather(gathered_inputs, padded_input.contiguous()) + + # Remove padding for each gathered tensor + gathered_inputs = [tensor[:size] for tensor, size in zip(gathered_inputs, all_sizes)] + + # Concatenate along batch dimension + return torch.cat(gathered_inputs, dim=0) + return layer_input + + +class SVDHook(_Hook): + """ + A forward hook for calculating incremental SVD on layer inputs. The hook is designed to be registered to a PyTorch + module using the `register_forward_hook` method. + + This hook performs a step of incremental Singular Value Decomposition (SVD) on the inputs of a specified layer + during the forward pass of a neural network. The hook also tracks convergence of the computed components using + cosine similarity between the current and previous components. + + Args: + name (str): Name of the layer to which this hook is attached. + n_components (int): Number of principal components to compute. + sim_thresh (Union[float, torch.Tensor]): Similarity threshold for convergence. + prepare_layer_inputs_fn (Optional[callable]): Function to prepare layer inputs for SVD. + """ + + def __init__( + self, + n_components: int, + sim_thresh: Union[float, torch.Tensor], + **base_class_kwargs, + ): + super().__init__(**base_class_kwargs) + self.n_components = n_components + self.sim_thresh = sim_thresh + if isinstance(sim_thresh, torch.Tensor) and len(sim_thresh.shape) > 0: + check1 = sim_thresh.size(0) == n_components or sim_thresh.size(0) == 1 + check2 = len(sim_thresh.shape) == 1 + if not (check1 and check2): + raise ValueError( + "if sim_thresh is a tensor with more than 0 dimensions it must have shape (n_components,) or (1,)" + ) + self.svd = IncrementalPCA( + n_components=n_components, + copy=True, + lowrank=True, + lowrank_seed=42, + ) + self.model_input = None + self.converged = torch.zeros((n_components,), dtype=torch.bool) + + @torch.no_grad() + def __call__(self, model, input, output): + previous_components = None + if hasattr(self.svd, "components_"): + previous_components = self.svd.components_.clone().detach() + states = self.prepare_layer_inputs(input) + states = self.gather_layer_inputs(states) + # check if batch sizes is more than the number of components + if states.size(0) < self.n_components: + print(f"skipping SVD for {self.name} because there are less than {self.n_components} examples") + return + self.svd.partial_fit(states.to(torch.float32)) + # add if statement to check if we are in the first step where previous_components is None + if previous_components is None: + return + components = self.svd.components_ + if len(components.shape) == 1: + components = components.reshape(1, -1) + previous_components = previous_components.reshape(1, -1) + # consider as converged if enough components have converged via cossim + sim = torch.nn.functional.cosine_similarity(components, previous_components) + self.converged = sim >= self.sim_thresh + + +# This is used to determine if inputs of two different layers are equal. For such cases, SVD +# needs to be done for only for one of the equal inputs. +class HashHook(_Hook): + """ + A forward hook for hashing layer inputs. The hook is designed to be registered to a PyTorch module using the + `register_forward_hook` method. + + This hook hashes the inputs of a specified layer during the forward pass of a neural network and stores the hash + values for later analysis or comparison. + + Args: + name (str): Name of the layer to which this hook is attached. hashed_inputs (list): List of hashed inputs. + prepare_layer_inputs_fn (Optional[callable]): Function to prepare layer inputs for hashing. + """ + + def __init__(self, **base_class_kwargs): + super().__init__(**base_class_kwargs) + self.hashed_inputs = [] + + @staticmethod + def hash_fn(tensor): + return hash(tuple(tensor.view(-1).tolist())) + + @torch.no_grad() + def __call__(self, model, input, output): + x = self.prepare_layer_inputs(input) + x = self.gather_layer_inputs(x) + self.hashed_inputs.append(self.hash_fn(x.cpu())) + + +def find_equal_values(dictionary: dict) -> dict: + """ + Find keys in a dictionary that have the same value. + + This function takes a dictionary and returns a new dictionary containing keys that have the same value. The keys in + the output dictionary are the values from the input dictionary, and the values are lists of keys that share the + same value. + """ + value_dict = defaultdict(list) + for k, v in dictionary.items(): + value_dict[v].append(k) + return {k: v for k, v in value_dict.items() if len(v) > 1} + + +def get_device_with_meta_params(model: torch.nn.Module) -> torch.device: + """ + Get the device of the model's parameters. Useful if some parameters are on meta device. + """ + devices = list({p.device for p in model.parameters() if p.device.type != "meta"}) + if len(devices) > 1: + warnings.warn(f"Could not determine device, model has multiple devices: {devices}") + return + return devices[0] + + +def move_inputs_to_device(inputs, device: Union[str, torch.device]): + """ + Move the inputs to the specified device. Adapted from hf.Trainer. + """ + if hasattr(inputs, "to"): + return inputs.to(device) + if isinstance(inputs, Mapping): + return type(inputs)({k: move_inputs_to_device(v, device) for k, v in inputs.items()}) + elif isinstance(inputs, (tuple, list)): + return type(inputs)(move_inputs_to_device(v, device) for v in inputs) + else: + warnings.warn(f"input of type {type(inputs)} could not be moved to the correct device") + return inputs + + +def prepare_model_inputs_fn_language_modeling(model_input, peft_config: LoraConfig): + """ + Get the indices of the items that should be used for SVD. + + Attributes: + model_input (dict): The model inputs. + peft_config (LoraConfig): The configuration for the LoRA layers. + """ + if not isinstance(model_input, dict): + raise ValueError("When using `prepare_model_inputs_fn_language_modeling` inputs must be a dictionary") + mask = model_input.get("attention_mask", torch.ones_like(model_input["input_ids"])).bool() + if peft_config.eva_config.use_label_mask and hasattr(model_input, "labels"): + mask = torch.logical_and(mask, model_input["labels"] != peft_config.eva_config.label_mask_value) + return mask.nonzero() + + +def prepare_layer_inputs_fn_language_modeling(layer_input, model_input, layer_name) -> torch.Tensor: + """ + if not all items in the input should be used for SVD, this function can be used to get the indices of the items + that should be used. + + Attributes: + layer_input (torch.Tensor): The layer inputs. + model_input (torch.Tensor): + The model inputs or if `prepare_model_inputs_fn` is not None the output of this function. + layer_name (str): The name of the layer. + + Returns: + torch.Tensor: The input to the SVD. + """ + # if layer inputs are not a tensor, we simply get the first item + if isinstance(layer_input, torch.Tensor): + pass + elif isinstance(layer_input, (tuple, list)): + layer_input = layer_input[0] + else: + raise ValueError( + f"unsupported input type {type(layer_input)} for prepare_layer_inputs_fn in layer {layer_name}, " + "please provide a custom prepare_layer_inputs_fn" + ) + # in this case model_input is the output of `prepare_model_inputs_fn_language_modeling` + return layer_input[model_input.T.unbind()] + + +def forward_fn_dict(model, inputs): + return model(**inputs) + + +def _get_eva_state_dict( + model: torch.nn.Module, + dataloader: Iterable, + peft_config: Optional[LoraConfig], + target_module_check_fn: callable, + forward_fn: Optional[callable], + prepare_model_inputs_fn: Optional[callable], + prepare_layer_inputs_fn: Union[callable, dict[str, callable], None], + gather_distributed_inputs: bool, + show_progress_bar: bool, +) -> dict: + # Computes the rank distribution for each layer based on the explained variance ratio. + # when rank_pattern flag is False, all values in max_components are the same + def _get_rank_distribution(hooks, layer_hook_map, equal_inputs_map, rank_budget, max_components): + exp_vars = {k: h[0].svd.explained_variance_ratio_[: max_components[k]] for k, h in hooks.items()} + keys, values = zip(*[(k, c) for k, name in layer_hook_map.items() for c in exp_vars[name]]) + idx = torch.stack(values).argsort(descending=True) + counts = Counter([keys[i] for i in idx[:rank_budget]]) + counts = {k: counts.get(k, 0) for k in layer_hook_map.keys()} # add layers with 0 rank + for k, k_hook in equal_inputs_map.items(): + # ensure hook layers have the highest rank if they are equal to another layer + rank, rank_hook = counts[k], counts[k_hook] + if rank_hook >= rank: + continue + counts[k_hook], counts[k] = rank, rank_hook + return counts + + # dataloader is not empty + if len(dataloader) == 0: + raise ValueError("dataloader is empty") + + # check if dist is initialized + if dist.is_initialized() and gather_distributed_inputs: + warnings.warn( + "torch.distributed is initialized and `gather_distributed_inputs` is True, " + "therefore EVA initialization will gather tensors from all ranks. " + "Ensure the model does not receive the same inputs on different ranks." + ) + + # for unusually high rho values, define an upper limit + rho_threshold = 1000 + rho = peft_config.eva_config.rho + if rho > rho_threshold: + max_dim = max(max(p.shape) for p in model.parameters()) + rho_ceil = max_dim // peft_config.r + rho = min(rho, rho_ceil) + + training = model.training + device = get_device_with_meta_params(model) + model.eval() + + # get model inputs + inputs = next(iter(dataloader)) + if device is not None: + inputs = move_inputs_to_device(inputs, device) + if prepare_model_inputs_fn is not None: + model_inputs_for_hooks = prepare_model_inputs_fn(inputs, peft_config) + else: + model_inputs_for_hooks = deepcopy(inputs) + + hooks = {} + max_components = {} + rank_budget = 0 + for name, module in model.named_modules(): + if not target_module_check_fn(name, module): + continue + if isinstance(prepare_layer_inputs_fn, Mapping): + fn = prepare_layer_inputs_fn.pop(name, None) + else: + fn = prepare_layer_inputs_fn + hook = HashHook(name=name, prepare_layer_inputs_fn=fn, gather_distributed_inputs=gather_distributed_inputs) + hook.model_input = model_inputs_for_hooks + handle = module.register_forward_hook(hook) + hooks[name] = (hook, handle) + layer_rank = peft_config.rank_pattern.get( + get_pattern_key(peft_config.rank_pattern.keys(), name), peft_config.r + ) + max_components[name] = round(layer_rank * rho) + rank_budget += layer_rank + if isinstance(prepare_layer_inputs_fn, Mapping) and len(prepare_layer_inputs_fn) > 0: + raise ValueError( + "prepare_layer_inputs_fn is a mapping but the following module names were not found in the model: " + f"{prepare_layer_inputs_fn.keys()}" + ) + + # forward for one batch to check which layer inputs are equal to avoid unneeded svd calculations + forward_fn(model, inputs) + hash_dict = {k: h[0].hashed_inputs[0] for k, h in hooks.items()} + # equal input maps groups layers which receive the same input. One layer is defined as the key and receives an svd + # hook. For the remaining layers the svd results can be skipped. + equal_inputs = list(find_equal_values(hash_dict).values()) + equal_inputs_map = {vv: v[0] for v in equal_inputs for vv in v[1:]} + # for layers with equal inputs we need to make sure that the max_components are the same + for names in equal_inputs: + max_value = max(max_components[n] for n in names) + for n in names: + max_components[n] = max_value + + # initialize svd hooks + for name in list(hooks.keys()): + hook, handle = hooks.pop(name) + handle.remove() + if name in equal_inputs_map: + continue + hook = SVDHook( + n_components=max_components[name], + sim_thresh=peft_config.eva_config.tau, + name=name, + prepare_layer_inputs_fn=hook._prepare_layer_inputs_fn, + gather_distributed_inputs=gather_distributed_inputs, + ) + module = model.get_submodule(name) + handle = module.register_forward_hook(hook) + hooks[name] = (hook, handle) # adding the old handle here so we dont get errors in the first forward pass + layer_hook_map = {**dict(zip(hooks.keys(), hooks.keys())), **equal_inputs_map} + + # start svd calculation + if show_progress_bar and (not dist.is_initialized() or dist.get_rank() == 0): + pbar = tqdm(iter(cycle(dataloader)), position=0, leave=False) + use_tqdm = True + else: + pbar = iter(cycle(dataloader)) + use_tqdm = False + convergence_dict = {k: False for k in hooks.keys()} + rank_dist = max_components.copy() + for inputs in pbar: + if device is not None: + inputs = move_inputs_to_device(inputs, device) + if prepare_model_inputs_fn is not None: + model_inputs_for_hooks = prepare_model_inputs_fn(inputs, peft_config) + else: + model_inputs_for_hooks = deepcopy(inputs) + + for name in list(hooks.keys()): + hook, handle = hooks[name] + # check if all components that are needed for the rank distribution have converged + converged = torch.all(hook.converged[: rank_dist[name]]) + # if a layer has switched from not converged to converged in the current step + if (not convergence_dict[name]) and converged and handle: + handle.remove() + handle = None + convergence_dict[name] = True + continue + # if a layer has switched from converged to not converged in the current step + elif convergence_dict[name] and not converged: + module = model.get_submodule(name) + handle = module.register_forward_hook(hook) + convergence_dict[name] = False + hook.model_input = model_inputs_for_hooks + hooks[name] = (hook, handle) + + if use_tqdm: + layer_converged = list(convergence_dict.values()) + [ + convergence_dict[v] for v in equal_inputs_map.values() + ] + pbar.set_description(f"{sum(layer_converged)}/{len(layer_converged)} layers have converged") + + if all(convergence_dict.values()): + break + + forward_fn(model, inputs) + + # in case some hooks have to skip the svd calculation because the number of tokens is less than the number of + # components + if not all(hasattr(h[0].svd, "components_") for h in hooks.values()): + continue + + rank_dist = _get_rank_distribution(hooks, layer_hook_map, equal_inputs_map, rank_budget, max_components) + + # check all custom hooks have been removed + remaining_hooks = {n for n, m in model.named_modules() for v in m._forward_hooks.values() if isinstance(v, _Hook)} + if len(remaining_hooks) > 0: + raise ValueError( + f"Found active hooks added by EVA that weren't properly removed: {remaining_hooks}. " + "Please report this issue at https://github.com/huggingface/peft/issues" + ) + + eva_state_dict = {} + for name, rank in rank_dist.items(): + hook = hooks[layer_hook_map[name]][0] + if not torch.all(hook.converged[:rank]): + raise ValueError( + f"Layer {name} has not converged but was assigned rank {rank}. " + "Please report this issue at https://github.com/huggingface/peft/issues" + ) + u = hook.svd.components_[:rank] + if peft_config.eva_config.whiten: + u /= hook.svd.singular_values_[:rank].sqrt().reshape(-1, 1) + eva_state_dict[name] = u + + # restore model state + model.train(training) + + # move tensors to device + if device is not None: + eva_state_dict = {k: v.to(device) for k, v in eva_state_dict.items()} + + return eva_state_dict + + +def _load_eva_state_dict( + model: torch.nn.Module, + eva_state_dict: dict, + adapter_name: str, +): + peft_config = copy(model.peft_config[adapter_name]) + missing_eva_inits = [] + new_target_modules = [] + other_module_names = [] + rank_pattern = {} + alpha_pattern = {} + for name, module in model.named_modules(): + name_in_base_model = name.replace("base_model.model.", "") + if not isinstance(module, LoraLayer): + other_module_names.append(name_in_base_model) + continue + # Regexp matching - Find key which matches current target_name in patterns provided + r = peft_config.rank_pattern.get(get_pattern_key(peft_config.rank_pattern.keys(), name), peft_config.r) + alpha = peft_config.alpha_pattern.get( + get_pattern_key(peft_config.alpha_pattern.keys(), name), peft_config.lora_alpha + ) + if name in eva_state_dict: + w = eva_state_dict.pop(name) + new_rank = w.size(0) + if new_rank == 0: + parent, _, target_name = _get_submodules(model, name) + setattr(parent, target_name, module.get_base_layer()) + continue + elif new_rank != r: + if peft_config.eva_config.adjust_scaling_factors: + alpha *= new_rank / r + if new_rank != r or module.lora_A[adapter_name].weight.device.type == "meta": + peft_config.init_lora_weights = "eva" + module.update_layer(adapter_name=adapter_name, r=new_rank, lora_alpha=alpha, config=peft_config) + module.lora_A[adapter_name].weight.copy_(w) + new_target_modules.append(name_in_base_model) + else: + peft_config.init_lora_weights = True + module.update_layer(adapter_name=adapter_name, r=r, lora_alpha=alpha, config=peft_config) + missing_eva_inits.append(name_in_base_model) + new_rank = r + # update rank pattern and alpha pattern + if new_rank != peft_config.r: + rank_pattern[name_in_base_model] = new_rank + if alpha != peft_config.lora_alpha: + alpha_pattern[name_in_base_model] = alpha + + # update target modules if some lora layers have been removed due to their EVA rank being 0 + new_target_modules = new_target_modules + missing_eva_inits + if len(new_target_modules) >= MIN_TARGET_MODULES_FOR_OPTIMIZATION: + new_target_modules = _find_minimal_target_modules(new_target_modules, other_module_names) + model.peft_config[adapter_name].target_modules = new_target_modules + + # set rank pattern obtained from EVA + model.peft_config[adapter_name].rank_pattern = rank_pattern + + # when adjust_scaling_factors is True, lora scaling factors have been adjusted after the rank redistribution + model.peft_config[adapter_name].alpha_pattern = alpha_pattern + + if missing_eva_inits: + warnings.warn( + "the following layers were initialized with init_lora_weights=True because they " + f"were not found in the eva state_dict: {missing_eva_inits}\ncurrently the " + f"following lora modules are not supported by EVA: {UNSUPPORTED_LORA_MODULES}" + ) + + +@torch.no_grad() +def get_eva_state_dict( + model: torch.nn.Module, + dataloader: Iterable, + peft_config: Optional[LoraConfig] = None, + forward_fn: Optional[callable] = forward_fn_dict, + prepare_model_inputs_fn: Optional[callable] = prepare_model_inputs_fn_language_modeling, + prepare_layer_inputs_fn: Union[callable, dict[str, callable], None] = prepare_layer_inputs_fn_language_modeling, + adapter_name: str = "default", + gather_distributed_inputs: bool = True, + show_progress_bar: bool = True, +) -> dict: + """ + Compute the SVD for each layer in the model. + + This function computes the Singular Value Decomposition (SVD) for each layer in the model. It uses the incremental + PCA method to compute the SVD components. The function also checks for convergence of the computed components using + cosine similarity. The rank distribution for each layer is determined based on the explained variance ratio. + + Args: + model (torch.nn.Module): The model to compute the SVD for. Does not need to be a PeftModel. + dataloader (Iterable): The dataloader to use for the forward pass. + peft_config (Optional[LoraConfig]): + The configuration for the LoRA layers. Only required if `model` is not a PeftModel. + forward_fn (callable): + The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default + behavior is `return model(**inputs)` + prepare_model_inputs_fn (Optional[callable]): + This function receives the model inputs and the peft_config and passes the output to + `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original + model inputs. For example for language modeling the attention mask is used to determine which indices are + padding tokens and should not be used for SVD. Any function defined here expects two arguments: + `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used + by default. + prepare_layer_inputs_fn (Union[callable, Dict[str, callable], None]): + This function receives the layer inputs, the model inputs (potentially modified by + `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for + that particular layer. Any custom function defined here expects three arguments: `layer_input`, + `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in + peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this + case model_inputs is the mask used to determine which indices should be used for SVD (created by + `prepare_model_inputs_fn_language_modeling`). + adapter_name (str): The name of the adapter to compute the SVD for. + gather_distributed_inputs (bool): + Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the + layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this + argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting. + show_progress_bar (bool): Whether to show a progress bar. Default is True. + + Returns: + eva_state_dict (dict): The state dictionary containing the SVD components for each layer. + """ + + def target_module_check_fn_peft_model(name, module, unsupported_lora_modules): + "check if a module is an adapter module via base_layer attribute" + return hasattr(module, "base_layer") and not isinstance(module, unsupported_lora_modules) + + def target_module_check_fn_default(name, module, peft_config): + "check if a module is an adapter module via target_modules" + is_target_module = True + if peft_config.target_modules is not None: + is_target_module = check_target_module_exists(peft_config, name) + # Conv1D for GPT2 support + return isinstance(module, (torch.nn.Linear, Conv1D)) and is_target_module + + is_peft_model = hasattr(model, "peft_config") + + # get peft_config + if is_peft_model and peft_config is None: + peft_config = model.peft_config[adapter_name] + elif peft_config is None: + raise ValueError("peft_config is required if model is not a PeftModel") + + # setup context and target module check function + if is_peft_model: + ctx = model.disable_adapter() + target_module_check_fn = partial( + target_module_check_fn_peft_model, unsupported_lora_modules=UNSUPPORTED_LORA_MODULES + ) + else: + ctx = nullcontext() + target_module_check_fn = partial(target_module_check_fn_default, peft_config=peft_config) + + with ctx: + eva_state_dict = _get_eva_state_dict( + model=model, + dataloader=dataloader, + peft_config=peft_config, + target_module_check_fn=target_module_check_fn, + forward_fn=forward_fn, + prepare_model_inputs_fn=prepare_model_inputs_fn, + prepare_layer_inputs_fn=prepare_layer_inputs_fn, + gather_distributed_inputs=gather_distributed_inputs, + show_progress_bar=show_progress_bar, + ) + return eva_state_dict + + +@torch.no_grad() +def initialize_lora_eva_weights( + model: torch.nn.Module, + dataloader: Optional[Iterable] = None, + eva_state_dict: Optional[dict] = None, + forward_fn: Optional[callable] = forward_fn_dict, + prepare_model_inputs_fn: Optional[callable] = prepare_model_inputs_fn_language_modeling, + prepare_layer_inputs_fn: Union[callable, dict[str, callable], None] = prepare_layer_inputs_fn_language_modeling, + adapter_name: str = "default", + gather_distributed_inputs: bool = True, + show_progress_bar: bool = True, +): + """ + Initialize the weights of the LoRA layers using the EVA method. + + This function initializes the weights of the LoRA layers using the EVA method. It computes the SVD for each adapter + layer and updates the weights accordingly. + + Args: + model (PeftModel): The peft model to compute the SVD for. + dataloader (Optional[Iterable]): + The dataloader to use for the forward pass. If None, eva_state_dict needs to be provided. + eva_state_dict (Optional[dict]): + The state_dict to load into the model. If None, a dataloader needs to be provided and the state_dict will + be computed using `get_eva_state_dict`. + forward_fn (callable): + The forward function to use for the forward pass. Takes two arguments: `model` and `inputs`. Default + behavior is `return model(**inputs)` + prepare_model_inputs_fn (Optional[callable]): + This function receives the model inputs and the peft_config and passes the output to + `prepare_layer_inputs_fn`. Can be used to modify the input to the SVD computation based on the original + model inputs. For example for language modeling the attention mask is used to determine which indices are + padding tokens and should not be used for SVD. Any function defined here expects two arguments: + `model_input` and `peft_config`. `peft.tuners.lora.eva.prepare_model_inputs_fn_language_modeling` is used + by default. + prepare_layer_inputs_fn (Union[callable, Dict[str, callable], None]): + This function receives the layer inputs, the model inputs (potentially modified by + `prepare_model_inputs_fn`) and the name of the layer and returns the inputs that should be used for SVD for + that particular layer. Any custom function defined here expects three arguments: `layer_input`, + `model_input`, and `layer_name` and should return a 2d tensor. The default logic can be found in + peft.tuners.lora.eva.prepare_layer_inputs_fn_language_modeling and works for language modeling. In this + case model_inputs is the mask used to determine which indices should be used for SVD (created by + `prepare_model_inputs_fn_language_modeling`). + adapter_name (str): The name of the adapter to initialize the weights for. + gather_distributed_inputs (bool): + Whether to gather the layer inputs from all ranks. Default is True meaning in a distributed setting the + layer inputs will be gathered from all ranks for the SVD computation. For non-distributed settings this + argument is ignored. Set to False if you are using a non-distributed dataloader in a distributed setting. + show_progress_bar (bool): Whether to show a progress bar. Default is True. + + Returns: + model (torch.nn.Module): The model with the initialized LoRA weights. + """ + if not hasattr(model, "peft_config"): + raise ValueError("model must be a PeftModel") + + # eva currently only works with a single active adapter + # Important: when removing this requirement, make sure eva init works correctly if the new rank is 0. + if len(model.active_adapters) > 1: + raise ValueError("`initialize_lora_eva_weights` currently only works with a single active adapter") + + # initialize_lora_eva_weights only works with `init_lora_weights='eva'` + if model.peft_config[adapter_name].init_lora_weights != "eva": + raise ValueError("`initialize_lora_eva_weights` can only be used with `init_lora_weights='eva'`") + + # compute svd + if eva_state_dict is None: + if dataloader is None: + raise ValueError("dataloader is required if eva_state_dict is not provided") + eva_state_dict = get_eva_state_dict( + model=model, + dataloader=dataloader, + forward_fn=forward_fn, + prepare_model_inputs_fn=prepare_model_inputs_fn, + prepare_layer_inputs_fn=prepare_layer_inputs_fn, + adapter_name=adapter_name, + gather_distributed_inputs=gather_distributed_inputs, + show_progress_bar=show_progress_bar, + ) + + _load_eva_state_dict(model, eva_state_dict, adapter_name) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/gptq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..d210e7e45d9c6e7003210909235cbdf49b9614eb --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/gptq.py @@ -0,0 +1,135 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from ...import_utils import is_gptqmodel_available +from .config import LoraConfig +from .layer import LoraVariant + + +class GPTQLoraLinear(torch.nn.Module, LoraLayer): + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + super().__init__() + LoraLayer.__init__(self, base_layer) + + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.use_dora and config.use_qalora: + raise NotImplementedError( + f"DoRA and QA-LoRA at the same time is not supported for {self.__class__.__name__} (yet)." + ) + elif config.use_dora: + from .variants import DoraLinearVariant + + variant = DoraLinearVariant() + elif config.use_qalora: + from .variants import QALoraLinearVariant + + variant = QALoraLinearVariant() + else: + variant = None + return variant + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + result = self.quant_linear_module(x) + + if self.disable_adapters: + return result + + lora_A_keys = self.lora_A.keys() + + for active_adapter in self.active_adapters: + if active_adapter not in lora_A_keys: + continue + torch_result_dtype = result.dtype + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + result = result + lora_B(lora_A(dropout(x))) * scaling + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + ) + + result = result.to(torch_result_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + # TODO: Check if it is better as suggested by users https://github.com/PanQiWei/AutoGPTQ/pull/102 + # def reset_lora_parameters(self, adapter_name): + # if adapter_name in self.lora_A.keys(): + # torch.nn.init.xavier_uniform_(self.lora_A[adapter_name].weight) + # torch.nn.init.zeros_(self.lora_B[adapter_name].weight) + + +def dispatch_gptq( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_gptqmodel_available(): + from gptqmodel.nn_modules.qlinear import BaseQuantLinear + + if isinstance(target_base_layer, BaseQuantLinear): + new_module = GPTQLoraLinear(target, adapter_name, config=config, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/hqq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..31f9a3f893db3746a5b0bbc1f0c6d78c6642ff8c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/hqq.py @@ -0,0 +1,244 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +import warnings +from typing import Any, Optional + +import torch + +from peft.import_utils import is_hqq_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .config import LoraConfig +from .layer import LoraLayer, LoraVariant + + +if is_hqq_available(): + from hqq.core.quantize import HQQLinear + + class HqqLoraLinear(torch.nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + if config.lora_bias: + raise ValueError(f"{self.__class__.__name__} does not support lora_bias yet, set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if not config.use_dora: + return None + + from .variants import DoraLinearVariant + + return DoraLinearVariant() + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + + output = layer.dequantize() + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output + lora_data + else: + w_data = self.lora_variant[active_adapter].merge_safe(self, active_adapter, output) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + output = layer.dequantize() + + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_data = self.get_delta_weight(active_adapter) + w_data = output.to(lora_data.dtype).to(lora_data.device) - lora_data + else: + w_data = self.lora_variant[active_adapter].unmerge(self, active_adapter, output) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + + def get_delta_weight(self, adapter): + return ( + transpose( + self.lora_B[adapter].weight @ self.lora_A[adapter].weight, + False, + ) + * self.scaling[adapter] + ) + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + result = self.base_layer(x, *args, **kwargs) + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + output = lora_B(lora_A(dropout(sub_batch))) * scaling + if requires_conversion: + output = output.to(expected_dtype) + result[sub_batch_indices_list[i]] += output + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + result = result + lora_B(lora_A(dropout(x))) * scaling + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + ) + + if requires_conversion: + result = result.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_hqq(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_hqq_available() and isinstance(target_base_layer, HQQLinear): + new_module = HqqLoraLinear(target_base_layer, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/inc.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/inc.py new file mode 100644 index 0000000000000000000000000000000000000000..60d92ea851d207aa987e750c4fbd73bf1d6cb6c0 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/inc.py @@ -0,0 +1,80 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# NOTE: PEFT tests related to INC are handled under Optimum-Habana repository: +# - LLMs: https://github.com/huggingface/optimum-habana/blob/main/tests/test_peft_inference.py +# - Diffusers: https://github.com/huggingface/optimum-habana/blob/main/tests/test_diffusers.py + +from typing import Optional + +import torch + +from peft.import_utils import is_inc_available +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig +from .layer import Linear + + +if is_inc_available(): + + class IncLoraLinear(Linear): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs, + ): + super().__init__(base_layer, adapter_name, config=config, **kwargs) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + raise NotImplementedError("Merging LoRA with INC layers is not yet implemented") + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + raise NotImplementedError("Unmerging LoRA from INC layers is not yet implemented") + + +def dispatch_inc(target: torch.nn.Module, adapter_name: str, config: LoraConfig, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_inc_available(): + from neural_compressor.torch.algorithms.fp8_quant._quant_common.helper_modules import ( + PatchedLinear, + ) + + if isinstance(target_base_layer, PatchedLinear): + new_module = IncLoraLinear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/intruders.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/intruders.py new file mode 100644 index 0000000000000000000000000000000000000000..81f0ae479087ef8ed2010dc7f6aeeec5c3d21635 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/intruders.py @@ -0,0 +1,160 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from .layer import LoraLayer + + +def reduce_intruder_dimension( + peft_model, + old_adapter_name="default", + new_adapter_name="intruder_reduced", + top_k=10, + threshold_epsilon=0.5, + mitigation_lambda=0.75, + logging_sink=print, +): + """ + Intruder dimension mitigation based on https://huggingface.co/papers/2410.21228 ("LoRA vs Full Fine-tuning: An + Illusion of Equivalence"). + + This method can recover previous knowledge (i.e. mitigate forgetting) by post-processing already trained low-rank + adapters. This comes at a cost of task accuracy - tuning the `migration_lambda` value can be used to trade between + these two factors. + + After mitigation is done there will be a new adapter with the name set in `new_adapter_name` which is also set to + be the currently active adapter. Inference on the mitigated model will therefore use the modified adapter. To + switch back to the original adapter you can use `peft_model.set_adapter()`. + + Currently only LoRA is supported as it is not clear whether this method generalizes to other delta-weight methods. + + Parameters: + peft_model: + The PEFT model with a loaded LoRA adapter with the name provided in `old_adapter_name`. Currently mixed + models are not supported. + + top_k (default: 10) + Consider the top-k dimensions for intruder detection. The larger the value, the more dimensions will be + considered for intruder detection analysis (and the more false-postiives there can be). Operates on the + cosine similarity between base weights and adapter weights roughly sorted by influence of dimension + (determined by singular value decomposition), so a top-k of 10 will look at the 10 most 'important' + dimensions. + + threshold_epsilon (default: 0.5) + Threshold value when to consider a cosine similarity between base weight and adapter weight as intruder. + According to the paper, intruder dimensions show near-zero absolute cosine similarity with pre-trained + singular vectors. The lower this value, the less potential intruder dimensions are identified. The higher + the value, the more potential false-positives are considered as intruders. + + mitigation_lambda (default: 0.75) + The relative portion of the intruder dimensions that is subtracted from the adapter's delta weight. The + higher the value the more of the intruder dimension is subtracted but the more information is lost. Refer + to Figure 8 in the paper for a trade-off analysis. + + logging_sink (default: print) + Function that prints information about the mitigation process. Set to None if you don't want any output. + """ + # Note that this function currently doesn't support `compile_kwargs` similar to the LoRA conversion tooling + # since there's was no clear way how `torch.compile` can be used to improve performance at the time of + # implementation. See discussion: https://github.com/huggingface/peft/pull/2999#discussion_r2717989613 + + def no_logging_sink(*args, **kwargs): + pass + + if logging_sink is None: + logging_sink = no_logging_sink + + if peft_model.peft_type != "LORA": + raise ValueError("The provided model is not using LoRA and is therefore not supported.") + + peft_model.add_adapter(new_adapter_name, peft_model.peft_config[old_adapter_name]) + + # apply mitigation on the old adapter's weights and move them to the new adapter's weights + for layer_name, layer in peft_model.named_modules(): + if not isinstance(layer, LoraLayer): + continue + + W = layer.get_base_layer().weight.data + dW = layer.get_delta_weight(old_adapter_name) + W_merged = W + dW + is_embedding = old_adapter_name not in layer.lora_B + + cast_to_fp32 = W.dtype in (torch.float16, torch.bfloat16) + + if cast_to_fp32: + W_dtype = W.dtype + W = W.float() + + # compare base weights and adapter weights using cosine similarity. + # based on this similarity we can find intruder dimensions using threshold_epsilon + # on the top_k dimensions + U_base, _S_base, _V_base = torch.linalg.svd(W, full_matrices=False) + U_merged, S_merged, V_merged = torch.linalg.svd(W_merged, full_matrices=False) + + cos_sim = (U_merged.T @ U_base).abs().max(dim=1).values + intruder_idcs = torch.where(cos_sim[:top_k] < threshold_epsilon)[0].tolist() + + if not intruder_idcs: + logging_sink(f"{layer_name}: No intruders") + + # we're not modifying the weights since there are no intruders but we make sure to copy the + # adapter weights unmodified to the new adapter, otherwise these weights will be + # initialized randomly + if is_embedding: + layer.lora_embedding_B[new_adapter_name].data = layer.lora_embedding_B[old_adapter_name].data.clone() + layer.lora_embedding_A[new_adapter_name].data = layer.lora_embedding_A[old_adapter_name].data.clone() + else: + layer.lora_B[new_adapter_name].weight.data = layer.lora_B[old_adapter_name].weight.data.clone() + layer.lora_A[new_adapter_name].weight.data = layer.lora_A[old_adapter_name].weight.data.clone() + continue + else: + logging_sink(f"{layer_name}: Intruders: {len(intruder_idcs)}") + + # the paper computes the intruder dimensions that are subtracted on (W + dW), so we do the same. experiments + # showed that this achieves better knowledge recovery than on dW alone. + B_intruder = U_merged[:, intruder_idcs] @ torch.diag(S_merged)[intruder_idcs, :].sqrt() + A_intruder = (torch.diag(S_merged)[:, intruder_idcs]).sqrt() @ V_merged[intruder_idcs, :] + + # apply mitigation and recover dW = (B@A). + # (W+dW+mitigation)-W = dW+mitigation, so we can convert dW back to A/B using SVD + # since we know the effective rank from the adapter config. + # + # note that we also remove the scaling from dW which is applied in get_delta_weight() since + # it impacts mitigation performance both in task accuracy and forgetting. + W_mitigated = W_merged + (mitigation_lambda - 1) * (B_intruder @ A_intruder) + dW_mitigated = W_mitigated - W + dW_mitigated /= layer.scaling[old_adapter_name] + + U_dW, S_dW, V_dW = torch.linalg.svd(dW_mitigated, full_matrices=False) + + # Note: share scaling by S equally between B and A to avoid one matrix having a significantly + # different norm and avoid possibly weird training dynamics. + effective_rank = layer.r[old_adapter_name] + B_new = U_dW[:, :effective_rank] @ torch.diag(S_dW[:effective_rank]).sqrt() + A_new = torch.diag(S_dW[:effective_rank]).sqrt() @ V_dW[:effective_rank] + + if is_embedding: + layer.lora_embedding_B[new_adapter_name].data = B_new + layer.lora_embedding_A[new_adapter_name].data = A_new + else: + layer.lora_B[new_adapter_name].weight.data = B_new + layer.lora_A[new_adapter_name].weight.data = A_new + + # cast W back from float32 to whatever it was before to save memory in the long run + if cast_to_fp32: + W = W.to(W_dtype) + + logging_sink(f"Enabling new adapter {new_adapter_name}") + peft_model.set_adapter(new_adapter_name) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..bcf504345750c85e9641c62ea0f1680729435710 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/layer.py @@ -0,0 +1,2381 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import math +import warnings +from contextlib import contextmanager +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from torch import svd_lowrank +from transformers.pytorch_utils import Conv1D + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils.integrations import ( + dequantize_module_weight, + gather_params_ctx, + get_bnb_param_type, + skip_init_on_device, +) +from peft.utils.loftq_utils import loftq_init +from peft.utils.other import transpose +from peft.utils.warning import PeftWarning + +from .config import LoraConfig + + +VARIANT_KWARG_KEYS = ["alora_offsets"] + + +class LoraVariant: + """ + Base class for LoRA variants, e.g. DoRA. + + This class should be subclassed and the methods below should be implemented accordingly. The methods should be + implemented as static methods, this makes it easier to combine variants. + + Note for developers: These methods are prone to change and should thus considered to be "private". Use at your own + discretion. + """ + + @staticmethod + def init(module: LoraLayer, adapter_name: str) -> None: + """Initialization code for the LoRA variant, it's called within `update_layer`""" + raise NotImplementedError + + @staticmethod + def merge_safe(module: LoraLayer, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + """Safe merging of the weights from `merge(..., safe_merge=True)`, should return a new tensor""" + raise NotImplementedError + + @staticmethod + def merge_unsafe(module: LoraLayer, active_adapter: str, orig_weight: torch.Tensor) -> None: + """Unsafe merging of the weights from `merge(..., safe_merge=False)`, should modify the weight in-place""" + + @staticmethod + def unmerge(module: LoraLayer, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + """Remove the adapter weights from the original weights, then return them""" + + @staticmethod + def forward( + module: LoraLayer, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + """ + The forward pass of the LoRA variant, should return the overall result (not just the diff) + + Args: + module (LoraLayer): The module on which the forward pass is called + active_adapter (str): The name of the active adapter + x (torch.Tensor): The input to the forward call + result (torch.Tensor): The result from the base model + **kwargs: Additional arguments passed from [`LoraLayer.forward`]. + """ + raise NotImplementedError + + +class LoraLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("lora_A", "lora_B", "lora_embedding_A", "lora_embedding_B") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "lora_alpha", "scaling", "lora_dropout") + + def __init__(self, base_layer: nn.Module, ephemeral_gpu_offload: bool = False, **kwargs) -> None: + self.base_layer = base_layer + self.r = {} + self.lora_alpha = {} + self.scaling = {} + self.lora_dropout = nn.ModuleDict({}) + self.lora_A = nn.ModuleDict({}) + self.lora_B = nn.ModuleDict({}) + # For Embedding layer + self.lora_embedding_A = nn.ParameterDict({}) + self.lora_embedding_B = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.use_dora: dict[str, bool] = {} # not actively used anymore after #2443, keep it for BC + self.use_rslora: dict[str, bool] = {} + self.lora_bias: dict[str, bool] = {} + self.lora_magnitude_vector = torch.nn.ModuleDict() # for DoRA + self._caches: dict[str, Any] = {} # small ad hoc cache; values are not part of the state_dict + self.ephemeral_gpu_offload: bool = ephemeral_gpu_offload + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled: bool = True + self.lora_variant: dict[str, LoraVariant] = {} + self.kwargs = kwargs + + base_layer = self.get_base_layer() + in_features, out_features = self._get_in_out_features(base_layer) + self.in_features = in_features + self.out_features = out_features + + def _get_in_out_features(self, module: nn.Module) -> tuple[int, int] | tuple[None, None]: + return _get_in_out_features(module) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + """Return a matching LoRA variant for this layer type. + + Given the init arguments of this layer, return the correct LoRA variant, if any. E.g., if `use_dora=True`, this + method should return the DoRA variant for the given layer. If `use_alora=True`, same for aLoRA. + + If there is no fitting variant, return None. + + Note: If this layer type does not support the LoRA variant at all, please raise an error during __init__ as is + convention, and not here. + + """ + return None + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + # collect the kwargs + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + + target_name = kwargs.get("target_name", "") # preserve target_name before overwriting kwargs + kwargs["target_name"] = target_name # restore target_name + tied_adapter = kwargs.get("tied_adapter", None) + + # This code works for linear layers, override for other layer types + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + if lora_bias and (getattr(self.get_base_layer(), "bias", None) is None): + warnings.warn( + f"`lora_bias=True` was passed but the targeted layer of type {type(self.get_base_layer()).__name__} " + "has no bias. This means that merging LoRA weights won't be possible.", + PeftWarning, + ) + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + self.lora_variant[adapter_name] = lora_variant + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout.update(nn.ModuleDict({adapter_name: lora_dropout_layer})) + + # Actual trainable parameters + self.lora_A[adapter_name] = nn.Linear(self.in_features, r, bias=False) + self.lora_B[adapter_name] = nn.Linear(r, self.out_features, bias=lora_bias) + + # Tying adapters is only implemented for Linear layers + # where the source is the embedding layer. + # Currently, this is the most prevelant way of tying layers (weight tying) + if tied_adapter: + lora_A_params = tied_adapter["lora_A"] + lora_B_params = tied_adapter["lora_B"] + + self.lora_A[adapter_name].weight = torch.nn.Parameter(lora_A_params) + self.lora_B[adapter_name].weight = torch.nn.Parameter(lora_B_params) + + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed + if isinstance(init_lora_weights, str) and init_lora_weights.startswith("pissa"): + with gather_params_ctx(self.get_base_layer().weight): + self.pissa_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.startswith("corda"): + with gather_params_ctx(self.get_base_layer().weight): + self.corda_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.lower() == "olora": + with gather_params_ctx(self.get_base_layer().weight): + self.olora_init(adapter_name) + elif init_lora_weights == "loftq": + with gather_params_ctx(self.get_base_layer().weight): + self.loftq_init(adapter_name, config) + elif init_lora_weights == "eva": + nn.init.zeros_(self.lora_B[adapter_name].weight) + elif init_lora_weights == "orthogonal": + with gather_params_ctx(self.get_base_layer().weight): + self.orthogonal_init(adapter_name) + elif init_lora_weights == "lora_ga": + with gather_params_ctx(self.get_base_layer().weight): + self.lora_ga_init(adapter_name, config.lora_ga_config) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + # Check for adapters that were added or removed from the arrow_model. + # The arrow model may be modified after creation by adding new experts + # (pre-trained or trainable) or by removing existing ones. Whenever such + # a change occurs, on_adapter_change() is called to update the set of + # active task-specific experts and, if needed, to handle recomputing prototypes + # and doing general knowledge subtraction (GKS) again. + if hasattr(self, "lora_arrow"): + for adapter in self.lora_variant: + if adapter in self.lora_arrow: + self.lora_arrow[adapter].on_adapter_change(self.lora_A, self.lora_B) + + def reset_lora_parameters(self, adapter_name, init_lora_weights): + if init_lora_weights is False: + return + + if adapter_name in self.lora_A.keys(): + if init_lora_weights is True: + # initialize A the same way as the default for nn.Linear and B to zero + # https://github.com/microsoft/LoRA/blob/a0a92e0f26c067cf94747bdbf1ce73793fa44d19/loralib/layers.py#L124 + nn.init.kaiming_uniform_(self.lora_A[adapter_name].weight, a=math.sqrt(5)) + elif init_lora_weights.lower() == "gaussian": + nn.init.normal_(self.lora_A[adapter_name].weight, std=1 / self.r[adapter_name]) + else: + raise ValueError(f"Unknown initialization {init_lora_weights=}") + nn.init.zeros_(self.lora_B[adapter_name].weight) + if self.lora_bias[adapter_name]: + nn.init.zeros_(self.lora_B[adapter_name].bias) + if adapter_name in self.lora_embedding_A.keys(): + # Initialize A to zeros and B the same way as the default for nn.Embedding, see: + # https://github.com/microsoft/LoRA/blob/4c0333854cb905966f8cc4e9a74068c1e507c7b7/loralib/layers.py#L59-L60 + nn.init.zeros_(self.lora_embedding_A[adapter_name]) + nn.init.normal_(self.lora_embedding_B[adapter_name]) + if self.lora_bias[adapter_name]: + # embeddings are not supported at the moment, but still adding this for consistency + nn.init.zeros_(self.lora_embedding_B[adapter_name].bias) + + def olora_init(self, adapter_name): + base_layer = self.get_base_layer() + orig_weight = base_layer.weight + bnb_param_type = get_bnb_param_type(orig_weight) + dtype = orig_weight.dtype + + if bnb_param_type: + # check without importing bitsandbytes and robust to bnb_4bit_quant_storage=float* + weight_tensor = dequantize_module_weight(base_layer) + elif dtype in [torch.float32, torch.float16, torch.bfloat16]: + weight_tensor = orig_weight + else: + raise TypeError(f"Unsupported data type for the base layer. Got {dtype}.") + + scale_factor = self.scaling[adapter_name] + r = self.r[adapter_name] + weight_tensor = weight_tensor.to(torch.float32) + Q, R = torch.linalg.qr(weight_tensor.data) + + Qr, Rr = Q[:, :r], R[:r] + + self.lora_A[adapter_name].weight.data = Rr.contiguous() + self.lora_B[adapter_name].weight.data = Qr.contiguous() + + weight_tensor.data -= scale_factor * self.lora_B[adapter_name].weight @ self.lora_A[adapter_name].weight + if bnb_param_type == "4bit": + weight_tensor = orig_weight.__class__( + weight_tensor, + quant_type=orig_weight.quant_type, + quant_storage=orig_weight.quant_storage, + compress_statistics=orig_weight.compress_statistics, + module=orig_weight.module, + ).to(orig_weight.device) + base_layer.weight = weight_tensor + elif bnb_param_type == "8bit": + weight_tensor = orig_weight.__class__( + weight_tensor, + requires_grad=orig_weight.requires_grad, + has_fp16_weights=orig_weight.has_fp16_weights, + ).to(orig_weight.device) + base_layer.weight = weight_tensor + else: + weight_tensor = weight_tensor.to(dtype) + base_layer.weight.data = weight_tensor + + def pissa_init(self, adapter_name, init_lora_weights): + weight = self.get_base_layer().weight + dtype = weight.dtype + if dtype not in [torch.float32, torch.float16, torch.bfloat16]: + raise TypeError( + "Please initialize PiSSA under float32, float16, or bfloat16. " + "Subsequently, re-quantize the residual model to help minimize quantization errors." + ) + weight = transpose(weight.to(torch.float32), self.fan_in_fan_out) + if init_lora_weights == "pissa": + # USV^T = W <-> VSU^T = W^T, where W^T = weight.data in R^{out_channel, in_channel}, + V, S, Uh = torch.linalg.svd(weight.data, full_matrices=False) + Vr = V[:, : self.r[adapter_name]] + Sr = S[: self.r[adapter_name]] + Sr /= self.scaling[adapter_name] + Uhr = Uh[: self.r[adapter_name]] + elif len(init_lora_weights.split("_niter_")) == 2: + Vr, Sr, Ur = svd_lowrank( + weight.data, self.r[adapter_name], niter=int(init_lora_weights.split("_niter_")[-1]) + ) + Sr /= self.scaling[adapter_name] + Uhr = Ur.t() + else: + raise ValueError( + f"init_lora_weights should be 'pissa' or 'pissa_niter_[number of iters]', got {init_lora_weights} instead." + ) + + lora_A = torch.diag(torch.sqrt(Sr)) @ Uhr + lora_B = Vr @ torch.diag(torch.sqrt(Sr)) + self.lora_A[adapter_name].weight.data = lora_A + self.lora_B[adapter_name].weight.data = lora_B + weight = weight.data - self.scaling[adapter_name] * lora_B @ lora_A + weight = transpose(weight.to(dtype), self.fan_in_fan_out) + self.get_base_layer().weight.data = weight + + def corda_init(self, adapter_name, init_lora_weights): + linear = self.get_base_layer() + weight = linear.weight + dtype = weight.dtype + if dtype not in [torch.float32, torch.float16, torch.bfloat16]: + raise TypeError( + "Please initialize CorDA under float32, float16, or bfloat16. " + "Subsequently, re-quantize the residual model to help minimize quantization errors." + ) + weight = weight.to(torch.float32) + # For Conv1D, weight is stored as (in_features, out_features), transposed compared to Linear + if isinstance(linear, Conv1D): + out_dim = weight.data.size(1) + in_dim = weight.data.size(0) + else: + out_dim = weight.data.size(0) + in_dim = weight.data.size(1) + + # Calculate WC from covariance matrix + if not hasattr(linear, "eigens"): + raise ValueError( + "`eigens` attribute not found for layer, please run `preprocess_corda` first. " + "More information can be found at examples/corda_finetuning/README.md." + ) + eigens = linear.eigens + U = eigens.U_WC + S = eigens.S_WC + V = eigens.V_WC + r = self.r[adapter_name] + + # nan or inf check + if torch.isnan(S).any() or torch.isinf(S).any(): + raise ValueError( + "Invalid value found in matrix S. Please file an issue at https://github.com/huggingface/peft/issues." + ) + if torch.isnan(U).any() or torch.isinf(U).any(): + raise ValueError( + "Invalid value found in matrix U. Please file an issue at https://github.com/huggingface/peft/issues." + ) + if torch.isnan(V).any() or torch.isinf(V).any(): + raise ValueError( + "Invalid value found in matrix V. Please file an issue at https://github.com/huggingface/peft/issues." + ) + + # Sanity check + if U.size(0) != out_dim or U.size(1) != r: + raise ValueError( + f"Matrix U size mismatch: {U.size()} vs. ({out_dim}, {r}). Please make sure the `lora_config` and " + "`model` argument of `preprocess_corda` is consistent with `get_peft_model`. If you're using cache " + "in `preprocess_corda`, please make sure the cache is built with the same model and LoRA rank." + ) + if S.size(0) != r: + raise ValueError( + f"Matrix S size mismatch: {S.size()} vs. ({r},). Please make sure the `lora_config` and `model` argument " + "of `preprocess_corda` is consistent with `get_peft_model`. If you're using cache in `preprocess_corda`, " + "please make sure the cache is built with the same model and LoRA rank." + ) + if V.size(0) != in_dim or V.size(1) != r: + raise ValueError( + f"Matrix V size mismatch: {V.size()} vs. ({in_dim}, {r}). Please make sure the `lora_config` and " + "`model` argument of `preprocess_corda` is consistent with `get_peft_model`. If you're using cache " + "in `preprocess_corda`, please make sure the cache is built with the same model and LoRA rank." + ) + + # Apply alpha + S /= self.scaling[adapter_name] + + # Init lora_A and lora_B weights + lora_A = V.t().mul(S.sqrt().view(-1, 1)).contiguous() + lora_B = U.mul(S.sqrt()).contiguous() + self.lora_A[adapter_name].weight.data = lora_A + self.lora_B[adapter_name].weight.data = lora_B + + # For Conv1D, lora_B @ lora_A gives (out_dim, in_dim) but weight is (in_dim, out_dim) + # So we need to transpose before subtraction + delta = self.scaling[adapter_name] * lora_B @ lora_A + delta = transpose(delta, fan_in_fan_out=self.fan_in_fan_out) + weight = weight.data - delta + weight = weight.to(dtype) + self.get_base_layer().weight.data = weight + + # Remove redundant fields + del linear.eigens + + def loftq_init(self, adapter_name, config: LoraConfig): + weight = self.get_base_layer().weight + kwargs = { + "num_bits": config.loftq_config["loftq_bits"], + "reduced_rank": self.r[adapter_name], + "num_iter": config.loftq_config["loftq_iter"], + } + + qweight, lora_A, lora_B = loftq_init(weight, **kwargs) + if adapter_name in self.lora_A.keys(): + # initialize A the same way as the default for nn.Linear and B to zero + self.lora_A[adapter_name].weight.data = lora_A + self.lora_B[adapter_name].weight.data = lora_B + if adapter_name in self.lora_embedding_A.keys(): + # initialize a the same way as the default for nn.linear and b to zero + self.lora_embedding_A[adapter_name].weight.data = lora_A + self.lora_embedding_B[adapter_name].weight.data = lora_B + self.get_base_layer().weight.data = qweight + + @torch.no_grad() + def orthogonal_init(self, adapter_name): + # https://datta0.github.io/posts/rethink-lora-init/#orthogonal-initialisation + rank = self.r[adapter_name] + if rank % 2 != 0: + raise ValueError(f"Orthogonal initialization requires the LoRA rank to be even, got {rank} instead.") + + X = torch.randn(rank, rank) + Q, _ = torch.linalg.qr(X) + q_odd = Q[0::2, :] # Odd rows + q_even = Q[1::2, :] # Even rows + dtype = self.get_base_layer().weight.dtype + lora_A = torch.randn(self.in_features, rank // 2).mm(q_odd).T / 10.0 + lora_B = torch.randn(rank // 2, self.out_features).T.mm(q_even) / 10.0 + self.lora_A[adapter_name].weight = nn.Parameter(lora_A.contiguous().to(dtype)) + self.lora_B[adapter_name].weight = nn.Parameter(lora_B.contiguous().to(dtype)) + + def lora_ga_init(self, adapter_name, lora_ga_config): + """ + Initialize LoRA weights using gradient approximation. + + Uses SVD on the gradient matrix to initialize adapters in a way that aligns with the direction of full + fine-tuning. + + Expects that `preprocess_loraga` has been called before this, which attaches the `loraga_grad` attribute to the + base layer. + + If gradients are not available (e.g., when loading from a saved adapter), falls back to gaussian + initialization. The weights will be overwritten by the state_dict anyway. + """ + base_layer = self.get_base_layer() + + # Check for gradient attached by preprocess_loraga + if not hasattr(base_layer, "_peft_loraga_grad"): + # When loading from saved adapter, gradients won't be available + # Fall back to gaussian initialization (weights will be overwritten by state_dict) + self.reset_lora_parameters(adapter_name, init_lora_weights=True) + return + + grad = base_layer._peft_loraga_grad + + # Check for lora_ga_config + if lora_ga_config is None: + raise ValueError( + "lora_ga_config must be provided when init_lora_weights='lora_ga'. " + "Please pass lora_ga_config=LoraGAConfig(...) to LoraConfig." + ) + direction = lora_ga_config.direction + scale = lora_ga_config.scale + stable_gamma = lora_ga_config.stable_gamma + dtype = self.get_base_layer().weight.dtype + + grad = grad.to(torch.float32) + weight = self.get_base_layer().weight + + grad = transpose(grad, self.fan_in_fan_out) + + r = self.r[adapter_name] + + # torch.svd_lowrank returns (U, S, V) where grad ≈ U @ diag(S) @ V.T + # So V is shape (in_features, k) and we need V.T which is (k, in_features) for lora_A + U, S, V = torch.svd_lowrank(grad, q=min(4 * r, min(grad.shape)), niter=4) + + # V is (in_features, k), we need Vh = V.T which is (k, in_features) + Vh = V.t() + + U = U[:, : 2 * r] + S = S[: 2 * r] + Vh = Vh[: 2 * r, :] + + if direction == "ArBr": + # Alternating: A takes rows at odd indices [1,3,5,7], B takes columns at even indices [0,2,4,6] + lora_A_weight = Vh[1 : 2 * r : 2, :] # Shape: (r, in_features) + lora_B_weight = U[:, 0 : 2 * r : 2] # Shape: (out_features, r) + S_B = S[0 : 2 * r : 2] + lora_B_weight = lora_B_weight @ torch.diag(S_B) + + elif direction == "A2rBr": + # A takes second half rows [r:2r], B takes first half columns [:r] + lora_A_weight = Vh[r : 2 * r, :] # Shape: (r, in_features) + lora_B_weight = U[:, :r] # Shape: (out_features, r) + S_B = S[:r] + lora_B_weight = lora_B_weight @ torch.diag(S_B) + + elif direction == "ArB2r": + # A takes first half rows [:r], B takes second half columns [r:2r] + lora_A_weight = Vh[:r, :] # Shape: (r, in_features) + lora_B_weight = U[:, r : 2 * r] # Shape: (out_features, r) + S_B = S[r : 2 * r] + lora_B_weight = lora_B_weight @ torch.diag(S_B) + + elif direction == "random": + indices = torch.randperm(2 * r)[:r] + lora_A_weight = Vh[indices, :] # Shape: (r, in_features) + S_B = S[indices] + lora_B_weight = U[:, indices] @ torch.diag(S_B) # Shape: (out_features, r) + + scaling_factor = self.scaling[adapter_name] + out_features = weight.shape[0] + + if scale == "stable": + scale_factor = (out_features**0.25) / (stable_gamma**0.5) + lora_B_weight = lora_B_weight * scale_factor + + elif scale == "weight_svd": + weight_data = transpose(weight.data.to(torch.float32), self.fan_in_fan_out) + _, weight_S, _ = torch.svd_lowrank(weight_data, q=r, niter=4) + if S_B[0] > 0: + scale_factor = weight_S[0] / S_B[0] + lora_B_weight = lora_B_weight * scale_factor + + elif scale == "gd_scale": + lora_A_weight = lora_A_weight / scaling_factor + lora_B_weight = lora_B_weight / scaling_factor + + # Convert to target dtype first to ensure weight offset matches adapter precision + lora_A_weight = lora_A_weight.to(dtype) + lora_B_weight = lora_B_weight.to(dtype) + + # Assign LoRA weights + # lora_A should be (r, in_features), lora_B should be (out_features, r) + self.lora_A[adapter_name].weight.data = lora_A_weight.contiguous() + self.lora_B[adapter_name].weight.data = lora_B_weight.contiguous() + + # Modify base weights: W_new = W_old - scaling * (B @ A) + # Important: compute offset in fp32 using dtype-converted weights to match forward pass precision + weight_data = transpose(weight.data.to(torch.float32), self.fan_in_fan_out) + weight_offset = scaling_factor * (lora_B_weight.float() @ lora_A_weight.float()) + weight_data = weight_data - weight_offset + weight_data = transpose(weight_data.to(dtype), self.fan_in_fan_out) + self.get_base_layer().weight.data = weight_data + + # Remove redundant fields + del base_layer._peft_loraga_grad + + def _cache_store(self, key: str, value: Any) -> None: + # cache intermediate values, e.g. weight norm of DoRA + self._caches[key] = value + + def _cache_pop(self, key: str) -> Any: + # retrieve and remove from ad hoc cache + value = self._caches.pop(key) + return value + + def set_scale(self, adapter: str, scale: float | int) -> None: + """Set the scale of the given adapter to the initial scale multiplied by the provided factor + + The initial scale is determined by the configured `r` (rank) and `lora_alpha`. + """ + if adapter not in self.scaling: + # Ignore the case where the adapter is not in the layer + return + if self.use_rslora.get(adapter, False): + self.scaling[adapter] = scale * self.lora_alpha[adapter] / math.sqrt(self.r[adapter]) + else: + self.scaling[adapter] = scale * self.lora_alpha[adapter] / self.r[adapter] + + def scale_layer(self, scale: float | int) -> None: + """Multiply the current scale of all active adapters by the provided factor""" + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + + self.scaling[active_adapter] *= scale + + def unscale_layer(self, scale: Optional[float | int] = None) -> None: + """Divide the current scale of all active adapters by the provided factor. If `scale=None` is passed, reset to + initial scale + + The initial scale is determined by the configured `r` (rank) and `lora_alpha`. + + """ + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + + if scale is None: + if self.use_rslora.get(active_adapter, False): + self.scaling[active_adapter] = self.lora_alpha[active_adapter] / math.sqrt(self.r[active_adapter]) + else: + self.scaling[active_adapter] = self.lora_alpha[active_adapter] / self.r[active_adapter] + else: + self.scaling[active_adapter] = self.scaling[active_adapter] / scale + + def _check_forward_args(self, x, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + adapter_names = kwargs.get("adapter_names", None) + if adapter_names is None: + return + + if len(x) != len(adapter_names): + msg = ( + "Length of `adapter_names` should be the same as the number of inputs, but got " + f"{len(adapter_names)} and {len(x)} respectively." + ) + raise ValueError(msg) + + if self.merged: + # It is unclear what would be the right thing to do if users pass adapter_names and there are merged + # adapters. Therefore, it is better to raise an error in this case. + msg = "Cannot pass `adapter_names` when there are merged adapters, please call `unmerge_adapter` first." + raise ValueError(msg) + + # DoRA is not supported (yet), check that it's not being used. Don't check "__base__", as this is the + # placeholder for the base model. + unique_adapters = {name for name in adapter_names if name != "__base__"} + for adapter_name in unique_adapters: + if self.use_dora.get(adapter_name, False): + msg = "Cannot pass `adapter_names` when DoRA is enabled." + raise ValueError(msg) + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + alora_offsets = variant_kwargs.get("alora_offsets", None) + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_A.keys(): + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]].to(lora_A.weight.dtype) + if active_adapter not in self.lora_variant: # vanilla LoRA + lora_output = lora_B(lora_A(dropout(sub_batch))) * scaling + result[sub_batch_indices_list[i]] += lora_output.to(torch_result_dtype) + else: + if alora_offsets is not None: + variant_kwargs["alora_offsets"] = [alora_offsets[j] for j in sub_batch_indices_list[i]] + lora_output = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=sub_batch, + result=result[sub_batch_indices_list[i]], + **variant_kwargs, + **kwargs, + ) + result[sub_batch_indices_list[i]] = lora_output.to(torch_result_dtype) + + return result + + +# Below code is based on https://github.com/microsoft/LoRA/blob/main/loralib/layers.py +# and modified to work with PyTorch FSDP + + +# ------------------------------------------------------------------------------------------ +# Copyright (c) Microsoft Corporation. All rights reserved. +# Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. +# ------------------------------------------------------------------------------------------ + + +class Linear(nn.Module, LoraLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + **kwargs, + ) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def resolve_lora_variant(self, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if config.arrow_config is not None: + from .variants import ArrowLinearVariant + + return ArrowLinearVariant() + + if config.use_bdlora is not None: + from .variants import BdLoraLinearVariant + + return BdLoraLinearVariant() + + use_alora = config.alora_invocation_tokens is not None + if not config.use_dora and not use_alora: + return None + + from .variants import ALoraLinearVariant, DoraLinearVariant + + if use_alora: + return ALoraLinearVariant() + else: + return DoraLinearVariant() + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.lora_A.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + orig_dtype = orig_weight.dtype + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + else: + orig_weight = self.lora_variant[active_adapter].merge_safe(self, active_adapter, orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + new_bias = base_layer.bias + self.lora_B[active_adapter].bias * self.scaling[active_adapter] + if not torch.isfinite(new_bias).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + base_layer.bias.data = new_bias.to(orig_dtype) + + else: + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight + else: + self.lora_variant[active_adapter].merge_unsafe(self, active_adapter, base_layer.weight) + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + base_layer.bias.data += self.lora_B[active_adapter].bias * self.scaling[active_adapter] + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + weight = self.get_base_layer().weight + if active_adapter not in self.lora_variant: # vanilla LoRA + orig_dtype = weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight.to(orig_dtype) + else: + unmerged = self.lora_variant[active_adapter].unmerge(self, active_adapter, weight) + weight.data = unmerged + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias * self.scaling[active_adapter] + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.lora_B[adapter].weight.device + dtype = self.lora_B[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, self.fan_in_fan_out) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **variant_kwargs, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + lora_A_keys = self.lora_A.keys() + for active_adapter in self.active_adapters: + if active_adapter not in lora_A_keys: + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + x = self._cast_input_dtype(x, lora_A.weight.dtype) + if active_adapter not in self.lora_variant: # vanilla LoRA + result = result + lora_B(lora_A(dropout(x))) * scaling + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + + result = result.to(torch_result_dtype) + + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class Embedding(nn.Module, LoraLayer): + # LoRA implemented in a Embedding layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + init_lora_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + if config.lora_bias: + # lora_bias=True is not supported (yet) for embedding layers, as they use nn.Parameter + raise ValueError(f"lora_bias={config.lora_bias} is not supported for {self.__class__.__name__}.") + + super().__init__() + LoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = config.fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if not config.use_dora: + return None + + from .variants import DoraEmbeddingVariant + + return DoraEmbeddingVariant() + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + self.lora_variant[adapter_name] = lora_variant + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + # Actual trainable parameters + weight_A = torch.randn((r, self.in_features)) + weight_B = torch.randn((self.out_features, r)) + self.lora_embedding_A[adapter_name] = nn.Parameter(weight_A) + self.lora_embedding_B[adapter_name] = nn.Parameter(weight_B) + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + if init_lora_weights == "loftq": + self.loftq_init(adapter_name) + elif init_lora_weights == "lora_ga": + # Embedding layers don't support LoRA-GA, fall back to standard initialization + self.reset_lora_parameters(adapter_name, True) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.lora_embedding_A.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + if active_adapter not in self.lora_variant: # vanilla LoRA + orig_weight += self.get_delta_weight(active_adapter).to(orig_dtype) + else: + orig_weight = self.lora_variant[active_adapter].merge_safe(self, active_adapter, orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + else: + if active_adapter not in self.lora_variant: # vanilla LoRA + base_layer.weight.data += self.get_delta_weight(active_adapter).to(orig_dtype) + else: + self.lora_variant[active_adapter].merge_unsafe(self, active_adapter, base_layer.weight) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + orig_dtype = self.get_base_layer().weight.dtype + if active_adapter in self.lora_embedding_A.keys(): + weight = self.get_base_layer().weight + if active_adapter not in self.lora_variant: # vanilla LoRA + weight.data -= self.get_delta_weight(active_adapter).to(orig_dtype) + else: + unmerged = self.lora_variant[active_adapter].unmerge(self, active_adapter, weight) + weight.data = unmerged + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.lora_embedding_B[adapter].device + dtype = self.lora_embedding_A[adapter].dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_A = self.lora_embedding_A[adapter] + weight_B = self.lora_embedding_B[adapter] + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, True) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_embedding_A[adapter] = weight_A.to(dtype) + self.lora_embedding_B[adapter] = weight_B.to(dtype) + + return output_tensor + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + result = self.base_layer(x, *args, **kwargs) + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to LoRA contributions too. + embed_scale = self._get_embed_scale() + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self.lora_embedding_A.keys(): + continue + + embedding_A = self.lora_embedding_A[active_adapter].T + embedding_B = self.lora_embedding_B[active_adapter].T + scaling = self.scaling[active_adapter] + + # getting the sub-batch, passing it to LoRA layers and updating the corresponding indices of the linear + # layer output + sub_batch = x[sub_batch_indices_list[i]] + after_A = self._embed(sub_batch, embedding_A) + adapter_output = (after_A @ embedding_B) * scaling + + # Apply embed_scale to match the base layer's scaling + if embed_scale is not None: + adapter_output = adapter_output * embed_scale.to(adapter_output.dtype) + + result[sub_batch_indices_list[i]] += adapter_output + + return result + + def _embed(self, input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + base_layer = self.get_base_layer() + return F.embedding( + input, + weight, + padding_idx=base_layer.padding_idx, + max_norm=base_layer.max_norm, + norm_type=base_layer.norm_type, + scale_grad_by_freq=base_layer.scale_grad_by_freq, + sparse=base_layer.sparse, + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # TODO: no dtype conversion here, unlike in Linear, is that correct? + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to LoRA contributions too. + embed_scale = self._get_embed_scale() + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_embedding_A: + continue + + if active_adapter not in self.lora_variant: # vanilla LoRA + embedding_A = self.lora_embedding_A[active_adapter].T + embedding_B = self.lora_embedding_B[active_adapter].T + scaling = self.scaling[active_adapter] + after_A = self._embed(x, embedding_A) + adapter_output = (after_A @ embedding_B) * scaling + + # Apply embed_scale to match the base layer's scaling + if embed_scale is not None: + adapter_output = adapter_output * embed_scale.to(adapter_output.dtype) + + result = result + adapter_output + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + result = result.to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class _ConvNd(nn.Module, LoraLayer): + # Lora implemented in a conv(2,3)d layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + super().__init__() + LoraLayer.__init__(self, base_layer) + if kwargs.get("use_alora", False): + raise ValueError("aLoRA does not support adapting conv layers.") + if base_layer.groups > 1: + warnings.warn("LoRA adapter added to ConvNd layer with groups > 1. Merging is not supported.") + + if r % base_layer.groups != 0: + raise ValueError( + f"Targeting a {base_layer.__class__.__name__} with groups={base_layer.groups} and rank {r}. " + "Currently, support is limited to conv layers where the rank is divisible by groups. " + "Either choose a different rank or do not target this specific layer." + ) + + self._active_adapter = adapter_name + self._kernel_dim = base_layer.weight.dim() + + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + if lora_bias and (getattr(self.get_base_layer(), "bias", None) is None): + warnings.warn( + f"`lora_bias=True` was passed but the targeted layer of type {type(self.get_base_layer()).__name__} " + "has no bias. This means that merging LoRA weights won't be possible.", + PeftWarning, + ) + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + self.lora_variant[adapter_name] = lora_variant + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + # Actual trainable parameters + base_layer = self.get_base_layer() + kernel_size = base_layer.kernel_size + stride = base_layer.stride + padding = base_layer.padding + conv_layer = type(base_layer) + out_kernel = out_stride = (1,) * (self._kernel_dim - 2) + self.lora_A[adapter_name] = conv_layer(self.in_features, r, kernel_size, stride, padding, bias=False) + self.lora_B[adapter_name] = conv_layer( + r, self.out_features, out_kernel, out_stride, groups=base_layer.groups, bias=lora_bias + ) + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + if init_lora_weights == "loftq": + self.loftq_init(adapter_name) + elif init_lora_weights == "lora_ga": + # Conv layers don't support LoRA-GA, fall back to standard initialization + self.reset_lora_parameters(adapter_name, True) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def _get_dora_factor_view(self): + return (-1,) + (1,) * (self._kernel_dim - 1) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights inside the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.lora_A.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + + if base_layer.groups > 1: + # https://github.com/huggingface/peft/pull/2403 + raise NotImplementedError("Merging is not supported for _ConvNd layers with groups > 1!") + + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + else: + orig_weight = self.lora_variant[active_adapter].merge_safe(self, active_adapter, orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + new_bias = base_layer.bias + self.lora_B[active_adapter].bias * self.scaling[active_adapter] + if not torch.isfinite(new_bias).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + base_layer.bias.data = new_bias.to(orig_dtype) + + else: + if active_adapter not in self.lora_variant: # vanilla LoRA + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight.to(orig_dtype) + else: + self.lora_variant[active_adapter].merge_unsafe(self, active_adapter, base_layer.weight) + + if self.lora_bias[active_adapter]: + if getattr(base_layer, "bias", None) is None: + raise RuntimeError( + "Impossible to merge LoRA with `lora_bias=True` because the base layer has no bias." + ) + base_layer.bias.data += self.lora_B[active_adapter].bias * self.scaling[active_adapter] + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + weight = self.get_base_layer().weight + if active_adapter not in self.lora_variant: # vanilla LoRA + orig_dtype = weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight.to(orig_dtype) + else: + unmerged = self.lora_variant[active_adapter].unmerge(self, active_adapter, weight) + weight.data = unmerged + + if self.lora_bias[active_adapter]: + self.get_base_layer().bias.data -= self.lora_B[active_adapter].bias * self.scaling[active_adapter] + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.lora_B[adapter].weight.device + dtype = self.lora_A[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + # https://github.com/bmaltais/kohya_ss/blob/feb6728762a8f463d15ba936d189d4c3abfaa1ab/networks/lora.py#L117 + if self.get_base_layer().weight.size()[2:4] == (1, 1): + # conv2d 1x1 + output_tensor = (weight_B.squeeze(3).squeeze(2) @ weight_A.squeeze(3).squeeze(2)).unsqueeze(2).unsqueeze( + 3 + ) * self.scaling[adapter] + else: + output_tensor = self.conv_fn(weight_A.transpose(0, 1), weight_B) + + if self.get_base_layer().groups > 1: + output_tensor = output_tensor * self.scaling[adapter] + else: + output_tensor = output_tensor.transpose(0, 1) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + variant_kwargs = {k: kwargs.pop(k, None) for k in VARIANT_KWARG_KEYS} # don't pass these to base_layer + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + x = self._cast_input_dtype(x, lora_A.weight.dtype) + + if active_adapter not in self.lora_variant: # vanilla LoRA + result = result + lora_B(lora_A(dropout(x))) * scaling + else: + result = self.lora_variant[active_adapter].forward( + self, + active_adapter=active_adapter, + x=x, + result=result, + **variant_kwargs, + **kwargs, + ) + + result = result.to(torch_result_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class Conv2d(_ConvNd): + # Lora implemented in a conv2d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 4: + raise ValueError(f"Conv2d layer kernel must have 4 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv2d + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if not config.use_dora: + return None + + from .variants import DoraConv2dVariant + + return DoraConv2dVariant() + + +class Conv1d(_ConvNd): + # Lora implemented in a conv1d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 3: + raise ValueError(f"Conv1d layer kernel must have 3 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv1d + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if not config.use_dora: + return None + + from .variants import DoraConv1dVariant + + return DoraConv1dVariant() + + +class Conv3d(_ConvNd): + # Lora implemented in a conv3d layer + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + if not self._kernel_dim == 5: + raise ValueError(f"Conv3d layer kernel must have 5 dimensions, not {self._kernel_dim}") + self.conv_fn = F.conv3d + + def resolve_lora_variant(self, *, config: LoraConfig, **kwargs) -> Optional[LoraVariant]: + if not config.use_dora: + return None + + from .variants import DoraConv3dVariant + + return DoraConv3dVariant() + + +class MultiheadAttention(nn.Module, LoraLayer): + """LoRA implemented in a multihead attention layer + + This is currently only implemented for the case of `_qkv_same_embed_dim = True`, i.e. query, key, and value having + the same dimension. + + Note: LoRA is applied to both the in_proj (query/key/value) and out_proj. There is currently no way to specify only + one of them. Don't try to apply LoRA to the out_proj of MultiheadAttention by targeting that layer specifically, + since the forward method of that layer is not being used, hence the LoRA adapter would be ignored. + + This is a little bit hacky because of the way that MultiheadAttention is implemented in PyTorch: There are no + `nn.Linear` layers which we can hook onto or, in case of output projection, `.forward` is not used. This + implementation works around these problems by merging the weights before the forward call and unmerging them after + the forward call. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ) -> None: + # TODO work with separate weights + if not getattr(base_layer, "_qkv_same_embed_dim", True): + # default for this value appears to be True: + # https://github.com/pytorch/pytorch/blob/701ba5203fe68d55d655bd4d6c008be94cf34ea5/torch/nn/modules/activation.py#L1128-L1130 + raise ValueError( + f"Only same embed for query/key/value is supported as of now for {self.__class__.__name__}." + ) + if config.use_dora: + # TODO: probably not so hard to implement + raise ValueError(f"{self.__class__.__name__} does not support DoRA (yet), please set use_dora to False") + if kwargs.get("use_alora", False): + raise ValueError(f"{self.__class__.__name__} does not support aLoRA (yet), please set use_alora to False") + super().__init__() + LoraLayer.__init__(self, base_layer, **kwargs) + + # Note: LoRA is applied to both in_proj and out_proj. There is currently no way to only specify one of them. + if isinstance(base_layer.out_proj, nn.Linear): + self.base_layer.out_proj = Linear( + base_layer.out_proj, + adapter_name, + r=r, + lora_alpha=lora_alpha, + config=config, + **kwargs, + ) + else: + raise ValueError(f"out_proj must be an instance of nn.Linear for {self.__class__.__name__}.") + + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, lora_alpha=lora_alpha, config=config) + + @property + def embed_dim(self) -> int: + return self.get_base_layer().embed_dim + + @property + def kdim(self) -> Optional[int]: + return self.get_base_layer().kdim + + @property + def vdim(self) -> Optional[int]: + return self.get_base_layer().vdim + + @property + def _qkv_same_embed_dim(self) -> bool: + return self.get_base_layer()._qkv_same_embed_dim + + @property + def num_heads(self) -> int: + return self.get_base_layer().num_heads + + @property + def dropout(self) -> float: + return self.get_base_layer().dropout + + @property + def batch_first(self) -> bool: + return self.get_base_layer().batch_first + + @property + def head_dim(self) -> int: + return self.get_base_layer().head_dim + + @property + def in_proj_weight(self) -> nn.Parameter: + return self.get_base_layer().in_proj_weight + + @property + def in_proj_bias(self) -> nn.Parameter: + return self.get_base_layer().in_proj_bias + + @property + def out_proj(self) -> nn.Module: + return self.get_base_layer().out_proj.get_base_layer() + + @property + def bias_k(self) -> Optional[nn.Parameter]: + return self.get_base_layer().bias_k + + @property + def bias_v(self) -> Optional[nn.Parameter]: + return self.get_base_layer().bias_v + + def merge_masks(self, *args, **kwargs) -> tuple[Optional[torch.Tensor], Optional[int]]: + return self.get_base_layer().merge_masks(*args, **kwargs) + + @property + def add_zero_attn(self) -> bool: + return self.get_base_layer().add_zero_attn + + def update_layer(self, *args, **kwargs) -> None: + super().update_layer(*args, **kwargs) + # Note: LoRA is applied to both in_proj and out_proj. There is currently no way to only specify one of them. + self.base_layer.out_proj.update_layer(*args, **kwargs) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + # Implementation follows this: + # https://github.com/Baijiong-Lin/LoRA-Torch/blob/4bfed6820b64fcf47064c30f30606a190a4f0d2e/loratorch/layers.py#L73-L79 + # Notably, instead of mutating the weight, we delete the original weight and replace it by the merged weight + # TODO: work with separate weights + for active_adapter in adapter_names: + if active_adapter in self.lora_A.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.out_proj.weight.dtype + if safe_merge: + # TODO: work with separate weights + # merging in_proj (nn.Parameter) + orig_weight_in = base_layer.in_proj_weight.data.detach().clone() + orig_weight_in += self.get_delta_weight(active_adapter).to(orig_dtype) + if not torch.isfinite(orig_weight_in).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + # merging out_proj (subclass of nn.Linear) + orig_weight_out = base_layer.out_proj.weight.data.detach().clone() + orig_weight_out += base_layer.out_proj.get_delta_weight(active_adapter).to(orig_dtype) + if not torch.isfinite(orig_weight_out).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + # unregister parameter implicitly and overwrite using merged weights; gradients are computed after + # forward and, thus, after unmerging (see forward()), therefore this is safe to do. + del base_layer.in_proj_weight + base_layer.in_proj_weight = orig_weight_in + + del base_layer.out_proj.get_base_layer().weight + base_layer.out_proj.get_base_layer().weight = orig_weight_out + base_layer.out_proj.merge(adapter_names=[active_adapter]) + else: + # merging in_proj (nn.Parameter) + # TODO: work with separate weights + delta_weight = self.get_delta_weight(active_adapter).to(orig_dtype) + weight_merged = base_layer.in_proj_weight.data.detach() + delta_weight + + # unregister parameter implicitly and overwrite using merged weights; gradients are computed after + # forward and, thus, after unmerging (see forward()), therefore this is safe to do. + del base_layer.in_proj_weight + base_layer.in_proj_weight = weight_merged + + # merging out_proj (subclass of nn.Linear) + delta_weight = base_layer.out_proj.get_delta_weight(active_adapter).to(orig_dtype) + weight_merged = base_layer.out_proj.weight.data.detach() + delta_weight + del base_layer.out_proj.get_base_layer().weight + base_layer.out_proj.get_base_layer().weight = weight_merged + base_layer.out_proj.merge(adapter_names=[active_adapter]) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + # TODO work with separate weights + base_layer = self.get_base_layer() + orig_dtype = base_layer.out_proj.base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + # Ensure that requires_grad=False for the base weights after unmerging. This may not matter since + # requires_grad was False when the optimizer was initialized, but still let's try to be correct here. + + # in_proj + delta_weight = self.get_delta_weight(active_adapter).to(orig_dtype) + old_weight = base_layer.in_proj_weight.data - delta_weight + del base_layer.in_proj_weight + base_layer.register_parameter("in_proj_weight", nn.Parameter(old_weight, requires_grad=False)) + + # out_proj + delta_weight = base_layer.out_proj.get_delta_weight(active_adapter).to(orig_dtype) + old_weight = base_layer.out_proj.base_layer.weight.data - delta_weight + del base_layer.out_proj.base_layer.weight + base_layer.out_proj.base_layer.register_parameter( + "weight", nn.Parameter(old_weight, requires_grad=False) + ) + + self.get_base_layer().out_proj.unmerge() + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> nn.MultiheadAttention: + """ + Merging and unloading of the MultiheadAttention module + + This requires an extra step for MultiheadAttention, which is why there is this special method instead of + relying on the normal merge_and_unload code path. + """ + if merge: + self.merge(safe_merge=safe_merge, adapter_names=adapter_names) + base_layer = self.get_base_layer() + + # extra steps: re-register weights, take care of out_proj layer + # in_proj + weight = base_layer.in_proj_weight + del base_layer.in_proj_weight + base_layer.register_parameter("in_proj_weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + # out_proj + out_proj_layer = base_layer.out_proj.get_base_layer() + weight = out_proj_layer.weight + del out_proj_layer.weight + out_proj_layer.register_parameter("weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + base_layer.out_proj = out_proj_layer + return base_layer + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.lora_B[adapter].weight.device + dtype = self.lora_B[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # float16 because the `@` and matmul operation in general is not supported in torch + cpu + fp16. + cast_to_fp32 = device.type == "cpu" and dtype == torch.float16 + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = (weight_B @ weight_A) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + def _check_forward_args(self, x, *args, **kwargs): + if "adapter_names" in kwargs: + raise TypeError(f"lora.{self.__class__.__name__} does not support mixed adapter batches.") + super()._check_forward_args(x, *args, **kwargs) + + def forward(self, query: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = query.dtype + self._check_forward_args(query, *args, **kwargs) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(query, *args, **kwargs) + elif self.merged: + result = self.base_layer(query, *args, **kwargs) + else: + out_proj = self.get_base_layer().out_proj + if out_proj.active_adapters != self.active_adapters: + # We have a case that in_proj and out_proj have diverging merged adapters. We cannot + # really deal with this correctly, thus it's better to raise than possibly create a hard to debug mess + cls_name = self.get_base_layer().__class__.__name__ + raise ValueError( + f"The out_proj layer of {cls_name} has merged layers but {cls_name} itself doesn't; please ensure " + "that either both or none have merged layers" + ) + + # Merge all adapters that are active for this module, i.e. the LoRA weights for in_proj and out_proj. + # in_proj uses nn.Parameters, therefore, there is no forward method to be used and we have to explicitly + # merge for the LoRA weights to have an effect: + # https://github.com/pytorch/pytorch/blob/6ebb26d572d5fcdc6ac0d1297bdf8d1eb5d20722/torch/nn/modules/activation.py#L1020 + # For out_proj, we have an nn.Linear (or rather: NonDynamicallyQuantizableLinear), but its forward method + # is not used: + # https://github.com/pytorch/pytorch/blob/6ebb26d572d5fcdc6ac0d1297bdf8d1eb5d20722/torch/nn/modules/activation.py#L1267-L1271 + # Therefore, its LoRA weights also need to be merged to have an effect. + active_adapters = [a for a in self.active_adapters if a in self.lora_A] + try: + self.merge(adapter_names=active_adapters) + result = self.base_layer(query, *args, **kwargs) + finally: + # it's safe to call unmerge(), which unmerges all adapters, because we checked that not self.merged, + # i.e. there is was no merged layer before + self.unmerge() + + result = (result[0].to(previous_dtype), result[1].to(previous_dtype) if result[1] is not None else result[1]) + return result + + # The decorator is needed in case low_cpu_mem_usage=True is used, as we don't want the base layer weights to be + # moved to meta device. This requires the use of PEFT's implementation of init_empty_weight instead of using the one + # from accelerate. + @skip_init_on_device + def _restore_weights(self): + # Restore the weights as registered parameters on the base layer. + # This is necessary because the way that weights are merged/unmerged (which is necessary for forward to work + # correctly), the Module "forgets" these attributes. Therefore, we need to call register_parameter explicitly. + # We cannot call register_parameter for merging/unmerging because that cuts them off from the autograd graph. + # Note that this is hacky, since we need to ensure that _restore_weights is called by each method that needs it. + + # in_proj + # TODO work with separate weights + base_layer = self.get_base_layer() + weight = base_layer.in_proj_weight + del base_layer.in_proj_weight + base_layer.register_parameter("in_proj_weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + # out_proj + base_layer = base_layer.out_proj.get_base_layer() + weight = base_layer.weight + del base_layer.weight + base_layer.register_parameter("weight", nn.Parameter(weight.data, requires_grad=weight.requires_grad)) + + def state_dict(self, *args, **kwargs): + self._restore_weights() + return super().state_dict(*args, **kwargs) + + def named_modules(self, *args, **kwargs): + # Note: no need to also implement modules(), as modules() calls named_modules() under the hood + self._restore_weights() + return super().named_modules(*args, **kwargs) + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +class _LoraParameterProxy(nn.Module): + """This proxies an `nn.Parameter` that is targeted with LoRA. + Intended to be used in conjunction with `nn.utils.parametrize`, see `ParamWrapper`. + """ + + def __init__(self, delta_weight): + super().__init__() + self.delta_weight = delta_weight + + def forward(self, W): + return W + self.delta_weight + + +# copied from: +# https://github.com/pytorch/pytorch/blob/5e386eec9426f174eea130c0c012d9f65ebe65fb/torch/nn/utils/parametrize.py#L75-L79 +def _register_parameter_or_buffer(module, name, X): + if isinstance(X, nn.Parameter): + module.register_parameter(name, X) + else: + module.register_buffer(name, X) + + +class ParamWrapper(nn.Module, LoraLayer): + """A LoRA wrapper for `nn.Parameter`. This layer is dispatched if users target a parameter directly with + `lora_config.target_parameters` + Note: + - When accessing the wrapped nn.Parameter directly, e.g. via `module.weight`, the LoRA weights are *not* + applied. + - It is currently not implemented to target multiple parameters on the same module. To achieve this, it is + currently required to create a separate LoRA adapter (with another adapter name) and activate both at the + same time. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + parameter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + self.parameter_name = parameter_name + super().__init__() + LoraLayer.__init__(self, base_layer, **kwargs) + + if config.lora_dropout: + # It's not possible to factor out x from lora_B(lora_A(dropout(x))), so dropout can't be correctly + # implemented + raise ValueError(f"lora.{self.__class__.__name__} does not work with lora_dropout != 0.") + if config.fan_in_fan_out: + raise ValueError(f"lora.{self.__class__.__name__} does not work with fan_in_fan_out.") + if config.lora_bias: + raise ValueError(f"lora.{self.__class__.__name__} does not work with lora_bias=True.") + if config.use_dora: + raise ValueError(f"lora.{self.__class__.__name__} does not work with use_dora=True.") + if is_target_conv_1d_layer: + raise ValueError(f"lora.{self.__class__.__name__} does not work with is_target_conv_1d_layer=True.") + + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def _get_in_out_features(self, module: nn.Module) -> tuple[int, int] | tuple[None, None]: + # For ParamWrapper, we don't derive the in_features and out_features based on the base layer type, but directly + # from the targeted parameter. + param = self.get_param() + if param.ndim == 3: + num_experts, in_features, out_features = param.shape + else: + num_experts, in_features, out_features = 1, param.shape[1], param.shape[0] + if param.ndim not in (2, 3): + raise ValueError( + f"lora.{self.__class__.__name__} was initialized with {param.ndim} dimensional Parameter, but only 2d " + "and 3d are supported." + ) + # we have to store the num_experts attribute here, as the parent class only stores in_features and out_features. + self.num_experts = num_experts + return in_features, out_features + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + **kwargs, + ) -> None: + # same method as in lora.Linear but taking into account that there can be multiple experts (3d parameter) + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + lora_bias = config.lora_bias + inference_mode = config.inference_mode + # This code works for linear layers, override for other layer types + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + lora_variant = self.resolve_lora_variant(config=config) + if lora_variant is not None: + raise ValueError(f"lora.{self.__class__.__name__} does not work with LoRA variants like DoRA.") + + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + # It's not possible to factor out x from lora_B(lora_A(dropout(x))), so dropout can't be correctly + # implemented + raise ValueError(f"lora.{self.__class__.__name__} does not work with lora_dropout != 0.") + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout.update(nn.ModuleDict({adapter_name: lora_dropout_layer})) + # Actual trainable parameters + # Difference to normal update_layer: consider experts. LoRA layers still use nn.Linear for consistency with + # lora.Linear. + self.lora_A[adapter_name] = nn.Linear(self.in_features, r * self.num_experts, bias=False) + self.lora_B[adapter_name] = nn.Linear(r * self.num_experts, self.out_features, bias=lora_bias) + self.lora_bias[adapter_name] = lora_bias + + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_rslora[adapter_name] = use_rslora + + self.use_dora[adapter_name] = config.use_dora + + # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed + if isinstance(init_lora_weights, str) and init_lora_weights.startswith("pissa"): + with gather_params_ctx(self.get_base_layer().weight): + self.pissa_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.startswith("corda"): + with gather_params_ctx(self.get_base_layer().weight): + self.corda_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.lower() == "olora": + with gather_params_ctx(self.get_base_layer().weight): + self.olora_init(adapter_name) + elif init_lora_weights == "loftq": + with gather_params_ctx(self.get_base_layer().weight): + self.loftq_init(adapter_name) + elif init_lora_weights == "eva": + nn.init.zeros_(self.lora_B[adapter_name].weight) + elif init_lora_weights == "orthogonal": + with gather_params_ctx(self.get_base_layer().weight): + self.orthogonal_init(adapter_name) + elif init_lora_weights == "lora_ga": + with gather_params_ctx(self.get_base_layer().weight): + self.lora_ga_init(adapter_name, config.lora_ga_config) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + # call this before init of the lora variants + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, config=config, **kwargs) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def _move_adapter_to_device_of_base_layer(self, adapter_name: str, device: Optional[torch.device] = None) -> None: + """ + Move the adapter of the given name to the device of the base layer. Needs special handling for nn.Parameter + """ + device = self.get_param().device + meta = torch.device("meta") + param = self.get_param() + + for adapter_layer_name in self.adapter_layer_names + self.other_param_names: + adapter_layer = getattr(self, adapter_layer_name, None) + if not isinstance(adapter_layer, (nn.ModuleDict, nn.ParameterDict, BufferDict)): + continue + if adapter_name not in adapter_layer: + continue + if any(p.device == meta for p in adapter_layer.parameters()): + continue + + if param.dtype.is_floating_point or param.dtype.is_complex: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(device, dtype=param.dtype) + else: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(device) + + def get_param(self): + param = getattr(self.get_base_layer(), self.parameter_name) + return param + + def get_delta_weight(self, adapter_name, *args, **kwargs): + if self.num_experts == 1: + delta_weight = Linear.get_delta_weight(self, adapter_name, *args, **kwargs) + else: + weight_A = self.lora_A[adapter_name].weight + weight_B = self.lora_B[adapter_name].weight + # shape: experts x rank x in_features + weight_A = weight_A.reshape(self.num_experts, -1, weight_A.shape[-1]) + # shape: out_features x rank x experts + weight_B = weight_B.reshape(weight_B.shape[0], -1, self.num_experts) + # fan_in_fan_out must be False, so no transpose call here + delta_weight = torch.einsum("o r e, e r i -> e i o", weight_B, weight_A) * self.scaling[adapter_name] + + base_layer = self.get_base_layer() + param = self.get_param() + delta_weight = delta_weight.to(param.device, param.dtype) + return delta_weight + + @contextmanager + def _activate_lora(self, active_adapters: list[str]): + if not active_adapters or not any(adapter in self.lora_A for adapter in active_adapters): + # no active adapters for this layer + yield + return + + delta_weight = None + for active_adapter in active_adapters: + if active_adapter not in self.lora_A: + continue + if delta_weight is None: + delta_weight = self.get_delta_weight(active_adapter) + else: + delta_weight = delta_weight + self.get_delta_weight(active_adapter) + + base_layer = self.get_base_layer() + requires_grad_before = self.get_param().requires_grad + nn.utils.parametrize.register_parametrization( + base_layer, self.parameter_name, _LoraParameterProxy(delta_weight) + ) + # set requires_grad, as it defaults to False + base_layer.parametrizations[self.parameter_name].original.requires_grad_(requires_grad_before) + try: + with nn.utils.parametrize.cached(): + yield + finally: + self._remove_parametrizations() + + def _remove_parametrizations(self): + # Remove the parametrization of this specific parameter + base_layer = self.get_base_layer() + parameter_name = self.parameter_name + if parameter_name not in base_layer.parametrizations: + raise ValueError( + "Something went wrong, please report this issue on PEFT: https://github.com/huggingface/peft/issues" + ) + + param_list = base_layer.parametrizations[parameter_name] + if len(param_list) == 1: + # last parametrization, we can safely remove it completely + nn.utils.parametrize.remove_parametrizations(base_layer, parameter_name, leave_parametrized=False) + return + + # If there are multiple parametrizations for the same parameter_name, we only want to remove the LoRA proxy. + # Unfortunately, PyTorch does not support this directly, so we need to take care of it manually. To achieve + # this, we check the ParameterList from the back until we find the _LoraParameterProxy instance and then remove + # it. + reversed_indices = reversed(range(len(param_list))) + for i in reversed_indices: + module = param_list[i] + if isinstance(module, _LoraParameterProxy): + del param_list[i] + break + else: # no break encountered + # this should not happen, but raising an error is probably not necessary + warnings.warn( + f"Could not find any LoRA parametrization on {self}, please open an issue on " + "https://github.com/huggingface/peft/issues and report this warning." + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + # same as lora.Linear.merge but not hard-coding base_layer.weight and without special cases like variants removed + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.lora_A.keys(): + base_layer = self.get_base_layer() + param = getattr(base_layer, self.parameter_name) + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = param.data.clone() + orig_dtype = orig_weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + param.data = orig_weight + + else: + delta_weight = self.get_delta_weight(active_adapter) + param.data += delta_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + # same as lora.Linear.unmerge but not hard-coding base_layer.weight and without special cases like variants removed + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + param = getattr(self.get_base_layer(), self.parameter_name) + orig_dtype = param.dtype + delta_weight = self.get_delta_weight(active_adapter) + param.data -= delta_weight.to(orig_dtype) + + def _check_forward_args(self, x, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + if kwargs.get("adapter_names", None): + raise ValueError(f"lora.{self.__class__.__name__} does not support mixed adapter batches yet.") + super()._check_forward_args(x, *args, **kwargs) + + def unload_and_optionally_merge_module(self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]]): + base_layer = self.base_layer + # ParamWrappers can be nested, so merge and retrieve base layer recursively + if merge: + self.merge(safe_merge=safe_merge, adapter_names=adapter_names) + while isinstance(base_layer, ParamWrapper): + base_layer.merge(safe_merge=safe_merge, adapter_names=adapter_names) + base_layer = base_layer.base_layer + else: + base_layer = self.get_base_layer() + return base_layer + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + raise ValueError(f"lora.{self.__class__.__name__} does not support mixed batch inference") + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + with self._activate_lora(self.active_adapters): + result = self.base_layer(x, *args, **kwargs) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + idx = rep.find("(") + 1 + # insert the name of the parameter to allow the repr to be disambiguous when multiple parameters on the same + # module are being targeted + rep = f"{rep[:idx]}\n parameter_name='{self.parameter_name}',{rep[idx:]}" + return "lora." + rep + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + parameter_name: Optional[str] = None, + **kwargs, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if parameter_name is not None: + new_module = ParamWrapper(target, adapter_name, parameter_name=parameter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Embedding): + new_module = Embedding(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Conv2d): + new_module = Conv2d(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Conv3d): + new_module = Conv3d(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, nn.Conv1d): + new_module = Conv1d(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.MultiheadAttention): + new_module = MultiheadAttention(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if config.fan_in_fan_out: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, config=config, **kwargs) + elif isinstance(target_base_layer, Conv1D): + if not config.fan_in_fan_out: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + config.fan_in_fan_out = True + new_module = Linear(target, adapter_name, is_target_conv_1d_layer=True, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/loraga.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/loraga.py new file mode 100644 index 0000000000000000000000000000000000000000..0e73c5fe7ae50cac89e10d5702410e4dd1275b71 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/loraga.py @@ -0,0 +1,191 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Reference code: https://github.com/Outsider565/LoRA-GA +# Reference paper: https://arxiv.org/abs/2407.05000 + +import os +from collections.abc import Callable +from typing import Any, Optional + +import torch +import torch.nn as nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.lora.config import LoraConfig +from peft.tuners.lora.model import LoraModel + + +def get_target_modules(model: nn.Module, config: LoraConfig): + """ + Iterate over LoRA-GA target name and modules of a model. A module is a target if its name is in + `config.target_modules` and is `nn.Linear` or `Conv1D`. + """ + for name, module in model.named_modules(): + if LoraModel._check_target_module_exists(config, name) and isinstance(module, (nn.Linear, Conv1D)): + yield name, module + + +def get_model_device(model: nn.Module) -> str: + if hasattr(model, "module"): # Handle DeepSpeed/DataParallel + model = model.module + return next(iter(model.parameters())).device + + +@torch.no_grad() +def preprocess_loraga( + model: nn.Module, + lora_config: LoraConfig, + train_step: Callable[[], None], + cache_file: Optional[str] = None, +): + """ + Build necessary LoRA-GA fields for a model by estimating gradients. + + For each linear layer, gradients will be estimated by running the provided train_step callback. These gradients are + then attached to the modules and used during initialization. + + Args: + model (`nn.Module`): + Model to preprocess. + lora_config (`LoraConfig`): + Lora configuration of the model. `lora_config.lora_ga_config` should be set. + train_step (`Callable[[], None]`): + Callback to run gradient estimation. Typically you should run model forward and backward passes in this + callback. The gradients will be accumulated across all calls within this callback. + cache_file (`Optional[str]`): + Optional path to cache file for saving/loading gradients. If provided and the file exists, gradients will + be loaded from cache. Otherwise, gradients will be estimated and saved to this path. + + Upon completion, the following fields are set for each target module: + _peft_loraga_grad (`torch.Tensor`): + Accumulated gradient for the weight matrix. + """ + if lora_config.lora_ga_config is None: + raise ValueError( + "If you want to use LoRA-GA, please initialize the LoraConfig with " + "init_lora_weights='lora_ga' and lora_ga_config=LoraGAConfig(...)." + ) + + # Populate target_modules from defaults if empty + # This logic mirrors BaseTuner._prepare_adapter_config which runs after get_peft_model. + # Since preprocess_loraga is called before get_peft_model, we need to handle this ourselves. + if lora_config.target_modules is None: + model_config = LoraModel.get_model_config(model) + target_modules = LoraModel.target_module_mapping.get(model_config["model_type"]) + if target_modules is None: + raise ValueError("Please specify `target_modules` in `peft_config`") + lora_config.target_modules = set(target_modules) + + # Check for quantized models - LoRA-GA requires full-precision gradients + for name, module in get_target_modules(model, lora_config): + if hasattr(module, "quant_state"): + raise ValueError( + f"LoRA-GA does not support quantized models. Found quantized module: '{name}'. " + "LoRA-GA requires full-precision gradients during preprocessing." + ) + + # If cache exists, load from cache + if cache_file is not None and os.path.exists(cache_file) and os.path.getsize(cache_file) > 0: + cache = torch.load(cache_file, map_location=get_model_device(model)) + for name, module in get_target_modules(model, lora_config): + module._peft_loraga_grad = cache[f"{name}._peft_loraga_grad"] + else: + # Estimate gradients by running train_step + estimate_gradients(model, lora_config, train_step) + + # Save cache to disk if specified + if cache_file is not None: + cache: dict[str, Any] = {} + for name, module in get_target_modules(model, lora_config): + cache[f"{name}._peft_loraga_grad"] = module._peft_loraga_grad + + os.makedirs(os.path.dirname(cache_file), exist_ok=True) + torch.save(cache, cache_file) + + +def estimate_gradients( + model: nn.Module, + lora_config: LoraConfig, + train_step: Callable[[], None], +): + """ + Estimate gradients for LoRA-GA initialization. + + This function enables gradient computation ONLY on target module weights and runs the train_step callback. This is + more memory-efficient than enabling gradients globally. + """ + # Remember original training state + was_training = model.training + model.train() + + # Get target modules list once for efficiency + target_module_list = list(get_target_modules(model, lora_config)) + + # Check if any supported layers were found + if not target_module_list: + raise ValueError( + "No supported layers found for LoRA-GA initialization. " + "LoRA-GA only supports nn.Linear and Conv1D layers. " + "Please ensure your model contains at least one of these layer types in target_modules." + ) + + # Initialize gradient storage and count for each target module + for name, module in target_module_list: + module._peft_loraga_grad_count = 0 + + # Memory-efficient gradient computation: disable gradients for all parameters first, + # then enable only for target module weights + original_requires_grad = {} + for name, param in model.named_parameters(): + original_requires_grad[name] = param.requires_grad + param.requires_grad = False + + # Enable gradients ONLY for target module weights + for name, module in target_module_list: + module.weight.requires_grad = True + + # Register backward hooks to count gradient computations + hooks = [] + + def backward_hook(module, grad_input, grad_output): + module._peft_loraga_grad_count += 1 + + for name, module in target_module_list: + hook = module.register_full_backward_hook(backward_hook) + hooks.append(hook) + + # Enable gradient computation and run train_step + with torch.enable_grad(): + train_step() + + # Remove hooks + for hook in hooks: + hook.remove() + + # Restore original requires_grad state for all parameters + for name, param in model.named_parameters(): + if name in original_requires_grad: + param.requires_grad = original_requires_grad[name] + + # Average gradients and clean up temporary fields + for name, module in target_module_list: + if module._peft_loraga_grad_count > 0: + module._peft_loraga_grad = module.weight.grad.detach() / module._peft_loraga_grad_count + module.weight.grad = None + del module._peft_loraga_grad_count + + # Restore original training state + if not was_training: + model.eval() diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..5ad58646fcbc0415ca564043cdb212b5040959df --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/model.py @@ -0,0 +1,954 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import math +import operator +import re +import warnings +from contextlib import contextmanager +from dataclasses import replace +from functools import partial, reduce +from typing import Literal, Optional + +import packaging.version +import torch +import transformers +from torch import nn + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import ( + BaseTuner, + BaseTunerLayer, + find_parameter_name_by_module, + get_device_map, + replicate_layers, +) +from peft.utils import ( + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + AuxiliaryTrainingWrapper, + ModulesToSaveWrapper, + _freeze_adapter, + _get_submodules, + get_peft_model_state_dict, + get_quantization_config, +) +from peft.utils.merge_utils import dare_linear, dare_ties, magnitude_prune, task_arithmetic, ties +from peft.utils.other import get_pattern_key + +from .aqlm import dispatch_aqlm +from .awq import dispatch_awq +from .config import LoraConfig +from .eetq import dispatch_eetq +from .gptq import dispatch_gptq +from .hqq import dispatch_hqq +from .inc import dispatch_inc +from .layer import Conv2d, LoraLayer, ParamWrapper, dispatch_default +from .te import dispatch_transformer_engine +from .torchao import dispatch_torchao +from .tp_layer import dispatch_megatron + + +def _adapter_names_pre_forward_hook(target, args, kwargs, adapter_names): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["adapter_names"] = adapter_names + return args, kwargs + + +def _alora_offsets_pre_forward_hook(target, args, kwargs, alora_offsets): + kwargs["alora_offsets"] = alora_offsets + return args, kwargs + + +def _get_encoder(model: nn.Module) -> nn.Module | None: + """Check if the model has an encoder and if it has, returns it; otherwise returns None""" + if not hasattr(model, "get_encoder"): + return None + + encoder = model.get_encoder() + # https://github.com/huggingface/transformers/pull/42156 + # new logic in transformers v5: all PretrainedModels return a model here, but it is self if there is no encoder + if encoder is model: + return None + return encoder + + +class LoraModel(BaseTuner): + """ + Creates Low Rank Adapter (LoRA) model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2106.09685. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LoraConfig`]): The configuration of the Lora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The Lora model. + + Example: + + ```py + >>> from transformers import AutoModelForSeq2SeqLM + >>> from peft import LoraModel, LoraConfig + + >>> config = LoraConfig( + ... task_type="SEQ_2_SEQ_LM", + ... r=8, + ... lora_alpha=32, + ... target_modules=["q", "v"], + ... lora_dropout=0.01, + ... ) + + >>> model = AutoModelForSeq2SeqLM.from_pretrained("t5-base") + >>> lora_model = LoraModel(model, config, "default") + ``` + + ```py + >>> import torch + >>> import transformers + >>> from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training + + >>> rank = ... + >>> target_modules = ["q_proj", "k_proj", "v_proj", "out_proj", "fc_in", "fc_out", "wte"] + >>> config = LoraConfig( + ... r=4, lora_alpha=16, target_modules=target_modules, lora_dropout=0.1, bias="none", task_type="CAUSAL_LM" + ... ) + >>> quantization_config = transformers.BitsAndBytesConfig(load_in_8bit=True) + + >>> tokenizer = transformers.AutoTokenizer.from_pretrained( + ... "kakaobrain/kogpt", + ... revision="KoGPT6B-ryan1.5b-float16", # or float32 version: revision=KoGPT6B-ryan1.5b + ... bos_token="[BOS]", + ... eos_token="[EOS]", + ... unk_token="[UNK]", + ... pad_token="[PAD]", + ... mask_token="[MASK]", + ... ) + >>> model = transformers.GPTJForCausalLM.from_pretrained( + ... "kakaobrain/kogpt", + ... revision="KoGPT6B-ryan1.5b-float16", # or float32 version: revision=KoGPT6B-ryan1.5b + ... pad_token_id=tokenizer.eos_token_id, + ... use_cache=False, + ... device_map={"": rank}, + ... torch_dtype=torch.float16, + ... quantization_config=quantization_config, + ... ) + >>> model = prepare_model_for_kbit_training(model) + >>> lora_model = get_peft_model(model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`LoraConfig`]): The configuration of the Lora model. + """ + + prefix: str = "lora_" + tuner_layer_cls = LoraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING + + def _prepare_model(self, peft_config: LoraConfig, model: nn.Module): + r""" + A private method to modify the model structure before adapter is applied. + + Args: + peft_config (`PeftConfig`): + The prepared adapter config. + model (`nn.Module`): + The model that is going to be adapted. + """ + if peft_config.layer_replication: + replicate_layers(model, peft_config.layer_replication) + + def _create_and_replace( + self, + lora_config, + adapter_name, + target, + target_name, + parent, + current_key, + *, + parameter_name: Optional[str] = None, + ) -> None: + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + if lora_config.target_parameters: + # Right now, unfortunately, we don't support multiple adapters with target_parameters on the same model. + other_configs_use_target_params = any( + conf.target_parameters for key, conf in self.peft_config.items() if key != adapter_name + ) + if other_configs_use_target_params: + raise ValueError( + f"Adding a LoRA config with `target_parameters={lora_config.target_parameters}` but there are " + "already other LoRA adapters on this model that use `target_parameters`. At the moment, only " + "one LoRA adapter per model with `target_parameters` is allowed." + ) + + # Regexp matching - Find key which matches current target_name in patterns provided + r_key = get_pattern_key(lora_config.rank_pattern.keys(), current_key) + alpha_key = get_pattern_key(lora_config.alpha_pattern.keys(), current_key) + r = lora_config.rank_pattern.get(r_key, lora_config.r) + alpha = lora_config.alpha_pattern.get(alpha_key, lora_config.lora_alpha) + + # Checks if the target is marked as a tied layer + # If true, we add the reference to lora adapters of embedding layer in `tied_adapter` + is_tied = target_name in (getattr(lora_config, "target_modules_to_tie", []) or []) + tied_adapter = {} + if is_tied: + tied_module = self.model.get_input_embeddings() + emb_A = tied_module.lora_embedding_A[adapter_name] + emb_B = tied_module.lora_embedding_B[adapter_name] + + tied_adapter = {"lora_A": emb_B.t(), "lora_B": emb_A.t()} + + kwargs = { + "r": r, + "lora_alpha": alpha, + "target_name": current_key, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + "ephemeral_gpu_offload": lora_config.runtime_config.ephemeral_gpu_offload, + "parameter_name": parameter_name, + "tied_adapter": tied_adapter, + } + + # for torchao merging, we need the get_apply_tensor_subclass from the quantization config + try: + kwargs["get_apply_tensor_subclass"] = operator.attrgetter( + "hf_quantizer.quantization_config.get_apply_tensor_subclass" + )(self.model) + except AttributeError: + pass + + quant_methods = ["gptq", "aqlm", "awq"] + for quant_method in quant_methods: + quantization_config = get_quantization_config(self.model, method=quant_method) + if quantization_config is not None: + kwargs[f"{quant_method}_quantization_config"] = quantization_config + + # note: AdaLoraLayer is a subclass of LoraLayer, we need to exclude it + from peft.tuners.adalora import AdaLoraLayer + + # if the target is a ParamWrapper, we nest it to allow targeting multiple nn.Parameter on the same module + wrap_target_param = isinstance(target, ParamWrapper) and (adapter_name in target.lora_A) + if isinstance(target, LoraLayer) and not isinstance(target, AdaLoraLayer) and not wrap_target_param: + target.update_layer( + adapter_name, + r, + lora_alpha=alpha, + target_name=current_key, + config=lora_config, + ) + else: + if isinstance(target, ParamWrapper) and (parameter_name == target.parameter_name): + raise ValueError( + "Trying to target the same nn.Parameter twice, this should not happen. Please open an issue on the " + "PEFT repo: https://github.com/huggingface/peft/issues" + ) + device_map = get_device_map(self.model) + new_module = self._create_new_module(lora_config, adapter_name, target, device_map=device_map, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + def _replace_module(self, parent, child_name, new_module, child): + # override in LoraModel to handle quantized weights properly + + setattr(parent, child_name, new_module) + # It's not necessary to set requires_grad here, as that is handled by + # _mark_only_adapters_as_trainable + + # child layer wraps the original module, unpack it + if hasattr(child, "base_layer"): + child = child.base_layer + + meta = torch.device("meta") + # dispatch to correct device + for name, module in new_module.named_modules(): + if (self.prefix in name) or ("ranknum" in name): + if hasattr(child, "qweight"): + weight = child.qweight + elif hasattr(child, "W_q"): + weight = child.W_q + elif hasattr(child, "weight"): + weight = child.weight + elif getattr(child, "in_proj_weight", None) is not None: # MHA + weight = child.in_proj_weight + else: + weight = next(child.parameters()) + if not any(p.device == meta for p in module.parameters()): + module.to(weight.device) + + @staticmethod + def _create_new_module(lora_config, adapter_name, target, **kwargs): + # Collect dispatcher functions to decide what backend to use for the replaced LoRA layer. The order matters, + # because the first match is always used. Therefore, the default layers should be checked last. + dispatchers = [] + + if lora_config._custom_modules: + # Experimental custom LoRA module support. Allows users to pass a custom mapping for unsupported layer + # types by impelementing their own LoRA layers. + def dynamic_dispatch_func(target, adapter_name, config, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + for key, custom_cls in config._custom_modules.items(): + if isinstance(target_base_layer, key): + new_module = custom_cls(target, adapter_name, config=config, **kwargs) + break + + return new_module + + dispatchers.append(dynamic_dispatch_func) + + # avoid eager bnb import + if is_bnb_available(): + from .bnb import dispatch_bnb_8bit + + dispatchers.append(dispatch_bnb_8bit) + + if is_bnb_4bit_available(): + from .bnb import dispatch_bnb_4bit + + dispatchers.append(dispatch_bnb_4bit) + + dispatchers.extend( + [ + dispatch_eetq, + dispatch_aqlm, + dispatch_awq, + dispatch_gptq, + dispatch_hqq, + dispatch_inc, + dispatch_torchao, + dispatch_megatron, + dispatch_transformer_engine, + dispatch_default, + ] + ) + + new_module = None + for dispatcher in dispatchers: + new_module = dispatcher(target, adapter_name, config=lora_config, **kwargs) + if new_module is not None: # first match wins + break + + if new_module is None: + # no module could be matched + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `torch.nn.Embedding`, `torch.nn.Conv1d`, `torch.nn.Conv2d`, `torch.nn.Conv3d`, " + "`transformers.pytorch_utils.Conv1D`, `torch.nn.MultiheadAttention.`." + ) + + return new_module + + @contextmanager + def _enable_peft_forward_hooks(self, *args, **kwargs): + # If adapter_names is passed as an argument, we inject it into the forward arguments. + adapter_names = kwargs.pop("adapter_names", None) + alora_offsets = kwargs.pop("alora_offsets", None) + + if adapter_names is None and alora_offsets is None: + # nothing to do + yield + return + hook_handles = [] + + if alora_offsets is not None: + # TODO: remove once transformers 4.52 is no longer supported. Note that 4.52.0 is yanked, so 4.52.1 + # is the first 4.52 release. + transformers_lt_4_52 = packaging.version.parse(transformers.__version__) < packaging.version.parse( + "4.52.1" + ) + if transformers_lt_4_52: + raise ValueError("Using aLoRA requires transformers >= 4.52.1.") + + from transformers.modeling_layers import GradientCheckpointingLayer + + for n, layer in self.named_modules(): + # gradient checkpointing layer are executed concurrently to the 'normal' forward call + # (in the backward step the gradient checkpointing layer's forward will be executed again). + # this means that when the gradient checkpointing layer is called, the _enable_peft_forward_hooks + # context manager is long gone. to be consistent with the normal forward we need to register the pre + # hooks for this concurrent forward call as well. + # + # Note that this will lead to double application of whatever the callbacks do in normal forward. + # Make sure that whatever change is done, can be applied more than once without harm (idempotency). + if isinstance(layer, GradientCheckpointingLayer) and layer.gradient_checkpointing: + + def forward_pre_hook(name, module, inputs, **kwargs): + for submodule in module.modules(): + if isinstance(submodule, LoraLayer): + handle = submodule.register_forward_pre_hook( + partial(_alora_offsets_pre_forward_hook, alora_offsets=kwargs["alora_offsets"]), + with_kwargs=True, + ) + module._peft_gradient_checkpointing_forward_hooks.append(handle) + + def backward_hook(name, module, *grad_output, **kwargs): + while module._peft_gradient_checkpointing_forward_hooks: + module._peft_gradient_checkpointing_forward_hooks.pop().remove() + + if getattr(layer, "_peft_gradient_checkpointing_forward_hooks", []): + raise ValueError( + "Multiple invocations of PEFT forward hooks before .backward() with enabled gradient " + "checkpointing. Disable gradient checkpointing or only call forward once per backward." + ) + layer._peft_gradient_checkpointing_forward_hooks = [] + handle = layer.register_forward_pre_hook(partial(forward_pre_hook, n, alora_offsets=alora_offsets)) + layer._peft_gradient_checkpointing_forward_hooks.append(handle) + handle = layer.register_full_backward_hook(partial(backward_hook, n)) + layer._peft_gradient_checkpointing_forward_hooks.append(handle) + if isinstance(layer, LoraLayer): + pre_forward = partial(_alora_offsets_pre_forward_hook, alora_offsets=alora_offsets) + handle = layer.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + num_beams = kwargs.get("num_beams", None) + uses_beam_search = isinstance(num_beams, int) and (num_beams > 1) + if uses_beam_search: + if alora_offsets is not None: + raise ValueError("Beam search not yet supported for aLoRA.") + if adapter_names is not None: + if self.training: + raise ValueError("Cannot pass `adapter_names` when the model is in training mode.") + + # Check that users only passed actually existing adapters. + # Note: We cannot do this on the layer level, as each individual layer may not have each adapter. Still, we want + # to check that there is at least one layer with the given name, or else something like typos can easily slip. + expected_adapters = set() + for layer in self.modules(): + if isinstance(layer, LoraLayer): + expected_adapters |= layer.lora_A.keys() + expected_adapters |= layer.lora_embedding_A.keys() + unique_adapters = {name for name in adapter_names if name != "__base__"} + unexpected_adapters = unique_adapters - expected_adapters + if unexpected_adapters: + raise ValueError( + f"Trying to infer with non-existing adapter(s): {', '.join(sorted(unexpected_adapters))}" + ) + + # deal with beam search + original_adapter_names = adapter_names[:] + if uses_beam_search: + if not isinstance(adapter_names, (list, tuple)): + raise TypeError(f"Got adapter names of type {type(adapter_names)}, expected a list of str.") + # When there is beam search, the inputs are repeated n times, thus we repeat each adapter name n times and + # then flatten the nested list. For encoder-decoder models, this extended list should not be applied to the + # encoder part. Further below, the original argument is thus restored for the encoder. + adapter_names = sum(([n] * kwargs["num_beams"] for n in adapter_names), []) + + for module in self.modules(): + if isinstance(module, LoraLayer) or isinstance(module, AuxiliaryTrainingWrapper): + pre_forward = partial(_adapter_names_pre_forward_hook, adapter_names=adapter_names) + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + encoder = _get_encoder(self.model) + if uses_beam_search and (encoder is not None): + # For encoder-decoder models, even when applying beam search, the encoder part of the model should not use + # the extended adapter_names. This is because the encoder still uses the original, non-extended samples. + for module in encoder.modules(): + if isinstance(module, LoraLayer) or isinstance(module, AuxiliaryTrainingWrapper): + # Add another hook to overwrite the kwargs with the original adapter names -- this is easier than + # trying to exclude the encoder. + pre_forward = partial(_adapter_names_pre_forward_hook, adapter_names=original_adapter_names) + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + yield + + for handle in hook_handles: + handle.remove() + + def _check_merge_allowed(self): + """Verify that the configuration supports merging. + + Currently gptq quantization and replicated layers do not support merging. + """ + super()._check_merge_allowed() + if getattr(self.model, "quantization_method", None) == "gptq": + raise ValueError("Cannot merge LORA layers when the model is gptq quantized") + if self.peft_config.get("layer_replication"): + raise ValueError("Cannot merge LORA layers when base model layers are replicated") + + def _prepare_adapter_config(self, peft_config, model_config): + if peft_config.target_modules is None: + if model_config["model_type"] in self.target_module_mapping: + peft_config.target_modules = set(self.target_module_mapping[model_config["model_type"]]) + elif not peft_config.target_parameters: + raise ValueError("Please specify `target_modules` or `target_parameters`in `peft_config`") + return peft_config + + def _check_add_weighted_adapter( + self, adapters: list[str], combination_type: str, svd_rank: int | None + ) -> tuple[str, int, str]: + """ + Helper function to check if the arguments to add_weighted_adapter are valid and compatible with the underlying + model. + """ + for adapter in adapters: + if adapter not in list(self.peft_config.keys()): + raise ValueError(f"Adapter {adapter} does not exist") + + for adapter in adapters: + if self.peft_config[adapter].target_parameters: + raise ValueError( + f"add_weighted_adapter does not support targeting nn.Parameter (problematic adapter '{adapter}')" + ) + + # If more than one of the adapters targets the same module with modules_to_save, raise an error, as these + # modules cannot be merged. First, find the ModulesToSaveWrapper instances in the model, then check if they + # have modules for the adapters to be merged. + modules_to_save_wrappers = [module for module in self.modules() if isinstance(module, ModulesToSaveWrapper)] + problematic_wrappers = [ + wrapper + for wrapper in modules_to_save_wrappers + if sum(adapter in wrapper.modules_to_save for adapter in adapters) > 1 + ] + if problematic_wrappers: + raise ValueError( + "Cannot add weighted adapters if they target the same module with modules_to_save, but found " + f"{len(problematic_wrappers)} such instance(s)." + ) + + # if there is only one adapter, we can only use linear merging + combination_type = "linear" if len(adapters) == 1 else combination_type + + adapters_ranks: list[int] = [ + # When allocating tensors for the new adapter, we need the maximum possible rank to not overflow + config.r if not config.rank_pattern else max(config.r, *config.rank_pattern.values()) + for config in (self.peft_config[adapter] for adapter in adapters) + ] + + if combination_type in ("linear", "ties", "dare_ties", "dare_linear", "magnitude_prune"): + # all adapters ranks should be same, new rank is just this value + if len(set(adapters_ranks)) != 1: + raise ValueError( + "All adapters must have the same r value when using combination_type linear, ties, dare_ties or " + "dare_linear." + ) + new_rank = adapters_ranks[0] + elif combination_type == "cat": + # adapters ranks may be different, new rank is sum of all ranks + # be careful, because output adapter rank may be really big if mixing a lot of adapters + new_rank = sum(adapters_ranks) + elif combination_type.endswith("svd"): + # new rank is the max of all ranks of the adapters if not provided + new_rank = svd_rank or max(adapters_ranks) + else: + raise ValueError(f"Invalid combination_type: {combination_type}") + + target_module_types = [type(self.peft_config[adapter].target_modules) for adapter in adapters] + if not target_module_types: + raise ValueError(f"Found no adapter matching the names in {adapters}") + if len(set(target_module_types)) > 1: + raise ValueError( + "all adapter configs should follow the same target modules type. " + "Combining adapters with `target_modules` type being a mix of list/set and string is not supported." + ) + + if target_module_types[0] is str: + new_target_modules = "|".join(f"({self.peft_config[adapter].target_modules})" for adapter in adapters) + elif target_module_types[0] is set: + new_target_modules = reduce( + operator.or_, (self.peft_config[adapter].target_modules for adapter in adapters) + ) + else: + raise TypeError(f"Invalid type {target_module_types[0]} found in target_modules") + + return combination_type, new_rank, new_target_modules + + def add_weighted_adapter( + self, + adapters: list[str], + weights: list[float], + adapter_name: str, + combination_type: str = "svd", + svd_rank: int | None = None, + svd_clamp: int | None = None, + svd_full_matrices: bool = True, + svd_driver: str | None = None, + density: float | None = None, + majority_sign_method: Literal["total", "frequency"] = "total", + ) -> None: + """ + This method adds a new adapter by merging the given adapters with the given weights. + + When using the `cat` combination_type you should be aware that rank of the resulting adapter will be equal to + the sum of all adapters ranks. So it's possible that the mixed adapter may become too big and result in OOM + errors. + + Args: + adapters (`list`): + List of adapter names to be merged. + weights (`list`): + List of weights for each adapter. Weights can be positive or negative, allowing for both addition and + subtraction of adapter effects. + adapter_name (`str`): + Name of the new adapter. + combination_type (`str`): + The merging type can be one of [`svd`, `linear`, `cat`, `ties`, `ties_svd`, `dare_ties`, `dare_linear`, + `dare_ties_svd`, `dare_linear_svd`, `magnitude_prune`, `magnitude_prune_svd`]. When using the `cat` + combination_type, the rank of the resulting adapter is equal to the sum of all adapters ranks (the + mixed adapter may be too big and result in OOM errors). + svd_rank (`int`, *optional*): + Rank of output adapter for svd. If None provided, will use max rank of merging adapters. + svd_clamp (`float`, *optional*): + A quantile threshold for clamping SVD decomposition output. If None is provided, do not perform + clamping. Defaults to None. + svd_full_matrices (`bool`, *optional*): + Controls whether to compute the full or reduced SVD, and consequently, the shape of the returned + tensors U and Vh. Defaults to True. + svd_driver (`str`, *optional*): + Name of the cuSOLVER method to be used. This keyword argument only works when merging on CUDA. Can be + one of [None, `gesvd`, `gesvdj`, `gesvda`]. For more info please refer to `torch.linalg.svd` + documentation. Defaults to None. + density (`float`, *optional*): + Value between 0 and 1. 0 means all values are pruned and 1 means no values are pruned. Should be used + with [`ties`, `ties_svd`, `dare_ties`, `dare_linear`, `dare_ties_svd`, `dare_linear_svd`, + `magnintude_prune`, `magnitude_prune_svd`] + majority_sign_method (`str`): + The method, should be one of ["total", "frequency"], to use to get the magnitude of the sign values. + Should be used with [`ties`, `ties_svd`, `dare_ties`, `dare_ties_svd`] + """ + + if adapter_name in list(self.peft_config.keys()): + return + + combination_type, new_rank, new_target_modules = self._check_add_weighted_adapter( + adapters=adapters, + combination_type=combination_type, + svd_rank=svd_rank, + ) + + self.peft_config[adapter_name] = replace( + self.peft_config[adapters[0]], + r=new_rank, + lora_alpha=new_rank, + target_modules=new_target_modules, + alpha_pattern={}, + rank_pattern={}, + ) + self.inject_adapter(self.model, adapter_name) + + # Do we really need that? + _freeze_adapter(self.model, adapter_name) + + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + for key in key_list: + _, target, _ = _get_submodules(self.model, key) + if isinstance(target, LoraLayer): + if adapter_name in target.lora_A: + target_lora_A = target.lora_A[adapter_name].weight + target_lora_B = target.lora_B[adapter_name].weight + elif adapter_name in target.lora_embedding_A: + target_lora_A = target.lora_embedding_A[adapter_name] + target_lora_B = target.lora_embedding_B[adapter_name] + else: + continue + + target_lora_A.data = target_lora_A.data * 0.0 + target_lora_B.data = target_lora_B.data * 0.0 + if combination_type == "cat": + loras_A, loras_B = [], [] + for adapter, weight in zip(adapters, weights): + if adapter in target.lora_A: + current_adapter_lora_A = target.lora_A[adapter].weight + current_adapter_lora_B = target.lora_B[adapter].weight + elif adapter in target.lora_embedding_A: + current_adapter_lora_A = target.lora_embedding_A[adapter] + current_adapter_lora_B = target.lora_embedding_B[adapter] + else: + continue + loras_A.append(current_adapter_lora_A.data * weight * target.scaling[adapter]) + loras_B.append(current_adapter_lora_B.data) + + if len(loras_A) == 0: + raise ValueError("No matching LoRAs found. Please raise an issue on GitHub.") + loras_A = torch.cat(loras_A, dim=0) + loras_B = torch.cat(loras_B, dim=1) + target_lora_A.data[: loras_A.shape[0], :] = loras_A + target_lora_B.data[:, : loras_B.shape[1]] = loras_B + elif combination_type in [ + "svd", + "ties_svd", + "dare_linear_svd", + "dare_ties_svd", + "magnitude_prune_svd", + ]: + target_lora_A.data, target_lora_B.data = self._svd_generalized_task_arithmetic_weighted_adapter( + combination_type, + adapters, + weights, + new_rank, + target, + target_lora_A, + target_lora_B, + density, + majority_sign_method, + svd_clamp, + full_matrices=svd_full_matrices, + driver=svd_driver, + ) + elif combination_type in ["linear", "ties", "dare_linear", "dare_ties", "magnitude_prune"]: + target_lora_A.data, target_lora_B.data = self._generalized_task_arithmetic_weighted_adapter( + combination_type, adapters, weights, target, density, majority_sign_method + ) + + def _svd_generalized_task_arithmetic_weighted_adapter( + self, + combination_type, + adapters, + weights, + new_rank, + target, + target_lora_A, + target_lora_B, + density, + majority_sign_method, + clamp=None, + full_matrices=True, + driver=None, + ): + valid_adapters = [] + valid_weights = [] + is_embedding = any(adapter in target.lora_embedding_A for adapter in adapters) + for adapter, weight in zip(adapters, weights): + if adapter in target.lora_A or adapter in target.lora_embedding_A: + valid_adapters.append(adapter) + valid_weights.append(weight * target.scaling[adapter]) + + # if no valid adapter, nothing to do + if len(valid_adapters) == 0: + raise ValueError("No matching LoRAs found. Please raise an issue on Github.") + delta_weight = [target.get_delta_weight(adapter) for adapter in valid_adapters] + valid_weights = torch.tensor(valid_weights).to(delta_weight[0].device) + if combination_type == "svd": + delta_weight = task_arithmetic(delta_weight, valid_weights) + elif combination_type == "ties_svd": + delta_weight = ties(delta_weight, valid_weights, density, majority_sign_method) + elif combination_type == "dare_linear_svd": + delta_weight = dare_linear(delta_weight, valid_weights, density) + elif combination_type == "dare_ties_svd": + delta_weight = dare_ties(delta_weight, valid_weights, density, majority_sign_method) + elif combination_type == "magnitude_prune_svd": + delta_weight = magnitude_prune(delta_weight, valid_weights, density) + else: + raise ValueError(f"Invalid value passed to combination type: {combination_type}") + + conv2d = isinstance(target, Conv2d) + if conv2d: + conv2d_1x1 = target.weight.size()[2:4] == (1, 1) + if not conv2d_1x1: + delta_weight = delta_weight.flatten(start_dim=1) + else: + delta_weight = delta_weight.squeeze() + if (hasattr(target, "fan_in_fan_out") and target.fan_in_fan_out) or is_embedding: + delta_weight = delta_weight.T + + # based on https://github.com/kohya-ss/sd-scripts/blob/main/networks/svd_merge_lora.py#L114-L131 + U, S, Vh = torch.linalg.svd(delta_weight, full_matrices=full_matrices, driver=driver) + U = U[:, :new_rank] + S = S[:new_rank] + U = U @ torch.diag(S) + Vh = Vh[:new_rank, :] + if clamp is not None: + dist = torch.cat([U.flatten(), Vh.flatten()]) + hi_val = torch.quantile(dist, clamp) + low_val = -hi_val + U = U.clamp(low_val, hi_val) + Vh = Vh.clamp(low_val, hi_val) + if conv2d: + U = U.reshape(target_lora_B.data.shape) + Vh = Vh.reshape(target_lora_A.data.shape) + return Vh, U + + def _generalized_task_arithmetic_weighted_adapter( + self, + combination_type, + adapters, + weights, + target, + density, + majority_sign_method, + ): + # account weights for LoRA A and B layers. + valid_weights_A = [] + valid_weights_B = [] + lora_A_deltas = [] + lora_B_deltas = [] + for adapter, weight in zip(adapters, weights): + if adapter in target.lora_A: + current_adapter_lora_A = target.lora_A[adapter].weight + current_adapter_lora_B = target.lora_B[adapter].weight + elif adapter in target.lora_embedding_A: + current_adapter_lora_A = target.lora_embedding_A[adapter] + current_adapter_lora_B = target.lora_embedding_B[adapter] + else: + continue + # Support negative weights: take absolute value for sqrt, then apply sign + weight_with_scaling = weight * target.scaling[adapter] + sign = 1 if weight_with_scaling >= 0 else -1 + # apply sign only on one side of the weights, otherwise negative signs negate + valid_weights_A.append(math.sqrt(abs(weight_with_scaling)) * sign) + valid_weights_B.append(math.sqrt(abs(weight_with_scaling))) + lora_A_deltas.append(current_adapter_lora_A.data) + lora_B_deltas.append(current_adapter_lora_B.data) + valid_weights_A = torch.tensor(valid_weights_A).to(lora_A_deltas[0].device) + valid_weights_B = torch.tensor(valid_weights_B).to(lora_B_deltas[0].device) + valid_weights = [valid_weights_A, valid_weights_B] + lora_deltas = [lora_A_deltas, lora_B_deltas] + dtype = lora_A_deltas[0].dtype + for i, task_tensors in enumerate(lora_deltas): + if combination_type == "linear": + lora_deltas[i] = task_arithmetic(task_tensors, valid_weights[i]) + elif combination_type == "ties": + lora_deltas[i] = ties(task_tensors, valid_weights[i], density, majority_sign_method) + elif combination_type == "dare_linear": + lora_deltas[i] = dare_linear(task_tensors, valid_weights[i], density) + elif combination_type == "dare_ties": + lora_deltas[i] = dare_ties(task_tensors, valid_weights[i], density, majority_sign_method) + elif combination_type == "magnitude_prune": + lora_deltas[i] = magnitude_prune(task_tensors, valid_weights[i], density) + else: + raise ValueError("Invalid combination type") + lora_deltas = [delta.to(dtype) for delta in lora_deltas] + return lora_deltas + + def subtract_mutated_init(self, output_state_dict: dict[str, torch.Tensor], adapter_name: str, kwargs=None): + """ + This function can calculate the updates of the PiSSA/CorDA/OLoRA by comparing the parameters of the + PiSSA/CorDA/OLoRA adapter in `output_state_dict` with the initial values of PiSSA/CorDA/OLoRA in + `adapter_name`, thus converting PiSSA/CorDA/OLoRA to LoRA. + """ + for name, param in self.model.named_parameters(): + if ( + param.data.dtype != torch.float32 + and param.data.dtype != torch.float16 + and param.data.dtype != torch.bfloat16 + ) and adapter_name.startswith("pissa"): + warnings.warn( + r"Note that Quant(W_res) + AB != Quant(W) + \Delta(AB); " + "the converted LoRA, when combined with W or Quant(W), may introduce a certain gap in the fine-tuned model. " + "Therefore, we recommend directly using the Quant(W_res) in conjunction with the PiSSA adapter. " + ) + mutated_init_state_dict = get_peft_model_state_dict( + self, + state_dict=kwargs.get("state_dict", None), + adapter_name=adapter_name, + ) + tensors_lora = {} + for name in output_state_dict.keys(): + ## W = W^{res} + A_0 \times B_0, + ## W + \Delta W = W^{res} + A \times B, + ## \Delta W = A \times B - A_0 \times B_0 = [A | A_0] \times [B | -B_0]^T = A'B'. + if "lora_A" in name: + tensors_lora[name] = torch.cat( + [output_state_dict[name], mutated_init_state_dict[".".join(name.split(".")[1:])]], dim=0 + ) + elif "lora_B" in name: + tensors_lora[name] = torch.cat( + [output_state_dict[name], -mutated_init_state_dict[".".join(name.split(".")[1:])]], dim=1 + ) + + return tensors_lora + + def _add_modules_to_save_to_tie(self, peft_config: LoraConfig, tied_weight_keys: list[str]): + """ + Add embedding layer to `modules_to_save` and remove rest of the tied layers from `module_to_save`. Maintain a + separate set for layers to be tied in `peft_config.tied_weights_keys`. + + Args: + peft_config (LoraConfig) -- The configuration of the Lora model. + tied_weight_keys (list[str]) -- Contains the layers tied to the embedding layer. + """ + tied_weight_keys = set(tied_weight_keys) + peft_config.modules_to_tie = tied_weight_keys + + modules_to_save = getattr(peft_config, "modules_to_save", []) or [] + embed_layer_name = find_parameter_name_by_module(self.model, self.model.get_input_embeddings()) + + # the layer may already be included but we assume that adding the same module twice is not a problem + if embed_layer_name not in modules_to_save: + modules_to_save.append(embed_layer_name) + + # Iterate over `tied_weight_keys` which are + # fully qualified keys and remove matching keys from + # `modules_to_save`. It will only remove first encounter + # in `module_to_save`, which should be safe, because `tied_weight_keys` + # is a unique set of keys. These keys are removed because all the + # tied keys are handled in a separate flow + # outside of the usual `modules_to_save` flow + # See: peft.utils.other.set_additional_trainable_modules for details + for key in tied_weight_keys: + for m in modules_to_save: + if re.match(rf"(^|.*\.){m}($|\..*)", key): + modules_to_save.remove(m) + break + + peft_config.modules_to_save = modules_to_save + + def _add_targets_to_tie(self, peft_config: LoraConfig, tied_weight_keys: list[str]): + """ + Add embedding layer to `target_modules` and remove rest of the tied layers from `target_modules`. Maintain a + separate set for layers to be tied in `peft_config.target_modules_to_tie` + + Args: + peft_config (LoraConfig) -- The configuration of the Lora model. + tied_weight_keys (list[str]) -- Contains the layers tied to the embedding layer. + """ + tied_weight_keys = set(tied_weight_keys) + peft_config.target_modules_to_tie = tied_weight_keys + + raw_target_modules = getattr(peft_config, "target_modules", None) + + embed_layer_name = find_parameter_name_by_module(self.model, self.model.get_input_embeddings()) + + if isinstance(raw_target_modules, str): + # The way weight tying is handled for adapters, we always want to add + # lora adapters to the input embedding layer (embed_tokens) + # instead of output embedding layer. + raw_target_modules = rf"(?:{raw_target_modules}|^{re.escape(embed_layer_name)}$)" + peft_config.target_modules = raw_target_modules + return + + target_modules = set(raw_target_modules or []) + target_modules.add(embed_layer_name) + + # Iterate over `tied_weight_keys` which are + # fully qualified keys and remove matching keys from + # `target_modules`. It will only remove first encounter + # in `target_modules`, which should be safe, because `tied_weight_keys` + # is a unique set of keys. These keys are removed because all the + # tied keys are handled in a separate flow + # outside of the usual `target_modules` flow + # See: peft.tuners.tuners_utils.BaseTuner.inject_adapter for details + for key in tied_weight_keys: + for m in target_modules: + if re.match(rf"(^|.*\.){m}($|\..*)", key): + target_modules.remove(m) + break + + peft_config.target_modules = target_modules diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/te.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/te.py new file mode 100644 index 0000000000000000000000000000000000000000..f70d7244766e58cf2c19ca0ec399492b8d6a5d46 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/te.py @@ -0,0 +1,130 @@ +# SPDX-FileCopyrightText: Copyright (c) 2025 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: LicenseRef-Apache2 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional + +import torch + +from peft.import_utils import is_te_available +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import LoraConfig + + +if is_te_available(): + import transformer_engine as te + + +class TeLinear(torch.nn.Module, LoraLayer): + """LoRA layer for TransformerEngine linear modules. + + Supports ``te.pytorch.Linear``, ``te.pytorch.LayerNormLinear``, and ``te.pytorch.LayerNormMLP`` as base layers. + + Note: + Adapter weight merging (``merge`` / ``unmerge``) is **not supported** yet. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + r: int = 0, + lora_alpha: int = 1, + **kwargs, + ): + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer=base_layer, **kwargs) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """Not supported yet for TransformerEngine layers. + + Raises: + NotImplementedError: Always. + """ + raise NotImplementedError(f"{self.__class__.__name__} does not support merge yet.") + + def unmerge(self) -> None: + """Not supported yet for TransformerEngine layers. + + Raises: + NotImplementedError: Always. + """ + raise NotImplementedError(f"{self.__class__.__name__} does not support unmerge yet.") + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + raise ValueError(f"{self.__class__.__name__} does not support mixed_batch_forward yet.") + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + lora_A_keys = self.lora_A.keys() + for active_adapter in self.active_adapters: + if active_adapter not in lora_A_keys: + continue + + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + x = self._cast_input_dtype(x, lora_A.weight.dtype) + result = result + lora_B(lora_A(dropout(x))) * scaling + + result = result.to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_transformer_engine( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_te_available() and isinstance( + target_base_layer, (te.pytorch.LayerNormLinear, te.pytorch.LayerNormMLP, te.pytorch.Linear) + ): + new_module = TeLinear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/torchao.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/torchao.py new file mode 100644 index 0000000000000000000000000000000000000000..c3329a948add781c5fea02c0a50f7ce3982c54c5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/torchao.py @@ -0,0 +1,156 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Any, Optional + +import torch + +# from torch import nn +from peft.import_utils import is_torchao_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import LoraConfig +from .layer import Linear + + +class TorchaoLoraLinear(Linear): + """LoRA layer implementation for Linear layers using torchao data""" + + def __init__(self, *args, get_apply_tensor_subclass, **kwargs): + # this is not strictly necessary, as kwargs are stored either way, but we want to error early if + # get_apply_tensor_subclass is missing. + if kwargs["config"].lora_bias: + raise ValueError(f"{self.__class__.__name__} does not support lora_bias yet, set it to False") + + super().__init__(*args, **kwargs) + self.get_apply_tensor_subclass = get_apply_tensor_subclass + self._check_dtype_supported() + + def _check_dtype_supported(self): + # TODO: Not required once int4_weight_only is properly supported by torchao + base_layer = self.get_base_layer() + weight = base_layer.weight + # pytest tests/test_gpu_examples.py::PeftTorchaoGPUTests::test_causal_lm_training_single_gpu_torchao_0_int8_weight_only + if ( + # torchao 0.7.0+ + (hasattr(weight, "tensor_impl") and (weight.tensor_impl.data.dtype != torch.int8)) + or + # torchao < 0.7.0 + (hasattr(weight, "layout_tensor") and (weight.layout_tensor.data.dtype != torch.int8)) + ): + raise ValueError(f"{type(self).__name__} only supports int8 weights for now.") + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + from torchao import quantize_ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + self._check_dtype_supported() + + base_layer = self.get_base_layer() + weight = base_layer.weight + + for active_adapter in adapter_names: + try: + weight = weight.dequantize() + except NotImplementedError as exc: + msg = ( + f"Weights of type {type(weight).__name__} do not support dequantization (yet), which is needed to " + "support merging." + ) + raise NotImplementedError(msg) from exc + + if safe_merge and not torch.isfinite(weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + weight += self.get_delta_weight(active_adapter) + # TODO: once (if) torchao supports directly mutating the data, use that instead. + del base_layer.weight + base_layer.weight = weight + quantize_(base_layer, self.get_apply_tensor_subclass()) + del weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + from torchao import quantize_ + + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.lora_A.keys(): + continue + + base_layer = self.get_base_layer() + weight = base_layer.weight + try: + weight = weight.dequantize() + except NotImplementedError as exc: + msg = ( + f"Weights of type {type(weight).__name__} do not support dequantization (yet), which is needed to " + "support unmerging." + ) + raise NotImplementedError(msg) from exc + + weight -= self.get_delta_weight(active_adapter) + # We go through a dummy module because overriding the weight.data does not work, the tensor retains the old + # data. Therefore, we need to go through quantize_, which takes a module as input, and we need to delete and + # re-assign the weight. + # TODO: once (if) torchao supports directly mutating the data, use that instead. + del base_layer.weight + base_layer.weight = weight + quantize_(base_layer, self.get_apply_tensor_subclass()) + del weight + + def __repr__(self) -> str: + rep = super().__repr__() + return rep.replace("lora.Linear", f"lora.{self.__class__.__name__}") + + +def dispatch_torchao( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if not hasattr(target_base_layer, "weight"): + return new_module + + if not is_torchao_available(): + return new_module + + from torchao.dtypes import AffineQuantizedTensor + from torchao.quantization import LinearActivationQuantizedTensor + + if isinstance(target_base_layer.weight, (AffineQuantizedTensor, LinearActivationQuantizedTensor)): + new_module = TorchaoLoraLinear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/tp_layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/tp_layer.py new file mode 100644 index 0000000000000000000000000000000000000000..e5b7e07e85984f27f7aa5ccfeac4dca69538276f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/tp_layer.py @@ -0,0 +1,345 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import importlib +import math +import warnings +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.init as init + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils import transpose +from peft.utils.integrations import gather_params_ctx + +from .config import LoraConfig +from .layer import LoraLayer + + +class LoraParallelLinear(nn.Module, LoraLayer): + """ + When the target layer parallel_linear is RowParallelLinear, in order to keep the input and output shapes + consistent, we need to split the lora matrix A into rows, and the lora_B at this time should be a complete linear + layer; In the same way, when the target layer is ColumnParallelLinear, we perform column segmentation on lora_B, + while lora_A is still a complete linear layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + config: LoraConfig, + backend, + r: int = 0, + lora_alpha: int = 1, + is_target_conv_1d_layer: bool = False, + **kwargs, + ): + if config.lora_bias: + raise ValueError(f"{self.__class__.__name__} does not support lora_bias yet, set it to False") + + super().__init__() + LoraLayer.__init__(self, base_layer=base_layer, **kwargs) + + if config.use_dora: + raise ValueError(f"{self.__class__.__name__} does not support DoRA yet, please set it to False") + + self.backend = backend + self.is_parallel_a = isinstance(base_layer, backend.RowParallelLinear) + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + + megatron_config = kwargs["megatron_config"] + parallel_linear_kwargs = {"megatron_config": megatron_config} + init_method = init.xavier_normal_ + if hasattr(megatron_config, "init_method"): + init_method = megatron_config.init_method + input_is_parallel = True + gather_output = False + if self.is_parallel_a: + input_is_parallel = base_layer.input_is_parallel + else: + gather_output = base_layer.gather_output + self.update_layer( + adapter_name, + r, + lora_alpha=lora_alpha, + config=config, + init_method=init_method, + input_is_parallel=input_is_parallel, + gather_output=gather_output, + **parallel_linear_kwargs, + ) + + if is_target_conv_1d_layer: + raise ValueError( + f"{self.__class__.__name__} does not support target_conv_1d_layer yet, please set it to False" + ) + self.is_target_conv_1d_layer = False + + def update_layer( + self, + adapter_name: str, + r: int, + lora_alpha: int, + config: LoraConfig, + init_method=init.xavier_normal_, + input_is_parallel: bool = True, + gather_output: bool = False, + inference_mode: bool = False, + **parallel_linear_kwargs, + ) -> None: + lora_dropout = config.lora_dropout + init_lora_weights = config.init_lora_weights + use_rslora = config.use_rslora + use_dora = config.use_dora + + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + self.r[adapter_name] = r + self.lora_alpha[adapter_name] = lora_alpha + if lora_dropout > 0.0: + lora_dropout_layer = nn.Dropout(p=lora_dropout) + else: + lora_dropout_layer = nn.Identity() + + self.lora_dropout[adapter_name] = lora_dropout_layer + + megatron_config = parallel_linear_kwargs["megatron_config"] + # lora needs to be forced to upgrade to 32-bit precision, otherwise it will overflow + megatron_config.params_dtype = torch.float32 + if self.is_parallel_a: + lora_a = self.backend.RowParallelLinear( + input_size=self.in_features, + output_size=r, + bias=False, + input_is_parallel=input_is_parallel, + skip_bias_add=True, + init_method=init_method, + config=megatron_config, + ) + lora_b = nn.Linear(in_features=r, out_features=self.out_features, bias=False, dtype=torch.float32) + else: + lora_a = nn.Linear(in_features=self.in_features, out_features=r, bias=False, dtype=torch.float32) + lora_b = self.backend.ColumnParallelLinear( + input_size=r, + output_size=self.out_features, + bias=False, + gather_output=gather_output, + init_method=init_method, + config=megatron_config, + ) + self.lora_A[adapter_name] = lora_a + self.lora_B[adapter_name] = lora_b + if use_rslora: + self.scaling[adapter_name] = lora_alpha / math.sqrt(r) + else: + self.scaling[adapter_name] = lora_alpha / r + + self.use_dora[adapter_name] = use_dora + + # for inits that require access to the base weight, use gather_param_ctx so that the weight is gathered when using DeepSpeed + if isinstance(init_lora_weights, str) and init_lora_weights.startswith("pissa"): + with gather_params_ctx(self.get_base_layer().weight): + self.pissa_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.startswith("corda"): + with gather_params_ctx(self.get_base_layer().weight): + self.corda_init(adapter_name, init_lora_weights) + elif isinstance(init_lora_weights, str) and init_lora_weights.lower() == "olora": + with gather_params_ctx(self.get_base_layer().weight): + self.olora_init(adapter_name) + elif init_lora_weights == "loftq": + with gather_params_ctx(self.get_base_layer().weight): + self.loftq_init(adapter_name) + elif init_lora_weights: + self.reset_lora_parameters(adapter_name, init_lora_weights) + + # call this before dora_init + self._move_adapter_to_device_of_base_layer(adapter_name) + + if adapter_name in self.lora_variant: + self.lora_variant[adapter_name].init(self, adapter_name=adapter_name, config=config) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any): + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + # If weight is used for matrix multiplication here, the final aggregation operation of the original + # parallel_linear layer will be missing, so we need to directly call its forward function to obtain the + # output of the original parallel_linear layer. + if self.disable_adapters: + if self.merged: + self.unmerge() + result, bias = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + raise ValueError(f"{self.__class__.__name__} does not support mixed_batch_forward yet.") + elif self.merged: + result, bias = self.base_layer(x, *args, **kwargs) + else: + result, bias = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + for active_adapter in self.active_adapters: + if active_adapter not in self.lora_A.keys(): + continue + lora_A = self.lora_A[active_adapter] + lora_B = self.lora_B[active_adapter] + dropout = self.lora_dropout[active_adapter] + scaling = self.scaling[active_adapter] + x = self._cast_input_dtype(x, lora_A.weight.dtype) + result = result + lora_B(lora_A(dropout(x))) * scaling + + result = result.to(torch_result_dtype) + return result, bias + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.lora_A.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + delta_weight = self.get_delta_weight(active_adapter) + orig_weights = orig_weights + delta_weight + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data = base_layer.weight.data + delta_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.lora_A.keys(): + weight = self.get_base_layer().weight + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.lora_B[adapter].weight.device + dtype = self.lora_B[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_A = self.lora_A[adapter].weight + weight_B = self.lora_B[adapter].weight + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, self.fan_in_fan_out) * self.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.lora_A[adapter].weight.data = weight_A.to(dtype) + self.lora_B[adapter].weight.data = weight_B.to(dtype) + + return output_tensor + + def __repr__(self) -> str: + rep = super().__repr__() + return "lora." + rep + + +def dispatch_megatron( + target: torch.nn.Module, + adapter_name: str, + config: LoraConfig, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if config.megatron_config: + megatron_core = importlib.import_module(config.megatron_core) + else: + megatron_core = None + + if megatron_core and isinstance( + target_base_layer, + (megatron_core.tensor_parallel.ColumnParallelLinear, megatron_core.tensor_parallel.RowParallelLinear), + ): + megatron_kwargs = kwargs.copy() + megatron_config = config.megatron_config + if isinstance(megatron_config, dict): + transformer_config_class = megatron_core.transformer.transformer_config.TransformerConfig + megatron_config = transformer_config_class(**config.megatron_config) + megatron_kwargs["megatron_config"] = megatron_config + if megatron_kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `ColumnParallelLinear` " + "or `RowParallelLinear`. " + "Setting fan_in_fan_out to False." + ) + megatron_kwargs["fan_in_fan_out"] = config.fan_in_fan_out = False + new_module = LoraParallelLinear( + base_layer=target, + adapter_name=adapter_name, + config=config, + backend=megatron_core.tensor_parallel, + **megatron_kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/variants.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/variants.py new file mode 100644 index 0000000000000000000000000000000000000000..59643d523615a9a9ef1c0e3a264d2daaa03f8c97 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lora/variants.py @@ -0,0 +1,923 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import collections +import warnings +from typing import Any, Optional + +import torch +from accelerate.utils.imports import is_xpu_available +from torch import nn + +from peft.tuners.lora.config import BdLoraConfig +from peft.utils.other import transpose + +from .arrow import ArrowLoraLinearLayer +from .config import LoraConfig, PeftConfig +from .dora import DoraConv1dLayer, DoraConv2dLayer, DoraConv3dLayer, DoraEmbeddingLayer, DoraLinearLayer +from .layer import Conv1d, Conv2d, Conv3d, Embedding, Linear, LoraVariant, _ConvNd + + +class ArrowLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs): + """ + Initialise the ArrowLoraLinearLayer() inside lora_arrow. lora_arrow is nn.ModuleDict(), serving as a container + for ArrowLoraLinearLayer(). A layer of the base model with LoRA adapter loaded on it will be like: + ---------------------------------------------------- + (qkv_proj): lora.Linear4bit or lora.Linear( + (base_layer): Linear4bit or Linear (lora_dropout): ModuleDict( ... ) (lora_A): ModuleDict( ... ) + (lora_B): ModuleDict( ... ) (lora_embedding_A): ParameterDict( ... ) (lora_embedding_B): ParameterDict( + ... ) (lora_magnitude_vector): ModuleDict( ... ) (lora_arrow): ModuleDict( + (arrow_router): ArrowLoraLinearLayer() ) + ) + ---------------------------------------------------- + + Args: + module (Linear): LoRA Layer of the model, containing base_layer, lora_A, lora_B, etc. + adapter_name (str): name of the adapter that will be put in lora_arrow. + The adapter_name is "arrow_router" by default, set in create_arrow_model() in ./arrow.py + """ + # Checking for arrow necessary config + arrow_config = config.arrow_config + if arrow_config is None: + raise ValueError("ArrowLinearVariant.init() did not receive an arrow_config") + + # 1-a) build the ArrowLoRALayer + arrow_layer = ArrowLoraLinearLayer( + in_features=module.in_features, + arrow_config=arrow_config, + ).to(module.weight.device) + + # 1-b) register a container if it doesn’t exist yet + if not hasattr(module, "lora_arrow"): + module.lora_arrow = nn.ModuleDict() + + module.lora_arrow[adapter_name] = arrow_layer + + @staticmethod + def forward( + module: Linear, + *, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + """ + Parameters mirror those in PEFT’s `LoraVariant.forward`. Called every time the host Linear does a fwd pass. + + build_prototypes() and gen_know_sub() should run only once before routing. Both are implemented in + ArrowLoraLinearLayer (see ./arrow.py). They are lazily invoked in the forward pass below. Attributes of + ArrowLoraLinearLayer() class ensure they execute only a single time. + + Args: + module (Linear): LoRA Layer of the model + active_adapter (str): name of the arrow route, which should be active to perform arrow. + x (torch.Tensor): input to the layer + result (torch.Tensor): output of the base layer. + + Return value: + output of the base model + delta weight computed by arrow layer. + """ + arrow = module.lora_arrow[active_adapter] # ArrowLoraLinearLayer + # Apply GenKnowSub the 1st time if applcable. By calling arrow/on_adapter_change(), + # gen_know_sub() is redone for newly added adapters after arrow.create_arrow_model(). + arrow.gen_know_sub(module.lora_A, module.lora_B) + # lazily build prototypes the 1st time after GenKnowSub. By calling arrow/on_adapter_change(), + # build_prototypes() is redone for newly added adapters after arrow.create_arrow_model(). + arrow.build_prototypes(module.lora_A, module.lora_B) + + # A forward path of ArrowLoraLinearLayer is called so routing performs. + # Accept and ignore extra variant kwargs (e.g., 'alora_offsets') for compatibility + delta = arrow( + x, + lora_A=module.lora_A, + lora_B=module.lora_B, + dropout=module.lora_dropout[active_adapter], + scaling=module.scaling, + ) + return result + delta + + """ + Since Arrow is a Mixture-of-Experts (MoE) approach, merging adapters is not meaningful or even possible: for each + token, the top-k LoRA experts are dynamically selected and routed. Because of this per-token routing, there is no + single set of weights that can represent a merged adapter. + """ + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise RuntimeError("Cannot merge an active Arrow router adapter. Remove it first.") + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + raise RuntimeError("Cannot merge an active Arrow router adapter. Remove it first.") + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise RuntimeError("Cannot unmerge an active Arrow router adapter. Remove it first.") + + +class DoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, **kwargs: Any) -> None: + if not module.lora_magnitude_vector: + # first dora layer being added, add lora_magnitude_vector to the list of learnable parameters + module.adapter_layer_names = module.adapter_layer_names[:] + ("lora_magnitude_vector",) + + dora_layer = DoraLinearLayer(fan_in_fan_out=getattr(module, "fan_in_fan_out", False)) + lora_A = module.lora_A[adapter_name].weight + lora_B = module.lora_B[adapter_name].weight + place_on_cpu = module.ephemeral_gpu_offload and (lora_A.device.type == "cpu" or lora_B.device.type == "cpu") + if module.ephemeral_gpu_offload: + if lora_A.device.type in ["cuda", "xpu"]: + lora_B = lora_B.to(lora_A.device) + else: + if lora_B.device.type not in ["cuda", "xpu"]: + if is_xpu_available(): + lora_B = lora_B.to("xpu") + else: + lora_B = lora_B.to("cuda") + lora_A = lora_A.to(lora_B.device) + scaling = module.scaling[adapter_name] + dora_layer.update_layer( + base_layer=module.get_base_layer(), + lora_A=lora_A, + lora_B=lora_B, + scaling=scaling, + place_on_cpu=place_on_cpu, + ) + module.lora_magnitude_vector[adapter_name] = dora_layer + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, transpose(delta_weight, module.fan_in_fan_out), scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = transpose(dora_factor.view(-1, 1), module.fan_in_fan_out) + new_weight = dora_factor * (orig_weight + delta_weight) + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, transpose(delta_weight, module.fan_in_fan_out), scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = transpose(dora_factor.view(-1, 1), module.fan_in_fan_out) + new_weight = dora_factor * (orig_weight.data + delta_weight) + new_weight = new_weight.to(orig_dtype) + orig_weight.data = new_weight + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = module._cache_pop(f"{active_adapter}-weight_norm") + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = orig_weight.data / dora_factor.view(-1, 1) - delta_weight + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + + if isinstance(dropout, nn.Identity) or not module.training: + base_result = result + else: + x = dropout(x) + base_result = None + + result = result + module.lora_magnitude_vector[active_adapter]( + x, + lora_A=lora_A, + lora_B=lora_B, + scaling=scaling, + base_layer=module.get_base_layer(), + base_result=base_result, + adapter_name=active_adapter, + ) + return result + + +class DoraEmbeddingVariant(DoraLinearVariant): + @staticmethod + def init(module: Embedding, adapter_name: str, **kwargs: Any) -> None: + if module.lora_magnitude_vector is None: + # first dora layer being added, add lora_magnitude_vector to the list of learnable parameters + module.adapter_layer_names = module.adapter_layer_names[:] + ("lora_magnitude_vector",) + + dora_layer = DoraEmbeddingLayer(fan_in_fan_out=True) + lora_embedding_A = module.lora_embedding_A[adapter_name] + lora_embedding_B = module.lora_embedding_B[adapter_name] + scaling = module.scaling[adapter_name] + dora_layer.update_layer( + base_layer=module.get_base_layer(), lora_A=lora_embedding_A, lora_B=lora_embedding_B, scaling=scaling + ) + module.lora_magnitude_vector[adapter_name] = dora_layer + + @staticmethod + def merge_safe(module: Embedding, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, delta_weight.T, scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = dora_factor.view(1, -1) + new_weight = dora_factor * (orig_weight + delta_weight) + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def merge_unsafe(module: Embedding, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = ( + module.lora_magnitude_vector[active_adapter] + .get_weight_norm(orig_weight, delta_weight.T, scaling=1) + .detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + dora_factor = dora_factor.view(1, -1) + new_weight = dora_factor * (orig_weight.data + delta_weight) + new_weight = new_weight.to(orig_dtype) + orig_weight.data = new_weight + + @staticmethod + def unmerge(module: Embedding, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = module._cache_pop(f"{active_adapter}-weight_norm") + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = orig_weight.data / dora_factor.view(1, -1) - delta_weight + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def forward( + module: Embedding, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + embedding_A = module.lora_embedding_A[active_adapter].T + embedding_B = module.lora_embedding_B[active_adapter].T + scaling = module.scaling[active_adapter] + + mag_norm_scale, dora_result = module.lora_magnitude_vector[active_adapter]( + x, + lora_A=embedding_A, + lora_B=embedding_B, + scaling=scaling, + base_layer=module.get_base_layer(), + embed_fn=module._embed, + adapter_name=active_adapter, + ) + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to DoRA contributions too. + # Note: embed_scale is applied AFTER weight norm calculation to preserve DoRA's weight geometry semantics. + embed_scale = module._get_embed_scale() + if embed_scale is not None: + dora_result = dora_result * embed_scale.to(dora_result.dtype) + + result = mag_norm_scale * result + dora_result + return result + + +class _DoraConvNdVariant(LoraVariant): + @staticmethod + def init_convd_variant(module: _ConvNd, adapter_name: str, dora_layer: nn.Module) -> None: + if module.lora_magnitude_vector is None: + # first dora layer being added, add lora_magnitude_vector to the list of learnable parameters + module.adapter_layer_names = module.adapter_layer_names[:] + ("lora_magnitude_vector",) + + lora_A = module.lora_A[adapter_name].weight + lora_B = module.lora_B[adapter_name].weight + scaling = module.scaling[adapter_name] + dora_layer.update_layer(base_layer=module.get_base_layer(), lora_A=lora_A, lora_B=lora_B, scaling=scaling) + module.lora_magnitude_vector[adapter_name] = dora_layer + + @staticmethod + def merge_safe(module: _ConvNd, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter].get_weight_norm(orig_weight, delta_weight, scaling=1).detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = dora_factor.view(*module._get_dora_factor_view()) * (orig_weight + delta_weight) + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def merge_unsafe(module: _ConvNd, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + # since delta_weight already includes scaling, set it to 1 here + weight_norm = ( + module.lora_magnitude_vector[active_adapter].get_weight_norm(orig_weight, delta_weight, scaling=1).detach() + ) + # We need to cache weight_norm because it has to be based on the original weights. We + # cannot calculate it on the fly based on the merged weights when unmerging because its a + # different value + module._cache_store(f"{active_adapter}-weight_norm", weight_norm) + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = dora_factor.view(*module._get_dora_factor_view()) * (orig_weight.data + delta_weight) + new_weight = new_weight.to(orig_dtype) + orig_weight.data = new_weight + + @staticmethod + def unmerge(module: _ConvNd, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + orig_dtype = orig_weight.dtype + delta_weight = module.get_delta_weight(active_adapter) + weight_norm = module._cache_pop(f"{active_adapter}-weight_norm") + dora_factor = module.lora_magnitude_vector[active_adapter].weight / weight_norm + new_weight = orig_weight.data / dora_factor.view(*module._get_dora_factor_view()) - delta_weight + new_weight = new_weight.to(orig_dtype) + return new_weight + + @staticmethod + def forward( + module: _ConvNd, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + + if isinstance(dropout, nn.Identity) or not module.training: + base_result = result + else: + x = dropout(x) + base_result = None + + result = result + module.lora_magnitude_vector[active_adapter]( + x, + lora_A=lora_A, + lora_B=lora_B, + scaling=scaling, + base_layer=module.get_base_layer(), + base_result=base_result, + adapter_name=active_adapter, + ) + return result + + +class DoraConv1dVariant(_DoraConvNdVariant): + @staticmethod + def init(module: Conv1d, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + dora_layer = DoraConv1dLayer(fan_in_fan_out=False) + _DoraConvNdVariant.init_convd_variant(module, adapter_name, dora_layer=dora_layer) + + +class DoraConv2dVariant(_DoraConvNdVariant): + @staticmethod + def init(module: Conv2d, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + dora_layer = DoraConv2dLayer(fan_in_fan_out=False) + _DoraConvNdVariant.init_convd_variant(module, adapter_name, dora_layer=dora_layer) + + +class DoraConv3dVariant(_DoraConvNdVariant): + @staticmethod + def init(module: Conv3d, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + dora_layer = DoraConv3dLayer(fan_in_fan_out=False) + _DoraConvNdVariant.init_convd_variant(module, adapter_name, dora_layer=dora_layer) + + +class QALoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + """ + Initializes QALoRA specific parameters for a given adapter. + + Args: + module (Linear): The linear module to be adapted. + adapter_name (str): The name of the adapter. + config (LoraConfig): The config of the LoRA adapter. + **kwargs: Additional keyword arguments. + """ + qalora_group_size = config.qalora_group_size + if module.in_features is not None and module.in_features % qalora_group_size != 0: + raise ValueError( + f"`use_qalora=True` requires `module.in_features` ({module.in_features}) to be" + f"divisible by 'qalora_group_size' ({qalora_group_size})" + ) + + if "qalora_group_size" not in module.other_param_names: + module.other_param_names = module.other_param_names + ("qalora_group_size",) + + if not hasattr(module, "qalora_group_size"): + module.qalora_group_size = {} + module.qalora_group_size[adapter_name] = qalora_group_size + + old_lora_A_layer = module.lora_A[adapter_name] + r = old_lora_A_layer.out_features + device = old_lora_A_layer.weight.device + dtype = old_lora_A_layer.weight.dtype + + new_lora_A_layer = nn.Linear( + old_lora_A_layer.in_features // module.qalora_group_size[adapter_name], + r, + bias=False, + device=device, + dtype=dtype, + ) + module.lora_A[adapter_name] = new_lora_A_layer + + @staticmethod + def get_delta_weight(module: Linear, active_adapter: str) -> torch.Tensor: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'get_delta_weight'.") + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'safe_merge'.") + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'merge_unsafe'.") + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("QALoRA for GPTQ layers does not support 'unmerge'.") + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + lora_A_weight = module.lora_A[active_adapter].weight + lora_B_weight = module.lora_B[active_adapter].weight + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + group_size = module.qalora_group_size[active_adapter] + + x_dropped = dropout(x) if module.training and not isinstance(dropout, nn.Identity) else x + orig_shape = x_dropped.shape + + # Reshape to 2D + if len(orig_shape) > 2: + x_flat = x_dropped.view(-1, module.in_features) + else: + x_flat = x_dropped + + batch_size, in_features = x_flat.shape + pooled_features = in_features // group_size + + x_pooled = x_flat.view(batch_size, pooled_features, group_size).mean(dim=2) + + x_pooled_scaled = x_pooled * pooled_features + + # LoRA computation + delta = x_pooled_scaled @ lora_A_weight.t() @ lora_B_weight.t() * scaling + + # Reshape back + if len(orig_shape) > 2: + delta = delta.view(orig_shape[:-1] + (delta.size(-1),)) + + return result + delta + + +class ALoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs: Any) -> None: + pass + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("aLoRA does not support safe merging.") + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + raise NotImplementedError("aLoRA does not support merging.") + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + raise NotImplementedError("aLoRA does not support unmerging.") + + @staticmethod + def forward( + module: Linear, + active_adapter: str, + x: torch.Tensor, + result: torch.Tensor, + **kwargs, + ) -> torch.Tensor: + alora_offsets = kwargs.get("alora_offsets", None) + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) + result_shape = result.shape + B = result_shape[0] # batch + if len(result_shape) == 3: + T = result_shape[1] # tokens + else: + T = 1 + D = result_shape[-1] # dimensions + Dx = x.shape[-1] + device = result.device + if alora_offsets is None: # use base model only, but ensure 0 gradient + mask = torch.zeros((B, T), dtype=torch.bool) + else: + # If alora_offsets[i] is None, this means that the invocation sequence was not found in the + # input. As a result, the weights should not be activated anywhere (equivalent to base model). + # Convert None -> 0 and clip to T + offsets = torch.tensor( + [0 if o is None else min(int(o), T) for o in alora_offsets], + device=device, + dtype=torch.long, + ) + # Mask True on the last `offsets[i]` positions for each row i + pos = torch.arange(T, device=device).unsqueeze(0) # [1, T] + mask = pos >= (T - offsets).unsqueeze(1) + + # Flatten for vectorization + x_flat = x.view(-1, Dx) + res_flat = result.view(-1, D) + mask_flat = mask.view(-1) + + # Compute adapter on the selected tokens only + res_flat[mask_flat] += lora_B(lora_A(dropout(x_flat[mask_flat]))) * scaling + return result + + +def calculate_alora_offsets( + peft_config: PeftConfig, active_adapter: str, input_ids: torch.Tensor, adapter_names: Optional[list[str]] = None +) -> list[int]: + """ + This is a helper function for Activated LoRA (aLoRA) that searches each input token sequence for the last occurence + of the appropriate "alora_invocation_tokens" invocation sequence. The calculated alora_offset is the location of + the *start* of the invocation tokens, counting backward from the end (will therefore always be >= + len(alora_invocation_tokens). If adapter_names is passed, then each input uses the appropriate invocation sequence + for the specified adapter for that row. Logic is provided to handle mixed collections of adapters for which not all + are aLoRAs (e.g. some base model, some LoRA). + """ + if input_ids is None: + return [] + + batch_size = input_ids.shape[0] + alora_offsets = [None] * batch_size + + cached_invocation_tensors = {} + adapters_to_process_indices = collections.defaultdict(list) + + for i in range(batch_size): + current_adapter_name = adapter_names[i] if adapter_names and i < len(adapter_names) else active_adapter + + if current_adapter_name == "__base__": + alora_offsets[i] = None + continue + + if current_adapter_name not in peft_config: + warnings.warn(f"Adapter '{current_adapter_name}' not found in peft_config. Using base model for row {i}.") + alora_offsets[i] = None + continue + + current_peft_config = peft_config[current_adapter_name] + + invocation_tokens = getattr(current_peft_config, "alora_invocation_tokens", None) + if invocation_tokens is None: + alora_offsets[i] = None # Not an aLoRA adapter or wrong type + continue + + if current_adapter_name not in cached_invocation_tensors: + cached_invocation_tensors[current_adapter_name] = torch.tensor( + invocation_tokens, dtype=torch.long, device=input_ids.device + ) + + adapters_to_process_indices[current_adapter_name].append(i) + + for adapter_name_to_process, indices in adapters_to_process_indices.items(): + current_invocation_ids_tensor = cached_invocation_tensors[adapter_name_to_process] + invocation_len = len(current_invocation_ids_tensor) + + for i in indices: + sequence = input_ids[i] + seq_len = len(sequence) + best_match_start_idx = -1 + + possible_starts = (sequence == current_invocation_ids_tensor[0]).nonzero(as_tuple=True)[0] + + for start_idx_tensor in possible_starts: + idx = start_idx_tensor.item() + if idx + invocation_len <= seq_len: + if torch.equal(sequence[idx : idx + invocation_len], current_invocation_ids_tensor): + if idx > best_match_start_idx: + best_match_start_idx = idx + + if best_match_start_idx != -1: + offset_val = seq_len - best_match_start_idx + alora_offsets[i] = offset_val if offset_val > 0 else None + else: # Invocation sequence not found in input + alora_offsets[i] = None + return alora_offsets + + +def is_alora_relevant_in_batch(model: nn.Module, adapter_names: Optional[list[str]] = None): + """ + Helper function to determine if the current batch has any aLoRA adapters. + """ + is_alora_relevant = False + if getattr(model.active_peft_config, "alora_invocation_tokens", None): + is_alora_relevant = True + elif adapter_names: + for name in adapter_names: + if name == "__base__": + continue + config_ = model.peft_config.get(name) + if config_ and getattr(config_, "alora_invocation_tokens", None): + is_alora_relevant = True + break + + return is_alora_relevant + + +def get_alora_offsets_for_forward( + model: nn.Module, input_ids: torch.Tensor = None, inputs_embeds: torch.Tensor = None, **kwargs +): + """ + Wrapper around calculate_alora_offsets, for the .forward of the model. It only calculates alora_offsets if the + batch contains aLoRA adapters. + """ + adapter_names_for_offset_calc = kwargs.get("adapter_names", None) + if not is_alora_relevant_in_batch(model, adapter_names_for_offset_calc): + # Nothing to compute + return kwargs + alora_offsets = kwargs.get("alora_offsets") + if alora_offsets is None: + if input_ids is None and inputs_embeds is not None: + warnings.warn( + "Cannot calculate aLoRA offsets when only inputs_embeds are provided. Disabling aLoRA for this forward pass." + ) + kwargs["alora_offsets"] = None + elif input_ids is not None: + kwargs["alora_offsets"] = calculate_alora_offsets( + model.peft_config, + model.active_adapter, + input_ids, + adapter_names=adapter_names_for_offset_calc, + ) + else: + kwargs["alora_offsets"] = None + return kwargs + + +def get_alora_offsets_for_generate(model: nn.module, *args, **kwargs): + """ + Wrapper around calculate_alora_offsets, for the .generate of the model. It only calculates alora_offsets if the + batch contains aLoRA adapters. + """ + adapter_names_for_offset_calc = kwargs.get("adapter_names") + if not is_alora_relevant_in_batch(model, adapter_names_for_offset_calc): + # Nothing to compute + return kwargs + alora_offsets_from_kwargs = kwargs.get("alora_offsets") + if alora_offsets_from_kwargs is None: + current_input_ids = kwargs.get("input_ids") + if current_input_ids is None: # args[0] is usually input_ids + if args and isinstance(args[0], torch.Tensor): + current_input_ids = args[0] + else: + current_input_ids = None + + if current_input_ids is not None: + if current_input_ids.ndim == 1: + current_input_ids = current_input_ids.unsqueeze(0) + calculated_offsets = calculate_alora_offsets( + model.peft_config, + model.active_adapter, + current_input_ids, + adapter_names=adapter_names_for_offset_calc, + ) + kwargs["alora_offsets"] = calculated_offsets + + else: + warnings.warn( + "Cannot calculate aLoRA offsets during generate as input_ids are not available. Disabling aLoRA." + ) + + kwargs["alora_offsets"] = None + return kwargs + + +class BlockDiagonalLinear(nn.Module): + def __init__( + self, + in_features: int, + out_features: int, + nblocks: int, + init_zero: bool = False, + dtype: torch.dtype = torch.float32, + device: torch.device = torch.device("cpu"), + ): + super().__init__() + self.in_features = in_features + self.out_features = out_features + self.nblocks = nblocks + if self.in_features % nblocks != 0 or self.out_features % nblocks != 0: + raise ValueError( + f"self.in_features={self.in_features} or self.out_features={self.out_features} not divisible by {self.nblocks}" + ) + # Create weight with specified dtype and device + self.weight = nn.Parameter(torch.empty(out_features, in_features // nblocks, dtype=dtype, device=device)) + + if init_zero: + torch.nn.init.zeros_(self.weight) + else: + torch.nn.init.kaiming_uniform_(self.weight) + + def forward(self, x: torch.Tensor) -> torch.Tensor: + first_dims = x.shape[:-1] + if x.dim() != 2: + x = x.reshape(-1, x.shape[-1]) + B = x.shape[0] + nb = self.nblocks + m = x.shape[-1] // nb + n = self.out_features // nb + x = x.reshape(B, nb, m) + w = self.weight.view(nb, n, m) + out = torch.einsum("bim,inm->bin", x, w) + return out.reshape(*first_dims, -1) + + def weight_as_blockdiagonal_matrix(self): + """Returns weight in a format similar to a vanilla LoRA adapter. For this, we stack the blocks on the diagonal, + leaving the off-diagonals padded with zero.""" + return torch.block_diag(*torch.chunk(self.weight, self.nblocks, dim=0)) + + +class BdLoraLinearVariant(LoraVariant): + @staticmethod + def init(module: Linear, adapter_name: str, config: LoraConfig, **kwargs) -> None: + use_bdlora = config.use_bdlora + target_name = kwargs.get("target_name", "") + + # Handle case where use_bdlora is a dict (from saved config) instead of BdLoraConfig object + if isinstance(use_bdlora, dict): + use_bdlora = BdLoraConfig(**use_bdlora) + + lora_a_blockdiagonal_pattern = use_bdlora.target_modules_bd_a or [] + lora_b_blockdiagonal_pattern = use_bdlora.target_modules_bd_b or [] + nblocks = use_bdlora.nblocks + + has_lora_a_blockdiagonal = any(pattern in target_name for pattern in lora_a_blockdiagonal_pattern) + has_lora_b_blockdiagonal = any(pattern in target_name for pattern in lora_b_blockdiagonal_pattern) + + if has_lora_a_blockdiagonal and has_lora_b_blockdiagonal: + raise ValueError(f"Target {target_name} matches both A and B block-diagonal patterns") + if use_bdlora.match_strict and not (has_lora_a_blockdiagonal or has_lora_b_blockdiagonal): + raise ValueError( + f"Target {target_name} matches neither A nor B block-diagonal patterns." + "If this is intentional, set match_strict=False in BdLoraConfig during initialization. " + ) + + if has_lora_a_blockdiagonal: + r = module.lora_A[adapter_name].out_features + base_layer = module.get_base_layer() + layer = BlockDiagonalLinear( + base_layer.in_features, + r, + nblocks=nblocks, + init_zero=False, + dtype=base_layer.weight.dtype, + device=base_layer.weight.device, + ) + module.lora_A[adapter_name] = layer + elif has_lora_b_blockdiagonal: + r = module.lora_B[adapter_name].in_features + base_layer = module.get_base_layer() + layer = BlockDiagonalLinear( + r, + base_layer.out_features, + nblocks=nblocks, + init_zero=True, + dtype=base_layer.weight.dtype, + device=base_layer.weight.device, + ) + module.lora_B[adapter_name] = layer + + @staticmethod + def forward(module: Linear, active_adapter: str, x: torch.Tensor, result: torch.Tensor, **kwargs) -> torch.Tensor: + lora_A = module.lora_A[active_adapter] + lora_B = module.lora_B[active_adapter] + dropout = module.lora_dropout[active_adapter] + scaling = module.scaling[active_adapter] + x = dropout(x) + # Cast input dtype to match lora_A weight dtype + x = module._cast_input_dtype(x, lora_A.weight.dtype) + result += lora_B(lora_A(x)) * scaling + return result + + @staticmethod + def _get_weight_from_module_maybe_blockdiagonal(module: nn.Module) -> torch.Tensor: + if isinstance(module, BlockDiagonalLinear): + return module.weight_as_blockdiagonal_matrix() + else: + return module.weight # type: ignore + + @staticmethod + def _get_bdlora_delta_weight(module: Linear, adapter: str) -> torch.Tensor: + """Similar to get_delta_weight for a linear module, but we have to eventually reshape the blocks + of the weights.""" + device = module.lora_B[adapter].weight.device + # Use base layer dtype to ensure compatibility with merge/unmerge operations + base_layer = module.get_base_layer() + dtype = base_layer.weight.dtype + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_A = BdLoraLinearVariant._get_weight_from_module_maybe_blockdiagonal(module.lora_A[adapter]) + weight_B = BdLoraLinearVariant._get_weight_from_module_maybe_blockdiagonal(module.lora_B[adapter]) + + if cast_to_fp32: + weight_A = weight_A.float() + weight_B = weight_B.float() + + output_tensor = transpose(weight_B @ weight_A, module.fan_in_fan_out) * module.scaling[adapter] + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # Ensure output tensor matches base layer dtype + return output_tensor.to(dtype=dtype) + + @staticmethod + def merge_safe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + return orig_weight + BdLoraLinearVariant._get_bdlora_delta_weight(module, active_adapter) + + @staticmethod + def merge_unsafe(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> None: + orig_weight.data += BdLoraLinearVariant._get_bdlora_delta_weight(module, active_adapter) + + @staticmethod + def unmerge(module: Linear, active_adapter: str, orig_weight: torch.Tensor) -> torch.Tensor: + return orig_weight - BdLoraLinearVariant._get_bdlora_delta_weight(module, active_adapter) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lycoris_utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lycoris_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..7ea7a260569cb1f16ed868b55b529e02d4a0c11a --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/lycoris_utils.py @@ -0,0 +1,263 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from abc import abstractmethod +from dataclasses import dataclass, field +from typing import Any, Optional, Union + +import torch +import torch.nn as nn + +from peft.config import PeftConfig + +from .tuners_utils import ( + BaseTuner, + BaseTunerLayer, + _get_in_out_features, + check_adapters_to_merge, +) + + +@dataclass +class LycorisConfig(PeftConfig): + r""" + A base config for LyCORIS like adapters + """ + + rank_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to ranks which are different from the default rank specified by `r`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + alpha_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "The mapping from layer names or regexp expression to alphas which are different from the default alpha specified by `alpha`. " + "For example, `{'^model.decoder.layers.0.encoder_attn.k_proj': 16}`." + ) + }, + ) + + +class LycorisLayer(BaseTunerLayer): + r""" + A base layer for LyCORIS like adapters + """ + + # adapter_layer_names needs to be defined on the child class + other_param_names = ("r", "alpha", "scaling", "rank_dropout", "module_dropout") + + def __init__(self, base_layer: nn.Module) -> None: + self.base_layer = base_layer + self.r = {} + self.alpha = {} + self.scaling = {} + self.rank_dropout = {} + self.rank_dropout_scale = {} + self.module_dropout = {} + + # Tuner info + self._disable_adapters = False + self.merged_adapters = [] + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + + in_features, out_features = _get_in_out_features(self.get_base_layer()) + self.in_features = in_features + self.out_features = out_features + + @property + @abstractmethod + def _available_adapters(self) -> set[str]: ... + + def _init_empty_weights(self, cls, *args, **kwargs) -> None: + # A helper method that allows to initialize the layer of the given class without spending time to initialize the + # model weights. The implementation is inspired by + # https://pytorch.org/docs/stable/generated/torch.nn.utils.skip_init.html but this function cannot be used + # directly. + # Instead of this approach, it would be possible to bypass the __init__ of the class but that runs the risk of + # omitting important logic inside that __init__. + kwargs = kwargs.copy() + final_device = kwargs.pop("device", "cpu") + cls.__init__(self, *args, device="meta", **kwargs) + self.to_empty(device=final_device) + + @abstractmethod + def create_adapter_parameters(self, adapter_name: str, r: int, **kwargs): ... + + # TODO: refactor LoRA to use the same approach + @abstractmethod + def _get_delta_activations(self, adapter_name: str, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + """Activations added on top of the base layer output (i.e. after the base layer forward pass)""" + + @abstractmethod + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: ... + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self._available_adapters: + base_layer = self.get_base_layer() + if safe_merge: + orig_weights = base_layer.weight.data.clone() + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += self.get_delta_weight(active_adapter) + self.merged_adapters.append(active_adapter) + + @abstractmethod + def reset_adapter_parameters(self, adapter_name: str): ... + + def set_scale(self, adapter, scale): + if adapter not in self._available_adapters: + # Ignore the case where the adapter is not in the layer + return + self.scaling[adapter] = scale * self.alpha[adapter] / self.r[adapter] + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + self.scaling[active_adapter] *= scale + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self._available_adapters: + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def unscale_layer(self, scale=None) -> None: + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + if scale is None: + self.scaling[active_adapter] = self.alpha[active_adapter] / self.r[active_adapter] + else: + self.scaling[active_adapter] /= scale + + @abstractmethod + def update_layer(self, adapter_name: str, r: int, alpha: float, **kwargs): ... + + +class LycorisTuner(BaseTuner): + r""" + A base tuner for LyCORIS like adapters + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`LoraConfig`]): The configuration of the Lora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + """ + + prefix: str + tuner_layer_cls = LycorisLayer + layers_mapping: dict[type[torch.nn.Module], type[LycorisLayer]] + + @abstractmethod + def _create_and_replace( + self, + config: LycorisConfig, + adapter_name: str, + target: Union[LycorisLayer, nn.Module], + target_name, + parent, + current_key, + ): ... + + @classmethod + def _create_new_module(cls, config: LycorisConfig, adapter_name: str, target: nn.Module, **kwargs) -> LycorisLayer: + # Find corresponding subtype of provided target module + new_module_cls = None + for subtype, target_cls in cls.layers_mapping.items(): + if ( + hasattr(target, "base_layer") + and isinstance(target.get_base_layer(), subtype) + and isinstance(target, BaseTunerLayer) + ): + # nested tuner layers are allowed + new_module_cls = target_cls + break + elif isinstance(target, subtype): + new_module_cls = target_cls + break + + # We didn't find corresponding type, so adapter for this layer is not supported + if new_module_cls is None: + supported_modules = ", ".join(layer.__name__ for layer in cls.layers_mapping.keys()) + raise ValueError( + f"Target module of type {type(target)} not supported, " + f"currently only adapters for {supported_modules} are supported" + ) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, (torch.nn.Conv2d, torch.nn.Conv1d)): + new_module = new_module_cls(target, adapter_name=adapter_name, **kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + new_module = new_module_cls(target, adapter_name=adapter_name, **kwargs) + else: + supported_modules = ", ".join(layer.__name__ for layer in cls.layers_mapping.keys()) + raise ValueError( + f"Target module of type {type(target)} not supported, " + f"currently only adapters for {supported_modules} are supported" + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..ca8aceeb0dc772c6db6157834de40ab2c43fe291 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import MissConfig +from .layer import MissLayer, MissLinear +from .model import MissModel + + +__all__ = ["MissConfig", "MissLayer", "MissLinear", "MissModel"] + +register_peft_method(name="miss", config_cls=MissConfig, model_cls=MissModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a0cef7ab34b3b35a4806c58a2e74acfbd3980b36 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/config.py @@ -0,0 +1,140 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class MissConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`MiSSModel`]. + + Args: + r (`int`): + The rank of MiSS across different layers. It is best to set 'r' to an even number; otherwise, the default + initialization method will not work. The rank of MiSS corresponds to a low-rank decomposition along the + in_features dimension. + miss_dropout (`float`): + The dropout probability for MiSS layers. + mini_r (`int`): + The rank of MiSS corresponds to a low-rank decomposition along the out_features dimension. When you set + `init_weights=mini`, you need to set `mini_r`. Please make sure that `out_features` is divisible by + `mini_r`. + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear modules are chosen, excluding + the output layer. If this is not specified, modules will be chosen according to the model architecture. If + the architecture is not known, an error will be raised -- in this case, you should specify the target + modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + init_weights (bool | Literal["bat", "mini"]): + Different initializations correspond to different MiSS variants. By default(balance), the most efficient + and general method in MiSS will be used. 'bat': In this mode, you can enable nonlinear updates across + different shards. 'mini': In this mode, you can set a smaller rank to use fewer trainable parameters, but + it is recommended to keep `out_features % mini_r == 0`. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`str`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field( + default=64, + metadata={ + "help": "The rank of MiSS corresponds to a low-rank decomposition along the in_features dimension.", + "note": "It is best to set 'r' to an even number; otherwise, the default initialization method will not work.", + }, + ) + miss_dropout: float = field(default=0.0, metadata={"help": "MiSS dropout"}) + mini_r: int = field( + default=1, + metadata={ + "help": "The rank of MiSS corresponds to a low-rank decomposition along the out_features dimension.", + "note": "It is recommended that mini_r be divisible by out_features. When mini_r == out_features, the mini method is equivalent to the default efficient MiSS.", + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with MiSS.", + "example": "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' ", + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from MiSS."}, + ) + init_weights: bool | Literal["bat", "mini"] = field( + default=True, + metadata={ + "help": ( + "True -> MiSS balance; `bat` -> Bat; `mini` -> smaller rank and efficiency" + "Whether to initialize the weights of the MiSS layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index." + }, + ) + layers_pattern: Optional[str] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern." + }, + ) + bias: str = field(default="none", metadata={"help": "Bias type for MiSS. Can be 'none', 'all' or 'MiSS_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from MiSS layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.MISS + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..2861c7c5b945bb8a017735b45ecdb0d73a7b03e2 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/layer.py @@ -0,0 +1,397 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import math +import warnings +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + + +class MissLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("miss_block",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("miss_r", "miss_dropout", "miss_mini_r") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.miss_r = {} + self.miss_dropout = nn.ModuleDict({}) + self.miss_mini_r = {} + self.miss_block = nn.ParameterDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + def update_layer( + self, + adapter_name: str, + r: int, + mini_r: int, + miss_dropout, + init_weights: bool | str, + inference_mode: bool = False, + **kwargs, + ) -> None: + """Internal function to create miss adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + init_weights (`bool`): Whether to initialize weights. + """ + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + + self.miss_r[adapter_name] = r + self.miss_mini_r[adapter_name] = mini_r + if miss_dropout > 0.0: + miss_dropout_layer = nn.Dropout(p=miss_dropout) + else: + miss_dropout_layer = nn.Identity() + + self.miss_dropout[adapter_name] = miss_dropout_layer + + # Determine shape of MiSS weights + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(r, self.out_features), requires_grad=True) + else: + raise TypeError(f"MiSS is not implemented for base layers of type {type(base_layer).__name__}") + + # Initialize weights + if init_weights == "bat": + if self.in_features % r != 0 or self.out_features % r != 0: + raise ValueError("The weight matrix must be fully divisible into [r, r] blocks.") + self.reset_bat_parameters(adapter_name, r) + elif init_weights == "mini": + if self.out_features % mini_r != 0: + raise ValueError( + "mini_r is divided along the out_features dimension. For optimal performance and implementation simplicity," + "it is recommended that out_features be divisible by mini_r." + "Error: {self.out_features} % mini_r != 0" + ) + self.reset_mini_parameters(adapter_name, r, mini_r) + elif init_weights: + self.reset_miss_parameters(adapter_name, r) + else: + self.reset_miss_parameters_random(adapter_name) + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_miss_parameters(self, adapter_name: str, r): + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(r, self.out_features), requires_grad=True) + + def reset_bat_parameters(self, adapter_name: str, r): + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(self.out_features // r, r, r), requires_grad=True) + + def reset_mini_parameters(self, adapter_name: str, r, mini_r): + self.miss_block[adapter_name] = nn.Parameter(torch.zeros(r, mini_r), requires_grad=True) + + def reset_miss_parameters_random(self, adapter_name: str): + nn.init.kaiming_uniform_(self.miss_block[adapter_name], a=math.sqrt(5)) + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.miss_block.keys(): + continue + + warnings.warn("Scaling operation for MiSS not supported! Automatically set scale to 1.") + + def unscale_layer(self, scale=None) -> None: + for active_adapter in self.active_adapters: + if active_adapter not in self.miss_block.keys(): + continue + + warnings.warn("Unscaling operation for MiSS not supported! Keeping scale at 1.") + + +class MissLinear(nn.Module, MissLayer): + """ + MiSS implemented in a dense layer. + """ + + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 0, + mini_r: int = 0, + miss_dropout: float = 0.0, + init_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + super().__init__() + MissLayer.__init__(self, base_layer, **kwargs) + self._active_adapter = adapter_name + self.update_layer(adapter_name, r, mini_r, miss_dropout, init_weights, **kwargs) + self.miss_fn = init_weights + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.miss_block.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + if self.miss_fn == "bat": + delta_weight = self.get_delta_weight(active_adapter, orig_weight) + orig_weight += delta_weight + elif self.miss_fn == "mini": + delta_weight = self.get_delta_weight_miss(active_adapter, self.base_layer.weight.data) + orig_weight = delta_weight + else: + delta_weight = self.get_delta_weight_miss(active_adapter, self.base_layer.weight.data) + orig_weight = delta_weight + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight.to(orig_dtype) + else: + if self.miss_fn == "bat": + delta_weight = self.get_delta_weight(active_adapter, self.base_layer.weight.data) + base_layer.weight.data += delta_weight.to(orig_dtype) + elif self.miss_fn == "mini": + delta_weight = self.get_delta_weight_miss(active_adapter, self.base_layer.weight.data) + base_layer.weight.data = delta_weight.to(orig_dtype) + else: + delta_weight = self.get_delta_weight_miss(active_adapter, self.base_layer.weight.data) + base_layer.weight.data = delta_weight.to(orig_dtype) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if active_adapter in self.miss_block.keys(): + orig_weight = self.get_base_layer().weight.data.clone() + if self.miss_fn == "bat": + delta_weight = self.get_delta_weight(active_adapter, orig_weight, re=True) + elif self.miss_fn == "mini": + delta_weight = self.get_delta_weight_miss(active_adapter, orig_weight, re=True) + else: + delta_weight = self.get_delta_weight_miss(active_adapter, orig_weight, re=True) + + base_layer.weight.data = delta_weight.to(orig_dtype) + + def get_delta_weight(self, adapter, orig_weight, re: bool = False) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.miss_block[adapter].device + dtype = self.miss_block[adapter].dtype + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_miss = self.miss_block[adapter] + + if cast_to_fp32: + weight_miss = weight_miss.float() + orig_weight = orig_weight.to(weight_miss.dtype) + + r = weight_miss.size(-1) + if re: + o = orig_weight.reshape(orig_weight.size(0) // r, r, orig_weight.size(1) // r, r).permute(2, 0, 1, 3) + one = torch.eye(weight_miss.size(-1)).to(weight_miss.device) + # inverse must be in float32, after that the dtype can be adjusted if needed + inv_I_plus_b = torch.inverse(one + weight_miss) + inv_I_plus_b = inv_I_plus_b.to(weight_miss.dtype) + w = (o - weight_miss) @ inv_I_plus_b + output_tensor = w.permute(1, 2, 0, 3).reshape(*orig_weight.shape) + else: + w = ( + orig_weight.reshape(orig_weight.size(0) // r, r, orig_weight.size(1) // r, r).permute(2, 0, 1, 3) + @ weight_miss + + weight_miss + ) + output_tensor = w.permute(1, 2, 0, 3).reshape(*orig_weight.shape) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.miss_block[adapter].data = weight_miss.to(dtype) + + return output_tensor + + def get_delta_weight_miss(self, adapter, orig_weight, re: bool = False) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.miss_block[adapter].device + dtype = self.miss_block[adapter].dtype + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + weight_miss = self.miss_block[adapter] + + if cast_to_fp32: + weight_miss = weight_miss.float() + + in_features = orig_weight.size(-1) + out_features = orig_weight.size(0) + r = weight_miss.size(0) + if self.miss_fn == "mini": + weight_miss = weight_miss.repeat(1, out_features // self.miss_mini_r[adapter]) + + if in_features % r != 0: + last_size = in_features % r + n_block = in_features // r + n_block_size = n_block * r + + if re: + orig_weight[:, :n_block_size] = ( + (orig_weight[:, :n_block_size].reshape(-1, n_block, r).permute(1, 2, 0) - weight_miss) + .permute(2, 0, 1) + .reshape(*orig_weight[:, :n_block_size].shape) + ) + orig_weight[:, n_block_size:] = ( + orig_weight[:, n_block_size:] - (weight_miss.transpose(0, 1))[:, :last_size] + ) + else: + orig_weight[:, :n_block_size] = ( + (orig_weight[:, :n_block_size].reshape(-1, n_block, r).permute(1, 2, 0) + weight_miss) + .permute(2, 0, 1) + .reshape(*orig_weight[:, :n_block_size].shape) + ) + orig_weight[:, n_block_size:] = ( + orig_weight[:, n_block_size:] + (weight_miss.transpose(0, 1))[:, :last_size] + ) + output_tensor = orig_weight + + else: + if re: + w = orig_weight.reshape(-1, orig_weight.size(1) // r, r).permute(1, 2, 0) - weight_miss + output_tensor = w.permute(2, 0, 1).reshape(*orig_weight.shape) + else: + w = orig_weight.reshape(-1, orig_weight.size(1) // r, r).permute(1, 2, 0) + weight_miss + output_tensor = w.permute(2, 0, 1).reshape(*orig_weight.shape) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + # cast back the weights + self.miss_block[adapter].data = weight_miss.to(dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + if self.miss_fn == "bat": + orig_weight = self.base_layer.weight.data.clone() + for active_adapter in self.active_adapters: + if active_adapter not in self.miss_block.keys(): + continue + delta_weight = self.get_delta_weight(active_adapter, orig_weight) + orig_weight = orig_weight + delta_weight + + x = self._cast_input_dtype(x, orig_weight.dtype) + bias = self._cast_input_dtype(self.base_layer.bias, orig_weight.dtype) + result = F.linear(input=x, weight=orig_weight, bias=bias) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.miss_block.keys(): + continue + miss = self.miss_block[active_adapter] + if self.miss_fn == "mini": + miss = miss.repeat(1, self.base_layer.out_features // self.miss_mini_r[active_adapter]) + + dropout = self.miss_dropout[active_adapter] + r = miss.size(0) + if x.size(-1) % r != 0: + padding_size = (r - x.size(-1) % r) % r + x = F.pad(x, (0, padding_size)) + x = self._cast_input_dtype(x, miss.dtype) + result = result + torch.sum(dropout(x).reshape(*x.shape[:-1], x.size(-1) // r, r), dim=-2) @ miss + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + # only 'bat' can be converted in a straightforward way + return self.miss_fn == "bat" + + def __repr__(self) -> str: + rep = super().__repr__() + return "miss." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/model.py new file mode 100644 index 0000000000000000000000000000000000000000..7dd6e655e181a0a3e495e1d38edf0d06c48d1e57 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/miss/model.py @@ -0,0 +1,130 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +import torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING + +from .layer import MissLayer, MissLinear + + +class MissModel(BaseTuner): + """ + Creates Householder reflection adaptation (MiSS) model from a pretrained model. The method is described in + https://huggingface.co/papers/2409.15371 + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`MissConfig`]): The configuration of the MiSS model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The MiSS model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import MissModel, MissConfig + + >>> config_te = MissConfig( + ... r=8, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... init_weights=True, + ... ) + >>> config_unet = MissConfig( + ... r=8, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... init_weights=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = MissModel(model.text_encoder, config_te, "default") + >>> model.unet = MissModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`MissConfig`]): The configuration of the MiSS model. + """ + + prefix: str = "miss_" + tuner_layer_cls = MissLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + miss_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": miss_config.r, + "mini_r": miss_config.mini_r, + "miss_dropout": miss_config.miss_dropout, + "init_weights": miss_config.init_weights, + } + kwargs["bias"] = bias + + # If it is not a MissLayer, create a new module, else update it with new adapters + if not isinstance(target, MissLayer): + new_module = self._create_new_module(miss_config, adapter_name, target, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + else: + target.update_layer( + adapter_name, + r=miss_config.r, + init_weights=miss_config.init_weights, + miss_dropout=miss_config.miss_dropout, + mini_r=miss_config.mini_r, + ) + + @staticmethod + def _create_new_module(miss_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + new_module = MissLinear(target, adapter_name, **kwargs) + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only `torch.nn.Linear` is supported." + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/mixed/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/mixed/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2955d7258ddcf76b47b38fd6fd5ebeb3d1d6110c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/mixed/__init__.py @@ -0,0 +1,18 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .model import COMPATIBLE_TUNER_TYPES, MixedModel + + +__all__ = ["COMPATIBLE_TUNER_TYPES", "MixedModel"] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/mixed/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/mixed/model.py new file mode 100644 index 0000000000000000000000000000000000000000..60a23cc929b4e588627d1a12f873a5d5470d2bdf --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/mixed/model.py @@ -0,0 +1,314 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Any, Optional, Union + +import torch +from torch import nn +from tqdm import tqdm + +from peft.tuners import adalora, loha, lokr, lora, oft, shira +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer, _delete_auxiliary_adapter +from peft.utils import ( + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + ModulesToSaveWrapper, + PeftType, + _get_submodules, + get_gptqmodel_quant_linear, +) +from peft.utils.other import _set_adapter + + +# Collection of constants used for all tuners +COMPATIBLE_TUNER_TYPES = (PeftType.LORA, PeftType.LOHA, PeftType.LOKR, PeftType.ADALORA, PeftType.OFT, PeftType.SHIRA) +PREFIXES = [ + lora.LoraModel.prefix, + lokr.LoKrModel.prefix, + loha.LoHaModel.prefix, + oft.OFTModel.prefix, + shira.ShiraModel.prefix, +] +Configs = Union[ + lora.LoraConfig, loha.LoHaConfig, lokr.LoKrConfig, adalora.AdaLoraConfig, oft.OFTConfig, shira.ShiraConfig +] +Layers = ( + lora.layer.LoraLayer, + loha.layer.LoHaLayer, + lokr.layer.LoKrLayer, + adalora.layer.AdaLoraLayer, + oft.OFTLayer, + shira.ShiraLayer, +) + + +class MixedModel(BaseTuner): + """ + A class that allows to mix different types of adapters in a single model. + + Note: This class should usually not be initialized directly. Instead, use `get_peft_model` with the argument + `mixed=True`. + + Args: + model (:obj:`nn.Module`): + The model to be tuned. + config (:obj:`PeftConfig`): + The config of the model to be tuned. The adapter type must be compatible. + adapter_name (:obj:`str`): + The name of the first adapter. + """ + + def __init__(self, model: nn.Module, config: Configs, adapter_name: str) -> None: + super().__init__(model, config, adapter_name) + + def _check_new_adapter_config(self, config: Configs) -> None: + """ + A helper method to check the config when a new adapter is being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + if not isinstance(config, Configs.__args__): + raise ValueError( + f"{self.__class__.__name__} only supports {COMPATIBLE_TUNER_TYPES} configs, but got {type(config)}." + ) + + super()._check_new_adapter_config(config) + + def _create_and_replace( + self, + config: Configs, + *args: Any, + **kwargs: Any, + ) -> None: + if isinstance(config, adalora.AdaLoraConfig): + adalora.AdaLoraModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, lora.LoraConfig): + lora.LoraModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, loha.LoHaConfig): + loha.LoHaModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, lokr.LoKrConfig): + lokr.LoKrModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, oft.OFTConfig): + oft.OFTModel._create_and_replace(self, config, *args, **kwargs) + elif isinstance(config, shira.ShiraConfig): + shira.ShiraModel._create_and_replace(self, config, *args, **kwargs) + else: + raise ValueError(f"Unsupported config type {type(config)}, should be one of {COMPATIBLE_TUNER_TYPES}.") + + def _replace_module(self, parent, child_name, new_module, child) -> None: + setattr(parent, child_name, new_module) + # It's not necessary to set requires_grad here, as that is handled by + # _mark_only_adapters_as_trainable + + # child layer wraps the original module, unpack it + if hasattr(child, "base_layer"): + child = child.get_base_layer() + elif hasattr(child, "quant_linear_module"): + # TODO maybe not necessary to have special treatment? + child = child.quant_linear_module + + if not hasattr(new_module, "base_layer"): + new_module.weight = child.weight + if hasattr(child, "bias"): + new_module.bias = child.bias + + if getattr(child, "state", None) is not None: + if hasattr(new_module, "base_layer"): + new_module.base_layer.state = child.state + else: + new_module.state = child.state + new_module.to(child.weight.device) + + meta = torch.device("meta") + # dispatch to correct device + for name, module in new_module.named_modules(): + if any(prefix in name for prefix in PREFIXES): + if hasattr(child, "qweight"): + weight = child.qweight + elif hasattr(child, "W_q"): + weight = child.W_q + elif hasattr(child, "weight"): + weight = child.weight + elif getattr(child, "in_proj_weight", None) is not None: # MHA + weight = child.in_proj_weight + else: + weight = next(child.parameters()) + + if not any(p.device == meta for p in module.parameters()): + module.to(weight.device) + + def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None: + for n, p in model.named_parameters(): + if not any(prefix in n for prefix in PREFIXES): + p.requires_grad = False + + for active_adapter in self.active_adapters: + bias = getattr(self.peft_config[active_adapter], "bias", "none") + if bias == "none": + continue + + if bias == "all": + for n, p in model.named_parameters(): + if "bias" in n: + p.requires_grad = True + elif bias == "lora_only": + # TODO: check if this is needed for other supported types + for m in model.modules(): + if isinstance(m, Layers) and hasattr(m, "bias") and m.bias is not None: + m.bias.requires_grad = True + else: + raise ValueError(f"Requested bias: {bias}, is not implemented.") + + @staticmethod + def _create_new_module(config, adapter_name, target, **kwargs): + gptq_quantization_config = kwargs.get("gptq_quantization_config", None) + GPTQQuantLinear = get_gptqmodel_quant_linear(gptq_quantization_config) + if (gptq_quantization_config is not None) or (GPTQQuantLinear is not None): + raise ValueError(f"GPTQ quantization not supported for {config.peft_type.value} (yet).") + + loaded_in_8bit = kwargs.pop("loaded_in_8bit", False) + loaded_in_4bit = kwargs.pop("loaded_in_4bit", False) + if loaded_in_8bit or loaded_in_4bit: + raise ValueError(f"8bit and 4bit quantization not supported for {config.peft_type.value} (yet).") + + if isinstance(config, adalora.AdaLoraConfig): + new_module = adalora.AdaLoraModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, lora.LoraConfig): + new_module = lora.LoraModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, loha.LoHaConfig): + new_module = loha.LoHaModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, lokr.LoKrConfig): + new_module = lokr.LoKrModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, oft.OFTConfig): + new_module = oft.OFTModel._create_new_module(config, adapter_name, target, **kwargs) + elif isinstance(config, shira.ShiraConfig): + new_module = shira.ShiraModel._create_new_module(config, adapter_name, target, **kwargs) + else: + raise ValueError(f"Unknown config type {type(config)}, should be one of {COMPATIBLE_TUNER_TYPES}.") + return new_module + + def set_adapter(self, adapter_name: Union[str, list[str]], inference_mode: bool = False) -> None: + _set_adapter(self, adapter_name, inference_mode=inference_mode) # handle auxiliary modules + for module in self.model.modules(): + if isinstance(module, Layers): + if module.merged: + warnings.warn("Adapter cannot be set when the model is merged. Unmerging the model first.") + module.unmerge() + module.set_adapter(adapter_name, inference_mode=inference_mode) + self.active_adapter = adapter_name + + @staticmethod + def _prepare_adapter_config(peft_config, model_config): + if peft_config.target_modules is None: + if model_config["model_type"] not in TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING: + raise ValueError("Please specify `target_modules` in `peft_config`") + + peft_config.target_modules = set( + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING[model_config["model_type"]] + ) + return peft_config + + def _unload_and_optionally_merge( + self, + merge=True, + progressbar: bool = False, + safe_merge: bool = False, + adapter_names: Optional[list[str]] = None, + ): + if merge: + if getattr(self.model, "quantization_method", None) == "gptq": + raise ValueError("Cannot merge layers when the model is gptq quantized") + + def merge_recursively(module): + # helper function to recursively merge the base_layer of the target + path = [] + layer = module + while hasattr(layer, "base_layer"): + path.append(layer) + layer = layer.base_layer + for layer_before, layer_after in zip(path[:-1], path[1:]): + layer_after.merge(safe_merge=safe_merge, adapter_names=adapter_names) + layer_before.base_layer = layer_after.base_layer + module.merge(safe_merge=safe_merge, adapter_names=adapter_names) + + key_list = [key for key, _ in self.model.named_modules() if not any(prefix in key for prefix in PREFIXES)] + desc = "Unloading " + ("and merging " if merge else "") + "model" + + for key in tqdm(key_list, disable=not progressbar, desc=desc): + try: + parent, target, target_name = _get_submodules(self.model, key) + except AttributeError: + continue + + if hasattr(target, "base_layer"): + if merge: + merge_recursively(target) + self._replace_module(parent, target_name, target.get_base_layer(), target) + elif isinstance(target, ModulesToSaveWrapper): + # save any additional trainable modules part of `modules_to_save` + new_module = target.modules_to_save[target.active_adapter] + if hasattr(new_module, "base_layer"): + # check if the module is itself a tuner layer + if merge: + new_module.merge(safe_merge=safe_merge, adapter_names=adapter_names) + new_module = new_module.get_base_layer() + setattr(parent, target_name, new_module) + + # Clean up peft_config from the model since all PEFT modules have been removed. + # This prevents spurious warnings when re-wrapping the model with get_peft_model(). + if hasattr(self.model, "peft_config"): + del self.model.peft_config + + return self.model + + def add_weighted_adapter(self, *args: Any, **kwargs: Any) -> None: + raise NotImplementedError(f"Weighted adapters are not supported for {self.__class__.__name__} (yet).") + + def delete_adapter(self, adapter_name: Union[str, list[str]]) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (Union[str, list[str]]): Name of the adapter(s) to delete. + """ + if isinstance(adapter_name, str): + adapter_names = [adapter_name] + else: + adapter_names = adapter_name + + mismatched = set(adapter_names) - set(self.peft_config.keys()) + if mismatched: + raise ValueError( + f"Adapter(s) {sorted(mismatched)} not found, available adapters: {sorted(self.peft_config.keys())}" + ) + + for adapter_name in adapter_names: + del self.peft_config[adapter_name] + + key_list = [key for key, _ in self.model.named_modules() if not any(prefix in key for prefix in PREFIXES)] + new_adapter = None + for key in key_list: + _, target, _ = _get_submodules(self.model, key) + if isinstance(target, BaseTunerLayer): + target.delete_adapter(adapter_name) + if new_adapter is None: + new_adapter = target.active_adapters[:] + + self.active_adapter = new_adapter or [] + _delete_auxiliary_adapter(self.model, adapter_name, new_active_adapters=new_adapter) + + def generate(self, *args: Any, **kwargs: Any): + return self.model.generate(*args, **kwargs) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fe692a93378254601753cc9b17218fdd5a92b8de --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/__init__.py @@ -0,0 +1,25 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import MultitaskPromptTuningConfig, MultitaskPromptTuningInit +from .model import MultitaskPromptEmbedding + + +__all__ = ["MultitaskPromptEmbedding", "MultitaskPromptTuningConfig", "MultitaskPromptTuningInit"] + +register_peft_method( + name="multitask_prompt_tuning", config_cls=MultitaskPromptTuningConfig, model_cls=MultitaskPromptEmbedding +) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6cb279573559e4fa33a973aa35e052647a6ab8f9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/config.py @@ -0,0 +1,62 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.tuners.prompt_tuning import PromptTuningConfig +from peft.utils import PeftType + + +class MultitaskPromptTuningInit(str, enum.Enum): + # initialize prompt with text + TEXT = "TEXT" + # initialize prompt with random matrix + RANDOM = "RANDOM" + # average the prefix and column matrices obtained during source training + AVERAGE_SOURCE_TASKS = "AVERAGE_SOURCE_TASKS" + # pick prefix and column matrices for a particular task obtained during source training + EXACT_SOURCE_TASK = "EXACT_SOURCE_TASK" + # only use the prompt embeddings trained during source training + ONLY_SOURCE_SHARED = "ONLY_SOURCE_SHARED" + + +@dataclass +class MultitaskPromptTuningConfig(PromptTuningConfig): + prompt_tuning_init: Union[MultitaskPromptTuningInit, str] = field( + default=MultitaskPromptTuningInit.RANDOM, + metadata={ + "help": ( + "How to initialize the prompt tuning parameters. Can be one of TEXT, RANDOM, AVERAGE_SOURCE_TASKS, " + "EXACT_SOURCE_TASK, ONLY_SOURCE_SHARED." + ), + }, + ) + prompt_tuning_init_state_dict_path: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The path of source state dict. This is required when training the downstream target prompt from " + "the pretrained source prompt" + ), + }, + ) + prompt_tuning_init_task: Optional[int] = field(default=0, metadata={"help": "source task id for initialization"}) + num_ranks: Optional[int] = field(default=1, metadata={"help": "ranks"}) + num_tasks: Optional[int] = field(default=1, metadata={"help": "number of tasks"}) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.MULTITASK_PROMPT_TUNING diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..20d9d498f48c4f3bc7087c38b4f8072d8de66637 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/multitask_prompt_tuning/model.py @@ -0,0 +1,120 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch + +from peft.tuners.prompt_tuning import PromptEmbedding +from peft.utils import TaskType +from peft.utils.save_and_load import torch_load + +from .config import MultitaskPromptTuningConfig, MultitaskPromptTuningInit + + +# This code is adapted for the paper: https://huggingface.co/papers/2303.02861 and +# constitutes the work done at MIT-IBM Watson Research Lab. + + +class MultitaskPromptEmbedding(PromptEmbedding): + def __init__(self, config: MultitaskPromptTuningConfig, word_embeddings): + super().__init__(config, word_embeddings) + + self.num_tasks = config.num_tasks + self.num_ranks = config.num_ranks + self.num_virtual_tokens = config.num_virtual_tokens + + self.num_transformer_submodules = config.num_transformer_submodules + if self.num_transformer_submodules is None: + self.num_transformer_submodules = 2 if config.task_type == TaskType.SEQ_2_SEQ_LM else 1 + + self.token_dim = config.token_dim + + total_virtual_tokens = self.num_virtual_tokens * self.num_transformer_submodules + + self.prefix_task_cols = torch.nn.Parameter( + torch.normal( + mean=0, + std=0.02, + size=(self.num_tasks, total_virtual_tokens, self.num_ranks), + ) + ) + self.prefix_task_rows = torch.nn.Parameter( + torch.normal( + mean=0, + std=0.02, + size=(self.num_tasks, self.num_ranks, self.token_dim), + ) + ) + + if config.prompt_tuning_init in [ + MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS, + MultitaskPromptTuningInit.EXACT_SOURCE_TASK, + MultitaskPromptTuningInit.ONLY_SOURCE_SHARED, + ]: + if config.prompt_tuning_init_state_dict_path is None: + raise ValueError( + f"prompt_tuning_init_state_dict_path needs to be specified with {config.prompt_tuning_init} " + "init method" + ) + + if config.prompt_tuning_init_state_dict_path.endswith(".safetensors"): + from safetensors.torch import load_file + + state_dict: dict = load_file(config.prompt_tuning_init_state_dict_path) + else: + state_dict: dict = torch_load( + config.prompt_tuning_init_state_dict_path, + map_location=word_embeddings.weight.device, + ) + + if config.prompt_tuning_init in [ + MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS, + MultitaskPromptTuningInit.EXACT_SOURCE_TASK, + ]: + prefix_task_cols_: torch.Tensor = state_dict["prefix_task_cols"] + prefix_task_rows_: torch.Tensor = state_dict["prefix_task_rows"] + + if config.prompt_tuning_init == MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS: + prefix_task_cols_ = prefix_task_cols_.mean(0, keepdim=True) + prefix_task_rows_ = prefix_task_rows_.mean(0, keepdim=True) + elif config.prompt_tuning_init == MultitaskPromptTuningInit.EXACT_SOURCE_TASK: + prefix_task_cols_ = prefix_task_cols_[config.prompt_tuning_init_task, ...].unsqueeze(0) + prefix_task_rows_ = prefix_task_rows_[config.prompt_tuning_init_task, ...].unsqueeze(0) + + state_dict = { + "embedding.weight": state_dict["prompt_embeddings"], + "prefix_task_cols": prefix_task_cols_, + "prefix_task_rows": prefix_task_rows_, + } + + self.load_state_dict(state_dict, strict=True) + elif config.prompt_tuning_init == MultitaskPromptTuningInit.ONLY_SOURCE_SHARED: + state_dict = { + "embedding.weight": state_dict["prompt_embeddings"], + } + + self.load_state_dict(state_dict, strict=False) + + def forward(self, indices, task_ids): + if task_ids is None: + raise ValueError("task_ids cannot be None") + + prompt_embeddings = self.embedding(indices) + + task_cols = torch.index_select(self.prefix_task_cols, 0, task_ids) + task_rows = torch.index_select(self.prefix_task_rows, 0, task_ids) + task_prompts = torch.matmul(task_cols, task_rows) + + prompt_embeddings *= task_prompts + + return prompt_embeddings diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..32e21e32f64b02315731642542cf0bf31227d7a4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/__init__.py @@ -0,0 +1,52 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_eetq_available +from peft.utils import register_peft_method + +from .config import OFTConfig +from .gptq import GPTQOFTLinear +from .layer import Conv2d, Linear, OFTLayer +from .model import OFTModel + + +__all__ = [ + "Conv2d", + "GPTQOFTLinear", + "Linear", + "OFTConfig", + "OFTLayer", + "OFTModel", +] + +register_peft_method(name="oft", config_cls=OFTConfig, model_cls=OFTModel) + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + if (name == "EetqOFTLinear") and is_eetq_available(): + from .eetq import EetqOFTLinear + + return EetqOFTLinear + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/aqlm.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/aqlm.py new file mode 100644 index 0000000000000000000000000000000000000000..d455d2fe4149be2d78e8386c1aee668de4a74829 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/aqlm.py @@ -0,0 +1,105 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Any, Optional + +import torch + +from peft.import_utils import is_aqlm_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +if is_aqlm_available(): + from aqlm import QuantizedLinear + + +class AqlmOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 0, + oft_block_size: int = 32, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + init_weights=init_weights, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + if self.disable_adapters: + return self.base_layer(x) + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + + result = self.base_layer(x) + if requires_conversion: + result = result.to(expected_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_aqlm( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_aqlm_available() and isinstance(target_base_layer, QuantizedLinear): + new_module = AqlmOFTLinear(target, adapter_name, **kwargs) + target.qweight = target_base_layer.codes + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/awq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/awq.py new file mode 100644 index 0000000000000000000000000000000000000000..9629d20dd49113fb250a8ca0923be4b241bde9eb --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/awq.py @@ -0,0 +1,107 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_gptqmodel_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +class AwqOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name, + r: int = 0, + oft_block_size: int = 32, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: bool = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + if self.disable_adapters: + result = self.quant_linear_module(x) + return result + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.quant_linear_module(x) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_awq( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_gptqmodel_available(): + from gptqmodel.nn_modules.qlinear.gemm_awq import AwqGEMMQuantLinear + + if isinstance(target_base_layer, AwqGEMMQuantLinear): + new_module = AwqOFTLinear(target, adapter_name, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..a5da56279bac877da807faacbb74121fb10e3875 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/bnb.py @@ -0,0 +1,388 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight + +from .layer import OFTLayer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, OFTLayer): + # OFT implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Merge oft module to 8-bit linear may get different generations due to rounding errors.") + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8 + # dequantization directly + output = dequantize_bnb_weight(weight, state=state) + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data, output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.oft_R.keys(): + continue + warnings.warn( + "Unmerge oft module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = w_data.to(oft_data.dtype).to(oft_data.device) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + state.reset_grads() + + def get_delta_weight(self, adapter): + return self.oft_R[adapter].get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.base_layer(x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target.state.has_fp16_weights, + "threshold": target.state.threshold, + "index": target.index, + } + ) + new_module = Linear8bitLt(target, adapter_name, **eightbit_kwargs) + + return new_module + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, OFTLayer): + # OFT implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + init_weights: bool = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Merge oft module to 4-bit linear may get different generations due to rounding errors.") + # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930 + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + oft_data = self.get_delta_weight(active_adapter) + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data, output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.oft_R.keys(): + continue + warnings.warn( + "Unmerge oft module to 4-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + def get_delta_weight(self, adapter): + return self.oft_R[adapter].get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + # As per Tim Dettmers, for 4bit, we need to defensively clone here. + # The reason is that in some cases, an error can occur that backprop + # does not work on a manipulated view. This issue may be solved with + # newer PyTorch versions but this would need extensive testing to be + # sure. + # result = result.clone() + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.base_layer(x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + new_module = Linear4bit(target, adapter_name, **fourbit_kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9c62e1becea23cd3ca0f0d568f8c176d96c70a78 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/config.py @@ -0,0 +1,213 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +import packaging.version + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class OFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`OFTModel`]. + + Args: + r (`int`): OFT rank, number of OFT blocks per injected layer. + oft_block_size (`int`): OFT block size across different layers. + module_dropout (`float`): + The multiplicative dropout probability, by setting OFT blocks to identity during training, similar to the + dropout layer in LoRA. + target_modules (`Optional[Union[list[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear modules are chosen, excluding + the output layer. If this is not specified, modules will be chosen according to the model architecture. If + the architecture is not known, an error will be raised -- in this case, you should specify the target + modules manually. + fan_in_fan_out (`bool`): Set this to True if the layer to replace stores weight like (fan_in, fan_out). + bias (`str`): Bias type for OFT. Can be 'none', 'all' or 'oft_only'. If 'all' or 'oft_only', the + corresponding biases will be updated during training. Be aware that this means that, even when disabling + the adapters, the model will not produce the same output as the base model would have without adaptation. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + init_weights (`bool`): + Whether to perform initialization of OFT weights. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + coft (`bool`): + Whether to use the constrained variant of OFT or not, off by default. + eps (`float`): + The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True. + block_share (`bool`): + Whether to share the OFT parameters between blocks or not. This is `False` by default. + """ + + r: int = field(default=0, metadata={"help": "OFT rank, number of OFT blocks per injected layer."}) + oft_block_size: int = field( + default=32, + metadata={ + "help": "OFT block size across different layers.", + "note": "You can only specify either r or oft_block_size, but not both simultaneously, because r x oft_block_size = layer dimension.", + }, + ) + module_dropout: float = field( + default=0.0, + metadata={ + "help": "OFT multiplicative dropout, randomly setting blocks of OFT to be identity matrix, similar to the dropout layer in LoRA." + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with OFT." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer." + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + bias: Literal["none", "all", "oft_only"] = field( + default="none", metadata={"help": "Bias type for OFT. Can be 'none', 'all' or 'oft_only'"} + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from OFT."}, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the OFT layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. " + "This should target the `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from OFT layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + coft: bool = field( + default=False, + metadata={"help": "Whether to use the constrained variant of OFT or not."}, + ) + eps: float = field( + default=6e-5, + metadata={ + "help": "The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True." + }, + ) + block_share: bool = field( + default=False, + metadata={"help": "Whether to share the OFT parameters between blocks or not."}, + ) + use_cayley_neumann: bool = field( + default=True, + metadata={ + "help": "Whether to use the Cayley-Neumann Formulation of OFT or not. Set to True to improve computational efficiency but comes at costs of bigger approximation error for orthogonality." + }, + ) + num_cayley_neumann_terms: int = field( + default=5, + metadata={ + "help": "Number of Cayley-Neumann terms to use. Higher number results in less approximation error for orthogonality." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.OFT + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + if self.r == 0 and self.oft_block_size == 0: + raise ValueError( + f"Either `r` or `oft_block_size` must be non-zero. Currently, r = {self.r} and oft_block_size = {self.oft_block_size}." + ) + if not (self.r != 0) ^ (self.oft_block_size != 0): + raise ValueError( + f"You can only specify either r ({self.r}) or oft_block_size ({self.oft_block_size}), but not both simultaneously, because r x oft_block_size == in_features." + ) + + @classmethod + def check_kwargs(cls, **kwargs): + r""" + Check if the kwargs are valid for the configuration. + + Args: + kwargs (additional keyword arguments, *optional*): + Additional keyword arguments passed along to the child class initialization. + """ + if "oft_block_size" not in kwargs: + raise ValueError( + "OFT has been updated since PEFT 0.14.0. Your trained adapter weights are incompatible " + "with the latest version of OFT. Please retrain your adapter weights with newer PEFT versions. " + "Alternatively, downgrade PEFT to version 0.13.0 to use the old adapter weights." + ) + if kwargs.get("use_cayley_neumann", False): + peft_version = kwargs.get("peft_version", "0.0.0") # if not present, set a low dummy version + # remove commit hash, if present + peft_version = peft_version.partition("@")[0] + parsed_version = packaging.version.Version(peft_version) + min_version = packaging.version.Version("0.18.0") + # note: config.peft_version was added in 0.18.0, so if it's missing, it means we're below min version + if parsed_version < min_version: + msg = ( + "The cayley-neumann parameterization has been slightly changed to be more numerically stable in " + "PEFT 0.18.0. Please retrain your adapter weights with newer PEFT versions. Alternatively, " + "downgrade PEFT to version 0.17.0 to use the old parameterization." + ) + warnings.warn(msg) + return super().check_kwargs(**kwargs) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/eetq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/eetq.py new file mode 100644 index 0000000000000000000000000000000000000000..2d6538165a4f040617e68ff1bceca494f112c3e5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/eetq.py @@ -0,0 +1,116 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_eetq_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +if is_eetq_available(): + from eetq import EetqLinear + + class EetqOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name, + r: int = 0, + oft_block_size: int = 0, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + init_weights=init_weights, + coft=coft, + eps=eps, + block_share=block_share, + fan_in_fan_out=fan_in_fan_out, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + if self.disable_adapters: + return self.quant_linear_module(x) + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + + result = self.quant_linear_module(x) + if requires_conversion: + result = result.to(expected_dtype) + return result + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + raise AttributeError("Merging LoRA layers is not supported for Eetq layers.") + + def unmerge(self) -> None: + raise AttributeError("Unmerging LoRA layers is not supported for Eetq layers.") + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_eetq( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_eetq_available() and isinstance(target_base_layer, EetqLinear): + new_module = EetqOFTLinear(target, adapter_name, **kwargs) + target.weight = target_base_layer.weight + + if hasattr(target, "bias"): + target.bias = target_base_layer.bias + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/gptq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/gptq.py new file mode 100644 index 0000000000000000000000000000000000000000..df6c03b9bd86205a47eb3fe0b7ce3c904ffd185c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/gptq.py @@ -0,0 +1,106 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from typing import Any, Optional + +import torch + +from peft.import_utils import is_gptqmodel_available +from peft.tuners.oft.layer import OFTLayer +from peft.tuners.tuners_utils import BaseTunerLayer + + +class GPTQOFTLinear(torch.nn.Module, OFTLayer): + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: bool = True, + **kwargs, + ): + super().__init__() + OFTLayer.__init__(self, base_layer) + + # self.base_layer and self.quant_linear_module are the same; we need the former for consistency and the latter + # for backwards compatibility + self.quant_linear_module = base_layer + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def forward(self, x: torch.Tensor): + # note: logic differs from default Linear because merging is not supported + if self.disable_adapters: + return self.quant_linear_module(x) + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + oft_R = self.oft_R[active_adapter] + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + if requires_conversion: + x = x.to(expected_dtype) + + result = self.quant_linear_module(x) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_gptq( + target: torch.nn.Module, + adapter_name: str, + **kwargs: Any, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_gptqmodel_available(): + from gptqmodel.nn_modules.qlinear import BaseQuantLinear + + if isinstance(target_base_layer, BaseQuantLinear): + new_module = GPTQOFTLinear(target, adapter_name, **kwargs) + target.qweight = target_base_layer.qweight + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/hqq.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/hqq.py new file mode 100644 index 0000000000000000000000000000000000000000..5f83dd11b0bb4f4c349dd1beb95733b5e617c158 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/hqq.py @@ -0,0 +1,186 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +import warnings +from typing import Optional + +import torch + +from peft.import_utils import is_hqq_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .layer import OFTLayer + + +if is_hqq_available(): + from hqq.core.quantize import HQQLinear + + class HqqOFTLinear(torch.nn.Module, OFTLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + init_weights: bool = True, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = False + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + init_weights=init_weights, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter not in self.lora_A.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + + output = layer.dequantize() + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data, output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = output.to(oft_data.dtype).to(oft_data.device) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.oft_R.keys(): + continue + + layer = self.get_base_layer() + quant_config = {**copy.deepcopy(layer.quant_config), "offload_meta": layer.offload_meta} + output = layer.dequantize() + + oft_data = self.get_delta_weight(active_adapter) + + output = torch.transpose(output, 0, 1) + w_data = torch.mm(oft_data.t(), output.to(oft_data.dtype)) + w_data = torch.transpose(w_data, 0, 1) + w_data = w_data.to(oft_data.dtype).to(oft_data.device) + + new_hqq_layer = HQQLinear(None, quant_config, compute_dtype=layer.compute_dtype, device=layer.device) + quant_config.pop("offload_meta", None) + new_hqq_layer.quantize(w_data, **quant_config) + self.base_layer = new_hqq_layer + + def get_delta_weight(self, adapter): + return self.oft_R[adapter].get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = x.dtype + x = self._cast_input_dtype(x, oft_R.weight.dtype) + + x = oft_R(x) + + result = self.base_layer(x, *args, **kwargs) + if requires_conversion: + result = result.to(expected_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_hqq(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_hqq_available() and isinstance(target_base_layer, HQQLinear): + new_module = HqqOFTLinear(target_base_layer, adapter_name, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/inc.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/inc.py new file mode 100644 index 0000000000000000000000000000000000000000..6ed855bc7dc65af10d77a2f486abb8fc27c12dd5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/inc.py @@ -0,0 +1,78 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# NOTE: PEFT tests related to INC are handled under Optimum-Habana repository: +# - LLMs: https://github.com/huggingface/optimum-habana/blob/main/tests/test_peft_inference.py +# - Diffusers: https://github.com/huggingface/optimum-habana/blob/main/tests/test_diffusers.py + +from typing import Optional + +import torch + +from peft.import_utils import is_inc_available +from peft.tuners.tuners_utils import BaseTunerLayer + +from .layer import Linear + + +if is_inc_available(): + + class IncOFTLinear(Linear): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + **kwargs, + ): + super().__init__(base_layer, adapter_name, **kwargs) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + raise NotImplementedError("Merging OFT with INC layers is not yet implemented") + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + raise NotImplementedError("Unmerging OFT from INC layers is not yet implemented") + + +def dispatch_inc(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if is_inc_available(): + from neural_compressor.torch.algorithms.fp8_quant._quant_common.helper_modules import ( + PatchedLinear, + ) + + if isinstance(target_base_layer, PatchedLinear): + new_module = IncOFTLinear(target, adapter_name, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..7653dd3d6075d11b9f0fd5bc9a9914c80d1b4105 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/layer.py @@ -0,0 +1,1229 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import OFTConfig + + +class MultiplicativeDropoutLayer(nn.Module): + """ + Implements the multiplicative dropout layer for OFT. + """ + + def __init__(self, p=0.0): + """ + Initializes the multiplicative dropout layer. + + Parameters: + p (float): The probability of dropping out a block. Defaults to 0.0. + """ + super().__init__() + self.p = p + + def forward(self, x): + """ + Applies multiplicative dropout to the input tensor. + + Parameters: + x (Tensor): The input tensor of shape (D, H, H), where `D` represents + the number of OFT blocks, and `H` is the size of the square blocks along the last two dimensions, + the block size in OFT. + """ + if self.training and self.p > 0: + # Ensure the last two dimensions are the same + if x.shape[-1] != x.shape[-2]: + raise ValueError("The last two dimensions of input should be the same!") + + D, H, _ = x.shape + + # If block share, skip the multiplicative dropout + if D == 1: + return x + + num_to_replace = int(self.p * D) + num_zeros = D - num_to_replace + mask = torch.cat([torch.ones(num_to_replace, device=x.device), torch.zeros(num_zeros, device=x.device)]) + mask = mask[torch.randperm(D)].view(D, 1, 1) + eye_matrix = torch.eye(H, device=x.device).repeat(D, 1, 1) + x = (1 - mask) * x + mask * eye_matrix + return x + + +class OFTRotationModule(nn.Module): + def __init__( + self, + r, + n_elements, + block_size, + in_features, + coft=False, + eps=6e-5, + block_share=False, + kernel_size=(0, 0), + use_cayley_neumann=True, + num_cayley_neumann_terms=5, + ): + super().__init__() + self.r = r + self.n_elements = n_elements + self.block_size = block_size + self.in_features = in_features + self.weight = nn.Parameter(torch.empty(r, n_elements)) + self.coft = coft + self.eps = eps + self.block_share = block_share + # Conv2d specific parameters + self.kernel_size = kernel_size + self.use_cayley_neumann = use_cayley_neumann + self.num_cayley_neumann_terms = num_cayley_neumann_terms + # Create indices for upper triangle (excluding diagonal) + rows, cols = torch.triu_indices(block_size, block_size, 1) + self.register_buffer("rows", rows, persistent=False) + self.register_buffer("cols", cols, persistent=False) + + def _pytorch_skew_symmetric(self, vec, block_size): + batch_size = vec.shape[0] + matrix = torch.zeros(batch_size, block_size, block_size, device=vec.device, dtype=vec.dtype) + + matrix[:, self.rows, self.cols] = vec + matrix = matrix - matrix.transpose(-2, -1) + return matrix + + def _pytorch_skew_symmetric_inv(self, matrix, block_size): + batch_size = matrix.shape[0] + + # Extract the upper triangular elements + vec = matrix[:, self.rows, self.cols] + return vec + + def _cayley_batch( + self, Q: torch.Tensor, block_size: int, use_cayley_neumann: bool = True, num_neumann_terms: int = 5 + ) -> torch.Tensor: + """ + Perform the Cayley parametrization on a batch of skew-symmetric matrices. + + Args: + data: A batch of skew-symmetric matrices of shape (b, r, c). + """ + + b, _ = Q.shape + previous_dtype = Q.dtype + + # Q_skew = SkewSymmetric.apply(Q, block_size) + Q_skew = self._pytorch_skew_symmetric(Q, block_size) + + if use_cayley_neumann: + R = torch.eye(block_size, device=Q.device, dtype=Q.dtype).repeat(b, 1, 1) + if num_neumann_terms > 1: + R.add_(Q_skew, alpha=2.0) + if num_neumann_terms > 2: + Q_squared = torch.bmm(Q_skew, Q_skew) + R.add_(Q_squared, alpha=2.0) + + Q_power = Q_squared + for _ in range(3, num_neumann_terms - 1): + Q_power = torch.bmm(Q_power, Q_skew) + R.add_(Q_power, alpha=2.0) + Q_power = torch.bmm(Q_power, Q_skew) + R.add_(Q_power) + else: + id_mat = ( + torch.eye(Q_skew.shape[-1], device=Q_skew.device) + .unsqueeze(0) + .expand(b, Q_skew.shape[-1], Q_skew.shape[-1]) + ) + R = torch.linalg.solve(id_mat + Q_skew, id_mat - Q_skew, left=False) + + return R.to(previous_dtype) + + # Copied from https://github.com/Zeju1997/oft/blob/84cebb965df69781e3d9c3c875f5980b421eaf24/oft-control/oft.py#L52 + def _project_batch(self, Q, eps=1e-5): + oft_R = self._pytorch_skew_symmetric(Q, self.block_size) + # scaling factor for each of the smaller block matrix + eps = eps * 1 / torch.sqrt(torch.tensor(oft_R.shape[0])) + I = ( # noqa: E741 + torch.zeros((oft_R.size(1), oft_R.size(1)), device=oft_R.device, dtype=oft_R.dtype) + .unsqueeze(0) + .expand_as(oft_R) + ) + diff = oft_R - I + norm_diff = torch.norm(oft_R - I, dim=(1, 2), keepdim=True) + mask = (norm_diff <= eps).bool() + out = torch.where(mask, oft_R, I + eps * (diff / norm_diff)) + + return self._pytorch_skew_symmetric_inv(out, self.block_size) + + # Copied from https://github.com/Zeju1997/oft/blob/84cebb965df69781e3d9c3c875f5980b421eaf24/oft-control/oft.py#L155 + def _block_diagonal(self, oft_R: torch.Tensor, rank: int) -> torch.Tensor: + if oft_R.shape[0] == 1: + # block share + blocks = [oft_R[0, ...] for i in range(rank)] + else: + blocks = [oft_R[i, ...] for i in range(rank)] + + # Use torch.block_diag to create the block diagonal matrix + A = torch.block_diag(*blocks) + + return A + + def _unfold(self, x): + """ + Unfold with stride=1, padding=0 to preserve spatial dimensions. Only use kernel_size from base layer to define + patch size. + """ + batch_size, in_channels, in_height, in_width = x.shape + + if isinstance(self.kernel_size, int): + kernel_height, kernel_width = self.kernel_size, self.kernel_size + else: + kernel_height, kernel_width = self.kernel_size + + stride_h = stride_w = 1 + pad_h = pad_w = 0 + + # output dimensions + out_height = (in_height + 2 * pad_h - kernel_height) // stride_h + 1 + out_width = (in_width + 2 * pad_w - kernel_width) // stride_w + 1 + + # Reshape input from [B, C, H, W] to [B, C, H_out, W_out, K_H, K_W] + x_unfolded = x.unfold(2, kernel_height, stride_h).unfold(3, kernel_width, stride_w) + x_unfolded = x_unfolded.permute(0, 2, 3, 1, 4, 5).contiguous() + x_unfolded = x_unfolded.view(batch_size * out_height * out_width, -1) + + return x_unfolded + + def _fold(self, x_unfolded, orig_shape): + """ + Fold back to preserve spatial dimensions. + """ + batch_size, in_channels, in_height, in_width = orig_shape + + if isinstance(self.kernel_size, int): + kernel_height, kernel_width = self.kernel_size, self.kernel_size + else: + kernel_height, kernel_width = self.kernel_size + + # With stride=1, padding=0: + out_height = in_height - kernel_height + 1 + out_width = in_width - kernel_width + 1 + + # Reshape: [B*H_out*W_out, C*K_H*K_W] -> [B, H_out, W_out, C, K_H, K_W] + x_reshaped = x_unfolded.view(batch_size, out_height, out_width, in_channels, kernel_height, kernel_width) + + # Permute to: [B, C, H_out, W_out, K_H, K_W] + x_reshaped = x_reshaped.permute(0, 3, 1, 2, 4, 5).contiguous() + + # Use F.fold to reconstruct 4D tensor + x_folded = F.fold( + x_reshaped.view(batch_size, in_channels * kernel_height * kernel_width, out_height * out_width), + output_size=(in_height, in_width), + kernel_size=(kernel_height, kernel_width), + stride=(1, 1), + ) + + return x_folded + + def forward(self, x): + # This module doesn't need to implement the orthogonal transform + # It's primarily a container for the parameter + # The actual transformation logic stays in your OFTLayer + + required_dtype = x.dtype + if required_dtype != self.weight.dtype: + x = x.to(self.weight.dtype) + + orig_shape = x.shape + + if self.coft: + with torch.no_grad(): + self.weight.copy_(self._project_batch(self.weight, eps=self.eps)) + + orth_rotate = self._cayley_batch( + self.weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms + ) + + # Unfold the input for Conv2d layer + if len(orig_shape) == 4: + x = self._unfold(x) + + folded_shape = x.shape + rank = self.in_features // self.block_size if self.block_share else self.r + batch_dims = x.shape[:-1] + x_reshaped = x.reshape(*batch_dims, rank, self.block_size) + + if self.block_share: + orth_rotate = orth_rotate.repeat(rank, 1, 1) + x_rotated_reshaped = torch.einsum("...rk,rkc->...rc", x_reshaped, orth_rotate) + else: + x_rotated_reshaped = torch.einsum("...rk,rkc->...rc", x_reshaped, orth_rotate) + + x_rotated = x_rotated_reshaped.reshape(*folded_shape) + + if len(orig_shape) == 4: + x_rotated = self._fold(x_rotated, orig_shape) + + return x_rotated.to(required_dtype) + + def get_weight(self): + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + weight = self.weight + + if self.coft: + with torch.no_grad(): + weight = self._project_batch(weight, eps=self.eps) + self.weight.copy_(weight) + + orth_rotate = self._cayley_batch( + weight, self.block_size, self.use_cayley_neumann, self.num_cayley_neumann_terms + ) + + rank = self.r if not self.block_share else self.in_features // self.block_size + return self._block_diagonal(orth_rotate, rank) + + +class OFTLayer(BaseTunerLayer): + """ + Implements the OFT layer. + """ + + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("oft_R", "oft_embedding_R") + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("r", "oft_block_size", "oft_dropout") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + """ + Initializes the OFT layer. + + Note, currently only support linear layer and convolutional layer, with further support for other layers to be + added soon. + + Parameters: + base_layer: the pretrained model layer + """ + self.base_layer = base_layer + self.oft_R = nn.ModuleDict({}) + # For Embedding layer + self.oft_embedding_R = nn.ModuleDict({}) + self.oft_block_size = {} + self.r = {} + self.oft_block_size = {} + self.oft_dropout = nn.ModuleDict({}) + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, nn.Conv2d): + in_features, out_features = base_layer.in_channels, base_layer.out_channels + elif isinstance(base_layer, nn.Embedding): + in_features, out_features = base_layer.embedding_dim, base_layer.num_embeddings + elif hasattr(base_layer, "infeatures") and hasattr(base_layer, "outfeatures"): + # QuantLinear + in_features, out_features = base_layer.infeatures, base_layer.outfeatures + elif hasattr(base_layer, "input_size") and hasattr(base_layer, "output_size"): + # Megatron ColumnParallelLinear,RowParallelLinear + in_features, out_features = base_layer.input_size, base_layer.output_size + elif hasattr(base_layer, "codebooks") and base_layer.__class__.__name__ == "QuantizedLinear": + # AQLM QuantLinear + in_features, out_features = base_layer.in_features, base_layer.out_features + elif hasattr(base_layer, "bits") and base_layer.__class__.__name__ == "AwqGEMMQuantLinear": + # Awq layers + in_features, out_features = base_layer.in_features, base_layer.out_features + elif base_layer.__class__.__name__ == "EetqLinear": + # Eetq layers + in_features, out_features = base_layer.in_features, base_layer.out_features + elif hasattr(base_layer, "W_q") and base_layer.__class__.__name__ == "HQQLinear": + # HQQ layers + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + # possibly support user provided custom layer types using dynamic dispatch + if hasattr(base_layer, "in_features") and hasattr(base_layer, "out_features"): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + in_features, out_features = None, None + warnings.warn( + f"Unsupported layer type '{type(base_layer)}' encountered, proceed at your own risk.", UserWarning + ) + + self.in_features = in_features + self.out_features = out_features + + def set_scale(self, adapter, scale): + if adapter not in self.scaling: + # Ignore the case where the adapter is not in the layer + return + + warnings.warn("Scaling operation for OFT not supported! Automatically set scale to 1.") + + def scale_layer(self, scale: float) -> None: + if scale == 1: + return + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Scaling operation for OFT not supported! Automatically set scale to 1.") + + def unscale_layer(self, scale=None) -> None: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + warnings.warn("Unscaling operation for OFT not supported! Keeping scale to 1.") + + def update_layer( + self, + adapter_name, + r, + oft_block_size, + module_dropout, + coft, + eps, + block_share, + init_weights, + use_cayley_neumann, + num_cayley_neumann_terms, + inference_mode: bool = False, + **kwargs, + ): + """ + Update the linear layer with trainable OFT weights. Override for other layer types. + """ + """Internal function to create oft adapter + + Args: + adapter_name (`str`): Name for the adapter to add. + r (`int`): Rank for the added adapter. + oft_block_size (`int`): The block size for added adapter. + module_dropout (`float`): + The multiplicative dropout probability for disabling adapter blocks during training. + coft (`bool`): Whether to use the constrained variant of OFT or not. + eps (`float`): + The control strength of COFT. The freedom of rotation. Only has an effect if `coft` is set to True. + block_share (`bool`): Whether to share the OFT parameters between blocks or not. + init_weights (`bool`): Whether to initialize weights. + """ + # Initialize the MultiplicativeDropoutLayer for module_dropout > 0.0. + if module_dropout > 0.0: + oft_dropout_layer = MultiplicativeDropoutLayer(p=module_dropout) + else: + oft_dropout_layer = nn.Identity() + self.oft_dropout.update(nn.ModuleDict({adapter_name: oft_dropout_layer})) + + if r == 0 and oft_block_size != 0: + if self.in_features % oft_block_size != 0 or oft_block_size > self.in_features: + old_oft_block_size = oft_block_size + oft_block_size = self.adjust_oft_parameters(self.in_features, oft_block_size) + warnings.warn( + f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})." + ) + r = int(self.in_features // oft_block_size) + elif r != 0 and oft_block_size == 0: + if self.in_features % r != 0 or r > self.in_features: + old_r = r + r = self.adjust_oft_parameters(self.in_features, r) + warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).") + oft_block_size = int(self.in_features // r) + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # Create weights with provided shape + n_elements = oft_block_size * (oft_block_size - 1) // 2 + self.oft_R[adapter_name] = OFTRotationModule( + r if not block_share else 1, + n_elements, + oft_block_size, + self.in_features, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + # Initialize weights + self.reset_oft_parameters(adapter_name, init_weights) + + # set oft r and block size + self.r[adapter_name] = r + self.oft_block_size[adapter_name] = oft_block_size + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_oft_parameters(self, adapter_name, init_weights): + """ + Reset the OFT parameters. + """ + if init_weights is False: + if adapter_name in self.oft_R.keys(): + nn.init.normal_(self.oft_R[adapter_name].weight, mean=0.0, std=0.1) + return + if adapter_name in self.oft_embedding_R.keys(): + nn.init.normal_(self.oft_embedding_R[adapter_name].weight, mean=0.0, std=0.1) + return + + if adapter_name in self.oft_R.keys(): + if init_weights is True: + # initialize oft_R to zero + nn.init.zeros_(self.oft_R[adapter_name].weight) + else: + raise ValueError(f"Unknown initialization {init_weights=}") + if adapter_name in self.oft_embedding_R.keys(): + if init_weights is True: + # initialize oft_embedding_R to zero + nn.init.zeros_(self.oft_embedding_R[adapter_name].weight) + else: + raise ValueError(f"Unknown initialization {init_weights=}") + + def adjust_oft_parameters(self, in_features, params): + """ + Adjust the OFT parameters to be divisible by the in_features dimension. + """ + if params < in_features: + higher_params = params + while higher_params <= in_features and in_features % higher_params != 0: + higher_params += 1 + else: + return in_features + + lower_params = params + while lower_params > 1 and in_features % lower_params != 0: + lower_params -= 1 + + if (params - lower_params) <= (higher_params - params): + return lower_params + else: + return higher_params + + +class Linear(nn.Module, OFTLayer): + """OFT implemented in Linear layer""" + + def __init__( + self, + base_layer, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: Union[bool, str] = True, + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.oft_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + else: + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.oft_R.keys(): + oft_mat = self.get_delta_weight(active_adapter) + + previous_dtype = oft_mat.dtype + if previous_dtype != torch.float32: + oft_mat = oft_mat.to(torch.float32) + + orig_weights = self.get_base_layer().weight.data + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(torch.linalg.inv(oft_mat).to(previous_dtype), orig_weights.to(previous_dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + + base_layer.weight.data = orig_weights.to(orig_dtype) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.oft_R[adapter].weight.device + dtype = self.oft_R[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + oft_R_module = self.oft_R[adapter] + + if cast_to_fp32: + # Temporarily work in fp32 for faster CPU matmul + original_weight = oft_R_module.weight.data + oft_R_module.weight.data = oft_R_module.weight.data.float() + oft_mat = oft_R_module.get_weight() + oft_R_module.weight.data = original_weight # restore + return oft_mat.to(dtype) + else: + return oft_R_module.get_weight() + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + oft_R = self.oft_R[active_adapter] + + x = self._cast_input_dtype(x, oft_R.weight.dtype) + x = oft_R(x) + + result = self.base_layer(x.to(previous_dtype), *args, **kwargs) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +class Conv2d(nn.Module, OFTLayer): + """OFT implemented in Conv2d layer""" + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + init_weights: Union[bool, str] = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + + # Create adapter and set it active + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def update_layer( + self, + adapter_name, + r, + oft_block_size, + module_dropout, + coft, + eps, + block_share, + init_weights, + use_cayley_neumann, + num_cayley_neumann_terms, + inference_mode: bool = False, + **kwargs, + ): + """ + Update the conv2d layer with trainable OFT weights. + """ + # Initialize the MultiplicativeDropoutLayer for module_dropout > 0.0. + if module_dropout > 0.0: + oft_dropout_layer = MultiplicativeDropoutLayer(p=module_dropout) + else: + oft_dropout_layer = nn.Identity() + self.oft_dropout.update(nn.ModuleDict({adapter_name: oft_dropout_layer})) + + # layer information from the base layer + base_layer = self.get_base_layer() + if base_layer.dilation[0] > 1: + raise ValueError("Conv2d with dilation > 1 is not supported by OFT.") + + conv_filter_dim = self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + + if r == 0 and oft_block_size != 0: + if conv_filter_dim % oft_block_size != 0 or oft_block_size > conv_filter_dim: + old_oft_block_size = oft_block_size + oft_block_size = self.adjust_oft_parameters(conv_filter_dim, oft_block_size) + warnings.warn( + f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})." + ) + r = int(conv_filter_dim // oft_block_size) + elif r != 0 and oft_block_size == 0: + if conv_filter_dim % r != 0 or r > conv_filter_dim: + old_r = r + r = self.adjust_oft_parameters(conv_filter_dim, r) + warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).") + oft_block_size = int(conv_filter_dim // r) + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # Create weights with provided shape + n_elements = oft_block_size * (oft_block_size - 1) // 2 + self.oft_R[adapter_name] = OFTRotationModule( + r if not block_share else 1, + n_elements, + oft_block_size, + conv_filter_dim, + coft=coft, + eps=eps, + block_share=block_share, + kernel_size=base_layer.kernel_size, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + # Initialize weights + self.reset_oft_parameters(adapter_name, init_weights) + + # set oft r and block size + self.r[adapter_name] = r + self.oft_block_size[adapter_name] = oft_block_size + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.oft_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + oft_mat = self.get_delta_weight(active_adapter) + + orig_weights = orig_weights.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = orig_weights.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + else: + oft_mat = self.get_delta_weight(active_adapter) + + orig_weights = base_layer.weight.data.clone() + orig_weights = orig_weights.view( + self.out_features, self.in_features * base_layer.kernel_size[0] * base_layer.kernel_size[0] + ) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(oft_mat, orig_weights.to(oft_mat.dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = orig_weights.view( + self.out_features, self.in_features, base_layer.kernel_size[0], base_layer.kernel_size[0] + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.oft_R.keys(): + oft_mat = self.get_delta_weight(active_adapter) + + previous_dtype = oft_mat.dtype + if previous_dtype != torch.float32: + oft_mat = oft_mat.to(torch.float32) + + orig_weights = self.get_base_layer().weight.data.clone() + orig_weights = orig_weights.view( + self.out_features, + self.in_features * self.get_base_layer().kernel_size[0] * self.get_base_layer().kernel_size[0], + ) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = torch.mm(torch.linalg.inv(oft_mat).to(previous_dtype), orig_weights.to(previous_dtype)) + orig_weights = torch.transpose(orig_weights, 0, 1) + orig_weights = orig_weights.view( + self.out_features, + self.in_features, + self.get_base_layer().kernel_size[0], + self.get_base_layer().kernel_size[0], + ) + + base_layer.weight.data = orig_weights.to(orig_dtype) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.oft_R[adapter].weight.device + dtype = self.oft_R[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + oft_R_module = self.oft_R[adapter] + + if cast_to_fp32: + # Temporarily work in fp32 for faster CPU matmul + original_weight = oft_R_module.weight.data + oft_R_module.weight.data = oft_R_module.weight.data.float() + oft_mat = oft_R_module.get_weight() + oft_R_module.weight.data = original_weight # restore + return oft_mat.to(dtype) + else: + return oft_R_module.get_weight() + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_R.keys(): + continue + + oft_R = self.oft_R[active_adapter] + x = self._cast_input_dtype(x, oft_R.weight.dtype) + x = oft_R(x) + + result = self.base_layer(x.to(previous_dtype), *args, **kwargs) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +class Embedding(nn.Module, OFTLayer): + # OFT implemented in a Embedding layer + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + r: int = 8, + oft_block_size: int = 0, + module_dropout: float = 0.0, + coft: bool = False, + eps: float = 6e-5, + block_share: bool = False, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + fan_in_fan_out: bool = False, # unused for embedding, kept for API parity + init_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + super().__init__() + OFTLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + r, + oft_block_size=oft_block_size, + module_dropout=module_dropout, + coft=coft, + eps=eps, + block_share=block_share, + init_weights=init_weights, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + def update_layer( + self, + adapter_name, + r, + oft_block_size, + module_dropout, + coft, + eps, + block_share, + init_weights, + use_cayley_neumann, + num_cayley_neumann_terms, + inference_mode: bool = False, + **kwargs, + ): + # collect the kwargs + kwargs = locals().copy() + del kwargs["self"] + + if r == 0 and oft_block_size != 0: + if self.in_features % oft_block_size != 0 or oft_block_size > self.in_features: + old_oft_block_size = oft_block_size + oft_block_size = self.adjust_oft_parameters(self.in_features, oft_block_size) + warnings.warn( + f"Invalid `oft_block_size` ({old_oft_block_size})! Adjusted `oft_block_size` to ({oft_block_size})." + ) + r = int(self.in_features // oft_block_size) + elif r != 0 and oft_block_size == 0: + if self.in_features % r != 0 or r > self.in_features: + old_r = r + r = self.adjust_oft_parameters(self.in_features, r) + warnings.warn(f"Invalid `r` ({old_r})! Adjusted `r` to ({r}).") + oft_block_size = int(self.in_features // r) + else: + raise ValueError( + "Something went wrong, please report this error: https://github.com/huggingface/peft/issues" + ) + + # Create weights with provided shape + n_elements = oft_block_size * (oft_block_size - 1) // 2 + self.oft_embedding_R[adapter_name] = OFTRotationModule( + r if not block_share else 1, + n_elements, + oft_block_size, + self.in_features, + coft=coft, + eps=eps, + block_share=block_share, + use_cayley_neumann=use_cayley_neumann, + num_cayley_neumann_terms=num_cayley_neumann_terms, + ) + + # Initialize weights + self.reset_oft_parameters(adapter_name, init_weights) + + # set oft r and block size + self.r[adapter_name] = r + self.oft_block_size[adapter_name] = oft_block_size + + # Move new weights to device + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.oft_embedding_R.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + if safe_merge: + # Note that safe_merge will be slower than the normal merge + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), oft_mat) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + else: + orig_weights = base_layer.weight.data + oft_mat = self.get_delta_weight(active_adapter) + orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), oft_mat) + + base_layer.weight.data = orig_weights.contiguous().to(orig_dtype) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.oft_embedding_R.keys(): + oft_mat = self.get_delta_weight(active_adapter) + + previous_dtype = oft_mat.dtype + if previous_dtype != torch.float32: + oft_mat = oft_mat.to(torch.float32) + + orig_weights = self.get_base_layer().weight.data + orig_weights = torch.mm(orig_weights.to(oft_mat.dtype), torch.linalg.inv(oft_mat)) + + base_layer.weight.data = orig_weights.to(orig_dtype) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.oft_embedding_R[adapter].weight.device + dtype = self.oft_embedding_R[adapter].weight.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + oft_R_module = self.oft_embedding_R[adapter] + + if cast_to_fp32: + # Temporarily work in fp32 for faster CPU matmul + original_weight = oft_R_module.weight.data + oft_R_module.weight.data = oft_R_module.weight.data.float() + oft_mat = oft_R_module.get_weight() + oft_R_module.weight.data = original_weight # restore + return oft_mat.to(dtype) + else: + return oft_R_module.get_weight() + + def _embed(self, input: torch.Tensor, weight: torch.Tensor) -> torch.Tensor: + base_layer = self.get_base_layer() + return F.embedding( + input, + weight, + padding_idx=base_layer.padding_idx, + max_norm=base_layer.max_norm, + norm_type=base_layer.norm_type, + scale_grad_by_freq=base_layer.scale_grad_by_freq, + sparse=base_layer.sparse, + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + # x is token ids (usually LongTensor); rotation is applied to embedding outputs + if self.disable_adapters: + if self.merged: + self.unmerge() + return self.base_layer(x, *args, **kwargs) + if self.merged: + return self.base_layer(x, *args, **kwargs) + + result = self.base_layer(x, *args, **kwargs) + out_dtype = result.dtype + + for active_adapter in self.active_adapters: + if active_adapter not in self.oft_embedding_R: + continue + oft_embedding_R = self.oft_embedding_R[active_adapter] + result = self._cast_input_dtype(result, oft_embedding_R.weight.dtype) + result = oft_embedding_R(result) + + return result.to(out_dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + oft_config: OFTConfig, + **kwargs, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Conv2d): + new_module = Conv2d(target, adapter_name, **kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = oft_config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, **kwargs) + elif isinstance(target_base_layer, torch.nn.Embedding): + embedding_kwargs = kwargs.copy() + embedding_kwargs.pop("fan_in_fan_out", None) + new_module = Embedding(target, adapter_name, **embedding_kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..2b4b20f24bf13d9c8067b933714ae8d8061406ab --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/oft/model.py @@ -0,0 +1,200 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import ( + BaseTuner, + get_device_map, +) +from peft.utils import ( + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + get_quantization_config, +) + +from .aqlm import dispatch_aqlm +from .awq import dispatch_awq +from .eetq import dispatch_eetq +from .gptq import dispatch_gptq +from .hqq import dispatch_hqq +from .inc import dispatch_inc +from .layer import OFTLayer, dispatch_default + + +class OFTModel(BaseTuner): + """ + Creates Orthogonal Finetuning model from a pretrained model. The method is described in + https://huggingface.co/papers/2306.07280 + + Args: + model (`torch.nn.Module`): The model to which the adapter tuner layers will be attached. + config ([`OFTConfig`]): The configuration of the OFT model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The OFT model. + + Example: + ```py + >>> from diffusers import StableDiffusionPipeline + >>> from peft import OFTModel, OFTConfig + + >>> config_te = OFTConfig( + ... r=8, + ... target_modules=["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"], + ... module_dropout=0.0, + ... init_weights=True, + ... ) + >>> config_unet = OFTConfig( + ... r=8, + ... target_modules=[ + ... "proj_in", + ... "proj_out", + ... "to_k", + ... "to_q", + ... "to_v", + ... "to_out.0", + ... "ff.net.0.proj", + ... "ff.net.2", + ... ], + ... module_dropout=0.0, + ... init_weights=True, + ... ) + + >>> model = StableDiffusionPipeline.from_pretrained("runwayml/stable-diffusion-v1-5") + >>> model.text_encoder = OFTModel(model.text_encoder, config_te, "default") + >>> model.unet = OFTModel(model.unet, config_unet, "default") + ``` + + **Attributes**: + - **model** ([`~torch.nn.Module`]) -- The model to be adapted. + - **peft_config** ([`OFTConfig`]): The configuration of the OFT model. + """ + + prefix: str = "oft_" + tuner_layer_cls = OFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + oft_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + kwargs = { + "r": oft_config.r, + "oft_block_size": oft_config.oft_block_size, + "module_dropout": oft_config.module_dropout, + "coft": oft_config.coft, + "eps": oft_config.eps, + "block_share": oft_config.block_share, + "use_cayley_neumann": oft_config.use_cayley_neumann, + "num_cayley_neumann_terms": oft_config.num_cayley_neumann_terms, + "fan_in_fan_out": oft_config.fan_in_fan_out, + "init_weights": oft_config.init_weights, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + + quant_methods = ["gptq", "aqlm", "awq"] + for quant_method in quant_methods: + quantization_config = get_quantization_config(self.model, method=quant_method) + if quantization_config is not None: + kwargs[f"{quant_method}_quantization_config"] = quantization_config + + # If it is not a OFTLayer, create a new module, else update it with new adapters + if not isinstance(target, OFTLayer): + device_map = get_device_map(self.model) + new_module = self._create_new_module(oft_config, adapter_name, target, device_map=device_map, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + else: + target.update_layer( + adapter_name, + r=oft_config.r, + oft_block_size=oft_config.oft_block_size, + module_dropout=oft_config.module_dropout, + coft=oft_config.coft, + eps=oft_config.eps, + block_share=oft_config.block_share, + use_cayley_neumann=oft_config.use_cayley_neumann, + num_cayley_neumann_terms=oft_config.num_cayley_neumann_terms, + init_weights=oft_config.init_weights, + ) + + @staticmethod + def _create_new_module(oft_config, adapter_name, target, **kwargs): + # Collect dispatcher functions to decide what backend to use for the replaced OFT layer. The order matters, + # because the first match is always used. Therefore, the default layers should be checked last. + dispatchers = [] + + # avoid eager bnb import + if is_bnb_available(): + from .bnb import dispatch_bnb_8bit + + dispatchers.append(dispatch_bnb_8bit) + + if is_bnb_4bit_available(): + from .bnb import dispatch_bnb_4bit + + dispatchers.append(dispatch_bnb_4bit) + + dispatchers.extend( + [ + dispatch_eetq, + dispatch_aqlm, + dispatch_awq, + dispatch_gptq, + dispatch_hqq, + dispatch_inc, + dispatch_default, + ] + ) + + new_module = None + for dispatcher in dispatchers: + new_module = dispatcher(target, adapter_name, oft_config=oft_config, **kwargs) + if new_module is not None: # first match wins + break + + if new_module is None: + # no module could be matched + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `torch.nn.Conv2d`." + ) + + return new_module + + def _check_merge_allowed(self): + """Verify that the configuration supports merging. + + Currently gptq quantization and replicated layers do not support merging. + """ + super()._check_merge_allowed() + if getattr(self.model, "quantization_method", None) == "gptq": + raise ValueError("Cannot merge OFT layers when the model is gptq quantized") + if self.peft_config.get("layer_replication"): + raise ValueError("Cannot merge OFT layers when base model layers are replicated") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..801e93fc5380e6fc2ae48798e6650a9a41cb2dcc --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/__init__.py @@ -0,0 +1,15 @@ +from peft.utils import register_peft_method + +from .config import OSFConfig +from .layer import Linear, OSFLayer +from .model import OSFModel + + +__all__ = ["Linear", "OSFConfig", "OSFLayer", "OSFModel"] + +register_peft_method( + name="osf", + config_cls=OSFConfig, + model_cls=OSFModel, + is_mixed_compatible=False, +) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/config.py new file mode 100644 index 0000000000000000000000000000000000000000..77a08964d4fce411870e088879f6a5a8b4d993c8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/config.py @@ -0,0 +1,80 @@ +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class OSFConfig(PeftConfig): + """ + Configuration for Orthogonal Subspace Fine-tuning (OSF). + + Args: + effective_rank (`int` or `float`, *optional*): + Preserved SVD rank ("high" subspace). The top-``effective_rank`` singular directions are frozen and + retained across tasks; the remaining dimensions form the trainable low-rank subspace. If `None`, defaults + to 50% of the smaller weight dimension per target module. Note: This differs from LoRA's `r` (trainable + rank). In OSF, the trainable rank is `min(weight.shape) - effective_rank`. + target_modules (`Union[list[str], str]`, *optional*): + The names of the modules to apply OSF to. Can be a list of module names or `"all-linear"`. + rank_pattern (`dict[str, int|float]`, *optional*): + A dictionary of regex patterns to override `effective_rank` for specific modules. Values can be absolute + integers or fractions in (0, 1], interpreted as a fraction of the smaller matrix dimension per target. + """ + + effective_rank: Optional[Union[int, float]] = field( + default=None, + metadata={ + "help": ( + 'Preserved SVD rank ("high" subspace). The top-`effective_rank` singular directions are frozen ' + "and retained across tasks; the remaining dimensions form the trainable low-rank subspace. " + "Trainable rank equals min(weight.shape) - effective_rank. If None, defaults to 50% of the smaller " + "weight dimension per target module. Floats in (0, 1] are interpreted as a fraction of the smaller " + "matrix dimension per target." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "The names of the modules to apply OSF to. Can be a list of module names or 'all-linear'."}, + ) + rank_pattern: Optional[dict[str, Union[int, float]]] = field( + default=None, + metadata={ + "help": ( + "A dictionary of regex patterns to override effective_rank per module. Values can be absolute " + "integers or fractions in (0, 1], interpreted as a fraction of the smaller matrix dimension." + ) + }, + ) + + # Additional optional fields for compatibility with generic test harnesses + init_weights: Optional[bool] = field( + default=None, + metadata={ + "help": ( + "If provided, toggles custom weight initialization behavior for certain methods. OSF ignores this " + "flag but accepts it for config compatibility." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={"help": "Optional list of module names to save separately (ignored by OSF but accepted)."}, + ) + target_svd_config: Optional[dict[str, int]] = field( + default=None, + metadata={ + "help": ( + "Optional per-parameter SVD target rank mapping (e.g., {'lin0.weight': 8}). OSF currently ignores " + "this field but accepts it for forward compatibility." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.OSF diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..d0fe153e5c1db73da5f853c8ddaf66232f4e0488 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/layer.py @@ -0,0 +1,289 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from functools import partial +from typing import Any, Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer + +from .utils import ( + decompose_weight_matrix, + reconstruct_weight_matrix, +) + + +class OSFLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names: tuple[str, ...] = ("osf_svd_params",) + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = ("_osf_U_high", "_osf_S_high", "_osf_V_high") + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.effective_rank = {} + # Map adapter_name -> ParameterDict{"U_low", "S_low", "V_low"} + self.osf_svd_params = nn.ModuleDict({}) + # Store high-rank (frozen) components as buffers that track device moves + self._osf_U_high = BufferDict({}) + self._osf_S_high = BufferDict({}) + self._osf_V_high = BufferDict({}) + # Track hook handles for cleanup + self.hook_handles = [] + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + # Get layer dimensions + base_layer = self.get_base_layer() + # Prefer the universally available weight shape when possible. + if ( + hasattr(base_layer, "weight") + and isinstance(base_layer.weight, torch.Tensor) + and base_layer.weight.ndim == 2 + ): + # For Linear-like modules, weight is [out_features, in_features] + out_features, in_features = base_layer.weight.shape + elif isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif hasattr(base_layer, "infeatures") and hasattr(base_layer, "outfeatures"): + # QuantLinear + in_features, out_features = base_layer.infeatures, base_layer.outfeatures + elif hasattr(base_layer, "input_size") and hasattr(base_layer, "output_size"): + # Megatron ColumnParallelLinear, RowParallelLinear + in_features, out_features = base_layer.input_size, base_layer.output_size + elif hasattr(base_layer, "in_features") and hasattr(base_layer, "out_features"): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + in_features, out_features = None, None + warnings.warn( + f"Unsupported layer type '{type(base_layer)}' encountered; could not infer in/out features.", + UserWarning, + ) + + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name: str, effective_rank: int, **kwargs): + """Update layer to add a new OSF adapter.""" + if effective_rank <= 0: + raise ValueError( + f"`effective_rank` should be a positive integer value but the value passed is {effective_rank}" + ) + + # Store the rank for this adapter + self.effective_rank[adapter_name] = effective_rank + + # Perform SVD decomposition on the base layer weight + base_layer = self.get_base_layer() + weight = base_layer.weight.data + svd_dict = decompose_weight_matrix(weight, top_k=effective_rank) + + # Store high-rank (frozen) components as buffers + self._osf_U_high[adapter_name] = svd_dict["U_high"] + self._osf_S_high[adapter_name] = svd_dict["S_high"] + self._osf_V_high[adapter_name] = svd_dict["V_high"] + + # Create ParameterDict for trainable low-rank components + svd_params = nn.ParameterDict( + { + "U_low": svd_dict["U_low"], + "S_low": svd_dict["S_low"], + "V_low": svd_dict["V_low"], + } + ) + self.osf_svd_params[adapter_name] = svd_params + + # Attach gradient hooks for orthogonal projection + self._attach_hooks(adapter_name) + + # Set the adapter as active + self.set_adapter(self.active_adapters) + + def _attach_hooks(self, adapter_name: str): + """Attach gradient hooks for the given adapter.""" + if adapter_name not in self.osf_svd_params: + return + + svd_module = self.osf_svd_params[adapter_name] + + def hook(grad, name: str, adapter: str, layer: OSFLayer): + # Project gradient to be orthogonal to high-rank subspace for U_low/V_low + # Access buffers dynamically to ensure they're on the correct device + if name == "U_low": + U_high = layer._osf_U_high[adapter] + proj = U_high @ (U_high.transpose(0, 1) @ grad) + return grad - proj + elif name == "V_low": + V_high = layer._osf_V_high[adapter] + proj = (grad @ V_high.transpose(0, 1)) @ V_high + return grad - proj + return grad + + # Store hook handles for later cleanup + handle_u = svd_module["U_low"].register_hook(partial(hook, name="U_low", adapter=adapter_name, layer=self)) + handle_v = svd_module["V_low"].register_hook(partial(hook, name="V_low", adapter=adapter_name, layer=self)) + + self.hook_handles.extend([handle_u, handle_v]) + + def _detach_hooks(self): + """Remove all gradient hooks.""" + for handle in self.hook_handles: + handle.remove() + self.hook_handles.clear() + + def _reconstruct_weight(self, adapter_name: str) -> torch.Tensor: + """Reconstruct weight matrix from SVD components for given adapter.""" + if adapter_name not in self.osf_svd_params: + return self.get_base_layer().weight + + svd_module = self.osf_svd_params[adapter_name] + svd_dict = { + "U_high": self._osf_U_high[adapter_name], + "S_high": self._osf_S_high[adapter_name], + "V_high": self._osf_V_high[adapter_name], + "U_low": svd_module["U_low"], + "S_low": svd_module["S_low"], + "V_low": svd_module["V_low"], + } + return reconstruct_weight_matrix(svd_dict) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + if adapter_names is None: + adapter_names = self.active_adapters + + for active_adapter in adapter_names: + if active_adapter in self.osf_svd_params.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + new_weight = self._reconstruct_weight(active_adapter) + + if not torch.isfinite(new_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = new_weight.to(orig_weight.dtype) + else: + new_weight = self._reconstruct_weight(active_adapter) + base_layer.weight.data = new_weight + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + # For OSF, unmerging means restoring the original weight + # Since we modify the weight in-place, we need to store the original weight + # This is a limitation of the current OSF implementation + warnings.warn("OSF does not support unmerging. Original weights are permanently modified.") + + def __del__(self): + """Cleanup hooks on deletion.""" + self._detach_hooks() + + +class Linear(nn.Module, OSFLayer): + # OSF implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + effective_rank: int = None, + **kwargs, + ) -> None: + super().__init__() + OSFLayer.__init__(self, base_layer, **kwargs) + + # Set default effective_rank if not provided + if effective_rank is None: + # Default to 50% of min dimension + effective_rank = min(self.in_features, self.out_features) // 2 + + self._active_adapter = adapter_name + self.update_layer(adapter_name, effective_rank, **kwargs) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + if self.disable_adapters: + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + # Use reconstructed weight for forward pass + base_layer = self.get_base_layer() + bias = base_layer.bias + + # Use the active adapter's reconstructed weight + active_adapter = self.active_adapters[0] if self.active_adapters else None + if active_adapter and active_adapter in self.osf_svd_params: + weight = self._reconstruct_weight(active_adapter) + orig_dtype = x.dtype # assume that the intended dtype is that of the input + x = self._cast_input_dtype(x, weight.dtype) + if bias is not None: + bias = bias.to(weight.dtype) + result = F.linear(x, weight, bias) + result = result.to(orig_dtype) + else: + result = self.base_layer(x, *args, **kwargs) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "osf." + rep + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + osf_config, + **kwargs, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + new_module = Linear(target, adapter_name, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f04e0c49983a50a9a5227762437c4cff48f00544 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/model.py @@ -0,0 +1,124 @@ +from __future__ import annotations + +import re + +import torch +import torch.nn as nn + +from peft.tuners.tuners_utils import BaseTuner +from peft.utils.constants import TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING + +from .layer import OSFLayer, dispatch_default + + +class OSFModel(BaseTuner): + """A minimal tuner implementing Orthogonal Subspace Fine-tuning.""" + + prefix: str = "osf_" + tuner_layer_cls = OSFLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING + + def __init__( + self, + model, + config, + adapter_name, + low_cpu_mem_usage: bool = False, + state_dict: dict[str, torch.Tensor] | None = None, + ): + # Pass state_dict through for compatibility with BaseTuner + super().__init__( + model, + config, + adapter_name, + low_cpu_mem_usage=low_cpu_mem_usage, + state_dict=state_dict, + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped base model. + + This mirrors the behavior of other tuners (e.g., LoRA), ensuring attributes like `device` resolve to the + underlying transformers model. + """ + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "model": # avoid infinite recursion during init + raise + return getattr(self.model, name) + + def _prepare_adapter_config(self, peft_config, model_config): + # If target_modules is unspecified, try mapping; else fall back to all linear layers for custom models + if getattr(peft_config, "target_modules", None) is None: + model_type = model_config.get("model_type") + if model_type in self.target_module_mapping: + peft_config.target_modules = set(self.target_module_mapping[model_type]) + else: + from peft.utils.constants import INCLUDE_LINEAR_LAYERS_SHORTHAND + + peft_config.target_modules = INCLUDE_LINEAR_LAYERS_SHORTHAND + return peft_config + + def _create_and_replace( + self, + osf_config, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + *, + parameter_name: str | None = None, + ) -> None: + # OSF only works on 2D weight matrices + if not hasattr(target, "weight") or len(target.weight.shape) != 2: + return None + + # Determine effective rank for this target (supports int or fractional in (0,1]) + def _resolve_rank(value, min_dim: int) -> int: + if value is None: + return max(min_dim // 2, 0) + # floats in (0,1] => fraction of min_dim + if isinstance(value, float) and 0 < value <= 1: + r = int(min_dim * value) + else: + r = int(value) + return max(min(min_dim, r), 0) + + min_dim = min(target.weight.shape) + effective_rank = _resolve_rank(getattr(osf_config, "effective_rank", None), min_dim) + + # Check for per-module rank overrides (allow int or fractional) + if hasattr(osf_config, "rank_pattern") and osf_config.rank_pattern: + for pattern, rank in osf_config.rank_pattern.items(): + if re.search(pattern, current_key): + effective_rank = _resolve_rank(rank, min_dim) + break + + kwargs = { + "effective_rank": effective_rank, + } + + # Create a new or update an existing OSF layer in place + if isinstance(target, OSFLayer): + target.update_layer(adapter_name, **kwargs) + else: + new_module = dispatch_default(target, adapter_name, osf_config, **kwargs) + if new_module is None: + return None + # If adding an additional adapter, keep it frozen initially + if adapter_name not in self.active_adapters: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None: + for n, p in model.named_parameters(): + # Only OSF adapter parameters (in osf_svd_params) should be trainable + if "osf_svd_params" not in n: + p.requires_grad = False + + # Use BaseTuner's merge and merge_and_unload implementations. + # Explicitly disallow unmerging at the model level for OSF. + def unmerge_adapter(self, *args, **kwargs): + raise NotImplementedError("OSF models do not support unmerging") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/utils.py new file mode 100644 index 0000000000000000000000000000000000000000..0030e22b09da586e3327a646ad91541b8b69bcb1 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/osf/utils.py @@ -0,0 +1,133 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Utilities for Orthogonal Subspace Learning with Adaptive OSF.""" + +from __future__ import annotations + +from typing import Any + +import torch +import torch.distributed as dist +from torch import nn + + +# Note: OSF now relies on OSFLayer + BaseTuner; no model-level helpers required here. + + +__all__ = [ + "decompose_weight_matrix", + "project_gradient_to_orthogonal_space", + "reconstruct_weight_matrix", +] + + +def _wait_if_async(tensor): + """Wait for AsyncCollectiveTensor if needed, otherwise return tensor as-is.""" + if hasattr(tensor, "wait"): + return tensor.wait() + return tensor + + +def decompose_weight_matrix(weight: torch.Tensor, top_k: int) -> dict[str, Any]: + """Perform an SVD of ``weight`` and split it into frozen and trainable parts.""" + device_local = weight.device + orig_dtype = weight.dtype + W = weight.to(torch.float32) + U, S, Vt = torch.linalg.svd(W, full_matrices=False) + k = min(top_k, S.shape[0]) + + svd = { + "U_high": U[:, :k].contiguous().detach().to(device=device_local, dtype=orig_dtype), + "S_high": S[:k].contiguous().detach().to(device=device_local, dtype=orig_dtype), + "V_high": Vt[:k, :].contiguous().detach().to(device=device_local, dtype=orig_dtype), + "U_low": nn.Parameter(U[:, k:].contiguous().detach().to(device=device_local, dtype=orig_dtype)), + "S_low": nn.Parameter(S[k:].contiguous().detach().to(device=device_local, dtype=orig_dtype)), + "V_low": nn.Parameter(Vt[k:, :].contiguous().detach().to(device=device_local, dtype=orig_dtype)), + "rank_high": k, + } + return svd + + +def reconstruct_weight_matrix(svd_dict: dict[str, torch.Tensor]) -> torch.Tensor: + """Reconstruct a weight matrix from its SVD components.""" + U_high = svd_dict["U_high"] + S_high = svd_dict["S_high"] + V_high = svd_dict["V_high"] + U_low = svd_dict["U_low"] + S_low = svd_dict["S_low"] + V_low = svd_dict["V_low"] + + high_part = ( + torch.mm(U_high * S_high.unsqueeze(0), V_high) + if U_high.numel() > 0 and S_high.numel() > 0 + else torch.zeros(U_low.size(0), V_low.size(1), device=U_high.device) + ) + low_part = ( + torch.mm(U_low * S_low.unsqueeze(0), V_low) + if U_low.numel() > 0 and S_low.numel() > 0 + else torch.zeros(U_high.size(0), V_high.size(1), device=U_low.device) + ) + return high_part + low_part + + +def project_gradient_to_orthogonal_space(svd_dict: dict[str, Any]) -> None: + """Project gradients of ``U_low`` and ``V_low`` to be orthogonal to the high rank space.""" + if svd_dict["U_low"].grad is None and svd_dict["S_low"].grad is None and svd_dict["V_low"].grad is None: + return + + U_high = svd_dict["U_high"] + V_high = svd_dict["V_high"] + + # Project U_low gradients to space orthogonal to U_high + if svd_dict["U_low"].grad is not None: + dU = svd_dict["U_low"].grad + # Support distributed tensors by operating on the local shard + local_U_high = getattr(U_high, "to_local", lambda: U_high)() + local_dU = getattr(dU, "to_local", lambda: dU)() + + # Perform projection computation using memory-efficient operations + # Memory-optimized projection: dU = dU - U_high @ (U_high.T @ dU) + # Use addmm_ for efficient in-place operation + # Compute local contribution to (U_high^T @ dU); all-reduce to get global projection + proj_coeff = torch.mm(local_U_high.transpose(0, 1), local_dU) + if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1: + dist.all_reduce(proj_coeff, op=dist.ReduceOp.SUM) + # Apply projection using only local rows of U_high + local_dU.addmm_(local_U_high, proj_coeff, alpha=-1.0) + + if hasattr(dU, "_local_tensor"): + dU._local_tensor.copy_(local_dU) + else: + dU.copy_(local_dU) + + # Repeat projection for V_low using V_high + if svd_dict["V_low"].grad is not None: + dV = svd_dict["V_low"].grad + local_V_high = getattr(V_high, "to_local", lambda: V_high)() + local_dV = getattr(dV, "to_local", lambda: dV)() + + # Compute Gram matrix G = V_high^T @ V_high for global projection across row-sharded V_high + # Assumes column dimension is consistent across ranks (row sharding over singular vectors) + G_local = torch.mm(local_V_high.transpose(0, 1), local_V_high) + if dist.is_available() and dist.is_initialized() and dist.get_world_size() > 1: + dist.all_reduce(G_local, op=dist.ReduceOp.SUM) + + # Apply projection: dV = dV - dV @ G (use local shard of dV) + update = torch.mm(local_dV, G_local) + local_dV.add_(update, alpha=-1.0) + + if hasattr(dV, "_local_tensor"): + dV._local_tensor.copy_(local_dV) + else: + dV.copy_(local_dV) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..9195c0d75d3d11e752d0477b64edd79599bdaa01 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PromptEncoderConfig, PromptEncoderReparameterizationType +from .model import PromptEncoder + + +__all__ = ["PromptEncoder", "PromptEncoderConfig", "PromptEncoderReparameterizationType"] + +register_peft_method(name="p_tuning", config_cls=PromptEncoderConfig, model_cls=PromptEncoder) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..a69c13db9c8a0f57a7daa7d312472625251fb6c8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/config.py @@ -0,0 +1,60 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum +from dataclasses import dataclass, field +from typing import Union + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +class PromptEncoderReparameterizationType(str, enum.Enum): + MLP = "MLP" + LSTM = "LSTM" + + +@dataclass +class PromptEncoderConfig(PromptLearningConfig): + """ + This is the configuration class to store the configuration of a [`PromptEncoder`]. + + Args: + encoder_reparameterization_type (Union[[`PromptEncoderReparameterizationType`], `str`]): + The type of reparameterization to use. + encoder_hidden_size (`int`): The hidden size of the prompt encoder. + encoder_num_layers (`int`): The number of layers of the prompt encoder. + encoder_dropout (`float`): The dropout probability of the prompt encoder. + """ + + encoder_reparameterization_type: Union[str, PromptEncoderReparameterizationType] = field( + default=PromptEncoderReparameterizationType.MLP, + metadata={"help": "How to reparameterize the prompt encoder"}, + ) + encoder_hidden_size: int = field( + default=None, + metadata={"help": "The hidden size of the prompt encoder"}, + ) + encoder_num_layers: int = field( + default=2, + metadata={"help": "The number of layers of the prompt encoder"}, + ) + encoder_dropout: float = field( + default=0.0, + metadata={"help": "The dropout of the prompt encoder"}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.P_TUNING diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..ade2b1128158376c134441687803b85d444cfb96 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/p_tuning/model.py @@ -0,0 +1,130 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Based on https://github.com/NVIDIA/NeMo/blob/main/nemo/collections/nlp/modules/common/prompt_encoder.py +# with some refactor +import warnings + +import torch + +from .config import PromptEncoderConfig, PromptEncoderReparameterizationType + + +class PromptEncoder(torch.nn.Module): + """ + The prompt encoder network that is used to generate the virtual token embeddings for p-tuning. + + Args: + config ([`PromptEncoderConfig`]): The configuration of the prompt encoder. + + Example: + + ```py + >>> from peft import PromptEncoder, PromptEncoderConfig + + >>> config = PromptEncoderConfig( + ... peft_type="P_TUNING", + ... task_type="SEQ_2_SEQ_LM", + ... num_virtual_tokens=20, + ... token_dim=768, + ... num_transformer_submodules=1, + ... num_attention_heads=12, + ... num_layers=12, + ... encoder_reparameterization_type="MLP", + ... encoder_hidden_size=768, + ... ) + + >>> prompt_encoder = PromptEncoder(config) + ``` + + **Attributes**: + - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt encoder. + - **mlp_head** (`torch.nn.Sequential`) -- The MLP head of the prompt encoder if `inference_mode=False`. + - **lstm_head** (`torch.nn.LSTM`) -- The LSTM head of the prompt encoder if `inference_mode=False` and + `encoder_reparameterization_type="LSTM"`. + - **token_dim** (`int`) -- The hidden embedding dimension of the base transformer model. + - **input_size** (`int`) -- The input size of the prompt encoder. + - **output_size** (`int`) -- The output size of the prompt encoder. + - **hidden_size** (`int`) -- The hidden size of the prompt encoder. + - **total_virtual_tokens** (`int`): The total number of virtual tokens of the + prompt encoder. + - **encoder_type** (Union[[`PromptEncoderReparameterizationType`], `str`]): The encoder type of the prompt + encoder. + + + Input shape: (`batch_size`, `total_virtual_tokens`) + + Output shape: (`batch_size`, `total_virtual_tokens`, `token_dim`) + """ + + def __init__(self, config): + super().__init__() + self.token_dim = config.token_dim + self.input_size = self.token_dim + self.output_size = self.token_dim + self.hidden_size = config.encoder_hidden_size + self.total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules + self.encoder_type = config.encoder_reparameterization_type + + # embedding + self.embedding = torch.nn.Embedding(self.total_virtual_tokens, self.token_dim) + if not config.inference_mode: + if self.encoder_type == PromptEncoderReparameterizationType.LSTM: + lstm_dropout = config.encoder_dropout + num_layers = config.encoder_num_layers + # LSTM + self.lstm_head = torch.nn.LSTM( + input_size=self.input_size, + hidden_size=self.hidden_size, + num_layers=num_layers, + dropout=lstm_dropout, + bidirectional=True, + batch_first=True, + ) + + self.mlp_head = torch.nn.Sequential( + torch.nn.Linear(self.hidden_size * 2, self.hidden_size * 2), + torch.nn.ReLU(), + torch.nn.Linear(self.hidden_size * 2, self.output_size), + ) + + elif self.encoder_type == PromptEncoderReparameterizationType.MLP: + encoder_num_layers_default = PromptEncoderConfig.encoder_num_layers + if config.encoder_num_layers != encoder_num_layers_default: + warnings.warn( + f"for {self.encoder_type.value}, the argument `encoder_num_layers` is ignored. " + f"Exactly {encoder_num_layers_default} MLP layers are used." + ) + layers = [ + torch.nn.Linear(self.input_size, self.hidden_size), + torch.nn.ReLU(), + torch.nn.Linear(self.hidden_size, self.hidden_size), + torch.nn.ReLU(), + torch.nn.Linear(self.hidden_size, self.output_size), + ] + self.mlp_head = torch.nn.Sequential(*layers) + + else: + raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.") + + def forward(self, indices): + input_embeds = self.embedding(indices) + if self.encoder_type == PromptEncoderReparameterizationType.LSTM: + output_embeds = self.mlp_head(self.lstm_head(input_embeds)[0]) + elif self.encoder_type == PromptEncoderReparameterizationType.MLP: + output_embeds = self.mlp_head(input_embeds) + else: + raise ValueError("Prompt encoder type not recognized. Please use one of MLP (recommended) or LSTM.") + + return output_embeds diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1c18933eba3fa44106ba9fa89ba34ecd12a2bed4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PolyConfig +from .layer import Linear, PolyLayer +from .model import PolyModel + + +__all__ = ["Linear", "PolyConfig", "PolyLayer", "PolyModel"] + +register_peft_method(name="poly", config_cls=PolyConfig, model_cls=PolyModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/config.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a77bc5db447edd4ba97c1b1c407f3cfc620cb4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/config.py @@ -0,0 +1,103 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class PolyConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`PolyModel`]. + - [Polytropon (Poly)](https://huggingface.co/papers/2202.13914) + - [Multi-Head Routing (MHR)](https://huggingface.co/papers/2211.03831) + + Args: + r (`int`): Attention dimension of each Lora in Poly. + target_modules (`Union[List[str],str]`): The names of the modules to apply Poly to. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + modules_to_save (`List[str]`): List of modules apart from Poly layers to be set as trainable + and saved in the final checkpoint. + init_weights (bool): Whether to perform initialization of Poly weights. + poly_type (`Literal["poly"]`): The variant of the Poly module to use. Currently, only "poly" + is supported. + n_tasks (`int`): The number of tasks in a multitasking scenario. + n_skills (`int`): The number of skills (LoRA) in each Poly layer. + n_splits (`int`): The number of splits within each LoRA of a Poly layer. A value greater + than 1 indicates the use of Multi-Head Routing (MHR). + """ + + r: int = field(default=8, metadata={"help": "Lora attention dimension"}) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "List of module names or regex expression of the module names to replace with Poly." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$' " + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from Poly."}, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": "List of modules apart from Poly layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved." + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the Poly layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + poly_type: Literal["poly"] = field( + default="poly", + metadata={"help": 'Type of Poly modules to be used. Currently only "poly" is supported.'}, + ) + n_tasks: int = field( + default=1, + metadata={"help": "Number of tasks in multitasking scenario."}, + ) + n_skills: int = field( + default=4, + metadata={"help": "Number of skills (LoRA) in each Poly layer."}, + ) + n_splits: int = field( + default=1, + metadata={"help": "Number of splits within each LoRA of a Poly layer."}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.POLY + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..2f700997a54f247f4cf77172700d40b54e6c2600 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/layer.py @@ -0,0 +1,165 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math +from typing import Any + +import torch +import torch.nn as nn + +from peft.tuners.tuners_utils import BaseTunerLayer + +from .config import PolyConfig +from .router import get_router + + +class PolyLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("poly_lora_A", "poly_lora_B", "poly_router") + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("r", "n_tasks", "n_skills", "n_splits") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.n_tasks = {} + self.n_skills = {} + self.n_splits = {} + self.poly_type = {} + self.poly_router = nn.ModuleDict() + self.poly_lora_A = nn.ParameterDict() + self.poly_lora_B = nn.ParameterDict() + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + self.in_features = in_features + self.out_features = out_features + + def update_layer(self, adapter_name, poly_config, inference_mode: bool = False, **kwargs): + if poly_config.r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {poly_config.r}") + + self.r[adapter_name] = poly_config.r + self.n_tasks[adapter_name] = poly_config.n_tasks + self.n_skills[adapter_name] = poly_config.n_skills + self.n_splits[adapter_name] = poly_config.n_splits + self.poly_type[adapter_name] = poly_config.poly_type + + self.poly_lora_A[adapter_name] = nn.Parameter( + torch.empty( + poly_config.n_splits, + poly_config.n_skills, + self.in_features // poly_config.n_splits, + poly_config.r, + ) + ) + self.poly_lora_B[adapter_name] = nn.Parameter( + torch.empty( + poly_config.n_splits, + poly_config.n_skills, + poly_config.r, + self.out_features // poly_config.n_splits, + ) + ) + self.poly_router[adapter_name] = get_router(poly_config) + + self.reset_poly_parameters(adapter_name, init_weights=poly_config.init_weights) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_poly_parameters(self, adapter_name, init_weights): + if adapter_name in self.poly_lora_A.keys(): + # initialize A the same way as the default for nn.Linear + # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L269 + n_splits, n_skills, d, r = self.poly_lora_A[adapter_name].shape + for skill in range(n_skills): + for split in range(n_splits): + param = torch.empty((r, d)) + torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5)) + self.poly_lora_A[adapter_name].data[split, skill, :, :] = param.T + + if init_weights: + # initialize B to zero + torch.nn.init.zeros_(self.poly_lora_B[adapter_name]) + else: + # initialize B the same way as the default for nn.Linear + n_splits, n_skills, r, d = self.poly_lora_B[adapter_name].shape + for skill in range(n_skills): + for split in range(n_splits): + param = torch.empty((d, r)) + torch.nn.init.kaiming_uniform_(param, a=math.sqrt(5)) + self.poly_lora_B[adapter_name].data[split, skill, :, :] = param.T + + # initialized router + self.poly_router[adapter_name].reset() + + +class Linear(nn.Module, PolyLayer): + # Lora implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + poly_config: PolyConfig, + **kwargs, + ) -> None: + super().__init__() + PolyLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + self.update_layer(adapter_name, poly_config) + + def forward(self, x: torch.Tensor, *args: Any, task_ids: torch.Tensor = None, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + if self.disable_adapters: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.poly_lora_A.keys(): + continue + + r = self.r[active_adapter] + poly_router = self.poly_router[active_adapter] + poly_lora_A = self.poly_lora_A[active_adapter] + poly_lora_B = self.poly_lora_B[active_adapter] + + # Combine the output of LoRAs + # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L293 + mixing_weights = poly_router(task_ids=task_ids, input_ids=x) + bs, n_splits, n_skills = mixing_weights.size() + + # A is n_splits, n_skills, D // n_splits, rank + # we want bs, n_splits, D // n_splits, rank + A = torch.einsum("bqs,qsdr->bqdr", (mixing_weights, poly_lora_A)) + B = torch.einsum("bqs,qsrd->bqrd", (mixing_weights, poly_lora_B)) + + A = A.reshape(bs, self.in_features, r) + B = B.transpose(1, 2).reshape(bs, r, self.out_features) + + x = x.to(A.dtype) + result += x.bmm(A).bmm(B) / r + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "poly." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/model.py new file mode 100644 index 0000000000000000000000000000000000000000..bf7060026310a1f489512293b3afa216105a16cc --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/model.py @@ -0,0 +1,104 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from contextlib import contextmanager +from typing import Any + +import torch +from torch import nn + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING + +from .config import PolyConfig +from .layer import Linear, PolyLayer + + +class PolyModel(BaseTuner): + prefix: str = "poly_" + tuner_layer_cls = PolyLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + poly_config: PolyConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + **optional_kwargs: Any, + ): + if isinstance(target, PolyLayer): + target.update_layer(adapter_name, poly_config) + else: + new_module = self._create_new_module( + poly_config, + adapter_name, + target, + ) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(poly_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + return Linear(target, adapter_name, poly_config, **kwargs) + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + def _register_pre_hooks(self, task_ids): + """Helper method to register pre hooks.""" + if task_ids is None: + return [] + + def pre_hook(_, args, kwargs): + kwargs["task_ids"] = task_ids + return args, kwargs + + handles = [] + + for module in self.model.modules(): + if isinstance(module, Linear): + handle = module.register_forward_pre_hook(pre_hook, with_kwargs=True) + handles.append(handle) + + return handles + + @contextmanager + def _manage_pre_hooks(self, task_ids): + """Context manager to handle the lifecycle of pre hooks.""" + handles = self._register_pre_hooks(task_ids) + try: + yield + finally: + for handle in handles: + handle.remove() + + def forward(self, *args, task_ids=None, **kwargs): + with self._manage_pre_hooks(task_ids): + return self.model(*args, **kwargs) + + def generate(self, *args, task_ids=None, **kwargs): + with self._manage_pre_hooks(task_ids): + return self.model.generate(*args, **kwargs) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/router.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/router.py new file mode 100644 index 0000000000000000000000000000000000000000..3dda3e75e35b6a9fbd5a2412815a0f05421f2ef4 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/poly/router.py @@ -0,0 +1,81 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from abc import ABC, abstractmethod + +import torch +from torch import nn +from torch.distributions.relaxed_bernoulli import RelaxedBernoulli + +from .config import PolyConfig + + +EPS = 1e-12 + + +def get_router(poly_config: PolyConfig) -> nn.Module: + if poly_config.poly_type == "poly": + return PolyRouter(poly_config) + else: + raise ValueError( + f"Unsupported poly_type: {poly_config.poly_type}. " + "Currently, only the following types are supported: " + "`poly`." + ) + + +class Router(nn.Module, ABC): + @abstractmethod + def reset(self): ... + + @abstractmethod + def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor): ... + + +class PolyRouter(Router): + # It's a simplified implementation of + # https://github.com/microsoft/mttl/blob/ce4ca51dbca73be656feb9b3e5233633e3c5dec7/mttl/models/poly.py#L138 + def __init__(self, poly_config: PolyConfig): + super().__init__() + + self.poly_type = poly_config.poly_type + self.n_tasks = poly_config.n_tasks + self.n_skills = poly_config.n_skills + self.n_splits = poly_config.n_splits + + self.module_logits = nn.Parameter(torch.empty((self.n_tasks, self.n_splits * self.n_skills))) + + def reset(self): + torch.nn.init.uniform_(self.module_logits, -1e-3, 1e-3) + + def forward(self, task_ids: torch.Tensor, input_ids: torch.Tensor): + if task_ids is None: + raise ValueError("task_ids should not be None.") + if task_ids.max().item() >= self.n_tasks: + raise ValueError(f"Only {self.n_tasks} tasks available. Found task id = {task_ids.max().item()}") + + # move task id to input's device + task_ids = task_ids.to(self.module_logits.device) + + module_logits = self.module_logits[task_ids] + module_logits = module_logits.view(-1, self.n_splits, self.n_skills) + + if self.training: + module_logits = RelaxedBernoulli(temperature=1.0, logits=module_logits).rsample() + else: + module_logits = torch.sigmoid(module_logits) + + module_weights = module_logits / (module_logits.sum(dim=-1, keepdim=True) + EPS) + + return module_weights diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..939f74d3f689f400dfdcb0139f4a2cf04cce52fc --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PrefixTuningConfig +from .model import PrefixEncoder + + +__all__ = ["PrefixEncoder", "PrefixTuningConfig"] + +register_peft_method(name="prefix_tuning", config_cls=PrefixTuningConfig, model_cls=PrefixEncoder) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..6eed77167a6e0b928e59e7e07fbf842c2d7a2d83 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/config.py @@ -0,0 +1,42 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from dataclasses import dataclass, field + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +@dataclass +class PrefixTuningConfig(PromptLearningConfig): + """ + This is the configuration class to store the configuration of a [`PrefixEncoder`]. + + Args: + encoder_hidden_size (`int`): The hidden size of the prompt encoder. + prefix_projection (`bool`): Whether to project the prefix embeddings. + """ + + encoder_hidden_size: int = field( + default=None, + metadata={"help": "The hidden size of the encoder"}, + ) + prefix_projection: bool = field( + default=False, + metadata={"help": "Whether to project the prefix tokens"}, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PREFIX_TUNING diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c4a3a383998b4b9154d96047847f77412110ba08 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prefix_tuning/model.py @@ -0,0 +1,101 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Based on https://github.com/THUDM/P-tuning-v2/blob/main/model/prefix_encoder.py +# with some refactor +import torch + + +class PrefixEncoder(torch.nn.Module): + r""" + The `torch.nn` model to encode the prefix. + + Args: + config ([`PrefixTuningConfig`]): The configuration of the prefix encoder. + + Example: + + ```py + >>> from peft import PrefixEncoder, PrefixTuningConfig + + >>> config = PrefixTuningConfig( + ... peft_type="PREFIX_TUNING", + ... task_type="SEQ_2_SEQ_LM", + ... num_virtual_tokens=20, + ... token_dim=768, + ... num_transformer_submodules=1, + ... num_attention_heads=12, + ... num_layers=12, + ... encoder_hidden_size=768, + ... ) + >>> prefix_encoder = PrefixEncoder(config) + ``` + + **Attributes**: + - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prefix encoder. + - **transform** (`torch.nn.Sequential`) -- The two-layer MLP to transform the prefix embeddings if + `prefix_projection` is `True`. + - **prefix_projection** (`bool`) -- Whether to project the prefix embeddings. + + Input shape: (`batch_size`, `num_virtual_tokens`) + + Output shape: (`batch_size`, `num_virtual_tokens`, `2*layers*hidden`) + """ + + def __init__(self, config): + super().__init__() + self.prefix_projection = config.prefix_projection + token_dim = config.token_dim + num_layers = config.num_layers + encoder_hidden_size = config.encoder_hidden_size + num_virtual_tokens = config.num_virtual_tokens + if self.prefix_projection and not config.inference_mode: + # Use a two-layer MLP to encode the prefix + self.embedding = torch.nn.Embedding(num_virtual_tokens, token_dim) + self.transform = torch.nn.Sequential( + torch.nn.Linear(token_dim, encoder_hidden_size), + torch.nn.Tanh(), + torch.nn.Linear(encoder_hidden_size, num_layers * 2 * token_dim), + ) + else: + self.embedding = torch.nn.Embedding(num_virtual_tokens, num_layers * 2 * token_dim) + + def forward(self, prefix: torch.Tensor): + if self.prefix_projection: + prefix_tokens = self.embedding(prefix) + past_key_values = self.transform(prefix_tokens) + else: + past_key_values = self.embedding(prefix) + return past_key_values + + def load_prompt_embeddings(self, prompt_embeddings: torch.Tensor) -> None: + """ + Load the flattened prompt embeddings saved by PEFT (`prompt_embeddings`). + + For prefix tuning, this is only supported when `prefix_projection=False`, because in that case the learned + parameters are the KV prefix itself (`embedding.weight` has shape `[num_virtual_tokens, + num_layers*2*token_dim]`). + + If `prefix_projection=True`, the parameters are (virtual token embeddings + an MLP) and there is no general way + to invert the projection to recover those parameters from a flattened KV prefix. + """ + if self.prefix_projection: + raise ValueError("Cannot load flattened prompt embeddings when `prefix_projection=True`.") + if prompt_embeddings.shape != self.embedding.weight.shape: + raise ValueError( + "Invalid `prompt_embeddings` shape. Expected " + f"{tuple(self.embedding.weight.shape)}, got {tuple(prompt_embeddings.shape)}." + ) + with torch.no_grad(): + self.embedding.weight.copy_(prompt_embeddings.to(self.embedding.weight.device)) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..c99ca6a26fea22e3d829c16eec378e82633e1b7b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PromptTuningConfig, PromptTuningInit +from .model import PromptEmbedding + + +__all__ = ["PromptEmbedding", "PromptTuningConfig", "PromptTuningInit"] + +register_peft_method(name="prompt_tuning", config_cls=PromptTuningConfig, model_cls=PromptEmbedding) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b41669efe898e88dfd015042e0c78258fb9b3a14 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/config.py @@ -0,0 +1,91 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import enum +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PromptLearningConfig +from peft.utils import PeftType + + +class PromptTuningInit(str, enum.Enum): + TEXT = "TEXT" + SAMPLE_VOCAB = "SAMPLE_VOCAB" + RANDOM = "RANDOM" + + +@dataclass +class PromptTuningConfig(PromptLearningConfig): + """ + This is the configuration class to store the configuration of a [`PromptEmbedding`]. + + Args: + prompt_tuning_init (Union[[`PromptTuningInit`], `str`]): + The initialization of the prompt embedding. `TEXT` will initialize with your text. `SAMPLE_VOCAB` will + initialize with randomly sampled tokens from the model's vocabulary. `RANDOM` will initialize with randomly + sampled continuous, soft tokens (warning: sampled soft tokens may fall outside of embedding manifold) + prompt_tuning_init_text (`str`, *optional*): + The text to initialize the prompt embedding. Only used if `prompt_tuning_init` is `TEXT`. + tokenizer_name_or_path (`str`, *optional*): + The name or path of the tokenizer. Only used if `prompt_tuning_init` is `TEXT`. + tokenizer_kwargs (`dict`, *optional*): + The keyword arguments to pass to `AutoTokenizer.from_pretrained`. Only used if `prompt_tuning_init` is + `TEXT`. + """ + + prompt_tuning_init: Union[PromptTuningInit, str] = field( + default=PromptTuningInit.RANDOM, + metadata={"help": "How to initialize the prompt tuning parameters"}, + ) + prompt_tuning_init_text: Optional[str] = field( + default=None, + metadata={ + "help": "The text to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`" + }, + ) + tokenizer_name_or_path: Optional[str] = field( + default=None, + metadata={ + "help": "The tokenizer to use for prompt tuning initialization. Only used if prompt_tuning_init is `TEXT`" + }, + ) + + tokenizer_kwargs: Optional[dict] = field( + default=None, + metadata={ + "help": ( + "The keyword arguments to pass to `AutoTokenizer.from_pretrained`. Only used if prompt_tuning_init is " + "`TEXT`" + ), + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PROMPT_TUNING + if (self.prompt_tuning_init == PromptTuningInit.TEXT) and not self.tokenizer_name_or_path: + raise ValueError( + f"When prompt_tuning_init='{PromptTuningInit.TEXT.value}', " + f"tokenizer_name_or_path can't be {self.tokenizer_name_or_path}." + ) + if (self.prompt_tuning_init == PromptTuningInit.TEXT) and self.prompt_tuning_init_text is None: + raise ValueError( + f"When prompt_tuning_init='{PromptTuningInit.TEXT.value}', " + f"prompt_tuning_init_text can't be {self.prompt_tuning_init_text}." + ) + if self.tokenizer_kwargs and (self.prompt_tuning_init != PromptTuningInit.TEXT): + raise ValueError( + f"tokenizer_kwargs only valid when using prompt_tuning_init='{PromptTuningInit.TEXT.value}'." + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3c6fc50d156fa98d2c8ebf8f1aaaa5a6fa1b7c9e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/prompt_tuning/model.py @@ -0,0 +1,105 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import math + +import torch + +from peft.utils.integrations import gather_params_ctx + +from .config import PromptTuningInit + + +class PromptEmbedding(torch.nn.Module): + """ + The model to encode virtual tokens into prompt embeddings. + + Args: + config ([`PromptTuningConfig`]): The configuration of the prompt embedding. + word_embeddings (`torch.nn.Module`): The word embeddings of the base transformer model. + + **Attributes**: + - **embedding** (`torch.nn.Embedding`) -- The embedding layer of the prompt embedding. + + Example: + + ```py + >>> from peft import PromptEmbedding, PromptTuningConfig + + >>> config = PromptTuningConfig( + ... peft_type="PROMPT_TUNING", + ... task_type="SEQ_2_SEQ_LM", + ... num_virtual_tokens=20, + ... token_dim=768, + ... num_transformer_submodules=1, + ... num_attention_heads=12, + ... num_layers=12, + ... prompt_tuning_init="TEXT", + ... prompt_tuning_init_text="Predict if sentiment of this review is positive, negative or neutral", + ... tokenizer_name_or_path="t5-base", + ... ) + + >>> # t5_model.shared is the word embeddings of the base model + >>> prompt_embedding = PromptEmbedding(config, t5_model.shared) + ``` + + Input Shape: (`batch_size`, `total_virtual_tokens`) + + Output Shape: (`batch_size`, `total_virtual_tokens`, `token_dim`) + """ + + def __init__(self, config, word_embeddings): + super().__init__() + + total_virtual_tokens = config.num_virtual_tokens * config.num_transformer_submodules + self.embedding = torch.nn.Embedding(total_virtual_tokens, config.token_dim) + if config.prompt_tuning_init == PromptTuningInit.SAMPLE_VOCAB and not config.inference_mode: + # Randomly sample tokens from the tokenizer's vocab + vocab_size = word_embeddings.num_embeddings + init_token_ids = torch.randint(0, vocab_size, (total_virtual_tokens,), dtype=torch.long).to( + word_embeddings.weight.device + ) + with gather_params_ctx(word_embeddings.parameters()): + word_embedding_weights = word_embeddings(init_token_ids).detach().clone() + word_embedding_weights = word_embedding_weights.to(torch.float32) + self.embedding.weight = torch.nn.Parameter(word_embedding_weights) + + elif config.prompt_tuning_init == PromptTuningInit.TEXT and not config.inference_mode: + from transformers import AutoTokenizer + + tokenizer_kwargs = config.tokenizer_kwargs or {} + # security: disallow trust_remote_code, as this could allow code execution when loading a prompt tuning + # checkpoint + tokenizer_kwargs.pop("trust_remote_code", None) + tokenizer = AutoTokenizer.from_pretrained(config.tokenizer_name_or_path, **tokenizer_kwargs) + init_text = config.prompt_tuning_init_text + init_token_ids = tokenizer(init_text)["input_ids"] + # Trim or iterate until num_text_tokens matches total_virtual_tokens + num_text_tokens = len(init_token_ids) + if num_text_tokens > total_virtual_tokens: + init_token_ids = init_token_ids[:total_virtual_tokens] + elif num_text_tokens < total_virtual_tokens: + num_reps = math.ceil(total_virtual_tokens / num_text_tokens) + init_token_ids = init_token_ids * num_reps + init_token_ids = init_token_ids[:total_virtual_tokens] + init_token_ids = torch.LongTensor(init_token_ids).to(word_embeddings.weight.device) + with gather_params_ctx(word_embeddings.parameters()): + word_embedding_weights = word_embeddings(init_token_ids).detach().clone() + word_embedding_weights = word_embedding_weights.to(torch.float32) + self.embedding.weight = torch.nn.Parameter(word_embedding_weights) + + def forward(self, indices): + # Just get embeddings + prompt_embeddings = self.embedding(indices) + return prompt_embeddings diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2901fbac1eac8dde6a92d7acbb989096dea22c27 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import PsoftConfig +from .layer import Linear, PsoftLayer +from .model import PsoftModel + + +__all__ = ["Linear", "PsoftConfig", "PsoftLayer", "PsoftModel"] + +register_peft_method(name="psoft", config_cls=PsoftConfig, model_cls=PsoftModel, prefix="psoft_") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b8f6a731d56af34788b7a03c20e10bfeb550cdb1 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/config.py @@ -0,0 +1,313 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class PsoftConfig(PeftConfig): + """ + Configuration for PSOFT (Efficient Orthogonal Fine-Tuning with Principal Subspace Adaptation). + + PSOFT inserts an r*r orthogonal transformation R between low-rank matrices A and B, so the low-rank update is ΔW = + B @ (R-I) @ A. Only R (and optional tunable vectors) are trained; A and B are initialized with psoft_init + (SVD-based, row-orthogonal A) and frozen. + + Args: + r (`int`): + Defaults to 32. PSOFT rank (r) controls the adapter capacity through an r*r transformation R. Smaller ranks + 32-128 are typically sufficient for simple tasks, More complex tasks may benefit from 64-256, increasing + expressiveness at the cost of additional parameters and computation. See the paper for empirically + validated settings: https://openreview.net/forum?id=FSHrinMArK. + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen (if + the model is a PreTrainedModel, the output layer excluded). If this is not specified, modules will be + chosen according to the model architecture. If the architecture is not known, an error will be raised -- in + this case, you should specify the target modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + psoft_alpha (`int`): Defaults to 32. It controls PSOFT scaling factor. Same semantics as LoRA alpha. + psoft_dropout (`float`): Defaults to 0.0. Dropout for PSOFT path. Same semantics as LoRA dropout. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + ab_svd_init (`Literal["psoft_init", "pissa_init"]`): + Defaults to 'psoft_init'. Initialization strategy for A and B used to construct the principal subspace in + PSOFT. 'psoft_init': SVD-based initialization with row-orthogonal A, ensuring strict orthogonality (PSOFT). + 'pissa_init': SVD-based initialization with symmetric A and B (standard PiSSA). + psoft_svd (`Literal["full", "lowrank"]`): + Defaults to 'full'. SVD backend for initialization: 'full' uses torch.linalg.svd; 'lowrank' uses + torch.svd_lowrank. + psoft_svd_lowrank_niter (`int`): + Only used when psoft_svd='lowrank'. Defaults to 10. Number of power iterations used by torch.svd_lowrank + when psoft_svd='lowrank'. + psoft_orth (`bool`): + Defaults to 'True'. If True, constrains R to be orthogonal via Cayley parameterization, preserving the + geometric relationships among column of the pre-trained weight vectors. If False, R is a free matrix + without orthogonality constraints. + psoft_mag_b (`bool`): + Defaults to 'True'. If True, learns a diagonal scaling vector on the 'output' side of R. Commonly paired + with psoft_mag_a to increase task adaptability, with slight distortion to the pre-trained geometry. + psoft_mag_a (`bool`): + Defaults to 'True'. If True, learns a diagonal scaling vector on the 'input' side of R. Commonly paired + with psoft_mag_b to increase task adaptability, with slight distortion to the pre-trained geometry. + use_cayley_neumann (`bool`): + Defaults to 'False'. Whether to use the Cayley-Neumann formulation of PSOFT or not. Set to True to improve + computational efficiency but comes at costs of bigger approximation error for orthogonality. + num_cayley_neumann_terms (`int`): + Defaults to 5. Only used when use_cayley_neumann=True. Number of Cayley-Neumann terms to use. Higher number + results in less approximation error for orthogonality. + cayley_neumann_eps (`optional[float]`): + Defaults to 'None'. Only used when use_cayley_neumann=True. Optional Frobenius-norm bound for the generator + matrix Q in the Cayley-Neumann approximation. If None (default), no rescaling is applied. If set to a value + in (0, 1) (e.g., 0.9), Q is rescaled whenever ||Q||_F exceeds the threshold to improve numerical stability. + See https://spherelab.ai/oftv2/ for details. + init_weights (`bool`): + Defaults to 'True'. Whether to initialize the weights of the PSOFT layers with their default + initialization. Don't change this setting, except if you know exactly what you're doing. + modules_to_save (`List[str]`): + List of modules apart from adapter layers to be set as trainable and saved in the final checkpoint. + layers_to_transform (`Union[List[int], int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "PSOFT rank (r) controls the adapter capacity through an r*r transformation R. " + "Smaller ranks 32-128 are typically sufficient for simple tasks, More complex tasks may benefit from 64-256, " + "increasing expressiveness at the cost of additional parameters and computation. " + "See the paper for empirically validated settings: https://openreview.net/forum?id=FSHrinMArK. " + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with PSOFT. " + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded). " + "If not specified, modules will be chosen according to the model architecture, If the architecture is " + "not known, an error will be raised -- in this case, you should specify the target modules manually. " + ), + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from PSOFT. "}, + ) + psoft_alpha: int = field( + default=32, metadata={"help": "It controls PSOFT scaling factor. Same semantics as LoRA alpha. "} + ) + psoft_dropout: float = field( + default=0.0, metadata={"help": "Dropout for PSOFT path. Same semantics as LoRA dropout. "} + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out). "}, + ) + ab_svd_init: Literal["psoft_init", "pissa_init"] = field( + default="psoft_init", + metadata={ + "help": ( + "Initialization strategy for A and B used to construct the principal subspace in PSOFT. " + "- 'psoft_init': SVD-based initialization with row-orthogonal A (asymmetric A and B), ensuring strict orthogonality (PSOFT). " + "- 'pissa_init': SVD-based initialization with symmetric A and B, without strict orthogonality constraint (standard PiSSA). " + ) + }, + ) + psoft_svd: Literal["full", "lowrank"] = field( + default="full", + metadata={ + "help": "SVD backend for initialization: 'full' uses torch.linalg.svd; 'lowrank' uses torch.svd_lowrank. " + }, + ) + psoft_svd_lowrank_niter: int = field( + default=10, + metadata={ + "help": "Number of power iterations used by torch.svd_lowrank when psoft_svd='lowrank'. Only used when psoft_svd='lowrank'. " + }, + ) + psoft_orth: bool = field( + default=True, + metadata={ + "help": ( + "If True, constrains R to be orthogonal via Cayley parameterization, preserving the geometric relationships among column of the pre-trained weight vectors. " + "If False, R is a free matrix without orthogonality constraints. " + ) + }, + ) + psoft_mag_b: bool = field( + default=True, + metadata={ + "help": ( + "If True, learns a diagonal scaling vector on the 'output' side of R. " + "Commonly paired with psoft_mag_a to increase task adaptability, with slight distortion to the pre-trained geometry. " + ) + }, + ) + psoft_mag_a: bool = field( + default=True, + metadata={ + "help": ( + "If True, learns a diagonal scaling vector on the 'input' side of R. " + "Commonly paired with psoft_mag_b to increase task adaptability, with slight distortion to the pre-trained geometry. " + ) + }, + ) + use_cayley_neumann: bool = field( + default=False, + metadata={ + "help": "Whether to use the Cayley-Neumann Formulation of PSOFT or not. Set to True to improve computational efficiency but comes at costs of bigger approximation error for orthogonality. " + }, + ) + num_cayley_neumann_terms: int = field( + default=5, + metadata={ + "help": "Number of Cayley-Neumann terms to use. Higher number results in less approximation error for orthogonality. Only used when use_cayley_neumann=True." + }, + ) + cayley_neumann_eps: Optional[float] = field( + default=None, + metadata={ + "help": ( + "Optional Frobenius-norm bound for the generator matrix Q in the Cayley-Neumann approximation. Only used when use_cayley_neumann=True. " + "If None (default), no rescaling is applied. " + "If set to a value in (0, 1) (e.g., 0.9), Q is rescaled whenever ||Q||_F exceeds the threshold to improve numerical stability. " + "See https://spherelab.ai/oftv2/ for details. " + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from PSOFT layers to be set as trainable and saved in the final checkpoint. " + "For example, in Sequence Classification or Token Classification tasks, " + "the final layer `classifier/score` are randomly initialized and as such need to be trainable and saved. " + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the PSOFT layers with their default initialization. " + "Don't change this setting, except if you know exactly what you're doing. " + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index. " + "This only works when target_modules is a list of str." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern. " + "This only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`. " + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PSOFT + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + + if self.r <= 0: + raise ValueError(f"`r` must be a positive integer; got {self.r}.") + + allowed_inits = {"psoft_init", "pissa_init"} + if self.ab_svd_init not in allowed_inits: + raise ValueError(f"`ab_svd_init` must be one of {sorted(allowed_inits)}; got {self.ab_svd_init!r}.") + + allowed_svd_backends = {"full", "lowrank"} + if self.psoft_svd not in allowed_svd_backends: + raise ValueError(f"`psoft_svd` must be one of {sorted(allowed_svd_backends)}; got {self.psoft_svd!r}.") + + DEFAULT_LOW_RANK_NITER = self.__dataclass_fields__["psoft_svd_lowrank_niter"].default + if self.psoft_svd != "lowrank" and self.psoft_svd_lowrank_niter != DEFAULT_LOW_RANK_NITER: + warnings.warn( + "`psoft_svd_lowrank_niter` is only used when `psoft_svd='lowrank'`. " + f"Got psoft_svd={self.psoft_svd!r}, so psoft_svd_lowrank_niter=" + f"{self.psoft_svd_lowrank_niter} will be ignored.", + UserWarning, + ) + + DEFAULT_NUM_CAYLEY_NEUMANN_TERMS = self.__dataclass_fields__["num_cayley_neumann_terms"].default + if self.use_cayley_neumann: + if self.num_cayley_neumann_terms <= 0: + raise ValueError( + f"`num_cayley_neumann_terms` must be a positive integer; got {self.num_cayley_neumann_terms}." + ) + if self.cayley_neumann_eps is not None and not (0.0 < self.cayley_neumann_eps < 1.0): + raise ValueError(f"`cayley_neumann_eps` must be in (0, 1) when set; got {self.cayley_neumann_eps}.") + else: + if self.num_cayley_neumann_terms != DEFAULT_NUM_CAYLEY_NEUMANN_TERMS: + warnings.warn( + "`num_cayley_neumann_terms` is only used when `use_cayley_neumann=True`. " + f"Since `use_cayley_neumann=False`, `num_cayley_neumann_terms={self.num_cayley_neumann_terms}` will be ignored.", + UserWarning, + ) + if self.cayley_neumann_eps is not None: + warnings.warn( + "`cayley_neumann_eps` is only used when `use_cayley_neumann=True`. " + f"Since `use_cayley_neumann=False`, `cayley_neumann_eps={self.cayley_neumann_eps}` will be ignored.", + UserWarning, + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..a5e82fd3d93a9e7d8839f99a4ad7d0f92f8de60b --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/layer.py @@ -0,0 +1,488 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import Any, Optional + +import torch +from torch import nn, svd_lowrank + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils.integrations import gather_params_ctx +from peft.utils.other import transpose + +from .config import PsoftConfig + + +class OrthLayer(nn.Module): + """ + r*r orthogonal transformation R used in PSOFT between A and B. Forward: output = input @ R.T + """ + + def __init__( + self, + size: int, + orth: bool = True, + mag_b: bool = True, + mag_a: bool = True, + use_cayley_neumann: bool = False, + num_cayley_neumann_terms: int = 5, + cayley_neumann_eps: Optional[float] = None, + ): + super().__init__() + self.size = size + self.orth = orth + self.mag_b = mag_b + self.mag_a = mag_a + self.use_cayley_neumann = use_cayley_neumann + self.num_cayley_neumann_terms = num_cayley_neumann_terms + self.cayley_neumann_eps = cayley_neumann_eps + + if orth: + self.weight = nn.Parameter(torch.empty((size * (size - 1)) // 2)) + rows, cols = torch.triu_indices(size, size, 1) + self.register_buffer("rows", rows, persistent=False) + self.register_buffer("cols", cols, persistent=False) + else: + self.weight = nn.Parameter(torch.empty(size, size)) + + self.vector_b = nn.Parameter(torch.empty(size)) if mag_b else None + self.vector_a = nn.Parameter(torch.empty(size)) if mag_a else None + + def reset_parameters(self, init_weights: bool = True) -> None: + params = [self.weight] + if self.vector_b is not None: + params.append(self.vector_b) + if self.vector_a is not None: + params.append(self.vector_a) + + if any(p.is_meta for p in params): + return + + with torch.no_grad(): + if init_weights: + if self.orth: + self.weight.zero_() + else: + nn.init.eye_(self.weight) + + if self.vector_b is not None: + self.vector_b.fill_(1.0) + if self.vector_a is not None: + self.vector_a.fill_(1.0) + else: + if self.orth: + nn.init.normal_(self.weight, mean=0.0, std=0.1) + else: + nn.init.eye_(self.weight) + self.weight.add_(torch.randn_like(self.weight) * 0.1) + + if self.vector_b is not None: + self.vector_b.fill_(1.0) + if self.vector_a is not None: + self.vector_a.fill_(1.0) + + def forward(self, input: torch.Tensor) -> torch.Tensor: + R = self.get_matrix() + + if input.device.type == "cpu" and input.dtype in (torch.float16, torch.bfloat16): + compute_dtype = torch.float32 + else: + compute_dtype = input.dtype + + return (input.to(compute_dtype) @ R.to(compute_dtype).t()).to(input.dtype) + + # Adapted from the Cayley/Neumann-based orthogonal parametrization used in OFT v2 + # (PEFT implementation: https://github.com/huggingface/peft/blob/main/src/peft/tuners/oft/layer.py) #L104 + def _skew_symmetric(self) -> torch.Tensor: + Q = torch.zeros((self.size, self.size), device=self.weight.device, dtype=self.weight.dtype) + Q = Q.index_put((self.rows, self.cols), self.weight) + return Q - Q.transpose(0, 1) + + # Adapted from the Cayley/Neumann-based orthogonal parametrization used in OFT v2 + # (PEFT implementation: https://github.com/huggingface/peft/blob/main/src/peft/tuners/oft/layer.py) #L160 + def _project_Q(self, Q: torch.Tensor, eps: float = 0.9) -> torch.Tensor: + norm = torch.linalg.norm(Q, ord="fro") + if torch.isfinite(norm) and norm > eps: + Q = Q * (eps / (norm + 1e-12)) + return Q + + # R = (I+Q)(I-Q)^(-1) + def get_matrix(self) -> torch.Tensor: + cast_to_fp32 = False + orig_dtype = None + + if not self.orth: + R = self.weight + else: + Q = self._skew_symmetric() + orig_dtype = Q.dtype + cast_to_fp32 = (Q.device.type == "cpu") and (orig_dtype in (torch.float16, torch.bfloat16)) + if cast_to_fp32: + Q = Q.float() + + id_mat = torch.eye(self.size, device=Q.device, dtype=Q.dtype) + + if self.use_cayley_neumann: + if self.cayley_neumann_eps is not None: + Q = self._project_Q(Q, eps=self.cayley_neumann_eps) + t = int(self.num_cayley_neumann_terms) + + R = id_mat.clone() + if t > 1: + R.add_(Q, alpha=2.0) + if t > 2: + Q_squared = Q @ Q + R.add_(Q_squared, alpha=2.0) + + Q_power = Q_squared + for _ in range(3, t - 1): + Q_power = Q_power @ Q + R.add_(Q_power, alpha=2.0) + + Q_power = Q_power @ Q + R.add_(Q_power) + else: + R = torch.linalg.solve(id_mat - Q, id_mat + Q, left=False) + + # Apply scaling vectors to R + if self.vector_b is not None: + R = self.vector_b[:, None] * R + if self.vector_a is not None: + R = R * self.vector_a[None, :] + + if cast_to_fp32: + R = R.to(orig_dtype) + + return R + + def __repr__(self) -> str: + return ( + f"psoft.{self.__class__.__name__}(" + f"size={self.size}, orth={self.orth}, " + f"use_cayley_neumann={self.use_cayley_neumann}, " + f"num_cayley_neumann_terms={int(self.num_cayley_neumann_terms)}, " + f"cayley_neumann_eps={self.cayley_neumann_eps}, " + f"mag_a={self.mag_a}, mag_b={self.mag_b}" + f")" + ) + + +class PsoftLayer(BaseTunerLayer): + adapter_layer_names: tuple[str, ...] = ("psoft_R",) + other_param_names: tuple[str, ...] = ( + "r", + "psoft_alpha", + "scaling", + "psoft_dropout", + "psoft_svd", + "psoft_svd_lowrank_niter", + "ab_svd_init", + ) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + super().__init__() + self.base_layer = base_layer + + # per-adapter hyperparams + self.r: dict[str, int] = {} + self.psoft_alpha: dict[str, float] = {} + self.scaling: dict[str, float] = {} + self.psoft_dropout = nn.ModuleDict({}) + self.psoft_svd: dict[str, str] = {} + self.psoft_svd_lowrank_niter: dict[str, int] = {} + self.ab_svd_init: dict[str, Optional[str]] = {} + + # per-adapter trainable module + self.psoft_R = nn.ModuleDict({}) + + # per-adapter cache state + self._psoft_A_cache = BufferDict(persistent=False) + self._psoft_B_cache = BufferDict(persistent=False) + + self.merged_adapters: list[str] = [] + self._disable_adapters = False + self.kwargs = kwargs + + self.fan_in_fan_out = False + + base_layer = self.get_base_layer() + in_features, out_features = _get_in_out_features(base_layer) + self.in_features = in_features + self.out_features = out_features + + def _get_psoft_ab_cache_buffers(self, adapter_name: str): + return self._psoft_A_cache[adapter_name], self._psoft_B_cache[adapter_name] + + def _set_psoft_ab_cache_buffers(self, adapter_name: str, A: torch.Tensor, B: torch.Tensor) -> None: + self._psoft_A_cache[adapter_name] = A + self._psoft_B_cache[adapter_name] = B + + def update_layer(self, adapter_name: str, config: PsoftConfig, **kwargs: Any) -> None: + ab_svd_init = config.ab_svd_init + init_weights = config.init_weights + + r = int(config.r) + + self.fan_in_fan_out = config.fan_in_fan_out + + self.r[adapter_name] = r + self.psoft_alpha[adapter_name] = config.psoft_alpha + self.scaling[adapter_name] = config.psoft_alpha / r + + self.psoft_dropout[adapter_name] = ( + nn.Dropout(p=config.psoft_dropout) if config.psoft_dropout > 0.0 else nn.Identity() + ) + + self.ab_svd_init[adapter_name] = config.ab_svd_init + self.psoft_svd[adapter_name] = config.psoft_svd + self.psoft_svd_lowrank_niter[adapter_name] = config.psoft_svd_lowrank_niter + + self.psoft_R[adapter_name] = OrthLayer( + size=r, + orth=config.psoft_orth, + mag_b=config.psoft_mag_b, + mag_a=config.psoft_mag_a, + use_cayley_neumann=config.use_cayley_neumann, + num_cayley_neumann_terms=config.num_cayley_neumann_terms, + cayley_neumann_eps=config.cayley_neumann_eps, + ) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.psoft_R[adapter_name].reset_parameters(init_weights=init_weights) + self.psoft_R[adapter_name].requires_grad_(True) + + with gather_params_ctx(self.get_base_layer().weight): + self._build_psoft_ab_cache_buffers(adapter_name, ab_svd_init) + + self.set_adapter([adapter_name]) + + # Adapted from the asymmetric SVD used in PiSSA + # (PEFT implementation: https://github.com/huggingface/peft/blob/main/src/peft/tuners/lora/layer.py) #L316 + def _build_psoft_ab_cache_buffers(self, adapter_name: str, init_type: str) -> None: + with torch.no_grad(): + base = self.get_base_layer() + weight = base.weight + dtype = weight.dtype + if dtype not in (torch.float32, torch.float16, torch.bfloat16): + raise TypeError("PSOFT init requires float32/float16/bfloat16. Re-quantize after init if needed.") + + # W: (out, in) fp32 + W = transpose(weight.to(torch.float32), self.fan_in_fan_out) + + r = self.r[adapter_name] + Vr, Sr, Uhr = self._compute_svd_factors( + W, + r, + svd_mode=self.psoft_svd[adapter_name], + niter=self.psoft_svd_lowrank_niter[adapter_name], + ) + + Sr_scaled = Sr / self.scaling[adapter_name] + + if init_type == "psoft_init": + A = Uhr # (r, in) + B = Vr @ torch.diag(Sr_scaled) # (out, r) + elif init_type == "pissa_init": + s_sqrt = torch.sqrt(Sr_scaled) + A = torch.diag(s_sqrt) @ Uhr # (r, in) + B = Vr @ torch.diag(s_sqrt) # (out, r) + else: + raise ValueError(f"Unknown ab_svd_init: {init_type}") + + A = A.contiguous().detach() + B = B.contiguous().detach() + + self._set_psoft_ab_cache_buffers(adapter_name, A, B) + + def _compute_svd_factors(self, weight: torch.Tensor, r: int, *, svd_mode: str, niter: int): + # weight: (out, in) fp32 + if svd_mode == "full": + U, S, Vh = torch.linalg.svd(weight.data, full_matrices=False) + Vr = U[:, :r] # (out, r) + Sr = S[:r] # (r,) + Uhr = Vh[:r, :] # (r, in) + elif svd_mode == "lowrank": + U, S, V = svd_lowrank(weight.data, q=r, niter=niter) # V: (in, r) + Vr = U[:, :r] + Sr = S[:r] + Uhr = V[:, :r].t() # (r, in) + else: + raise ValueError(f"Unknown svd_mode: {svd_mode}") + return Vr, Sr, Uhr + + +class Linear(nn.Module, PsoftLayer): + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + config: PsoftConfig, + **kwargs: Any, + ) -> None: + super().__init__() + PsoftLayer.__init__(self, base_layer, **kwargs) + + self.fan_in_fan_out = config.fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, config=config, **kwargs) + + def _get_R_matrix(self, adapter_name: str) -> torch.Tensor: + return self.psoft_R[adapter_name].get_matrix() + + def get_delta_weight(self, adapter_name: str) -> torch.Tensor: + """ + ΔW = scaling * B (R - id_mat) A Returns in base weight layout (respecting fan_in_fan_out). + """ + + A, B = self._get_psoft_ab_cache_buffers(adapter_name) + base_w = self.get_base_layer().weight + device = base_w.device + out_dtype = base_w.dtype + + R = self._get_R_matrix(adapter_name) + r = self.r[adapter_name] + + compute_dtype = ( + torch.float32 if (device.type == "cpu" and out_dtype in (torch.float16, torch.bfloat16)) else out_dtype + ) + + A_c = A.to(device=device, dtype=compute_dtype) + B_c = B.to(device=device, dtype=compute_dtype) + R_c = R.to(device=device, dtype=compute_dtype) + + id_mat = torch.eye(r, device=device, dtype=compute_dtype) + delta = B_c @ (R_c - id_mat) @ A_c # (out, in) + delta = transpose(delta, self.fan_in_fan_out) + delta = delta * self.scaling[adapter_name] + + return delta.to(dtype=out_dtype) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + base_layer = self.get_base_layer() + + for active_adapter in adapter_names: + if active_adapter not in self.psoft_R: + continue + + if safe_merge: + orig_weight = base_layer.weight.data.clone() + orig_dtype = orig_weight.dtype + + delta_weight = self.get_delta_weight(active_adapter) + orig_weight += delta_weight.to(orig_dtype) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight.to(base_layer.weight.dtype) + + self.merged_adapters.append(active_adapter) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.", UserWarning) + return + + weight = self.get_base_layer().weight + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + + if active_adapter not in self.psoft_R: + continue + + orig_dtype = weight.dtype + delta_weight = self.get_delta_weight(active_adapter) + weight.data -= delta_weight.to(orig_dtype) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + psoft_keys = self.psoft_R.keys() + for active_adapter in self.active_adapters: + if active_adapter not in psoft_keys: + continue + + A, B = self._get_psoft_ab_cache_buffers(active_adapter) + + dropout = self.psoft_dropout[active_adapter] + scaling = self.scaling[active_adapter] + R_layer = self.psoft_R[active_adapter] + + x_cast = self._cast_input_dtype(x, A.dtype) + x_d = dropout(x_cast) + + A_c = A.to(device=x_d.device, dtype=x_d.dtype) + B_c = B.to(device=x_d.device, dtype=x_d.dtype) + + xa = x_d @ A_c.t() + xr = R_layer(xa) + + delta_y = (xr - xa) @ B_c.t() + result = result + (delta_y * scaling) + + result = result.to(torch_result_dtype) + + return result + + def __repr__(self) -> str: + return "psoft." + super().__repr__() + + +def dispatch_default( + target: nn.Module, + adapter_name: str, + config: PsoftConfig, + **kwargs, +) -> Optional[nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if config.fan_in_fan_out: + warnings.warn( + "fan_in_fan_out=True is not compatible with `torch.nn.Linear`. Setting fan_in_fan_out=False." + ) + config.fan_in_fan_out = False + new_module = Linear(target, adapter_name, config=config, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..27e0306b2f3ac55bc4c6d5d3a413b991ab6df2dc --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/psoft/model.py @@ -0,0 +1,84 @@ +# Copyright 2026-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Optional + +from torch import nn + +from peft.tuners.tuners_utils import BaseTuner, get_device_map +from peft.utils import TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING + +from .config import PsoftConfig +from .layer import PsoftLayer, dispatch_default + + +class PsoftModel(BaseTuner): + """ + PSOFT (Efficient Orthogonal Fine-Tuning with Principal Subspace Adaptation) model. + + Inserts an r*r orthogonal (or scaled) transformation R between low-rank A and B: ΔW = B @ (R-I) @ A. Use + ab_svd_init="psoft_init" to initialize A/B from SVD and freeze them, training only R (and optional magnitude + vectors). + + Args: + model: The model to adapt. + config: PsoftConfig. + adapter_name: Adapter name, default "default". + low_cpu_mem_usage: Create empty adapter weights on meta device. + """ + + prefix: str = "psoft_" + tuner_layer_cls = PsoftLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + peft_config: PsoftConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + *, + parameter_name: Optional[str] = None, + ) -> None: + if current_key is None: + raise ValueError("Current key must not be None.") + + kwargs = { + "target_name": current_key, + "parameter_name": parameter_name, + } + + if isinstance(target, PsoftLayer): + target.update_layer(adapter_name, config=peft_config, **kwargs) + return + + device_map = get_device_map(self.model) + new_module = self._create_new_module(peft_config, adapter_name, target, device_map=device_map, **kwargs) + + if adapter_name not in self.active_adapters: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(psoft_config: PsoftConfig, adapter_name: str, target: nn.Module, **kwargs) -> nn.Module: + new_module = dispatch_default(target, adapter_name, config=psoft_config, **kwargs) + if new_module is None: + raise ValueError( + f"Target module {target} is not supported by minimal PSOFT. Only torch.nn.Linear is supported." + ) + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..2cc9e19c0f67276d8a054b01a3ef08faed51d3fa --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/__init__.py @@ -0,0 +1,26 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +from peft.utils import register_peft_method + +from .config import PveraConfig +from .layer import Linear, PveraLayer +from .model import PveraModel + + +__all__ = ["Linear", "PveraConfig", "PveraLayer", "PveraModel"] + + +register_peft_method(name="pvera", config_cls=PveraConfig, model_cls=PveraModel, prefix="pvera_lambda_") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..8fc7fcbbfda049f92b6a1a432a738b7a08835363 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/bnb.py @@ -0,0 +1,419 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight +from peft.utils.other import transpose + +from .layer import PveraLayer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, PveraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + pvera_A, + pvera_B, + r: int = 0, + pvera_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + d_initial: float = 0.1, + **kwargs, + ) -> None: + super().__init__() + PveraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + pvera_A, + pvera_B, + r, + pvera_dropout=pvera_dropout, + init_weights=init_weights, + d_initial=d_initial, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + if self.merged: + warnings.warn( + f"Already following adapters were merged {','.join(self.merged_adapters)}. " + f"You are now additionally merging {','.join(self.active_adapters)}." + ) + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.pvera_lambda_d.keys(): + continue + + warnings.warn( + "Merge pvera module to 8-bit linear may get different generations due to rounding errors." + ) + pvera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + output = dequantize_bnb_weight(weight, state) + w_data = output.to(pvera_data.dtype).to(pvera_data.device) + pvera_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.pvera_lambda_d.keys(): + continue + warnings.warn( + "Unmerge pvera module to 8-bit linear may get different generations due to rounding errors." + ) + pvera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + w_data = output.to(pvera_data.dtype).to(pvera_data.device) - pvera_data + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): The name of the adapter for which the delta weight should be computed. + + Returns: + torch.Tensor: The computed delta weight for the PVeRA adapter. + + Note: + This method implements the PVeRA-specific weight update. Unlike LoRA, PVeRA uses shared projection + matrices (pvera_A and pvera_B) across all layers, along with per-layer trainable parameters (lambda_d + and lambda_b). + """ + # Retrieve shared projection matrices + pvera_A = self.pvera_A[adapter] + pvera_B = self.pvera_B[adapter] + + # Retrieve per-layer trainable parameters + device = pvera_B.device + dtype = pvera_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + lambda_d = self.pvera_lambda_d[adapter] + lambda_b = self.pvera_lambda_b[adapter] + + if cast_to_fp32: + pvera_A = pvera_A.float() + pvera_B = pvera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = pvera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = pvera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + # In PVeRA, the first half of the lambda_d and sliced_A vector corresponds to the mean (mu) and the second half to the log-variance (logvar). When merging, we can only do mean sampling, and therefore only need the first half + lambda_d = lambda_d[: lambda_d.size(0) // 2, :] + sliced_A = sliced_A[: sliced_A.size(0) // 2, :] + + # PVeRA-specific computation: + # 1. Apply lambda_d to the input projection (pvera_A) + # 2. Apply lambda_b to the output projection (pvera_B) + # 3. Compute the outer product of the scaled projections + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Perform the forward pass using the PVeRA adapter. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after applying the PVeRA adaptation. + + Note: + This method implements the PVeRA-specific forward pass. It applies the shared projections (pvera_A and + pvera_B) along with the per-layer trainable parameters (lambda_d and lambda_b) to compute the adapter + output. + """ + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.pvera_lambda_d.keys(): + continue + + lambda_d = self.pvera_lambda_d[active_adapter] + lambda_b = self.pvera_lambda_b[active_adapter] + + pvera_A = self.pvera_A[active_adapter] + pvera_B = self.pvera_B[active_adapter] + + dropout = self.pvera_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = lambda_d.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + sliced_A = pvera_A[:, : self.in_features].to(x.device) + sliced_B = pvera_B[: self.out_features, :].to(x.device) + + x_temp = dropout(x.to(lambda_d.dtype)) + + adapter_output = lambda_b * torch.nn.functional.linear( + lambda_d * torch.nn.functional.linear(x_temp, sliced_A), sliced_B + ) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + result = result + adapter_output + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "pvera." + rep + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, PveraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + pvera_A, + pvera_B, + r: int = 0, + pvera_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + d_initial: float = 0.1, + **kwargs, + ) -> None: + super().__init__() + PveraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + pvera_A, + pvera_B, + r, + pvera_dropout=pvera_dropout, + init_weights=init_weights, + d_initial=d_initial, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + if self.merged: + warnings.warn( + f"Already following adapters were merged {','.join(self.merged_adapters)}. " + f"You are now additionally merging {','.join(self.active_adapters)}." + ) + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.pvera_lambda_d.keys(): + continue + + warnings.warn( + "Merge pvera module to 4-bit linear may get different generations due to rounding errors." + ) + pvera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + pvera_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.pvera_lambda_d.keys(): + continue + warnings.warn( + "Unmerge pvera module to 4-bit linear may get different generations due to rounding errors." + ) + pvera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) - pvera_data + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + + def get_delta_weight(self, adapter) -> torch.Tensor: + pvera_A = self.pvera_A[adapter] + pvera_B = self.pvera_B[adapter] + + device = pvera_B.device + dtype = pvera_B.dtype + + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + lambda_d = self.pvera_lambda_d[adapter] + lambda_b = self.pvera_lambda_b[adapter] + + if cast_to_fp32: + pvera_A = pvera_A.float() + pvera_B = pvera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = pvera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = pvera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + # In PVeRA, the first half of the lambda_d and sliced_A vector corresponds to the mean (mu) and the second half to the log-variance (logvar). When merging, we can only do mean sampling, and therefore only need the first half + lambda_d = lambda_d[: lambda_d.size(0) // 2, :] + sliced_A = sliced_A[: sliced_A.size(0) // 2, :] + + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result = result.clone() + for active_adapter in self.active_adapters: + if active_adapter not in self.pvera_lambda_d.keys(): + continue + + lambda_d = self.pvera_lambda_d[active_adapter] + lambda_b = self.pvera_lambda_b[active_adapter] + + pvera_A = self.pvera_A[active_adapter] + pvera_B = self.pvera_B[active_adapter] + + dropout = self.pvera_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = lambda_d.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + sliced_A = pvera_A[:, : self.in_features].to(x.device) + sliced_B = pvera_B[: self.out_features, :].to(x.device) + + x_temp = dropout(x.to(lambda_d.dtype)) + + adapter_output = lambda_b * torch.nn.functional.linear( + lambda_d * torch.nn.functional.linear(x_temp, sliced_A), sliced_B + ) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + result = result + adapter_output + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "pvera." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9c3524afd718ab0261e6d23fc81a1a3d16833211 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/config.py @@ -0,0 +1,205 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class PveraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`PveraModel`]. + + Paper: https://www.arxiv.org/abs/2512.07703. + + Args: + r (`int`, *optional*, defaults to `256`): + PVeRA parameter dimension ("rank"). Choose higher values than LoRA ranks here, since PVeRA shares + parameters across layers and therefore uses far fewer parameters than LoRA. + target_modules (`Union[List[str], str]`): + The names of the modules to apply PVeRA to. Only linear layers are supported. When passing a string, a + regex match will be performed. If this is specified as 'all-linear', then all linear/Conv1D modules are + chosen. If this is not specified, modules will bechosen according to the model architecture. If the + architecture is not known, an error will be raised. + projection_prng_key (`int`): + PVeRA PRNG init key. Used for initialising pvera_A and pvera_B for new models or when loading a checkpoint + that did not include these projections. Defaults to `0`. + save_projection (`bool`): + Whether to save the pvera_A / pvera_B projections in the state dict alongside per layer lambda_b / lambda_d + weights. This will increase the size of the checkpoint, but guarantee that we can reload the checkpoint on + all system configurations. Defaults to `True`. + pvera_dropout (`float`): + The dropout probability for PVeRA layers. + d_initial (`float`, *optional*, defaults to `0.1`): + Initial value for `pvera_lambda_d` vector used when initializing the PVeRA parameters. Small values (<=0.1) + are recommended. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + bias (`str`): + Bias type for PVeRA. Can be 'none', 'all' or 'pvera_only'. If 'all' or 'pvera_only', the corresponding + biases will be updated during training. Be aware that this means that, even when disabling the adapters, + the model will not produce the same output as the base model would have without adaptation. + modules_to_save (`List[str]`): + List of modules apart from PVeRA layers to be set as trainable and saved in the final checkpoint. + init_weights (`bool`): + Whether to initialize the weights of the PVeRA layers with their default initialization. Don't change this + setting, except if you know exactly what you're doing. + layers_to_transform (`Union[List[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply the PVeRA transformations on + the layer indexes that are specified in this list. If a single integer is passed, it will apply the PVeRA + transformations on the layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + sample_at_inference (`bool` | `dict`, defaults to `False`): + Whether to sample from the learned PVeRA distribution at inference. If false, the learned mean is used. The + default is False (indicating false for all adapters). If True is provided, then the value will be true for + all adapters. If a dict is provided, then a specific value can be specified per adapter (with False by + default for non-specified adapters). For example + `sample_at_inference={'encoder.layer.0.attention.attention.query': True}` will only sample at inference for + one specific adapter. + """ + + r: int = field( + default=256, + metadata={ + "help": ( + "PVeRA parameter dimension ('rank'). Choose higher values than LoRA ranks here, since PVeRA shares " + "parameters across layers and therefore uses far fewer parameters than LoRA." + ) + }, + ) + + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The names of the modules to apply PVeRA to. Only linear layers are supported. When passing a string, a " + "regex match will be performed. If this is specified as 'all-linear', then all linear/Conv1D modules are " + "chosen. If this is not specified, modules will bechosen according to the model architecture. If the " + "architecture is not known, an error will be raised." + ) + }, + ) + projection_prng_key: int = field( + default=0, + metadata={ + "help": ( + "PVeRA PRNG init key. Used for initialising pvera_A and pvera_B for new models or when loading a checkpoint " + "that did not include these projections. Defaults to `0`." + ) + }, + ) + save_projection: bool = field( + default=True, + metadata={ + "help": ( + "Whether to save the pvera_A / pvera_B projections in the state dict alongside per layer lambda_b / lambda_d " + "weights. This will increase the size of the checkpoint, but guarantee that we can reload the checkpoint on " + "all system configurations. Defaults to `True`." + ) + }, + ) + pvera_dropout: float = field(default=0.0, metadata={"help": "The dropout probability for PVeRA layers."}) + d_initial: float = field(default=0.1, metadata={"help": "Initial value for d vector. Default is 0.1."}) + fan_in_fan_out: bool = field( + default=False, + metadata={ + "help": ( + "Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses " + "`Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`." + ) + }, + ) + bias: str = field( + default="none", + metadata={ + "help": ( + "Bias type for PVeRA. Can be 'none', 'all' or 'pvera_only'. If 'all' or 'pvera_only', the corresponding " + "biases will be updated during training. Be aware that this means that, even when disabling the adapters, " + "the model will not produce the same output as the base model would have without adaptation." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from PVeRA layers to be set as trainable and saved in the final checkpoint." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the PVeRA layers with their default initialization. Don't change this " + "setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, if this argument is specified, it will apply the PVeRA transformations on " + "the layer indexes that are specified in this list. If a single integer is passed, it will apply the PVeRA " + "transformations on the layer at this index." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the " + "`nn.ModuleList` of the model, which is often called `'layers'` or `'h'`." + ) + }, + ) + sample_at_inference: bool = field( + default=False, + metadata={ + "help": ( + "Whether to sample from the learned PVeRA distribution at inference. If false, the learned mean is used. The " + "default is False (indicating false for all adapters). If True is provided, then the value will be true for " + "all adapters. If a dict is provided, then a specific value can be specified per adapter (with False by " + "default for non-specified adapters). For example " + "`sample_at_inference={'encoder.layer.0.attention.attention.query': True}` will only sample at inference for " + "one specific adapter." + ), + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.PVERA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + if not self.save_projection: + warnings.warn( + "Specified to not save pvera_A and pvera_B within the state dictionary, instead they will be restored " + "using the PRNG key store in `config.projection_prng_key`. Consider setting `config.save_projection` " + "to `True` to guarantee restoring the checkpoint correctly on all system configurations." + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..02940f7a2f7a5f571d5a3af94164f744007a1b2e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/layer.py @@ -0,0 +1,310 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .._buffer_dict import BufferDict + + +class PveraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("pvera_lambda_b", "pvera_lambda_d") + other_param_names = ("pvera_A", "pvera_B") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.pvera_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.pvera_lambda_b = nn.ParameterDict({}) + self.pvera_lambda_d = nn.ParameterDict({}) + + # Stores a reference to the pvera_A/B BufferDict. + # Set to `None` otherwise to avoid computation with random weights + self.pvera_A: Optional[BufferDict] = None + self.pvera_B: Optional[BufferDict] = None + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + in_features, out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + @property + def merged(self) -> bool: + return bool(self.merged_adapters) + + def update_layer( + self, + adapter_name, + pvera_A: BufferDict, + pvera_B: BufferDict, + r, + pvera_dropout, + init_weights, + d_initial: float = 0.1, + inference_mode: bool = False, + **kwargs, + ): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + self.r[adapter_name] = r + if pvera_dropout > 0.0: + pvera_dropout_layer = nn.Dropout(p=pvera_dropout) + else: + pvera_dropout_layer = nn.Identity() + + self.pvera_dropout.update(nn.ModuleDict({adapter_name: pvera_dropout_layer})) + # Actual trainable parameters + self.pvera_lambda_b[adapter_name] = nn.Parameter(torch.ones(self.out_features), requires_grad=True) + self.pvera_lambda_d[adapter_name] = nn.Parameter(torch.randn(r * 2), requires_grad=True) + + # non trainable references to pvera_A/B buffers + self.pvera_A = pvera_A + self.pvera_B = pvera_B + if adapter_name not in pvera_A: + # This means that this is not the first PVeRA adapter. We have to add an entry in the dict for this adapter. + if len(self.pvera_A) < 1: + raise ValueError( + "The `pvera_A` and `pvera_B` buffers are empty. This should not happen. Please report this issue." + ) + # we can take any of the existing adapter's parameters, as they should all be identical + pvera_A_param = list(self.pvera_A.values())[0] + pvera_B_param = list(self.pvera_B.values())[0] + + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional PVeRA " + "adapter was added after the first one with incompatible shapes." + ) + # check input size + if pvera_A_param.shape[1] < self.in_features: + raise ValueError(error_tmpl.format("pvera_A", pvera_A_param.shape[1], self.in_features)) + # check output size + if pvera_B_param.shape[0] < self.out_features: + raise ValueError(error_tmpl.format("pvera_B", pvera_B_param.shape[0], self.out_features)) + # check r + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional PVeRA " + "adapter with a lower rank was added after the first one; loading the adapters " + "in reverse order may solve this." + ) + if pvera_A_param.shape[0] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("pvera_A", pvera_A_param.shape[0], self.r[adapter_name])) + if pvera_B_param.shape[1] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("pvera_B", pvera_B_param.shape[1], self.r[adapter_name])) + + self.pvera_A[adapter_name] = pvera_A_param + self.pvera_B[adapter_name] = pvera_B_param + + if init_weights: + self.reset_pvera_parameters(adapter_name, d_initial=d_initial) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_pvera_parameters(self, adapter_name, d_initial: float = 0.1): + if adapter_name in self.pvera_lambda_d.keys(): + with torch.no_grad(): + nn.init.zeros_(self.pvera_lambda_d[adapter_name]).fill_(d_initial) + nn.init.zeros_(self.pvera_lambda_b[adapter_name]) + + +class Linear(nn.Linear, PveraLayer): + # PVeRA implemented in a dense layer + def __init__( + self, + base_layer, + pvera_A: BufferDict, + pvera_B: BufferDict, + adapter_name: str, + r: int = 0, + pvera_dropout: float = 0.0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + is_target_conv_1d_layer: bool = False, + init_weights: bool = True, + d_initial: float = 0.1, + sample_at_inference: bool = False, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called + super(nn.Linear, self).__init__() + PveraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + self.sample_at_inference = sample_at_inference + + self._active_adapter = adapter_name + self.update_layer(adapter_name, pvera_A, pvera_B, r, pvera_dropout, init_weights, d_initial=d_initial) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.pvera_lambda_d.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += self.get_delta_weight(active_adapter) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.pvera_lambda_d.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + pvera_A = self.pvera_A[adapter] + pvera_B = self.pvera_B[adapter] + + device = pvera_B.device + dtype = pvera_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + lambda_d = self.pvera_lambda_d[adapter] + lambda_b = self.pvera_lambda_b[adapter] + + if cast_to_fp32: + pvera_A = pvera_A.float() + pvera_B = pvera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = pvera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = pvera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + # In PVeRA, the first half of the lambda_d and sliced_A vector corresponds to the mean (mu) and the second half to the log-variance (logvar). When merging, we can only do mean sampling, and therefore only need the first half + lambda_d = lambda_d[: lambda_d.size(0) // 2, :] + sliced_A = sliced_A[: sliced_A.size(0) // 2, :] + + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def _reparametrize(self, mu, logvar, sample_at_inference): + if self.training or (not self.training and sample_at_inference): + std = torch.exp(0.5 * logvar) + eps = torch.randn_like(std) + z = mu + eps * std + else: + z = mu + return z + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.pvera_lambda_d.keys(): + continue + + lambda_d = self.pvera_lambda_d[active_adapter] + lambda_b = self.pvera_lambda_b[active_adapter] + + pvera_A = self.pvera_A[active_adapter] + pvera_B = self.pvera_B[active_adapter] + + # As adapted layers may have different shapes and PVeRA contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared pvera_A and pvera_B. + sliced_A = pvera_A[:, : self.in_features].to(x.device) + sliced_B = pvera_B[: self.out_features, :].to(x.device) + + dropout = self.pvera_dropout[active_adapter] + x = x.to(lambda_d.dtype) + mu, logvar = (lambda_d * F.linear(dropout(x), sliced_A)).chunk(2, dim=-1) + result = result + lambda_b * F.linear( + self._reparametrize(mu, logvar, self.sample_at_inference), sliced_B + ) + + result = result.to(previous_dtype) + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "pvera." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/model.py new file mode 100644 index 0000000000000000000000000000000000000000..a930bc42877218af4a7e29fa692c3ca01f3da904 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/pvera/model.py @@ -0,0 +1,271 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings + +import torch +import torch.nn as nn +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING, +) + +from .._buffer_dict import BufferDict +from ..tuners_utils import _maybe_include_all_linear_layers +from .config import PveraConfig +from .layer import Linear, PveraLayer + + +class PveraModel(BaseTuner): + """ + Creates Probabilistic Vector-based Random Matrix Adaptation (PVeRA) model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`PveraConfig`]): The configuration of the PVeRA model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The PVeRA model. + + Example: + + ```py + >>> from transformers import AutoModel + >>> from peft import PveraConfig, get_peft_model + + >>> base_model = AutoModel.from_pretrained("facebook/dinov2-base") + >>> config = PveraConfig(r=128, sample_at_inference=False) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`PveraConfig`]): The configuration of the PVeRA model. + """ + + prefix: str = "pvera_lambda_" + tuner_layer_cls = PveraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING + + def _find_dim(self, config) -> tuple[int, int]: + """ + Finds the largest input and output dimensions across linear layers that have been wrapped with PVeRA. + + This will be used for determining the size of the shared pvera_A and pvera_B matrices. + """ + model_config = self.get_model_config(self.model) + + peft_config = self._prepare_adapter_config(config, model_config) + peft_config = _maybe_include_all_linear_layers(peft_config, self.model) + + largest_shape = None + for key, module in self.model.named_modules(): + if not self._check_target_module_exists(peft_config, key): + continue + + if isinstance(module, nn.Linear): + module_shape = module.out_features, module.in_features + elif isinstance(module, Conv1D): + module_shape = module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape + module_shape = module_shape[::-1] + else: + continue + + if largest_shape is None: + largest_shape = module_shape + continue + + if module_shape != largest_shape: + largest_shape = tuple(max(a, b) for a, b in zip(largest_shape, module_shape)) + + if largest_shape is None: + msg = "No layers types compatible with PVeRA were found. Please check `peft_config.target_modules`." + raise ValueError(msg) + + return largest_shape + + def _init_pvera_A_pvera_B(self, config: PveraConfig, adapter_name: str) -> None: + linear_out_dim, linear_in_dim = self._find_dim(config) + + # use of persistent to exclude pvera_A and pvera_B from the state dict if we choose not to save them. + self.pvera_A = BufferDict({}, persistent=config.save_projection) + self.pvera_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of pvera_A and pvera_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + pvera_A = torch.nn.init.kaiming_uniform_(torch.empty(config.r * 2, linear_in_dim), generator=generator) + pvera_B = torch.nn.init.kaiming_uniform_(torch.empty(linear_out_dim, config.r), generator=generator) + + self.pvera_A[adapter_name] = pvera_A + self.pvera_B[adapter_name] = pvera_B + + def _pre_injection_hook(self, model: nn.Module, config: PveraConfig, adapter_name: str) -> None: + self._init_pvera_A_pvera_B(config, adapter_name) + + def _check_new_adapter_config(self, config: PveraConfig) -> None: + """ + A helper method to check the config when a new adapter is being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + super()._check_new_adapter_config(config) + + for existing_config in self.peft_config.values(): + if existing_config is config: + # skip the current config + continue + + if existing_config.projection_prng_key != config.projection_prng_key: + raise ValueError( + f"PVeRA PRNG initialisation key must be the same for all adapters. Got {config.projection_prng_key=} but " + f"previous config had {existing_config.projection_prng_key}." + ) + + save_project_unique_values = {config.save_projection for config in self.peft_config.values()} + if len(save_project_unique_values) > 1: + raise ValueError( + "PVeRA projection weights must be saved for all adapters or none, but got multiple different values: " + f"{save_project_unique_values}" + ) + + def _create_and_replace( + self, + pvera_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + r = pvera_config.r + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": r, + "pvera_dropout": pvera_config.pvera_dropout, + "fan_in_fan_out": pvera_config.fan_in_fan_out, + "init_weights": pvera_config.init_weights, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + kwargs["bias"] = bias + + if isinstance(target, Linear): + target.update_layer( + adapter_name, + self.pvera_A, + self.pvera_B, + r, + pvera_config.pvera_dropout, + pvera_config.init_weights, + d_initial=pvera_config.d_initial, + ) + else: + new_module = self._create_new_module( + pvera_config, self.pvera_A, self.pvera_B, adapter_name, target, current_key, **kwargs + ) + if adapter_name not in self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(pvera_config, pvera_A, pvera_B, adapter_name, target, current_key, **kwargs): + # avoid eager bnb import + if is_bnb_available(): + import bitsandbytes as bnb + + from .bnb import Linear8bitLt + + if is_bnb_4bit_available(): + from .bnb import Linear4bit + + bias = kwargs.pop("bias", False) + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target_base_layer.state.has_fp16_weights, + "threshold": target_base_layer.state.threshold, + "index": target_base_layer.index, + } + ) + return Linear8bitLt(target, adapter_name, pvera_A, pvera_B, **eightbit_kwargs) + elif loaded_in_4bit and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + return Linear4bit(target, adapter_name, pvera_A, pvera_B, **fourbit_kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = pvera_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = pvera_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`." + ) + + if isinstance(pvera_config.sample_at_inference, bool): + module_sample_at_inference = pvera_config.sample_at_inference + else: + module_sample_at_inference = pvera_config.sample_at_inference.get(current_key, False) + + new_module = Linear( + target, + pvera_A, + pvera_B, + adapter_name, + bias=bias, + d_initial=pvera_config.d_initial, + sample_at_inference=module_sample_at_inference, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..fbad681aeb0231254f5caae6b9bf9aa3a2c76ef0 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/__init__.py @@ -0,0 +1,40 @@ +# Copyright 2025-present the HuggingFace Inc. team. + +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.utils import register_peft_method + +from .config import RandLoraConfig +from .layer import Linear, RandLoraLayer +from .model import RandLoraModel + + +__all__ = ["Linear", "RandLoraConfig", "RandLoraLayer", "RandLoraModel"] + +register_peft_method(name="randlora", config_cls=RandLoraConfig, model_cls=RandLoraModel, prefix="randlora_") + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..353295e88aab41f4ca59669ec51e4dc479ad1e3e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/bnb.py @@ -0,0 +1,456 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight +from peft.utils.other import transpose + +from .layer import RandLoraLayer, UniqueBaseGrad + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, RandLoraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + randlora_A, + randlora_B, + r: int = 0, + randlora_alpha: int = 0, + randlora_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RandLoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + randlora_A, + randlora_B, + r, + randlora_alpha=randlora_alpha, + randlora_dropout=randlora_dropout, + init_weights=init_weights, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.randlora_lambda.keys(): + continue + + warnings.warn( + "Merge RandLora module to 8-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + output = dequantize_bnb_weight(weight, state) + w_data = output.to(randlora_data.dtype).to(randlora_data.device) + randlora_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.randlora_lambda.keys(): + continue + warnings.warn( + "Unmerge randlora module to 8-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + w_data = output.to(randlora_data.dtype).to(randlora_data.device) - randlora_data + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + + def get_scaled_bases(self, adapter, device=None) -> list[torch.Tensor, torch.Tensor]: + """ + Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the + correct order to fit the target layers' dimensions + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + randlora_A = self.randlora_A[adapter] + randlora_B = self.randlora_B[adapter] + + if device is None: + device = randlora_B.device + dtype = randlora_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + randlora_lambda = self.randlora_lambda[adapter].to(device) + randlora_gamma = self.randlora_gamma[adapter].to(device) + + if cast_to_fp32: + randlora_A = randlora_A.float() + randlora_B = randlora_B.float() + randlora_lambda = randlora_lambda.float() + randlora_gamma = randlora_gamma.float() + + # The trainable parameters are always applied to randlora_A, the smallest basis. + min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features) + + # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B. + sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device) + sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device) + + # Flattening the matrices over the rank and number of bases dimensions is more memory efficient + update_B = sliced_B.flatten(start_dim=1) + update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1) + if min_dim == self.in_features: + return update_A, update_B + + return update_B.T, update_A.T + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + update_B, update_A = self.get_scaled_bases(adapter) + + update = update_B @ update_A + output_tensor = transpose(update, self.fan_in_fan_out) + + scaling = self.scaling[adapter] + + return output_tensor * scaling + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Perform the forward pass using the RandLora adapter. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after applying the RandLora adaptation. + + Note: + This method implements the RandLora-specific forward pass. It applies the shared projections + (randlora_A and randlora_B) along with the per-layer trainable parameters (lambda and gamma) to compute + the adapter output. + """ + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.randlora_lambda.keys(): + continue + + update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device) + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = update_A.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + dropout = self.randlora_dropout[active_adapter] + x_temp = dropout(x.to(update_A.dtype)) + + adapter_output = torch.nn.functional.linear(torch.nn.functional.linear(x_temp, update_B), update_A) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + scaling = self.scaling[active_adapter] + result = result + adapter_output * scaling + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "randlora." + rep + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, RandLoraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + randlora_A, + randlora_B, + r: int = 0, + randlora_alpha: int = 0, + randlora_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RandLoraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + randlora_A, + randlora_B, + r, + randlora_alpha=randlora_alpha, + randlora_dropout=randlora_dropout, + init_weights=init_weights, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.randlora_lambda.keys(): + continue + + warnings.warn( + "Merge RandLora module to 4-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + randlora_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.randlora_lambda.keys(): + continue + warnings.warn( + "Unmerge RandLora module to 4-bit linear may get different generations due to rounding errors." + ) + randlora_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) - randlora_data + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + + def get_scaled_bases(self, adapter, device=None) -> list[torch.Tensor, torch.Tensor]: + """ + Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the + correct order to fit the target layers' dimensions + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + randlora_A = self.randlora_A[adapter] + randlora_B = self.randlora_B[adapter] + if device is None: + device = randlora_B.device + dtype = randlora_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + randlora_lambda = self.randlora_lambda[adapter].to(device) + randlora_gamma = self.randlora_gamma[adapter].to(device) + + if cast_to_fp32: + randlora_A = randlora_A.float() + randlora_B = randlora_B.float() + randlora_lambda = randlora_lambda.float() + randlora_gamma = randlora_gamma.float() + + # The trainable parameters are always applied to randlora_A, the smallest basis. + min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features) + + # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B. + sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device) + sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device) + # Flattening the matrices over the rank and number of bases dimensions is more memory efficient + update_B = sliced_B.flatten(start_dim=1) + update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1) + if min_dim == self.in_features: + return update_A, update_B + + return update_B.T, update_A.T + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + update_B, update_A = self.get_scaled_bases(adapter) + + update = update_B @ update_A + output_tensor = transpose(update, self.fan_in_fan_out) + + scaling = self.scaling[adapter] + + return output_tensor * scaling + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result = result.clone() + for active_adapter in self.active_adapters: + if active_adapter not in self.randlora_lambda.keys(): + continue + + update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device) + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = update_A.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + dropout = self.randlora_dropout[active_adapter] + x_temp = dropout(x.to(update_A.dtype)) + + adapter_output = torch.nn.functional.linear(torch.nn.functional.linear(x_temp, update_B), update_A) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + scaling = self.scaling[active_adapter] + result = result + adapter_output * scaling + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "randlora." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..b194b974331dd9abcb5777295ae4e79d8b81da56 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/config.py @@ -0,0 +1,199 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class RandLoraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`RandLoraModel`]. + + Paper: https://huggingface.co/papers/2502.00987. + + Args: + r (`int`, *optional*, defaults to `32`): + RandLora's random basis rank dimension. Contrary to Lora, this parameter is inversely proportional to the + amount of trainable parameters as reducing it increases trainable parameters. + target_modules (`Union[list[str], str]`): + The names of the modules to apply RandLora to. Only linear layers are supported. + projection_prng_key (`int`): + RandLora PRNG init key. Used for initialising basis_A and basis_B for new models or when loading a + checkpoint that did not include these projections. Defaults to `0`. + save_projection (`bool`): + Whether to save the global basis_A / basis_B random basis in the state dict alongside per layer lambda / + gamma diagonal matrices. This will increase the size of the checkpoint, but guarantee that we can reload + the checkpoint on all system configurations. Defaults to `True`. + sparse (`bool`): + Whether to use sparse random bases as described in the RandLora paper. The bases are ternary sparse bases + (only containing -1, 0 and 1) where the attribution probability is 1/6 for -1 and 1 and 2/3 for 0. These + sparse matrices aim to be used for matmul free computation in the future, see + https://huggingface.co/papers/2406.02528v1 The current implementation is a proof of concept however where + the sparseness is not used to improve speed or memory usage. Using sparse matrices typically does not + reduce performance and can even help reduce overfitting. Defaults to `False`. + very_sparse (`bool`): + Whether to use highly sparse random bases as described in the RandLora paper. The very sparse bases are + ternary sparse bases (only containing -1, 0 and 1) given a matrix with smallest dimension d, the + attribution probability is 1/√D for -1 and 1 and 1- 2/√D for 0. Using these sparse matrices can further + reduce overfitting over the `sparse` alternatives but will most likely decrease performance as a results. + Use carefully. Defaults to `False`. + randlora_dropout (`float`): + The dropout probability for RandLora layers. + randlora_alpha (`float`): + The scaling coefficient for RandLora layers, this would typically be 20 times the rank. Because the + `randlora_alpha` coefficient is large by default, it can lead to numerical instabilities especially when + learning rates are high. If training is unstable, consider reducing the learning rate or the + `randlora_alpha` coefficient. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + bias (`str`): + Bias type. Can be 'none', 'all' or 'randlora_only'. If 'all' or 'randlora_only', the corresponding biases + will be updated during training. Be aware that this means that, even when disabling the adapters, the model + will not produce the same output as the base model would have without adaptation. + modules_to_save (`list[str]`): + list of modules apart from RandLora layers to be set as trainable and saved in the final checkpoint. + init_weights (`bool`): + Whether to initialize the weights of the RandLora layers with their default initialization. Don't change + this setting, except if you know exactly what you're doing. + layers_to_transform (`Union[list[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply the RandLora transformations + on the layer indexes that are specified in this list. If a single integer is passed, it will apply the + RandLora transformations on the layer at this index. + layers_pattern (`str`): + The layer pattern name, used only if `layers_to_transform` is different from `None` and if the layer + pattern is not in the common layers pattern. + """ + + r: int = field(default=32, metadata={"help": "RandLora random basis rank"}) + + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "list of module names or regex expression of the module names to replace with RandLora." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + projection_prng_key: int = field( + default=0, + metadata={ + "help": ( + "RandLora PRNG init key. Used for initialising basis_A and basis_B for new models or when loading a " + "checkpoint that did not include these projections." + ) + }, + ) + save_projection: bool = field( + default=True, + metadata={ + "help": ( + "Whether to save the basis_A / basis_B projections in the state dict alongside per layer lambda / " + "gamma weights. This will increase the size of the checkpoint, but guarantee that we can reload " + "the checkpoint on all system configurations." + ) + }, + ) + sparse: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use sparse random bases as described in the RandLora paper." + "The current implementation is a proof of concept where the sparseness" + "is not used to improve speed or memory usage." + ) + }, + ) + very_sparse: bool = field( + default=False, + metadata={ + "help": ( + "Whether to use very sparse random bases." + "The current implementation is a proof of concept where the sparseness" + "is not used to improve speed or memory usage." + ) + }, + ) + randlora_dropout: float = field(default=0.0, metadata={"help": "Dropout in the adapter layers"}) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + randlora_alpha: int = field( + default=640, + metadata={ + "help": "Scaling coefficient in the adapter layers, typically 20 times the rank of the random bases." + }, + ) + bias: str = field( + default="none", metadata={"help": "Bias type for RandLora. Can be 'none', 'all' or 'randlora_only'"} + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "list of modules apart from RandLora layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the RandLora layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers" + " indexes that are specified inside this list. If a single integer is passed, PEFT will transform only" + " the layer at this index." + ) + }, + ) + layers_pattern: Optional[str] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer" + " pattern is not in the common layers pattern." + ) + }, + ) + + def __post_init__(self): + self.peft_type = PeftType.RANDLORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + + if not self.save_projection: + warnings.warn( + "Specified to not save basis_A and basis_B within the state dictionary, instead they will be restored " + "using the PRNG key store in `config.projection_prng_key`. Consider setting `config.save_projection` " + "to `True` to guarantee restoring the checkpoint correctly on all system configurations." + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..679a417439a9f1b9c4b16697903e2064f92bed51 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/layer.py @@ -0,0 +1,353 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .._buffer_dict import BufferDict + + +class UniqueBaseGrad(torch.autograd.Function): + # Memory efficent for a unique base + @staticmethod + def forward(ctx, randlora_A, randlora_lambda, randlora_gamma): + out = randlora_lambda[:, :, None] * randlora_A * randlora_gamma[None,] + ctx.save_for_backward(randlora_A, randlora_lambda, randlora_gamma) + return out + + @staticmethod + def backward(ctx, grad_output): + randlora_A, randlora_lambda, randlora_gamma = ctx.saved_tensors + randlora_A, randlora_lambda, randlora_gamma = ( + randlora_A.to(grad_output.dtype), + randlora_lambda.to(grad_output.dtype), + randlora_gamma.to(grad_output.dtype), + ) + grad_randlora_lambda = torch.einsum("kbj,kvj,bj->kb", grad_output, randlora_A, randlora_gamma) + grad_randlora_gamma = torch.einsum("kbj,kvj,kb->bj", grad_output, randlora_A, randlora_lambda) + return None, grad_randlora_lambda, grad_randlora_gamma + + +class RandLoraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("randlora_lambda", "randlora_gamma") + other_param_names = ("randlora_A", "randlora_B") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.scaling = {} + self.randlora_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.randlora_lambda = nn.ParameterDict({}) + self.randlora_gamma = nn.ParameterDict({}) + + # Stores a reference to the randlora_A/B BufferDict. + # Set to `None` otherwise to avoid computation with random weights + self.randlora_A: Optional[BufferDict] = None + self.randlora_B: Optional[BufferDict] = None + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + # flag to enable/disable casting of input to weight dtype during forward call + self.cast_input_dtype_enabled = True + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + in_features, out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + @property + def merged(self) -> bool: + return bool(self.merged_adapters) + + def update_layer( + self, + adapter_name, + randlora_A: BufferDict, + randlora_B: BufferDict, + r, + randlora_alpha, + randlora_dropout, + init_weights, + inference_mode: bool = False, + **kwargs, + ): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + self.r[adapter_name] = r + if randlora_dropout > 0.0: + randlora_dropout_layer = nn.Dropout(p=randlora_dropout) + else: + randlora_dropout_layer = nn.Identity() + + self.randlora_dropout.update(nn.ModuleDict({adapter_name: randlora_dropout_layer})) + + # Actual trainable parameters + num_bases = min(self.in_features, self.out_features) / r + self.num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 # Full rank + self.randlora_lambda[adapter_name] = nn.Parameter(torch.randn(r, self.num_bases), requires_grad=True) + self.randlora_gamma[adapter_name] = nn.Parameter( + torch.ones(self.num_bases, min(self.out_features, self.in_features)) + / max(self.out_features, self.in_features), + requires_grad=True, + ) + + self.scaling[adapter_name] = randlora_alpha / r + + # non trainable references to randlora_A/B buffers + self.randlora_A = randlora_A + self.randlora_B = randlora_B + if adapter_name not in randlora_A: + # This means that this is not the first RandLora adapter. We have to add an entry in the dict for this adapter. + if len(self.randlora_A) < 1: + raise ValueError( + "The `randlora_A` and `randlora_B` buffers are empty. This should not happen. Please report this issue." + ) + # we can take any of the existing adapter's parameters, as they should all be identical + randlora_A_param = list(self.randlora_A.values())[0] + randlora_B_param = list(self.randlora_B.values())[0] + + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional RandLora " + "adapter was added after the first one with incompatible shapes." + ) + max_dim, min_dim = max(self.in_features, self.out_features), min(self.in_features, self.out_features) + # check input size + if randlora_B_param.shape[0] < max_dim: + raise ValueError(error_tmpl.format("randlora_B", randlora_B_param.shape[0], max_dim)) + # check output size + if randlora_A_param.shape[-1] < min_dim: + raise ValueError(error_tmpl.format("randlora_A", randlora_A_param.shape[1], min_dim)) + + # check r + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional RandLora " + "adapter with a lower rank was added after the first one; loading the adapters " + "in reverse order may solve this." + ) + if randlora_A_param.shape[0] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("randlora_A", randlora_A_param.shape[0], self.r[adapter_name])) + + if randlora_B_param.shape[-1] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("randlora_B", randlora_B_param.shape[-1], self.r[adapter_name])) + + self.randlora_A[adapter_name] = randlora_A_param + self.randlora_B[adapter_name] = randlora_B_param + + if init_weights: + self.reset_randlora_parameters(adapter_name) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_randlora_parameters(self, adapter_name): + if adapter_name in self.randlora_lambda.keys(): + with torch.no_grad(): + nn.init.zeros_(self.randlora_lambda[adapter_name]) + nn.init.constant_(self.randlora_gamma[adapter_name], 1 / max(self.randlora_gamma[adapter_name].shape)) + + +class Linear(nn.Linear, RandLoraLayer): + # RandLora implemented in a dense layer + def __init__( + self, + base_layer, + randlora_A: BufferDict, + randlora_B: BufferDict, + adapter_name: str, + r: int = 0, + randlora_alpha: int = 0, + randlora_dropout: float = 0.0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + is_target_conv_1d_layer: bool = False, + init_weights: bool = True, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called + super(nn.Linear, self).__init__() + RandLoraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, randlora_A, randlora_B, r, randlora_alpha, randlora_dropout, init_weights) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.randlora_lambda.keys(): + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights.to(orig_dtype) + else: + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data += delta_weight.to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + active_adapter = self.merged_adapters.pop() + if active_adapter in self.randlora_lambda.keys(): + delta_weight = self.get_delta_weight(active_adapter) + base_layer.weight.data -= delta_weight.to(orig_dtype) + + def get_scaled_bases(self, adapter, device=None) -> tuple[torch.Tensor, torch.Tensor]: + """ + Performs scaling on the smallest random base (randlora_A) and returns randlora_A and randlora_B in the correct + order to fit the target layers' dimensions + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + randlora_A = self.randlora_A[adapter] + randlora_B = self.randlora_B[adapter] + if device is None: + device = randlora_B.device + dtype = randlora_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + randlora_lambda = self.randlora_lambda[adapter].to(device) + randlora_gamma = self.randlora_gamma[adapter].to(device) + + if cast_to_fp32: + randlora_A = randlora_A.float() + randlora_B = randlora_B.float() + randlora_lambda = randlora_lambda.float() + randlora_gamma = randlora_gamma.float() + + # The trainable parameters are always applied to randlora_A, the smallest basis. + min_dim, max_dim = min(self.out_features, self.in_features), max(self.out_features, self.in_features) + + # As adapted layers may have different shapes and RandLora contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared randlora_A and randlora_B. + sliced_A = randlora_A[:, : self.num_bases, :min_dim].to(device) + sliced_B = randlora_B[:max_dim, : self.num_bases, :].to(device) + + # Flattening the matrices over the rank and number of bases dimensions is more memory efficient + update_B = sliced_B.flatten(start_dim=1) + update_A = UniqueBaseGrad.apply(sliced_A, randlora_lambda, randlora_gamma).flatten(end_dim=1) + + # Since update_A is applied on the smallest dimension, test whether update_A or update_B should be applied first. This is done to reduce trainable parameters. + if min_dim == self.in_features: + return update_A, update_B + return update_B.T, update_A.T + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + update_B, update_A = self.get_scaled_bases(adapter) + + update = (update_B.T @ update_A.T).T + output_tensor = transpose(update, self.fan_in_fan_out) + + scaling = self.scaling[adapter] + return output_tensor * scaling + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.randlora_lambda.keys(): + continue + dropout = self.randlora_dropout[active_adapter] + update_B, update_A = self.get_scaled_bases(active_adapter, device=x.device) + x = x.to(update_A.dtype) + scaling = self.scaling[active_adapter] + result = result + F.linear(F.linear(dropout(x), update_B), update_A) * scaling + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "randlora." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3146438f3821aba61ac94c8e31243b00eb748011 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/randlora/model.py @@ -0,0 +1,356 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +import warnings +from typing import Union + +import torch +import torch.nn as nn +from accelerate.utils.imports import is_bf16_available +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, +) + +from .._buffer_dict import BufferDict +from ..tuners_utils import _maybe_include_all_linear_layers +from .config import RandLoraConfig +from .layer import Linear, RandLoraLayer + + +def _kaiming_init( + tensor_or_shape: Union[torch.Tensor, tuple[int, ...]], + generator: torch.Generator, +) -> torch.Tensor: + """ + Kaiming Uniform Initialisation adapted to accept a `torch.Generator` object for PRNG. + + Args: + tensor_or_shape (`Union[torch.Tensor, tuple[int, ...]]`): + Tensor to initialise, or shape of new tensor to create and then initialise. + generator: (`torch.Generator`): + Generator object that manages the state of the PRNG algorithm in use. + + Returns: + `torch.Tensor`: The initialised tensor. + """ + if isinstance(tensor_or_shape, tuple): + tensor = torch.empty( + tensor_or_shape, + dtype=torch.bfloat16 if is_bf16_available() else torch.float16, + ) + else: + tensor = tensor_or_shape + + with torch.no_grad(): + basis = torch.nn.init.kaiming_uniform_(tensor, a=math.sqrt(5), generator=generator) + return basis + + +class RandLoraModel(BaseTuner): + """ + Creates a RandLoRA model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`RandLoraConfig`]): The configuration of the RandLora model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The RandLora model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import RandLoraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = RandLoraConfig(r=32) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`RandLoraConfig`]): The configuration of the RandLora model. + """ + + prefix: str = "randlora_" + tuner_layer_cls = RandLoraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING + + def _find_dim(self, config) -> tuple[int, int]: + """ + Finds the largest input and output dimensions across linear layers that have been wrapped with RandLora. + + This will be used for determining the size of the shared randlora_A and randlora_B matrices. + """ + model_config = self.get_model_config(self.model) + + peft_config = self._prepare_adapter_config(config, model_config) + peft_config = _maybe_include_all_linear_layers(peft_config, self.model) + + largest_shape = None + for key, module in self.model.named_modules(): + if not self._check_target_module_exists(peft_config, key): + continue + + if isinstance(module, nn.Linear): + module_shape = module.out_features, module.in_features + elif isinstance(module, Conv1D): + module_shape = module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape + module_shape = module_shape[::-1] + else: + continue + + if largest_shape is None: + largest_shape = module_shape + continue + + if module_shape != largest_shape: + largest_shape = tuple(max(a, b) for a, b in zip(largest_shape, module_shape)) + + if largest_shape is None: + msg = "No layers types compatible with RandLora were found. Please check `peft_config.target_modules`." + raise ValueError(msg) + + return largest_shape + + def _init_randlora_A_randlora_B_sparse(self, config: RandLoraConfig, adapter_name: str, sparsity: int = 3) -> None: + """ + Sparse random projections as described in https://cs-people.bu.edu/evimaria/cs565/kdd-rp.pdf + """ + + linear_out_dim, linear_in_dim = self._find_dim(config) + max_dim, min_dim = max(linear_out_dim, linear_in_dim), min(linear_out_dim, linear_in_dim) + + # use of persistent to exclude randlora_A and randlora_B from the state dict if we choose not to save them. + self.randlora_A = BufferDict({}, persistent=config.save_projection) + self.randlora_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of randlora_A and randlora_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + + # The gamma matrix is applied on A meaning it can be unique (shared) across the n scaling matrices. + # We also set randlora_A as the smallest matrix to reduce trainable parameters. + randlora_A = torch.rand((config.r, 1, min_dim), generator=generator) + + # Number of bases to ensure full rank + num_bases = min_dim / config.r + num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 # Ensure full rank + randlora_B = torch.rand((max_dim, num_bases, config.r), generator=generator) + + # The current implementation is a proof of concept and does take into consideration + # the sparsity to reduce memory usage or speed up compute + randlora_B_sparse = torch.zeros(randlora_B.shape) + randlora_A_sparse = torch.zeros(randlora_A.shape) + randlora_B_sparse[randlora_B < 1 / (2 * sparsity)] = -1 + randlora_B_sparse[randlora_B > 1 - 1 / (2 * sparsity)] = 1 + randlora_A_sparse[randlora_A < 1 / (2 * sparsity)] = -1 + randlora_A_sparse[randlora_A > 1 - 1 / (2 * sparsity)] = 1 + + # Std normalization is empirically found to be the best + randlora_A, randlora_B = ( + randlora_A_sparse / randlora_A_sparse.std(), + randlora_B_sparse / randlora_B_sparse.std(), + ) + self.randlora_A[adapter_name] = randlora_A + self.randlora_B[adapter_name] = randlora_B + + def _init_randlora_A_randlora_B(self, config: RandLoraConfig, adapter_name: str) -> None: + linear_out_dim, linear_in_dim = self._find_dim(config) + max_dim, min_dim = max(linear_out_dim, linear_in_dim), min(linear_out_dim, linear_in_dim) + + # use of persistent to exclude randlora_A and randlora_B from the state dict if we choose not to save them. + self.randlora_A = BufferDict({}, persistent=config.save_projection) + self.randlora_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of randlora_A and randlora_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + + # The gamma matrix is applied on A meaning it can be unique (shared) across the n scaling matrices. + # We also set randlora_A as the smallest matrix to reduce trainable parameters. + randlora_A = _kaiming_init((config.r, 1, min_dim), generator=generator) + + # Ensure full rank + num_bases = min(linear_out_dim, linear_in_dim) / config.r + num_bases = int(num_bases) if num_bases.is_integer() else int(num_bases) + 1 + randlora_B = torch.cat( + [_kaiming_init((max_dim, 1, config.r), generator=generator) for _ in range(num_bases)], dim=1 + ) + + # Std normalization is empirically found to be the best + randlora_A, randlora_B = randlora_A / randlora_A.std(), randlora_B / randlora_B.std() + self.randlora_A[adapter_name] = randlora_A + self.randlora_B[adapter_name] = randlora_B + + def _pre_injection_hook(self, model: nn.Module, config: RandLoraConfig, adapter_name: str) -> None: + if config.very_sparse: + linear_out_dim, linear_in_dim = self._find_dim(config) + self._init_randlora_A_randlora_B_sparse( + config, adapter_name, sparsity=math.sqrt(min(linear_out_dim, linear_in_dim)) + ) + elif config.sparse: + self._init_randlora_A_randlora_B_sparse(config, adapter_name, sparsity=3) + else: + self._init_randlora_A_randlora_B(config, adapter_name) + + def _check_new_adapter_config(self, config: RandLoraConfig) -> None: + """ + A helper method to check the config when a new adapter is being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + super()._check_new_adapter_config(config) + + for existing_config in self.peft_config.values(): + if existing_config is config: + # skip the current config + continue + + if existing_config.projection_prng_key != config.projection_prng_key: + raise ValueError( + f"RandLora PRNG initialisation key must be the same for all adapters. Got {config.projection_prng_key=} but " + f"previous config had {existing_config.projection_prng_key}." + ) + + save_project_unique_values = sorted({config.save_projection for config in self.peft_config.values()}) + if len(save_project_unique_values) > 1: + raise ValueError( + "RandLora projection weights must be saved for all adapters or none, but got multiple different values: " + f"{save_project_unique_values}" + ) + + def _create_and_replace( + self, + randlora_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + r = randlora_config.r + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": r, + "randlora_alpha": randlora_config.randlora_alpha, + "randlora_dropout": randlora_config.randlora_dropout, + "fan_in_fan_out": randlora_config.fan_in_fan_out, + "init_weights": randlora_config.init_weights, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + kwargs["bias"] = bias + if isinstance(target, Linear): + target.update_layer( + adapter_name, + self.randlora_A, + self.randlora_B, + r, + randlora_config.randlora_alpha, + randlora_config.randlora_dropout, + randlora_config.init_weights, + ) + else: + new_module = self._create_new_module( + randlora_config, self.randlora_A, self.randlora_B, adapter_name, target, **kwargs + ) + if adapter_name not in self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(randlora_config, randlora_A, randlora_B, adapter_name, target, **kwargs): + # avoid eager bnb import + if is_bnb_available(): + import bitsandbytes as bnb + + from .bnb import Linear8bitLt + + if is_bnb_4bit_available(): + from .bnb import Linear4bit + + bias = kwargs.pop("bias", False) + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target_base_layer.state.has_fp16_weights, + "threshold": target_base_layer.state.threshold, + "index": target_base_layer.index, + } + ) + return Linear8bitLt(target, adapter_name, randlora_A, randlora_B, **eightbit_kwargs) + elif loaded_in_4bit and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + return Linear4bit(target, adapter_name, randlora_A, randlora_B, **fourbit_kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = randlora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = randlora_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`." + ) + new_module = Linear( + target, + randlora_A, + randlora_B, + adapter_name, + bias=bias, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..97b2f0f54fc113f3470c5c7835b0b2cec133319e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/__init__.py @@ -0,0 +1,47 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + + +# Based on implementation made available in https://github.com/ppetrushkov/peft/tree/road (not from paper authors) + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.utils import register_peft_method + +from .config import RoadConfig +from .layer import Linear, RoadLayer +from .model import RoadModel + + +__all__ = [ + "Linear", + "RoadConfig", + "RoadLayer", + "RoadModel", +] + +register_peft_method(name="road", config_cls=RoadConfig, model_cls=RoadModel, is_mixed_compatible=True) + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..95e9b82b0ca7cee95b179762f6820467731a76d9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/bnb.py @@ -0,0 +1,407 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Any, Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight + +from .config import RoadVariant +from .layer import RoadLayer, _apply_road, _get_delta_weight + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, RoadLayer): + # Road implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + variant: RoadVariant = "road_1", + group_size: int = 64, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RoadLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + variant=variant, + group_size=group_size, + init_weights=init_weights, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self._available_adapters: + warnings.warn( + "Merge road module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + # Dequantize the result of identity matrix and int8 weight because bitsandbytes does not support int8 + # dequantization directly + output = dequantize_bnb_weight(weight, state=state) + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + + w_data = torch.matmul(road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.device).contiguous() + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + if self.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(road_R, bias_data.to(road_R.dtype)) + bias.data = new_bias.to(orig_dtype) + + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self._available_adapters: + warnings.warn( + "Unmerge road module to 8-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(road_R.dtype) + + w_data = torch.matmul(inv_road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.device).contiguous() + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + + if self.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(inv_road_R, bias_data) + bias.data = new_bias.to(orig_dtype) + + state.reset_grads() + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype) + + result = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + result, + ) + + if requires_conversion: + x = x.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "road." + rep + + def dispatch_bnb_8bit(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target.state.has_fp16_weights, + "threshold": target.state.threshold, + "index": target.index, + } + ) + new_module = Linear8bitLt(target, adapter_name, **eightbit_kwargs) + + return new_module + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, RoadLayer): + # OFT implemented in a dense layer + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + variant: RoadVariant = "road_1", + group_size: int = 64, + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + RoadLayer.__init__(self, base_layer) + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + variant=variant, + group_size=group_size, + init_weights=init_weights, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self._available_adapters: + warnings.warn( + "Merge oft module to 4-bit linear may get different generations due to rounding errors." + ) + # Refer to https://gist.github.com/ChrisHayduk/1a53463331f52dca205e55982baf9930 + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + w_data = torch.matmul(road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.device) + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + if self.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(road_R, bias_data.to(road_R.dtype)) + bias.data = new_bias.to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self._available_adapters: + warnings.warn( + "Unmerge oft module to 4-bit linear may get different generations due to rounding errors." + ) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + output = dequantize_bnb_weight(weight, state=weight.quant_state) + + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(road_R.dtype) + + w_data = torch.matmul(inv_road_R, output.to(road_R.dtype)) + w_data = w_data.to(road_R.dtype).to(road_R.device) + + if "bnb_quantized" in kwargs: + kwargs["bnb_quantized"] = False + kwargs["requires_grad"] = False + kwargs.pop("data", None) + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), **kwargs).to(weight.device) + + if self.get_base_layer().bias is not None: + bias = self.get_base_layer().bias + orig_dtype = bias.dtype + bias_data = bias.data + new_bias = torch.matmul(inv_road_R, bias_data) + bias.data = new_bias.to(orig_dtype) + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + # As per Tim Dettmers, for 4bit, we need to defensively clone here. + # The reason is that in some cases, an error can occur that backprop + # does not work on a manipulated view. This issue may be solved with + # newer PyTorch versions but this would need extensive testing to be + # sure. + # result = result.clone() + + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype) + + result = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + result, + ) + if requires_conversion: + x = x.to(expected_dtype) + + return result + + def __repr__(self) -> str: + rep = super().__repr__() + return "oft." + rep + + def dispatch_bnb_4bit(target: torch.nn.Module, adapter_name: str, **kwargs): + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + if loaded_in_4bit and is_bnb_4bit_available() and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + new_module = Linear4bit(target, adapter_name, **fourbit_kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/config.py new file mode 100644 index 0000000000000000000000000000000000000000..26c37a1fd03d36baaff536ca33cae56231df7356 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/config.py @@ -0,0 +1,126 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +RoadVariant = Literal["road_1", "road_2", "road_4"] + + +@dataclass +class RoadConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`RoadModel`]. RoAd adapter is proposed in + https://huggingface.co/papers/2409.00119. + + Args: + variant (Union[`RoadVariant`, `str`]): + The variant of the Road model to use. It can be one of road_1, road_2, or road_4. Refer to the paper for + more details. + - road_1: Uses the same scale and angle for all pairs of elements. + This variant has lowest number of parameters, it stores a number equal to the output hidden size of + parameters for each layer that RoAd is applied to. + - road_2: Uses the same scale and angle for each element. + This variant has 2x the number of parameters compared to road_1. + - road_4: Uses two different scales and angles for each ellement. + This variant has 4x the number of parameters compared to road_1. + group_size (`int`): + Group size defines how elements are grouped together into 2D vectors for rotation. Within each group + element 0 is paired with element group_size/2, then element 1 is paired with element group_size/2+1 and so + on. This has no effect on the model performance, since elements are unordered, however it has some effect + on inference speed when used in e.g. VLLM. For best speed group size of at least 32 or 64 (the default) is + recommended. Note that model hidden size (or hidden size per partition when used with tensor parallelism) + must be divisible by group_size, so for very small models you might need to reduce this parameter. + init_weights (`bool`): + Whether to perform initialization of RoAd weights. + target_modules (`Optional[Union[List[str], str]]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen (if + the model is a PreTrainedModel, the output layer excluded). If this is not specified, modules will be + chosen according to the model architecture. If the architecture is not known, an error will be raised -- in + this case, you should specify the target modules manually. + modules_to_save (`List[str]`): + List of modules apart from Road layers to be set as trainable and saved in the final checkpoint. + """ + + variant: Union[str, RoadVariant] = field( + default="road_1", + metadata={"help": ("Variant of the Road model to use.")}, + ) + group_size: int = field( + default=64, + metadata={ + "help": ( + "Group size defines how elements are grouped together into 2D vectors for rotation. " + "Within each group element 0 is paired with element group_size/2, " + "then element 1 is paired with element group_size/2+1 and so on. " + "This has no effect on the model performance, since elements are unordered, " + "however it has some effect on inference speed when used in e.g. VLLM. " + "For best speed group size of at least 64 is recommended. " + "Note that model hidden size (or hidden size per partition when used with tensor parallelism) " + "must be divisible by group_size, so for very small models you might need to reduce this parameter." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the RoAd layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with Road." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'." + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D " + "(if the model is a PreTrainedModel, the output layer excluded)." + "If not specified, modules will be chosen according to the model architecture, If the architecture is " + "not known, an error will be raised -- in this case, you should specify the target modules manually." + ), + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from RoAd layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.ROAD + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + if self.variant not in ["road_1", "road_2", "road_4"]: + raise ValueError(f"Invalid variant {self.variant} specified. Please choose from road_1, road_2 or road_4") + if self.group_size <= 0 or self.group_size % 2 != 0: + raise ValueError(f"The group_size must be divisible by 2 when using RoadLayer, but got {self.group_size}.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..d59dc056d5d293315aec29e089cca99a4d9a3279 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/layer.py @@ -0,0 +1,418 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Any, Optional, Union + +import torch +import torch.nn as nn + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + +from .config import RoadConfig, RoadVariant + + +class RoadLayer(BaseTunerLayer): + """ + Road layer. + + Generally the idea of RoAD is to split the input vector into many 2D vectors and rotate each 2D vector with its own + 2D rotation matrix. For additional flexibility, each rotation matrix is multiplied by a trainable scale. + + when applied to vector R @ x each pair of elements of x is transformed like this: `y₀ = x₀ * α * cosθ - xₙ * α * + sinθ` and `yₙ = x₀ * α * sinθ + xₙ * α * cosθ` + + The scales α and angles θ are learned for each pair of elements and, moreover, each of the 4 instances in the + rotation matrix may actually be different (when using variant 2 or 4). + + Note that instead of using two consecutive elements x₀ x₁ we first split the whole vector into groups and pair + elements from the first with the second half of the same group, which allows for more efficient inference + implementation. + + The adapter needs to only store the angles θ and scales α, rather than the full matrix R and the inference + implementation only needs to do elementwise vector multiplications. + + For merging the weights, we make use of the following formula: R @ (W @ x + b) = (R @ W) @ x + R @ b. The lhs part + is how it is used in unmerged state (using efficient elementwise implementation instead of matrix multiplication) + and the rhs part is how it is used in merged state where (R @ W) becomes the new weight matrix and R @ b becomes + the new bias. + + """ + + adapter_layer_names: tuple[str, ...] = ("road_theta", "road_alpha") + other_param_names: tuple[str, ...] = ("variant", "group_size") + + def __init__(self, base_layer: nn.Module, ephemeral_gpu_offload: bool = False, **kwargs) -> None: + self.base_layer = base_layer + self.variant = {} + self.group_size = {} + self.road_theta = nn.ParameterDict({}) + self.road_alpha = nn.ParameterDict({}) + + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + raise ValueError(f"Unsupported layer type '{type(base_layer)}' encountered, cannot apply RoAd adapter.") + self.in_features = in_features + self.out_features = out_features + + @property + def _available_adapters(self) -> set[str]: + return {*self.road_theta} + + def update_layer( + self, + adapter_name, + variant, + group_size, + init_weights, + inference_mode: bool = False, + ): + self.variant[adapter_name] = variant + self.group_size[adapter_name] = group_size + + if self.out_features % group_size != 0: + raise ValueError( + f"The out_features of the base layer must be divisible by group_size ({group_size}) when using RoadLayer." + ) + + # Actual trainable parameters + if variant == "road_1": + size = self.out_features // 2 + elif variant == "road_2": + size = self.out_features + elif variant == "road_4": + size = self.out_features * 2 + else: + raise ValueError( + f"Unsupported variant {variant} for RoadLayer. Supported variants are road_1, road_2, and road_4." + ) + self.road_theta[adapter_name] = nn.Parameter(torch.empty(size)) + self.road_alpha[adapter_name] = nn.Parameter(torch.empty(size)) + + self.reset_parameters(adapter_name, init_weights) + self._move_adapter_to_device_of_base_layer(adapter_name) + + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_parameters(self, adapter_name, init_weights): + if init_weights is False: + nn.init.normal_(self.road_theta[adapter_name].data, mean=0.0, std=0.5) + nn.init.normal_(self.road_alpha[adapter_name].data, mean=1.0, std=0.5) + return + nn.init.zeros_(self.road_theta[adapter_name].data) + nn.init.ones_(self.road_alpha[adapter_name].data) + + +class Linear(nn.Module, RoadLayer): + # Road implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + variant: RoadVariant = "road_1", + group_size: int = 64, + init_weights: Union[bool, str] = True, + **kwargs, + ) -> None: + super().__init__() + RoadLayer.__init__(self, base_layer, **kwargs) + + self._active_adapter = adapter_name + + self.update_layer( + adapter_name, + variant, + group_size, + init_weights=init_weights, + ) + + def _check_forward_args(self, x, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + adapter_names = kwargs.get("adapter_names", None) + if adapter_names is None: + return + + if len(x) != len(adapter_names): + msg = ( + "Length of `adapter_names` should be the same as the number of inputs, but got " + f"{len(adapter_names)} and {len(x)} respectively." + ) + raise ValueError(msg) + + if self.merged: + # It is unclear what would be the right thing to do if users pass adapter_names and there are merged + # adapters. Therefore, it is better to raise an error in this case. + msg = "Cannot pass `adapter_names` when there are merged adapters, please call `unmerge_adapter` first." + raise ValueError(msg) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + elif adapter_names is not None: + result = self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + torch_result_dtype = result.dtype + + for active_adapter in self.active_adapters: + if active_adapter not in self._available_adapters: + continue + + result = self._cast_input_dtype(result, self.road_theta[active_adapter].dtype) + result = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + result, + ) + + result = result.to(torch_result_dtype) + + return result + + def _mixed_batch_forward( + self, x: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + result = self.base_layer(x, *args, **kwargs) + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + for i, active_adapter in enumerate(unique_adapters): + if active_adapter == "__base__": + continue + if active_adapter not in self._available_adapters: + continue + + dtype = self.road_theta[active_adapter].data.dtype + + # getting the sub-batch, passing it to Road layers and updating the corresponding indices of the linear + # layer output + sub_batch = result[sub_batch_indices_list[i]].to(dtype) + result[sub_batch_indices_list[i]] = _apply_road( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter], + self.road_alpha[active_adapter], + sub_batch, + ) + + return result + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self._available_adapters: + base_layer = self.get_base_layer() + orig_dtype = base_layer.weight.dtype + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weight = base_layer.weight.data.clone() + orig_weight = torch.matmul(road_R.to(orig_dtype), orig_weight) + + if not torch.isfinite(orig_weight).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + + if base_layer.bias is not None: + orig_bias = base_layer.bias.clone() + orig_bias = torch.matmul(road_R.to(orig_dtype), orig_bias) + + if not torch.isfinite(orig_bias).all(): + raise ValueError( + f"NaNs detected in the merged bias. The adapter {active_adapter} seems to be broken" + ) + + base_layer.bias.data = orig_bias.contiguous().to(orig_dtype) + else: + orig_weight = base_layer.weight.data + orig_weight = torch.matmul(road_R.to(orig_dtype), orig_weight) + base_layer.weight.data = orig_weight.contiguous().to(orig_dtype) + + if base_layer.bias is not None: + orig_bias = base_layer.bias.data + orig_bias = torch.matmul(road_R.to(orig_dtype), orig_bias) + base_layer.bias.data = orig_bias.contiguous().to(orig_dtype) + + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + # Going in reverse order + active_adapter = self.merged_adapters.pop() + if active_adapter in self._available_adapters: + weight = self.get_base_layer().weight + orig_dtype = weight.dtype + road_R = _get_delta_weight( + self.variant[active_adapter], + self.group_size[active_adapter], + self.road_theta[active_adapter].data, + self.road_alpha[active_adapter].data, + ) + # Since our matrix are not necessarily orthogonal we need inverse instead of transpose. + # In practice we expect this to basically always work since we start from block diagonal rotation matrix. + inv_road_R = torch.linalg.inv(road_R.to(torch.float32)).to(orig_dtype) + orig_weight = torch.matmul(inv_road_R, weight.data) + weight.data = orig_weight.contiguous() + + if self.get_base_layer().bias is not None: + orig_bias = torch.matmul(inv_road_R, self.get_base_layer().bias.data) + self.get_base_layer().bias.data = orig_bias.contiguous() + + def __repr__(self) -> str: + rep = super().__repr__() + return "road." + rep + + +def _get_delta_weight(variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor): + first_col, second_col = _prepare_cols(variant, group_size, road_theta, road_alpha) + + # To help understand the logic below consider how rope embeddings work + # here it is similar, but done in groups. + # https://discuss.huggingface.co/t/is-llama-rotary-embedding-implementation-correct/44509/3 + + # First column is simply put on the main diagonal + output_tensor = torch.diag(first_col) + # For second column we need to swap each half groups and add minus sign + size = second_col.shape[0] + swapped_second_col = second_col.reshape(-1, 2, group_size // 2)[:, [1, 0], :].flatten() + rotated_diag_second_col = torch.diag(swapped_second_col).reshape(-1, 2, group_size // 2, size)[:, [1, 0], :, :] + rotated_diag_second_col[:, 0, :, :] *= -1 + rotated_diag_second_col = rotated_diag_second_col.reshape(size, size) + output_tensor += rotated_diag_second_col + + return output_tensor + + +def _prepare_cols( + variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor +) -> tuple[torch.Tensor, torch.Tensor]: + # In inference mode, this can be cached + if variant == "road_1": + # In each group there are only group_size // 2 parameters that are reused + road_theta = road_theta.reshape(-1, group_size // 2).repeat_interleave(2, dim=0).flatten() + road_alpha = road_alpha.reshape(-1, group_size // 2).repeat_interleave(2, dim=0).flatten() + + theta_cos = road_theta.cos() + theta_sin = road_theta.sin() + + first_col = road_alpha * theta_cos + second_col = road_alpha * theta_sin + elif variant == "road_2": + # Each group has exactly group_size parameters + theta_cos = road_theta.cos() + theta_sin = road_theta.sin() + + first_col = road_alpha * theta_cos + second_col = road_alpha * theta_sin + elif variant == "road_4": + # Each group has 2*group_size parameters, first half used for first column, second half for second column + road_theta = road_theta.reshape(-1, 2, group_size) + theta_cos = road_theta[:, 0, :].cos().flatten() + theta_sin = road_theta[:, 1, :].sin().flatten() + road_alpha = road_alpha.reshape(-1, 2, group_size) + alpha_1 = road_alpha[:, 0, :].flatten() + alpha_2 = road_alpha[:, 1, :].flatten() + + first_col = alpha_1 * theta_cos + second_col = alpha_2 * theta_sin + else: + raise ValueError( + f"Unsupported variant {variant} for RoadLayer. Supported variants are road_1, road_2, and road_4." + ) + + return first_col, second_col + + +def _apply_road( + variant: RoadVariant, group_size: int, road_theta: torch.Tensor, road_alpha: torch.Tensor, x: torch.Tensor +): + first_col, second_col = _prepare_cols(variant, group_size, road_theta, road_alpha) + + # Split in half groups and join back + # See equation 4 in the RoAD paper + x_grouped = x.reshape(-1, 2, group_size // 2) + x1 = x_grouped[:, 0, :] + x2 = x_grouped[:, 1, :] + rotate_half_x = torch.stack((-x2, x1), dim=1).reshape(x.shape) + result = x * first_col + rotate_half_x * second_col + return result + + +def dispatch_default( + target: torch.nn.Module, + adapter_name: str, + road_config: RoadConfig, + **kwargs, +) -> Optional[torch.nn.Module]: + new_module = None + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + new_module = Linear(target, adapter_name, **kwargs) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/model.py new file mode 100644 index 0000000000000000000000000000000000000000..03138636bcb0a89b808a60860f14538e538d694d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/road/model.py @@ -0,0 +1,164 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import operator +from contextlib import contextmanager +from functools import partial + +from torch import nn + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.road.config import RoadConfig +from peft.tuners.tuners_utils import ( + BaseTuner, + get_device_map, +) +from peft.utils import TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING + +from .layer import RoadLayer, dispatch_default + + +def _adapter_names_pre_forward_hook(target, args, kwargs, adapter_names): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["adapter_names"] = adapter_names + return args, kwargs + + +class RoadModel(BaseTuner): + """ """ + + prefix: str = "road_" + tuner_layer_cls = RoadLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + road_config: RoadConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key, + ) -> None: + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Regexp matching - Find key which matches current target_name in patterns provided + variant = road_config.variant + group_size = road_config.group_size + + kwargs = { + "variant": variant, + "group_size": group_size, + "init_weights": road_config.init_weights, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + # for torchao merging, we need the get_apply_tensor_subclass from the quantization config + try: + kwargs["get_apply_tensor_subclass"] = operator.attrgetter( + "hf_quantizer.quantization_config.get_apply_tensor_subclass" + )(self.model) + except AttributeError: + pass + + if isinstance(target, RoadLayer): + target.update_layer( + adapter_name, + variant, + group_size, + init_weights=road_config.init_weights, + ) + else: + device_map = get_device_map(self.model) + new_module = self._create_new_module(road_config, adapter_name, target, device_map=device_map, **kwargs) + if adapter_name not in self.active_adapters: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(road_config: RoadConfig, adapter_name, target, **kwargs): + dispatchers = [] + + # avoid eager bnb import + if is_bnb_available(): + from .bnb import dispatch_bnb_8bit + + dispatchers.append(dispatch_bnb_8bit) + + if is_bnb_4bit_available(): + from .bnb import dispatch_bnb_4bit + + dispatchers.append(dispatch_bnb_4bit) + + dispatchers.extend( + [ + dispatch_default, + ] + ) + + new_module = None + for dispatcher in dispatchers: + new_module = dispatcher(target, adapter_name, road_config=road_config, **kwargs) + if new_module is not None: # first match wins + break + + if new_module is None: + # no module could be matched + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + return new_module + + @contextmanager + def _enable_peft_forward_hooks(self, *args, **kwargs): + # If adapter_names is passed as an argument, we inject it into the forward arguments. + adapter_names = kwargs.pop("adapter_names", None) + if adapter_names is None: + # nothing to do + yield + return + + if self.training: + raise ValueError("Cannot pass `adapter_names` when the model is in training mode.") + + # Check that users only passed actually existing adapters. + # Note: We cannot do this on the layer level, as each individual layer may not have each adapter. Still, we want + # to check that there is at least one layer with the given name, or else something like typos can easily slip. + expected_adapters = set() + for layer in self.modules(): + if isinstance(layer, RoadLayer): + expected_adapters |= layer.road_theta.keys() + unique_adapters = {name for name in adapter_names if name != "__base__"} + unexpected_adapters = unique_adapters - expected_adapters + if unexpected_adapters: + raise ValueError(f"Trying to infer with non-existing adapter(s): {', '.join(sorted(unexpected_adapters))}") + + hook_handles = [] + for module in self.modules(): + if isinstance(module, RoadLayer): + pre_forward = partial(_adapter_names_pre_forward_hook, adapter_names=adapter_names) + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + # TODO LoRA also has hooks for beam search, ignore this for now + + yield + + for handle in hook_handles: + handle.remove() diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..d5391b96059fc08580a12adb8b216b3a8bfd8024 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/__init__.py @@ -0,0 +1,27 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import ShiraConfig +from .layer import Linear, ShiraLayer +from .model import ShiraModel + + +__all__ = ["Linear", "ShiraConfig", "ShiraLayer", "ShiraModel"] + + +register_peft_method( + name="shira", config_cls=ShiraConfig, model_cls=ShiraModel, prefix="shira_", is_mixed_compatible=True +) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/config.py new file mode 100644 index 0000000000000000000000000000000000000000..d868e51490637c47c13b3c0ae2cb1f5c88cb7ebc --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/config.py @@ -0,0 +1,129 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field +from typing import Literal, Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + +from .mask_functions import random_mask + + +@dataclass +class ShiraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`ShiraModel`]. + + Args: + r (`int`, *optional*, defaults to `32`): + For a given target module, the number of SHiRA parameters is computed as r(m+n), where the original tensor + dimensions are m x n. This means the number of SHiRA parameters is the same as that for a LoRA adapter. + SHiRA is a high rank adapter. Setting this r parameter does not restrict the rank to this value. + mask_type (`str`, defaults to `random`): + Type of mask function. Defaults to a random sparse mask. An optional user-defined mask_fn to compute the + mask value can also be supplied by instantiating `config = ShiraConfig(...)` and then setting + `config.mask_fn = `. For a pretrained weight with shape m x n, the custom mask + function must return only one mask (shape: m x n) which must be binary 0 or 1 with num_shira_parameters = + r(m + n) for linear layers. Device and dtype of mask must be same as base layer's weight's device and + dtype. Please see mask_functions.py for more details and to see the default random sparse mask + implementation. + random_seed (`int`, *optional*, defaults to `None`): + random seed for the torch generator for random_mask. + target_modules (`Union[List[str], str]`): + List of module names or regex expression of the module names to replace with SHiRA. For example, ['q', 'v'] + or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. Only linear layers are supported. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + init_weights (`bool`, defaults to `True`): + Initialize SHiRA weight to have zero values. If set to False, SHiRA weights are initialized to randn values + instead of zeros and this is used only for testing. + modules_to_save (`List[str]`): + List of modules apart from SHiRA layers to be set as trainable and saved in the final checkpoint. + """ + + r: int = field( + default=32, + metadata={ + "help": ( + "For a given target module, the number of SHiRA parameters is computed as r(m+n), where the original " + "tensor dimensions are m x n. This means the number of SHiRA parameters is the same as that for a LoRA adapter. " + "SHiRA is a high rank adapter. Setting this r parameter does not restrict the rank to this value." + ) + }, + ) + mask_type: Literal["random"] = field( + default="random", + metadata={ + "help": ( + "Type of mask function. Defaults to a random sparse mask. " + "An optional user-defined mask_fn to compute the mask value can also be supplied by instantiating `config = ShiraConfig(...)` and then setting " + "`config.mask_fn = `. For a pretrained weight with shape m x n, the custom mask function must return only one mask (shape: m x n) " + "which must be binary 0 or 1 with num_shira_parameters = r(m + n) for linear layers. Device and dtype of mask must be same as base layer's weight's device and dtype. " + "Please see mask_functions.py for more details and to see the default random sparse mask implementation." + ) + }, + ) + random_seed: Optional[int] = field( + default=None, metadata={"help": "random seed for the torch generator for random_mask"} + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with SHiRA." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": "Initialize SHiRA weight to have zero values. If set to False, SHiRA weights are initialized to randn values instead of zeros and this is used only for testing." + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from SHiRA layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.SHIRA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + if self.mask_type == "random": + self.mask_fn = random_mask + else: + if not self.inference_mode: + warnings.warn( + f"Argument {self.mask_type=} is not recognized, please supply your own masking function by calling `config.mask_fn = my_mask_fn`." + ) + self.mask_fn = None diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ff5626ccdcd8c367a009bc55d6c2efc6c6d1ea30 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/layer.py @@ -0,0 +1,221 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import copy +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge + + +class ShiraLayer(BaseTunerLayer): + # List all names of layers that may contain trainable adapter weights + adapter_layer_names = ("shira_weight",) + # All names of other adapter-related parameters + other_param_names = ("r", "scaling", "shira_indices") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.scaling = {} + self.shira_weight = nn.ParameterDict({}) + self.shira_indices = {} + self.weight_shape = base_layer.weight.shape # Assumes SHiRA is on some layer with "weight" parameter + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + else: + raise NotImplementedError("Only nn.Linear layers supported currently") + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + def update_layer( + self, + adapter_name, + mask, + r, + init_weights: bool = True, + inference_mode: bool = False, + **kwargs, + ): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + self.r[adapter_name] = r + self.scaling[adapter_name] = ( + 1.0 # Default scale during training. Can be set to any (non-negative) value during inference. + ) + # The number of shira weights in this layer is determined by r such that the total number of weights is the same as a LoRA Layer (for direct comparisons) + num_shira_weight = r * (self.in_features + self.out_features) + if num_shira_weight > self.in_features * self.out_features: + raise ValueError( + f"The set rank {r} results in more shira params than the total number of params in the base layer {self.in_features * self.out_features} and this is not allowed." + ) + + # Actual trainable parameters + # We have used a vector parameter with fixed indices that we use inside a torch.sparse_coo_tensor in get_delta_weight function. + # Directly using a torch.sparse_coo_tensor as a parameter could have been possible but we ran into some issues similar to: + # https://github.com/pytorch/pytorch/issues/79542. + shira_init_weight = torch.zeros(num_shira_weight) if init_weights else torch.randn(num_shira_weight) + self.shira_weight[adapter_name] = nn.Parameter( + shira_init_weight.to(self.base_layer.weight.dtype).to(self.base_layer.weight.device), + requires_grad=True, + ) + + if mask is not None: + # Compute the shira_indices from the mask. Make sure the mask is formed using r*(self.in_features + self.out_features) and not some other K. + mask_indices = torch.where(mask == 1.0) + self.shira_indices[adapter_name] = torch.cat( + [mask_indices[0].unsqueeze(0), mask_indices[1].unsqueeze(0)], 0 + ).to(torch.int) + self.shira_indices[adapter_name] = self.shira_indices[adapter_name].to(self.base_layer.weight.device) + + if self.shira_indices[adapter_name].shape[1] != self.shira_weight[adapter_name].shape[0]: + raise ValueError( + f"The SHiRA indices and weights are not the same dimensions for adapter {adapter_name} in layer {self.base_layer}" + ) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_shira_parameters(self, adapter_name): + nn.init.zeros_(self.shira_weight[adapter_name]) + + def set_scale(self, adapter, scale): + if adapter not in self.scaling: + # Ignore the case where the adapter is not in the layer + return + self.scaling[adapter] = scale + + +class Linear(nn.Module, ShiraLayer): + # SHiRA implemented in a dense layer + def __init__( + self, + base_layer, + mask, + adapter_name: str, + r: int = 0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stored weight like (fan_in, fan_out) + init_weights: bool = True, + **kwargs, + ) -> None: + super().__init__() + ShiraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + if self.base_layer is not self.get_base_layer(): + raise ValueError("SHiRA does not support nested base layers") + + self._active_adapter = adapter_name + self.update_layer(adapter_name, mask, r, init_weights=init_weights) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.shira_weight.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += self.get_delta_weight(active_adapter) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.shira_weight.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + + # In multi-gpu environment, the indices are at the wrong gpu. This is needed to correct this. + self.shira_indices[adapter] = self.shira_indices[adapter].to(self.shira_weight[adapter].device) + return torch.sparse_coo_tensor( + self.shira_indices[adapter], self.shira_weight[adapter] * self.scaling[adapter], self.weight_shape + ) + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + new_weight = copy.deepcopy(self.base_layer.weight.data) + for active_adapter in self.active_adapters: + if active_adapter not in self.shira_weight.keys(): + continue + new_weight += self.get_delta_weight(active_adapter) + + result = F.linear(x, new_weight, bias=self.base_layer.bias) + + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + # delta weight is sparse, which does not work with SVD + return False + + def __repr__(self) -> str: + rep = super().__repr__() + return "shira." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/mask_functions.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/mask_functions.py new file mode 100644 index 0000000000000000000000000000000000000000..d8afbfa8ed23589c74306b0d6e2da071e2f64a11 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/mask_functions.py @@ -0,0 +1,72 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +This module is intended to store mask functions for use inside SHiRA construction. The mask functions are required to +have a specific signature as shown below. + +Required positional arguments: + base_layer - This is the linear layer where the shira adapter will be attached. r - This parameter is used to + determine the number of parameters in the + shira adapter in a way that is consistent with LoRA sizing. SHiRA is a high rank adapter. Setting this + parameter does not restrict the adapter rank. +Keyword arguments can be provided as needed by the particular mask function implementation. + +Return: + mask - this is a torch.tensor of the same shape as base_layer.weight that contains 0s and 1s with the same + dtype and device as base_layer.weight + +If you would like to attach SHiRA adapters to a model using PEFT methods (such as get_peft_model()), using more +arguments than the provided positional arguments, you can create the mask function reference like the following: + +``` + def create_mask_function_reference(**my_kwargs): + def mask_fn(base_layer, r): + ... your implementation here that might use my_kwargs ... + return mask + return mask_fn +``` +Then, you can create your peft model with custom SHiRA mask as follows: +``` + model = ... + my_kwargs = ... + mask_fn = create_mask_function_reference(**my_kwargs) + peft_config = ShiraConfig(r=4, mask_type='my_custom_mask') + peft_config.mask_fn = mask_fn + peft_model = get_peft_model(model, peft_config) +``` + +Complete training examples are provided in the examples/shira/ directory. +""" + +from typing import Optional + +import torch +import torch.nn as nn + + +def random_mask(base_layer: nn.Module, r: int, random_seed: Optional[int] = None, **kwargs) -> torch.tensor: + shape = base_layer.weight.shape + num_shira_weights = r * (shape[0] + shape[1]) + random_generator = torch.Generator() + if random_seed is not None: + random_generator.manual_seed(random_seed) + idx = (torch.randperm(base_layer.weight.numel(), generator=random_generator)[:num_shira_weights]).to( + base_layer.weight.device + ) + val = torch.ones_like(idx.type(base_layer.weight.dtype)) + mask = torch.zeros_like(base_layer.weight.view(1, -1)) + mask = mask.scatter_(1, idx.unsqueeze(0), val.unsqueeze(0)).view(shape) + + return mask diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/model.py new file mode 100644 index 0000000000000000000000000000000000000000..c212a9bf2c110bba5a180eaf2cac0bda9a93ee6e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/shira/model.py @@ -0,0 +1,142 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings + +import torch + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, +) + +from .layer import Linear, ShiraLayer + + +class ShiraModel(BaseTuner): + """ + Creates a Sparse High Rank Adapter (SHiRA) Model from a pretrained model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`ShiraConfig`]): The configuration of the SHiRA model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + + Returns: + `torch.nn.Module`: The SHiRA model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import ShiraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = ShiraConfig(r=32) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`ShiraConfig`]): The configuration of the SHiRA model. + """ + + prefix: str = "shira_" + tuner_layer_cls = ShiraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING + + def _create_and_replace( + self, + shira_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + bias = hasattr(target, "bias") and target.bias is not None + kwargs = {} + kwargs["bias"] = bias + if shira_config.mask_type == "random": + kwargs["random_seed"] = shira_config.random_seed + + for k, v in optional_kwargs.items(): + kwargs[k] = v + + if isinstance(target, Linear): + mask = ( + shira_config.mask_fn(target.base_layer, shira_config.r, **kwargs) + if shira_config.mask_fn is not None + else None + ) + target.update_layer( + adapter_name, + mask, + shira_config.r, + init_weights=shira_config.init_weights, + ) + else: + new_module = self._create_new_module(shira_config, adapter_name, target, **kwargs) + if adapter_name not in self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(shira_config, adapter_name, target, **kwargs): + fan_in_fan_out = shira_config.fan_in_fan_out + + _ = kwargs.pop("bias", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if fan_in_fan_out: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + fan_in_fan_out = shira_config.fan_in_fan_out = False + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + mask = ( + shira_config.mask_fn(target_base_layer, shira_config.r, **kwargs) + if shira_config.mask_fn is not None + else None + ) + + new_module = Linear( + target, + mask, + adapter_name, + shira_config.r, + fan_in_fan_out, + init_weights=shira_config.init_weights, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4aa7bf8e5fc4705cb7b190cee0de53ac8db89573 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/__init__.py @@ -0,0 +1,33 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import TrainableTokensConfig +from .layer import TrainableTokensLayer +from .model import TrainableTokensModel + + +__all__ = [ + "TrainableTokensConfig", + "TrainableTokensLayer", + "TrainableTokensModel", +] + +register_peft_method( + name="trainable_tokens", + config_cls=TrainableTokensConfig, + model_cls=TrainableTokensModel, + is_mixed_compatible=False, +) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/config.py new file mode 100644 index 0000000000000000000000000000000000000000..7412d7f06474c510679e0f3004ae10c20910b00f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/config.py @@ -0,0 +1,89 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class TrainableTokensConfig(PeftConfig): + """ + Configuration for the `TrainableTokens` method. + + Allows for training new tokens (and re-training existing ones) without training the full embedding matrix. By + marking a few select tokens (identified by their indices) trainable and leaving the rest untouched, this method can + be used to add new tokens or changing the embedding of existing tokens while saving on memory. Both storage as well + as working memory usage are reduced in contrast to training the embedding matrix fully. + + Note that training with FSDP/DeepSpeed might not yet be fully supported. + + Args: + token_indices (`list[int]`): + List of integers, signifying the indices of the tokens you want to be trainable. To find the index of a + token with a tokenizer, you can tokenize the string and look at the returned `input_ids`. The closer the + amount of indices is to the total amount of tokens, the less efficient this method gets. + target_modules (`Optional[Union[list[str], str]]`): + List of module names or regex expression of the module names to replace with our `TrainableTokensLayer`. If + not defined, it will attempt to get the model's input embedding layer if the model has a + `get_input_embeddings` method (transformer models usually do), if that fails the default is 'embed_tokens'. + Other example targets are `embedding`, `encoder.embeddings` or `decoder.embeddings`. + init_weights (`bool`): + By default the new token weights are initialized to be the same as the respective token embeddings. This + makes TrainableTokens a no-op when not trained. If set to `False` the weights will be random values. Do not + change this setting unless you know exactly what you're doing. + """ + + token_indices: list[int] = field( + default_factory=list, + metadata={ + "help": ( + "List of integers, signifying the indices of the tokens you want to be trainable. " + "To find the index of a token with a tokenizer, you can tokenize the string and " + "look at the returned `input_ids`. The closer the amount of indices is to the total amount of " + "tokens, the less efficient this method gets." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with our " + "`TrainableTokensLayer`. If not defined, it will default to the model's input embedding layer if " + "the model has a `get_input_embeddings` method (transformer models usually do), if that fails the " + "default is 'embed_tokens'. Other example targets could be `embedding`, `encoder.embeddings` or " + "`decoder.embeddings`." + ), + }, + ) + + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "By default the new token weights are initialized to be the same as the respective token embeddings. " + "This makes TrainableTokens a no-op when not trained. If set to `False` the weights will be random " + "values. Do not change this setting unless you know exactly what you're doing. " + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.TRAINABLE_TOKENS diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..78c8df40912f66369d245679658076492843cb4e --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/layer.py @@ -0,0 +1,262 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import warnings +from typing import Optional + +import torch +import torch.distributed as dist +import torch.nn as nn +import torch.nn.functional as F + +from peft.tuners._buffer_dict import BufferDict +from peft.tuners.tuners_utils import BaseTunerLayer, _get_in_out_features, check_adapters_to_merge +from peft.utils.integrations import check_deepspeed_zero3_enabled, gather_params_ctx + + +class TrainableTokensLayer(nn.Module, BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("trainable_tokens_delta",) + + # All names of other parameters that may contain adapter-related parameters + other_param_names = ("token_indices", "trainable_tokens_original") + + def __init__( + self, + base_layer: nn.Module, + adapter_name: str, + token_indices: list[int], + tied_adapter: Optional[TrainableTokensLayer] = None, + **kwargs, + ) -> None: + super().__init__() + + self.base_layer = base_layer + self._active_adapter = adapter_name + self.kwargs = kwargs + + # wrap the tied adapter in a list so that it is excluded from .(named_)modules() and, therefore, + # not included in the state dict since it would be a copy of the tied adapter anyway. + self._tied_adapter = [tied_adapter] if tied_adapter else [] + + # we store the updated weights of particular tokens and their originals. we assume + # that the count of new tokens is far smaller than the number of total tokens. + # + # In case we have weight tying with another token adapter, we'll have no actual + # references on our own but use everything from the tied adapter. + if not self.tied_adapter: + self.trainable_tokens_delta = nn.ParameterDict({}) + self.trainable_tokens_original = BufferDict({}) + self.token_indices = {} + else: + self.trainable_tokens_delta = self.tied_adapter.trainable_tokens_delta + self.trainable_tokens_original = self.tied_adapter.trainable_tokens_original + self.token_indices = self.tied_adapter.token_indices + + # Mark the weight as unmerged + self.merged_adapters = [] + + in_features, out_features = _get_in_out_features(self.get_base_layer()) + self.in_features = in_features + self.out_features = out_features + + @property + def tied_adapter(self): + if self._tied_adapter: + return self._tied_adapter[0] + return None + + def _collect_token_weights(self, weight: torch.Tensor, rows: torch.Tensor, embed_dim: int) -> torch.Tensor: + """DeepSpeed zero3 specific code to initialize trainable tokens. + + Ensures that only the necessary weights are collected to a single rank, initialized, and then shared with all + ranks. + """ + src_rank = 0 + # right now, only CUDA is implemented + device = torch.device("cuda", torch.cuda.current_device()) + + with gather_params_ctx([weight], modifier_rank=None): + if dist.is_available() and dist.is_initialized() and dist.get_rank() == src_rank: + token_weights = weight[rows].clone() + else: + # build an empty tensor with correct shape/type/device + token_weights = torch.empty( + (len(rows), embed_dim), + dtype=weight.dtype, + device=device, + ) + + # share the weights with all ranks + dist.broadcast(token_weights, src=src_rank) + return token_weights + + def update_layer(self, adapter_name, **kwargs): + if kwargs.get("tied_adapter", None): + # as a tied adapter, we're just following whatever the adpater we're tied to does, we don't update anything. + return + + self.token_indices[adapter_name] = kwargs["token_indices"] + init_weights = kwargs.get("init_weights", True) + + # we initialize the delta embedding weights from the base embedding matrix and replace values instead of + # adding/subtracting deltas. we do it this way and use `embedding.weight.index_copy()` to write the updated + # values during `forward()` to avoid that the user resizing the embedding matrix, effectively filling the new + # token space with random values, training the model with TrainableTokensLayer, initializing the model anew - + # thus re-initializing the new embeddings again with new random variables. If we would add/subtract deltas + # onto the new values, we would get undefined behavior. By replacing the specific token values we always + # get defined behavior. + weight = self.get_base_layer().weight + + if hasattr(self.get_base_layer(), "embedding_dim"): + embed_dim = self.get_base_layer().embedding_dim + else: + # lm_head doesn't have embedding_dim attribute + embed_dim = self.get_base_layer().in_features + + if init_weights: + if check_deepspeed_zero3_enabled(): + values = self._collect_token_weights(weight, self.token_indices[adapter_name], embed_dim) + else: + values = self.weight[self.token_indices[adapter_name]] + else: + # random init with matching dtype/device + values = torch.randn( + (len(self.token_indices[adapter_name]), embed_dim), + dtype=weight.dtype, + device=weight.device, + ) + + self.trainable_tokens_delta[adapter_name] = nn.Parameter(values.clone(), requires_grad=True) + self.trainable_tokens_original[adapter_name] = values.clone() + + self._move_adapter_to_device_of_base_layer(adapter_name) + + def _check_overlapping_tokens(self, adapter_names): + """Raises an error if the token indices of the given adapter names are overlapping. + This is currently not supported and can lead to undefined behavior of the model if no specific merging between + the overlapping indices' values is applied. + """ + if len(adapter_names) <= 1: + return + + indices = set() + + # we take already merged adapters into account as well since they can be overridden by new adapters as well. + for adapter_name in set(adapter_names + self.merged_adapters): + index_set = set(self.token_indices[adapter_name]) + if len(indices.intersection(index_set)): + raise ValueError( + f"Token indices of adapter {adapter_name} are already defined and would result in " + "undefined merging behavior. Only disjunct token indices are currently supported." + ) + indices.update(index_set) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + adapter_names = check_adapters_to_merge(self, adapter_names) + + if not adapter_names: + # no adapter to merge + return + + self._check_overlapping_tokens(adapter_names) + + merged = self.base_layer.weight.data + + for adapter_name in adapter_names: + index = torch.tensor(self.token_indices[adapter_name]).to(merged.device) + deltas = self.trainable_tokens_delta[adapter_name].to(merged) + merged = merged.index_copy(dim=0, index=index, source=deltas) + + if safe_merge and not torch.isfinite(merged).all(): + raise ValueError(f"NaNs detected in the merged weights. The adapter {adapter_name} seems to be broken") + + self.base_layer.weight.data = merged + self.merged_adapters.extend(adapter_names) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + adapter_name = self.merged_adapters.pop() + + index = torch.tensor(self.token_indices[adapter_name]).to(self.base_layer.weight.device) + originals = self.trainable_tokens_original[adapter_name].to(self.base_layer.weight) + self.base_layer.weight.data.index_copy_(dim=0, index=index, source=originals) + + def get_merged_weights(self, active_adapters) -> torch.Tensor: + W = self.base_layer.weight + + for adapter_name in active_adapters: + index = torch.tensor(self.token_indices[adapter_name]).to(W.device) + deltas = self.trainable_tokens_delta[adapter_name].to(W) + W = W.index_copy(dim=0, index=index, source=deltas) + + # Note: the return type is a Tensor, not an nn.Parameter. This can lead to some errors, e.g. torch's + # model.get_parameter fails as it does a type check. But we cannot return an nn.Parameter here, as it can lead + # to other failures, as this is not a true nn.Parameter of the model. + return W + + def forward_adapters(self, x: torch.Tensor, active_adapters, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters or not active_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + self._check_overlapping_tokens(active_adapters) + + W = self.get_merged_weights(active_adapters) + + # Normally it should be very clear that we're wrapping Embedding layers but there are cases, such as + # tying weights with an LM head where the layer we wrap is a Linear layer. Therefore we must choose + # accordingly. + # + # TODO: the isinstance checks, especially the one for nn.Linear, may not hold for quantized layers; + # TODO: we may need to find a better way to detect quantized layers. + if isinstance(self.base_layer, torch.nn.Embedding): + result = F.embedding( + input=x, + weight=W, + padding_idx=self.base_layer.padding_idx, + max_norm=self.base_layer.max_norm, + norm_type=self.base_layer.norm_type, + scale_grad_by_freq=self.base_layer.scale_grad_by_freq, + sparse=self.base_layer.sparse, + ) + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since we're using F.embedding directly, we need to apply this scaling manually. + embed_scale = self._get_embed_scale() + if embed_scale is not None: + result = result * embed_scale.to(result.dtype) + elif isinstance(self.base_layer, torch.nn.Linear): + # Probably a tied adapter that wraps an LM head. + result = F.linear( + input=x, + weight=W, + ) + else: + raise ValueError( + "TrainableTokensLayer wraps an unknown layer type, maybe you are targeting the wrong layer?" + ) + + return result + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + return self.forward_adapters(x, self.active_adapters, *args, **kwargs) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/model.py new file mode 100644 index 0000000000000000000000000000000000000000..a3a7c7ae520eab045a2dd1449fa1bb9785578f51 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/trainable_tokens/model.py @@ -0,0 +1,153 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import torch.nn as nn + +from peft.config import PeftConfig +from peft.tuners.tuners_utils import BaseTuner +from peft.utils import _get_input_embeddings_name, _get_submodules + +from .layer import TrainableTokensLayer + + +class TrainableTokensModel(BaseTuner): + prefix: str = "trainable_tokens_" + tuner_layer_cls = TrainableTokensLayer + + def _prepare_adapter_config(self, peft_config, model_config): + # target_modules can be none which prompts us to infer the embedding layer name ourselves. + if peft_config.target_modules is None: + peft_config.target_modules = _get_input_embeddings_name(self.model, "embed_tokens") + + return peft_config + + def inject_adapter( + self, + model: nn.Module, + adapter_name: str, + autocast_adapter_dtype: bool = True, + low_cpu_mem_usage: bool = False, + **kwargs, + ) -> None: + super().inject_adapter( + model=model, + adapter_name=adapter_name, + autocast_adapter_dtype=autocast_adapter_dtype, + low_cpu_mem_usage=low_cpu_mem_usage, + **kwargs, + ) + + model_config = self.get_model_config(self) + + # In case of weight-tying we need to adapt the tied weights as well and use tie the embedding adapter. + # + # The TrainableTokensLayer supports being tied to another TrainableTokensLayer meaning that the layer will + # not do any changes on its own but solely rely on the weights from the tied adapter. We will search for the + # tied weights and put tied TrainableTokensLayer adapters on them, all tied to the adapter of the embedding + # matrix. + tied_weights_module_names = self._get_module_names_tied_with_embedding() + + if ( + tied_weights_module_names + and model_config.get("tie_word_embeddings", False) + and isinstance(self.model.get_input_embeddings(), TrainableTokensLayer) + ): + # disable removing of duplicates since we're essentially only dealing with duplicates (i.e. tied weights) + for name, module in self.model.named_modules(remove_duplicate=False): + matched_keys = [target_key for target_key in tied_weights_module_names if name.endswith(target_key)] + if matched_keys: + parent, target, target_name = _get_submodules(model, name) + + # If the module is already a TrainableTokensLayer, we need to replace it with a tied version + # instead of just updating it. This handles the case where the user explicitly targeted + # both the embedding and tied layers in target_modules. + if isinstance(target, TrainableTokensLayer): + # Replace the existing layer with a new one that's tied to the embedding + peft_config = self.peft_config[adapter_name].to_dict() + peft_config["tied_adapter"] = self.model.get_input_embeddings() + + new_module = self._create_new_module( + peft_config, adapter_name, target.base_layer, **peft_config + ) + self._replace_module(parent, target_name, new_module, target.base_layer) + else: + # Module hasn't been wrapped yet, create and replace normally + peft_config = self.peft_config[adapter_name].to_dict() + peft_config["tied_adapter"] = self.model.get_input_embeddings() + + self._create_and_replace_dict( + peft_config, + adapter_name, + target, + target_name, + parent, + matched_keys[0], + ) + + def _get_tied_target_modules(self, *args, **kwargs): + # Normally this method would return the layers that target tied layers. + # + # We override this method since we explicitly support tied weights tied to the embedding layer. + # Therefore, we don't need the warning issued by returning the modules here. + return [] + + def _create_and_replace_dict( + self, + peft_config: dict, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + ) -> None: + """ + The same as `_create_and_replace` but takes a dictionary instead of a peft config so that we can add keys that + are not present in the config, such as `tied_adapter`. + """ + kwargs = peft_config + + if isinstance(target, TrainableTokensLayer): + target.update_layer(adapter_name, **kwargs) + else: + new_module = self._create_new_module(peft_config, adapter_name, target, **kwargs) + self._replace_module(parent, target_name, new_module, target) + + def _create_and_replace( + self, + peft_config: PeftConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + ) -> None: + """ + A private method to create and replace the target module with the adapter module. + """ + kwargs = peft_config.to_dict() + self._create_and_replace_dict(kwargs, adapter_name, target, target_name, parent, current_key) + + @staticmethod + def _create_new_module(peft_config, adapter_name, target, **kwargs): + new_module = TrainableTokensLayer(target, adapter_name, **kwargs) + new_module.update_layer( + adapter_name, + init_weights=kwargs["init_weights"], + token_indices=kwargs["token_indices"], + tied_adapter=kwargs.get("tied_adapter", None), + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/tuners_utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/tuners_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..1e90e3b328aebd9d11bb11947e4823df4683d856 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/tuners_utils.py @@ -0,0 +1,2181 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +import dataclasses +import os +import re +import textwrap +import warnings +from abc import ABC, abstractmethod +from collections.abc import Sequence +from contextlib import contextmanager, nullcontext +from typing import Any, Optional, Union, overload + +import torch +from accelerate.hooks import AlignDevicesHook +from accelerate.utils import named_module_tensors, offload_state_dict +from packaging import version +from torch import nn +from tqdm import tqdm +from transformers import PreTrainedModel +from transformers.pytorch_utils import Conv1D + +from peft.mapping import PEFT_TYPE_TO_PREFIX_MAPPING +from peft.utils import INCLUDE_LINEAR_LAYERS_SHORTHAND +from peft.utils.constants import ( + DUMMY_MODEL_CONFIG, + DUMMY_TARGET_MODULES, + EMBEDDING_LAYER_NAMES, + MIN_TARGET_MODULES_FOR_OPTIMIZATION, + SEQ_CLS_HEAD_NAMES, +) +from peft.utils.integrations import init_empty_weights +from peft.utils.other import ( + AuxiliaryTrainingWrapper, + _get_module_names_tied_with_embedding, + _set_adapter, + _set_layer_requires_grad, + match_target_against_key, + set_additional_trainable_modules, +) +from peft.utils.peft_types import PeftType, TaskType +from peft.utils.warning import PeftWarning + +from ..config import PeftConfig +from ..utils import _get_submodules +from ._buffer_dict import BufferDict + + +warn_msg_weight_tying = ( + "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, " + "but no implementation exists to tie the adapters. " + "This can lead to complications, for example when merging the adapter " + "or converting your model to formats other than safetensors. " + "Check the discussion here: https://github.com/huggingface/peft/issues/2777" +) +_torch_supports_dtensor = version.parse(torch.__version__) >= version.parse("2.5.0") +_torch_supports_distributed = _torch_supports_dtensor and torch.distributed.is_available() + + +@contextmanager +def onload_layer(layer): + r""" + A utility for modifying a module containing one or more tuners and a base layer, any of which are offloaded to the + CPU or disk. Moves a module's sub-modules to the execution device before some action is performed, after that the + base layer state dictionary is re-assigned (if that layer was offloaded to the disk) and finally the parameters are + offloaded. + + If the module has no offloaded sub-modules, this function does nothing. + + Args: + layer ('torch.nn.Module'): + layer with tuners to be merged + """ + + offloaded_modules = [] + for name, module in layer.named_modules(): + if name in ["", "base_layer"]: + continue + if hasattr(module, "_hf_hook") and isinstance(module._hf_hook, AlignDevicesHook) and module._hf_hook.offload: + module._hf_hook.pre_forward(module) + offloaded_modules.append(module) + + base_layer_offload = False + if hasattr(layer, "base_layer") and ( + hasattr(layer.base_layer, "_hf_hook") + and isinstance(layer.base_layer._hf_hook, AlignDevicesHook) + and layer.base_layer._hf_hook.offload + ): + # check if the base layer is disk-offloaded (must contain a 'dataset' and an offload index) + if torch.device("meta") in layer.base_layer._hf_hook.original_devices.values() and hasattr( + layer.base_layer._hf_hook.weights_map, "dataset" + ): + # find the disk-offload index (maps modules to safetensors) from the `dataset` (OffloadedWeightsLoader object) + index = layer.base_layer._hf_hook.weights_map.dataset.index + module_name = list(dict(layer.base_layer._hf_hook.weights_map.dataset).keys())[0] # any module will do + file_name = index[module_name]["safetensors_file"] + base_name_arr = [] + # get effective dir name + for i in os.path.split(file_name): + if "--" in i: + base_name_arr.append(i) + break + base_name_arr.append(i) + base_name = os.path.join(*base_name_arr) + safetensors_filename = base_name + "-merged" + layer.base_layer._hf_hook.pre_forward(layer.base_layer) + base_layer_offload = True + + yield + + for module in offloaded_modules: + module._hf_hook.post_forward(module, torch.tensor([])) + + if base_layer_offload: + # re-make weights map (must be on cpu to send params to the disk via memmap if disk offload) + layer.base_layer._hf_hook.weights_map = { + name: param.to("cpu") for name, param in named_module_tensors(layer.base_layer) + } + # offload weights map to disk if original device is the disk + if torch.device("meta") in layer.base_layer._hf_hook.original_devices.values() and hasattr( + layer.base_layer._hf_hook.weights_map, "dataset" + ): + # rewrite directory with merged weights + offload_state_dict(safetensors_filename, layer.base_layer._hf_hook.weights_map) + layer.base_layer._hf_hook.post_forward(layer.base_layer, torch.tensor([])) + + +def _check_lora_target_modules_mamba(peft_config: PeftConfig, model: nn.Module, target_name: str): + """ + Prevent applying LoRA to incompatible modules in specific architectures (e.g., Mamba). + """ + + lora_like_types = {"LORA", "ADALORA", "XLORA", "RANDLORA"} + incompatible_modules = {"out_proj", "conv1d"} + mamba_model_types = {"falcon_h1", "mamba", "mamba2", "falcon_mamba"} + + if ( + peft_config.peft_type in lora_like_types + and hasattr(model, "config") + and getattr(model.config, "model_type", None) in mamba_model_types + ): + if target_name in incompatible_modules: + raise ValueError( + f"[PEFT:{peft_config.peft_type}] Module '{target_name}' is incompatible with Mamba-based models " + f"(model_type='{model.config.model_type}'). Incompatible modules: {incompatible_modules}. " + "Please remove it from `target_modules` to avoid compatibility issues." + ) + + +def _get_in_out_features(module: nn.Module) -> tuple[int, int] | tuple[None, None]: + """ + Get the in_features and out_features of the layer. + + Returns in_features and out_features as a tuple. If they cannot be determined, return a tuple of None and None. + This function covers a broad range of layers, some of which the caller might not support. Therefore, just because + this function returns a valid result does not imply that the layer type is supported. + """ + if isinstance(module, nn.Linear): + if _torch_supports_distributed and isinstance(module.weight, torch.distributed.tensor.DTensor): + # If Tensor Parallel is used, the weight is sharded, so we need to get the local shape + out_features, in_features = module.weight.to_local().shape + else: + in_features, out_features = module.in_features, module.out_features + elif isinstance(module, nn.Conv1d): + in_features, out_features = module.in_channels, module.out_channels + elif isinstance(module, nn.Conv2d): + in_features, out_features = module.in_channels, module.out_channels + elif isinstance(module, nn.Conv3d): + in_features, out_features = module.in_channels, module.out_channels + elif isinstance(module, nn.Embedding): + in_features, out_features = module.num_embeddings, module.embedding_dim + elif isinstance(module, Conv1D): + in_features, out_features = ( + module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape + ) + elif isinstance(module, nn.MultiheadAttention): + if not module._qkv_same_embed_dim: + raise ValueError("Only same dim for query/key/value is supported as of now for MultiheadAttention.") + in_features, out_features = module.embed_dim, 3 * module.embed_dim + elif hasattr(module, "infeatures") and hasattr(module, "outfeatures"): + # QuantLinear + in_features, out_features = module.infeatures, module.outfeatures + elif hasattr(module, "input_size") and hasattr(module, "output_size"): + # Megatron ColumnParallelLinear,RowParallelLinear + in_features, out_features = module.input_size, module.output_size + elif module.__class__.__name__ == "Linear" or module.__class__.__name__ == "LayerNormLinear": + # TransformerEngine + in_features, out_features = module.in_features, module.out_features + elif module.__class__.__name__ == "LayerNormMLP": + # TransformerEngine + ln_weight = module.layer_norm_weight + ln_size = ln_weight.shape[0] + in_features, out_features = ln_size, ln_size + elif hasattr(module, "codebooks") and module.__class__.__name__ == "QuantizedLinear": + # AQLM QuantLinear + in_features, out_features = module.in_features, module.out_features + elif hasattr(module, "bits") and module.__class__.__name__ == "AwqGEMMQuantLinear": + # Awq layers + in_features, out_features = module.in_features, module.out_features + elif module.__class__.__name__ == "EetqLinear": + # Eetq layers + in_features, out_features = module.in_features, module.out_features + elif hasattr(module, "W_q") and module.__class__.__name__ == "HQQLinear": + # HQQ layers + in_features, out_features = module.in_features, module.out_features + elif module.__class__.__name__ == "PatchedLinear": + # INC layers + in_features, out_features = module.in_features, module.out_features + else: + # possibly support user provided custom layer types using dynamic dispatch + if hasattr(module, "in_features") and hasattr(module, "out_features"): + in_features, out_features = module.in_features, module.out_features + else: + in_features, out_features = None, None + warnings.warn(f"Unsupported layer type '{type(module)}' encountered, proceed at your own risk.", UserWarning) + return in_features, out_features + + +class BaseTuner(nn.Module, ABC): + r""" + A base tuner model that provides the common methods and attributes for all tuners that are injectable into a + torch.nn.Module + + For adding a new Tuner class, one needs to overwrite the following methods: + + - **_prepare_adapter_config**: + A private method to eventually prepare the adapter config, for example in case the field `target_modules` is + missing. + - **_create_and_replace**: + A private method to create and replace the target module with the adapter module. + - **_check_target_module_exists**: + A private helper method to check if the passed module's key name matches any of the target modules in the + adapter_config. + + The easiest is to check what is done in the `peft.tuners.lora.LoraModel` class. + + Attributes: + model (`torch.nn.Module`): + The model to which the adapter tuner layers will be attached. + forward (`Callable`): + The forward method of the model. + peft_config (`Union[`PeftConfig`, dict[str, PeftConfig]]`): + The adapter configuration object, it should be a dictionary of `str` to `PeftConfig` objects. One can also + pass a PeftConfig object and a new adapter will be created with the default name `adapter` or create a new + dictionary with a key `adapter_name` and a value of that peft config. + config (`dict[str, Any]`): + The model configuration object, it should be a dictionary of `str` to `Any` objects. + targeted_module_names (`list[str]`): + The list of module names that were actually adapted. Can be useful to inspect if you want to quickly + double-check that the `config.target_modules` were specified correctly. + targeted_parameter_names (`list[str]`): + The list of parameter names that were actually adapted. Can be useful to inspect if you want to quickly + double-check that the `config.target_parameters` were specified correctly. + prefix (`str`) + The PEFT-method specific unique prefix. E.g. `"lora_"` for LoRA. + """ + + # Required attributes for child classes: + + # The unique prefix for this PEFT method, e.g. 'lora_' for LoRA. + prefix: str + # The class of the tuner layer, e.g. `LoraLayer` for LoRA. + tuner_layer_cls: type[BaseTunerLayer] + # The default target modules for various transformers model architectures, like Llama. This is useful to allow users + # to skip specifying the `target_modules` in the config of the PEFT method. The default is often something like + # `{'llama': ['q_proj', 'v_proj'], ...}`. + target_module_mapping: dict[str, list[str]] + + def __init__( + self, + model, + peft_config: Union[PeftConfig, dict[str, PeftConfig]], + adapter_name: str, + low_cpu_mem_usage: bool = False, + state_dict: Optional[dict[str, torch.Tensor]] = None, + ) -> None: + super().__init__() + + self.model = model + self.targeted_module_names: list[str] = [] + self.targeted_parameter_names: list[str] = [] + + # For advanced developers, if you want to attach multiple adapters to your + # model, just add a `peft_config` dict attribute to your model. + if not hasattr(self, "peft_config"): + self.peft_config = {adapter_name: peft_config} if isinstance(peft_config, PeftConfig) else peft_config + else: + warnings.warn( + "Already found a `peft_config` attribute in the model. This will lead to having multiple adapters" + " in the model. Make sure to know what you are doing!" + ) + if isinstance(peft_config, PeftConfig): + self.peft_config[adapter_name] = peft_config + else: + # user is adding a dict of PeftConfigs + self.peft_config.update(peft_config) + + self.active_adapter: str | list[str] = adapter_name + self._pre_injection_hook(self.model, self.peft_config[adapter_name], adapter_name) + if peft_config != PeftType.XLORA or peft_config[adapter_name] != PeftType.XLORA: + self.inject_adapter(self.model, adapter_name, low_cpu_mem_usage=low_cpu_mem_usage, state_dict=state_dict) + + self._post_injection_hook(self.model, self.peft_config[adapter_name], adapter_name) + + # Copy the peft_config in the injected model. + self.model.peft_config = self.peft_config + + @property + def active_adapters(self) -> list[str]: + if isinstance(self.active_adapter, str): + return [self.active_adapter] + # is already a list of str + return self.active_adapter + + def forward(self, *args: Any, **kwargs: Any): + return self.model.forward(*args, **kwargs) + + def _pre_injection_hook(self, model: nn.Module, config: PeftConfig, adapter_name: str) -> None: + r""" + A hook to be called before the adapter is injected into the model. This method can be overridden by child + classes to perform any pre-injection operations. + + Args: + model (`nn.Module`): + The model to be adapted. + config (`PeftConfig`): + The adapter config. + adapter_name (`str`): + The adapter name. + """ + pass + + def _post_injection_hook(self, model: nn.Module, config: PeftConfig, adapter_name: str) -> None: + r""" + A hook to be called after the adapter is injected into the model. This method can be overridden by child + classes to perform any post-injection operations. + + Args: + model (`nn.Module`): + The model to be adapted. + config (`PeftConfig`): + The adapter config. + adapter_name (`str`): + The adapter name. + """ + pass + + def _prepare_adapter_config(self, peft_config: PeftConfig, model_config: dict) -> PeftConfig: + r""" + A private method to prepare the adapter config. + + For transformers based models, if `peft_config.target_modules` is None, for some model architectures, we can + automatically infer the target modules from the `TRANSFORMERS_MODELS_TO_XXX_TARGET_MODULES_MAPPING`. + + Args: + peft_config (`PeftConfig`): + The adapter config. + model_config (`dict`): + The transformers model config, that config should contain the `model_type` key. + + Returns: + peft_config (`PeftConfig`): + The PEFT config with updated `target_modules`. + + Raises: + ValueError: + Raises an error if the model type was not recognized. + """ + if peft_config.target_modules is None: + target_modules = self.target_module_mapping.get(model_config["model_type"]) + if target_modules is None: + raise ValueError("Please specify `target_modules` in `peft_config`") + peft_config.target_modules = set(target_modules) + return peft_config + + def _prepare_model(self, peft_config: PeftConfig, model: nn.Module): + r""" + A private method to modify the model structure before adapter is applied. + + See `peft.tuner.lora.LoraModel._prepare_model` for an example. + + Args: + peft_config (`PeftConfig`): + The prepared adapter config. + model (`nn.Module`): + The model that is going to be adapted. + """ + pass + + @staticmethod + def _check_tied_module_exists(peft_config: PeftConfig, key: str) -> bool | re.Match[str] | None: + """ + A helper method to check if the passed module's key name matches any of the tied modules + + Args: + config (`PeftConfig`): + A config to match target modules from. + key (`str`): + A key to search any matches in config. + + Returns: + `bool` + True if key matches any tied modules from config, False if no match found. + """ + target_modules_to_tie = getattr(peft_config, "target_modules_to_tie", []) or [] + return key in target_modules_to_tie or any( + key.endswith(f".{target_key}") for target_key in target_modules_to_tie + ) + + @staticmethod + def _check_target_module_exists(peft_config: PeftConfig, key: str) -> bool | re.Match[str] | None: + """ + A helper method to check if the passed module's key name matches any of the target modules in the + adapter_config. + + Args: + config (`PeftConfig`): + A config to match target modules from. + key (`str`): + A key to search any matches in config. + + Returns: + `bool` | `re.Match[str]` | `None`: + True or re.Match object if key matches any target modules from config, False or None if no match found. + """ + return check_target_module_exists(peft_config, key) + + @abstractmethod + def _create_and_replace( + self, + peft_config: PeftConfig, + adapter_name: str, + target: nn.Module, + target_name: str, + parent: nn.Module, + current_key: str, + parameter_name: Optional[str] = None, + ) -> None: + r""" + Inplace replacement of the target module with the adapter layer. This method needs to be overridden by all the + tuner classes. + + Check `peft.tuners.lora.LoraModel._create_and_replace` for an example. + + Args: + peft_config (`PeftConfig`): + The adapter config. + adapter_name (`str`): + The adapter name. + target (`nn.Module`): + The target module. + target_name (`str`): + The target module's name. + parent (`nn.Module`): + The parent module. + current_key (`str`): + The key of the current target being adapted. + parameter_name (`str`, *optional*) + If, and only if, an `nn.Parameter` is being targeted, this is the name of the parameter. + """ + ... + + def _mark_only_adapters_as_trainable(self, model: nn.Module) -> None: + """ + A helper method to mark only the adapter layers as trainable (i.e. module.requires_grad = False). + """ + for n, p in model.named_parameters(): + if self.prefix not in n: + p.requires_grad = False + + for active_adapter in self.active_adapters: + bias = getattr(self.peft_config[active_adapter], "bias", "none") + if bias == "none": + continue + + if bias == "all": + for n, p in model.named_parameters(): + if "bias" in n: + p.requires_grad = True + elif bias.endswith("_only"): # e.g. "lora_only" or "boft_only" + for m in model.modules(): + if isinstance(m, self.tuner_layer_cls) and hasattr(m, "bias") and m.bias is not None: + m.bias.requires_grad = True + else: + raise NotImplementedError(f"Requested bias: {bias}, is not implemented.") + + def _enable_adapter_layers(self, enabled: bool = True) -> None: + for module in self.model.modules(): + if isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)): + module.enable_adapters(enabled) + + def disable_adapter_layers(self) -> None: + """ + Disable all adapters in-place. + + When disabling all adapters, the model output corresponds to the output of the base model. + """ + # TODO: deprecate in favor of enable_adapters + for active_adapter in self.active_adapters: + bias_val = getattr(self.peft_config[active_adapter], "bias", "none") + if bias_val != "none": + msg = ( + f"Careful, disabling adapter layers with bias configured to be '{bias_val}' does not produce the " + "same output as the base model would without adaption." + ) + warnings.warn(msg) + self._enable_adapter_layers(enabled=False) + + def enable_adapter_layers(self) -> None: + """ + Enable all adapters in-place + """ + # TODO: deprecate in favor of enable_adapters + self._enable_adapter_layers(enabled=True) + + def delete_adapter(self, adapter_name: str) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (str): Name of the adapter to be deleted. + """ + if adapter_name not in list(self.peft_config.keys()): + raise ValueError(f"Adapter {adapter_name} does not exist") + del self.peft_config[adapter_name] + + new_adapter = delete_adapter( + model=self.model, adapter_name=adapter_name, prefix=self.prefix, layer_cls=self.tuner_layer_cls + ) + self.active_adapter = new_adapter or [] + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + set_requires_grad(self.model, adapter_names=adapter_names, requires_grad=requires_grad) + + def _check_new_adapter_config(self, config: PeftConfig) -> None: + """ + A helper method to check the config of a new adapter being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + if len(self.peft_config) <= 1: + return + + # It is assumed that the config was added to self.peft_config *before* calling this check. We should thus never + # encounter the error below. Still, it is better to verify this, or else subsequent checks could be incorrect. + if not any(conf is config for conf in self.peft_config.values()): + raise ValueError( + "_check_new_peft_config was called incorrectly, this should not happen. Please open an issue and " + "report the error: https://github.com/huggingface/peft/issues" + ) + + bias_values = [getattr(conf, "bias", "none") for conf in self.peft_config.values()] + if sum(bias_value != "none" for bias_value in bias_values) > 1: + raise ValueError( + f"{self.__class__.__name__} supports only 1 adapter with bias. When using multiple adapters, " + "set bias to 'none' for all adapters." + ) + + def _cast_adapter_dtype(self, adapter_name: str, autocast_adapter_dtype: bool = True) -> None: + """ + A helper method to cast the adapter weights to the correct dtype. + + Currently, this only upcasts float16 and bfloat16 to float32. + + Args: + adapter_name (`str`): + The adapter name. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. + + """ + cast_adapter_dtype(self.model, adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + def _check_merge_allowed(self): + """Helper method to check whether the adapter can be merged. + + Raise a ValueError if it is not possible to merge the adapter with the given configuration. + """ + example_code = textwrap.dedent( + """ + ```python + from transformers import AutoModelForCausalLM + + # Load original tied model + model = AutoModelForCausalLM.from_pretrained("google/gemma-2-2b-it", tie_word_embeddings=False) + + # Set the randomly initialized lm_head to the previously tied embeddings + model.lm_head.weight.data = model.model.embed_tokens.weight.data.clone() + + # Save the untied model + untied_model_dir = "dir/for/untied/model" + model.save_pretrained(untied_model_dir) + model.config.save_pretrained(untied_model_dir) + + # Now use the original model but in untied format + model = AutoModelForCausalLM.from_pretrained(untied_model_dir) + ``` + """ + ) + tied_target_modules = self._get_tied_target_modules(self.model) + if tied_target_modules: + warnings.warn( + f"Model with `tie_word_embeddings=True` and the {tied_target_modules=} are part of the adapter. " + "This can lead to complications. " + "You can opt to merge the adapter after cloning the weights (to untie the embeddings). " + "You can untie the embeddings by loading the model with `tie_word_embeddings=False`. For example:" + + example_code + ) + + def _unload_and_optionally_merge( + self, + merge: bool = True, + progressbar: bool = False, + safe_merge: bool = False, + adapter_names: Optional[list[str]] = None, + ) -> None: + if merge: + self._check_merge_allowed() + + key_list = [key for key, _ in self.model.named_modules() if self.prefix not in key] + desc = "Unloading " + ("and merging " if merge else "") + "model" + for key in tqdm(key_list, disable=not progressbar, desc=desc): + try: + parent, target, target_name = _get_submodules(self.model, key) + except AttributeError: + continue + with onload_layer(target): + if hasattr(target, "unload_and_optionally_merge_module"): + # if layers have special unloading method, like MultiheadAttention, use that + unloaded_module = target.unload_and_optionally_merge_module( + merge=merge, safe_merge=safe_merge, adapter_names=adapter_names + ) + self._replace_module(parent, target_name, unloaded_module, target) + elif hasattr(target, "base_layer"): + if merge: + target.merge(safe_merge=safe_merge, adapter_names=adapter_names) + self._replace_module(parent, target_name, target.get_base_layer(), target) + + # Clean up peft_config from the model since all PEFT modules have been removed. + # This prevents spurious warnings when re-wrapping the model with get_peft_model(). + if hasattr(self.model, "peft_config"): + del self.model.peft_config + + return self.model + + def merge_and_unload( + self, progressbar: bool = False, safe_merge: bool = False, adapter_names: Optional[list[str]] = None + ) -> torch.nn.Module: + r""" + This method merges the adapter layers into the base model. + + This is needed if someone wants to use the base model as a standalone model. The returned model has the same + architecture as the original base model. + + It is important to assign the returned model to a variable and use it, this is not an in-place operation! + + Args: + progressbar (`bool`): + whether to show a progressbar indicating the unload and merge process (default: False). + safe_merge (`bool`): + whether to activate the safe merging check to check if there is any potential Nan in the adapter + weights. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import PeftModel + + >>> model_id = ... + >>> base_model = AutoModelForCausalLM.from_pretrained(model_id) + >>> peft_model_id = ... + >>> model = PeftModel.from_pretrained(base_model, peft_model_id) + >>> merged_model = model.merge_and_unload() + ``` + """ + return self._unload_and_optionally_merge( + progressbar=progressbar, safe_merge=safe_merge, adapter_names=adapter_names + ) + + def unload(self) -> torch.nn.Module: + """ + Return the base model by removing all the PEFT modules. + + It is important to assign the returned model to a variable and use it, this is not an in-place operation! + """ + return self._unload_and_optionally_merge(merge=False) + + def _check_target_module_compatiblity(self, peft_config: PeftConfig, model: nn.Module, target_name: str): + """ + Prevent applying LoRA to incompatible modules in specific architectures (e.g., Mamba). + """ + _check_lora_target_modules_mamba(peft_config, model, target_name) + + def _create_and_replace_parameter( + self, peft_config, adapter_name, target, target_name, parent, current_key + ) -> None: + raise NotImplementedError(f"{self.__class__.__name__} does not support targeting nn.Parameter.") + + def inject_adapter( + self, + model: nn.Module, + adapter_name: str, + autocast_adapter_dtype: bool = True, + low_cpu_mem_usage: bool = False, + state_dict: Optional[dict[str, torch.Tensor]] = None, + ) -> None: + r""" + Creates adapter layers and replaces the target modules with the adapter layers. This method is called under the + hood by `peft.mapping.get_peft_model` if a non-prompt tuning adapter class is passed. + + The corresponding PEFT config is directly retrieved from the `peft_config` attribute of the BaseTuner class. + + Args: + model (`nn.Module`): + The model to be tuned. + adapter_name (`str`): + The adapter name. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + state_dict (`dict`, *optional*, defaults to `None`) + If a state_dict is passed here, the adapters will be injected based on the entries of the state_dict. + This can be useful when the exact `target_modules` of the PEFT method is unknown, for instance because + the checkpoint was created without meta data. Note that the values from the state_dict are not used, + only the keys are used to determine the correct layers that should be adapted. + + """ + ################################### + # PREPARATION OF MODEL AND CONFIG # + ################################### + + peft_config = self.peft_config[adapter_name] + excluded_modules = [] + unmatched_modules = [] + targeted_modules_from_peft_config: list[str] = [] # only relevant if state_dict is passed + targets_to_tie: list[str] = [] + # Note: If possible, all checks should be performed *at the start of this method*. + # This way, we can raise early if something goes wrong, without leaving the model + # in a bad (half-initialized) state. + self._check_new_adapter_config(peft_config) + + self._check_tied_modules(model, peft_config) + + model_config = self.get_model_config(model) + + peft_config = self._prepare_adapter_config(peft_config, model_config) + + self._prepare_model(peft_config, model) + + if getattr(peft_config, "target_parameters", []) and state_dict: + raise ValueError( + "Trying to inject a PEFT adapter from a state_dict but the PEFT config uses `target_parameters`. This " + "is not supported -- when using `target_parameters`, please inject the adapter without the state_dict." + ) + + named_modules = list(model.named_modules()) + key_list = [key for key, _ in named_modules] + + uses_dummy_target_modules = getattr(peft_config, "target_modules", None) == DUMMY_TARGET_MODULES + if uses_dummy_target_modules: + # dummy adapter, we allow not matching any module + named_modules = [] + key_list = [] + + # update peft_config.target_modules if required + peft_config = _maybe_include_all_linear_layers(peft_config, model) + + # This is an optimization to reduce the number of entries in the target_modules list. The reason is that in some + # circumstances, target_modules can contain hundreds of entries. Since each target module is checked against + # each module of the net (which can be thousands), this can become quite expensive when many adapters are being + # added. Often, the target_modules can be condensed in such a case, which speeds up the process. + # A context in which this can happen is when diffusers loads non-PEFT LoRAs. As there is no meta info on + # target_modules in that case, they are just inferred by listing all keys from the state_dict, which can be + # quite a lot. See: https://github.com/huggingface/diffusers/issues/9297 + # As there is a small chance for undiscovered bugs, we apply this optimization only if the list of + # target_modules is sufficiently big. + # We also exclude IA³ from this optimization. This is because IA³ has both target_modules and + # feedforward_modules, which are coupled (the latter must be a subset). It would be possible to change the logic + # to keep both in sync, but it's not quite trivial and probably not worth the effort. See #2429. + if ( + isinstance(peft_config.target_modules, (list, set)) + and (len(peft_config.target_modules) >= MIN_TARGET_MODULES_FOR_OPTIMIZATION) + and (peft_config.peft_type != PeftType.IA3) + ): + suffixes = tuple("." + suffix for suffix in peft_config.target_modules) + names_no_target = [ + name for name in key_list if (name not in peft_config.target_modules) and not name.endswith(suffixes) + ] + new_target_modules = _find_minimal_target_modules(peft_config.target_modules, names_no_target) + if len(new_target_modules) < len(peft_config.target_modules): + peft_config.target_modules = new_target_modules + + ############################### + # MATCHING & CREATING MODULES # + ############################### + + existing_adapter_prefixes = [] + for key, module in named_modules: + if isinstance(module, BaseTunerLayer): + existing_adapter_prefixes.append(key + ".") + + # TODO: check if this the most robust way + module_names: set[str] = set() + if state_dict is not None: + prefix = PEFT_TYPE_TO_PREFIX_MAPPING[peft_config.peft_type] + # Find the module name from the state_dict. Also defensively remove '_orig_mod.', which might be inserted if + # the model was torch.compiled beforehand + module_names = {k.rsplit("." + prefix, 1)[0].removeprefix("_orig_mod.") for k in state_dict} + + for key, module in named_modules: + if not key: + continue + + # It is possible that we're adding an additional adapter, so if we encounter a key that clearly belongs to a + # previous adapter we can skip here since we don't want to interfere with adapter internals. + for adapter_key in existing_adapter_prefixes: + if key.startswith(adapter_key): + excluded_modules.append(key) + break + + if excluded_modules and excluded_modules[-1] == key: + continue + + if state_dict is None: + # normal mechanism: match the modules using the peft_config + result = self._check_target_module_exists(peft_config, key) + # If the module is a tied layer, then we skip injecting + # any adapter here and tie it later to the adapter of the source layer. + # In this loop we only add adapters to the source layer (eg: embed_tokens) + # Only applicable if `ensure_weight_tying = True` for LoraConfig + if self._check_tied_module_exists(peft_config, key): + targets_to_tie.append(key) + continue + if isinstance(result, _ExcludedModule): + excluded_modules.append(key) + elif not result: + unmatched_modules.append(key) + else: + self.targeted_module_names.append(key) + parent, target, target_name = _get_submodules(model, key) + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace( + peft_config, adapter_name, target, target_name, parent, current_key=key + ) + else: + # defensively remove _orig_mod prefix in case the model is compiled + key = key.removeprefix("_orig_mod.") + # use the state_dict to match modules instead + if key not in module_names: + unmatched_modules.append(key) + else: + # If the module is a tied layer, then we skip injecting + # any adapter here and tie it later to the adapter of the source layer. + # In this loop we only add adapters to the source layer (eg: embed_tokens) + # Only applicable if `ensure_weight_tying = True` for LoraConfig + if self._check_tied_module_exists(peft_config, key): + targets_to_tie.append(key) + continue + self.targeted_module_names.append(key) + parent, target, target_name = _get_submodules(model, key) + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace( + peft_config, adapter_name, target, target_name, parent, current_key=key + ) + + # still record what would have been matched via the config so that the two results can be compared + if self._check_target_module_exists(peft_config, key): + targeted_modules_from_peft_config.append(key) + + if getattr(peft_config, "target_parameters", []): + # Note: We don't need to check for no state_dict being passed, since we already checked this earlier. + self._inject_parameters( + peft_config=peft_config, model=model, adapter_name=adapter_name, low_cpu_mem_usage=low_cpu_mem_usage + ) + + # Here we inject tied adapters for all the layers which were tied + # Only applicable if `ensure_weight_tying = True` for LoraConfig + for key in targets_to_tie: + self.targeted_module_names.append(key) + parent, target, target_name = _get_submodules(model, key) + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace(peft_config, adapter_name, target, target_name, parent, current_key=key) + + #################### + # CHECK FOR ERRORS # + #################### + + if state_dict is not None: + # in case that the state_dict was used as source of truth and it resulted in different outcomes than what + # would have been matched with the PEFT config, warn the user about that. + targeted_set_from_peft_config = set(targeted_modules_from_peft_config) + targeted_set_from_state_dict = set(self.targeted_module_names) + diff_peft_config = targeted_set_from_peft_config - targeted_set_from_state_dict + diff_state_dict = targeted_set_from_state_dict - targeted_set_from_peft_config + warning_msg = "" + if diff_peft_config or diff_state_dict: + warning_msg = ( + "While injecting the PEFT adapters, an inconsistency was discovered between the PEFT config and " + "the provided state_dict. This is not necessarily an issue and can be ignored if this was the " + "intent. " + ) + if diff_peft_config: + warning_msg += ( + f"The PEFT config contained these additional target modules: {sorted(diff_peft_config)}. " + ) + if diff_state_dict: + warning_msg += f"The state_dict contained these additional target modules: {sorted(diff_state_dict)}. " + if warning_msg: + warnings.warn(warning_msg, RuntimeWarning) + + if not self.targeted_module_names and not self.targeted_parameter_names and not uses_dummy_target_modules: + if excluded_modules and not unmatched_modules: + # All targeted modules were excluded + raise ValueError( + "All modules were excluded. This is likely unintended. " + "Check your `target_modules`, `exclude_modules` and `modules_to_save` configuration." + ) + elif not excluded_modules and unmatched_modules and not peft_config.target_modules: + raise ValueError( + "No `target_modules` passed but also no `target_parameters` found. Please check the values for " + "these arguments." + ) + elif not excluded_modules and unmatched_modules: + # None of the targeted modules matched + error_msg = ( + f"Target modules {peft_config.target_modules} not found in the base model. " + f"Please check the target modules and try again." + ) + if getattr(peft_config, "layers_to_transform", None) is not None: + error_msg += f" Note: You specified 'layers_to_transform': {peft_config.layers_to_transform}." + if getattr(peft_config, "layers_pattern", None) is not None: + error_msg += f" You also specified 'layers_pattern': {peft_config.layers_pattern}." + raise ValueError(error_msg) + else: + # Some modules did not match and some matched but were excluded + error_msg = ( + "No modules were targeted for adaptation. " + "This might be caused by a combination of mismatched target modules and excluded modules. " + "Please check your `target_modules` and `exclude_modules` configuration. You may also have " + "only targeted modules that are marked to be saved (`modules_to_save`)." + ) + if getattr(peft_config, "layers_to_transform", None) is not None: + error_msg += f" Note: You specified 'layers_to_transform': {peft_config.layers_to_transform}." + if getattr(peft_config, "layers_pattern", None) is not None: + error_msg += f" You also specified 'layers_pattern': {peft_config.layers_pattern}." + raise ValueError(error_msg) + + elif hasattr(peft_config, "exclude_modules") and peft_config.exclude_modules and not excluded_modules: + # exclude_modules was passed but was not used + warnings.warn( + f"You have passed exclude_modules={peft_config.exclude_modules} but no modules were excluded. " + "Please check that exclude_modules was set correctly." + ) + + elif not uses_dummy_target_modules: + # If we landed here, it means that at least one module or parameter was adapted, so let's not raise an + # error. However, let's warn the user if it seems like + # - they wanted to match a module but there was no match + # - they wanted to match a parameter but there was no match + if peft_config.target_modules and not self.targeted_module_names: + warnings.warn( + f"target_modules={peft_config.target_modules} were set but no module was matched.", RuntimeWarning + ) + elif getattr(peft_config, "target_parameters", []) and not self.targeted_parameter_names: + warnings.warn( + f"target_parameters={peft_config.target_parameters} were set but no parameter was matched.", + RuntimeWarning, + ) + + ################ + # HOUSEKEEPING # + ################ + + # It's important to set the adapter here (again), because otherwise it can happen that if a 2nd adapter is + # added, and it targets different layer(s) than the first adapter (which is active), then those different + # layers will be activated, which we don't want. + self.set_adapter(self.active_adapters, inference_mode=peft_config.inference_mode) + self._mark_only_adapters_as_trainable(model) + + if self.peft_config[adapter_name].inference_mode: + for n, p in model.named_parameters(): + if adapter_name in n: + p.requires_grad = False + + set_additional_trainable_modules( + model=model, + peft_config=peft_config, + model_config=BaseTuner.get_model_config(self), + adapter_name=adapter_name, + activate_adapter=adapter_name in self.active_adapters, + ) + + def _inject_parameters( + self, peft_config: PeftConfig, model: nn.Module, adapter_name: str, low_cpu_mem_usage: bool + ) -> None: + """Inject layers based on peft_config.target_modules""" + + def strip_base_layer_from_name(module_name): + # It is possible that the layer is already a PEFT layer and needs updating with a new adapter. In this case, + # the name of parameter would be something like `model.layers.0.experts.base_layer.weight`, i.e. there is a + # "base_layer" inserted in the name. We need to remove that, otherwise we won't be able to match correctly + # (in this case, "experts.weight" would not match). + name = ".base_layer" + while name in module_name: + prefix, _, suffix = module_name.rpartition(name) + module_name = prefix + suffix + return module_name + + def create_and_replace_param(module_name, key, param_name): + # helper function to avoid duplication + parent, target, target_name = _get_submodules(model, module_name) + unwrapped_module_name = strip_base_layer_from_name(module_name) + unwrapped_module = model.get_submodule(unwrapped_module_name) + # use the class name for checking to avoid circular import + if isinstance(unwrapped_module, BaseTunerLayer) and unwrapped_module.__class__.__name__ != "ParamWrapper": + raise ValueError( + f"Trying to wrap an `nn.Parameter` of layer '{unwrapped_module_name}' of type " + f"{type(target).__name__}, which is not a valid target. Make sure that this layer is not " + "also targeted with `target_modules`. For some models, PEFT will do this automatically, " + "try setting `target_modules=[]` to prevent it." + ) + + self._check_target_module_compatiblity(peft_config, model, target_name) + ctx = init_empty_weights if low_cpu_mem_usage else nullcontext + with ctx(): + self._create_and_replace( + peft_config, + adapter_name, + target, + target_name, + parent, + current_key=key, + parameter_name=param_name.rpartition(".")[-1], + ) + + # TODO very simple matching, might not cover all use cases + unsorted_target_names = set(peft_config.target_parameters) + # As the order of matching can influence the nesting of multiple params on the same module, ensure determinism + # by sorting. + target_names = sorted(unsorted_target_names) + for module_name, module in model.named_modules(): + if hasattr(module, "parametrizations"): + # Deal with the case that the parameter is already parametrized. The issue is that we would not be able + # to match `f"{module_name}.{param_name}"`, as the parameter is now something like + # `module.parametrization.weight`. + for key in target_names: + target_module_name, _, param_name = key.rpartition(".") + if target_module_name != module_name: + continue + if getattr(module, param_name, None) is None: + continue + create_and_replace_param(module_name, key, param_name) + self.targeted_parameter_names.append(key) + else: + # Standard case: the parameter is not already parametrized. Note, however, that the model could already + # be nested with lora.ParamWrapper, as this is how we allow targeting multiple Parameters on the same + # module. + unwrapped_module_name = strip_base_layer_from_name(module_name) + # we're interested in finding the "lowest" module that contains the parameter, hence recurse=False + for param_name, param in module.named_parameters(recurse=False): + key = f"{unwrapped_module_name}.{param_name}" + if (key in target_names) or any(key.endswith(f".{target_key}") for target_key in target_names): + # Note: We use the unwrapped_module_name to check if the key matches, but we use the module_name for + # replacement, since we want to replace the wrapped module. + create_and_replace_param(module_name, key, param_name) + self.targeted_parameter_names.append(key) + + def _replace_module(self, parent, child_name, new_module, child) -> None: + """ + Replace the sub-module of a given moduel with a new PEFT module. + + This also deals with device placement of the new module to be in line with the child module. + + Args: + parent (`nn.Module`): + The parent module on which the replacement should take place. + child_name (`str`): + The name of the child module to be replaced. + new_module (`nn.Module`): + The new PEFT module. + child (`nn.Module`): + The original child module that is being replaced. + + """ + setattr(parent, child_name, new_module) + # It's not necessary to set requires_grad here, as that is handled by + # _mark_only_adapters_as_trainable + + # child layer wraps the original module, unpack it + if hasattr(child, "base_layer"): + child = child.base_layer + + if not hasattr(new_module, "base_layer"): + new_module.weight = child.weight + if hasattr(child, "bias"): + new_module.bias = child.bias + + if getattr(child, "state", None) is not None: + if hasattr(new_module, "base_layer"): + new_module.base_layer.state = child.state + else: + new_module.state = child.state + new_module.to(child.weight.device) + + meta = torch.device("meta") + # dispatch to correct device + for name, module in new_module.named_modules(): + if self.prefix in name: + if hasattr(child, "qweight"): + weight = child.qweight + elif hasattr(child, "W_q"): + weight = child.W_q + elif hasattr(child, "weight"): + weight = child.weight + elif getattr(child, "in_proj_weight", None) is not None: # MHA + weight = child.in_proj_weight + else: + weight = next(child.parameters()) + + if not any(p.device == meta for p in module.parameters()): + module.to(weight.device) + + def merge_adapter(self, adapter_names: Optional[list[str]] = None, safe_merge: bool = False) -> None: + """ + This method merges the adapter layers into the base model. + + Merging adapters can lead to a speed up of the forward pass. A copy of the adapter weights is still kept in + memory, which is required to unmerge the adapters. In order to merge the adapter weights without keeping them + in memory, please call `merge_and_unload`. + + Args: + adapter_names (`list[str]`, *optional*): + The list of adapter names that should be merged. If `None`, all active adapters will be merged. + Defaults to `None`. + safe_merge (`bool`, *optional*): + If `True`, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + """ + # Note: The order of arguments here is: + # adapter_names, safe_merge + # For layer.merge, the order is: + # safe_merge, adapter_names + # This is not so nice but this method here started with only adapter_names, thus putting safe_merge first would + # be a backwards incompatible change. + self._check_merge_allowed() + for module in self.model.modules(): + if isinstance(module, BaseTunerLayer): + with onload_layer(module): + module.merge(adapter_names=adapter_names, safe_merge=safe_merge) + + def unmerge_adapter(self): + """ + This method unmerges all merged adapter layers from the base model. + """ + for module in self.model.modules(): + if isinstance(module, BaseTunerLayer): + with onload_layer(module): + module.unmerge() + + def set_adapter(self, adapter_name: str | list[str], inference_mode: bool = False) -> None: + """Set the active adapter(s). + + Args: + adapter_name (str, list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + set_adapter( + self.model, adapter_name=adapter_name, inference_mode=inference_mode, layer_cls=self.tuner_layer_cls + ) + self.active_adapter = adapter_name + + @staticmethod + def get_model_config(model: nn.Module) -> dict: + """ + This method gets the config from a model in dictionary form. If model has not attribute config, then this + method returns a default config. + + Args: + model (`nn.Module`): + Model to get the config from. + default (`dict|None`, *optional*):: + What to return if model does not have a config attribute. + """ + model_config = getattr(model, "config", DUMMY_MODEL_CONFIG) + if hasattr(model_config, "to_dict"): + model_config = model_config.to_dict() + elif dataclasses.is_dataclass(model_config): + model_config = dataclasses.asdict(model_config) + return model_config + + def _get_tied_target_modules(self, model: nn.Module) -> list[str]: + tied_target_modules = [] + model_config = self.get_model_config(model) + if model_config.get("tie_word_embeddings"): + for target_module in self.targeted_module_names: + # This potentially yields false positives since we're just looking at the layer names. So if we use a + # model that uses weight-tying of lm_head and embed_tokens, a third, unrelated, layer which is + # unfortunately named so that it is in EMBEDDING_LAYER_NAMES will be falsely reported here as well. + if target_module.split(".")[-1] in EMBEDDING_LAYER_NAMES: + tied_target_modules.append(target_module) + return tied_target_modules + + def _get_module_names_tied_with_embedding(self) -> list[str]: + return _get_module_names_tied_with_embedding(self) + + def _add_modules_to_save_to_tie(self, peft_config, tied_weight_keys): + """ + This method adds modules to tie to `peft_config` so that those modules can be tied downstream. By default this + method raises a warning, and each tuner class extending `BaseTuner` can choose to implement this. + + Check `peft.tuners.lora.LoraModel._add_modules_to_save_to_tie` for an example. + """ + warnings.warn(warn_msg_weight_tying) + + def _add_targets_to_tie(self, peft_config, tied_weight_keys): + """ + This method adds targets to tie to `peft_config` so that those modules can be tied downstream. By default this + method raises a warning, and each tuner class extending `BaseTuner` can choose to implement this. + + Check `peft.tuners.lora.LoraModel._add_targets_to_tie` for an example. + """ + warnings.warn(warn_msg_weight_tying) + + def _check_tied_modules(self, model: nn.Module, peft_config): + """ + Checks if any of the tied layers are targetted via `modules_to_save` or `target_modules`. Updates the + `peft_config` in place with any layers/adapters that needs to be tied + """ + modules_to_save = set(getattr(peft_config, "modules_to_save", []) or []) + # `EMBEDDING_LAYER_NAMES` contains only the stripped name of the module + # eg: To get a match for model.embed_tokens, we need to extract `embed_tokens` + is_embedding_to_save = any(m.split(".")[-1] in EMBEDDING_LAYER_NAMES for m in modules_to_save) + + raw_target_modules = getattr(peft_config, "target_modules", None) + if isinstance(raw_target_modules, str): + is_embedding_in_target = any( + match_target_against_key(raw_target_modules, m) for m in EMBEDDING_LAYER_NAMES + ) + else: + target_modules = set(raw_target_modules or []) + # `EMBEDDING_LAYER_NAMES` contains only the stripped name of the module + # eg: To get a match for model.embed_tokens, we need to extract `embed_tokens` + is_embedding_in_target = any(m.split(".")[-1] in EMBEDDING_LAYER_NAMES for m in target_modules) + + tied_weight_keys = self._get_module_names_tied_with_embedding() + + if getattr(peft_config, "ensure_weight_tying", False): + if tied_weight_keys: + if is_embedding_to_save: + self._add_modules_to_save_to_tie(peft_config, tied_weight_keys) + elif is_embedding_in_target: + self._add_targets_to_tie(peft_config, tied_weight_keys) + else: + warnings.warn( + "You have requested `ensure_weight_tying`, but no tied modules are added in either " + "`modules_to_save` or `target_modules`" + ) + else: + warnings.warn("You have requested `ensure_weight_tying`, but no tied modules were found in the model") + + elif (is_embedding_to_save or is_embedding_in_target) and tied_weight_keys: + if hasattr(peft_config, "ensure_weight_tying"): + msg = ( + "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, " + "but `ensure_weight_tying` is not set to True. " + "This can lead to complications, for example when merging the adapter " + "or converting your model to formats other than safetensors. " + "Check the discussion here: https://github.com/huggingface/peft/issues/2777" + ) + warnings.warn(msg) + else: + msg = ( + "Model has `tie_word_embeddings=True` and a tied layer is part of the adapter, " + "but no implementation exists to tie the adapters. " + "This can lead to complications, for example when merging the adapter " + "or converting your model to formats other than safetensors. " + "Check the discussion here: https://github.com/huggingface/peft/issues/2777" + ) + warnings.warn(msg) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + """ + Whether it is possible for the adapter of this model to be converted to LoRA. + + Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight. + """ + return all( + module.supports_lora_conversion() for module in self.modules() if isinstance(module, BaseTunerLayer) + ) + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.model, name) + + +class BaseTunerLayer(ABC): + r""" + A tuner layer mixin that provides the common methods and attributes for all tuners. + + Args: + is_pluggable (`bool`, *optional*): + Whether the adapter layer can be plugged to any pytorch module + active_adapters (Union[List[`str`], `str`], *optional*): + The name of the active adapter. + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = () + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = () + + # indicates whether all adapters should be disabled + _disable_adapters: bool = False + + # the currently active adapter(s) + _active_adapter: str | list[str] = "default" + + # List all merged adapters + merged_adapters: list[str] = [] + + def get_base_layer(self) -> nn.Module: + """ + (Recursively) get the base_layer. + + This is necessary for the case that the tuner layer wraps another tuner layer. + + """ + base_layer = self + while hasattr(base_layer, "base_layer"): + base_layer = base_layer.base_layer + return base_layer + + def _get_embed_scale(self): + """ + Extract embed_scale from base layer if present and valid. + + Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling to embeddings in their forward + method. This method checks for the presence of an `embed_scale` attribute. If it exists, it is assumed to be a + scalar. Its shape is validated accordingly. + + Returns: + torch.Tensor or None: The embed_scale tensor if found and valid, None otherwise. + """ + base_layer = self.get_base_layer() + if not hasattr(base_layer, "embed_scale"): + return None + + embed_scale = base_layer.embed_scale + + # Convert scalar values to tensors + if isinstance(embed_scale, (int, float)): + return torch.tensor(embed_scale, device=base_layer.weight.device, dtype=base_layer.weight.dtype) + + # Validate tensor shape - must be scalar (0-d) or 1-element tensor for proper broadcasting + if isinstance(embed_scale, torch.Tensor): + if embed_scale.numel() == 1: + return embed_scale + else: + # Log warning but don't fail - this maintains backward compatibility + warnings.warn( + f"Found embed_scale attribute with shape {embed_scale.shape}, expected scalar. " + "Embedding scaling will not be applied. If this is unexpected, please open an issue at " + "https://github.com/huggingface/peft/issues", + PeftWarning, + ) + return None + + return None + + @property + def weight(self) -> torch.Tensor: + # This is required for some transformers code, e.g. for T5, weight is accessed as: + # self.wo.weight + # where "wo" is the adapter layer. + # https://github.com/huggingface/transformers/blob/78f6ed6c70b29c1560780e3869a7ad4c6b3d2710/src/transformers + # /models/t5/modeling_t5.py#L292 + base_layer = self.get_base_layer() + if hasattr(base_layer, "qweight"): + # QuantLinear + weight = base_layer.qweight + else: + # Other layers + weight = base_layer.weight + return weight + + @property + def bias(self) -> torch.Tensor: + base_layer = self.get_base_layer() + return base_layer.bias + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + raise NotImplementedError + + def unmerge(self) -> None: + raise NotImplementedError + + @property + def merged(self) -> bool: + return bool(self.merged_adapters) + + @property + def disable_adapters(self) -> bool: + # use a property to ensure that disable_adapters is not set directly, instead use the enable_adapters method + return self._disable_adapters + + @property + def active_adapter(self) -> str | list[str]: + # use a property to ensure that active_adapter is not set directly, instead use the set_adapter method + return self._active_adapter + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + adapters = set() + for layer_name in self.adapter_layer_names: + module = getattr(self, layer_name) + if not isinstance(module, (nn.ModuleDict, nn.ParameterDict)): + continue + adapters.update(set(module.keys())) + return adapters + + @property + def active_adapters(self): + if isinstance(self.active_adapter, str): + return [self.active_adapter] + # is already a list of str + return self.active_adapter + + def enable_adapters(self, enabled: bool) -> None: + """Toggle the enabling and disabling of adapters + + Takes care of setting the requires_grad flag for the adapter weights. + + Args: + enabled (bool): True to enable adapters, False to disable adapters + """ + if enabled: + self.set_adapter(self.active_adapters) + self._disable_adapters = False + else: + # disable grads on all adapter layers + for layer_name in self.adapter_layer_names: + module_dict = getattr(self, layer_name) + for layer in module_dict.values(): + _set_layer_requires_grad(layer, False) + self._disable_adapters = True + + def set_adapter(self, adapter_names: str | list[str], inference_mode: bool = False) -> None: + """Set the active adapter(s). + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_name (`str` or `list[str]`): + The name(s) of the adapter(s) to set as active. + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + adapter_names = [adapter_names] + + # Deactivate grads on the inactive adapter and activate grads on the active adapter (if not in inference mode) + for layer_name in self.adapter_layer_names: + module_dict = getattr(self, layer_name) + for key, layer in module_dict.items(): + should_require_grad = (key in adapter_names) and (not inference_mode) + _set_layer_requires_grad(layer, should_require_grad) + + self._active_adapter = adapter_names + + def _all_available_adapter_names(self) -> list[str]: + """Return a sorted list of all available adapter names""" + adapter_names = set() + for name in self.adapter_layer_names + self.other_param_names: + # we check each possible attribute and if it's a dict or ModuleDict, we assume that the keys are the adapter + # names + attr = getattr(self, name) + if hasattr(attr, "keys"): + adapter_names.update(attr.keys()) + return sorted(adapter_names) + + def delete_adapter(self, adapter_name: str) -> None: + """ + Delete an adapter from the layer + + This should be called on all adapter layers, or else we will get an inconsistent state. + + This method will also set a new active adapter if the deleted adapter was an active adapter. It is important + that the new adapter is chosen in a deterministic way, so that the same adapter is chosen on all layers. + + Args: + adapter_name (`str`): The name of the adapter to delete + + """ + for attr in self.adapter_layer_names + self.other_param_names: + if adapter_name in getattr(self, attr): + del getattr(self, attr)[adapter_name] + + if adapter_name in self.active_adapters: + # choose a new active adapter + active_adapters = self.active_adapters[:] + active_adapters.remove(adapter_name) + if active_adapters: + self.set_adapter(active_adapters) + else: + # no active adapters left, set a new default adapter + # here we get the list of all adapters existing adapter names and choose the first one + remaining_adapters = self._all_available_adapter_names() + if not remaining_adapters: + self.set_adapter([]) + else: + new_active_adapter = remaining_adapters[0] + warnings.warn( + f"Adapter {adapter_name} was active which is now deleted. Setting active adapter to " + f"{new_active_adapter}." + ) + self.set_adapter(remaining_adapters[0]) + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + if isinstance(adapter_names, str): + adapter_names_set = {adapter_names} + else: + adapter_names_set = set(adapter_names) + + for layer_name in self.adapter_layer_names: + module_dict = getattr(self, layer_name) + for key, layer in module_dict.items(): + if key in adapter_names_set: + _set_layer_requires_grad(layer, requires_grad) + + def _get_base_layer_device_and_dtype(self, base_layer): + """ + Helper function to determine the device and dtype of the base layer. If not possible to determine, return None. + """ + device, dtype = None, None + + # check weight and qweight (for GPTQ) + for weight_name in ("weight", "qweight"): + weight = getattr(base_layer, weight_name, None) + if weight is not None: + device = weight.device + dtype = weight.dtype + break + + if hasattr(base_layer, "compute_dtype"): # bnb Linear4bitLt + dtype = base_layer.compute_dtype + + return device, dtype + + def _move_adapter_to_device_of_base_layer(self, adapter_name: str, device: Optional[torch.device] = None) -> None: + """ + Move the adapter of the given name to the device, and possibly dtype, of the base layer. + """ + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.MultiheadAttention): + base_layer = base_layer.out_proj + base_layer_device, base_layer_dtype = self._get_base_layer_device_and_dtype(base_layer) + + target_device = device if device is not None else base_layer_device + if target_device is None: + # could not determine device + return + + target_dtype = None + if base_layer_dtype is not None: + # don't cast to int dtype + if base_layer_dtype.is_floating_point or base_layer_dtype.is_complex: + target_dtype = base_layer_dtype + + meta = torch.device("meta") + + # loop through all potential adapter layers and move them to the device of the base layer; be careful to only + # move this specific adapter to the device, as the other adapters could be on different devices + # see #1639 + for adapter_layer_name in self.adapter_layer_names + self.other_param_names: + adapter_layer = getattr(self, adapter_layer_name, None) + if not isinstance(adapter_layer, (nn.ModuleDict, nn.ParameterDict, BufferDict)): + continue + if adapter_name not in adapter_layer: + continue + if any(p.device == meta for p in adapter_layer.parameters()): + continue + + if target_dtype is not None: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(target_device, dtype=target_dtype) + else: + adapter_layer[adapter_name] = adapter_layer[adapter_name].to(target_device) + + @overload + def _cast_input_dtype(self, x: None, dtype: torch.dtype) -> None: ... + + @overload + def _cast_input_dtype(self, x: torch.Tensor, dtype: torch.dtype) -> torch.Tensor: ... + + def _cast_input_dtype(self, x, dtype: torch.dtype): + """ + Whether to cast the dtype of the input of the forward method. + + Usually, we want to enable this to align the input dtype with the dtype of the weight, but by setting + layer.cast_input_dtype=False, this can be disabled if necessary. + + Enabling or disabling can be managed via the peft.helpers.disable_lora_input_dtype_casting context manager. + """ + if x is None: # useful e.g. if x is the bias, which can be None + return None + + cast_input_dtype_enabled = getattr(self, "cast_input_dtype_enabled", True) + if (not cast_input_dtype_enabled) or (x.dtype == dtype): + return x + return x.to(dtype=dtype) + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + """ + Whether it is possible for this layer type to be converted to LoRA. + + Normally, this works if the PEFT method is additive, i.e. W' = W_base + delta_weight. + """ + return False + + +def _find_minimal_target_modules( + target_modules: list[str] | set[str], other_module_names: list[str] | set[str] +) -> set[str]: + """Find the minimal set of target modules that is sufficient to separate them from the other modules. + + Sometimes, a very large list of target_modules could be passed, which can slow down loading of adapters (e.g. when + loaded from diffusers). It may be possible to condense this list from hundreds of items to just a handful of + suffixes that are sufficient to distinguish the target modules from the other modules. + + Example: + ```py + >>> from peft.tuners.tuners_utils import _find_minimal_target_modules + + >>> target_modules = [f"model.decoder.layers.{i}.self_attn.q_proj" for i in range(100)] + >>> target_modules += [f"model.decoder.layers.{i}.self_attn.v_proj" for i in range(100)] + >>> other_module_names = [f"model.encoder.layers.{i}.self_attn.k_proj" for i in range(100)] + >>> _find_minimal_target_modules(target_modules, other_module_names) + {"q_proj", "v_proj"} + ``` + + Args: + target_modules (`list[str]` | `set[str]`): + The list of target modules. + other_module_names (`list[str]` | `set[str]`): + The list of other module names. They must not overlap with the target modules. + + Returns: + `set[str]`: + The minimal set of target modules that is sufficient to separate them from the other modules. + + Raises: + ValueError: + If `target_modules` is not a list or set of strings or if it contains an empty string. Also raises an error + if `target_modules` and `other_module_names` contain common elements. + """ + if isinstance(target_modules, str) or not target_modules: + raise ValueError("target_modules should be a list or set of strings.") + + target_modules = set(target_modules) + if "" in target_modules: + raise ValueError("target_modules should not contain an empty string.") + + other_module_names = set(other_module_names) + if not target_modules.isdisjoint(other_module_names): + msg = ( + "target_modules and other_module_names contain common elements, this should not happen, please " + "open a GitHub issue at https://github.com/huggingface/peft/issues with the code to reproduce this issue" + ) + raise ValueError(msg) + + # it is assumed that module name parts are separated by a "." + def generate_suffixes(s): + parts = s.split(".") + return [".".join(parts[i:]) for i in range(len(parts))][::-1] + + # Create a reverse lookup for other_module_names to quickly check suffix matches + other_module_suffixes = {suffix for item in other_module_names for suffix in generate_suffixes(item)} + + # Find all potential suffixes from target_modules + target_modules_suffix_map = {item: generate_suffixes(item) for item in target_modules} + + # Initialize a set for required suffixes + required_suffixes = set() + + # We sort the target_modules_suffix_map simply to get deterministic behavior, since sets have no order. In theory + # the order should not matter but in case there is a bug, it's better for the bug to be deterministic. + for item, suffixes in sorted(target_modules_suffix_map.items(), key=lambda tup: tup[1]): + # Go through target_modules items, shortest suffixes first + for suffix in suffixes: + # If the suffix is already in required_suffixes or matches other_module_names, skip it + if suffix in required_suffixes or suffix in other_module_suffixes: + continue + # Check if adding this suffix covers the item + if not any(item.endswith("." + req_suffix) for req_suffix in required_suffixes): + required_suffixes.add(suffix) + break + + if not required_suffixes: + return set(target_modules) + return required_suffixes + + +class _ExcludedModule: + """ + A private helper method used to represent excluded modules in the check_target_module_exists function. + """ + + def __bool__(self): + return False + + +def check_target_module_exists(config, key: str) -> bool | re.Match[str] | None: + """A helper method to check if the passed module's key name matches any of the target modules in the adapter_config. + + Args: + config (`PeftConfig`): + A config to match target modules from. + key (`str`): + A key to search any matches in config + + Returns: + `bool` | `re.Match[str]` | `None`: + True or re.Match object if key matches any target modules from config, False or None if no match found. + """ + if hasattr(config, "exclude_modules") and config.exclude_modules: + if isinstance(config.exclude_modules, str): + if re.fullmatch(config.exclude_modules, key): + return _ExcludedModule() + elif key in config.exclude_modules: + return _ExcludedModule() + elif any(key.endswith(f".{exclude_key}") for exclude_key in config.exclude_modules): + return _ExcludedModule() + + # Adapters should never match on modules to save modules as it is a guarantee for conflicts of behavior + # between `ModulesToSaveWrapper` internals and the potential adapter. + modules_to_save = getattr(config, "modules_to_save", None) + if modules_to_save: + if any(re.match(rf"(^|.*\.){m}($|\..*)", key) for m in modules_to_save): + return _ExcludedModule() + + if (config.target_modules is None) and (config.target_parameters is not None): + # this is allowed if config.target_parameters are specified + return False + + if isinstance(config.target_modules, str): + target_module_found = match_target_against_key(config.target_modules, key) + elif key in config.target_modules: + # this module is specified directly in target_modules + target_module_found = True + else: + target_module_found = any(key.endswith(f".{target_key}") for target_key in config.target_modules) + + layer_indexes = getattr(config, "layers_to_transform", None) + layers_pattern = getattr(config, "layers_pattern", None) + + is_using_layer_indexes = layer_indexes is not None and ( + len(layer_indexes) != 0 if isinstance(layer_indexes, list) else True + ) + if is_using_layer_indexes and target_module_found: + layer_index = None + # TODO: It's still unclear how empty layers_pattern (None, [], or "") should behave + # For now, empty layers_pattern means any layer pattern is ok + if layers_pattern is None or len(layers_pattern) == 0: + layer_index = re.match(r".*\.[^.]*\.(\d+)\.", key) + else: + layers_pattern = [layers_pattern] if isinstance(layers_pattern, str) else layers_pattern + for pattern in layers_pattern: + layer_index = re.match(rf".*\.{pattern}\.(\d+)\.", key) + if layer_index is not None: + break + + if layer_index is None: + target_module_found = False + else: + layer_index = int(layer_index.group(1)) + if isinstance(layer_indexes, int): + target_module_found = layer_index == layer_indexes + else: + target_module_found = layer_index in layer_indexes + + return target_module_found + + +def inspect_matched_modules(tuner: BaseTuner, adapter_name: str = "default") -> dict: + """ + A helper function to inspect the set of matched and unmatched modules for a PEFT model and the given adapter. + """ + config = tuner.peft_config[adapter_name] + key_list = [key for key, _ in tuner.model.named_modules()] + module_dict = {"matched": [], "unmatched": []} + for key in key_list: + if tuner._check_target_module_exists(config, key): + module_dict["matched"].append(key) + else: + module_dict["unmatched"].append(key) + return module_dict + + +def _maybe_include_all_linear_layers(peft_config: PeftConfig, model: nn.Module) -> PeftConfig: + """ + Helper function to update `target_modules` to all linear/Conv1D layers if provided as 'all-linear'. Adapted from + the QLoRA repository: https://github.com/artidoro/qlora/blob/main/qlora.py + """ + if not hasattr(peft_config, "target_modules"): + return peft_config + + # if `target_modules` is a string, convert to lower case and check if it matches "all-linear" + if not ( + isinstance(peft_config.target_modules, str) + and peft_config.target_modules.lower() == INCLUDE_LINEAR_LAYERS_SHORTHAND + ): + return peft_config + + linear_classes = (torch.nn.Linear, Conv1D) + linear_names = ("Linear",) + linear_module_names = set() + for name, module in model.named_modules(): + # match with all linear classes. + if isinstance(module, linear_classes): + linear_module_names.add(name) + elif isinstance(module, BaseTunerLayer) and any(n in type(module).__name__ for n in linear_names): + # If the model already has adapter layers applied, then the "linear" layer is actually an adapter layer, + # e.g. lora.Linear, and not nn.Linear. To target this layer, we don't want to check the layer type, as there + # are many possible layer types (one for each PEFT method) and the list would quickly get out of date. Thus + # we rely on the name of the layer class, which by convention is something like "Linear", "Linear4bit", + # "HqqLoraLinear", ... in PEFT. It's not pretty but should generally work. + # See 2390 + linear_module_names.add(name) + + # Try to remove linear layers that should not be targeted as best as possible. We have to rely on convention as + # there are no hard rules to detect these modules. + module_names_to_exclude = set() + if isinstance(model, PreTrainedModel): + output_emb = model.get_output_embeddings() + if output_emb is not None: + # ignore the last classification head for text generation models + last_module_name = [name for name, module in model.named_modules() if module is output_emb][0] + module_names_to_exclude.add(last_module_name) + elif peft_config.task_type == TaskType.SEQ_CLS: + # ignore classifier head for classification models (issue 2027) + # there is no fix name for the classifier head, so check the common ones + for name in SEQ_CLS_HEAD_NAMES: + cls_head = getattr(model, name, None) + if cls_head is not None: + last_module_name = [name for name, module in model.named_modules() if module is cls_head][0] + module_names_to_exclude.add(last_module_name) + break + + # we don't want nested LoRA layers, i.e. LoRA being applied to possibly existing lora_A, lora_B, etc. + # see 2390 + for prefix, module in model.named_modules(): + if isinstance(module, BaseTunerLayer): + for suffix, child in module.named_modules(): + if suffix: + module_names_to_exclude.add(f"{prefix}.{suffix}") + + linear_module_names -= module_names_to_exclude + peft_config.target_modules = linear_module_names + return peft_config + + +def check_adapters_to_merge(module: BaseTunerLayer, adapter_names: Optional[list[str]] = None) -> list[str]: + """ + Helper function to check which adapters should be merged. + + Only return those adapters that are not already merged. Give a warning if some or all of the adapters are already + merged. + + """ + if adapter_names is None: + adapter_names = module.active_adapters + if isinstance(adapter_names, str): + raise ValueError(f"adapter_names should be a list of strings, got {adapter_names!r}.") + + if module.merged: + merged_adapters = set(module.merged_adapters) + adapter_names = [name for name in adapter_names if name not in merged_adapters] + + if adapter_names: + warnings.warn( + f"Already following adapters were merged {','.join(module.merged_adapters)}. " + f"You are now additionally merging {','.join(adapter_names)}." + ) + else: + warnings.warn("All adapters are already merged, nothing to do.") + + return adapter_names + + +def clone_module(module: nn.Module, share_weights=False): + """Clone a module in a pytorch model. + + Clones a module of a model, optionally sharing all the parameters between the original and the clone. Simplifies + reusing a module when manipulating the architecture of a model. + """ + clone = copy.deepcopy(module) + + def _share_weights(src: nn.Module, dst: nn.Module): + for name, param in src.named_parameters(recurse=False): + dst.register_parameter(name, param) + + if share_weights: + for name, submodule in module.named_modules(): + _share_weights(submodule, clone.get_submodule(name)) + + return clone + + +def replicate_layers(model: nn.Module, layer_map: list[tuple[int, int]]): + """Replicate layers in a transfomer model with weight sharing. + + This function looks for a module list attribute at model[(.model)*].layers and replicates the layers in the module + list according to the layer map. For example the map `[[0, 4], [2, 5]]` will take the set of layers `[0, 1, 2, 3, + 4]` and replace them with a module list containing `[0, 1, 2, 3, 2, 3, 4]`. + """ + while hasattr(model, "model"): + model = model.model + # Some variants of the bert model nest the main model under the bert attribute. + if hasattr(model, "bert"): + model = model.bert + + model_type = None + layers: nn.ModuleList = None + if hasattr(model, "layers"): + model_type = "llama" + layers = model.layers + elif hasattr(model, "encoder") and hasattr(model.encoder, "layer"): + model_type = "bert" + layers = model.encoder.layer + elif hasattr(model, "h"): + model_type = "falcon" + layers = model.h + if not model_type or not isinstance(layers, nn.ModuleList): + raise ValueError( + "Could not locate the layers attribute in the model. " + "Expected Llama, Bert or Falcon compatible architectures." + ) + + new_layers = [] + for start, end in layer_map: + for i in range(start, end): + current_idx = len(new_layers) + new_layers.append(clone_module(layers[i], share_weights=True)) + # This is a hack needed to work around the layer_idx introduced in HF transformers. + for submodule in new_layers[-1].modules(): + if hasattr(submodule, "layer_idx"): + submodule.layer_idx = current_idx + layers = nn.ModuleList(new_layers) + if model_type == "llama": + model.layers = layers + elif model_type == "bert": + model.encoder.layer = layers + elif model_type == "falcon": + model.h = layers + else: + raise ValueError("Unexpected model type, need to handle post-processing of layers.") + if hasattr(model.config, "num_hidden_layers"): # Common to Llama, Bert, Falcon. + model.config.num_hidden_layers = len(new_layers) + + +def find_parameter_name_by_module(model: nn.Module, reference_module: nn.Module) -> str: + """ + Find layer name from the model by matching the reference module to the model named modules + + Args: + model (nn.Module): The model with named modules + reference_module (nn.Module): The reference module to find + + Returns: + str: Name of the layer + """ + for n, m in model.named_modules(): + if m is reference_module: + return n + + return "" + + +############################### +# FUNCTIONS FOR functional.py # +############################### + + +def set_adapter( + model, + adapter_name: str | list[str], + inference_mode: bool = False, + layer_cls: type[BaseTunerLayer] = BaseTunerLayer, +) -> None: + """Set the active PEFT adapter(s) of the model. + + Active adapters are those adapters that participate in the forward pass. Use this function if you want to switch + between multiple PEFT adapters. + + Args: + model (`nn.Module`): + The model on which the adapter(s) should be set. + adapter_name (str, list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + layer_cls (type, optional): + The class of the adapter layer. Defaults to `BaseTunerLayer`. + """ + _set_adapter(model, adapter_name, inference_mode=inference_mode) # auxiliary modules + for module in model.modules(): + if isinstance(module, layer_cls): + if module.merged: + warnings.warn("Adapter cannot be set when the model is merged. Unmerging the model first.") + module.unmerge() + module.set_adapter(adapter_name, inference_mode=inference_mode) + + +def _delete_auxiliary_adapter(model, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + for module in model.modules(): + if isinstance(module, AuxiliaryTrainingWrapper): + module.delete_adapter(adapter_name, new_active_adapters=new_active_adapters) + + +def delete_adapter( + model: nn.Module, adapter_name: str, prefix: str, layer_cls: type[BaseTunerLayer] = BaseTunerLayer +) -> list[str] | None: + """ + Delete an existing PEFT adapter. + + Note: This function does not delete the PEFT config on the model, if there is one. It will also not completely + purge the PEFT layers if the last PEFT adapter is deleted. For this, consider using `model.unload()` if using a + PEFT model instance, or just reloading the base model. + + Args: + model (`nn.Module`): + The model from which the adapter should be deleted. + adapter_name (str): + The name of the adapter to be deleted. + prefix (str): + The prefix of the PEFT method, e.g. "lora_" for LoRA. + layer_cls (type, optional): + The class of the adapter layer. Defaults to `BaseTunerLayer`. + + Returns: + new_adapter (list[str] | None): + The name of remaining adapter(s) after deletion, or `None` if there are no active adapters left. Use this + to set the new active adapter of the model if necessary. + """ + key_list = [key for key, _ in model.named_modules() if prefix not in key] + new_adapter = None + + for key in key_list: + _, target, _ = _get_submodules(model, key) + if isinstance(target, layer_cls): + target.delete_adapter(adapter_name) + if new_adapter is None: + new_adapter = target.active_adapters[:] + + _delete_auxiliary_adapter(model, adapter_name=adapter_name, new_active_adapters=new_adapter) + return new_adapter + + +def cast_adapter_dtype(model: nn.Module, adapter_name: str, autocast_adapter_dtype: bool = True) -> None: + """ + A helper method to cast the adapter weights to the correct dtype. + + Currently, this only upcasts float16 and bfloat16 to float32. + + Args: + adapter_name (`str`): + The adapter name. + autocast_adapter_dtype (`bool`, *optional*): + Whether to autocast the adapter dtype. Defaults to `True`. + """ + if not autocast_adapter_dtype: + return + + dtypes_to_convert_to_fp32 = {torch.float16, torch.bfloat16} + + for module in model.modules(): + if not isinstance(module, BaseTunerLayer): + continue + + for submodule in module.modules(): + if not isinstance(submodule, (nn.ModuleDict, nn.ParameterDict, BufferDict)): + continue + + if adapter_name not in submodule: + continue + + if isinstance(submodule[adapter_name], nn.Parameter): + if submodule[adapter_name].dtype in dtypes_to_convert_to_fp32: + submodule[adapter_name].data = submodule[adapter_name].data.to(torch.float32) + continue + + if isinstance(submodule[adapter_name], torch.Tensor): # e.g. from a BufferDict + if submodule[adapter_name].dtype in dtypes_to_convert_to_fp32: + submodule[adapter_name] = submodule[adapter_name].to(torch.float32) + continue + + for param in submodule[adapter_name].parameters(): + if param.dtype in dtypes_to_convert_to_fp32: + param.data = param.data.to(torch.float32) + + +def set_requires_grad(model, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + model (`nn.Module`): + The model from which the adapter should be deleted. + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + for module in model.modules(): + if isinstance(module, (BaseTunerLayer, AuxiliaryTrainingWrapper)): + module.set_requires_grad(adapter_names=adapter_names, requires_grad=requires_grad) + + +def get_device_map(model) -> dict: + if hasattr(model, "hf_device_map"): + # Multi-device case: accelerate dispatch is active and exposes hf_device_map + device_map = model.hf_device_map + else: + # Single-device case: + # Recent Transformers versions intentionally skip accelerate hooks when the + # device_map resolves to a single device (e.g. "cpu" or one GPU), so + # hf_device_map is not set. All parameters are guaranteed to be on the + # same device, which can be inferred from the first parameter. + device_map = {"": next(model.parameters()).device} + return device_map diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..8e71a08461e8b7cb2fb5513a3bf908a4a98c0747 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import VBLoRAConfig +from .layer import Linear, VBLoRALayer +from .model import VBLoRAModel + + +__all__ = ["Linear", "VBLoRAConfig", "VBLoRALayer", "VBLoRAModel"] + +register_peft_method(name="vblora", config_cls=VBLoRAConfig, model_cls=VBLoRAModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..0a969b0875d883cf8967d5601f72ee3bb3684ee3 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/config.py @@ -0,0 +1,196 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class VBLoRAConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`VBLoRAConfig`]. + + Paper: https://huggingface.co/papers/2405.15179 + + Args: + r (`int`): + The rank of incremental matrices. + num_vectors (`int`): + Number of vectors in the vector bank. Use higher values when the model size increases. + vector_length (`int`): + The length of the vectors in the vector bank. The length of the vectors should be divisible by the hidden + dimension of the model. + topk (`int`): + The K value for top-K selection. A larger value of K increases the size of the saved model. In practice, + setting K=2 typically provides the best performance and parameter efficiency. For more details, refer to + the discussion in the paper. + target_modules (`Union[List[str], str]`): + The names of the modules to apply the adapter to. If this is specified, only the modules with the specified + names will be replaced. When passing a string, a regex match will be performed. When passing a list of + strings, either an exact match will be performed or it is checked if the name of the module ends with any + of the passed strings. If this is specified as 'all-linear', then all linear/Conv1D modules are chosen, + excluding the output layer. If this is not specified, modules will be chosen according to the model + architecture. If the architecture is not known, an error will be raised -- in this case, you should specify + the target modules manually. + exclude_modules (`Optional[Union[List[str], str]]`): + The names of the modules to not apply the adapter. When passing a string, a regex match will be performed. + When passing a list of strings, either an exact match will be performed or it is checked if the name of the + module ends with any of the passed strings. + save_only_topk_weights (`bool`): + Whether to only save the topk weights. Setting `save_only_topk_weights = True` significantly reduces + storage space. However, models saved in this mode can be used for merging or inference only, not for + resuming training. + vblora_dropout (`float`): + The dropout probability for VBLoRA layers. + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + bias (`str`): + Bias type for VBLoRA. Can be 'none', 'all' or 'vblora_only'. If 'all' or 'vblora_only', the corresponding + biases will be updated during training. Be aware that this means that, even when disabling the adapters, + the model will not produce the same output as the base model would have without adaptation. + modules_to_save (`List[str]`): + List of modules apart from VBLoRA layers to be set as trainable and saved in the final checkpoint. + init_vector_bank_bound (`float`): + The vector bank is initialized with a uniform distribution between -init_vector_bank_bound and + init_vector_bank_bound. Avoid initializing the vector bank with all zeros to prevent zero gradients. A + small value, such as 0.02, is typically effective. Initializing with a large value may cause training + instability. + init_logits_std (`float`): + The logits are initialized with a normal distribution with a standard deviation of init_logits_std. Default + is 0.1. + layers_to_transform (`Union[List[int],int]`): + The layer indices to transform. If a list of ints is passed, it will apply the adapter to the layer indices + that are specified in this list. If a single integer is passed, it will apply the transformations on the + layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + """ + + r: int = field(default=4, metadata={"help": "The rank of incremental matrices."}) + num_vectors: int = field( + default=256, + metadata={"help": "Number of vectors in the vector bank. Use higher values when the model size increases."}, + ) + vector_length: int = field( + default=256, + metadata={ + "help": "The length of the vectors in the vector bank. The length of the vectors should be divisible by " + "the hidden dimension of the model." + }, + ) + topk: int = field( + default=2, + metadata={ + "help": "The K value for top-K selection. A larger value of K increases the size of the saved model. " + "In practice, setting K=2 typically provides the best performance and parameter efficiency. " + "For more details, refer to the discussion in the paper." + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with LoRA." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'." + "This can also be a wildcard 'all-linear' which matches all linear/Conv1D layers except the output layer." + "If not specified, modules will be chosen according to the model architecture, If the architecture is " + "not known, an error will be raised -- in this case, you should specify the target modules manually." + ) + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex expression of the module names to exclude from VBLoRA."}, + ) + save_only_topk_weights: bool = field( + default=False, + metadata={ + "help": ( + "Whether to only save the topk weights. Setting `save_only_topk_weights = True` significantly reduces " + "storage space. However, models saved in this mode can be used for merging or inference only, not for " + "resuming training." + ) + }, + ) + vblora_dropout: float = field(default=0.0, metadata={"help": "VBLoRA dropout"}) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + bias: str = field(default="none", metadata={"help": "Bias type for VBLoRA. Can be 'none', 'all' or 'vblora_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from VBLoRA layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + init_vector_bank_bound: float = field( + default=0.02, + metadata={ + "help": ( + "The vector bank is initialized with a uniform distribution between -init_vector_bank_bound and" + " init_vector_bank_bound. Avoid initializing the vector bank with all zeros to prevent zero gradients." + " A small value, such as 0.02, is typically effective. Initializing with a large value may cause" + " training instability." + ), + }, + ) + init_logits_std: float = field( + default=0.1, + metadata={ + "help": ( + "The logits are initialized with a normal distribution with a standard deviation of init_logits_std. " + "Default value 0.1 typically works well." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers indexes that are specified inside this list. If a single integer is passed, PEFT will transform only the layer at this index. " + "This only works when target_modules is a list of str. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer pattern is not in the common layers pattern." + "This only works when target_modules is a list of str." + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.VBLORA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..ddcdb2cbabf34954f79560e2bd4fd965c964b6d1 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/layer.py @@ -0,0 +1,258 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + + +class VBLoRALayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("vblora_logits_A", "vblora_logits_B", "vblora_vector_bank") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.topk = {} + self.vblora_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.vblora_logits_A = nn.ParameterDict({}) + self.vblora_logits_B = nn.ParameterDict({}) + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + in_features, out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + @property + def merged(self) -> bool: + return bool(self.merged_adapters) + + def update_layer( + self, + adapter_name: str, + vblora_vector_bank, + r: int, + topk: int, + num_vectors: int, + vector_length: float, + vblora_dropout: float = 0.0, + init_logits_std: float = 0.01, + inference_mode: bool = False, + **kwargs, + ): + if r <= 0: + raise ValueError(f"`r` {r} should be a positive integer value") + if topk <= 0: + raise ValueError(f"`topk` {topk} should be a positive integer value") + + if self.in_features % vector_length != 0: + raise ValueError(f"`in_features` {self.in_features} must be divisible by `vector_length` {vector_length}") + if self.out_features % vector_length != 0: + raise ValueError( + f"`out_features` {self.out_features} must be divisible by `vector_length` {vector_length}" + ) + + self.r[adapter_name] = r + self.topk[adapter_name] = topk + if vblora_dropout > 0.0: + vblora_dropout_layer = nn.Dropout(p=vblora_dropout) + else: + vblora_dropout_layer = nn.Identity() + self.vblora_dropout.update(nn.ModuleDict({adapter_name: vblora_dropout_layer})) + self.vblora_logits_A[adapter_name] = nn.Parameter( + torch.zeros(r, self.in_features // vector_length, num_vectors), requires_grad=True + ) + self.vblora_logits_B[adapter_name] = nn.Parameter( + torch.zeros(self.out_features // vector_length, r, num_vectors), requires_grad=True + ) + self.vblora_vector_bank = vblora_vector_bank + self.reset_vblora_logits(adapter_name, init_logits_std) + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_vblora_logits(self, adapter_name, init_logits_std): + if adapter_name in self.vblora_logits_A.keys(): + with torch.no_grad(): + nn.init.normal_(self.vblora_logits_A[adapter_name], 0, init_logits_std) + nn.init.normal_(self.vblora_logits_B[adapter_name], 0, init_logits_std) + + +class Linear(nn.Linear, VBLoRALayer): + # VBLoRA implemented in a dense layer + def __init__( + self, + base_layer, + vblora_vector_bank, + adapter_name: str, + r: int, + num_vectors: int, + vector_length: int, + topk: int = 2, + vblora_dropout: float = 0.0, + init_logits_std: float = 0.01, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + is_target_conv_1d_layer: bool = False, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called + super(nn.Linear, self).__init__() + VBLoRALayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer( + adapter_name, vblora_vector_bank, r, topk, num_vectors, vector_length, vblora_dropout, init_logits_std + ) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.vblora_logits_A.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + orig_weights += self.get_delta_weight(active_adapter) + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += self.get_delta_weight(active_adapter) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.vblora_logits_A.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def _get_low_rank_matrix(self, logits: torch.tensor, vblora_vector_bank, topk) -> torch.Tensor: + top_k_logits, indices = logits.topk(topk, dim=-1) + topk_weights = F.softmax(top_k_logits, dim=-1) + return (topk_weights.unsqueeze(-1) * vblora_vector_bank[indices]).sum(-2) + + def _get_lora_matrices(self, adapter, cast_to_fp32=False) -> tuple[torch.Tensor, torch.Tensor]: + vblora_logits_A = self.vblora_logits_A[adapter] + vblora_logits_B = self.vblora_logits_B[adapter] + + # Check for infinity values when training. If found, training was likely resumed from a `save_only_topk_weights` model. + if self.training and vblora_logits_A[0, 0].isinf().any(): + raise RuntimeError( + "Found infinity values in VB-LoRA logits. Ensure training was not resumed from a `save_only_topk_weights` model." + ) + + vblora_vector_bank = self.vblora_vector_bank[adapter].to(vblora_logits_A.device) + topk = self.topk[adapter] + # In case users wants to merge the adapter weights that are in + # float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # float16 because the `@` and matmul operation in general is not supported in torch + cpu + fp16. + if cast_to_fp32: + vblora_logits_A = vblora_logits_A.float() + vblora_logits_B = vblora_logits_B.float() + vblora_vector_bank = vblora_vector_bank.float() + + # A: (rank, in_tile, vector_length) -> (rank, in_tile x vector_length) + A = self._get_low_rank_matrix(vblora_logits_A, vblora_vector_bank, topk).reshape(vblora_logits_A.shape[0], -1) + # B: (out_tile, rank, vector_length) -> (out_tile, vector_length, rank) -> (out_tile x vector_length, rank) + B = ( + self._get_low_rank_matrix(vblora_logits_B, vblora_vector_bank, topk) + .transpose(1, 2) + .reshape(-1, vblora_logits_B.shape[1]) + ) + return A, B + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + device = self.vblora_logits_A[adapter].device + dtype = self.vblora_logits_A[adapter].dtype + cast_to_fp32 = device.type == "cpu" and dtype == torch.float16 + A, B = self._get_lora_matrices(adapter, cast_to_fp32) + output_tensor = transpose(B @ A, self.fan_in_fan_out) + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.vblora_logits_A.keys(): + continue + A, B = self._get_lora_matrices(active_adapter) + x = x.to(self.vblora_vector_bank[active_adapter].dtype) + dropout = self.vblora_dropout[active_adapter] + result = result + F.linear(F.linear(dropout(x), A), B) + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "vblora." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..745ce61ffedbd58e9c87a80ee887f403dc9a1941 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vblora/model.py @@ -0,0 +1,209 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings + +import torch +import torch.nn as nn +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING + +from .config import VBLoRAConfig +from .layer import Linear, VBLoRALayer + + +class VBLoRAModel(BaseTuner): + """ + Creates VBLoRA model from a pretrained transformers model. + + The method is described in detail in https://huggingface.co/papers/2405.15179. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`VBLoRAConfig`]): The configuration of the VBLoRA model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The VBLoRA model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import VBLoRAConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = VBLoRAConfig( + ... task_type="SEQ_CLS", + ... r=4, + ... target_modules=["fc1", "fc2", "k_proj", "out_proj", "q_proj", "v_proj"], + ... num_vectors=60, + ... vector_length=256, + ... save_only_topk_weights=True, + ... ) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`VBLoRAConfig`]): The configuration of the VBLoRAConfig model. + """ + + prefix: str = "vblora_" + tuner_layer_cls = VBLoRALayer + target_module_mapping = TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING + + def _init_vblora_vector_bank(self, config: VBLoRAConfig, adapter_name: str) -> None: + vblora_vector_bank = torch.zeros(config.num_vectors, config.vector_length) + torch.nn.init.uniform_(vblora_vector_bank, -config.init_vector_bank_bound, config.init_vector_bank_bound) + self.vblora_vector_bank[adapter_name] = vblora_vector_bank + + def _pre_injection_hook(self, model: nn.Module, config: VBLoRAConfig, adapter_name: str) -> None: + self.vblora_vector_bank = nn.ParameterDict({}) + + def _create_and_replace( + self, + vblora_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "fan_in_fan_out": vblora_config.fan_in_fan_out, + "bias": bias, + } + self._init_vblora_vector_bank(vblora_config, adapter_name) + # TODO: add quantization support + + if isinstance(target, Linear): + target.update_layer( + adapter_name=adapter_name, + vblora_vector_bank=self.vblora_vector_bank, + r=vblora_config.r, + topk=vblora_config.topk, + num_vectors=vblora_config.num_vectors, + vector_length=vblora_config.vector_length, + vblora_dropout=vblora_config.vblora_dropout, + init_logits_std=vblora_config.init_logits_std, + ) + else: + new_module = self._create_new_module( + vblora_config=vblora_config, + vblora_vector_bank=self.vblora_vector_bank, + adapter_name=adapter_name, + target=target, + **kwargs, + ) + if adapter_name not in self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(vblora_config, vblora_vector_bank, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = vblora_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = vblora_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`." + ) + new_module = Linear( + base_layer=target, + vblora_vector_bank=vblora_vector_bank, + adapter_name=adapter_name, + r=vblora_config.r, + num_vectors=vblora_config.num_vectors, + vector_length=vblora_config.vector_length, + topk=vblora_config.topk, + vblora_dropout=vblora_config.vblora_dropout, + init_logits_std=vblora_config.init_logits_std, + **kwargs, + ) + + return new_module + + def get_nb_savable_parameters(self, adapter="default") -> tuple[int, int]: + r""" + Returns the number of savable VB-LoRA parameters and other savable parameters. + """ + logits_params = 0 + vector_bank_params = 0 + other_params = 0 + for name, param in self.named_parameters(): + if "vblora_logits" in name: + logits_params += param.numel() + elif "vblora_vector_bank" in name: + vector_bank_params += param.numel() + elif param.requires_grad: + other_params += param.numel() + if self.peft_config[adapter].save_only_topk_weights: + num_vectors = self.peft_config[adapter].num_vectors + factor = 1 # factor to count float32-equivalent parameters + if num_vectors < 2**8: + factor = 0.25 + elif num_vectors < 2**15: + factor = 0.5 + elif num_vectors < 2**31: + factor = 1 + else: + factor = 2 + topk_weight_params = ( + logits_params / self.peft_config[adapter].num_vectors * (self.peft_config[adapter].topk - 1) + ) + topk_indices_params = ( + logits_params / self.peft_config[adapter].num_vectors * self.peft_config[adapter].topk * factor + ) + vblora_params = int(vector_bank_params + topk_weight_params + topk_indices_params) + else: + vblora_params = vector_bank_params + logits_params + return vblora_params, other_params + + def print_savable_parameters(self) -> None: + r""" + Prints the number of savable VB-LoRA parameters and total savable parameters. + """ + vblora_params, other_params = self.get_nb_savable_parameters() + print( + f"VB-LoRA params to-be-saved (float32-equivalent): {vblora_params:,d} " + f"|| total params to-be-saved: {(vblora_params + other_params):,d}" + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..25c4a96619524bfdcd41a8f7df331533ba370782 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/__init__.py @@ -0,0 +1,40 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.utils import register_peft_method + +from .config import VeraConfig +from .layer import Linear, VeraLayer +from .model import VeraModel + + +__all__ = ["Linear", "VeraConfig", "VeraLayer", "VeraModel"] + + +register_peft_method(name="vera", config_cls=VeraConfig, model_cls=VeraModel, prefix="vera_lambda_") + + +def __getattr__(name): + if (name == "Linear8bitLt") and is_bnb_available(): + from .bnb import Linear8bitLt + + return Linear8bitLt + + if (name == "Linear4bit") and is_bnb_4bit_available(): + from .bnb import Linear4bit + + return Linear4bit + + raise AttributeError(f"module {__name__} has no attribute {name}") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/bnb.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/bnb.py new file mode 100644 index 0000000000000000000000000000000000000000..71d20e4b1163ab9cc93b7b33c2aa022ddd3eb11f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/bnb.py @@ -0,0 +1,411 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from typing import Optional + +import bitsandbytes as bnb +import torch + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import check_adapters_to_merge +from peft.utils.integrations import dequantize_bnb_weight +from peft.utils.other import transpose + +from .layer import VeraLayer + + +if is_bnb_available(): + + class Linear8bitLt(torch.nn.Module, VeraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + vera_A, + vera_B, + r: int = 0, + vera_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + d_initial: float = 0.1, + **kwargs, + ) -> None: + super().__init__() + VeraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + vera_A, + vera_B, + r, + vera_dropout=vera_dropout, + init_weights=init_weights, + d_initial=d_initial, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + if self.merged: + warnings.warn( + f"Already following adapters were merged {','.join(self.merged_adapters)}. " + f"You are now additionally merging {','.join(self.active_adapters)}." + ) + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.vera_lambda_d.keys(): + continue + + warnings.warn( + "Merge vera module to 8-bit linear may get different generations due to rounding errors." + ) + vera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + + output = dequantize_bnb_weight(weight, state) + w_data = output.to(vera_data.dtype).to(vera_data.device) + vera_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.vera_lambda_d.keys(): + continue + warnings.warn( + "Unmerge vera module to 8-bit linear may get different generations due to rounding errors." + ) + vera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + state = self.get_base_layer().state + if state.SCB is None: + state.SCB = weight.SCB + output = dequantize_bnb_weight(weight, state=state) + + w_data = output.to(vera_data.dtype).to(vera_data.device) - vera_data + + self.get_base_layer().weight = bnb.nn.Int8Params( + w_data.to("cpu"), requires_grad=False, has_fp16_weights=weight.has_fp16_weights + ).to(weight.device) + state.reset_grads() + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): The name of the adapter for which the delta weight should be computed. + + Returns: + torch.Tensor: The computed delta weight for the VeRA adapter. + + Note: + This method implements the VeRA-specific weight update. Unlike LoRA, VeRA uses shared projection + matrices (vera_A and vera_B) across all layers, along with per-layer trainable parameters (lambda_d and + lambda_b). + """ + # Retrieve shared projection matrices + vera_A = self.vera_A[adapter] + vera_B = self.vera_B[adapter] + + # Retrieve per-layer trainable parameters + device = vera_B.device + dtype = vera_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + lambda_d = self.vera_lambda_d[adapter] + lambda_b = self.vera_lambda_b[adapter] + + if cast_to_fp32: + vera_A = vera_A.float() + vera_B = vera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = vera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = vera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + # VeRA-specific computation: + # 1. Apply lambda_d to the input projection (vera_A) + # 2. Apply lambda_b to the output projection (vera_B) + # 3. Compute the outer product of the scaled projections + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + """ + Perform the forward pass using the VeRA adapter. + + Args: + x (torch.Tensor): Input tensor. + + Returns: + torch.Tensor: Output tensor after applying the VeRA adaptation. + + Note: + This method implements the VeRA-specific forward pass. It applies the shared projections (vera_A and + vera_B) along with the per-layer trainable parameters (lambda_d and lambda_b) to compute the adapter + output. + """ + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.vera_lambda_d.keys(): + continue + + lambda_d = self.vera_lambda_d[active_adapter] + lambda_b = self.vera_lambda_b[active_adapter] + + vera_A = self.vera_A[active_adapter] + vera_B = self.vera_B[active_adapter] + + dropout = self.vera_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = lambda_d.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + sliced_A = vera_A[:, : self.in_features].to(x.device) + sliced_B = vera_B[: self.out_features, :].to(x.device) + + x_temp = dropout(x.to(lambda_d.dtype)) + + adapter_output = lambda_b * torch.nn.functional.linear( + lambda_d * torch.nn.functional.linear(x_temp, sliced_A), sliced_B + ) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + result = result + adapter_output + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "vera." + rep + + +if is_bnb_4bit_available(): + + class Linear4bit(torch.nn.Module, VeraLayer): + def __init__( + self, + base_layer: torch.nn.Module, + adapter_name: str, + vera_A, + vera_B, + r: int = 0, + vera_dropout: float = 0.0, + fan_in_fan_out: bool = False, + init_weights: bool = True, + d_initial: float = 0.1, + **kwargs, + ) -> None: + super().__init__() + VeraLayer.__init__(self, base_layer) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer( + adapter_name, + vera_A, + vera_B, + r, + vera_dropout=vera_dropout, + init_weights=init_weights, + d_initial=d_initial, + ) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + if self.merged: + warnings.warn( + f"Already following adapters were merged {','.join(self.merged_adapters)}. " + f"You are now additionally merging {','.join(self.active_adapters)}." + ) + + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + return + + for active_adapter in adapter_names: + if active_adapter not in self.vera_lambda_d.keys(): + continue + + warnings.warn( + "Merge vera module to 4-bit linear may get different generations due to rounding errors." + ) + vera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + # torch.compile can introduce attributes preceded by '_', remove them + kwargs = {k: v for k, v in kwargs.items() if not k.startswith("_")} + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + vera_data + + if safe_merge and not torch.isfinite(w_data).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter not in self.vera_lambda_d.keys(): + continue + warnings.warn( + "Unmerge vera module to 4-bit linear may get different generations due to rounding errors." + ) + vera_data = self.get_delta_weight(active_adapter) + + weight = self.get_base_layer().weight + kwargs = weight.__dict__ + w_data = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) - vera_data + + self.get_base_layer().weight = bnb.nn.Params4bit(w_data.to("cpu"), requires_grad=False, **kwargs).to( + weight.device + ) + + def get_delta_weight(self, adapter) -> torch.Tensor: + vera_A = self.vera_A[adapter] + vera_B = self.vera_B[adapter] + + device = vera_B.device + dtype = vera_B.dtype + + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + lambda_d = self.vera_lambda_d[adapter] + lambda_b = self.vera_lambda_b[adapter] + + if cast_to_fp32: + vera_A = vera_A.float() + vera_B = vera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = vera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = vera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + result = result.clone() + for active_adapter in self.active_adapters: + if active_adapter not in self.vera_lambda_d.keys(): + continue + + lambda_d = self.vera_lambda_d[active_adapter] + lambda_b = self.vera_lambda_b[active_adapter] + + vera_A = self.vera_A[active_adapter] + vera_B = self.vera_B[active_adapter] + + dropout = self.vera_dropout[active_adapter] + + requires_conversion = not torch.is_autocast_enabled() + if requires_conversion: + expected_dtype = result.dtype + compute_dtype = lambda_d.dtype + if x.dtype != compute_dtype: + x = x.to(compute_dtype) + + sliced_A = vera_A[:, : self.in_features].to(x.device) + sliced_B = vera_B[: self.out_features, :].to(x.device) + + x_temp = dropout(x.to(lambda_d.dtype)) + + adapter_output = lambda_b * torch.nn.functional.linear( + lambda_d * torch.nn.functional.linear(x_temp, sliced_A), sliced_B + ) + + if requires_conversion: + adapter_output = adapter_output.to(expected_dtype) + + result = result + adapter_output + + # Ensure the output tensor has the same dtype as the input tensor + return result.to(x.dtype) + + def __repr__(self) -> str: + rep = super().__repr__() + return "vera." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/config.py new file mode 100644 index 0000000000000000000000000000000000000000..df880b7af0df6b92717e339f131474340e2ade3c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/config.py @@ -0,0 +1,162 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + + +@dataclass +class VeraConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`VeraModel`]. + + Paper: https://huggingface.co/papers/2310.11454. + + Args: + r (`int`, *optional*, defaults to `256`): + VeRA parameter dimension ("rank"). Choose higher values than LoRA ranks here, since VeRA uses far fewer + parameters than LoRA (see Table 1). + target_modules (`Union[List[str], str]`): + The names of the modules to apply Vera to. Only linear layers are supported. + projection_prng_key (`int`): + Vera PRNG init key. Used for initialising vera_A and vera_B for new models or when loading a checkpoint + that did not include these projections. Defaults to `0`. + save_projection (`bool`): + Whether to save the vera_A / vera_B projections in the state dict alongside per layer lambda_b / lambda_d + weights. This will increase the size of the checkpoint, but guarantee that we can reload the checkpoint on + all system configurations. Defaults to `True`. + vera_dropout (`float`): + The dropout probability for Vera layers. + d_initial (`float`, *optional*, defaults to `0.1`): + Initial init value for `vera_lambda_d` vector used when initializing the VeRA parameters. Small values + (<=0.1) are recommended (see Table 6c in the paper). + fan_in_fan_out (`bool`): + Set this to True if the layer to replace stores weight like (fan_in, fan_out). For example, gpt-2 uses + `Conv1D` which stores weights like (fan_in, fan_out) and hence this should be set to `True`. + bias (`str`): + Bias type for Vera. Can be 'none', 'all' or 'vera_only'. If 'all' or 'vera_only', the corresponding biases + will be updated during training. Be aware that this means that, even when disabling the adapters, the model + will not produce the same output as the base model would have without adaptation. + modules_to_save (`List[str]`): + List of modules apart from Vera layers to be set as trainable and saved in the final checkpoint. + init_weights (`bool`): + Whether to initialize the weights of the Vera layers with their default initialization. Don't change this + setting, except if you know exactly what you're doing. + layers_to_transform (`Union[List[int],int]`): + The layer indexes to transform, if this argument is specified, it will apply the Vera transformations on + the layer indexes that are specified in this list. If a single integer is passed, it will apply the Vera + transformations on the layer at this index. + layers_pattern (`Optional[Union[List[str], str]]`): + The layer pattern name, used only if `layers_to_transform` is different from `None`. This should target the + `nn.ModuleList` of the model, which is often called `'layers'` or `'h'`. + """ + + r: int = field(default=256, metadata={"help": "Vera attention dimension"}) + + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or regex expression of the module names to replace with Vera." + "For example, ['q', 'v'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Only linear layers are supported." + ) + }, + ) + projection_prng_key: int = field( + default=0, + metadata={ + "help": ( + "Vera PRNG init key. Used for initialising vera_A and vera_B for new models or when loading a " + "checkpoint that did not include these projections." + ) + }, + ) + save_projection: bool = field( + default=True, + metadata={ + "help": ( + "Whether to save the vera_A / vera_B projections in the state dict alongside per layer lambda_b / " + "lambda_d weights. This will increase the size of the checkpoint, but guarantee that we can reload " + "the checkpoint on all system configurations." + ) + }, + ) + vera_dropout: float = field(default=0.0, metadata={"help": "Vera dropout"}) + d_initial: float = field(default=0.1, metadata={"help": "Initial init value for d vector."}) + fan_in_fan_out: bool = field( + default=False, + metadata={"help": "Set this to True if the layer to replace stores weight like (fan_in, fan_out)"}, + ) + bias: str = field(default="none", metadata={"help": "Bias type for Vera. Can be 'none', 'all' or 'vera_only'"}) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules apart from Vera layers to be set as trainable and saved in the final checkpoint. For" + " example, in Sequence Classification or Token Classification tasks, the final layer" + " `classifier/score` are randomly initialized and as such need to be trainable and saved." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Whether to initialize the weights of the Vera layers with their default initialization. Don't change " + "this setting, except if you know exactly what you're doing." + ), + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "The layer indexes to transform, is this argument is specified, PEFT will transform only the layers" + " indexes that are specified inside this list. If a single integer is passed, PEFT will transform only" + " the layer at this index." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "The layer pattern name, used only if `layers_to_transform` is different to None and if the layer " + "pattern is not in the common layers pattern. This should target the `nn.ModuleList` of the " + "model, which is often called `'layers'` or `'h'`." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.VERA + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + if not self.save_projection: + warnings.warn( + "Specified to not save vera_A and vera_B within the state dictionary, instead they will be restored " + "using the PRNG key store in `config.projection_prng_key`. Consider setting `config.save_projection` " + "to `True` to guarantee restoring the checkpoint correctly on all system configurations." + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..3c61957c852aff39083dbbdfb21a18172be02bc1 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/layer.py @@ -0,0 +1,294 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Optional + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .._buffer_dict import BufferDict + + +class VeraLayer(BaseTunerLayer): + # List all names of layers that may contain adapter weights + adapter_layer_names = ("vera_lambda_b", "vera_lambda_d") + other_param_names = ("vera_A", "vera_B") + + def __init__(self, base_layer: nn.Module, **kwargs): + self.base_layer = base_layer + self.r = {} + self.vera_dropout = nn.ModuleDict({}) + + # For storing vector scale + self.vera_lambda_b = nn.ParameterDict({}) + self.vera_lambda_d = nn.ParameterDict({}) + + # Stores a reference to the vera_A/B BufferDict. + # Set to `None` otherwise to avoid computation with random weights + self.vera_A: Optional[BufferDict] = None + self.vera_B: Optional[BufferDict] = None + + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + in_features, out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + in_features, out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + + self.in_features = in_features + self.out_features = out_features + self.kwargs = kwargs + + @property + def merged(self) -> bool: + return bool(self.merged_adapters) + + def update_layer( + self, + adapter_name, + vera_A: BufferDict, + vera_B: BufferDict, + r, + vera_dropout, + init_weights, + d_initial: float = 0.1, + inference_mode: bool = False, + **kwargs, + ): + if r <= 0: + raise ValueError(f"`r` should be a positive integer value but the value passed is {r}") + self.r[adapter_name] = r + if vera_dropout > 0.0: + vera_dropout_layer = nn.Dropout(p=vera_dropout) + else: + vera_dropout_layer = nn.Identity() + + self.vera_dropout.update(nn.ModuleDict({adapter_name: vera_dropout_layer})) + # Actual trainable parameters + self.vera_lambda_b[adapter_name] = nn.Parameter(torch.ones(self.out_features), requires_grad=True) + self.vera_lambda_d[adapter_name] = nn.Parameter(torch.randn(r), requires_grad=True) + + # non trainable references to vera_A/B buffers + self.vera_A = vera_A + self.vera_B = vera_B + if adapter_name not in vera_A: + # This means that this is not the first VeRA adapter. We have to add an entry in the dict for this adapter. + if len(self.vera_A) < 1: + raise ValueError( + "The `vera_A` and `vera_B` buffers are empty. This should not happen. Please report this issue." + ) + # we can take any of the existing adapter's parameters, as they should all be identical + vera_A_param = list(self.vera_A.values())[0] + vera_B_param = list(self.vera_B.values())[0] + + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional VeRA " + "adapter was added after the first one with incompatible shapes." + ) + # check input size + if vera_A_param.shape[1] < self.in_features: + raise ValueError(error_tmpl.format("vera_A", vera_A_param.shape[1], self.in_features)) + # check output size + if vera_B_param.shape[0] < self.out_features: + raise ValueError(error_tmpl.format("vera_B", vera_B_param.shape[0], self.out_features)) + # check r + error_tmpl = ( + "{} has a size of {} but {} or greater is required; this probably happened because an additional VeRA " + "adapter with a lower rank was added after the first one; loading the adapters " + "in reverse order may solve this." + ) + if vera_A_param.shape[0] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("vera_A", vera_A_param.shape[0], self.r[adapter_name])) + if vera_B_param.shape[1] < self.r[adapter_name]: + raise ValueError(error_tmpl.format("vera_B", vera_B_param.shape[1], self.r[adapter_name])) + + self.vera_A[adapter_name] = vera_A_param + self.vera_B[adapter_name] = vera_B_param + + if init_weights: + self.reset_vera_parameters(adapter_name, d_initial=d_initial) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters, inference_mode=inference_mode) + + def reset_vera_parameters(self, adapter_name, d_initial: float = 0.1): + if adapter_name in self.vera_lambda_d.keys(): + with torch.no_grad(): + nn.init.zeros_(self.vera_lambda_d[adapter_name]).fill_(d_initial) + nn.init.zeros_(self.vera_lambda_b[adapter_name]) + + +class Linear(nn.Linear, VeraLayer): + # Vera implemented in a dense layer + def __init__( + self, + base_layer, + vera_A: BufferDict, + vera_B: BufferDict, + adapter_name: str, + r: int = 0, + vera_dropout: float = 0.0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + is_target_conv_1d_layer: bool = False, + init_weights: bool = True, + d_initial: float = 0.1, + **kwargs, + ) -> None: + # this gets the init from nn.Linear's super perspective, i.e. nn.Module.__init__, which should always be called + super(nn.Linear, self).__init__() + VeraLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + + self._active_adapter = adapter_name + self.update_layer(adapter_name, vera_A, vera_B, r, vera_dropout, init_weights, d_initial=d_initial) + self.is_target_conv_1d_layer = is_target_conv_1d_layer + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.vera_lambda_d.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + + orig_weights += self.get_delta_weight(active_adapter) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += self.get_delta_weight(active_adapter) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.vera_lambda_d.keys(): + self.get_base_layer().weight.data -= self.get_delta_weight(active_adapter) + + def get_delta_weight(self, adapter) -> torch.Tensor: + """ + Compute the delta weight for the given adapter. + + Args: + adapter (str): + The name of the adapter for which the delta weight should be computed. + """ + vera_A = self.vera_A[adapter] + vera_B = self.vera_B[adapter] + + device = vera_B.device + dtype = vera_B.dtype + + # In case users wants to merge the adapter weights that are in + # (b)float16 while being on CPU, we need to cast the weights to float32, perform the merge and then cast back to + # (b)float16 because some CPUs have slow bf16/fp16 matmuls. + cast_to_fp32 = device.type == "cpu" and (dtype == torch.float16 or dtype == torch.bfloat16) + + lambda_d = self.vera_lambda_d[adapter] + lambda_b = self.vera_lambda_b[adapter] + + if cast_to_fp32: + vera_A = vera_A.float() + vera_B = vera_B.float() + lambda_d = lambda_d.float() + lambda_b = lambda_b.float() + + sliced_A = vera_A[:, : self.in_features].to(lambda_d.device) + sliced_B = vera_B[: self.out_features, :].to(lambda_d.device) + lambda_b = lambda_b.unsqueeze(-1) + lambda_d = lambda_d.unsqueeze(-1) + output_tensor = transpose((lambda_b * sliced_B) @ (lambda_d * sliced_A), self.fan_in_fan_out) + + if cast_to_fp32: + output_tensor = output_tensor.to(dtype=dtype) + + return output_tensor + + def forward(self, x: torch.Tensor, *args, **kwargs) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.vera_lambda_d.keys(): + continue + + lambda_d = self.vera_lambda_d[active_adapter] + lambda_b = self.vera_lambda_b[active_adapter] + + vera_A = self.vera_A[active_adapter] + vera_B = self.vera_B[active_adapter] + + # As adapted layers may have different shapes and VeRA contains a single shared pair of A and B matrices, + # we initialize these matrices with the largest required size for each dimension. + # During the forward pass, required submatrices are sliced out from the shared vera_A and vera_B. + sliced_A = vera_A[:, : self.in_features].to(x.device) + sliced_B = vera_B[: self.out_features, :].to(x.device) + + dropout = self.vera_dropout[active_adapter] + x = x.to(lambda_d.dtype) + result = result + lambda_b * F.linear(lambda_d * F.linear(dropout(x), sliced_A), sliced_B) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "vera." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/model.py new file mode 100644 index 0000000000000000000000000000000000000000..f85d84e259a008bdc9dd709e810f881815450e7d --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/vera/model.py @@ -0,0 +1,294 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import math +import warnings +from typing import Union + +import torch +import torch.nn as nn +from torch.nn.init import _calculate_correct_fan +from transformers.pytorch_utils import Conv1D + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer +from peft.utils import ( + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, +) + +from .._buffer_dict import BufferDict +from ..tuners_utils import _maybe_include_all_linear_layers +from .config import VeraConfig +from .layer import Linear, VeraLayer + + +def _kaiming_init( + tensor_or_shape: Union[torch.Tensor, tuple[int, ...]], + generator: torch.Generator, +) -> torch.Tensor: + """ + Kaiming Uniform Initialisation adapted to accept a `torch.Generator` object for PRNG. + + Args: + tensor_or_shape (`Union[torch.Tensor, tuple[int, ...]]`): + Tensor to initialise, or shape of new tensor to create and then initialise. + generator: (`torch.Generator`): + Generator object that manages the state of the PRNG algorithm in use. + + Returns: + `torch.Tensor`: The initialised tensor. + """ + if isinstance(tensor_or_shape, tuple): + tensor = torch.empty(tensor_or_shape) + else: + tensor = tensor_or_shape + fan = _calculate_correct_fan(tensor, "fan_in") + gain = math.sqrt(2) + std = gain / math.sqrt(fan) + bound = math.sqrt(3.0) * std + + with torch.no_grad(): + return tensor.uniform_(-bound, bound, generator=generator) + + +class VeraModel(BaseTuner): + """ + Creates Vector-based Random Matrix Adaptation (Vera) model from a pretrained transformers model. + + Args: + model ([`~transformers.PreTrainedModel`]): The model to be adapted. + config ([`VeraConfig`]): The configuration of the Vera model. + adapter_name (`str`): The name of the adapter, defaults to `"default"`. + low_cpu_mem_usage (`bool`, `optional`, defaults to `False`): + Create empty adapter weights on meta device. Useful to speed up the loading process. + + Returns: + `torch.nn.Module`: The Vera model. + + Example: + + ```py + >>> from transformers import AutoModelForCausalLM + >>> from peft import VeraConfig, get_peft_model + + >>> base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m") + >>> config = VeraConfig(r=128) + >>> model = get_peft_model(base_model, config) + ``` + + **Attributes**: + - **model** ([`~transformers.PreTrainedModel`]) -- The model to be adapted. + - **peft_config** ([`VeraConfig`]): The configuration of the Vera model. + """ + + prefix: str = "vera_lambda_" + tuner_layer_cls = VeraLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING + + def _find_dim(self, config) -> tuple[int, int]: + """ + Finds the largest input and output dimensions across linear layers that have been wrapped with VeRA. + + This will be used for determining the size of the shared vera_A and vera_B matrices. + """ + model_config = self.get_model_config(self.model) + + peft_config = self._prepare_adapter_config(config, model_config) + peft_config = _maybe_include_all_linear_layers(peft_config, self.model) + + largest_shape = None + for key, module in self.model.named_modules(): + if not self._check_target_module_exists(peft_config, key): + continue + + if isinstance(module, nn.Linear): + module_shape = module.out_features, module.in_features + elif isinstance(module, Conv1D): + module_shape = module.weight.ds_shape if hasattr(module.weight, "ds_shape") else module.weight.shape + module_shape = module_shape[::-1] + else: + continue + + if largest_shape is None: + largest_shape = module_shape + continue + + if module_shape != largest_shape: + largest_shape = tuple(max(a, b) for a, b in zip(largest_shape, module_shape)) + + if largest_shape is None: + msg = "No layers types compatible with VeRA were found. Please check `peft_config.target_modules`." + raise ValueError(msg) + + return largest_shape + + def _init_vera_A_vera_B(self, config: VeraConfig, adapter_name: str) -> None: + linear_out_dim, linear_in_dim = self._find_dim(config) + + # use of persistent to exclude vera_A and vera_B from the state dict if we choose not to save them. + self.vera_A = BufferDict({}, persistent=config.save_projection) + self.vera_B = BufferDict({}, persistent=config.save_projection) + + # deterministic init of vera_A and vera_B if we know the key + generator = torch.Generator(device="cpu").manual_seed(config.projection_prng_key) + vera_A = _kaiming_init((config.r, linear_in_dim), generator=generator) + vera_B = _kaiming_init((linear_out_dim, config.r), generator=generator) + + self.vera_A[adapter_name] = vera_A + self.vera_B[adapter_name] = vera_B + + def _pre_injection_hook(self, model: nn.Module, config: VeraConfig, adapter_name: str) -> None: + self._init_vera_A_vera_B(config, adapter_name) + + def _check_new_adapter_config(self, config: VeraConfig) -> None: + """ + A helper method to check the config when a new adapter is being added. + + Raise a ValueError if there is something wrong with the config or if it conflicts with existing adapters. + + """ + super()._check_new_adapter_config(config) + + for existing_config in self.peft_config.values(): + if existing_config is config: + # skip the current config + continue + + if existing_config.projection_prng_key != config.projection_prng_key: + raise ValueError( + f"Vera PRNG initialisation key must be the same for all adapters. Got {config.projection_prng_key=} but " + f"previous config had {existing_config.projection_prng_key}." + ) + + save_project_unique_values = sorted({config.save_projection for config in self.peft_config.values()}) + if len(save_project_unique_values) > 1: + raise ValueError( + "VeRA projection weights must be saved for all adapters or none, but got multiple different values: " + f"{save_project_unique_values}" + ) + + def _create_and_replace( + self, + vera_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + r = vera_config.r + bias = hasattr(target, "bias") and target.bias is not None + kwargs = { + "r": r, + "vera_dropout": vera_config.vera_dropout, + "fan_in_fan_out": vera_config.fan_in_fan_out, + "init_weights": vera_config.init_weights, + "loaded_in_8bit": getattr(self.model, "is_loaded_in_8bit", False), + "loaded_in_4bit": getattr(self.model, "is_loaded_in_4bit", False), + } + kwargs["bias"] = bias + + if isinstance(target, Linear): + target.update_layer( + adapter_name, + self.vera_A, + self.vera_B, + r, + vera_config.vera_dropout, + vera_config.init_weights, + d_initial=vera_config.d_initial, + ) + else: + new_module = self._create_new_module(vera_config, self.vera_A, self.vera_B, adapter_name, target, **kwargs) + if adapter_name not in self.active_adapter: + # adding an additional adapter: it is not automatically trainable + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(vera_config, vera_A, vera_B, adapter_name, target, **kwargs): + # avoid eager bnb import + if is_bnb_available(): + import bitsandbytes as bnb + + from .bnb import Linear8bitLt + + if is_bnb_4bit_available(): + from .bnb import Linear4bit + + bias = kwargs.pop("bias", False) + loaded_in_8bit = kwargs.get("loaded_in_8bit", False) + loaded_in_4bit = kwargs.get("loaded_in_4bit", False) + + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if loaded_in_8bit and isinstance(target_base_layer, bnb.nn.Linear8bitLt): + eightbit_kwargs = kwargs.copy() + eightbit_kwargs.update( + { + "has_fp16_weights": target_base_layer.state.has_fp16_weights, + "threshold": target_base_layer.state.threshold, + "index": target_base_layer.index, + } + ) + return Linear8bitLt(target, adapter_name, vera_A, vera_B, **eightbit_kwargs) + elif loaded_in_4bit and isinstance(target_base_layer, bnb.nn.Linear4bit): + fourbit_kwargs = kwargs.copy() + fourbit_kwargs.update( + { + "compute_dtype": target_base_layer.compute_dtype, + "compress_statistics": target_base_layer.weight.compress_statistics, + "quant_type": target_base_layer.weight.quant_type, + } + ) + return Linear4bit(target, adapter_name, vera_A, vera_B, **fourbit_kwargs) + elif isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = vera_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = vera_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`, `transformers.pytorch_utils.Conv1D`." + ) + new_module = Linear( + target, + vera_A, + vera_B, + adapter_name, + bias=bias, + d_initial=vera_config.d_initial, + **kwargs, + ) + + return new_module diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..f0e6fbc7e40eeccc393c662c09c81c032760dbfe --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/__init__.py @@ -0,0 +1,24 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import WaveFTConfig +from .layer import WaveFTLayer, WaveFTLinear +from .model import WaveFTModel + + +__all__ = ["WaveFTConfig", "WaveFTLayer", "WaveFTLinear", "WaveFTModel"] + +register_peft_method(name="waveft", model_cls=WaveFTModel, config_cls=WaveFTConfig) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/config.py new file mode 100644 index 0000000000000000000000000000000000000000..f2233c94e4ec583f52cb3cd4193e93de25f8ea3f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/config.py @@ -0,0 +1,265 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from dataclasses import dataclass, field +from typing import Optional, Union + +from peft.config import PeftConfig +from peft.utils import PeftType + +from .constants import WAVELET_REDUCTIONS + + +@dataclass +class WaveFTConfig(PeftConfig): + """ + This is the configuration class to store the configuration of a [`WaveFTModel`]. It is used to define the + parameters for Wavelet-based Fine-Tuning (WaveFT), an approach that leverages the sparsity of wavelet transforms + for parameter-efficient fine-tuning of pretrained models. + + Args: + n_frequency (`int`): + Number of learnable wavelet coefficients for the Discrete Wavelet Transform (DWT). 'n_frequency' is an + integer that is greater than 0 and less than or equal to the total number of elements in the original + weight matrix (d_out * d_in). This parameter directly controls the number of trainable parameters for each + adapted layer. A higher 'n_frequency' generally leads to better performance but also increases GPU memory + usage, with a minor impact on training speed. + scaling (`float`): + The scaling factor applied to the reconstructed delta W matrix. This is a crucial hyperparameter, analogous + to `lora_alpha` in LoRA. It can be tuned during hyperparameter search. Our default value for SDXL + personalization is 25. + wavelet_family (`str`): + The wavelet family (e.g., 'db1', 'sym2', 'coif1') to use for the DWT and Inverse DWT (IDWT). Defaults to + 'db1' (Haar wavelet). Different wavelet families have varying filter lengths which affect the training time + substantially + use_idwt (`bool`): + Set to False for efficient adaptation. Whether to use the Inverse Discrete Wavelet Transform (IDWT) to + reconstruct the delta weights from the learned wavelet coefficients. If `True` (default), the IDWT is + applied. If `False`, the learned coefficients are directly used to form a sparse delta weight matrix, which + is faster but performs worse for the SDXL personalization task. + random_loc_seed (`int`): + Seed for determining the random locations of the `n_frequency` learnable wavelet coefficients within the + full wavelet coefficient matrix. + target_modules (`Union[list[str],str]`): + List of module names or a regex expression identifying the modules to be adapted with WaveFT. For example, + `['q_proj', 'v_proj']` or `'.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'`. Currently, only linear + layers (`torch.nn.Linear`) are supported. + exclude_modules (`Optional[Union[List[str], str]]`): + List of module names or a regex expression for modules to exclude from WaveFT adaptation. + fan_in_fan_out (`bool`): + Set to `True` if the weights of the layer to be replaced are stored in `(fan_in, fan_out)` format. Default + is `False`. + bias (`str`): + Bias type for WaveFT. Can be 'none', 'all', or 'waveft_only'. ('fourier_only' was likely a typo and has + been corrected to 'waveft_only' if it implies bias only on adapted parameters) If 'waveft_only', biases are + added only to the WaveFT components. If 'all', biases are added to both base and WaveFT components. If + 'none', no new biases are added. + modules_to_save (`list[str]`): + List of modules, in addition to WaveFT layers, that should be marked as trainable and saved in the final + checkpoint. Useful for layers like classifiers in sequence or token classification tasks that are randomly + initialized and need training. + layers_to_transform (`Union[list[int],int]`): + Specific layer indices to transform. If provided, PEFT will only adapt layers at these indices. If a single + integer is given, only that layer is transformed. + layers_pattern (`Optional[Union[List[str], str]]`): + Pattern for layer names, used if `layers_to_transform` is specified and the layer pattern is not standard + (e.g., not 'layers' or 'h'). This should target the `nn.ModuleList` attribute in the model. + n_frequency_pattern (`dict`): + A dictionary mapping layer names (or regex) to specific `n_frequency` values, overriding the global + `n_frequency`. Example: `{"model.decoder.layers.0.encoder_attn.k_proj": 1000}`. + init_weights (`bool`): + Initialization strategy for the learnable wavelet coefficients (spectrum). If `True` (default), + coefficients are initialized to zeros. If `False`, coefficients are initialized from a standard normal + distribution scaled by a small factor. + proportional_parameters (`bool`): + If `True`, `n_frequency` is allocated proportionally to each layer's `input_dim * output_dim`. Default is + `False`. Note: This option is included for experimental thoroughness to allow researchers to reproduce + paper results, rather than for practical utility, as no beneficial scenarios have been identified. + """ + + n_frequency: int = field( + default=2592, # Default value might need adjustment based on common use cases or paper findings + metadata={ + "help": ( + "Number of learnable wavelet coefficients for the Discrete Wavelet Transform (DWT). " + "'n_frequency' is an integer that is greater than 0 and less than or equal to the " + "total number of elements in the original weight matrix (d_out * d_in). " + "This parameter directly controls the number of trainable parameters for each adapted layer. " + "A higher 'n_frequency' generally leads to better performance but also increases " + "GPU memory usage, with a minor impact on training speed." + ) + }, + ) + scaling: float = field( + default=25.0, # Default value seems low based on typical examples, might need adjustment + metadata={ + "help": ( + "The scaling factor applied to the reconstructed delta W matrix. This is a crucial " + "hyperparameter, analogous to 'lora_alpha' in LoRA. It can be tuned during hyperparameter " + "search. Default value for SDXL personalization is 25. " + ) + }, + ) + wavelet_family: str = field( + default="db1", + metadata={ + "help": ( + "The wavelet family (e.g., 'db1', 'sym2', 'coif1') to use for the DWT and Inverse DWT (IDWT). " + "Defaults to 'db1' (Haar wavelet). Different wavelet families have varying filter lengths " + "which affect the training time substantially. Size differences are handled automatically " + "if use_idwt is True." + ) + }, + ) + use_idwt: bool = field( + default=True, + metadata={ + "help": ( + "Set to False for efficient adaptation. " + "Whether to use the Inverse Discrete Wavelet Transform (IDWT) to reconstruct the delta " + "weights from the learned wavelet coefficients. If True (default), the IDWT is applied. " + "If False, the learned coefficients are directly used to form a sparse delta weight matrix, " + "which is faster but performs worse for the SDXL personalization task." + ) + }, + ) + random_loc_seed: int = field( + default=777, + metadata={ + "help": ( + "Seed for determining the random locations of the 'n_frequency' learnable wavelet " + "coefficients within the full wavelet coefficient matrix." + ) + }, + ) + fan_in_fan_out: bool = field( + default=False, + metadata={ + "help": ( + "Set to True if the weights of the layer to be replaced are stored in (fan_in, fan_out) " + "format. Default is False." + ) + }, + ) + target_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "List of module names or a regex expression identifying the modules to be adapted with WaveFT. " + "For example, ['q_proj', 'v_proj'] or '.*decoder.*(SelfAttention|EncDecAttention).*(q|v)$'. " + "Currently, only linear layers (torch.nn.Linear) are supported." + ) + }, + ) + exclude_modules: Optional[Union[list[str], str]] = field( + default=None, + metadata={"help": "List of module names or regex for modules to exclude from WaveFT adaptation."}, + ) + bias: str = field( + default="none", + metadata={ + "help": ( + "Bias type for WaveFT. Can be 'none', 'all', or 'waveft_only'. " + "If 'waveft_only', biases are added only to the WaveFT components. " + "If 'all', biases are added to both base and WaveFT components. " + "If 'none', no new biases are added." + ) + }, + ) + modules_to_save: Optional[list[str]] = field( + default=None, + metadata={ + "help": ( + "List of modules, in addition to WaveFT layers, that should be marked as trainable " + "and saved in the final checkpoint. Useful for layers like classifiers in sequence " + "or token classification tasks that are randomly initialized and need training." + ) + }, + ) + layers_to_transform: Optional[Union[list[int], int]] = field( + default=None, + metadata={ + "help": ( + "Specific layer indices to transform. If provided, PEFT will only adapt layers at these " + "indices. If a single integer is given, only that layer is transformed." + ) + }, + ) + layers_pattern: Optional[Union[list[str], str]] = field( + default=None, + metadata={ + "help": ( + "Pattern for layer names, used if `layers_to_transform` is specified and the layer " + "pattern is not standard (e.g., not 'layers' or 'h'). This should target the " + "`nn.ModuleList` attribute in the model." + ) + }, + ) + n_frequency_pattern: Optional[dict] = field( + default_factory=dict, + metadata={ + "help": ( + "A dictionary mapping layer names (or regex) to specific `n_frequency` values, " + 'overriding the global `n_frequency`. Example: {"model.decoder.layers.0.encoder_attn.k_proj": 1000}.' + ) + }, + ) + proportional_parameters: bool = field( + default=False, + metadata={ + "help": ( + "If True, 'n_frequency' is allocated proportionally to each layer's " + "input_dim * output_dim. Default is False. Note: This option is included " + "for experimental thoroughness to allow researchers to reproduce paper results, " + "rather than for practical utility, as no beneficial scenarios have been identified." + ) + }, + ) + init_weights: bool = field( + default=True, + metadata={ + "help": ( + "Initialization strategy for the learnable wavelet coefficients (spectrum). " + "If True (default), coefficients are initialized to zeros. " + "If False, coefficients are initialized from a standard normal distribution scaled by a small factor." + ) + }, + ) + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.WAVEFT + self.target_modules = ( + set(self.target_modules) if isinstance(self.target_modules, list) else self.target_modules + ) + self.exclude_modules = ( + set(self.exclude_modules) if isinstance(self.exclude_modules, list) else self.exclude_modules + ) + # if target_modules is a regex expression, then layers_to_transform should be None + if isinstance(self.target_modules, str) and self.layers_to_transform is not None: + raise ValueError("`layers_to_transform` cannot be used when `target_modules` is a str.") + + # if target_modules is a regex expression, then layers_pattern should be None + if isinstance(self.target_modules, str) and self.layers_pattern is not None: + raise ValueError("`layers_pattern` cannot be used when `target_modules` is a str.") + # check for layers_to_transform and layers_pattern + if self.layers_pattern and not self.layers_to_transform: + raise ValueError("When `layers_pattern` is specified, `layers_to_transform` must also be specified. ") + + if self.wavelet_family not in WAVELET_REDUCTIONS: + raise ValueError( + f"Wavelet family {self.wavelet_family} not supported. Supported wavelet families are: {list(WAVELET_REDUCTIONS.keys())}" + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/constants.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..b1559f4fa5bb13039ab9687b643690d988513eb9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/constants.py @@ -0,0 +1,96 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +""" +Dimensional reduction amounts for different wavelet families during wavelet transforms Each tuple (rows, cols) +represents the reduction in matrix dimensions that occurs when applying wavelet decomposition/reconstruction due to +boundary effects and filter sizes. These values are used to pre-pad matrices before wavelet processing to ensure the +reconstructed matrix maintains the original target dimensions. +""" + +WAVELET_REDUCTIONS = { + "db1": (0, 0), + "db2": (2, 2), + "db3": (4, 4), + "db4": (6, 6), + "db5": (8, 8), + "db6": (10, 10), + "db7": (12, 12), + "db8": (14, 14), + "db9": (16, 16), + "db10": (18, 18), + "db11": (20, 20), + "db12": (22, 22), + "db13": (24, 24), + "db14": (26, 26), + "db15": (28, 28), + "db16": (30, 30), + "db17": (32, 32), + "db18": (34, 34), + "db19": (36, 36), + "db20": (38, 38), + "db21": (40, 40), + "db22": (42, 42), + "db23": (44, 44), + "db24": (46, 46), + "db25": (48, 48), + "db26": (50, 50), + "db27": (52, 52), + "db28": (54, 54), + "db29": (56, 56), + "db30": (58, 58), + "db31": (60, 60), + "db32": (62, 62), + "db33": (64, 64), + "db34": (66, 66), + "db35": (68, 68), + "db36": (70, 70), + "db37": (72, 72), + "db38": (74, 74), + "sym2": (2, 2), + "sym3": (4, 4), + "sym4": (6, 6), + "sym5": (8, 8), + "sym6": (10, 10), + "sym7": (12, 12), + "sym8": (14, 14), + "sym9": (16, 16), + "sym10": (18, 18), + "sym11": (20, 20), + "sym12": (22, 22), + "sym13": (24, 24), + "sym14": (26, 26), + "sym15": (28, 28), + "sym16": (30, 30), + "sym17": (32, 32), + "sym18": (34, 34), + "sym19": (36, 36), + "sym20": (38, 38), + "coif1": (4, 4), + "coif2": (10, 10), + "coif3": (16, 16), + "coif4": (22, 22), + "coif5": (28, 28), + "coif6": (34, 34), + "coif7": (40, 40), + "coif8": (46, 46), + "coif9": (52, 52), + "coif10": (58, 58), + "coif11": (64, 64), + "coif12": (70, 70), + "coif13": (76, 76), + "coif14": (82, 82), + "coif15": (88, 88), + "coif16": (94, 94), + "coif17": (100, 100), +} diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..c24fa5da56456f91055fed6b4b704db2ece76cf0 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/layer.py @@ -0,0 +1,298 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Any, Optional, Union + +import torch +import torch.nn as nn +import torch.nn.functional as F +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTunerLayer, check_adapters_to_merge +from peft.utils.other import transpose + +from .constants import WAVELET_REDUCTIONS +from .waverec2d import waverec2d + + +class WaveFTLayer(BaseTunerLayer): + # All names of layers that may contain (trainable) adapter weights + adapter_layer_names = ("waveft_spectrum",) + # All names of other parameters that may contain adapter-related parameters + other_param_names = ( + "waveft_n_frequency", + "waveft_scaling", + "waveft_random_loc_seed", + "waveft_wavelet_family", + "waveft_indices", + "waveft_use_idwt", + ) + + def __init__(self, base_layer: nn.Module, **kwargs) -> None: + self.base_layer = base_layer + self.waveft_n_frequency = {} + self.waveft_scaling = {} + self.waveft_spectrum = nn.ParameterDict({}) + self.waveft_wavelet_family = {} + self.waveft_indices = {} + self.waveft_random_loc_seed = {} + self.waveft_use_idwt = {} + # Mark the weight as unmerged + self._disable_adapters = False + self.merged_adapters = [] + self.kwargs = kwargs + + base_layer = self.get_base_layer() + if isinstance(base_layer, nn.Linear): + self.in_features, self.out_features = base_layer.in_features, base_layer.out_features + elif isinstance(base_layer, Conv1D): + self.in_features, self.out_features = ( + base_layer.weight.ds_shape if hasattr(base_layer.weight, "ds_shape") else base_layer.weight.shape + ) + else: + raise ValueError(f"Unsupported layer type {type(base_layer)}") + + def update_layer( + self, adapter_name, n_frequency, scaling, init_weights, random_loc_seed, wavelet_family="db1", use_idwt=True + ): + if n_frequency <= 0: + raise ValueError(f"`n_frequency` should be a positive integer value but the value passed is {n_frequency}") + if n_frequency > self.in_features * self.out_features: + raise ValueError( + f"`n_frequency` should be less than or equal to the product of the input and output dimensions " + f"but the value passed is {n_frequency} and the product is {self.in_features * self.out_features}" + ) + + self.waveft_n_frequency[adapter_name] = n_frequency + self.waveft_random_loc_seed[adapter_name] = random_loc_seed + self.waveft_wavelet_family[adapter_name] = wavelet_family + self.waveft_use_idwt[adapter_name] = use_idwt + + # Get the expanded dimensions based on wavelet family + reduction_rows, reduction_cols = WAVELET_REDUCTIONS[wavelet_family] + + # Generate random indices within the original dimensions + # We handle padding separately in get_delta_weight + generator = torch.Generator().manual_seed(self.waveft_random_loc_seed[adapter_name]) + indices = torch.randperm(self.out_features * self.in_features, generator=generator)[:n_frequency] + + # Convert to row, col format for the original dimensions + self.waveft_indices[adapter_name] = torch.stack( + [indices // self.in_features, indices % self.in_features], dim=0 + ) + + self.waveft_scaling[adapter_name] = scaling + + # Actual trainable parameters + # Initialize based on init_weights + if init_weights: + # Initialize with zeros later using reset_wave_parameters + self.waveft_spectrum[adapter_name] = nn.Parameter(torch.empty(n_frequency), requires_grad=True) + self.reset_wave_parameters(adapter_name) # Initialize to zeros now + else: + # Initialize with randn scaled by a small std dev to prevent explosion + std_dev = 0.01 # Using a small std dev for initial random weights + self.waveft_spectrum[adapter_name] = nn.Parameter(torch.randn(n_frequency) * std_dev, requires_grad=True) + + self._move_adapter_to_device_of_base_layer(adapter_name) + self.set_adapter(self.active_adapters) + + @torch.no_grad() + def reset_wave_parameters(self, adapter_name): + if adapter_name in self.waveft_spectrum.keys(): + nn.init.zeros_(self.waveft_spectrum[adapter_name]) + + def get_delta_weight(self, adapter) -> torch.Tensor: + spectrum = self.waveft_spectrum[adapter] + indices = self.waveft_indices[adapter].to(spectrum.device) + wavelet_family = self.waveft_wavelet_family[adapter] + + # Choose whether to use IDWT or direct spectrum based on adapter setting + if self.waveft_use_idwt[adapter]: + reduction_rows, reduction_cols = WAVELET_REDUCTIONS[wavelet_family] + + # Create a padded spectrum matrix with additional rows and columns + # to account for the reduction during wavelet reconstruction + padded_out_features = self.out_features + reduction_rows + padded_in_features = self.in_features + reduction_cols + + # Make dimensions even if needed for wavelet processing + if padded_out_features % 2 != 0: + padded_out_features += 1 + if padded_in_features % 2 != 0: + padded_in_features += 1 + + # Create the padded dense spectrum matrix + dense_spectrum = torch.zeros( + padded_out_features, padded_in_features, device=spectrum.device, dtype=spectrum.dtype + ) + + # Calculate padding offsets to center the original data in the padded matrix + row_offset = (padded_out_features - self.out_features) // 2 + col_offset = (padded_in_features - self.in_features) // 2 + + # Adjust indices to account for padding offsets + padded_indices = indices.clone() + padded_indices[0, :] += row_offset + padded_indices[1, :] += col_offset + + # Place spectrum values in the padded matrix + # Filter out any indices that would be out of bounds + valid_mask = (padded_indices[0, :] < padded_out_features) & (padded_indices[1, :] < padded_in_features) + valid_indices = padded_indices[:, valid_mask] + valid_spectrum = spectrum[valid_mask] + + # Set the spectrum values in the padded matrix + dense_spectrum[valid_indices[0, :], valid_indices[1, :]] = valid_spectrum + + # Split into four sub-bands + H, W = dense_spectrum.shape + H2, W2 = H // 2, W // 2 + cA = dense_spectrum[:H2, :W2] # top-left + cH = dense_spectrum[:H2, W2:] # top-right + cV = dense_spectrum[H2:, :W2] # bottom-left + cD = dense_spectrum[H2:, W2:] # bottom-right + + # Construct wavelet-coefficient tuple + coeffs = (cA, (cH, cV, cD)) + + # Reconstruct with the specified wavelet family + delta_weight = waverec2d(coeffs, wavelet_family) * self.waveft_scaling[adapter] + + # Ensure the delta weight has exactly the correct dimensions + if delta_weight.shape[0] != self.out_features or delta_weight.shape[1] != self.in_features: + # Calculate where to start slicing to get a centered crop + start_row = (delta_weight.shape[0] - self.out_features) // 2 + start_col = (delta_weight.shape[1] - self.in_features) // 2 + + # Slice to the exact output size needed + delta_weight = delta_weight[ + start_row : start_row + self.out_features, start_col : start_col + self.in_features + ] + else: + # Simple direct use of spectrum without IDWT + dense_spectrum = torch.zeros( + self.out_features, self.in_features, device=spectrum.device, dtype=spectrum.dtype + ) + dense_spectrum[indices[0, :], indices[1, :]] = spectrum + delta_weight = dense_spectrum * self.waveft_scaling[adapter] + + return delta_weight + + +class WaveFTLinear(nn.Module, WaveFTLayer): + # WaveFT implemented in a dense layer + def __init__( + self, + base_layer, + adapter_name: str, + n_frequency: int = 1000, + scaling: float = 150.0, + fan_in_fan_out: bool = False, # Set this to True if the layer to replace stores weight like (fan_in, fan_out) + init_weights: Union[bool, str] = False, + random_loc_seed: int = 777, + wavelet_family: str = "db1", + use_idwt: bool = True, + **kwargs, + ) -> None: + super().__init__() + WaveFTLayer.__init__(self, base_layer, **kwargs) + self.fan_in_fan_out = fan_in_fan_out + self._active_adapter = adapter_name + self.update_layer(adapter_name, n_frequency, scaling, init_weights, random_loc_seed, wavelet_family, use_idwt) + + def merge(self, safe_merge: bool = False, adapter_names: Optional[list[str]] = None) -> None: + """ + Merge the active adapter weights into the base weights + + Args: + safe_merge (`bool`, *optional*): + If True, the merge operation will be performed in a copy of the original weights and check for NaNs + before merging the weights. This is useful if you want to check if the merge operation will produce + NaNs. Defaults to `False`. + adapter_names (`List[str]`, *optional*): + The list of adapter names that should be merged. If None, all active adapters will be merged. Defaults + to `None`. + """ + adapter_names = check_adapters_to_merge(self, adapter_names) + if not adapter_names: + # no adapter to merge + return + + for active_adapter in adapter_names: + if active_adapter in self.waveft_spectrum.keys(): + base_layer = self.get_base_layer() + if safe_merge: + # Note that safe_merge will be slower than the normal merge + # because of the copy operation. + orig_weights = base_layer.weight.data.clone() + orig_weights += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + + if not torch.isfinite(orig_weights).all(): + raise ValueError( + f"NaNs detected in the merged weights. The adapter {active_adapter} seems to be broken" + ) + + base_layer.weight.data = orig_weights + else: + base_layer.weight.data += transpose(self.get_delta_weight(active_adapter), self.fan_in_fan_out) + self.merged_adapters.append(active_adapter) + + def unmerge(self) -> None: + """ + This method unmerges all merged adapter layers from the base weights. + """ + if not self.merged: + warnings.warn("Already unmerged. Nothing to do.") + return + while len(self.merged_adapters) > 0: + active_adapter = self.merged_adapters.pop() + if active_adapter in self.waveft_spectrum.keys(): + self.get_base_layer().weight.data -= transpose( + self.get_delta_weight(active_adapter), self.fan_in_fan_out + ) + + def forward(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + previous_dtype = x.dtype + + if self.disable_adapters: + if self.merged: + self.unmerge() + result = self.base_layer(x, *args, **kwargs) + elif self.merged: + result = self.base_layer(x, *args, **kwargs) + else: + result = self.base_layer(x, *args, **kwargs) + for active_adapter in self.active_adapters: + if active_adapter not in self.waveft_spectrum.keys(): + continue + + delta_w = self.get_delta_weight(active_adapter) + x = self._cast_input_dtype(x, delta_w.dtype) + result = result + F.linear(x, delta_w) + + result = result.to(previous_dtype) + return result + + def supports_lora_conversion(self, adapter_name: str = "default") -> bool: + if isinstance(self.get_base_layer(), Conv1D): + # get_delta_weight does not transpose Conv1D because it is used in forward, therefore, it has the wrong + # shape for conversion + return False + return True + + def __repr__(self) -> str: + rep = super().__repr__() + return "waveft." + rep diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/model.py new file mode 100644 index 0000000000000000000000000000000000000000..3ecc8ac6b0d8407ed378517e91de9c35f05b9be9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/model.py @@ -0,0 +1,195 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings + +import torch +from transformers.pytorch_utils import Conv1D + +from peft.tuners.tuners_utils import BaseTuner, BaseTunerLayer, check_target_module_exists +from peft.utils import ( + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, +) +from peft.utils.other import get_pattern_key + +from .layer import WaveFTLayer, WaveFTLinear + + +class WaveFTModel(BaseTuner): + prefix: str = "waveft_" + tuner_layer_cls: type[BaseTunerLayer] = WaveFTLayer + target_module_mapping = TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING + + def _calculate_proportional_parameters(self, model: torch.nn.Module, waveft_config): + """Calculate proportional parameter allocation for all target modules.""" + target_modules_info = [] + for name, module in model.named_modules(): + if check_target_module_exists(waveft_config, name): + # Handle case where module is already wrapped with WaveFT + if isinstance(module, WaveFTLayer): + # Use the base layer for dimension calculations + base_module = module.base_layer + if isinstance(base_module, torch.nn.Linear): + input_dim, output_dim = base_module.in_features, base_module.out_features + elif isinstance(base_module, Conv1D): + input_dim, output_dim = base_module.weight.shape[1], base_module.weight.shape[0] + else: + continue + elif isinstance(module, torch.nn.Linear): + input_dim, output_dim = module.in_features, module.out_features + elif isinstance(module, Conv1D): + input_dim, output_dim = module.weight.shape[1], module.weight.shape[0] + else: + continue + target_modules_info.append((name, input_dim, output_dim)) + + if not target_modules_info: + raise ValueError("No target modules found for proportional parameter allocation.") + + total_sum = sum(input_dim * output_dim for (_, input_dim, output_dim) in target_modules_info) + num_layers = len(target_modules_info) + total_budget = waveft_config.n_frequency * num_layers + + n_frequency_dict = {} + for name, input_dim, output_dim in target_modules_info: + layer_ratio = (input_dim * output_dim) / total_sum + n_freq = round(layer_ratio * total_budget) + n_frequency_dict[name] = n_freq + + return n_frequency_dict + + def _create_and_replace( + self, + waveft_config, + adapter_name, + target, + target_name, + parent, + current_key, + **optional_kwargs, + ): + if current_key is None: + raise ValueError("Current Key shouldn't be `None`") + + # Calculate proportional parameters if needed (only once per adapter) + if waveft_config.proportional_parameters: + if not hasattr(self, "_proportional_params_cache"): + self._proportional_params_cache = {} + if adapter_name not in self._proportional_params_cache: + n_frequency_dict = self._calculate_proportional_parameters(self.model, waveft_config) + self._proportional_params_cache[adapter_name] = n_frequency_dict + + # Determine n_frequency: Priority order: + # 1. From proportional parameter cache (if proportional_parameters=True) + # 2. From optional_kwargs (if passed directly) + # 3. From n_frequency_pattern in config + # 4. From default n_frequency in config + n_frequency = None + if ( + waveft_config.proportional_parameters + and hasattr(self, "_proportional_params_cache") + and adapter_name in self._proportional_params_cache + ): + n_frequency = self._proportional_params_cache[adapter_name].get(current_key) + + if n_frequency is None and "n_frequency" in optional_kwargs: + n_frequency = optional_kwargs["n_frequency"] + + if n_frequency is None: + pattern_keys = list(waveft_config.n_frequency_pattern.keys()) + target_name_key = get_pattern_key(pattern_keys, current_key) + n_frequency = waveft_config.n_frequency_pattern.get(target_name_key, waveft_config.n_frequency) + + # Determine wavelet_family + wavelet_family = None + if "wavelet_family" in optional_kwargs: + wavelet_family = optional_kwargs["wavelet_family"] + if wavelet_family is None: + wavelet_family = waveft_config.wavelet_family + + scaling = waveft_config.scaling + random_loc_seed = waveft_config.random_loc_seed + bias = hasattr(target, "bias") and target.bias is not None + # Prepare kwargs for module creation/update + kwargs = { + "n_frequency": n_frequency, + "scaling": scaling, + "fan_in_fan_out": waveft_config.fan_in_fan_out, + "init_weights": waveft_config.init_weights, + "random_loc_seed": waveft_config.random_loc_seed, + "wavelet_family": wavelet_family, # Use determined wavelet family + } + kwargs["bias"] = bias + + if isinstance(target, WaveFTLayer): + target.update_layer( + adapter_name, + n_frequency, + scaling, + waveft_config.init_weights, + random_loc_seed, + wavelet_family=wavelet_family, # Pass determined wavelet family + use_idwt=waveft_config.use_idwt, + ) + else: + new_module = self._create_new_module(waveft_config, adapter_name, target, **kwargs) + if adapter_name != self.active_adapter: + new_module.requires_grad_(False) + self._replace_module(parent, target_name, new_module, target) + + @staticmethod + def _create_new_module(waveft_config, adapter_name, target, **kwargs): + if isinstance(target, BaseTunerLayer): + target_base_layer = target.get_base_layer() + else: + target_base_layer = target + + if isinstance(target_base_layer, torch.nn.Linear): + if kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to True but the target module is `torch.nn.Linear`. " + "Setting fan_in_fan_out to False." + ) + kwargs["fan_in_fan_out"] = waveft_config.fan_in_fan_out = False + elif isinstance(target_base_layer, Conv1D): + kwargs["is_target_conv_1d_layer"] = True + if not kwargs["fan_in_fan_out"]: + warnings.warn( + "fan_in_fan_out is set to False but the target module is `Conv1D`. Setting fan_in_fan_out to True." + ) + kwargs["fan_in_fan_out"] = waveft_config.fan_in_fan_out = True + else: + raise ValueError( + f"Target module {target} is not supported. Currently, only the following modules are supported: " + "`torch.nn.Linear`." + ) + + kwargs["wavelet_family"] = waveft_config.wavelet_family + kwargs["use_idwt"] = waveft_config.use_idwt + new_module = WaveFTLinear(target, adapter_name, **kwargs) + + return new_module + + def delete_adapter(self, adapter_name: str) -> None: + """ + Deletes an existing adapter. + + Args: + adapter_name (str): Name of the adapter to be deleted. + """ + super().delete_adapter(adapter_name) + # Clean up proportional parameters cache + if hasattr(self, "_proportional_params_cache") and adapter_name in self._proportional_params_cache: + del self._proportional_params_cache[adapter_name] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/wavelet.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/wavelet.py new file mode 100644 index 0000000000000000000000000000000000000000..c66acd85f65570652f18d47d5bed12eb3a174ea5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/wavelet.py @@ -0,0 +1,513 @@ +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Minimal wavelet implementation extracted from PyWavelets + +This code contains portions derived from PyWavelets: Copyright (c) 2006-2012 Filip Wasilewski +Copyright (c) 2012- The PyWavelets Developers + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit +persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the +Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE +WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR +COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +Original source: https://github.com/PyWavelets/pywt +""" + +import math +from collections.abc import Sequence + + +class Wavelet: + """ + Minimal wavelet class that implements the most commonly used wavelets. + + Supports: + - Daubechies wavelets: db1-db10, haar + - Symlets: sym2-sym10 + - Coiflets: coif1-coif5 + """ + + def __init__(self, name: str): + """ + Initialize a wavelet by name. + + Args: + name: Wavelet name (e.g., 'db4', 'haar', 'sym5', 'coif2') + """ + self.name = name.lower() + self._compute_filters() + + def _compute_filters(self): + """Compute the four filter banks from the base coefficients.""" + if self.name == "haar": + # Haar is the same as db1 + base_coeffs = _WAVELET_COEFFS["db1"] + elif self.name in _WAVELET_COEFFS: + base_coeffs = _WAVELET_COEFFS[self.name] + else: + raise ValueError(f"Unknown wavelet name '{self.name}'. Available wavelets: {list(_WAVELET_COEFFS.keys())}") + + # Determine if this is a coiflet (needs sqrt(2) scaling) + scale_factor = math.sqrt(2) if self.name.startswith("coif") else 1.0 + + # Apply scaling to base coefficients + scaled_coeffs = [c * scale_factor for c in base_coeffs] + + # Compute the four filter banks following PyWavelets convention + # rec_lo = scaled base coefficients + self._rec_lo = scaled_coeffs[:] + + # dec_lo = rec_lo reversed + self._dec_lo = scaled_coeffs[::-1] + + # rec_hi = alternating signs of dec_lo + self._rec_hi = [(-1) ** i * scaled_coeffs[len(scaled_coeffs) - 1 - i] for i in range(len(scaled_coeffs))] + + # dec_hi = alternating signs of rec_lo + self._dec_hi = [(-1) ** (len(scaled_coeffs) - 1 - i) * scaled_coeffs[i] for i in range(len(scaled_coeffs))] + + @property + def dec_lo(self) -> Sequence[float]: + """Lowpass decomposition filter.""" + return self._dec_lo + + @property + def dec_hi(self) -> Sequence[float]: + """Highpass decomposition filter.""" + return self._dec_hi + + @property + def rec_lo(self) -> Sequence[float]: + """Lowpass reconstruction filter.""" + return self._rec_lo + + @property + def rec_hi(self) -> Sequence[float]: + """Highpass reconstruction filter.""" + return self._rec_hi + + @property + def dec_len(self) -> int: + """Decomposition filters length.""" + return len(self._dec_lo) + + @property + def rec_len(self) -> int: + """Reconstruction filters length.""" + return len(self._rec_lo) + + @property + def filter_bank(self) -> tuple[Sequence[float], Sequence[float], Sequence[float], Sequence[float]]: + """Tuple of all four filter banks (dec_lo, dec_hi, rec_lo, rec_hi).""" + return (self.dec_lo, self.dec_hi, self.rec_lo, self.rec_hi) + + def __len__(self) -> int: + """Return the length of the decomposition filters.""" + return self.dec_len + + def __repr__(self) -> str: + return f"Wavelet(name='{self.name}')" + + +# Wavelet coefficients extracted from PyWavelets +# These are the reconstruction lowpass filter coefficients +_WAVELET_COEFFS = { + # Daubechies wavelets + "db1": [ + 0.7071067811865475244008443621048490392848359376884740365883398, + 0.7071067811865475244008443621048490392848359376884740365883398, + ], + "db2": [ + 0.4829629131445341433748715998644486838169524195042022752011715, + 0.8365163037378079055752937809168732034593703883484392934953414, + 0.2241438680420133810259727622404003554678835181842717613871683, + -0.1294095225512603811744494188120241641745344506599652569070016, + ], + "db3": [ + 0.3326705529500826159985115891390056300129233992450683597084705, + 0.80689150931333875, + 0.45987750211933132, + -0.13501102001039084, + -0.085441273882241486, + 0.035226291882100656, + ], + "db4": [ + 0.2303778133088965008632911830440708500016152482483092977910968, + 0.7148465705529156470899219552739926037076084010993081758450110, + 0.6308807679298589078817163383006152202032229226771951174057473, + -0.02798376941685985421141374718007538541198732022449175284003358, + -0.1870348117190930840795706727890814195845441743745800912057770, + 0.03084138183556076362721936253495905017031482172003403341821219, + 0.03288301166688519973540751354924438866454194113754971259727278, + -0.01059740178506903210488320852402722918109996490637641983484974, + ], + "db5": [ + 0.1601023979741929144807237480204207336505441246250578327725699, + 0.6038292697971896705401193065250621075074221631016986987969283, + 0.7243085284377729277280712441022186407687562182320073725767335, + 0.1384281459013207315053971463390246973141057911739561022694652, + -0.2422948870663820318625713794746163619914908080626185983913726, + -0.03224486958463837464847975506213492831356498416379847225434268, + 0.07757149384004571352313048938860181980623099452012527983210146, + -0.006241490212798274274190519112920192970763557165687607323417435, + -0.01258075199908199946850973993177579294920459162609785020169232, + 0.003335725285473771277998183415817355747636524742305315099706428, + ], + "db6": [ + 0.1115407433501094636213239172409234390425395919844216759082360, + 0.4946238903984530856772041768778555886377863828962743623531834, + 0.7511339080210953506789344984397316855802547833382612009730420, + 0.3152503517091976290859896548109263966495199235172945244404163, + -0.2262646939654398200763145006609034656705401539728969940143487, + -0.1297668675672619355622896058765854608452337492235814701599310, + 0.09750160558732304910234355253812534233983074749525514279893193, + 0.02752286553030572862554083950419321365738758783043454321494202, + -0.03158203931748602956507908069984866905747953237314842337511464, + 0.0005538422011614961392519183980465012206110262773864964295476524, + 0.004777257510945510639635975246820707050230501216581434297593254, + -0.001077301085308479564852621609587200035235233609334419689818580, + ], + "db7": [ + 0.07785205408500917901996352195789374837918305292795568438702937, + 0.3965393194819173065390003909368428563587151149333287401110499, + 0.7291320908462351199169430703392820517179660611901363782697715, + 0.4697822874051931224715911609744517386817913056787359532392529, + -0.1439060039285649754050683622130460017952735705499084834401753, + -0.2240361849938749826381404202332509644757830896773246552665095, + 0.07130921926683026475087657050112904822711327451412314659575113, + 0.08061260915108307191292248035938190585823820965629489058139218, + -0.03802993693501441357959206160185803585446196938467869898283122, + -0.01657454163066688065410767489170265479204504394820713705239272, + 0.01255099855609984061298988603418777957289474046048710038411818, + 0.0004295779729213665211321291228197322228235350396942409742946366, + -0.001801640704047490915268262912739550962585651469641090625323864, + 0.0003537137999745202484462958363064254310959060059520040012524275, + ], + "db8": [ + 0.05441584224310400995500940520299935503599554294733050397729280, + 0.3128715909142999706591623755057177219497319740370229185698712, + 0.6756307362972898068078007670471831499869115906336364227766759, + 0.5853546836542067127712655200450981944303266678053369055707175, + -0.01582910525634930566738054787646630415774471154502826559735335, + -0.2840155429615469265162031323741647324684350124871451793599204, + 0.0004724845739132827703605900098258949861948011288770074644084096, + 0.1287474266204784588570292875097083843022601575556488795577000, + -0.01736930100180754616961614886809598311413086529488394316977315, + -0.04408825393079475150676372323896350189751839190110996472750391, + 0.01398102791739828164872293057263345144239559532934347169146368, + 0.008746094047405776716382743246475640180402147081140676742686747, + -0.004870352993451574310422181557109824016634978512157003764736208, + -0.0003917403733769470462980803573237762675229350073890493724492694, + 0.0006754494064505693663695475738792991218489630013558432103617077, + -0.0001174767841247695337306282316988909444086693950311503927620013, + ], + "db9": [ + 0.03807794736387834658869765887955118448771714496278417476647192, + 0.2438346746125903537320415816492844155263611085609231361429088, + 0.6048231236901111119030768674342361708959562711896117565333713, + 0.6572880780513005380782126390451732140305858669245918854436034, + 0.1331973858250075761909549458997955536921780768433661136154346, + -0.2932737832791749088064031952421987310438961628589906825725112, + -0.09684078322297646051350813353769660224825458104599099679471267, + 0.1485407493381063801350727175060423024791258577280603060771649, + 0.03072568147933337921231740072037882714105805024670744781503060, + -0.06763282906132997367564227482971901592578790871353739900748331, + 0.0002509471148314519575871897499885543315176271993709633321834164, + 0.02236166212367909720537378270269095241855646688308853754721816, + -0.004723204757751397277925707848242465405729514912627938018758526, + -0.004281503682463429834496795002314531876481181811463288374860455, + 0.001847646883056226476619129491125677051121081359600318160732515, + 0.0002303857635231959672052163928245421692940662052463711972260006, + -0.0002519631889427101369749886842878606607282181543478028214134265, + 0.00003934732031627159948068988306589150707782477055517013507359938, + ], + "db10": [ + 0.02667005790055555358661744877130858277192498290851289932779975, + 0.1881768000776914890208929736790939942702546758640393484348595, + 0.5272011889317255864817448279595081924981402680840223445318549, + 0.6884590394536035657418717825492358539771364042407339537279681, + 0.2811723436605774607487269984455892876243888859026150413831543, + -0.2498464243273153794161018979207791000564669737132073715013121, + -0.1959462743773770435042992543190981318766776476382778474396781, + 0.1273693403357932600826772332014009770786177480422245995563097, + 0.09305736460357235116035228983545273226942917998946925868063974, + -0.07139414716639708714533609307605064767292611983702150917523756, + -0.02945753682187581285828323760141839199388200516064948779769654, + 0.03321267405934100173976365318215912897978337413267096043323351, + 0.003606553566956169655423291417133403299517350518618994762730612, + -0.01073317548333057504431811410651364448111548781143923213370333, + 0.001395351747052901165789318447957707567660542855688552426721117, + 0.001992405295185056117158742242640643211762555365514105280067936, + -0.0006858566949597116265613709819265714196625043336786920516211903, + -0.0001164668551292854509514809710258991891527461854347597362819235, + 0.00009358867032006959133405013034222854399688456215297276443521873, + -0.00001326420289452124481243667531226683305749240960605829756400674, + ], + # Symlets + "sym2": [0.48296291314469025, 0.83651630373746899, 0.22414386804185735, -0.12940952255092145], + "sym3": [ + 0.33267055295095688, + 0.80689150931333875, + 0.45987750211933132, + -0.13501102001039084, + -0.085441273882241486, + 0.035226291882100656, + ], + "sym4": [ + 0.032223100604042702, + -0.012603967262037833, + -0.099219543576847216, + 0.29785779560527736, + 0.80373875180591614, + 0.49761866763201545, + -0.02963552764599851, + -0.075765714789273325, + ], + "sym5": [ + 0.019538882735286728, + -0.021101834024758855, + -0.17532808990845047, + 0.016602105764522319, + 0.63397896345821192, + 0.72340769040242059, + 0.1993975339773936, + -0.039134249302383094, + 0.029519490925774643, + 0.027333068345077982, + ], + "sym6": [ + -0.007800708325034148, + 0.0017677118642428036, + 0.044724901770665779, + -0.021060292512300564, + -0.072637522786462516, + 0.3379294217276218, + 0.787641141030194, + 0.49105594192674662, + -0.048311742585632998, + -0.11799011114819057, + 0.0034907120842174702, + 0.015404109327027373, + ], + "sym7": [ + 0.010268176708511255, + 0.0040102448715336634, + -0.10780823770381774, + -0.14004724044296152, + 0.28862963175151463, + 0.76776431700316405, + 0.5361019170917628, + 0.017441255086855827, + -0.049552834937127255, + 0.067892693501372697, + 0.03051551316596357, + -0.01263630340325193, + -0.0010473848886829163, + 0.0026818145682578781, + ], + "sym8": [ + 0.0018899503327594609, + -0.0003029205147213668, + -0.014952258337048231, + 0.0038087520138906151, + 0.049137179673607506, + -0.027219029917056003, + -0.051945838107709037, + 0.3644418948353314, + 0.77718575170052351, + 0.48135965125837221, + -0.061273359067658524, + -0.14329423835080971, + 0.0076074873249176054, + 0.031695087811492981, + -0.00054213233179114812, + -0.0033824159510061256, + ], + "sym9": [ + 0.0010694900329086053, + -0.00047315449868008311, + -0.010264064027633142, + 0.0088592674934004842, + 0.06207778930288603, + -0.018233770779395985, + -0.19155083129728512, + 0.035272488035271894, + 0.61733844914093583, + 0.717897082764412, + 0.238760914607303, + -0.054568958430834071, + 0.00058346274612580684, + 0.03022487885827568, + -0.01152821020767923, + -0.013271967781817119, + 0.00061978088898558676, + 0.0014009155259146807, + ], + "sym10": [ + -0.00045932942100465878, + 0.000057036083618494284, + 0.0045931735853118284, + -0.00080435893201654491, + -0.02035493981231129, + 0.0057649120335819086, + 0.049994972077376687, + -0.0319900568824278, + -0.035536740473817552, + 0.38382676106708546, + 0.7695100370211071, + 0.47169066693843925, + -0.070880535783243853, + -0.15949427888491757, + 0.011609893903711381, + 0.045927239231092203, + -0.0014653825813050513, + -0.0086412992770224222, + 0.000095632670722894754, + 0.00077015980911449011, + ], + # Coiflets (note: these will be multiplied by sqrt(2) in the class) + "coif1": [ + -0.05142972847076845595317549230122688830344559947132656813651045, + 0.2389297284707684559531754923012268883034455994713265681365104, + 0.6028594569415369119063509846024537766068911989426531362730209, + 0.2721405430584630880936490153975462233931088010573468637269790, + -0.05142972847076845595317549230122688830344559947132656813651045, + -0.01107027152923154404682450769877311169655440052867343186348954, + ], + "coif2": [ + 0.01158759673871686817889714882853120395708315073355502818875931, + -0.02932013798346856448679594524397843054053420947418409889774786, + -0.04763959031100813225872995081511549408622753909592460525840745, + 0.2730210465347666137982239328923516270034828327990699588033501, + 0.5746823938568638472459483149751499367740786490481481391460366, + 0.2948671936956191896750637208703777973914107635455611537640778, + -0.05408560709171142997443672832006888537570221990444706777525838, + -0.04202648046077160694657530752545884878978719268926222513485613, + 0.01674441016327950635146257083249391698866289538037299820224006, + 0.003967883612962012109043447090269950094081810916481648252817197, + -0.001289203356140659543141355500990678257894936161704492503370186, + -0.0005095053991076441489598480835620951586540050976664367876412655, + ], + "coif3": [ + -0.002682418670922068664584689955153722375535836177157637134187840, + 0.005503126707831385107969640263617469178794666057252906037981936, + 0.01658356047917034608134280439996549525220639437145367606178002, + -0.04650776447872697640390293095170192691113917841041002855534619, + -0.04322076356021191118175840907244577856782537221435748296465882, + 0.2865033352736474630249006862976158896891076238443844211133873, + 0.5612852568703300445990941995240077241406247774064453800050914, + 0.3029835717728241602862575774374668529867757043461413348549577, + -0.05077014075488886159516471867138370972545857441670871832472707, + -0.05819625076158553022607041679522801089624825903982541419721721, + 0.02443409432116695639462954438418928805487699080947974989338820, + 0.01122924096203786563399489540091488781245346096838814728167341, + -0.006369601011048822977293753932627342482077585617391852852955559, + -0.001820458915566242322836631665832145136570132777862391313328351, + 0.0007902051009575939937150950543290226440287715441826917281929124, + 0.0003296651737931830308416338897758022998655744276957481989605186, + -0.00005019277455327664998007173088097694083956570594580641192332170, + -0.00002446573425530813115445387662881902303945941576472342106918209, + ], + "coif4": [ + 0.0006309612114309468490753696608619526520153127603444406835368201, + -0.001152225143769973488683007937016166047881572156705066038094891, + -0.005194525163470323267558201363327294331811309729430512113592118, + 0.011360930899781950641704454327495718441159520023894304805142070, + 0.018945061045616642675204041814669158097013442370604397885045773, + -0.051719843705815280952009072709014825996085808127950893370164031, + -0.034486140470944806827159094088779177962124655341862998060866093, + 0.30227251053656843537076103037201073987915654650542997843779746, + 0.55454790624088107896085831311334062609863843227892842936901802, + 0.30791766802517503548651698686002846493302655084140026096325632, + -0.04352500928126570063143077306027663648139777048547894956715080, + -0.06488795097143100103160862688937301504802507374726020928892066, + 0.01988077364815951966984001670075537628468542316950829728327598, + 0.01763894787126169746077061344050946967036166456074020965866088, + -0.007366054847173363935072651649653007115003169492027095040477055, + -0.002312432307658842282830374733100847689924654369899030169556169, + 0.0014260063442333715226509754100697734398974715092509045804651032, + 0.0004666984635537353670445650012678936080062341977092967649055398, + -0.0001270007842387334077388950072420113055088253899932456267893098, + -0.0001130536369789104919020013936507623832962772709844179610938550, + 0.00003048364879677801030096883509693508426509710688913073244616617, + 0.00001266744808933008194725929652978169473830765616675686100903086, + -0.000001584926580756893754069651095690142946796090146306140001598, + -0.000001123948088281542889088159169056968300680087779667334879506, + ], + "coif5": [ + -0.0001444992186438190986841213894961515720877049723502928655308158, + 0.0002541649492011946935899015644804259825374993423205648946709984, + 0.0015016192805175522217354963668928299350735326077949346507003370, + -0.0029411108712655515426850089360913424188662278991737055486839309, + -0.0071777671514877191801104649507158618871157411936681659380839993, + 0.016680426640070654149267486742006854522334094142598667043628439, + 0.019433238433489604119639447772308536988043628308900006988094899, + -0.064934946567212502582522008002547701764467194128935170823607736, + -0.036249793089132571825087765037251085892962369926089901862924065, + 0.29804266217809436069693444260411251439893892734398765007426945, + 0.55749162970920071628061190166750547398568080072951806509736879, + 0.30731644529206781686031633026138686170779831068030092889493625, + -0.047088034719761145117688715152051398948700623993077406913889346, + -0.068890522508050074805015336128652797797076949077503388892816063, + 0.020697343297747766068568936830651656003659188170019885439659031, + 0.021640668655956855043817421090949779825140639715020046717736369, + -0.0081089373078953680936950024508066654697766705721301481097854397, + -0.0049881737671041853808073796089816945023009226058734090095808033, + 0.0024486914321021269742893936892468103370072825113159100554056433, + 0.0014095103899593442621166984842002926701899968616244946547893994, + -0.0005637801876093825733169550088901318936072015721509885859509815, + -0.0002859004477225750899655442618734663056802618537327806113618985, + 0.00012739637513815208006169426577159456832051015616166327985688948, + 0.00005416263410701044073894700796327336007788688985721449717765655, + -0.00001736867944346280636144226913926838103159698473080996002509476, + -0.00001392656190060010871169838885327726938969652863554900825705905, + 0.000003582065515946048838215026334503092089635988710863959063568069, + 0.000001914022895847318655772885654240700542388103264097264264779554, + -0.00000031262488377016899432194683906058825900951892071223097080609, + -0.00000034030635502511647536690616071863203084936306302829968850306, + 0.000000059816065238516936893488966688516710847096926983547983503726, + 0.000000047001427849456491830476615736016736014244615701046223529866, + -0.000000006158615709678364180659098549671046676203853020063205641804, + -0.000000009225635096344935080070901936862847863830913641424076095562, + 0.000000001028486074518821265015830073593127726988903862842106883701, + 0.000000001168734175186263778695686067593866982925127816327529890618, + -0.00000000009468626176069127302554946536142654377756003084491946024, + -0.00000000016230233142152041788509334089966065953985768924968863072, + 0.000000000015076656859346950325398899897135970089618140503825462985, + 0.000000000015770990416421915106306877550025550097686639869166742016, + -0.000000000001084900468648598127623517893686893316653633996513097476, + -0.000000000001968659779411804788815966829825641065085077654946686012, + 0.000000000000098745634639726633264577838416327095717894829823436076, + 0.000000000000196734781460508097097473336847436635654948853090962606, + -0.000000000000008021080145299890797556481653726965016924825037889883, + -0.000000000000021030408801651651406095853493993966926736862877194669, + 0.000000000000000723888697830915633925166893301949334507697669655816, + 0.000000000000001943208515072761516084547140065815027641765976721267, + ], +} + + +def wavelist() -> list[str]: + """Return a list of available wavelet names.""" + return list(_WAVELET_COEFFS.keys()) + ["haar"] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/waverec2d.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/waverec2d.py new file mode 100644 index 0000000000000000000000000000000000000000..907049787abee6603dc090eff7332e672d440aab --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/waveft/waverec2d.py @@ -0,0 +1,316 @@ +# Copyright 2021 Moritz Wolter +# Copyright 2025-present the HuggingFace Inc. team. +# +# Licensed under the EUPL v1.2 +# +# This file contains code derived from PyTorch-Wavelet-Toolbox: +# https://github.com/v0lta/PyTorch-Wavelet-Toolbox +# +# Original work by Moritz Wolter, licensed under EUPL v1.2 +# Modifications and integration by HuggingFace Inc. team + +from collections.abc import Callable, Sequence +from functools import partial +from typing import Any, NamedTuple, Protocol, TypeAlias, Union, cast, overload + +import numpy as np +import torch +from typing_extensions import Unpack + +from .wavelet import Wavelet as minimal_wavelet + + +class WaveletDetailTuple2d(NamedTuple): + horizontal: torch.Tensor + vertical: torch.Tensor + diagonal: torch.Tensor + + +WaveletCoeff2d: TypeAlias = tuple[torch.Tensor, Unpack[tuple[WaveletDetailTuple2d, ...]]] +WaveletDetailDict: TypeAlias = dict[str, torch.Tensor] +WaveletCoeffNd: TypeAlias = tuple[torch.Tensor, Unpack[tuple[WaveletDetailDict, ...]]] + + +class Wavelet(Protocol): + name: str + dec_lo: Sequence[float] + dec_hi: Sequence[float] + rec_lo: Sequence[float] + rec_hi: Sequence[float] + dec_len: int + rec_len: int + filter_bank: tuple[Sequence[float], Sequence[float], Sequence[float], Sequence[float]] + + def __len__(self) -> int: + return len(self.dec_lo) + + +class WaveletTensorTuple(NamedTuple): + dec_lo: torch.Tensor + dec_hi: torch.Tensor + rec_lo: torch.Tensor + rec_hi: torch.Tensor + + @classmethod + def from_wavelet(cls, wavelet: Wavelet, dtype: torch.dtype) -> "WaveletTensorTuple": + return cls( + torch.tensor(wavelet.dec_lo, dtype=dtype), + torch.tensor(wavelet.dec_hi, dtype=dtype), + torch.tensor(wavelet.rec_lo, dtype=dtype), + torch.tensor(wavelet.rec_hi, dtype=dtype), + ) + + +def _as_wavelet(wavelet: Union[Wavelet, str]) -> Wavelet: + if isinstance(wavelet, str): + return minimal_wavelet(wavelet) + else: + return wavelet + + +def _is_dtype_supported(dtype: torch.dtype) -> bool: + return dtype in [torch.float16, torch.bfloat16, torch.float32, torch.float64] + + +def _outer(a: torch.Tensor, b: torch.Tensor) -> torch.Tensor: + a_flat = torch.reshape(a, [-1]) + b_flat = torch.reshape(b, [-1]) + a_mul = torch.unsqueeze(a_flat, dim=-1) + b_mul = torch.unsqueeze(b_flat, dim=0) + return a_mul * b_mul + + +def _check_if_tensor(array: Any) -> torch.Tensor: + if not isinstance(array, torch.Tensor): + raise ValueError("First element of coeffs must be the approximation coefficient tensor.") + return array + + +def _check_axes_argument(axes: Sequence[int]) -> None: + if len(set(axes)) != len(axes): + raise ValueError("Cant transform the same axis twice.") + + +def _check_same_device(tensor: torch.Tensor, torch_device: torch.device) -> torch.Tensor: + if torch_device != tensor.device: + raise ValueError("coefficients must be on the same device") + return tensor + + +def _check_same_dtype(tensor: torch.Tensor, torch_dtype: torch.dtype) -> torch.Tensor: + if torch_dtype != tensor.dtype: + raise ValueError("coefficients must have the same dtype") + return tensor + + +@overload +def _coeff_tree_map( + coeffs: list[torch.Tensor], function: Callable[[torch.Tensor], torch.Tensor] +) -> list[torch.Tensor]: ... +@overload +def _coeff_tree_map(coeffs: WaveletCoeff2d, function: Callable[[torch.Tensor], torch.Tensor]) -> WaveletCoeff2d: ... +@overload +def _coeff_tree_map(coeffs: WaveletCoeffNd, function: Callable[[torch.Tensor], torch.Tensor]) -> WaveletCoeffNd: ... +def _coeff_tree_map(coeffs, function): + approx = function(coeffs[0]) + result_lst: list[Any] = [] + for element in coeffs[1:]: + if isinstance(element, tuple): + result_lst.append(WaveletDetailTuple2d(function(element[0]), function(element[1]), function(element[2]))) + elif isinstance(element, dict): + new_dict = {key: function(value) for key, value in element.items()} + result_lst.append(new_dict) + elif isinstance(element, torch.Tensor): + result_lst.append(function(element)) + else: + raise ValueError(f"Unexpected input type {type(element)}") + if not result_lst: + return [approx] if isinstance(coeffs, list) else (approx,) + elif isinstance(result_lst[0], torch.Tensor): + return [approx] + cast(list[torch.Tensor], result_lst) + else: + cast_result_lst = cast(Union[list[WaveletDetailDict], list[WaveletDetailTuple2d]], result_lst) + return (approx, *cast_result_lst) + + +def _check_same_device_dtype( + coeffs: Union[list[torch.Tensor], WaveletCoeff2d, WaveletCoeffNd], +) -> tuple[torch.device, torch.dtype]: + c = _check_if_tensor(coeffs[0]) + torch_device, torch_dtype = c.device, c.dtype + _coeff_tree_map(coeffs, partial(_check_same_device, torch_device=torch_device)) + _coeff_tree_map(coeffs, partial(_check_same_dtype, torch_dtype=torch_dtype)) + return torch_device, torch_dtype + + +def _get_transpose_order(axes: Sequence[int], data_shape: Sequence[int]) -> tuple[list[int], list[int]]: + axes = [a + len(data_shape) if a < 0 else a for a in axes] + all_axes = list(range(len(data_shape))) + remove_transformed = list(filter(lambda a: a not in axes, all_axes)) + return remove_transformed, axes + + +def _swap_axes(data: torch.Tensor, axes: Sequence[int]) -> torch.Tensor: + _check_axes_argument(axes) + front, back = _get_transpose_order(axes, list(data.shape)) + return torch.permute(data, front + back) + + +def _undo_swap_axes(data: torch.Tensor, axes: Sequence[int]) -> torch.Tensor: + _check_axes_argument(axes) + front, back = _get_transpose_order(axes, list(data.shape)) + restore_sorted = torch.argsort(torch.tensor(front + back)).tolist() + return torch.permute(data, restore_sorted) + + +def _fold_axes(data: torch.Tensor, keep_no: int) -> tuple[torch.Tensor, list[int]]: + dshape = list(data.shape) + return (torch.reshape(data, [int(np.prod(dshape[:-keep_no]))] + dshape[-keep_no:]), dshape) + + +def _unfold_axes(data: torch.Tensor, ds: list[int], keep_no: int) -> torch.Tensor: + return torch.reshape(data, ds[:-keep_no] + list(data.shape[-keep_no:])) + + +def _preprocess_coeffs(coeffs, ndim: int, axes, add_channel_dim: bool = False): + if isinstance(axes, int): + axes = (axes,) + torch_dtype = _check_if_tensor(coeffs[0]).dtype + if not _is_dtype_supported(torch_dtype): + raise ValueError(f"Input dtype {torch_dtype} not supported") + if ndim <= 0: + raise ValueError("Number of dimensions must be positive") + if tuple(axes) != tuple(range(-ndim, 0)): + if len(axes) != ndim: + raise ValueError(f"{ndim}D transforms work with {ndim} axes.") + else: + swap_fn = partial(_swap_axes, axes=axes) + coeffs = _coeff_tree_map(coeffs, swap_fn) + ds = list(coeffs[0].shape) + if len(ds) < ndim: + raise ValueError(f"At least {ndim} input dimensions required.") + elif len(ds) == ndim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.unsqueeze(0)) + elif len(ds) > ndim + 1: + coeffs = _coeff_tree_map(coeffs, lambda t: _fold_axes(t, ndim)[0]) + if add_channel_dim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.unsqueeze(1)) + return coeffs, ds + + +def _postprocess_coeffs(coeffs, ndim: int, ds: list[int], axes): + if isinstance(axes, int): + axes = (axes,) + if ndim <= 0: + raise ValueError("Number of dimensions must be positive") + if len(ds) < ndim: + raise ValueError(f"At least {ndim} input dimensions required.") + elif len(ds) == ndim: + coeffs = _coeff_tree_map(coeffs, lambda x: x.squeeze(0)) + elif len(ds) > ndim + 1: + unfold_axes_fn = partial(_unfold_axes, ds=ds, keep_no=ndim) + coeffs = _coeff_tree_map(coeffs, unfold_axes_fn) + if tuple(axes) != tuple(range(-ndim, 0)): + if len(axes) != ndim: + raise ValueError(f"{ndim}D transforms work with {ndim} axes.") + else: + undo_swap_fn = partial(_undo_swap_axes, axes=axes) + coeffs = _coeff_tree_map(coeffs, undo_swap_fn) + return coeffs + + +def _postprocess_tensor( + data: torch.Tensor, ndim: int, ds: list[int], axes: Union[tuple[int, ...], int] +) -> torch.Tensor: + return _postprocess_coeffs(coeffs=[data], ndim=ndim, ds=ds, axes=axes)[0] + + +def _get_filter_tensors( + wavelet: Union[Wavelet, str], flip: bool, device: torch.device, dtype: torch.dtype +) -> WaveletTensorTuple: + wavelet = _as_wavelet(wavelet) + if flip: + filters = WaveletTensorTuple( + torch.tensor(wavelet.rec_lo, device=device, dtype=dtype), + torch.tensor(wavelet.rec_hi, device=device, dtype=dtype), + torch.tensor(wavelet.dec_lo, device=device, dtype=dtype), + torch.tensor(wavelet.dec_hi, device=device, dtype=dtype), + ) + else: + filters = WaveletTensorTuple.from_wavelet(wavelet, dtype=dtype) + filters = WaveletTensorTuple( + filters.dec_lo.to(device), + filters.dec_hi.to(device), + filters.rec_lo.to(device), + filters.rec_hi.to(device), + ) + return filters + + +def _adjust_padding_at_reconstruction(tensor_len: int, coeff_len: int, padr: int, padl: int) -> tuple[int, int]: + if 2 * coeff_len - tensor_len == 1: + padr += 1 + elif 2 * coeff_len - tensor_len != 0: + raise ValueError("incorrect padding") + return padr, padl + + +def _construct_2d_filt(lo: torch.Tensor, hi: torch.Tensor) -> torch.Tensor: + ll = _outer(lo, lo) + lh = _outer(hi, lo) + hl = _outer(lo, hi) + hh = _outer(hi, hi) + filt = torch.stack([ll, lh, hl, hh], 0) + filt = filt.unsqueeze(1) + return filt + + +def waverec2d( + coeffs: WaveletCoeff2d, + wavelet: Union[Wavelet, str], + axes: tuple[int, int] = (-2, -1), +) -> torch.Tensor: + coeffs, ds = _preprocess_coeffs(coeffs, ndim=2, axes=axes) + torch_device, torch_dtype = _check_same_device_dtype(coeffs) + + _, _, rec_lo, rec_hi = _get_filter_tensors(wavelet, flip=False, device=torch_device, dtype=torch_dtype) + filt_len = rec_lo.shape[-1] + rec_filt = _construct_2d_filt(lo=rec_lo, hi=rec_hi) + + res_ll = coeffs[0] + for c_pos, coeff_tuple in enumerate(coeffs[1:]): + if not isinstance(coeff_tuple, tuple) or len(coeff_tuple) != 3: + raise ValueError(f"Unexpected detail coefficient type: {type(coeff_tuple)}. Must be a 3-tuple.") + + curr_shape = res_ll.shape + for coeff in coeff_tuple: + if coeff.shape != curr_shape: + raise ValueError("All coefficients on each level must have the same shape") + + res_lh, res_hl, res_hh = coeff_tuple + res_ll = torch.stack([res_ll, res_lh, res_hl, res_hh], 1) + res_ll = torch.nn.functional.conv_transpose2d(res_ll, rec_filt, stride=2).squeeze(1) + + padl = (2 * filt_len - 3) // 2 + padr = (2 * filt_len - 3) // 2 + padt = (2 * filt_len - 3) // 2 + padb = (2 * filt_len - 3) // 2 + if c_pos < len(coeffs) - 2: + padr, padl = _adjust_padding_at_reconstruction( + res_ll.shape[-1], coeffs[c_pos + 2][0].shape[-1], padr, padl + ) + padb, padt = _adjust_padding_at_reconstruction( + res_ll.shape[-2], coeffs[c_pos + 2][0].shape[-2], padb, padt + ) + + if padt > 0: + res_ll = res_ll[..., padt:, :] + if padb > 0: + res_ll = res_ll[..., :-padb, :] + if padl > 0: + res_ll = res_ll[..., padl:] + if padr > 0: + res_ll = res_ll[..., :-padr] + + res_ll = _postprocess_tensor(res_ll, ndim=2, ds=ds, axes=axes) + return res_ll diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..6eae1f779b81e883f1dd64e3a4fca859391836c5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/__init__.py @@ -0,0 +1,23 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from peft.utils import register_peft_method + +from .config import XLoraConfig +from .model import XLoraModel + + +__all__ = ["XLoraConfig", "XLoraModel"] + +register_peft_method(name="xlora", config_cls=XLoraConfig, model_cls=XLoraModel) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/classifier.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/classifier.py new file mode 100644 index 0000000000000000000000000000000000000000..1ccf9edf9db3178ba9dc4dd3e07989251a676cb8 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/classifier.py @@ -0,0 +1,195 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import builtins +from typing import Optional, Union + +import torch +import torch.nn as nn + +from .config import XLoraConfig + + +Number = Union[builtins.int, builtins.float, builtins.bool] + + +class TemperatureScaledSoftmax(nn.Module): + def __init__(self, temperature=1.0): + super().__init__() + self.temperature = temperature + self.softmax = nn.Softmax(dim=-1) + + def forward(self, logits): + # Scale logits by the temperature + scaled_logits = logits / self.temperature + # Apply softmax to the scaled logits + return self.softmax(scaled_logits) + + +class XLoraClassifier(nn.Module): + """ + A classifier to select LoRA layers for XLora. + """ + + def __init__( + self, + model: nn.Module, # PeftModel + config: XLoraConfig, + n_classes: int, + n_layers: int, + device: torch.device, + ): + """ + Construct an X-LoRA classifier from a model, config and some metadata. Note that n_layers is the number of LoRA + adapter layers, not the number of model layers. + """ + super().__init__() + + self.n_classes = n_classes + self.n_layers = n_layers + self.config = config + self.log_scalings = [] + self.softmax = TemperatureScaledSoftmax(temperature=self.config.softmax_temperature) + self.override_scaling_pass_value: Number = config.scaling_pass_value + + self.scalings_logging = False + + self.dtype = next(model.parameters()).dtype + add_dropout = config.xlora_dropout_p > 0.0 + + layers = [] + if self.config.xlora_depth == 1: + if config.layerwise_scalings: # bias=False if we have just one layer + last = nn.Linear(config.hidden_size, n_classes * n_layers, bias=True).to(device).to(self.dtype) + else: + last = nn.Linear(config.hidden_size, n_classes, bias=True).to(device).to(self.dtype) + else: + if self.config.xlora_depth <= 0: + raise ValueError("X-LoRA depth must be strictly positive.") + + layers.append(nn.Linear(config.hidden_size, config.xlora_size, bias=True).to(device).to(self.dtype)) + + layers.append(nn.ReLU()) + if add_dropout: + layers.append(nn.Dropout(p=config.xlora_dropout_p)) + + for _ in range(config.xlora_depth - 2): + layers.append(nn.Linear(config.xlora_size, config.xlora_size, bias=True).to(device).to(self.dtype)) + + layers.append(nn.ReLU()) + if add_dropout: + layers.append(nn.Dropout(p=config.xlora_dropout_p)) + + if config.layerwise_scalings: + last = nn.Linear(config.xlora_size, n_classes * n_layers, bias=True).to(device).to(self.dtype) + else: + last = nn.Linear(config.xlora_size, n_classes, bias=True).to(device).to(self.dtype) + self.layers = nn.Sequential(*layers, last) + + def make_dummy_scalings( + self, + input_ids: Optional[torch.LongTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + *args, + **kwargs, + ) -> torch.Tensor: + """ + Make some dummy scalings for the scalings pass (the one to get the logits for the X-LoRA classifier). These are + of shape (batch_size, seq_len, n_layers, n_classes) and filled with the override scalings pass value. Note that + n_layers is the number of LoRA adapter layers, not the number of model layers. + """ + if input_ids is not None: + batch_size = input_ids.shape[0] + device = input_ids.device + seq_len = input_ids.shape[1] + else: + batch_size = inputs_embeds.shape[0] + device = inputs_embeds.device + seq_len = inputs_embeds.shape[1] + + return torch.full( # type: ignore + (batch_size, seq_len, self.n_layers, self.n_classes), + self.override_scaling_pass_value, + ).to(device=device, dtype=self.dtype) + + def forward( + self, + result, + input_ids: Optional[torch.LongTensor] = None, + inputs_embeds: Optional[torch.FloatTensor] = None, + *args, + **kwargs, + ) -> torch.Tensor: + """ + Using the hidden states of the model, predict `n_classes` LoRA alpha values. Returns the scalings. + """ + if input_ids is not None: + batch_size = input_ids.shape[0] + seq_len = input_ids.shape[1] + else: + batch_size = inputs_embeds.shape[0] + seq_len = inputs_embeds.shape[1] + + hidden_states = result.hidden_states # type: ignore + + hidden_state = hidden_states[-1] # Get the last hidden state + + ### Classifier run + # hidden_state=[batch_size, seq_len, hidden_size] + logits = self.layers.forward(hidden_state) + + ### Repeat to make layerwise scalings + ### If layerwise_scalings=False, then the classifier only outputs logits which are not layer-wise. + ### So, we expand them to the correct shape. + if not self.config.layerwise_scalings: + logits = logits.unsqueeze(2) + logits = logits.expand(-1, -1, self.n_layers, -1) + + ### Classifier run + + scalings = logits.reshape(batch_size, seq_len, self.n_layers, self.n_classes) + # scalings = [batch_size, seq_len, n_layers, n_classes] + + if self.config.enable_softmax: + scalings = self.softmax(scalings) + + if self.scalings_logging: + self.log_scalings.append(scalings) + + return scalings + + def _get_bucketed_scalings(self) -> dict[int, tuple[list[int], list[torch.Tensor]]]: + """ + Returns bucketed scalings, bucketed by seq_len. Each value consists of the positions (the first) and the + associated tensors. The positions are paired with the associated tensors and give the position in the scaling + log. Each scaling is a tensor of shape (batch_size, seq_len, n_layers, n_classes)). + """ + seqlens_map: dict[int, tuple[list[int], list[torch.Tensor]]] = {} + for i, scaling in enumerate(self.log_scalings): + seq_len = scaling.shape[1] + if seq_len not in seqlens_map: + seqlens_map[seq_len] = ([i], [scaling]) + else: + seqlens_map[seq_len][0].append(i) + seqlens_map[seq_len][1].append(scaling) + + return seqlens_map + + def _set_override_scaling_pass_value(self, value: Union[Number, None]): + if value is None: + self.override_scaling_pass_value = 1 / self.n_classes + else: + self.override_scaling_pass_value = value + self.config.scaling_pass_value = self.override_scaling_pass_value diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/config.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/config.py new file mode 100644 index 0000000000000000000000000000000000000000..9cdb0f6e49f367c640ef4abf14e29b3b60f22fa6 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/config.py @@ -0,0 +1,102 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import warnings +from dataclasses import dataclass +from typing import Optional + +from peft.config import PeftConfig +from peft.utils.peft_types import PeftType + + +@dataclass +class XLoraConfig(PeftConfig): + r""" + This is the configuration class to store the configuration of a `XLoraModel`. When the config is reloaded, the + paths of the `adapters` field is disregarded in favor of the saved adapters. As such, only the keys matter during + loading. + + Args: + hidden_size (`int`): + Hidden size of the base model. + adapters (`dict`): + Mapping of adapter names to the LoRA adapter id, as per PeftModel.load_adapter. *They will be automatically + loaded*, to use as LoRA experts. When using from_pretrained, pass the new adapters dict as a keyword + argument. + enable_softmax (`bool`, *optional*, defaults to `True`): + Enable softmax application for the X-LoRA classifier. + enable_softmax_topk (`bool`, *optional*, defaults to `False`): + Enable softmax application for the top-k LoRA adapters. Mutually exclusive to `enable_softmax` and must + only be set if `top_k_lora` is. + softmax_temperature (`float`, *optional*, defaults to 1.0): + Softmax temperature, lower yields sharper predictions + layerwise_scalings (`bool`, *optional*, defaults to `False`): + If True, generate scalings for each LoRA adapter (each layer). If this is False, then scalings will be + broadcasted, the same, to each layer. + top_k_lora (`int`, *optional*, defaults to None): + Sparsely select the top_k LoRA experts instead of the default dense method. + xlora_depth (`int`, *optional*, defaults to 1): + Depth of the X-LoRA classifier. + xlora_size (`int`, *optional*, defaults to 2048): + Hidden size of the X-LoRA classifier, irrelevant if `xlora_depth=1`. + xlora_dropout_p (`float`, *optional*, defaults to 0.2): + Dropout probability of the X-LoRA classifier, irrelevant if `xlora_depth=1`. + use_trainable_adapters (`bool`, *optional*, defaults to False): + Make the adapters trainable. + scaling_pass_value (`float`, *optional*, defaults to 0): + Scaling pass value. + global_scaling_weight (`float`, *optional*, defaults to 1): + Weight to multiply output of each LoRA adapter by. + """ + + hidden_size: int = None # type: ignore + adapters: dict[str, str] = None # type: ignore + enable_softmax: bool = True + enable_softmax_topk: bool = False + layerwise_scalings: bool = False + xlora_depth: int = 1 + xlora_size: int = 2048 + xlora_dropout_p: float = 0.2 + use_trainable_adapters: bool = False + softmax_temperature: float = 1.0 + top_k_lora: Optional[int] = None + scaling_pass_value: float = 0.0 + global_scaling_weight: float = 1.0 + + def __post_init__(self): + super().__post_init__() + self.peft_type = PeftType.XLORA + + if self.hidden_size is None: + warnings.warn( + "No value was provided for `hidden_size`. This will be set to 4096 by default, please ensure that this is correct." + ) + self.hidden_size = 4096 + if self.adapters is None: + warnings.warn( + "No value was provided for for `adapters`. This will be set to empty, please ensure that this is correct." + ) + self.adapters = {} + + if self.enable_softmax_topk and self.top_k_lora is None: + warnings.warn("`enable_softmax_topk` enabled `top_k_lora` is not set") + + if self.enable_softmax_topk and self.enable_softmax: + warnings.warn( + "`enable_softmax_topk` and `enable_softmax` are both enabled. This will result in worse performance." + ) + + if self.top_k_lora is not None and self.top_k_lora < 1: + warnings.warn("`top_k_lora` value must be at least 1.") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/layer.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/layer.py new file mode 100644 index 0000000000000000000000000000000000000000..c3be6bcb5c23a986dfaac38e5cf6c303a6ee16b5 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/layer.py @@ -0,0 +1,237 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +from collections.abc import Callable +from typing import Any, Optional + +import torch +import torch.nn as nn +from torch import Tensor + +from peft.tuners import lora + +from .config import XLoraConfig + + +class XLoraLayer: + """ + A XLoraLayer wraps any LoraLayer and performs the XLora operation on the LoRA adaptors specified. Its primary API + is the forward method, which uses the scalings to execute the XLora algorithm. + """ + + def __init__( + self, + model: nn.Module, # XLoraModel + target: lora.LoraLayer, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + self.model = model + self.target_forward = target_forward + self.target = target + self.layer_number = layer_number + self.config = config + + """ + Apply the scalings for the adapter. + """ + + @staticmethod + def apply_scalings_to_x(x: torch.Tensor, scalings_layer: torch.Tensor, adapter: int) -> torch.Tensor: + # scalings_layer = [batch_size, seq_len, n_classes] + scalings = scalings_layer[:, :, adapter].unsqueeze(-1) + # scalings_layer = [batch_size, seq_len, 1] + return x * scalings + + """ + Get the scalings for this layer, potentially applying topk and topk+softmax. This is called before + `apply_scalings_to_x` + """ + + def get_maybe_topk_scalings(self, scalings) -> torch.Tensor: + # xlora_scalings = [batch_size, seq_len, n_classes] + xlora_scalings: Tensor = scalings[:, :, self.layer_number, :] # type: ignore + + if self.config.top_k_lora is not None: + _, topk_indices = torch.topk(xlora_scalings, k=self.config.top_k_lora, dim=-1) + + # Mask the topk to True, the rest to False + mask = torch.zeros_like(xlora_scalings, dtype=torch.bool) + mask.scatter_(-1, topk_indices, True) + + xlora_scalings = xlora_scalings * mask.to(xlora_scalings.dtype) + + # Apply per-token normalization to the xLoRA scaling factors using a softmax + if self.config.enable_softmax_topk: + nonzero_mask = xlora_scalings != 0 + full = xlora_scalings.masked_fill(~nonzero_mask, float("-inf")) + new_scalings = torch.softmax(full, dim=-1) + xlora_scalings = new_scalings.masked_fill(~nonzero_mask, 0.0) + + return xlora_scalings + + +class XLoraLinearLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Linear, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + previous_dtype = x.dtype + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_A.keys(): + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora[active_adapter]: + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + lora_A = self.target.lora_A[active_adapter] + lora_B = self.target.lora_B[active_adapter] + dropout = self.target.lora_dropout[active_adapter] + scaling = self.target.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) # type: ignore + if scalings is not None: + x_mod = self.apply_scalings_to_x(x, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + x_mod = x + scaling_weight = 1 + result += lora_B(lora_A(dropout(x_mod))) * scaling * scaling_weight + + result = result.to(previous_dtype) + return result + + +class XLoraEmbeddingLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Embedding, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Some embedding layers (e.g., Gemma3TextScaledWordEmbedding) apply scaling in their forward method. + # Since base_layer(x) already includes this scaling, we need to apply it to X-LoRA contributions too. + embed_scale = self.target._get_embed_scale() + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_embedding_A: + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora.get(active_adapter, False): + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + embedding_A = self.target.lora_embedding_A[active_adapter].T + embedding_B = self.target.lora_embedding_B[active_adapter].T + scaling = self.target.scaling[active_adapter] + after_A = self.target._embed(x, embedding_A) # type: ignore + if scalings is not None: + after_A_mod = self.apply_scalings_to_x(after_A, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + after_A_mod = after_A + scaling_weight = 1 + + adapter_output = (after_A_mod @ embedding_B) * scaling * scaling_weight + + # Apply embed_scale to match the base layer's scaling + if embed_scale is not None: + adapter_output = adapter_output * embed_scale.to(adapter_output.dtype) + + result += adapter_output + + return result + + +class XLoraConv2dLayer(XLoraLayer): + def __init__( + self, + model: nn.Module, + target: lora.Conv2d, + target_forward: Callable[..., Any], + layer_number: int, + config: XLoraConfig, + ) -> None: + super().__init__(model, target, target_forward, layer_number, config) + + def forward(self, x: Tensor, *args: Any, scalings: Optional[Tensor] = None, **kwargs: Any) -> Tensor: + """ + This method is designed to be a drop-in-replacement for the LoRA layers' .forward method. To use it, a bound + method must be created (bound to an instance of the XLoraLayer class). + """ + + previous_dtype = x.dtype + + if scalings is not None: + xlora_scalings = self.get_maybe_topk_scalings(scalings) + + result = self.target.base_layer(x, *args, **kwargs) + + # Ignore if disabled. We want to make sure this is always run. + if not self.target.merged: + for adapter_n, active_adapter in enumerate(self.target.active_adapters): + if active_adapter not in self.target.lora_A.keys(): + continue + # TODO: implement X-LoRA with Lora+Dora layers + if self.target.use_dora[active_adapter]: + raise ValueError("X-LoRA currently does not support LoRA layers with DoRA") + lora_A = self.target.lora_A[active_adapter] + lora_B = self.target.lora_B[active_adapter] + dropout = self.target.lora_dropout[active_adapter] + scaling = self.target.scaling[active_adapter] + x = x.to(lora_A.weight.dtype) # type: ignore + if scalings is not None: + x_mod = self.apply_scalings_to_x(x, xlora_scalings, adapter_n) + scaling_weight = self.config.global_scaling_weight + else: + x_mod = x + scaling_weight = 1 + result += lora_B(lora_A(dropout(x_mod))) * scaling * scaling_weight + + result = result.to(previous_dtype) + return result diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/model.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/model.py new file mode 100644 index 0000000000000000000000000000000000000000..25e0902bfd0ea2580ee790116f2e5ffb1c1abd32 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/tuners/xlora/model.py @@ -0,0 +1,524 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +from contextlib import contextmanager +from functools import partial +from typing import Optional, Union + +import torch +import torch.nn as nn + +from peft.tuners.lora.layer import LoraLayer +from peft.tuners.lora.model import LoraModel +from peft.tuners.tuners_utils import BaseTuner +from peft.utils.constants import DUMMY_TARGET_MODULES +from peft.utils.save_and_load import set_peft_model_state_dict + +from .. import lora +from .classifier import XLoraClassifier +from .config import XLoraConfig +from .layer import XLoraConv2dLayer, XLoraEmbeddingLayer, XLoraLinearLayer + + +def convert_layers_to_xlora( + base: nn.Module, # PeftModel + xloramodel: nn.Module, # XLoraModel + config: XLoraConfig, +) -> tuple[int, torch.device | None]: + """ + Returns the number of swapped layers. + """ + total_swapped = 0 + all_layers = [] + + device = None + for module in base.modules(): + # Check the exact type because classes like OPTLearnedPositionalEmbedding inherit from nn.Embedding + if isinstance(module, lora.Linear): + device = module.lora_A[next(iter(module.lora_A))].weight.device + new_layer = XLoraLinearLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + elif isinstance(module, lora.Embedding): + device = module.lora_embedding_A[next(iter(module.lora_embedding_A))].device + new_layer = XLoraEmbeddingLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + elif isinstance(module, lora.Conv2d): + device = module.lora_A[next(iter(module.lora_A))].weight.device + new_layer = XLoraConv2dLayer( + model=xloramodel, + target=module, + target_forward=module.forward, + layer_number=total_swapped, + config=config, + ) + all_layers.append(new_layer) + module.forward = new_layer.forward # type: ignore[method-assign] + total_swapped += 1 + + return (total_swapped, device) + + +def _load_adapter_into_lora_model( + lora_model: LoraModel, + adapter_name: str, + model_id: str, + torch_device: Optional[str] = None, + ephemeral_gpu_offload: bool = False, + autocast_adapter_dtype: bool = True, + subfolder: Optional[str] = None, + **kwargs, +): + """ + This method emulates the behavior of `PeftModel.from_pretrained`. Updates to `PeftModel.from_pretrained` may need + to be reflected here. + + All params pertain to the adapter (adapter name, model id, `i` is the adapter number in 0 indexing). + """ + from peft.peft_model import PeftModel + from peft.tuners.lora.config import LoraConfig + from peft.utils.other import infer_device + from peft.utils.save_and_load import load_peft_weights + + hf_hub_download_kwargs, kwargs = PeftModel._split_kwargs(kwargs) + if torch_device is None: + torch_device = infer_device() + + if adapter_name not in lora_model.peft_config: + # load the config + lora_peft_config = LoraConfig.from_pretrained( + model_id, + ephemeral_gpu_offload=ephemeral_gpu_offload, + subfolder=subfolder, + **hf_hub_download_kwargs, + ) + lora_peft_config.inference_mode = False + lora_model.peft_config[adapter_name] = lora_peft_config + lora_model.inject_adapter(lora_model.model, adapter_name) + + adapter_weights = load_peft_weights(model_id, device=torch_device, subfolder=subfolder, **hf_hub_download_kwargs) + new_adapter_weights = {} + # Rework the keys to contain the adapter numbers + for old_key in adapter_weights.keys(): + key: str = old_key + # Remove all the prefixes until we have model.<...> + while not (key.startswith("model.") and not key.startswith("model.model.")): + key = key[key.find(".") + 1 :] + # We always want model.model + key = "model." + key + new_adapter_weights[key] = adapter_weights[old_key] + + # load the weights into the model + ignore_mismatched_sizes = kwargs.get("ignore_mismatched_sizes", False) + load_result = set_peft_model_state_dict( + lora_model, + new_adapter_weights, + adapter_name=adapter_name, + ignore_mismatched_sizes=ignore_mismatched_sizes, + ) + if len(load_result.unexpected_keys) > 0: + raise ValueError( + f"Got unexpected keys! Please raise an issue and tag @EricLBuehler.\n\nunexpected_keys={load_result.unexpected_keys}" + ) + + if hasattr(lora_model, "_cast_adapter_dtype"): + lora_model._cast_adapter_dtype(adapter_name=adapter_name, autocast_adapter_dtype=autocast_adapter_dtype) + + +class XLoraModel(BaseTuner): + """ + Creates an X-LoRA (Mixture of LoRA experts), model from a pretrained transformers model. Currently, this X-LoRA + implementation only works with models with a transformer architecture. + + The method is described in detail in https://huggingface.co/papers/2402.07148. + + Args: + model ([`torch.nn.Module`]): The model to be adapted. + config ([`XLoraConfig`]): The configuration of the Lora model. + adapter_name (`str`): The name of the adapter, does not affect the LoRA adapter names. + + Returns: + `torch.nn.Module`: The X-LoRA model. + + Example: + ```py + >>> from transformers import AutoModelForCausalLM, AutoConfig, BitsAndBytesConfig + >>> from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training + + >>> model_config = AutoConfig.from_pretrained("mistralai/Mistral-7B-Instruct-v0.1") + >>> config = XLoraConfig( + ... task_type="CAUSAL_LM", + ... hidden_size=model_config.hidden_size, + ... xlora_depth=4, + ... adapters={ + ... "adapter_1": "./path/to/the/checkpoint/", + ... "adapter_2": "./path/to/the/checkpoint/", + ... "adapter_n": "./path/to/the/checkpoint/", + ... }, + ... ) + >>> int8_config = BitsAndBytesConfig(load_in_8bit=True) + >>> model = AutoModelForCausalLM.from_pretrained( + ... "mistralai/Mistral-7B-Instruct-v0.1", + ... trust_remote_code=True, + ... attn_implementation="flash_attention_2", + ... device_map="cuda:0", + ... torch_dtype=torch.bfloat16, + ... quantization_config=int8_config, + ... ) + >>> model = prepare_model_for_kbit_training(4) + >>> xlora_model = get_peft_model(model, config) + ``` + """ + + def __init__( + self, + model: nn.Module, + config: Union[dict[str, XLoraConfig], XLoraConfig], + adapter_name: str, + torch_device: Optional[str] = None, + ephemeral_gpu_offload: bool = False, + autocast_adapter_dtype: bool = True, + **kwargs, + ) -> None: + """ + Create a new X-LoRA model + + Args: + model (`nn.Module`): + Base model to apply X-LoRA to. + config: ([`XLoraConfig`]): + X-LoRA configuration object. + adapter_name: (`str`): + Adapter name for the X-LoRA adapter. + torch_device (`str`, *optional*, defaults to None): + (For loading the LoRA adapters) The device to load the adapter on. If `None`, the device will be + inferred. + ephemeral_gpu_offload (`bool`, *optional*, defaults to `False`): + (For loading the LoRA adapters) Whether to use ephemeral GPU offloading for partially loaded modules. + Defaults to `False`. + autocast_adapter_dtype (`bool`, *optional*, defaults to `True`): + (For loading the LoRA adapters) Whether to autocast the adapter dtype. Defaults to `True`. Right now, + this will only cast adapter weights using float16 and bfloat16 to float32, as this is typically + required for stable training, and only affect select PEFT tuners. + kwargs: (`optional`): + (For loading the LoRA adapters) Additional arguments to modify the way the adapter is loaded, e.g. the + token for Hugging Face Hub. + """ + + nn.Module.__init__(self) + + if isinstance(config, dict): + conf = config[adapter_name] + else: + conf = config + + # Create an empty LoraModel + base_lora_config = copy.copy(conf) + base_lora_config.target_modules = DUMMY_TARGET_MODULES + # Imitate a LoraConfig, fields might need to be updated if LoraConfig is updated + base_lora_config.layer_replication = None + base_lora_config.bias = "none" + lora_model = LoraModel(model, base_lora_config, adapter_name) + + self.xlora_config = conf + self.lora_model = lora_model + + peft_config = conf + + if hasattr(model.config, "use_cache") and model.config.use_cache: + raise ValueError("`use_cache` must be False") + + adapters_items = peft_config.adapters.items() + if hasattr(self.xlora_config, "_subfolders"): + adapters_items = zip(peft_config.adapters.items(), self.xlora_config._subfolders) + else: + adapters_items = peft_config.adapters.items() + + if hasattr(self.xlora_config, "_subfolders"): + for i, (_adapter_name, model_id), subfolder in enumerate(adapters_items): + _load_adapter_into_lora_model( + lora_model=self.lora_model, + adapter_name=str(i), + model_id=model_id, + torch_device=torch_device, + ephemeral_gpu_offload=ephemeral_gpu_offload, + autocast_adapter_dtype=autocast_adapter_dtype, + subfolder=subfolder, + **kwargs, + ) + else: + for i, (_adapter_name, model_id) in enumerate(adapters_items): + _load_adapter_into_lora_model( + lora_model=self.lora_model, + adapter_name=str(i), + model_id=model_id, + torch_device=torch_device, + ephemeral_gpu_offload=ephemeral_gpu_offload, + autocast_adapter_dtype=autocast_adapter_dtype, + subfolder=None, + **kwargs, + ) + + self.lora_model.set_adapter(list(peft_config.adapters.keys())) + + self._maybe_freeze_all_adapters() + + total_swapped, device = convert_layers_to_xlora( + model, + self, + peft_config, + ) + + n_classes = len(peft_config.adapters) + xlora_classifier = XLoraClassifier(model, peft_config, n_classes, total_swapped, device) + + # Setup the model internal state + self.internal_xlora_classifier = xlora_classifier + self.internal_xlora_scalings = None # type: ignore + # Controlled by enable_adapter_layers or disable_adapter_layers + self.disabled = False + + def _maybe_freeze_all_adapters(self): + self.eval() + if not self.xlora_config.use_trainable_adapters: + for name, param in self.named_parameters(): + if "lora_" in name: + param.requires_grad = False + + def generate(self, *args, **kwargs): + kwargs["use_cache"] = False + res = self.lora_model.generate(*args, **kwargs) # type: ignore + # This is necessary because we use PeftModel.disable_adapter() which reenables the adapters + self._maybe_freeze_all_adapters() + return res + + @contextmanager + def _enable_peft_forward_hooks(self, *generate_args, **generate_kwargs): + def scalings_injection_hook(target, args, kwargs, scalings): + # pre-forward hook to inject the adapter_names argument when using mixed adapter batches inference + kwargs["scalings"] = scalings + return args, kwargs + + hook_handles = [] + + def _pre_forward(module, *args, **kwargs): + # =========================== Forward pass with "dummy" scalings ================== + nonlocal hook_handles + + args_real = args[0] + kwargs_real = args[1] + kwargs_real.update(kwargs) + + dummy_scalings = self.internal_xlora_classifier.make_dummy_scalings(*args_real, **kwargs_real) + + for module in self.modules(): + if isinstance(module, LoraLayer): + pre_forward = partial(scalings_injection_hook, scalings=dummy_scalings) + existing_hooks = getattr(module, "_forward_pre_hooks", {}) + if any(val is scalings_injection_hook for val in existing_hooks.values()): + # When calling generate, module.forward is called multiple times inside the forward hook + # context, resulting in multiple hooks being registered. Therefore, we check if the hooks is + # already present and skip it in that case. + continue + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + with torch.no_grad(): + self.lora_model.disable_adapter_layers() + + try: + scaling_pass_kwargs = kwargs_real.copy() + scaling_pass_kwargs["output_hidden_states"] = True + scaling_pass_kwargs["return_dict"] = True + try: + base_output = self.lora_model.model.forward(*args_real, **scaling_pass_kwargs) + finally: + # Clean everything up + for handle in hook_handles: + handle.remove() + finally: + self.lora_model.enable_adapter_layers() + + xlora_scalings = self.internal_xlora_classifier(result=base_output, *args_real, **kwargs_real) + # Store computed scalings to fix get_latest_scalings() returning None + self.internal_xlora_scalings = xlora_scalings + + # =========================== Real forward pass with calculated scalings ================== + + hook_handles = [] + for module in self.modules(): + if isinstance(module, LoraLayer): + pre_forward = partial(scalings_injection_hook, scalings=xlora_scalings) + handle = module.register_forward_pre_hook(pre_forward, with_kwargs=True) + hook_handles.append(handle) + + if not self.disabled: + forward_handle = self.lora_model.model.register_forward_pre_hook(_pre_forward, with_kwargs=True) + + # Run the forward pass: first the scaling pass in the hook, and then with the base model + try: + yield + finally: + if not self.disabled: + for handle in hook_handles: + handle.remove() + forward_handle.remove() + + def __getattr__(self, name: str): + """Forward missing attributes to the wrapped module.""" + try: + return super().__getattr__(name) # defer to nn.Module's logic + except AttributeError: + if name == "lora_model": # see #1892: prevent infinite recursion if class is not initialized + raise + return getattr(self.lora_model, name) + + @staticmethod + def _prepare_adapter_config(peft_config, _model_config): + # Handle X-LoRA case + return peft_config + + """ + Does nothing. X-LoRA needs adapters to be frozen. + """ + + def _mark_only_adapters_as_trainable(self) -> None: ... + + """ + This enables the X-LoRA adapter. + """ + + def enable_adapter_layers(self) -> None: + self.disabled = False + + """ + This diasables the X-LoRA adapter. + """ + + def disable_adapter_layers(self) -> None: + self.disabled = True + + def _create_and_replace( + self, + lora_config, + adapter_name, + target, + target_name, + parent, + current_key, + ): + # Does nothing because XLoraModel has no target modules + pass + + @staticmethod + def _check_target_module_exists(lora_config, key): + # Does nothing because XLoraModel has no target modules + return False + + def forward(self, *args, **kwargs): + return self.lora_model.model(*args, **kwargs) + + def set_topk_lora(self, value: Optional[int]): + """ + Sparsely select the specified top_k LoRA experts instead of the default dense method. Set to None to use dense. + This is reflected in the config. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.config.top_k_lora = value + + def set_global_scaling_weight(self, weight: float): + """ + Set the global LoRA weight, a scalar to multiply the output of each LoRA adapter by. This is by default 1. This + is reflected in the config. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.config.global_scaling_weight = weight + + def set_scaling_pass_value(self, value: float | None): + """ + Set the scaling pass value, the value to set the scalings to during the scaling pass. If the value is None, the + scaling pass value will be 1/n where n is the number of adapters. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier._set_override_scaling_pass_value(value) + + def get_global_scaling_weight(self) -> float: + """ + Get the global LoRA weight. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier.config.global_scaling_weight + + def get_latest_scalings(self) -> Optional[torch.Tensor]: + """ + Returns the latest scalings prediction, or None if no scalings have been predicted. The tensor is of shape + (batch_size, seq_len, n_layers, n_classes). + """ + return self.internal_xlora_scalings + + def get_scalings_log(self) -> list[torch.Tensor]: + """ + Returns a shallow (only copying the list itself not the tensors) copy of the list containing the scalings log. + Editing the list does not change the underlying log. The tensors are of shape (batch_size, seq_len, n_layers, + n_classes). The seq_len dim may vary with input dimension. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier.log_scalings.copy() + + def enable_scalings_logging(self): + """ + Enable scalings logging. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.scalings_logging = True + + def disable_scalings_logging(self): + """ + Disable scalings logging, without clearing the log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.scalings_logging = False + + def clear_scalings_log(self): + """ + Clear the scalings log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + classifier.log_scalings.clear() + + def get_bucketed_scalings_log(self) -> dict[int, tuple[list[int], list[torch.Tensor]]]: + """ + Returns bucketed scalings, bucketed by seq_len. Each value consists of the positions (the first) and the + associated tensors. The positions are paired with the associated tensors and give the position in the scaling + log. + """ + classifier: XLoraClassifier = self.internal_xlora_classifier # type: ignore + return classifier._get_bucketed_scalings() diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/__init__.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e96f515e8868d23255b268b897c9ff5fcd08ba9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/__init__.py @@ -0,0 +1,134 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .integrations import map_cache_to_layer_device_map +from .loftq_utils import replace_lora_weights_loftq +from .other import ( + CONFIG_NAME, + INCLUDE_LINEAR_LAYERS_SHORTHAND, + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, + WEIGHTS_NAME, + AuxiliaryTrainingWrapper, + ModulesToSaveWrapper, + TrainableTokensWrapper, + _freeze_adapter, + _get_batch_size, + _get_input_embeddings_name, + _get_submodules, + _is_valid_match, + _prepare_prompt_learning_config, + _set_adapter, + _set_trainable, + bloom_model_postprocess_past_key_value, + cast_mixed_precision_params, + get_gptqmodel_quant_linear, + get_quantization_config, + id_tensor_storage, + infer_device, + prepare_model_for_kbit_training, + set_additional_trainable_modules, + shift_tokens_right, + transpose, +) +from .peft_types import PeftType, TaskType, register_peft_method +from .save_and_load import get_peft_model_state_dict, load_peft_weights, set_peft_model_state_dict +from .warning import PeftWarning + + +__all__ = [ + "CONFIG_NAME", + "INCLUDE_LINEAR_LAYERS_SHORTHAND", + "SAFETENSORS_WEIGHTS_NAME", + "TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING", + "WEIGHTS_NAME", + "AuxiliaryTrainingWrapper", + "ModulesToSaveWrapper", + "PeftType", + "PeftWarning", + "TaskType", + "TrainableTokensWrapper", + "_freeze_adapter", + "_get_batch_size", + "_get_input_embeddings_name", + "_get_submodules", + "_is_valid_match", + "_prepare_prompt_learning_config", + "_set_adapter", + "_set_trainable", + "bloom_model_postprocess_past_key_value", + "cast_mixed_precision_params", + "get_gptqmodel_quant_linear", + "get_peft_model_state_dict", + "get_quantization_config", + "id_tensor_storage", + "infer_device", + "load_peft_weights", + "map_cache_to_layer_device_map", + "prepare_model_for_kbit_training", + "register_peft_method", + "replace_lora_weights_loftq", + "set_additional_trainable_modules", + "set_peft_model_state_dict", + "shift_tokens_right", + "transpose", +] diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/constants.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/constants.py new file mode 100644 index 0000000000000000000000000000000000000000..24f53a9ff0404ef92ef88681833f1f8f398f090f --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/constants.py @@ -0,0 +1,365 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import torch +from transformers import BloomPreTrainedModel + +from ..import_utils import is_transformers_le_4_53 + + +# needed for prefix-tuning of bloom model +def bloom_model_postprocess_past_key_value(past_key_values): + past_key_values = torch.cat(past_key_values) + total_layers, batch_size, num_attention_heads, num_virtual_tokens, head_dim = past_key_values.shape + keys = past_key_values[: total_layers // 2] + keys = keys.transpose(2, 3).reshape( + total_layers // 2, batch_size * num_attention_heads, head_dim, num_virtual_tokens + ) + values = past_key_values[total_layers // 2 :] + values = values.reshape(total_layers // 2, batch_size * num_attention_heads, num_virtual_tokens, head_dim) + + return tuple(zip(keys, values)) + + +# needed for prefix-tuning of StarCoder models +def starcoder_model_postprocess_past_key_value(past_key_values): + result = [] + for k in past_key_values: + k = k[:, :, 0] + k = k.permute([1, 2, 0, 3]) + k = k.reshape(*k.shape[:-2], -1) + result.append(k) + return tuple(result) + + +# TODO: remove this once transformers 4.53 is no longer supported +TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING = {} +if is_transformers_le_4_53: + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING["gpt_bigcode"] = ( + starcoder_model_postprocess_past_key_value + ) + + +if hasattr(BloomPreTrainedModel, "_convert_to_standard_cache"): + # special handling for bloom architecture was fixed in: + # https://github.com/huggingface/transformers/pull/31445 + # the _convert_to_standard_cache method is removed in the PR and thus serves as an indicator + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING["bloom"] = bloom_model_postprocess_past_key_value + + +####################################### +# DEFAULT MAPPINGS FOR TARGET_MODULES # +####################################### + +TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "v"], + "mt5": ["q", "v"], + "bart": ["q_proj", "v_proj"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "blip-2": ["q", "v", "q_proj", "v_proj"], + "opt": ["q_proj", "v_proj"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "xlm-roberta": ["query", "value"], + "electra": ["query", "value"], + "deberta-v2": ["query_proj", "value_proj"], + "deberta": ["in_proj"], + "layoutlm": ["query", "value"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "chatglm": ["query_key_value"], + "gpt_bigcode": ["c_attn"], + "mpt": ["Wqkv"], + "RefinedWebModel": ["query_key_value"], + "RefinedWeb": ["query_key_value"], + "falcon": ["query_key_value"], + "btlm": ["c_proj", "c_attn"], + "codegen": ["qkv_proj"], + "mistral": ["q_proj", "v_proj"], + "mixtral": ["q_proj", "v_proj"], + "stablelm": ["q_proj", "v_proj"], + "phi": ["q_proj", "v_proj", "fc1", "fc2"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], + "rwkv": ["key", "value", "receptance", "output"], + "rwkv7": ["r_proj", "k_proj", "v_proj", "o_proj", "key", "value"], +} + +# target module mappings that are identical to LORA +TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() + +# mappings that are similar to LORA with small changes +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING["gpt_bigcode"] = ["mlp.c_proj"] +TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING["gpt2"] = ["mlp.c_proj"] + +TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING["phi"] = ["q_proj", "v_proj"] + +TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING["phi"] = ["q_proj", "v_proj"] + +TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING["dinov2"] = ["query", "value"] + +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING = TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING.copy() +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING["gpt_bigcode"] = ["mlp.c_proj"] +TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING["gpt2"] = ["mlp.c_proj"] + +# target module mappings that differ from LORA +TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING = { + "llama": ["input_layernorm", "post_attention_layernorm", "norm"], + "bloom": ["input_layernorm", "post_attention_layernorm", "ln_f"], + "llava": [ + "multi_modal_projector", + "input_layernorm", + "post_attention_layernorm", + "norm", + "embed_tokens", + "lm_head", + ], + "t5": ["layer_norm", "final_layer_norm"], + "mt5": ["layer_norm", "final_layer_norm"], + "bart": ["self_attn_layer_norm", "encoder_attn_layer_norm", "final_layer_norm"], + "gpt2": ["ln_1", "ln_2", "ln_f"], + "blip-2": ["layernorm", "LayerNorm", "final_layer_norm", "self_attn_layer_norm"], + "gptj": ["ln_1", "ln_f"], + "falcon": ["input_layernorm", "post_attention_layernorm", "ln_f"], + "mistral": ["input_layernorm", "post_attention_layernorm", "norm"], + "phi": ["input_layernorm", "final_layernorm"], + "gemma": ["input_layernorm", "post_attention_layernorm", "norm"], + "gemma2": [ + "input_layernorm", + "post_attention_layernorm", + "pre_feedforward_layernorm", + "post_feedforward_layernorm", + "norm", + ], + "gemma3_text": [ + "input_layernorm", + "post_attention_layernorm", + "pre_feedforward_layernorm", + "post_feedforward_layernorm", + "norm", + ], + "qwen2": ["post_attention_layernorm"], + "qwen3": ["post_attention_layernorm"], +} + +TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING = { + "t5": ["k", "v", "wo"], + "mt5": ["k", "v", "wi_1"], + "gpt2": ["c_attn", "mlp.c_proj"], + "bloom": ["query_key_value", "mlp.dense_4h_to_h"], + "roberta": ["key", "value", "output.dense"], + "opt": ["q_proj", "k_proj", "fc2"], + "gptj": ["q_proj", "v_proj", "fc_out"], + "gpt_neox": ["query_key_value", "dense_4h_to_h"], + "gpt_neo": ["q_proj", "v_proj", "c_proj"], + "bart": ["q_proj", "v_proj", "fc2"], + "gpt_bigcode": ["c_attn", "mlp.c_proj"], + "llama": ["k_proj", "v_proj", "down_proj"], + "llama4": ["q_proj", "v_proj", "down_proj"], + "mistral": ["k_proj", "v_proj", "down_proj"], + "mixtral": ["k_proj", "v_proj", "w2"], + "bert": ["key", "value", "output.dense"], + "deberta-v2": ["key_proj", "value_proj", "output.dense"], + "deberta": ["in_proj", "output.dense"], + "RefinedWebModel": ["query_key_value", "dense_4h_to_h"], + "RefinedWeb": ["query_key_value", "dense_4h_to_h"], + "falcon": ["query_key_value", "dense_4h_to_h"], + "phi": ["q_proj", "v_proj", "fc2"], + "gemma": ["q_proj", "v_proj", "down_proj"], + "gemma2": ["q_proj", "v_proj", "down_proj"], + "gemma3_text": ["q_proj", "v_proj", "down_proj"], + "qwen2": ["q_proj", "v_proj", "down_proj"], + "qwen3": ["q_proj", "v_proj", "down_proj"], +} + +TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING = { + "t5": ["wo"], + "mt5": [], + "gpt2": ["mlp.c_proj"], + "bloom": ["mlp.dense_4h_to_h"], + "roberta": ["output.dense"], + "opt": ["fc2"], + "gptj": ["fc_out"], + "gpt_neox": ["dense_4h_to_h"], + "gpt_neo": ["c_proj"], + "bart": ["fc2"], + "gpt_bigcode": ["mlp.c_proj"], + "llama": ["down_proj"], + "llama4": ["down_proj"], + "mistral": ["down_proj"], + "mixtral": ["w2"], + "bert": ["output.dense"], + "deberta-v2": ["output.dense"], + "deberta": ["output.dense"], + "RefinedWeb": ["dense_4h_to_h"], + "RefinedWebModel": ["dense_4h_to_h"], + "falcon": ["dense_4h_to_h"], + "phi": ["fc2"], + "gemma": ["down_proj"], + "gemma2": ["down_proj"], + "gemma3_text": ["down_proj"], + "qwen2": ["down_proj"], + "qwen3": ["down_proj"], +} + +TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "k", "v", "o", "wi", "wo"], + "mt5": ["q", "k", "v", "o", "wi_0", "wi_1", "wo"], + "bart": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "key", "value", "dense"], + # "xlm-roberta": ["query", "value"], + # "electra": ["query", "value"], + "deberta-v2": ["query_proj", "key_proj", "value_proj", "dense"], + "gpt_bigcode": ["c_attn"], + "deberta": ["in_proj"], + # "layoutlm": ["query", "value"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING = { + "t5": ["q", "k", "v", "o", "wi", "wo"], + "mt5": ["q", "k", "v", "o", "wi_0", "wi_1", "wo"], + "bart": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gpt2": ["c_attn"], + "bloom": ["query_key_value"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "deberta-v2": ["query_proj", "key_proj", "value_proj", "dense"], + "gpt_bigcode": ["c_attn"], + "deberta": ["in_proj"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +TRANSFORMERS_MODELS_TO_OSF_TARGET_MODULES_MAPPING = { + "llama": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "llama4": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "mistral": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "mixtral": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma2": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gemma3_text": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "qwen2": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "qwen3": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "phi": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "down_proj", "up_proj"], + "gpt2": ["c_attn", "c_proj"], + "bloom": ["query_key_value", "dense_4h_to_h"], + "opt": ["q_proj", "k_proj", "v_proj", "out_proj", "fc1", "fc2"], + "gptj": ["q_proj", "k_proj", "v_proj", "out_proj", "fc_in", "fc_out"], + "gpt_neox": ["query_key_value", "dense_4h_to_h"], + "falcon": ["query_key_value", "dense_4h_to_h"], + "gpt_bigcode": ["c_attn", "c_proj"], +} + +TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING = { + "t5": ["q", "v"], + "mt5": ["q", "v"], + "bart": ["q_proj", "v_proj"], + "gpt2": ["mlp.c_proj"], + "bloom": ["query_key_value"], + "blip-2": ["q", "v", "q_proj", "v_proj"], + "opt": ["q_proj", "v_proj"], + "gptj": ["q_proj", "v_proj"], + "gpt_neox": ["query_key_value"], + "gpt_neo": ["q_proj", "v_proj"], + "bert": ["query", "value"], + "roberta": ["query", "value"], + "xlm-roberta": ["query", "value"], + "electra": ["query", "value"], + "deberta-v2": ["query_proj", "value_proj"], + "deberta": ["in_proj"], + "layoutlm": ["query", "value"], + "llama": ["q_proj", "v_proj"], + "llama4": ["q_proj", "v_proj"], + "chatglm": ["query_key_value"], + "gpt_bigcode": ["mlp.c_proj"], + "mpt": ["Wqkv"], + "RefinedWebModel": ["query_key_value"], + "RefinedWeb": ["query_key_value"], + "falcon": ["query_key_value"], + "codegen": ["qkv_proj"], + "mistral": ["q_proj", "v_proj"], + "mixtral": ["q_proj", "v_proj"], + "stablelm": ["q_proj", "v_proj"], + "phi": ["q_proj", "v_proj", "fc1", "fc2"], + "gemma": ["q_proj", "v_proj"], + "gemma2": ["q_proj", "v_proj"], + "gemma3_text": ["q_proj", "v_proj"], + "qwen2": ["q_proj", "v_proj"], + "qwen3": ["q_proj", "v_proj"], +} + +################## +# MISC CONSTANTS # +################## +WEIGHTS_NAME = "adapter_model.bin" +SAFETENSORS_WEIGHTS_NAME = "adapter_model.safetensors" +CONFIG_NAME = "adapter_config.json" +EMBEDDING_LAYER_NAMES = ["embed_tokens", "lm_head"] +SEQ_CLS_HEAD_NAMES = ["score", "classifier"] +INCLUDE_LINEAR_LAYERS_SHORTHAND = "all-linear" +TOKENIZER_CONFIG_NAME = "tokenizer_config.json" +DUMMY_TARGET_MODULES = "dummy-target-modules" +DUMMY_MODEL_CONFIG = {"model_type": "custom"} + +# If users specify more than this number of target modules, we apply an optimization to try to reduce the target modules +# to a minimal set of suffixes, which makes loading faster. We only apply this when exceeding a certain size since +# otherwise there is no point in optimizing and there is a small chance of bugs in the optimization algorithm, so no +# point in taking unnecessary risks. See #2045 for more context. +MIN_TARGET_MODULES_FOR_OPTIMIZATION = 20 diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/hotswap.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/hotswap.py new file mode 100644 index 0000000000000000000000000000000000000000..2b08c372e132b1084c10df79ab35a42f2cdf19ef --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/hotswap.py @@ -0,0 +1,630 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import math +import warnings +from operator import attrgetter +from typing import Literal, Optional + +import torch + +from peft.config import PeftConfig +from peft.mapping import PEFT_TYPE_TO_CONFIG_MAPPING, PEFT_TYPE_TO_PREFIX_MAPPING +from peft.tuners.lora import Conv2d, Linear, LoraConfig, LoraLayer + +from .other import get_pattern_key, infer_device +from .peft_types import PeftType +from .save_and_load import _insert_adapter_name_into_state_dict, load_peft_weights + + +# so far only LoRA is supported +CONFIG_KEYS_TO_CHECK = {PeftType.LORA: ["use_rslora", "lora_dropout", "alpha_pattern", "use_dora"]} + + +def _update_scaling(lora_module, adapter_name, scaling=None): + """ + Update the value of the scalings of the LoRA module. + + Takes into consideration that scalings can be tensors from prepare_model_for_compiled_hotswap. + """ + if lora_module.scaling[adapter_name] == scaling: + return + + if isinstance(lora_module.scaling[adapter_name], torch.Tensor): + lora_module.scaling[adapter_name].fill_(scaling) + elif isinstance(lora_module.scaling[adapter_name], (float, int)): + lora_module.scaling[adapter_name] = scaling + else: + raise ValueError( + "Something went wrong when trying to set the new scale value, expected to find the old value to be of type " + f"float or torch.Tensor, got {type(lora_module.scaling[adapter_name])} instead." + ) + + +def _convert_scalings_to_tensor(model) -> bool: + """ + Convert the LoRA scaling values into torch.tensors to prevent recompilation if they change. + + Returns: + bool: + Returns `True` if an appropriate adapter was found, else `False`. + """ + found_adapter = False + for module in model.modules(): + if not isinstance(module, LoraLayer): + continue + + found_adapter = True + scaling = module.scaling + for key, val in scaling.items(): + if isinstance(val, float): + # no need to deal with dtype as scalars are coerced + scaling[key] = torch.tensor(val, device=module.weight.device) + elif not isinstance(val, torch.Tensor): + raise ValueError( + "Something went wrong while trying to convert the scalings, expected to find values of type float " + f"but found {type(val)} instead." + ) + return found_adapter + + +def _get_padded_linear(lora_module: torch.nn.Module, target_rank: int, is_lora_A: bool) -> torch.nn.Linear: + """ + Get a new Linear layer for LoRA with padded weights according to the target rank. + + Args: + lora_module (nn.Module): + The LoRA sub-module (e.g. module.lora_A[adapter_name]). + target_rank (int): + The desired rank to pad to. + is_lora_A (bool): + True if this is the LoRA A matrix, False if LoRA B. + + Returns: + nn.Linear: + A newly created and padded Linear layer. If the rank already fit, the original layer is returned. + """ + weight = lora_module.weight + # For LoRA A, the "rank dimension" is weight.size(0) (out_features). + # For LoRA B, it is weight.size(1) (in_features). + original_rank = weight.size(0) if is_lora_A else weight.size(1) + + # If no padding needed + if original_rank == target_rank: + return lora_module + + if original_rank > target_rank: + raise ValueError( + f"Trying to pad the adapter to the target rank {target_rank}, but the original rank is larger " + f"({original_rank}). This is not possible." + ) + + out_features, in_features = weight.shape + + # lora_A and lora_B are always nn.Linear + if is_lora_A: + # LoRA A affects out_features + padded = torch.zeros(target_rank, in_features, device=weight.device, dtype=weight.dtype) + padded[:original_rank, :] = weight + new_layer = torch.nn.Linear(in_features, target_rank, bias=lora_module.bias is not None) + else: + # LoRA B affects in_features + padded = torch.zeros(out_features, target_rank, device=weight.device, dtype=weight.dtype) + padded[:, :original_rank] = weight + new_layer = torch.nn.Linear(target_rank, out_features, bias=lora_module.bias is not None) + + # Sanity check + if new_layer.weight.shape != padded.shape: + raise ValueError( + "Something went wrong when trying to pad the LoRA Linear weights, the new shape should be " + f"{padded.shape} but {new_layer.weight.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + if (lora_module.bias is not None) and (new_layer.bias.shape != lora_module.bias.shape): + raise ValueError( + "Something went wrong when trying to pad the LoRA Linear bias, the new shape should be " + f"{lora_module.bias.shape} but {new_layer.bias.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + + new_layer.weight.data = padded + # Copy bias if present + if lora_module.bias is not None: + new_layer.bias.data = lora_module.bias.data + + return new_layer + + +def _get_padded_conv2d(lora_module: torch.nn.Module, target_rank: int, is_lora_A: bool) -> torch.nn.Conv2d: + """ + Get a new Conv2d layer for LoRA with padded weights according to the target rank. + + Args: + lora_module (nn.Module): + The LoRA sub-module (e.g. module.lora_A[adapter_name]). + target_rank (int): + The desired rank to pad to. + is_lora_A (bool): + True if this is the LoRA A matrix, False if LoRA B. + + Returns: + nn.Conv2d: + A newly created and padded Conv2d layer. If the rank already fit, the original layer is returned. + """ + weight = lora_module.weight + # For Conv2d: [out_channels, in_channels, kernel_height, kernel_width] + out_channels, in_channels, kh, kw = weight.shape + original_rank = out_channels if is_lora_A else in_channels + + if original_rank == target_rank: + return lora_module + + if original_rank > target_rank: + raise ValueError( + f"Trying to pad the adapter to the target rank {target_rank}, but the original rank is larger " + f"({original_rank}). This is not possible." + ) + + # lora_A and lora_B are always nn.Conv2d + if is_lora_A: + # LoRA A affects out_channels + padded = torch.zeros(target_rank, in_channels, kh, kw, device=weight.device, dtype=weight.dtype) + padded[:out_channels, :, :, :] = weight + new_layer = torch.nn.Conv2d( + in_channels, + target_rank, + kernel_size=lora_module.kernel_size, + stride=lora_module.stride, + padding=lora_module.padding, + bias=lora_module.bias is not None, + groups=lora_module.groups, + ) + else: + # LoRA B affects in_channels + padded = torch.zeros(out_channels, target_rank, kh, kw, device=weight.device, dtype=weight.dtype) + padded[:, :in_channels, :, :] = weight + new_layer = torch.nn.Conv2d( + target_rank, + out_channels, + kernel_size=lora_module.kernel_size, + stride=lora_module.stride, + padding=lora_module.padding, + bias=lora_module.bias is not None, + groups=lora_module.groups, + ) + + # Sanity check + if new_layer.weight.shape != padded.shape: + raise ValueError( + "Something went wrong when trying to pad the LoRA weights, the new shape should be " + f"{padded.shape} but {new_layer.weight.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + if (lora_module.bias is not None) and (new_layer.bias.shape != lora_module.bias.shape): + raise ValueError( + "Something went wrong when trying to pad the LoRA Conv2d bias, the new shape should be " + f"{lora_module.bias.shape} but {new_layer.bias.shape} was found. Please open an issue on PEFT " + "(https://github.com/huggingface/peft/issues) and report this error." + ) + + new_layer.weight.data = padded + # Copy bias if present + if lora_module.bias is not None: + new_layer.bias.data = lora_module.bias.data + + return new_layer + + +def _pad_lora_weights(model: torch.nn.Module, target_rank: int) -> bool: + """ + Pad LoRA weights in a model to a target rank while preserving the original behavior. + + Args: + model (nn.Module): The model containing LoRA modules (with lora_A and lora_B). + target_rank (int): The target rank to pad to. + + Returns: + bool: + Returns `True` if an appropriate adapter was found, else `False`. + """ + found_adapter = False + + for module in model.modules(): + # Decide which pad function to call based on module type + if isinstance(module, Linear): + pad_fn = _get_padded_linear + elif isinstance(module, Conv2d): + pad_fn = _get_padded_conv2d + else: + # Skip any other module types + continue + + # Pad LoRA A + for adapter_name, lora_A_module in module.lora_A.items(): + new_layer = pad_fn(lora_A_module, target_rank=target_rank, is_lora_A=True) + module.lora_A[adapter_name] = new_layer + + # Pad LoRA B + for adapter_name, lora_B_module in module.lora_B.items(): + new_layer = pad_fn(lora_B_module, target_rank=target_rank, is_lora_A=False) + module.lora_B[adapter_name] = new_layer + + found_adapter = True + return found_adapter + + +def prepare_model_for_compiled_hotswap( + model: torch.nn.Module, + *, + target_rank: Optional[int] = None, + config: Optional[LoraConfig | dict[str, LoraConfig]] = None, + check_compiled: Literal["error", "warn", "ignore"] = "error", +) -> None: + """ + Helper function that prepares the model so that it can later be compiled and then used with hot-swapping. + + It is necessary to call this function on the model for hot-swapping to work if both of these are true: + + - the different LoRA adapters have different ranks and/or different alpha values (i.e. scalings) + - you plan to torch.compile the model and want to avoid re-compilation + + It is important to call this function *after* the first LoRA adapter has been loaded (i.e. the one that will be + swapped out) but *before* the model is compiled. + + Even with this function, hot-swapping LoRA adapters that target different layers is still not supported. + + Note: This function modifies the model in-place. If you want to restore the model to its initial state, you will + have to reload it. + + Args: + model (`nn.Module`): + The model with the loaded adapter, before compilation. + target_rank (`int`, *optional*): + The target rank to pad the LoRA weights to. Should be the maximum rank among all LoRA adapters that will be + hot-swapped. If not specified, the target ranks will not be changed. + config (`LoraConfig` or `dict[str, LoraConfig]`, *optional*): + Optionally pass the `LoraConfig`s of the LoRA adapters. If passed, the rank in the configs will be updated + to `target_rank`. + check_compiled (`str`, *optional*, defaults to `"error"`): + How to handle the case when the model is already compiled, which should generally be avoided. The options + are: + - "error" (default): raise an error + - "warn": issue a warning + - "ignore": do nothing + + Raises: + ValueError + If the model is already compiled or if no adpater layer was found, raise an error. + + Example: + + ```py + base_model = ... + model = PeftModel.from_pretrained(base_model, path_adapter_0) + # Prepare the model to allow hotswapping even if ranks/scalings of 2nd adapter differ. + # You can skip this step if all ranks and scalings are identical. + prepare_model_for_compiled_hotswap(model, target_rank=highest_lora_rank) + model = torch.compile(model) + # do inference with adapter 0 + # replace the "default" lora adapter with the new one + hotswap_adapter(model, path_adapter_1, adapter_name="default", torch_device=device) + # do inference with adapter 1 + ``` + + """ + is_compiled = hasattr(model, "_orig_mod") or getattr(model, "_compiled_call_impl", False) + if is_compiled: + if check_compiled == "error": + raise ValueError("Call prepare_model_for_compiled_hotswap *before* compiling the model") + elif check_compiled == "warn": + warnings.warn( + "prepare_model_for_compiled_hotswap was called with a model that is already compiled. This will likely " + "result in re-compilation, hurting performance. Call the function before compiling the model." + ) + elif check_compiled != "ignore": + raise ValueError( + f"check_compiles should be one of 'error', 'warn', or 'ignore', got '{check_compiled}' instead." + ) + + conversion_found_adapter = _convert_scalings_to_tensor(model) + if target_rank is not None: + padding_found_adapter = _pad_lora_weights(model, target_rank=target_rank) + else: + padding_found_adapter = False + + if not (conversion_found_adapter or padding_found_adapter): + raise ValueError( + "No adapter layers found on the model, make sure call `prepare_model_for_compiled_hotswap` after loading " + "the first adapter and before loading the second adapter." + ) + + if not config: + return + if target_rank is None: + return + + if not isinstance(config, dict): + # config can be either a PeftConfig, or a dict of PeftConfigs like PeftModel.peft_config + config = {"dummy": config} + + for lora_config in config.values(): + lora_config.r = target_rank + if lora_config.rank_pattern: + for key in lora_config.rank_pattern: + lora_config.rank_pattern[key] = target_rank + + +def hotswap_adapter_from_state_dict( + model: torch.nn.Module, + state_dict: dict[str, torch.Tensor], + adapter_name: str, + config: LoraConfig, + parameter_prefix: str = "lora_", +): + """ + Swap out the adapter weights from the model with the weights from state_dict. + + As of now, only LoRA is supported. + + This is a low-level function that assumes that the adapters have been checked for compatibility and that the + state_dict has been correctly mapped to work with PEFT. For a high level function that performs this work for you, + use `hotswap_adapter` instead. + + Args: + model (`nn.Module`): + The model with the loaded adapter. + state_dict (`dict[str, torch.Tensor]`): + The state dict of the new adapter, which needs to be compatible (targeting same modules etc.). + adapter_name (`str`): + The name of the adapter that should be hot-swapped, e.g. `"default"`. The name will remain the same after + swapping. + config (`LoraConfig`): + The config of the LoRA adapter. This is used to determine the scaling and rank of the adapter. + parameter_prefix (`str`, *optional*, defaults to `"lora_"`) + The prefix used to identify the adapter's keys in the state dict. For LoRA, this would be `"lora_"` (the + default). + + Raises: + RuntimeError + If the old and the new adapter are not compatible, a RuntimeError is raised. + + """ + # Ensure that all the keys of the new adapter correspond exactly to the keys of the old adapter, otherwise + # hot-swapping is not possible + + # _orig_mod is for torch.compile(model) and _compiled_call_impl is for model.compile() (not wrapped) + is_compiled = hasattr(model, "_orig_mod") + is_compiled_inplace = bool(getattr(model, "_compiled_call_impl", None)) + # TODO: there is probably a more precise way to identify the adapter keys + missing_keys = {k for k in model.state_dict() if (parameter_prefix in k) and (adapter_name in k)} + unexpected_keys = [] + + # first: dry run, not swapping anything + for key, new_val in state_dict.items(): + try: + old_val = attrgetter(key)(model) + except AttributeError: + unexpected_keys.append(key) + continue + + if is_compiled: + missing_keys.remove("_orig_mod." + key) + else: + missing_keys.remove(key) + + # Right now, we don't deal with unexpected keys, i.e. if the adapter being swapped in targeting new layers. We could + # probably add LoRA to these layers ad hoc, but that would not work with compiled models. + if unexpected_keys: + msg = f"Hot swapping the adapter did not succeed, unexpected keys found: {', '.join(unexpected_keys)}." + raise RuntimeError(msg) + + # If the adapter that is being swapped in is missing some keys, this is fine. We just need to ensure that those LoRA + # weights from the previous adapter are set to 0 so that they don't influence the output. We don't need to worry + # about ranks are alphas. + for key in missing_keys: + # in case it's a compiled model + key = key.removeprefix("_orig_mod.") + # get LoRA parent module name by removing the 'lora_*..weight' part + module_name = ".".join(key.split(".")[:-3]) + module = model.get_submodule(module_name) + old_val = attrgetter(key)(model) + old_val.data.fill_(0.0) + + # actual swapping + for key, new_val in state_dict.items(): + # get LoRA parent module name by removing the 'lora_*..weight' part + module_name = ".".join(key.split(".")[:-3]) + module = model.get_submodule(module_name) + + # swap alpha/scaling + r_key = get_pattern_key(config.rank_pattern.keys(), key) + alpha_key = get_pattern_key(config.alpha_pattern.keys(), key) + rank = config.rank_pattern.get(r_key, config.r) + alpha = config.alpha_pattern.get(alpha_key, config.lora_alpha) + if config.use_rslora: + scaling = alpha / math.sqrt(rank) + else: + scaling = alpha / rank + _update_scaling(module, adapter_name=adapter_name, scaling=scaling) + + # swap actual weights + # no need to account for potential _orig_mod in key here, as torch handles that + old_val = attrgetter(key)(model) + new_val = new_val.to(old_val.data.device) + + # We try to detect if the model is compiled but it does not always work, e.g. if hotswapping is called from + # within the model itself. In this case, swap_tensors raises RuntimeError and should continue without + # swap_tensors. + if not is_compiled and not is_compiled_inplace: + try: + torch.utils.swap_tensors(old_val, new_val) + continue + except RuntimeError: + is_compiled = True + + # Compiled models don't work with swap_tensors because there are weakrefs for the tensor. It is unclear if + # this workaround could not cause trouble but the tests indicate that it works. + if old_val.shape == new_val.shape: + # either + # - adapters had the same rank + # - adapters were padded with prepare_model_for_compiled_hotswap and 2nd adapter was larger + old_val.data.copy_(new_val.data) + else: + # if 2nd adapter was smaller, ensure to fill up to adapter dimension and set the rest to zeros + if old_val.dim() not in (2, 4): + raise NotImplementedError( + f"Trying to hotswap an adapter whose weight has {old_val.dim()} dimensions, but only Conv2d and " + "Linear are supported" + ) + + # Linear or Conv2d: the check for dim 0 or 1 works for both of these layer types + if old_val.shape[0] > new_val.shape[0]: + old_val.data.fill_(0) + old_val.data[: new_val.shape[0]].copy_(new_val.data) + elif old_val.shape[1] > new_val.shape[1]: + old_val.data.fill_(0) + old_val.data[:, : new_val.shape[1]].copy_(new_val.data) + else: + raise ValueError( + f"Incompatible shapes found for LoRA weights {key}: {old_val.shape} vs {new_val.shape}. Please " + "ensure that all ranks are padded to the largest rank among all LoRA adapters by using " + "peft.utils.hotswap.prepare_model_for_compiled_hotswap." + ) + + +def check_hotswap_configs_compatible(config0: PeftConfig, config1: PeftConfig) -> None: + """ + Check if two configs are compatible for hot-swapping. + + Only LoRA parameters are checked for now. + + To hot-swap two adapters, their configs must be compatible. Otherwise, the results could be false. E.g. if they use + different alpha values, after hot-swapping, the alphas from the first adapter would still be used with the weights + from the 2nd adapter, which would result in incorrect behavior. There is probably a way to swap these values as + well, but that's not implemented yet, and we need to be careful not to trigger re-compilation if the model is + compiled (so no modification of the dict). + + """ + + if config0.peft_type != config1.peft_type: + msg = f"Incompatible PEFT types found: {config0.peft_type.value} and {config1.peft_type.value}" + raise ValueError(msg) + + if config0.peft_type not in CONFIG_KEYS_TO_CHECK: + msg = ( + f"Hotswapping only supports {', '.join(CONFIG_KEYS_TO_CHECK.keys())} but " + f"{config0.peft_type.value} was passed." + ) + raise ValueError(msg) + config_keys_to_check = CONFIG_KEYS_TO_CHECK[config0.peft_type] + + # TODO: This is a very rough check only for LoRA at the moment. Also, there might be some options that don't + # necessarily require an error. + config0 = config0.to_dict() + config1 = config1.to_dict() + sentinel = object() + for key in config_keys_to_check: + val0 = config0.get(key, sentinel) + val1 = config1.get(key, sentinel) + if val0 != val1: + raise ValueError(f"Configs are incompatible: for {key}, {val0} != {val1}") + + +def hotswap_adapter(model, model_name_or_path, adapter_name, torch_device=None, **kwargs): + """Substitute old adapter data with new adapter data, keeping the rest the same. + + As of now, only LoRA is supported. + + This function is useful when you want to replace the loaded adapter with a new adapter. The adapter name will + remain the same, but the weights and other parameters will be swapped out. + + If the adapters are incomptabile, e.g. targeting different layers or having different alpha values, an error will + be raised. + + Example: + + ```py + >>> import torch + >>> from transformers import AutoModelForCausalLM + >>> from peft import PeftModel + >>> from peft.utils.hotswap import hotswap_adapter + + >>> model_id = ... + >>> inputs = ... + >>> device = ... + >>> model = AutoModelForCausalLM.from_pretrained(model_id).to(device) + + >>> # load lora 0 + >>> model = PeftModel.from_pretrained(model, "path-adapter-0") + >>> model = torch.compile(model) # optionally compile the model + >>> with torch.inference_mode(): + ... output_adapter_0 = model(inputs) + + >>> # replace the "default" lora adapter with the new one + >>> hotswap_adapter(model, "path-adapter-1", adapter_name="default", torch_device=device) + >>> with torch.inference_mode(): + ... output_adapter_1 = model(inputs).logits + ``` + + Args: + model ([`~PeftModel`]): + The PEFT model with the loaded adapter. + model_name_or_path (`str`): + The name or path of the model to load the new adapter from. + adapter_name (`str`): + The name of the adapter to swap, e.g. `"default"`. The name will stay the same after swapping. + torch_device: (`str`, *optional*, defaults to None): + The device to load the new adapter onto. + **kwargs (`optional`): + Additional keyword arguments used for loading the config and weights. + + """ + if torch_device is None: + torch_device = infer_device() + + ############################ + # LOAD CONFIG AND VALIDATE # + ############################ + hf_kwargs = { + "subfolder": kwargs.get("subfolder", None), + "revision": kwargs.get("revision", None), + "cache_dir": kwargs.get("cache_dir", None), + "token": kwargs.get("token", None), + } + if use_auth_token := kwargs.get("use_auth_token", None): + hf_kwargs["use_auth_token"] = use_auth_token + config_cls = PEFT_TYPE_TO_CONFIG_MAPPING[PeftConfig._get_peft_type(model_name_or_path, **hf_kwargs)] + config = config_cls.from_pretrained(model_name_or_path, **kwargs) + # config keys that could affect the model output besides what is determined by the state_dict + check_hotswap_configs_compatible(model.active_peft_config, config) + + state_dict = load_peft_weights(model_name_or_path, device=torch_device, **kwargs) + + ########################### + # LOAD & REMAP STATE_DICT # + ########################### + + parameter_prefix = PEFT_TYPE_TO_PREFIX_MAPPING[config.peft_type] + peft_model_state_dict = _insert_adapter_name_into_state_dict( + state_dict, adapter_name=adapter_name, parameter_prefix=parameter_prefix + ) + + hotswap_adapter_from_state_dict( + model=model, + state_dict=peft_model_state_dict, + adapter_name=adapter_name, + parameter_prefix=parameter_prefix, + config=config, + ) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/incremental_pca.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/incremental_pca.py new file mode 100644 index 0000000000000000000000000000000000000000..de4a7c05174dc436f4c75965ef9585afb480183c --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/incremental_pca.py @@ -0,0 +1,338 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from typing import Optional + +import torch + + +class IncrementalPCA: + """ + An implementation of Incremental Principal Components Analysis (IPCA) that leverages PyTorch for GPU acceleration. + Adapted from https://github.com/scikit-learn/scikit-learn/blob/main/sklearn/decomposition/_incremental_pca.py + + This class provides methods to fit the model on data incrementally in batches, and to transform new data based on + the principal components learned during the fitting process. + + Args: + n_components (int, optional): Number of components to keep. If `None`, it's set to the minimum of the + number of samples and features. Defaults to None. + copy (bool): If False, input data will be overwritten. Defaults to True. + batch_size (int, optional): The number of samples to use for each batch. Only needed if self.fit is called. + If `None`, it's inferred from the data and set to `5 * n_features`. Defaults to None. + svd_driver (str, optional): name of the cuSOLVER method to be used for torch.linalg.svd. This keyword + argument only works on CUDA inputs. Available options are: None, gesvd, gesvdj, and gesvda. Defaults to + None. + lowrank (bool, optional): Whether to use torch.svd_lowrank instead of torch.linalg.svd which can be faster. + Defaults to False. + lowrank_q (int, optional): For an adequate approximation of n_components, this parameter defaults to + n_components * 2. + lowrank_niter (int, optional): Number of subspace iterations to conduct for torch.svd_lowrank. + Defaults to 4. + lowrank_seed (int, optional): Seed for making results of torch.svd_lowrank reproducible. + """ + + def __init__( + self, + n_components: Optional[int] = None, + copy: Optional[bool] = True, + batch_size: Optional[int] = None, + svd_driver: Optional[str] = None, + lowrank: bool = False, + lowrank_q: Optional[int] = None, + lowrank_niter: int = 4, + lowrank_seed: Optional[int] = None, + ): + self.n_components = n_components + self.copy = copy + self.batch_size = batch_size + self.svd_driver = svd_driver + self.lowrank = lowrank + self.lowrank_q = lowrank_q + self.lowrank_niter = lowrank_niter + self.lowrank_seed = lowrank_seed + + self.n_features_ = None + + if self.lowrank: + self._validate_lowrank_params() + + def _validate_lowrank_params(self): + if self.lowrank_q is None: + if self.n_components is None: + raise ValueError("n_components must be specified when using lowrank mode with lowrank_q=None.") + self.lowrank_q = self.n_components * 2 + elif self.lowrank_q < self.n_components: + raise ValueError("lowrank_q must be greater than or equal to n_components.") + + def _svd_fn_full(self, X): + return torch.linalg.svd(X, full_matrices=False, driver=self.svd_driver) + + def _svd_fn_lowrank(self, X): + seed_enabled = self.lowrank_seed is not None + with torch.random.fork_rng(enabled=seed_enabled): + if seed_enabled: + torch.manual_seed(self.lowrank_seed) + U, S, V = torch.svd_lowrank(X, q=self.lowrank_q, niter=self.lowrank_niter) + return U, S, V.mH + + def _validate_data(self, X) -> torch.Tensor: + """ + Validates and converts the input data `X` to the appropriate tensor format. + + Args: + X (torch.Tensor): Input data. + + Returns: + torch.Tensor: Converted to appropriate format. + """ + valid_dtypes = [torch.float32, torch.float64] + + if not isinstance(X, torch.Tensor): + X = torch.tensor(X, dtype=torch.float32) + elif self.copy: + X = X.clone() + + n_samples, n_features = X.shape + if self.n_components is None: + pass + elif self.n_components > n_features: + raise ValueError( + f"n_components={self.n_components} invalid for n_features={n_features}, " + "need more rows than columns for IncrementalPCA processing." + ) + elif self.n_components > n_samples: + raise ValueError( + f"n_components={self.n_components} must be less or equal to the batch number of samples {n_samples}" + ) + + if X.dtype not in valid_dtypes: + X = X.to(torch.float32) + + return X + + @staticmethod + def _incremental_mean_and_var( + X, last_mean, last_variance, last_sample_count + ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]: + """ + Computes the incremental mean and variance for the data `X`. + + Args: + X (torch.Tensor): The batch input data tensor with shape (n_samples, n_features). + last_mean (torch.Tensor): The previous mean tensor with shape (n_features,). + last_variance (torch.Tensor): The previous variance tensor with shape (n_features,). + last_sample_count (torch.Tensor): The count tensor of samples processed before the current batch. + + Returns: + Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: Updated mean, variance tensors, and total sample count. + """ + if X.shape[0] == 0: + return last_mean, last_variance, last_sample_count + + if last_sample_count > 0: + if last_mean is None: + raise ValueError("last_mean should not be None if last_sample_count > 0.") + if last_variance is None: + raise ValueError("last_variance should not be None if last_sample_count > 0.") + + new_sample_count = torch.tensor([X.shape[0]], device=X.device) + updated_sample_count = last_sample_count + new_sample_count + + if last_mean is None: + last_sum = torch.zeros(X.shape[1], dtype=torch.float64, device=X.device) + else: + last_sum = last_mean * last_sample_count + + new_sum = X.sum(dim=0, dtype=torch.float64) + + updated_mean = (last_sum + new_sum) / updated_sample_count + + T = new_sum / new_sample_count + temp = X - T + correction = temp.sum(dim=0, dtype=torch.float64).square() + temp.square_() + new_unnormalized_variance = temp.sum(dim=0, dtype=torch.float64) + new_unnormalized_variance -= correction / new_sample_count + if last_variance is None: + updated_variance = new_unnormalized_variance / updated_sample_count + else: + last_unnormalized_variance = last_variance * last_sample_count + last_over_new_count = last_sample_count.double() / new_sample_count + updated_unnormalized_variance = ( + last_unnormalized_variance + + new_unnormalized_variance + + last_over_new_count / updated_sample_count * (last_sum / last_over_new_count - new_sum).square() + ) + updated_variance = updated_unnormalized_variance / updated_sample_count + + return updated_mean, updated_variance, updated_sample_count + + @staticmethod + def _svd_flip(u, v, u_based_decision=True) -> tuple[torch.Tensor, torch.Tensor]: + """ + Adjusts the signs of the singular vectors from the SVD decomposition for deterministic output. + + This method ensures that the output remains consistent across different runs. + + Args: + u (torch.Tensor): Left singular vectors tensor. + v (torch.Tensor): Right singular vectors tensor. + u_based_decision (bool, optional): If True, uses the left singular vectors to determine the sign flipping. + Defaults to True. + + Returns: + Tuple[torch.Tensor, torch.Tensor]: Adjusted left and right singular vectors tensors. + """ + if u_based_decision: + max_abs_cols = torch.argmax(torch.abs(u), dim=0) + signs = torch.sign(u[max_abs_cols, range(u.shape[1])]) + else: + max_abs_rows = torch.argmax(torch.abs(v), dim=1) + signs = torch.sign(v[range(v.shape[0]), max_abs_rows]) + u *= signs[: u.shape[1]].view(1, -1) + v *= signs.view(-1, 1) + return u, v + + def fit(self, X, check_input=True): + """ + Fits the model with data `X` using minibatches of size `batch_size`. + + Args: + X (torch.Tensor): The input data tensor with shape (n_samples, n_features). + check_input (bool, optional): If True, validates the input. Defaults to True. + + Returns: + IncrementalPCA: The fitted IPCA model. + """ + if check_input: + X = self._validate_data(X) + n_samples, n_features = X.shape + if self.batch_size is None: + self.batch_size = 5 * n_features + + for batch in self.gen_batches(n_samples, self.batch_size, min_batch_size=self.n_components or 0): + self.partial_fit(X[batch], check_input=False) + + return self + + def partial_fit(self, X, check_input=True): + """ + Incrementally fits the model with batch data `X`. + + Args: + X (torch.Tensor): The batch input data tensor with shape (n_samples, n_features). + check_input (bool, optional): If True, validates the input. Defaults to True. + + Returns: + IncrementalPCA: The updated IPCA model after processing the batch. + """ + first_pass = not hasattr(self, "components_") + + if check_input: + X = self._validate_data(X) + n_samples, n_features = X.shape + + # Initialize attributes to avoid errors during the first call to partial_fit + if first_pass: + self.mean_ = None # Will be initialized properly in _incremental_mean_and_var based on data dimensions + self.var_ = None # Will be initialized properly in _incremental_mean_and_var based on data dimensions + self.n_samples_seen_ = torch.tensor([0], device=X.device) + self.n_features_ = n_features + if not self.n_components: + self.n_components = min(n_samples, n_features) + + if n_features != self.n_features_: + raise ValueError( + "Number of features of the new batch does not match the number of features of the first batch." + ) + + col_mean, col_var, n_total_samples = self._incremental_mean_and_var( + X, self.mean_, self.var_, self.n_samples_seen_ + ) + + if first_pass: + X -= col_mean + else: + col_batch_mean = torch.mean(X, dim=0) + X -= col_batch_mean + mean_correction_factor = torch.sqrt((self.n_samples_seen_.double() / n_total_samples) * n_samples) + mean_correction = mean_correction_factor * (self.mean_ - col_batch_mean) + X = torch.vstack( + ( + self.singular_values_.view((-1, 1)) * self.components_, + X, + mean_correction, + ) + ) + + if self.lowrank: + U, S, Vt = self._svd_fn_lowrank(X) + else: + U, S, Vt = self._svd_fn_full(X) + U, Vt = self._svd_flip(U, Vt, u_based_decision=False) + explained_variance = S**2 / (n_total_samples - 1) + explained_variance_ratio = S**2 / torch.sum(col_var * n_total_samples) + + self.n_samples_seen_ = n_total_samples + self.components_ = Vt[: self.n_components] + self.singular_values_ = S[: self.n_components] + self.mean_ = col_mean + self.var_ = col_var + self.explained_variance_ = explained_variance[: self.n_components] + self.explained_variance_ratio_ = explained_variance_ratio[: self.n_components] + if self.n_components not in (n_samples, n_features): + self.noise_variance_ = explained_variance[self.n_components :].mean() + else: + self.noise_variance_ = torch.tensor(0.0, device=X.device) + return self + + def transform(self, X) -> torch.Tensor: + """ + Applies dimensionality reduction to `X`. + + The input data `X` is projected on the first principal components previously extracted from a training set. + + Args: + X (torch.Tensor): New data tensor with shape (n_samples, n_features) to be transformed. + + Returns: + torch.Tensor: Transformed data tensor with shape (n_samples, n_components). + """ + X = X - self.mean_ + return torch.mm(X.double(), self.components_.T).to(X.dtype) + + @staticmethod + def gen_batches(n: int, batch_size: int, min_batch_size: int = 0): + """Generator to create slices containing `batch_size` elements from 0 to `n`. + + The last slice may contain less than `batch_size` elements, when `batch_size` does not divide `n`. + + Args: + n (int): Size of the sequence. + batch_size (int): Number of elements in each batch. + min_batch_size (int, optional): Minimum number of elements in each batch. Defaults to 0. + + Yields: + slice: A slice of `batch_size` elements. + """ + start = 0 + for _ in range(int(n // batch_size)): + end = start + batch_size + if end + min_batch_size > n: + continue + yield slice(start, end) + start = end + if start < n: + yield slice(start, n) diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/integrations.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/integrations.py new file mode 100644 index 0000000000000000000000000000000000000000..41ec60d6c366360de08c1b1d2307d4c5445afbb6 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/integrations.py @@ -0,0 +1,288 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import functools +from contextlib import contextmanager +from typing import Literal, Optional + +import packaging.version +import torch +import transformers +from torch import nn + + +def check_deepspeed_zero3_enabled() -> bool: + if packaging.version.parse(transformers.__version__) >= packaging.version.parse("4.33.0"): + from transformers.integrations import is_deepspeed_zero3_enabled + else: + from transformers.deepspeed import is_deepspeed_zero3_enabled + return is_deepspeed_zero3_enabled() + + +@contextmanager +def gather_params_ctx(param, modifier_rank: Optional[int] = 0, fwd_module: torch.nn.Module = None): + """Call DeepSpeed GatheredParameters context manager if DeepSpeed is enabled, otherwise do nothing.""" + + if not check_deepspeed_zero3_enabled(): + yield + return + + import deepspeed + + with deepspeed.zero.GatheredParameters(param, modifier_rank=modifier_rank, fwd_module=fwd_module): + yield + return + + +def dequantize_module_weight(module: torch.nn.Module) -> torch.nn.Parameter: + """ + Helper function to dequantize a quantized weight. + + This function should be extended if more quantization schemes are added to the library. + + If the weight is not quantized, it will be returned as is. + """ + if hasattr(module, "W_q"): # For handling HQQ quantized weight + weight = module.dequantize() + return weight + elif type(module.weight).__module__.startswith("torchao."): + # check for torchao without requiring any torchao imports + weight = module.weight.dequantize() + return weight + + weight = module.weight + if not isinstance(weight, torch.nn.Parameter): + if isinstance(weight, torch.Tensor): + # this is an FSDP-specific edge case + return weight # type: ignore + raise TypeError(f"Input weight should be of type nn.Parameter, got {type(weight)} instead") + + cls_name = weight.__class__.__name__ + if cls_name not in ("Params4bit", "Int8Params"): + return weight + + quant_state = getattr(module, "state", None) + device = weight.device + is_cpu = device.type == torch.device("cpu").type + weight = dequantize_bnb_weight(weight, state=quant_state) # no-op if not bnb + if is_cpu: + # dequantize_bnb_weight for 8bit moves the device in-place, thus we need to move it back to CPU if necessary + module.weight = module.weight.to(device) + return weight + + +def dequantize_bnb_weight(weight: torch.nn.Parameter, state=None): + """Helper function to dequantize 4bit or 8bit bnb weights.""" + import bitsandbytes as bnb + + device = weight.device + + cls_name = weight.__class__.__name__ + if cls_name == "Params4bit": + dequantized = bnb.functional.dequantize_4bit(weight.data, weight.quant_state) + return dequantized + + # 8bit case + if state is None: + raise ValueError( + "No `state` was passed for bnb 8bit quantized weights. Please open an issue on the PEFT repository and " + "report the error: https://github.com/huggingface/peft/issues" + ) + + if state.SCB is None: + state.SCB = weight.SCB + + if hasattr(bnb.functional, "int8_vectorwise_dequant"): + # Use bitsandbytes API if available (requires v0.45.0+) + dequantized = bnb.functional.int8_vectorwise_dequant(weight.data, state.SCB) + else: + # Multiply by (scale/127) to dequantize. + dequantized = weight.data * state.SCB.view(-1, 1) * 7.874015718698502e-3 + + return dequantized + + +def get_bnb_param_type(param: torch.nn.Parameter) -> Literal[False, "4bit", "8bit"]: + """Returns '4bit' or '8bit' if bitsandbytes parameter, else False""" + if param.__class__.__name__ == "Params4bit": + return "4bit" + if param.__class__.__name__ == "Int8Params": + return "8bit" + return False + + +# adapted from: +# https://github.com/huggingface/transformers/blob/eab6c491d439e83d5e31c660df6f7e36592eb0a2/src/transformers/generation/utils.py#L1617-L1643 +def get_layer_device_map(model): + """ + Derive the device map for the layers of the model. + """ + main_device = [d for d in model.hf_device_map.values() if d not in ["cpu", "disk"]][0] + + execution_device_map = { + name: main_device if device in ["cpu", "disk"] else device for name, device in model.hf_device_map.items() + } + + if execution_device_map is None: + return None + + if len(execution_device_map) == 1 and "" in execution_device_map: + return {idx: execution_device_map[""] for idx in range(model.config.num_hidden_layers)} + + layer_device_map = {} + for layer in execution_device_map: + for idx in range(model.config.num_hidden_layers): + if f".{idx}." in f"{layer}.": + layer_device_map[idx] = execution_device_map[layer] + break + for idx in range(model.config.num_hidden_layers): + if idx not in layer_device_map: + raise RuntimeError(f"layer {idx} has not been mapped to a device.") + return layer_device_map + + +# adapted from: +# https://github.com/huggingface/transformers/blob/eab6c491d439e83d5e31c660df6f7e36592eb0a2/src/transformers/cache_utils.py#L1159-L1179 +def map_cache_to_layer_device_map(model, cache) -> None: + """ + Ensure that the key and value cache of the model are on the same device as their corresponding layers. + """ + if not (isinstance(cache, transformers.Cache) and hasattr(model, "hf_device_map")): + return + + if isinstance(cache, transformers.EncoderDecoderCache): + map_cache_to_layer_device_map(model, cache.self_attention_cache) + return + + layer_device_map = get_layer_device_map(model) + for idx in range(model.config.num_hidden_layers): + layer_device = layer_device_map[idx] + if hasattr(cache, "layers"): + # new transformers uses cache.layers (>v4.55) + layer = cache.layers[idx] + layer.keys = layer.keys.to(layer_device) + layer.values = layer.values.to(layer_device) + else: + # old transformers uses cache.{key,value}_cache (<=v4.55) + # TODO: remove if we drop support for transformers <= 4.55 + cache.key_cache[idx] = cache.key_cache[idx].to(layer_device) + cache.value_cache[idx] = cache.value_cache[idx].to(layer_device) + + +################################## +# START: ADAPTED FROM ACCELERATE # +################################## +# +# Modified to support explicitly skipping layer initialization for faster switching between layer states +# (necessary for supporting `nn.MultiHeadAttention` adapters) + + +@contextmanager +def init_empty_weights(include_buffers: bool = None): + # adapted from accelerate.big_modeling.py + with _init_on_device(torch.device("meta"), include_buffers=include_buffers) as f: + yield f + + +@contextmanager +def _init_on_device(device: torch.device, include_buffers: bool = None): + # adapted from accelerate.big_modeling.py + old_register_parameter = nn.Module.register_parameter + if include_buffers: + old_register_buffer = nn.Module.register_buffer + + def register_empty_parameter(module, name, param): + # This works because torch first initializes the parameters with torch.empty, thus not assigning any new memory. + # Then the parameter is moved to meta device before reset_parameters() is called, which then operates on the + # meta device, making any subsequent calls to initialization methods no-ops. + old_register_parameter(module, name, param) + if (param is not None) and (getattr(_init_on_device, "_skip", False) is not True): + param_cls = type(module._parameters[name]) + kwargs = module._parameters[name].__dict__ + kwargs["requires_grad"] = param.requires_grad + module._parameters[name] = param_cls(module._parameters[name].to(device), **kwargs) + + def register_empty_buffer(module, name, buffer, persistent=True): + old_register_buffer(module, name, buffer, persistent=persistent) + if buffer is not None: + module._buffers[name] = module._buffers[name].to(device) + + # Patch tensor creation + if include_buffers: + tensor_constructors_to_patch = { + torch_function_name: getattr(torch, torch_function_name) + for torch_function_name in ["empty", "zeros", "ones", "full"] + } + else: + tensor_constructors_to_patch = {} + + def patch_tensor_constructor(fn): + def wrapper(*args, **kwargs): + kwargs["device"] = device + return fn(*args, **kwargs) + + return wrapper + + try: + nn.Module.register_parameter = register_empty_parameter + if include_buffers: + nn.Module.register_buffer = register_empty_buffer + for torch_function_name in tensor_constructors_to_patch.keys(): + setattr(torch, torch_function_name, patch_tensor_constructor(getattr(torch, torch_function_name))) + yield + finally: + nn.Module.register_parameter = old_register_parameter + if include_buffers: + nn.Module.register_buffer = old_register_buffer + for torch_function_name, old_torch_function in tensor_constructors_to_patch.items(): + setattr(torch, torch_function_name, old_torch_function) + + +@contextmanager +def _skip_init_on_device(): + # context manager to skip the _init_on_device context manager + old_val = getattr(_init_on_device, "_skip", False) + try: + _init_on_device._skip = True + yield + finally: + _init_on_device._skip = old_val + + +def skip_init_on_device(func): + """ + Ignore the init_on_device context manager when calling the decorated function. + + This is a narrow use decorator that allows us to avoid initializing on meta device even when we're inside the + init_empty_weights context. + + """ + + # The need for this functionality arose when working on MultiheadAttention, where we have to call _restore_weights + # repeatedly as parametes are overwritten and need to be re-registered. When using low_cpu_mem_usage=True, as + # register_parameter is patched inside of the init_empty_weights context, this would result in those parameters + # suddenly being moved to meta device. Using this decorator allows us to avoid this. + @functools.wraps(func) + def wrapper(*args, **kwargs): + with _skip_init_on_device(): + return func(*args, **kwargs) + + return wrapper + + +####### +# END # +####### diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/loftq_utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/loftq_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..ce502e167b5a7fd3c6b4617f12958d238e9ea4d9 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/loftq_utils.py @@ -0,0 +1,410 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Reference code: https://github.com/yxli2123/LoftQ/blob/main/utils.py +# Reference paper: https://huggingface.co/papers/2310.08659 + +from __future__ import annotations + +import logging +import os +from collections.abc import Callable +from typing import Optional, Union + +import torch +from accelerate.utils.memory import clear_device_cache +from huggingface_hub import snapshot_download +from huggingface_hub.errors import HFValidationError, LocalEntryNotFoundError +from safetensors import SafetensorError, safe_open +from transformers.utils import cached_file +from transformers.utils.hub import get_checkpoint_shard_files + +from peft.import_utils import is_bnb_4bit_available, is_bnb_available, is_xpu_available + + +class NFQuantizer: + def __init__(self, num_bits=2, device="cuda", method="normal", block_size=64, *args, **kwargs): + super().__init__(*args, **kwargs) + self.num_bits = num_bits + self.device = device + self.method = method + self.block_size = block_size + if self.method == "normal": + self.norm_lookup_table = self.create_normal_map(num_bits=self.num_bits) + self.norm_lookup_table = self.norm_lookup_table.to(device) + elif self.method == "uniform": + self.norm_lookup_table = self.create_uniform_map(num_bits=self.num_bits) + self.norm_lookup_table = self.norm_lookup_table.to(device) + else: + raise NotImplementedError("Other quantization methods not supported yet.") + + @staticmethod + def create_uniform_map(symmetric=False, num_bits=4): + if symmetric: + # print("symmetric uniform quantization") + negative = torch.linspace(-1, 0, 2 ** (num_bits - 1)) + positive = torch.linspace(0, 1, 2 ** (num_bits - 1)) + table = torch.cat([negative, positive[1:]]) + else: + # print("asymmetric uniform quantization") + table = torch.linspace(-1, 1, 2**num_bits) + return table + + @staticmethod + def create_normal_map(offset=0.9677083, symmetric=False, num_bits=2): + try: + from scipy.stats import norm + except ImportError: + raise ImportError("The required package 'scipy' is not installed. Please install it to continue.") + + variations = 2**num_bits + if symmetric: + v = norm.ppf(torch.linspace(1 - offset, offset, variations + 1)).tolist() + values = [] + for index in range(len(v) - 1): + values.append(0.5 * v[index] + 0.5 * v[index + 1]) + v = values + else: + # one more positive value, this is an asymmetric type + v1 = norm.ppf(torch.linspace(offset, 0.5, variations // 2 + 1)[:-1]).tolist() + v2 = [0] + v3 = (-norm.ppf(torch.linspace(offset, 0.5, variations // 2)[:-1])).tolist() + v = v1 + v2 + v3 + + values = torch.Tensor(v) + values = values.sort().values + values /= values.max() + return values + + def quantize_tensor(self, weight): + max_abs = torch.abs(weight).max() + weight_normed = weight / max_abs + + weight_normed_expanded = weight_normed.unsqueeze(-1) + + # Reshape L to have the same number of dimensions as X_expanded + L_reshaped = torch.tensor(self.norm_lookup_table).reshape(1, -1) + + # Calculate the absolute difference between X_expanded and L_reshaped + abs_diff = torch.abs(weight_normed_expanded - L_reshaped) + + # Find the index of the minimum absolute difference for each element + qweight = torch.argmin(abs_diff, dim=-1) + return qweight, max_abs + + def dequantize_tensor(self, qweight, max_abs): + qweight_flatten = qweight.flatten() + + weight_normed = self.norm_lookup_table[qweight_flatten] + weight = weight_normed * max_abs + + weight = weight.reshape(qweight.shape) + + return weight + + def quantize_block(self, weight): + if len(weight.shape) != 2: + raise ValueError(f"Only support 2D matrix, but your input has {len(weight.shape)} dimensions.") + if weight.shape[0] * weight.shape[1] % self.block_size != 0: + raise ValueError( + f"Weight with shape ({weight.shape[0]} x {weight.shape[1]}) " + f"is not dividable by block size {self.block_size}." + ) + + M, N = weight.shape + device = weight.device + + # Quantization + weight_flatten = weight.flatten() # (M*N, ) + weight_block = weight_flatten.reshape(-1, self.block_size) # (L, B), L = M * N / B + if self.method == "normal": + weight_max = weight_block.abs().max(dim=-1)[0] # (L, 1) + elif self.method == "uniform": + weight_max = weight_block.mean(dim=-1) + 2.5 * weight_block.std(dim=-1) + else: + raise NotImplementedError("Method not supported yet.") + weight_max = weight_max.unsqueeze(-1) + weight_divabs = weight_block / weight_max # (L, B) + weight_divabs = weight_divabs.unsqueeze(-1) # (L, B, 1) + L_reshaped = self.norm_lookup_table.reshape(1, -1) # (1, 2**K) + + abs_diff = torch.abs(weight_divabs - L_reshaped) # (L, B, 2**K) + qweight = torch.argmin(abs_diff, dim=-1) # (L, B) + + # Pack multiple k-bit into uint8 + qweight = qweight.reshape(-1, 8 // self.num_bits) + qweight_pack = torch.zeros((M * N // 8 * self.num_bits, 1), dtype=torch.uint8, device=device) + + # data format example: + # [1, 0, 3, 2] or [01, 00, 11, 10] -> [10110001], LIFO + for i in range(8 // self.num_bits): + qweight[:, i] = qweight[:, i] << i * self.num_bits + qweight_pack[:, 0] |= qweight[:, i] + + return qweight_pack, weight_max, weight.shape + + def dequantize_block(self, qweight, weight_max, weight_shape): + # unpack weight + device = qweight.device + weight = torch.zeros((qweight.shape[0], 8 // self.num_bits), dtype=torch.float32, device=device) + for i in range(8 // self.num_bits): + lookup_table_idx = qweight.to(torch.long) % 2**self.num_bits # get the most right 2 bits + lookup_table_idx = lookup_table_idx.to(torch.long) + weight[:, i] = self.norm_lookup_table[lookup_table_idx].squeeze() + qweight = qweight >> self.num_bits # right shift 2 bits of the original data + + weight_block = weight.reshape(-1, self.block_size) + weight = weight_block * weight_max + weight = weight.reshape(weight_shape) + + return weight + + +def _low_rank_decomposition(weight, reduced_rank=32): + """ + :param weight: The matrix to decompose, of shape (H, W) :param reduced_rank: the final rank :return: + """ + matrix_dimension = len(weight.size()) + if matrix_dimension != 2: + raise ValueError(f"Only support 2D matrix, but your input has {matrix_dimension} dimensions.") + + # Use SVD to decompose a matrix, default full_matrices is False to save parameters + U, S, Vh = torch.linalg.svd(weight, full_matrices=False) + + L = U @ (torch.sqrt(torch.diag(S)[:, 0:reduced_rank])) + R = torch.sqrt(torch.diag(S)[0:reduced_rank, :]) @ Vh + + return {"L": L, "R": R, "U": U, "S": S, "Vh": Vh, "reduced_rank": reduced_rank} + + +@torch.no_grad() +def loftq_init(weight: Union[torch.Tensor, torch.nn.Parameter], num_bits: int, reduced_rank: int, num_iter=1): + if is_bnb_available(): + import bitsandbytes as bnb + else: + raise ValueError("bitsandbytes is not available, please install it to use LoftQ.") + + if num_bits not in [2, 4, 8]: + raise ValueError("Only support 2, 4, 8 bits quantization") + if num_iter <= 0: + raise ValueError("Number of iterations must be greater than 0") + + out_feature, in_feature = weight.size() + device = weight.device + dtype = weight.dtype + logging.info( + f"Weight: ({out_feature}, {in_feature}) | Rank: {reduced_rank} | Num Iter: {num_iter} | Num Bits: {num_bits}" + ) + if not is_bnb_4bit_available() or num_bits in [2, 8]: + quantizer = NFQuantizer(num_bits=num_bits, device=device, method="normal", block_size=64) + compute_device = device + else: + compute_device = "xpu" if is_xpu_available() else "cuda" + + weight = weight.to(device=compute_device, dtype=torch.float32) + res = weight.clone() + for i in range(num_iter): + clear_device_cache() + # Quantization + if num_bits == 4 and is_bnb_4bit_available(): + qweight = bnb.nn.Params4bit( + res.to("cpu"), requires_grad=False, compress_statistics=False, quant_type="nf4" + ).to(compute_device) + dequantized_weight = bnb.functional.dequantize_4bit(qweight.data, qweight.quant_state) + else: + quantized_weight, max_abs, shape = quantizer.quantize_block(res) + dequantized_weight = quantizer.dequantize_block(quantized_weight, max_abs, shape) + + res = weight - dequantized_weight + + # Decompose the residual by SVD + output = _low_rank_decomposition(res, reduced_rank=reduced_rank) + L, R, reduced_rank = output["L"], output["R"], output["reduced_rank"] + res = weight - torch.mm(L, R) + + lora_A, lora_B = R, L + + return dequantized_weight.to(device=device, dtype=dtype), lora_A, lora_B + + +@torch.no_grad() +def _loftq_init_new(qweight, weight, num_bits: int, reduced_rank: int): + import bitsandbytes as bnb + + if num_bits != 4: + raise ValueError("Only 4 bit quantization supported at the moment.") + if not is_bnb_4bit_available(): + raise ValueError("bitsandbytes 4bit quantization is not available.") + + compute_device = "xpu" if is_xpu_available() else "cuda" + dequantized_weight = bnb.functional.dequantize_4bit(qweight.data, qweight.quant_state) + + weight = weight.to(device=compute_device, dtype=torch.float32) + residual = weight - dequantized_weight + clear_device_cache() + # Decompose the residualidual by SVD + output = _low_rank_decomposition(residual, reduced_rank=reduced_rank) + L, R, reduced_rank = output["L"], output["R"], output["reduced_rank"] + return R, L + + +class _SafetensorLoader: + """ + Simple utility class that loads tensors with safetensors from a single file or sharded files. + + Takes care of file name normalization etc. + + """ + + def __init__(self, peft_model, model_path): + if model_path is None: + try: + model_path = snapshot_download(peft_model.base_model.config._name_or_path, local_files_only=True) + except (AttributeError, HFValidationError) as exc: + raise ValueError( + "The provided model does not appear to be a transformers model or is a local model. In this case, " + "you must pass the model_path argument that points to the safetensors file." + ) from exc + except LocalEntryNotFoundError as exc: + raise ValueError( + "The model.safetensors file must be present on disk, but it could not be found." + ) from exc + + suffix = "model.safetensors" + if not model_path.endswith(suffix): + model_path = os.path.join(model_path, suffix) + + self.model_path = model_path + self.base_model_prefix = getattr(peft_model.get_base_model(), "base_model_prefix", None) + self.prefix = "base_model.model." + self.is_sharded = False + self.weight_map = None + + if not os.path.exists(model_path): + # check if the file is sharded + par_dir = model_path.rpartition(os.path.sep)[0] + try: + resolved_archive_file, sharded_metadata = get_checkpoint_shard_files( + par_dir, cached_file(par_dir, "model.safetensors.index.json") + ) + except OSError as exc: + raise FileNotFoundError( + f"Could not find file for {model_path}, ensure that there is a (sharded) safetensors file of the model." + ) from exc + + self.is_sharded = True + # maps from 'model-X-of-Y.safetensors' to full file path + file_map = {k.rpartition(os.path.sep)[-1]: k for k in resolved_archive_file} + self.weight_map = {k: file_map[v] for k, v in sharded_metadata["weight_map"].items()} + + def get_tensor(self, name): + if not self.is_sharded: + file_path = self.model_path + else: + file_path = self.weight_map[name] + + with safe_open(file_path, framework="pt", device="cpu") as f: + try: + tensor = f.get_tensor(name) + except SafetensorError as exc: + # no matching key found, we probably need to remove the base model prefix + if self.base_model_prefix: + # remove 1 extra character for "." + name = name[len(self.base_model_prefix) + 1 :] + tensor = f.get_tensor(name) + else: + raise exc + return tensor + + +@torch.no_grad() +def replace_lora_weights_loftq( + peft_model, + model_path: Optional[str] = None, + adapter_name: str = "default", + callback: Optional[Callable[[torch.nn.Module, str], bool]] = None, +): + """ + Replace the LoRA weights of a model quantized with bitsandbytes, using the LoftQ technique. + + The replacement is done on the fly by loading in the non-quantized weights from a locally stored safetensors model + file and initializing the LoRA weights such that the quantization error between the original and quantized weights + is minimized. + + As lazy loading is not possible with pickle, normal PyTorch checkpoint files cannot be supported. + + Depending on the model size, calling this function may take some time to finish. + + Args: + peft_model (`PeftModel`): + The model to replace the weights of. Must be a quantized PEFT model with LoRA layers. + model_path (`Optional[str]`): + The path to the model safetensors file. If the model is a Hugging Face model, this will be inferred from + the model's config. Otherwise, it must be provided. + adapter_name (`str`): + The name of the adapter to replace the weights of. The default adapter name is "default". + callback (`Optional[Callable[[PeftModel, str], bool]]`): + A callback function that will be called after each module is replaced. The callback function should take + the model and the name of the current module as input and return a boolean indicating whether the + replacement should be kept. If the callback returns False, the replacement will be rolled back. This can be + very useful to confirm that the LoftQ initialization actually decreases the quantization error of the + model. As an example, this callback could generate logits for given input and compare it with the logits + from the original, non-quanitzed model with the same input, and only return `True` if there is an + improvement. As this is a greedy optimization, it's possible that calling this function multiple times + yields incremental improvements. + """ + if not is_bnb_4bit_available(): + raise ValueError("bitsandbytes must be installed and the model must be quantized in 4bits.") + + from peft.tuners.lora import Linear4bit + + # model_path = _check_model_path_loftq(model_path, peft_model) + prefix = "base_model.model." + any_match = False + safetensor_loader = _SafetensorLoader(peft_model, model_path) + + # if too slow, consider adding tqdm as an option + for name, module in peft_model.named_modules(): + if not isinstance(module, Linear4bit): + continue + + if not name.startswith(prefix): + raise TypeError("The passed model does not appear to be a valid PeftModel") + + any_match = True + name = name[len(prefix) :] + tensor = safetensor_loader.get_tensor(name + ".weight") + + reduced_rank = module.r[adapter_name] + lora_A, lora_B = _loftq_init_new(module.weight, tensor, num_bits=4, reduced_rank=reduced_rank) + if not callback: + module.lora_A[adapter_name].weight.data = lora_A + module.lora_B[adapter_name].weight.data = lora_B + continue + + lora_A_before = module.lora_A[adapter_name].weight.data + lora_B_before = module.lora_B[adapter_name].weight.data + + module.lora_A[adapter_name].weight.data = lora_A + module.lora_B[adapter_name].weight.data = lora_B + should_replace = callback(peft_model, name) + if not should_replace: + # roll back + module.lora_A[adapter_name].weight.data = lora_A_before + module.lora_B[adapter_name].weight.data = lora_B_before + + del lora_A_before, lora_B_before + + if not any_match: + raise ValueError("No bnb LoRA module found on the model") diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/merge_utils.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/merge_utils.py new file mode 100644 index 0000000000000000000000000000000000000000..b62a1abf1eefe17d596461c529925e47e378c563 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/merge_utils.py @@ -0,0 +1,268 @@ +# Copyright 2024-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import warnings +from typing import Literal + +import torch + + +def reshape_weight_task_tensors(task_tensors, weights): + """ + Reshapes `weights` to match the shape of `task_tensors` by unsqeezing in the remaining dimenions. + + Args: + task_tensors (`torch.Tensor`): The tensors that will be used to reshape `weights`. + weights (`torch.Tensor`): The tensor to be reshaped. + + Returns: + `torch.Tensor`: The reshaped tensor. + """ + new_shape = weights.shape + (1,) * (task_tensors.dim() - weights.dim()) + weights = weights.view(new_shape) + return weights + + +def magnitude_based_pruning(tensor: torch.Tensor, density: float) -> torch.Tensor: + """ + Prune the smallest values of the task tensors and retain the top-k values based on the specified fraction + `density`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The tensor with the pruned weights. + """ + mask = torch.zeros_like(tensor).reshape(-1) + k = int(density * tensor.numel()) + top_k = torch.topk(tensor.abs().reshape(-1), k=k, largest=True) + mask[top_k[1]] = 1 + return tensor * mask.reshape(tensor.shape) + + +def random_pruning(tensor: torch.Tensor, density: float, rescale: bool) -> torch.Tensor: + """ + Prune random values based on the specified fraction `density`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. + + Returns: + `torch.Tensor`: The pruned tensor. + """ + mask = torch.bernoulli(torch.full_like(input=tensor, fill_value=density)) + pruned_tensor = tensor * mask + if rescale: + torch.div(input=pruned_tensor, other=density) + return pruned_tensor + + +def prune( + tensor: torch.Tensor, density: float, method: Literal["magnitude", "random"], rescale: bool = False +) -> torch.Tensor: + """ + Prune the values of task tensors based on the `method`. + + Args: + tensor (`torch.Tensor`):The tensor to prune. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + method (`str`):The method to use to prune. Should be one of ["magnitude", "random"]. + rescale (`bool`):Whether to rescale the result to preserve the expected value of the original tensor. + + Returns: + `torch.Tensor`: The pruned tensor. + """ + if density >= 1: + warnings.warn(f"The density {density} is greater than or equal to 1, no pruning will be performed.") + return tensor + elif density < 0: + raise ValueError(f"Density should be >= 0, got {density}") + if method == "magnitude": + return magnitude_based_pruning(tensor, density) + elif method == "random": + return random_pruning(tensor, density, rescale=rescale) + else: + raise ValueError(f"Unknown method {method}") + + +def calculate_majority_sign_mask( + tensor: torch.Tensor, method: Literal["total", "frequency"] = "total" +) -> torch.Tensor: + """ + Get the mask of the majority sign across the task tensors. Task tensors are stacked on dimension 0. + + Args: + tensor (`torch.Tensor`):The tensor to get the mask from. + method (`str`):The method to use to get the mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The majority sign mask. + """ + + sign = tensor.sign() + if method == "total": + sign_magnitude = tensor.sum(dim=0) + elif method == "frequency": + sign_magnitude = sign.sum(dim=0) + else: + raise RuntimeError(f'Unimplemented mask method "{method}"') + majority_sign = torch.where(sign_magnitude >= 0, 1, -1) + return sign == majority_sign + + +def disjoint_merge(task_tensors: torch.Tensor, majority_sign_mask: torch.Tensor) -> torch.Tensor: + """ + Merge the task tensors using disjoint merge. + + Args: + task_tensors (`torch.Tensor`):The task tensors to merge. + majority_sign_mask (`torch.Tensor`):The mask of the majority sign across the task tensors. + + Returns: + `torch.Tensor`: The merged tensor. + """ + mixed_task_tensors = (task_tensors * majority_sign_mask).sum(dim=0) + num_params_preserved = majority_sign_mask.sum(dim=0) + return mixed_task_tensors / torch.clamp(num_params_preserved, min=1.0) + + +def task_arithmetic(task_tensors: list[torch.Tensor], weights: torch.Tensor) -> torch.Tensor: + """ + Merge the task tensors using `task arithmetic`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + + Returns: + `torch.Tensor`: The merged tensor. + """ + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def magnitude_prune(task_tensors: list[torch.Tensor], weights: torch.Tensor, density: float) -> torch.Tensor: + """ + Merge the task tensors using `task arithmetic`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`): The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="magnitude") for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def ties( + task_tensors: list[torch.Tensor], + weights: torch.Tensor, + density: float, + majority_sign_method: Literal["total", "frequency"] = "total", +) -> torch.Tensor: + """ + Merge the task tensors using `ties`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + majority_sign_method (`str`): + The method to use to get the majority sign mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="magnitude") for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # Elect Sign + majority_sign_mask = calculate_majority_sign_mask(task_tensors, method=majority_sign_method) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + # Disjoint Merge + mixed_task_tensors = disjoint_merge(weighted_task_tensors, majority_sign_mask) + return mixed_task_tensors + + +def dare_linear(task_tensors: list[torch.Tensor], weights: torch.Tensor, density: float) -> torch.Tensor: + """ + Merge the task tensors using `dare linear`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="random", rescale=True) for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + mixed_task_tensors = weighted_task_tensors.sum(dim=0) + return mixed_task_tensors + + +def dare_ties( + task_tensors: list[torch.Tensor], + weights: torch.Tensor, + density: float, + majority_sign_method: Literal["total", "frequency"] = "total", +) -> torch.Tensor: + """ + Merge the task tensors using `dare ties`. + + Args: + task_tensors(`List[torch.Tensor]`):The task tensors to merge. + weights (`torch.Tensor`):The weights of the task tensors. + density (`float`):The fraction of values to preserve. Should be in [0,1]. + majority_sign_method (`str`): + The method to use to get the majority sign mask. Should be one of ["total", "frequency"]. + + Returns: + `torch.Tensor`: The merged tensor. + """ + # sparsify + task_tensors = [prune(tensor, density, method="random", rescale=True) for tensor in task_tensors] + task_tensors = torch.stack(task_tensors, dim=0) + # Elect Sign + majority_sign_mask = calculate_majority_sign_mask(task_tensors, method=majority_sign_method) + # weighted task tensors + weights = reshape_weight_task_tensors(task_tensors, weights) + weighted_task_tensors = task_tensors * weights + # Disjoint Merge + mixed_task_tensors = disjoint_merge(weighted_task_tensors, majority_sign_mask) + return mixed_task_tensors diff --git a/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/other.py b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/other.py new file mode 100644 index 0000000000000000000000000000000000000000..1e3103466b0418d1b0b2a7b48132b0c2ee9c58b1 --- /dev/null +++ b/tasks/tasksmith-f71b564d1bc2/tests/source/src/peft/utils/other.py @@ -0,0 +1,1707 @@ +# Copyright 2023-present the HuggingFace Inc. team. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +from __future__ import annotations + +import copy +import functools +import inspect +import os +import re +import warnings +from collections.abc import Sequence +from contextlib import nullcontext +from operator import attrgetter +from typing import Any, Optional, Union + +import accelerate +import torch +import transformers +from accelerate import FullyShardedDataParallelPlugin +from accelerate.hooks import add_hook_to_module, remove_hook_from_module +from accelerate.utils import is_npu_available, is_xpu_available +from huggingface_hub import file_exists +from huggingface_hub.errors import EntryNotFoundError, HFValidationError +from packaging import version +from safetensors.torch import storage_ptr, storage_size +from transformers import PreTrainedModel + +from ..import_utils import is_gptqmodel_available, is_torch_tpu_available, is_transformers_ge_v5_1_0 +from .constants import ( + CONFIG_NAME, + EMBEDDING_LAYER_NAMES, + INCLUDE_LINEAR_LAYERS_SHORTHAND, + SAFETENSORS_WEIGHTS_NAME, + TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING, + TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING, + TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING, + WEIGHTS_NAME, + bloom_model_postprocess_past_key_value, + starcoder_model_postprocess_past_key_value, +) + + +mlu_available = False +if version.parse(accelerate.__version__) >= version.parse("0.29.0"): + from accelerate.utils import is_mlu_available + + mlu_available = is_mlu_available() + +__all__ = [ + "CONFIG_NAME", + "EMBEDDING_LAYER_NAMES", + "INCLUDE_LINEAR_LAYERS_SHORTHAND", + "SAFETENSORS_WEIGHTS_NAME", + "TRANSFORMERS_MODELS_TO_ADALORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_BOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_C3A_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_DELORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_FOURIERFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_HRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_FEEDFORWARD_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_IA3_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LILY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LNTUNING_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOHA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LOKR_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_LORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_MISS_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_OFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_POLY_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PREFIX_TUNING_POSTPROCESS_MAPPING", + "TRANSFORMERS_MODELS_TO_PSOFT_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_PVERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_RANDLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_ROAD_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_SHIRA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VBLORA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_VERA_TARGET_MODULES_MAPPING", + "TRANSFORMERS_MODELS_TO_WAVEFT_TARGET_MODULES_MAPPING", + "WEIGHTS_NAME", + "bloom_model_postprocess_past_key_value", + "starcoder_model_postprocess_past_key_value", +] + + +# Get current device name based on available devices +def infer_device() -> str: + if torch.cuda.is_available(): + return "cuda" + elif hasattr(torch.backends, "mps") and torch.backends.mps.is_available(): + return "mps" + elif mlu_available: + return "mlu" + elif is_xpu_available(): + return "xpu" + elif is_npu_available(): + return "npu" + return "cpu" + + +def prepare_model_for_kbit_training(model, use_gradient_checkpointing=True, gradient_checkpointing_kwargs=None): + r""" + Note this method only works for `transformers` models. + + This method wraps the entire protocol for preparing a model before running a training. This includes: + 1- Cast the layernorm in fp32 2- making output embedding layer require grads 3- Add the upcasting of the lm + head to fp32 4- Freezing the base model layers to ensure they are not updated during training + + + Args: + model (`transformers.PreTrainedModel`): + The loaded model from `transformers` + use_gradient_checkpointing (`bool`, *optional*, defaults to `True`): + If True, use gradient checkpointing to save memory at the expense of slower backward pass. + gradient_checkpointing_kwargs (`dict`, *optional*, defaults to `None`): + Keyword arguments to pass to the gradient checkpointing function, please refer to the documentation of + `torch.utils.checkpoint.checkpoint` for more details about the arguments that you can pass to that method. + Note this is only available in the latest transformers versions (> 4.34.1). + """ + loaded_in_kbit = getattr(model, "is_loaded_in_8bit", False) or getattr(model, "is_loaded_in_4bit", False) + is_gptq_quantized = getattr(model, "quantization_method", None) == "gptq" + is_aqlm_quantized = getattr(model, "quantization_method", None) == "aqlm" + is_eetq_quantized = getattr(model, "quantization_method", None) == "eetq" + is_torchao_quantized = getattr(model, "quantization_method", None) == "torchao" + is_hqq_quantized = getattr(model, "quantization_method", None) == "hqq" or getattr(model, "hqq_quantized", False) + + if gradient_checkpointing_kwargs is None: + gradient_checkpointing_kwargs = {} + + for name, param in model.named_parameters(): + # freeze base model's layers + param.requires_grad = False + + if ( + not is_gptq_quantized + and not is_aqlm_quantized + and not is_eetq_quantized + and not is_hqq_quantized + and not is_torchao_quantized + ): + # cast all non INT8 parameters to fp32 + for param in model.parameters(): + if ( + (param.dtype == torch.float16) or (param.dtype == torch.bfloat16) + ) and param.__class__.__name__ != "Params4bit": + param.data = param.data.to(torch.float32) + + if ( + loaded_in_kbit + or is_gptq_quantized + or is_aqlm_quantized + or is_eetq_quantized + or is_hqq_quantized + or is_torchao_quantized + ) and use_gradient_checkpointing: + # When having `use_reentrant=False` + gradient_checkpointing, there is no need for this hack + if "use_reentrant" not in gradient_checkpointing_kwargs or gradient_checkpointing_kwargs["use_reentrant"]: + # For backward compatibility + if hasattr(model, "enable_input_require_grads"): + model.enable_input_require_grads() + else: + + def make_inputs_require_grad(module, input, output): + output.requires_grad_(True) + + model.get_input_embeddings().register_forward_hook(make_inputs_require_grad) + + # To support older transformers versions, check if the model supports gradient_checkpointing_kwargs + _supports_gc_kwargs = "gradient_checkpointing_kwargs" in list( + inspect.signature(model.gradient_checkpointing_enable).parameters + ) + + if not _supports_gc_kwargs and len(gradient_checkpointing_kwargs) > 0: + warnings.warn( + "gradient_checkpointing_kwargs is not supported in this version of transformers. The passed kwargs will be ignored." + " if you want to use that feature, please upgrade to the latest version of transformers.", + FutureWarning, + ) + + gc_enable_kwargs = ( + {} if not _supports_gc_kwargs else {"gradient_checkpointing_kwargs": gradient_checkpointing_kwargs} + ) + + # enable gradient checkpointing for memory efficiency + model.gradient_checkpointing_enable(**gc_enable_kwargs) + return model + + +# copied from transformers.models.bart.modeling_bart +def shift_tokens_right(input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int): + """ + Shift input ids one token to the right. + + Args: + input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): input ids + pad_token_id (`int`): The id of the `padding` token. + decoder_start_token_id (`int`): The id of the `start` token. + """ + shifted_input_ids = input_ids.new_zeros(input_ids.shape) + shifted_input_ids[:, 1:] = input_ids[:, :-1].clone() + shifted_input_ids[:, 0] = decoder_start_token_id + + if pad_token_id is None: + raise ValueError("self.model.config.pad_token_id has to be defined.") + # replace possible -100 values in labels by `pad_token_id` + shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id) + + return shifted_input_ids + + +def _set_layer_requires_grad(layer, requires_grad: bool) -> None: + """Set requires_grad on all leaf parameters of a layer. + + This handles the FSDP case where params may be non-leaf tensors (wrapped in DTensors). Only leaf tensors can have + their requires_grad flag toggled, so non-leaf tensors are silently skipped + + Args: + layer: A module, parameter or tensor + requires_grad: enable or disable gradients + """ + if isinstance(layer, (torch.nn.Parameter, torch.Tensor)): + if layer.is_leaf: + layer.requires_grad_(requires_grad) + else: + for param in layer.parameters(): + if param.is_leaf: + param.requires_grad_(requires_grad) + + +class AuxiliaryTrainingWrapper(torch.nn.Module): + """Wrap a specific module so that it can be trained and saved in a way that is tangential to how + PEFT normally works, e.g. fully training a classification layer instead of using an adapter. + + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = () + # All names of other parameters that may contain adapter-related parameters + other_param_names: tuple[str, ...] = () + # List all merged adapters + merged_adapters: list[str] = [] + + def __init__(self, module_to_save, adapter_name, **kwargs): + """Extra kwargs will be passed to `self.init_modules` and `self.update`.""" + super().__init__() + self.original_module = module_to_save + self._active_adapter = [adapter_name] + self._disable_adapters = False + self._adapters = set() + + self.init_modules(adapter_name, **kwargs) + + self.update(adapter_name, **kwargs) + self.check_module() + + def init_modules(self, adapter_name, **kwargs): + """A place to initialize PyTorch modules in `__init__` before the call to `self.update()`.""" + raise NotImplementedError + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + raise NotImplementedError + + def _error_message_name(self): + """Returns a user friendly identifier for error messages, e.g. for type compatibility error messages from + `check_module()` so that the user can backtrack where the error comes from. A generic "training wrapper" is + less helpful than "modules_to_save", for example. + """ + return "training wrapper" + + def check_module(self): + """Perform some sanity checks on the module to ensure that it works""" + # Try to anticipate some modules that users could try to target that would not work. + # Note: It's not possible to check hasattr(module, "forward"), since that returns True for ModuleDict and + # ModuleList, even though their forward methods cannot be called + forbidden_classes = (torch.nn.ModuleDict, torch.nn.ModuleList, torch.nn.ParameterDict, torch.nn.ParameterList) + if isinstance(self.original_module, forbidden_classes): + cls_name = self.original_module.__class__ + raise TypeError(f"{self._error_message_name()} cannot be applied to modules of type {cls_name}") + + # local import to avoid circular import + from peft.tuners.tuners_utils import BaseTunerLayer + + if isinstance(self.original_module, BaseTunerLayer): + # e.g. applying a training wrapper to a lora layer makes no sense + cls_name = self.original_module.__class__ + raise TypeError(f"{self._error_message_name()} cannot be applied to modules of type {cls_name}") + + @property + def disable_adapters(self) -> bool: + # use a property to ensure that disable_adapters is not set directly, instead use the enable_adapters method + return self._disable_adapters + + @property + def active_adapter(self) -> Union[list[str], str]: + # use a property to ensure that active_adapter is not set directly, instead use the set_adapter method + return self._active_adapter + + @property + def active_adapters(self) -> list[str]: + if isinstance(self._active_adapter, str): + return [self._active_adapter] + return self._active_adapter + + def _hasattr_wrapped(self, name, modules): + """Infrastructure to enable the implementing class to delegate attributes to other modules. + Returns True if the implementing class knows how to handle attribute `name`. + + Gets passed `modules` which is PyTorch's internal list of assigned modules from `nn.Module`. + """ + return False + + def _getattr_wrapped(self, name, modules): + """If `_hasattr_wrapped` returns True for `name`, then this function should return the corresponding + value associated with `name`. + """ + return + + def __getattr__(self, name: str): + # Note: This whole method may seem overly complex at first but PyTorch messes with __getattr__ in a way that + # requires very careful handling to avoid infinite recursion. + try: + return super().__getattr__(name) + except AttributeError: + pass + + if "_modules" not in self.__dict__: + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + # Could not find the attribute the PyTorch way. So let's check if it's an attribute on the + # original_module or the module further down (e.g., `modules_to_save[active_adapter]`). + modules = self.__dict__["_modules"] + if self.disable_adapters or (not self.active_adapters): + # no PEFT adapter is active, thus refer to original module + return getattr(self.original_module, name) + elif self._hasattr_wrapped(name, modules): + return self._getattr_wrapped(name, modules) + + # For some reason, there is no module corresponding to the active adapter; this should normally not be + # reached and exists as a failsafe (otherwise, a KeyError would be raised) + raise AttributeError(f"'{type(self).__name__}' object has no attribute '{name}'") + + def update(self, adapter_name, **kwargs): + """Called when this instance should be part of an adapter's training. + Adds the given adapter to the list of adapters that this instance is training along with. + + Additional kwargs are expected to be the same kwargs that are also passed for initializing this class. + """ + if adapter_name not in self._adapters: + self._adapters.add(adapter_name) + + def _create_new_hook(self, old_hook): + r""" + Creates a new hook based on the old hook. Use it only if you know what you are doing ! + """ + old_hook_cls = getattr(accelerate.hooks, old_hook.__class__.__name__) + old_hook_attr = old_hook.__dict__ + filtered_old_hook_attr = {} + old_hook_init_signature = inspect.signature(old_hook_cls.__init__) + for k in old_hook_attr.keys(): + if k in old_hook_init_signature.parameters: + filtered_old_hook_attr[k] = old_hook_attr[k] + new_hook = old_hook_cls(**filtered_old_hook_attr) + return new_hook + + def _check_forward_args(self, x, *args, **kwargs): + """Check if the arguments are compatible with the configs and state of the model""" + adapter_names = kwargs.get("adapter_names", None) + if adapter_names is None: + return + + if len(x) != len(adapter_names): + msg = ( + "Length of `adapter_names` should be the same as the number of inputs, but got " + f"{len(adapter_names)} and {len(x)} respectively." + ) + raise ValueError(msg) + + def _forward_wrapped(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + raise NotImplementedError + + def _forward_wrapped_mixed_batch( + self, x: torch.Tensor, active_adapter: str, *args: Any, **kwargs: Any + ) -> torch.Tensor: + raise NotImplementedError + + def _forward_wrapped_passthrough(self, x: torch.Tensor, *args: Any, **kwargs: Any) -> torch.Tensor: + """The forward call when no adapter is involved in the forward computation, only the base model""" + raise NotImplementedError + + def _mixed_batch_forward( + self, input: torch.Tensor, *args: Any, adapter_names: list[str], **kwargs: Any + ) -> torch.Tensor: + # This is a special method that handles the case when users pass the argument `adapter_names`. This is an + # extra argument that allows mixing different adapters in the same batch at inference time. + + SUPPORTED_MODULES = (torch.nn.Linear, torch.nn.Embedding, torch.nn.Conv1d, torch.nn.Conv2d, torch.nn.Conv3d) + + module_names = ", ".join([module.__name__ for module in SUPPORTED_MODULES]) + + if not isinstance(self.original_module, SUPPORTED_MODULES): + raise TypeError(f"Mixed batching is only supported for the following modules: {module_names}.") + + unique_adapters = set(adapter_names) + sub_batch_indices_list = [] + + for adapter in unique_adapters: + sub_batch_indices_list.append([index for index, item in enumerate(adapter_names) if item == adapter]) + + results = [0 for _ in range(len(input))] + + for i, active_adapter in enumerate(unique_adapters): + sub_batch = input[sub_batch_indices_list[i]] + + if active_adapter == "__base__": + output = self.original_module(sub_batch, *args, **kwargs) + else: + output = self._forward_wrapped_mixed_batch(sub_batch, active_adapter, *args, **kwargs) + + for index, j in enumerate(sub_batch_indices_list[i]): + results[j] = output[index] + + return torch.stack(results) + + def forward(self, x: torch.Tensor, *args, **kwargs): + self._check_forward_args(x, *args, **kwargs) + adapter_names = kwargs.pop("adapter_names", None) + + if self.disable_adapters or any(adapter not in self._adapters for adapter in self.active_adapters): + return self._forward_wrapped_passthrough(x, *args, **kwargs) + + if adapter_names is None: + return self._forward_wrapped(x, *args, **kwargs) + return self._mixed_batch_forward(x, *args, adapter_names=adapter_names, **kwargs) + + def enable_adapters(self, enabled: bool): + """Toggle the enabling and disabling of adapters + + Args: + enabled (bool): True to enable adapters, False to disable adapters + """ + if enabled: + self._disable_adapters = False + else: + self._disable_adapters = True + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + raise NotImplementedError + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + """Set the active adapter + + Note: This only deals with active_adapters, not with requires_grad. If the latter needs changing, handle it via + the subclass. + + Args: + adapter_names (str or list[str]): + The name(s) of the adapter(s) to set as active + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + self._active_adapter = adapter_names + else: + self._active_adapter = [] + for adapter_name in adapter_names: + if adapter_name not in self._adapters: + raise ValueError(f"Adapter {adapter_name} not found in {self._adapters}") + + self._active_adapter.append(adapter_name) + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """Delete an adapter from the layer, set a new active adapter if necessary""" + raise NotImplementedError + + def set_requires_grad(self, adapter_names: str | Sequence[str], requires_grad: bool = True) -> None: + """ + Enable or disable gradients on the given adapter(s). + + Args: + adapter_name (`str` or `Sequence[str]`): + The name of the adapter(s) whose gradients should be enabled/disabled. + requires_grad (`bool`, *optional*) + Whether to enable (`True`, default) or disable (`False`). + """ + if isinstance(adapter_names, str): + adapter_names_set = {adapter_names} + else: + adapter_names_set = set(adapter_names) + + for layer_name in self.adapter_layer_names: + # use attrgetter, as it resolves `.` in the attribute name + module_dict = attrgetter(layer_name)(self) + for key, layer in module_dict.items(): + if key in adapter_names_set: + _set_layer_requires_grad(layer, requires_grad) + + def adapter_state_dict(self, adapter_name): + """Return the state dict of this module for a given adapter.""" + raise NotImplementedError + + def adapter_state_dict_load_map(self, adapter_name): + """Return a mapping from the key present in disk-loaded state dict + and how it should be represented in the loaded model's state dict. + + The default should be a 1:1 mapping but it is important to define a mapping as it also serves as the + ground-truth for which keys are supposed to be loaded from a saved state dict. + """ + raise NotImplementedError + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Handles unloading when called from PEFT models. Returns the wrapped module + and handles merging onto the wrapped module if requested. + """ + raise NotImplementedError + + +class ModulesToSaveWrapper(AuxiliaryTrainingWrapper): + """Wraps a module that is supposed to be trained (i.e. `requires_grad_(True)`) and saved after training.""" + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = ("modules_to_save",) + + def __init__(self, module_to_save, adapter_name, tied_module=None): + super().__init__(module_to_save, adapter_name, tied_module=tied_module) + + def init_modules(self, adapter_name, **kwargs): + # we treat each adapter separately, so we have multiple adapters, same (copied) module for each + self.modules_to_save = torch.nn.ModuleDict({}) + + def _error_message_name(self): + return "modules_to_save" + + def _forward_wrapped(self, x, *args, **kwargs): + if not self.active_adapters: + return self._forward_wrapped_passthrough(x, *args, **kwargs) + return self.modules_to_save[self.active_adapters[0]](x, *args, **kwargs) + + def _forward_wrapped_mixed_batch(self, x, active_adapter, *args, **kwargs): + return self.modules_to_save[active_adapter](x, *args, **kwargs) + + def _forward_wrapped_passthrough(self, x, *args, **kwargs): + return self.original_module(x, *args, **kwargs) + + def _hasattr_wrapped(self, name, modules): + # this method is only called if there is at least one active adapter + return self.active_adapters[0] in modules["modules_to_save"] + + def _getattr_wrapped(self, name, modules): + return getattr(modules["modules_to_save"][self.active_adapters[0]], name) + + def update(self, adapter_name, tied_module=None, **kwargs): + super().update(adapter_name) + + context_manager = nullcontext() + for _, param in self.original_module.named_parameters(): + num_params = param.numel() + # if using DS Zero 3 and the weights are initialized empty + if num_params == 0 and hasattr(param, "ds_numel"): + import deepspeed + + context_manager = deepspeed.zero.GatheredParameters(self.original_module.parameters(), modifier_rank=0) + break + + if adapter_name not in self.modules_to_save: + with context_manager: + if tied_module: + new_linear = torch.nn.Linear(*tied_module.weight.shape, bias=False) + new_linear.weight = tied_module.weight + + self.modules_to_save[adapter_name] = new_linear + else: + self.modules_to_save[adapter_name] = copy.deepcopy(self.original_module) + + if hasattr(self.modules_to_save[adapter_name], "_hf_hook"): + old_hook = self.modules_to_save[adapter_name]._hf_hook + new_hook = self._create_new_hook(old_hook) + remove_hook_from_module(self.modules_to_save[adapter_name]) + add_hook_to_module(self.modules_to_save[adapter_name], new_hook) + + self.original_module.requires_grad_(False) + + # note that there currently cannot be more than one active adapter for the same layer with modules to save + # since there would be no clear way to decide which adapter's weights are the correct ones. therefore we + # assume that there is only one active adapter. this precondition is enforced by _set_adapter. + if adapter_name == self.active_adapter: + _set_layer_requires_grad(self.modules_to_save[adapter_name], True) + + def enable_adapters(self, enabled: bool): + """Takes care of setting the required_grad flag on the modules_to_save. + If adapters are enabled, gradients for the modules_to_save are required as well. + """ + super().enable_adapters(enabled) + + if enabled: + for adapter_name in self.active_adapters: + _set_layer_requires_grad(self.modules_to_save[adapter_name], True) + else: + for module in self.modules_to_save.values(): + _set_layer_requires_grad(module, False) + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + if isinstance(adapter_name, str): + return adapter_name + + # adapter_name is a list of str + if len(adapter_name) == 0: + raise ValueError("Please specify at least one adapter to set") + + adapter_names_in_module = [n for n in adapter_name if n in self.modules_to_save] + + if len(adapter_names_in_module) > 1: + raise ValueError(f"Only one adapter can be set at a time for {self}, got {len(adapter_names_in_module)}") + + adapter_name_to_set: str | None + if not adapter_names_in_module: + adapter_name_to_set = None + else: + adapter_name_to_set = adapter_names_in_module[0] + + return adapter_name_to_set + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + """Set the active adapter + + Additionally, this function will set the specified adapter to trainable (i.e., requires_grad=True) unless + inference_mode is True. + + Args: + adapter_names (list[str], str): + The name(s) of the adapter(s) to set as active. + inference_mode (bool, optional): + Whether the activated adapter should be frozen (i.e. `requires_grad=False`). Default is False. + """ + if isinstance(adapter_names, str): + adapter_names = [adapter_names] + + if len(adapter_names) > 1: + raise ValueError(f"Attempted to set multiple ({adapter_names}) adapters at once for modules_to_save.") + + for currently_active_adapter_name in self.active_adapters: + _set_layer_requires_grad(self.modules_to_save[currently_active_adapter_name], False) + + if len(adapter_names) == 0: + # when calling model.add_adapter, the new adapter is not automatically active + self._active_adapter = [] + return + + adapter_name = adapter_names[0] + + if adapter_name not in self._adapters: + raise ValueError(f"Adapter {adapter_name} not found in {self._adapters}") + + _set_layer_requires_grad(self.modules_to_save[adapter_name], not inference_mode) + self._active_adapter = adapter_name + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """ + Delete the adapter if present. + + This method will also set a new active adapter if the deleted adapter was the active adapter. It is important + that the new adapter is chosen by the caller in a deterministic way, so that the same adapter is chosen on all + layers. + """ + if adapter_name not in self.modules_to_save: + return + + # set new active adapter, if necessary + # note: there can only ever be one active adapter, unlike for LoRA etc. + if isinstance(new_active_adapters, (list, tuple)) and len(new_active_adapters) > 1: + name = self.__class__.__name__ + raise ValueError( + f"Attempted to set multiple ({new_active_adapters}) adapters at once for {name}, which is not allowed." + ) + + if adapter_name in self._adapters: + self._adapters.remove(adapter_name) + + if not new_active_adapters: + # no active adapter now + del self.modules_to_save[adapter_name] + self._active_adapter = [] + return + + new_active_adapter = new_active_adapters[0] + if new_active_adapter not in self.modules_to_save: + # a new active adapter was chosen but it seems like it has no modules_to_save + del self.modules_to_save[adapter_name] + self._active_adapter = [] + return + + if new_active_adapter != self.active_adapters[0]: + self.set_adapter(new_active_adapter) + del self.modules_to_save[adapter_name] + + def adapter_state_dict_load_map(self, adapter_name): + # Maps the module keys as they are in the saved state dict to the in-memory state dict. + # Must contain all keys that are supposed to be loaded. + if adapter_name not in self._adapters: + # In caes of multiple adapters, each bringing their own modules to save, each + # ModulesToSaveWrapper will be queried but not every wrapper is obliged to serve the same adapters. + return {} + return {k: f"modules_to_save.{adapter_name}.{k}" for k in self.modules_to_save[adapter_name].state_dict()} + + def adapter_state_dict(self, adapter_name, state_dict): + if adapter_name not in self._adapters: + # In caes of multiple adapters, each bringing their own modules to save, each + # ModulesToSaveWrapper will be queried but not every wrapper is obliged to serve the same adapters. + return {} + + return { + k: state_dict[f"modules_to_save.{adapter_name}.{k}"] + for k in self.modules_to_save[adapter_name].state_dict() + } + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Unloading in case of `ModulesToSave` means to simply return the wrapped module. + + However, if the wrapped module is itself a tuner, we'll call merge on it before. + """ + new_module = self.modules_to_save[self.active_adapter] + + # TODO: not sure if this is still a sensible thing to do. We would basically have to + # do the same checks as `_unload_and_optionally_merge` to support MHA, for example. + if hasattr(new_module, "base_layer"): + # check if the module is itself a tuner layer + if merge: + new_module.merge(safe_merge=safe_merge, adapter_names=adapter_names) + new_module = new_module.get_base_layer() + + return new_module + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + return set(self.modules_to_save.keys()) + + +class TrainableTokensWrapper(AuxiliaryTrainingWrapper): + """Wraps a module (typically an embedding layer) that is supposed to be re-trained selectively (i.e. + solely updating a few columns) using the `TrainableTokensLayer` PEFT method. + + Supports weight-tying to another adapter when passed a `tied_adapter` which is expected to be a + `TrainableTokensLayer`. + """ + + # All names of layers that may contain adapter (trainable) weights + adapter_layer_names: tuple[str, ...] = ("token_adapter.trainable_tokens_delta",) + other_param_names: tuple[str, ...] = ("token_adapter.token_indices", "token_adapter.trainable_tokens_original") + + def __init__( + self, + module_to_save: torch.nn.Module, + adapter_name: str, + token_indices: list[int], + tied_adapter=None, + ) -> None: + super().__init__(module_to_save, adapter_name, token_indices=token_indices, tied_adapter=tied_adapter) + + # unset the original_module attribute since we're using a property to remove this from the state dict. + self.original_module = None + + @property + def original_module(self): + # use a property instead of an attribute to exclude this pointer from the state dict + # to make sure that it will not be saved. + return self.token_adapter.base_layer + + def init_modules(self, adapter_name, token_indices, tied_adapter): + # use a local import to avoid potential circular imports + from peft.tuners.trainable_tokens import TrainableTokensLayer + + # since super().__init__() calls update before we have a chance to initialise the adapter we would + # need here, we do the initialization here. + self.token_adapter = TrainableTokensLayer(self.original_module, adapter_name, token_indices, tied_adapter) + + def _error_message_name(self): + return "trainable_token_indices" + + def _hasattr_wrapped(self, name, modules): + return name == "weight" + + def _getattr_wrapped(self, name, modules): + # some models query self.wte.weight.dtype, some may query the weights directly. for the first case it is not + # necessary to do anything special but we don't know if is going to be `.dtype`. so we need to get the merged + # weights from the adapter. + if name == "weight": + return modules["token_adapter"].get_merged_weights(self.token_adapter.active_adapters) + + raise RuntimeError( + f"This code should've never been reached, probably a bad check in `_hasattr_wrapped` for {name}. " + "Please file an issue under https://github.com/huggingface/peft/issues." + ) + + def _forward_wrapped(self, x, *args, **kwargs): + if not self.active_adapters: + return self._forward_wrapped_passthrough(x, *args, **kwargs) + return self.token_adapter(x) + + def _forward_wrapped_mixed_batch(self, x, active_adapter, *args, **kwargs): + return self.token_adapter.forward_adapters(x, [active_adapter]) + + def _forward_wrapped_passthrough(self, x, *args, **kwargs): + # the token adapter knows how to deal with disabled adapter / no active adapter, don't call original_module + # directly + return self.token_adapter(x, *args, **kwargs) + + def update(self, active_adapter, **kwargs): + # TODO this does not support deepspeed/fsdp since it is missing a context manager + # see ModulesToSaveWrapper implementation + if active_adapter not in self._adapters: + self.token_adapter.update_layer(active_adapter, **kwargs) + + super().update(active_adapter) + + def adapter_state_dict_load_map(self, adapter_name): + if self.token_adapter.tied_adapter: + return {} + return {"token_adapter.trainable_tokens_delta": f"token_adapter.trainable_tokens_delta.{adapter_name}"} + + def adapter_state_dict(self, adapter_name, state_dict): + if self.token_adapter.tied_adapter: + # storing of weight-tied layers is not up to us and will be handled by + # transformers. we're just here to keep those layers in sync during training. + # therefore we return an empty state dict. + return {} + + return { + f"token_adapter.{k}": state_dict[f"token_adapter.{k}.{adapter_name}"] for k in ["trainable_tokens_delta"] + } + + def enable_adapters(self, enabled: bool): + """Enables/disables the underlying `TrainableTokens` adapter. + Also handles the internal adapter disable flag. + """ + super().enable_adapters(enabled) + + self.token_adapter.enable_adapters(enabled) + + def check_set_adapter(self, adapter_name: str | list[str]) -> str | None: + """Helper function to check if the given adapter(s) can be set. + + Return the name of the adapter to be set or None if no adapter should be set. + """ + if isinstance(adapter_name, str): + return adapter_name + + # adapter_name is a list of str + if len(adapter_name) == 0: + raise ValueError("Please specify at least one adapter to set") + + # TODO In theory, multiple active trainable tokens is fine when the indices don't overlap + adapter_names_in_module = [n for n in adapter_name if n in self.token_adapter.trainable_tokens_delta] + + if len(adapter_names_in_module) > 1: + raise ValueError(f"Only one adapter can be set at a time for {self}, got {len(adapter_names_in_module)}") + + adapter_name_to_set: str | None + if not adapter_names_in_module: + adapter_name_to_set = None + else: + adapter_name_to_set = adapter_names_in_module[0] + + return adapter_name_to_set + + def set_adapter(self, adapter_names: Union[str, list[str]], inference_mode: bool = False) -> None: + super().set_adapter(adapter_names, inference_mode=inference_mode) + self.token_adapter.set_adapter(adapter_names, inference_mode=inference_mode) + + def delete_adapter(self, adapter_name: str, new_active_adapters: Optional[list[str]]) -> None: + """ + Delete the adapter if present. + + This method will also set a new active adapter if the deleted adapter was the active adapter. It is important + that the new adapter is chosen by the caller in a deterministic way, so that the same adapter is chosen on all + layers. + """ + self.token_adapter.delete_adapter(adapter_name) + + # set new active adapter, if necessary + # note: there can only ever be one active adapter, unlike for LoRA etc. + if isinstance(new_active_adapters, (list, tuple)) and len(new_active_adapters) > 1: + name = self.__class__.__name__ + raise ValueError( + f"Attempted to set multiple ({new_active_adapters}) adapters at once for {name}, which is not allowed." + ) + + if adapter_name in self._adapters: + self._adapters.remove(adapter_name) + + if not new_active_adapters: + self._active_adapter = [] + return + + if new_active_adapters[0] not in self.token_adapter.trainable_tokens_delta: + # a new active adapter was chosen but it seems like it has no trainable_tokens + self._active_adapter = [] + return + + new_active_adapter = new_active_adapters[0] + self.set_adapter(new_active_adapter) + + def unload_and_optionally_merge_module( + self, merge: bool, safe_merge: bool, adapter_names: Optional[list[str]] + ) -> torch.nn.Module: + """Unloading for `TrainableTokensWrapper` means to return the wrapped module, e.g. the embedding layer and, + if requested, merging the `TrainableTokens` adapter onto the wrapped module. + """ + if merge: + self.token_adapter.merge(safe_merge=safe_merge, adapter_names=adapter_names) + return self.token_adapter.get_base_layer() + + def _get_available_adapters(self) -> set[str]: + """Return all adapter names that can be found on this module.""" + return set(self.token_adapter.trainable_tokens_delta.keys()) + + +def _get_input_embeddings_name(model, default=None): + if not hasattr(model, "get_input_embeddings"): + return default + + input_embeddings = model.get_input_embeddings() + for name, module in model.named_modules(): + if module is input_embeddings: + return name + + return default + + +def _get_submodules(model, key): + parent = model.get_submodule(".".join(key.split(".")[:-1])) + target_name = key.split(".")[-1] + target = model.get_submodule(key) + return parent, target, target_name + + +def _get_submodules_with_grandparent(model, key): + parent = model.get_submodule(".".join(key.split(".")[:-1])) + try: + grandparent = model.get_submodule(".".join(key.split(".")[:-2])) + except AttributeError: + # no grand parent + grandparent = None + target_name = key.split(".")[-1] + target = model.get_submodule(key) + return parent, grandparent, target, target_name + + +def _freeze_adapter(model, adapter_name): + for n, p in model.named_parameters(): + if adapter_name in n: + p.requires_grad = False + + +def _set_trainable( + model, + adapter_name, + module_names, + inference_mode: bool, + strict_module_check: bool = False, + wrapper_cls: Optional[AuxiliaryTrainingWrapper] = None, + activate_adapter: bool = True, + **wrapper_kwargs, +): + """Wraps modules that are supposed to be re-trained either normally, i.e. marking them to require gradients and + saving them alongside other modules, or with certain methods that go alongside PEFT methods, such as retraining + specific token indices using selective read/write. + + Note that you need to validate beforehand if there are layers targeted by multiple wrappers, e.g. if the + 'embedding' layer is configured for both `ModulesToSaveWrapper` and `TrainableTokensWrapper` there would be + conflicts down the line. + + The default is to wrap the module in a `ModulesToSaveWrapper` wrapper. + + If `strict_module_check` is set, this method raises an ValueError, similar to BaseTuner.inject_adapter when none of + the requested modules in `module_names` is not found in the model. + + The `active_adapter` flag indicates if this new adapter should be activated. + """ + from peft.tuners.tuners_utils import BaseTunerLayer + + if wrapper_cls is None: + wrapper_cls = ModulesToSaveWrapper + + if not module_names: + # This is useful for the case that the PEFT config does not have `modules_to_save`, e.g. + # in the case of prompt tuning and friends. + return + + trainable_modules = [] + found_modules = set() + # disable removal of duplicates to support targeting tied weights + key_list = [key for key, _ in model.named_modules(remove_duplicate=False)] + + for key in key_list: + target_module_found = any(key.endswith(target_key) for target_key in module_names) + if target_module_found: + parent, grandparent, target, target_name = _get_submodules_with_grandparent(model, key) + if isinstance(grandparent, BaseTunerLayer): + # This is an extreme edge case: Let's assume that there is a PEFT config with + # modules_to_save=["default"], which is the same name as the adapter name. The PEFT method's adapter + # (e.g. LoRA) is applied first. Then, when the modules_to_save matching is performed, the LoRA layer + # would be considered a valid target. Assuming that the name is "foo.bar.lora_A.default", it would + # match, with "default" being an nn.Linear and the parent, "lora_A", being an nn.ModuleDict. This by + # itself is not enough to prove that this is an unintended match. Thererfore, we also need to check the + # grandparent, "bar", that would be a lora.LoraLayer. When we see this, we should raise an error. + raise ValueError( + f"You are trying to target a module with {wrapper_cls} that is a child of {type(grandparent)}. " + "This is almost certainly not the intended behavior. Please ensure that the adapter name, " + f"'{adapter_name}', does not conflict with any of the targeted modules." + ) + + # For transformers >=5 we need to check the grandparent to detect already modified tied weights. The way + # the new `get_tied_weights_keys` works is that we resolve the current name of the module tied to the + # embeddings. If we replaced the tied weight (i.e. moved it to, say, `lm_head.token_adapter.base_layer`) + # we'll get the new name whereas the old way was that we got `lm_head` regardless of whether it was modified + # or not. We'll assume that we always have two levels of nesting and therefore do the same check as before + # but on the grandparent to accomodate for the new behavior. + if isinstance(grandparent, wrapper_cls): + grandparent.update(adapter_name, **wrapper_kwargs) + grandparent.set_adapter(grandparent.active_adapter, inference_mode=inference_mode) + elif isinstance(target, wrapper_cls): + target.update(adapter_name, **wrapper_kwargs) + target.set_adapter(target.active_adapter, inference_mode=inference_mode) + else: + new_module = wrapper_cls(target, adapter_name, **wrapper_kwargs) + if activate_adapter: + new_module.set_adapter(adapter_name, inference_mode=inference_mode) + else: + new_module.set_adapter([], inference_mode=inference_mode) + setattr(parent, target_name, new_module) + trainable_modules.append(new_module) + found_modules.add(target_name) + + not_found = set(module_names).difference(found_modules) + if strict_module_check and not found_modules: + raise ValueError( + f"Target modules {not_found} not found in the base model. Please check the target modules and try again." + ) + + return trainable_modules + + +def _set_adapter(model, adapter_name: str | list[str], inference_mode: bool = False) -> None: + """Call set_adapter on the AuxiliaryTrainingWrapper modules""" + for module in model.modules(): + if isinstance(module, AuxiliaryTrainingWrapper): + # only check the adapter_name if we actually encounter a AuxiliaryTrainingWrapper, otherwise we don't care + adapter_name_to_set = module.check_set_adapter(adapter_name) + + # if the adapter is found in this module, set it as the active adapter, else disable the adapters of this + # module + if adapter_name_to_set in module._adapters: + module.set_adapter(adapter_name_to_set, inference_mode=inference_mode) + else: + module.set_adapter([], inference_mode=inference_mode) + + +def _prepare_prompt_learning_config(peft_config, model_config): + # In case of VLM we focus on the language model portion of the model. + if "text_config" in model_config: + model_config = model_config["text_config"] + + if peft_config.num_layers is None: + if "num_hidden_layers" in model_config: + num_layers = model_config["num_hidden_layers"] + elif "num_layers" in model_config: + num_layers = model_config["num_layers"] + elif "n_layer" in model_config: + num_layers = model_config["n_layer"] + else: + raise ValueError("Please specify `num_layers` in `peft_config`") + peft_config.num_layers = num_layers + + if peft_config.token_dim is None: + if "hidden_size" in model_config: + token_dim = model_config["hidden_size"] + elif "n_embd" in model_config: + token_dim = model_config["n_embd"] + elif "d_model" in model_config: + token_dim = model_config["d_model"] + else: + raise ValueError("Please specify `token_dim` in `peft_config`") + peft_config.token_dim = token_dim + + if peft_config.num_attention_heads is None: + if "num_attention_heads" in model_config: + num_attention_heads = model_config["num_attention_heads"] + elif "n_head" in model_config: + num_attention_heads = model_config["n_head"] + elif "num_heads" in model_config: + num_attention_heads = model_config["num_heads"] + elif "encoder_attention_heads" in model_config: + num_attention_heads = model_config["encoder_attention_heads"] + else: + raise ValueError("Please specify `num_attention_heads` in `peft_config`") + peft_config.num_attention_heads = num_attention_heads + + # For grouped-query attention, see #1901. + if (peft_config.peft_type in {"PREFIX_TUNING", "CARTRIDGE"}) and ("num_key_value_heads" in model_config): + num_key_value_heads = model_config["num_key_value_heads"] + if model_config.get("head_dim", None) is not None: + head_dim = model_config["head_dim"] + else: + head_dim = peft_config.token_dim // peft_config.num_attention_heads + peft_config.token_dim = head_dim * num_key_value_heads + peft_config.num_attention_heads = num_key_value_heads + + if getattr(peft_config, "encoder_hidden_size", None) is None: + peft_config.encoder_hidden_size = peft_config.token_dim + + return peft_config + + +def _get_no_split_modules(model) -> set[str]: + """ + Get the modules of the model that should not be split when using device_map. We iterate through the modules to get + the underlying `_no_split_modules`. + + Returns: + `List[str]`: List of modules that should not be split + """ + # After discussion in https://github.com/huggingface/transformers/pull/38141, based on: + # https://github.com/huggingface/transformers/blob/1e921a3a9cea92b383ca4b0484ee45596bbdadc3/src/transformers/modeling_utils.py#L2677-L2704 + _no_split_modules: set[str] = set() + if not hasattr(model, "_no_split_modules"): + return _no_split_modules + + if is_transformers_ge_v5_1_0: + # See https://github.com/huggingface/transformers/commit/36ec3bfa33ebf6c3b38a1d6808292aeea4aae84d + return model._no_split_modules + + # TODO remove once transformers <5.1.0 is not supported anymore + modules_to_check = [model] + while len(modules_to_check) > 0: + module = modules_to_check.pop(-1) + # if the module does not appear in _no_split_modules, we also check the children + if module.__class__.__name__ not in _no_split_modules: + if isinstance(module, PreTrainedModel): + if module._no_split_modules is not None: + _no_split_modules = _no_split_modules | set(module._no_split_modules) + modules_to_check += list(module.children()) + return _no_split_modules + + +def fsdp_auto_wrap_policy(model): + if hasattr(FullyShardedDataParallelPlugin, "get_module_class_from_name"): + get_module_class_from_name = FullyShardedDataParallelPlugin.get_module_class_from_name + else: + from accelerate.utils.dataclasses import get_module_class_from_name + from torch.distributed.fsdp.wrap import _or_policy, lambda_auto_wrap_policy, transformer_auto_wrap_policy + + from ..tuners import CartridgeEncoder, PrefixEncoder, PromptEmbedding, PromptEncoder + + default_transformer_cls_names_to_wrap = ",".join(_get_no_split_modules(model)) + transformer_cls_names_to_wrap = os.environ.get( + "FSDP_TRANSFORMER_CLS_TO_WRAP", default_transformer_cls_names_to_wrap + ).split(",") + transformer_cls_to_wrap = {CartridgeEncoder, PrefixEncoder, PromptEncoder, PromptEmbedding} + for layer_class in transformer_cls_names_to_wrap: + if len(layer_class) == 0: + continue + transformer_cls = get_module_class_from_name(model, layer_class) + if transformer_cls is None: + raise Exception("Could not find the transformer layer class to wrap in the model.") + else: + transformer_cls_to_wrap.add(transformer_cls) + + def lambda_policy_fn(module): + if ( + len(list(module.named_children())) == 0 + and getattr(module, "weight", None) is not None + and module.weight.requires_grad + ): + return True + return False + + lambda_policy = functools.partial(lambda_auto_wrap_policy, lambda_fn=lambda_policy_fn) + transformer_wrap_policy = functools.partial( + transformer_auto_wrap_policy, + transformer_layer_cls=transformer_cls_to_wrap, + ) + + auto_wrap_policy = functools.partial(_or_policy, policies=[lambda_policy, transformer_wrap_policy]) + return auto_wrap_policy + + +def transpose(weight, fan_in_fan_out): + if not fan_in_fan_out: + return weight + + if isinstance(weight, torch.nn.Parameter): + return torch.nn.Parameter(weight.T) + return weight.T + + +def _is_valid_match(key: str, target_key: str): + """ + Helper function to match module names target_key and key. Makes sure that either the key is exactly the target_key + or the target_key is a submodule of key + """ + if key.endswith(target_key): + if len(key) > len(target_key): + return key.endswith("." + target_key) # must be a sub module + return True + return False + + +def _get_batch_size(input_ids: Optional[torch.Tensor], inputs_embeds: Optional[torch.Tensor]) -> int: + """Get the batch size based on either input_ids or input_embeds + + Raises an ValueError if both are None. + + """ + if (input_ids is None) and (inputs_embeds is None): + raise ValueError("You have to provide either input_ids or inputs_embeds") + + if input_ids is not None: + batch_size = input_ids.shape[0] + else: + batch_size = inputs_embeds.shape[0] + return batch_size + + +def get_quantization_config(model: torch.nn.Module, method: str): + """ + Get the quantization config of the related quantization method + """ + if ( + hasattr(model, "config") + and hasattr(model.config, "quantization_config") + and (getattr(model, "quantization_method", None) == method) + ): + return model.config.quantization_config + return None + + +def get_gptqmodel_quant_linear(gptq_quantization_config, device_map=None): + """ + Get the right GPTQQuantLinear class based on the quantization config file + """ + if gptq_quantization_config is None: + return None + + if not is_gptqmodel_available(): + return None + + from gptqmodel import BACKEND + from gptqmodel.quantization import METHOD + from gptqmodel.utils.importer import hf_select_quant_linear_v2 + + desc_act = gptq_quantization_config.desc_act + group_size = gptq_quantization_config.group_size + bits = gptq_quantization_config.bits + checkpoint_format = ( + gptq_quantization_config.checkpoint_format + if hasattr(gptq_quantization_config, "checkpoint_format") + else "gptq" + ) + sym = gptq_quantization_config.sym + meta = gptq_quantization_config.meta if hasattr(gptq_quantization_config, "meta") else None + + QuantLinear = hf_select_quant_linear_v2( + bits=bits, + group_size=group_size, + desc_act=desc_act, + sym=sym, + device_map=device_map, + format=checkpoint_format, + quant_method=METHOD.GPTQ, + meta=meta, + backend=BACKEND.AUTO_TRAINABLE, + pack=False, + ) + + return QuantLinear + + +def id_tensor_storage(tensor: torch.Tensor) -> tuple[torch.device, int, int]: + """ + Unique identifier to a tensor storage. Multiple different tensors can share the same underlying storage. For + example, "meta" tensors all share the same storage, and thus their identifier will all be equal. This identifier is + guaranteed to be unique and constant for this tensor's storage during its lifetime. Two tensor storages with + non-overlapping lifetimes may have the same id. + + This method is the exact same copy of + https://github.com/huggingface/transformers/blob/main/src/transformers/pytorch_utils.py#L282C1-L300C58 but we added + it here manually to avoid import issue with old versions of transformers. + """ + if tensor.device.type == "xla" and is_torch_tpu_available(): + # NOTE: xla tensors dont have storage + # use some other unique id to distinguish. + # this is a XLA tensor, it must be created using torch_xla's + # device. So the following import is safe: + import torch_xla + + unique_id = torch_xla._XLAC._xla_get_tensor_id(tensor) + else: + unique_id = storage_ptr(tensor) + + return tensor.device, unique_id, storage_size(tensor) + + +def cast_mixed_precision_params(model, dtype): + """ + Cast all non-trainable parameters of the model to the given `dtype`. The `dtype` can be `torch.float16` or + `torch.bfloat16` as per the mixed-precision training you are performing. The trainable parameters are cast to full + precision. This is meant to reduce the GPU memory usage when using PEFT methods by using half-precision dtype for + non-trainable parameters. Having the trainable parameters in full-precision preserves training stability when using + automatic mixed-precision training. + + Args: + model (`torch.nn.Module`): + The model to cast the non-trainable parameters of. + dtype (`torch.dtype`): + The dtype to cast the non-trainable parameters to. The `dtype` can be `torch.float16` or + `torch.bfloat16` as per the mixed-precision training you are performing. + """ + for p in model.parameters(): + if not p.requires_grad: + p.data = p.to(dtype) + else: + p.data = p.to(torch.float32) + + +def str_to_bool(value: str) -> int: + """ + Converts a string representation of truth to `True` (1) or `False` (0). + + True values are `y`, `yes`, `t`, `true`, `on`, and `1`; False value are `n`, `no`, `f`, `false`, `off`, and `0`; + """ + # same as function as in accelerate.utils, which replaces the deprecated distutils.util.strtobool + value = value.lower() + if value in ("y", "yes", "t", "true", "on", "1"): + return 1 + elif value in ("n", "no", "f", "false", "off", "0"): + return 0 + else: + raise ValueError(f"invalid truth value {value}") + + +def check_file_exists_on_hf_hub(repo_id: str, filename: str, **kwargs) -> Optional[bool]: + """Check if a file exists on HF Hub, if check was not successful returns None instead of erroring. + + Respect offline mode if set. + + """ + exists: Optional[bool] = None + if str_to_bool(os.environ.get("HF_HUB_OFFLINE", "0")): + # user set offline mode, cannot check + return exists + + try: + exists = file_exists(repo_id, filename, **kwargs) + except (HFValidationError, EntryNotFoundError): + # error, exists stays None + pass + except Exception as e: + warnings.warn( + f"Unable to fetch remote file due to the following error {e} - silently ignoring the lookup" + f" for the file {filename} in {repo_id}." + ) + + return exists + + +def match_target_against_key(target_pattern: str, key: str): + """Backing function for `target_modules` config parameter. + + Having this as its own function ensures that target key matching can be implemented in the same way everywhere. + """ + return re.fullmatch(target_pattern, key) + + +def get_pattern_key(pattern_keys: Sequence[str], key_to_match: str) -> str: + """Match a substring of key_to_match in pattern keys""" + for key in pattern_keys: + match = re.match(rf"(.*\.)?({key})$", key_to_match) + if not match: + continue + return key + + return key_to_match + + +def set_additional_trainable_modules(model, peft_config, model_config, adapter_name, activate_adapter: bool = True): + """Handle the resolution of additional trainable modules (also called AuxiliaryTrainingWrapper) + by checking the config if such modules are requested and adding them to the model. + + Currently trainable tokens and modules to save are considered additional trainable modules. + + If `activate_adapter` is set to `False`, the adapter won't be activated. This is typically the case when + `model.add_adapter` or `model.load_adapter` are being called. + """ + if getattr(peft_config, "modules_to_save", None) is not None: + # this may add a new ModulesToSaveWrapper + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=getattr(peft_config, "modules_to_save", None), + activate_adapter=activate_adapter, + ) + + if getattr(peft_config, "modules_to_tie", None) is not None: + # Tie the modules if any tied layer is passed in `modules_to_save`. + # This should always be called after + # `_set_trainable` is called for `modules_to_save`. + tied_module = getattr(model.get_input_embeddings().modules_to_save, adapter_name) + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=getattr(peft_config, "modules_to_tie", None), + activate_adapter=activate_adapter, + tied_module=tied_module, + ) + + if getattr(peft_config, "trainable_token_indices", None) is not None: + if isinstance(peft_config.trainable_token_indices, dict): + target_layers = peft_config.trainable_token_indices + else: + layer_name = _get_input_embeddings_name(model, "embed_tokens") + target_layers = {layer_name: peft_config.trainable_token_indices} + + modules_to_save = getattr(peft_config, "modules_to_save", None) + if modules_to_save is not None: + for target_layer_name in target_layers: + if target_layer_name in modules_to_save: + raise ValueError( + "The embedding layer is already marked to be trained fully, either specify " + f'`modules_to_save=[..., "{target_layer_name}", ...]` or ' + f"`trainable_tokens={{'{target_layer_name}': x}}` but not both." + ) + + # Check weight tying configuration first to determine which layers to wrap + weights_tied = model_config.get("tie_word_embeddings", False) + ensure_weight_tying = getattr(peft_config, "ensure_weight_tying", False) + + # When multiple target layers are specified, check if they correspond to tied weights + indices_mismatch = False + layers_to_skip = set() + tied_layer_keys = [] + + if len(target_layers) > 1 and weights_tied: + # Get module names that are tied with the embedding + tied_module_names = set(_get_module_names_tied_with_embedding(model)) + + # Also get the input embedding layer name as it's the source of tied weights + embedding_module = model.get_input_embeddings() + # Get the full embedding name (not just the last part) to support nested structures + embedding_name = next(n for n, m in model.named_modules() if m is embedding_module) + + # Find which target layers are in the tied weights (including the embedding source) + for target_layer_name in target_layers: + # Check if this is the embedding layer (use endswith to allow flexible matching) + # This allows users to specify just "embed_tokens" OR "m1.encoder.embed_tokens" for precision + if embedding_name.endswith(target_layer_name): + tied_layer_keys.append(target_layer_name) + continue + # Check if this target layer matches any tied module (considering nested structures) + for tied_module in tied_module_names: + if tied_module.endswith(target_layer_name) or target_layer_name in tied_module.split("."): + tied_layer_keys.append(target_layer_name) + break + + # If we found multiple tied layers in our targets, check their indices + if len(tied_layer_keys) >= 2: + # Check if all tied layers have the same indices + first_indices = target_layers[tied_layer_keys[0]] + indices_mismatch = not all(target_layers[key] == first_indices for key in tied_layer_keys[1:]) + + # Raise error immediately if ensure_weight_tying=True and indices mismatch + if indices_mismatch and ensure_weight_tying: + tied_layers_info = ", ".join([f"{key}: {target_layers[key]}" for key in tied_layer_keys]) + raise ValueError( + f"Cannot ensure weight tying when different token indices are specified for tied layers. " + f"Conflicting layers: {tied_layers_info}. " + f"Please use the same indices for all tied layers or set ensure_weight_tying=False." + ) + + # If indices match, skip tied modules (except embedding) as they'll be handled by weight tying logic + if not indices_mismatch: + layers_to_skip = set(tied_layer_keys) & tied_module_names + + # Wrap target layers (skip those that will be handled by weight tying logic) + for target_layer_name, token_indices in target_layers.items(): + if target_layer_name in layers_to_skip: + continue + + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=[target_layer_name], + strict_module_check=True, + wrapper_cls=TrainableTokensWrapper, + token_indices=token_indices, + activate_adapter=activate_adapter, + ) + + # Warn if user expects weight tying but model doesn't have tied weights + if not weights_tied and ensure_weight_tying: + warnings.warn( + "ensure_weight_tying=True but the model does not have tied weights " + "(tie_word_embeddings=False). Weight tying will not be applied for trainable_token_indices." + ) + + # Apply weight tying when appropriate + should_apply_tying = ( + weights_tied + and isinstance(model.get_input_embeddings(), TrainableTokensWrapper) + and (ensure_weight_tying or not indices_mismatch) + ) + + if should_apply_tying: + # There might be the possibility that we have output weights that are tied to the input weights. + # In that case we will tie any module that wants tied weights to the token adapter to make sure that + # any modification is reflected in the tied layers as well. + tied_weights_module_names = _get_module_names_tied_with_embedding(model) + token_adapter = model.get_input_embeddings().token_adapter + _set_trainable( + model, + adapter_name, + inference_mode=peft_config.inference_mode, + module_names=tied_weights_module_names, + strict_module_check=True, + wrapper_cls=TrainableTokensWrapper, + token_indices=token_adapter.token_indices[adapter_name], + tied_adapter=model.get_input_embeddings().token_adapter, + ) + + +def create_attention_mask( + model, *, model_input, attention_mask, past_key_values, cache_position, batch_size, sequence_length, position_ids +): + # adapted from: + # https://github.com/huggingface/transformers/blob/cb4c56ce0dfa1350267ed28e57760986a58a9ba4/src/transformers/generation/utils.py#L644-L680 + # In PEFT, we sometimes need to re-create the attention mask. This is because some prompt learning methods insert + # new items into the sequence, which results in the attention mask needing an update. We re-use transformers code + # for this as much as possible. + transformers_ge_4_53_1 = version.parse(transformers.__version__) >= version.parse("4.53.1") + if transformers_ge_4_53_1: + # the function already exists in v4.53.0 but has a different signature, so we check for 4.53.1 + from transformers.masking_utils import create_masks_for_generate + else: + raise ImportError("Your transformers version is too old, please upgrade it to >= 4.53.1") + + # Create the causal mask with fixed shape in advance, to reduce recompilations. If the function to create + # the 4D causal mask exists, it should be present in the base model (XXXModel class) or in its decoder. + base_model = getattr(model, model.base_model_prefix, model) + decoder = base_model.get_decoder() if hasattr(base_model, "get_decoder") else None + causal_mask_creation_function = getattr(base_model, "_prepare_4d_causal_attention_mask_with_cache_position", None) + if causal_mask_creation_function is None and decoder is not None: # it may be in the decoder + causal_mask_creation_function = getattr(decoder, "_prepare_4d_causal_attention_mask_with_cache_position", None) + + # If it's not defined, it means the model uses the new general mask API + if causal_mask_creation_function is None: # can't be found + token_type_ids = getattr(model_input, "token_type_ids", None) + # Some models may overwrite the general one + causal_mask_creation_function = getattr(model, "create_masks_for_generate", create_masks_for_generate) + attention_mask = causal_mask_creation_function( + config=model.config, + # we only need batch size, seq_length and dtype here - we don't care about the values of the embeddings + input_embeds=torch.empty((batch_size, sequence_length), dtype=model.dtype), + attention_mask=attention_mask, + cache_position=cache_position, + past_key_values=past_key_values, + token_type_ids=token_type_ids, + position_ids=position_ids, + ) + else: + attention_mask = causal_mask_creation_function( + attention_mask, + sequence_length=sequence_length, + target_length=past_key_values.get_max_cache_shape(), + dtype=model.dtype, + cache_position=cache_position, + batch_size=batch_size, + config=model.config, + past_key_values=past_key_values, + position_ids=position_ids, + ) + return attention_mask + + +def _get_module_names_tied_with_embedding(model) -> list[str]: + """ + Get the list of the fully qualified names of the modules that are tied to the input embeddings. In case of a + source-target-mapping `_tied_weights_keys`, it will attempt to identify the input embedding weights from the + mapping and return the list of tied modules accordingly. This gives a unified interface to both transformers v4 + tied weights and v5 mapped tied weights. + + For example: For models which have `embed_tokens` and `lm_head` as the tied keys, this function will return + [`lm_head`]. The PEFT model is assumed to be transparent: returned names will be relative to the base model, so + even though `model.base_model.lm_head` is tied, the returned name is `lm_head` since such attributes are forwarded + to the base model anyway. Non-transformer models have to provide a `_tied_weights_keys` attribute for this function + to work. + + Note that this function will not check if weight tying is disabled by the model's config. There can be the case + that the weight tying definition is present but the tying is disabled via `model_config.tie_word_embeddings=False`. + You have to check that yourself. + """ + tied_weights: list[str] = [] + + if hasattr(model, "get_base_model"): + # unpack PeftModel + model = model.get_base_model() + + if hasattr(model, "tuner_layer_cls"): + # unpack BaseTuner + model = model.model + + if not hasattr(model, "_tied_weights_keys"): + return [] + + base_layer_pattern = re.compile(r"[^.]+\.base_layer\.") + + if isinstance(model._tied_weights_keys, dict): + if not hasattr(model, "get_input_embeddings"): + raise ValueError( + "The supplied model implements `_tied_weights_keys` as a dict but doesn't implement " + "'get_input_embeddings' so we can't determine which weights are tied to embeddings." + ) + + # collect all _tied_weights_keys, as sub-modules may have additional entries + tied_weights_keys: dict[str, str] = {} + for module_name, module in model.named_modules(): + module_tied_weights_keys = getattr(module, "_tied_weights_keys", None) + if module_tied_weights_keys and not module_name: + tied_weights_keys.update(module_tied_weights_keys) + elif module_tied_weights_keys: + tied_weights_keys.update( + {f"{module_name}.{k}": f"{module_name}.{v}" for k, v in module_tied_weights_keys.items()} + ) + + # technically it would be sufficient to just return candidates since that contains all the keys of + # all models that are tied (not just equal!) to the input embeddings. the only reason why we aren't + # doing that is because we need to filter out the original embedding name since we promise to just + # return the keys of the tying targets. + input_embedding_params = set(model.get_input_embeddings().parameters()) + candidates = [n for n, p in model.named_parameters(remove_duplicate=False) if p in input_embedding_params] + + # Consider the case that sources and targets are already wrapped by a PEFT method. In that case we won't + # find them by their old names. Therefore, we need to create a map of the new names to the old names so + # that we can translate back and forth. + peft_reverse_mapping = {base_layer_pattern.sub("", name): name for name in candidates} + + # AuxiliaryTrainingWrapper don't have an adapter suffix but still have a base_layer attribute, + # add those as a potential translation. + peft_reverse_mapping.update(**{name.replace("base_layer.", ""): name for name in candidates}) + + tied_weights.extend( + peft_reverse_mapping.get(k, k) + for k, v in tied_weights_keys.items() + if peft_reverse_mapping.get(v, v) in candidates + ) + + elif model._tied_weights_keys is not None: + # TODO remove this when transformers