Stage Harbor release files 63501-64000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-955732fda55e/tests/source/tests/test_multitask_prompt_tuning.py +288 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_osf.py +72 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_other.py +624 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_poly.py +100 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_randlora.py +301 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_seq_classifier.py +320 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_shira.py +278 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_stablediffusion.py +462 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_target_parameters.py +546 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_torch_compile.py +599 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_trainable_tokens.py +1397 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_tuners_utils.py +0 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_vblora.py +269 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_vera.py +298 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_vision_models.py +160 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/test_xlora.py +473 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/testing_common.py +1887 -0
- tasks/tasksmith-955732fda55e/tests/source/tests/testing_utils.py +390 -0
- tasks/tasksmith-955732fda55e/tests/test.sh +3 -0
- tasks/tasksmith-955732fda55e/tests/test_driver.py +41 -0
- tasks/tasksmith-955732fda55e/tests/test_results.py +65 -0
- tasks/tasksmith-9aea936e30e4/environment/Dockerfile +9 -0
- tasks/tasksmith-9aea936e30e4/environment/source/.gitignore +145 -0
- tasks/tasksmith-9aea936e30e4/environment/source/.pre-commit-config.yaml +13 -0
- tasks/tasksmith-9aea936e30e4/environment/source/Dockerfile +8 -0
- tasks/tasksmith-9aea936e30e4/environment/source/LICENSE +201 -0
- tasks/tasksmith-9aea936e30e4/environment/source/Makefile +71 -0
- tasks/tasksmith-9aea936e30e4/environment/source/README.md +189 -0
- tasks/tasksmith-9aea936e30e4/environment/source/docker/README.md +6 -0
- tasks/tasksmith-9aea936e30e4/environment/source/docker/peft-cpu/Dockerfile +46 -0
- tasks/tasksmith-9aea936e30e4/environment/source/docker/peft-gpu/Dockerfile +78 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/alora_finetuning/README.md +76 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/alora_finetuning/alora_finetuning.py +259 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/arrow_multitask/arrow_phi3_mini.py +383 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/arrow_multitask/requirements.txt +8 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/README.md +15 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/bdlora-performance.png +3 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/bdlora-sharding.png +3 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/bdlora_peft_demo.ipynb +439 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/chat.py +64 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/vllm_server.bash +13 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/__init__.py +0 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/boft_controlnet.md +177 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/eval.py +206 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/eval.sh +29 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/requirements.txt +10 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/test_controlnet.py +133 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/test_controlnet.sh +29 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/train_controlnet.py +545 -0
- tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/train_controlnet.sh +42 -0
tasks/tasksmith-955732fda55e/tests/source/tests/test_multitask_prompt_tuning.py
ADDED
|
@@ -0,0 +1,288 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
import tempfile
|
| 17 |
+
|
| 18 |
+
import pytest
|
| 19 |
+
import torch
|
| 20 |
+
from torch.testing import assert_close
|
| 21 |
+
from transformers import AutoModelForCausalLM
|
| 22 |
+
|
| 23 |
+
from peft import get_peft_model
|
| 24 |
+
from peft.peft_model import PeftModel
|
| 25 |
+
from peft.tuners.multitask_prompt_tuning import MultitaskPromptTuningConfig, MultitaskPromptTuningInit
|
| 26 |
+
from peft.utils import infer_device
|
| 27 |
+
from peft.utils.other import WEIGHTS_NAME, prepare_model_for_kbit_training
|
| 28 |
+
from peft.utils.save_and_load import get_peft_model_state_dict
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
MODELS_TO_TEST = [
|
| 32 |
+
"trl-internal-testing/tiny-random-LlamaForCausalLM",
|
| 33 |
+
]
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class TestMultiTaskPromptTuning:
|
| 37 |
+
"""
|
| 38 |
+
Tests for the MultiTaskPromptTuning model.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
@pytest.fixture
|
| 42 |
+
def config(cls) -> MultitaskPromptTuningConfig:
|
| 43 |
+
return MultitaskPromptTuningConfig(
|
| 44 |
+
task_type="CAUSAL_LM",
|
| 45 |
+
num_virtual_tokens=50,
|
| 46 |
+
num_tasks=3,
|
| 47 |
+
prompt_tuning_init_text=(
|
| 48 |
+
"classify the following into either positive or negative, or entailment, neutral or contradiction:"
|
| 49 |
+
),
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
transformers_class = AutoModelForCausalLM
|
| 53 |
+
torch_device = infer_device()
|
| 54 |
+
|
| 55 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 56 |
+
def test_prepare_for_training(self, model_id, config):
|
| 57 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 58 |
+
model = get_peft_model(model, config)
|
| 59 |
+
model = model.to(self.torch_device)
|
| 60 |
+
|
| 61 |
+
dummy_input = torch.LongTensor([[1, 1, 1]]).to(self.torch_device)
|
| 62 |
+
dummy_output = model.get_input_embeddings()(dummy_input)
|
| 63 |
+
|
| 64 |
+
assert not dummy_output.requires_grad
|
| 65 |
+
|
| 66 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 67 |
+
def test_prepare_for_int8_training(self, model_id, config):
|
| 68 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 69 |
+
model = prepare_model_for_kbit_training(model)
|
| 70 |
+
model = model.to(self.torch_device)
|
| 71 |
+
|
| 72 |
+
for param in model.parameters():
|
| 73 |
+
assert not param.requires_grad
|
| 74 |
+
|
| 75 |
+
model = get_peft_model(model, config)
|
| 76 |
+
|
| 77 |
+
# For backward compatibility
|
| 78 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 79 |
+
model.enable_input_require_grads()
|
| 80 |
+
else:
|
| 81 |
+
|
| 82 |
+
def make_inputs_require_grad(module, input, output):
|
| 83 |
+
output.requires_grad_(True)
|
| 84 |
+
|
| 85 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 86 |
+
|
| 87 |
+
dummy_input = torch.LongTensor([[1, 1, 1]]).to(self.torch_device)
|
| 88 |
+
dummy_output = model.get_input_embeddings()(dummy_input)
|
| 89 |
+
|
| 90 |
+
assert dummy_output.requires_grad
|
| 91 |
+
|
| 92 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 93 |
+
def test_save_pretrained(self, model_id, config):
|
| 94 |
+
seed = 420
|
| 95 |
+
torch.manual_seed(seed)
|
| 96 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 97 |
+
model = get_peft_model(model, config)
|
| 98 |
+
model = model.to(self.torch_device)
|
| 99 |
+
|
| 100 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 101 |
+
model.save_pretrained(tmp_dirname)
|
| 102 |
+
|
| 103 |
+
torch.manual_seed(seed)
|
| 104 |
+
model_from_pretrained = AutoModelForCausalLM.from_pretrained(model_id)
|
| 105 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 106 |
+
|
| 107 |
+
# check if the state dicts are equal
|
| 108 |
+
state_dict = get_peft_model_state_dict(model)
|
| 109 |
+
|
| 110 |
+
state_dict_from_pretrained = get_peft_model_state_dict(model_from_pretrained)
|
| 111 |
+
|
| 112 |
+
# check if same keys
|
| 113 |
+
assert state_dict.keys() == state_dict_from_pretrained.keys()
|
| 114 |
+
|
| 115 |
+
# Check that the number of saved parameters is 4 -- 2 layers of (tokens and gate).
|
| 116 |
+
assert len(state_dict) == 3
|
| 117 |
+
|
| 118 |
+
# check if tensors equal
|
| 119 |
+
for key in state_dict.keys():
|
| 120 |
+
assert torch.allclose(
|
| 121 |
+
state_dict[key].to(self.torch_device), state_dict_from_pretrained[key].to(self.torch_device)
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
# check if `adapter_model.safetensors` is present
|
| 125 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_model.safetensors"))
|
| 126 |
+
|
| 127 |
+
# check if `adapter_config.json` is present
|
| 128 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_config.json"))
|
| 129 |
+
|
| 130 |
+
# check if `pytorch_model.bin` is not present
|
| 131 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "pytorch_model.bin"))
|
| 132 |
+
|
| 133 |
+
# check if `config.json` is not present
|
| 134 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "config.json"))
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 137 |
+
def test_save_pretrained_regression(self, model_id, config):
|
| 138 |
+
seed = 420
|
| 139 |
+
torch.manual_seed(seed)
|
| 140 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 141 |
+
model = get_peft_model(model, config)
|
| 142 |
+
model = model.to(self.torch_device)
|
| 143 |
+
|
| 144 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 145 |
+
model.save_pretrained(tmp_dirname, safe_serialization=False)
|
| 146 |
+
|
| 147 |
+
torch.manual_seed(seed)
|
| 148 |
+
model_from_pretrained = AutoModelForCausalLM.from_pretrained(model_id)
|
| 149 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 150 |
+
|
| 151 |
+
# check if the state dicts are equal
|
| 152 |
+
state_dict = get_peft_model_state_dict(model)
|
| 153 |
+
|
| 154 |
+
state_dict_from_pretrained = get_peft_model_state_dict(model_from_pretrained)
|
| 155 |
+
|
| 156 |
+
# check if same keys
|
| 157 |
+
assert state_dict.keys() == state_dict_from_pretrained.keys()
|
| 158 |
+
|
| 159 |
+
# Check that the number of saved parameters is 4 -- 2 layers of (tokens and gate).
|
| 160 |
+
assert len(state_dict) == 3
|
| 161 |
+
|
| 162 |
+
# check if tensors equal
|
| 163 |
+
for key in state_dict.keys():
|
| 164 |
+
assert torch.allclose(
|
| 165 |
+
state_dict[key].to(self.torch_device), state_dict_from_pretrained[key].to(self.torch_device)
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# check if `adapter_model.bin` is present for regression
|
| 169 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_model.bin"))
|
| 170 |
+
|
| 171 |
+
# check if `adapter_config.json` is present
|
| 172 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_config.json"))
|
| 173 |
+
|
| 174 |
+
# check if `pytorch_model.bin` is not present
|
| 175 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "pytorch_model.bin"))
|
| 176 |
+
|
| 177 |
+
# check if `config.json` is not present
|
| 178 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "config.json"))
|
| 179 |
+
|
| 180 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 181 |
+
def test_generate(self, model_id, config):
|
| 182 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 183 |
+
model = get_peft_model(model, config)
|
| 184 |
+
model = model.to(self.torch_device)
|
| 185 |
+
|
| 186 |
+
input_ids = torch.LongTensor([[1, 1, 1], [2, 1, 2]]).to(self.torch_device)
|
| 187 |
+
attention_mask = torch.LongTensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 188 |
+
task_ids = torch.LongTensor([1, 2]).to(self.torch_device)
|
| 189 |
+
|
| 190 |
+
# check if `generate` works
|
| 191 |
+
_ = model.generate(input_ids=input_ids, attention_mask=attention_mask, task_ids=task_ids)
|
| 192 |
+
|
| 193 |
+
# check if `generate` works if positional arguments are passed
|
| 194 |
+
_ = model.generate(input_ids, attention_mask=attention_mask, task_ids=task_ids)
|
| 195 |
+
|
| 196 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 197 |
+
def test_use_cache(self, model_id, config):
|
| 198 |
+
"""Test that MultiTaskPromptTuning works when Llama config use_cache=True."""
|
| 199 |
+
torch.manual_seed(0)
|
| 200 |
+
input_ids = torch.LongTensor([[1, 1, 1], [2, 1, 2]]).to(self.torch_device)
|
| 201 |
+
task_ids = torch.LongTensor([1, 2]).to(self.torch_device)
|
| 202 |
+
|
| 203 |
+
original = AutoModelForCausalLM.from_pretrained(model_id)
|
| 204 |
+
mpt = get_peft_model(original, config)
|
| 205 |
+
mpt = mpt.to(self.torch_device)
|
| 206 |
+
|
| 207 |
+
expected = mpt.generate(input_ids=input_ids, max_length=8, task_ids=task_ids)
|
| 208 |
+
|
| 209 |
+
# Set use_cache = True and generate output again.
|
| 210 |
+
mpt.base_model.config.use_cache = True
|
| 211 |
+
actual = mpt.generate(input_ids=input_ids, max_length=8, task_ids=task_ids)
|
| 212 |
+
assert_close(expected, actual, rtol=0, atol=0)
|
| 213 |
+
|
| 214 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 215 |
+
def test_bf16_inference(self, model_id, config):
|
| 216 |
+
"""Test that MultiTaskPromptTuning works when Llama using a half-precision model."""
|
| 217 |
+
input_ids = torch.LongTensor([[1, 1, 1], [2, 1, 2]]).to(self.torch_device)
|
| 218 |
+
task_ids = torch.tensor([1, 2]).to(self.torch_device)
|
| 219 |
+
|
| 220 |
+
original = AutoModelForCausalLM.from_pretrained(model_id, dtype=torch.bfloat16)
|
| 221 |
+
mpt = get_peft_model(original, config)
|
| 222 |
+
mpt = mpt.to(self.torch_device)
|
| 223 |
+
_ = mpt.generate(input_ids=input_ids, task_ids=task_ids)
|
| 224 |
+
|
| 225 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 226 |
+
def test_generate_text_with_random_init(self, model_id, config) -> None:
|
| 227 |
+
torch.manual_seed(0)
|
| 228 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 229 |
+
config.prompt_tuning_init = MultitaskPromptTuningInit.RANDOM
|
| 230 |
+
model = get_peft_model(model, config)
|
| 231 |
+
model = model.to(self.torch_device)
|
| 232 |
+
|
| 233 |
+
input_ids = torch.LongTensor([[1, 1, 1], [2, 1, 2]]).to(self.torch_device)
|
| 234 |
+
attention_mask = torch.LongTensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 235 |
+
task_ids = torch.LongTensor([0]).to(self.torch_device)
|
| 236 |
+
|
| 237 |
+
# check if `generate` works
|
| 238 |
+
_ = model.generate(input_ids=input_ids, attention_mask=attention_mask, task_ids=task_ids)
|
| 239 |
+
|
| 240 |
+
with pytest.raises(ValueError):
|
| 241 |
+
# check if `generate` raises an error if task_ids are not passed
|
| 242 |
+
_ = model.generate(input_ids, attention_mask=attention_mask)
|
| 243 |
+
|
| 244 |
+
@pytest.mark.parametrize(
|
| 245 |
+
"prompt_tuning_init",
|
| 246 |
+
[
|
| 247 |
+
MultitaskPromptTuningInit.AVERAGE_SOURCE_TASKS,
|
| 248 |
+
MultitaskPromptTuningInit.EXACT_SOURCE_TASK,
|
| 249 |
+
MultitaskPromptTuningInit.ONLY_SOURCE_SHARED,
|
| 250 |
+
],
|
| 251 |
+
)
|
| 252 |
+
@pytest.mark.parametrize("model_id", MODELS_TO_TEST)
|
| 253 |
+
def test_generate_text_with_other_init(self, prompt_tuning_init, model_id, config) -> None:
|
| 254 |
+
# This test is flaky, hence fixing the seed. The reason is somehow related to:
|
| 255 |
+
# https://github.com/huggingface/transformers/blob/e786844425b6b1112c76513d66217ce2fe6aea41/src/transformers/generation/utils.py#L2691
|
| 256 |
+
# When an EOS token is generated, the loop is exited and the pytest.raises at the bottom is not triggered
|
| 257 |
+
# because `forward` of the PEFT model, which should raise the error, is never called.
|
| 258 |
+
torch.manual_seed(42) # seed 43 fails with transformers v4.42.3 and torch v2.3.1
|
| 259 |
+
|
| 260 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 261 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 262 |
+
model = get_peft_model(model, config)
|
| 263 |
+
model.save_pretrained(tmp_dirname, safe_serialization=False) # bc torch.load is used
|
| 264 |
+
|
| 265 |
+
config = MultitaskPromptTuningConfig(
|
| 266 |
+
task_type="CAUSAL_LM",
|
| 267 |
+
num_virtual_tokens=50,
|
| 268 |
+
num_tasks=1,
|
| 269 |
+
prompt_tuning_init_text=(
|
| 270 |
+
"classify the following into either positive or negative, or entailment, neutral or contradiction:"
|
| 271 |
+
),
|
| 272 |
+
prompt_tuning_init=prompt_tuning_init,
|
| 273 |
+
prompt_tuning_init_state_dict_path=os.path.join(tmp_dirname, WEIGHTS_NAME),
|
| 274 |
+
)
|
| 275 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 276 |
+
model = get_peft_model(model, config)
|
| 277 |
+
model = model.to(self.torch_device)
|
| 278 |
+
|
| 279 |
+
input_ids = torch.LongTensor([[1, 1, 1], [2, 1, 2]]).to(self.torch_device)
|
| 280 |
+
attention_mask = torch.LongTensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 281 |
+
task_ids = torch.LongTensor([0]).to(self.torch_device)
|
| 282 |
+
|
| 283 |
+
# check if `generate` works
|
| 284 |
+
_ = model.generate(input_ids=input_ids, attention_mask=attention_mask, task_ids=task_ids)
|
| 285 |
+
|
| 286 |
+
with pytest.raises(ValueError, match="task_ids cannot be None"):
|
| 287 |
+
# check if `generate` raises an error if task_ids are not passed
|
| 288 |
+
_ = model.generate(input_ids, attention_mask=attention_mask)
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_osf.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pytest
|
| 2 |
+
import torch
|
| 3 |
+
from torch.testing import assert_close
|
| 4 |
+
|
| 5 |
+
from peft import OSFConfig, get_peft_model
|
| 6 |
+
from peft.tuners.osf.layer import OSFLayer
|
| 7 |
+
from peft.tuners.osf.utils import (
|
| 8 |
+
decompose_weight_matrix,
|
| 9 |
+
reconstruct_weight_matrix,
|
| 10 |
+
)
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def test_osf_roundtrip():
|
| 14 |
+
w = torch.randn(10, 8)
|
| 15 |
+
svd = decompose_weight_matrix(w, top_k=4)
|
| 16 |
+
w_rec = reconstruct_weight_matrix(svd)
|
| 17 |
+
assert_close(w_rec, w, atol=1e-5, rtol=1e-5)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class DummyConfig(dict):
|
| 21 |
+
pass
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
class DummyModel(torch.nn.Module):
|
| 25 |
+
def __init__(self, config=None):
|
| 26 |
+
super().__init__()
|
| 27 |
+
self.config = config
|
| 28 |
+
self.linear = torch.nn.Linear(8, 4)
|
| 29 |
+
|
| 30 |
+
def forward(self, x):
|
| 31 |
+
return self.linear(x)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def test_osf_gradient_projection_hook():
|
| 35 |
+
torch.manual_seed(0)
|
| 36 |
+
model = DummyModel(DummyConfig())
|
| 37 |
+
# Specify target module explicitly for DummyModel
|
| 38 |
+
cfg = OSFConfig(target_modules=["linear"], effective_rank=2)
|
| 39 |
+
wrapped = get_peft_model(model, cfg)
|
| 40 |
+
x = torch.randn(3, 8)
|
| 41 |
+
wrapped(x).sum().backward()
|
| 42 |
+
# Access the injected OSF layer
|
| 43 |
+
osf_linear = wrapped.base_model.model.linear
|
| 44 |
+
adapter = wrapped.base_model.active_adapters[0]
|
| 45 |
+
U_high = osf_linear._osf_U_high[adapter]
|
| 46 |
+
V_high = osf_linear._osf_V_high[adapter]
|
| 47 |
+
svd_params = osf_linear.osf_svd_params[adapter]
|
| 48 |
+
# Check orthogonality of gradients after projection
|
| 49 |
+
proj_u = U_high.T @ svd_params["U_low"].grad
|
| 50 |
+
proj_v = svd_params["V_low"].grad @ V_high.T
|
| 51 |
+
assert_close(proj_u, torch.zeros_like(proj_u), atol=1e-6, rtol=1e-6)
|
| 52 |
+
assert_close(proj_v, torch.zeros_like(proj_v), atol=1e-6, rtol=1e-6)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def test_osf_merge_and_unload_and_unmerge_behavior():
|
| 56 |
+
model = DummyModel(DummyConfig())
|
| 57 |
+
cfg = OSFConfig(target_modules=["linear"], effective_rank=2)
|
| 58 |
+
wrapped = get_peft_model(model, cfg)
|
| 59 |
+
|
| 60 |
+
# merge_adapter should work via BaseTuner and OSFLayer.merge
|
| 61 |
+
osf_linear = wrapped.base_model.model.linear
|
| 62 |
+
assert isinstance(osf_linear, OSFLayer)
|
| 63 |
+
wrapped.merge_adapter()
|
| 64 |
+
assert osf_linear.merged, "OSF layer should be marked as merged after merge_adapter()"
|
| 65 |
+
|
| 66 |
+
# unmerge_adapter is not supported for OSF
|
| 67 |
+
with pytest.raises(NotImplementedError):
|
| 68 |
+
wrapped.unmerge_adapter()
|
| 69 |
+
|
| 70 |
+
# merge_and_unload should return the base model (no OSF wrappers)
|
| 71 |
+
merged_model = wrapped.merge_and_unload()
|
| 72 |
+
assert isinstance(merged_model.linear, torch.nn.Linear)
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_other.py
ADDED
|
@@ -0,0 +1,624 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import copy
|
| 16 |
+
from contextlib import contextmanager
|
| 17 |
+
from unittest.mock import patch
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
import torch
|
| 21 |
+
from torch import nn
|
| 22 |
+
from transformers import (
|
| 23 |
+
AutoModelForCausalLM,
|
| 24 |
+
AutoModelForSeq2SeqLM,
|
| 25 |
+
AutoModelForSequenceClassification,
|
| 26 |
+
LlavaForConditionalGeneration,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
from peft import LoraConfig, PeftModel, VeraConfig, get_peft_model
|
| 30 |
+
from peft.utils.other import ModulesToSaveWrapper, _get_module_names_tied_with_embedding, _get_no_split_modules
|
| 31 |
+
|
| 32 |
+
from .testing_utils import hub_online_once
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class ModelWithModuleDict(nn.Module):
|
| 36 |
+
def __init__(self):
|
| 37 |
+
super().__init__()
|
| 38 |
+
self.other_layer = nn.Linear(10, 10)
|
| 39 |
+
self.module = nn.ModuleDict({"foo": nn.Linear(10, 10)})
|
| 40 |
+
|
| 41 |
+
def forward(self):
|
| 42 |
+
return self.module["foo"](torch.rand(1, 10))
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ModelWithModuleList(nn.Module):
|
| 46 |
+
def __init__(self):
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.other_layer = nn.Linear(10, 10)
|
| 49 |
+
self.module = nn.ModuleList([nn.Linear(10, 10)])
|
| 50 |
+
|
| 51 |
+
def forward(self):
|
| 52 |
+
return self.module[0](torch.rand(1, 10))
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ModelWithParameterDict(nn.Module):
|
| 56 |
+
def __init__(self):
|
| 57 |
+
super().__init__()
|
| 58 |
+
self.other_layer = nn.Linear(10, 10)
|
| 59 |
+
self.module = nn.ParameterDict({"foo": nn.Parameter(torch.rand(10, 10))})
|
| 60 |
+
|
| 61 |
+
def forward(self):
|
| 62 |
+
return self.module["foo"]
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class ModelWithParameterList(nn.Module):
|
| 66 |
+
def __init__(self):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.other_layer = nn.Linear(10, 10)
|
| 69 |
+
self.module = nn.ParameterList([nn.Parameter(torch.rand(10, 10))])
|
| 70 |
+
|
| 71 |
+
def forward(self):
|
| 72 |
+
return self.module[0]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@pytest.mark.parametrize(
|
| 76 |
+
"cls", [ModelWithModuleDict, ModelWithModuleList, ModelWithParameterDict, ModelWithParameterList]
|
| 77 |
+
)
|
| 78 |
+
def test_modules_to_save_targets_module_dict_raises(cls):
|
| 79 |
+
model = cls()
|
| 80 |
+
peft_config = LoraConfig(
|
| 81 |
+
target_modules=["other_layer"],
|
| 82 |
+
modules_to_save=["module"],
|
| 83 |
+
)
|
| 84 |
+
model() # sanity check that the model would normally work
|
| 85 |
+
|
| 86 |
+
msg = "modules_to_save cannot be applied to modules of type"
|
| 87 |
+
with pytest.raises(TypeError, match=msg):
|
| 88 |
+
get_peft_model(model=model, peft_config=peft_config)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def test_get_peft_model_revision_warning(tmp_path):
|
| 92 |
+
base_model_id = "peft-internal-testing/tiny-random-BertModel"
|
| 93 |
+
base_revision = "v2.0.0"
|
| 94 |
+
base_model = AutoModelForCausalLM.from_pretrained(base_model_id, revision=base_revision).eval()
|
| 95 |
+
lora_config = LoraConfig(revision=base_revision)
|
| 96 |
+
|
| 97 |
+
overwrite_revision = "main"
|
| 98 |
+
overwrite_warning = f"peft config has already set base model revision to {base_revision}, overwriting with revision {overwrite_revision}"
|
| 99 |
+
with pytest.warns(UserWarning, match=overwrite_warning):
|
| 100 |
+
_ = get_peft_model(base_model, lora_config, revision=overwrite_revision)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def test_load_multiple_adapters_different_modules_to_save(tmp_path):
|
| 104 |
+
# This tests the error described in #2422 where loading multiple adapters with different modules_to_save
|
| 105 |
+
# attributes fails (due to a regression from #2376).
|
| 106 |
+
|
| 107 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-random-LlamaForCausalLM")
|
| 108 |
+
|
| 109 |
+
def peft_config(**kwargs):
|
| 110 |
+
return LoraConfig(target_modules="all-linear", **kwargs)
|
| 111 |
+
|
| 112 |
+
original_model = copy.deepcopy(model)
|
| 113 |
+
|
| 114 |
+
peft_config_0 = peft_config(modules_to_save=["0.post_attention_layernorm"])
|
| 115 |
+
peft_config_1 = peft_config(modules_to_save=["0.post_attention_layernorm"])
|
| 116 |
+
peft_config_2 = peft_config(modules_to_save=["1.post_attention_layernorm"])
|
| 117 |
+
|
| 118 |
+
# Save adapter 0, nothing fancy, should be equal to base model weighs
|
| 119 |
+
peft_model = get_peft_model(copy.deepcopy(original_model), peft_config_0)
|
| 120 |
+
peft_model.save_pretrained(tmp_path / "adapter_0")
|
| 121 |
+
|
| 122 |
+
# Save adapter 1, modules to save weights are modified randomly, should be unique to adapter 1
|
| 123 |
+
peft_model = get_peft_model(copy.deepcopy(original_model), peft_config_1)
|
| 124 |
+
peft_model.model.model.layers[0].post_attention_layernorm.weight.data = torch.rand_like(
|
| 125 |
+
peft_model.model.model.layers[0].post_attention_layernorm.weight.data
|
| 126 |
+
)
|
| 127 |
+
adapter_1_saved = peft_model.model.model.layers[0].post_attention_layernorm.weight.data.clone()
|
| 128 |
+
peft_model.save_pretrained(tmp_path / "adapter_1")
|
| 129 |
+
|
| 130 |
+
# Save adapter 2, modules to save weights are modified randomly, should be unique to adapter 2
|
| 131 |
+
peft_model = get_peft_model(copy.deepcopy(original_model), peft_config_2)
|
| 132 |
+
peft_model.model.model.layers[1].post_attention_layernorm.weight.data = torch.rand_like(
|
| 133 |
+
peft_model.model.model.layers[1].post_attention_layernorm.weight.data
|
| 134 |
+
)
|
| 135 |
+
adapter_2_saved = peft_model.model.model.layers[1].post_attention_layernorm.weight.data.clone()
|
| 136 |
+
peft_model.save_pretrained(tmp_path / "adapter_2")
|
| 137 |
+
|
| 138 |
+
del peft_model
|
| 139 |
+
|
| 140 |
+
combined_model = PeftModel.from_pretrained(original_model, tmp_path / "adapter_0", adapter_name="adapter_0")
|
| 141 |
+
combined_model.load_adapter(tmp_path / "adapter_1", adapter_name="adapter_1")
|
| 142 |
+
combined_model.load_adapter(tmp_path / "adapter_2", adapter_name="adapter_2")
|
| 143 |
+
|
| 144 |
+
# For adapter 0 we expect every mentioned modules to save layer of this test to be equal to the original model
|
| 145 |
+
# since we didn't modify it for adapter 0 and only adapter 0 is active.
|
| 146 |
+
combined_model.set_adapter("adapter_0")
|
| 147 |
+
assert torch.allclose(
|
| 148 |
+
combined_model.model.model.layers[0].post_attention_layernorm.weight,
|
| 149 |
+
original_model.model.layers[0].post_attention_layernorm.weight,
|
| 150 |
+
)
|
| 151 |
+
assert torch.allclose(
|
| 152 |
+
combined_model.model.model.layers[1].post_attention_layernorm.weight,
|
| 153 |
+
original_model.model.layers[1].post_attention_layernorm.weight,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
# For adapter 1 we expect that the modified module to save 0.post_attention_layernorm is modified, the other
|
| 157 |
+
# module to save layers mentioned above should be untouched.
|
| 158 |
+
combined_model.set_adapter("adapter_1")
|
| 159 |
+
assert torch.allclose(
|
| 160 |
+
combined_model.model.model.layers[0].post_attention_layernorm.weight,
|
| 161 |
+
adapter_1_saved,
|
| 162 |
+
)
|
| 163 |
+
assert torch.allclose(
|
| 164 |
+
combined_model.model.model.layers[1].post_attention_layernorm.weight,
|
| 165 |
+
original_model.model.layers[1].post_attention_layernorm.weight,
|
| 166 |
+
)
|
| 167 |
+
|
| 168 |
+
# For adapter 2 we expect its module to save layer (1.post_attention_layernorm) to be modified but the other
|
| 169 |
+
# module to save weights should be kept original.
|
| 170 |
+
combined_model.set_adapter("adapter_2")
|
| 171 |
+
assert torch.allclose(
|
| 172 |
+
combined_model.model.model.layers[0].post_attention_layernorm.weight,
|
| 173 |
+
original_model.model.layers[0].post_attention_layernorm.weight,
|
| 174 |
+
)
|
| 175 |
+
assert torch.allclose(
|
| 176 |
+
combined_model.model.model.layers[1].post_attention_layernorm.weight,
|
| 177 |
+
adapter_2_saved,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
class TestModulesToSaveAttributeAccess:
|
| 182 |
+
"""Test attribute access on the ModulesToSaveWrapper class.
|
| 183 |
+
|
| 184 |
+
When we have modules_to_save, the original module is wrapped. As long as only forward was called on this wrapped
|
| 185 |
+
module, we were good. However, if, for instance, model parameters were directly accessed by another module, this
|
| 186 |
+
would typically fail, as the wrapper does not have this attribute. We had special properties for weight and bias,
|
| 187 |
+
but this is not enough. Therefore, attribute access is now transiently delegated to the active adapter (or original
|
| 188 |
+
module, if the adapter is disabled).
|
| 189 |
+
|
| 190 |
+
For one example, see #2099.
|
| 191 |
+
|
| 192 |
+
"""
|
| 193 |
+
|
| 194 |
+
@pytest.fixture
|
| 195 |
+
def mlp(self):
|
| 196 |
+
class MLP(nn.Module):
|
| 197 |
+
def __init__(self):
|
| 198 |
+
super().__init__()
|
| 199 |
+
self.lin0 = nn.Linear(1, 2)
|
| 200 |
+
self.lin1 = nn.Linear(3, 4)
|
| 201 |
+
|
| 202 |
+
return MLP()
|
| 203 |
+
|
| 204 |
+
def test_transient_attribute_access_default_adapter(self, mlp):
|
| 205 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 206 |
+
model = get_peft_model(mlp, config)
|
| 207 |
+
assert model.lin1.weight is model.lin1.modules_to_save["default"].weight
|
| 208 |
+
assert model.lin1.bias is model.lin1.modules_to_save["default"].bias
|
| 209 |
+
|
| 210 |
+
def test_transient_attribute_access_non_default_adapter(self, mlp):
|
| 211 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 212 |
+
model = get_peft_model(mlp, config)
|
| 213 |
+
model.add_adapter("other", config)
|
| 214 |
+
|
| 215 |
+
# at this point, default is still active
|
| 216 |
+
assert model.lin1.weight is model.lin1.modules_to_save["default"].weight
|
| 217 |
+
assert model.lin1.bias is model.lin1.modules_to_save["default"].bias
|
| 218 |
+
assert model.lin1.weight is not model.lin1.modules_to_save["other"].weight
|
| 219 |
+
assert model.lin1.bias is not model.lin1.modules_to_save["other"].bias
|
| 220 |
+
|
| 221 |
+
model.set_adapter("other")
|
| 222 |
+
assert model.lin1.weight is not model.lin1.modules_to_save["default"].weight
|
| 223 |
+
assert model.lin1.bias is not model.lin1.modules_to_save["default"].bias
|
| 224 |
+
assert model.lin1.weight is model.lin1.modules_to_save["other"].weight
|
| 225 |
+
assert model.lin1.bias is model.lin1.modules_to_save["other"].bias
|
| 226 |
+
|
| 227 |
+
def test_transient_attribute_access_disabled_adapter(self, mlp):
|
| 228 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 229 |
+
model = get_peft_model(mlp, config)
|
| 230 |
+
|
| 231 |
+
# at this point, default is still active
|
| 232 |
+
assert model.lin1.weight is model.lin1.modules_to_save["default"].weight
|
| 233 |
+
assert model.lin1.bias is model.lin1.modules_to_save["default"].bias
|
| 234 |
+
assert model.lin1.weight is not model.lin1.original_module.weight
|
| 235 |
+
assert model.lin1.bias is not model.lin1.original_module.bias
|
| 236 |
+
|
| 237 |
+
with model.disable_adapter():
|
| 238 |
+
assert model.lin1.weight is not model.lin1.modules_to_save["default"].weight
|
| 239 |
+
assert model.lin1.bias is not model.lin1.modules_to_save["default"].bias
|
| 240 |
+
assert model.lin1.weight is model.lin1.original_module.weight
|
| 241 |
+
assert model.lin1.bias is model.lin1.original_module.bias
|
| 242 |
+
|
| 243 |
+
def test_transient_attribute_access_uninitialized_adapter(self, mlp):
|
| 244 |
+
# ensure that there is no weird infinite recursion when accessing a non-existing attribute on the class itself
|
| 245 |
+
with pytest.raises(AttributeError, match="has no attribute 'original_module'"):
|
| 246 |
+
ModulesToSaveWrapper.original_module
|
| 247 |
+
|
| 248 |
+
def test_transient_attribute_access_attr_does_not_exist_on_modules_to_save(self, mlp):
|
| 249 |
+
# ensure that there is no weird infinite recursion when accessing a non-existing attribute on the
|
| 250 |
+
# ModelToSaveWrapper instance
|
| 251 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 252 |
+
model = get_peft_model(mlp, config)
|
| 253 |
+
|
| 254 |
+
with pytest.raises(AttributeError, match="has no attribute 'foo'"):
|
| 255 |
+
model.lin1.foo
|
| 256 |
+
|
| 257 |
+
def test_transient_attribute_access_attr_does_not_exist_on_original_module(self, mlp):
|
| 258 |
+
# ensure that there is no weird infinite recursion when accessing a non-existing attribute on the
|
| 259 |
+
# original module of the ModelToSaveWrapper instance
|
| 260 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 261 |
+
model = get_peft_model(mlp, config)
|
| 262 |
+
|
| 263 |
+
with pytest.raises(AttributeError, match="has no attribute 'foo'"):
|
| 264 |
+
with model.disable_adapter():
|
| 265 |
+
model.lin1.foo
|
| 266 |
+
|
| 267 |
+
def test_transient_attribute_access_non_existing_adapter(self, mlp):
|
| 268 |
+
# This should normally never happen, as the active adapter should always exist, but it's a failsafe
|
| 269 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 270 |
+
model = get_peft_model(mlp, config)
|
| 271 |
+
model.base_model.model.lin1._active_adapter = "does-not-exist"
|
| 272 |
+
with pytest.raises(AttributeError, match="has no attribute 'weight'"):
|
| 273 |
+
model.lin1.weight
|
| 274 |
+
|
| 275 |
+
|
| 276 |
+
class TestModulesToSaveNameSubstringBug:
|
| 277 |
+
"""Test a bug that could occur with multiple modules to save where one adapter's name is a substring of another
|
| 278 |
+
adapter's name.
|
| 279 |
+
|
| 280 |
+
This bug was the result of an error in the logic of modifying the state_dict for modules_to_save in
|
| 281 |
+
set_peft_model_state_dict. The error in the logic was that it was checked if an entry from modules_to_save (a set
|
| 282 |
+
of strings) is a substring of a key of the state_dict. If it was, a new name was assigned to that key in the
|
| 283 |
+
state_dict, which would allow to load the weight later.
|
| 284 |
+
|
| 285 |
+
The issue that stems from the substring check occurs if there are multiple modules_to_save, and one of them has a
|
| 286 |
+
name that is a substring of another. So e.g. if one is named "classifier" and the other is named "classifier2",
|
| 287 |
+
there could be a false match.
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
This bug was reported in #2289.
|
| 291 |
+
|
| 292 |
+
"""
|
| 293 |
+
|
| 294 |
+
def get_model(self):
|
| 295 |
+
class MyModule(nn.Module):
|
| 296 |
+
def __init__(self):
|
| 297 |
+
super().__init__()
|
| 298 |
+
self.lin = nn.Linear(5, 4)
|
| 299 |
+
# important: "classifier" is a substring of "classifier2", "classifier3", "classifier4"
|
| 300 |
+
self.classifier = nn.Linear(4, 2)
|
| 301 |
+
self.classifier2 = nn.Linear(4, 2)
|
| 302 |
+
self.classifier3 = nn.Linear(4, 2)
|
| 303 |
+
self.classifier4 = nn.Linear(4, 2)
|
| 304 |
+
|
| 305 |
+
def forward(self, x):
|
| 306 |
+
x = self.lin(x)
|
| 307 |
+
return self.classifier(x) + self.classifier2(x) + self.classifier3(x) + self.classifier4(x)
|
| 308 |
+
|
| 309 |
+
torch.manual_seed(0)
|
| 310 |
+
return MyModule()
|
| 311 |
+
|
| 312 |
+
@pytest.fixture
|
| 313 |
+
def path_merged_and_unmerged(self, tmp_path):
|
| 314 |
+
# Create 2 checkpoints:
|
| 315 |
+
# 1. merged: the model after calling merge_and_unload
|
| 316 |
+
# 2. unmerged: the PEFT model saved without calling merge_and_unload
|
| 317 |
+
path = tmp_path / "model.pt"
|
| 318 |
+
|
| 319 |
+
lora_config = LoraConfig(
|
| 320 |
+
target_modules=["lin"],
|
| 321 |
+
# important: "classifier" is a substring of "classifier2", "classifier3", "classifier4"
|
| 322 |
+
modules_to_save=["classifier", "classifier2", "classifier3", "classifier4"],
|
| 323 |
+
)
|
| 324 |
+
model = get_peft_model(self.get_model(), lora_config)
|
| 325 |
+
# mock training
|
| 326 |
+
for _ in range(5):
|
| 327 |
+
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
|
| 328 |
+
output = model(torch.randn(10, 5))
|
| 329 |
+
loss = output.sum()
|
| 330 |
+
loss.backward()
|
| 331 |
+
optimizer.step()
|
| 332 |
+
|
| 333 |
+
# save the peft model without merging
|
| 334 |
+
path_unmerged = tmp_path / "unmerged"
|
| 335 |
+
model.save_pretrained(path_unmerged)
|
| 336 |
+
|
| 337 |
+
# merge the model and save state_dict
|
| 338 |
+
path_merged = tmp_path / "merged"
|
| 339 |
+
merged = model.merge_and_unload()
|
| 340 |
+
state_dict = merged.state_dict()
|
| 341 |
+
torch.save(state_dict, path_merged)
|
| 342 |
+
|
| 343 |
+
return path_merged, path_unmerged
|
| 344 |
+
|
| 345 |
+
def test_load_merged_and_unmerged_same_weights(self, path_merged_and_unmerged):
|
| 346 |
+
# Note that this test is quasi flaky, it has a 1 in 4 chance of passing even without the bugfix. It passes when
|
| 347 |
+
# "classifier" happens to be the last element of the set model.modules_to_save. The order of the set is random.
|
| 348 |
+
# It is not possible just run this test multiple times to minimize the probability of this happening, because
|
| 349 |
+
# within the same process, the hash order is consistent. With the bug fix, this doesn't matter, as the test will
|
| 350 |
+
# always pass, but if there is a regression, there is a 1 in 4 chance of not catching it. Since the CI runs many
|
| 351 |
+
# tests, it is overall very unlikely that none will catch it though. If you see this test failing in CI, thus be
|
| 352 |
+
# aware that some of the passing tests may just pass owing to randomness.
|
| 353 |
+
path_merged, path_unmerged = path_merged_and_unmerged
|
| 354 |
+
|
| 355 |
+
# load the merged model directly
|
| 356 |
+
state_dict = torch.load(path_merged, weights_only=True)
|
| 357 |
+
model = self.get_model()
|
| 358 |
+
model.load_state_dict(state_dict)
|
| 359 |
+
sd_merged = model.state_dict()
|
| 360 |
+
del model
|
| 361 |
+
|
| 362 |
+
# load the unmerged model and merge it
|
| 363 |
+
unmerged = PeftModel.from_pretrained(self.get_model(), path_unmerged)
|
| 364 |
+
sd_unmerged = unmerged.merge_and_unload().state_dict()
|
| 365 |
+
|
| 366 |
+
assert sd_merged.keys() == sd_unmerged.keys()
|
| 367 |
+
for key in sd_merged.keys():
|
| 368 |
+
param_merged = sd_merged[key]
|
| 369 |
+
param_unmerged = sd_unmerged[key]
|
| 370 |
+
assert torch.allclose(param_merged, param_unmerged)
|
| 371 |
+
|
| 372 |
+
|
| 373 |
+
class TestTargetingAuxiliaryTrainingWrapper:
|
| 374 |
+
"""AuxiliaryTrainingWrapper such as ModulesToSaveWrapper and TrainableTokensWrapper are
|
| 375 |
+
in general not to be targeted by PEFT methods such as adapters. For example, a ModulesToSaveWrapper's children
|
| 376 |
+
modules should not be targeted by `LoraConfig(target_modules='all-linear')`, among other things.
|
| 377 |
+
"""
|
| 378 |
+
|
| 379 |
+
@pytest.fixture
|
| 380 |
+
def plain_model_cls(self):
|
| 381 |
+
class PlainModel(nn.Module):
|
| 382 |
+
def __init__(self, i, o):
|
| 383 |
+
super().__init__()
|
| 384 |
+
self.layer1 = nn.Linear(i, o)
|
| 385 |
+
|
| 386 |
+
def forward(self, x):
|
| 387 |
+
return self.layer1(x)
|
| 388 |
+
|
| 389 |
+
return PlainModel
|
| 390 |
+
|
| 391 |
+
@pytest.fixture
|
| 392 |
+
def nested_model_cls(self, plain_model_cls):
|
| 393 |
+
class NestedModel(nn.Module):
|
| 394 |
+
def __init__(self):
|
| 395 |
+
super().__init__()
|
| 396 |
+
self.layer1 = nn.Linear(10, 20)
|
| 397 |
+
self.layer2 = nn.Linear(20, 5)
|
| 398 |
+
self.layer3 = plain_model_cls(5, 10)
|
| 399 |
+
|
| 400 |
+
def forward(self, x):
|
| 401 |
+
x = self.layer1(x)
|
| 402 |
+
x = self.layer2(x)
|
| 403 |
+
x = self.layer3(x)
|
| 404 |
+
return x
|
| 405 |
+
|
| 406 |
+
return NestedModel
|
| 407 |
+
|
| 408 |
+
def test_nested_ignores_modules_to_save(self, nested_model_cls, plain_model_cls):
|
| 409 |
+
# Make sure that `target_modules` is not targeting the nested modules of a module marked as module to save.
|
| 410 |
+
model = nested_model_cls()
|
| 411 |
+
config = LoraConfig(
|
| 412 |
+
target_modules=["layer1"],
|
| 413 |
+
modules_to_save=["layer3"],
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
peft_model = get_peft_model(model, config)
|
| 417 |
+
assert isinstance(peft_model.model.layer3.modules_to_save.default, plain_model_cls)
|
| 418 |
+
|
| 419 |
+
def test_targeting_module_to_save_raises(self, nested_model_cls):
|
| 420 |
+
model = nested_model_cls()
|
| 421 |
+
config = LoraConfig(
|
| 422 |
+
target_modules=["layer1"],
|
| 423 |
+
modules_to_save=["layer1"],
|
| 424 |
+
)
|
| 425 |
+
msg = "No modules were targeted for adaptation. This might be caused by a combination"
|
| 426 |
+
with pytest.raises(ValueError, match=msg):
|
| 427 |
+
get_peft_model(model, config)
|
| 428 |
+
|
| 429 |
+
def test_modules_to_save_targets_tuner_layer_raises(self):
|
| 430 |
+
# See e.g. issue 2027 and 2477
|
| 431 |
+
# Prevent users from (accidentally) targeting the same layer both with a tuner and modules_to_save. Normally, PEFT
|
| 432 |
+
# will not target the same layer with both a tuner and ModulesToSaveWrapper. However, if modules_to_save is
|
| 433 |
+
# automatically inferred, e.g. when using AutoModelForSequenceClassification, the ModulesToSaveWrapper is applied ex
|
| 434 |
+
# post, which can lead to the double wrapping.
|
| 435 |
+
model_id = "peft-internal-testing/tiny-random-OPTForCausalLM"
|
| 436 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id)
|
| 437 |
+
|
| 438 |
+
# Note: target_modules="all-linear" would also work and is closer to the original issue, but let's explicitly target
|
| 439 |
+
# "score" here in case that "all-linear" will be fixed to no longer target the score layer.
|
| 440 |
+
peft_config = LoraConfig(target_modules=["score"], task_type="SEQ_CLS")
|
| 441 |
+
|
| 442 |
+
# Since the `score` layer is in `model.modules_to_save` it should be ignored when targeted,
|
| 443 |
+
# therefore the layer should not be adapted.
|
| 444 |
+
msg = "No modules were targeted for adaptation. This might be caused by a combination"
|
| 445 |
+
with pytest.raises(ValueError, match=msg) as e:
|
| 446 |
+
get_peft_model(model, peft_config)
|
| 447 |
+
|
| 448 |
+
def test_targeting_trainable_tokens_raises(self):
|
| 449 |
+
model_id = "peft-internal-testing/tiny-random-OPTForCausalLM"
|
| 450 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id)
|
| 451 |
+
|
| 452 |
+
peft_config = LoraConfig(target_modules=["embed_tokens"], task_type="SEQ_CLS", trainable_token_indices=[0, 1])
|
| 453 |
+
|
| 454 |
+
# While this message might not be the most helpful message, at least it is not silently failing
|
| 455 |
+
msg = "trainable_token_indices cannot be applied to modules of type <class 'peft.tuners.lora.layer.Embedding'>"
|
| 456 |
+
with pytest.raises(TypeError, match=msg) as e:
|
| 457 |
+
get_peft_model(model, peft_config)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
class TestAdapterTargeting:
|
| 461 |
+
"""Make sure that already existing adapters cannot be targeted to avoid conflicts."""
|
| 462 |
+
|
| 463 |
+
@pytest.fixture
|
| 464 |
+
def base_model_cls(self):
|
| 465 |
+
class M(torch.nn.Module):
|
| 466 |
+
def __init__(self):
|
| 467 |
+
super().__init__()
|
| 468 |
+
self.l1 = torch.nn.Linear(10, 20)
|
| 469 |
+
self.l2 = torch.nn.Conv2d(1, 1, 2)
|
| 470 |
+
|
| 471 |
+
def forward(self, x):
|
| 472 |
+
return self.l2(self.l1(x))
|
| 473 |
+
|
| 474 |
+
return M
|
| 475 |
+
|
| 476 |
+
@pytest.mark.parametrize(
|
| 477 |
+
"config_cls, config_kwargs",
|
| 478 |
+
[
|
| 479 |
+
(LoraConfig, {"target_modules": "l1.*"}),
|
| 480 |
+
(LoraConfig, {"target_modules": "l2.*"}),
|
| 481 |
+
(VeraConfig, {"target_modules": "l1.*"}),
|
| 482 |
+
(VeraConfig, {"target_modules": "(l1|vera_A).*"}), # also target the shared layer
|
| 483 |
+
],
|
| 484 |
+
)
|
| 485 |
+
def test_self_targeting_is_ignored(self, base_model_cls, config_cls, config_kwargs):
|
| 486 |
+
base_model = base_model_cls()
|
| 487 |
+
config1 = config_cls(**config_kwargs)
|
| 488 |
+
config2 = config_cls(**config_kwargs)
|
| 489 |
+
|
| 490 |
+
adapter1_name = "ADAPTER_1_512858" # sufficiently unique names to make reliable testing easier
|
| 491 |
+
adapter2_name = "ADAPTER_2_845781"
|
| 492 |
+
|
| 493 |
+
peft_model = get_peft_model(base_model, config1, adapter_name=adapter1_name)
|
| 494 |
+
state_dict_keys_1 = peft_model.state_dict().keys()
|
| 495 |
+
|
| 496 |
+
peft_model.add_adapter(adapter2_name, config2)
|
| 497 |
+
state_dict_keys_2 = peft_model.state_dict().keys()
|
| 498 |
+
|
| 499 |
+
# Ideally there should be no new modules targeted beyond existing ModuleDicts. Therefore the keys
|
| 500 |
+
# of the new state dict should only differ after the adapter name portion of the keys - not before.
|
| 501 |
+
# Expected:
|
| 502 |
+
# - a.b.<adapter_name_1>.xyz
|
| 503 |
+
# - a.b.<adapter_name_2>.xyz
|
| 504 |
+
# We're not expecting this to happen and test against it:
|
| 505 |
+
# - a.b.<adapter_name_1>.xyz
|
| 506 |
+
# - a.<adapter_name_2>.xyz
|
| 507 |
+
def remove_adapter_portion(adapter_name, key):
|
| 508 |
+
if key.endswith(f".{adapter_name}"):
|
| 509 |
+
return key.removesuffix(f".{adapter_name}")
|
| 510 |
+
return key.split(f".{adapter_name}.")[0]
|
| 511 |
+
|
| 512 |
+
adapter_invariant_keys1 = {remove_adapter_portion(adapter1_name, key) for key in state_dict_keys_1}
|
| 513 |
+
adapter_invariant_keys2 = {
|
| 514 |
+
remove_adapter_portion(adapter2_name, remove_adapter_portion(adapter1_name, key))
|
| 515 |
+
for key in state_dict_keys_2
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
assert adapter_invariant_keys1 == adapter_invariant_keys2
|
| 519 |
+
|
| 520 |
+
|
| 521 |
+
class TestGetNoSplitModules:
|
| 522 |
+
# Ensure that children are considered when determining _no_split_modules
|
| 523 |
+
# see https://github.com/huggingface/transformers/pull/38141
|
| 524 |
+
|
| 525 |
+
def test_get_no_split_modules_simple(self):
|
| 526 |
+
# choose a model where recursively visiting children is *not* required
|
| 527 |
+
model_id = "peft-internal-testing/opt-125m"
|
| 528 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 529 |
+
assert model._no_split_modules == ["OPTDecoderLayer"]
|
| 530 |
+
no_split_modules = _get_no_split_modules(model)
|
| 531 |
+
assert no_split_modules == {"OPTDecoderLayer"}
|
| 532 |
+
|
| 533 |
+
def test_get_no_split_modules_recursive(self):
|
| 534 |
+
# choose a model where recursively visiting children is required
|
| 535 |
+
model_id = "hf-internal-testing/tiny-random-LlavaForConditionalGeneration"
|
| 536 |
+
model = LlavaForConditionalGeneration.from_pretrained(model_id)
|
| 537 |
+
# sanity check: just visiting the model itself is not enough:
|
| 538 |
+
assert model._no_split_modules == []
|
| 539 |
+
|
| 540 |
+
no_split_modules = _get_no_split_modules(model)
|
| 541 |
+
assert no_split_modules == {"CLIPEncoderLayer", "LlamaDecoderLayer"}
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
class TestGetModuleNamesTiedWithEmbedding:
|
| 545 |
+
# TODO remove mapping when transformers <5 is not supported anymore as it is the default
|
| 546 |
+
# from there on. also remove the 'list' tied weights type
|
| 547 |
+
model_tied_weights_mapping = {
|
| 548 |
+
"peft-internal-testing/tiny-random-BertModel": {
|
| 549 |
+
"cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
|
| 550 |
+
"cls.predictions.decoder.bias": "bert.embeddings.word_embeddings.bias",
|
| 551 |
+
},
|
| 552 |
+
"peft-internal-testing/opt-125m": {
|
| 553 |
+
"lm_head.weight": "model.decoder.embed_tokens.weight",
|
| 554 |
+
},
|
| 555 |
+
"peft-internal-testing/tiny-random-t5": {
|
| 556 |
+
"lm_head.weight": "shared.weight",
|
| 557 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 558 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 559 |
+
},
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
model_ids = [
|
| 563 |
+
"peft-internal-testing/opt-125m",
|
| 564 |
+
"peft-internal-testing/tiny-random-BertModel",
|
| 565 |
+
"peft-internal-testing/tiny-random-t5",
|
| 566 |
+
]
|
| 567 |
+
|
| 568 |
+
@contextmanager
|
| 569 |
+
def patch_model(self, model_id, tied_weights_type):
|
| 570 |
+
with hub_online_once(model_id):
|
| 571 |
+
if "t5" in model_id:
|
| 572 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
| 573 |
+
else:
|
| 574 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 575 |
+
|
| 576 |
+
tied_weights_keys = list(self.model_tied_weights_mapping[model_id].keys())
|
| 577 |
+
expected_module_names = sorted({k.rpartition(".")[0] for k in tied_weights_keys})
|
| 578 |
+
|
| 579 |
+
if tied_weights_type == "list":
|
| 580 |
+
# for transformers >=5 this tests compatibility with transformers <5
|
| 581 |
+
with patch.object(model, "_tied_weights_keys", list(tied_weights_keys)):
|
| 582 |
+
yield model, expected_module_names
|
| 583 |
+
|
| 584 |
+
elif tied_weights_type == "mapping":
|
| 585 |
+
# for transformers <5 this tests compatibility with transformers >=5
|
| 586 |
+
mapping = self.model_tied_weights_mapping[model_id]
|
| 587 |
+
|
| 588 |
+
with patch.object(model, "_tied_weights_keys", mapping):
|
| 589 |
+
yield model, expected_module_names
|
| 590 |
+
|
| 591 |
+
else:
|
| 592 |
+
raise RuntimeError("Invalid fixture request")
|
| 593 |
+
|
| 594 |
+
@pytest.mark.parametrize("tied_weights_type", ["list", "mapping"])
|
| 595 |
+
@pytest.mark.parametrize("model_id", model_ids)
|
| 596 |
+
def test_get_modules_tied_to_embedding(self, model_id, tied_weights_type):
|
| 597 |
+
with self.patch_model(model_id, tied_weights_type) as (model, expected):
|
| 598 |
+
if tied_weights_type == "mapping":
|
| 599 |
+
assert isinstance(model._tied_weights_keys, dict)
|
| 600 |
+
|
| 601 |
+
# transformers defines the bias as tied even if it doesn't exist, filter out in that case
|
| 602 |
+
if not hasattr(model.get_input_embeddings(), "bias"):
|
| 603 |
+
expected = list(filter(lambda k: "bias" not in k, expected))
|
| 604 |
+
|
| 605 |
+
modules = _get_module_names_tied_with_embedding(model)
|
| 606 |
+
|
| 607 |
+
assert expected == modules
|
| 608 |
+
|
| 609 |
+
@pytest.mark.parametrize("tied_weights_type", ["list", "mapping"])
|
| 610 |
+
@pytest.mark.parametrize("model_id", model_ids)
|
| 611 |
+
def test_get_modules_tied_to_embedding_peft(self, model_id, tied_weights_type):
|
| 612 |
+
with self.patch_model(model_id, tied_weights_type) as (model, expected):
|
| 613 |
+
if tied_weights_type == "mapping":
|
| 614 |
+
assert isinstance(model._tied_weights_keys, dict)
|
| 615 |
+
|
| 616 |
+
# transformers defines the bias as tied even if it doesn't exist, filter out in that case
|
| 617 |
+
if not hasattr(model.get_input_embeddings(), "bias"):
|
| 618 |
+
expected = list(filter(lambda k: "bias" not in k, expected))
|
| 619 |
+
|
| 620 |
+
peft_model = get_peft_model(model, LoraConfig())
|
| 621 |
+
|
| 622 |
+
modules = peft_model._get_module_names_tied_with_embedding()
|
| 623 |
+
|
| 624 |
+
assert expected == modules
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_poly.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
|
| 3 |
+
# coding=utf-8
|
| 4 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 5 |
+
#
|
| 6 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 7 |
+
# you may not use this file except in compliance with the License.
|
| 8 |
+
# You may obtain a copy of the License at
|
| 9 |
+
#
|
| 10 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 11 |
+
#
|
| 12 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 13 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 14 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 15 |
+
# See the License for the specific language governing permissions and
|
| 16 |
+
# limitations under the License.
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import tempfile
|
| 20 |
+
import unittest
|
| 21 |
+
|
| 22 |
+
import torch
|
| 23 |
+
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
|
| 24 |
+
|
| 25 |
+
from peft import PeftModel, PolyConfig, TaskType, get_peft_model
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class TestPoly(unittest.TestCase):
|
| 29 |
+
def test_poly(self):
|
| 30 |
+
torch.manual_seed(0)
|
| 31 |
+
model_name_or_path = "google/flan-t5-small"
|
| 32 |
+
|
| 33 |
+
atol, rtol = 1e-6, 1e-6
|
| 34 |
+
r = 8 # rank of lora in poly
|
| 35 |
+
n_tasks = 3 # number of tasks
|
| 36 |
+
n_skills = 2 # number of skills (loras)
|
| 37 |
+
n_splits = 4 # number of heads
|
| 38 |
+
lr = 1e-2
|
| 39 |
+
num_epochs = 10
|
| 40 |
+
|
| 41 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
|
| 42 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
|
| 43 |
+
|
| 44 |
+
peft_config = PolyConfig(
|
| 45 |
+
task_type=TaskType.SEQ_2_SEQ_LM,
|
| 46 |
+
poly_type="poly",
|
| 47 |
+
r=r,
|
| 48 |
+
n_tasks=n_tasks,
|
| 49 |
+
n_skills=n_skills,
|
| 50 |
+
n_splits=n_splits,
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
model = get_peft_model(base_model, peft_config)
|
| 54 |
+
|
| 55 |
+
# generate some dummy data
|
| 56 |
+
text = os.__doc__.splitlines()
|
| 57 |
+
assert len(text) > 10
|
| 58 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True)
|
| 59 |
+
inputs["task_ids"] = torch.arange(len(text)) % n_tasks
|
| 60 |
+
inputs["labels"] = tokenizer((["A", "B"] * 100)[: len(text)], return_tensors="pt")["input_ids"]
|
| 61 |
+
|
| 62 |
+
# simple training loop
|
| 63 |
+
model.train()
|
| 64 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
|
| 65 |
+
losses = []
|
| 66 |
+
for _ in range(num_epochs):
|
| 67 |
+
outputs = model(**inputs)
|
| 68 |
+
loss = outputs.loss
|
| 69 |
+
loss.backward()
|
| 70 |
+
optimizer.step()
|
| 71 |
+
optimizer.zero_grad()
|
| 72 |
+
losses.append(loss.item())
|
| 73 |
+
|
| 74 |
+
# loss improved by at least 50%
|
| 75 |
+
assert losses[-1] < (0.5 * losses[0])
|
| 76 |
+
|
| 77 |
+
# check that saving and loading works
|
| 78 |
+
torch.manual_seed(0)
|
| 79 |
+
model.eval()
|
| 80 |
+
logits_before = model(**inputs).logits
|
| 81 |
+
tokens_before = model.generate(**inputs)
|
| 82 |
+
|
| 83 |
+
with model.disable_adapter():
|
| 84 |
+
logits_disabled = model(**inputs).logits
|
| 85 |
+
tokens_disabled = model.generate(**inputs)
|
| 86 |
+
|
| 87 |
+
assert not torch.allclose(logits_before, logits_disabled, atol=atol, rtol=rtol)
|
| 88 |
+
assert not torch.allclose(tokens_before, tokens_disabled, atol=atol, rtol=rtol)
|
| 89 |
+
|
| 90 |
+
# saving and loading
|
| 91 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 92 |
+
model.save_pretrained(tmp_dir)
|
| 93 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
|
| 94 |
+
loaded = PeftModel.from_pretrained(base_model, tmp_dir)
|
| 95 |
+
|
| 96 |
+
torch.manual_seed(0)
|
| 97 |
+
output_after = loaded(**inputs).logits
|
| 98 |
+
tokens_after = loaded.generate(**inputs)
|
| 99 |
+
assert torch.allclose(logits_before, output_after, atol=atol, rtol=rtol)
|
| 100 |
+
assert torch.allclose(tokens_before, tokens_after, atol=atol, rtol=rtol)
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_randlora.py
ADDED
|
@@ -0,0 +1,301 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# This test file is for tests specific to RandLora, since Randlora has some specific challenges due to the shared weights.
|
| 16 |
+
# These tests are copied from the test_vera.py file
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
|
| 20 |
+
import pytest
|
| 21 |
+
import torch
|
| 22 |
+
from accelerate.utils.imports import is_bf16_available
|
| 23 |
+
from safetensors import safe_open
|
| 24 |
+
from torch import nn
|
| 25 |
+
|
| 26 |
+
from peft import PeftModel, RandLoraConfig, get_peft_model
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class MLP(nn.Module):
|
| 30 |
+
def __init__(self, bias=True):
|
| 31 |
+
super().__init__()
|
| 32 |
+
self.relu = nn.ReLU()
|
| 33 |
+
self.lin0 = nn.Linear(10, 20, bias=bias)
|
| 34 |
+
self.lin1 = nn.Linear(20, 20, bias=bias) # lin1 and lin2 have same shape
|
| 35 |
+
self.lin2 = nn.Linear(20, 20, bias=bias)
|
| 36 |
+
self.lin3 = nn.Linear(20, 2, bias=bias)
|
| 37 |
+
self.sm = nn.LogSoftmax(dim=-1)
|
| 38 |
+
|
| 39 |
+
def forward(self, X):
|
| 40 |
+
X = self.lin0(X)
|
| 41 |
+
X = self.relu(X)
|
| 42 |
+
X = self.lin1(X)
|
| 43 |
+
X = self.relu(X)
|
| 44 |
+
X = self.lin2(X)
|
| 45 |
+
X = self.relu(X)
|
| 46 |
+
X = self.lin3(X)
|
| 47 |
+
X = self.sm(X)
|
| 48 |
+
return X
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Tests copied from the TestVera class in test_vera.py.
|
| 52 |
+
# Changes to the code file should be reflected here.
|
| 53 |
+
class TestRandLora:
|
| 54 |
+
@pytest.fixture
|
| 55 |
+
def mlp(self):
|
| 56 |
+
torch.manual_seed(0)
|
| 57 |
+
model = MLP()
|
| 58 |
+
return model
|
| 59 |
+
|
| 60 |
+
@pytest.fixture
|
| 61 |
+
def mlp_same_prng(self, mlp):
|
| 62 |
+
torch.manual_seed(0)
|
| 63 |
+
|
| 64 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 65 |
+
# creates a default RandLora adapter
|
| 66 |
+
peft_model = get_peft_model(mlp, config)
|
| 67 |
+
config2 = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 68 |
+
peft_model.add_adapter("other", config2)
|
| 69 |
+
return peft_model
|
| 70 |
+
|
| 71 |
+
def test_multiple_adapters_same_prng_weights(self, mlp_same_prng):
|
| 72 |
+
# we can have multiple adapters with the same prng key, in which case the weights should be shared
|
| 73 |
+
assert (
|
| 74 |
+
mlp_same_prng.base_model.model.lin1.randlora_A["default"]
|
| 75 |
+
is mlp_same_prng.base_model.model.lin1.randlora_A["other"]
|
| 76 |
+
)
|
| 77 |
+
assert (
|
| 78 |
+
mlp_same_prng.base_model.model.lin1.randlora_B["default"]
|
| 79 |
+
is mlp_same_prng.base_model.model.lin1.randlora_B["other"]
|
| 80 |
+
)
|
| 81 |
+
assert (
|
| 82 |
+
mlp_same_prng.base_model.model.lin2.randlora_A["default"]
|
| 83 |
+
is mlp_same_prng.base_model.model.lin2.randlora_A["other"]
|
| 84 |
+
)
|
| 85 |
+
assert (
|
| 86 |
+
mlp_same_prng.base_model.model.lin2.randlora_B["default"]
|
| 87 |
+
is mlp_same_prng.base_model.model.lin2.randlora_B["other"]
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
input = torch.randn(5, 10)
|
| 91 |
+
mlp_same_prng.set_adapter("default")
|
| 92 |
+
output_default = mlp_same_prng(input)
|
| 93 |
+
mlp_same_prng.set_adapter("other")
|
| 94 |
+
output_other = mlp_same_prng(input)
|
| 95 |
+
assert not torch.allclose(output_default, output_other, atol=1e-3, rtol=1e-3)
|
| 96 |
+
|
| 97 |
+
def test_multiple_adapters_different_prng_raises(self):
|
| 98 |
+
# we cannot have multiple adapters with different prng keys
|
| 99 |
+
model = MLP()
|
| 100 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 101 |
+
# creates a default RandLora adapter
|
| 102 |
+
peft_model = get_peft_model(model, config)
|
| 103 |
+
config2 = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, projection_prng_key=123)
|
| 104 |
+
|
| 105 |
+
msg = (
|
| 106 |
+
r"RandLora PRNG initialisation key must be the same for all adapters. Got config.projection_prng_key=123 but "
|
| 107 |
+
r"previous config had 0"
|
| 108 |
+
)
|
| 109 |
+
with pytest.raises(ValueError, match=msg):
|
| 110 |
+
peft_model.add_adapter("other", config2)
|
| 111 |
+
|
| 112 |
+
def test_multiple_adapters_save_load_save_projection_true(self, mlp_same_prng, tmp_path):
|
| 113 |
+
# check saving and loading works with multiple adapters and saved projection weights
|
| 114 |
+
torch.manual_seed(0)
|
| 115 |
+
input = torch.randn(5, 10)
|
| 116 |
+
mlp_same_prng.set_adapter("default")
|
| 117 |
+
output_default = mlp_same_prng(input)
|
| 118 |
+
mlp_same_prng.set_adapter("other")
|
| 119 |
+
output_other = mlp_same_prng(input)
|
| 120 |
+
|
| 121 |
+
# sanity check
|
| 122 |
+
assert not torch.allclose(output_default, output_other, atol=1e-3, rtol=1e-3)
|
| 123 |
+
|
| 124 |
+
save_path = tmp_path / "randlora"
|
| 125 |
+
mlp_same_prng.save_pretrained(save_path)
|
| 126 |
+
assert os.path.exists(save_path / "adapter_config.json")
|
| 127 |
+
assert os.path.exists(save_path / "other" / "adapter_config.json")
|
| 128 |
+
|
| 129 |
+
torch.manual_seed(0)
|
| 130 |
+
mlp = MLP()
|
| 131 |
+
peft_model = PeftModel.from_pretrained(mlp, save_path)
|
| 132 |
+
peft_model.load_adapter(save_path / "other", "other")
|
| 133 |
+
|
| 134 |
+
peft_model.set_adapter("default")
|
| 135 |
+
output_default_loaded = peft_model(input)
|
| 136 |
+
peft_model.set_adapter("other")
|
| 137 |
+
output_other_loaded = peft_model(input)
|
| 138 |
+
|
| 139 |
+
assert torch.allclose(output_default, output_default_loaded, atol=1e-3, rtol=1e-3)
|
| 140 |
+
assert torch.allclose(output_other, output_other_loaded, atol=1e-3, rtol=1e-3)
|
| 141 |
+
|
| 142 |
+
def test_multiple_adapters_save_load_save_projection_false(self, mlp, tmp_path):
|
| 143 |
+
# check saving and loading works with multiple adapters without saved projection weights
|
| 144 |
+
torch.manual_seed(1)
|
| 145 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 146 |
+
# creates a default RandLora adapter
|
| 147 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 148 |
+
config2 = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 149 |
+
peft_model.add_adapter("second", config2)
|
| 150 |
+
|
| 151 |
+
input = torch.randn(5, 10)
|
| 152 |
+
peft_model.set_adapter("first")
|
| 153 |
+
output_first = peft_model(input)
|
| 154 |
+
peft_model.set_adapter("second")
|
| 155 |
+
output_second = peft_model(input)
|
| 156 |
+
|
| 157 |
+
# sanity check
|
| 158 |
+
assert not torch.allclose(output_first, output_second, atol=1e-3, rtol=1e-3)
|
| 159 |
+
|
| 160 |
+
save_path = tmp_path / "randlora"
|
| 161 |
+
peft_model.save_pretrained(save_path)
|
| 162 |
+
assert os.path.exists(save_path / "first" / "adapter_config.json")
|
| 163 |
+
assert os.path.exists(save_path / "second" / "adapter_config.json")
|
| 164 |
+
|
| 165 |
+
torch.manual_seed(0)
|
| 166 |
+
mlp = MLP()
|
| 167 |
+
peft_model = PeftModel.from_pretrained(mlp, save_path / "first", adapter_name="first")
|
| 168 |
+
peft_model.load_adapter(save_path / "second", "second")
|
| 169 |
+
|
| 170 |
+
peft_model.set_adapter("first")
|
| 171 |
+
output_first_loaded = peft_model(input)
|
| 172 |
+
peft_model.set_adapter("second")
|
| 173 |
+
output_second_loaded = peft_model(input)
|
| 174 |
+
|
| 175 |
+
assert torch.allclose(output_first, output_first_loaded, atol=1e-3, rtol=1e-3)
|
| 176 |
+
assert torch.allclose(output_second, output_second_loaded, atol=1e-3, rtol=1e-3)
|
| 177 |
+
|
| 178 |
+
def test_multiple_adapters_save_projection_true_contains_randlora_A_randlora_B(self, mlp_same_prng, tmp_path):
|
| 179 |
+
# check that the state_dicts don't contain the projection weights
|
| 180 |
+
save_path = tmp_path / "randlora"
|
| 181 |
+
mlp_same_prng.save_pretrained(save_path)
|
| 182 |
+
|
| 183 |
+
sd_default = {}
|
| 184 |
+
with safe_open(save_path / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 185 |
+
for key in f.keys():
|
| 186 |
+
sd_default[key] = f.get_tensor(key)
|
| 187 |
+
|
| 188 |
+
assert any("randlora_A" in key for key in sd_default)
|
| 189 |
+
assert any("randlora_B" in key for key in sd_default)
|
| 190 |
+
# default rank for RandLora is 32
|
| 191 |
+
assert sd_default["base_model.randlora_A"].shape == (32, 1, 20)
|
| 192 |
+
assert sd_default["base_model.randlora_B"].shape == (20, 1, 32)
|
| 193 |
+
|
| 194 |
+
sd_other = {}
|
| 195 |
+
with safe_open(save_path / "other" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 196 |
+
for key in f.keys():
|
| 197 |
+
sd_other[key] = f.get_tensor(key)
|
| 198 |
+
|
| 199 |
+
assert any("randlora_A" in key for key in sd_other)
|
| 200 |
+
assert any("randlora_B" in key for key in sd_other)
|
| 201 |
+
assert sd_other["base_model.randlora_A"].shape == (32, 1, 20)
|
| 202 |
+
assert sd_other["base_model.randlora_B"].shape == (20, 1, 32)
|
| 203 |
+
|
| 204 |
+
def test_multiple_adapters_save_projection_false_contains_no_randlora_A_randlora_B(self, mlp, tmp_path):
|
| 205 |
+
torch.manual_seed(1)
|
| 206 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 207 |
+
# creates a default RandLora adapter
|
| 208 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 209 |
+
config2 = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 210 |
+
peft_model.add_adapter("second", config2)
|
| 211 |
+
|
| 212 |
+
save_path = tmp_path / "randlora"
|
| 213 |
+
peft_model.save_pretrained(save_path)
|
| 214 |
+
|
| 215 |
+
sd_default = {}
|
| 216 |
+
with safe_open(save_path / "first" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 217 |
+
for key in f.keys():
|
| 218 |
+
sd_default[key] = f.get_tensor(key)
|
| 219 |
+
|
| 220 |
+
assert not any("randlora_A" in key for key in sd_default)
|
| 221 |
+
assert not any("randlora_B" in key for key in sd_default)
|
| 222 |
+
|
| 223 |
+
sd_other = {}
|
| 224 |
+
with safe_open(save_path / "second" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 225 |
+
for key in f.keys():
|
| 226 |
+
sd_other[key] = f.get_tensor(key)
|
| 227 |
+
|
| 228 |
+
assert not any("randlora_A" in key for key in sd_other)
|
| 229 |
+
assert not any("randlora_B" in key for key in sd_other)
|
| 230 |
+
|
| 231 |
+
def test_randlora_A_randlora_B_share_memory(self, mlp_same_prng):
|
| 232 |
+
randlora_A = mlp_same_prng.randlora_A["default"]
|
| 233 |
+
randlora_B = mlp_same_prng.randlora_B["default"]
|
| 234 |
+
|
| 235 |
+
# these tensors should share the same data
|
| 236 |
+
assert randlora_A.data_ptr() == mlp_same_prng.base_model.model.lin1.randlora_A["default"].data_ptr()
|
| 237 |
+
assert randlora_B.data_ptr() == mlp_same_prng.base_model.model.lin1.randlora_B["default"].data_ptr()
|
| 238 |
+
assert randlora_A.data_ptr() == mlp_same_prng.base_model.model.lin2.randlora_A["default"].data_ptr()
|
| 239 |
+
assert randlora_B.data_ptr() == mlp_same_prng.base_model.model.lin2.randlora_B["default"].data_ptr()
|
| 240 |
+
# sanity check: these tensors shouldn't share the same data
|
| 241 |
+
assert randlora_A.data_ptr() != randlora_B.data_ptr()
|
| 242 |
+
|
| 243 |
+
def test_randlora_lambda_dont_share_memory(self, mlp_same_prng):
|
| 244 |
+
# sanity check: these tensors shouldn't share the same data
|
| 245 |
+
assert (
|
| 246 |
+
mlp_same_prng.base_model.model.lin1.randlora_lambda["default"].data_ptr()
|
| 247 |
+
!= mlp_same_prng.base_model.model.lin1.randlora_lambda["other"].data_ptr()
|
| 248 |
+
)
|
| 249 |
+
assert (
|
| 250 |
+
mlp_same_prng.base_model.model.lin1.randlora_lambda["default"].data_ptr()
|
| 251 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_lambda["default"].data_ptr()
|
| 252 |
+
)
|
| 253 |
+
assert (
|
| 254 |
+
mlp_same_prng.base_model.model.lin1.randlora_lambda["other"].data_ptr()
|
| 255 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_lambda["other"].data_ptr()
|
| 256 |
+
)
|
| 257 |
+
assert (
|
| 258 |
+
mlp_same_prng.base_model.model.lin1.randlora_gamma["default"].data_ptr()
|
| 259 |
+
!= mlp_same_prng.base_model.model.lin1.randlora_gamma["other"].data_ptr()
|
| 260 |
+
)
|
| 261 |
+
assert (
|
| 262 |
+
mlp_same_prng.base_model.model.lin1.randlora_gamma["default"].data_ptr()
|
| 263 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_gamma["default"].data_ptr()
|
| 264 |
+
)
|
| 265 |
+
assert (
|
| 266 |
+
mlp_same_prng.base_model.model.lin1.randlora_gamma["other"].data_ptr()
|
| 267 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_gamma["other"].data_ptr()
|
| 268 |
+
)
|
| 269 |
+
|
| 270 |
+
def test_randlora_different_shapes(self, mlp):
|
| 271 |
+
config = RandLoraConfig(target_modules=["lin0", "lin3"], init_weights=False)
|
| 272 |
+
mlp_different_shapes = get_peft_model(mlp, config)
|
| 273 |
+
|
| 274 |
+
randlora_A = mlp_different_shapes.randlora_A["default"]
|
| 275 |
+
randlora_B = mlp_different_shapes.randlora_B["default"]
|
| 276 |
+
|
| 277 |
+
# sanity check
|
| 278 |
+
assert mlp.lin0.base_layer.weight.shape != mlp.lin3.base_layer.weight.shape
|
| 279 |
+
|
| 280 |
+
# lin0 has the largest output dimension, lin3 has the largest input dimension
|
| 281 |
+
# randlora_A should have the shape of (rank, largest_in), randlora_B should have the shape of (largest_out, rank)
|
| 282 |
+
assert randlora_A.shape == (config.r, 1, mlp.lin3.in_features)
|
| 283 |
+
assert randlora_B.shape == (mlp.lin0.out_features, 1, config.r)
|
| 284 |
+
|
| 285 |
+
# should not raise
|
| 286 |
+
input = torch.randn(5, 10)
|
| 287 |
+
mlp_different_shapes(input)
|
| 288 |
+
|
| 289 |
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
| 290 |
+
def test_randlora_dtypes(self, dtype):
|
| 291 |
+
if dtype == torch.bfloat16:
|
| 292 |
+
# skip if bf16 is not supported on hardware, see #1872
|
| 293 |
+
if not is_bf16_available():
|
| 294 |
+
pytest.skip("bfloat16 not supported on this system, skipping the test")
|
| 295 |
+
|
| 296 |
+
model = MLP().to(dtype)
|
| 297 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 298 |
+
peft_model = get_peft_model(model, config)
|
| 299 |
+
inputs = torch.randn(5, 10).to(dtype)
|
| 300 |
+
output = peft_model(inputs) # should not raise
|
| 301 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
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License governing permissions and limitations under the License.
|
| 13 |
+
|
| 14 |
+
import pytest
|
| 15 |
+
import torch
|
| 16 |
+
from transformers import AutoModelForSequenceClassification
|
| 17 |
+
|
| 18 |
+
from peft import (
|
| 19 |
+
AdaLoraConfig,
|
| 20 |
+
BOFTConfig,
|
| 21 |
+
BoneConfig,
|
| 22 |
+
C3AConfig,
|
| 23 |
+
DeloraConfig,
|
| 24 |
+
FourierFTConfig,
|
| 25 |
+
GraloraConfig,
|
| 26 |
+
HRAConfig,
|
| 27 |
+
IA3Config,
|
| 28 |
+
LoraConfig,
|
| 29 |
+
MissConfig,
|
| 30 |
+
OFTConfig,
|
| 31 |
+
PrefixTuningConfig,
|
| 32 |
+
PromptEncoderConfig,
|
| 33 |
+
PromptTuningConfig,
|
| 34 |
+
PromptTuningInit,
|
| 35 |
+
RoadConfig,
|
| 36 |
+
ShiraConfig,
|
| 37 |
+
VBLoRAConfig,
|
| 38 |
+
VeraConfig,
|
| 39 |
+
WaveFTConfig,
|
| 40 |
+
get_peft_model,
|
| 41 |
+
)
|
| 42 |
+
from peft.utils.other import ModulesToSaveWrapper
|
| 43 |
+
|
| 44 |
+
from .testing_common import PeftCommonTester
|
| 45 |
+
from .testing_utils import hub_online_once
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
# Note: models from peft-internal-testing are just the safetensors versions of hf-internal-testing
|
| 49 |
+
PEFT_SEQ_CLS_MODELS_TO_TEST = [
|
| 50 |
+
"peft-internal-testing/tiny-random-BertForSequenceClassification",
|
| 51 |
+
"peft-internal-testing/tiny-random-RobertaForSequenceClassification",
|
| 52 |
+
"trl-internal-testing/tiny-LlamaForSequenceClassification-3.2",
|
| 53 |
+
]
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
ALL_CONFIGS = [
|
| 57 |
+
(
|
| 58 |
+
AdaLoraConfig,
|
| 59 |
+
{
|
| 60 |
+
"task_type": "SEQ_CLS",
|
| 61 |
+
"target_modules": None,
|
| 62 |
+
"total_step": 1,
|
| 63 |
+
},
|
| 64 |
+
),
|
| 65 |
+
(
|
| 66 |
+
BOFTConfig,
|
| 67 |
+
{
|
| 68 |
+
"task_type": "SEQ_CLS",
|
| 69 |
+
"target_modules": None,
|
| 70 |
+
},
|
| 71 |
+
),
|
| 72 |
+
(
|
| 73 |
+
BoneConfig,
|
| 74 |
+
{
|
| 75 |
+
"task_type": "SEQ_CLS",
|
| 76 |
+
"target_modules": None,
|
| 77 |
+
"r": 2,
|
| 78 |
+
},
|
| 79 |
+
),
|
| 80 |
+
(
|
| 81 |
+
MissConfig,
|
| 82 |
+
{
|
| 83 |
+
"task_type": "SEQ_CLS",
|
| 84 |
+
"target_modules": None,
|
| 85 |
+
"r": 2,
|
| 86 |
+
},
|
| 87 |
+
),
|
| 88 |
+
(
|
| 89 |
+
DeloraConfig,
|
| 90 |
+
{
|
| 91 |
+
"task_type": "SEQ_CLS",
|
| 92 |
+
"target_modules": None,
|
| 93 |
+
"r": 2,
|
| 94 |
+
},
|
| 95 |
+
),
|
| 96 |
+
(
|
| 97 |
+
FourierFTConfig,
|
| 98 |
+
{
|
| 99 |
+
"task_type": "SEQ_CLS",
|
| 100 |
+
"n_frequency": 10,
|
| 101 |
+
"target_modules": None,
|
| 102 |
+
},
|
| 103 |
+
),
|
| 104 |
+
(
|
| 105 |
+
GraloraConfig,
|
| 106 |
+
{
|
| 107 |
+
"task_type": "SEQ_CLS",
|
| 108 |
+
"target_modules": None,
|
| 109 |
+
},
|
| 110 |
+
),
|
| 111 |
+
(
|
| 112 |
+
HRAConfig,
|
| 113 |
+
{
|
| 114 |
+
"task_type": "SEQ_CLS",
|
| 115 |
+
"target_modules": None,
|
| 116 |
+
},
|
| 117 |
+
),
|
| 118 |
+
(
|
| 119 |
+
IA3Config,
|
| 120 |
+
{
|
| 121 |
+
"task_type": "SEQ_CLS",
|
| 122 |
+
"target_modules": None,
|
| 123 |
+
"feedforward_modules": None,
|
| 124 |
+
},
|
| 125 |
+
),
|
| 126 |
+
(
|
| 127 |
+
LoraConfig,
|
| 128 |
+
{
|
| 129 |
+
"task_type": "SEQ_CLS",
|
| 130 |
+
"r": 8,
|
| 131 |
+
"lora_alpha": 32,
|
| 132 |
+
"target_modules": None,
|
| 133 |
+
"lora_dropout": 0.05,
|
| 134 |
+
"bias": "none",
|
| 135 |
+
},
|
| 136 |
+
),
|
| 137 |
+
# LoRA + trainable tokens
|
| 138 |
+
(
|
| 139 |
+
LoraConfig,
|
| 140 |
+
{
|
| 141 |
+
"task_type": "SEQ_CLS",
|
| 142 |
+
"r": 8,
|
| 143 |
+
"lora_alpha": 32,
|
| 144 |
+
"target_modules": None,
|
| 145 |
+
"lora_dropout": 0.05,
|
| 146 |
+
"bias": "none",
|
| 147 |
+
"trainable_token_indices": [0, 1, 3],
|
| 148 |
+
},
|
| 149 |
+
),
|
| 150 |
+
(
|
| 151 |
+
OFTConfig,
|
| 152 |
+
{
|
| 153 |
+
"task_type": "SEQ_CLS",
|
| 154 |
+
"target_modules": None,
|
| 155 |
+
},
|
| 156 |
+
),
|
| 157 |
+
(
|
| 158 |
+
PrefixTuningConfig,
|
| 159 |
+
{
|
| 160 |
+
"task_type": "SEQ_CLS",
|
| 161 |
+
"num_virtual_tokens": 10,
|
| 162 |
+
},
|
| 163 |
+
),
|
| 164 |
+
(
|
| 165 |
+
PromptEncoderConfig,
|
| 166 |
+
{
|
| 167 |
+
"task_type": "SEQ_CLS",
|
| 168 |
+
"num_virtual_tokens": 10,
|
| 169 |
+
"encoder_hidden_size": 32,
|
| 170 |
+
},
|
| 171 |
+
),
|
| 172 |
+
(
|
| 173 |
+
PromptTuningConfig,
|
| 174 |
+
{
|
| 175 |
+
"task_type": "SEQ_CLS",
|
| 176 |
+
"num_virtual_tokens": 10,
|
| 177 |
+
},
|
| 178 |
+
),
|
| 179 |
+
(
|
| 180 |
+
RoadConfig,
|
| 181 |
+
{
|
| 182 |
+
"task_type": "SEQ_CLS",
|
| 183 |
+
"variant": "road_1",
|
| 184 |
+
"group_size": 2,
|
| 185 |
+
},
|
| 186 |
+
),
|
| 187 |
+
(
|
| 188 |
+
ShiraConfig,
|
| 189 |
+
{
|
| 190 |
+
"r": 1,
|
| 191 |
+
"task_type": "SEQ_CLS",
|
| 192 |
+
"target_modules": None,
|
| 193 |
+
"init_weights": False,
|
| 194 |
+
},
|
| 195 |
+
),
|
| 196 |
+
(
|
| 197 |
+
VBLoRAConfig,
|
| 198 |
+
{
|
| 199 |
+
"task_type": "SEQ_CLS",
|
| 200 |
+
"target_modules": None,
|
| 201 |
+
"vblora_dropout": 0.05,
|
| 202 |
+
"vector_length": 1,
|
| 203 |
+
"num_vectors": 2,
|
| 204 |
+
},
|
| 205 |
+
),
|
| 206 |
+
(
|
| 207 |
+
VeraConfig,
|
| 208 |
+
{
|
| 209 |
+
"task_type": "SEQ_CLS",
|
| 210 |
+
"r": 8,
|
| 211 |
+
"target_modules": None,
|
| 212 |
+
"vera_dropout": 0.05,
|
| 213 |
+
"projection_prng_key": 0xFF,
|
| 214 |
+
"d_initial": 0.1,
|
| 215 |
+
"save_projection": True,
|
| 216 |
+
"bias": "none",
|
| 217 |
+
},
|
| 218 |
+
),
|
| 219 |
+
(
|
| 220 |
+
C3AConfig,
|
| 221 |
+
{
|
| 222 |
+
"task_type": "SEQ_CLS",
|
| 223 |
+
"block_size": 1,
|
| 224 |
+
"target_modules": None,
|
| 225 |
+
},
|
| 226 |
+
),
|
| 227 |
+
(
|
| 228 |
+
WaveFTConfig,
|
| 229 |
+
{
|
| 230 |
+
"task_type": "SEQ_CLS",
|
| 231 |
+
"n_frequency": 8,
|
| 232 |
+
"target_modules": None,
|
| 233 |
+
},
|
| 234 |
+
),
|
| 235 |
+
]
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
class TestSequenceClassificationModels(PeftCommonTester):
|
| 239 |
+
r"""
|
| 240 |
+
Tests for basic coverage of AutoModelForSequenceClassification and classification-specific cases. Most of the
|
| 241 |
+
functionality is probably already covered by other tests.
|
| 242 |
+
"""
|
| 243 |
+
|
| 244 |
+
transformers_class = AutoModelForSequenceClassification
|
| 245 |
+
|
| 246 |
+
def prepare_inputs_for_testing(self):
|
| 247 |
+
input_ids = torch.tensor([[1, 1, 1], [1, 2, 1]]).to(self.torch_device)
|
| 248 |
+
attention_mask = torch.tensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 249 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 250 |
+
|
| 251 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 252 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 253 |
+
def test_attributes_parametrized(self, model_id, config_cls, config_kwargs):
|
| 254 |
+
self._test_model_attr(model_id, config_cls, config_kwargs.copy())
|
| 255 |
+
|
| 256 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 257 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 258 |
+
def test_adapter_name(self, model_id, config_cls, config_kwargs):
|
| 259 |
+
self._test_adapter_name(model_id, config_cls, config_kwargs.copy())
|
| 260 |
+
|
| 261 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 262 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 263 |
+
def test_prepare_for_training_parametrized(self, model_id, config_cls, config_kwargs):
|
| 264 |
+
self._test_prepare_for_training(model_id, config_cls, config_kwargs.copy())
|
| 265 |
+
|
| 266 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 267 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 268 |
+
def test_prompt_tuning_text_prepare_for_training(self, model_id, config_cls, config_kwargs):
|
| 269 |
+
if config_cls != PromptTuningConfig:
|
| 270 |
+
pytest.skip(f"This test does not apply to {config_cls}")
|
| 271 |
+
config_kwargs = config_kwargs.copy()
|
| 272 |
+
config_kwargs["prompt_tuning_init"] = PromptTuningInit.TEXT
|
| 273 |
+
config_kwargs["prompt_tuning_init_text"] = "This is a test prompt."
|
| 274 |
+
config_kwargs["tokenizer_name_or_path"] = model_id
|
| 275 |
+
self._test_prepare_for_training(model_id, config_cls, config_kwargs.copy())
|
| 276 |
+
|
| 277 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 278 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 279 |
+
def test_save_pretrained(self, model_id, config_cls, config_kwargs):
|
| 280 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy())
|
| 281 |
+
|
| 282 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 283 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 284 |
+
def test_save_pretrained_pickle(self, model_id, config_cls, config_kwargs):
|
| 285 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy(), safe_serialization=False)
|
| 286 |
+
|
| 287 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 288 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 289 |
+
def test_save_pretrained_selected_adapters(self, model_id, config_cls, config_kwargs):
|
| 290 |
+
self._test_save_pretrained_selected_adapters(model_id, config_cls, config_kwargs.copy())
|
| 291 |
+
|
| 292 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 293 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 294 |
+
def test_save_pretrained_selected_adapters_pickle(self, model_id, config_cls, config_kwargs):
|
| 295 |
+
self._test_save_pretrained_selected_adapters(
|
| 296 |
+
model_id, config_cls, config_kwargs.copy(), safe_serialization=False
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 300 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 301 |
+
def test_from_pretrained_config_construction(self, model_id, config_cls, config_kwargs):
|
| 302 |
+
self._test_from_pretrained_config_construction(model_id, config_cls, config_kwargs.copy())
|
| 303 |
+
|
| 304 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 305 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 306 |
+
def test_modules_to_save_correctly_set(self, model_id, config_cls, config_kwargs):
|
| 307 |
+
# tests for a regression, introduced via #2220, where modules_to_save was not applied to prompt learning methods
|
| 308 |
+
with hub_online_once(model_id):
|
| 309 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 310 |
+
config = config_cls(
|
| 311 |
+
base_model_name_or_path=model_id,
|
| 312 |
+
**config_kwargs,
|
| 313 |
+
)
|
| 314 |
+
model = get_peft_model(model, config)
|
| 315 |
+
base_model = model.get_base_model()
|
| 316 |
+
# classifier layer is called either "classifier" or "score"
|
| 317 |
+
classifier = getattr(base_model, "classifier", getattr(base_model, "score", None))
|
| 318 |
+
if classifier is None:
|
| 319 |
+
raise ValueError(f"Could not determine classifier layer name for {model_id}, please fix the test")
|
| 320 |
+
assert isinstance(classifier, ModulesToSaveWrapper)
|
tasks/tasksm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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# This test file is for tests specific to SHiRA.
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
import torch
|
| 21 |
+
from accelerate.utils.imports import is_bf16_available
|
| 22 |
+
from torch import nn
|
| 23 |
+
|
| 24 |
+
from peft import PeftModel, ShiraConfig, get_peft_model
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def custom_random_mask_function_with_custom_kwargs(custom_arg):
|
| 28 |
+
def mask_fn(base_layer, r):
|
| 29 |
+
"""
|
| 30 |
+
This mask function is similar to the random_mask provided in src/peft/tuners/shira/mask_functions.py except the
|
| 31 |
+
seed is derived from custom_kwargs. Please use this as an example to create your own custom sparse masks that
|
| 32 |
+
may use custom_kwargs. Remember, for a pretrained weight with shape m, n, mask_fn must return only one mask
|
| 33 |
+
(shape: m, n) which must be binary 0 or 1 with num_shira_parameters = r(m+n) for linear layers. Device and
|
| 34 |
+
dtype of mask must be same as base layer's weight's device and dtype.
|
| 35 |
+
"""
|
| 36 |
+
new_seed = custom_arg
|
| 37 |
+
shape = base_layer.weight.shape
|
| 38 |
+
num_shira_weights = r * (shape[0] + shape[1])
|
| 39 |
+
random_generator = torch.Generator()
|
| 40 |
+
random_generator.manual_seed(new_seed)
|
| 41 |
+
|
| 42 |
+
idx = (torch.randperm(base_layer.weight.numel(), generator=random_generator)[:num_shira_weights]).to(
|
| 43 |
+
base_layer.weight.device
|
| 44 |
+
)
|
| 45 |
+
val = torch.ones_like(idx.type(base_layer.weight.dtype))
|
| 46 |
+
mask = torch.zeros_like(base_layer.weight.view(1, -1))
|
| 47 |
+
mask = mask.scatter_(1, idx.unsqueeze(0), val.unsqueeze(0)).view(shape)
|
| 48 |
+
|
| 49 |
+
return mask
|
| 50 |
+
|
| 51 |
+
return mask_fn
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class MLP(nn.Module):
|
| 55 |
+
def __init__(self, bias=True):
|
| 56 |
+
super().__init__()
|
| 57 |
+
self.relu = nn.ReLU()
|
| 58 |
+
self.lin0 = nn.Linear(10, 20, bias=bias)
|
| 59 |
+
self.lin1 = nn.Linear(20, 40, bias=bias) # lin1 and lin2 have same shape
|
| 60 |
+
self.lin2 = nn.Linear(40, 30, bias=bias)
|
| 61 |
+
self.lin3 = nn.Linear(30, 10, bias=bias)
|
| 62 |
+
self.sm = nn.LogSoftmax(dim=-1)
|
| 63 |
+
|
| 64 |
+
def forward(self, X):
|
| 65 |
+
X = self.lin0(X)
|
| 66 |
+
X = self.relu(X)
|
| 67 |
+
X = self.lin1(X)
|
| 68 |
+
X = self.relu(X)
|
| 69 |
+
X = self.lin2(X)
|
| 70 |
+
X = self.relu(X)
|
| 71 |
+
X = self.lin3(X)
|
| 72 |
+
X = self.sm(X)
|
| 73 |
+
return X
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class TestShira:
|
| 77 |
+
@pytest.fixture
|
| 78 |
+
def mlp(self):
|
| 79 |
+
torch.manual_seed(0)
|
| 80 |
+
model = MLP()
|
| 81 |
+
return model
|
| 82 |
+
|
| 83 |
+
def test_mlp_single_adapter_shapes(self, mlp):
|
| 84 |
+
# torch.manual_seed(0)
|
| 85 |
+
|
| 86 |
+
r = 2
|
| 87 |
+
config = ShiraConfig(r=r, target_modules=["lin1", "lin2"])
|
| 88 |
+
# creates a default SHiRA adapter
|
| 89 |
+
peft_model = get_peft_model(mlp, config)
|
| 90 |
+
|
| 91 |
+
shira_weight1_size = peft_model.base_model.model.lin1.shira_weight["default"].shape[0]
|
| 92 |
+
shira_weight2_size = peft_model.base_model.model.lin2.shira_weight["default"].shape[0]
|
| 93 |
+
shira_indices1_size = peft_model.base_model.model.lin1.shira_indices["default"].shape[1]
|
| 94 |
+
shira_indices2_size = peft_model.base_model.model.lin2.shira_indices["default"].shape[1]
|
| 95 |
+
|
| 96 |
+
base_weight1_size = peft_model.base_model.model.lin1.base_layer.weight.shape
|
| 97 |
+
base_weight2_size = peft_model.base_model.model.lin2.base_layer.weight.shape
|
| 98 |
+
|
| 99 |
+
delta_weight1_shape = peft_model.base_model.model.lin1.get_delta_weight("default").shape
|
| 100 |
+
delta_weight2_shape = peft_model.base_model.model.lin2.get_delta_weight("default").shape
|
| 101 |
+
|
| 102 |
+
assert shira_weight1_size == r * (base_weight1_size[0] + base_weight1_size[1])
|
| 103 |
+
assert shira_weight2_size == r * (base_weight2_size[0] + base_weight2_size[1])
|
| 104 |
+
|
| 105 |
+
assert shira_weight1_size == shira_indices1_size
|
| 106 |
+
assert shira_weight2_size == shira_indices2_size
|
| 107 |
+
|
| 108 |
+
assert delta_weight1_shape == base_weight1_size
|
| 109 |
+
assert delta_weight2_shape == base_weight2_size
|
| 110 |
+
|
| 111 |
+
return peft_model
|
| 112 |
+
|
| 113 |
+
def test_multiple_adapters_save_load(self, mlp, tmp_path):
|
| 114 |
+
# check saving and loading works with multiple adapters
|
| 115 |
+
# note, the random seeds in the below two configs are not the default values.
|
| 116 |
+
# so it will lead to different random sparse masks between saving and loading.
|
| 117 |
+
# our goal is to make sure that loaded indices are exactly the same as the saved indices regardless of what initial random mask gets generated.
|
| 118 |
+
# we will also make sure that parameters are saved and loaded correctly, and the output remains the same.
|
| 119 |
+
config = ShiraConfig(r=2, target_modules=["lin1", "lin2"], random_seed=56)
|
| 120 |
+
# creates a default SHiRA adapter
|
| 121 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 122 |
+
config2 = ShiraConfig(r=3, target_modules=["lin1", "lin2", "lin3"], random_seed=67)
|
| 123 |
+
peft_model.add_adapter("second", config2)
|
| 124 |
+
|
| 125 |
+
assert torch.all(peft_model.base_model.model.lin1.shira_weight["first"] == 0)
|
| 126 |
+
assert torch.all(peft_model.base_model.model.lin2.shira_weight["first"] == 0)
|
| 127 |
+
assert torch.all(peft_model.base_model.model.lin1.shira_weight["second"] == 0)
|
| 128 |
+
assert torch.all(peft_model.base_model.model.lin2.shira_weight["second"] == 0)
|
| 129 |
+
assert torch.all(peft_model.base_model.model.lin3.shira_weight["second"] == 0)
|
| 130 |
+
|
| 131 |
+
shira_assign_val1_f = torch.randn_like(peft_model.base_model.model.lin1.shira_weight["first"])
|
| 132 |
+
peft_model.base_model.model.lin1.shira_weight["first"] = shira_assign_val1_f
|
| 133 |
+
shira_indices1_f = peft_model.base_model.model.lin1.shira_indices["first"]
|
| 134 |
+
shira_assign_val2_f = torch.randn_like(peft_model.base_model.model.lin2.shira_weight["first"])
|
| 135 |
+
peft_model.base_model.model.lin2.shira_weight["first"] = shira_assign_val2_f
|
| 136 |
+
shira_indices2_f = peft_model.base_model.model.lin2.shira_indices["first"]
|
| 137 |
+
|
| 138 |
+
shira_assign_val1_s = torch.randn_like(peft_model.base_model.model.lin1.shira_weight["second"])
|
| 139 |
+
peft_model.base_model.model.lin1.shira_weight["second"] = shira_assign_val1_s
|
| 140 |
+
shira_indices1_s = peft_model.base_model.model.lin1.shira_indices["second"]
|
| 141 |
+
shira_assign_val2_s = torch.randn_like(peft_model.base_model.model.lin2.shira_weight["second"])
|
| 142 |
+
peft_model.base_model.model.lin2.shira_weight["second"] = shira_assign_val2_s
|
| 143 |
+
shira_indices2_s = peft_model.base_model.model.lin2.shira_indices["second"]
|
| 144 |
+
shira_assign_val3_s = torch.randn_like(peft_model.base_model.model.lin3.shira_weight["second"])
|
| 145 |
+
peft_model.base_model.model.lin3.shira_weight["second"] = shira_assign_val3_s
|
| 146 |
+
shira_indices3_s = peft_model.base_model.model.lin3.shira_indices["second"]
|
| 147 |
+
|
| 148 |
+
input = torch.randn(5, 10)
|
| 149 |
+
peft_model.set_adapter("first")
|
| 150 |
+
output_first = peft_model(input)
|
| 151 |
+
peft_model.set_adapter("second")
|
| 152 |
+
output_second = peft_model(input)
|
| 153 |
+
|
| 154 |
+
# sanity check
|
| 155 |
+
assert not torch.allclose(output_first, output_second, atol=1e-3, rtol=1e-3)
|
| 156 |
+
|
| 157 |
+
save_path = os.path.join(tmp_path, "shira")
|
| 158 |
+
peft_model.save_pretrained(save_path)
|
| 159 |
+
assert os.path.exists(os.path.join(save_path, "first", "adapter_config.json"))
|
| 160 |
+
assert os.path.exists(os.path.join(save_path, "second", "adapter_config.json"))
|
| 161 |
+
del peft_model
|
| 162 |
+
|
| 163 |
+
torch.manual_seed(0)
|
| 164 |
+
mlp = MLP()
|
| 165 |
+
peft_model = PeftModel.from_pretrained(mlp, os.path.join(save_path, "first"), adapter_name="first")
|
| 166 |
+
peft_model.load_adapter(os.path.join(save_path, "second"), "second")
|
| 167 |
+
|
| 168 |
+
peft_model.set_adapter("first")
|
| 169 |
+
output_first_loaded = peft_model(input)
|
| 170 |
+
peft_model.set_adapter("second")
|
| 171 |
+
output_second_loaded = peft_model(input)
|
| 172 |
+
|
| 173 |
+
assert torch.allclose(output_first, output_first_loaded)
|
| 174 |
+
assert torch.allclose(output_second, output_second_loaded)
|
| 175 |
+
|
| 176 |
+
assert torch.all(shira_assign_val1_f == peft_model.base_model.model.lin1.shira_weight["first"])
|
| 177 |
+
assert torch.all(shira_assign_val2_f == peft_model.base_model.model.lin2.shira_weight["first"])
|
| 178 |
+
assert torch.all(shira_indices1_f == peft_model.base_model.model.lin1.shira_indices["first"])
|
| 179 |
+
assert torch.all(shira_indices2_f == peft_model.base_model.model.lin2.shira_indices["first"])
|
| 180 |
+
assert torch.all(shira_assign_val1_s == peft_model.base_model.model.lin1.shira_weight["second"])
|
| 181 |
+
assert torch.all(shira_assign_val2_s == peft_model.base_model.model.lin2.shira_weight["second"])
|
| 182 |
+
assert torch.all(shira_assign_val3_s == peft_model.base_model.model.lin3.shira_weight["second"])
|
| 183 |
+
assert torch.all(shira_indices1_s == peft_model.base_model.model.lin1.shira_indices["second"])
|
| 184 |
+
assert torch.all(shira_indices2_s == peft_model.base_model.model.lin2.shira_indices["second"])
|
| 185 |
+
assert torch.all(shira_indices3_s == peft_model.base_model.model.lin3.shira_indices["second"])
|
| 186 |
+
|
| 187 |
+
return peft_model
|
| 188 |
+
|
| 189 |
+
def test_save_load_custom_mask_function(self, mlp, tmp_path):
|
| 190 |
+
# we want to see if saving and loading works when a custom mask is involved
|
| 191 |
+
config = ShiraConfig(r=2, mask_type="custom", target_modules=["lin1", "lin2"], init_weights=False)
|
| 192 |
+
custom_arg = 120
|
| 193 |
+
custom_mask_fn = custom_random_mask_function_with_custom_kwargs(custom_arg)
|
| 194 |
+
config.mask_fn = custom_mask_fn
|
| 195 |
+
|
| 196 |
+
# create a custom mask SHiRA adapter
|
| 197 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 198 |
+
|
| 199 |
+
shira_assign_val1_f = peft_model.base_model.model.lin1.shira_weight["first"]
|
| 200 |
+
shira_indices1_f = peft_model.base_model.model.lin1.shira_indices["first"]
|
| 201 |
+
shira_assign_val2_f = peft_model.base_model.model.lin2.shira_weight["first"]
|
| 202 |
+
shira_indices2_f = peft_model.base_model.model.lin2.shira_indices["first"]
|
| 203 |
+
|
| 204 |
+
input = torch.randn(5, 10)
|
| 205 |
+
peft_model.set_adapter("first")
|
| 206 |
+
output_first = peft_model(input)
|
| 207 |
+
|
| 208 |
+
save_path = os.path.join(tmp_path, "shira")
|
| 209 |
+
peft_model.save_pretrained(save_path)
|
| 210 |
+
assert os.path.exists(os.path.join(save_path, "first", "adapter_config.json"))
|
| 211 |
+
del peft_model
|
| 212 |
+
|
| 213 |
+
torch.manual_seed(0)
|
| 214 |
+
mlp = MLP()
|
| 215 |
+
peft_model = PeftModel.from_pretrained(mlp, os.path.join(save_path, "first"), adapter_name="first")
|
| 216 |
+
|
| 217 |
+
peft_model.set_adapter("first")
|
| 218 |
+
output_first_loaded = peft_model(input)
|
| 219 |
+
|
| 220 |
+
assert torch.allclose(output_first, output_first_loaded)
|
| 221 |
+
|
| 222 |
+
assert torch.all(shira_assign_val1_f == peft_model.base_model.model.lin1.shira_weight["first"])
|
| 223 |
+
assert torch.all(shira_assign_val2_f == peft_model.base_model.model.lin2.shira_weight["first"])
|
| 224 |
+
assert torch.all(shira_indices1_f == peft_model.base_model.model.lin1.shira_indices["first"])
|
| 225 |
+
assert torch.all(shira_indices2_f == peft_model.base_model.model.lin2.shira_indices["first"])
|
| 226 |
+
|
| 227 |
+
return peft_model
|
| 228 |
+
|
| 229 |
+
def test_save_load_default_random_mask_with_seed_function(self, mlp, tmp_path):
|
| 230 |
+
# we want to see if saving and loading works when a random mask is involved but the random seed is fixed.
|
| 231 |
+
config = ShiraConfig(r=2, target_modules=["lin1", "lin2"], random_seed=567, init_weights=False)
|
| 232 |
+
|
| 233 |
+
# create a custom mask SHiRA adapter
|
| 234 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 235 |
+
|
| 236 |
+
shira_assign_val1_f = peft_model.base_model.model.lin1.shira_weight["first"]
|
| 237 |
+
shira_indices1_f = peft_model.base_model.model.lin1.shira_indices["first"]
|
| 238 |
+
shira_assign_val2_f = peft_model.base_model.model.lin2.shira_weight["first"]
|
| 239 |
+
shira_indices2_f = peft_model.base_model.model.lin2.shira_indices["first"]
|
| 240 |
+
|
| 241 |
+
input = torch.randn(5, 10)
|
| 242 |
+
peft_model.set_adapter("first")
|
| 243 |
+
output_first = peft_model(input)
|
| 244 |
+
|
| 245 |
+
save_path = os.path.join(tmp_path, "shira")
|
| 246 |
+
peft_model.save_pretrained(save_path)
|
| 247 |
+
assert os.path.exists(os.path.join(save_path, "first", "adapter_config.json"))
|
| 248 |
+
del peft_model
|
| 249 |
+
|
| 250 |
+
torch.manual_seed(0)
|
| 251 |
+
mlp = MLP()
|
| 252 |
+
peft_model = PeftModel.from_pretrained(mlp, os.path.join(save_path, "first"), adapter_name="first")
|
| 253 |
+
|
| 254 |
+
peft_model.set_adapter("first")
|
| 255 |
+
output_first_loaded = peft_model(input)
|
| 256 |
+
|
| 257 |
+
assert torch.allclose(output_first, output_first_loaded)
|
| 258 |
+
|
| 259 |
+
assert torch.all(shira_assign_val1_f == peft_model.base_model.model.lin1.shira_weight["first"])
|
| 260 |
+
assert torch.all(shira_assign_val2_f == peft_model.base_model.model.lin2.shira_weight["first"])
|
| 261 |
+
assert torch.all(shira_indices1_f == peft_model.base_model.model.lin1.shira_indices["first"])
|
| 262 |
+
assert torch.all(shira_indices2_f == peft_model.base_model.model.lin2.shira_indices["first"])
|
| 263 |
+
|
| 264 |
+
return peft_model
|
| 265 |
+
|
| 266 |
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
| 267 |
+
def test_shira_dtypes(self, dtype):
|
| 268 |
+
if dtype == torch.bfloat16:
|
| 269 |
+
# skip if bf16 is not supported on hardware, see #1872
|
| 270 |
+
if not is_bf16_available():
|
| 271 |
+
pytest.skip("bfloat16 not supported on this system, skipping the test")
|
| 272 |
+
|
| 273 |
+
model = MLP().to(dtype)
|
| 274 |
+
config = ShiraConfig(r=2, target_modules=["lin1", "lin2"])
|
| 275 |
+
peft_model = get_peft_model(model, config)
|
| 276 |
+
inputs = torch.randn(5, 10).to(dtype)
|
| 277 |
+
output = peft_model(inputs) # should not raise
|
| 278 |
+
assert output.dtype == dtype
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_stablediffusion.py
ADDED
|
@@ -0,0 +1,462 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import copy
|
| 16 |
+
from dataclasses import asdict, replace
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import pytest
|
| 20 |
+
import torch
|
| 21 |
+
from diffusers import AutoModel, StableDiffusionPipeline
|
| 22 |
+
|
| 23 |
+
from peft import (
|
| 24 |
+
BOFTConfig,
|
| 25 |
+
HRAConfig,
|
| 26 |
+
LoHaConfig,
|
| 27 |
+
LoKrConfig,
|
| 28 |
+
LoraConfig,
|
| 29 |
+
OFTConfig,
|
| 30 |
+
convert_to_lora,
|
| 31 |
+
get_peft_model,
|
| 32 |
+
get_peft_model_state_dict,
|
| 33 |
+
inject_adapter_in_model,
|
| 34 |
+
set_peft_model_state_dict,
|
| 35 |
+
)
|
| 36 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 37 |
+
|
| 38 |
+
from .testing_common import PeftCommonTester
|
| 39 |
+
from .testing_utils import hub_online_once, set_init_weights_false, temp_seed
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
PEFT_DIFFUSERS_SD_MODELS_TO_TEST = ["hf-internal-testing/tiny-sd-pipe"]
|
| 43 |
+
DIFFUSERS_CONFIGS = [
|
| 44 |
+
(
|
| 45 |
+
LoraConfig,
|
| 46 |
+
{
|
| 47 |
+
"text_encoder": {
|
| 48 |
+
"r": 8,
|
| 49 |
+
"lora_alpha": 32,
|
| 50 |
+
"target_modules": ["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
|
| 51 |
+
"lora_dropout": 0.0,
|
| 52 |
+
"bias": "none",
|
| 53 |
+
"init_lora_weights": False,
|
| 54 |
+
},
|
| 55 |
+
"unet": {
|
| 56 |
+
"r": 8,
|
| 57 |
+
"lora_alpha": 32,
|
| 58 |
+
"target_modules": [
|
| 59 |
+
"proj_in",
|
| 60 |
+
"proj_out",
|
| 61 |
+
"to_k",
|
| 62 |
+
"to_q",
|
| 63 |
+
"to_v",
|
| 64 |
+
"to_out.0",
|
| 65 |
+
"ff.net.0.proj",
|
| 66 |
+
"ff.net.2",
|
| 67 |
+
],
|
| 68 |
+
"lora_dropout": 0.0,
|
| 69 |
+
"bias": "none",
|
| 70 |
+
"init_lora_weights": False,
|
| 71 |
+
},
|
| 72 |
+
},
|
| 73 |
+
),
|
| 74 |
+
(
|
| 75 |
+
LoHaConfig,
|
| 76 |
+
{
|
| 77 |
+
"text_encoder": {
|
| 78 |
+
"r": 8,
|
| 79 |
+
"alpha": 32,
|
| 80 |
+
"target_modules": ["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
|
| 81 |
+
"rank_dropout": 0.0,
|
| 82 |
+
"module_dropout": 0.0,
|
| 83 |
+
"init_weights": False,
|
| 84 |
+
},
|
| 85 |
+
"unet": {
|
| 86 |
+
"r": 8,
|
| 87 |
+
"alpha": 32,
|
| 88 |
+
"target_modules": [
|
| 89 |
+
"proj_in",
|
| 90 |
+
"proj_out",
|
| 91 |
+
"to_k",
|
| 92 |
+
"to_q",
|
| 93 |
+
"to_v",
|
| 94 |
+
"to_out.0",
|
| 95 |
+
"ff.net.0.proj",
|
| 96 |
+
"ff.net.2",
|
| 97 |
+
],
|
| 98 |
+
"rank_dropout": 0.0,
|
| 99 |
+
"module_dropout": 0.0,
|
| 100 |
+
"init_weights": False,
|
| 101 |
+
},
|
| 102 |
+
},
|
| 103 |
+
),
|
| 104 |
+
(
|
| 105 |
+
LoKrConfig,
|
| 106 |
+
{
|
| 107 |
+
"text_encoder": {
|
| 108 |
+
"r": 8,
|
| 109 |
+
"alpha": 32,
|
| 110 |
+
"target_modules": ["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
|
| 111 |
+
"rank_dropout": 0.0,
|
| 112 |
+
"module_dropout": 0.0,
|
| 113 |
+
"init_weights": False,
|
| 114 |
+
},
|
| 115 |
+
"unet": {
|
| 116 |
+
"r": 8,
|
| 117 |
+
"alpha": 32,
|
| 118 |
+
"target_modules": [
|
| 119 |
+
"proj_in",
|
| 120 |
+
"proj_out",
|
| 121 |
+
"to_k",
|
| 122 |
+
"to_q",
|
| 123 |
+
"to_v",
|
| 124 |
+
"to_out.0",
|
| 125 |
+
"ff.net.0.proj",
|
| 126 |
+
"ff.net.2",
|
| 127 |
+
],
|
| 128 |
+
"rank_dropout": 0.0,
|
| 129 |
+
"module_dropout": 0.0,
|
| 130 |
+
"init_weights": False,
|
| 131 |
+
},
|
| 132 |
+
},
|
| 133 |
+
),
|
| 134 |
+
(
|
| 135 |
+
OFTConfig,
|
| 136 |
+
{
|
| 137 |
+
"text_encoder": {
|
| 138 |
+
"r": 1,
|
| 139 |
+
"oft_block_size": 0,
|
| 140 |
+
"target_modules": ["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
|
| 141 |
+
"module_dropout": 0.0,
|
| 142 |
+
"init_weights": False,
|
| 143 |
+
"use_cayley_neumann": False,
|
| 144 |
+
},
|
| 145 |
+
"unet": {
|
| 146 |
+
"r": 1,
|
| 147 |
+
"oft_block_size": 0,
|
| 148 |
+
"target_modules": [
|
| 149 |
+
"proj_in",
|
| 150 |
+
"proj_out",
|
| 151 |
+
"to_k",
|
| 152 |
+
"to_q",
|
| 153 |
+
"to_v",
|
| 154 |
+
"to_out.0",
|
| 155 |
+
"ff.net.0.proj",
|
| 156 |
+
"ff.net.2",
|
| 157 |
+
],
|
| 158 |
+
"module_dropout": 0.0,
|
| 159 |
+
"init_weights": False,
|
| 160 |
+
"use_cayley_neumann": False,
|
| 161 |
+
},
|
| 162 |
+
},
|
| 163 |
+
),
|
| 164 |
+
(
|
| 165 |
+
BOFTConfig,
|
| 166 |
+
{
|
| 167 |
+
"text_encoder": {
|
| 168 |
+
"boft_block_num": 1,
|
| 169 |
+
"boft_block_size": 0,
|
| 170 |
+
"target_modules": ["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
|
| 171 |
+
"boft_dropout": 0.0,
|
| 172 |
+
"init_weights": False,
|
| 173 |
+
},
|
| 174 |
+
"unet": {
|
| 175 |
+
"boft_block_num": 1,
|
| 176 |
+
"boft_block_size": 0,
|
| 177 |
+
"target_modules": [
|
| 178 |
+
"proj_in",
|
| 179 |
+
"proj_out",
|
| 180 |
+
"to_k",
|
| 181 |
+
"to_q",
|
| 182 |
+
"to_v",
|
| 183 |
+
"to_out.0",
|
| 184 |
+
"ff.net.0.proj",
|
| 185 |
+
"ff.net.2",
|
| 186 |
+
],
|
| 187 |
+
"boft_dropout": 0.0,
|
| 188 |
+
"init_weights": False,
|
| 189 |
+
},
|
| 190 |
+
},
|
| 191 |
+
),
|
| 192 |
+
(
|
| 193 |
+
HRAConfig,
|
| 194 |
+
{
|
| 195 |
+
"text_encoder": {
|
| 196 |
+
"r": 8,
|
| 197 |
+
"target_modules": ["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
|
| 198 |
+
"init_weights": False,
|
| 199 |
+
},
|
| 200 |
+
"unet": {
|
| 201 |
+
"r": 8,
|
| 202 |
+
"target_modules": [
|
| 203 |
+
"proj_in",
|
| 204 |
+
"proj_out",
|
| 205 |
+
"to_k",
|
| 206 |
+
"to_q",
|
| 207 |
+
"to_v",
|
| 208 |
+
"to_out.0",
|
| 209 |
+
"ff.net.0.proj",
|
| 210 |
+
"ff.net.2",
|
| 211 |
+
],
|
| 212 |
+
"init_weights": False,
|
| 213 |
+
},
|
| 214 |
+
},
|
| 215 |
+
),
|
| 216 |
+
]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def skip_if_not_lora(config_cls):
|
| 220 |
+
if config_cls != LoraConfig:
|
| 221 |
+
pytest.skip("Skipping test because it is only applicable to LoraConfig")
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
class TestStableDiffusionModel(PeftCommonTester):
|
| 225 |
+
r"""
|
| 226 |
+
Tests that diffusers StableDiffusion model works with PEFT as expected.
|
| 227 |
+
"""
|
| 228 |
+
|
| 229 |
+
transformers_class = StableDiffusionPipeline
|
| 230 |
+
sd_model = StableDiffusionPipeline.from_pretrained("hf-internal-testing/tiny-sd-pipe")
|
| 231 |
+
|
| 232 |
+
def instantiate_sd_peft(self, model_id, config_cls, config_kwargs):
|
| 233 |
+
# Instantiate StableDiffusionPipeline
|
| 234 |
+
if model_id == "hf-internal-testing/tiny-sd-pipe":
|
| 235 |
+
# in CI, this model often times out on the hub, let's cache it
|
| 236 |
+
model = copy.deepcopy(self.sd_model)
|
| 237 |
+
else:
|
| 238 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 239 |
+
|
| 240 |
+
config_kwargs = config_kwargs.copy()
|
| 241 |
+
text_encoder_kwargs = config_kwargs.pop("text_encoder")
|
| 242 |
+
unet_kwargs = config_kwargs.pop("unet")
|
| 243 |
+
# the remaining config kwargs should be applied to both configs
|
| 244 |
+
for key, val in config_kwargs.items():
|
| 245 |
+
text_encoder_kwargs[key] = val
|
| 246 |
+
unet_kwargs[key] = val
|
| 247 |
+
|
| 248 |
+
# Instantiate text_encoder adapter
|
| 249 |
+
config_text_encoder = config_cls(**text_encoder_kwargs)
|
| 250 |
+
model.text_encoder = get_peft_model(model.text_encoder, config_text_encoder)
|
| 251 |
+
|
| 252 |
+
# Instantiate unet adapter
|
| 253 |
+
config_unet = config_cls(**unet_kwargs)
|
| 254 |
+
model.unet = get_peft_model(model.unet, config_unet)
|
| 255 |
+
|
| 256 |
+
# Move model to device
|
| 257 |
+
model = model.to(self.torch_device)
|
| 258 |
+
|
| 259 |
+
return model
|
| 260 |
+
|
| 261 |
+
def prepare_inputs_for_testing(self):
|
| 262 |
+
return {
|
| 263 |
+
"prompt": "a high quality digital photo of a cute corgi",
|
| 264 |
+
"num_inference_steps": 3,
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
@pytest.mark.parametrize("model_id", PEFT_DIFFUSERS_SD_MODELS_TO_TEST)
|
| 268 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", DIFFUSERS_CONFIGS)
|
| 269 |
+
def test_merge_layers(self, model_id, config_cls, config_kwargs):
|
| 270 |
+
if (config_cls == LoKrConfig) and (self.torch_device not in ["cuda", "xpu"]):
|
| 271 |
+
pytest.skip("Merging test with LoKr fails without GPU")
|
| 272 |
+
|
| 273 |
+
# Instantiate model & adapters
|
| 274 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 275 |
+
model = self.instantiate_sd_peft(model_id, config_cls, config_kwargs)
|
| 276 |
+
|
| 277 |
+
# Generate output for peft modified StableDiffusion
|
| 278 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 279 |
+
with temp_seed(seed=42):
|
| 280 |
+
peft_output = np.array(model(**dummy_input).images[0]).astype(np.float32)
|
| 281 |
+
|
| 282 |
+
# Merge adapter and model
|
| 283 |
+
if config_cls not in [LoHaConfig, OFTConfig, HRAConfig]:
|
| 284 |
+
# TODO: Merging the text_encoder is leading to issues on CPU with PyTorch 2.1
|
| 285 |
+
model.text_encoder = model.text_encoder.merge_and_unload()
|
| 286 |
+
model.unet = model.unet.merge_and_unload()
|
| 287 |
+
|
| 288 |
+
# Generate output for peft merged StableDiffusion
|
| 289 |
+
with temp_seed(seed=42):
|
| 290 |
+
merged_output = np.array(model(**dummy_input).images[0]).astype(np.float32)
|
| 291 |
+
|
| 292 |
+
# Images are in uint8 drange, so use large atol
|
| 293 |
+
assert np.allclose(peft_output, merged_output, atol=1.0)
|
| 294 |
+
|
| 295 |
+
@pytest.mark.parametrize("model_id", PEFT_DIFFUSERS_SD_MODELS_TO_TEST)
|
| 296 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", DIFFUSERS_CONFIGS)
|
| 297 |
+
def test_merge_layers_safe_merge(self, model_id, config_cls, config_kwargs):
|
| 298 |
+
if (config_cls == LoKrConfig) and (self.torch_device not in ["cuda", "xpu"]):
|
| 299 |
+
pytest.skip("Merging test with LoKr fails without GPU")
|
| 300 |
+
|
| 301 |
+
# Instantiate model & adapters
|
| 302 |
+
model = self.instantiate_sd_peft(model_id, config_cls, config_kwargs)
|
| 303 |
+
|
| 304 |
+
# Generate output for peft modified StableDiffusion
|
| 305 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 306 |
+
with temp_seed(seed=42):
|
| 307 |
+
peft_output = np.array(model(**dummy_input).images[0]).astype(np.float32)
|
| 308 |
+
|
| 309 |
+
# Merge adapter and model
|
| 310 |
+
if config_cls not in [LoHaConfig, OFTConfig, HRAConfig]:
|
| 311 |
+
# TODO: Merging the text_encoder is leading to issues on CPU with PyTorch 2.1
|
| 312 |
+
model.text_encoder = model.text_encoder.merge_and_unload(safe_merge=True)
|
| 313 |
+
model.unet = model.unet.merge_and_unload(safe_merge=True)
|
| 314 |
+
|
| 315 |
+
# Generate output for peft merged StableDiffusion
|
| 316 |
+
with temp_seed(seed=42):
|
| 317 |
+
merged_output = np.array(model(**dummy_input).images[0]).astype(np.float32)
|
| 318 |
+
|
| 319 |
+
# Images are in uint8 drange, so use large atol
|
| 320 |
+
assert np.allclose(peft_output, merged_output, atol=1.0)
|
| 321 |
+
|
| 322 |
+
@pytest.mark.parametrize("model_id", PEFT_DIFFUSERS_SD_MODELS_TO_TEST)
|
| 323 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", DIFFUSERS_CONFIGS)
|
| 324 |
+
def test_add_weighted_adapter_base_unchanged(self, model_id, config_cls, config_kwargs):
|
| 325 |
+
skip_if_not_lora(config_cls)
|
| 326 |
+
# Instantiate model & adapters
|
| 327 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 328 |
+
model = self.instantiate_sd_peft(model_id, config_cls, config_kwargs)
|
| 329 |
+
|
| 330 |
+
# Get current available adapter config
|
| 331 |
+
text_encoder_adapter_name = next(iter(model.text_encoder.peft_config.keys()))
|
| 332 |
+
unet_adapter_name = next(iter(model.unet.peft_config.keys()))
|
| 333 |
+
text_encoder_adapter_config = replace(model.text_encoder.peft_config[text_encoder_adapter_name])
|
| 334 |
+
unet_adapter_config = replace(model.unet.peft_config[unet_adapter_name])
|
| 335 |
+
|
| 336 |
+
# Create weighted adapters
|
| 337 |
+
model.text_encoder.add_weighted_adapter([unet_adapter_name], [0.5], "weighted_adapter_test")
|
| 338 |
+
model.unet.add_weighted_adapter([unet_adapter_name], [0.5], "weighted_adapter_test")
|
| 339 |
+
|
| 340 |
+
# Assert that base adapters config did not change
|
| 341 |
+
assert asdict(text_encoder_adapter_config) == asdict(model.text_encoder.peft_config[text_encoder_adapter_name])
|
| 342 |
+
assert asdict(unet_adapter_config) == asdict(model.unet.peft_config[unet_adapter_name])
|
| 343 |
+
|
| 344 |
+
@pytest.mark.parametrize("model_id", PEFT_DIFFUSERS_SD_MODELS_TO_TEST)
|
| 345 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", DIFFUSERS_CONFIGS)
|
| 346 |
+
def test_disable_adapter(self, model_id, config_cls, config_kwargs):
|
| 347 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 348 |
+
self._test_disable_adapter(model_id, config_cls, config_kwargs)
|
| 349 |
+
|
| 350 |
+
@pytest.mark.parametrize("model_id", PEFT_DIFFUSERS_SD_MODELS_TO_TEST)
|
| 351 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", DIFFUSERS_CONFIGS)
|
| 352 |
+
def test_load_model_low_cpu_mem_usage(self, model_id, config_cls, config_kwargs):
|
| 353 |
+
# Instantiate model & adapters
|
| 354 |
+
pipe = self.instantiate_sd_peft(model_id, config_cls, config_kwargs)
|
| 355 |
+
|
| 356 |
+
te_state_dict = get_peft_model_state_dict(pipe.text_encoder)
|
| 357 |
+
unet_state_dict = get_peft_model_state_dict(pipe.unet)
|
| 358 |
+
|
| 359 |
+
del pipe
|
| 360 |
+
pipe = self.instantiate_sd_peft(model_id, config_cls, config_kwargs)
|
| 361 |
+
|
| 362 |
+
config_kwargs = config_kwargs.copy()
|
| 363 |
+
text_encoder_kwargs = config_kwargs.pop("text_encoder")
|
| 364 |
+
unet_kwargs = config_kwargs.pop("unet")
|
| 365 |
+
# the remaining config kwargs should be applied to both configs
|
| 366 |
+
for key, val in config_kwargs.items():
|
| 367 |
+
text_encoder_kwargs[key] = val
|
| 368 |
+
unet_kwargs[key] = val
|
| 369 |
+
|
| 370 |
+
config_text_encoder = config_cls(**text_encoder_kwargs)
|
| 371 |
+
config_unet = config_cls(**unet_kwargs)
|
| 372 |
+
|
| 373 |
+
# check text encoder
|
| 374 |
+
inject_adapter_in_model(config_text_encoder, pipe.text_encoder, low_cpu_mem_usage=True)
|
| 375 |
+
# sanity check that the adapter was applied:
|
| 376 |
+
assert any(isinstance(module, BaseTunerLayer) for module in pipe.text_encoder.modules())
|
| 377 |
+
|
| 378 |
+
assert "meta" in {p.device.type for p in pipe.text_encoder.parameters()}
|
| 379 |
+
set_peft_model_state_dict(pipe.text_encoder, te_state_dict, low_cpu_mem_usage=True)
|
| 380 |
+
assert "meta" not in {p.device.type for p in pipe.text_encoder.parameters()}
|
| 381 |
+
|
| 382 |
+
# check unet
|
| 383 |
+
inject_adapter_in_model(config_unet, pipe.unet, low_cpu_mem_usage=True)
|
| 384 |
+
# sanity check that the adapter was applied:
|
| 385 |
+
assert any(isinstance(module, BaseTunerLayer) for module in pipe.unet.modules())
|
| 386 |
+
|
| 387 |
+
assert "meta" in {p.device.type for p in pipe.unet.parameters()}
|
| 388 |
+
set_peft_model_state_dict(pipe.unet, unet_state_dict, low_cpu_mem_usage=True)
|
| 389 |
+
assert "meta" not in {p.device.type for p in pipe.unet.parameters()}
|
| 390 |
+
|
| 391 |
+
def test_lora_conversion(self):
|
| 392 |
+
# For now, testing a model with only linear layers, as other types are not supported yet
|
| 393 |
+
torch.manual_seed(0)
|
| 394 |
+
model_id = "hf-internal-testing/tiny-flux2"
|
| 395 |
+
|
| 396 |
+
# from Flux2TransformerTests in Diffusers
|
| 397 |
+
height = 4
|
| 398 |
+
width = 4
|
| 399 |
+
batch_size = 1
|
| 400 |
+
num_latent_channels = 4
|
| 401 |
+
sequence_length = 48
|
| 402 |
+
embedding_dim = 16
|
| 403 |
+
|
| 404 |
+
hidden_states = torch.randn((batch_size, height * width, num_latent_channels))
|
| 405 |
+
encoder_hidden_states = torch.randn((batch_size, sequence_length, embedding_dim))
|
| 406 |
+
|
| 407 |
+
t_coords = torch.arange(1)
|
| 408 |
+
h_coords = torch.arange(height)
|
| 409 |
+
w_coords = torch.arange(width)
|
| 410 |
+
l_coords = torch.arange(1)
|
| 411 |
+
image_ids = torch.cartesian_prod(t_coords, h_coords, w_coords, l_coords) # [height * width, 4]
|
| 412 |
+
image_ids = image_ids.unsqueeze(0).expand(batch_size, -1, -1)
|
| 413 |
+
|
| 414 |
+
text_t_coords = torch.arange(1)
|
| 415 |
+
text_h_coords = torch.arange(1)
|
| 416 |
+
text_w_coords = torch.arange(1)
|
| 417 |
+
text_l_coords = torch.arange(sequence_length)
|
| 418 |
+
text_ids = torch.cartesian_prod(text_t_coords, text_h_coords, text_w_coords, text_l_coords)
|
| 419 |
+
text_ids = text_ids.unsqueeze(0).expand(batch_size, -1, -1)
|
| 420 |
+
|
| 421 |
+
timestep = torch.tensor([1.0]).expand(batch_size)
|
| 422 |
+
guidance = torch.tensor([1.0]).expand(batch_size)
|
| 423 |
+
|
| 424 |
+
inputs = {
|
| 425 |
+
"hidden_states": hidden_states,
|
| 426 |
+
"encoder_hidden_states": encoder_hidden_states,
|
| 427 |
+
"timestep": timestep,
|
| 428 |
+
"img_ids": image_ids,
|
| 429 |
+
"txt_ids": text_ids,
|
| 430 |
+
"guidance": guidance,
|
| 431 |
+
}
|
| 432 |
+
|
| 433 |
+
with hub_online_once(model_id):
|
| 434 |
+
model = AutoModel.from_pretrained(model_id, subfolder="transformer")
|
| 435 |
+
with torch.inference_mode():
|
| 436 |
+
output_base = model(**inputs)
|
| 437 |
+
|
| 438 |
+
loha_config = LoHaConfig(target_modules=["to_q", "to_v"], init_weights=False, alpha=100)
|
| 439 |
+
model_loha = get_peft_model(copy.deepcopy(model), loha_config)
|
| 440 |
+
with torch.inference_mode():
|
| 441 |
+
output_loha = model_loha(**inputs)
|
| 442 |
+
|
| 443 |
+
# sanity check: loha changes outputs
|
| 444 |
+
atol, rtol = 1e-4, 1e-4
|
| 445 |
+
assert not torch.allclose(output_base.sample, output_loha.sample, atol=atol, rtol=rtol)
|
| 446 |
+
|
| 447 |
+
lora_config, state_dict = convert_to_lora(model_loha, rank=4)
|
| 448 |
+
model_lora = get_peft_model(model, lora_config).eval()
|
| 449 |
+
with torch.inference_mode():
|
| 450 |
+
output_lora = model_lora(**inputs)
|
| 451 |
+
load_result = set_peft_model_state_dict(model_lora, state_dict)
|
| 452 |
+
assert not load_result.unexpected_keys
|
| 453 |
+
|
| 454 |
+
with torch.inference_mode():
|
| 455 |
+
output_converted = model_lora(**inputs)
|
| 456 |
+
|
| 457 |
+
# calculate MSE
|
| 458 |
+
mse_lora = torch.nn.functional.mse_loss(output_loha.sample, output_lora.sample)
|
| 459 |
+
mse_converted = torch.nn.functional.mse_loss(output_loha.sample, output_converted.sample)
|
| 460 |
+
|
| 461 |
+
# converted model should be significantly closer to the LoHa model than the base model
|
| 462 |
+
assert mse_lora / mse_converted > 2
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_target_parameters.py
ADDED
|
@@ -0,0 +1,546 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import pytest
|
| 16 |
+
import torch
|
| 17 |
+
from torch import nn
|
| 18 |
+
from transformers import AutoModelForCausalLM
|
| 19 |
+
|
| 20 |
+
import peft
|
| 21 |
+
from peft import LoraConfig, TaskType, get_peft_model
|
| 22 |
+
|
| 23 |
+
from .testing_common import PeftCommonTester
|
| 24 |
+
from .testing_utils import hub_online_once, set_init_weights_false
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
ALL_CONFIGS = [
|
| 28 |
+
##########
|
| 29 |
+
# Llama4 #
|
| 30 |
+
##########
|
| 31 |
+
# target down_proj
|
| 32 |
+
(
|
| 33 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 34 |
+
LoraConfig,
|
| 35 |
+
{
|
| 36 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 37 |
+
"target_modules": [],
|
| 38 |
+
"lora_dropout": 0.0,
|
| 39 |
+
"target_parameters": [
|
| 40 |
+
"feed_forward.experts.down_proj",
|
| 41 |
+
],
|
| 42 |
+
},
|
| 43 |
+
),
|
| 44 |
+
# target gate_up_proj and down_proj, but not on the same module
|
| 45 |
+
(
|
| 46 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 47 |
+
LoraConfig,
|
| 48 |
+
{
|
| 49 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 50 |
+
"target_modules": [],
|
| 51 |
+
"lora_dropout": 0.0,
|
| 52 |
+
"target_parameters": [
|
| 53 |
+
"0.feed_forward.experts.gate_up_proj",
|
| 54 |
+
"1.feed_forward.experts.down_proj",
|
| 55 |
+
],
|
| 56 |
+
},
|
| 57 |
+
),
|
| 58 |
+
# target down_proj and gate_up_proj on the same module
|
| 59 |
+
(
|
| 60 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 61 |
+
LoraConfig,
|
| 62 |
+
{
|
| 63 |
+
"task_type": "CAUSAL_LM",
|
| 64 |
+
"r": 8,
|
| 65 |
+
"lora_alpha": 32,
|
| 66 |
+
"target_modules": None,
|
| 67 |
+
"lora_dropout": 0.0,
|
| 68 |
+
"bias": "none",
|
| 69 |
+
"target_parameters": [
|
| 70 |
+
"feed_forward.experts.down_proj",
|
| 71 |
+
"feed_forward.experts.gate_up_proj",
|
| 72 |
+
],
|
| 73 |
+
},
|
| 74 |
+
),
|
| 75 |
+
# target q_proj, v_proj as modules, and down_proj as parameter
|
| 76 |
+
(
|
| 77 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 78 |
+
LoraConfig,
|
| 79 |
+
{
|
| 80 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 81 |
+
"target_modules": ["q_proj", "v_proj"],
|
| 82 |
+
"lora_dropout": 0.0,
|
| 83 |
+
"target_parameters": [
|
| 84 |
+
"feed_forward.experts.down_proj",
|
| 85 |
+
],
|
| 86 |
+
},
|
| 87 |
+
),
|
| 88 |
+
###########
|
| 89 |
+
# gpt-oss #
|
| 90 |
+
###########
|
| 91 |
+
# target down_proj
|
| 92 |
+
(
|
| 93 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 94 |
+
LoraConfig,
|
| 95 |
+
{
|
| 96 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 97 |
+
"target_modules": [],
|
| 98 |
+
"lora_dropout": 0.0,
|
| 99 |
+
"target_parameters": [
|
| 100 |
+
"mlp.experts.down_proj",
|
| 101 |
+
],
|
| 102 |
+
},
|
| 103 |
+
),
|
| 104 |
+
# target gate_up_proj and down_proj, but not on the same module
|
| 105 |
+
(
|
| 106 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 107 |
+
LoraConfig,
|
| 108 |
+
{
|
| 109 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 110 |
+
"target_modules": [],
|
| 111 |
+
"lora_dropout": 0.0,
|
| 112 |
+
"target_parameters": [
|
| 113 |
+
"0.mlp.experts.gate_up_proj",
|
| 114 |
+
"1.mlp.experts.down_proj",
|
| 115 |
+
],
|
| 116 |
+
},
|
| 117 |
+
),
|
| 118 |
+
# target down_proj and gate_up_proj on the same module
|
| 119 |
+
(
|
| 120 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 121 |
+
LoraConfig,
|
| 122 |
+
{
|
| 123 |
+
"task_type": "CAUSAL_LM",
|
| 124 |
+
"r": 8,
|
| 125 |
+
"lora_alpha": 32,
|
| 126 |
+
"target_modules": None,
|
| 127 |
+
"lora_dropout": 0.0,
|
| 128 |
+
"bias": "none",
|
| 129 |
+
"target_parameters": [
|
| 130 |
+
"mlp.experts.down_proj",
|
| 131 |
+
"mlp.experts.gate_up_proj",
|
| 132 |
+
],
|
| 133 |
+
},
|
| 134 |
+
),
|
| 135 |
+
# target q_proj, v_proj as modules, and down_proj as parameter
|
| 136 |
+
(
|
| 137 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 138 |
+
LoraConfig,
|
| 139 |
+
{
|
| 140 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 141 |
+
"target_modules": ["q_proj", "v_proj"],
|
| 142 |
+
"lora_dropout": 0.0,
|
| 143 |
+
"target_parameters": [
|
| 144 |
+
"mlp.experts.down_proj",
|
| 145 |
+
],
|
| 146 |
+
},
|
| 147 |
+
),
|
| 148 |
+
]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class MyAutoModelForCausalLM(AutoModelForCausalLM):
|
| 152 |
+
@classmethod
|
| 153 |
+
def from_pretrained(cls, *args, **kwargs):
|
| 154 |
+
torch.manual_seed(0)
|
| 155 |
+
model = AutoModelForCausalLM.from_pretrained(*args, **kwargs)
|
| 156 |
+
|
| 157 |
+
# check that we load the original model, not, say, a trained checkpoint
|
| 158 |
+
if args[0] == "trl-internal-testing/tiny-Llama4ForCausalLM":
|
| 159 |
+
# model contains weights with values ~1e36 or nan, so we need to reinitialize with sane values
|
| 160 |
+
with torch.no_grad():
|
| 161 |
+
for param in model.parameters():
|
| 162 |
+
param.data = torch.randn(param.shape)
|
| 163 |
+
return model
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class TestDecoderModelsTargetParameters(PeftCommonTester):
|
| 167 |
+
# This is more or less a copy of TestDecoderModels at the time of the PR being added. Unnecessary code is removed,
|
| 168 |
+
# like code required for testing non-LoRA methods. The tests being included are not selected to test specific
|
| 169 |
+
# functionality of targeting nn.Parameters, they (together with the tests in test_custom_models.py) just ensure that
|
| 170 |
+
# generally, nothing is broken.
|
| 171 |
+
transformers_class = MyAutoModelForCausalLM
|
| 172 |
+
|
| 173 |
+
def prepare_inputs_for_testing(self):
|
| 174 |
+
input_ids = torch.tensor([[1, 1, 1], [1, 2, 1]]).to(self.torch_device)
|
| 175 |
+
attention_mask = torch.tensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 176 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 177 |
+
|
| 178 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 179 |
+
def test_attributes_parametrized(self, model_id, config_cls, config_kwargs):
|
| 180 |
+
self._test_model_attr(model_id, config_cls, config_kwargs.copy())
|
| 181 |
+
|
| 182 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 183 |
+
def test_adapter_name(self, model_id, config_cls, config_kwargs):
|
| 184 |
+
self._test_adapter_name(model_id, config_cls, config_kwargs.copy())
|
| 185 |
+
|
| 186 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 187 |
+
def test_prepare_for_training_parametrized(self, model_id, config_cls, config_kwargs):
|
| 188 |
+
self._test_prepare_for_training(model_id, config_cls, config_kwargs.copy())
|
| 189 |
+
|
| 190 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 191 |
+
def test_save_pretrained(self, model_id, config_cls, config_kwargs):
|
| 192 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy())
|
| 193 |
+
|
| 194 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 195 |
+
def test_save_pretrained_pickle(self, model_id, config_cls, config_kwargs):
|
| 196 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy(), safe_serialization=False)
|
| 197 |
+
|
| 198 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 199 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 200 |
+
def test_save_pretrained_selected_adapters(self, model_id, config_cls, config_kwargs):
|
| 201 |
+
self._test_save_pretrained_selected_adapters(model_id, config_cls, config_kwargs.copy())
|
| 202 |
+
|
| 203 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 204 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 205 |
+
def test_save_pretrained_selected_adapters_pickle(self, model_id, config_cls, config_kwargs):
|
| 206 |
+
self._test_save_pretrained_selected_adapters(
|
| 207 |
+
model_id, config_cls, config_kwargs.copy(), safe_serialization=False
|
| 208 |
+
)
|
| 209 |
+
|
| 210 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 211 |
+
def test_from_pretrained_config_construction(self, model_id, config_cls, config_kwargs):
|
| 212 |
+
self._test_from_pretrained_config_construction(model_id, config_cls, config_kwargs.copy())
|
| 213 |
+
|
| 214 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 215 |
+
def test_merge_layers(self, model_id, config_cls, config_kwargs):
|
| 216 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 217 |
+
self._test_merge_layers(model_id, config_cls, config_kwargs.copy())
|
| 218 |
+
|
| 219 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 220 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 221 |
+
def test_merge_layers_multi(self, model_id, config_cls, config_kwargs):
|
| 222 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 223 |
+
self._test_merge_layers_multi(model_id, config_cls, config_kwargs.copy())
|
| 224 |
+
|
| 225 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 226 |
+
def test_merge_layers_nan(self, model_id, config_cls, config_kwargs):
|
| 227 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 228 |
+
self._test_merge_layers_nan(model_id, config_cls, config_kwargs.copy())
|
| 229 |
+
|
| 230 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 231 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 232 |
+
def test_mixed_adapter_batches(self, model_id, config_cls, config_kwargs):
|
| 233 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 234 |
+
msg = "lora.ParamWrapper does not support mixed adapter batches yet."
|
| 235 |
+
with pytest.raises(ValueError, match=msg):
|
| 236 |
+
self._test_mixed_adapter_batches(model_id, config_cls, config_kwargs.copy())
|
| 237 |
+
|
| 238 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 239 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 240 |
+
def test_generate_with_mixed_adapter_batches(self, model_id, config_cls, config_kwargs):
|
| 241 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 242 |
+
msg = "lora.ParamWrapper does not support mixed adapter batches yet."
|
| 243 |
+
with pytest.raises(ValueError, match=msg):
|
| 244 |
+
self._test_generate_with_mixed_adapter_batches_and_beam_search(model_id, config_cls, config_kwargs.copy())
|
| 245 |
+
|
| 246 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 247 |
+
def test_generate(self, model_id, config_cls, config_kwargs):
|
| 248 |
+
self._test_generate(model_id, config_cls, config_kwargs.copy())
|
| 249 |
+
|
| 250 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 251 |
+
def test_generate_pos_args(self, model_id, config_cls, config_kwargs):
|
| 252 |
+
self._test_generate_pos_args(model_id, config_cls, config_kwargs.copy(), raises_err=False)
|
| 253 |
+
|
| 254 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 255 |
+
def test_merge_layers_fp16(self, model_id, config_cls, config_kwargs):
|
| 256 |
+
self._test_merge_layers_fp16(model_id, config_cls, config_kwargs.copy())
|
| 257 |
+
|
| 258 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 259 |
+
def test_generate_half_prec(self, model_id, config_cls, config_kwargs):
|
| 260 |
+
self._test_generate_half_prec(model_id, config_cls, config_kwargs.copy())
|
| 261 |
+
|
| 262 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 263 |
+
def test_training_decoders(self, model_id, config_cls, config_kwargs):
|
| 264 |
+
self._test_training(model_id, config_cls, config_kwargs.copy())
|
| 265 |
+
|
| 266 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 267 |
+
def test_training_decoders_gradient_checkpointing(self, model_id, config_cls, config_kwargs):
|
| 268 |
+
self._test_training_gradient_checkpointing(model_id, config_cls, config_kwargs.copy())
|
| 269 |
+
|
| 270 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 271 |
+
def test_inference_safetensors(self, model_id, config_cls, config_kwargs):
|
| 272 |
+
self._test_inference_safetensors(model_id, config_cls, config_kwargs.copy())
|
| 273 |
+
|
| 274 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 275 |
+
def test_peft_model_device_map(self, model_id, config_cls, config_kwargs):
|
| 276 |
+
self._test_peft_model_device_map(model_id, config_cls, config_kwargs.copy())
|
| 277 |
+
|
| 278 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 279 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 280 |
+
def test_delete_adapter(self, model_id, config_cls, config_kwargs):
|
| 281 |
+
self._test_delete_adapter(model_id, config_cls, config_kwargs.copy())
|
| 282 |
+
|
| 283 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 284 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 285 |
+
def test_delete_inactive_adapter(self, model_id, config_cls, config_kwargs):
|
| 286 |
+
self._test_delete_inactive_adapter(model_id, config_cls, config_kwargs.copy())
|
| 287 |
+
|
| 288 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 289 |
+
def test_adding_multiple_adapters_with_bias_raises(self, model_id, config_cls, config_kwargs):
|
| 290 |
+
self._test_adding_multiple_adapters_with_bias_raises(model_id, config_cls, config_kwargs.copy())
|
| 291 |
+
|
| 292 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 293 |
+
def test_unload_adapter(self, model_id, config_cls, config_kwargs):
|
| 294 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 295 |
+
self._test_unload_adapter(model_id, config_cls, config_kwargs.copy())
|
| 296 |
+
|
| 297 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 298 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 299 |
+
def test_weighted_combination_of_adapters(self, model_id, config_cls, config_kwargs):
|
| 300 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 301 |
+
msg = "add_weighted_adapter does not support targeting nn.Parameter"
|
| 302 |
+
with pytest.raises(ValueError, match=msg):
|
| 303 |
+
self._test_weighted_combination_of_adapters(model_id, config_cls, config_kwargs.copy())
|
| 304 |
+
|
| 305 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 306 |
+
def test_training_prompt_learning_tasks(self, model_id, config_cls, config_kwargs):
|
| 307 |
+
self._test_training_prompt_learning_tasks(model_id, config_cls, config_kwargs.copy())
|
| 308 |
+
|
| 309 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 310 |
+
def test_disable_adapter(self, model_id, config_cls, config_kwargs):
|
| 311 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 312 |
+
self._test_disable_adapter(model_id, config_cls, config_kwargs.copy())
|
| 313 |
+
|
| 314 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 315 |
+
def test_passing_input_embeds_works(self, model_id, config_cls, config_kwargs):
|
| 316 |
+
self._test_passing_input_embeds_works("", model_id, config_cls, config_kwargs.copy())
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class TestTargetParameters:
|
| 320 |
+
# Tests specifically designed for target_parameters
|
| 321 |
+
def test_targeting_module_and_targeting_param_equivalent(self):
|
| 322 |
+
# Test that using LoRA with target_modules vs target_parameters yields identical results.
|
| 323 |
+
# note: we purposely target the gate_proj because its weight is not square (unlike q_proj, ...), this makes it
|
| 324 |
+
# easier to catch shape errors
|
| 325 |
+
torch.manual_seed(0)
|
| 326 |
+
model_id = "hf-internal-testing/tiny-random-LlamaForCausalLM"
|
| 327 |
+
with hub_online_once(model_id):
|
| 328 |
+
model0 = AutoModelForCausalLM.from_pretrained(model_id)
|
| 329 |
+
x = torch.arange(10).view(2, 5)
|
| 330 |
+
with torch.inference_mode():
|
| 331 |
+
out_base = model0(x, output_hidden_states=True).hidden_states[-1]
|
| 332 |
+
|
| 333 |
+
# targeting the module
|
| 334 |
+
config0 = LoraConfig(target_modules=["gate_proj"], init_lora_weights=False)
|
| 335 |
+
model0 = get_peft_model(model0, config0)
|
| 336 |
+
|
| 337 |
+
# targeting the parameter
|
| 338 |
+
model1 = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
|
| 339 |
+
config1 = LoraConfig(target_modules=[], target_parameters=["gate_proj.weight"], init_lora_weights=False)
|
| 340 |
+
model1 = get_peft_model(model1, config1)
|
| 341 |
+
|
| 342 |
+
gate_proj_0_0 = model0.base_model.model.model.layers[0].mlp.gate_proj
|
| 343 |
+
gate_proj_0_1 = model0.base_model.model.model.layers[1].mlp.gate_proj
|
| 344 |
+
gate_proj_1_0 = model1.base_model.model.model.layers[0].mlp.gate_proj
|
| 345 |
+
gate_proj_1_1 = model1.base_model.model.model.layers[1].mlp.gate_proj
|
| 346 |
+
|
| 347 |
+
# ensure that the randomly initialized LoRA weights are identical
|
| 348 |
+
gate_proj_1_0.lora_A.default.weight.data.copy_(gate_proj_0_0.lora_A.default.weight.data)
|
| 349 |
+
gate_proj_1_1.lora_A.default.weight.data.copy_(gate_proj_0_1.lora_A.default.weight.data)
|
| 350 |
+
gate_proj_1_0.lora_B.default.weight.data.copy_(gate_proj_0_0.lora_B.default.weight.data)
|
| 351 |
+
gate_proj_1_1.lora_B.default.weight.data.copy_(gate_proj_0_1.lora_B.default.weight.data)
|
| 352 |
+
|
| 353 |
+
with torch.inference_mode():
|
| 354 |
+
out_lora_0 = model0(x, output_hidden_states=True).hidden_states[-1]
|
| 355 |
+
out_lora_1 = model1(x, output_hidden_states=True).hidden_states[-1]
|
| 356 |
+
|
| 357 |
+
# sanity check: basemodel outputs should be different
|
| 358 |
+
atol, rtol = 1e-6, 1e-6
|
| 359 |
+
assert not torch.allclose(out_base, out_lora_0, atol=atol, rtol=rtol)
|
| 360 |
+
|
| 361 |
+
# LoRA outputs should be the same
|
| 362 |
+
assert torch.allclose(out_lora_0, out_lora_1, atol=atol, rtol=rtol)
|
| 363 |
+
|
| 364 |
+
def test_target_multiple_parameters_on_same_module(self, monkeypatch):
|
| 365 |
+
# test that if we target multiple nn.Parameters on the same module, all of them are being used during the
|
| 366 |
+
# forward pass
|
| 367 |
+
torch.manual_seed(0)
|
| 368 |
+
model_id = "trl-internal-testing/tiny-Llama4ForCausalLM"
|
| 369 |
+
with hub_online_once(model_id):
|
| 370 |
+
x = torch.arange(10).view(2, 5)
|
| 371 |
+
model = MyAutoModelForCausalLM.from_pretrained(model_id)
|
| 372 |
+
shape_gate_up_proj = model.model.layers[0].feed_forward.experts.gate_up_proj.shape
|
| 373 |
+
shape_down_proj = model.model.layers[0].feed_forward.experts.down_proj.shape
|
| 374 |
+
num_layers = len(model.model.layers)
|
| 375 |
+
|
| 376 |
+
target_parameters = ["feed_forward.experts.gate_up_proj", "feed_forward.experts.down_proj"]
|
| 377 |
+
num_params = len(target_parameters)
|
| 378 |
+
config = LoraConfig(target_parameters=target_parameters, init_lora_weights=False)
|
| 379 |
+
model = get_peft_model(model, config)
|
| 380 |
+
|
| 381 |
+
# CHECK FORWARD CALLS
|
| 382 |
+
|
| 383 |
+
# log the weights seen during the forward call
|
| 384 |
+
weights = []
|
| 385 |
+
|
| 386 |
+
def mock_forward(self, W):
|
| 387 |
+
weights.append(W)
|
| 388 |
+
return orig_forward(self, W)
|
| 389 |
+
|
| 390 |
+
from peft.tuners.lora.layer import _LoraParameterProxy
|
| 391 |
+
|
| 392 |
+
orig_forward = _LoraParameterProxy.forward
|
| 393 |
+
monkeypatch.setattr(_LoraParameterProxy, "forward", mock_forward)
|
| 394 |
+
|
| 395 |
+
num_steps = 3
|
| 396 |
+
with torch.inference_mode():
|
| 397 |
+
for _ in range(num_steps):
|
| 398 |
+
out_base = model(x, output_hidden_states=True).hidden_states[-1]
|
| 399 |
+
|
| 400 |
+
actual_call_count = len(weights)
|
| 401 |
+
# Note: We call forward twice per step, once to create the parametrization and once for the actual forward
|
| 402 |
+
# step. This may be a bit wasteful but it's not clear how to prevent this and overall is probably negligible
|
| 403 |
+
num_forward_per_step = 2
|
| 404 |
+
# Since https://github.com/huggingface/transformers/pull/39501, one of the parameters is accessed twice per
|
| 405 |
+
# forward call, but we cache all calls after the first.
|
| 406 |
+
expected_call_count = num_steps * num_layers * num_params * num_forward_per_step
|
| 407 |
+
assert actual_call_count == expected_call_count
|
| 408 |
+
|
| 409 |
+
actual_shapes = {W.shape for W in weights}
|
| 410 |
+
expected_shapes = {shape_gate_up_proj, shape_down_proj}
|
| 411 |
+
assert actual_shapes == expected_shapes
|
| 412 |
+
|
| 413 |
+
# CHECK WEIGHT UPDATES
|
| 414 |
+
|
| 415 |
+
lora_weights_before = {
|
| 416 |
+
k: v.clone() for k, v in model.named_parameters() if "lora_A.default" in k or "lora_B.default" in k
|
| 417 |
+
}
|
| 418 |
+
# sanity check:
|
| 419 |
+
assert len(lora_weights_before) == 2 * num_layers * num_params
|
| 420 |
+
# train
|
| 421 |
+
optim = torch.optim.SGD(model.parameters(), lr=0.01)
|
| 422 |
+
for _ in range(10):
|
| 423 |
+
optim.zero_grad()
|
| 424 |
+
out = model(x)
|
| 425 |
+
loss = out.logits.sum()
|
| 426 |
+
loss.backward()
|
| 427 |
+
optim.step()
|
| 428 |
+
|
| 429 |
+
lora_weights_after = {
|
| 430 |
+
k: v for k, v in model.named_parameters() if "lora_A.default" in k or "lora_B.default" in k
|
| 431 |
+
}
|
| 432 |
+
assert lora_weights_before.keys() == lora_weights_after.keys()
|
| 433 |
+
atol, rtol = 0.1, 0.1
|
| 434 |
+
for key in lora_weights_before.keys():
|
| 435 |
+
assert not torch.allclose(lora_weights_before[key], lora_weights_after[key], atol=atol, rtol=rtol)
|
| 436 |
+
|
| 437 |
+
def test_target_parameters_works_with_existing_parametrization(self):
|
| 438 |
+
# When a parameter is already parametrized, we want the LoRA parametrization to work with it correctly.
|
| 439 |
+
class MyLinear(nn.Linear):
|
| 440 |
+
# For testing purposes, define a linear layer with 2 parameters: weight and other_weight.
|
| 441 |
+
def __init__(self, *args, **kwargs):
|
| 442 |
+
super().__init__(*args, **kwargs)
|
| 443 |
+
nn.init.ones_(self.weight)
|
| 444 |
+
self.other_weight = nn.Parameter(torch.ones(self.weight.shape))
|
| 445 |
+
|
| 446 |
+
class MyModule(nn.Module):
|
| 447 |
+
def __init__(self):
|
| 448 |
+
super().__init__()
|
| 449 |
+
self.lin = MyLinear(2, 2, bias=False)
|
| 450 |
+
|
| 451 |
+
def forward(self, x):
|
| 452 |
+
return self.lin(x)
|
| 453 |
+
|
| 454 |
+
class MyParametrization(nn.Module):
|
| 455 |
+
def __init__(self):
|
| 456 |
+
super().__init__()
|
| 457 |
+
|
| 458 |
+
def forward(self, x):
|
| 459 |
+
return x + 1
|
| 460 |
+
|
| 461 |
+
# base model
|
| 462 |
+
model = MyModule()
|
| 463 |
+
x = torch.ones((2, 2))
|
| 464 |
+
|
| 465 |
+
# sanity check: result should be 1*1 + 1*1 == 2
|
| 466 |
+
output_base = model(x)
|
| 467 |
+
assert torch.all(output_base == 2)
|
| 468 |
+
|
| 469 |
+
# add parametrization to the weight
|
| 470 |
+
nn.utils.parametrize.register_parametrization(model.lin, "weight", MyParametrization())
|
| 471 |
+
|
| 472 |
+
# result should be (1+1)*1 + (1+1)*1 == 4
|
| 473 |
+
output_parametrized = model(x)
|
| 474 |
+
assert torch.all(output_parametrized == 4)
|
| 475 |
+
|
| 476 |
+
# add LoRA parametrization to the weight
|
| 477 |
+
config = LoraConfig(r=2, lora_alpha=6, target_parameters=["lin.weight"], init_lora_weights=False)
|
| 478 |
+
model = get_peft_model(model, config)
|
| 479 |
+
# manually set LoRA weights to ones
|
| 480 |
+
nn.init.ones_(model.base_model.model.lin.lora_A["default"].weight)
|
| 481 |
+
nn.init.ones_(model.base_model.model.lin.lora_B["default"].weight)
|
| 482 |
+
|
| 483 |
+
output_lora = model(x)
|
| 484 |
+
# delta_weight should be: (1+1) * lora_scale = (1+1) * (alpha / rank) = 2 * (6 / 2) = 6
|
| 485 |
+
# result should be: (1+1+6)*1 + (1+1+6)*1 == 8 + 8 == 16
|
| 486 |
+
assert torch.all(output_lora == 16)
|
| 487 |
+
|
| 488 |
+
# calling twice should yield the same result
|
| 489 |
+
output_lora2 = model(x)
|
| 490 |
+
assert torch.allclose(output_lora, output_lora2)
|
| 491 |
+
|
| 492 |
+
# add another LoRA parametrization to other_weight, should have no effect on the output
|
| 493 |
+
config = LoraConfig(r=2, lora_alpha=6, target_parameters=["lin.other_weight"], init_lora_weights=False)
|
| 494 |
+
model.add_adapter("other", config)
|
| 495 |
+
|
| 496 |
+
output_other_lora = model(x)
|
| 497 |
+
# delta_weight should be: (1+1) * lora_scale = (1+1) * (alpha / rank) = 2 * (6 / 2) = 6
|
| 498 |
+
# result should be: (1+1+6)*1 + (1+1+6)*1 == 8 + 8 == 16
|
| 499 |
+
assert torch.all(output_other_lora == output_lora)
|
| 500 |
+
|
| 501 |
+
# after unloading, the output should be the same as before LoRA was applied
|
| 502 |
+
unloaded = model.unload()
|
| 503 |
+
output_unloaded = unloaded(x)
|
| 504 |
+
assert torch.all(output_unloaded == output_parametrized)
|
| 505 |
+
|
| 506 |
+
def test_target_parameter_result_caching_works(self, monkeypatch):
|
| 507 |
+
# See 2912
|
| 508 |
+
# There was an issue with the caching of _LoraParameterProxy not working correctly. This test checks that the
|
| 509 |
+
# results returned from the forward call are all identical to ensure they're not recomputed each time.
|
| 510 |
+
torch.manual_seed(0)
|
| 511 |
+
model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
|
| 512 |
+
|
| 513 |
+
tensor_storage = []
|
| 514 |
+
|
| 515 |
+
def store_tensors_deco(fn):
|
| 516 |
+
def wrapper(*args, **kwargs):
|
| 517 |
+
result = fn(*args, **kwargs)
|
| 518 |
+
tensor_storage.append(result)
|
| 519 |
+
return result
|
| 520 |
+
|
| 521 |
+
return wrapper
|
| 522 |
+
|
| 523 |
+
monkeypatch.setattr(
|
| 524 |
+
peft.tuners.lora.layer._LoraParameterProxy,
|
| 525 |
+
"forward",
|
| 526 |
+
store_tensors_deco(peft.tuners.lora.layer._LoraParameterProxy.forward),
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
with hub_online_once(model_id):
|
| 530 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 531 |
+
config = LoraConfig(
|
| 532 |
+
target_modules=[],
|
| 533 |
+
# for simplicity, only target a single layer
|
| 534 |
+
target_parameters=["0.mlp.experts.gate_up_proj"],
|
| 535 |
+
)
|
| 536 |
+
model = get_peft_model(model, config)
|
| 537 |
+
x = torch.arange(100).view(2, 50) # larger input to hit many experts
|
| 538 |
+
|
| 539 |
+
# forward is called twice, once at initialization of the parametrization and once during the forward pass,
|
| 540 |
+
# after which it is cached; without caching, it would be called 25 times.
|
| 541 |
+
output = model(x, output_hidden_states=True)
|
| 542 |
+
assert len(set(map(id, tensor_storage))) == 2
|
| 543 |
+
|
| 544 |
+
# sanity check: a second forward call _does_ trigger a new forward
|
| 545 |
+
output = model(x, output_hidden_states=True)
|
| 546 |
+
assert len(set(map(id, tensor_storage))) == 4
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_torch_compile.py
ADDED
|
@@ -0,0 +1,599 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# The intent of the tests contained in this file is to check as many PEFT features as possible with torch.compile. This
|
| 16 |
+
# is thus a document on how well torch.compile is supported by PEFT. Currently, we know that certain features do not
|
| 17 |
+
# work with torch.compile. The corresponding tests should be marked with `@pytest.mark.xfail(strict=True)`.
|
| 18 |
+
#
|
| 19 |
+
# When adding a new test that fails with torch.compile, please make sure first that it does NOT fail without
|
| 20 |
+
# torch.compile.
|
| 21 |
+
|
| 22 |
+
import gc
|
| 23 |
+
import os
|
| 24 |
+
|
| 25 |
+
import pytest
|
| 26 |
+
import torch
|
| 27 |
+
from accelerate.utils.memory import clear_device_cache
|
| 28 |
+
from transformers import (
|
| 29 |
+
AutoModelForCausalLM,
|
| 30 |
+
AutoTokenizer,
|
| 31 |
+
BitsAndBytesConfig,
|
| 32 |
+
DataCollatorForLanguageModeling,
|
| 33 |
+
Trainer,
|
| 34 |
+
TrainerCallback,
|
| 35 |
+
TrainingArguments,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
from peft import (
|
| 39 |
+
AdaLoraConfig,
|
| 40 |
+
BOFTConfig,
|
| 41 |
+
BoneConfig,
|
| 42 |
+
HRAConfig,
|
| 43 |
+
IA3Config,
|
| 44 |
+
LNTuningConfig,
|
| 45 |
+
LoHaConfig,
|
| 46 |
+
LoKrConfig,
|
| 47 |
+
LoraConfig,
|
| 48 |
+
MissConfig,
|
| 49 |
+
OFTConfig,
|
| 50 |
+
PeftModel,
|
| 51 |
+
TaskType,
|
| 52 |
+
VBLoRAConfig,
|
| 53 |
+
VeraConfig,
|
| 54 |
+
get_peft_model,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
from .testing_utils import load_dataset_english_quotes, require_bitsandbytes
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# only run (very slow) torch.compile tests when explicitly asked to
|
| 61 |
+
if os.environ.get("PEFT_DEBUG_WITH_TORCH_COMPILE") != "1":
|
| 62 |
+
pytest.skip(allow_module_level=True)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
# Mapping: name of the setting -> (Peft config instance, torch.compile kwargs)
|
| 66 |
+
SETTINGS = {
|
| 67 |
+
"adalora": (AdaLoraConfig(task_type=TaskType.CAUSAL_LM, total_step=5), {}),
|
| 68 |
+
"boft": (BOFTConfig(task_type=TaskType.CAUSAL_LM), {}),
|
| 69 |
+
"dora": (LoraConfig(task_type=TaskType.CAUSAL_LM, use_dora=True), {}),
|
| 70 |
+
"ia3": (IA3Config(task_type=TaskType.CAUSAL_LM), {}),
|
| 71 |
+
"ln_tuning": (LNTuningConfig(task_type=TaskType.CAUSAL_LM, target_modules=["final_layer_norm"]), {}),
|
| 72 |
+
"loha": (LoHaConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 73 |
+
"lokr": pytest.param(
|
| 74 |
+
(LoKrConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 75 |
+
),
|
| 76 |
+
"lora": (LoraConfig(task_type=TaskType.CAUSAL_LM), {}),
|
| 77 |
+
"lora-target-embeddings": pytest.param(
|
| 78 |
+
(LoraConfig(task_type=TaskType.CAUSAL_LM, target_modules=["embed_tokens"]), {}),
|
| 79 |
+
),
|
| 80 |
+
"lora-with-modules-to-save": (LoraConfig(task_type=TaskType.CAUSAL_LM, modules_to_save=["embed_tokens"]), {}),
|
| 81 |
+
"oft": (OFTConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 82 |
+
"vblora": (VBLoRAConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], vector_length=2), {}),
|
| 83 |
+
"vera": (VeraConfig(task_type=TaskType.CAUSAL_LM), {}),
|
| 84 |
+
"hra": (HRAConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 85 |
+
"bone": (BoneConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2), {}),
|
| 86 |
+
"bone-bat": (
|
| 87 |
+
BoneConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2, init_weights="bat"),
|
| 88 |
+
{},
|
| 89 |
+
),
|
| 90 |
+
"miss": (MissConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2), {}),
|
| 91 |
+
"miss-bat": (
|
| 92 |
+
MissConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2, init_weights="bat"),
|
| 93 |
+
{},
|
| 94 |
+
),
|
| 95 |
+
"miss-mini": (
|
| 96 |
+
MissConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2, init_weights="mini"),
|
| 97 |
+
{},
|
| 98 |
+
),
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@pytest.mark.single_gpu_tests
|
| 103 |
+
class TestTorchCompileCausalLM:
|
| 104 |
+
"""
|
| 105 |
+
Tests for using torch.compile with causal LM.
|
| 106 |
+
|
| 107 |
+
Tip: When adding a new test, set `fake_compile = True` below. With this setting, torch.compile is being skipped.
|
| 108 |
+
This is useful for two reasons:
|
| 109 |
+
|
| 110 |
+
- compile is slow, so to quickly iterate on the test, it's best to disable it and only enable it at the very end
|
| 111 |
+
- even if you expect the test to fail with compile, as compile does not work with every PEFT feature, it still MUST
|
| 112 |
+
succeed without compile, otherwise the test is incorrect.
|
| 113 |
+
|
| 114 |
+
Before creating the PR, disable `fake_compile`.
|
| 115 |
+
"""
|
| 116 |
+
|
| 117 |
+
fake_compile = False
|
| 118 |
+
model_id = "peft-internal-testing/tiny-random-OPTForCausalLM"
|
| 119 |
+
max_train_loss = 15.0 # generous threshold for maximum loss after training
|
| 120 |
+
|
| 121 |
+
@pytest.fixture(autouse=True)
|
| 122 |
+
def teardown(self):
|
| 123 |
+
r"""
|
| 124 |
+
Efficient mechanism to free GPU memory after each test. Based on
|
| 125 |
+
https://github.com/huggingface/transformers/issues/21094
|
| 126 |
+
"""
|
| 127 |
+
clear_device_cache(garbage_collection=True)
|
| 128 |
+
gc.collect()
|
| 129 |
+
|
| 130 |
+
@pytest.fixture(scope="class")
|
| 131 |
+
def tokenizer(self):
|
| 132 |
+
return AutoTokenizer.from_pretrained(self.model_id)
|
| 133 |
+
|
| 134 |
+
@pytest.fixture(scope="class")
|
| 135 |
+
def data(self, tokenizer):
|
| 136 |
+
def tokenize(samples):
|
| 137 |
+
# For some reason, the max sequence length is not honored by the tokenizer, resulting in IndexErrors. Thus,
|
| 138 |
+
# manually ensure that sequences are not too long.
|
| 139 |
+
tokenized = tokenizer(samples["quote"])
|
| 140 |
+
tokenized["input_ids"] = [input_ids[: tokenizer.model_max_length] for input_ids in tokenized["input_ids"]]
|
| 141 |
+
tokenized["attention_mask"] = [
|
| 142 |
+
input_ids[: tokenizer.model_max_length] for input_ids in tokenized["attention_mask"]
|
| 143 |
+
]
|
| 144 |
+
return tokenized
|
| 145 |
+
|
| 146 |
+
data = load_dataset_english_quotes()
|
| 147 |
+
data = data.map(tokenize, batched=True)
|
| 148 |
+
# We need to manually remove unused columns. This is because we cannot use remove_unused_columns=True in the
|
| 149 |
+
# Trainer, as this leads to errors with torch.compile. We also cannot just leave them in, as they contain
|
| 150 |
+
# strings. Therefore, manually remove all unused columns.
|
| 151 |
+
data = data.remove_columns(["quote", "author", "tags"])
|
| 152 |
+
return data
|
| 153 |
+
|
| 154 |
+
def compile(self, model, compile_kwargs):
|
| 155 |
+
compile_kwargs = compile_kwargs.copy()
|
| 156 |
+
# those are only for the Trainer arguments
|
| 157 |
+
compile_kwargs.pop("torch_compile_backend", None)
|
| 158 |
+
compile_kwargs.pop("torch_compile_mode", None)
|
| 159 |
+
if self.fake_compile:
|
| 160 |
+
return model
|
| 161 |
+
return torch.compile(model, **compile_kwargs)
|
| 162 |
+
|
| 163 |
+
@pytest.mark.parametrize("settings", SETTINGS.values(), ids=SETTINGS.keys())
|
| 164 |
+
def test_causal_lm_training_trainer_compile(self, settings, tokenizer, data, tmp_path):
|
| 165 |
+
r"""Train a PEFT model with torch.compile using Trainer"""
|
| 166 |
+
tmp_dir = tmp_path / "model"
|
| 167 |
+
config, compile_kwargs = settings
|
| 168 |
+
|
| 169 |
+
torch.manual_seed(0)
|
| 170 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 171 |
+
self.model_id,
|
| 172 |
+
device_map="auto",
|
| 173 |
+
)
|
| 174 |
+
model = get_peft_model(model, config)
|
| 175 |
+
|
| 176 |
+
# record outputs before training
|
| 177 |
+
model.eval()
|
| 178 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 179 |
+
with torch.inference_mode():
|
| 180 |
+
output_before = model(sample)
|
| 181 |
+
model.train()
|
| 182 |
+
|
| 183 |
+
train_kwargs = {
|
| 184 |
+
"per_device_train_batch_size": 4,
|
| 185 |
+
"max_steps": 5,
|
| 186 |
+
"learning_rate": 1e-3,
|
| 187 |
+
"logging_steps": 1,
|
| 188 |
+
"output_dir": tmp_dir,
|
| 189 |
+
"seed": 0,
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
if isinstance(config, AdaLoraConfig):
|
| 193 |
+
train_kwargs["learning_rate"] = 1e-2
|
| 194 |
+
|
| 195 |
+
training_args = TrainingArguments(
|
| 196 |
+
torch_compile=not self.fake_compile,
|
| 197 |
+
torch_compile_backend=compile_kwargs.get("torch_compile_backend", None),
|
| 198 |
+
torch_compile_mode=compile_kwargs.get("torch_compile_mode", None),
|
| 199 |
+
**train_kwargs,
|
| 200 |
+
)
|
| 201 |
+
trainer = Trainer(
|
| 202 |
+
model=model,
|
| 203 |
+
train_dataset=data["train"],
|
| 204 |
+
args=training_args,
|
| 205 |
+
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
|
| 206 |
+
)
|
| 207 |
+
model.config.use_cache = False
|
| 208 |
+
|
| 209 |
+
if isinstance(config, AdaLoraConfig):
|
| 210 |
+
|
| 211 |
+
class OptimizerStepCallback(TrainerCallback):
|
| 212 |
+
def on_optimizer_step(self, args, state, control, **kwargs):
|
| 213 |
+
model.update_and_allocate(state.global_step)
|
| 214 |
+
|
| 215 |
+
trainer.add_callback(OptimizerStepCallback())
|
| 216 |
+
|
| 217 |
+
trainer.train()
|
| 218 |
+
|
| 219 |
+
model.eval()
|
| 220 |
+
atol, rtol = 1e-4, 1e-4
|
| 221 |
+
with torch.inference_mode():
|
| 222 |
+
output_after = model(sample)
|
| 223 |
+
tokens_after = model.generate(sample)
|
| 224 |
+
assert torch.isfinite(output_after.logits).all()
|
| 225 |
+
# sanity check: model was updated
|
| 226 |
+
assert not torch.allclose(output_before.logits, output_after.logits, atol=atol, rtol=rtol)
|
| 227 |
+
assert trainer.state.log_history[-1]["train_loss"] < self.max_train_loss
|
| 228 |
+
|
| 229 |
+
# check saving the model and loading it without compile
|
| 230 |
+
model.save_pretrained(tmp_path)
|
| 231 |
+
del model
|
| 232 |
+
torch.manual_seed(0)
|
| 233 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map="auto")
|
| 234 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 235 |
+
with torch.inference_mode():
|
| 236 |
+
output_loaded = model(sample)
|
| 237 |
+
tokens_loaded = model.generate(sample)
|
| 238 |
+
assert torch.allclose(output_after.logits, output_loaded.logits, atol=atol, rtol=rtol)
|
| 239 |
+
assert (tokens_after == tokens_loaded).all()
|
| 240 |
+
|
| 241 |
+
@pytest.mark.parametrize("settings", SETTINGS.values(), ids=SETTINGS.keys())
|
| 242 |
+
def test_causal_lm_training_pytorch_compile(self, settings, tokenizer, data, tmp_path):
|
| 243 |
+
r"""Train a PEFT model with torch.compile using PyTorch training loop"""
|
| 244 |
+
torch.manual_seed(0)
|
| 245 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 246 |
+
self.model_id,
|
| 247 |
+
device_map="auto",
|
| 248 |
+
)
|
| 249 |
+
config, compile_kwargs = settings
|
| 250 |
+
model = get_peft_model(model, config)
|
| 251 |
+
if isinstance(config, AdaLoraConfig):
|
| 252 |
+
model.base_model.peft_config["default"].total_step = 5
|
| 253 |
+
model = self.compile(model, compile_kwargs)
|
| 254 |
+
|
| 255 |
+
# record outputs before training
|
| 256 |
+
model.eval()
|
| 257 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 258 |
+
with torch.inference_mode():
|
| 259 |
+
output_before = model(sample)
|
| 260 |
+
model.train()
|
| 261 |
+
|
| 262 |
+
model.config.use_cache = False
|
| 263 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 264 |
+
batch_size = 4
|
| 265 |
+
losses = []
|
| 266 |
+
max_steps = 5 * batch_size
|
| 267 |
+
for i in range(0, max_steps, batch_size):
|
| 268 |
+
batch = tokenizer.pad(data["train"][i : i + batch_size], return_tensors="pt").to(model.device)
|
| 269 |
+
# add targets
|
| 270 |
+
batch["labels"] = batch["input_ids"].clone()
|
| 271 |
+
optimizer.zero_grad()
|
| 272 |
+
outputs = model(**batch)
|
| 273 |
+
loss = outputs.loss
|
| 274 |
+
loss.backward()
|
| 275 |
+
optimizer.step()
|
| 276 |
+
losses.append(loss.item())
|
| 277 |
+
if isinstance(config, AdaLoraConfig):
|
| 278 |
+
model.base_model.update_and_allocate(i)
|
| 279 |
+
|
| 280 |
+
model.eval()
|
| 281 |
+
with torch.inference_mode():
|
| 282 |
+
output_after = model(sample)
|
| 283 |
+
tokens_after = model.generate(sample)
|
| 284 |
+
assert torch.isfinite(output_after.logits).all()
|
| 285 |
+
atol, rtol = 1e-4, 1e-4
|
| 286 |
+
# sanity check: model was updated
|
| 287 |
+
assert not torch.allclose(output_before.logits, output_after.logits, atol=atol, rtol=rtol)
|
| 288 |
+
assert losses[-1] < self.max_train_loss
|
| 289 |
+
|
| 290 |
+
# check saving the model and loading it without compile
|
| 291 |
+
model.save_pretrained(tmp_path)
|
| 292 |
+
del model
|
| 293 |
+
torch.manual_seed(0)
|
| 294 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map="auto")
|
| 295 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 296 |
+
with torch.inference_mode():
|
| 297 |
+
output_loaded = model(sample)
|
| 298 |
+
tokens_loaded = model.generate(sample)
|
| 299 |
+
assert torch.allclose(output_after.logits, output_loaded.logits, atol=atol, rtol=rtol)
|
| 300 |
+
assert (tokens_after == tokens_loaded).all()
|
| 301 |
+
|
| 302 |
+
@require_bitsandbytes
|
| 303 |
+
def test_causal_lm_training_lora_bnb_compile(self, tokenizer, data, tmp_path):
|
| 304 |
+
r"""Train a bnb quantized LoRA model with torch.compile using PyTorch training loop"""
|
| 305 |
+
torch.manual_seed(0)
|
| 306 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 307 |
+
self.model_id,
|
| 308 |
+
device_map="auto",
|
| 309 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 310 |
+
)
|
| 311 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM)
|
| 312 |
+
model = get_peft_model(model, config)
|
| 313 |
+
model = self.compile(model, {})
|
| 314 |
+
|
| 315 |
+
# record outputs before training
|
| 316 |
+
model.eval()
|
| 317 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 318 |
+
with torch.inference_mode():
|
| 319 |
+
output_before = model(sample)
|
| 320 |
+
model.train()
|
| 321 |
+
|
| 322 |
+
model.config.use_cache = False
|
| 323 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 324 |
+
batch_size = 4
|
| 325 |
+
losses = []
|
| 326 |
+
max_steps = 5 * batch_size
|
| 327 |
+
for i in range(0, max_steps, batch_size):
|
| 328 |
+
batch = tokenizer.pad(data["train"][i : i + batch_size], return_tensors="pt").to(model.device)
|
| 329 |
+
# add targets
|
| 330 |
+
batch["labels"] = batch["input_ids"].clone()
|
| 331 |
+
optimizer.zero_grad()
|
| 332 |
+
outputs = model(**batch)
|
| 333 |
+
loss = outputs.loss
|
| 334 |
+
loss.backward()
|
| 335 |
+
optimizer.step()
|
| 336 |
+
losses.append(loss.item())
|
| 337 |
+
|
| 338 |
+
model.eval()
|
| 339 |
+
with torch.inference_mode():
|
| 340 |
+
output_after = model(sample)
|
| 341 |
+
assert torch.isfinite(output_after.logits).all()
|
| 342 |
+
atol, rtol = 5e-4, 5e-4
|
| 343 |
+
# sanity check: model was updated
|
| 344 |
+
assert not torch.allclose(output_before.logits, output_after.logits, atol=atol, rtol=rtol)
|
| 345 |
+
assert losses[-1] < self.max_train_loss
|
| 346 |
+
|
| 347 |
+
# check saving the model and loading it without compile
|
| 348 |
+
model.save_pretrained(tmp_path)
|
| 349 |
+
del model
|
| 350 |
+
torch.manual_seed(0)
|
| 351 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 352 |
+
self.model_id, device_map="auto", quantization_config=BitsAndBytesConfig(load_in_4bit=True)
|
| 353 |
+
)
|
| 354 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 355 |
+
|
| 356 |
+
with torch.inference_mode():
|
| 357 |
+
# after loading, outputs are float32 for some reason
|
| 358 |
+
output_loaded = model(sample)
|
| 359 |
+
assert torch.allclose(output_after.logits, output_loaded.logits, atol=atol, rtol=rtol)
|
| 360 |
+
|
| 361 |
+
@require_bitsandbytes
|
| 362 |
+
def test_causal_lm_multiple_lora_adapter_compile(self, tokenizer, data):
|
| 363 |
+
torch.manual_seed(0)
|
| 364 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 365 |
+
self.model_id,
|
| 366 |
+
device_map="auto",
|
| 367 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 368 |
+
).eval()
|
| 369 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 370 |
+
with torch.inference_mode():
|
| 371 |
+
output_base = model(sample)
|
| 372 |
+
|
| 373 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 374 |
+
model = get_peft_model(model, config)
|
| 375 |
+
model.add_adapter("other", config)
|
| 376 |
+
model = self.compile(model, {})
|
| 377 |
+
model.eval()
|
| 378 |
+
|
| 379 |
+
with torch.inference_mode():
|
| 380 |
+
output_default_adapter = model(sample)
|
| 381 |
+
model.set_adapter("other")
|
| 382 |
+
with torch.inference_mode():
|
| 383 |
+
output_other_adapter = model(sample)
|
| 384 |
+
|
| 385 |
+
atol, rtol = 1e-4, 1e-4
|
| 386 |
+
# outputs of the base model != output of default adapter != output of other adapter
|
| 387 |
+
assert not torch.allclose(output_base.logits, output_default_adapter.logits, atol=atol, rtol=rtol)
|
| 388 |
+
assert not torch.allclose(output_base.logits, output_other_adapter.logits, atol=atol, rtol=rtol)
|
| 389 |
+
assert not torch.allclose(output_default_adapter.logits, output_other_adapter.logits, atol=atol, rtol=rtol)
|
| 390 |
+
|
| 391 |
+
# now delete the other adapter
|
| 392 |
+
model.delete_adapter("other")
|
| 393 |
+
model.set_adapter("default")
|
| 394 |
+
with torch.inference_mode():
|
| 395 |
+
output_after_delete = model(sample)
|
| 396 |
+
|
| 397 |
+
# outputs after delete == output of default adapter
|
| 398 |
+
assert torch.allclose(output_default_adapter.logits, output_after_delete.logits, atol=atol, rtol=rtol)
|
| 399 |
+
|
| 400 |
+
def test_causal_lm_disable_lora_adapter_compile(self, tokenizer, data):
|
| 401 |
+
torch.manual_seed(0)
|
| 402 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 403 |
+
self.model_id,
|
| 404 |
+
device_map="auto",
|
| 405 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 406 |
+
).eval()
|
| 407 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 408 |
+
with torch.inference_mode():
|
| 409 |
+
output_base = model(sample)
|
| 410 |
+
|
| 411 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 412 |
+
model = get_peft_model(model, config).eval()
|
| 413 |
+
model = self.compile(model, {})
|
| 414 |
+
output_lora = model(sample)
|
| 415 |
+
|
| 416 |
+
with model.disable_adapter():
|
| 417 |
+
with torch.inference_mode():
|
| 418 |
+
output_disabled = model(sample)
|
| 419 |
+
|
| 420 |
+
atol, rtol = 5e-4, 5e-4
|
| 421 |
+
# outputs of the base model == output disabled adapter != output of lora adapter
|
| 422 |
+
assert torch.allclose(output_base.logits, output_disabled.logits, atol=atol, rtol=rtol)
|
| 423 |
+
assert not torch.allclose(output_base.logits, output_lora.logits, atol=atol, rtol=rtol)
|
| 424 |
+
|
| 425 |
+
@require_bitsandbytes
|
| 426 |
+
def test_causal_lm_merging_lora_adapter_compile(self, tokenizer, data):
|
| 427 |
+
# merge the adapter
|
| 428 |
+
torch.manual_seed(0)
|
| 429 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 430 |
+
self.model_id,
|
| 431 |
+
device_map="auto",
|
| 432 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 433 |
+
).eval()
|
| 434 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 435 |
+
with torch.inference_mode():
|
| 436 |
+
output_base = model(sample)
|
| 437 |
+
|
| 438 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 439 |
+
model = get_peft_model(model, config).eval()
|
| 440 |
+
with torch.inference_mode():
|
| 441 |
+
output_lora = model(sample)
|
| 442 |
+
|
| 443 |
+
model.merge_adapter()
|
| 444 |
+
with torch.inference_mode():
|
| 445 |
+
output_merged = model(sample)
|
| 446 |
+
|
| 447 |
+
# merging is less precise, be more tolerant
|
| 448 |
+
atol, rtol = 1e-1, 1e-1
|
| 449 |
+
# outputs of the base model != output of lora adapter == output of merged adapter
|
| 450 |
+
assert not torch.allclose(output_base.logits, output_lora.logits, atol=atol, rtol=rtol)
|
| 451 |
+
assert torch.allclose(output_lora.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 452 |
+
|
| 453 |
+
@require_bitsandbytes
|
| 454 |
+
def test_causal_lm_merging_multiple_lora_adapters_compile(self, tokenizer, data):
|
| 455 |
+
# merge multiple adapters at once
|
| 456 |
+
torch.manual_seed(0)
|
| 457 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 458 |
+
self.model_id,
|
| 459 |
+
device_map="auto",
|
| 460 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 461 |
+
).eval()
|
| 462 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 463 |
+
with torch.inference_mode():
|
| 464 |
+
output_base = model(sample)
|
| 465 |
+
|
| 466 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 467 |
+
model = get_peft_model(model, config).eval()
|
| 468 |
+
model.add_adapter("other", config)
|
| 469 |
+
with torch.inference_mode():
|
| 470 |
+
output_default = model(sample)
|
| 471 |
+
|
| 472 |
+
model.set_adapter("other")
|
| 473 |
+
with torch.inference_mode():
|
| 474 |
+
output_other = model(sample)
|
| 475 |
+
|
| 476 |
+
model.base_model.merge_adapter(["default", "other"])
|
| 477 |
+
with torch.inference_mode():
|
| 478 |
+
output_merged = model(sample)
|
| 479 |
+
|
| 480 |
+
# merging is less precise, be more tolerant
|
| 481 |
+
atol, rtol = 1e-1, 1e-1
|
| 482 |
+
# outputs of the base model != output of default adapter != output of other adapter
|
| 483 |
+
assert not torch.allclose(output_base.logits, output_default.logits, atol=atol, rtol=rtol)
|
| 484 |
+
assert not torch.allclose(output_base.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 485 |
+
assert not torch.allclose(output_default.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 486 |
+
# outputs of merged adapter != all others
|
| 487 |
+
assert not torch.allclose(output_base.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 488 |
+
assert not torch.allclose(output_default.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 489 |
+
assert not torch.allclose(output_other.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 490 |
+
|
| 491 |
+
@require_bitsandbytes
|
| 492 |
+
def test_causal_lm_merge_and_unload_lora_adapter_compile(self, tokenizer, data):
|
| 493 |
+
torch.manual_seed(0)
|
| 494 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 495 |
+
self.model_id,
|
| 496 |
+
device_map="auto",
|
| 497 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 498 |
+
).eval()
|
| 499 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 500 |
+
with torch.inference_mode():
|
| 501 |
+
output_base = model(sample)
|
| 502 |
+
|
| 503 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 504 |
+
model = get_peft_model(model, config).eval()
|
| 505 |
+
model = self.compile(model, {})
|
| 506 |
+
with torch.inference_mode():
|
| 507 |
+
output_lora = model(sample)
|
| 508 |
+
|
| 509 |
+
unloaded = model.merge_and_unload()
|
| 510 |
+
with torch.inference_mode():
|
| 511 |
+
output_unloaded = unloaded(sample)
|
| 512 |
+
|
| 513 |
+
# merging is less precise, be more tolerant
|
| 514 |
+
atol, rtol = 1e-1, 1e-1
|
| 515 |
+
# outputs of the base model != output of lora adapter == output of unloaded adapter
|
| 516 |
+
assert not torch.allclose(output_base.logits, output_lora.logits, atol=atol, rtol=rtol)
|
| 517 |
+
assert torch.allclose(output_lora.logits, output_unloaded.logits, atol=atol, rtol=rtol)
|
| 518 |
+
|
| 519 |
+
@require_bitsandbytes
|
| 520 |
+
def test_causal_lm_mixed_batch_lora_adapter_compile(self, tokenizer, data):
|
| 521 |
+
torch.manual_seed(0)
|
| 522 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 523 |
+
self.model_id,
|
| 524 |
+
device_map="auto",
|
| 525 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 526 |
+
).eval()
|
| 527 |
+
|
| 528 |
+
# we need at least 3 samples for this to work!
|
| 529 |
+
sample = {
|
| 530 |
+
"input_ids": torch.arange(12).reshape(3, 4).to("cuda"),
|
| 531 |
+
"attention_mask": torch.ones(3, 4).long().to("cuda"),
|
| 532 |
+
}
|
| 533 |
+
|
| 534 |
+
with torch.inference_mode():
|
| 535 |
+
output_base = model(**sample)
|
| 536 |
+
|
| 537 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 538 |
+
model = get_peft_model(model, config).eval()
|
| 539 |
+
with torch.inference_mode():
|
| 540 |
+
output_default = model(**sample)
|
| 541 |
+
|
| 542 |
+
model.add_adapter("other", config)
|
| 543 |
+
model.set_adapter("other")
|
| 544 |
+
with torch.inference_mode():
|
| 545 |
+
output_other = model(**sample)
|
| 546 |
+
|
| 547 |
+
model = self.compile(model, {})
|
| 548 |
+
|
| 549 |
+
# set adapter_indices so that it alternates between 0 (base), lora 1, and lora 2
|
| 550 |
+
adapter_names = ["__base__", "default", "other"]
|
| 551 |
+
with torch.inference_mode():
|
| 552 |
+
output_mixed = model(**sample, adapter_names=adapter_names)
|
| 553 |
+
|
| 554 |
+
atol, rtol = 5e-4, 5e-4
|
| 555 |
+
# outputs of the base model != output of lora adapter 1 != output of other adapter
|
| 556 |
+
assert not torch.allclose(output_base.logits, output_default.logits, atol=atol, rtol=rtol)
|
| 557 |
+
assert not torch.allclose(output_default.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 558 |
+
assert not torch.allclose(output_other.logits, output_mixed.logits, atol=atol, rtol=rtol)
|
| 559 |
+
# outputs of mixed adapter is mix of all 3
|
| 560 |
+
assert torch.allclose(output_base.logits[0], output_mixed.logits[0], atol=atol, rtol=rtol)
|
| 561 |
+
assert torch.allclose(output_default.logits[1], output_mixed.logits[1], atol=atol, rtol=rtol)
|
| 562 |
+
assert torch.allclose(output_other.logits[2], output_mixed.logits[2], atol=atol, rtol=rtol)
|
| 563 |
+
|
| 564 |
+
@require_bitsandbytes
|
| 565 |
+
def test_causal_lm_add_weighted_adapter_lora_adapter_compile(self, tokenizer, data):
|
| 566 |
+
torch.manual_seed(0)
|
| 567 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 568 |
+
self.model_id,
|
| 569 |
+
device_map="auto",
|
| 570 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 571 |
+
).eval()
|
| 572 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 573 |
+
with torch.inference_mode():
|
| 574 |
+
output_base = model(sample)
|
| 575 |
+
|
| 576 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 577 |
+
model = get_peft_model(model, config).eval()
|
| 578 |
+
model.add_adapter("other", config)
|
| 579 |
+
with torch.inference_mode():
|
| 580 |
+
output_default = model(sample)
|
| 581 |
+
|
| 582 |
+
model.set_adapter("other")
|
| 583 |
+
with torch.inference_mode():
|
| 584 |
+
output_other = model(sample)
|
| 585 |
+
|
| 586 |
+
model.add_weighted_adapter(["default", "other"], [0.5, 0.5], adapter_name="combined")
|
| 587 |
+
model.set_adapter("combined")
|
| 588 |
+
with torch.inference_mode():
|
| 589 |
+
output_combined = model(sample)
|
| 590 |
+
|
| 591 |
+
atol, rtol = 1e-4, 1e-4
|
| 592 |
+
# outputs of the base model != output of default adapter != output of other adapter
|
| 593 |
+
assert not torch.allclose(output_base.logits, output_default.logits, atol=atol, rtol=rtol)
|
| 594 |
+
assert not torch.allclose(output_base.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 595 |
+
assert not torch.allclose(output_default.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 596 |
+
# outputs of combined adapter != all others
|
| 597 |
+
assert not torch.allclose(output_base.logits, output_combined.logits, atol=atol, rtol=rtol)
|
| 598 |
+
assert not torch.allclose(output_default.logits, output_combined.logits, atol=atol, r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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import copy
|
| 18 |
+
from unittest.mock import patch
|
| 19 |
+
|
| 20 |
+
import pytest
|
| 21 |
+
import torch
|
| 22 |
+
from safetensors.torch import load_file as safe_load_file
|
| 23 |
+
from transformers import AutoModelForCausalLM, AutoModelForSeq2SeqLM, AutoTokenizer, BartConfig, BartModel
|
| 24 |
+
|
| 25 |
+
from peft import AutoPeftModel, LoraConfig, PeftModel, TrainableTokensConfig, get_peft_model
|
| 26 |
+
from peft.tuners.trainable_tokens.layer import TrainableTokensLayer
|
| 27 |
+
from peft.utils import TrainableTokensWrapper, get_peft_model_state_dict, is_transformers_ge_v5
|
| 28 |
+
|
| 29 |
+
from .testing_utils import hub_online_once
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class ModelEmb(torch.nn.Module):
|
| 33 |
+
def __init__(self):
|
| 34 |
+
super().__init__()
|
| 35 |
+
self.emb = torch.nn.Embedding(100, 10)
|
| 36 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 37 |
+
|
| 38 |
+
def forward(self, x):
|
| 39 |
+
return self.lin0(self.emb(x))
|
| 40 |
+
|
| 41 |
+
def get_input_embeddings(self):
|
| 42 |
+
return self.emb
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ModelEmbedIn(torch.nn.Module):
|
| 46 |
+
def __init__(self):
|
| 47 |
+
super().__init__()
|
| 48 |
+
self.embed_in = torch.nn.Embedding(100, 10)
|
| 49 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 50 |
+
|
| 51 |
+
def forward(self, x):
|
| 52 |
+
return self.lin0(self.embed_in(x))
|
| 53 |
+
|
| 54 |
+
def get_input_embeddings(self):
|
| 55 |
+
return self.embed_in
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class ModelEmbedMultiple(torch.nn.Module):
|
| 59 |
+
def __init__(self):
|
| 60 |
+
super().__init__()
|
| 61 |
+
self.embed_in = torch.nn.Embedding(100, 10)
|
| 62 |
+
self.embed_in_2 = torch.nn.Embedding(100, 10)
|
| 63 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 64 |
+
|
| 65 |
+
def forward(self, x):
|
| 66 |
+
return self.lin0(self.embed_in(x) + self.embed_in_2(x))
|
| 67 |
+
|
| 68 |
+
def get_input_embeddings(self):
|
| 69 |
+
return self.embed_in
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
class ModelEmbedInNoGet(torch.nn.Module):
|
| 73 |
+
def __init__(self):
|
| 74 |
+
super().__init__()
|
| 75 |
+
self.embed_in = torch.nn.Embedding(100, 10)
|
| 76 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 77 |
+
|
| 78 |
+
def forward(self, x):
|
| 79 |
+
return self.lin0(self.embed_in(x))
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class TestTrainableTokens:
|
| 83 |
+
@pytest.fixture
|
| 84 |
+
def model_id(self):
|
| 85 |
+
return "trl-internal-testing/tiny-random-LlamaForCausalLM"
|
| 86 |
+
|
| 87 |
+
@pytest.fixture
|
| 88 |
+
def model_multi_embedding(self):
|
| 89 |
+
class MultiEmbeddingMLP(torch.nn.Module):
|
| 90 |
+
def __init__(self):
|
| 91 |
+
super().__init__()
|
| 92 |
+
self.emb_text = torch.nn.Embedding(10, 5)
|
| 93 |
+
self.emb_image = torch.nn.Embedding(8, 5)
|
| 94 |
+
self.lin0 = torch.nn.Linear(5, 10)
|
| 95 |
+
self.lin1 = torch.nn.Linear(10, 20)
|
| 96 |
+
|
| 97 |
+
def forward(self, x_text, x_image):
|
| 98 |
+
x_text = self.emb_text(x_text)
|
| 99 |
+
x_image = self.emb_image(x_image)
|
| 100 |
+
y = self.lin0(torch.concat([x_text, x_image], dim=1).view(-1, 5))
|
| 101 |
+
y = self.lin1(y)
|
| 102 |
+
return y, (x_text, x_image)
|
| 103 |
+
|
| 104 |
+
return MultiEmbeddingMLP()
|
| 105 |
+
|
| 106 |
+
@pytest.fixture
|
| 107 |
+
def model(self, model_id):
|
| 108 |
+
with hub_online_once(model_id):
|
| 109 |
+
# This must not be a yield fixture so that we don't carry the hub_online_once
|
| 110 |
+
# behavior over to the rest of the test that uses this fixture
|
| 111 |
+
return AutoModelForCausalLM.from_pretrained(model_id)
|
| 112 |
+
|
| 113 |
+
@pytest.fixture
|
| 114 |
+
def tokenizer(self, model_id):
|
| 115 |
+
return AutoTokenizer.from_pretrained(model_id)
|
| 116 |
+
|
| 117 |
+
def simulate_training(self, trainable_tokens_layer, adapter_name="default"):
|
| 118 |
+
"""Simulates training of trainable_tokens adapter layer by assigning random
|
| 119 |
+
values to the delta tokens.
|
| 120 |
+
"""
|
| 121 |
+
trainable_tokens_layer.trainable_tokens_delta[adapter_name].data = torch.rand_like(
|
| 122 |
+
trainable_tokens_layer.trainable_tokens_delta[adapter_name].data
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
def test_stand_alone_usage(self, model, tokenizer, tmp_path):
|
| 126 |
+
original_model = copy.deepcopy(model)
|
| 127 |
+
|
| 128 |
+
peft_config = TrainableTokensConfig(target_modules=["embed_tokens"], token_indices=[0, 1, 3])
|
| 129 |
+
peft_model = get_peft_model(model, peft_config)
|
| 130 |
+
save_path = tmp_path / "stand_alone_usage"
|
| 131 |
+
|
| 132 |
+
# simulate normal use but take care to use the tokens that we expect to be modified
|
| 133 |
+
# (+1 that we don't expect to be modified)
|
| 134 |
+
X = {
|
| 135 |
+
"input_ids": torch.tensor([[0, 1, 2, 3]]),
|
| 136 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1]]),
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
idcs_to_modify = peft_config.token_indices
|
| 140 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 141 |
+
|
| 142 |
+
self.simulate_training(peft_model.model.model.embed_tokens)
|
| 143 |
+
output_train = peft_model(output_hidden_states=True, **X)
|
| 144 |
+
|
| 145 |
+
peft_model.save_pretrained(save_path)
|
| 146 |
+
peft_model_org = peft_model
|
| 147 |
+
|
| 148 |
+
# check whether the token indices differ from the base model after loading the model
|
| 149 |
+
# from the checkpoint.
|
| 150 |
+
peft_model = AutoPeftModel.from_pretrained(save_path)
|
| 151 |
+
output_load = peft_model(output_hidden_states=True, **X)
|
| 152 |
+
output_orig = original_model(output_hidden_states=True, **X)
|
| 153 |
+
|
| 154 |
+
# on the way, make sure that the embedding matrix itself was not modified
|
| 155 |
+
assert torch.allclose(
|
| 156 |
+
peft_model.model.model.embed_tokens.weight,
|
| 157 |
+
peft_model_org.model.model.embed_tokens.weight,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
W_load = output_load.hidden_states[0]
|
| 161 |
+
W_orig = output_orig.hidden_states[0]
|
| 162 |
+
W_train = output_train.hidden_states[0]
|
| 163 |
+
|
| 164 |
+
# all PEFT model embed outputs must equal the outputs during 'training' to make sure
|
| 165 |
+
# that saving/loading works properly.
|
| 166 |
+
assert torch.allclose(W_load, W_train)
|
| 167 |
+
|
| 168 |
+
assert not torch.allclose(W_load[:, idcs_to_modify], W_orig[:, idcs_to_modify])
|
| 169 |
+
assert torch.allclose(W_load[:, idcs_to_keep], W_orig[:, idcs_to_keep])
|
| 170 |
+
|
| 171 |
+
@pytest.mark.parametrize(
|
| 172 |
+
"peft_config",
|
| 173 |
+
[
|
| 174 |
+
LoraConfig(
|
| 175 |
+
target_modules="all-linear",
|
| 176 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 177 |
+
),
|
| 178 |
+
],
|
| 179 |
+
)
|
| 180 |
+
def test_combined_with_peft_method_usage(self, model, tokenizer, peft_config, tmp_path):
|
| 181 |
+
original_model = copy.deepcopy(model)
|
| 182 |
+
peft_model = get_peft_model(model, peft_config)
|
| 183 |
+
save_path = tmp_path / "combined_usage"
|
| 184 |
+
|
| 185 |
+
# simulate normal use but take care to use the tokens that we expect to be modified
|
| 186 |
+
# (+2 that we don't expect to be modified)
|
| 187 |
+
X = {
|
| 188 |
+
"input_ids": torch.tensor([[0, 1, 2, 3, 4]]),
|
| 189 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1, 1]]),
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
idcs_to_modify = peft_config.trainable_token_indices["embed_tokens"]
|
| 193 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 194 |
+
|
| 195 |
+
self.simulate_training(peft_model.model.model.embed_tokens.token_adapter)
|
| 196 |
+
output_train = peft_model(output_hidden_states=True, **X)
|
| 197 |
+
|
| 198 |
+
peft_model.save_pretrained(save_path)
|
| 199 |
+
peft_model_org = peft_model
|
| 200 |
+
|
| 201 |
+
# check whether the token indices differ from the base model
|
| 202 |
+
peft_model = AutoPeftModel.from_pretrained(save_path)
|
| 203 |
+
output_load = peft_model(output_hidden_states=True, **X)
|
| 204 |
+
output_orig = original_model(output_hidden_states=True, **X)
|
| 205 |
+
|
| 206 |
+
W_load = output_load.hidden_states[0]
|
| 207 |
+
W_orig = output_orig.hidden_states[0]
|
| 208 |
+
W_train = output_train.hidden_states[0]
|
| 209 |
+
|
| 210 |
+
# all PEFT model embed outputs must equal the outputs during 'training' to make sure
|
| 211 |
+
# that saving/loading works properly.
|
| 212 |
+
assert torch.allclose(W_load, W_train)
|
| 213 |
+
|
| 214 |
+
assert not torch.allclose(W_load[:, idcs_to_modify], W_orig[:, idcs_to_modify])
|
| 215 |
+
assert torch.allclose(W_load[:, idcs_to_keep], W_orig[:, idcs_to_keep])
|
| 216 |
+
|
| 217 |
+
def test_basic_training(self, model, tokenizer):
|
| 218 |
+
# ensure that the model can be trained and backpropagation works
|
| 219 |
+
config = TrainableTokensConfig(
|
| 220 |
+
target_modules=["embed_tokens"],
|
| 221 |
+
token_indices=[0, 10],
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
model = get_peft_model(model, config)
|
| 225 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1)
|
| 226 |
+
|
| 227 |
+
initial_delta = model.model.model.embed_tokens.trainable_tokens_delta.default.clone()
|
| 228 |
+
initial_originals = model.model.model.embed_tokens.trainable_tokens_original.default.clone()
|
| 229 |
+
|
| 230 |
+
X = {
|
| 231 |
+
"input_ids": torch.tensor([[0, 1, 2, 3, 4]]),
|
| 232 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1, 1]]),
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
for step in range(3):
|
| 236 |
+
optimizer.zero_grad()
|
| 237 |
+
y_pred = model(**X)
|
| 238 |
+
loss = y_pred.logits.mean()
|
| 239 |
+
loss.backward()
|
| 240 |
+
optimizer.step()
|
| 241 |
+
|
| 242 |
+
assert torch.allclose(
|
| 243 |
+
model.model.model.embed_tokens.trainable_tokens_original.default,
|
| 244 |
+
initial_originals,
|
| 245 |
+
)
|
| 246 |
+
assert not torch.allclose(
|
| 247 |
+
model.model.model.embed_tokens.trainable_tokens_delta.default,
|
| 248 |
+
initial_delta,
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
@pytest.mark.parametrize(
|
| 252 |
+
"peft_config",
|
| 253 |
+
[
|
| 254 |
+
LoraConfig(
|
| 255 |
+
target_modules="all-linear",
|
| 256 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 257 |
+
),
|
| 258 |
+
],
|
| 259 |
+
)
|
| 260 |
+
def test_disable_adapters_with_merging(self, model, tokenizer, peft_config):
|
| 261 |
+
X = {
|
| 262 |
+
"input_ids": torch.tensor([[0, 1, 2, 3, 4]]),
|
| 263 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1, 1]]),
|
| 264 |
+
}
|
| 265 |
+
|
| 266 |
+
model = get_peft_model(model, peft_config)
|
| 267 |
+
model.eval()
|
| 268 |
+
|
| 269 |
+
outputs_before = model(**X).logits
|
| 270 |
+
|
| 271 |
+
model.train()
|
| 272 |
+
lr = 0.01
|
| 273 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
|
| 274 |
+
|
| 275 |
+
# train at least 3 steps for all parameters to be updated (probably this is required because of symmetry
|
| 276 |
+
# breaking of some LoRA layers that are initialized with constants)
|
| 277 |
+
for _ in range(3):
|
| 278 |
+
optimizer.zero_grad()
|
| 279 |
+
y_pred = model(**X)
|
| 280 |
+
loss = y_pred.logits.mean()
|
| 281 |
+
loss.backward()
|
| 282 |
+
optimizer.step()
|
| 283 |
+
|
| 284 |
+
model.eval()
|
| 285 |
+
outputs_unmerged = model(**X).logits
|
| 286 |
+
model.merge_adapter()
|
| 287 |
+
outputs_after = model(**X).logits
|
| 288 |
+
|
| 289 |
+
with model.disable_adapter():
|
| 290 |
+
outputs_disabled = model(**X).logits
|
| 291 |
+
|
| 292 |
+
# check that after leaving the disable_adapter context, everything is enabled again
|
| 293 |
+
outputs_enabled_after_disable = model(**X).logits
|
| 294 |
+
|
| 295 |
+
atol, rtol = 1e-5, 1e-5 # tolerances higher than defaults since merging introduces some numerical instability
|
| 296 |
+
|
| 297 |
+
# check that there is a difference in results after training
|
| 298 |
+
assert not torch.allclose(outputs_before, outputs_after, atol=atol, rtol=rtol)
|
| 299 |
+
|
| 300 |
+
# unmerged or merged should make no difference
|
| 301 |
+
assert torch.allclose(outputs_after, outputs_unmerged, atol=atol, rtol=rtol)
|
| 302 |
+
|
| 303 |
+
# check that disabling adapters gives the same results as before training
|
| 304 |
+
assert torch.allclose(outputs_before, outputs_disabled, atol=atol, rtol=rtol)
|
| 305 |
+
|
| 306 |
+
# check that enabling + disabling adapters does not change the results
|
| 307 |
+
assert torch.allclose(outputs_after, outputs_enabled_after_disable, atol=atol, rtol=rtol)
|
| 308 |
+
|
| 309 |
+
@pytest.mark.parametrize(
|
| 310 |
+
"peft_config",
|
| 311 |
+
[
|
| 312 |
+
LoraConfig(
|
| 313 |
+
target_modules="all-linear",
|
| 314 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 315 |
+
),
|
| 316 |
+
],
|
| 317 |
+
)
|
| 318 |
+
def test_safe_merge_with_adapter(self, model, tokenizer, peft_config):
|
| 319 |
+
X = {
|
| 320 |
+
"input_ids": torch.tensor([[0, 1, 2, 3]]),
|
| 321 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1]]),
|
| 322 |
+
}
|
| 323 |
+
|
| 324 |
+
model = model.eval()
|
| 325 |
+
logits_base = model(**X).logits
|
| 326 |
+
|
| 327 |
+
model = get_peft_model(model, peft_config).eval()
|
| 328 |
+
logits_peft = model(**X).logits
|
| 329 |
+
|
| 330 |
+
atol, rtol = 1e-6, 1e-6 # default
|
| 331 |
+
|
| 332 |
+
model_unloaded = model.merge_and_unload(safe_merge=True)
|
| 333 |
+
logits_unloaded = model_unloaded(**X).logits
|
| 334 |
+
|
| 335 |
+
# check that the logits are the same after unloading
|
| 336 |
+
assert torch.allclose(logits_peft, logits_unloaded, atol=atol, rtol=rtol)
|
| 337 |
+
|
| 338 |
+
@pytest.mark.parametrize(
|
| 339 |
+
"peft_config",
|
| 340 |
+
[
|
| 341 |
+
LoraConfig(
|
| 342 |
+
target_modules="all-linear",
|
| 343 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 344 |
+
),
|
| 345 |
+
],
|
| 346 |
+
)
|
| 347 |
+
def test_load_multiple_adapters(self, model, peft_config, tmp_path):
|
| 348 |
+
# tests if having more than one adpater (even with just the same config) works
|
| 349 |
+
original_model = copy.deepcopy(model)
|
| 350 |
+
model = get_peft_model(model, peft_config)
|
| 351 |
+
|
| 352 |
+
model.save_pretrained(tmp_path)
|
| 353 |
+
del model
|
| 354 |
+
|
| 355 |
+
model = original_model
|
| 356 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 357 |
+
load_result1 = model.load_adapter(tmp_path, adapter_name="other")
|
| 358 |
+
load_result2 = model.load_adapter(tmp_path, adapter_name="yet-another")
|
| 359 |
+
|
| 360 |
+
assert load_result1.missing_keys == []
|
| 361 |
+
assert load_result2.missing_keys == []
|
| 362 |
+
|
| 363 |
+
@pytest.mark.parametrize(
|
| 364 |
+
"peft_config_factory",
|
| 365 |
+
[
|
| 366 |
+
lambda token_indices: LoraConfig(
|
| 367 |
+
target_modules="all-linear",
|
| 368 |
+
trainable_token_indices={"embed_tokens": token_indices},
|
| 369 |
+
),
|
| 370 |
+
],
|
| 371 |
+
)
|
| 372 |
+
def test_multiple_adapters_different_token_indices(self, model, peft_config_factory, tmp_path):
|
| 373 |
+
# tests if multiple adapters with different token indices work
|
| 374 |
+
original_model = copy.deepcopy(model)
|
| 375 |
+
|
| 376 |
+
token_indices_1 = [0, 1, 2]
|
| 377 |
+
token_indices_2 = [2, 3, 4]
|
| 378 |
+
|
| 379 |
+
peft_config_1 = peft_config_factory(token_indices_1)
|
| 380 |
+
peft_config_2 = peft_config_factory(token_indices_2)
|
| 381 |
+
|
| 382 |
+
model = get_peft_model(model, peft_config_1, adapter_name="adapter_1")
|
| 383 |
+
model.add_adapter("adapter_2", peft_config_2)
|
| 384 |
+
|
| 385 |
+
# "train" adapter 1
|
| 386 |
+
model.set_adapter("adapter_1")
|
| 387 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_1")
|
| 388 |
+
|
| 389 |
+
# "train" adapter 2
|
| 390 |
+
model.set_adapter("adapter_2")
|
| 391 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_2")
|
| 392 |
+
|
| 393 |
+
# now we infer on adapter 1 and on adapter 2 and check if the requested indices are changed for
|
| 394 |
+
# each adapter. e.g., for adapter 1, only token indices 1 should be changed.
|
| 395 |
+
X = {
|
| 396 |
+
"input_ids": torch.tensor([list(set(token_indices_1 + token_indices_2))]),
|
| 397 |
+
"attention_mask": torch.tensor([[1] * (len(set(token_indices_1 + token_indices_2)))]),
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
original_output = original_model(output_hidden_states=True, **X).hidden_states[0]
|
| 401 |
+
|
| 402 |
+
# infer with adapter 1, embeddings for token indices 1 should be changed, no others.
|
| 403 |
+
model.set_adapter("adapter_1")
|
| 404 |
+
adapter_1_output = model(output_hidden_states=True, **X).hidden_states[0]
|
| 405 |
+
|
| 406 |
+
idcs_to_modify = token_indices_1
|
| 407 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 408 |
+
|
| 409 |
+
assert not torch.allclose(adapter_1_output[:, idcs_to_modify], original_output[:, idcs_to_modify])
|
| 410 |
+
assert torch.allclose(adapter_1_output[:, idcs_to_keep], original_output[:, idcs_to_keep])
|
| 411 |
+
|
| 412 |
+
# infer with adapter 2, embeddings for token indices 2 should be changed, no others.
|
| 413 |
+
model.set_adapter("adapter_2")
|
| 414 |
+
adapter_2_output = model(output_hidden_states=True, **X).hidden_states[0]
|
| 415 |
+
|
| 416 |
+
idcs_to_modify = token_indices_2
|
| 417 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 418 |
+
|
| 419 |
+
assert not torch.allclose(adapter_2_output[:, idcs_to_modify], original_output[:, idcs_to_modify])
|
| 420 |
+
assert torch.allclose(adapter_2_output[:, idcs_to_keep], original_output[:, idcs_to_keep])
|
| 421 |
+
|
| 422 |
+
@pytest.mark.parametrize(
|
| 423 |
+
"peft_config_factory",
|
| 424 |
+
[
|
| 425 |
+
lambda token_indices: LoraConfig(
|
| 426 |
+
target_modules="all-linear",
|
| 427 |
+
trainable_token_indices={"embed_tokens": token_indices},
|
| 428 |
+
),
|
| 429 |
+
],
|
| 430 |
+
)
|
| 431 |
+
def test_multiple_adapters_overlapping_token_indices_merging(self, model, peft_config_factory, tmp_path):
|
| 432 |
+
# tests that merging multiple adapters that have overlapping indices is not defined at the moment
|
| 433 |
+
# and would yield undefined behavior. note that merging a single adapter is fine.
|
| 434 |
+
original_model = copy.deepcopy(model)
|
| 435 |
+
|
| 436 |
+
token_indices_1 = [0, 1, 2]
|
| 437 |
+
token_indices_2 = [2, 3, 4]
|
| 438 |
+
|
| 439 |
+
peft_config_1 = peft_config_factory(token_indices_1)
|
| 440 |
+
peft_config_2 = peft_config_factory(token_indices_2)
|
| 441 |
+
|
| 442 |
+
model = get_peft_model(model, peft_config_1, adapter_name="adapter_1")
|
| 443 |
+
model.add_adapter("adapter_2", peft_config_2)
|
| 444 |
+
|
| 445 |
+
with pytest.raises(ValueError) as e:
|
| 446 |
+
model.merge_and_unload(adapter_names=["adapter_1", "adapter_2"])
|
| 447 |
+
assert "are already defined and would result in undefined merging behavior" in str(e)
|
| 448 |
+
|
| 449 |
+
@pytest.mark.parametrize(
|
| 450 |
+
"peft_config_factory",
|
| 451 |
+
[
|
| 452 |
+
lambda targets, token_indices: LoraConfig(
|
| 453 |
+
target_modules=targets,
|
| 454 |
+
trainable_token_indices={"embed_tokens": token_indices},
|
| 455 |
+
),
|
| 456 |
+
],
|
| 457 |
+
)
|
| 458 |
+
def test_multiple_adapters_mixed_forward(self, model, peft_config_factory, tmp_path):
|
| 459 |
+
# tests if multiple adapters with different token indices work
|
| 460 |
+
original_model = copy.deepcopy(model)
|
| 461 |
+
|
| 462 |
+
token_indices_1 = [0, 1, 2]
|
| 463 |
+
token_indices_2 = [2, 3, 4]
|
| 464 |
+
|
| 465 |
+
peft_config_1 = peft_config_factory(".*q_proj", token_indices_1)
|
| 466 |
+
peft_config_2 = peft_config_factory(".*o_proj", token_indices_2)
|
| 467 |
+
|
| 468 |
+
model = get_peft_model(model, peft_config_1, adapter_name="adapter_1")
|
| 469 |
+
model.add_adapter("adapter_2", peft_config_2)
|
| 470 |
+
|
| 471 |
+
# "train" adapter 1
|
| 472 |
+
model.set_adapter("adapter_1")
|
| 473 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_1")
|
| 474 |
+
|
| 475 |
+
# "train" adapter 2
|
| 476 |
+
model.set_adapter("adapter_2")
|
| 477 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_2")
|
| 478 |
+
|
| 479 |
+
# forward(adapter_names=...) is not available in train mode
|
| 480 |
+
model.eval()
|
| 481 |
+
|
| 482 |
+
# Build a batch of 2 items, each the same input sequence but each sequence will be passed to a different
|
| 483 |
+
# adapter via mixed batch forward.
|
| 484 |
+
input_sequence = list(set(token_indices_1 + token_indices_2))
|
| 485 |
+
X = {
|
| 486 |
+
"input_ids": torch.tensor([input_sequence, input_sequence]),
|
| 487 |
+
"attention_mask": torch.tensor([[1] * len(input_sequence), [1] * len(input_sequence)]),
|
| 488 |
+
}
|
| 489 |
+
batch_adapter_names = ["adapter_1", "adapter_2"]
|
| 490 |
+
|
| 491 |
+
original_output = original_model(output_hidden_states=True, **X)
|
| 492 |
+
mixed_output = model(output_hidden_states=True, adapter_names=batch_adapter_names, **X)
|
| 493 |
+
|
| 494 |
+
# check that the active adapter is still the last activated adapter, adapter_2
|
| 495 |
+
assert model.model.model.embed_tokens.token_adapter.active_adapter == ["adapter_2"]
|
| 496 |
+
|
| 497 |
+
adapter_1_output = mixed_output.hidden_states[0][0:1]
|
| 498 |
+
original_output_1 = original_output.hidden_states[0][0:1]
|
| 499 |
+
adapter_2_output = mixed_output.hidden_states[0][1:2]
|
| 500 |
+
original_output_2 = original_output.hidden_states[0][1:2]
|
| 501 |
+
|
| 502 |
+
idcs_to_modify = token_indices_1
|
| 503 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 504 |
+
|
| 505 |
+
assert not torch.allclose(adapter_1_output[:, idcs_to_modify], original_output_1[:, idcs_to_modify])
|
| 506 |
+
assert torch.allclose(adapter_1_output[:, idcs_to_keep], original_output_1[:, idcs_to_keep])
|
| 507 |
+
|
| 508 |
+
idcs_to_modify = token_indices_2
|
| 509 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 510 |
+
|
| 511 |
+
assert not torch.allclose(adapter_2_output[:, idcs_to_modify], original_output_2[:, idcs_to_modify])
|
| 512 |
+
assert torch.allclose(adapter_2_output[:, idcs_to_keep], original_output_2[:, idcs_to_keep])
|
| 513 |
+
|
| 514 |
+
def test_stand_alone_raises_target_layer_not_found(self, model):
|
| 515 |
+
config = TrainableTokensConfig(target_modules=["doesnt_exist"], token_indices=[0, 1, 3])
|
| 516 |
+
with pytest.raises(ValueError) as e:
|
| 517 |
+
model = get_peft_model(model, config)
|
| 518 |
+
assert "Target modules ['doesnt_exist'] not found in the base model." in str(e)
|
| 519 |
+
|
| 520 |
+
@pytest.mark.parametrize(
|
| 521 |
+
"peft_config, target_layer_name",
|
| 522 |
+
[
|
| 523 |
+
(LoraConfig(trainable_token_indices={"does-not-exist": [0, 1, 2]}), "does-not-exist"),
|
| 524 |
+
],
|
| 525 |
+
)
|
| 526 |
+
def test_combined_with_peft_raises_target_layer_not_found(self, model, peft_config, target_layer_name):
|
| 527 |
+
# same as test_stand_alone_raises_target_layer_not_found but tests the peft method integration
|
| 528 |
+
with pytest.raises(ValueError) as e:
|
| 529 |
+
model = get_peft_model(model, peft_config)
|
| 530 |
+
assert f"Target modules {{{repr(target_layer_name)}}} not found in the base model." in str(e)
|
| 531 |
+
|
| 532 |
+
def test_multiple_targets(self, model_multi_embedding):
|
| 533 |
+
# tests the ability of targeting two modules with the same token indices
|
| 534 |
+
original_model = copy.deepcopy(model_multi_embedding)
|
| 535 |
+
config = TrainableTokensConfig(target_modules=["emb_text", "emb_image"], token_indices=[0, 1])
|
| 536 |
+
peft_model = get_peft_model(model_multi_embedding, config)
|
| 537 |
+
|
| 538 |
+
self.simulate_training(peft_model.model.emb_text)
|
| 539 |
+
self.simulate_training(peft_model.model.emb_image)
|
| 540 |
+
|
| 541 |
+
X = {
|
| 542 |
+
"x_text": torch.tensor([[0, 1, 2]]),
|
| 543 |
+
"x_image": torch.tensor([[0, 1, 2]]),
|
| 544 |
+
}
|
| 545 |
+
|
| 546 |
+
_, (emb_text_orig, emb_image_orig) = original_model(**X)
|
| 547 |
+
_, (emb_text_peft, emb_image_peft) = peft_model(**X)
|
| 548 |
+
|
| 549 |
+
assert not torch.allclose(emb_text_orig[:, [0, 1]], emb_text_peft[:, [0, 1]])
|
| 550 |
+
assert torch.allclose(emb_text_orig[:, [2]], emb_text_peft[:, [2]])
|
| 551 |
+
assert not torch.allclose(emb_image_orig[:, [0, 1]], emb_image_peft[:, [0, 1]])
|
| 552 |
+
assert torch.allclose(emb_image_orig[:, [2]], emb_image_peft[:, [2]])
|
| 553 |
+
|
| 554 |
+
@pytest.mark.parametrize(
|
| 555 |
+
"peft_config",
|
| 556 |
+
[
|
| 557 |
+
LoraConfig(
|
| 558 |
+
target_modules="all-linear",
|
| 559 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 560 |
+
),
|
| 561 |
+
],
|
| 562 |
+
)
|
| 563 |
+
def test_no_embeddings_in_save_with_combined_usage(self, model, tokenizer, peft_config, tmp_path):
|
| 564 |
+
# make sure that in combined use the only state dict key is that of the token deltas and nothing more
|
| 565 |
+
|
| 566 |
+
peft_model = get_peft_model(model, peft_config)
|
| 567 |
+
state_dict = get_peft_model_state_dict(
|
| 568 |
+
model=peft_model,
|
| 569 |
+
state_dict=None,
|
| 570 |
+
adapter_name="default",
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
embedding_keys = [n for n in state_dict.keys() if "embed_tokens" in n]
|
| 574 |
+
assert embedding_keys == ["base_model.model.model.embed_tokens.token_adapter.trainable_tokens_delta"]
|
| 575 |
+
|
| 576 |
+
@pytest.fixture()
|
| 577 |
+
def model_weight_untied(self, model):
|
| 578 |
+
return model
|
| 579 |
+
|
| 580 |
+
@pytest.fixture()
|
| 581 |
+
def model_id_weight_tied(self):
|
| 582 |
+
return "peft-internal-testing/opt-125m"
|
| 583 |
+
|
| 584 |
+
@pytest.fixture()
|
| 585 |
+
def model_weight_tied(self, request, model_id_weight_tied):
|
| 586 |
+
model_weight_tied = AutoModelForCausalLM.from_pretrained(model_id_weight_tied)
|
| 587 |
+
tied_keys = model_weight_tied._tied_weights_keys
|
| 588 |
+
|
| 589 |
+
# TODO remove when transformers <5 is not supported anymore
|
| 590 |
+
if not hasattr(request, "param") or request.param == "list":
|
| 591 |
+
if isinstance(tied_keys, list):
|
| 592 |
+
# transformers <5, list is already the default
|
| 593 |
+
yield model_weight_tied
|
| 594 |
+
else:
|
| 595 |
+
# simulate transformers <5 for backward compatibility testing
|
| 596 |
+
with patch.object(model_weight_tied, "_tied_weights_keys", list(tied_keys.keys())):
|
| 597 |
+
yield model_weight_tied
|
| 598 |
+
|
| 599 |
+
elif request.param == "mapping":
|
| 600 |
+
if isinstance(tied_keys, dict):
|
| 601 |
+
# transformers >=5, mapping is already the default
|
| 602 |
+
yield model_weight_tied
|
| 603 |
+
else:
|
| 604 |
+
# simulate transformers >=5
|
| 605 |
+
mapping = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
|
| 606 |
+
|
| 607 |
+
with patch.object(model_weight_tied, "_tied_weights_keys", mapping):
|
| 608 |
+
yield model_weight_tied
|
| 609 |
+
|
| 610 |
+
else:
|
| 611 |
+
raise RuntimeError("Invalid request")
|
| 612 |
+
|
| 613 |
+
@pytest.mark.parametrize(
|
| 614 |
+
"peft_config",
|
| 615 |
+
[
|
| 616 |
+
LoraConfig(
|
| 617 |
+
target_modules="all-linear",
|
| 618 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 619 |
+
),
|
| 620 |
+
],
|
| 621 |
+
)
|
| 622 |
+
def test_weight_tying_noop_when_model_is_untied(self, model_weight_untied, peft_config, tmp_path):
|
| 623 |
+
# test if the weight tying is affected as well when we modified the embedding.
|
| 624 |
+
assert model_weight_untied._tied_weights_keys
|
| 625 |
+
assert not model_weight_untied.config.tie_word_embeddings
|
| 626 |
+
|
| 627 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 628 |
+
assert hasattr(peft_model.model.model.embed_tokens, "token_adapter")
|
| 629 |
+
assert not hasattr(peft_model.model.lm_head, "token_adapter")
|
| 630 |
+
|
| 631 |
+
@pytest.mark.parametrize(
|
| 632 |
+
"peft_config, model_weight_tied",
|
| 633 |
+
[
|
| 634 |
+
(
|
| 635 |
+
LoraConfig(
|
| 636 |
+
target_modules="all-linear",
|
| 637 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 638 |
+
),
|
| 639 |
+
"list",
|
| 640 |
+
),
|
| 641 |
+
(
|
| 642 |
+
LoraConfig(
|
| 643 |
+
target_modules="all-linear",
|
| 644 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 645 |
+
),
|
| 646 |
+
"mapping",
|
| 647 |
+
),
|
| 648 |
+
],
|
| 649 |
+
indirect=["model_weight_tied"],
|
| 650 |
+
)
|
| 651 |
+
def test_weight_tying_applied_when_model_is_tied(self, model_weight_tied, peft_config, tmp_path):
|
| 652 |
+
# test if the weight tying is affected as well when we modified the embedding.
|
| 653 |
+
assert model_weight_tied._tied_weights_keys
|
| 654 |
+
assert model_weight_tied.config.tie_word_embeddings
|
| 655 |
+
|
| 656 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 657 |
+
|
| 658 |
+
# make it so that the input embeddings diverge. when the weights are tied this should
|
| 659 |
+
# reflect in the output embeddings as well.
|
| 660 |
+
self.simulate_training(peft_model.model.model.decoder.embed_tokens.token_adapter)
|
| 661 |
+
|
| 662 |
+
# we have to find out if the input embedding tying is doing its job during forward.
|
| 663 |
+
# for this we can leverage the fact that emb_out(1/emb_in(x)) is embed_dim on the
|
| 664 |
+
# diagonal iff emb_in.weight == emb_out.weight.
|
| 665 |
+
token_indices = [0, 1, 2, 3]
|
| 666 |
+
emb_dim = 768
|
| 667 |
+
emb_in = peft_model.model.model.decoder.embed_tokens(torch.tensor([token_indices]))
|
| 668 |
+
emb_out = peft_model.model.lm_head(1 / emb_in)
|
| 669 |
+
|
| 670 |
+
assert torch.allclose(torch.diag(emb_out[0]), torch.tensor([emb_dim] * len(token_indices)).float())
|
| 671 |
+
|
| 672 |
+
# make sure that the state dict does not include weight-tied weights.
|
| 673 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 674 |
+
assert not [key for key in state_dict if any(tied_key in key for tied_key in peft_model._tied_weights_keys)]
|
| 675 |
+
|
| 676 |
+
# make sure that merging and unloading restores the weight-tying.
|
| 677 |
+
merged_model = peft_model.merge_and_unload()
|
| 678 |
+
|
| 679 |
+
assert merged_model.model.decoder.embed_tokens.weight.data_ptr() == merged_model.lm_head.weight.data_ptr()
|
| 680 |
+
|
| 681 |
+
@pytest.mark.parametrize("model_weight_tied", ["list", "mapping"], indirect=["model_weight_tied"])
|
| 682 |
+
def test_weight_tying_applied_when_model_is_tied_standalone(self, model_weight_tied):
|
| 683 |
+
# since weight tying is currently not supported make sure that an error is raised when attempting
|
| 684 |
+
# to use a model that has tied input/output embeddings
|
| 685 |
+
assert model_weight_tied._tied_weights_keys
|
| 686 |
+
assert model_weight_tied.config.tie_word_embeddings
|
| 687 |
+
|
| 688 |
+
peft_config = TrainableTokensConfig(
|
| 689 |
+
target_modules=["embed_tokens"],
|
| 690 |
+
token_indices=[0, 1, 3],
|
| 691 |
+
)
|
| 692 |
+
|
| 693 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 694 |
+
|
| 695 |
+
# make it so that the input embeddings diverge. when the weights are tied this should
|
| 696 |
+
# reflect in the output embeddings as well.
|
| 697 |
+
self.simulate_training(peft_model.model.model.decoder.embed_tokens)
|
| 698 |
+
|
| 699 |
+
# we have to find out if the input embedding tying is doing its job during forward.
|
| 700 |
+
# for this we can leverage the fact that emb_out(1/emb_in(x)) is embed_dim on the
|
| 701 |
+
# diagonal iff emb_in.weight == emb_out.weight.
|
| 702 |
+
token_indices = [0, 1, 2, 3]
|
| 703 |
+
emb_dim = 768
|
| 704 |
+
emb_in = peft_model.model.model.decoder.embed_tokens(torch.tensor([token_indices]))
|
| 705 |
+
emb_out = peft_model.model.lm_head(1 / emb_in)
|
| 706 |
+
|
| 707 |
+
assert torch.allclose(torch.diag(emb_out[0]), torch.tensor([emb_dim] * len(token_indices)).float())
|
| 708 |
+
|
| 709 |
+
# make sure that the state dict does not include weight-tied weights.
|
| 710 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 711 |
+
assert not [key for key in state_dict if any(tied_key in key for tied_key in peft_model._tied_weights_keys)]
|
| 712 |
+
|
| 713 |
+
# make sure that merging and unloading restores the weight-tying.
|
| 714 |
+
merged_model = peft_model.merge_and_unload()
|
| 715 |
+
|
| 716 |
+
assert merged_model.model.decoder.embed_tokens.weight.data_ptr() == merged_model.lm_head.weight.data_ptr()
|
| 717 |
+
|
| 718 |
+
def test_weight_tying_normally_issues_warning(self, model_weight_tied, recwarn):
|
| 719 |
+
# When using models with weight tying and targeting the embedding or the tied layer should raise a warning.
|
| 720 |
+
peft_config = LoraConfig(target_modules=["embed_tokens"])
|
| 721 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 722 |
+
|
| 723 |
+
warnings = [w.message.args[0] for w in recwarn]
|
| 724 |
+
warnings = [msg for msg in warnings if "Model with `tie_word_embeddings=True` and the" in msg]
|
| 725 |
+
assert warnings
|
| 726 |
+
|
| 727 |
+
def test_weight_tying_state_dict_ignores_tied_weights(self, model_weight_tied):
|
| 728 |
+
# since weight tying is currently not supported make sure that an error is raised when attempting
|
| 729 |
+
# to use a model that has tied input/output embeddings
|
| 730 |
+
assert model_weight_tied._tied_weights_keys
|
| 731 |
+
assert model_weight_tied.config.tie_word_embeddings
|
| 732 |
+
|
| 733 |
+
peft_config = TrainableTokensConfig(
|
| 734 |
+
target_modules=["embed_tokens"],
|
| 735 |
+
token_indices=[0, 1, 3],
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 739 |
+
|
| 740 |
+
state_dict = peft_model.state_dict()
|
| 741 |
+
peft_state_dict = get_peft_model_state_dict(peft_model)
|
| 742 |
+
|
| 743 |
+
# the state dict or the peft model state dict must not include tied adapter weights
|
| 744 |
+
state_dict_keys = [n for n, _ in state_dict.items() if "tied_adapter." in n]
|
| 745 |
+
peft_state_dict_keys = [n for n, _ in peft_state_dict.items() if "tied_adapter." in n]
|
| 746 |
+
|
| 747 |
+
assert not state_dict_keys
|
| 748 |
+
assert not peft_state_dict_keys
|
| 749 |
+
|
| 750 |
+
@pytest.mark.parametrize(
|
| 751 |
+
"peft_config",
|
| 752 |
+
[
|
| 753 |
+
LoraConfig(
|
| 754 |
+
target_modules="all-linear",
|
| 755 |
+
trainable_token_indices={"shared": [0, 1, 3]},
|
| 756 |
+
),
|
| 757 |
+
],
|
| 758 |
+
)
|
| 759 |
+
def test_weight_tying_applied_when_model_is_tied_encoder_decoder(self, peft_config):
|
| 760 |
+
model_id = "peft-internal-testing/tiny-random-t5"
|
| 761 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
| 762 |
+
|
| 763 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 764 |
+
|
| 765 |
+
# make it so that the input embeddings diverge. when the weights are tied this should
|
| 766 |
+
# reflect in the output embeddings as well.
|
| 767 |
+
self.simulate_training(peft_model.model.shared.token_adapter)
|
| 768 |
+
|
| 769 |
+
# we have to find out if the input embedding tying is doing its job during forward.
|
| 770 |
+
# for this we can leverage the fact that emb_out(1/emb_in(x)) is embed_dim on the
|
| 771 |
+
# diagonal iff emb_in.weight == emb_out.weight.
|
| 772 |
+
token_indices = [0, 1, 2, 3]
|
| 773 |
+
emb_dim = base_model.config.d_model
|
| 774 |
+
emb_in = peft_model.model.encoder.embed_tokens(torch.tensor([token_indices]))
|
| 775 |
+
emb_out = peft_model.model.lm_head(1 / emb_in)
|
| 776 |
+
|
| 777 |
+
assert torch.allclose(torch.diag(emb_out[0]), torch.tensor([emb_dim] * len(token_indices)).float())
|
| 778 |
+
|
| 779 |
+
# T5 has a decoder embedding layer, we can simply check if it's forward is equal to the encoder
|
| 780 |
+
# embedding forward.
|
| 781 |
+
emb_out = peft_model.model.decoder.embed_tokens(torch.tensor([token_indices]))
|
| 782 |
+
|
| 783 |
+
assert torch.allclose(emb_in, emb_out)
|
| 784 |
+
|
| 785 |
+
# make sure that the state dict does not include weight-tied weights.
|
| 786 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 787 |
+
assert not [key for key in state_dict if any(tied_key in key for tied_key in peft_model._tied_weights_keys)]
|
| 788 |
+
|
| 789 |
+
# make sure that merging and unloading restores the weight-tying.
|
| 790 |
+
merged_model = peft_model.merge_and_unload()
|
| 791 |
+
|
| 792 |
+
assert merged_model.encoder.embed_tokens.weight.data_ptr() == merged_model.lm_head.weight.data_ptr()
|
| 793 |
+
assert (
|
| 794 |
+
merged_model.encoder.embed_tokens.weight.data_ptr() == merged_model.decoder.embed_tokens.weight.data_ptr()
|
| 795 |
+
)
|
| 796 |
+
|
| 797 |
+
@pytest.mark.parametrize(
|
| 798 |
+
"peft_config",
|
| 799 |
+
[
|
| 800 |
+
LoraConfig(
|
| 801 |
+
target_modules="all-linear",
|
| 802 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 803 |
+
modules_to_save=["embed_tokens"],
|
| 804 |
+
),
|
| 805 |
+
],
|
| 806 |
+
)
|
| 807 |
+
def test_modules_to_save_excludes_trainable_tokens(self, model, peft_config):
|
| 808 |
+
with pytest.raises(ValueError) as e:
|
| 809 |
+
get_peft_model(model, peft_config)
|
| 810 |
+
assert "The embedding layer is already marked to be trained fully" in str(e)
|
| 811 |
+
|
| 812 |
+
def test_merge_and_unload_standalone(self, model):
|
| 813 |
+
# test basic functionality of merge_and_unload for standalone TrainableTokens
|
| 814 |
+
token_indices = [0, 1, 3]
|
| 815 |
+
|
| 816 |
+
peft_config = TrainableTokensConfig(
|
| 817 |
+
target_modules=["embed_tokens"],
|
| 818 |
+
token_indices=token_indices,
|
| 819 |
+
)
|
| 820 |
+
|
| 821 |
+
peft_model = get_peft_model(model, peft_config)
|
| 822 |
+
|
| 823 |
+
self.simulate_training(peft_model.model.model.embed_tokens)
|
| 824 |
+
expected_changed_weights = peft_model.model.model.embed_tokens.trainable_tokens_delta.default.data.clone()
|
| 825 |
+
|
| 826 |
+
# make sure no TrainableTokensLayer is in the module
|
| 827 |
+
merged_model = peft_model.merge_and_unload()
|
| 828 |
+
for _, module in merged_model.named_modules():
|
| 829 |
+
assert not isinstance(module, TrainableTokensLayer)
|
| 830 |
+
|
| 831 |
+
# make sure that deltas are applied to the embedding matrix
|
| 832 |
+
assert torch.allclose(merged_model.model.embed_tokens.weight.data[token_indices], expected_changed_weights)
|
| 833 |
+
|
| 834 |
+
def test_original_module_not_in_state_dict(self, model):
|
| 835 |
+
# Every AuxiliaryTrainingWrapper has an original_module attribute. Since the TrainableTokensWrapper is wrapping
|
| 836 |
+
# a TrainableTokensLayer and it already has a base layer which serves as the original module, we don't need that
|
| 837 |
+
# and so it should not come up in the state dict to save memory.
|
| 838 |
+
|
| 839 |
+
peft_config = LoraConfig(
|
| 840 |
+
target_modules="all-linear",
|
| 841 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
peft_model = get_peft_model(model, peft_config)
|
| 845 |
+
|
| 846 |
+
# make sure that the original module is present and accessible even though
|
| 847 |
+
# we want to exclude it from the state dict.
|
| 848 |
+
assert peft_model.model.model.embed_tokens.original_module
|
| 849 |
+
|
| 850 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 851 |
+
|
| 852 |
+
assert not [k for k in state_dict if ".original_module.weight" in k]
|
| 853 |
+
|
| 854 |
+
state_dict = peft_model.state_dict()
|
| 855 |
+
assert not [k for k in state_dict if ".original_module.weight" in k]
|
| 856 |
+
|
| 857 |
+
@pytest.fixture
|
| 858 |
+
def model_emb(self):
|
| 859 |
+
return ModelEmb()
|
| 860 |
+
|
| 861 |
+
@pytest.fixture
|
| 862 |
+
def model_embed_in(self):
|
| 863 |
+
return ModelEmbedIn()
|
| 864 |
+
|
| 865 |
+
@pytest.fixture
|
| 866 |
+
def model_embed_in_no_get(self):
|
| 867 |
+
return ModelEmbedInNoGet()
|
| 868 |
+
|
| 869 |
+
@pytest.fixture
|
| 870 |
+
def model_embed_multiple(self):
|
| 871 |
+
return ModelEmbedMultiple()
|
| 872 |
+
|
| 873 |
+
@pytest.mark.parametrize(
|
| 874 |
+
"model_fixture_name, getter",
|
| 875 |
+
[
|
| 876 |
+
("model_emb", lambda model: model.emb),
|
| 877 |
+
("model_embed_in", lambda model: model.embed_in),
|
| 878 |
+
("model", lambda model: model.model.model.embed_tokens),
|
| 879 |
+
],
|
| 880 |
+
)
|
| 881 |
+
def test_default_embedding_name_is_inferred_standalone(self, model_fixture_name, getter, request):
|
| 882 |
+
# make sure that the auto targeting works when `target_module=None`
|
| 883 |
+
base_model = request.getfixturevalue(model_fixture_name)
|
| 884 |
+
|
| 885 |
+
peft_config = TrainableTokensConfig(target_modules=None, token_indices=[0, 1, 3])
|
| 886 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 887 |
+
|
| 888 |
+
assert isinstance(getter(peft_model), TrainableTokensLayer)
|
| 889 |
+
|
| 890 |
+
@pytest.mark.parametrize(
|
| 891 |
+
"model_fixture_name, getter",
|
| 892 |
+
[
|
| 893 |
+
("model_emb", lambda model: model.emb),
|
| 894 |
+
("model_embed_in", lambda model: model.embed_in),
|
| 895 |
+
("model", lambda model: model.model.model.embed_tokens),
|
| 896 |
+
],
|
| 897 |
+
)
|
| 898 |
+
def test_default_embedding_name_is_inferred_combined(self, model_fixture_name, getter, request):
|
| 899 |
+
# make sure that the auto targeting works when `target_module=None`
|
| 900 |
+
base_model = request.getfixturevalue(model_fixture_name)
|
| 901 |
+
|
| 902 |
+
peft_config = LoraConfig(target_modules="all-linear", trainable_token_indices=[0, 1, 3])
|
| 903 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 904 |
+
|
| 905 |
+
assert isinstance(getter(peft_model), TrainableTokensWrapper)
|
| 906 |
+
|
| 907 |
+
def test_default_embedding_name_cannot_be_inferred(self, model_embed_in_no_get):
|
| 908 |
+
# should default to default value `embed_tokens` which is not present in this model
|
| 909 |
+
base_model = model_embed_in_no_get
|
| 910 |
+
|
| 911 |
+
peft_config = TrainableTokensConfig(target_modules=None, token_indices=[0, 1, 3])
|
| 912 |
+
|
| 913 |
+
with pytest.raises(ValueError) as e:
|
| 914 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 915 |
+
|
| 916 |
+
assert "Target modules embed_tokens not found in the base model." in str(e)
|
| 917 |
+
|
| 918 |
+
def test_embedding_name_is_used_when_given_standalone(self, model_embed_multiple):
|
| 919 |
+
peft_config = TrainableTokensConfig(target_modules="embed_in_2", token_indices=[0, 1, 3])
|
| 920 |
+
peft_model = get_peft_model(model_embed_multiple, peft_config)
|
| 921 |
+
|
| 922 |
+
assert isinstance(peft_model.model.embed_in_2, TrainableTokensLayer)
|
| 923 |
+
assert not isinstance(peft_model.model.embed_in, TrainableTokensLayer)
|
| 924 |
+
|
| 925 |
+
def test_embedding_name_is_used_when_given_combined(self, model_embed_multiple):
|
| 926 |
+
peft_config = LoraConfig(target_modules="all-linear", trainable_token_indices={"embed_in_2": [0, 1, 3]})
|
| 927 |
+
peft_model = get_peft_model(model_embed_multiple, peft_config)
|
| 928 |
+
|
| 929 |
+
assert isinstance(peft_model.model.embed_in_2, TrainableTokensWrapper)
|
| 930 |
+
assert not isinstance(peft_model.model.embed_in, TrainableTokensWrapper)
|
| 931 |
+
|
| 932 |
+
@pytest.mark.parametrize("resize_embedding", [True, False])
|
| 933 |
+
@pytest.mark.parametrize(
|
| 934 |
+
"peft_config",
|
| 935 |
+
[
|
| 936 |
+
LoraConfig(target_modules="all-linear", trainable_token_indices=[1, 2, 3]),
|
| 937 |
+
TrainableTokensConfig(target_modules=None, token_indices=[1, 2, 3]),
|
| 938 |
+
],
|
| 939 |
+
)
|
| 940 |
+
def test_save_pretrained_auto(self, model, resize_embedding, peft_config, tmp_path):
|
| 941 |
+
# make sure that embeddings are saved alongside trainable token weights but only when
|
| 942 |
+
# the we detect the embedding to be resized (as detected by save_embedding_layers="auto")
|
| 943 |
+
if resize_embedding:
|
| 944 |
+
model.resize_token_embeddings(model.config.vocab_size + 2)
|
| 945 |
+
peft_model = get_peft_model(model, peft_config)
|
| 946 |
+
|
| 947 |
+
peft_model.save_pretrained(tmp_path, save_embedding_layers="auto")
|
| 948 |
+
state_dict = safe_load_file(tmp_path / "adapter_model.safetensors")
|
| 949 |
+
|
| 950 |
+
if isinstance(peft_config, TrainableTokensConfig):
|
| 951 |
+
contains_embedding = "base_model.model.model.embed_tokens.base_layer.weight" in state_dict
|
| 952 |
+
else:
|
| 953 |
+
contains_embedding = "base_model.model.model.embed_tokens.token_adapter.base_layer.weight" in state_dict
|
| 954 |
+
|
| 955 |
+
if resize_embedding:
|
| 956 |
+
assert contains_embedding
|
| 957 |
+
else:
|
| 958 |
+
assert not contains_embedding
|
| 959 |
+
|
| 960 |
+
def test_embed_scale_is_applied(self):
|
| 961 |
+
"""Test that TrainableTokens correctly handles embeddings with scaling (e.g., Gemma3)."""
|
| 962 |
+
model_id = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"
|
| 963 |
+
with hub_online_once(model_id):
|
| 964 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 965 |
+
orig_embedding = base_model.get_input_embeddings()
|
| 966 |
+
|
| 967 |
+
peft_config = TrainableTokensConfig(target_modules=["embed_tokens"], token_indices=[0, 1, 3])
|
| 968 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 969 |
+
|
| 970 |
+
# sanity check: with the default embed_scale, the embedding output should be reasonably sized
|
| 971 |
+
peft_embedding = peft_model.base_model.model.get_input_embeddings()
|
| 972 |
+
max_embedding_output = peft_embedding(torch.arange(10)).abs().max(0)[0]
|
| 973 |
+
assert (max_embedding_output < 100.0).all()
|
| 974 |
+
|
| 975 |
+
# set embed_scale to an absurdly high value, then check that the embedding output is also scaled to a high
|
| 976 |
+
# value
|
| 977 |
+
orig_embedding.embed_scale.fill_(10000.0)
|
| 978 |
+
max_embedding_output = peft_embedding(torch.arange(10)).abs().max(0)[0]
|
| 979 |
+
assert (max_embedding_output > 100.0).all()
|
| 980 |
+
|
| 981 |
+
# set embed_scale to zero, then check that the embedding output is also zero
|
| 982 |
+
orig_embedding.embed_scale.fill_(0)
|
| 983 |
+
embedding_output = peft_embedding(torch.arange(10))
|
| 984 |
+
assert (embedding_output == 0.0).all()
|
| 985 |
+
|
| 986 |
+
def test_scaled_embedding_with_lora(self):
|
| 987 |
+
"""
|
| 988 |
+
Test that TrainableTokens works with LoRA on scaled embeddings when both are active simultaneously.
|
| 989 |
+
"""
|
| 990 |
+
model_id = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"
|
| 991 |
+
with hub_online_once(model_id):
|
| 992 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 993 |
+
orig_embedding = base_model.get_input_embeddings()
|
| 994 |
+
|
| 995 |
+
# Apply both TrainableTokens and LoRA to the same model
|
| 996 |
+
peft_config = LoraConfig(target_modules=["q_proj"], trainable_token_indices={"embed_tokens": [0, 1, 3]})
|
| 997 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 998 |
+
|
| 999 |
+
x = torch.arange(10)
|
| 1000 |
+
peft_embedding = peft_model.base_model.model.get_input_embeddings()
|
| 1001 |
+
embedding_output = peft_embedding(x)
|
| 1002 |
+
max_embedding_output = embedding_output.abs().max(0)[0]
|
| 1003 |
+
assert (max_embedding_output < 100.0).all()
|
| 1004 |
+
peft_model.merge_adapter()
|
| 1005 |
+
embedding_merged = peft_embedding(x)
|
| 1006 |
+
assert torch.allclose(embedding_output, embedding_merged)
|
| 1007 |
+
peft_model.unmerge_adapter()
|
| 1008 |
+
|
| 1009 |
+
# set embed_scale to an absurdly high value, then check that the embedding output is also scaled to a high
|
| 1010 |
+
# value
|
| 1011 |
+
orig_embedding.embed_scale.fill_(10000.0)
|
| 1012 |
+
max_embedding_output = peft_embedding(x).abs().max(0)[0]
|
| 1013 |
+
assert (max_embedding_output > 100.0).all()
|
| 1014 |
+
|
| 1015 |
+
# set embed_scale to zero, then check that the embedding output is also zero
|
| 1016 |
+
orig_embedding.embed_scale.fill_(0)
|
| 1017 |
+
embedding_output = peft_embedding(x)
|
| 1018 |
+
assert (embedding_output == 0.0).all()
|
| 1019 |
+
|
| 1020 |
+
# Tests for ensure_weight_tying parameter with trainable_token_indices
|
| 1021 |
+
# See #2864 for details on the expected behavior
|
| 1022 |
+
@pytest.mark.parametrize(
|
| 1023 |
+
"trainable_token_indices",
|
| 1024 |
+
[
|
| 1025 |
+
[1, 2, 3], # list format
|
| 1026 |
+
{"embed_tokens": [1, 2, 3]}, # dict format - single layer
|
| 1027 |
+
{"lm_head": [1, 2], "embed_tokens": [1, 2]}, # dict format - same indices
|
| 1028 |
+
{"lm_head": [1, 2], "embed_tokens": [3, 4]}, # dict format - different indices
|
| 1029 |
+
],
|
| 1030 |
+
)
|
| 1031 |
+
def test_ensure_weight_tying_warns_when_model_not_tied(
|
| 1032 |
+
self, model_weight_untied, recwarn, trainable_token_indices
|
| 1033 |
+
):
|
| 1034 |
+
"""Should warn when ensure_weight_tying=True but model doesn't have tied weights"""
|
| 1035 |
+
peft_config = LoraConfig(
|
| 1036 |
+
target_modules="all-linear",
|
| 1037 |
+
trainable_token_indices=trainable_token_indices,
|
| 1038 |
+
ensure_weight_tying=True,
|
| 1039 |
+
)
|
| 1040 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 1041 |
+
|
| 1042 |
+
warnings_list = [w.message.args[0] for w in recwarn]
|
| 1043 |
+
expected = "ensure_weight_tying=True but the model does not have tied weights"
|
| 1044 |
+
assert any(expected in msg for msg in warnings_list)
|
| 1045 |
+
|
| 1046 |
+
# Verify adapters are not tied (model doesn't have tied weights)
|
| 1047 |
+
if isinstance(trainable_token_indices, dict) and len(trainable_token_indices) > 1:
|
| 1048 |
+
embed_adapter = peft_model.model.model.embed_tokens.token_adapter
|
| 1049 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1050 |
+
assert embed_adapter is not None
|
| 1051 |
+
assert lm_head_adapter is not None
|
| 1052 |
+
assert embed_adapter.trainable_tokens_delta is not lm_head_adapter.trainable_tokens_delta
|
| 1053 |
+
|
| 1054 |
+
def test_weight_tying_bc_different_indices_treated_separately(self, model_weight_tied):
|
| 1055 |
+
"""Backwards compatibility: different indices should be treated separately when ensure_weight_tying=False"""
|
| 1056 |
+
peft_config = LoraConfig(
|
| 1057 |
+
target_modules="all-linear",
|
| 1058 |
+
trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]},
|
| 1059 |
+
ensure_weight_tying=False, # BC behavior
|
| 1060 |
+
)
|
| 1061 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1062 |
+
|
| 1063 |
+
# Check that both layers have token adapters but they're NOT tied
|
| 1064 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1065 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1066 |
+
|
| 1067 |
+
assert embed_adapter is not None
|
| 1068 |
+
assert lm_head_adapter is not None
|
| 1069 |
+
# They should NOT share the same delta parameters (treated as separate)
|
| 1070 |
+
assert embed_adapter.trainable_tokens_delta is not lm_head_adapter.trainable_tokens_delta
|
| 1071 |
+
# They should have different token indices
|
| 1072 |
+
assert embed_adapter.token_indices["default"] == [3, 4]
|
| 1073 |
+
assert lm_head_adapter.token_indices["default"] == [1, 2]
|
| 1074 |
+
|
| 1075 |
+
def test_ensure_weight_tying_errors_with_different_indices(self, model_weight_tied):
|
| 1076 |
+
"""Should raise error when ensure_weight_tying=True with different indices for embedding and lm_head"""
|
| 1077 |
+
peft_config = LoraConfig(
|
| 1078 |
+
target_modules="all-linear",
|
| 1079 |
+
trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]},
|
| 1080 |
+
ensure_weight_tying=True,
|
| 1081 |
+
)
|
| 1082 |
+
|
| 1083 |
+
msg = "Cannot ensure weight tying when different token indices are specified"
|
| 1084 |
+
with pytest.raises(ValueError, match=msg):
|
| 1085 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1086 |
+
|
| 1087 |
+
@pytest.mark.parametrize(
|
| 1088 |
+
"trainable_token_indices, ensure_weight_tying",
|
| 1089 |
+
[
|
| 1090 |
+
([1, 2], True),
|
| 1091 |
+
([1, 2], False),
|
| 1092 |
+
({"lm_head": [1, 2], "embed_tokens": [1, 2]}, True),
|
| 1093 |
+
({"lm_head": [1, 2], "embed_tokens": [1, 2]}, False),
|
| 1094 |
+
],
|
| 1095 |
+
)
|
| 1096 |
+
def test_ensure_weight_tying_applied_with_same_indices(
|
| 1097 |
+
self, model_weight_tied, trainable_token_indices, ensure_weight_tying
|
| 1098 |
+
):
|
| 1099 |
+
"""Should apply weight tying when ensure_weight_tying=True with same indices"""
|
| 1100 |
+
peft_config = LoraConfig(
|
| 1101 |
+
target_modules="all-linear",
|
| 1102 |
+
trainable_token_indices=trainable_token_indices,
|
| 1103 |
+
ensure_weight_tying=ensure_weight_tying,
|
| 1104 |
+
)
|
| 1105 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1106 |
+
|
| 1107 |
+
# Check that weight tying is properly applied
|
| 1108 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1109 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1110 |
+
|
| 1111 |
+
# They should share the same delta parameters (weight tying)
|
| 1112 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1113 |
+
# They should have the same token indices
|
| 1114 |
+
assert embed_adapter.token_indices["default"] == [1, 2]
|
| 1115 |
+
assert lm_head_adapter.token_indices["default"] == [1, 2]
|
| 1116 |
+
|
| 1117 |
+
def test_weight_tying_bc_same_indices_applied(self, model_weight_tied):
|
| 1118 |
+
"""When indices are the same, weight tying should be applied even when ensure_weight_tying=False"""
|
| 1119 |
+
peft_config = LoraConfig(
|
| 1120 |
+
target_modules="all-linear",
|
| 1121 |
+
trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]},
|
| 1122 |
+
ensure_weight_tying=False, # BC: still applies tying when indices are the same
|
| 1123 |
+
)
|
| 1124 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1125 |
+
|
| 1126 |
+
# Even with ensure_weight_tying=False, BC behavior should still tie when indices are same
|
| 1127 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1128 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1129 |
+
|
| 1130 |
+
# They should share the same delta parameters (BC behavior)
|
| 1131 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1132 |
+
|
| 1133 |
+
def test_ensure_weight_tying_with_single_layer(self, model_weight_tied):
|
| 1134 |
+
"""ensure_weight_tying should work with single layer (list format)"""
|
| 1135 |
+
peft_config = LoraConfig(
|
| 1136 |
+
target_modules="all-linear",
|
| 1137 |
+
trainable_token_indices=[1, 2, 3],
|
| 1138 |
+
ensure_weight_tying=True,
|
| 1139 |
+
)
|
| 1140 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1141 |
+
|
| 1142 |
+
# Should apply weight tying to tied layers automatically
|
| 1143 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1144 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1145 |
+
|
| 1146 |
+
# They should share the same delta parameters
|
| 1147 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1148 |
+
|
| 1149 |
+
def test_untied_model_list_format_no_ensure(self, model_weight_untied):
|
| 1150 |
+
"""Untied model with list format, ensure_weight_tying=False - trainable tokens on embeddings only"""
|
| 1151 |
+
peft_config = LoraConfig(
|
| 1152 |
+
target_modules="all-linear",
|
| 1153 |
+
trainable_token_indices=[1, 2, 3],
|
| 1154 |
+
ensure_weight_tying=False,
|
| 1155 |
+
)
|
| 1156 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 1157 |
+
|
| 1158 |
+
# Only embed_tokens should have token adapter
|
| 1159 |
+
assert hasattr(peft_model.model.model.embed_tokens, "token_adapter")
|
| 1160 |
+
assert not hasattr(peft_model.model.lm_head, "token_adapter")
|
| 1161 |
+
|
| 1162 |
+
def test_tied_model_list_format_no_ensure(self, model_weight_tied):
|
| 1163 |
+
"""Tied model with list format, ensure_weight_tying=False - tied trainable tokens"""
|
| 1164 |
+
peft_config = LoraConfig(
|
| 1165 |
+
target_modules="all-linear",
|
| 1166 |
+
trainable_token_indices=[1, 2, 3],
|
| 1167 |
+
ensure_weight_tying=False,
|
| 1168 |
+
)
|
| 1169 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1170 |
+
|
| 1171 |
+
# Both should have token adapters and be tied
|
| 1172 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1173 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1174 |
+
|
| 1175 |
+
# They should share the same delta parameters (BC behavior)
|
| 1176 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1177 |
+
|
| 1178 |
+
@pytest.mark.parametrize(
|
| 1179 |
+
"trainable_token_indices",
|
| 1180 |
+
[
|
| 1181 |
+
{"lm_head": [1, 2], "embed_tokens": [1, 2]}, # same indices
|
| 1182 |
+
{"lm_head": [1, 2], "embed_tokens": [3, 4]}, # different indices
|
| 1183 |
+
],
|
| 1184 |
+
)
|
| 1185 |
+
def test_untied_model_dict_no_ensure(self, model_weight_untied, trainable_token_indices):
|
| 1186 |
+
"""Untied model with dict format, ensure_weight_tying=False - treat as separate"""
|
| 1187 |
+
peft_config = LoraConfig(
|
| 1188 |
+
target_modules="all-linear",
|
| 1189 |
+
trainable_token_indices=trainable_token_indices,
|
| 1190 |
+
ensure_weight_tying=False,
|
| 1191 |
+
)
|
| 1192 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 1193 |
+
|
| 1194 |
+
# Both should have token adapters but NOT tied (since model doesn't have tied weights)
|
| 1195 |
+
embed_adapter = peft_model.model.model.embed_tokens.token_adapter
|
| 1196 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1197 |
+
|
| 1198 |
+
assert embed_adapter is not None
|
| 1199 |
+
assert lm_head_adapter is not None
|
| 1200 |
+
# They should NOT share delta parameters (model doesn't have tied weights)
|
| 1201 |
+
assert embed_adapter.trainable_tokens_delta is not lm_head_adapter.trainable_tokens_delta
|
| 1202 |
+
|
| 1203 |
+
@pytest.mark.skipif(
|
| 1204 |
+
not is_transformers_ge_v5, reason="Test requires transformers v5+ dict format for _tied_weights_keys"
|
| 1205 |
+
)
|
| 1206 |
+
def test_composite_model_multiple_embed_tokens_specific_targeting(self):
|
| 1207 |
+
"""Test that users can specify full paths to disambiguate multiple embed_tokens layers.
|
| 1208 |
+
|
| 1209 |
+
This tests the scenario where a composite model has multiple sub-models, each with their own embed_tokens, and
|
| 1210 |
+
users need to target them independently with different token indices.
|
| 1211 |
+
"""
|
| 1212 |
+
|
| 1213 |
+
# Create a composite model with two BART sub-models
|
| 1214 |
+
class CompositeModel(torch.nn.Module):
|
| 1215 |
+
def __init__(self):
|
| 1216 |
+
super().__init__()
|
| 1217 |
+
config1 = BartConfig(
|
| 1218 |
+
vocab_size=100,
|
| 1219 |
+
d_model=32,
|
| 1220 |
+
encoder_layers=1,
|
| 1221 |
+
decoder_layers=1,
|
| 1222 |
+
encoder_attention_heads=2,
|
| 1223 |
+
decoder_attention_heads=2,
|
| 1224 |
+
encoder_ffn_dim=64,
|
| 1225 |
+
decoder_ffn_dim=64,
|
| 1226 |
+
)
|
| 1227 |
+
self.m1 = BartModel(config1)
|
| 1228 |
+
|
| 1229 |
+
config2 = BartConfig(
|
| 1230 |
+
vocab_size=100,
|
| 1231 |
+
d_model=32,
|
| 1232 |
+
encoder_layers=1,
|
| 1233 |
+
decoder_layers=1,
|
| 1234 |
+
encoder_attention_heads=2,
|
| 1235 |
+
decoder_attention_heads=2,
|
| 1236 |
+
encoder_ffn_dim=64,
|
| 1237 |
+
decoder_ffn_dim=64,
|
| 1238 |
+
)
|
| 1239 |
+
config2.tie_word_embeddings = False # m2 doesn't tie weights
|
| 1240 |
+
self.m2 = BartModel(config2)
|
| 1241 |
+
|
| 1242 |
+
# Add a config attribute for PEFT
|
| 1243 |
+
self.config = config1
|
| 1244 |
+
|
| 1245 |
+
# Use dict format to correctly represent independent tied weights within each sub-model
|
| 1246 |
+
self._tied_weights_keys = {
|
| 1247 |
+
"m1.decoder.embed_tokens.weight": "m1.encoder.embed_tokens.weight",
|
| 1248 |
+
"m2.decoder.embed_tokens.weight": "m2.encoder.embed_tokens.weight",
|
| 1249 |
+
}
|
| 1250 |
+
|
| 1251 |
+
def get_input_embeddings(self):
|
| 1252 |
+
return self.m1.encoder.embed_tokens
|
| 1253 |
+
|
| 1254 |
+
model = CompositeModel()
|
| 1255 |
+
|
| 1256 |
+
# User specifies different token indices for each sub-model's embed_tokens
|
| 1257 |
+
# This should NOT raise an error because they are distinct sub-models
|
| 1258 |
+
# With ensure_weight_tying=True, m1's internal tying should still work
|
| 1259 |
+
peft_config = LoraConfig(
|
| 1260 |
+
target_modules="all-linear",
|
| 1261 |
+
trainable_token_indices={
|
| 1262 |
+
"m1.encoder.embed_tokens": [1, 2, 3],
|
| 1263 |
+
"m2.encoder.embed_tokens": [4, 5, 6],
|
| 1264 |
+
},
|
| 1265 |
+
ensure_weight_tying=True, # Verify that weight tying works correctly
|
| 1266 |
+
)
|
| 1267 |
+
|
| 1268 |
+
# This should work without errors - the key is that it doesn't raise ValueError
|
| 1269 |
+
# about conflicting indices because m1 and m2 are independent
|
| 1270 |
+
peft_model = get_peft_model(model, peft_config)
|
| 1271 |
+
|
| 1272 |
+
# Verify that both layers got their adapters with correct indices
|
| 1273 |
+
m1_encoder_adapter = peft_model.m1.encoder.embed_tokens.token_adapter
|
| 1274 |
+
m2_adapter = peft_model.m2.encoder.embed_tokens.token_adapter
|
| 1275 |
+
|
| 1276 |
+
assert m1_encoder_adapter is not None
|
| 1277 |
+
assert m2_adapter is not None
|
| 1278 |
+
|
| 1279 |
+
# They should have different token indices as specified
|
| 1280 |
+
assert m1_encoder_adapter.token_indices["default"] == [1, 2, 3]
|
| 1281 |
+
assert m2_adapter.token_indices["default"] == [4, 5, 6]
|
| 1282 |
+
|
| 1283 |
+
# They should NOT share the same delta parameters (they're independent sub-models)
|
| 1284 |
+
assert m1_encoder_adapter.trainable_tokens_delta is not m2_adapter.trainable_tokens_delta
|
| 1285 |
+
|
| 1286 |
+
# m1's decoder should be tied to m1's encoder (internal weight tying within m1)
|
| 1287 |
+
m1_decoder_adapter = peft_model.m1.decoder.embed_tokens.token_adapter
|
| 1288 |
+
assert m1_decoder_adapter is not None
|
| 1289 |
+
assert m1_encoder_adapter.trainable_tokens_delta is m1_decoder_adapter.trainable_tokens_delta
|
| 1290 |
+
|
| 1291 |
+
# m2's decoder should NOT have an adapter since it's not tied and we didn't target it
|
| 1292 |
+
assert not hasattr(peft_model.m2.decoder.embed_tokens, "token_adapter")
|
| 1293 |
+
|
| 1294 |
+
def test_composite_model_short_name_matching(self):
|
| 1295 |
+
"""Test that short names like 'embed_tokens' still work but match the input embedding."""
|
| 1296 |
+
|
| 1297 |
+
class CompositeModel(torch.nn.Module):
|
| 1298 |
+
def __init__(self):
|
| 1299 |
+
super().__init__()
|
| 1300 |
+
config = BartConfig(
|
| 1301 |
+
vocab_size=100,
|
| 1302 |
+
d_model=32,
|
| 1303 |
+
encoder_layers=1,
|
| 1304 |
+
decoder_layers=1,
|
| 1305 |
+
encoder_attention_heads=2,
|
| 1306 |
+
decoder_attention_heads=2,
|
| 1307 |
+
encoder_ffn_dim=64,
|
| 1308 |
+
decoder_ffn_dim=64,
|
| 1309 |
+
)
|
| 1310 |
+
self.m1 = BartModel(config)
|
| 1311 |
+
self.config = config
|
| 1312 |
+
|
| 1313 |
+
def get_input_embeddings(self):
|
| 1314 |
+
return self.m1.encoder.embed_tokens
|
| 1315 |
+
|
| 1316 |
+
model = CompositeModel()
|
| 1317 |
+
|
| 1318 |
+
# User specifies just "embed_tokens" - should match m1.encoder.embed_tokens via endswith
|
| 1319 |
+
peft_config = LoraConfig(
|
| 1320 |
+
target_modules="all-linear",
|
| 1321 |
+
trainable_token_indices={"embed_tokens": [1, 2, 3]},
|
| 1322 |
+
ensure_weight_tying=True,
|
| 1323 |
+
)
|
| 1324 |
+
|
| 1325 |
+
peft_model = get_peft_model(model, peft_config)
|
| 1326 |
+
|
| 1327 |
+
# Should work and apply to the input embeddings
|
| 1328 |
+
assert hasattr(peft_model.m1.encoder.embed_tokens, "token_adapter")
|
| 1329 |
+
assert peft_model.m1.encoder.embed_tokens.token_adapter.token_indices["default"] == [1, 2, 3]
|
| 1330 |
+
|
| 1331 |
+
def test_targeting_both_embedding_and_tied_layer_explicitly(self, model_weight_tied):
|
| 1332 |
+
"""Test that explicitly targeting both embedding and tied layers works correctly.
|
| 1333 |
+
|
| 1334 |
+
When target_modules includes both "embed_tokens" and "lm_head" (which are tied in the model), both layers get
|
| 1335 |
+
wrapped and weight tying is properly applied between them.
|
| 1336 |
+
"""
|
| 1337 |
+
peft_config = TrainableTokensConfig(
|
| 1338 |
+
target_modules=["model.decoder.embed_tokens", "lm_head"], # Explicitly target both
|
| 1339 |
+
token_indices=[1, 2, 3],
|
| 1340 |
+
)
|
| 1341 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1342 |
+
|
| 1343 |
+
# Both should have been wrapped as TrainableTokensLayer
|
| 1344 |
+
embed_layer = peft_model.model.model.decoder.embed_tokens
|
| 1345 |
+
lm_head_layer = peft_model.model.lm_head
|
| 1346 |
+
|
| 1347 |
+
assert isinstance(embed_layer, TrainableTokensLayer)
|
| 1348 |
+
assert isinstance(lm_head_layer, TrainableTokensLayer)
|
| 1349 |
+
|
| 1350 |
+
# They should share the same delta parameters (tied)
|
| 1351 |
+
assert embed_layer.trainable_tokens_delta["default"] is lm_head_layer.trainable_tokens_delta["default"]
|
| 1352 |
+
|
| 1353 |
+
# Both should have the same token indices
|
| 1354 |
+
assert embed_layer.token_indices["default"] == [1, 2, 3]
|
| 1355 |
+
assert lm_head_layer.token_indices["default"] == [1, 2, 3]
|
| 1356 |
+
|
| 1357 |
+
def test_multiple_trainable_token_adapters_same_model(self, model_weight_tied):
|
| 1358 |
+
"""Test adding multiple trainable token adapters to the same model with tied layers.
|
| 1359 |
+
|
| 1360 |
+
This verifies that adding multiple adapters to the same tied layers (embed_tokens and lm_head) works correctly,
|
| 1361 |
+
with each adapter maintaining its own token indices while preserving weight tying.
|
| 1362 |
+
"""
|
| 1363 |
+
# Add first adapter with both embed_tokens and lm_head targeted
|
| 1364 |
+
peft_config1 = TrainableTokensConfig(
|
| 1365 |
+
target_modules=["model.decoder.embed_tokens", "lm_head"],
|
| 1366 |
+
token_indices=[1, 2, 3],
|
| 1367 |
+
)
|
| 1368 |
+
peft_model = get_peft_model(model_weight_tied, peft_config1)
|
| 1369 |
+
|
| 1370 |
+
# Add second adapter to the same layers
|
| 1371 |
+
peft_config2 = TrainableTokensConfig(
|
| 1372 |
+
target_modules=["model.decoder.embed_tokens", "lm_head"],
|
| 1373 |
+
token_indices=[4, 5, 6],
|
| 1374 |
+
)
|
| 1375 |
+
peft_model.add_adapter("adapter2", peft_config2)
|
| 1376 |
+
|
| 1377 |
+
# Get the wrapped layers
|
| 1378 |
+
embed_layer = peft_model.model.model.decoder.embed_tokens
|
| 1379 |
+
lm_head_layer = peft_model.model.lm_head
|
| 1380 |
+
|
| 1381 |
+
# Check first adapter
|
| 1382 |
+
assert "default" in embed_layer.token_indices
|
| 1383 |
+
assert "default" in lm_head_layer.token_indices
|
| 1384 |
+
assert embed_layer.token_indices["default"] == [1, 2, 3]
|
| 1385 |
+
assert lm_head_layer.token_indices["default"] == [1, 2, 3]
|
| 1386 |
+
|
| 1387 |
+
# First adapter should maintain tying
|
| 1388 |
+
assert embed_layer.trainable_tokens_delta["default"] is lm_head_layer.trainable_tokens_delta["default"]
|
| 1389 |
+
|
| 1390 |
+
# Check second adapter
|
| 1391 |
+
assert "adapter2" in embed_layer.token_indices
|
| 1392 |
+
assert "adapter2" in lm_head_layer.token_indices
|
| 1393 |
+
assert embed_layer.token_indices["adapter2"] == [4, 5, 6]
|
| 1394 |
+
assert lm_head_layer.token_indices["adapter2"] == [4, 5, 6]
|
| 1395 |
+
|
| 1396 |
+
# Second adapter should also maintain tying
|
| 1397 |
+
assert embed_layer.trainable_tokens_delta["adapter2"] is lm_head_layer.trainable_tokens_delta["adapter2"]
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_tuners_utils.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_vblora.py
AD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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
import pytest
|
| 18 |
+
import torch
|
| 19 |
+
from accelerate.utils.imports import is_bf16_available
|
| 20 |
+
from safetensors import safe_open
|
| 21 |
+
from torch import nn
|
| 22 |
+
|
| 23 |
+
from peft import PeftModel, VBLoRAConfig, get_peft_model
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class MLP(nn.Module):
|
| 27 |
+
def __init__(self, bias=True):
|
| 28 |
+
super().__init__()
|
| 29 |
+
self.relu = nn.ReLU()
|
| 30 |
+
self.lin0 = nn.Linear(10, 20, bias=bias)
|
| 31 |
+
self.lin1 = nn.Linear(20, 20, bias=bias) # lin1 and lin2 have same shape
|
| 32 |
+
self.lin2 = nn.Linear(20, 20, bias=bias)
|
| 33 |
+
self.lin3 = nn.Linear(20, 2, bias=bias)
|
| 34 |
+
self.sm = nn.LogSoftmax(dim=-1)
|
| 35 |
+
|
| 36 |
+
def forward(self, X):
|
| 37 |
+
X = self.lin0(X)
|
| 38 |
+
X = self.relu(X)
|
| 39 |
+
X = self.lin1(X)
|
| 40 |
+
X = self.relu(X)
|
| 41 |
+
X = self.lin2(X)
|
| 42 |
+
X = self.relu(X)
|
| 43 |
+
X = self.lin3(X)
|
| 44 |
+
X = self.sm(X)
|
| 45 |
+
return X
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class TestVBLoRA:
|
| 49 |
+
def get_mlp(self):
|
| 50 |
+
model = MLP()
|
| 51 |
+
return model
|
| 52 |
+
|
| 53 |
+
def test_vblora_parameters(self):
|
| 54 |
+
mlp = self.get_mlp()
|
| 55 |
+
vector_length = 2
|
| 56 |
+
num_vectors = 10
|
| 57 |
+
config = VBLoRAConfig(
|
| 58 |
+
target_modules=["lin0", "lin1", "lin3"], vector_length=vector_length, num_vectors=num_vectors
|
| 59 |
+
)
|
| 60 |
+
mlp_vblora = get_peft_model(mlp, config)
|
| 61 |
+
|
| 62 |
+
vector_bank = mlp_vblora.vblora_vector_bank["default"]
|
| 63 |
+
|
| 64 |
+
vblora_lin0_logits_B = mlp_vblora.lin0.vblora_logits_B["default"]
|
| 65 |
+
assert vblora_lin0_logits_B.shape == (mlp.lin0.out_features // vector_length, config.r, num_vectors)
|
| 66 |
+
|
| 67 |
+
vblora_lin1_logits_A = mlp_vblora.lin1.vblora_logits_A["default"]
|
| 68 |
+
assert vblora_lin1_logits_A.shape == (config.r, mlp.lin1.in_features // vector_length, num_vectors)
|
| 69 |
+
|
| 70 |
+
vblora_lin3_logits_A = mlp_vblora.lin3.vblora_logits_A["default"]
|
| 71 |
+
assert vblora_lin3_logits_A.shape == (config.r, mlp.lin3.in_features // vector_length, num_vectors)
|
| 72 |
+
|
| 73 |
+
assert vector_bank.shape == (num_vectors, vector_length)
|
| 74 |
+
|
| 75 |
+
# test if the vector bank is shared across the layers
|
| 76 |
+
assert (
|
| 77 |
+
mlp_vblora.lin0.vblora_vector_bank["default"].data_ptr()
|
| 78 |
+
== mlp_vblora.lin3.vblora_vector_bank["default"].data_ptr()
|
| 79 |
+
)
|
| 80 |
+
assert mlp_vblora.lin1.vblora_vector_bank["default"].data_ptr() == vector_bank.data_ptr()
|
| 81 |
+
|
| 82 |
+
# should not raise
|
| 83 |
+
input = torch.randn(5, 10)
|
| 84 |
+
mlp_vblora(input)
|
| 85 |
+
|
| 86 |
+
def test_save_with_topk_weights(self, tmp_path):
|
| 87 |
+
torch.manual_seed(0)
|
| 88 |
+
mlp = self.get_mlp()
|
| 89 |
+
vector_length = 2
|
| 90 |
+
num_vectors = 10
|
| 91 |
+
topk = 2
|
| 92 |
+
config = VBLoRAConfig(
|
| 93 |
+
target_modules=["lin0", "lin3"],
|
| 94 |
+
topk=topk,
|
| 95 |
+
vector_length=vector_length,
|
| 96 |
+
num_vectors=num_vectors,
|
| 97 |
+
save_only_topk_weights=True,
|
| 98 |
+
)
|
| 99 |
+
mlp_vblora = get_peft_model(mlp, config)
|
| 100 |
+
save_path = tmp_path / "vblora"
|
| 101 |
+
mlp_vblora.save_pretrained(save_path)
|
| 102 |
+
assert os.path.exists(save_path / "adapter_model.safetensors")
|
| 103 |
+
|
| 104 |
+
adapter_model_dict = {}
|
| 105 |
+
with safe_open(save_path / "adapter_model.safetensors", framework="pt") as f:
|
| 106 |
+
for k in f.keys():
|
| 107 |
+
adapter_model_dict[k] = f.get_tensor(k)
|
| 108 |
+
assert "base_model.model.lin0.vblora_logits_A_topk_indices" in adapter_model_dict
|
| 109 |
+
assert "base_model.model.lin0.vblora_logits_A_topk_weights" in adapter_model_dict
|
| 110 |
+
assert "base_model.model.lin3.vblora_logits_B_topk_indices" in adapter_model_dict
|
| 111 |
+
assert "base_model.model.lin3.vblora_logits_B_topk_weights" in adapter_model_dict
|
| 112 |
+
assert "base_model.model.lin0.vblora_logits_A" not in adapter_model_dict
|
| 113 |
+
assert "base_model.model.lin3.vblora_logits_B" not in adapter_model_dict
|
| 114 |
+
|
| 115 |
+
assert adapter_model_dict["base_model.model.lin0.vblora_logits_B_topk_indices"].shape == (
|
| 116 |
+
mlp.lin0.out_features // vector_length,
|
| 117 |
+
config.r,
|
| 118 |
+
topk,
|
| 119 |
+
)
|
| 120 |
+
assert adapter_model_dict["base_model.model.lin0.vblora_logits_B_topk_weights"].shape == (
|
| 121 |
+
mlp.lin0.out_features // vector_length,
|
| 122 |
+
config.r,
|
| 123 |
+
topk - 1,
|
| 124 |
+
)
|
| 125 |
+
assert adapter_model_dict["base_model.model.lin3.vblora_logits_A_topk_indices"].shape == (
|
| 126 |
+
config.r,
|
| 127 |
+
mlp.lin3.in_features // vector_length,
|
| 128 |
+
topk,
|
| 129 |
+
)
|
| 130 |
+
assert adapter_model_dict["base_model.model.lin3.vblora_logits_A_topk_weights"].shape == (
|
| 131 |
+
config.r,
|
| 132 |
+
mlp.lin3.in_features // vector_length,
|
| 133 |
+
topk - 1,
|
| 134 |
+
)
|
| 135 |
+
|
| 136 |
+
@pytest.mark.parametrize("save_only_topk_weights", [True, False])
|
| 137 |
+
def test_save_load(self, save_only_topk_weights, tmp_path):
|
| 138 |
+
torch.manual_seed(0)
|
| 139 |
+
mlp = self.get_mlp()
|
| 140 |
+
config = VBLoRAConfig(
|
| 141 |
+
target_modules=["lin0", "lin1", "lin3"],
|
| 142 |
+
topk=2,
|
| 143 |
+
vector_length=2,
|
| 144 |
+
num_vectors=10,
|
| 145 |
+
save_only_topk_weights=save_only_topk_weights,
|
| 146 |
+
)
|
| 147 |
+
mlp_vblora = get_peft_model(mlp, config)
|
| 148 |
+
save_path = tmp_path / "vblora"
|
| 149 |
+
mlp_vblora.save_pretrained(save_path)
|
| 150 |
+
assert os.path.exists(save_path / "adapter_config.json")
|
| 151 |
+
|
| 152 |
+
del mlp
|
| 153 |
+
torch.manual_seed(0) # make sure the base model has the same weights
|
| 154 |
+
mlp = self.get_mlp()
|
| 155 |
+
mlp_vblora_loaded = PeftModel.from_pretrained(mlp, save_path)
|
| 156 |
+
|
| 157 |
+
input = torch.randn(5, 10)
|
| 158 |
+
output = mlp_vblora(input)
|
| 159 |
+
output_loaded = mlp_vblora_loaded(input)
|
| 160 |
+
assert torch.allclose(output, output_loaded, atol=1e-8, rtol=1e-5)
|
| 161 |
+
|
| 162 |
+
def test_resume_training_model_with_topk_weights(self, tmp_path):
|
| 163 |
+
torch.manual_seed(1)
|
| 164 |
+
mlp = self.get_mlp()
|
| 165 |
+
config = VBLoRAConfig(
|
| 166 |
+
target_modules=["lin0", "lin1", "lin3"],
|
| 167 |
+
topk=2,
|
| 168 |
+
vector_length=2,
|
| 169 |
+
num_vectors=10,
|
| 170 |
+
save_only_topk_weights=True,
|
| 171 |
+
)
|
| 172 |
+
mlp_vblora = get_peft_model(mlp, config)
|
| 173 |
+
save_path = tmp_path / "vblora"
|
| 174 |
+
mlp_vblora.save_pretrained(save_path)
|
| 175 |
+
|
| 176 |
+
input = torch.randn(5, 10)
|
| 177 |
+
mlp_vblora.train()
|
| 178 |
+
# should not raise
|
| 179 |
+
mlp_vblora(input)
|
| 180 |
+
|
| 181 |
+
del mlp
|
| 182 |
+
torch.manual_seed(1)
|
| 183 |
+
mlp = self.get_mlp()
|
| 184 |
+
mlp_vblora_loaded = PeftModel.from_pretrained(mlp, save_path)
|
| 185 |
+
mlp_vblora_loaded.train()
|
| 186 |
+
msg = "Found infinity values in VB-LoRA logits. Ensure training was not resumed from a `save_only_topk_weights` model."
|
| 187 |
+
with pytest.raises(RuntimeError, match=msg):
|
| 188 |
+
mlp_vblora_loaded(input)
|
| 189 |
+
|
| 190 |
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
| 191 |
+
def test_vblora_dtypes(self, dtype):
|
| 192 |
+
mlp = self.get_mlp()
|
| 193 |
+
if dtype == torch.bfloat16:
|
| 194 |
+
if not is_bf16_available():
|
| 195 |
+
pytest.skip("bfloat16 not supported on this system, skipping the test")
|
| 196 |
+
|
| 197 |
+
config = VBLoRAConfig(
|
| 198 |
+
target_modules=["lin0", "lin1", "lin3"], vector_length=2, num_vectors=10, save_only_topk_weights=False
|
| 199 |
+
)
|
| 200 |
+
mlp_vblora = get_peft_model(mlp.to(dtype), config)
|
| 201 |
+
inputs = torch.randn(5, 10).to(dtype)
|
| 202 |
+
output = mlp_vblora(inputs) # should not raise
|
| 203 |
+
assert output.dtype == dtype
|
| 204 |
+
|
| 205 |
+
def test_vblora_nb_savable_params_only_topk_weights(self):
|
| 206 |
+
mlp = self.get_mlp()
|
| 207 |
+
vector_length = 2
|
| 208 |
+
num_vectors = 10
|
| 209 |
+
topk = 2
|
| 210 |
+
r = 4
|
| 211 |
+
config = VBLoRAConfig(
|
| 212 |
+
target_modules=["lin0", "lin1"],
|
| 213 |
+
vector_length=vector_length,
|
| 214 |
+
num_vectors=num_vectors,
|
| 215 |
+
topk=topk,
|
| 216 |
+
r=r,
|
| 217 |
+
save_only_topk_weights=True,
|
| 218 |
+
)
|
| 219 |
+
mlp_vblora = get_peft_model(mlp, config)
|
| 220 |
+
|
| 221 |
+
mlp_vblora.lin3.requires_grad_(True) # set lin3 to trainable
|
| 222 |
+
|
| 223 |
+
adapter_params, other_params = mlp_vblora.get_nb_savable_parameters()
|
| 224 |
+
factor = 0.25 # dtype of index is uint8
|
| 225 |
+
topk_indices_parameter = int(
|
| 226 |
+
(mlp.lin0.out_features + mlp.lin0.in_features + mlp.lin1.out_features + mlp.lin1.in_features)
|
| 227 |
+
/ vector_length
|
| 228 |
+
* r
|
| 229 |
+
* topk
|
| 230 |
+
* factor
|
| 231 |
+
)
|
| 232 |
+
topk_weights_parameter = int(
|
| 233 |
+
(mlp.lin0.out_features + mlp.lin0.in_features + mlp.lin1.out_features + mlp.lin1.in_features)
|
| 234 |
+
/ vector_length
|
| 235 |
+
* r
|
| 236 |
+
* (topk - 1)
|
| 237 |
+
)
|
| 238 |
+
vector_bank_parameter = num_vectors * vector_length
|
| 239 |
+
assert adapter_params == topk_indices_parameter + topk_weights_parameter + vector_bank_parameter
|
| 240 |
+
assert other_params == (mlp.lin3.in_features + 1) * mlp.lin3.out_features
|
| 241 |
+
|
| 242 |
+
def test_vblora_nb_savable_params_all_logits(self):
|
| 243 |
+
mlp = self.get_mlp()
|
| 244 |
+
vector_length = 2
|
| 245 |
+
num_vectors = 10
|
| 246 |
+
topk = 2
|
| 247 |
+
r = 4
|
| 248 |
+
config = VBLoRAConfig(
|
| 249 |
+
target_modules=["lin0", "lin1"],
|
| 250 |
+
vector_length=vector_length,
|
| 251 |
+
num_vectors=num_vectors,
|
| 252 |
+
topk=topk,
|
| 253 |
+
r=r,
|
| 254 |
+
save_only_topk_weights=False,
|
| 255 |
+
)
|
| 256 |
+
mlp_vblora = get_peft_model(mlp, config)
|
| 257 |
+
|
| 258 |
+
mlp_vblora.lin3.requires_grad_(True) # set lin3 to trainable
|
| 259 |
+
|
| 260 |
+
adapter_params, other_params = mlp_vblora.get_nb_savable_parameters()
|
| 261 |
+
logits_parameter = int(
|
| 262 |
+
(mlp.lin0.out_features + mlp.lin0.in_features + mlp.lin1.out_features + mlp.lin1.in_features)
|
| 263 |
+
/ vector_length
|
| 264 |
+
* r
|
| 265 |
+
* num_vectors
|
| 266 |
+
)
|
| 267 |
+
vector_bank_parameter = num_vectors * vector_length
|
| 268 |
+
assert adapter_params == logits_parameter + vector_bank_parameter
|
| 269 |
+
assert other_params == (mlp.lin3.in_features + 1) * mlp.lin3.out_features
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_vera.py
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# This test file is for tests specific to VeRA, since VeRA has some specific challenges due to the shared weights.
|
| 16 |
+
|
| 17 |
+
import os
|
| 18 |
+
|
| 19 |
+
import pytest
|
| 20 |
+
import torch
|
| 21 |
+
from accelerate.utils.imports import is_bf16_available
|
| 22 |
+
from safetensors import safe_open
|
| 23 |
+
from torch import nn
|
| 24 |
+
|
| 25 |
+
from peft import PeftModel, VeraConfig, get_peft_model
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class MLP(nn.Module):
|
| 29 |
+
def __init__(self, bias=True):
|
| 30 |
+
super().__init__()
|
| 31 |
+
self.relu = nn.ReLU()
|
| 32 |
+
self.lin0 = nn.Linear(10, 20, bias=bias)
|
| 33 |
+
self.lin1 = nn.Linear(20, 20, bias=bias) # lin1 and lin2 have same shape
|
| 34 |
+
self.lin2 = nn.Linear(20, 20, bias=bias)
|
| 35 |
+
self.lin3 = nn.Linear(20, 2, bias=bias)
|
| 36 |
+
self.sm = nn.LogSoftmax(dim=-1)
|
| 37 |
+
|
| 38 |
+
def forward(self, X):
|
| 39 |
+
X = self.lin0(X)
|
| 40 |
+
X = self.relu(X)
|
| 41 |
+
X = self.lin1(X)
|
| 42 |
+
X = self.relu(X)
|
| 43 |
+
X = self.lin2(X)
|
| 44 |
+
X = self.relu(X)
|
| 45 |
+
X = self.lin3(X)
|
| 46 |
+
X = self.sm(X)
|
| 47 |
+
return X
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
class TestVera:
|
| 51 |
+
@pytest.fixture
|
| 52 |
+
def mlp(self):
|
| 53 |
+
torch.manual_seed(0)
|
| 54 |
+
model = MLP()
|
| 55 |
+
return model
|
| 56 |
+
|
| 57 |
+
@pytest.fixture
|
| 58 |
+
def mlp_same_prng(self, mlp):
|
| 59 |
+
torch.manual_seed(0)
|
| 60 |
+
|
| 61 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 62 |
+
# creates a default VeRA adapter
|
| 63 |
+
peft_model = get_peft_model(mlp, config)
|
| 64 |
+
config2 = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 65 |
+
peft_model.add_adapter("other", config2)
|
| 66 |
+
return peft_model
|
| 67 |
+
|
| 68 |
+
def test_multiple_adapters_same_prng_weights(self, mlp_same_prng):
|
| 69 |
+
# we can have multiple adapters with the same prng key, in which case the weights should be shared
|
| 70 |
+
assert (
|
| 71 |
+
mlp_same_prng.base_model.model.lin1.vera_A["default"]
|
| 72 |
+
is mlp_same_prng.base_model.model.lin1.vera_A["other"]
|
| 73 |
+
)
|
| 74 |
+
assert (
|
| 75 |
+
mlp_same_prng.base_model.model.lin1.vera_B["default"]
|
| 76 |
+
is mlp_same_prng.base_model.model.lin1.vera_B["other"]
|
| 77 |
+
)
|
| 78 |
+
assert (
|
| 79 |
+
mlp_same_prng.base_model.model.lin2.vera_A["default"]
|
| 80 |
+
is mlp_same_prng.base_model.model.lin2.vera_A["other"]
|
| 81 |
+
)
|
| 82 |
+
assert (
|
| 83 |
+
mlp_same_prng.base_model.model.lin2.vera_B["default"]
|
| 84 |
+
is mlp_same_prng.base_model.model.lin2.vera_B["other"]
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
input = torch.randn(5, 10)
|
| 88 |
+
mlp_same_prng.set_adapter("default")
|
| 89 |
+
output_default = mlp_same_prng(input)
|
| 90 |
+
mlp_same_prng.set_adapter("other")
|
| 91 |
+
output_other = mlp_same_prng(input)
|
| 92 |
+
assert not torch.allclose(output_default, output_other, atol=1e-3, rtol=1e-3)
|
| 93 |
+
|
| 94 |
+
def test_multiple_adapters_different_prng_raises(self):
|
| 95 |
+
# we cannot have multiple adapters with different prng keys
|
| 96 |
+
model = MLP()
|
| 97 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 98 |
+
# creates a default VeRA adapter
|
| 99 |
+
peft_model = get_peft_model(model, config)
|
| 100 |
+
config2 = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, projection_prng_key=123)
|
| 101 |
+
|
| 102 |
+
msg = (
|
| 103 |
+
r"Vera PRNG initialisation key must be the same for all adapters. Got config.projection_prng_key=123 but "
|
| 104 |
+
r"previous config had 0"
|
| 105 |
+
)
|
| 106 |
+
with pytest.raises(ValueError, match=msg):
|
| 107 |
+
peft_model.add_adapter("other", config2)
|
| 108 |
+
|
| 109 |
+
def test_multiple_adapters_save_load_save_projection_true(self, mlp_same_prng, tmp_path):
|
| 110 |
+
# check saving and loading works with multiple adapters and saved projection weights
|
| 111 |
+
torch.manual_seed(0)
|
| 112 |
+
input = torch.randn(5, 10)
|
| 113 |
+
mlp_same_prng.set_adapter("default")
|
| 114 |
+
output_default = mlp_same_prng(input)
|
| 115 |
+
mlp_same_prng.set_adapter("other")
|
| 116 |
+
output_other = mlp_same_prng(input)
|
| 117 |
+
|
| 118 |
+
# sanity check
|
| 119 |
+
assert not torch.allclose(output_default, output_other, atol=1e-3, rtol=1e-3)
|
| 120 |
+
|
| 121 |
+
save_path = tmp_path / "vera"
|
| 122 |
+
mlp_same_prng.save_pretrained(save_path)
|
| 123 |
+
assert os.path.exists(save_path / "adapter_config.json")
|
| 124 |
+
assert os.path.exists(save_path / "other" / "adapter_config.json")
|
| 125 |
+
|
| 126 |
+
torch.manual_seed(0)
|
| 127 |
+
mlp = MLP()
|
| 128 |
+
peft_model = PeftModel.from_pretrained(mlp, save_path)
|
| 129 |
+
peft_model.load_adapter(save_path / "other", "other")
|
| 130 |
+
|
| 131 |
+
peft_model.set_adapter("default")
|
| 132 |
+
output_default_loaded = peft_model(input)
|
| 133 |
+
peft_model.set_adapter("other")
|
| 134 |
+
output_other_loaded = peft_model(input)
|
| 135 |
+
|
| 136 |
+
assert torch.allclose(output_default, output_default_loaded, atol=1e-3, rtol=1e-3)
|
| 137 |
+
assert torch.allclose(output_other, output_other_loaded, atol=1e-3, rtol=1e-3)
|
| 138 |
+
|
| 139 |
+
def test_multiple_adapters_save_load_save_projection_false(self, mlp, tmp_path):
|
| 140 |
+
# check saving and loading works with multiple adapters without saved projection weights
|
| 141 |
+
torch.manual_seed(1)
|
| 142 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 143 |
+
# creates a default VeRA adapter
|
| 144 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 145 |
+
config2 = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 146 |
+
peft_model.add_adapter("second", config2)
|
| 147 |
+
|
| 148 |
+
input = torch.randn(5, 10)
|
| 149 |
+
peft_model.set_adapter("first")
|
| 150 |
+
output_first = peft_model(input)
|
| 151 |
+
peft_model.set_adapter("second")
|
| 152 |
+
output_second = peft_model(input)
|
| 153 |
+
|
| 154 |
+
# sanity check
|
| 155 |
+
assert not torch.allclose(output_first, output_second, atol=1e-3, rtol=1e-3)
|
| 156 |
+
|
| 157 |
+
save_path = tmp_path / "vera"
|
| 158 |
+
peft_model.save_pretrained(save_path)
|
| 159 |
+
assert os.path.exists(save_path / "first" / "adapter_config.json")
|
| 160 |
+
assert os.path.exists(save_path / "second" / "adapter_config.json")
|
| 161 |
+
|
| 162 |
+
torch.manual_seed(0)
|
| 163 |
+
mlp = MLP()
|
| 164 |
+
peft_model = PeftModel.from_pretrained(mlp, save_path / "first", adapter_name="first")
|
| 165 |
+
peft_model.load_adapter(save_path / "second", "second")
|
| 166 |
+
|
| 167 |
+
peft_model.set_adapter("first")
|
| 168 |
+
output_first_loaded = peft_model(input)
|
| 169 |
+
peft_model.set_adapter("second")
|
| 170 |
+
output_second_loaded = peft_model(input)
|
| 171 |
+
|
| 172 |
+
assert torch.allclose(output_first, output_first_loaded, atol=1e-3, rtol=1e-3)
|
| 173 |
+
assert torch.allclose(output_second, output_second_loaded, atol=1e-3, rtol=1e-3)
|
| 174 |
+
|
| 175 |
+
def test_multiple_adapters_save_projection_true_contains_vera_A_vera_B(self, mlp_same_prng, tmp_path):
|
| 176 |
+
# check that the state_dicts don't contain the projection weights
|
| 177 |
+
save_path = tmp_path / "vera"
|
| 178 |
+
mlp_same_prng.save_pretrained(save_path)
|
| 179 |
+
|
| 180 |
+
sd_default = {}
|
| 181 |
+
with safe_open(save_path / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 182 |
+
for key in f.keys():
|
| 183 |
+
sd_default[key] = f.get_tensor(key)
|
| 184 |
+
|
| 185 |
+
assert any("vera_A" in key for key in sd_default)
|
| 186 |
+
assert any("vera_B" in key for key in sd_default)
|
| 187 |
+
# default rank for VeRA is 256
|
| 188 |
+
assert sd_default["base_model.vera_A"].shape == (256, 20)
|
| 189 |
+
assert sd_default["base_model.vera_B"].shape == (20, 256)
|
| 190 |
+
|
| 191 |
+
sd_other = {}
|
| 192 |
+
with safe_open(save_path / "other" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 193 |
+
for key in f.keys():
|
| 194 |
+
sd_other[key] = f.get_tensor(key)
|
| 195 |
+
|
| 196 |
+
assert any("vera_A" in key for key in sd_other)
|
| 197 |
+
assert any("vera_B" in key for key in sd_other)
|
| 198 |
+
assert sd_other["base_model.vera_A"].shape == (256, 20)
|
| 199 |
+
assert sd_other["base_model.vera_B"].shape == (20, 256)
|
| 200 |
+
|
| 201 |
+
def test_multiple_adapters_save_projection_false_contains_no_vera_A_vera_B(self, mlp, tmp_path):
|
| 202 |
+
torch.manual_seed(1)
|
| 203 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 204 |
+
# creates a default VeRA adapter
|
| 205 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 206 |
+
config2 = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 207 |
+
peft_model.add_adapter("second", config2)
|
| 208 |
+
|
| 209 |
+
save_path = tmp_path / "vera"
|
| 210 |
+
peft_model.save_pretrained(save_path)
|
| 211 |
+
|
| 212 |
+
sd_default = {}
|
| 213 |
+
with safe_open(save_path / "first" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 214 |
+
for key in f.keys():
|
| 215 |
+
sd_default[key] = f.get_tensor(key)
|
| 216 |
+
|
| 217 |
+
assert not any("vera_A" in key for key in sd_default)
|
| 218 |
+
assert not any("vera_B" in key for key in sd_default)
|
| 219 |
+
|
| 220 |
+
sd_other = {}
|
| 221 |
+
with safe_open(save_path / "second" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 222 |
+
for key in f.keys():
|
| 223 |
+
sd_other[key] = f.get_tensor(key)
|
| 224 |
+
|
| 225 |
+
assert not any("vera_A" in key for key in sd_other)
|
| 226 |
+
assert not any("vera_B" in key for key in sd_other)
|
| 227 |
+
|
| 228 |
+
def test_vera_A_vera_B_share_memory(self, mlp_same_prng):
|
| 229 |
+
vera_A = mlp_same_prng.vera_A["default"]
|
| 230 |
+
vera_B = mlp_same_prng.vera_B["default"]
|
| 231 |
+
|
| 232 |
+
# these tensors should share the same data
|
| 233 |
+
assert vera_A.data_ptr() == mlp_same_prng.base_model.model.lin1.vera_A["default"].data_ptr()
|
| 234 |
+
assert vera_B.data_ptr() == mlp_same_prng.base_model.model.lin1.vera_B["default"].data_ptr()
|
| 235 |
+
assert vera_A.data_ptr() == mlp_same_prng.base_model.model.lin2.vera_A["default"].data_ptr()
|
| 236 |
+
assert vera_B.data_ptr() == mlp_same_prng.base_model.model.lin2.vera_B["default"].data_ptr()
|
| 237 |
+
# sanity check: these tensors shouldn't share the same data
|
| 238 |
+
assert vera_A.data_ptr() != vera_B.data_ptr()
|
| 239 |
+
|
| 240 |
+
def test_vera_lambda_dont_share_memory(self, mlp_same_prng):
|
| 241 |
+
# sanity check: these tensors shouldn't share the same data
|
| 242 |
+
assert (
|
| 243 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_b["default"].data_ptr()
|
| 244 |
+
!= mlp_same_prng.base_model.model.lin1.vera_lambda_b["other"].data_ptr()
|
| 245 |
+
)
|
| 246 |
+
assert (
|
| 247 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_b["default"].data_ptr()
|
| 248 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_b["default"].data_ptr()
|
| 249 |
+
)
|
| 250 |
+
assert (
|
| 251 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_b["other"].data_ptr()
|
| 252 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_b["other"].data_ptr()
|
| 253 |
+
)
|
| 254 |
+
assert (
|
| 255 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_d["default"].data_ptr()
|
| 256 |
+
!= mlp_same_prng.base_model.model.lin1.vera_lambda_d["other"].data_ptr()
|
| 257 |
+
)
|
| 258 |
+
assert (
|
| 259 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_d["default"].data_ptr()
|
| 260 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_d["default"].data_ptr()
|
| 261 |
+
)
|
| 262 |
+
assert (
|
| 263 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_d["other"].data_ptr()
|
| 264 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_d["other"].data_ptr()
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
def test_vera_different_shapes(self, mlp):
|
| 268 |
+
config = VeraConfig(target_modules=["lin0", "lin3"], init_weights=False)
|
| 269 |
+
mlp_different_shapes = get_peft_model(mlp, config)
|
| 270 |
+
|
| 271 |
+
vera_A = mlp_different_shapes.vera_A["default"]
|
| 272 |
+
vera_B = mlp_different_shapes.vera_B["default"]
|
| 273 |
+
|
| 274 |
+
# sanity check
|
| 275 |
+
assert mlp.lin0.base_layer.weight.shape != mlp.lin3.base_layer.weight.shape
|
| 276 |
+
|
| 277 |
+
# lin0 has the largest output dimension, lin3 has the largest input dimension
|
| 278 |
+
# vera_A should have the shape of (rank, largest_in), vera_B should have the shape of (largest_out, rank)
|
| 279 |
+
assert vera_A.shape == (config.r, mlp.lin3.in_features)
|
| 280 |
+
assert vera_B.shape == (mlp.lin0.out_features, config.r)
|
| 281 |
+
|
| 282 |
+
# should not raise
|
| 283 |
+
input = torch.randn(5, 10)
|
| 284 |
+
mlp_different_shapes(input)
|
| 285 |
+
|
| 286 |
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
| 287 |
+
def test_vera_dtypes(self, dtype):
|
| 288 |
+
if dtype == torch.bfloat16:
|
| 289 |
+
# skip if bf16 is not supported on hardware, see #1872
|
| 290 |
+
if not is_bf16_available():
|
| 291 |
+
pytest.skip("bfloat16 not supported on this system, skipping the test")
|
| 292 |
+
|
| 293 |
+
model = MLP().to(dtype)
|
| 294 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 295 |
+
peft_model = get_peft_model(model, config)
|
| 296 |
+
inputs = torch.randn(5, 10).to(dtype)
|
| 297 |
+
output = peft_model(inputs) # should not raise
|
| 298 |
+
assert output.dtype == dtype
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_vision_models.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2024-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# This is not a full on test suite of vision models, since we already run many tests on dummy models with Conv2d layers
|
| 16 |
+
# and on stable diffusion models. Instead, this file contains specific tests for bugs that have been found in the past.
|
| 17 |
+
import gc
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pytest
|
| 21 |
+
import torch
|
| 22 |
+
from accelerate.utils.memory import clear_device_cache
|
| 23 |
+
from safetensors.torch import load_file
|
| 24 |
+
from transformers import (
|
| 25 |
+
AutoImageProcessor,
|
| 26 |
+
AutoModelForImageClassification,
|
| 27 |
+
AutoProcessor,
|
| 28 |
+
LlavaForConditionalGeneration,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
from peft import (
|
| 32 |
+
BOFTConfig,
|
| 33 |
+
HRAConfig,
|
| 34 |
+
LoHaConfig,
|
| 35 |
+
LoKrConfig,
|
| 36 |
+
LoraConfig,
|
| 37 |
+
OFTConfig,
|
| 38 |
+
PeftModel,
|
| 39 |
+
PrefixTuningConfig,
|
| 40 |
+
get_peft_model,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
from .testing_utils import load_cat_image
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
CONFIGS = {
|
| 47 |
+
"lora": LoraConfig(target_modules=["convolution"], modules_to_save=["classifier", "normalization"]),
|
| 48 |
+
"loha": LoHaConfig(target_modules=["convolution"], modules_to_save=["classifier", "normalization"]),
|
| 49 |
+
"lokr": LoKrConfig(target_modules=["convolution"], modules_to_save=["classifier", "normalization"]),
|
| 50 |
+
"oft": OFTConfig(
|
| 51 |
+
r=1, oft_block_size=0, target_modules=["convolution"], modules_to_save=["classifier", "normalization"]
|
| 52 |
+
),
|
| 53 |
+
"hra": HRAConfig(target_modules=["convolution"], modules_to_save=["classifier", "normalization"]),
|
| 54 |
+
# Cannot target multiple layers with BOFT because some convolutional kernel dimensions vary and there is no common
|
| 55 |
+
# denominator for the boft_block_size except 1, but using 1 results in an error in the fbd_cuda kernel:
|
| 56 |
+
# > Error in forward_fast_block_diag_cuda_kernel: an illegal memory access was encountered
|
| 57 |
+
"boft": BOFTConfig(
|
| 58 |
+
target_modules=["0.layer.0.convolution"], modules_to_save=["classifier", "normalization"], boft_block_size=2
|
| 59 |
+
),
|
| 60 |
+
}
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
# Ensure that models like Llava that pass past_key_values automatically do not fail, see #1938
|
| 64 |
+
class TestPastKV:
|
| 65 |
+
def test_past_kv(self):
|
| 66 |
+
model_id = "peft-internal-testing/tiny-LlavaForConditionalGeneration"
|
| 67 |
+
prompt = "USER: <image>\nWhat are these?\nASSISTANT:"
|
| 68 |
+
|
| 69 |
+
# prepare model and inputs
|
| 70 |
+
model = LlavaForConditionalGeneration.from_pretrained(
|
| 71 |
+
model_id,
|
| 72 |
+
low_cpu_mem_usage=True,
|
| 73 |
+
)
|
| 74 |
+
processor = AutoProcessor.from_pretrained(model_id)
|
| 75 |
+
raw_image = np.random.randint(0, 255, (224, 224, 3), dtype=np.uint8)
|
| 76 |
+
inputs = processor(text=prompt, images=raw_image, return_tensors="pt")
|
| 77 |
+
|
| 78 |
+
# get peft model
|
| 79 |
+
peft_config = PrefixTuningConfig(task_type="CAUSAL_LM", num_virtual_tokens=20)
|
| 80 |
+
model = get_peft_model(model, peft_config)
|
| 81 |
+
# check that this does not raise
|
| 82 |
+
model(**inputs, output_hidden_states=True)
|
| 83 |
+
|
| 84 |
+
|
| 85 |
+
class TestResnet:
|
| 86 |
+
# saftensors version of the hf-internal-testing model
|
| 87 |
+
model_id = "peft-internal-testing/tiny-random-ResNetForImageClassification"
|
| 88 |
+
cat_image = load_cat_image() # for caching
|
| 89 |
+
|
| 90 |
+
@pytest.fixture(autouse=True)
|
| 91 |
+
def teardown(self):
|
| 92 |
+
r"""
|
| 93 |
+
Efficient mechanism to free GPU memory after each test. Based on
|
| 94 |
+
https://github.com/huggingface/transformers/issues/21094
|
| 95 |
+
"""
|
| 96 |
+
clear_device_cache(garbage_collection=True)
|
| 97 |
+
gc.collect()
|
| 98 |
+
|
| 99 |
+
@pytest.fixture(scope="class")
|
| 100 |
+
def image_processor(self):
|
| 101 |
+
image_processor = AutoImageProcessor.from_pretrained(self.model_id)
|
| 102 |
+
return image_processor
|
| 103 |
+
|
| 104 |
+
@pytest.fixture(scope="class")
|
| 105 |
+
def data(self, image_processor):
|
| 106 |
+
return image_processor(self.cat_image, return_tensors="pt")
|
| 107 |
+
|
| 108 |
+
@pytest.mark.parametrize("config", CONFIGS.values(), ids=CONFIGS.keys())
|
| 109 |
+
def test_model_with_batchnorm_reproducibility(self, config, tmp_path, data):
|
| 110 |
+
# see 1732
|
| 111 |
+
torch.manual_seed(0)
|
| 112 |
+
model = AutoModelForImageClassification.from_pretrained(self.model_id)
|
| 113 |
+
model = get_peft_model(model, config)
|
| 114 |
+
|
| 115 |
+
# record outputs before training
|
| 116 |
+
model.eval()
|
| 117 |
+
with torch.inference_mode():
|
| 118 |
+
output_before = model(**data)
|
| 119 |
+
model.train()
|
| 120 |
+
|
| 121 |
+
# train the model
|
| 122 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 123 |
+
batch_size = 4
|
| 124 |
+
max_steps = 5 * batch_size
|
| 125 |
+
labels = torch.zeros(1, 3)
|
| 126 |
+
labels[0, 1] = 1
|
| 127 |
+
for i in range(0, max_steps, batch_size):
|
| 128 |
+
optimizer.zero_grad()
|
| 129 |
+
outputs = model(**data, labels=labels)
|
| 130 |
+
loss = outputs.loss
|
| 131 |
+
loss.backward()
|
| 132 |
+
optimizer.step()
|
| 133 |
+
|
| 134 |
+
# record outputs after training
|
| 135 |
+
model.eval()
|
| 136 |
+
with torch.inference_mode():
|
| 137 |
+
output_after = model(**data)
|
| 138 |
+
assert torch.isfinite(output_after.logits).all()
|
| 139 |
+
atol, rtol = 1e-4, 1e-4
|
| 140 |
+
# sanity check: model was updated
|
| 141 |
+
assert not torch.allclose(output_before.logits, output_after.logits, atol=atol, rtol=rtol)
|
| 142 |
+
|
| 143 |
+
# check saving the model and loading it
|
| 144 |
+
model.save_pretrained(tmp_path)
|
| 145 |
+
del model
|
| 146 |
+
|
| 147 |
+
torch.manual_seed(0)
|
| 148 |
+
model = AutoModelForImageClassification.from_pretrained(self.model_id)
|
| 149 |
+
model = PeftModel.from_pretrained(model, tmp_path).eval()
|
| 150 |
+
with torch.inference_mode():
|
| 151 |
+
output_loaded = model(**data)
|
| 152 |
+
assert torch.allclose(output_after.logits, output_loaded.logits, atol=atol, rtol=rtol)
|
| 153 |
+
|
| 154 |
+
# ensure that the checkpoint file contains the buffers
|
| 155 |
+
model_running_mean = len([k for k in model.state_dict().keys() if "running_mean" in k])
|
| 156 |
+
state_dict = load_file(tmp_path / "adapter_model.safetensors")
|
| 157 |
+
checkpoint_running_mean = len([k for k in state_dict.keys() if "running_mean" in k])
|
| 158 |
+
# note that the model has twice as many "running_mean", as there is one copy per ModulesToSaveWrapper, we need
|
| 159 |
+
# to multiply by 2 to get the same number
|
| 160 |
+
assert model_running_mean == checkpoint_running_mean * 2
|
tasks/tasksmith-955732fda55e/tests/source/tests/test_xlora.py
ADDED
|
@@ -0,0 +1,473 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import os
|
| 16 |
+
from functools import wraps
|
| 17 |
+
|
| 18 |
+
import huggingface_hub
|
| 19 |
+
import pytest
|
| 20 |
+
import torch
|
| 21 |
+
from safetensors.torch import load_file
|
| 22 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 23 |
+
|
| 24 |
+
from peft import LoraConfig, PeftType, TaskType, XLoraConfig, get_peft_model
|
| 25 |
+
from peft.peft_model import PeftModel
|
| 26 |
+
from peft.tuners.xlora.layer import XLoraLayer
|
| 27 |
+
from peft.utils import infer_device
|
| 28 |
+
|
| 29 |
+
from .testing_utils import hub_online_once
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def flaky(num_tries: int):
|
| 33 |
+
"""Decorator for test functions that are flaky"""
|
| 34 |
+
|
| 35 |
+
def decorator(func):
|
| 36 |
+
@wraps(func)
|
| 37 |
+
def wrapper(*args, **kwargs):
|
| 38 |
+
for _ in range(num_tries):
|
| 39 |
+
try:
|
| 40 |
+
return func(*args, **kwargs)
|
| 41 |
+
except AssertionError as e:
|
| 42 |
+
print(f"Failed test {func.__name__} with error: {e}")
|
| 43 |
+
continue
|
| 44 |
+
raise AssertionError(f"Failed test {func.__name__} after {num_tries} tries")
|
| 45 |
+
|
| 46 |
+
return wrapper
|
| 47 |
+
|
| 48 |
+
return decorator
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
class TestXlora:
|
| 52 |
+
torch_device = infer_device()
|
| 53 |
+
|
| 54 |
+
model_id = "peft-internal-testing/opt-125m"
|
| 55 |
+
num_loras = 4
|
| 56 |
+
|
| 57 |
+
@pytest.fixture(scope="class")
|
| 58 |
+
def lora_dir(self, tmp_path_factory):
|
| 59 |
+
return tmp_path_factory.mktemp("lora")
|
| 60 |
+
|
| 61 |
+
@pytest.fixture(scope="class")
|
| 62 |
+
def lora_embedding_dir(self, tmp_path_factory):
|
| 63 |
+
return tmp_path_factory.mktemp("lora_embedding")
|
| 64 |
+
|
| 65 |
+
@pytest.fixture(scope="class")
|
| 66 |
+
def saved_lora_adapters(self, lora_dir):
|
| 67 |
+
file_names = []
|
| 68 |
+
|
| 69 |
+
lora_configs = [
|
| 70 |
+
LoraConfig(task_type="CAUSAL_LM", target_modules=["q_proj", "v_proj"], init_lora_weights=False)
|
| 71 |
+
for _ in range(self.num_loras)
|
| 72 |
+
]
|
| 73 |
+
# have 1 LoRA with different target modules
|
| 74 |
+
lora_configs[-1] = LoraConfig(
|
| 75 |
+
task_type="CAUSAL_LM", target_modules=["k_proj", "q_proj", "v_proj"], init_lora_weights=False
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
for i, lora_config in enumerate(lora_configs, start=1):
|
| 79 |
+
torch.manual_seed(i)
|
| 80 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 81 |
+
peft_model = get_peft_model(model, lora_config)
|
| 82 |
+
file_name = os.path.join(lora_dir, f"checkpoint-{i}")
|
| 83 |
+
peft_model.save_pretrained(file_name)
|
| 84 |
+
file_names.append(file_name)
|
| 85 |
+
return file_names
|
| 86 |
+
|
| 87 |
+
@pytest.fixture(scope="class")
|
| 88 |
+
def saved_lora_embedding_adapters(self, lora_embedding_dir):
|
| 89 |
+
file_names = []
|
| 90 |
+
for i in range(1, self.num_loras + 1):
|
| 91 |
+
torch.manual_seed(i)
|
| 92 |
+
lora_config = LoraConfig(task_type="CAUSAL_LM", init_lora_weights=False, target_modules=["embed_tokens"])
|
| 93 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 94 |
+
peft_model = get_peft_model(model, lora_config)
|
| 95 |
+
file_name = os.path.join(lora_embedding_dir, f"checkpoint-{i}")
|
| 96 |
+
peft_model.save_pretrained(file_name)
|
| 97 |
+
file_names.append(file_name)
|
| 98 |
+
return file_names
|
| 99 |
+
|
| 100 |
+
@pytest.fixture(scope="class")
|
| 101 |
+
def tokenizer(self):
|
| 102 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_id, trust_remote_code=True, device_map=self.torch_device)
|
| 103 |
+
return tokenizer
|
| 104 |
+
|
| 105 |
+
@pytest.fixture(scope="function")
|
| 106 |
+
def embedding_model(self, saved_lora_embedding_adapters):
|
| 107 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 108 |
+
model.config.use_cache = False
|
| 109 |
+
adapters = {str(i): file_name for i, file_name in enumerate(saved_lora_embedding_adapters)}
|
| 110 |
+
|
| 111 |
+
peft_config = XLoraConfig(
|
| 112 |
+
task_type=TaskType.CAUSAL_LM,
|
| 113 |
+
peft_type=PeftType.XLORA,
|
| 114 |
+
hidden_size=model.config.hidden_size,
|
| 115 |
+
xlora_depth=8,
|
| 116 |
+
adapters=adapters,
|
| 117 |
+
)
|
| 118 |
+
model = get_peft_model(model, peft_config).to(self.torch_device)
|
| 119 |
+
return model
|
| 120 |
+
|
| 121 |
+
@pytest.fixture(scope="function")
|
| 122 |
+
def model(self, saved_lora_adapters):
|
| 123 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 124 |
+
model.config.use_cache = False
|
| 125 |
+
adapters = {str(i): file_name for i, file_name in enumerate(saved_lora_adapters)}
|
| 126 |
+
|
| 127 |
+
peft_config = XLoraConfig(
|
| 128 |
+
task_type=TaskType.CAUSAL_LM,
|
| 129 |
+
peft_type=PeftType.XLORA,
|
| 130 |
+
hidden_size=model.config.hidden_size,
|
| 131 |
+
xlora_depth=8,
|
| 132 |
+
adapters=adapters,
|
| 133 |
+
)
|
| 134 |
+
model = get_peft_model(model, peft_config).to(self.torch_device)
|
| 135 |
+
return model
|
| 136 |
+
|
| 137 |
+
@pytest.fixture(scope="function")
|
| 138 |
+
def model_layerwise(self, saved_lora_adapters):
|
| 139 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 140 |
+
model.config.use_cache = False
|
| 141 |
+
adapters = {str(i): file_name for i, file_name in enumerate(saved_lora_adapters)}
|
| 142 |
+
|
| 143 |
+
peft_config = XLoraConfig(
|
| 144 |
+
task_type=TaskType.CAUSAL_LM,
|
| 145 |
+
peft_type=PeftType.XLORA,
|
| 146 |
+
hidden_size=model.config.hidden_size,
|
| 147 |
+
xlora_depth=8,
|
| 148 |
+
adapters=adapters,
|
| 149 |
+
layerwise_scalings=True,
|
| 150 |
+
)
|
| 151 |
+
model = get_peft_model(model, peft_config).to(self.torch_device)
|
| 152 |
+
return model
|
| 153 |
+
|
| 154 |
+
def test_functional(self, tokenizer, model):
|
| 155 |
+
model.enable_scalings_logging()
|
| 156 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 157 |
+
outputs = model.generate(
|
| 158 |
+
input_ids=inputs.to(self.torch_device),
|
| 159 |
+
max_new_tokens=32,
|
| 160 |
+
)
|
| 161 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 162 |
+
|
| 163 |
+
def test_forward_hooks_are_cleaned_up(self, tokenizer, model):
|
| 164 |
+
# There was an issue that forward hooks would accumulate during generation, since one hook per forward step was
|
| 165 |
+
# being registered and generate would call forward multiple times. This is already undesirable, but to make it
|
| 166 |
+
# worse, only the last hook was removed, resulting in hooks accumulating.
|
| 167 |
+
# See https://github.com/huggingface/peft/issues/1472#issuecomment-3235817807
|
| 168 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 169 |
+
model.generate(input_ids=inputs.to(self.torch_device), max_new_tokens=10)
|
| 170 |
+
num_hooks_gen1 = len(model.base_model.model.model.decoder.layers[0].self_attn.k_proj._forward_pre_hooks)
|
| 171 |
+
|
| 172 |
+
model.generate(input_ids=inputs.to(self.torch_device), max_new_tokens=10)
|
| 173 |
+
num_hooks_gen2 = len(model.base_model.model.model.decoder.layers[0].self_attn.k_proj._forward_pre_hooks)
|
| 174 |
+
assert num_hooks_gen1 == num_hooks_gen2 == 0
|
| 175 |
+
|
| 176 |
+
def test_scalings_logging_methods(self, tokenizer, model):
|
| 177 |
+
model.enable_scalings_logging()
|
| 178 |
+
|
| 179 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 180 |
+
outputs = model.generate(
|
| 181 |
+
input_ids=inputs.to(self.torch_device),
|
| 182 |
+
max_new_tokens=32,
|
| 183 |
+
)
|
| 184 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 185 |
+
|
| 186 |
+
_ = model.get_latest_scalings()
|
| 187 |
+
# 32 is the numeber of max scalings. 3 is the number of prompt tokens.
|
| 188 |
+
assert 32 + 3 >= len(model.get_scalings_log()) > 0
|
| 189 |
+
|
| 190 |
+
model.disable_scalings_logging()
|
| 191 |
+
|
| 192 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 193 |
+
outputs = model.generate(
|
| 194 |
+
input_ids=inputs.to(self.torch_device),
|
| 195 |
+
max_new_tokens=32,
|
| 196 |
+
)
|
| 197 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 198 |
+
|
| 199 |
+
assert 32 >= len(model.get_scalings_log()) > 0
|
| 200 |
+
|
| 201 |
+
bucketed = model.get_bucketed_scalings_log()
|
| 202 |
+
keys = bucketed.keys()
|
| 203 |
+
# Once bucket for each token as we aren't using cache
|
| 204 |
+
assert len(bucketed) == 32 == len(keys)
|
| 205 |
+
seq_len = inputs.shape[1]
|
| 206 |
+
for key in keys:
|
| 207 |
+
assert len(bucketed[key][0]) == 1
|
| 208 |
+
assert len(bucketed[key][1]) == 1
|
| 209 |
+
assert bucketed[key][0][0] == key - seq_len
|
| 210 |
+
|
| 211 |
+
model.clear_scalings_log()
|
| 212 |
+
assert len(model.get_scalings_log()) == 0
|
| 213 |
+
|
| 214 |
+
def test_misc_methods(self, tokenizer, model):
|
| 215 |
+
model.set_global_scaling_weight(1.5)
|
| 216 |
+
assert model.internal_xlora_classifier.config.global_scaling_weight == 1.5
|
| 217 |
+
assert model.get_global_scaling_weight() == 1.5
|
| 218 |
+
|
| 219 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 220 |
+
outputs = model.generate(
|
| 221 |
+
input_ids=inputs.to(self.torch_device),
|
| 222 |
+
max_new_tokens=32,
|
| 223 |
+
)
|
| 224 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 225 |
+
|
| 226 |
+
assert str(model) is not None
|
| 227 |
+
|
| 228 |
+
# On CI (but not locally), this test is flaky since transformers v4.45.0.
|
| 229 |
+
@flaky(num_tries=5)
|
| 230 |
+
def test_save_load_functional(self, tokenizer, model, tmp_path):
|
| 231 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 232 |
+
outputs = model.generate(
|
| 233 |
+
input_ids=inputs.to(self.torch_device),
|
| 234 |
+
max_new_tokens=32,
|
| 235 |
+
)
|
| 236 |
+
before_logits = outputs[: inputs.shape[1] :]
|
| 237 |
+
assert torch.isfinite(before_logits).all()
|
| 238 |
+
|
| 239 |
+
model.save_pretrained(save_directory=tmp_path)
|
| 240 |
+
|
| 241 |
+
del model
|
| 242 |
+
|
| 243 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 244 |
+
model.config.use_cache = False
|
| 245 |
+
model = PeftModel.from_pretrained(model=model, model_id=tmp_path).to(self.torch_device)
|
| 246 |
+
|
| 247 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 248 |
+
outputs = model.generate(
|
| 249 |
+
input_ids=inputs.to(self.torch_device),
|
| 250 |
+
max_new_tokens=32,
|
| 251 |
+
)
|
| 252 |
+
after_logits = outputs[: inputs.shape[1] :]
|
| 253 |
+
assert torch.isfinite(after_logits).all()
|
| 254 |
+
assert torch.equal(after_logits, before_logits)
|
| 255 |
+
|
| 256 |
+
def test_save_load_functional_pt(self, tokenizer, model, tmp_path):
|
| 257 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 258 |
+
outputs = model.generate(
|
| 259 |
+
input_ids=inputs.to(self.torch_device),
|
| 260 |
+
max_new_tokens=32,
|
| 261 |
+
)
|
| 262 |
+
before_logits = outputs[: inputs.shape[1] :]
|
| 263 |
+
assert torch.isfinite(before_logits).all()
|
| 264 |
+
|
| 265 |
+
model.save_pretrained(save_directory=tmp_path, safe_serialization=False)
|
| 266 |
+
|
| 267 |
+
del model
|
| 268 |
+
|
| 269 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 270 |
+
model.config.use_cache = False
|
| 271 |
+
model = PeftModel.from_pretrained(model=model, model_id=tmp_path, safe_serialization=False).to(
|
| 272 |
+
self.torch_device
|
| 273 |
+
)
|
| 274 |
+
|
| 275 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 276 |
+
outputs = model.generate(
|
| 277 |
+
input_ids=inputs.to(self.torch_device),
|
| 278 |
+
max_new_tokens=32,
|
| 279 |
+
)
|
| 280 |
+
after_logits = outputs[: inputs.shape[1] :]
|
| 281 |
+
assert torch.isfinite(after_logits).all()
|
| 282 |
+
assert torch.equal(after_logits, before_logits), (after_logits, before_logits)
|
| 283 |
+
|
| 284 |
+
def test_topk_lora(self, tokenizer, model):
|
| 285 |
+
model.set_topk_lora(2)
|
| 286 |
+
assert model.internal_xlora_classifier.config.top_k_lora == 2
|
| 287 |
+
|
| 288 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 289 |
+
outputs = model.generate(
|
| 290 |
+
input_ids=inputs.to(self.torch_device),
|
| 291 |
+
max_new_tokens=32,
|
| 292 |
+
)
|
| 293 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 294 |
+
|
| 295 |
+
def test_softmax_topk(self, tokenizer, model):
|
| 296 |
+
# Just reach in to set the config
|
| 297 |
+
model.internal_xlora_classifier.config.top_k_lora = 2
|
| 298 |
+
model.internal_xlora_classifier.config.enable_softmax = False
|
| 299 |
+
model.internal_xlora_classifier.config.enable_softmax_topk = True
|
| 300 |
+
|
| 301 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 302 |
+
outputs = model.generate(
|
| 303 |
+
input_ids=inputs.to(self.torch_device),
|
| 304 |
+
max_new_tokens=32,
|
| 305 |
+
)
|
| 306 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 307 |
+
|
| 308 |
+
def test_set_override_scaling_pass_value(self, model):
|
| 309 |
+
# Defaults to 0
|
| 310 |
+
assert model.internal_xlora_classifier.override_scaling_pass_value == 0.0
|
| 311 |
+
|
| 312 |
+
# Set it to 2 and make sure it actually is
|
| 313 |
+
model.set_scaling_pass_value(2)
|
| 314 |
+
assert model.internal_xlora_classifier.override_scaling_pass_value == 2
|
| 315 |
+
assert model.internal_xlora_classifier.config.scaling_pass_value == 2
|
| 316 |
+
|
| 317 |
+
# Set it to None and make sure it is 1/n
|
| 318 |
+
model.set_scaling_pass_value(None)
|
| 319 |
+
assert model.internal_xlora_classifier.override_scaling_pass_value == 1 / self.num_loras
|
| 320 |
+
assert model.internal_xlora_classifier.config.scaling_pass_value == 1 / self.num_loras
|
| 321 |
+
|
| 322 |
+
def test_functional_layerwise(self, tokenizer, model_layerwise):
|
| 323 |
+
model_layerwise.enable_scalings_logging()
|
| 324 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 325 |
+
outputs = model_layerwise.generate(
|
| 326 |
+
input_ids=inputs.to(self.torch_device),
|
| 327 |
+
max_new_tokens=32,
|
| 328 |
+
)
|
| 329 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 330 |
+
|
| 331 |
+
def test_disable_adapter(self, tokenizer, model):
|
| 332 |
+
model.enable_scalings_logging()
|
| 333 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 334 |
+
with model.disable_adapter():
|
| 335 |
+
outputs_disabled = model.generate(
|
| 336 |
+
input_ids=inputs.to(self.torch_device),
|
| 337 |
+
max_new_tokens=32,
|
| 338 |
+
)
|
| 339 |
+
outputs = model.generate(
|
| 340 |
+
input_ids=inputs.to(self.torch_device),
|
| 341 |
+
max_new_tokens=32,
|
| 342 |
+
)
|
| 343 |
+
assert torch.isfinite(outputs_disabled[: inputs.shape[1] :]).all()
|
| 344 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 345 |
+
assert not torch.equal(outputs, outputs_disabled)
|
| 346 |
+
|
| 347 |
+
def test_functional_embedding(self, tokenizer, embedding_model):
|
| 348 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 349 |
+
outputs = embedding_model.generate(
|
| 350 |
+
input_ids=inputs.to(self.torch_device),
|
| 351 |
+
max_new_tokens=32,
|
| 352 |
+
)
|
| 353 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 354 |
+
|
| 355 |
+
def test_xlora_loading_valid(self):
|
| 356 |
+
# This test also simulatenously tests the loading-from-hub functionality!
|
| 357 |
+
torch.manual_seed(123)
|
| 358 |
+
|
| 359 |
+
model_id = "peft-internal-testing/opt-125m"
|
| 360 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 361 |
+
model.config.use_cache = False
|
| 362 |
+
|
| 363 |
+
adapters = [
|
| 364 |
+
"peft-internal-testing/opt-125m-dummy-lora",
|
| 365 |
+
"peft-internal-testing/opt-125m-dummy-lora",
|
| 366 |
+
]
|
| 367 |
+
adapters = {str(i): file_name for i, file_name in enumerate(adapters)}
|
| 368 |
+
|
| 369 |
+
peft_config = XLoraConfig(
|
| 370 |
+
task_type=TaskType.CAUSAL_LM,
|
| 371 |
+
peft_type=PeftType.XLORA,
|
| 372 |
+
hidden_size=model.config.hidden_size,
|
| 373 |
+
adapters=adapters,
|
| 374 |
+
xlora_depth=8,
|
| 375 |
+
xlora_size=2048,
|
| 376 |
+
layerwise_scalings=True,
|
| 377 |
+
xlora_dropout_p=0.2,
|
| 378 |
+
)
|
| 379 |
+
model = get_peft_model(model, peft_config)
|
| 380 |
+
|
| 381 |
+
downloaded = huggingface_hub.hf_hub_download(repo_id=adapters["0"], filename="adapter_model.safetensors")
|
| 382 |
+
sd = load_file(downloaded)
|
| 383 |
+
w0 = model.base_model.model.model.decoder.layers[0].self_attn.q_proj.lora_A["0"].weight
|
| 384 |
+
w1 = sd["base_model.model.model.decoder.layers.0.self_attn.q_proj.lora_A.weight"]
|
| 385 |
+
|
| 386 |
+
assert torch.allclose(w0, w1)
|
| 387 |
+
|
| 388 |
+
def test_scalings_storage(self, tokenizer, model):
|
| 389 |
+
model.enable_scalings_logging()
|
| 390 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 391 |
+
outputs = model.generate(
|
| 392 |
+
input_ids=inputs.to(self.torch_device),
|
| 393 |
+
max_new_tokens=10,
|
| 394 |
+
)
|
| 395 |
+
|
| 396 |
+
latest_scalings = model.get_latest_scalings()
|
| 397 |
+
assert latest_scalings is not None, "get_latest_scalings() should not return None after generation"
|
| 398 |
+
assert isinstance(latest_scalings, torch.Tensor)
|
| 399 |
+
assert torch.isfinite(latest_scalings).all(), "Scalings should contain finite values"
|
| 400 |
+
|
| 401 |
+
def test_per_token_normalization_with_softmax_topk(self, tokenizer, model, monkeypatch):
|
| 402 |
+
model.internal_xlora_classifier.config.top_k_lora = 2
|
| 403 |
+
model.internal_xlora_classifier.config.enable_softmax = False
|
| 404 |
+
model.internal_xlora_classifier.config.enable_softmax_topk = True
|
| 405 |
+
|
| 406 |
+
captured_data = []
|
| 407 |
+
orig_get_maybe_topk_scalings = XLoraLayer.get_maybe_topk_scalings
|
| 408 |
+
|
| 409 |
+
def mock_get_maybe_topk_scalings(self, scalings):
|
| 410 |
+
result = orig_get_maybe_topk_scalings(self, scalings)
|
| 411 |
+
if getattr(model, "internal_xlora_scalings", None) is not None:
|
| 412 |
+
captured_data.append(result)
|
| 413 |
+
return result
|
| 414 |
+
|
| 415 |
+
monkeypatch.setattr(XLoraLayer, "get_maybe_topk_scalings", mock_get_maybe_topk_scalings)
|
| 416 |
+
|
| 417 |
+
model.enable_scalings_logging()
|
| 418 |
+
inputs = tokenizer.encode("Test per token normalization", add_special_tokens=False, return_tensors="pt")
|
| 419 |
+
outputs = model.generate(
|
| 420 |
+
input_ids=inputs.to(self.torch_device),
|
| 421 |
+
max_new_tokens=1,
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
for scaling in captured_data:
|
| 425 |
+
weight_sums = scaling.sum(dim=-1)
|
| 426 |
+
assert torch.allclose(weight_sums, torch.ones_like(weight_sums), atol=1e-5), (
|
| 427 |
+
"Per-token scaling weights are not normalized to sum to 1."
|
| 428 |
+
)
|
| 429 |
+
|
| 430 |
+
def test_xlora_embed_scale_is_applied(self, tmp_path):
|
| 431 |
+
"""Test that X-LoRA correctly handles embeddings with scaling (e.g., Gemma3)."""
|
| 432 |
+
model_id = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"
|
| 433 |
+
with hub_online_once(model_id):
|
| 434 |
+
# Create and save Gemma3-compatible LoRA adapters
|
| 435 |
+
adapters = {}
|
| 436 |
+
for i in range(2):
|
| 437 |
+
torch.manual_seed(i + 1)
|
| 438 |
+
lora_config = LoraConfig(
|
| 439 |
+
task_type="CAUSAL_LM", init_lora_weights=False, target_modules=["embed_tokens"]
|
| 440 |
+
)
|
| 441 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 442 |
+
peft_model = get_peft_model(model, lora_config)
|
| 443 |
+
adapter_path = os.path.join(tmp_path, f"checkpoint-{i + 1}")
|
| 444 |
+
peft_model.save_pretrained(adapter_path)
|
| 445 |
+
adapters[str(i)] = adapter_path
|
| 446 |
+
|
| 447 |
+
# Load base model and test X-LoRA with embed_scale
|
| 448 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_id).to(self.torch_device)
|
| 449 |
+
base_model.config.use_cache = False
|
| 450 |
+
orig_embedding = base_model.get_input_embeddings()
|
| 451 |
+
|
| 452 |
+
xlora_config = XLoraConfig(
|
| 453 |
+
task_type=TaskType.CAUSAL_LM,
|
| 454 |
+
hidden_size=base_model.config.hidden_size,
|
| 455 |
+
adapters=adapters,
|
| 456 |
+
)
|
| 457 |
+
xlora_model = get_peft_model(base_model, xlora_config)
|
| 458 |
+
|
| 459 |
+
x = torch.arange(10).to(self.torch_device)
|
| 460 |
+
xlora_embedding = xlora_model.base_model.model.get_input_embeddings()
|
| 461 |
+
max_embedding_output = xlora_embedding(x).abs().max(0)[0]
|
| 462 |
+
assert (max_embedding_output < 100.0).all()
|
| 463 |
+
|
| 464 |
+
# set embed_scale to an absurdly high value, then check that the embedding output is also scaled to a high
|
| 465 |
+
# value
|
| 466 |
+
orig_embedding.embed_scale.fill_(10000.0)
|
| 467 |
+
max_embedding_output = xlora_embedding(x).abs().max(0)[0]
|
| 468 |
+
assert (max_embedding_output > 100.0).all()
|
| 469 |
+
|
| 470 |
+
# set embed_scale to zero, then check that the embedding output is also zero
|
| 471 |
+
orig_embedding.embed_scale.fill_(0)
|
| 472 |
+
embedding_output = xlora_embedding(x)
|
| 473 |
+
assert (embedding_output == 0.0).all()
|
tasks/tasksmith-955732fda55e/tests/source/tests/testing_common.py
ADDED
|
@@ -0,0 +1,1887 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import copy
|
| 15 |
+
import json
|
| 16 |
+
import os
|
| 17 |
+
import pickle
|
| 18 |
+
import platform
|
| 19 |
+
import re
|
| 20 |
+
import shutil
|
| 21 |
+
import tempfile
|
| 22 |
+
import warnings
|
| 23 |
+
from dataclasses import replace
|
| 24 |
+
from operator import attrgetter
|
| 25 |
+
|
| 26 |
+
import pytest
|
| 27 |
+
import torch
|
| 28 |
+
import yaml
|
| 29 |
+
from diffusers import StableDiffusionPipeline
|
| 30 |
+
from packaging import version
|
| 31 |
+
from safetensors.torch import save_file
|
| 32 |
+
|
| 33 |
+
from peft import (
|
| 34 |
+
AdaLoraConfig,
|
| 35 |
+
BOFTConfig,
|
| 36 |
+
CPTConfig,
|
| 37 |
+
GraloraConfig,
|
| 38 |
+
IA3Config,
|
| 39 |
+
LNTuningConfig,
|
| 40 |
+
LoHaConfig,
|
| 41 |
+
LoKrConfig,
|
| 42 |
+
LoraConfig,
|
| 43 |
+
OSFConfig,
|
| 44 |
+
PeftModel,
|
| 45 |
+
PrefixTuningConfig,
|
| 46 |
+
PromptEncoderConfig,
|
| 47 |
+
PromptLearningConfig,
|
| 48 |
+
PromptTuningConfig,
|
| 49 |
+
RoadConfig,
|
| 50 |
+
VBLoRAConfig,
|
| 51 |
+
VeraConfig,
|
| 52 |
+
convert_to_lora,
|
| 53 |
+
get_peft_model,
|
| 54 |
+
get_peft_model_state_dict,
|
| 55 |
+
inject_adapter_in_model,
|
| 56 |
+
prepare_model_for_kbit_training,
|
| 57 |
+
set_peft_model_state_dict,
|
| 58 |
+
)
|
| 59 |
+
from peft.tuners._buffer_dict import BufferDict
|
| 60 |
+
from peft.tuners.lora import LoraLayer
|
| 61 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 62 |
+
from peft.utils import (
|
| 63 |
+
AuxiliaryTrainingWrapper,
|
| 64 |
+
ModulesToSaveWrapper,
|
| 65 |
+
TrainableTokensWrapper,
|
| 66 |
+
_get_submodules,
|
| 67 |
+
infer_device,
|
| 68 |
+
is_transformers_ge_v5,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
from .testing_utils import get_state_dict, hub_online_once
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _skip_if_merging_not_supported(model_id, config_cls, config_kwargs):
|
| 75 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 76 |
+
pytest.skip("Prompt learning does not support merging, skipping this test.")
|
| 77 |
+
if config_kwargs.get("alora_invocation_tokens") is not None:
|
| 78 |
+
pytest.skip("Test not applicable for Activated LoRA")
|
| 79 |
+
if issubclass(config_cls, OSFConfig):
|
| 80 |
+
pytest.skip(f"Skipping test for {model_id} with {config_cls} as OSF adapter merge/unload are not implemented.")
|
| 81 |
+
if model_id.startswith("Conv2dGroups") and (config_cls == LoraConfig):
|
| 82 |
+
# note: right now, only LoRA supports groups>1, if other PEFT methods add support, they might also need to skip
|
| 83 |
+
pytest.skip("Merging conv layers with groups>1 and LoRA is not supported.")
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def _skip_if_adding_weighted_adapters_not_supported(config):
|
| 87 |
+
if not isinstance(config, (IA3Config, LoraConfig)):
|
| 88 |
+
pytest.skip("This PEFT method does not support adding weighted adapters, skipping this test.")
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _skip_if_deleting_adapter_not_supported(config_cls, config_kwargs):
|
| 92 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 93 |
+
pytest.skip("Prompt learning does not support deletion of adapters, skipping this test.")
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def _skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs):
|
| 97 |
+
if "gpt2" not in model_id.lower():
|
| 98 |
+
return
|
| 99 |
+
|
| 100 |
+
if config_cls not in (IA3Config, LoHaConfig, LoKrConfig, LoraConfig):
|
| 101 |
+
pytest.skip("This PEFT method does not support Conv1D layers, skipping this test.")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class PeftCommonTester:
|
| 105 |
+
r"""
|
| 106 |
+
A large testing suite for testing common functionality of the PEFT models.
|
| 107 |
+
|
| 108 |
+
Attributes:
|
| 109 |
+
torch_device (`torch.device`):
|
| 110 |
+
The device on which the tests will be run.
|
| 111 |
+
transformers_class (`transformers.PreTrainedModel`):
|
| 112 |
+
The transformers class that is being tested.
|
| 113 |
+
"""
|
| 114 |
+
|
| 115 |
+
torch_device = infer_device()
|
| 116 |
+
transformers_class = None
|
| 117 |
+
|
| 118 |
+
def prepare_inputs_for_common(self):
|
| 119 |
+
raise NotImplementedError
|
| 120 |
+
|
| 121 |
+
def check_modelcard(self, tmp_dirname, model):
|
| 122 |
+
# check the generated README.md
|
| 123 |
+
filename = os.path.join(tmp_dirname, "README.md")
|
| 124 |
+
assert os.path.exists(filename)
|
| 125 |
+
with open(filename, encoding="utf-8") as f:
|
| 126 |
+
readme = f.read()
|
| 127 |
+
metainfo = re.search(r"---\n(.*?)\n---", readme, re.DOTALL).group(1)
|
| 128 |
+
dct = yaml.safe_load(metainfo)
|
| 129 |
+
assert dct["library_name"] == "peft"
|
| 130 |
+
|
| 131 |
+
if hasattr(model, "config"):
|
| 132 |
+
assert dct["base_model"] == model.config.to_dict()["_name_or_path"]
|
| 133 |
+
else: # a custom model
|
| 134 |
+
assert "base_model" not in dct
|
| 135 |
+
|
| 136 |
+
# The Hub expects the lora tag to be set for PEFT LoRA models since they
|
| 137 |
+
# have explicit support for things like inference.
|
| 138 |
+
if model.active_peft_config.peft_type.value == "LORA":
|
| 139 |
+
assert "lora" in dct["tags"]
|
| 140 |
+
|
| 141 |
+
def check_config_json(self, tmp_dirname, model):
|
| 142 |
+
# check the generated config.json
|
| 143 |
+
filename = os.path.join(tmp_dirname, "adapter_config.json")
|
| 144 |
+
assert os.path.exists(filename)
|
| 145 |
+
with open(filename, encoding="utf-8") as f:
|
| 146 |
+
config = json.load(f)
|
| 147 |
+
|
| 148 |
+
if hasattr(model, "config"): # custom models don't have a config attribute
|
| 149 |
+
assert config["base_model_name_or_path"] == model.config.to_dict()["_name_or_path"]
|
| 150 |
+
|
| 151 |
+
def perturb_trainable_token_weights_if_used(self, model, config_kwargs, adapter_name="default", scale=1.0):
|
| 152 |
+
"""TrainableTokensLayer is initialized to be a no-op by default. Since there's currently no way to pass
|
| 153 |
+
`init_weights=False` to the trainable tokens layer when used in conjunction with LoRA, we have to do it like
|
| 154 |
+
this to make sure that it is *not* a no-op (essentially simulating "training" of the adapter).
|
| 155 |
+
"""
|
| 156 |
+
if "trainable_token_indices" not in config_kwargs:
|
| 157 |
+
return
|
| 158 |
+
|
| 159 |
+
token_wrapper = None
|
| 160 |
+
|
| 161 |
+
if hasattr(model, "get_input_embeddings"):
|
| 162 |
+
token_wrapper = model.get_input_embeddings()
|
| 163 |
+
else:
|
| 164 |
+
for module in model.modules():
|
| 165 |
+
if isinstance(module, TrainableTokensWrapper):
|
| 166 |
+
token_wrapper = module
|
| 167 |
+
break
|
| 168 |
+
|
| 169 |
+
# for a model with trainable_token_indices there should always be a trainable token wrapper somewhere.
|
| 170 |
+
# if not, then there's something broken.
|
| 171 |
+
assert token_wrapper is not None
|
| 172 |
+
|
| 173 |
+
token_wrapper.token_adapter.trainable_tokens_delta[adapter_name].data = (
|
| 174 |
+
torch.rand_like(token_wrapper.token_adapter.trainable_tokens_delta[adapter_name].data) * scale
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
def _test_model_attr(self, model_id, config_cls, config_kwargs):
|
| 178 |
+
with hub_online_once(model_id):
|
| 179 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 180 |
+
config = config_cls(
|
| 181 |
+
base_model_name_or_path=model_id,
|
| 182 |
+
**config_kwargs,
|
| 183 |
+
)
|
| 184 |
+
model = get_peft_model(model, config)
|
| 185 |
+
|
| 186 |
+
assert hasattr(model, "save_pretrained")
|
| 187 |
+
assert hasattr(model, "from_pretrained")
|
| 188 |
+
assert hasattr(model, "push_to_hub")
|
| 189 |
+
|
| 190 |
+
def _test_adapter_name(self, model_id, config_cls, config_kwargs):
|
| 191 |
+
with hub_online_once(model_id):
|
| 192 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 193 |
+
config = config_cls(
|
| 194 |
+
base_model_name_or_path=model_id,
|
| 195 |
+
**config_kwargs,
|
| 196 |
+
)
|
| 197 |
+
model = get_peft_model(model, config, adapter_name="test-adapter")
|
| 198 |
+
correctly_converted = False
|
| 199 |
+
for n, _ in model.named_parameters():
|
| 200 |
+
if "test-adapter" in n:
|
| 201 |
+
correctly_converted = True
|
| 202 |
+
break
|
| 203 |
+
|
| 204 |
+
assert correctly_converted
|
| 205 |
+
|
| 206 |
+
def _test_prepare_for_training(self, model_id, config_cls, config_kwargs):
|
| 207 |
+
if config_kwargs.get("trainable_token_indices", None) is not None:
|
| 208 |
+
# incompatible because trainable tokens is marking embeddings as trainable
|
| 209 |
+
pytest.skip("Trainable tokens is incompatible with this test.")
|
| 210 |
+
|
| 211 |
+
# some tests require specific tokenizers, make sure that they can be fetched as well
|
| 212 |
+
with hub_online_once(model_id + config_kwargs.get("tokenizer_name_or_path", "")):
|
| 213 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 214 |
+
config = config_cls(
|
| 215 |
+
base_model_name_or_path=model_id,
|
| 216 |
+
**config_kwargs,
|
| 217 |
+
)
|
| 218 |
+
model = get_peft_model(model, config)
|
| 219 |
+
|
| 220 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 221 |
+
dummy_output = model.get_input_embeddings()(dummy_input["input_ids"])
|
| 222 |
+
|
| 223 |
+
assert not dummy_output.requires_grad
|
| 224 |
+
|
| 225 |
+
# load with `prepare_model_for_kbit_training`
|
| 226 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 227 |
+
model = prepare_model_for_kbit_training(model)
|
| 228 |
+
|
| 229 |
+
for param in model.parameters():
|
| 230 |
+
assert not param.requires_grad
|
| 231 |
+
|
| 232 |
+
config = config_cls(
|
| 233 |
+
base_model_name_or_path=model_id,
|
| 234 |
+
**config_kwargs,
|
| 235 |
+
)
|
| 236 |
+
model = get_peft_model(model, config)
|
| 237 |
+
|
| 238 |
+
# For backward compatibility
|
| 239 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 240 |
+
model.enable_input_require_grads()
|
| 241 |
+
else:
|
| 242 |
+
|
| 243 |
+
def make_inputs_require_grad(module, input, output):
|
| 244 |
+
output.requires_grad_(True)
|
| 245 |
+
|
| 246 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 247 |
+
|
| 248 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 249 |
+
dummy_output = model.get_input_embeddings()(dummy_input["input_ids"])
|
| 250 |
+
|
| 251 |
+
assert dummy_output.requires_grad
|
| 252 |
+
|
| 253 |
+
def _test_load_model_low_cpu_mem_usage(self, model_id, config_cls, config_kwargs):
|
| 254 |
+
# Ensure that low_cpu_mem_usage=True works for from_pretrained and load_adapter and that the resulting model's
|
| 255 |
+
# parameters are on the correct device.
|
| 256 |
+
with hub_online_once(model_id):
|
| 257 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 258 |
+
config = config_cls(
|
| 259 |
+
base_model_name_or_path=model_id,
|
| 260 |
+
**config_kwargs,
|
| 261 |
+
)
|
| 262 |
+
model = get_peft_model(model, config)
|
| 263 |
+
|
| 264 |
+
# note: not using the context manager here because it fails on Windows CI for some reason
|
| 265 |
+
tmp_dirname = tempfile.mkdtemp()
|
| 266 |
+
try:
|
| 267 |
+
model.save_pretrained(tmp_dirname)
|
| 268 |
+
|
| 269 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 270 |
+
model = PeftModel.from_pretrained(
|
| 271 |
+
model, tmp_dirname, torch_device=self.torch_device, low_cpu_mem_usage=True
|
| 272 |
+
)
|
| 273 |
+
assert {p.device.type for p in model.parameters()} == {self.torch_device}
|
| 274 |
+
|
| 275 |
+
model.load_adapter(tmp_dirname, adapter_name="other", low_cpu_mem_usage=True)
|
| 276 |
+
assert {p.device.type for p in model.parameters()} == {self.torch_device}
|
| 277 |
+
finally:
|
| 278 |
+
try:
|
| 279 |
+
shutil.rmtree(tmp_dirname)
|
| 280 |
+
except PermissionError:
|
| 281 |
+
# windows error
|
| 282 |
+
pass
|
| 283 |
+
|
| 284 |
+
# also test injecting directly
|
| 285 |
+
del model
|
| 286 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 287 |
+
inject_adapter_in_model(config, model, low_cpu_mem_usage=True) # check that there is no error
|
| 288 |
+
|
| 289 |
+
if not isinstance(config, LNTuningConfig):
|
| 290 |
+
# LN tuning does not add adapter layers that could be on meta device, it only changes the requires_grad.
|
| 291 |
+
# Therefore, there is no meta device for LN tuning.
|
| 292 |
+
assert "meta" in {p.device.type for p in model.parameters()}
|
| 293 |
+
|
| 294 |
+
def _test_save_pretrained(self, model_id, config_cls, config_kwargs, safe_serialization=True):
|
| 295 |
+
# ensure that the weights are randomly initialized
|
| 296 |
+
if issubclass(config_cls, LoraConfig):
|
| 297 |
+
config_kwargs = config_kwargs.copy()
|
| 298 |
+
config_kwargs["init_lora_weights"] = False
|
| 299 |
+
if issubclass(config_cls, IA3Config):
|
| 300 |
+
config_kwargs = config_kwargs.copy()
|
| 301 |
+
config_kwargs["init_ia3_weights"] = False
|
| 302 |
+
if hasattr(config_cls, "init_weights"):
|
| 303 |
+
config_kwargs = config_kwargs.copy()
|
| 304 |
+
config_kwargs["init_weights"] = False
|
| 305 |
+
|
| 306 |
+
with hub_online_once(model_id):
|
| 307 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 308 |
+
config = config_cls(
|
| 309 |
+
base_model_name_or_path=model_id,
|
| 310 |
+
**config_kwargs,
|
| 311 |
+
)
|
| 312 |
+
model = get_peft_model(model, config)
|
| 313 |
+
model = model.to(self.torch_device)
|
| 314 |
+
|
| 315 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 316 |
+
if safe_serialization:
|
| 317 |
+
model.save_pretrained(tmp_dirname)
|
| 318 |
+
else:
|
| 319 |
+
model.save_pretrained(tmp_dirname, safe_serialization=False)
|
| 320 |
+
|
| 321 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 322 |
+
with warnings.catch_warnings(record=True) as recs:
|
| 323 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 324 |
+
# ensure that there is no warning
|
| 325 |
+
assert not any("Found missing adapter keys" in str(rec.message) for rec in recs)
|
| 326 |
+
|
| 327 |
+
# check if the state dicts are equal
|
| 328 |
+
if issubclass(config_cls, PromptEncoderConfig):
|
| 329 |
+
# For prompt encoding, when loading the whole state_dict, there are differences, therefore, only load
|
| 330 |
+
# adapter-specific weights for comparison.
|
| 331 |
+
# TODO: is this expected?
|
| 332 |
+
state_dict = get_peft_model_state_dict(model, unwrap_compiled=True)
|
| 333 |
+
state_dict_from_pretrained = get_peft_model_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 334 |
+
else:
|
| 335 |
+
state_dict = get_state_dict(model, unwrap_compiled=True)
|
| 336 |
+
state_dict_from_pretrained = get_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 337 |
+
|
| 338 |
+
# check if tensors equal
|
| 339 |
+
for key in state_dict.keys():
|
| 340 |
+
assert torch.allclose(
|
| 341 |
+
state_dict[key].to(self.torch_device), state_dict_from_pretrained[key].to(self.torch_device)
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
target_adapter_filename = "adapter_model.safetensors" if safe_serialization else "adapter_model.bin"
|
| 345 |
+
|
| 346 |
+
# check if `adapter_model.safetensors` is present
|
| 347 |
+
assert os.path.exists(os.path.join(tmp_dirname, target_adapter_filename))
|
| 348 |
+
|
| 349 |
+
# check if `adapter_config.json` is present
|
| 350 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_config.json"))
|
| 351 |
+
|
| 352 |
+
# check if `model.safetensors` is not present
|
| 353 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "model.safetensors"))
|
| 354 |
+
|
| 355 |
+
# check if `config.json` is not present
|
| 356 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "config.json"))
|
| 357 |
+
|
| 358 |
+
self.check_modelcard(tmp_dirname, model)
|
| 359 |
+
self.check_config_json(tmp_dirname, model)
|
| 360 |
+
|
| 361 |
+
def _test_save_pretrained_selected_adapters(self, model_id, config_cls, config_kwargs, safe_serialization=True):
|
| 362 |
+
if issubclass(config_cls, AdaLoraConfig):
|
| 363 |
+
# AdaLora does not support adding more than 1 adapter
|
| 364 |
+
pytest.skip(f"Test not applicable for {config_cls}")
|
| 365 |
+
|
| 366 |
+
# ensure that the weights are randomly initialized
|
| 367 |
+
if issubclass(config_cls, LoraConfig):
|
| 368 |
+
config_kwargs = config_kwargs.copy()
|
| 369 |
+
config_kwargs["init_lora_weights"] = False
|
| 370 |
+
elif issubclass(config_cls, IA3Config):
|
| 371 |
+
config_kwargs = config_kwargs.copy()
|
| 372 |
+
config_kwargs["init_ia3_weights"] = False
|
| 373 |
+
elif hasattr(config_cls, "init_weights"):
|
| 374 |
+
config_kwargs["init_weights"] = False
|
| 375 |
+
|
| 376 |
+
with hub_online_once(model_id):
|
| 377 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 378 |
+
config = config_cls(
|
| 379 |
+
base_model_name_or_path=model_id,
|
| 380 |
+
**config_kwargs,
|
| 381 |
+
)
|
| 382 |
+
model = get_peft_model(model, config)
|
| 383 |
+
model = model.to(self.torch_device)
|
| 384 |
+
|
| 385 |
+
new_adapter_config = config_cls(
|
| 386 |
+
base_model_name_or_path=model_id,
|
| 387 |
+
**config_kwargs,
|
| 388 |
+
)
|
| 389 |
+
|
| 390 |
+
model.add_adapter("new_adapter", new_adapter_config)
|
| 391 |
+
|
| 392 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 393 |
+
if safe_serialization:
|
| 394 |
+
model.save_pretrained(tmp_dirname)
|
| 395 |
+
else:
|
| 396 |
+
model.save_pretrained(tmp_dirname, safe_serialization=False)
|
| 397 |
+
|
| 398 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 399 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 400 |
+
|
| 401 |
+
new_adapter_dir = os.path.join(tmp_dirname, "new_adapter")
|
| 402 |
+
model_from_pretrained.load_adapter(new_adapter_dir, "new_adapter")
|
| 403 |
+
|
| 404 |
+
# check if the state dicts are equal
|
| 405 |
+
if issubclass(config_cls, PromptEncoderConfig):
|
| 406 |
+
# For prompt encoding, when loading the whole state_dict, there are differences, therefore, only load
|
| 407 |
+
# adapter-specific weights for comparison.
|
| 408 |
+
# TODO: is this expected?
|
| 409 |
+
state_dict = get_peft_model_state_dict(model, unwrap_compiled=True)
|
| 410 |
+
state_dict_from_pretrained = get_peft_model_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 411 |
+
else:
|
| 412 |
+
state_dict = get_state_dict(model, unwrap_compiled=True)
|
| 413 |
+
state_dict_from_pretrained = get_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 414 |
+
|
| 415 |
+
# check if same keys
|
| 416 |
+
assert state_dict.keys() == state_dict_from_pretrained.keys()
|
| 417 |
+
|
| 418 |
+
# check if tensors equal
|
| 419 |
+
for key in state_dict.keys():
|
| 420 |
+
assert torch.allclose(
|
| 421 |
+
state_dict[key].to(self.torch_device), state_dict_from_pretrained[key].to(self.torch_device)
|
| 422 |
+
)
|
| 423 |
+
|
| 424 |
+
target_adapter_filename = "adapter_model.safetensors" if safe_serialization else "adapter_model.bin"
|
| 425 |
+
|
| 426 |
+
# check if `adapter_model.safetensors` is present
|
| 427 |
+
assert os.path.exists(os.path.join(tmp_dirname, target_adapter_filename))
|
| 428 |
+
assert os.path.exists(os.path.join(new_adapter_dir, target_adapter_filename))
|
| 429 |
+
|
| 430 |
+
# check if `adapter_config.json` is present
|
| 431 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_config.json"))
|
| 432 |
+
assert os.path.exists(os.path.join(new_adapter_dir, "adapter_config.json"))
|
| 433 |
+
|
| 434 |
+
# check if `model.safetensors` is not present
|
| 435 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "model.safetensors"))
|
| 436 |
+
assert not os.path.exists(os.path.join(new_adapter_dir, "model.safetensors"))
|
| 437 |
+
|
| 438 |
+
# check if `config.json` is not present
|
| 439 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "config.json"))
|
| 440 |
+
assert not os.path.exists(os.path.join(new_adapter_dir, "config.json"))
|
| 441 |
+
|
| 442 |
+
self.check_modelcard(tmp_dirname, model)
|
| 443 |
+
self.check_config_json(tmp_dirname, model)
|
| 444 |
+
|
| 445 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 446 |
+
model.save_pretrained(tmp_dirname, selected_adapters=["default"])
|
| 447 |
+
|
| 448 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 449 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 450 |
+
|
| 451 |
+
assert "default" in model_from_pretrained.peft_config.keys()
|
| 452 |
+
assert "new_adapter" not in model_from_pretrained.peft_config.keys()
|
| 453 |
+
|
| 454 |
+
def _test_from_pretrained_config_construction(self, model_id, config_cls, config_kwargs):
|
| 455 |
+
with hub_online_once(model_id):
|
| 456 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 457 |
+
config = config_cls(base_model_name_or_path=model_id, **config_kwargs)
|
| 458 |
+
model = get_peft_model(model, config)
|
| 459 |
+
model = model.to(self.torch_device)
|
| 460 |
+
|
| 461 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 462 |
+
model.save_pretrained(tmp_dirname)
|
| 463 |
+
|
| 464 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 465 |
+
model_from_pretrained = PeftModel.from_pretrained(
|
| 466 |
+
model_from_pretrained, tmp_dirname, is_trainable=False, config=config
|
| 467 |
+
)
|
| 468 |
+
|
| 469 |
+
assert model_from_pretrained.peft_config["default"].inference_mode
|
| 470 |
+
assert model_from_pretrained.peft_config["default"] is config
|
| 471 |
+
|
| 472 |
+
def _test_load_multiple_adapters(self, model_id, config_cls, config_kwargs):
|
| 473 |
+
# just ensure that this works and raises no error
|
| 474 |
+
with hub_online_once(model_id):
|
| 475 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 476 |
+
config = config_cls(
|
| 477 |
+
base_model_name_or_path=model_id,
|
| 478 |
+
**config_kwargs,
|
| 479 |
+
)
|
| 480 |
+
model = get_peft_model(model, config)
|
| 481 |
+
|
| 482 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 483 |
+
model.save_pretrained(tmp_dirname)
|
| 484 |
+
del model
|
| 485 |
+
|
| 486 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 487 |
+
model = PeftModel.from_pretrained(model, tmp_dirname, torch_device=self.torch_device)
|
| 488 |
+
load_result1 = model.load_adapter(tmp_dirname, adapter_name="other")
|
| 489 |
+
load_result2 = model.load_adapter(tmp_dirname, adapter_name="yet-another")
|
| 490 |
+
|
| 491 |
+
# VBLoRA uses a shared "vblora_vector_bank" across all layers, causing it to appear
|
| 492 |
+
# in the missing keys list, which leads to failed test cases. So
|
| 493 |
+
# skipping the missing keys check for VBLoRA.
|
| 494 |
+
if config.peft_type != "VBLORA":
|
| 495 |
+
assert load_result1.missing_keys == []
|
| 496 |
+
assert load_result2.missing_keys == []
|
| 497 |
+
|
| 498 |
+
def _test_merge_layers_fp16(self, model_id, config_cls, config_kwargs):
|
| 499 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 500 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 501 |
+
if (self.torch_device in ["cpu"]) and (version.parse(torch.__version__) <= version.parse("2.1")):
|
| 502 |
+
pytest.skip("PyTorch 2.1 not supported for Half of addmm_impl_cpu_ ")
|
| 503 |
+
|
| 504 |
+
with hub_online_once(model_id):
|
| 505 |
+
model = self.transformers_class.from_pretrained(model_id, dtype=torch.float16)
|
| 506 |
+
config = config_cls(
|
| 507 |
+
base_model_name_or_path=model_id,
|
| 508 |
+
**config_kwargs,
|
| 509 |
+
)
|
| 510 |
+
model = get_peft_model(model, config)
|
| 511 |
+
model = model.to(device=self.torch_device, dtype=torch.float16)
|
| 512 |
+
|
| 513 |
+
model.eval()
|
| 514 |
+
|
| 515 |
+
# This should simply work
|
| 516 |
+
_ = model.merge_and_unload()
|
| 517 |
+
|
| 518 |
+
def _test_merge_layers_nan(self, model_id, config_cls, config_kwargs):
|
| 519 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 520 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 521 |
+
|
| 522 |
+
with hub_online_once(model_id):
|
| 523 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 524 |
+
config = config_cls(
|
| 525 |
+
base_model_name_or_path=model_id,
|
| 526 |
+
**config_kwargs,
|
| 527 |
+
)
|
| 528 |
+
|
| 529 |
+
model = get_peft_model(model, config)
|
| 530 |
+
model = model.to(self.torch_device)
|
| 531 |
+
|
| 532 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 533 |
+
|
| 534 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 535 |
+
|
| 536 |
+
model.eval()
|
| 537 |
+
|
| 538 |
+
# This should work
|
| 539 |
+
logits_unmerged = model(**dummy_input)[0]
|
| 540 |
+
|
| 541 |
+
model = model.merge_and_unload()
|
| 542 |
+
logits_merged = model(**dummy_input)[0]
|
| 543 |
+
|
| 544 |
+
assert torch.allclose(logits_unmerged, logits_merged, atol=1e-3, rtol=1e-3)
|
| 545 |
+
|
| 546 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 547 |
+
config = config_cls(
|
| 548 |
+
base_model_name_or_path=model_id,
|
| 549 |
+
**config_kwargs,
|
| 550 |
+
)
|
| 551 |
+
model = get_peft_model(model, config)
|
| 552 |
+
model = model.to(self.torch_device)
|
| 553 |
+
|
| 554 |
+
for name, module in model.named_parameters():
|
| 555 |
+
if model.prefix in name:
|
| 556 |
+
module.data[0] = torch.nan
|
| 557 |
+
|
| 558 |
+
with pytest.raises(
|
| 559 |
+
ValueError, match="NaNs detected in the merged weights. The adapter default seems to be broken"
|
| 560 |
+
):
|
| 561 |
+
model = model.merge_and_unload(safe_merge=True)
|
| 562 |
+
|
| 563 |
+
for name, module in model.named_parameters():
|
| 564 |
+
if (
|
| 565 |
+
"lora_A" in name
|
| 566 |
+
or "ia3" in name
|
| 567 |
+
or "lora_E" in name
|
| 568 |
+
or "lora_B" in name
|
| 569 |
+
or "vera_lambda" in name
|
| 570 |
+
or "fourierft_spectrum" in name
|
| 571 |
+
):
|
| 572 |
+
module.data[0] = torch.inf
|
| 573 |
+
|
| 574 |
+
with pytest.raises(
|
| 575 |
+
ValueError, match="NaNs detected in the merged weights. The adapter default seems to be broken"
|
| 576 |
+
):
|
| 577 |
+
model = model.merge_and_unload(safe_merge=True)
|
| 578 |
+
|
| 579 |
+
def _test_merge_layers(self, model_id, config_cls, config_kwargs):
|
| 580 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 581 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 582 |
+
|
| 583 |
+
with hub_online_once(model_id):
|
| 584 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 585 |
+
config = config_cls(
|
| 586 |
+
base_model_name_or_path=model_id,
|
| 587 |
+
**config_kwargs,
|
| 588 |
+
)
|
| 589 |
+
|
| 590 |
+
model = get_peft_model(model, config)
|
| 591 |
+
model = model.to(self.torch_device)
|
| 592 |
+
|
| 593 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 594 |
+
|
| 595 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 596 |
+
model.eval()
|
| 597 |
+
logits = model(**dummy_input)[0]
|
| 598 |
+
|
| 599 |
+
model.merge_adapter()
|
| 600 |
+
logits_merged = model(**dummy_input)[0]
|
| 601 |
+
model.unmerge_adapter()
|
| 602 |
+
logits_unmerged = model(**dummy_input)[0]
|
| 603 |
+
|
| 604 |
+
model = model.merge_and_unload()
|
| 605 |
+
|
| 606 |
+
# check that PEFT layers are completely removed
|
| 607 |
+
assert not any(isinstance(module, BaseTunerLayer) for module in model.modules())
|
| 608 |
+
logits_merged_unloaded = model(**dummy_input)[0]
|
| 609 |
+
|
| 610 |
+
conv_ids = ["Conv2d", "Conv3d", "Conv2d2"]
|
| 611 |
+
is_decoder = getattr(getattr(model, "config", None), "is_decoder", False)
|
| 612 |
+
atol, rtol = 1e-4, 1e-4
|
| 613 |
+
if self.torch_device in ["mlu"]:
|
| 614 |
+
atol, rtol = 1e-3, 1e-3 # MLU
|
| 615 |
+
if config.peft_type in ("ADALORA", "OFT"):
|
| 616 |
+
# these methods require a bit higher tolerance
|
| 617 |
+
atol, rtol = 1e-2, 1e-2
|
| 618 |
+
if (config.peft_type in {"IA3", "LORA", "OFT"}) and (model_id in conv_ids):
|
| 619 |
+
# for some reason, the Conv introduces a larger error
|
| 620 |
+
atol, rtol = 0.3, 0.01
|
| 621 |
+
if (config.peft_type == "OFT") and not is_decoder:
|
| 622 |
+
atol, rtol = 0.3, 0.01
|
| 623 |
+
if model_id == "trl-internal-testing/tiny-Llama4ForCausalLM":
|
| 624 |
+
# also getting larger errors here, not exactly sure why
|
| 625 |
+
atol, rtol = 0.3, 0.01
|
| 626 |
+
assert torch.allclose(logits, logits_merged, atol=atol, rtol=rtol)
|
| 627 |
+
assert torch.allclose(logits, logits_unmerged, atol=atol, rtol=rtol)
|
| 628 |
+
assert torch.allclose(logits, logits_merged_unloaded, atol=atol, rtol=rtol)
|
| 629 |
+
|
| 630 |
+
# For this test to work, weights should not be initialized to identity transform (e.g.
|
| 631 |
+
# init_lora_weights should be False).
|
| 632 |
+
transformers_model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 633 |
+
logits_transformers = transformers_model(**dummy_input)[0]
|
| 634 |
+
assert not torch.allclose(logits_merged, logits_transformers, atol=1e-10, rtol=1e-10)
|
| 635 |
+
|
| 636 |
+
# test that the logits are identical after a save-load-roundtrip
|
| 637 |
+
if hasattr(model, "save_pretrained"):
|
| 638 |
+
# model is a transformers model
|
| 639 |
+
tmp_dirname = tempfile.mkdtemp()
|
| 640 |
+
# note: not using the context manager here because it fails on Windows CI for some reason
|
| 641 |
+
try:
|
| 642 |
+
model.save_pretrained(tmp_dirname)
|
| 643 |
+
model_from_pretrained = self.transformers_class.from_pretrained(tmp_dirname).to(self.torch_device)
|
| 644 |
+
finally:
|
| 645 |
+
try:
|
| 646 |
+
shutil.rmtree(tmp_dirname)
|
| 647 |
+
except PermissionError:
|
| 648 |
+
# windows error
|
| 649 |
+
pass
|
| 650 |
+
else:
|
| 651 |
+
# model is not a transformers model
|
| 652 |
+
model_from_pretrained = pickle.loads(pickle.dumps(model))
|
| 653 |
+
|
| 654 |
+
logits_merged_from_pretrained = model_from_pretrained(**dummy_input)[0]
|
| 655 |
+
assert torch.allclose(logits_merged, logits_merged_from_pretrained, atol=atol, rtol=rtol)
|
| 656 |
+
|
| 657 |
+
def _test_merge_layers_multi(self, model_id, config_cls, config_kwargs):
|
| 658 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 659 |
+
if issubclass(config_cls, AdaLoraConfig):
|
| 660 |
+
# AdaLora does not support adding more than 1 adapter
|
| 661 |
+
pytest.skip("AdaLoRA does not support multiple adapters, skipping this test.")
|
| 662 |
+
if config_kwargs.get("trainable_token_indices", None) is not None:
|
| 663 |
+
pytest.skip(
|
| 664 |
+
"Merging two adapters with trainable tokens is tested elsewhere since adapters with "
|
| 665 |
+
"the same token indices cannot be merged."
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
config = config_cls(
|
| 669 |
+
base_model_name_or_path=model_id,
|
| 670 |
+
**config_kwargs,
|
| 671 |
+
)
|
| 672 |
+
if config_cls == VBLoRAConfig:
|
| 673 |
+
# for VBLoRA, increase this value or else the two adapters are too similar
|
| 674 |
+
config.init_logits_std *= 100
|
| 675 |
+
config.init_vector_bank_bound *= 100
|
| 676 |
+
|
| 677 |
+
with hub_online_once(model_id):
|
| 678 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 679 |
+
torch.manual_seed(0)
|
| 680 |
+
model = get_peft_model(model, config)
|
| 681 |
+
model = model.to(self.torch_device)
|
| 682 |
+
|
| 683 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 684 |
+
model.eval()
|
| 685 |
+
|
| 686 |
+
with torch.inference_mode():
|
| 687 |
+
logits_adapter_1 = model(**dummy_input)[0]
|
| 688 |
+
|
| 689 |
+
torch.manual_seed(1)
|
| 690 |
+
model.add_adapter("adapter-2", config)
|
| 691 |
+
model.set_adapter("adapter-2")
|
| 692 |
+
model.eval()
|
| 693 |
+
|
| 694 |
+
# sanity check: each adapter layer with a 'default' adapter should also have 'adapter-2'
|
| 695 |
+
containers = (torch.nn.ModuleDict, torch.nn.ParameterDict, BufferDict)
|
| 696 |
+
num_default = len([m for m in model.modules() if isinstance(m, containers) and "default" in m])
|
| 697 |
+
num_adapter2 = len([m for m in model.modules() if isinstance(m, containers) and "adapter-2" in m])
|
| 698 |
+
assert num_default > 0
|
| 699 |
+
assert num_default == num_adapter2
|
| 700 |
+
|
| 701 |
+
with torch.inference_mode():
|
| 702 |
+
logits_adapter_2 = model(**dummy_input)[0]
|
| 703 |
+
|
| 704 |
+
assert not torch.allclose(logits_adapter_1, logits_adapter_2, atol=1e-3, rtol=1e-3)
|
| 705 |
+
|
| 706 |
+
model.set_adapter("default")
|
| 707 |
+
|
| 708 |
+
with torch.inference_mode():
|
| 709 |
+
logits_adapter_1_after_set = model(**dummy_input)[0]
|
| 710 |
+
|
| 711 |
+
assert torch.allclose(logits_adapter_1_after_set, logits_adapter_1, atol=1e-3, rtol=1e-3)
|
| 712 |
+
|
| 713 |
+
model_copy = copy.deepcopy(model)
|
| 714 |
+
model_copy_2 = copy.deepcopy(model)
|
| 715 |
+
model_merged_all = model.merge_and_unload(adapter_names=["adapter-2", "default"])
|
| 716 |
+
|
| 717 |
+
with torch.inference_mode():
|
| 718 |
+
logits_merged_all = model_merged_all(**dummy_input)[0]
|
| 719 |
+
|
| 720 |
+
assert not torch.allclose(logits_merged_all, logits_adapter_2, atol=1e-3, rtol=1e-3)
|
| 721 |
+
assert not torch.allclose(logits_merged_all, logits_adapter_1, atol=1e-3, rtol=1e-3)
|
| 722 |
+
|
| 723 |
+
model_merged_adapter_2 = model_copy.merge_and_unload(adapter_names=["adapter-2"])
|
| 724 |
+
|
| 725 |
+
with torch.inference_mode():
|
| 726 |
+
logits_merged_adapter_2 = model_merged_adapter_2(**dummy_input)[0]
|
| 727 |
+
|
| 728 |
+
assert torch.allclose(logits_merged_adapter_2, logits_adapter_2, atol=1e-3, rtol=1e-3)
|
| 729 |
+
|
| 730 |
+
model_merged_adapter_default = model_copy_2.merge_and_unload(adapter_names=["default"])
|
| 731 |
+
|
| 732 |
+
with torch.inference_mode():
|
| 733 |
+
logits_merged_adapter_default = model_merged_adapter_default(**dummy_input)[0]
|
| 734 |
+
|
| 735 |
+
assert torch.allclose(logits_merged_adapter_default, logits_adapter_1, atol=1e-3, rtol=1e-3)
|
| 736 |
+
|
| 737 |
+
def _test_merge_layers_is_idempotent(self, model_id, config_cls, config_kwargs):
|
| 738 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 739 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 740 |
+
|
| 741 |
+
with hub_online_once(model_id):
|
| 742 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 743 |
+
config = config_cls(
|
| 744 |
+
base_model_name_or_path=model_id,
|
| 745 |
+
**config_kwargs,
|
| 746 |
+
)
|
| 747 |
+
model = get_peft_model(model, config)
|
| 748 |
+
model = model.to(self.torch_device)
|
| 749 |
+
model.eval()
|
| 750 |
+
torch.manual_seed(0)
|
| 751 |
+
model.merge_adapter()
|
| 752 |
+
logits_0 = model(**self.prepare_inputs_for_testing())[0]
|
| 753 |
+
|
| 754 |
+
# merging again should not change anything
|
| 755 |
+
# also check warning:
|
| 756 |
+
with pytest.warns(UserWarning, match="All adapters are already merged, nothing to do"):
|
| 757 |
+
model.merge_adapter()
|
| 758 |
+
logits_1 = model(**self.prepare_inputs_for_testing())[0]
|
| 759 |
+
|
| 760 |
+
assert torch.allclose(logits_0, logits_1, atol=1e-6, rtol=1e-6)
|
| 761 |
+
|
| 762 |
+
def _test_safe_merge(self, model_id, config_cls, config_kwargs):
|
| 763 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 764 |
+
torch.manual_seed(0)
|
| 765 |
+
|
| 766 |
+
with hub_online_once(model_id):
|
| 767 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 768 |
+
config = config_cls(
|
| 769 |
+
base_model_name_or_path=model_id,
|
| 770 |
+
**config_kwargs,
|
| 771 |
+
)
|
| 772 |
+
model = model.to(self.torch_device).eval()
|
| 773 |
+
|
| 774 |
+
inputs = self.prepare_inputs_for_testing()
|
| 775 |
+
logits_base = model(**inputs)[0]
|
| 776 |
+
|
| 777 |
+
model = get_peft_model(model, config).eval()
|
| 778 |
+
logits_peft = model(**inputs)[0]
|
| 779 |
+
|
| 780 |
+
atol, rtol = 1e-6, 1e-6 # default
|
| 781 |
+
# Initializing with LN tuning cannot be configured to change the outputs (unlike init_lora_weights=False)
|
| 782 |
+
if not issubclass(config_cls, LNTuningConfig):
|
| 783 |
+
# sanity check that the logits are different
|
| 784 |
+
assert not torch.allclose(logits_base, logits_peft, atol=atol, rtol=rtol)
|
| 785 |
+
|
| 786 |
+
model_unloaded = model.merge_and_unload(safe_merge=True)
|
| 787 |
+
logits_unloaded = model_unloaded(**inputs)[0]
|
| 788 |
+
|
| 789 |
+
if self.torch_device in ["mlu"]:
|
| 790 |
+
atol, rtol = 1e-3, 1e-3 # MLU
|
| 791 |
+
|
| 792 |
+
conv_ids = ["Conv2d", "Conv3d", "Conv2d2"]
|
| 793 |
+
if issubclass(config_cls, (IA3Config, LoraConfig)) and model_id in conv_ids: # more instability with Conv
|
| 794 |
+
atol, rtol = 1e-3, 1e-3
|
| 795 |
+
|
| 796 |
+
# check that the logits are the same after unloading
|
| 797 |
+
assert torch.allclose(logits_peft, logits_unloaded, atol=atol, rtol=rtol)
|
| 798 |
+
|
| 799 |
+
# Ensure that serializing with safetensors works, there was an error when weights were not contiguous
|
| 800 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 801 |
+
# serializing with torch.save works
|
| 802 |
+
torch.save(model_unloaded.state_dict(), os.path.join(tmp_dirname, "model.bin"))
|
| 803 |
+
|
| 804 |
+
# serializing with safetensors works
|
| 805 |
+
save_file(model_unloaded.state_dict(), os.path.join(tmp_dirname, "model.safetensors"))
|
| 806 |
+
|
| 807 |
+
def _test_mixed_adapter_batches(self, model_id, config_cls, config_kwargs):
|
| 808 |
+
# Test for mixing different adapters in a single batch by passing the adapter_names argument
|
| 809 |
+
if config_cls not in (LoraConfig, RoadConfig):
|
| 810 |
+
pytest.skip(f"Mixed adapter batches not supported for {config_cls}")
|
| 811 |
+
|
| 812 |
+
config = config_cls(
|
| 813 |
+
base_model_name_or_path=model_id,
|
| 814 |
+
**config_kwargs,
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
torch.manual_seed(0)
|
| 818 |
+
with hub_online_once(model_id):
|
| 819 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 820 |
+
model = get_peft_model(model, config, adapter_name="adapter0").eval()
|
| 821 |
+
model.add_adapter("adapter1", config)
|
| 822 |
+
model = model.to(self.torch_device).eval()
|
| 823 |
+
|
| 824 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs, adapter_name="adapter0")
|
| 825 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs, adapter_name="adapter1")
|
| 826 |
+
|
| 827 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 828 |
+
# ensure that we have at least 3 samples for this test
|
| 829 |
+
dummy_input = {k: torch.cat([v for _ in range(3)]) for k, v in dummy_input.items()}
|
| 830 |
+
with torch.inference_mode():
|
| 831 |
+
with model.disable_adapter():
|
| 832 |
+
output_base = model(**dummy_input)[0]
|
| 833 |
+
logits_base = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 834 |
+
|
| 835 |
+
model.set_adapter("adapter0")
|
| 836 |
+
with torch.inference_mode():
|
| 837 |
+
output_adapter0 = model(**dummy_input)[0]
|
| 838 |
+
logits_adapter0 = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 839 |
+
|
| 840 |
+
model.set_adapter("adapter1")
|
| 841 |
+
with torch.inference_mode():
|
| 842 |
+
output_adapter1 = model(**dummy_input)[0]
|
| 843 |
+
logits_adapter1 = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 844 |
+
|
| 845 |
+
atol, rtol = 1e-4, 1e-4
|
| 846 |
+
# sanity check that there are enough outputs and that they are different
|
| 847 |
+
assert len(output_base) == len(output_adapter0) == len(output_adapter1) >= 3
|
| 848 |
+
assert len(logits_base) == len(logits_adapter0) == len(logits_adapter1) >= 3
|
| 849 |
+
assert not torch.allclose(output_base, output_adapter0, atol=atol, rtol=rtol)
|
| 850 |
+
assert not torch.allclose(output_base, output_adapter1, atol=atol, rtol=rtol)
|
| 851 |
+
assert not torch.allclose(output_adapter0, output_adapter1, atol=atol, rtol=rtol)
|
| 852 |
+
assert not torch.allclose(logits_base, logits_adapter0, atol=atol, rtol=rtol)
|
| 853 |
+
assert not torch.allclose(logits_base, logits_adapter1, atol=atol, rtol=rtol)
|
| 854 |
+
assert not torch.allclose(logits_adapter0, logits_adapter1, atol=atol, rtol=rtol)
|
| 855 |
+
|
| 856 |
+
# alternate between base model, adapter0, and adapter1
|
| 857 |
+
adapters = ["__base__", "adapter0", "adapter1"]
|
| 858 |
+
dummy_input["adapter_names"] = [adapters[i % 3] for i in (range(len(dummy_input["input_ids"])))]
|
| 859 |
+
with torch.inference_mode():
|
| 860 |
+
output_mixed = model(**dummy_input)[0]
|
| 861 |
+
logits_mixed = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 862 |
+
|
| 863 |
+
assert torch.allclose(output_base[::3], output_mixed[::3], atol=atol, rtol=rtol)
|
| 864 |
+
assert torch.allclose(output_adapter0[1::3], output_mixed[1::3], atol=atol, rtol=rtol)
|
| 865 |
+
assert torch.allclose(output_adapter1[2::3], output_mixed[2::3], atol=atol, rtol=rtol)
|
| 866 |
+
assert torch.allclose(logits_base[::3], logits_mixed[::3], atol=atol, rtol=rtol)
|
| 867 |
+
assert torch.allclose(logits_adapter0[1::3], logits_mixed[1::3], atol=atol, rtol=rtol)
|
| 868 |
+
assert torch.allclose(logits_adapter1[2::3], logits_mixed[2::3], atol=atol, rtol=rtol)
|
| 869 |
+
|
| 870 |
+
def _test_generate_with_mixed_adapter_batches_and_beam_search(self, model_id, config_cls, config_kwargs):
|
| 871 |
+
# Test generating with beam search and with mixing different adapters in a single batch by passing the
|
| 872 |
+
# adapter_names argument. See #2283.
|
| 873 |
+
if config_cls not in (LoraConfig,):
|
| 874 |
+
# note: RoAD supports mixed adapter batches but not beam search
|
| 875 |
+
pytest.skip(f"Mixed adapter batches not supported for {config_cls}")
|
| 876 |
+
if config_kwargs.get("alora_invocation_tokens") is not None:
|
| 877 |
+
pytest.skip("Beam search not yet supported for aLoRA") # beam search not yet fully supported
|
| 878 |
+
if config_kwargs.get("trainable_token_indices", None) is not None:
|
| 879 |
+
# for some configurations this test will fail since the adapter values don't differ.
|
| 880 |
+
# this is probably a problem with the test setup and not with the implementation.
|
| 881 |
+
pytest.skip("Trainable token indices is not supported here (yet).")
|
| 882 |
+
|
| 883 |
+
config = config_cls(
|
| 884 |
+
base_model_name_or_path=model_id,
|
| 885 |
+
**config_kwargs,
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
torch.manual_seed(0)
|
| 889 |
+
with hub_online_once(model_id):
|
| 890 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 891 |
+
model = get_peft_model(model, config, adapter_name="adapter0").eval()
|
| 892 |
+
model.add_adapter("adapter1", config)
|
| 893 |
+
|
| 894 |
+
# In contrast to forward, for generate, it can sometimes happen that we get the same results as the base model
|
| 895 |
+
# even with LoRA applied because the impact of LoRA is not big enough. Therefore, use this "trick" to make LoRA
|
| 896 |
+
# stronger.
|
| 897 |
+
for name, param in model.named_parameters():
|
| 898 |
+
if model.base_model.prefix in name:
|
| 899 |
+
param.data.mul_(10.0)
|
| 900 |
+
|
| 901 |
+
model = model.to(self.torch_device).eval()
|
| 902 |
+
|
| 903 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 904 |
+
# ensure that we have at least 3 samples for this test
|
| 905 |
+
dummy_input = {k: torch.cat([v for _ in range(3)]) for k, v in dummy_input.items()}
|
| 906 |
+
gen_kwargs = {**dummy_input, "max_length": 20, "num_beams": 10, "early_stopping": True}
|
| 907 |
+
with torch.inference_mode():
|
| 908 |
+
with model.disable_adapter():
|
| 909 |
+
gen_base = model.generate(**gen_kwargs)
|
| 910 |
+
|
| 911 |
+
model.set_adapter("adapter0")
|
| 912 |
+
with torch.inference_mode():
|
| 913 |
+
gen_adapter0 = model.generate(**gen_kwargs)
|
| 914 |
+
|
| 915 |
+
model.set_adapter("adapter1")
|
| 916 |
+
with torch.inference_mode():
|
| 917 |
+
gen_adapter1 = model.generate(**gen_kwargs)
|
| 918 |
+
|
| 919 |
+
def remove_padding(seq, pad_value):
|
| 920 |
+
lst = list(seq)
|
| 921 |
+
while lst and (lst[-1] == pad_value):
|
| 922 |
+
lst.pop()
|
| 923 |
+
return lst
|
| 924 |
+
|
| 925 |
+
def gens_are_same(gen0, gen1):
|
| 926 |
+
# Special function to compare generations. We cannot use torch.allclose it will raise an error when sequence
|
| 927 |
+
# lengths differ. Morevoer, we need to remove the padding from the sequences. This is because, even though
|
| 928 |
+
# normally identical sequences should have the same length, when we do mixed adapter batches, each sample
|
| 929 |
+
# will be padded to the longest sequence in that mixed batch, which can be different from the longest
|
| 930 |
+
# sequence without mixed adapter batches.
|
| 931 |
+
pad_value = model.config.eos_token_id
|
| 932 |
+
for sample0, sample1 in zip(gen0, gen1):
|
| 933 |
+
sample0 = remove_padding(sample0, pad_value)
|
| 934 |
+
sample1 = remove_padding(sample1, pad_value)
|
| 935 |
+
if (len(sample0) != len(sample1)) or (sample0 != sample1):
|
| 936 |
+
# at least one sample differs, the generations are not identical
|
| 937 |
+
return False
|
| 938 |
+
return True
|
| 939 |
+
|
| 940 |
+
# sanity check that there are enough outputs and that they are different
|
| 941 |
+
assert len(gen_base) == len(gen_adapter0) == len(gen_adapter1)
|
| 942 |
+
assert len(gen_adapter1) >= 3
|
| 943 |
+
assert not gens_are_same(gen_base, gen_adapter0)
|
| 944 |
+
assert not gens_are_same(gen_base, gen_adapter1)
|
| 945 |
+
assert not gens_are_same(gen_adapter0, gen_adapter1)
|
| 946 |
+
|
| 947 |
+
# alternate between base model, adapter0, and adapter1
|
| 948 |
+
adapters = ["__base__", "adapter0", "adapter1"]
|
| 949 |
+
gen_kwargs["adapter_names"] = [adapters[i % 3] for i in (range(len(dummy_input["input_ids"])))]
|
| 950 |
+
|
| 951 |
+
with torch.inference_mode():
|
| 952 |
+
gen_mixed = model.generate(**gen_kwargs)
|
| 953 |
+
|
| 954 |
+
assert gens_are_same(gen_base[::3], gen_mixed[::3])
|
| 955 |
+
assert gens_are_same(gen_adapter0[1::3], gen_mixed[1::3])
|
| 956 |
+
assert gens_are_same(gen_adapter1[2::3], gen_mixed[2::3])
|
| 957 |
+
|
| 958 |
+
def _test_generate(self, model_id, config_cls, config_kwargs):
|
| 959 |
+
with hub_online_once(model_id):
|
| 960 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 961 |
+
config = config_cls(
|
| 962 |
+
base_model_name_or_path=model_id,
|
| 963 |
+
**config_kwargs,
|
| 964 |
+
)
|
| 965 |
+
model = get_peft_model(model, config)
|
| 966 |
+
model = model.to(self.torch_device)
|
| 967 |
+
|
| 968 |
+
inputs = self.prepare_inputs_for_testing()
|
| 969 |
+
|
| 970 |
+
# check if `generate` works
|
| 971 |
+
_ = model.generate(**inputs)
|
| 972 |
+
|
| 973 |
+
def _test_generate_pos_args(self, model_id, config_cls, config_kwargs, raises_err: bool):
|
| 974 |
+
with hub_online_once(model_id):
|
| 975 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 976 |
+
config = config_cls(
|
| 977 |
+
base_model_name_or_path=model_id,
|
| 978 |
+
**config_kwargs,
|
| 979 |
+
)
|
| 980 |
+
model = get_peft_model(model, config)
|
| 981 |
+
model = model.to(self.torch_device)
|
| 982 |
+
|
| 983 |
+
inputs = self.prepare_inputs_for_testing()
|
| 984 |
+
if raises_err:
|
| 985 |
+
with pytest.raises(TypeError):
|
| 986 |
+
# check if `generate` raises an error if positional arguments are passed
|
| 987 |
+
_ = model.generate(inputs["input_ids"])
|
| 988 |
+
else:
|
| 989 |
+
# check if `generate` works if positional arguments are passed
|
| 990 |
+
_ = model.generate(inputs["input_ids"])
|
| 991 |
+
|
| 992 |
+
def _test_generate_half_prec(self, model_id, config_cls, config_kwargs):
|
| 993 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 994 |
+
|
| 995 |
+
with hub_online_once(model_id):
|
| 996 |
+
model = self.transformers_class.from_pretrained(model_id, dtype=torch.bfloat16)
|
| 997 |
+
config = config_cls(
|
| 998 |
+
base_model_name_or_path=model_id,
|
| 999 |
+
**config_kwargs,
|
| 1000 |
+
)
|
| 1001 |
+
model = get_peft_model(model, config)
|
| 1002 |
+
model = model.to(self.torch_device)
|
| 1003 |
+
|
| 1004 |
+
input_ids = torch.LongTensor([[1, 1, 1], [2, 1, 2]]).to(self.torch_device)
|
| 1005 |
+
attention_mask = torch.LongTensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 1006 |
+
|
| 1007 |
+
# check if `generate` works
|
| 1008 |
+
_ = model.generate(input_ids=input_ids, attention_mask=attention_mask)
|
| 1009 |
+
|
| 1010 |
+
def _test_training(self, model_id, config_cls, config_kwargs):
|
| 1011 |
+
if (config_cls == AdaLoraConfig) and ("roberta" in model_id.lower()):
|
| 1012 |
+
# TODO: no gradients on the "dense" layer, other layers work, not sure why
|
| 1013 |
+
pytest.skip("AdaLora with RoBERTa does not work correctly")
|
| 1014 |
+
if (config_cls == PrefixTuningConfig) and ("bert" in model_id.lower()):
|
| 1015 |
+
# TODO: prefix tuning fails with roberta, deberta, etc., requires investigation
|
| 1016 |
+
pytest.skip("Prefix tuning fails with Bert* type models.")
|
| 1017 |
+
|
| 1018 |
+
with hub_online_once(model_id):
|
| 1019 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1020 |
+
config = config_cls(
|
| 1021 |
+
base_model_name_or_path=model_id,
|
| 1022 |
+
**config_kwargs,
|
| 1023 |
+
)
|
| 1024 |
+
model = get_peft_model(model, config)
|
| 1025 |
+
model = model.to(self.torch_device)
|
| 1026 |
+
|
| 1027 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1028 |
+
|
| 1029 |
+
# check if `training` works
|
| 1030 |
+
output = model(**inputs)[0]
|
| 1031 |
+
loss = output.sum()
|
| 1032 |
+
loss.backward()
|
| 1033 |
+
|
| 1034 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 1035 |
+
# we cannot reliably identify the trainable part of the prompt learning method, thus skipping this check
|
| 1036 |
+
return
|
| 1037 |
+
|
| 1038 |
+
for n, param in model.named_parameters():
|
| 1039 |
+
if (model.prefix in n) or ("modules_to_save" in n) or ("token_adapter.trainable_tokens" in n):
|
| 1040 |
+
assert param.grad is not None
|
| 1041 |
+
else:
|
| 1042 |
+
assert param.grad is None
|
| 1043 |
+
|
| 1044 |
+
def _test_inference_safetensors(self, model_id, config_cls, config_kwargs):
|
| 1045 |
+
if (config_cls == PrefixTuningConfig) and ("deberta" in model_id.lower()):
|
| 1046 |
+
# TODO: raises an error:
|
| 1047 |
+
# TypeError: DebertaModel.forward() got an unexpected keyword argument 'past_key_values'
|
| 1048 |
+
pytest.skip("DeBERTa with PrefixTuning does not work correctly")
|
| 1049 |
+
|
| 1050 |
+
config = config_cls(
|
| 1051 |
+
base_model_name_or_path=model_id,
|
| 1052 |
+
**config_kwargs,
|
| 1053 |
+
)
|
| 1054 |
+
with hub_online_once(model_id):
|
| 1055 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1056 |
+
model = get_peft_model(model, config)
|
| 1057 |
+
model = model.to(self.torch_device)
|
| 1058 |
+
|
| 1059 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1060 |
+
|
| 1061 |
+
# check if `training` works
|
| 1062 |
+
output = model(**inputs)[0]
|
| 1063 |
+
logits = output[0]
|
| 1064 |
+
|
| 1065 |
+
loss = output.sum()
|
| 1066 |
+
loss.backward()
|
| 1067 |
+
|
| 1068 |
+
# set to eval mode, since things like dropout can affect the output otherwise
|
| 1069 |
+
model.eval()
|
| 1070 |
+
logits = model(**inputs)[0][0]
|
| 1071 |
+
|
| 1072 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1073 |
+
model.save_pretrained(tmp_dirname, safe_serialization=True)
|
| 1074 |
+
assert "adapter_model.safetensors" in os.listdir(tmp_dirname)
|
| 1075 |
+
assert "adapter_model.bin" not in os.listdir(tmp_dirname)
|
| 1076 |
+
|
| 1077 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 1078 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname).to(
|
| 1079 |
+
self.torch_device
|
| 1080 |
+
)
|
| 1081 |
+
|
| 1082 |
+
logits_from_pretrained = model_from_pretrained(**inputs)[0][0]
|
| 1083 |
+
assert torch.allclose(logits, logits_from_pretrained, atol=1e-4, rtol=1e-4)
|
| 1084 |
+
|
| 1085 |
+
def _test_training_layer_indexing(self, model_id, config_cls, config_kwargs):
|
| 1086 |
+
if config_cls in (VBLoRAConfig, VeraConfig):
|
| 1087 |
+
# TODO investigate why these two are flaky
|
| 1088 |
+
# pytest tests/test_decoder_models.py tests/test_feature_extraction_models.py -k "layer_indexing and (vera
|
| 1089 |
+
# or vblora)"
|
| 1090 |
+
pytest.skip("VBLoRA and VeRA are flaky with layer indexing, possibly because of shared weights.")
|
| 1091 |
+
try:
|
| 1092 |
+
config = config_cls(
|
| 1093 |
+
base_model_name_or_path=model_id,
|
| 1094 |
+
layers_to_transform=[0],
|
| 1095 |
+
**config_kwargs,
|
| 1096 |
+
)
|
| 1097 |
+
except TypeError:
|
| 1098 |
+
pytest.skip("This PEFT method does not support layers_to_transform, skipping it.")
|
| 1099 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 1100 |
+
|
| 1101 |
+
with hub_online_once(model_id):
|
| 1102 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1103 |
+
model = get_peft_model(model, config)
|
| 1104 |
+
model = model.to(self.torch_device)
|
| 1105 |
+
|
| 1106 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1107 |
+
|
| 1108 |
+
# check if `training` works
|
| 1109 |
+
output = model(**inputs)[0]
|
| 1110 |
+
logits = output[0]
|
| 1111 |
+
|
| 1112 |
+
loss = output.sum()
|
| 1113 |
+
loss.backward()
|
| 1114 |
+
|
| 1115 |
+
has_trainable_tokens = config_kwargs.get("trainable_token_indices", None) is not None
|
| 1116 |
+
nb_trainable = 0
|
| 1117 |
+
|
| 1118 |
+
for n, param in model.named_parameters():
|
| 1119 |
+
if model.prefix in n or (has_trainable_tokens and "trainable_tokens" in n):
|
| 1120 |
+
assert param.grad is not None
|
| 1121 |
+
nb_trainable += 1
|
| 1122 |
+
else:
|
| 1123 |
+
assert param.grad is None
|
| 1124 |
+
|
| 1125 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1126 |
+
model.save_pretrained(tmp_dirname)
|
| 1127 |
+
|
| 1128 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 1129 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname).to(
|
| 1130 |
+
self.torch_device
|
| 1131 |
+
)
|
| 1132 |
+
|
| 1133 |
+
logits_from_pretrained = model_from_pretrained(**inputs)[0][0]
|
| 1134 |
+
atol, rtol = 1e-4, 1e-4
|
| 1135 |
+
assert torch.allclose(logits, logits_from_pretrained, atol=atol, rtol=rtol)
|
| 1136 |
+
|
| 1137 |
+
# check the nb of trainable params again but without layers_to_transform
|
| 1138 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1139 |
+
config = config_cls(
|
| 1140 |
+
base_model_name_or_path=model_id,
|
| 1141 |
+
**config_kwargs,
|
| 1142 |
+
)
|
| 1143 |
+
model = get_peft_model(model, config)
|
| 1144 |
+
nb_trainable_all = 0
|
| 1145 |
+
|
| 1146 |
+
for n, param in model.named_parameters():
|
| 1147 |
+
if model.prefix in n or (has_trainable_tokens and "trainable_tokens" in n):
|
| 1148 |
+
nb_trainable_all += 1
|
| 1149 |
+
|
| 1150 |
+
mod_list = next((m for m in model.modules() if isinstance(m, torch.nn.ModuleList)), None)
|
| 1151 |
+
if mod_list and len(mod_list) == 1:
|
| 1152 |
+
# there is only a single layer
|
| 1153 |
+
assert nb_trainable == nb_trainable_all
|
| 1154 |
+
else:
|
| 1155 |
+
# more than 1 layer, i.e. setting layers_to_transform=[0] should target fewer layers
|
| 1156 |
+
assert nb_trainable < nb_trainable_all
|
| 1157 |
+
|
| 1158 |
+
def _test_training_gradient_checkpointing(self, model_id, config_cls, config_kwargs, use_reentrant=True):
|
| 1159 |
+
# Note that certain configurations, such as activated lora with 'alora_invocation_tokens': [1000], do not
|
| 1160 |
+
# generate gradients since the adapter is never activated so this will be a no-op for this test. It is still
|
| 1161 |
+
# a valid test but it might be confusing to see a test pass if it is not supposed to.
|
| 1162 |
+
|
| 1163 |
+
if config_cls == PrefixTuningConfig:
|
| 1164 |
+
pytest.skip("Prefix Tuning does not support gradient checkpointing, skipping this test.")
|
| 1165 |
+
if (config_cls == AdaLoraConfig) and ("roberta" in model_id.lower()):
|
| 1166 |
+
# TODO: no gradients on the "dense" layer, other layers work, not sure why
|
| 1167 |
+
pytest.skip("AdaLora with RoBERTa does not work correctly")
|
| 1168 |
+
|
| 1169 |
+
if not is_transformers_ge_v5:
|
| 1170 |
+
# TODO: remove once transformers < 5.0 no longer supported
|
| 1171 |
+
if "gptbigcode" in model_id.lower():
|
| 1172 |
+
pytest.skip("GPTBigCode doesn't implement gradient checkpointing correctly in transformers < 5.0.")
|
| 1173 |
+
if "bart" in model_id.lower():
|
| 1174 |
+
pytest.skip(
|
| 1175 |
+
"Bart in transformers < 5.0 doesn't handle input sharing well enough. See transformers#41821"
|
| 1176 |
+
)
|
| 1177 |
+
|
| 1178 |
+
with hub_online_once(model_id):
|
| 1179 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1180 |
+
|
| 1181 |
+
if not getattr(model, "supports_gradient_checkpointing", False):
|
| 1182 |
+
pytest.skip(f"Model {model_id} does not support gradient checkpointing")
|
| 1183 |
+
|
| 1184 |
+
# Disable lora_dropout and friends to remove non-determinism in gradient creation
|
| 1185 |
+
for key in list(config_kwargs.keys()):
|
| 1186 |
+
if key.endswith("dropout"):
|
| 1187 |
+
del config_kwargs[key]
|
| 1188 |
+
|
| 1189 |
+
config = config_cls(
|
| 1190 |
+
base_model_name_or_path=model_id,
|
| 1191 |
+
**config_kwargs,
|
| 1192 |
+
)
|
| 1193 |
+
model = get_peft_model(model, config)
|
| 1194 |
+
model = model.to(self.torch_device)
|
| 1195 |
+
params = [(n, p) for n, p in model.named_parameters() if p.requires_grad]
|
| 1196 |
+
|
| 1197 |
+
# if we don't set this, gradient checkpointing is not activated.
|
| 1198 |
+
model.train(True)
|
| 1199 |
+
|
| 1200 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1201 |
+
|
| 1202 |
+
# invocation to get the reference non-zero grads that are supposed to exist without gradient checkpointing;
|
| 1203 |
+
# note we're squaring the output for bigger gradients
|
| 1204 |
+
output = model(**inputs)[0] ** 2
|
| 1205 |
+
|
| 1206 |
+
loss = output.sum()
|
| 1207 |
+
loss.backward()
|
| 1208 |
+
|
| 1209 |
+
non_zero_grad_params_normal = {n for n, p in params if p.grad.abs().sum() > 0}
|
| 1210 |
+
|
| 1211 |
+
for name, param in params:
|
| 1212 |
+
param.grad = None
|
| 1213 |
+
|
| 1214 |
+
# invocation with gradient checkpointing for comparison
|
| 1215 |
+
model.prepare_model_for_gradient_checkpointing(model)
|
| 1216 |
+
model.gradient_checkpointing_enable({"use_reentrant": use_reentrant})
|
| 1217 |
+
|
| 1218 |
+
output = model(**inputs)[0] ** 2
|
| 1219 |
+
|
| 1220 |
+
loss = output.sum()
|
| 1221 |
+
loss.backward()
|
| 1222 |
+
|
| 1223 |
+
non_zero_grad_params_checkpointing = {n for n, p in params if p.grad.abs().sum() > 0}
|
| 1224 |
+
assert non_zero_grad_params_normal == non_zero_grad_params_checkpointing
|
| 1225 |
+
|
| 1226 |
+
for n, param in model.named_parameters():
|
| 1227 |
+
if "prompt_encoder." in n: # prompt tuning methods
|
| 1228 |
+
if not issubclass(config_cls, CPTConfig):
|
| 1229 |
+
assert param.grad is not None
|
| 1230 |
+
elif (
|
| 1231 |
+
"delta_embedding" in n
|
| 1232 |
+
): # delta_embedding is the embedding that should be updated with grads in CPT
|
| 1233 |
+
assert param.grad is not None
|
| 1234 |
+
elif hasattr(model, "prefix") and (model.prefix in n): # non-prompt tuning methods
|
| 1235 |
+
assert param.grad is not None
|
| 1236 |
+
elif "trainable_tokens_" in n: # trainable tokens layer
|
| 1237 |
+
assert param.grad is not None
|
| 1238 |
+
else:
|
| 1239 |
+
assert param.grad is None
|
| 1240 |
+
|
| 1241 |
+
def _test_peft_model_device_map(self, model_id, config_cls, config_kwargs):
|
| 1242 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 1243 |
+
config = config_cls(
|
| 1244 |
+
base_model_name_or_path=model_id,
|
| 1245 |
+
**config_kwargs,
|
| 1246 |
+
)
|
| 1247 |
+
|
| 1248 |
+
with hub_online_once(model_id):
|
| 1249 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1250 |
+
|
| 1251 |
+
model = get_peft_model(model, config)
|
| 1252 |
+
model = model.to(self.torch_device)
|
| 1253 |
+
|
| 1254 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1255 |
+
model.save_pretrained(tmp_dirname)
|
| 1256 |
+
|
| 1257 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 1258 |
+
_ = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname, device_map={"": "cpu"}).to(
|
| 1259 |
+
self.torch_device
|
| 1260 |
+
)
|
| 1261 |
+
|
| 1262 |
+
def _test_training_prompt_learning_tasks(self, model_id, config_cls, config_kwargs):
|
| 1263 |
+
if not issubclass(config_cls, PromptLearningConfig):
|
| 1264 |
+
pytest.skip(f"Test not applicable for {config_cls}")
|
| 1265 |
+
|
| 1266 |
+
with hub_online_once(model_id):
|
| 1267 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1268 |
+
config = config_cls(
|
| 1269 |
+
base_model_name_or_path=model_id,
|
| 1270 |
+
**config_kwargs,
|
| 1271 |
+
)
|
| 1272 |
+
model = get_peft_model(model, config)
|
| 1273 |
+
model = model.to(self.torch_device)
|
| 1274 |
+
|
| 1275 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1276 |
+
|
| 1277 |
+
# check if `training` works
|
| 1278 |
+
output = model(**inputs)[0]
|
| 1279 |
+
loss = output.sum()
|
| 1280 |
+
loss.backward()
|
| 1281 |
+
|
| 1282 |
+
if issubclass(config_cls, CPTConfig):
|
| 1283 |
+
parameters = []
|
| 1284 |
+
for name, param in model.prompt_encoder.named_parameters():
|
| 1285 |
+
if name != "default.embedding.weight":
|
| 1286 |
+
parameters.append(param)
|
| 1287 |
+
else:
|
| 1288 |
+
parameters = model.prompt_encoder.parameters()
|
| 1289 |
+
|
| 1290 |
+
# check that prompt encoder has grads
|
| 1291 |
+
for param in parameters:
|
| 1292 |
+
assert param.grad is not None
|
| 1293 |
+
|
| 1294 |
+
def _test_delete_adapter(self, model_id, config_cls, config_kwargs):
|
| 1295 |
+
_skip_if_deleting_adapter_not_supported(config_cls, config_kwargs)
|
| 1296 |
+
if config_cls == AdaLoraConfig:
|
| 1297 |
+
pytest.skip("AdaLoRA does not support multiple adapters")
|
| 1298 |
+
|
| 1299 |
+
config = config_cls(
|
| 1300 |
+
base_model_name_or_path=model_id,
|
| 1301 |
+
**config_kwargs,
|
| 1302 |
+
)
|
| 1303 |
+
|
| 1304 |
+
with hub_online_once(model_id):
|
| 1305 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1306 |
+
adapter_to_delete = "delete_me"
|
| 1307 |
+
model = get_peft_model(model, config)
|
| 1308 |
+
model.add_adapter(adapter_to_delete, config)
|
| 1309 |
+
model.set_adapter(adapter_to_delete)
|
| 1310 |
+
model = model.to(self.torch_device)
|
| 1311 |
+
model.delete_adapter(adapter_to_delete)
|
| 1312 |
+
assert adapter_to_delete not in model.peft_config
|
| 1313 |
+
assert model.active_adapters == ["default"]
|
| 1314 |
+
|
| 1315 |
+
key_list = [key for key, _ in model.named_modules()]
|
| 1316 |
+
for key in key_list:
|
| 1317 |
+
_, target, _ = _get_submodules(model, key)
|
| 1318 |
+
attributes_to_check = getattr(target, "adapter_layer_names", []) + getattr(
|
| 1319 |
+
target, "other_param_names", []
|
| 1320 |
+
)
|
| 1321 |
+
for attr in attributes_to_check:
|
| 1322 |
+
assert adapter_to_delete not in attrgetter(attr)(target)
|
| 1323 |
+
|
| 1324 |
+
# check auxiliary modules
|
| 1325 |
+
for module in model.modules():
|
| 1326 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1327 |
+
assert adapter_to_delete not in module._adapters
|
| 1328 |
+
assert module.active_adapters == ["default"]
|
| 1329 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1330 |
+
assert adapter_to_delete not in module.modules_to_save
|
| 1331 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1332 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_delta
|
| 1333 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_original
|
| 1334 |
+
|
| 1335 |
+
# check that we can also delete the last remaining adapter
|
| 1336 |
+
model.delete_adapter("default")
|
| 1337 |
+
assert "default" not in model.peft_config
|
| 1338 |
+
assert model.active_adapters == []
|
| 1339 |
+
|
| 1340 |
+
for module in model.modules():
|
| 1341 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1342 |
+
assert "default" not in module._adapters
|
| 1343 |
+
assert module.active_adapters == []
|
| 1344 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1345 |
+
assert "default" not in module.modules_to_save
|
| 1346 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1347 |
+
assert "default" not in module.token_adapter.trainable_tokens_delta
|
| 1348 |
+
assert "default" not in module.token_adapter.trainable_tokens_original
|
| 1349 |
+
|
| 1350 |
+
input = self.prepare_inputs_for_testing()
|
| 1351 |
+
# note: we cannot call model(**input) because PeftModel always expects there to be at least one adapter
|
| 1352 |
+
model.base_model(**input) # should not raise an error
|
| 1353 |
+
|
| 1354 |
+
def _test_delete_inactive_adapter(self, model_id, config_cls, config_kwargs):
|
| 1355 |
+
if config_cls == AdaLoraConfig:
|
| 1356 |
+
pytest.skip("AdaLoRA does not support multiple adapters")
|
| 1357 |
+
_skip_if_deleting_adapter_not_supported(config_cls, config_kwargs)
|
| 1358 |
+
|
| 1359 |
+
config = config_cls(
|
| 1360 |
+
base_model_name_or_path=model_id,
|
| 1361 |
+
**config_kwargs,
|
| 1362 |
+
)
|
| 1363 |
+
|
| 1364 |
+
with hub_online_once(model_id):
|
| 1365 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1366 |
+
adapter_to_delete = "delete_me"
|
| 1367 |
+
model = get_peft_model(model, config)
|
| 1368 |
+
model.add_adapter(adapter_to_delete, config)
|
| 1369 |
+
# "delete_me" is added but not activated
|
| 1370 |
+
model = model.to(self.torch_device)
|
| 1371 |
+
model.delete_adapter(adapter_to_delete)
|
| 1372 |
+
assert adapter_to_delete not in model.peft_config
|
| 1373 |
+
assert model.active_adapters == ["default"]
|
| 1374 |
+
|
| 1375 |
+
key_list = [key for key, _ in model.named_modules()]
|
| 1376 |
+
for key in key_list:
|
| 1377 |
+
_, target, _ = _get_submodules(model, key)
|
| 1378 |
+
attributes_to_check = getattr(target, "adapter_layer_names", []) + getattr(
|
| 1379 |
+
target, "other_param_names", []
|
| 1380 |
+
)
|
| 1381 |
+
for attr in attributes_to_check:
|
| 1382 |
+
assert adapter_to_delete not in attrgetter(attr)(target)
|
| 1383 |
+
|
| 1384 |
+
# check auxiliary modules
|
| 1385 |
+
for module in model.modules():
|
| 1386 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1387 |
+
assert adapter_to_delete not in module._adapters
|
| 1388 |
+
assert module.active_adapters == ["default"]
|
| 1389 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1390 |
+
assert adapter_to_delete not in module.modules_to_save
|
| 1391 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1392 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_delta
|
| 1393 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_original
|
| 1394 |
+
|
| 1395 |
+
# check that we can also delete the last remaining adapter
|
| 1396 |
+
model.delete_adapter("default")
|
| 1397 |
+
assert "default" not in model.peft_config
|
| 1398 |
+
assert model.active_adapters == []
|
| 1399 |
+
|
| 1400 |
+
for module in model.modules():
|
| 1401 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1402 |
+
assert "default" not in module._adapters
|
| 1403 |
+
assert module.active_adapters == []
|
| 1404 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1405 |
+
assert "default" not in module.modules_to_save
|
| 1406 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1407 |
+
assert "default" not in module.token_adapter.trainable_tokens_delta
|
| 1408 |
+
assert "default" not in module.token_adapter.trainable_tokens_original
|
| 1409 |
+
|
| 1410 |
+
input = self.prepare_inputs_for_testing()
|
| 1411 |
+
# note: we cannot call model(**input) because PeftModel always expects there to be at least one adapter
|
| 1412 |
+
model.base_model(**input) # should not raise an error
|
| 1413 |
+
|
| 1414 |
+
def _test_delete_unknown_adapter_raises(self, model_id, config_cls, config_kwargs):
|
| 1415 |
+
# Check that we get a nice error message when trying to delete an adapter that does not exist.
|
| 1416 |
+
config = config_cls(base_model_name_or_path=model_id, **config_kwargs)
|
| 1417 |
+
with hub_online_once(model_id):
|
| 1418 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1419 |
+
adapter_to_delete = "delete_me"
|
| 1420 |
+
model = get_peft_model(model, config)
|
| 1421 |
+
|
| 1422 |
+
msg = "Adapter unknown-adapter does not exist"
|
| 1423 |
+
with pytest.raises(ValueError, match=msg):
|
| 1424 |
+
model.delete_adapter("unknown-adapter")
|
| 1425 |
+
|
| 1426 |
+
def _test_unload_adapter(self, model_id, config_cls, config_kwargs):
|
| 1427 |
+
with hub_online_once(model_id):
|
| 1428 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1429 |
+
num_params_base = len(model.state_dict())
|
| 1430 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1431 |
+
with torch.inference_mode():
|
| 1432 |
+
logits_transformers = model(**dummy_input)[0]
|
| 1433 |
+
|
| 1434 |
+
config = config_cls(
|
| 1435 |
+
base_model_name_or_path=model_id,
|
| 1436 |
+
**config_kwargs,
|
| 1437 |
+
)
|
| 1438 |
+
model = get_peft_model(model, config)
|
| 1439 |
+
model = model.to(self.torch_device)
|
| 1440 |
+
|
| 1441 |
+
if isinstance(config, PromptLearningConfig):
|
| 1442 |
+
# prompt learning does not support unloading
|
| 1443 |
+
with pytest.raises(AttributeError):
|
| 1444 |
+
model = model.unload()
|
| 1445 |
+
else:
|
| 1446 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 1447 |
+
with torch.inference_mode():
|
| 1448 |
+
logits_with_adapter = model(**dummy_input)[0]
|
| 1449 |
+
|
| 1450 |
+
model.eval()
|
| 1451 |
+
model = model.unload()
|
| 1452 |
+
num_params_unloaded = len(model.state_dict())
|
| 1453 |
+
with torch.inference_mode():
|
| 1454 |
+
logits_unload = model(**dummy_input)[0]
|
| 1455 |
+
|
| 1456 |
+
# check that PEFT layers are completely removed
|
| 1457 |
+
assert not any(isinstance(module, BaseTunerLayer) for module in model.modules())
|
| 1458 |
+
assert not torch.allclose(logits_with_adapter, logits_unload, atol=1e-10, rtol=1e-10)
|
| 1459 |
+
assert torch.allclose(logits_transformers, logits_unload, atol=1e-4, rtol=1e-4)
|
| 1460 |
+
assert num_params_base == num_params_unloaded
|
| 1461 |
+
|
| 1462 |
+
def _test_weighted_combination_of_adapters_lora(self, model, config, adapter_list, weight_list):
|
| 1463 |
+
_skip_if_adding_weighted_adapters_not_supported(config)
|
| 1464 |
+
model.add_adapter(adapter_list[1], config)
|
| 1465 |
+
model.add_adapter(adapter_list[2], replace(config, r=20))
|
| 1466 |
+
model = model.to(self.torch_device)
|
| 1467 |
+
|
| 1468 |
+
# test re-weighting single adapter
|
| 1469 |
+
model.add_weighted_adapter([adapter_list[0]], [weight_list[0]], "single_adapter_reweighting")
|
| 1470 |
+
|
| 1471 |
+
# test svd re-weighting with multiple adapters
|
| 1472 |
+
model.add_weighted_adapter(adapter_list[1:], weight_list[1:], "multi_adapter_svd_reweighting")
|
| 1473 |
+
|
| 1474 |
+
# test ties_svd re-weighting with multiple adapters
|
| 1475 |
+
model.add_weighted_adapter(
|
| 1476 |
+
adapter_list[1:],
|
| 1477 |
+
weight_list[1:],
|
| 1478 |
+
"multi_adapter_ties_svd_reweighting",
|
| 1479 |
+
combination_type="ties_svd",
|
| 1480 |
+
density=0.5,
|
| 1481 |
+
)
|
| 1482 |
+
|
| 1483 |
+
# test dare_linear_svd re-weighting with multiple adapters
|
| 1484 |
+
model.add_weighted_adapter(
|
| 1485 |
+
adapter_list[1:],
|
| 1486 |
+
weight_list[1:],
|
| 1487 |
+
"multi_adapter_dare_linear_svd_reweighting",
|
| 1488 |
+
combination_type="dare_linear_svd",
|
| 1489 |
+
density=0.5,
|
| 1490 |
+
)
|
| 1491 |
+
|
| 1492 |
+
# test dare_ties_svd re-weighting with multiple adapters
|
| 1493 |
+
model.add_weighted_adapter(
|
| 1494 |
+
adapter_list[1:],
|
| 1495 |
+
weight_list[1:],
|
| 1496 |
+
"multi_adapter_dare_ties_svd_reweighting",
|
| 1497 |
+
combination_type="dare_ties_svd",
|
| 1498 |
+
density=0.5,
|
| 1499 |
+
)
|
| 1500 |
+
|
| 1501 |
+
# test magnitude_prune_svd re-weighting with multiple adapters
|
| 1502 |
+
model.add_weighted_adapter(
|
| 1503 |
+
adapter_list[1:],
|
| 1504 |
+
weight_list[1:],
|
| 1505 |
+
"multi_adapter_magnitude_prune_svd_reweighting",
|
| 1506 |
+
combination_type="magnitude_prune_svd",
|
| 1507 |
+
density=0.5,
|
| 1508 |
+
)
|
| 1509 |
+
|
| 1510 |
+
# test cat re-weighting with multiple adapters
|
| 1511 |
+
model.add_weighted_adapter(
|
| 1512 |
+
adapter_list[1:], weight_list[1:], "multi_adapter_cat_reweighting", combination_type="cat"
|
| 1513 |
+
)
|
| 1514 |
+
|
| 1515 |
+
# test linear re-weighting with multiple adapters
|
| 1516 |
+
model.add_weighted_adapter(
|
| 1517 |
+
adapter_list[:2], weight_list[:2], "multi_adapter_linear_reweighting", combination_type="linear"
|
| 1518 |
+
)
|
| 1519 |
+
|
| 1520 |
+
# test ties re-weighting with multiple adapters
|
| 1521 |
+
model.add_weighted_adapter(
|
| 1522 |
+
adapter_list[:2], weight_list[:2], "multi_adapter_ties_reweighting", combination_type="ties", density=0.5
|
| 1523 |
+
)
|
| 1524 |
+
|
| 1525 |
+
# test dare_linear re-weighting with multiple adapters
|
| 1526 |
+
model.add_weighted_adapter(
|
| 1527 |
+
adapter_list[:2],
|
| 1528 |
+
weight_list[:2],
|
| 1529 |
+
"multi_adapter_dare_linear_reweighting",
|
| 1530 |
+
combination_type="dare_linear",
|
| 1531 |
+
density=0.5,
|
| 1532 |
+
)
|
| 1533 |
+
|
| 1534 |
+
# test dare_ties re-weighting with multiple adapters
|
| 1535 |
+
model.add_weighted_adapter(
|
| 1536 |
+
adapter_list[:2],
|
| 1537 |
+
weight_list[:2],
|
| 1538 |
+
"multi_adapter_dare_ties_reweighting",
|
| 1539 |
+
combination_type="dare_ties",
|
| 1540 |
+
density=0.5,
|
| 1541 |
+
)
|
| 1542 |
+
|
| 1543 |
+
# test magnitude_prune re-weighting with multiple adapters
|
| 1544 |
+
model.add_weighted_adapter(
|
| 1545 |
+
adapter_list[:2],
|
| 1546 |
+
weight_list[:2],
|
| 1547 |
+
"multi_adapter_magnitude_prune_reweighting",
|
| 1548 |
+
combination_type="magnitude_prune",
|
| 1549 |
+
density=0.5,
|
| 1550 |
+
)
|
| 1551 |
+
|
| 1552 |
+
# test linear re-weighting with multiple adapters with only first adapter having non zero weight
|
| 1553 |
+
model.add_weighted_adapter(
|
| 1554 |
+
adapter_list[:2],
|
| 1555 |
+
[weight_list[0], 0],
|
| 1556 |
+
"multi_adapter_linear_reweighting_single_enabled",
|
| 1557 |
+
combination_type="linear",
|
| 1558 |
+
)
|
| 1559 |
+
|
| 1560 |
+
with pytest.raises(ValueError):
|
| 1561 |
+
model.add_weighted_adapter(
|
| 1562 |
+
adapter_list[1:],
|
| 1563 |
+
weight_list[1:],
|
| 1564 |
+
"multi_adapter_linear_reweighting_uneven_r",
|
| 1565 |
+
combination_type="linear",
|
| 1566 |
+
)
|
| 1567 |
+
|
| 1568 |
+
with pytest.raises(ValueError):
|
| 1569 |
+
model.add_weighted_adapter(
|
| 1570 |
+
adapter_list[1:],
|
| 1571 |
+
weight_list[1:],
|
| 1572 |
+
"multi_adapter_ties_reweighting_uneven_r",
|
| 1573 |
+
combination_type="ties",
|
| 1574 |
+
density=0.5,
|
| 1575 |
+
)
|
| 1576 |
+
|
| 1577 |
+
with pytest.raises(ValueError):
|
| 1578 |
+
model.add_weighted_adapter(
|
| 1579 |
+
adapter_list[1:],
|
| 1580 |
+
weight_list[1:],
|
| 1581 |
+
"multi_adapter_dare_linear_reweighting_uneven_r",
|
| 1582 |
+
combination_type="dare_linear",
|
| 1583 |
+
density=0.5,
|
| 1584 |
+
)
|
| 1585 |
+
|
| 1586 |
+
with pytest.raises(ValueError):
|
| 1587 |
+
model.add_weighted_adapter(
|
| 1588 |
+
adapter_list[1:],
|
| 1589 |
+
weight_list[1:],
|
| 1590 |
+
"multi_adapter_dare_ties_reweighting_uneven_r",
|
| 1591 |
+
combination_type="dare_ties",
|
| 1592 |
+
density=0.5,
|
| 1593 |
+
)
|
| 1594 |
+
|
| 1595 |
+
with pytest.raises(ValueError):
|
| 1596 |
+
model.add_weighted_adapter(
|
| 1597 |
+
adapter_list[1:],
|
| 1598 |
+
weight_list[1:],
|
| 1599 |
+
"multi_adapter_magnitude_prune_reweighting_uneven_r",
|
| 1600 |
+
combination_type="magnitude_prune",
|
| 1601 |
+
density=0.5,
|
| 1602 |
+
)
|
| 1603 |
+
|
| 1604 |
+
new_adapters = [
|
| 1605 |
+
"single_adapter_reweighting",
|
| 1606 |
+
"multi_adapter_svd_reweighting",
|
| 1607 |
+
"multi_adapter_ties_svd_reweighting",
|
| 1608 |
+
"multi_adapter_dare_linear_svd_reweighting",
|
| 1609 |
+
"multi_adapter_dare_ties_svd_reweighting",
|
| 1610 |
+
"multi_adapter_magnitude_prune_svd_reweighting",
|
| 1611 |
+
"multi_adapter_cat_reweighting",
|
| 1612 |
+
"multi_adapter_linear_reweighting",
|
| 1613 |
+
"multi_adapter_linear_reweighting_single_enabled",
|
| 1614 |
+
"multi_adapter_ties_reweighting",
|
| 1615 |
+
"multi_adapter_dare_linear_reweighting",
|
| 1616 |
+
"multi_adapter_dare_ties_reweighting",
|
| 1617 |
+
"multi_adapter_magnitude_prune_reweighting",
|
| 1618 |
+
]
|
| 1619 |
+
for new_adapter in new_adapters:
|
| 1620 |
+
assert new_adapter in model.peft_config
|
| 1621 |
+
|
| 1622 |
+
key_list = [key for key, _ in model.named_modules()]
|
| 1623 |
+
for key in key_list:
|
| 1624 |
+
_, target, _ = _get_submodules(model, key)
|
| 1625 |
+
if isinstance(target, LoraLayer):
|
| 1626 |
+
for adapter_name in new_adapters:
|
| 1627 |
+
if "single" in adapter_name:
|
| 1628 |
+
new_delta_weight = target.get_delta_weight(adapter_name)
|
| 1629 |
+
weighted_original_delta_weights = target.get_delta_weight(adapter_list[0]) * weight_list[0]
|
| 1630 |
+
sign = 1 if weight_list[0] > 0 else -1
|
| 1631 |
+
weighted_original_delta_weights = sign * weighted_original_delta_weights
|
| 1632 |
+
assert torch.allclose(new_delta_weight, weighted_original_delta_weights, atol=1e-4, rtol=1e-4)
|
| 1633 |
+
elif "svd" in adapter_name:
|
| 1634 |
+
assert target.r[adapter_name] == 20
|
| 1635 |
+
elif "linear" in adapter_name:
|
| 1636 |
+
assert target.r[adapter_name] == 8
|
| 1637 |
+
elif "cat" in adapter_name:
|
| 1638 |
+
assert target.r[adapter_name] == 28
|
| 1639 |
+
|
| 1640 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1641 |
+
model.eval()
|
| 1642 |
+
for adapter_name in new_adapters:
|
| 1643 |
+
# ensuring new adapters pass the forward loop
|
| 1644 |
+
model.set_adapter(adapter_name)
|
| 1645 |
+
assert model.active_adapter == adapter_name
|
| 1646 |
+
assert model.active_adapters == [adapter_name]
|
| 1647 |
+
model(**dummy_input)[0]
|
| 1648 |
+
|
| 1649 |
+
def _test_weighted_combination_of_adapters_ia3(self, model, config, adapter_list, weight_list):
|
| 1650 |
+
model.add_adapter(adapter_list[1], config)
|
| 1651 |
+
model.add_adapter(adapter_list[2], config)
|
| 1652 |
+
model = model.to(self.torch_device)
|
| 1653 |
+
|
| 1654 |
+
# test re-weighting single adapter
|
| 1655 |
+
model.add_weighted_adapter([adapter_list[0]], [weight_list[0]], "single_adapter_reweighting")
|
| 1656 |
+
|
| 1657 |
+
# test re-weighting with multiple adapters
|
| 1658 |
+
model.add_weighted_adapter(adapter_list[1:], weight_list[1:], "multi_adapter_reweighting")
|
| 1659 |
+
|
| 1660 |
+
new_adapters = [
|
| 1661 |
+
"single_adapter_reweighting",
|
| 1662 |
+
"multi_adapter_reweighting",
|
| 1663 |
+
]
|
| 1664 |
+
for new_adapter in new_adapters:
|
| 1665 |
+
assert new_adapter in model.peft_config
|
| 1666 |
+
|
| 1667 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1668 |
+
model.eval()
|
| 1669 |
+
for adapter_name in new_adapters:
|
| 1670 |
+
# ensuring new adapters pass the forward loop
|
| 1671 |
+
model.set_adapter(adapter_name)
|
| 1672 |
+
assert model.active_adapter == adapter_name
|
| 1673 |
+
assert model.active_adapters == [adapter_name]
|
| 1674 |
+
model(**dummy_input)[0]
|
| 1675 |
+
|
| 1676 |
+
def _test_weighted_combination_of_adapters(self, model_id, config_cls, config_kwargs):
|
| 1677 |
+
if issubclass(config_cls, AdaLoraConfig):
|
| 1678 |
+
# AdaLora does not support adding more than 1 adapter
|
| 1679 |
+
return pytest.skip(f"Test not applicable for {config_cls}")
|
| 1680 |
+
if model_id.endswith("qwen2"):
|
| 1681 |
+
# Qwen2 fails with weighted adapter combinations using SVD
|
| 1682 |
+
return pytest.skip(f"Test does not work with model {model_id}")
|
| 1683 |
+
if "gemma" in model_id.lower():
|
| 1684 |
+
return pytest.skip("Combining Gemma adapters with SVD is currently failing")
|
| 1685 |
+
|
| 1686 |
+
adapter_list = ["adapter1", "adapter_2", "adapter_3"]
|
| 1687 |
+
weight_list = [0.5, 1.5, 1.5]
|
| 1688 |
+
negative_weight_list = [-0.5, -0.8, -1.2]
|
| 1689 |
+
# Initialize the config
|
| 1690 |
+
config = config_cls(
|
| 1691 |
+
base_model_name_or_path=model_id,
|
| 1692 |
+
**config_kwargs,
|
| 1693 |
+
)
|
| 1694 |
+
|
| 1695 |
+
if not isinstance(config, (LoraConfig, IA3Config)):
|
| 1696 |
+
# This test is only applicable for Lora and IA3 configs
|
| 1697 |
+
return pytest.skip(f"Test not applicable for {config}")
|
| 1698 |
+
|
| 1699 |
+
with hub_online_once(model_id):
|
| 1700 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1701 |
+
model = get_peft_model(model, config, adapter_list[0])
|
| 1702 |
+
|
| 1703 |
+
if isinstance(config, LoraConfig):
|
| 1704 |
+
self._test_weighted_combination_of_adapters_lora(model, config, adapter_list, weight_list)
|
| 1705 |
+
self._test_weighted_combination_of_adapters_lora(model, config, adapter_list, negative_weight_list)
|
| 1706 |
+
elif isinstance(config, IA3Config):
|
| 1707 |
+
self._test_weighted_combination_of_adapters_ia3(model, config, adapter_list, weight_list)
|
| 1708 |
+
self._test_weighted_combination_of_adapters_ia3(model, config, adapter_list, negative_weight_list)
|
| 1709 |
+
else:
|
| 1710 |
+
pytest.skip(f"Test not applicable for {config}")
|
| 1711 |
+
|
| 1712 |
+
def _test_disable_adapter(self, model_id, config_cls, config_kwargs):
|
| 1713 |
+
task_type = config_kwargs.get("task_type")
|
| 1714 |
+
if (task_type == "SEQ_2_SEQ_LM") and (config_cls in (PromptTuningConfig, PromptEncoderConfig)):
|
| 1715 |
+
pytest.skip("Seq2Seq + prompt tuning/prompt encoder does not work with disabling adapters")
|
| 1716 |
+
|
| 1717 |
+
def get_output(model):
|
| 1718 |
+
# helper function that works with different model types
|
| 1719 |
+
torch.manual_seed(0)
|
| 1720 |
+
|
| 1721 |
+
if hasattr(model, "generate"):
|
| 1722 |
+
# let's check the scores, not the output ids, since the latter can easily be identical even if the
|
| 1723 |
+
# weights are slightly changed
|
| 1724 |
+
output = model.generate(**input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 1725 |
+
# take element 0, as output is a tuple
|
| 1726 |
+
else:
|
| 1727 |
+
output = model(**input)
|
| 1728 |
+
|
| 1729 |
+
if hasattr(output, "images"): # for SD
|
| 1730 |
+
import numpy as np
|
| 1731 |
+
|
| 1732 |
+
img = output.images[0]
|
| 1733 |
+
return torch.from_numpy(np.array(img))
|
| 1734 |
+
|
| 1735 |
+
return output
|
| 1736 |
+
|
| 1737 |
+
# initialize model
|
| 1738 |
+
with hub_online_once(model_id):
|
| 1739 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1740 |
+
|
| 1741 |
+
# output from BASE MODEL
|
| 1742 |
+
input = self.prepare_inputs_for_testing()
|
| 1743 |
+
output_before = get_output(model)
|
| 1744 |
+
|
| 1745 |
+
# output from PEFT MODEL
|
| 1746 |
+
if hasattr(self, "instantiate_sd_peft"):
|
| 1747 |
+
# SD models are instantiated differently
|
| 1748 |
+
peft_model = self.instantiate_sd_peft(model_id, config_cls, config_kwargs)
|
| 1749 |
+
else:
|
| 1750 |
+
config = config_cls(
|
| 1751 |
+
base_model_name_or_path=model_id,
|
| 1752 |
+
**config_kwargs,
|
| 1753 |
+
)
|
| 1754 |
+
peft_model = get_peft_model(model, config)
|
| 1755 |
+
|
| 1756 |
+
# trainable_token_indices doesn't have support for `init_weights` so we have to do this manually
|
| 1757 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 1758 |
+
|
| 1759 |
+
output_peft = get_output(peft_model)
|
| 1760 |
+
|
| 1761 |
+
# first check trivial case is not true that peft does not affect the output; for this to work, init_weight
|
| 1762 |
+
# must be False (if the config supports it)
|
| 1763 |
+
if isinstance(peft_model, StableDiffusionPipeline):
|
| 1764 |
+
# for SD, check that most pixels have different values
|
| 1765 |
+
assert (output_before != output_peft).float().mean() > 0.8
|
| 1766 |
+
else:
|
| 1767 |
+
assert not torch.allclose(output_before, output_peft)
|
| 1768 |
+
|
| 1769 |
+
# output with DISABLED ADAPTER
|
| 1770 |
+
if isinstance(peft_model, StableDiffusionPipeline):
|
| 1771 |
+
with peft_model.unet.disable_adapter():
|
| 1772 |
+
with peft_model.text_encoder.disable_adapter():
|
| 1773 |
+
output_peft_disabled = get_output(peft_model)
|
| 1774 |
+
# for SD, very rarely, a pixel can differ
|
| 1775 |
+
assert (output_before != output_peft_disabled).float().mean() < 1e-4
|
| 1776 |
+
else:
|
| 1777 |
+
atol, rtol = 1e-6, 1e-6
|
| 1778 |
+
if (platform.system() == "Windows") and (model_id == "trl-internal-testing/tiny-Llama4ForCausalLM"):
|
| 1779 |
+
# for some reason, Windows CI fails with stricter tolerance
|
| 1780 |
+
atol, rtol = 1e-5, 1e-5
|
| 1781 |
+
|
| 1782 |
+
with peft_model.disable_adapter():
|
| 1783 |
+
output_peft_disabled = get_output(peft_model)
|
| 1784 |
+
assert torch.allclose(output_before, output_peft_disabled, atol=atol, rtol=rtol)
|
| 1785 |
+
|
| 1786 |
+
# after leaving the disable_adapter context, the output should be the same as with enabled adapter again
|
| 1787 |
+
# see #1501
|
| 1788 |
+
output_peft_after_disabled = get_output(peft_model)
|
| 1789 |
+
assert torch.allclose(output_peft, output_peft_after_disabled, atol=atol, rtol=rtol)
|
| 1790 |
+
|
| 1791 |
+
# TODO: add tests to check if disabling adapters works after calling merge_adapter
|
| 1792 |
+
|
| 1793 |
+
def _test_adding_multiple_adapters_with_bias_raises(self, model_id, config_cls, config_kwargs):
|
| 1794 |
+
config_kwargs = config_kwargs.copy()
|
| 1795 |
+
config_kwargs["bias"] = "all"
|
| 1796 |
+
try:
|
| 1797 |
+
config = config_cls(
|
| 1798 |
+
base_model_name_or_path=model_id,
|
| 1799 |
+
**config_kwargs,
|
| 1800 |
+
)
|
| 1801 |
+
except TypeError:
|
| 1802 |
+
pytest.skip(f"{config_cls} does not support the 'bias' argument, skipping this test.")
|
| 1803 |
+
|
| 1804 |
+
with hub_online_once(model_id):
|
| 1805 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1806 |
+
model = get_peft_model(model, config, "adapter0")
|
| 1807 |
+
|
| 1808 |
+
if config_cls == LoraConfig or config_cls == AdaLoraConfig:
|
| 1809 |
+
with pytest.raises(ValueError):
|
| 1810 |
+
model.add_adapter("adapter1", replace(config, r=20))
|
| 1811 |
+
|
| 1812 |
+
if config_cls == BOFTConfig:
|
| 1813 |
+
with pytest.raises(ValueError):
|
| 1814 |
+
model.add_adapter("adapter1", replace(config, boft_block_num=1, boft_block_size=0))
|
| 1815 |
+
|
| 1816 |
+
# (superficial) test that the model is not left in a half-initialized state when adding an adapter fails
|
| 1817 |
+
assert "adapter1" not in model.peft_config
|
| 1818 |
+
assert "adapter1" not in model.base_model.peft_config
|
| 1819 |
+
|
| 1820 |
+
def _test_passing_input_embeds_works(self, test_name, model_id, config_cls, config_kwargs):
|
| 1821 |
+
# https://github.com/huggingface/peft/issues/727
|
| 1822 |
+
with hub_online_once(model_id):
|
| 1823 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1824 |
+
config = config_cls(
|
| 1825 |
+
base_model_name_or_path=model_id,
|
| 1826 |
+
**config_kwargs,
|
| 1827 |
+
)
|
| 1828 |
+
model = get_peft_model(model, config, adapter_name="test-adapter").to(self.torch_device)
|
| 1829 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1830 |
+
inputs_embeds = model.get_input_embeddings()(dummy_input["input_ids"])
|
| 1831 |
+
# just check that no error is raised
|
| 1832 |
+
model.forward(inputs_embeds=inputs_embeds)
|
| 1833 |
+
|
| 1834 |
+
def _test_lora_conversion(self, model_id, config_cls, config_kwargs):
|
| 1835 |
+
# This is a simple test that converting a non-LoRA adapter to LoRA works. If the model doesn't support
|
| 1836 |
+
# conversion, the test is skipped. For detailed tests of this functionality, check test_lora_conversion.py,
|
| 1837 |
+
# which provides depper tests. The purpose of this test is only provide a broad check across PEFT methods.
|
| 1838 |
+
torch.manual_seed(0)
|
| 1839 |
+
if "qwen2" in model_id: # dummy qwen2 has very small weights
|
| 1840 |
+
rank = 4
|
| 1841 |
+
else:
|
| 1842 |
+
rank = 8
|
| 1843 |
+
|
| 1844 |
+
if config_cls == GraloraConfig:
|
| 1845 |
+
# GraLoRA exhibits higher conversion error
|
| 1846 |
+
max_mse = 1.0
|
| 1847 |
+
else:
|
| 1848 |
+
# relatively high upper limit for MSE since we have to work with a low LoRA rank for dummy models
|
| 1849 |
+
max_mse = 0.5
|
| 1850 |
+
|
| 1851 |
+
with hub_online_once(model_id):
|
| 1852 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1853 |
+
config = config_cls(
|
| 1854 |
+
base_model_name_or_path=model_id,
|
| 1855 |
+
**config_kwargs,
|
| 1856 |
+
)
|
| 1857 |
+
model = get_peft_model(model, config).eval()
|
| 1858 |
+
|
| 1859 |
+
if not model.supports_lora_conversion():
|
| 1860 |
+
return
|
| 1861 |
+
if ("OPT" in model_id) and ("fc1" in config.target_modules):
|
| 1862 |
+
# the fc1 and fc2 layers in OPT have size (16, 4), thus choose smaller rank
|
| 1863 |
+
rank = 4
|
| 1864 |
+
|
| 1865 |
+
X = self.prepare_inputs_for_testing()
|
| 1866 |
+
with torch.no_grad():
|
| 1867 |
+
with model.disable_adapter():
|
| 1868 |
+
output_base = model(**X, output_hidden_states=True)
|
| 1869 |
+
output_before = model(**X, output_hidden_states=True)
|
| 1870 |
+
|
| 1871 |
+
# create the converted lora adapter
|
| 1872 |
+
lora_config, state_dict = convert_to_lora(model, rank=rank)
|
| 1873 |
+
del model
|
| 1874 |
+
|
| 1875 |
+
# load the converted LoRA model
|
| 1876 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1877 |
+
model = get_peft_model(model, lora_config).eval()
|
| 1878 |
+
load_result = set_peft_model_state_dict(model, state_dict)
|
| 1879 |
+
assert not load_result.unexpected_keys
|
| 1880 |
+
|
| 1881 |
+
with torch.no_grad():
|
| 1882 |
+
output_after = model(**X, output_hidden_states=True)
|
| 1883 |
+
|
| 1884 |
+
diff1 = output_before.hidden_states[-1] - output_base.hidden_states[-1]
|
| 1885 |
+
diff2 = output_after.hidden_states[-1] - output_base.hidden_states[-1]
|
| 1886 |
+
mse = torch.nn.functional.mse_loss(diff1, diff2).item()
|
| 1887 |
+
assert mse < max_mse, f"LoRA conversion MSE too high, {mse:.4f}, only {max_mse:.1f} allowed"
|
tasks/tasksmith-955732fda55e/tests/source/tests/testing_utils.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import os
|
| 15 |
+
from contextlib import contextmanager
|
| 16 |
+
from functools import lru_cache, wraps
|
| 17 |
+
from unittest import mock
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pytest
|
| 21 |
+
import torch
|
| 22 |
+
from accelerate.test_utils.testing import get_backend
|
| 23 |
+
from datasets import load_dataset
|
| 24 |
+
|
| 25 |
+
from peft import (
|
| 26 |
+
AdaLoraConfig,
|
| 27 |
+
IA3Config,
|
| 28 |
+
LNTuningConfig,
|
| 29 |
+
LoraConfig,
|
| 30 |
+
PromptLearningConfig,
|
| 31 |
+
VBLoRAConfig,
|
| 32 |
+
)
|
| 33 |
+
from peft.import_utils import (
|
| 34 |
+
is_aqlm_available,
|
| 35 |
+
is_auto_awq_available,
|
| 36 |
+
is_auto_gptq_available,
|
| 37 |
+
is_eetq_available,
|
| 38 |
+
is_gptqmodel_available,
|
| 39 |
+
is_hqq_available,
|
| 40 |
+
is_optimum_available,
|
| 41 |
+
is_torchao_available,
|
| 42 |
+
)
|
| 43 |
+
from peft.utils import is_transformers_ge_v5
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# Globally shared model cache used by `hub_online_once`.
|
| 47 |
+
_HUB_MODEL_ACCESSES = {}
|
| 48 |
+
# Some tests with multi GPU require specific device maps to ensure that the models are loaded in two devices
|
| 49 |
+
DEVICE_MAP_MAP: dict[str, dict[str, int]] = {
|
| 50 |
+
"facebook/opt-6.7b": {
|
| 51 |
+
"model.decoder.embed_tokens": 0,
|
| 52 |
+
"model.decoder.embed_positions": 0,
|
| 53 |
+
"model.decoder.final_layer_norm": 0,
|
| 54 |
+
"model.decoder.layers.0": 0,
|
| 55 |
+
"model.decoder.layers.1": 0,
|
| 56 |
+
"model.decoder.layers.2": 0,
|
| 57 |
+
"model.decoder.layers.3": 0,
|
| 58 |
+
"model.decoder.layers.4": 0,
|
| 59 |
+
"model.decoder.layers.5": 0,
|
| 60 |
+
"model.decoder.layers.6": 0,
|
| 61 |
+
"model.decoder.layers.7": 0,
|
| 62 |
+
"model.decoder.layers.8": 0,
|
| 63 |
+
"model.decoder.layers.9": 0,
|
| 64 |
+
"model.decoder.layers.10": 0,
|
| 65 |
+
"model.decoder.layers.11": 0,
|
| 66 |
+
"model.decoder.layers.12": 0,
|
| 67 |
+
"model.decoder.layers.13": 0,
|
| 68 |
+
"model.decoder.layers.14": 0,
|
| 69 |
+
"model.decoder.layers.15": 0,
|
| 70 |
+
"model.decoder.layers.16": 1,
|
| 71 |
+
"model.decoder.layers.17": 1,
|
| 72 |
+
"model.decoder.layers.18": 1,
|
| 73 |
+
"model.decoder.layers.19": 1,
|
| 74 |
+
"model.decoder.layers.20": 1,
|
| 75 |
+
"model.decoder.layers.21": 1,
|
| 76 |
+
"model.decoder.layers.22": 1,
|
| 77 |
+
"model.decoder.layers.23": 1,
|
| 78 |
+
"model.decoder.layers.24": 1,
|
| 79 |
+
"model.decoder.layers.25": 1,
|
| 80 |
+
"model.decoder.layers.26": 1,
|
| 81 |
+
"model.decoder.layers.27": 1,
|
| 82 |
+
"model.decoder.layers.28": 1,
|
| 83 |
+
"model.decoder.layers.29": 1,
|
| 84 |
+
"model.decoder.layers.30": 1,
|
| 85 |
+
"model.decoder.layers.31": 1,
|
| 86 |
+
"lm_head": 0, # tied with embed_tokens
|
| 87 |
+
},
|
| 88 |
+
"peft-internal-testing/opt-125m": {
|
| 89 |
+
"model.decoder.embed_tokens": 0,
|
| 90 |
+
"model.decoder.embed_positions": 0,
|
| 91 |
+
"model.decoder.final_layer_norm": 1,
|
| 92 |
+
"model.decoder.layers.0": 0,
|
| 93 |
+
"model.decoder.layers.1": 0,
|
| 94 |
+
"model.decoder.layers.2": 0,
|
| 95 |
+
"model.decoder.layers.3": 0,
|
| 96 |
+
"model.decoder.layers.4": 0,
|
| 97 |
+
"model.decoder.layers.5": 0,
|
| 98 |
+
"model.decoder.layers.6": 1,
|
| 99 |
+
"model.decoder.layers.7": 1,
|
| 100 |
+
"model.decoder.layers.8": 1,
|
| 101 |
+
"model.decoder.layers.9": 1,
|
| 102 |
+
"model.decoder.layers.10": 1,
|
| 103 |
+
"model.decoder.layers.11": 1,
|
| 104 |
+
"lm_head": 0,
|
| 105 |
+
},
|
| 106 |
+
"marcsun13/opt-350m-gptq-4bit": {
|
| 107 |
+
"model.decoder.embed_tokens": 0,
|
| 108 |
+
"model.decoder.embed_positions": 0,
|
| 109 |
+
"model.decoder.layers.0": 0,
|
| 110 |
+
"model.decoder.layers.1": 0,
|
| 111 |
+
"model.decoder.layers.2": 0,
|
| 112 |
+
"model.decoder.layers.3": 0,
|
| 113 |
+
"model.decoder.layers.4": 0,
|
| 114 |
+
"model.decoder.layers.5": 0,
|
| 115 |
+
"model.decoder.layers.6": 1,
|
| 116 |
+
"model.decoder.layers.7": 1,
|
| 117 |
+
"model.decoder.layers.8": 1,
|
| 118 |
+
"model.decoder.layers.9": 1,
|
| 119 |
+
"model.decoder.layers.10": 1,
|
| 120 |
+
"model.decoder.layers.11": 1,
|
| 121 |
+
"model.decoder.final_layer_norm": 1,
|
| 122 |
+
"lm_head": 0, # tied with embed_tokens
|
| 123 |
+
},
|
| 124 |
+
"google/flan-t5-base": {
|
| 125 |
+
"shared": 0,
|
| 126 |
+
"encoder": 0,
|
| 127 |
+
"decoder": 1,
|
| 128 |
+
"final_layer_norm": 1,
|
| 129 |
+
"decoder.embed_tokens": 0, # tied with encoder.embed_tokens
|
| 130 |
+
"lm_head": 0, # tied with encoder.embed_tokens
|
| 131 |
+
},
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
torch_device, device_count, memory_allocated_func = get_backend()
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def require_non_cpu(test_case):
|
| 139 |
+
"""
|
| 140 |
+
Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no
|
| 141 |
+
hardware accelerator available.
|
| 142 |
+
"""
|
| 143 |
+
return pytest.mark.skipif(torch_device == "cpu", reason="test requires a hardware accelerator")(test_case)
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def require_non_xpu(test_case):
|
| 147 |
+
"""
|
| 148 |
+
Decorator marking a test that should be skipped for XPU.
|
| 149 |
+
"""
|
| 150 |
+
return pytest.mark.skipif(torch_device == "xpu", reason="test requires a non-XPU")(test_case)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def require_torch_gpu(test_case):
|
| 154 |
+
"""
|
| 155 |
+
Decorator marking a test that requires a GPU. Will be skipped when no GPU is available.
|
| 156 |
+
"""
|
| 157 |
+
return pytest.mark.skipif(not torch.cuda.is_available(), reason="test requires GPU")(test_case)
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def require_torch_multi_gpu(test_case):
|
| 161 |
+
"""
|
| 162 |
+
Decorator marking a test that requires multiple GPUs. Will be skipped when less than 2 GPUs are available.
|
| 163 |
+
"""
|
| 164 |
+
multi_cuda_unavailable = not torch.cuda.is_available() or (device_count < 2)
|
| 165 |
+
return pytest.mark.skipif(multi_cuda_unavailable, reason="test requires multiple GPUs")(test_case)
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def require_torch_multi_accelerator(test_case):
|
| 169 |
+
"""
|
| 170 |
+
Decorator marking a test that requires multiple hardware accelerators. These tests are skipped on a machine without
|
| 171 |
+
multiple accelerators.
|
| 172 |
+
"""
|
| 173 |
+
multi_device_unavailable = (torch_device == "cpu") or (device_count < 2)
|
| 174 |
+
return pytest.mark.skipif(multi_device_unavailable, reason="test requires multiple hardware accelerators")(
|
| 175 |
+
test_case
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
def require_bitsandbytes(test_case):
|
| 180 |
+
"""
|
| 181 |
+
Decorator marking a test that requires the bitsandbytes library. Will be skipped when the library is not installed.
|
| 182 |
+
"""
|
| 183 |
+
try:
|
| 184 |
+
import bitsandbytes # noqa: F401
|
| 185 |
+
|
| 186 |
+
test_case = pytest.mark.bitsandbytes(test_case)
|
| 187 |
+
except ImportError:
|
| 188 |
+
test_case = pytest.mark.skip(reason="test requires bitsandbytes")(test_case)
|
| 189 |
+
return test_case
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
def require_auto_gptq(test_case):
|
| 193 |
+
"""
|
| 194 |
+
Decorator marking a test that requires auto-gptq. These tests are skipped when auto-gptq isn't installed.
|
| 195 |
+
"""
|
| 196 |
+
is_gptq_avaiable = is_gptqmodel_available() or is_auto_gptq_available()
|
| 197 |
+
return pytest.mark.skipif(not is_gptq_avaiable, reason="test requires auto-gptq")(test_case)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def require_gptqmodel(test_case):
|
| 201 |
+
"""
|
| 202 |
+
Decorator marking a test that requires gptqmodel. These tests are skipped when gptqmodel isn't installed.
|
| 203 |
+
"""
|
| 204 |
+
return pytest.mark.skipif(not is_gptqmodel_available(), reason="test requires gptqmodel")(test_case)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
def require_aqlm(test_case):
|
| 208 |
+
"""
|
| 209 |
+
Decorator marking a test that requires aqlm. These tests are skipped when aqlm isn't installed.
|
| 210 |
+
"""
|
| 211 |
+
return pytest.mark.skipif(not is_aqlm_available(), reason="test requires aqlm")(test_case)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def require_hqq(test_case):
|
| 215 |
+
"""
|
| 216 |
+
Decorator marking a test that requires aqlm. These tests are skipped when aqlm isn't installed.
|
| 217 |
+
"""
|
| 218 |
+
return pytest.mark.skipif(not is_hqq_available(), reason="test requires hqq")(test_case)
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def require_auto_awq(test_case):
|
| 222 |
+
"""
|
| 223 |
+
Decorator marking a test that requires auto-awq. These tests are skipped when auto-awq isn't installed.
|
| 224 |
+
"""
|
| 225 |
+
return pytest.mark.skipif(not is_auto_awq_available(), reason="test requires auto-awq")(test_case)
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def require_eetq(test_case):
|
| 229 |
+
"""
|
| 230 |
+
Decorator marking a test that requires eetq. These tests are skipped when eetq isn't installed.
|
| 231 |
+
"""
|
| 232 |
+
return pytest.mark.skipif(not is_eetq_available(), reason="test requires eetq")(test_case)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def require_optimum(test_case):
|
| 236 |
+
"""
|
| 237 |
+
Decorator marking a test that requires optimum. These tests are skipped when optimum isn't installed.
|
| 238 |
+
"""
|
| 239 |
+
return pytest.mark.skipif(not is_optimum_available(), reason="test requires optimum")(test_case)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def require_torchao(test_case):
|
| 243 |
+
"""
|
| 244 |
+
Decorator marking a test that requires torchao. These tests are skipped when torchao isn't installed.
|
| 245 |
+
"""
|
| 246 |
+
return pytest.mark.skipif(not is_torchao_available(), reason="test requires torchao")(test_case)
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def require_deterministic_for_xpu(test_case):
|
| 250 |
+
@wraps(test_case)
|
| 251 |
+
def wrapper(*args, **kwargs):
|
| 252 |
+
if torch_device == "xpu":
|
| 253 |
+
original_state = torch.are_deterministic_algorithms_enabled()
|
| 254 |
+
try:
|
| 255 |
+
torch.use_deterministic_algorithms(True)
|
| 256 |
+
return test_case(*args, **kwargs)
|
| 257 |
+
finally:
|
| 258 |
+
torch.use_deterministic_algorithms(original_state)
|
| 259 |
+
else:
|
| 260 |
+
return test_case(*args, **kwargs)
|
| 261 |
+
|
| 262 |
+
return wrapper
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
@contextmanager
|
| 266 |
+
def temp_seed(seed: int):
|
| 267 |
+
"""Temporarily set the random seed. This works for python numpy, pytorch."""
|
| 268 |
+
|
| 269 |
+
np_state = np.random.get_state()
|
| 270 |
+
np.random.seed(seed)
|
| 271 |
+
|
| 272 |
+
torch_state = torch.random.get_rng_state()
|
| 273 |
+
torch.random.manual_seed(seed)
|
| 274 |
+
|
| 275 |
+
if torch.cuda.is_available():
|
| 276 |
+
torch_cuda_states = torch.cuda.get_rng_state_all()
|
| 277 |
+
torch.cuda.manual_seed_all(seed)
|
| 278 |
+
|
| 279 |
+
try:
|
| 280 |
+
yield
|
| 281 |
+
finally:
|
| 282 |
+
np.random.set_state(np_state)
|
| 283 |
+
|
| 284 |
+
torch.random.set_rng_state(torch_state)
|
| 285 |
+
if torch.cuda.is_available():
|
| 286 |
+
torch.cuda.set_rng_state_all(torch_cuda_states)
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def get_state_dict(model, unwrap_compiled=True):
|
| 290 |
+
"""
|
| 291 |
+
Get the state dict of a model. If the model is compiled, unwrap it first.
|
| 292 |
+
"""
|
| 293 |
+
if unwrap_compiled:
|
| 294 |
+
model = getattr(model, "_orig_mod", model)
|
| 295 |
+
return model.state_dict()
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
@lru_cache
|
| 299 |
+
def load_dataset_english_quotes():
|
| 300 |
+
# can't use pytest fixtures for now because of unittest style tests
|
| 301 |
+
data = load_dataset("ybelkada/english_quotes_copy")
|
| 302 |
+
return data
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
@lru_cache
|
| 306 |
+
def load_cat_image():
|
| 307 |
+
# can't use pytest fixtures for now because of unittest style tests
|
| 308 |
+
dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
|
| 309 |
+
image = dataset["test"]["image"][0]
|
| 310 |
+
return image
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def set_init_weights_false(config_cls, kwargs):
|
| 314 |
+
# helper function that sets the config kwargs such that the model is *not* initialized as an identity transform
|
| 315 |
+
kwargs = kwargs.copy()
|
| 316 |
+
|
| 317 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 318 |
+
return kwargs
|
| 319 |
+
if config_cls in (LNTuningConfig, VBLoRAConfig):
|
| 320 |
+
return kwargs
|
| 321 |
+
|
| 322 |
+
if config_cls in (LoraConfig, AdaLoraConfig):
|
| 323 |
+
kwargs["init_lora_weights"] = False
|
| 324 |
+
elif config_cls == IA3Config:
|
| 325 |
+
kwargs["init_ia3_weights"] = False
|
| 326 |
+
else:
|
| 327 |
+
kwargs["init_weights"] = False
|
| 328 |
+
return kwargs
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
@contextmanager
|
| 332 |
+
def hub_online_once(model_id: str):
|
| 333 |
+
"""Set env[HF_HUB_OFFLINE]=1 (and patch transformers/hugging_face_hub to think that it was always that way)
|
| 334 |
+
for model ids that were already to avoid contacting the hub twice for the same model id in the context. The global
|
| 335 |
+
variable `_HUB_MODEL_ACCESSES` tracks the number of hits per model id between `hub_online_once` calls.
|
| 336 |
+
|
| 337 |
+
The reason for doing a context manager and not patching specific methods (e.g., `from_pretrained`) is that there
|
| 338 |
+
are a lot of places (`PeftConfig.from_pretrained`, `get_peft_state_dict`, `load_adapter`, ...) that possibly
|
| 339 |
+
communicate with the hub to download files / check versions / etc.
|
| 340 |
+
|
| 341 |
+
Note that using this context manager can cause problems when used in code sections that access different resources.
|
| 342 |
+
Example:
|
| 343 |
+
|
| 344 |
+
```
|
| 345 |
+
def test_something(model_id, config_kwargs):
|
| 346 |
+
with hub_online_once(model_id):
|
| 347 |
+
model = ...from_pretrained(model_id)
|
| 348 |
+
self.do_something_specific_with_model(model)
|
| 349 |
+
```
|
| 350 |
+
It is assumed that `do_something_specific_with_model` is an absract method that is implement by several tests.
|
| 351 |
+
Imagine the first test simply does `model.generate([1,2,3])`. The second call from another test suite however uses
|
| 352 |
+
a tokenizer (`AutoTokenizer.from_pretrained(model_id)`) - this will fail since the first pass was online but didn't
|
| 353 |
+
use the tokenizer and we're now in offline mode and cannot fetch the tokenizer. The recommended workaround is to
|
| 354 |
+
extend the cache key (`model_id` passed to `hub_online_once` in this case) by something in case the tokenizer is
|
| 355 |
+
used, so that these tests don't share a cache pool with the tests that don't use a tokenizer.
|
| 356 |
+
|
| 357 |
+
It is best to avoid using this context manager in *yield* fixtures (normal fixtures are fine) as this is equivalent
|
| 358 |
+
to wrapping the whole test in the context manager without explicitly writing it out, leading to unexpected
|
| 359 |
+
`HF_HUB_OFFLINE` behavior in the test body.
|
| 360 |
+
"""
|
| 361 |
+
global _HUB_MODEL_ACCESSES
|
| 362 |
+
override = {}
|
| 363 |
+
|
| 364 |
+
try:
|
| 365 |
+
if model_id in _HUB_MODEL_ACCESSES:
|
| 366 |
+
override = {"HF_HUB_OFFLINE": "1"}
|
| 367 |
+
_HUB_MODEL_ACCESSES[model_id] += 1
|
| 368 |
+
elif model_id not in _HUB_MODEL_ACCESSES:
|
| 369 |
+
_HUB_MODEL_ACCESSES[model_id] = 0
|
| 370 |
+
is_offline = override.get("HF_HUB_OFFLINE", False) == "1"
|
| 371 |
+
|
| 372 |
+
with (
|
| 373 |
+
# strictly speaking it is not necessary to set the environment variable since most code that's out there
|
| 374 |
+
# is evaluating it at import time and we'd have to reload the modules for it to take effect. It's
|
| 375 |
+
# probably still a good idea to have it if there's some dynamic code that checks it.
|
| 376 |
+
mock.patch.dict(os.environ, override),
|
| 377 |
+
mock.patch("huggingface_hub.constants.HF_HUB_OFFLINE", is_offline),
|
| 378 |
+
):
|
| 379 |
+
if is_transformers_ge_v5:
|
| 380 |
+
with mock.patch("transformers.utils.hub.is_offline_mode", lambda: is_offline):
|
| 381 |
+
yield
|
| 382 |
+
else: # TODO remove if transformers <= 4 no longer supported
|
| 383 |
+
with mock.patch("transformers.utils.hub._is_offline_mode", is_offline):
|
| 384 |
+
yield
|
| 385 |
+
except Exception:
|
| 386 |
+
# in case of an error we have to assume that we didn't access the model properly from the hub
|
| 387 |
+
# for the first time, so the next call cannot be considered cached.
|
| 388 |
+
if _HUB_MODEL_ACCESSES.get(model_id) == 0:
|
| 389 |
+
del _HUB_MODEL_ACCESSES[model_id]
|
| 390 |
+
raise
|
tasks/tasksmith-955732fda55e/tests/test.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -eu
|
| 3 |
+
exec /usr/local/bin/python -I /tests/grade.py
|
tasks/tasksmith-955732fda55e/tests/test_driver.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Private pytest entry point with a bounded framework-tampering check.
|
| 2 |
+
|
| 3 |
+
The host still owns reward parsing. This guard detects replacement or in-place
|
| 4 |
+
editing of unittest assertions, a demonstrated attack against repository tests.
|
| 5 |
+
It does not claim to isolate arbitrary test and solution code in one interpreter.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import sys
|
| 11 |
+
import unittest
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def run(arguments: list[str]) -> int:
|
| 15 |
+
import pytest
|
| 16 |
+
|
| 17 |
+
# Capture before pytest imports any repository modules. Retain code objects
|
| 18 |
+
# too: an attacker can mutate function.__code__ without replacing a method.
|
| 19 |
+
original = {
|
| 20 |
+
name: (value, getattr(value, "__code__", None))
|
| 21 |
+
for name, value in vars(unittest.TestCase).items()
|
| 22 |
+
if name.startswith("assert") and callable(value)
|
| 23 |
+
}
|
| 24 |
+
case = unittest.TestCase
|
| 25 |
+
# The harness supplies selectors and reporting explicitly. Repository addopts
|
| 26 |
+
# often enable optional coverage/report plugins that are intentionally not
|
| 27 |
+
# auto-loaded in this isolated verifier; they are not test dependencies.
|
| 28 |
+
code = int(pytest.main(["-o", "addopts=", *arguments]))
|
| 29 |
+
changed = []
|
| 30 |
+
for name, (method, implementation) in original.items():
|
| 31 |
+
current = getattr(case, name, None)
|
| 32 |
+
if current is not method or getattr(current, "__code__", None) is not implementation:
|
| 33 |
+
changed.append(name)
|
| 34 |
+
if unittest.TestCase is not case or changed:
|
| 35 |
+
sys.stderr.write("Verifier framework was modified: " + ", ".join(changed) + "\n")
|
| 36 |
+
return 254
|
| 37 |
+
return code
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
if __name__ == "__main__":
|
| 41 |
+
raise SystemExit(run(sys.argv[1:]))
|
tasks/tasksmith-955732fda55e/tests/test_results.py
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Strict test evidence used by repository recipes and their exported verifiers."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
from dataclasses import dataclass
|
| 6 |
+
from xml.etree import ElementTree
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
@dataclass(frozen=True)
|
| 10 |
+
class TestResults:
|
| 11 |
+
__test__ = False
|
| 12 |
+
statuses: dict[str, str]
|
| 13 |
+
returncode: int
|
| 14 |
+
|
| 15 |
+
@property
|
| 16 |
+
def passed(self) -> set[str]:
|
| 17 |
+
return {name for name, status in self.statuses.items() if status == "passed"}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def parse_junit(text: str, *, returncode: int) -> TestResults:
|
| 21 |
+
if "<!DOCTYPE" in text.upper() or "<!ENTITY" in text.upper():
|
| 22 |
+
raise ValueError("JUnit must not contain a DTD or entity declaration")
|
| 23 |
+
if returncode not in {0, 1}:
|
| 24 |
+
raise ValueError(f"Test runner did not complete normally: exit {returncode}")
|
| 25 |
+
try:
|
| 26 |
+
root = ElementTree.fromstring(text)
|
| 27 |
+
except ElementTree.ParseError as exc:
|
| 28 |
+
raise ValueError("Invalid JUnit report") from exc
|
| 29 |
+
if root.tag not in {"testsuite", "testsuites"}:
|
| 30 |
+
raise ValueError("Expected a JUnit testsuite or testsuites root")
|
| 31 |
+
statuses = {}
|
| 32 |
+
for case in root.iter("testcase"):
|
| 33 |
+
name, classname = case.get("name"), case.get("classname")
|
| 34 |
+
if not name or not classname:
|
| 35 |
+
raise ValueError("Test cases require a name and class identity")
|
| 36 |
+
identity = f"{classname}::{name}"
|
| 37 |
+
if identity in statuses:
|
| 38 |
+
raise ValueError(f"Duplicate test identity: {identity}")
|
| 39 |
+
if case.find("error") is not None:
|
| 40 |
+
status = "error"
|
| 41 |
+
elif case.find("failure") is not None:
|
| 42 |
+
status = "failed"
|
| 43 |
+
elif case.find("skipped") is not None:
|
| 44 |
+
status = "skipped"
|
| 45 |
+
else:
|
| 46 |
+
status = "passed"
|
| 47 |
+
statuses[identity] = status
|
| 48 |
+
if not statuses:
|
| 49 |
+
raise ValueError("Empty test result is not execution evidence")
|
| 50 |
+
if returncode == 0 and any(status in {"failed", "error"} for status in statuses.values()):
|
| 51 |
+
raise ValueError("JUnit failures contradict the runner exit code")
|
| 52 |
+
return TestResults(statuses, returncode)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def execution_contrast(healthy: TestResults, defective: TestResults) -> dict[str, list[str]]:
|
| 56 |
+
if healthy.returncode != 0 or not healthy.passed:
|
| 57 |
+
raise ValueError("Reference must execute successfully with passing tests")
|
| 58 |
+
if healthy.statuses.keys() != defective.statuses.keys():
|
| 59 |
+
raise ValueError("Mutation changed test collection; contrast is not comparable")
|
| 60 |
+
failing = sorted(
|
| 61 |
+
name for name in healthy.passed if defective.statuses[name] in {"failed", "error"}
|
| 62 |
+
)
|
| 63 |
+
if not failing or defective.returncode != 1:
|
| 64 |
+
raise ValueError("No intended fail-to-pass contrast")
|
| 65 |
+
return {"FAIL_TO_PASS": failing, "PASS_TO_PASS": sorted(healthy.passed - set(failing))}
|
tasks/tasksmith-9aea936e30e4/environment/Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim-bookworm
|
| 2 |
+
WORKDIR /workspace
|
| 3 |
+
RUN python -m pip install --no-cache-dir numpy==2.5.3 packaging==26.3 psutil==7.2.2 pyyaml==6.0.2 tqdm==4.67.1 torch==2.11.0+cpu transformers==4.51.3 accelerate==1.4.0 safetensors==0.5.3 huggingface_hub==0.30.2 tokenizers==0.21.4 regex==2026.9.10 filelock==3.32.6 requests==2.34.2 pytest==8.4.2 pytest-cov==6.1.0 setuptools==78.1.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu
|
| 4 |
+
COPY source /workspace
|
| 5 |
+
RUN python -m pip install --no-cache-dir --no-build-isolation -e .
|
| 6 |
+
ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
|
| 7 |
+
ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
|
| 8 |
+
RUN apt-get update && apt-get install -y --no-install-recommends tmux && rm -rf /var/lib/apt/lists/*
|
| 9 |
+
RUN useradd -m learner && chown -R learner:learner /workspace
|
tasks/tasksmith-9aea936e30e4/environment/source/.gitignore
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Byte-compiled / optimized / DLL files
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*$py.class
|
| 5 |
+
|
| 6 |
+
# C extensions
|
| 7 |
+
*.so
|
| 8 |
+
|
| 9 |
+
# Distribution / packaging
|
| 10 |
+
.Python
|
| 11 |
+
build/
|
| 12 |
+
develop-eggs/
|
| 13 |
+
dist/
|
| 14 |
+
downloads/
|
| 15 |
+
eggs/
|
| 16 |
+
.eggs/
|
| 17 |
+
lib/
|
| 18 |
+
lib64/
|
| 19 |
+
parts/
|
| 20 |
+
sdist/
|
| 21 |
+
var/
|
| 22 |
+
wheels/
|
| 23 |
+
pip-wheel-metadata/
|
| 24 |
+
share/python-wheels/
|
| 25 |
+
*.egg-info/
|
| 26 |
+
.installed.cfg
|
| 27 |
+
*.egg
|
| 28 |
+
MANIFEST
|
| 29 |
+
|
| 30 |
+
# PyInstaller
|
| 31 |
+
# Usually these files are written by a python script from a template
|
| 32 |
+
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
| 33 |
+
*.manifest
|
| 34 |
+
*.spec
|
| 35 |
+
|
| 36 |
+
# Installer logs
|
| 37 |
+
pip-log.txt
|
| 38 |
+
pip-delete-this-directory.txt
|
| 39 |
+
|
| 40 |
+
# Unit test / coverage reports
|
| 41 |
+
htmlcov/
|
| 42 |
+
.tox/
|
| 43 |
+
.nox/
|
| 44 |
+
.coverage
|
| 45 |
+
.coverage.*
|
| 46 |
+
.cache
|
| 47 |
+
nosetests.xml
|
| 48 |
+
coverage.xml
|
| 49 |
+
*.cover
|
| 50 |
+
*.py,cover
|
| 51 |
+
.hypothesis/
|
| 52 |
+
.pytest_cache/
|
| 53 |
+
|
| 54 |
+
# Translations
|
| 55 |
+
*.mo
|
| 56 |
+
*.pot
|
| 57 |
+
|
| 58 |
+
# Django stuff:
|
| 59 |
+
*.log
|
| 60 |
+
local_settings.py
|
| 61 |
+
db.sqlite3
|
| 62 |
+
db.sqlite3-journal
|
| 63 |
+
|
| 64 |
+
# Flask stuff:
|
| 65 |
+
instance/
|
| 66 |
+
.webassets-cache
|
| 67 |
+
|
| 68 |
+
# Scrapy stuff:
|
| 69 |
+
.scrapy
|
| 70 |
+
|
| 71 |
+
# Sphinx documentation
|
| 72 |
+
docs/_build/
|
| 73 |
+
|
| 74 |
+
# PyBuilder
|
| 75 |
+
target/
|
| 76 |
+
|
| 77 |
+
# Jupyter Notebook
|
| 78 |
+
.ipynb_checkpoints
|
| 79 |
+
|
| 80 |
+
# IPython
|
| 81 |
+
profile_default/
|
| 82 |
+
ipython_config.py
|
| 83 |
+
|
| 84 |
+
# pyenv
|
| 85 |
+
.python-version
|
| 86 |
+
|
| 87 |
+
# pipenv
|
| 88 |
+
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
| 89 |
+
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
| 90 |
+
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
| 91 |
+
# install all needed dependencies.
|
| 92 |
+
#Pipfile.lock
|
| 93 |
+
|
| 94 |
+
# PEP 582; used by e.g. github.com/David-OConnor/pyflow
|
| 95 |
+
__pypackages__/
|
| 96 |
+
|
| 97 |
+
# Celery stuff
|
| 98 |
+
celerybeat-schedule
|
| 99 |
+
celerybeat.pid
|
| 100 |
+
|
| 101 |
+
# SageMath parsed files
|
| 102 |
+
*.sage.py
|
| 103 |
+
|
| 104 |
+
# Environments
|
| 105 |
+
.env
|
| 106 |
+
.venv
|
| 107 |
+
env/
|
| 108 |
+
venv/
|
| 109 |
+
ENV/
|
| 110 |
+
env.bak/
|
| 111 |
+
venv.bak/
|
| 112 |
+
|
| 113 |
+
# Spyder project settings
|
| 114 |
+
.spyderproject
|
| 115 |
+
.spyproject
|
| 116 |
+
|
| 117 |
+
# Rope project settings
|
| 118 |
+
.ropeproject
|
| 119 |
+
|
| 120 |
+
# mkdocs documentation
|
| 121 |
+
/site
|
| 122 |
+
|
| 123 |
+
# mypy
|
| 124 |
+
.mypy_cache/
|
| 125 |
+
.dmypy.json
|
| 126 |
+
dmypy.json
|
| 127 |
+
|
| 128 |
+
# Pyre type checker
|
| 129 |
+
.pyre/
|
| 130 |
+
|
| 131 |
+
# VSCode
|
| 132 |
+
.vscode
|
| 133 |
+
|
| 134 |
+
# IntelliJ
|
| 135 |
+
.idea
|
| 136 |
+
|
| 137 |
+
# Mac .DS_Store
|
| 138 |
+
.DS_Store
|
| 139 |
+
|
| 140 |
+
# More test things
|
| 141 |
+
wandb
|
| 142 |
+
|
| 143 |
+
# method_comparison logs
|
| 144 |
+
method_comparison/MetaMathQA/cancelled_results/
|
| 145 |
+
method_comparison/MetaMathQA/temporary_results/
|
tasks/tasksmith-9aea936e30e4/environment/source/.pre-commit-config.yaml
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
repos:
|
| 2 |
+
- repo: https://github.com/astral-sh/ruff-pre-commit
|
| 3 |
+
rev: v0.12.8
|
| 4 |
+
hooks:
|
| 5 |
+
- id: ruff
|
| 6 |
+
args:
|
| 7 |
+
- --fix
|
| 8 |
+
- id: ruff-format
|
| 9 |
+
- repo: https://github.com/pre-commit/pre-commit-hooks
|
| 10 |
+
rev: v4.6.0
|
| 11 |
+
hooks:
|
| 12 |
+
- id: check-merge-conflict
|
| 13 |
+
- id: check-yaml
|
tasks/tasksmith-9aea936e30e4/environment/source/Dockerfile
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim-bookworm
|
| 2 |
+
WORKDIR /workspace
|
| 3 |
+
RUN python -m pip install --no-cache-dir numpy==2.5.3 packaging==26.3 psutil==7.2.2 pyyaml==6.0.2 tqdm==4.67.1 torch==2.11.0+cpu transformers==4.51.3 accelerate==1.4.0 safetensors==0.5.3 huggingface_hub==0.30.2 tokenizers==0.21.4 regex==2026.9.10 filelock==3.32.6 requests==2.34.2 pytest==8.4.2 pytest-cov==6.1.0 setuptools==78.1.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu
|
| 4 |
+
COPY . /workspace
|
| 5 |
+
RUN python -m pip install --no-cache-dir --no-build-isolation -e .
|
| 6 |
+
RUN rm -rf /workspace/.git /root/.cache/pip
|
| 7 |
+
ENV PYTHONDONTWRITEBYTECODE=1 PYTEST_DISABLE_PLUGIN_AUTOLOAD=1
|
| 8 |
+
ENV HF_HUB_OFFLINE=1 TRANSFORMERS_OFFLINE=1 HF_DATASETS_OFFLINE=1
|
tasks/tasksmith-9aea936e30e4/environment/source/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|
tasks/tasksmith-9aea936e30e4/environment/source/Makefile
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.PHONY: quality style test docs
|
| 2 |
+
|
| 3 |
+
check_dirs := src tests examples docs scripts docker
|
| 4 |
+
|
| 5 |
+
# Check that source code meets quality standards
|
| 6 |
+
|
| 7 |
+
# this target runs checks on all files
|
| 8 |
+
quality:
|
| 9 |
+
ruff check $(check_dirs)
|
| 10 |
+
ruff format --check $(check_dirs)
|
| 11 |
+
doc-builder style src/peft tests docs/source --max_len 119 --check_only
|
| 12 |
+
|
| 13 |
+
# Format source code automatically and check is there are any problems left that need manual fixing
|
| 14 |
+
style:
|
| 15 |
+
ruff check --fix $(check_dirs)
|
| 16 |
+
ruff format $(check_dirs)
|
| 17 |
+
doc-builder style src/peft tests docs/source --max_len 119
|
| 18 |
+
|
| 19 |
+
test:
|
| 20 |
+
python -m pytest -n 3 tests/ $(if $(IS_GITHUB_CI),--report-log "ci_tests.log",)
|
| 21 |
+
|
| 22 |
+
tests_examples_multi_gpu:
|
| 23 |
+
python -m pytest -m multi_gpu_tests tests/test_gpu_examples.py $(if $(IS_GITHUB_CI),--report-log "multi_gpu_examples.log",)
|
| 24 |
+
|
| 25 |
+
tests_examples_single_gpu:
|
| 26 |
+
python -m pytest -m single_gpu_tests tests/test_gpu_examples.py $(if $(IS_GITHUB_CI),--report-log "single_gpu_examples.log",)
|
| 27 |
+
|
| 28 |
+
tests_core_multi_gpu:
|
| 29 |
+
python -m pytest -m multi_gpu_tests tests/test_common_gpu.py $(if $(IS_GITHUB_CI),--report-log "core_multi_gpu.log",)
|
| 30 |
+
|
| 31 |
+
tests_core_single_gpu:
|
| 32 |
+
python -m pytest -m single_gpu_tests tests/test_common_gpu.py $(if $(IS_GITHUB_CI),--report-log "core_single_gpu.log",)
|
| 33 |
+
|
| 34 |
+
# exclude gemma tests, as generation fails with torch.compile, these failures
|
| 35 |
+
# trigger side effects that make other tests fail with 'RuntimeError: Offset
|
| 36 |
+
# increment outside graph capture encountered unexpectedly.'
|
| 37 |
+
# TODO re-enable gemma once/if it is fixed
|
| 38 |
+
tests_common_gpu:
|
| 39 |
+
python -m pytest tests/test_decoder_models.py -k "not gemma" $(if $(IS_GITHUB_CI),--report-log "common_decoder.log",)
|
| 40 |
+
python -m pytest tests/test_encoder_decoder_models.py $(if $(IS_GITHUB_CI),--report-log "common_encoder_decoder.log",)
|
| 41 |
+
python -m pytest tests/test_gptqmodel.py $(if $(IS_GITHUB_CI),--report-log "gptqmodel_gpu.log",)
|
| 42 |
+
|
| 43 |
+
tests_examples_multi_gpu_bnb:
|
| 44 |
+
python -m pytest -m "multi_gpu_tests and bitsandbytes" tests/test_gpu_examples.py $(if $(IS_GITHUB_CI),--report-log "multi_gpu_examples.log",)
|
| 45 |
+
|
| 46 |
+
tests_examples_single_gpu_bnb:
|
| 47 |
+
python -m pytest -m "single_gpu_tests and bitsandbytes" tests/test_gpu_examples.py $(if $(IS_GITHUB_CI),--report-log "single_gpu_examples.log",)
|
| 48 |
+
|
| 49 |
+
tests_core_multi_gpu_bnb:
|
| 50 |
+
python -m pytest -m "multi_gpu_tests and bitsandbytes" tests/test_common_gpu.py $(if $(IS_GITHUB_CI),--report-log "core_multi_gpu.log",)
|
| 51 |
+
|
| 52 |
+
tests_core_single_gpu_bnb:
|
| 53 |
+
python -m pytest -m "single_gpu_tests and bitsandbytes" tests/test_common_gpu.py $(if $(IS_GITHUB_CI),--report-log "core_single_gpu.log",)
|
| 54 |
+
|
| 55 |
+
# For testing transformers tests for bnb runners
|
| 56 |
+
transformers_tests:
|
| 57 |
+
RUN_SLOW=1 python -m pytest transformers-clone/tests/quantization/bnb $(if $(IS_GITHUB_CI),--report-log "transformers_tests.log",)
|
| 58 |
+
|
| 59 |
+
tests_regression:
|
| 60 |
+
python -m pytest -s --regression tests/regression/ $(if $(IS_GITHUB_CI),--report-log "regression_tests.log",)
|
| 61 |
+
|
| 62 |
+
tests_torch_compile:
|
| 63 |
+
python -m pytest tests/test_torch_compile.py $(if $(IS_GITHUB_CI),--report-log "compile_tests.log",)
|
| 64 |
+
|
| 65 |
+
tests_training:
|
| 66 |
+
accelerate launch --config_file tests/training/deepspeed_config.yaml tests/training/training.py $(if $(IS_GITHUB_CI),--report-log "training_deepspeed.log",)
|
| 67 |
+
accelerate launch --config_file tests/training/deepspeed_config.yaml tests/training/training.py --quant 4bit $(if $(IS_GITHUB_CI),--report-log "training_deepspeed_4bit.log",)
|
| 68 |
+
accelerate launch --config_file tests/training/deepspeed_config.yaml tests/training/training.py --quant 8bit $(if $(IS_GITHUB_CI),--report-log "training_deepspeed_8bit.log",)
|
| 69 |
+
accelerate launch --config_file tests/training/fsdp_config.yaml tests/training/training.py $(if $(IS_GITHUB_CI),--report-log "training_fsdp.log",)
|
| 70 |
+
accelerate launch --config_file tests/training/fsdp_config.yaml tests/training/training.py --quant 4bit $(if $(IS_GITHUB_CI),--report-log "training_fsdp_4bit.log",)
|
| 71 |
+
accelerate launch --config_file tests/training/fsdp_config.yaml tests/training/adapters.py $(if $(IS_GITHUB_CI),--report-log "training_fsdp_adapters.log",)
|
tasks/tasksmith-9aea936e30e4/environment/source/README.md
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!---
|
| 2 |
+
Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 3 |
+
|
| 4 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
you may not use this file except in compliance with the License.
|
| 6 |
+
You may obtain a copy of the License at
|
| 7 |
+
|
| 8 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
|
| 10 |
+
Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
See the License for the specific language governing permissions and
|
| 14 |
+
limitations under the License.
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
<h1 align="center"> <p>🤗 PEFT</p></h1>
|
| 18 |
+
<h3 align="center">
|
| 19 |
+
<p>State-of-the-art Parameter-Efficient Fine-Tuning (PEFT) methods</p>
|
| 20 |
+
</h3>
|
| 21 |
+
|
| 22 |
+
Fine-tuning large pretrained models is often prohibitively costly due to their scale. Parameter-Efficient Fine-Tuning (PEFT) methods enable efficient adaptation of large pretrained models to various downstream applications by only fine-tuning a small number of (extra) model parameters instead of all the model's parameters. This significantly decreases the computational and storage costs. Recent state-of-the-art PEFT techniques achieve performance comparable to fully fine-tuned models.
|
| 23 |
+
|
| 24 |
+
PEFT is integrated with Transformers for easy model training and inference, Diffusers for conveniently managing different adapters, and Accelerate for distributed training and inference for really big models.
|
| 25 |
+
|
| 26 |
+
> [!TIP]
|
| 27 |
+
> Visit the [PEFT](https://huggingface.co/PEFT) organization to read about the PEFT methods implemented in the library and to see notebooks demonstrating how to apply these methods to a variety of downstream tasks. Click the "Watch repos" button on the organization page to be notified of newly implemented methods and notebooks!
|
| 28 |
+
|
| 29 |
+
Check the PEFT Adapters API Reference section for a list of supported PEFT methods, and read the [Adapters](https://huggingface.co/docs/peft/en/conceptual_guides/adapter), [Soft prompts](https://huggingface.co/docs/peft/en/conceptual_guides/prompting), and [IA3](https://huggingface.co/docs/peft/en/conceptual_guides/ia3) conceptual guides to learn more about how these methods work.
|
| 30 |
+
|
| 31 |
+
## Quickstart
|
| 32 |
+
|
| 33 |
+
Install PEFT from pip:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
pip install peft
|
| 37 |
+
```
|
| 38 |
+
|
| 39 |
+
Prepare a model for training with a PEFT method such as LoRA by wrapping the base model and PEFT configuration with `get_peft_model`. For the bigscience/mt0-large model, you're only training 0.19% of the parameters!
|
| 40 |
+
|
| 41 |
+
```python
|
| 42 |
+
from transformers import AutoModelForCausalLM
|
| 43 |
+
from peft import LoraConfig, TaskType, get_peft_model
|
| 44 |
+
|
| 45 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 46 |
+
model_id = "Qwen/Qwen2.5-3B-Instruct"
|
| 47 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device)
|
| 48 |
+
peft_config = LoraConfig(
|
| 49 |
+
r=16,
|
| 50 |
+
lora_alpha=32,
|
| 51 |
+
task_type=TaskType.CAUSAL_LM,
|
| 52 |
+
# target_modules=["q_proj", "v_proj", ...] # optionally indicate target modules
|
| 53 |
+
)
|
| 54 |
+
model = get_peft_model(model, peft_config)
|
| 55 |
+
model.print_trainable_parameters()
|
| 56 |
+
# prints: trainable params: 3,686,400 || all params: 3,089,625,088 || trainable%: 0.1193
|
| 57 |
+
|
| 58 |
+
# now perform training on your dataset, e.g. using transformers Trainer, then save the model
|
| 59 |
+
model.save_pretrained("qwen2.5-3b-lora")
|
| 60 |
+
```
|
| 61 |
+
|
| 62 |
+
To load a PEFT model for inference:
|
| 63 |
+
|
| 64 |
+
```python
|
| 65 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 66 |
+
from peft import PeftModel
|
| 67 |
+
|
| 68 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 69 |
+
model_id = "Qwen/Qwen2.5-3B-Instruct"
|
| 70 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 71 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, device_map=device)
|
| 72 |
+
model = PeftModel.from_pretrained(model, "qwen2.5-3b-lora")
|
| 73 |
+
|
| 74 |
+
inputs = tokenizer("Preheat the oven to 350 degrees and place the cookie dough", return_tensors="pt")
|
| 75 |
+
outputs = model.generate(**inputs.to(device), max_new_tokens=50)
|
| 76 |
+
print(tokenizer.decode(outputs[0], skip_special_tokens=True))
|
| 77 |
+
|
| 78 |
+
# prints something like: Preheat the oven to 350 degrees and place the cookie dough in a baking dish [...]
|
| 79 |
+
```
|
| 80 |
+
|
| 81 |
+
## Why you should use PEFT
|
| 82 |
+
|
| 83 |
+
There are many benefits of using PEFT but the main one is the huge savings in compute and storage, making PEFT applicable to many different use cases.
|
| 84 |
+
|
| 85 |
+
### High performance on consumer hardware
|
| 86 |
+
|
| 87 |
+
Consider the memory requirements for training the following models on the [ought/raft/twitter_complaints](https://huggingface.co/datasets/ought/raft/viewer/twitter_complaints) dataset with an A100 80GB GPU with more than 64GB of CPU RAM.
|
| 88 |
+
|
| 89 |
+
| Model | Full Finetuning | PEFT-LoRA PyTorch | PEFT-LoRA DeepSpeed with CPU Offloading |
|
| 90 |
+
| --------- | ---- | ---- | ---- |
|
| 91 |
+
| bigscience/T0_3B (3B params) | 47.14GB GPU / 2.96GB CPU | 14.4GB GPU / 2.96GB CPU | 9.8GB GPU / 17.8GB CPU |
|
| 92 |
+
| bigscience/mt0-xxl (12B params) | OOM GPU | 56GB GPU / 3GB CPU | 22GB GPU / 52GB CPU |
|
| 93 |
+
| bigscience/bloomz-7b1 (7B params) | OOM GPU | 32GB GPU / 3.8GB CPU | 18.1GB GPU / 35GB CPU |
|
| 94 |
+
|
| 95 |
+
With LoRA you can fully finetune a 12B parameter model that would've otherwise run out of memory on the 80GB GPU, and comfortably fit and train a 3B parameter model. When you look at the 3B parameter model's performance, it is comparable to a fully finetuned model at a fraction of the GPU memory.
|
| 96 |
+
|
| 97 |
+
| Submission Name | Accuracy |
|
| 98 |
+
| --------- | ---- |
|
| 99 |
+
| Human baseline (crowdsourced) | 0.897 |
|
| 100 |
+
| Flan-T5 | 0.892 |
|
| 101 |
+
| lora-t0-3b | 0.863 |
|
| 102 |
+
|
| 103 |
+
> [!TIP]
|
| 104 |
+
> The bigscience/T0_3B model performance isn't optimized in the table above. You can squeeze even more performance out of it by playing around with the input instruction templates, LoRA hyperparameters, and other training related hyperparameters. The final checkpoint size of this model is just 19MB compared to 11GB of the full bigscience/T0_3B model. Learn more about the advantages of finetuning with PEFT in this [blog post](https://www.philschmid.de/fine-tune-flan-t5-peft).
|
| 105 |
+
|
| 106 |
+
### Quantization
|
| 107 |
+
|
| 108 |
+
Quantization is another method for reducing the memory requirements of a model by representing the data in a lower precision. It can be combined with PEFT methods to make it even easier to train and load LLMs for inference.
|
| 109 |
+
|
| 110 |
+
* Learn how to finetune [meta-llama/Llama-2-7b-hf](https://huggingface.co/meta-llama/Llama-2-7b-hf) with QLoRA and the [TRL](https://huggingface.co/docs/trl/index) library on a 16GB GPU in the [Finetune LLMs on your own consumer hardware using tools from PyTorch and Hugging Face ecosystem](https://pytorch.org/blog/finetune-llms/) blog post.
|
| 111 |
+
* Learn how to finetune a [openai/whisper-large-v2](https://huggingface.co/openai/whisper-large-v2) model for multilingual automatic speech recognition with LoRA and 8-bit quantization in this [notebook](https://colab.research.google.com/drive/1DOkD_5OUjFa0r5Ik3SgywJLJtEo2qLxO?usp=sharing) (see this [notebook](https://colab.research.google.com/drive/1vhF8yueFqha3Y3CpTHN6q9EVcII9EYzs?usp=sharing) instead for an example of streaming a dataset).
|
| 112 |
+
|
| 113 |
+
### Save compute and storage
|
| 114 |
+
|
| 115 |
+
PEFT can help you save storage by avoiding full finetuning of models on each of downstream task or dataset. In many cases, you're only finetuning a very small fraction of a model's parameters and each checkpoint is only a few MBs in size (instead of GBs). These smaller PEFT adapters demonstrate performance comparable to a fully finetuned model. If you have many datasets, you can save a lot of storage with a PEFT model and not have to worry about catastrophic forgetting or overfitting the backbone or base model.
|
| 116 |
+
|
| 117 |
+
## PEFT integrations
|
| 118 |
+
|
| 119 |
+
PEFT is widely supported across the Hugging Face ecosystem because of the massive efficiency it brings to training and inference.
|
| 120 |
+
|
| 121 |
+
### Diffusers
|
| 122 |
+
|
| 123 |
+
The iterative diffusion process consumes a lot of memory which can make it difficult to train. PEFT can help reduce the memory requirements and reduce the storage size of the final model checkpoint. For example, consider the memory required for training a Stable Diffusion model with LoRA on an A100 80GB GPU with more than 64GB of CPU RAM. The final model checkpoint size is only 8.8MB!
|
| 124 |
+
|
| 125 |
+
| Model | Full Finetuning | PEFT-LoRA | PEFT-LoRA with Gradient Checkpointing |
|
| 126 |
+
| --------- | ---- | ---- | ---- |
|
| 127 |
+
| CompVis/stable-diffusion-v1-4 | 27.5GB GPU / 3.97GB CPU | 15.5GB GPU / 3.84GB CPU | 8.12GB GPU / 3.77GB CPU |
|
| 128 |
+
|
| 129 |
+
> [!TIP]
|
| 130 |
+
> Take a look at the [examples/lora_dreambooth/train_dreambooth.py](examples/lora_dreambooth/train_dreambooth.py) training script to try training your own Stable Diffusion model with LoRA, and play around with the [smangrul/peft-lora-sd-dreambooth](https://huggingface.co/spaces/smangrul/peft-lora-sd-dreambooth) Space which is running on a T4 instance. Learn more about the PEFT integration in Diffusers in this [tutorial](https://huggingface.co/docs/peft/main/en/tutorial/peft_integrations#diffusers).
|
| 131 |
+
|
| 132 |
+
### Transformers
|
| 133 |
+
|
| 134 |
+
PEFT is directly integrated with [Transformers](https://huggingface.co/docs/transformers/main/en/peft). After loading a model, call `add_adapter` to add a new PEFT adapter to the model:
|
| 135 |
+
|
| 136 |
+
```python
|
| 137 |
+
from peft import LoraConfig
|
| 138 |
+
model = ... # transformers model
|
| 139 |
+
peft_config = LoraConfig(...)
|
| 140 |
+
model.add_adapter(lora_config, adapter_name="lora_1")
|
| 141 |
+
```
|
| 142 |
+
|
| 143 |
+
To load a trained PEFT adapter, call `load_adapter`:
|
| 144 |
+
|
| 145 |
+
```python
|
| 146 |
+
model = ... # transformers model
|
| 147 |
+
model.load_adapter(<path-to-adapter>, adapter_name="lora_1")
|
| 148 |
+
```
|
| 149 |
+
|
| 150 |
+
And to switch between different adapters, call `set_adapter`:
|
| 151 |
+
|
| 152 |
+
```python
|
| 153 |
+
model.set_adapter("lora_2")
|
| 154 |
+
```
|
| 155 |
+
|
| 156 |
+
The Transformers integration doesn't include all the functionalities offered in PEFT, such as methods for merging the adapter into the base model.
|
| 157 |
+
|
| 158 |
+
### Accelerate
|
| 159 |
+
|
| 160 |
+
[Accelerate](https://huggingface.co/docs/accelerate/index) is a library for distributed training and inference on various training setups and hardware (GPUs, TPUs, Apple Silicon, etc.). PEFT models work with Accelerate out of the box, making it really convenient to train really large models or use them for inference on consumer hardware with limited resources.
|
| 161 |
+
|
| 162 |
+
### TRL
|
| 163 |
+
|
| 164 |
+
PEFT can also be applied to training LLMs with RLHF components such as the ranker and policy. Get started by reading:
|
| 165 |
+
|
| 166 |
+
* [Fine-tune a Mistral-7b model with Direct Preference Optimization](https://towardsdatascience.com/fine-tune-a-mistral-7b-model-with-direct-preference-optimization-708042745aac) with PEFT and the [TRL](https://huggingface.co/docs/trl/index) library to learn more about the Direct Preference Optimization (DPO) method and how to apply it to a LLM.
|
| 167 |
+
* [Fine-tuning 20B LLMs with RLHF on a 24GB consumer GPU](https://huggingface.co/blog/trl-peft) with PEFT and the [TRL](https://huggingface.co/docs/trl/index) library, and then try out the [gpt2-sentiment_peft.ipynb](https://github.com/huggingface/trl/blob/main/examples/notebooks/gpt2-sentiment.ipynb) notebook to optimize GPT2 to generate positive movie reviews.
|
| 168 |
+
* [StackLLaMA: A hands-on guide to train LLaMA with RLHF](https://huggingface.co/blog/stackllama) with PEFT, and then try out the [stack_llama/scripts](https://github.com/huggingface/trl/tree/main/examples/research_projects/stack_llama/scripts) for supervised finetuning, reward modeling, and RL finetuning.
|
| 169 |
+
|
| 170 |
+
## Model support
|
| 171 |
+
|
| 172 |
+
Use this [Space](https://stevhliu-peft-methods.hf.space) or check out the [docs](https://huggingface.co/docs/peft/main/en/index) to find which models officially support a PEFT method out of the box. Even if you don't see a model listed below, you can manually configure the model config to enable PEFT for a model. Read the [New transformers architecture](https://huggingface.co/docs/peft/main/en/developer_guides/custom_models#new-transformers-architectures) guide to learn how.
|
| 173 |
+
|
| 174 |
+
## Contribute
|
| 175 |
+
|
| 176 |
+
If you would like to contribute to PEFT, please check out our [contribution guide](https://huggingface.co/docs/peft/developer_guides/contributing).
|
| 177 |
+
|
| 178 |
+
## Citing 🤗 PEFT
|
| 179 |
+
|
| 180 |
+
To use 🤗 PEFT in your publication, please cite it by using the following BibTeX entry.
|
| 181 |
+
|
| 182 |
+
```bibtex
|
| 183 |
+
@Misc{peft,
|
| 184 |
+
title = {{PEFT}: State-of-the-art Parameter-Efficient Fine-Tuning methods},
|
| 185 |
+
author = {Sourab Mangrulkar and Sylvain Gugger and Lysandre Debut and Younes Belkada and Sayak Paul and Benjamin Bossan and Marian Tietz},
|
| 186 |
+
howpublished = {\url{https://github.com/huggingface/peft}},
|
| 187 |
+
year = {2022}
|
| 188 |
+
}
|
| 189 |
+
```
|
tasks/tasksmith-9aea936e30e4/environment/source/docker/README.md
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# PEFT Docker images
|
| 2 |
+
|
| 3 |
+
Here we store all PEFT Docker images used in our testing infrastructure. We use python 3.11 for now on all our images.
|
| 4 |
+
|
| 5 |
+
- `peft-cpu`: PEFT compiled on CPU with all other HF libraries installed on main branch
|
| 6 |
+
- `peft-gpu`: PEFT complied for NVIDIA GPUs with all other HF libraries installed on main branch
|
tasks/tasksmith-9aea936e30e4/environment/source/docker/peft-cpu/Dockerfile
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Builds GPU docker image of PyTorch
|
| 2 |
+
# Uses multi-staged approach to reduce size
|
| 3 |
+
# Stage 1
|
| 4 |
+
# Use base conda image to reduce time
|
| 5 |
+
FROM continuumio/miniconda3:latest AS compile-image
|
| 6 |
+
# Specify py version
|
| 7 |
+
ENV PYTHON_VERSION=3.11
|
| 8 |
+
# Install apt libs - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile
|
| 9 |
+
RUN apt-get update && \
|
| 10 |
+
apt-get install -y curl git wget git-lfs ffmpeg libsndfile1-dev && \
|
| 11 |
+
apt-get clean && \
|
| 12 |
+
rm -rf /var/lib/apt/lists*
|
| 13 |
+
|
| 14 |
+
RUN git lfs install
|
| 15 |
+
|
| 16 |
+
# Create our conda env - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile
|
| 17 |
+
RUN conda create --name peft python=${PYTHON_VERSION} ipython jupyter pip
|
| 18 |
+
RUN python3 -m pip install --no-cache-dir --upgrade pip
|
| 19 |
+
|
| 20 |
+
# Below is copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile
|
| 21 |
+
# We don't install pytorch here yet since CUDA isn't available
|
| 22 |
+
# instead we use the direct torch wheel
|
| 23 |
+
ENV PATH=/opt/conda/envs/peft/bin:$PATH
|
| 24 |
+
# Activate our bash shell
|
| 25 |
+
RUN chsh -s /bin/bash
|
| 26 |
+
SHELL ["/bin/bash", "-c"]
|
| 27 |
+
# Activate the conda env and install transformers + accelerate from source
|
| 28 |
+
RUN source activate peft && \
|
| 29 |
+
python3 -m pip install --no-cache-dir \
|
| 30 |
+
librosa \
|
| 31 |
+
"soundfile>=0.12.1" \
|
| 32 |
+
scipy \
|
| 33 |
+
git+https://github.com/huggingface/transformers \
|
| 34 |
+
git+https://github.com/huggingface/accelerate \
|
| 35 |
+
peft[test]@git+https://github.com/huggingface/peft
|
| 36 |
+
|
| 37 |
+
# Install apt libs
|
| 38 |
+
RUN apt-get update && \
|
| 39 |
+
apt-get install -y curl git wget && \
|
| 40 |
+
apt-get clean && \
|
| 41 |
+
rm -rf /var/lib/apt/lists*
|
| 42 |
+
|
| 43 |
+
RUN echo "source activate peft" >> ~/.profile
|
| 44 |
+
|
| 45 |
+
# Activate the virtualenv
|
| 46 |
+
CMD ["/bin/bash"]
|
tasks/tasksmith-9aea936e30e4/environment/source/docker/peft-gpu/Dockerfile
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Builds GPU docker image of PyTorch
|
| 2 |
+
# Uses multi-staged approach to reduce size
|
| 3 |
+
# Stage 1
|
| 4 |
+
# Use base conda image to reduce time
|
| 5 |
+
FROM continuumio/miniconda3:latest AS compile-image
|
| 6 |
+
# Specify py version
|
| 7 |
+
ENV PYTHON_VERSION=3.11
|
| 8 |
+
# Install apt libs - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile
|
| 9 |
+
# Install audio-related libraries
|
| 10 |
+
RUN apt-get update && \
|
| 11 |
+
apt-get install -y curl git wget git-lfs ffmpeg libsndfile1-dev && \
|
| 12 |
+
apt-get clean && \
|
| 13 |
+
rm -rf /var/lib/apt/lists*
|
| 14 |
+
|
| 15 |
+
RUN git lfs install
|
| 16 |
+
|
| 17 |
+
# Create our conda env - copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile
|
| 18 |
+
RUN conda create --name peft python=${PYTHON_VERSION} ipython jupyter pip
|
| 19 |
+
|
| 20 |
+
# Below is copied from https://github.com/huggingface/accelerate/blob/main/docker/accelerate-gpu/Dockerfile
|
| 21 |
+
# We don't install pytorch here yet since CUDA isn't available
|
| 22 |
+
# instead we use the direct torch wheel
|
| 23 |
+
ENV PATH=/opt/conda/envs/peft/bin:$PATH
|
| 24 |
+
# Activate our bash shell
|
| 25 |
+
RUN chsh -s /bin/bash
|
| 26 |
+
SHELL ["/bin/bash", "-c"]
|
| 27 |
+
|
| 28 |
+
# Stage 2
|
| 29 |
+
FROM nvidia/cuda:12.8.1-devel-ubuntu22.04 AS build-image
|
| 30 |
+
COPY --from=compile-image /opt/conda /opt/conda
|
| 31 |
+
ENV PATH=/opt/conda/bin:$PATH
|
| 32 |
+
|
| 33 |
+
# Install apt libs
|
| 34 |
+
RUN apt-get update && \
|
| 35 |
+
apt-get install -y curl git wget && \
|
| 36 |
+
apt-get clean && \
|
| 37 |
+
rm -rf /var/lib/apt/lists*
|
| 38 |
+
|
| 39 |
+
RUN chsh -s /bin/bash
|
| 40 |
+
SHELL ["/bin/bash", "-c"]
|
| 41 |
+
|
| 42 |
+
RUN conda run -n peft pip install --no-cache-dir bitsandbytes optimum
|
| 43 |
+
|
| 44 |
+
# GPTQmodel doesn't find torch without build isolation
|
| 45 |
+
#
|
| 46 |
+
# Note: we are hard-coding CUDA_ARCH_LIST here since `gptqmodel` requires either nvidia-smi
|
| 47 |
+
# or CUDA_ARCH_LIST for compute capability information. Since the docker build is unlikely
|
| 48 |
+
# to have compute hardware available we use the information from the CI runner (which hosts
|
| 49 |
+
# a NVIDIA L4). So we fix the compute capability to 8.9. In the future we might extend this
|
| 50 |
+
# to a list of compute capabilities (separated by ;).
|
| 51 |
+
RUN CUDA_ARCH_LIST=8.9 conda run -n peft pip install --no-build-isolation gptqmodel
|
| 52 |
+
|
| 53 |
+
RUN \
|
| 54 |
+
# Add eetq for quantization testing; needs to run without build isolation since the setup
|
| 55 |
+
# script directly imports torch from the environment which would fail with isolation.
|
| 56 |
+
conda run -n peft pip install --no-build-isolation git+https://github.com/NetEase-FuXi/EETQ.git
|
| 57 |
+
|
| 58 |
+
# Activate the conda env and install transformers + accelerate from source
|
| 59 |
+
RUN conda run -n peft pip install -U --no-cache-dir \
|
| 60 |
+
librosa \
|
| 61 |
+
"soundfile>=0.12.1" \
|
| 62 |
+
scipy \
|
| 63 |
+
torchao \
|
| 64 |
+
fbgemm-gpu-genai>=1.2.0 \
|
| 65 |
+
git+https://github.com/huggingface/transformers \
|
| 66 |
+
git+https://github.com/huggingface/accelerate \
|
| 67 |
+
peft[test]@git+https://github.com/huggingface/peft \
|
| 68 |
+
# Add aqlm for quantization testing
|
| 69 |
+
aqlm[gpu]>=1.0.2 \
|
| 70 |
+
# Add HQQ for quantization testing
|
| 71 |
+
hqq
|
| 72 |
+
|
| 73 |
+
RUN conda run -n peft pip freeze | grep transformers
|
| 74 |
+
|
| 75 |
+
RUN echo "source activate peft" >> ~/.profile
|
| 76 |
+
|
| 77 |
+
# Activate the virtualenv
|
| 78 |
+
CMD ["/bin/bash"]
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/alora_finetuning/README.md
ADDED
|
@@ -0,0 +1,76 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Activated LoRA (aLoRA)
|
| 2 |
+
|
| 3 |
+
## Introduction
|
| 4 |
+
Activated LoRA (aLoRA) is an adapter that selectively activates its weights only after a given invocation sequence, ensuring that hidden states match the base model prior to this point. This allows reusing the base model KVs (stored in the KV cache) for tokens before the invocation,
|
| 5 |
+
enabling much faster real-world inference (e.g. vLLM) when switching between generation with the base model and generation with adapters.
|
| 6 |
+
See the [paper](https://huggingface.co/papers/2504.12397) for more details.
|
| 7 |
+
|
| 8 |
+
## Quick start (shown for Mistral 7B)
|
| 9 |
+
```python
|
| 10 |
+
import torch
|
| 11 |
+
from peft import LoraConfig, get_peft_model
|
| 12 |
+
from transformers import AutoTokenizer, AutoModelForCausalLM, Trainer, DataCollatorForLanguageModeling
|
| 13 |
+
from datasets import load_dataset
|
| 14 |
+
|
| 15 |
+
model = AutoModelForCausalLM.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3", device_map="auto")
|
| 16 |
+
tokenizer = AutoTokenizer.from_pretrained("mistralai/Mistral-7B-Instruct-v0.3")
|
| 17 |
+
dataset = load_dataset("Lots-of-LoRAs/task1660_super_glue_question_generation", split="train")
|
| 18 |
+
|
| 19 |
+
invocation_string = "[/INST]" # End of user turn in Mistral chat template
|
| 20 |
+
invocation_tokens = tokenizer.encode(invocation_string, add_special_tokens=False)
|
| 21 |
+
|
| 22 |
+
lora_config = LoraConfig(
|
| 23 |
+
task_type="CAUSAL_LM",
|
| 24 |
+
alora_invocation_tokens=invocation_tokens,
|
| 25 |
+
r=32,
|
| 26 |
+
target_modules=["q_proj", "k_proj", "v_proj"],
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
peft_model = get_peft_model(model, lora_config)
|
| 30 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 31 |
+
trainer = Trainer(
|
| 32 |
+
model=peft_model,
|
| 33 |
+
train_dataset=dataset,
|
| 34 |
+
dataset_text_field="text",
|
| 35 |
+
max_length=2048,
|
| 36 |
+
tokenizer=tokenizer,
|
| 37 |
+
data_collator=data_collator,
|
| 38 |
+
)
|
| 39 |
+
trainer.train()
|
| 40 |
+
peft_model.save_pretrained("alora-mistral-7b")
|
| 41 |
+
```
|
| 42 |
+
|
| 43 |
+
### Use the training example script directly
|
| 44 |
+
Pass the invocation string with `--invocation_string` when running the training example
|
| 45 |
+
script. For Mistral 7B, do:
|
| 46 |
+
```bash
|
| 47 |
+
python examples/alora_finetuning/alora_finetuning.py --base_model mistralai/Mistral-7B-Instruct-v0.3 --data_path Lots-of-LoRAs/task1660_super_glue_question_generation --invocation_string "[/INST]"
|
| 48 |
+
```
|
| 49 |
+
and similarly for Llama-3.2-3B-Instruct:
|
| 50 |
+
```bash
|
| 51 |
+
python examples/alora_finetuning/alora_finetuning.py --base_model meta-llama/Llama-3.2-3B-Instruct --data_path Lots-of-LoRAs/task1660_super_glue_question_generation --invocation_string "<|start_header_id|>assistant<|end_header_id|>"
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
### Full example of the script
|
| 55 |
+
```bash
|
| 56 |
+
python alora_finetuning.py \
|
| 57 |
+
--base_model "PATH_TO_MODEL" \
|
| 58 |
+
--data_path "PATH_TO_DATASET" \
|
| 59 |
+
--output_dir "PATH_TO_OUTPUT_DIR" \
|
| 60 |
+
--batch_size 1 \
|
| 61 |
+
--num_epochs 3 \
|
| 62 |
+
--learning_rate 3e-4 \
|
| 63 |
+
--cutoff_len 512 \
|
| 64 |
+
--val_set_size 500 \
|
| 65 |
+
--invocation_string "[/INST]" \
|
| 66 |
+
--quantize \
|
| 67 |
+
--eval_step 10 \
|
| 68 |
+
--save_step 100 \
|
| 69 |
+
--device "auto" \
|
| 70 |
+
--lora_r 32 \
|
| 71 |
+
--lora_alpha 32 \
|
| 72 |
+
--lora_dropout 0.05 \
|
| 73 |
+
--lora_target_modules "q_proj,k_proj,v_proj,o_proj,gate_proj,up_proj,down_proj" \
|
| 74 |
+
--hub_model_id "YOUR_HF_REPO" \
|
| 75 |
+
--push_to_hub
|
| 76 |
+
```
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/alora_finetuning/alora_finetuning.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
|
| 3 |
+
import torch
|
| 4 |
+
from datasets import load_dataset
|
| 5 |
+
from transformers import (
|
| 6 |
+
AutoModelForCausalLM,
|
| 7 |
+
AutoTokenizer,
|
| 8 |
+
BitsAndBytesConfig,
|
| 9 |
+
DataCollatorForLanguageModeling,
|
| 10 |
+
Trainer,
|
| 11 |
+
TrainingArguments,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from peft import LoraConfig, PeftModel, get_peft_model, prepare_model_for_kbit_training
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def train_model(
|
| 18 |
+
base_model: str,
|
| 19 |
+
data_path: str,
|
| 20 |
+
output_dir: str,
|
| 21 |
+
batch_size: int,
|
| 22 |
+
num_epochs: int,
|
| 23 |
+
learning_rate: float,
|
| 24 |
+
cutoff_len: int,
|
| 25 |
+
val_set_size: int,
|
| 26 |
+
invocation_string: str,
|
| 27 |
+
quantize: bool,
|
| 28 |
+
eval_step: int,
|
| 29 |
+
save_step: int,
|
| 30 |
+
device: str,
|
| 31 |
+
lora_r: int,
|
| 32 |
+
lora_alpha: int,
|
| 33 |
+
lora_dropout: float,
|
| 34 |
+
lora_target_modules: str,
|
| 35 |
+
hub_model_id: str,
|
| 36 |
+
push_to_hub: bool,
|
| 37 |
+
):
|
| 38 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
| 39 |
+
hf_token = os.getenv("HF_TOKEN")
|
| 40 |
+
|
| 41 |
+
if device == "auto":
|
| 42 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 43 |
+
else:
|
| 44 |
+
device = torch.device(device)
|
| 45 |
+
print(f"Using device: {device}")
|
| 46 |
+
|
| 47 |
+
tokenizer = AutoTokenizer.from_pretrained(base_model, token=hf_token)
|
| 48 |
+
tokenizer.pad_token = tokenizer.unk_token
|
| 49 |
+
invocation_tokens = tokenizer.encode(invocation_string, add_special_tokens=False)
|
| 50 |
+
|
| 51 |
+
if quantize:
|
| 52 |
+
if (torch.cuda.is_available() and torch.cuda.is_bf16_supported()) or torch.xpu.is_available():
|
| 53 |
+
bnb_4bit_compute_dtype = torch.bfloat16
|
| 54 |
+
else:
|
| 55 |
+
bnb_4bit_compute_dtype = torch.float16
|
| 56 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 57 |
+
base_model,
|
| 58 |
+
token=hf_token,
|
| 59 |
+
quantization_config=BitsAndBytesConfig(
|
| 60 |
+
load_in_4bit=True,
|
| 61 |
+
bnb_4bit_compute_dtype=bnb_4bit_compute_dtype,
|
| 62 |
+
bnb_4bit_use_double_quant=True,
|
| 63 |
+
bnb_4bit_quant_type="nf4",
|
| 64 |
+
),
|
| 65 |
+
)
|
| 66 |
+
model = prepare_model_for_kbit_training(model, use_gradient_checkpointing=True)
|
| 67 |
+
else:
|
| 68 |
+
model = AutoModelForCausalLM.from_pretrained(base_model, token=hf_token)
|
| 69 |
+
|
| 70 |
+
lora_config = LoraConfig(
|
| 71 |
+
task_type="CAUSAL_LM",
|
| 72 |
+
alora_invocation_tokens=invocation_tokens,
|
| 73 |
+
r=lora_r,
|
| 74 |
+
lora_alpha=lora_alpha,
|
| 75 |
+
target_modules=(lora_target_modules.split(",") if lora_target_modules else ["q_proj", "k_proj", "v_proj"]),
|
| 76 |
+
lora_dropout=lora_dropout,
|
| 77 |
+
bias="none",
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
model = get_peft_model(model, lora_config)
|
| 81 |
+
|
| 82 |
+
model.to(device)
|
| 83 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 84 |
+
|
| 85 |
+
dataset = load_dataset(data_path)
|
| 86 |
+
|
| 87 |
+
def tokenize_function(examples):
|
| 88 |
+
formatted_texts = [
|
| 89 |
+
tokenizer.apply_chat_template(
|
| 90 |
+
[
|
| 91 |
+
{"role": "user", "content": user_msg},
|
| 92 |
+
{"role": "assistant", "content": assistant_msg},
|
| 93 |
+
],
|
| 94 |
+
tokenize=False, # get plain text first
|
| 95 |
+
add_generation_prompt=False,
|
| 96 |
+
)
|
| 97 |
+
for user_msg, assistant_msg in zip(examples["input"], examples["output"])
|
| 98 |
+
]
|
| 99 |
+
|
| 100 |
+
# 2) Tokenize those texts
|
| 101 |
+
model_inputs = tokenizer(
|
| 102 |
+
formatted_texts,
|
| 103 |
+
padding="max_length",
|
| 104 |
+
truncation=True,
|
| 105 |
+
max_length=cutoff_len,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
labels = []
|
| 109 |
+
for ids in model_inputs["input_ids"]:
|
| 110 |
+
labels.append([(token_id if token_id != tokenizer.pad_token_id else -100) for token_id in ids])
|
| 111 |
+
model_inputs["labels"] = labels
|
| 112 |
+
|
| 113 |
+
return model_inputs
|
| 114 |
+
|
| 115 |
+
# Tokenize the dataset and prepare for training
|
| 116 |
+
tokenized_datasets = dataset.map(tokenize_function, batched=True, remove_columns=dataset["train"].column_names)
|
| 117 |
+
|
| 118 |
+
# Data collator to dynamically pad the batched examples
|
| 119 |
+
data_collator = DataCollatorForLanguageModeling(tokenizer, mlm=False)
|
| 120 |
+
|
| 121 |
+
training_args = TrainingArguments(
|
| 122 |
+
output_dir=output_dir,
|
| 123 |
+
num_train_epochs=num_epochs,
|
| 124 |
+
per_device_train_batch_size=batch_size,
|
| 125 |
+
per_device_eval_batch_size=batch_size,
|
| 126 |
+
warmup_steps=100,
|
| 127 |
+
weight_decay=0.01,
|
| 128 |
+
logging_dir="./logs",
|
| 129 |
+
logging_steps=eval_step,
|
| 130 |
+
save_steps=save_step,
|
| 131 |
+
save_total_limit=2,
|
| 132 |
+
push_to_hub=push_to_hub,
|
| 133 |
+
hub_model_id=hub_model_id,
|
| 134 |
+
gradient_accumulation_steps=16,
|
| 135 |
+
fp16=True,
|
| 136 |
+
learning_rate=learning_rate,
|
| 137 |
+
hub_token=hf_token,
|
| 138 |
+
)
|
| 139 |
+
|
| 140 |
+
if torch.cuda.is_available():
|
| 141 |
+
torch.cuda.empty_cache()
|
| 142 |
+
elif torch.xpu.is_available():
|
| 143 |
+
torch.xpu.empty_cache()
|
| 144 |
+
|
| 145 |
+
trainer = Trainer(
|
| 146 |
+
model=model,
|
| 147 |
+
args=training_args,
|
| 148 |
+
train_dataset=tokenized_datasets["train"],
|
| 149 |
+
eval_dataset=tokenized_datasets["test"],
|
| 150 |
+
data_collator=data_collator,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
trainer.train()
|
| 154 |
+
|
| 155 |
+
if push_to_hub:
|
| 156 |
+
trainer.push_to_hub(commit_message="Fine-tuned model")
|
| 157 |
+
|
| 158 |
+
model.save_pretrained(output_dir)
|
| 159 |
+
tokenizer.save_pretrained(output_dir)
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def model_inference(model_path: str, adapter_path: str, prompt: str = None, data_path: str = None):
|
| 163 |
+
"""
|
| 164 |
+
Simple inference with the tuned aLoRA adapter. Optionally (reuse_cache = True) demonstrates
|
| 165 |
+
that the aLoRA adapter can (but does not need to) use KV cache created by the base model,
|
| 166 |
+
perhaps during a prior generation turn.
|
| 167 |
+
|
| 168 |
+
Purely for demonstration purposes. See the [paper](https://huggingface.co/papers/2504.12397)
|
| 169 |
+
for realistic multiturn cache reuse examples.
|
| 170 |
+
"""
|
| 171 |
+
if prompt is None:
|
| 172 |
+
# Use first row of test data
|
| 173 |
+
dataset = load_dataset(data_path)
|
| 174 |
+
prompt = dataset["test"][0]["input"]
|
| 175 |
+
tokenizer = AutoTokenizer.from_pretrained(model_path)
|
| 176 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_path)
|
| 177 |
+
alora_model = PeftModel.from_pretrained(base_model, adapter_path)
|
| 178 |
+
chat = [{"role": "user", "content": prompt}]
|
| 179 |
+
text = tokenizer.apply_chat_template(chat, tokenize=False, add_generation_prompt=True)
|
| 180 |
+
inputs = tokenizer(text, return_tensors="pt").to(base_model.device)
|
| 181 |
+
|
| 182 |
+
# Generate answer with adapter
|
| 183 |
+
output_dict = alora_model.generate(**inputs, return_dict_in_generate=True, max_new_tokens=20)
|
| 184 |
+
alora_outputs = output_dict.sequences
|
| 185 |
+
|
| 186 |
+
# Print results
|
| 187 |
+
print(f"Prompt: {text}")
|
| 188 |
+
response = tokenizer.decode(alora_outputs[0][inputs["input_ids"].shape[1] :], skip_special_tokens=True)
|
| 189 |
+
print(f"Trained adapter response: {response}")
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
if __name__ == "__main__":
|
| 193 |
+
import argparse
|
| 194 |
+
|
| 195 |
+
parser = argparse.ArgumentParser(description="Fine-tune Mistral with Activated LoRA")
|
| 196 |
+
parser.add_argument(
|
| 197 |
+
"--base_model", type=str, default="mistralai/Mistral-7B-Instruct-v0.3", help="Base model path or name"
|
| 198 |
+
)
|
| 199 |
+
parser.add_argument(
|
| 200 |
+
"--data_path",
|
| 201 |
+
type=str,
|
| 202 |
+
default="Lots-of-LoRAs/task1660_super_glue_question_generation",
|
| 203 |
+
help="Dataset path or name",
|
| 204 |
+
)
|
| 205 |
+
parser.add_argument(
|
| 206 |
+
"--output_dir", type=str, default="path/to/output", help="Output directory for the fine-tuned model"
|
| 207 |
+
)
|
| 208 |
+
parser.add_argument("--batch_size", type=int, default=2, help="Batch size")
|
| 209 |
+
parser.add_argument("--num_epochs", type=int, default=1, help="Number of training epochs")
|
| 210 |
+
parser.add_argument("--learning_rate", type=float, default=1e-4, help="Learning rate")
|
| 211 |
+
parser.add_argument("--cutoff_len", type=int, default=2048, help="Cutoff length for tokenization")
|
| 212 |
+
parser.add_argument("--val_set_size", type=int, default=500, help="Validation set size")
|
| 213 |
+
parser.add_argument(
|
| 214 |
+
"--invocation_string",
|
| 215 |
+
type=str,
|
| 216 |
+
default="[/INST]",
|
| 217 |
+
help="String that activates the aLoRA adapter. Model dependent.",
|
| 218 |
+
)
|
| 219 |
+
parser.add_argument("--quantize", action="store_true", help="Use quantization")
|
| 220 |
+
parser.add_argument("--eval_step", type=int, default=10, help="Evaluation step interval")
|
| 221 |
+
parser.add_argument("--save_step", type=int, default=100, help="Save step interval")
|
| 222 |
+
parser.add_argument("--device", type=str, default="auto", help="Device to use for training")
|
| 223 |
+
parser.add_argument("--lora_r", type=int, default=32, help="LoRA rank")
|
| 224 |
+
parser.add_argument("--lora_alpha", type=int, default=32, help="LoRA alpha")
|
| 225 |
+
parser.add_argument("--lora_dropout", type=float, default=0.05, help="LoRA dropout rate")
|
| 226 |
+
parser.add_argument(
|
| 227 |
+
"--lora_target_modules", type=str, default=None, help="Comma-separated list of target modules for LoRA"
|
| 228 |
+
)
|
| 229 |
+
parser.add_argument(
|
| 230 |
+
"--hub_model_id",
|
| 231 |
+
type=str,
|
| 232 |
+
default="path/to/repo",
|
| 233 |
+
help="Repository name to push the model on the Hugging Face Hub",
|
| 234 |
+
)
|
| 235 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether to push the model to Hugging Face Hub")
|
| 236 |
+
args = parser.parse_args()
|
| 237 |
+
train_model(
|
| 238 |
+
base_model=args.base_model,
|
| 239 |
+
data_path=args.data_path,
|
| 240 |
+
output_dir=args.output_dir,
|
| 241 |
+
batch_size=args.batch_size,
|
| 242 |
+
num_epochs=args.num_epochs,
|
| 243 |
+
learning_rate=args.learning_rate,
|
| 244 |
+
cutoff_len=args.cutoff_len,
|
| 245 |
+
val_set_size=args.val_set_size,
|
| 246 |
+
invocation_string=args.invocation_string,
|
| 247 |
+
quantize=args.quantize,
|
| 248 |
+
eval_step=args.eval_step,
|
| 249 |
+
save_step=args.save_step,
|
| 250 |
+
device=args.device,
|
| 251 |
+
lora_r=args.lora_r,
|
| 252 |
+
lora_alpha=args.lora_alpha,
|
| 253 |
+
lora_dropout=args.lora_dropout,
|
| 254 |
+
lora_target_modules=args.lora_target_modules,
|
| 255 |
+
hub_model_id=args.hub_model_id,
|
| 256 |
+
push_to_hub=args.push_to_hub,
|
| 257 |
+
)
|
| 258 |
+
print("Model trained. Running test inference.")
|
| 259 |
+
model_inference(model_path=args.base_model, adapter_path=args.output_dir, data_path=args.data_path)
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/arrow_multitask/arrow_phi3_mini.py
ADDED
|
@@ -0,0 +1,383 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
"""
|
| 16 |
+
This script provides a simple evaluation pipeline for multiple-choice reasoning datasets
|
| 17 |
+
(e.g., BoolQ, HellaSwag, ARC, OpenBookQA, Winogrande) with different composition strategies.
|
| 18 |
+
|
| 19 |
+
Usage examples:
|
| 20 |
+
python arrow_phi3_mini.py --strategy base --ds_name arc-challenge
|
| 21 |
+
python arrow_phi3_mini.py --strategy arrow --ds_name boolq
|
| 22 |
+
python arrow_phi3_mini.py --strategy gks --ds_name hswag
|
| 23 |
+
|
| 24 |
+
Key features:
|
| 25 |
+
- Supports three strategies:
|
| 26 |
+
• "base" → Evaluate the quantized base model directly
|
| 27 |
+
• "arrow" → Use Arrow modular routing with task-specific adapters
|
| 28 |
+
• "gks" → Use Arrow + GenKnowSub (subtracting general-domain knowledge)
|
| 29 |
+
- Loads evaluation datasets from the Hugging Face Hub
|
| 30 |
+
- Implements a batched evaluation loop that computes per-option likelihoods and selects
|
| 31 |
+
the answer with the lowest average loss
|
| 32 |
+
- Reports simple accuracy
|
| 33 |
+
|
| 34 |
+
Implementation details:
|
| 35 |
+
- The base model is quantized to 4-bit using `BitsAndBytesConfig` (nf4, bf16 compute).
|
| 36 |
+
- For Arrow and GKS, task-specific adapters are loaded from the Hugging Face Hub:
|
| 37 |
+
TahaBa/phi3-mini-clustered-flan/ts_expert_i
|
| 38 |
+
- Task-specific adapters were trained on 10 clusters of FLAN tasks.
|
| 39 |
+
- The clusters were created using Model-Based Clustering (MBC):
|
| 40 |
+
1. Train a LoRA adapter for each individual task.
|
| 41 |
+
2. Apply k-means clustering to group tasks based on these adapters.
|
| 42 |
+
3. Train a LoRA adapter for each resulting cluster.
|
| 43 |
+
For more details, see the Arrow paper: https://huggingface.co/papers/2405.11157
|
| 44 |
+
|
| 45 |
+
- For GKS, general adapters are loaded from:
|
| 46 |
+
TahaBa/phi3-mini-general-adapters/...
|
| 47 |
+
- These adapters were trained on English, French, and German Wikipedia data
|
| 48 |
+
using a causal language modeling objective with (507-token context → 5-token completion) pairs.
|
| 49 |
+
- This setup encodes general knowledge into the LoRA space, which can then be
|
| 50 |
+
subtracted from task-specific adapters during inference to isolate and purify them.
|
| 51 |
+
For more details, see the GenKnowSub paper: https://huggingface.co/papers/2505.10939
|
| 52 |
+
|
| 53 |
+
- `evaluate_on_multi_choice_batched` handles tokenization, masking context tokens,
|
| 54 |
+
and computing per-choice log-likelihoods for fair comparison.
|
| 55 |
+
- Accuracy is printed at the end for the selected dataset.
|
| 56 |
+
|
| 57 |
+
This script is mainly meant for demonstration purposes and lightweight evaluation,
|
| 58 |
+
not full-scale benchmarking (batch size / max length can be tuned).
|
| 59 |
+
|
| 60 |
+
=======================================================================================
|
| 61 |
+
|
| 62 |
+
Results (evaluated with microsoft/Phi-3-mini-4k-instruct, 4-bit quantization):
|
| 63 |
+
|
| 64 |
+
| Dataset | Base Acc. | Arrow Acc. | Arrow+GKS Acc. |
|
| 65 |
+
|--------------|-----------|------------|----------------|
|
| 66 |
+
| ARC-Challenge| 0.4515 | 0.5418 | 0.5585 |
|
| 67 |
+
| ARC-Easy | 0.6894 | 0.8404 | 0.8473 |
|
| 68 |
+
| Winogrande | 0.5769 | 0.6550 | 0.6724 |
|
| 69 |
+
| BoolQ | 0.8146 | 0.8030 | 0.8247 |
|
| 70 |
+
| OpenBookQA | 0.43 | 0.448 | 0.472 |
|
| 71 |
+
| HellaSwag | 0.7318 | 0.7150 | 0.7376 |
|
| 72 |
+
|
| 73 |
+
Observations:
|
| 74 |
+
- Arrow generally improves over the base model by routing tokens to the most relevant task adapters.
|
| 75 |
+
- Applying GKS (general knowledge subtraction) consistently gives further gains compared to Arrow and Base.
|
| 76 |
+
|
| 77 |
+
These numbers are not meant as leaderboard results, but as a sanity check
|
| 78 |
+
to verify that the implementation works as expected and demonstrates
|
| 79 |
+
the benefits of Arrow and GenKnowSub.
|
| 80 |
+
"""
|
| 81 |
+
|
| 82 |
+
import argparse
|
| 83 |
+
import random
|
| 84 |
+
|
| 85 |
+
import numpy as np
|
| 86 |
+
import torch
|
| 87 |
+
from datasets import load_dataset
|
| 88 |
+
from sklearn.metrics import accuracy_score
|
| 89 |
+
from tqdm import tqdm
|
| 90 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
|
| 91 |
+
|
| 92 |
+
from peft import ArrowConfig, create_arrow_model
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
MODEL_NAME = "microsoft/Phi-3-mini-4k-instruct"
|
| 96 |
+
MODEL_MAX_LEN = 2048
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def parse_args():
|
| 100 |
+
parser = argparse.ArgumentParser(description="Training script with strategy selection")
|
| 101 |
+
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--strategy",
|
| 104 |
+
type=str,
|
| 105 |
+
choices=["base", "arrow", "gks"],
|
| 106 |
+
default="base",
|
| 107 |
+
help="Training strategy to use: base, arrow, or gks",
|
| 108 |
+
)
|
| 109 |
+
parser.add_argument(
|
| 110 |
+
"--ds_name",
|
| 111 |
+
type=str,
|
| 112 |
+
choices=["boolq", "hswag", "arc-easy", "arc-challenge", "oqa", "wg"],
|
| 113 |
+
default="arc-challenge",
|
| 114 |
+
help="Dataset to use: boolq, hswag, arc-easy, arc-challenge, oqa, wg",
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
return parser.parse_args()
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def read_test_dataset(ds_name):
|
| 121 |
+
if ds_name == "boolq":
|
| 122 |
+
ds = load_dataset("google/boolq", split="validation", trust_remote_code=True)
|
| 123 |
+
elif ds_name == "hswag":
|
| 124 |
+
ds = load_dataset("Rowan/hellaswag", split="validation", trust_remote_code=True)
|
| 125 |
+
elif ds_name == "arc-challenge":
|
| 126 |
+
ds = load_dataset("allenai/ai2_arc", "ARC-Challenge", split="validation", trust_remote_code=True)
|
| 127 |
+
elif ds_name == "arc-easy":
|
| 128 |
+
ds = load_dataset("allenai/ai2_arc", "ARC-Easy", split="validation", trust_remote_code=True)
|
| 129 |
+
elif ds_name == "oqa":
|
| 130 |
+
ds = load_dataset("allenai/openbookqa", split="validation", trust_remote_code=True)
|
| 131 |
+
elif ds_name == "wg":
|
| 132 |
+
ds = load_dataset("allenai/winogrande", "winogrande_xl", split="validation", trust_remote_code=True)
|
| 133 |
+
else:
|
| 134 |
+
raise f"Dataset {ds_name} is not supported yet."
|
| 135 |
+
|
| 136 |
+
return ds
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def extract_input_content(ds_name, row):
|
| 140 |
+
if ds_name == "boolq":
|
| 141 |
+
return f"[passage]{row['passage']}[question]{row['question']}"
|
| 142 |
+
if ds_name == "hswag":
|
| 143 |
+
return row["ctx"]
|
| 144 |
+
if (ds_name == "arc-challenge") or (ds_name == "arc-easy"):
|
| 145 |
+
return row["question"]
|
| 146 |
+
if ds_name == "oqa":
|
| 147 |
+
return row["question_stem"]
|
| 148 |
+
if ds_name == "wg":
|
| 149 |
+
return row["sentence"]
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def create_multi_choice_options(row, ds_name):
|
| 153 |
+
options_texts = []
|
| 154 |
+
content = extract_input_content(ds_name, row)
|
| 155 |
+
if ds_name == "boolq":
|
| 156 |
+
choices = ["true", "false"]
|
| 157 |
+
if ds_name == "hswag":
|
| 158 |
+
choices = row["endings"]
|
| 159 |
+
if (ds_name == "arc-challenge") or (ds_name == "arc-easy"):
|
| 160 |
+
choices = row["choices"]["text"]
|
| 161 |
+
if ds_name == "wg":
|
| 162 |
+
choices = [row["option1"], row["option2"]]
|
| 163 |
+
if ds_name == "oqa":
|
| 164 |
+
choices = row["choices"]["text"]
|
| 165 |
+
|
| 166 |
+
for choice in choices:
|
| 167 |
+
options_texts.append(f"<|user|>\n{content}<|end|>\n<|assistant|>{choice}<|end|>\n")
|
| 168 |
+
|
| 169 |
+
return options_texts
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def extract_multi_choice_target_index(row, ds_name):
|
| 173 |
+
if ds_name == "boolq":
|
| 174 |
+
return 0 if row["answer"] is True else 1
|
| 175 |
+
if ds_name == "hswag":
|
| 176 |
+
return int(row["label"])
|
| 177 |
+
if (ds_name == "arc-challenge") or (ds_name == "arc-easy"):
|
| 178 |
+
return row["choices"]["label"].index(row["answerKey"])
|
| 179 |
+
if ds_name == "wg":
|
| 180 |
+
return int(row["answer"]) - 1
|
| 181 |
+
if ds_name == "oqa":
|
| 182 |
+
return row["choices"]["label"].index(row["answerKey"])
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def set_seed(seed: int):
|
| 186 |
+
random.seed(seed)
|
| 187 |
+
np.random.seed(seed)
|
| 188 |
+
torch.manual_seed(seed)
|
| 189 |
+
if torch.cuda.is_available():
|
| 190 |
+
torch.cuda.manual_seed_all(seed)
|
| 191 |
+
elif hasattr(torch, "xpu") and torch.xpu.is_available():
|
| 192 |
+
torch.xpu.manual_seed_all(seed)
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def compute_loglike_loss(logits, labels, reduction="none"):
|
| 196 |
+
bs = logits.size(0)
|
| 197 |
+
vocab_size = logits.size(-1)
|
| 198 |
+
labels = labels.squeeze(-1)
|
| 199 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
| 200 |
+
shift_labels = labels[..., 1:].contiguous()
|
| 201 |
+
|
| 202 |
+
# Flatten the tokens
|
| 203 |
+
loss_fct = torch.nn.CrossEntropyLoss(reduction=reduction)
|
| 204 |
+
shift_logits = shift_logits.view(-1, vocab_size)
|
| 205 |
+
shift_labels = shift_labels.view(-1)
|
| 206 |
+
|
| 207 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
| 208 |
+
loss = loss_fct(shift_logits, shift_labels)
|
| 209 |
+
|
| 210 |
+
# reshape back
|
| 211 |
+
if reduction == "none":
|
| 212 |
+
loss = loss.view((bs, -1))
|
| 213 |
+
non_zero_loss = (loss != 0).sum(dim=-1)
|
| 214 |
+
non_zero_loss[non_zero_loss == 0] = 1
|
| 215 |
+
loss = loss.sum(dim=-1) / non_zero_loss
|
| 216 |
+
|
| 217 |
+
return loss.float() # Convert to float32 before returning
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def evaluate_on_multi_choice_batched(
|
| 221 |
+
eval_dataset, model, tokenizer, ds_name, labels, predictions, args, batch_size=32, max_length=512, device="auto"
|
| 222 |
+
):
|
| 223 |
+
# Local import to mirror your original function
|
| 224 |
+
model.eval()
|
| 225 |
+
|
| 226 |
+
if device == "auto":
|
| 227 |
+
device = torch.accelerator.current_accelerator().type if hasattr(torch, "accelerator") else "cuda"
|
| 228 |
+
else:
|
| 229 |
+
device = torch.device(device)
|
| 230 |
+
|
| 231 |
+
for start in tqdm(
|
| 232 |
+
range(0, len(eval_dataset), batch_size), total=(len(eval_dataset) + batch_size - 1) // batch_size
|
| 233 |
+
):
|
| 234 |
+
rows = [eval_dataset[i] for i in range(start, min(start + batch_size, len(eval_dataset)))]
|
| 235 |
+
|
| 236 |
+
# Build the flattened option texts for this batch
|
| 237 |
+
all_texts = []
|
| 238 |
+
options_per_sample = [] # number of options for each sample
|
| 239 |
+
ctx_lens_per_option = [] # context length replicated per option
|
| 240 |
+
|
| 241 |
+
for row in rows:
|
| 242 |
+
# options: ["<|user|>...<|assistant|>choiceA<|end|>", ...]
|
| 243 |
+
options = create_multi_choice_options(row, ds_name)
|
| 244 |
+
options_per_sample.append(len(options))
|
| 245 |
+
|
| 246 |
+
# compute context length once per sample (align with your -1 shift)
|
| 247 |
+
content = extract_input_content(ds_name, row)
|
| 248 |
+
context_prompt = f"<|user|>\n{content}<|end|>\n<|assistant|>"
|
| 249 |
+
ctx_len = len(tokenizer.encode(context_prompt)) - 1
|
| 250 |
+
|
| 251 |
+
all_texts.extend(options)
|
| 252 |
+
ctx_lens_per_option.extend([ctx_len] * len(options))
|
| 253 |
+
|
| 254 |
+
# collect gold label
|
| 255 |
+
labels.append(extract_multi_choice_target_index(row, ds_name))
|
| 256 |
+
|
| 257 |
+
# Tokenize all options in one go
|
| 258 |
+
tokenized = tokenizer(
|
| 259 |
+
all_texts,
|
| 260 |
+
return_tensors="pt",
|
| 261 |
+
padding=True,
|
| 262 |
+
truncation=True,
|
| 263 |
+
max_length=max_length,
|
| 264 |
+
)
|
| 265 |
+
tokenized = {k: v.to(device) for k, v in tokenized.items()}
|
| 266 |
+
|
| 267 |
+
# Create masked labels: ignore context and padding
|
| 268 |
+
masked_labels = tokenized["input_ids"].clone()
|
| 269 |
+
for i, ctx_len in enumerate(ctx_lens_per_option):
|
| 270 |
+
masked_labels[i, :ctx_len] = -100
|
| 271 |
+
masked_labels[tokenized["attention_mask"] == 0] = -100
|
| 272 |
+
|
| 273 |
+
with torch.no_grad():
|
| 274 |
+
logits = model(input_ids=tokenized["input_ids"], attention_mask=tokenized["attention_mask"]).logits
|
| 275 |
+
# per-sequence losses
|
| 276 |
+
losses = compute_loglike_loss(logits, masked_labels, reduction="none").detach().cpu()
|
| 277 |
+
|
| 278 |
+
# Reduce per sample (argmin across its options)
|
| 279 |
+
idx = 0
|
| 280 |
+
for n_opt in options_per_sample:
|
| 281 |
+
pred = torch.argmin(losses[idx : idx + n_opt]).item()
|
| 282 |
+
predictions.append(pred)
|
| 283 |
+
idx += n_opt
|
| 284 |
+
|
| 285 |
+
print(
|
| 286 |
+
f"Accuracy for dataset {args.ds_name} and strategy {args.strategy} is: {accuracy_score(labels, predictions)}"
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
if __name__ == "__main__":
|
| 291 |
+
args = parse_args()
|
| 292 |
+
print(f"Selected strategy: {args.strategy}")
|
| 293 |
+
print(f"Dataset name: {args.ds_name}")
|
| 294 |
+
|
| 295 |
+
# Loading the tokeniser
|
| 296 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 297 |
+
MODEL_NAME,
|
| 298 |
+
use_fast=True,
|
| 299 |
+
padding_side="right",
|
| 300 |
+
model_max_length=MODEL_MAX_LEN,
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
# Quantisation config
|
| 304 |
+
bnb_config = BitsAndBytesConfig(
|
| 305 |
+
load_in_4bit=True,
|
| 306 |
+
bnb_4bit_quant_type="nf4",
|
| 307 |
+
bnb_4bit_compute_dtype=torch.bfloat16,
|
| 308 |
+
bnb_4bit_use_double_quant=False,
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
# Loading the model
|
| 312 |
+
base_model = AutoModelForCausalLM.from_pretrained(
|
| 313 |
+
MODEL_NAME,
|
| 314 |
+
dtype=torch.bfloat16,
|
| 315 |
+
device_map="auto",
|
| 316 |
+
quantization_config=bnb_config,
|
| 317 |
+
)
|
| 318 |
+
|
| 319 |
+
# Loading the test dataset
|
| 320 |
+
test_dataset = read_test_dataset(args.ds_name)
|
| 321 |
+
print(f"{args.ds_name} is loaded with size: {len(test_dataset)}.")
|
| 322 |
+
|
| 323 |
+
labels, predictions = [], []
|
| 324 |
+
if args.strategy == "base":
|
| 325 |
+
# Batch-wise inference
|
| 326 |
+
with torch.no_grad():
|
| 327 |
+
evaluate_on_multi_choice_batched(
|
| 328 |
+
test_dataset,
|
| 329 |
+
base_model,
|
| 330 |
+
tokenizer,
|
| 331 |
+
args.ds_name,
|
| 332 |
+
labels,
|
| 333 |
+
predictions,
|
| 334 |
+
args,
|
| 335 |
+
batch_size=64, # tune this
|
| 336 |
+
max_length=512, # tune if options are long
|
| 337 |
+
device="auto",
|
| 338 |
+
)
|
| 339 |
+
else:
|
| 340 |
+
general_adapter_paths = []
|
| 341 |
+
if args.strategy == "gks":
|
| 342 |
+
arrow_config = ArrowConfig(
|
| 343 |
+
top_k=3,
|
| 344 |
+
router_temperature=1.0,
|
| 345 |
+
use_gks=True,
|
| 346 |
+
)
|
| 347 |
+
# General adapter paths from the hub
|
| 348 |
+
general_adapter_paths = [
|
| 349 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langen/checkpoint-17",
|
| 350 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langfr/checkpoint-35",
|
| 351 |
+
"TahaBa/phi3-mini-general-adapters/cluster0_batch16_prop1.0_langger/checkpoint-17",
|
| 352 |
+
]
|
| 353 |
+
else:
|
| 354 |
+
arrow_config = ArrowConfig(
|
| 355 |
+
top_k=3,
|
| 356 |
+
router_temperature=1.0,
|
| 357 |
+
)
|
| 358 |
+
|
| 359 |
+
# Task-specific adapter paths from the hub
|
| 360 |
+
task_specific_adapter_paths = [f"TahaBa/phi3-mini-clustered-flan/ts_expert_{i}" for i in range(10)]
|
| 361 |
+
|
| 362 |
+
# Creating the Arrow model
|
| 363 |
+
model = create_arrow_model(
|
| 364 |
+
base_model=base_model,
|
| 365 |
+
task_specific_adapter_paths=task_specific_adapter_paths,
|
| 366 |
+
general_adapter_paths=general_adapter_paths,
|
| 367 |
+
arrow_config=arrow_config,
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
# Batch-wise inference
|
| 371 |
+
with torch.no_grad():
|
| 372 |
+
evaluate_on_multi_choice_batched(
|
| 373 |
+
test_dataset,
|
| 374 |
+
model,
|
| 375 |
+
tokenizer,
|
| 376 |
+
args.ds_name,
|
| 377 |
+
labels,
|
| 378 |
+
predictions,
|
| 379 |
+
args,
|
| 380 |
+
batch_size=32, # tune this
|
| 381 |
+
max_length=512, # tune if options are long
|
| 382 |
+
device="auto",
|
| 383 |
+
)
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/arrow_multitask/requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
torch
|
| 2 |
+
transformers
|
| 3 |
+
accelerate
|
| 4 |
+
datasets
|
| 5 |
+
scikit-learn
|
| 6 |
+
tqdm
|
| 7 |
+
numpy
|
| 8 |
+
bitsandbytes
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# BD-LoRA Finetuning
|
| 2 |
+
|
| 3 |
+
Block-Diagonal LoRA (BD-LoRA) is a LoRA variant in which some LoRA factors are constrained to be block-diagonal.
|
| 4 |
+
This allows faster serving by eliminating communication overheads when running inference on multiple GPU, at the same finetuning performance as vanilla LoRA.
|
| 5 |
+
|
| 6 |
+
To get an overview on how to use BD-LoRA, please view the Python notebook at `peft/examples/bdlora_finetuning/bdlora_peft_demo.ipynb`.
|
| 7 |
+
|
| 8 |
+
To benefit from inference speed-ups, you need an inference engine that is compatible with BD-LoRA. At the moment, there is an experimental PR at https://github.com/vllm-project/vllm/pull/28136 which allows you to use BD-LoRA in vLLM. If you find this work useful, consider leaving a comment there.
|
| 9 |
+
|
| 10 |
+
To install, you can clone the GitHub repository connected to the fork at https://github.com/Conzel/vllm/tree/bdlora-bk. Then, install vLLM following the usual instructions: https://docs.vllm.ai/en/stable/getting_started/installation/. We assume that you have a hardware setup with at least 2 available GPUs.
|
| 11 |
+
|
| 12 |
+
This example folder contains 3 scripts:
|
| 13 |
+
- `bdlora_peft_demo.ipynb` Showcases how to instantiate a BD-LoRA model, train it, and save/reload the weights.
|
| 14 |
+
- `vllm_server.bash` Spins up a BD-LoRA compatible vLLM server. To use it, you need to run the notebook once to create adapters with the correct format.
|
| 15 |
+
- `chat.py` Can be used to query the vLLM server after it has finished booting up. Usage example: `python3 chat.py --target lora1`.
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/bdlora-performance.png
ADDED
|
Git LFS Details
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/bdlora-sharding.png
ADDED
|
Git LFS Details
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"cells": [
|
| 3 |
+
{
|
| 4 |
+
"cell_type": "markdown",
|
| 5 |
+
"id": "e2b69494",
|
| 6 |
+
"metadata": {},
|
| 7 |
+
"source": [
|
| 8 |
+
"# Block-Diagonal LoRA for Eliminating Communication Overhead in Tensor Parallel LoRA Serving"
|
| 9 |
+
]
|
| 10 |
+
},
|
| 11 |
+
{
|
| 12 |
+
"cell_type": "markdown",
|
| 13 |
+
"id": "2fb2b221",
|
| 14 |
+
"metadata": {},
|
| 15 |
+
"source": [
|
| 16 |
+
"## Introduction\n",
|
| 17 |
+
"Block-Diagonal LoRA (BD-LoRA) is a LoRA variant in which some LoRA factors are constrained to be block-diagonal. This allows faster serving by eliminating communication overheads \n",
|
| 18 |
+
"when running inference on multiple GPUs. Despite the block-diagonal constraint, BD-LoRA is similarly performant to vanilla LoRA at similar parameter counts.\n",
|
| 19 |
+
"\n",
|
| 20 |
+
"BD-LoRA is designed to be used with tensor parallelism, which means sharding the weights of a model among multiple GPUs. A popular sharding strategy is the [Megatron Sharding Strategy](https://arxiv.org/abs/1909.08053). For two linear layers $W_1$, $W_2$ that follow each other (for example the up and down projections in a transformer MLP module), we will shard the first layer in a column-parallel way (which requires LoRA B to be block-diagonal) and the second layer in a row-parallel way (which requires LoRA A to be block-diagonal). For the attention module, this can be similarly achieved by taking the Q, K and V projections together as $W_1$ and the out projection as $W_2$, sharding accordingly. This sharding allows a compatible inference engine to distribute each block-diagonal shard over a a different GPU, cutting the need to communicate partial results among GPUs. In the image below, you can see the exact sharding strategy and how this saves computational efforts.\n",
|
| 21 |
+
"\n",
|
| 22 |
+
"Paper: https://arxiv.org/html/2510.23346v1\n",
|
| 23 |
+
"\n",
|
| 24 |
+
"<div>\n",
|
| 25 |
+
"<img src=\"bdlora-sharding.png\" width=\"800\"/>\n",
|
| 26 |
+
"</div>\n",
|
| 27 |
+
"\n",
|
| 28 |
+
"### Performance, rank and parameter count\n",
|
| 29 |
+
"BD-LoRA achieves similar performance to LoRA (see image below, or the `method_comparison` folder in the peft repository root) at the same parameter count. However, as every other factor in BD-LoRA is block-diagonal, a BD-LoRA adapter will have less parameters than a LoRA adapter at the same rank. The performance of BD-LoRA is only competitive when the rank is then increased accordingly. We provide example code for rank-matching at the end of this example notebook.\n",
|
| 30 |
+
"\n",
|
| 31 |
+
"<div>\n",
|
| 32 |
+
"<img src=\"bdlora-performance.png\" width=\"600\"/>\n",
|
| 33 |
+
"</div>\n"
|
| 34 |
+
]
|
| 35 |
+
},
|
| 36 |
+
{
|
| 37 |
+
"cell_type": "code",
|
| 38 |
+
"execution_count": 1,
|
| 39 |
+
"id": "40eea544",
|
| 40 |
+
"metadata": {},
|
| 41 |
+
"outputs": [
|
| 42 |
+
{
|
| 43 |
+
"name": "stderr",
|
| 44 |
+
"output_type": "stream",
|
| 45 |
+
"text": [
|
| 46 |
+
"/efs/aconzel/workspace/peft/bdlora-peft/lib/python3.11/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
|
| 47 |
+
" from .autonotebook import tqdm as notebook_tqdm\n"
|
| 48 |
+
]
|
| 49 |
+
}
|
| 50 |
+
],
|
| 51 |
+
"source": [
|
| 52 |
+
"from peft.tuners import BdLoraConfig, LoraConfig\n",
|
| 53 |
+
"from peft import get_peft_model\n",
|
| 54 |
+
"from transformers import Trainer, TrainingArguments, DataCollatorForLanguageModeling, AutoModelForCausalLM, AutoTokenizer\n",
|
| 55 |
+
"from datasets import load_dataset\n",
|
| 56 |
+
"import torch"
|
| 57 |
+
]
|
| 58 |
+
},
|
| 59 |
+
{
|
| 60 |
+
"cell_type": "markdown",
|
| 61 |
+
"id": "5959e4ab",
|
| 62 |
+
"metadata": {},
|
| 63 |
+
"source": [
|
| 64 |
+
"## Quick Start\n",
|
| 65 |
+
"To use BD-LoRA, we can follow standard LoRA-training procedures. We only need to change the `LoraConfig` to a `BdLoraConfig` and specify which LoRA should be block-diagonal. \n",
|
| 66 |
+
"As an example, we will train a LLama-Model in such a way that it can later benefit from inference speed-up as specified in the BD-LoRA paper. However, BD-LoRA can be used with all other models that follow a transformer architecture. \n",
|
| 67 |
+
"\n",
|
| 68 |
+
"As explained in the introduction, we want to shard each module (MLP and attention) in an alternating fashion, first column-parallel with LoRA-B block-diagonal, then row-parallel with LoRA-A block-diagonal. Different from standard MLP modules, Llama also uses a gate projection, which we can fuse together with the up-projection.\n",
|
| 69 |
+
"\n",
|
| 70 |
+
"Therefore, we want the following block-diagonal factors (following the naming convention from the Llama architecture):\n",
|
| 71 |
+
"\n",
|
| 72 |
+
"- LoRA-A Block-Diagonal (Row-parallel sharding): Out (`out_proj`), Down (`down_proj`)\n",
|
| 73 |
+
"- LoRA-B Block-Diagonal (Column-parallel sharding): QKV (`q_proj, k_proj, v_proj`), Up+Gate (`up_proj, gate_proj`)\n",
|
| 74 |
+
"\n",
|
| 75 |
+
"Additionally, we need to know on how many GPUs we want to serve before we start training, as this corresponds to the number of block we will use for each block-diagonal factor. For this experiment, we will use 2 blocks (equivalent to a tensor-parallelism degree of 2). Caveat: For a small model such as Llama 3.2-1B which we are using, one would use a single GPU for serving, and use TP=2 or TP=8 only for larger models, like Llama 3.1-8B or Llama 3.3-70B respectively. "
|
| 76 |
+
]
|
| 77 |
+
},
|
| 78 |
+
{
|
| 79 |
+
"cell_type": "code",
|
| 80 |
+
"execution_count": 2,
|
| 81 |
+
"id": "6180c1f9",
|
| 82 |
+
"metadata": {},
|
| 83 |
+
"outputs": [],
|
| 84 |
+
"source": [
|
| 85 |
+
"model_name = \"meta-llama/Llama-3.2-1B\"\n",
|
| 86 |
+
"model = AutoModelForCausalLM.from_pretrained(model_name)\n",
|
| 87 |
+
"tokenizer = AutoTokenizer.from_pretrained(model_name)"
|
| 88 |
+
]
|
| 89 |
+
},
|
| 90 |
+
{
|
| 91 |
+
"cell_type": "code",
|
| 92 |
+
"execution_count": 3,
|
| 93 |
+
"id": "6a50e350",
|
| 94 |
+
"metadata": {},
|
| 95 |
+
"outputs": [
|
| 96 |
+
{
|
| 97 |
+
"name": "stdout",
|
| 98 |
+
"output_type": "stream",
|
| 99 |
+
"text": [
|
| 100 |
+
"trainable params: 44,826,624 || all params: 1,280,641,024 || trainable%: 3.5003\n"
|
| 101 |
+
]
|
| 102 |
+
}
|
| 103 |
+
],
|
| 104 |
+
"source": [
|
| 105 |
+
"target_modules=[\"q_proj\", \"v_proj\", \"k_proj\", \"up_proj\", \"gate_proj\", \"o_proj\", \"down_proj\"]\n",
|
| 106 |
+
"# Set this equal to the number of GPUs you want to serve the model with later\n",
|
| 107 |
+
"nblocks = 2\n",
|
| 108 |
+
"\n",
|
| 109 |
+
"bdlora_config = BdLoraConfig(\n",
|
| 110 |
+
" target_modules_bd_a=[\"o_proj\", \"down_proj\"],\n",
|
| 111 |
+
" target_modules_bd_b=[\"q_proj\", \"v_proj\", \"k_proj\", \"up_proj\", \"gate_proj\"],\n",
|
| 112 |
+
" nblocks=nblocks\n",
|
| 113 |
+
")\n",
|
| 114 |
+
"\n",
|
| 115 |
+
"config = LoraConfig(\n",
|
| 116 |
+
" r=96,\n",
|
| 117 |
+
" # adjust target modules and the ...target_modules_bd attributes according to model architecture (for example renaming)\n",
|
| 118 |
+
" target_modules=target_modules,\n",
|
| 119 |
+
" use_bdlora=bdlora_config,\n",
|
| 120 |
+
" lora_bias=False\n",
|
| 121 |
+
")\n",
|
| 122 |
+
"\n",
|
| 123 |
+
"peft_model = get_peft_model(model, config)\n",
|
| 124 |
+
"peft_model.print_trainable_parameters()"
|
| 125 |
+
]
|
| 126 |
+
},
|
| 127 |
+
{
|
| 128 |
+
"cell_type": "markdown",
|
| 129 |
+
"id": "c1facfea",
|
| 130 |
+
"metadata": {},
|
| 131 |
+
"source": [
|
| 132 |
+
"## Training\n",
|
| 133 |
+
"We train the model for 10 steps, this training block is just intended to showcase how BD-LoRA integrates into other huggingface tools."
|
| 134 |
+
]
|
| 135 |
+
},
|
| 136 |
+
{
|
| 137 |
+
"cell_type": "code",
|
| 138 |
+
"execution_count": 4,
|
| 139 |
+
"id": "64e4681b",
|
| 140 |
+
"metadata": {},
|
| 141 |
+
"outputs": [
|
| 142 |
+
{
|
| 143 |
+
"data": {
|
| 144 |
+
"text/html": [
|
| 145 |
+
"\n",
|
| 146 |
+
" <div>\n",
|
| 147 |
+
" \n",
|
| 148 |
+
" <progress value='10' max='10' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
|
| 149 |
+
" [10/10 00:31, Epoch 10/10]\n",
|
| 150 |
+
" </div>\n",
|
| 151 |
+
" <table border=\"1\" class=\"dataframe\">\n",
|
| 152 |
+
" <thead>\n",
|
| 153 |
+
" <tr style=\"text-align: left;\">\n",
|
| 154 |
+
" <th>Step</th>\n",
|
| 155 |
+
" <th>Training Loss</th>\n",
|
| 156 |
+
" </tr>\n",
|
| 157 |
+
" </thead>\n",
|
| 158 |
+
" <tbody>\n",
|
| 159 |
+
" <tr>\n",
|
| 160 |
+
" <td>1</td>\n",
|
| 161 |
+
" <td>3.137500</td>\n",
|
| 162 |
+
" </tr>\n",
|
| 163 |
+
" <tr>\n",
|
| 164 |
+
" <td>2</td>\n",
|
| 165 |
+
" <td>3.137500</td>\n",
|
| 166 |
+
" </tr>\n",
|
| 167 |
+
" <tr>\n",
|
| 168 |
+
" <td>3</td>\n",
|
| 169 |
+
" <td>3.126700</td>\n",
|
| 170 |
+
" </tr>\n",
|
| 171 |
+
" <tr>\n",
|
| 172 |
+
" <td>4</td>\n",
|
| 173 |
+
" <td>3.104900</td>\n",
|
| 174 |
+
" </tr>\n",
|
| 175 |
+
" <tr>\n",
|
| 176 |
+
" <td>5</td>\n",
|
| 177 |
+
" <td>3.085900</td>\n",
|
| 178 |
+
" </tr>\n",
|
| 179 |
+
" <tr>\n",
|
| 180 |
+
" <td>6</td>\n",
|
| 181 |
+
" <td>3.069800</td>\n",
|
| 182 |
+
" </tr>\n",
|
| 183 |
+
" <tr>\n",
|
| 184 |
+
" <td>7</td>\n",
|
| 185 |
+
" <td>3.056500</td>\n",
|
| 186 |
+
" </tr>\n",
|
| 187 |
+
" <tr>\n",
|
| 188 |
+
" <td>8</td>\n",
|
| 189 |
+
" <td>3.046100</td>\n",
|
| 190 |
+
" </tr>\n",
|
| 191 |
+
" <tr>\n",
|
| 192 |
+
" <td>9</td>\n",
|
| 193 |
+
" <td>3.038300</td>\n",
|
| 194 |
+
" </tr>\n",
|
| 195 |
+
" <tr>\n",
|
| 196 |
+
" <td>10</td>\n",
|
| 197 |
+
" <td>3.033100</td>\n",
|
| 198 |
+
" </tr>\n",
|
| 199 |
+
" </tbody>\n",
|
| 200 |
+
"</table><p>"
|
| 201 |
+
],
|
| 202 |
+
"text/plain": [
|
| 203 |
+
"<IPython.core.display.HTML object>"
|
| 204 |
+
]
|
| 205 |
+
},
|
| 206 |
+
"metadata": {},
|
| 207 |
+
"output_type": "display_data"
|
| 208 |
+
},
|
| 209 |
+
{
|
| 210 |
+
"data": {
|
| 211 |
+
"text/plain": [
|
| 212 |
+
"TrainOutput(global_step=10, training_loss=3.0836387634277345, metrics={'train_runtime': 38.346, 'train_samples_per_second': 66.761, 'train_steps_per_second': 0.261, 'total_flos': 1954507653120000.0, 'train_loss': 3.0836387634277345, 'epoch': 10.0})"
|
| 213 |
+
]
|
| 214 |
+
},
|
| 215 |
+
"execution_count": 4,
|
| 216 |
+
"metadata": {},
|
| 217 |
+
"output_type": "execute_result"
|
| 218 |
+
}
|
| 219 |
+
],
|
| 220 |
+
"source": [
|
| 221 |
+
"dataset = load_dataset(\"imdb\", split=\"train[:1%]\")\n",
|
| 222 |
+
"\n",
|
| 223 |
+
"tokenizer.pad_token = tokenizer.eos_token\n",
|
| 224 |
+
"def tokenize(batch):\n",
|
| 225 |
+
" return tokenizer(batch[\"text\"], truncation=True, padding=\"max_length\", max_length=128)\n",
|
| 226 |
+
"\n",
|
| 227 |
+
"dataset = dataset.map(tokenize, batched=True, remove_columns=[\"text\"])\n",
|
| 228 |
+
"training_args = TrainingArguments(\n",
|
| 229 |
+
" output_dir=\"./results\",\n",
|
| 230 |
+
" per_device_train_batch_size=8,\n",
|
| 231 |
+
" gradient_accumulation_steps=4,\n",
|
| 232 |
+
" warmup_steps=2,\n",
|
| 233 |
+
" max_steps=10,\n",
|
| 234 |
+
" learning_rate=2e-4,\n",
|
| 235 |
+
" logging_steps=1,\n",
|
| 236 |
+
")\n",
|
| 237 |
+
"\n",
|
| 238 |
+
"trainer = Trainer(\n",
|
| 239 |
+
" model=peft_model,\n",
|
| 240 |
+
" args=training_args,\n",
|
| 241 |
+
" train_dataset=dataset,\n",
|
| 242 |
+
" data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),\n",
|
| 243 |
+
")\n",
|
| 244 |
+
"\n",
|
| 245 |
+
"peft_model.config.use_cache = False\n",
|
| 246 |
+
"trainer.train()"
|
| 247 |
+
]
|
| 248 |
+
},
|
| 249 |
+
{
|
| 250 |
+
"cell_type": "markdown",
|
| 251 |
+
"id": "3ac31a38",
|
| 252 |
+
"metadata": {},
|
| 253 |
+
"source": [
|
| 254 |
+
"## Saving Model"
|
| 255 |
+
]
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"cell_type": "code",
|
| 259 |
+
"execution_count": 5,
|
| 260 |
+
"id": "28f49ee4",
|
| 261 |
+
"metadata": {},
|
| 262 |
+
"outputs": [],
|
| 263 |
+
"source": [
|
| 264 |
+
"peft_model.save_pretrained(\"example_bd_lora_adapter\")"
|
| 265 |
+
]
|
| 266 |
+
},
|
| 267 |
+
{
|
| 268 |
+
"cell_type": "markdown",
|
| 269 |
+
"id": "1a3d6fab",
|
| 270 |
+
"metadata": {},
|
| 271 |
+
"source": [
|
| 272 |
+
"## Example Output"
|
| 273 |
+
]
|
| 274 |
+
},
|
| 275 |
+
{
|
| 276 |
+
"cell_type": "code",
|
| 277 |
+
"execution_count": 6,
|
| 278 |
+
"id": "20c36df8",
|
| 279 |
+
"metadata": {},
|
| 280 |
+
"outputs": [
|
| 281 |
+
{
|
| 282 |
+
"name": "stderr",
|
| 283 |
+
"output_type": "stream",
|
| 284 |
+
"text": [
|
| 285 |
+
"Setting `pad_token_id` to `eos_token_id`:128001 for open-end generation.\n"
|
| 286 |
+
]
|
| 287 |
+
},
|
| 288 |
+
{
|
| 289 |
+
"name": "stdout",
|
| 290 |
+
"output_type": "stream",
|
| 291 |
+
"text": [
|
| 292 |
+
"The Batman Trilogy by Christopher Nolan\n",
|
| 293 |
+
"The Batman Trilogy by Christopher Nolan\n",
|
| 294 |
+
"The Batman Trilogy by Christopher Nolan\n",
|
| 295 |
+
"The Batman Trilogy by Christopher Nolan\n",
|
| 296 |
+
"The Batman Trilogy by Christopher Nolan\n",
|
| 297 |
+
"The Batman Trilogy by Christopher Nolan\n",
|
| 298 |
+
"The Batman Trilogy by Christopher Nolan\n",
|
| 299 |
+
"\n"
|
| 300 |
+
]
|
| 301 |
+
}
|
| 302 |
+
],
|
| 303 |
+
"source": [
|
| 304 |
+
"text = \"The Batman Trilogy by Christopher Nolan\"\n",
|
| 305 |
+
"inputs = tokenizer(text, return_tensors=\"pt\").to(model.device) \n",
|
| 306 |
+
"\n",
|
| 307 |
+
"outputs = peft_model.generate(**inputs, max_length=50)\n",
|
| 308 |
+
"decoded = tokenizer.decode(outputs[0], skip_special_tokens=True)\n",
|
| 309 |
+
"print(decoded)"
|
| 310 |
+
]
|
| 311 |
+
},
|
| 312 |
+
{
|
| 313 |
+
"cell_type": "markdown",
|
| 314 |
+
"id": "711eb30d",
|
| 315 |
+
"metadata": {},
|
| 316 |
+
"source": [
|
| 317 |
+
"## Investigating the shapes of LoRA Adapters\n",
|
| 318 |
+
"We can check out the adapter shapes to see if they follow the sharding patterns that we have discussed. To make the implementation more memory efficient, \n",
|
| 319 |
+
"the block-diagonal matrices are not saved in a block-diagonal manner, but the blocks are stacked along the non-rank dimensions. \n",
|
| 320 |
+
"\n",
|
| 321 |
+
"For example, if a layer is column sharded, such as the q-proj in Llama, then the LoRA-B factor is block-diagonal. Assume that the q-proj has layer weights (out_features, in_features), \n",
|
| 322 |
+
"then LoRA-A will have shape (rank, in_features), and LoRA-B will have shape (out_features, rank / TP), which corresponds to TP blocks of shape (out_features/TP, rank/TP) each. This can be checked by investigating the weight shapes:"
|
| 323 |
+
]
|
| 324 |
+
},
|
| 325 |
+
{
|
| 326 |
+
"cell_type": "code",
|
| 327 |
+
"execution_count": 7,
|
| 328 |
+
"id": "3660c4de",
|
| 329 |
+
"metadata": {},
|
| 330 |
+
"outputs": [
|
| 331 |
+
{
|
| 332 |
+
"name": "stdout",
|
| 333 |
+
"output_type": "stream",
|
| 334 |
+
"text": [
|
| 335 |
+
"Base layer has shape: [512, 2048]\n",
|
| 336 |
+
"LoRA-A (vanilla): [96, 2048]\n",
|
| 337 |
+
"LoRA-B (block-diagonal): [512, 48 ]\n"
|
| 338 |
+
]
|
| 339 |
+
}
|
| 340 |
+
],
|
| 341 |
+
"source": [
|
| 342 |
+
"shape_base = list(peft_model.state_dict()['base_model.model.model.layers.0.self_attn.v_proj.base_layer.weight'].shape)\n",
|
| 343 |
+
"shape_a = list(peft_model.state_dict()['base_model.model.model.layers.0.self_attn.v_proj.lora_A.default.weight'].shape)\n",
|
| 344 |
+
"shape_b = list(peft_model.state_dict()['base_model.model.model.layers.0.self_attn.v_proj.lora_B.default.weight'].shape)\n",
|
| 345 |
+
"print(f\"Base layer has shape: [{shape_base[0]}, {shape_base[1]}]\\nLoRA-A (vanilla): [{shape_a[0]}, {shape_a[1]}]\\nLoRA-B (block-diagonal): [{shape_b[0]}, {shape_b[1]} ]\")"
|
| 346 |
+
]
|
| 347 |
+
},
|
| 348 |
+
{
|
| 349 |
+
"cell_type": "markdown",
|
| 350 |
+
"id": "d95118af",
|
| 351 |
+
"metadata": {},
|
| 352 |
+
"source": [
|
| 353 |
+
"## Matching the rank\n",
|
| 354 |
+
"Assuming we want to achieve the same performance of a LoRA adapter of a given rank, at which rank would we have to train BD-LoRA? We can find this out by matching the number of trainable parameters. A simple iteration over the ranks of the BD-LoRA adapter is sufficient to do that:"
|
| 355 |
+
]
|
| 356 |
+
},
|
| 357 |
+
{
|
| 358 |
+
"cell_type": "code",
|
| 359 |
+
"execution_count": 8,
|
| 360 |
+
"id": "cd4fc45a",
|
| 361 |
+
"metadata": {},
|
| 362 |
+
"outputs": [
|
| 363 |
+
{
|
| 364 |
+
"name": "stdout",
|
| 365 |
+
"output_type": "stream",
|
| 366 |
+
"text": [
|
| 367 |
+
"BD-LoRA rank to match vanilla LoRA performance at rank 64: 96 at 45088768 vanilla LoRA params and 44826624 BD-LoRA params.\n"
|
| 368 |
+
]
|
| 369 |
+
}
|
| 370 |
+
],
|
| 371 |
+
"source": [
|
| 372 |
+
"def rank_to_params(r: int, bd_lora: bool, nblocks: int):\n",
|
| 373 |
+
" model = AutoModelForCausalLM.from_pretrained(model_name)\n",
|
| 374 |
+
" if bd_lora:\n",
|
| 375 |
+
" config = LoraConfig(\n",
|
| 376 |
+
" r=r,\n",
|
| 377 |
+
" target_modules=target_modules,\n",
|
| 378 |
+
" use_bdlora=bdlora_config,\n",
|
| 379 |
+
" lora_bias=False\n",
|
| 380 |
+
" )\n",
|
| 381 |
+
" else:\n",
|
| 382 |
+
" config = LoraConfig(\n",
|
| 383 |
+
" r=r,\n",
|
| 384 |
+
" # If you use a model different from Llama, change the settings below\n",
|
| 385 |
+
" target_modules=target_modules,\n",
|
| 386 |
+
" lora_bias=False\n",
|
| 387 |
+
" )\n",
|
| 388 |
+
"\n",
|
| 389 |
+
"\n",
|
| 390 |
+
" peft_model = get_peft_model(model, config)\n",
|
| 391 |
+
" return peft_model.get_nb_trainable_parameters()[0]\n",
|
| 392 |
+
"\n",
|
| 393 |
+
"r_orig = 64\n",
|
| 394 |
+
"r = r_orig\n",
|
| 395 |
+
"lora_nparams = rank_to_params(r, False, nblocks)\n",
|
| 396 |
+
"bdlora_nparams = 0\n",
|
| 397 |
+
"while bdlora_nparams < lora_nparams:\n",
|
| 398 |
+
" r += nblocks\n",
|
| 399 |
+
" bdlora_nparams = rank_to_params(r, True, nblocks)\n",
|
| 400 |
+
"# subtract nblocks again to be just under the parameter count of vanilla LoRA, following the original papers methodology\n",
|
| 401 |
+
"print(f\"BD-LoRA rank to match vanilla LoRA performance at rank {r_orig}: {r-nblocks} at {lora_nparams} vanilla LoRA params and {rank_to_params(r-nblocks, True, nblocks)} BD-LoRA params.\")"
|
| 402 |
+
]
|
| 403 |
+
},
|
| 404 |
+
{
|
| 405 |
+
"cell_type": "markdown",
|
| 406 |
+
"id": "d27b9545",
|
| 407 |
+
"metadata": {},
|
| 408 |
+
"source": [
|
| 409 |
+
"# Integration with vLLM\n",
|
| 410 |
+
"Currently, vLLM has an experimental PR that allows you to use it with BD-LoRA. Clone the github repository and check out the commit of \n",
|
| 411 |
+
"the pull request at https://github.com/vllm-project/vllm/pull/28136#. Then, install vLLM following the usual instructions: https://docs.vllm.ai/en/stable/getting_started/installation/. We assume that you have a hardware setup with at least 2 available GPUs. \n",
|
| 412 |
+
"\n",
|
| 413 |
+
"We have included a script that starts a vLLM server with two BD-LoRA modules at `vllm_server.bash` (you might have to kill this jupyter server beforehand, as it is likely already using your GPU resources).\n",
|
| 414 |
+
"Once the server has started, you can query it via `python3 chat.py \"Please write your message here.\" --target lora1`."
|
| 415 |
+
]
|
| 416 |
+
}
|
| 417 |
+
],
|
| 418 |
+
"metadata": {
|
| 419 |
+
"kernelspec": {
|
| 420 |
+
"display_name": "bdlora-peft",
|
| 421 |
+
"language": "python",
|
| 422 |
+
"name": "python3"
|
| 423 |
+
},
|
| 424 |
+
"language_info": {
|
| 425 |
+
"codemirror_mode": {
|
| 426 |
+
"name": "ipython",
|
| 427 |
+
"version": 3
|
| 428 |
+
},
|
| 429 |
+
"file_extension": ".py",
|
| 430 |
+
"mimetype": "text/x-python",
|
| 431 |
+
"name": "python",
|
| 432 |
+
"nbconvert_exporter": "python",
|
| 433 |
+
"pygments_lexer": "ipython3",
|
| 434 |
+
"version": "3.11.13"
|
| 435 |
+
}
|
| 436 |
+
},
|
| 437 |
+
"nbformat": 4,
|
| 438 |
+
"nbformat_minor": 5
|
| 439 |
+
}
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/chat.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
import asyncio
|
| 15 |
+
import json
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
import aiohttp
|
| 19 |
+
import typer
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def chat(
|
| 23 |
+
msg: str,
|
| 24 |
+
target: str = "lora1",
|
| 25 |
+
max_tokens: int = 100,
|
| 26 |
+
deterministic: bool = True,
|
| 27 |
+
record: str = "",
|
| 28 |
+
num_requests: int = 32,
|
| 29 |
+
):
|
| 30 |
+
payload = {
|
| 31 |
+
"model": target,
|
| 32 |
+
"prompt": msg,
|
| 33 |
+
"max_tokens": max_tokens,
|
| 34 |
+
}
|
| 35 |
+
if deterministic:
|
| 36 |
+
payload = payload | {"temperature": 0, "top_p": 1, "top_k": 1}
|
| 37 |
+
|
| 38 |
+
url = "http://localhost:8000/v1/completions"
|
| 39 |
+
|
| 40 |
+
async def _request(session):
|
| 41 |
+
async with session.post(url, json=payload) as response:
|
| 42 |
+
response_json = await response.json()
|
| 43 |
+
return response_json["choices"][0]["text"]
|
| 44 |
+
|
| 45 |
+
async def run_concurrent():
|
| 46 |
+
async with aiohttp.ClientSession() as session:
|
| 47 |
+
tasks = [_request(session) for _ in range(num_requests)]
|
| 48 |
+
return await asyncio.gather(*tasks)
|
| 49 |
+
|
| 50 |
+
start_time = time.time()
|
| 51 |
+
response_texts = asyncio.run(run_concurrent())
|
| 52 |
+
end_time = time.time()
|
| 53 |
+
|
| 54 |
+
print(f"Completed {num_requests} requests in {end_time - start_time:.2f} seconds")
|
| 55 |
+
|
| 56 |
+
if record:
|
| 57 |
+
with open(record, "w") as f:
|
| 58 |
+
json.dump({"prompt": msg, "responses": response_texts}, f, indent=2)
|
| 59 |
+
else:
|
| 60 |
+
print(response_texts[0])
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
typer.run(chat)
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/bdlora_finetuning/vllm_server.bash
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/bash
|
| 2 |
+
|
| 3 |
+
ADAPTER_PATH="example_bd_lora_adapter"
|
| 4 |
+
|
| 5 |
+
python -m vllm.entrypoints.openai.api_server \
|
| 6 |
+
--model meta-llama/Llama-3.2-1B \
|
| 7 |
+
--enable-lora \
|
| 8 |
+
--lora-modules lora1=$ADAPTER_PATH lora2=$ADAPTER_PATH \
|
| 9 |
+
--tensor-parallel-size 2 \
|
| 10 |
+
--block_diagonal_sharded_loras \
|
| 11 |
+
--max-lora-rank 128 \
|
| 12 |
+
--enforce-eager \
|
| 13 |
+
--port 8000
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/boft_controlnet.md
ADDED
|
@@ -0,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!--Copyright 2023 The HuggingFace Team. All rights reserved.
|
| 2 |
+
|
| 3 |
+
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
|
| 4 |
+
the License. You may obtain a copy of the License at
|
| 5 |
+
|
| 6 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 7 |
+
|
| 8 |
+
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
|
| 9 |
+
an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
|
| 10 |
+
specific language governing permissions and limitations under the License.
|
| 11 |
+
|
| 12 |
+
⚠️ Note that this file is in Markdown but contain specific syntax for our doc-builder (similar to MDX) that may not be
|
| 13 |
+
rendered properly in your Markdown viewer.
|
| 14 |
+
|
| 15 |
+
-->
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
# Fine-tuning for controllable generation with BOFT (ControlNet)
|
| 19 |
+
|
| 20 |
+
This guide demonstrates how to use BOFT, an orthogonal fine-tuning method, to fine-tune Stable Diffusion with either `stabilityai/stable-diffusion-2-1` or `runwayml/stable-diffusion-v1-5` model for controllable generation.
|
| 21 |
+
|
| 22 |
+
By using BOFT from 🤗 PEFT, we can significantly reduce the number of trainable parameters while still achieving impressive results in various fine-tuning tasks across different foundation models. BOFT enhances model efficiency by integrating full-rank orthogonal matrices with a butterfly structure into specific model blocks, such as attention blocks, mirroring the approach used in LoRA. During fine-tuning, only these inserted matrices are trained, leaving the original model parameters untouched. During inference, the trainable BOFT parameters can be merged into the original model, eliminating any additional computational costs.
|
| 23 |
+
|
| 24 |
+
As a member of the **orthogonal finetuning** class, BOFT presents a systematic and principled method for fine-tuning. It possesses several unique properties and has demonstrated superior performance compared to LoRA in a variety of scenarios. For further details on BOFT, please consult the [PEFT's GitHub repo's concept guide OFT](https://https://huggingface.co/docs/peft/index), the [original BOFT paper](https://huggingface.co/papers/2311.06243) and the [original OFT paper](https://huggingface.co/papers/2306.07280).
|
| 25 |
+
|
| 26 |
+
In this guide we provide a controllable generation (ControlNet) fine-tuning script that is available in [PEFT's GitHub repo examples](https://github.com/huggingface/peft/tree/main/examples/boft_controlnet). This implementation is adapted from [diffusers's ControlNet](https://github.com/huggingface/diffusers/tree/main/examples/controlnet) and [Hecong Wu's ControlLoRA](https://github.com/HighCWu/ControlLoRA). You can try it out and finetune on your custom images.
|
| 27 |
+
|
| 28 |
+
## Set up your environment
|
| 29 |
+
Start by cloning the PEFT repository:
|
| 30 |
+
|
| 31 |
+
```bash
|
| 32 |
+
git clone https://github.com/huggingface/peft
|
| 33 |
+
```
|
| 34 |
+
|
| 35 |
+
Navigate to the directory containing the training scripts for fine-tuning Dreambooth with BOFT:
|
| 36 |
+
```bash
|
| 37 |
+
cd peft/examples/boft_controlnet
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Set up your environment: install PEFT, and all the required libraries. At the time of writing this guide we recommend installing PEFT from source.
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
conda create --name peft python=3.10
|
| 44 |
+
conda activate peft
|
| 45 |
+
conda install pytorch==2.1.2 torchvision==0.16.2 torchaudio==2.1.2 pytorch-cuda=11.8 -c pytorch -c nvidia
|
| 46 |
+
conda install xformers -c xformers
|
| 47 |
+
pip install -r requirements.txt
|
| 48 |
+
pip install git+https://github.com/huggingface/peft
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
## Data
|
| 52 |
+
|
| 53 |
+
We use the [control-celeba-hq](https://huggingface.co/datasets/oftverse/control-celeba-hq) dataset for landmark-to-face controllable generation. We also provide evaluation scripts to evaluate the controllable generation performance. This task can be used to quantitatively compare different fine-tuning techniques.
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
export DATASET_NAME="oftverse/control-celeba-hq"
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
## Train controllable generation (ControlNet) with BOFT
|
| 60 |
+
|
| 61 |
+
Start with setting some hyperparameters for BOFT:
|
| 62 |
+
```bash
|
| 63 |
+
PEFT_TYPE="boft"
|
| 64 |
+
BLOCK_NUM=8
|
| 65 |
+
BLOCK_SIZE=0
|
| 66 |
+
N_BUTTERFLY_FACTOR=0
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
Here:
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
Navigate to the directory containing the training scripts for fine-tuning Stable Diffusion with BOFT for controllable generation:
|
| 73 |
+
|
| 74 |
+
```bash
|
| 75 |
+
./train_controlnet.sh
|
| 76 |
+
```
|
| 77 |
+
or
|
| 78 |
+
```bash
|
| 79 |
+
export MODEL_NAME="stabilityai/stable-diffusion-2-1"
|
| 80 |
+
# export MODEL_NAME="runwayml/stable-diffusion-v1-5"
|
| 81 |
+
|
| 82 |
+
export DATASET_NAME="oftverse/control-celeba-hq"
|
| 83 |
+
export PROJECT_NAME="controlnet_${PEFT_TYPE}"
|
| 84 |
+
export RUN_NAME="${PEFT_TYPE}_${BLOCK_NUM}${BLOCK_SIZE}${N_BUTTERFLY_FACTOR}"
|
| 85 |
+
export CONTROLNET_PATH=""
|
| 86 |
+
export OUTPUT_DIR="./output/${DATASET_NAME}/${RUN_NAME}"
|
| 87 |
+
|
| 88 |
+
accelerate launch train_controlnet.py \
|
| 89 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 90 |
+
--resume_from_checkpoint=$RESUME_PATH \
|
| 91 |
+
--controlnet_model_name_or_path=$CONTROLNET_PATH \
|
| 92 |
+
--output_dir=$OUTPUT_DIR \
|
| 93 |
+
--report_to="wandb" \
|
| 94 |
+
--dataset_name=$DATASET_NAME \
|
| 95 |
+
--resolution=512 \
|
| 96 |
+
--learning_rate=1e-5 \
|
| 97 |
+
--checkpointing_steps=5000 \
|
| 98 |
+
--max_train_steps=50000 \
|
| 99 |
+
--validation_steps=2000 \
|
| 100 |
+
--num_validation_images=12 \
|
| 101 |
+
--train_batch_size=4 \
|
| 102 |
+
--dataloader_num_workers=2 \
|
| 103 |
+
--seed="0" \
|
| 104 |
+
--lr_scheduler="constant" \
|
| 105 |
+
--lr_warmup_steps=0 \
|
| 106 |
+
--wandb_project_name=$PROJECT_NAME \
|
| 107 |
+
--wandb_run_name=$RUN_NAME \
|
| 108 |
+
--enable_xformers_memory_efficient_attention \
|
| 109 |
+
--use_boft \
|
| 110 |
+
--boft_block_num=$BLOCK_NUM \
|
| 111 |
+
--boft_block_size=$BLOCK_SIZE \
|
| 112 |
+
--boft_n_butterfly_factor=$N_BUTTERFLY_FACTOR \
|
| 113 |
+
--boft_dropout=0.1 \
|
| 114 |
+
--boft_bias="boft_only" \
|
| 115 |
+
--report_to="wandb" \
|
| 116 |
+
```
|
| 117 |
+
|
| 118 |
+
Run inference on the saved model to sample new images from the validation set:
|
| 119 |
+
|
| 120 |
+
```bash
|
| 121 |
+
./test_controlnet.sh
|
| 122 |
+
```
|
| 123 |
+
or
|
| 124 |
+
```bash
|
| 125 |
+
ITER_NUM=50000
|
| 126 |
+
|
| 127 |
+
export MODEL_NAME="stabilityai/stable-diffusion-2-1"
|
| 128 |
+
# export MODEL_NAME="runwayml/stable-diffusion-v1-5"
|
| 129 |
+
|
| 130 |
+
export RUN_NAME="${PEFT_TYPE}_${BLOCK_NUM}${BLOCK_SIZE}${N_BUTTERFLY_FACTOR}"
|
| 131 |
+
export DATASET_NAME="oftverse/control-celeba-hq"
|
| 132 |
+
export CKPT_NAME="checkpoint-${ITER_NUM}"
|
| 133 |
+
export OUTPUT_DIR="./output/${DATASET_NAME}/${RUN_NAME}/${CKPT_NAME}"
|
| 134 |
+
export CONTROLNET_PATH="${OUTPUT_DIR}/controlnet/model.safetensors"
|
| 135 |
+
export UNET_PATH="${OUTPUT_DIR}/unet/${RUN_NAME}"
|
| 136 |
+
export RESULTS_PATH="${OUTPUT_DIR}/results"
|
| 137 |
+
|
| 138 |
+
accelerate launch test_controlnet.py \
|
| 139 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 140 |
+
--dataset_name=$DATASET_NAME \
|
| 141 |
+
--controlnet_path=$CONTROLNET_PATH \
|
| 142 |
+
--unet_path=$UNET_PATH \
|
| 143 |
+
--adapter_name=$RUN_NAME \
|
| 144 |
+
--output_dir=$RESULTS_PATH \
|
| 145 |
+
--dataset_name=$DATASET_NAME \
|
| 146 |
+
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
Run evaluation on the sampled images to evaluate the landmark reprojection error:
|
| 150 |
+
|
| 151 |
+
```bash
|
| 152 |
+
./eval.sh
|
| 153 |
+
```
|
| 154 |
+
or
|
| 155 |
+
```bash
|
| 156 |
+
ITER_NUM=50000
|
| 157 |
+
|
| 158 |
+
export MODEL_NAME="stabilityai/stable-diffusion-2-1"
|
| 159 |
+
# export MODEL_NAME="runwayml/stable-diffusion-v1-5"
|
| 160 |
+
|
| 161 |
+
export RUN_NAME="${PEFT_TYPE}_${BLOCK_NUM}${BLOCK_SIZE}${N_BUTTERFLY_FACTOR}"
|
| 162 |
+
export DATASET_NAME="oftverse/control-celeba-hq"
|
| 163 |
+
export CKPT_NAME="checkpoint-${ITER_NUM}"
|
| 164 |
+
export OUTPUT_DIR="./output/${DATASET_NAME}/${RUN_NAME}/${CKPT_NAME}"
|
| 165 |
+
export CONTROLNET_PATH="${OUTPUT_DIR}/controlnet/model.safetensors"
|
| 166 |
+
export UNET_PATH="${OUTPUT_DIR}/unet/${RUN_NAME}"
|
| 167 |
+
|
| 168 |
+
accelerate launch eval.py \
|
| 169 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 170 |
+
--dataset_name=$DATASET_NAME \
|
| 171 |
+
--controlnet_path=$CONTROLNET_PATH \
|
| 172 |
+
--unet_path=$UNET_PATH \
|
| 173 |
+
--adapter_name=$RUN_NAME \
|
| 174 |
+
--output_dir=$OUTPUT_DIR \
|
| 175 |
+
--dataset_name=$DATASET_NAME \
|
| 176 |
+
--vis_overlays \
|
| 177 |
+
```
|
tasks/tasksm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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# The implementation is based on "Parameter-Efficient Orthogonal Finetuning
|
| 16 |
+
# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024.
|
| 17 |
+
|
| 18 |
+
import glob
|
| 19 |
+
import os
|
| 20 |
+
from pathlib import Path
|
| 21 |
+
|
| 22 |
+
import cv2
|
| 23 |
+
import face_alignment
|
| 24 |
+
import numpy as np
|
| 25 |
+
import torch
|
| 26 |
+
from accelerate import Accelerator
|
| 27 |
+
from skimage.io import imread
|
| 28 |
+
from torchvision.utils import save_image
|
| 29 |
+
from tqdm import tqdm
|
| 30 |
+
from transformers import AutoTokenizer
|
| 31 |
+
from utils.args_loader import parse_args
|
| 32 |
+
from utils.dataset import make_dataset
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
# Determine the best available device
|
| 36 |
+
if torch.cuda.is_available():
|
| 37 |
+
device = "cuda:0"
|
| 38 |
+
else:
|
| 39 |
+
# TODO: xpu support in facealignment will be ready after this PR is merged:https://github.com/1adrianb/face-alignment/pull/371
|
| 40 |
+
device = "cpu"
|
| 41 |
+
|
| 42 |
+
detect_model = face_alignment.FaceAlignment(face_alignment.LandmarksType.TWO_D, device=device, flip_input=False)
|
| 43 |
+
# with open('./data/celebhq-text/prompt_val_blip_full.json', 'rt') as f: # fill50k, COCO
|
| 44 |
+
# for line in f:
|
| 45 |
+
# val_data = json.loads(line)
|
| 46 |
+
|
| 47 |
+
end_list = np.array([17, 22, 27, 42, 48, 31, 36, 68], dtype=np.int32) - 1
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def count_txt_files(directory):
|
| 51 |
+
pattern = os.path.join(directory, "*.txt")
|
| 52 |
+
txt_files = glob.glob(pattern)
|
| 53 |
+
return len(txt_files)
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def plot_kpts(image, kpts, color="g"):
|
| 57 |
+
"""Draw 68 key points
|
| 58 |
+
Args:
|
| 59 |
+
image: the input image
|
| 60 |
+
kpt: (68, 3).
|
| 61 |
+
"""
|
| 62 |
+
if color == "r":
|
| 63 |
+
c = (255, 0, 0)
|
| 64 |
+
elif color == "g":
|
| 65 |
+
c = (0, 255, 0)
|
| 66 |
+
elif color == "b":
|
| 67 |
+
c = (255, 0, 0)
|
| 68 |
+
image = image.copy()
|
| 69 |
+
kpts = kpts.copy()
|
| 70 |
+
radius = max(int(min(image.shape[0], image.shape[1]) / 200), 1)
|
| 71 |
+
for i in range(kpts.shape[0]):
|
| 72 |
+
st = kpts[i, :2]
|
| 73 |
+
if kpts.shape[1] == 4:
|
| 74 |
+
if kpts[i, 3] > 0.5:
|
| 75 |
+
c = (0, 255, 0)
|
| 76 |
+
else:
|
| 77 |
+
c = (0, 0, 255)
|
| 78 |
+
image = cv2.circle(image, (int(st[0]), int(st[1])), radius, c, radius * 2)
|
| 79 |
+
if i in end_list:
|
| 80 |
+
continue
|
| 81 |
+
ed = kpts[i + 1, :2]
|
| 82 |
+
image = cv2.line(image, (int(st[0]), int(st[1])), (int(ed[0]), int(ed[1])), (255, 255, 255), radius)
|
| 83 |
+
return image
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def generate_landmark2d(dataset, input_dir, pred_lmk_dir, gt_lmk_dir, vis=False):
|
| 87 |
+
print("Generate 2d landmarks ...")
|
| 88 |
+
os.makedirs(pred_lmk_dir, exist_ok=True)
|
| 89 |
+
|
| 90 |
+
imagepath_list = sorted(glob.glob(f"{input_dir}/pred*.png"))
|
| 91 |
+
|
| 92 |
+
for imagepath in tqdm(imagepath_list):
|
| 93 |
+
name = Path(imagepath).stem
|
| 94 |
+
idx = int(name.split("_")[-1])
|
| 95 |
+
pred_txt_path = os.path.join(pred_lmk_dir, f"{idx}.txt")
|
| 96 |
+
gt_lmk_path = os.path.join(gt_lmk_dir, f"{idx}_gt_lmk.jpg")
|
| 97 |
+
gt_txt_path = os.path.join(gt_lmk_dir, f"{idx}.txt")
|
| 98 |
+
gt_img_path = os.path.join(gt_lmk_dir, f"{idx}_gt_img.jpg")
|
| 99 |
+
|
| 100 |
+
if (not os.path.exists(pred_txt_path)) or (not os.path.exists(gt_txt_path)):
|
| 101 |
+
image = imread(imagepath) # [:, :, :3]
|
| 102 |
+
out = detect_model.get_landmarks(image)
|
| 103 |
+
if out is None:
|
| 104 |
+
continue
|
| 105 |
+
|
| 106 |
+
pred_kpt = out[0].squeeze()
|
| 107 |
+
np.savetxt(pred_txt_path, pred_kpt)
|
| 108 |
+
|
| 109 |
+
# Your existing code for obtaining the image tensor
|
| 110 |
+
gt_lmk_img = dataset[idx]["conditioning_pixel_values"]
|
| 111 |
+
save_image(gt_lmk_img, gt_lmk_path)
|
| 112 |
+
|
| 113 |
+
gt_img = (dataset[idx]["pixel_values"]) * 0.5 + 0.5
|
| 114 |
+
save_image(gt_img, gt_img_path)
|
| 115 |
+
|
| 116 |
+
gt_img = (gt_img.permute(1, 2, 0) * 255).type(torch.uint8).cpu().numpy()
|
| 117 |
+
out = detect_model.get_landmarks(gt_img)
|
| 118 |
+
if out is None:
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
gt_kpt = out[0].squeeze()
|
| 122 |
+
np.savetxt(gt_txt_path, gt_kpt)
|
| 123 |
+
# gt_image = cv2.resize(cv2.imread(gt_lmk_path), (512, 512))
|
| 124 |
+
|
| 125 |
+
if vis:
|
| 126 |
+
gt_lmk_image = cv2.imread(gt_lmk_path)
|
| 127 |
+
|
| 128 |
+
# visualize predicted landmarks
|
| 129 |
+
vis_path = os.path.join(pred_lmk_dir, f"{idx}_overlay.jpg")
|
| 130 |
+
image = cv2.imread(imagepath)
|
| 131 |
+
image_point = plot_kpts(image, pred_kpt)
|
| 132 |
+
cv2.imwrite(vis_path, np.concatenate([image_point, gt_lmk_image], axis=1))
|
| 133 |
+
|
| 134 |
+
# visualize gt landmarks
|
| 135 |
+
vis_path = os.path.join(gt_lmk_dir, f"{idx}_overlay.jpg")
|
| 136 |
+
image = cv2.imread(gt_img_path)
|
| 137 |
+
image_point = plot_kpts(image, gt_kpt)
|
| 138 |
+
cv2.imwrite(vis_path, np.concatenate([image_point, gt_lmk_image], axis=1))
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def landmark_comparison(val_dataset, lmk_dir, gt_lmk_dir):
|
| 142 |
+
print("Calculating reprojection error")
|
| 143 |
+
lmk_err = []
|
| 144 |
+
|
| 145 |
+
pbar = tqdm(range(len(val_dataset)))
|
| 146 |
+
for i in pbar:
|
| 147 |
+
# line = val_dataset[i]
|
| 148 |
+
# img_name = line["image"].split(".")[0]
|
| 149 |
+
lmk1_path = os.path.join(gt_lmk_dir, f"{i}.txt")
|
| 150 |
+
lmk1 = np.loadtxt(lmk1_path)
|
| 151 |
+
lmk2_path = os.path.join(lmk_dir, f"{i}.txt")
|
| 152 |
+
|
| 153 |
+
if not os.path.exists(lmk2_path):
|
| 154 |
+
print(f"{lmk2_path} not exist")
|
| 155 |
+
continue
|
| 156 |
+
|
| 157 |
+
lmk2 = np.loadtxt(lmk2_path)
|
| 158 |
+
lmk_err.append(np.mean(np.linalg.norm(lmk1 - lmk2, axis=1)))
|
| 159 |
+
pbar.set_description(f"lmk_err: {np.mean(lmk_err):.5f}")
|
| 160 |
+
|
| 161 |
+
print("Reprojection error:", np.mean(lmk_err))
|
| 162 |
+
np.save(os.path.join(lmk_dir, "lmk_err.npy"), lmk_err)
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def main(args):
|
| 166 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 167 |
+
|
| 168 |
+
accelerator = Accelerator(
|
| 169 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 170 |
+
mixed_precision=args.mixed_precision,
|
| 171 |
+
log_with=args.report_to,
|
| 172 |
+
project_dir=logging_dir,
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
# Load the tokenizer
|
| 176 |
+
if args.tokenizer_name:
|
| 177 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
|
| 178 |
+
elif args.pretrained_model_name_or_path:
|
| 179 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 180 |
+
args.pretrained_model_name_or_path,
|
| 181 |
+
subfolder="tokenizer",
|
| 182 |
+
revision=args.revision,
|
| 183 |
+
use_fast=False,
|
| 184 |
+
)
|
| 185 |
+
|
| 186 |
+
val_dataset = make_dataset(args, tokenizer, accelerator, "test")
|
| 187 |
+
|
| 188 |
+
gt_lmk_dir = os.path.join(args.output_dir, "gt_lmk")
|
| 189 |
+
if not os.path.exists(gt_lmk_dir):
|
| 190 |
+
os.makedirs(gt_lmk_dir, exist_ok=True)
|
| 191 |
+
|
| 192 |
+
pred_lmk_dir = os.path.join(args.output_dir, "pred_lmk")
|
| 193 |
+
if not os.path.exists(pred_lmk_dir):
|
| 194 |
+
os.makedirs(pred_lmk_dir, exist_ok=True)
|
| 195 |
+
|
| 196 |
+
input_dir = os.path.join(args.output_dir, "results")
|
| 197 |
+
|
| 198 |
+
generate_landmark2d(val_dataset, input_dir, pred_lmk_dir, gt_lmk_dir, args.vis_overlays)
|
| 199 |
+
|
| 200 |
+
if count_txt_files(pred_lmk_dir) == len(val_dataset) and count_txt_files(gt_lmk_dir) == len(val_dataset):
|
| 201 |
+
landmark_comparison(val_dataset, pred_lmk_dir, gt_lmk_dir)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
if __name__ == "__main__":
|
| 205 |
+
args = parse_args()
|
| 206 |
+
main(args)
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/eval.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PEFT_TYPE="boft"
|
| 2 |
+
BLOCK_NUM=8
|
| 3 |
+
BLOCK_SIZE=0
|
| 4 |
+
N_BUTTERFLY_FACTOR=1
|
| 5 |
+
ITER_NUM=50000
|
| 6 |
+
|
| 7 |
+
export RUN_NAME="${PEFT_TYPE}_${BLOCK_NUM}${BLOCK_SIZE}${N_BUTTERFLY_FACTOR}"
|
| 8 |
+
|
| 9 |
+
export MODEL_NAME="stabilityai/stable-diffusion-2-1"
|
| 10 |
+
# export MODEL_NAME="runwayml/stable-diffusion-v1-5"
|
| 11 |
+
|
| 12 |
+
export DATASET_NAME="oftverse/control-celeba-hq"
|
| 13 |
+
export CKPT_NAME="checkpoint-${ITER_NUM}"
|
| 14 |
+
export OUTPUT_DIR="./output/${DATASET_NAME}/${RUN_NAME}/${CKPT_NAME}"
|
| 15 |
+
export CONTROLNET_PATH="${OUTPUT_DIR}/controlnet/model.safetensors"
|
| 16 |
+
export UNET_PATH="${OUTPUT_DIR}/unet/${RUN_NAME}"
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
accelerate launch eval.py \
|
| 20 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 21 |
+
--dataset_name=$DATASET_NAME \
|
| 22 |
+
--controlnet_path=$CONTROLNET_PATH \
|
| 23 |
+
--unet_path=$UNET_PATH \
|
| 24 |
+
--adapter_name=$RUN_NAME \
|
| 25 |
+
--output_dir=$OUTPUT_DIR \
|
| 26 |
+
--dataset_name=$DATASET_NAME \
|
| 27 |
+
--vis_overlays \
|
| 28 |
+
|
| 29 |
+
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
datasets==2.16.1
|
| 2 |
+
diffusers==0.34.0
|
| 3 |
+
transformers==4.54.0
|
| 4 |
+
accelerate==1.9.0
|
| 5 |
+
wandb==0.16.1
|
| 6 |
+
scikit-image==0.22.0
|
| 7 |
+
opencv-python==4.9.0.80
|
| 8 |
+
git+https://github.com/1adrianb/face-alignment.git
|
| 9 |
+
huggingface_hub==0.34.3
|
| 10 |
+
numpy<2.0.0
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/test_controlnet.py
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2023-present the HuggingFace Inc. team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# The implementation is based on "Parameter-Efficient Orthogonal Finetuning
|
| 16 |
+
# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024.
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import time
|
| 21 |
+
from pathlib import Path
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
from accelerate import Accelerator
|
| 26 |
+
from diffusers import DDIMScheduler
|
| 27 |
+
from diffusers.utils import check_min_version
|
| 28 |
+
from safetensors.torch import load_file
|
| 29 |
+
from tqdm import tqdm
|
| 30 |
+
from transformers import AutoTokenizer
|
| 31 |
+
from utils.args_loader import parse_args
|
| 32 |
+
from utils.dataset import make_dataset
|
| 33 |
+
from utils.light_controlnet import ControlNetModel
|
| 34 |
+
from utils.pipeline_controlnet import LightControlNetPipeline
|
| 35 |
+
from utils.unet_2d_condition import UNet2DConditionNewModel
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
sys.path.append("../../src")
|
| 39 |
+
from peft import PeftModel # noqa: E402
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 43 |
+
check_min_version("0.10.0.dev0")
|
| 44 |
+
if torch.xpu.is_available():
|
| 45 |
+
device = "xpu:0"
|
| 46 |
+
elif torch.cuda.is_available():
|
| 47 |
+
device = "cuda:0"
|
| 48 |
+
else:
|
| 49 |
+
device = "cpu"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def main(args):
|
| 53 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 54 |
+
|
| 55 |
+
accelerator = Accelerator(
|
| 56 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 57 |
+
mixed_precision=args.mixed_precision,
|
| 58 |
+
log_with=args.report_to,
|
| 59 |
+
project_dir=logging_dir,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Load the tokenizer
|
| 63 |
+
if args.tokenizer_name:
|
| 64 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
|
| 65 |
+
elif args.pretrained_model_name_or_path:
|
| 66 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 67 |
+
args.pretrained_model_name_or_path,
|
| 68 |
+
subfolder="tokenizer",
|
| 69 |
+
revision=args.revision,
|
| 70 |
+
use_fast=False,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
val_dataset = make_dataset(args, tokenizer, accelerator, "test")
|
| 74 |
+
|
| 75 |
+
controlnet_path = args.controlnet_path
|
| 76 |
+
unet_path = args.unet_path
|
| 77 |
+
|
| 78 |
+
controlnet = ControlNetModel()
|
| 79 |
+
controlnet.load_state_dict(load_file(controlnet_path))
|
| 80 |
+
unet = UNet2DConditionNewModel.from_pretrained(args.pretrained_model_name_or_path, subfolder="unet")
|
| 81 |
+
unet = PeftModel.from_pretrained(unet, unet_path, adapter_name=args.adapter_name)
|
| 82 |
+
|
| 83 |
+
pipe = LightControlNetPipeline.from_pretrained(
|
| 84 |
+
args.pretrained_model_name_or_path,
|
| 85 |
+
controlnet=controlnet,
|
| 86 |
+
unet=unet.model,
|
| 87 |
+
dtype=torch.float32,
|
| 88 |
+
requires_safety_checker=False,
|
| 89 |
+
).to(device)
|
| 90 |
+
|
| 91 |
+
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
|
| 92 |
+
|
| 93 |
+
if not os.path.exists(args.output_dir):
|
| 94 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 95 |
+
|
| 96 |
+
exist_lst = [int(img.split("_")[-1][:-4]) for img in os.listdir(args.output_dir)]
|
| 97 |
+
all_lst = np.arange(len(val_dataset))
|
| 98 |
+
idx_lst = [item for item in all_lst if item not in exist_lst]
|
| 99 |
+
|
| 100 |
+
print("Number of images to be processed: ", len(idx_lst))
|
| 101 |
+
|
| 102 |
+
np.random.seed(seed=int(time.time()))
|
| 103 |
+
np.random.shuffle(idx_lst)
|
| 104 |
+
|
| 105 |
+
for idx in tqdm(idx_lst):
|
| 106 |
+
output_path = os.path.join(args.output_dir, f"pred_img_{idx:04d}.png")
|
| 107 |
+
|
| 108 |
+
if not os.path.exists(output_path):
|
| 109 |
+
data = val_dataset[idx.item()]
|
| 110 |
+
negative_prompt = "low quality, blurry, unfinished"
|
| 111 |
+
|
| 112 |
+
with torch.no_grad():
|
| 113 |
+
pred_img = pipe(
|
| 114 |
+
data["text"],
|
| 115 |
+
[data["conditioning_pixel_values"]],
|
| 116 |
+
num_inference_steps=50,
|
| 117 |
+
guidance_scale=7,
|
| 118 |
+
negative_prompt=negative_prompt,
|
| 119 |
+
).images[0]
|
| 120 |
+
|
| 121 |
+
pred_img.save(output_path)
|
| 122 |
+
|
| 123 |
+
# control_img = Image.fromarray(
|
| 124 |
+
# (data["conditioning_pixel_value"] * 255).numpy().transpose(1, 2, 0).astype(np.uint8)
|
| 125 |
+
# )
|
| 126 |
+
# gt_img = Image.fromarray(
|
| 127 |
+
# ((data["pixel_value"] + 1.0) * 0.5 * 255).numpy().transpose(1, 2, 0).astype(np.uint8)
|
| 128 |
+
# )
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
if __name__ == "__main__":
|
| 132 |
+
args = parse_args()
|
| 133 |
+
main(args)
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/test_controlnet.sh
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PEFT_TYPE="boft"
|
| 2 |
+
BLOCK_NUM=8
|
| 3 |
+
BLOCK_SIZE=0
|
| 4 |
+
N_BUTTERFLY_FACTOR=1
|
| 5 |
+
ITER_NUM=50000
|
| 6 |
+
|
| 7 |
+
export RUN_NAME="${PEFT_TYPE}_${BLOCK_NUM}${BLOCK_SIZE}${N_BUTTERFLY_FACTOR}"
|
| 8 |
+
|
| 9 |
+
export MODEL_NAME="stabilityai/stable-diffusion-2-1"
|
| 10 |
+
# export MODEL_NAME="runwayml/stable-diffusion-v1-5"
|
| 11 |
+
|
| 12 |
+
export DATASET_NAME="oftverse/control-celeba-hq"
|
| 13 |
+
export CKPT_NAME="checkpoint-${ITER_NUM}"
|
| 14 |
+
export OUTPUT_DIR="./output/${DATASET_NAME}/${RUN_NAME}/${CKPT_NAME}"
|
| 15 |
+
export CONTROLNET_PATH="${OUTPUT_DIR}/controlnet/model.safetensors"
|
| 16 |
+
export UNET_PATH="${OUTPUT_DIR}/unet"
|
| 17 |
+
export RESULTS_PATH="${OUTPUT_DIR}/results"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
accelerate launch test_controlnet.py \
|
| 21 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 22 |
+
--dataset_name=$DATASET_NAME \
|
| 23 |
+
--controlnet_path=$CONTROLNET_PATH \
|
| 24 |
+
--unet_path=$UNET_PATH \
|
| 25 |
+
--adapter_name=$RUN_NAME \
|
| 26 |
+
--output_dir=$RESULTS_PATH \
|
| 27 |
+
--dataset_name=$DATASET_NAME \
|
| 28 |
+
|
| 29 |
+
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/train_controlnet.py
ADDED
|
@@ -0,0 +1,545 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
# The implementation is based on "Parameter-Efficient Orthogonal Finetuning
|
| 17 |
+
# via Butterfly Factorization" (https://huggingface.co/papers/2311.06243) in ICLR 2024.
|
| 18 |
+
|
| 19 |
+
import itertools
|
| 20 |
+
import logging
|
| 21 |
+
import math
|
| 22 |
+
import os
|
| 23 |
+
from pathlib import Path
|
| 24 |
+
|
| 25 |
+
import datasets
|
| 26 |
+
import diffusers
|
| 27 |
+
import torch
|
| 28 |
+
import torch.nn.functional as F
|
| 29 |
+
import torch.utils.checkpoint
|
| 30 |
+
import transformers
|
| 31 |
+
from accelerate import Accelerator
|
| 32 |
+
from accelerate.logging import get_logger
|
| 33 |
+
from accelerate.utils import set_seed
|
| 34 |
+
from diffusers import (
|
| 35 |
+
AutoencoderKL,
|
| 36 |
+
DDIMScheduler,
|
| 37 |
+
)
|
| 38 |
+
from diffusers.optimization import get_scheduler
|
| 39 |
+
from diffusers.utils import check_min_version
|
| 40 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 41 |
+
from packaging import version
|
| 42 |
+
from tqdm.auto import tqdm
|
| 43 |
+
from transformers import AutoTokenizer
|
| 44 |
+
from utils.args_loader import (
|
| 45 |
+
import_model_class_from_model_name_or_path,
|
| 46 |
+
parse_args,
|
| 47 |
+
)
|
| 48 |
+
from utils.dataset import collate_fn, log_validation, make_dataset
|
| 49 |
+
from utils.light_controlnet import ControlNetModel
|
| 50 |
+
from utils.tracemalloc import TorchTracemalloc, b2mb
|
| 51 |
+
from utils.unet_2d_condition import UNet2DConditionNewModel
|
| 52 |
+
|
| 53 |
+
from peft import BOFTConfig, get_peft_model
|
| 54 |
+
from peft.peft_model import PeftModel
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# Will error if the minimal version of diffusers is not installed. Remove at your own risks.
|
| 58 |
+
check_min_version("0.16.0.dev0")
|
| 59 |
+
|
| 60 |
+
logger = get_logger(__name__)
|
| 61 |
+
|
| 62 |
+
UNET_TARGET_MODULES = ["to_q", "to_v", "to_k", "query", "value", "key"]
|
| 63 |
+
|
| 64 |
+
TEXT_ENCODER_TARGET_MODULES = ["q_proj", "v_proj"]
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@torch.no_grad()
|
| 68 |
+
def save_adaptor(accelerator, output_dir, nets_dict):
|
| 69 |
+
for net_key in nets_dict.keys():
|
| 70 |
+
net_model = nets_dict[net_key]
|
| 71 |
+
unwarpped_net = accelerator.unwrap_model(net_model)
|
| 72 |
+
|
| 73 |
+
if isinstance(unwarpped_net, PeftModel):
|
| 74 |
+
unwarpped_net.save_pretrained(
|
| 75 |
+
os.path.join(output_dir, net_key),
|
| 76 |
+
state_dict=accelerator.get_state_dict(net_model),
|
| 77 |
+
safe_serialization=True,
|
| 78 |
+
)
|
| 79 |
+
else:
|
| 80 |
+
accelerator.save_model(
|
| 81 |
+
unwarpped_net,
|
| 82 |
+
os.path.join(output_dir, net_key),
|
| 83 |
+
safe_serialization=True,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def main(args):
|
| 88 |
+
logging_dir = Path(args.output_dir, args.logging_dir)
|
| 89 |
+
|
| 90 |
+
accelerator = Accelerator(
|
| 91 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 92 |
+
mixed_precision=args.mixed_precision,
|
| 93 |
+
log_with=args.report_to,
|
| 94 |
+
project_dir=logging_dir,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
if args.report_to == "wandb":
|
| 98 |
+
wandb_init = {
|
| 99 |
+
"wandb": {
|
| 100 |
+
"name": args.wandb_run_name,
|
| 101 |
+
"mode": "online",
|
| 102 |
+
}
|
| 103 |
+
}
|
| 104 |
+
|
| 105 |
+
# Make one log on every process with the configuration for debugging.
|
| 106 |
+
logging.basicConfig(
|
| 107 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 108 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 109 |
+
level=logging.INFO,
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 113 |
+
|
| 114 |
+
if accelerator.is_local_main_process:
|
| 115 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 116 |
+
transformers.utils.logging.set_verbosity_warning()
|
| 117 |
+
diffusers.utils.logging.set_verbosity_info()
|
| 118 |
+
else:
|
| 119 |
+
datasets.utils.logging.set_verbosity_error()
|
| 120 |
+
transformers.utils.logging.set_verbosity_error()
|
| 121 |
+
diffusers.utils.logging.set_verbosity_error()
|
| 122 |
+
|
| 123 |
+
# If passed along, set the training seed now.
|
| 124 |
+
if args.seed is not None:
|
| 125 |
+
set_seed(args.seed)
|
| 126 |
+
|
| 127 |
+
# Handle the repository creation
|
| 128 |
+
if accelerator.is_main_process:
|
| 129 |
+
if args.output_dir is not None:
|
| 130 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 131 |
+
|
| 132 |
+
# Load the tokenizer
|
| 133 |
+
if args.tokenizer_name:
|
| 134 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, revision=args.revision, use_fast=False)
|
| 135 |
+
elif args.pretrained_model_name_or_path:
|
| 136 |
+
tokenizer = AutoTokenizer.from_pretrained(
|
| 137 |
+
args.pretrained_model_name_or_path,
|
| 138 |
+
subfolder="tokenizer",
|
| 139 |
+
revision=args.revision,
|
| 140 |
+
use_fast=False,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
# import correct text encoder class
|
| 144 |
+
text_encoder_cls = import_model_class_from_model_name_or_path(args.pretrained_model_name_or_path, args.revision)
|
| 145 |
+
|
| 146 |
+
# Load scheduler and models
|
| 147 |
+
noise_scheduler = DDIMScheduler.from_pretrained(args.pretrained_model_name_or_path, subfolder="scheduler")
|
| 148 |
+
|
| 149 |
+
text_encoder = text_encoder_cls.from_pretrained(
|
| 150 |
+
args.pretrained_model_name_or_path, subfolder="text_encoder", revision=args.revision
|
| 151 |
+
)
|
| 152 |
+
vae = AutoencoderKL.from_pretrained(args.pretrained_model_name_or_path, subfolder="vae", revision=args.revision)
|
| 153 |
+
unet = UNet2DConditionNewModel.from_pretrained(
|
| 154 |
+
args.pretrained_model_name_or_path,
|
| 155 |
+
subfolder="unet",
|
| 156 |
+
revision=args.revision,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
controlnet = ControlNetModel()
|
| 160 |
+
|
| 161 |
+
if args.controlnet_model_name_or_path != "":
|
| 162 |
+
logger.info(f"Loading existing controlnet weights from {args.controlnet_model_name_or_path}")
|
| 163 |
+
controlnet.load_state_dict(torch.load(args.controlnet_model_name_or_path))
|
| 164 |
+
|
| 165 |
+
if args.use_boft:
|
| 166 |
+
config = BOFTConfig(
|
| 167 |
+
boft_block_size=args.boft_block_size,
|
| 168 |
+
boft_block_num=args.boft_block_num,
|
| 169 |
+
boft_n_butterfly_factor=args.boft_n_butterfly_factor,
|
| 170 |
+
target_modules=UNET_TARGET_MODULES,
|
| 171 |
+
boft_dropout=args.boft_dropout,
|
| 172 |
+
bias=args.boft_bias,
|
| 173 |
+
)
|
| 174 |
+
unet = get_peft_model(unet, config)
|
| 175 |
+
unet.print_trainable_parameters()
|
| 176 |
+
|
| 177 |
+
vae.requires_grad_(False)
|
| 178 |
+
controlnet.requires_grad_(True)
|
| 179 |
+
|
| 180 |
+
if not args.train_text_encoder:
|
| 181 |
+
text_encoder.requires_grad_(False)
|
| 182 |
+
|
| 183 |
+
unet.train()
|
| 184 |
+
controlnet.train()
|
| 185 |
+
|
| 186 |
+
if args.train_text_encoder and args.use_boft:
|
| 187 |
+
config = BOFTConfig(
|
| 188 |
+
boft_block_size=args.boft_block_size,
|
| 189 |
+
boft_block_num=args.boft_block_num,
|
| 190 |
+
boft_n_butterfly_factor=args.boft_n_butterfly_factor,
|
| 191 |
+
target_modules=TEXT_ENCODER_TARGET_MODULES,
|
| 192 |
+
boft_dropout=args.boft_dropout,
|
| 193 |
+
bias=args.boft_bias,
|
| 194 |
+
)
|
| 195 |
+
text_encoder = get_peft_model(text_encoder, config, adapter_name=args.wandb_run_name)
|
| 196 |
+
text_encoder.print_trainable_parameters()
|
| 197 |
+
|
| 198 |
+
if args.train_text_encoder:
|
| 199 |
+
text_encoder.train()
|
| 200 |
+
|
| 201 |
+
# For mixed precision training we cast the text_encoder and vae weights to half-precision
|
| 202 |
+
# as these models are only used for inference, keeping weights in full precision is not required.
|
| 203 |
+
weight_dtype = torch.float32
|
| 204 |
+
if accelerator.mixed_precision == "fp16":
|
| 205 |
+
weight_dtype = torch.float16
|
| 206 |
+
elif accelerator.mixed_precision == "bf16":
|
| 207 |
+
weight_dtype = torch.bfloat16
|
| 208 |
+
|
| 209 |
+
# Move unet, vae and text_encoder to device and cast to weight_dtype
|
| 210 |
+
unet.to(accelerator.device, dtype=weight_dtype)
|
| 211 |
+
vae.to(accelerator.device, dtype=weight_dtype)
|
| 212 |
+
controlnet.to(accelerator.device, dtype=weight_dtype)
|
| 213 |
+
|
| 214 |
+
if not args.train_text_encoder:
|
| 215 |
+
text_encoder.to(accelerator.device, dtype=weight_dtype)
|
| 216 |
+
|
| 217 |
+
if args.enable_xformers_memory_efficient_attention:
|
| 218 |
+
if accelerator.device.type == "xpu":
|
| 219 |
+
logger.warning("XPU doesn't support xformers yet, xformers is not applied.")
|
| 220 |
+
elif is_xformers_available():
|
| 221 |
+
import xformers
|
| 222 |
+
|
| 223 |
+
xformers_version = version.parse(xformers.__version__)
|
| 224 |
+
if xformers_version == version.parse("0.0.16"):
|
| 225 |
+
logger.warning(
|
| 226 |
+
"xFormers 0.0.16 cannot be used for training in some GPUs. If you observe problems during training, please update xFormers to at least 0.0.17. See https://huggingface.co/docs/diffusers/main/en/optimization/xformers for more details."
|
| 227 |
+
)
|
| 228 |
+
unet.enable_xformers_memory_efficient_attention()
|
| 229 |
+
controlnet.enable_xformers_memory_efficient_attention()
|
| 230 |
+
if args.train_text_encoder and not (args.use_lora or args.use_boft or args.use_oft):
|
| 231 |
+
text_encoder.enable_xformers_memory_efficient_attention()
|
| 232 |
+
else:
|
| 233 |
+
raise ValueError("xformers is not available. Make sure it is installed correctly")
|
| 234 |
+
|
| 235 |
+
if args.gradient_checkpointing:
|
| 236 |
+
controlnet.enable_gradient_checkpointing()
|
| 237 |
+
unet.enable_gradient_checkpointing()
|
| 238 |
+
if args.train_text_encoder and not (args.use_lora or args.use_boft or args.use_oft):
|
| 239 |
+
text_encoder.gradient_checkpointing_enable()
|
| 240 |
+
|
| 241 |
+
# Check that all trainable models are in full precision
|
| 242 |
+
low_precision_error_string = (
|
| 243 |
+
" Please make sure to always have all model weights in full float32 precision when starting training - even if"
|
| 244 |
+
" doing mixed precision training, copy of the weights should still be float32."
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
if accelerator.unwrap_model(controlnet).dtype != torch.float32:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"Controlnet loaded as datatype {accelerator.unwrap_model(controlnet).dtype}. {low_precision_error_string}"
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
if accelerator.unwrap_model(unet).dtype != torch.float32:
|
| 253 |
+
raise ValueError(
|
| 254 |
+
f"UNet loaded as datatype {accelerator.unwrap_model(unet).dtype}. {low_precision_error_string}"
|
| 255 |
+
)
|
| 256 |
+
|
| 257 |
+
# Enable TF32 for faster training on Ampere GPUs,
|
| 258 |
+
# cf https://pytorch.org/docs/stable/notes/cuda.html#tensorfloat-32-tf32-on-ampere-devices
|
| 259 |
+
if args.allow_tf32:
|
| 260 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
| 261 |
+
|
| 262 |
+
if args.scale_lr:
|
| 263 |
+
args.learning_rate = (
|
| 264 |
+
args.learning_rate * args.gradient_accumulation_steps * args.train_batch_size * accelerator.num_processes
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
# Use 8-bit Adam for lower memory usage or to fine-tune the model in 16GB GPUs
|
| 268 |
+
if args.use_8bit_adam:
|
| 269 |
+
try:
|
| 270 |
+
import bitsandbytes as bnb
|
| 271 |
+
except ImportError:
|
| 272 |
+
raise ImportError(
|
| 273 |
+
"To use 8-bit Adam, please install the bitsandbytes library: `pip install bitsandbytes`."
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
optimizer_class = bnb.optim.AdamW8bit
|
| 277 |
+
else:
|
| 278 |
+
optimizer_class = torch.optim.AdamW
|
| 279 |
+
|
| 280 |
+
params_to_optimize = [param for param in controlnet.parameters() if param.requires_grad]
|
| 281 |
+
params_to_optimize += [param for param in unet.parameters() if param.requires_grad]
|
| 282 |
+
|
| 283 |
+
if args.train_text_encoder:
|
| 284 |
+
params_to_optimize += [param for param in text_encoder.parameters() if param.requires_grad]
|
| 285 |
+
|
| 286 |
+
# Optimizer creation
|
| 287 |
+
optimizer = optimizer_class(
|
| 288 |
+
params_to_optimize,
|
| 289 |
+
lr=args.learning_rate,
|
| 290 |
+
betas=(args.adam_beta1, args.adam_beta2),
|
| 291 |
+
weight_decay=args.adam_weight_decay,
|
| 292 |
+
eps=args.adam_epsilon,
|
| 293 |
+
)
|
| 294 |
+
|
| 295 |
+
# Load the dataset
|
| 296 |
+
train_dataset = make_dataset(args, tokenizer, accelerator, "train")
|
| 297 |
+
val_dataset = make_dataset(args, tokenizer, accelerator, "test")
|
| 298 |
+
|
| 299 |
+
train_dataloader = torch.utils.data.DataLoader(
|
| 300 |
+
train_dataset,
|
| 301 |
+
shuffle=True,
|
| 302 |
+
collate_fn=collate_fn,
|
| 303 |
+
batch_size=args.train_batch_size,
|
| 304 |
+
num_workers=args.dataloader_num_workers,
|
| 305 |
+
)
|
| 306 |
+
|
| 307 |
+
# Scheduler and math around the number of training steps.
|
| 308 |
+
overrode_max_train_steps = False
|
| 309 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 310 |
+
if args.max_train_steps is None:
|
| 311 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 312 |
+
overrode_max_train_steps = True
|
| 313 |
+
|
| 314 |
+
lr_scheduler = get_scheduler(
|
| 315 |
+
args.lr_scheduler,
|
| 316 |
+
optimizer=optimizer,
|
| 317 |
+
num_warmup_steps=args.lr_warmup_steps * args.gradient_accumulation_steps,
|
| 318 |
+
num_training_steps=args.max_train_steps * args.gradient_accumulation_steps,
|
| 319 |
+
num_cycles=args.lr_num_cycles,
|
| 320 |
+
power=args.lr_power,
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
# Prepare everything with our `accelerator`.
|
| 324 |
+
controlnet, optimizer, train_dataloader, lr_scheduler = accelerator.prepare(
|
| 325 |
+
controlnet, optimizer, train_dataloader, lr_scheduler
|
| 326 |
+
)
|
| 327 |
+
|
| 328 |
+
if args.train_text_encoder:
|
| 329 |
+
text_encoder = accelerator.prepare(text_encoder)
|
| 330 |
+
|
| 331 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 332 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / args.gradient_accumulation_steps)
|
| 333 |
+
if overrode_max_train_steps:
|
| 334 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 335 |
+
# Afterwards we recalculate our number of training epochs
|
| 336 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 337 |
+
|
| 338 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 339 |
+
# The trackers initializes automatically on the main process.
|
| 340 |
+
if accelerator.is_main_process:
|
| 341 |
+
accelerator.init_trackers(args.wandb_project_name, config=vars(args), init_kwargs=wandb_init)
|
| 342 |
+
|
| 343 |
+
# Train!
|
| 344 |
+
total_batch_size = args.train_batch_size * accelerator.num_processes * args.gradient_accumulation_steps
|
| 345 |
+
|
| 346 |
+
logger.info("***** Running training *****")
|
| 347 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 348 |
+
logger.info(f" Num batches each epoch = {len(train_dataloader)}")
|
| 349 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 350 |
+
logger.info(f" Instantaneous batch size per device = {args.train_batch_size}")
|
| 351 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 352 |
+
logger.info(f" Gradient Accumulation steps = {args.gradient_accumulation_steps}")
|
| 353 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 354 |
+
|
| 355 |
+
global_step = 0
|
| 356 |
+
first_epoch = 0
|
| 357 |
+
|
| 358 |
+
# Potentially load in the weights and states from a previous save
|
| 359 |
+
|
| 360 |
+
if args.resume_from_checkpoint:
|
| 361 |
+
if args.resume_from_checkpoint != "latest":
|
| 362 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 363 |
+
else:
|
| 364 |
+
# Get the most recent checkpoint
|
| 365 |
+
dirs = os.listdir(args.output_dir)
|
| 366 |
+
if "checkpoint-current" in dirs:
|
| 367 |
+
path = "checkpoint-current"
|
| 368 |
+
dirs = [d for d in dirs if d.startswith("checkpoint") and d.endswith("0")]
|
| 369 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 370 |
+
|
| 371 |
+
else:
|
| 372 |
+
dirs = [d for d in dirs if d.startswith("checkpoint")]
|
| 373 |
+
dirs = sorted(dirs, key=lambda x: int(x.split("-")[1]))
|
| 374 |
+
path = dirs[-1] if len(dirs) > 0 else None
|
| 375 |
+
|
| 376 |
+
if path is None:
|
| 377 |
+
accelerator.print(
|
| 378 |
+
f"Checkpoint '{args.resume_from_checkpoint}' does not exist. Starting a new training run."
|
| 379 |
+
)
|
| 380 |
+
args.resume_from_checkpoint = None
|
| 381 |
+
initial_global_step = 0
|
| 382 |
+
else:
|
| 383 |
+
accelerator.print(f"Resuming from checkpoint {path}")
|
| 384 |
+
accelerator.load_state(os.path.join(args.output_dir, path))
|
| 385 |
+
if path.split("-")[1] == "current":
|
| 386 |
+
global_step = int(dirs[-1].split("-")[1])
|
| 387 |
+
else:
|
| 388 |
+
global_step = int(path.split("-")[1])
|
| 389 |
+
|
| 390 |
+
initial_global_step = global_step
|
| 391 |
+
resume_global_step = global_step * args.gradient_accumulation_steps
|
| 392 |
+
first_epoch = global_step // num_update_steps_per_epoch
|
| 393 |
+
resume_step = resume_global_step % (num_update_steps_per_epoch * args.gradient_accumulation_steps)
|
| 394 |
+
else:
|
| 395 |
+
initial_global_step = 0
|
| 396 |
+
|
| 397 |
+
progress_bar = tqdm(
|
| 398 |
+
range(0, args.max_train_steps),
|
| 399 |
+
initial=initial_global_step,
|
| 400 |
+
desc="Steps",
|
| 401 |
+
disable=not accelerator.is_local_main_process,
|
| 402 |
+
)
|
| 403 |
+
|
| 404 |
+
progress_bar.set_description("Steps")
|
| 405 |
+
|
| 406 |
+
for epoch in range(first_epoch, args.num_train_epochs):
|
| 407 |
+
with TorchTracemalloc() as tracemalloc:
|
| 408 |
+
for step, batch in enumerate(train_dataloader):
|
| 409 |
+
# Skip steps until we reach the resumed step
|
| 410 |
+
if args.resume_from_checkpoint and epoch == first_epoch and step < resume_step:
|
| 411 |
+
if step % args.gradient_accumulation_steps == 0:
|
| 412 |
+
progress_bar.update(1)
|
| 413 |
+
if args.report_to == "wandb":
|
| 414 |
+
accelerator.print(progress_bar)
|
| 415 |
+
continue
|
| 416 |
+
|
| 417 |
+
with accelerator.accumulate(controlnet), accelerator.accumulate(unet):
|
| 418 |
+
# Convert images to latent space
|
| 419 |
+
latents = vae.encode(batch["pixel_values"].to(dtype=weight_dtype)).latent_dist.sample()
|
| 420 |
+
latents = latents * vae.config.scaling_factor
|
| 421 |
+
|
| 422 |
+
# Sample noise that we'll add to the latents
|
| 423 |
+
noise = torch.randn_like(latents)
|
| 424 |
+
bsz = latents.shape[0]
|
| 425 |
+
|
| 426 |
+
# Sample a random timestep for each image
|
| 427 |
+
timesteps = torch.randint(
|
| 428 |
+
0, noise_scheduler.config.num_train_timesteps, (bsz,), device=latents.device
|
| 429 |
+
)
|
| 430 |
+
timesteps = timesteps.long()
|
| 431 |
+
|
| 432 |
+
# Add noise to the latents according to the noise magnitude at each timestep
|
| 433 |
+
# (this is the forward diffusion process)
|
| 434 |
+
noisy_latents = noise_scheduler.add_noise(latents, noise, timesteps)
|
| 435 |
+
|
| 436 |
+
# Get the text embedding for conditioning
|
| 437 |
+
encoder_hidden_states = text_encoder(batch["input_ids"])[0]
|
| 438 |
+
|
| 439 |
+
controlnet_image = batch["conditioning_pixel_values"].to(dtype=weight_dtype)
|
| 440 |
+
|
| 441 |
+
# Get the guided hint for the UNet (320 dim)
|
| 442 |
+
guided_hint = controlnet(
|
| 443 |
+
controlnet_cond=controlnet_image,
|
| 444 |
+
)
|
| 445 |
+
|
| 446 |
+
# Predict the noise residual
|
| 447 |
+
model_pred = unet(
|
| 448 |
+
noisy_latents,
|
| 449 |
+
timesteps,
|
| 450 |
+
guided_hint=guided_hint,
|
| 451 |
+
encoder_hidden_states=encoder_hidden_states,
|
| 452 |
+
).sample
|
| 453 |
+
|
| 454 |
+
# Get the target for loss depending on the prediction type
|
| 455 |
+
if noise_scheduler.config.prediction_type == "epsilon":
|
| 456 |
+
target = noise
|
| 457 |
+
elif noise_scheduler.config.prediction_type == "v_prediction":
|
| 458 |
+
target = noise_scheduler.get_velocity(latents, noise, timesteps)
|
| 459 |
+
else:
|
| 460 |
+
raise ValueError(f"Unknown prediction type {noise_scheduler.config.prediction_type}")
|
| 461 |
+
|
| 462 |
+
loss = F.mse_loss(model_pred.float(), target.float(), reduction="mean")
|
| 463 |
+
|
| 464 |
+
accelerator.backward(loss)
|
| 465 |
+
|
| 466 |
+
if accelerator.sync_gradients:
|
| 467 |
+
params_to_clip = (
|
| 468 |
+
itertools.chain(controlnet.parameters(), text_encoder.parameters())
|
| 469 |
+
if args.train_text_encoder
|
| 470 |
+
else itertools.chain(
|
| 471 |
+
controlnet.parameters(),
|
| 472 |
+
)
|
| 473 |
+
)
|
| 474 |
+
|
| 475 |
+
accelerator.clip_grad_norm_(params_to_clip, args.max_grad_norm)
|
| 476 |
+
|
| 477 |
+
optimizer.step()
|
| 478 |
+
lr_scheduler.step()
|
| 479 |
+
optimizer.zero_grad(set_to_none=args.set_grads_to_none)
|
| 480 |
+
|
| 481 |
+
# Checks if the accelerator has performed an optimization step behind the scenes
|
| 482 |
+
if accelerator.sync_gradients:
|
| 483 |
+
progress_bar.update(1)
|
| 484 |
+
if args.report_to == "wandb":
|
| 485 |
+
accelerator.print(progress_bar)
|
| 486 |
+
global_step += 1
|
| 487 |
+
|
| 488 |
+
step_save_path = os.path.join(args.output_dir, f"checkpoint-{global_step}")
|
| 489 |
+
|
| 490 |
+
if accelerator.is_main_process:
|
| 491 |
+
if global_step % args.validation_steps == 0 or global_step == 1:
|
| 492 |
+
logger.info(f"Running validation... \n Generating {args.num_validation_images} images.")
|
| 493 |
+
logger.info("Running validation... ")
|
| 494 |
+
|
| 495 |
+
with torch.no_grad():
|
| 496 |
+
log_validation(val_dataset, text_encoder, unet, controlnet, args, accelerator)
|
| 497 |
+
|
| 498 |
+
if global_step % args.checkpointing_steps == 0:
|
| 499 |
+
save_adaptor(accelerator, step_save_path, {"controlnet": controlnet, "unet": unet})
|
| 500 |
+
|
| 501 |
+
# save text_encoder if any
|
| 502 |
+
if args.train_text_encoder:
|
| 503 |
+
save_adaptor(accelerator, step_save_path, {"text_encoder": text_encoder})
|
| 504 |
+
|
| 505 |
+
accelerator.save_state(step_save_path)
|
| 506 |
+
|
| 507 |
+
logger.info(f"Saved {global_step} state to {step_save_path}")
|
| 508 |
+
logger.info(f"Saved current state to {step_save_path}")
|
| 509 |
+
|
| 510 |
+
logs = {"loss": loss.detach().item(), "lr": lr_scheduler.get_last_lr()[0]}
|
| 511 |
+
progress_bar.set_postfix(**logs)
|
| 512 |
+
accelerator.log(logs, step=global_step)
|
| 513 |
+
|
| 514 |
+
if global_step >= args.max_train_steps:
|
| 515 |
+
break
|
| 516 |
+
|
| 517 |
+
# Printing the GPU memory usage details such as allocated memory, peak memory, and total memory usage
|
| 518 |
+
accelerator.print(
|
| 519 |
+
f"{accelerator.device.type.upper()} Memory before entering the train : {b2mb(tracemalloc.begin)}"
|
| 520 |
+
)
|
| 521 |
+
accelerator.print(
|
| 522 |
+
f"{accelerator.device.type.upper()} Memory consumed at the end of the train (end-begin): {tracemalloc.used}"
|
| 523 |
+
)
|
| 524 |
+
accelerator.print(
|
| 525 |
+
f"{accelerator.device.type.upper()} Peak Memory consumed during the train (max-begin): {tracemalloc.peaked}"
|
| 526 |
+
)
|
| 527 |
+
accelerator.print(
|
| 528 |
+
f"{accelerator.device.type.upper()} Total Peak Memory consumed during the train (max): {tracemalloc.peaked + b2mb(tracemalloc.begin)}"
|
| 529 |
+
)
|
| 530 |
+
|
| 531 |
+
accelerator.print(f"CPU Memory before entering the train : {b2mb(tracemalloc.cpu_begin)}")
|
| 532 |
+
accelerator.print(f"CPU Memory consumed at the end of the train (end-begin): {tracemalloc.cpu_used}")
|
| 533 |
+
accelerator.print(f"CPU Peak Memory consumed during the train (max-begin): {tracemalloc.cpu_peaked}")
|
| 534 |
+
accelerator.print(
|
| 535 |
+
f"CPU Total Peak Memory consumed during the train (max): {tracemalloc.cpu_peaked + b2mb(tracemalloc.cpu_begin)}"
|
| 536 |
+
)
|
| 537 |
+
|
| 538 |
+
# Create the pipeline using using the trained modules and save it.
|
| 539 |
+
accelerator.wait_for_everyone()
|
| 540 |
+
accelerator.end_training()
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
if __name__ == "__main__":
|
| 544 |
+
args = parse_args()
|
| 545 |
+
main(args)
|
tasks/tasksmith-9aea936e30e4/environment/source/examples/boft_controlnet/train_controlnet.sh
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PEFT_TYPE="boft"
|
| 2 |
+
BLOCK_NUM=8
|
| 3 |
+
BLOCK_SIZE=0
|
| 4 |
+
N_BUTTERFLY_FACTOR=1
|
| 5 |
+
|
| 6 |
+
export DATASET_NAME="oftverse/control-celeba-hq"
|
| 7 |
+
export PROJECT_NAME="controlnet_${PEFT_TYPE}"
|
| 8 |
+
export RUN_NAME="${PEFT_TYPE}_${BLOCK_NUM}${BLOCK_SIZE}${N_BUTTERFLY_FACTOR}"
|
| 9 |
+
export CONTROLNET_PATH=""
|
| 10 |
+
|
| 11 |
+
export MODEL_NAME="stabilityai/stable-diffusion-2-1"
|
| 12 |
+
# export MODEL_NAME="runwayml/stable-diffusion-v1-5"
|
| 13 |
+
|
| 14 |
+
export OUTPUT_DIR="./output/${DATASET_NAME}/${RUN_NAME}"
|
| 15 |
+
|
| 16 |
+
accelerate launch train_controlnet.py \
|
| 17 |
+
--pretrained_model_name_or_path=$MODEL_NAME \
|
| 18 |
+
--resume_from_checkpoint=$RESUME_PATH \
|
| 19 |
+
--controlnet_model_name_or_path=$CONTROLNET_PATH \
|
| 20 |
+
--output_dir=$OUTPUT_DIR \
|
| 21 |
+
--report_to="wandb" \
|
| 22 |
+
--dataset_name=$DATASET_NAME \
|
| 23 |
+
--resolution=512 \
|
| 24 |
+
--learning_rate=1e-5 \
|
| 25 |
+
--checkpointing_steps=500 \
|
| 26 |
+
--max_train_steps=50000 \
|
| 27 |
+
--validation_steps=5000 \
|
| 28 |
+
--num_validation_images=12 \
|
| 29 |
+
--train_batch_size=4 \
|
| 30 |
+
--dataloader_num_workers=2 \
|
| 31 |
+
--seed="0" \
|
| 32 |
+
--lr_scheduler="constant" \
|
| 33 |
+
--lr_warmup_steps=0 \
|
| 34 |
+
--wandb_project_name=$PROJECT_NAME \
|
| 35 |
+
--wandb_run_name=$RUN_NAME \
|
| 36 |
+
--enable_xformers_memory_efficient_attention \
|
| 37 |
+
--use_boft \
|
| 38 |
+
--boft_block_num=$BLOCK_NUM \
|
| 39 |
+
--boft_block_size=$BLOCK_SIZE \
|
| 40 |
+
--boft_n_butterfly_factor=$N_BUTTERFLY_FACTOR \
|
| 41 |
+
--boft_dropout=0.1 \
|
| 42 |
+
--boft_bias="boft_only" \
|