Stage Harbor release files 69501-70000
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_osf.py +72 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_other.py +644 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_poly.py +103 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_pvera.py +244 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_randlora.py +245 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_seq_classifier.py +347 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_shira.py +278 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_stablediffusion.py +462 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_target_parameters.py +600 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_torch_compile.py +593 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_trainable_tokens.py +1389 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_tuners_utils.py +0 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_vblora.py +269 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_vera.py +242 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_vision_models.py +160 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/test_xlora.py +480 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/testing_common.py +1876 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/testing_utils.py +373 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/training/adapters.py +170 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/training/deepspeed_config.yaml +22 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/training/fsdp2_config.yaml +22 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/training/fsdp_config.yaml +25 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/training/lora_tp.py +227 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/training/tp_config.yaml +9 -0
- tasks/tasksmith-a27f5bd16532/tests/source/tests/training/training.py +161 -0
- tasks/tasksmith-a27f5bd16532/tests/test.sh +3 -0
- tasks/tasksmith-a27f5bd16532/tests/test_driver.py +41 -0
- tasks/tasksmith-a27f5bd16532/tests/test_results.py +65 -0
- tasks/tasksmith-ae8f12dc63d0/environment/Dockerfile +9 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/.devcontainer/devcontainer.json +29 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/.gitignore +144 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/.pre-commit-config.yaml +13 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/CODE_OF_CONDUCT.md +129 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/CONTRIBUTING.md +249 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/Dockerfile +8 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/LICENSE +201 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/Makefile +72 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/README.md +277 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/docker/README.md +74 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/docker/accelerate-cpu/Dockerfile +35 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/docker/accelerate-gpu-deepspeed/Dockerfile +46 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/docker/accelerate-gpu/Dockerfile +45 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/README.md +276 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/README.md +121 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/automatic_gradient_accumulation.py +243 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/checkpointing.py +326 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/cross_validation.py +281 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/ddp_comm_hook.py +232 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/deepspeed_with_config_support.py +723 -0
- tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/early_stopping.py +246 -0
tasks/tasksmith-a27f5bd16532/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-a27f5bd16532/tests/source/tests/test_other.py
ADDED
|
@@ -0,0 +1,644 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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.import_utils import is_transformers_ge_v5_1_0
|
| 31 |
+
from peft.utils.other import ModulesToSaveWrapper, _get_module_names_tied_with_embedding, _get_no_split_modules
|
| 32 |
+
|
| 33 |
+
from .testing_utils import hub_online_once
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class ModelWithModuleDict(nn.Module):
|
| 37 |
+
def __init__(self):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.other_layer = nn.Linear(10, 10)
|
| 40 |
+
self.module = nn.ModuleDict({"foo": nn.Linear(10, 10)})
|
| 41 |
+
|
| 42 |
+
def forward(self):
|
| 43 |
+
return self.module["foo"](torch.rand(1, 10))
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class ModelWithModuleList(nn.Module):
|
| 47 |
+
def __init__(self):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.other_layer = nn.Linear(10, 10)
|
| 50 |
+
self.module = nn.ModuleList([nn.Linear(10, 10)])
|
| 51 |
+
|
| 52 |
+
def forward(self):
|
| 53 |
+
return self.module[0](torch.rand(1, 10))
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
class ModelWithParameterDict(nn.Module):
|
| 57 |
+
def __init__(self):
|
| 58 |
+
super().__init__()
|
| 59 |
+
self.other_layer = nn.Linear(10, 10)
|
| 60 |
+
self.module = nn.ParameterDict({"foo": nn.Parameter(torch.rand(10, 10))})
|
| 61 |
+
|
| 62 |
+
def forward(self):
|
| 63 |
+
return self.module["foo"]
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class ModelWithParameterList(nn.Module):
|
| 67 |
+
def __init__(self):
|
| 68 |
+
super().__init__()
|
| 69 |
+
self.other_layer = nn.Linear(10, 10)
|
| 70 |
+
self.module = nn.ParameterList([nn.Parameter(torch.rand(10, 10))])
|
| 71 |
+
|
| 72 |
+
def forward(self):
|
| 73 |
+
return self.module[0]
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
@pytest.mark.parametrize(
|
| 77 |
+
"cls", [ModelWithModuleDict, ModelWithModuleList, ModelWithParameterDict, ModelWithParameterList]
|
| 78 |
+
)
|
| 79 |
+
def test_modules_to_save_targets_module_dict_raises(cls):
|
| 80 |
+
model = cls()
|
| 81 |
+
peft_config = LoraConfig(
|
| 82 |
+
target_modules=["other_layer"],
|
| 83 |
+
modules_to_save=["module"],
|
| 84 |
+
)
|
| 85 |
+
model() # sanity check that the model would normally work
|
| 86 |
+
|
| 87 |
+
msg = "modules_to_save cannot be applied to modules of type"
|
| 88 |
+
with pytest.raises(TypeError, match=msg):
|
| 89 |
+
get_peft_model(model=model, peft_config=peft_config)
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
def test_get_peft_model_revision_warning(tmp_path):
|
| 93 |
+
base_model_id = "peft-internal-testing/tiny-random-BertModel"
|
| 94 |
+
base_revision = "v2.0.0"
|
| 95 |
+
base_model = AutoModelForCausalLM.from_pretrained(base_model_id, revision=base_revision).eval()
|
| 96 |
+
lora_config = LoraConfig(revision=base_revision)
|
| 97 |
+
|
| 98 |
+
overwrite_revision = "main"
|
| 99 |
+
overwrite_warning = f"peft config has already set base model revision to {base_revision}, overwriting with revision {overwrite_revision}"
|
| 100 |
+
with pytest.warns(UserWarning, match=overwrite_warning):
|
| 101 |
+
_ = get_peft_model(base_model, lora_config, revision=overwrite_revision)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def test_load_multiple_adapters_different_modules_to_save(tmp_path):
|
| 105 |
+
# This tests the error described in #2422 where loading multiple adapters with different modules_to_save
|
| 106 |
+
# attributes fails (due to a regression from #2376).
|
| 107 |
+
|
| 108 |
+
model = AutoModelForCausalLM.from_pretrained("trl-internal-testing/tiny-random-LlamaForCausalLM")
|
| 109 |
+
|
| 110 |
+
def peft_config(**kwargs):
|
| 111 |
+
return LoraConfig(target_modules="all-linear", **kwargs)
|
| 112 |
+
|
| 113 |
+
original_model = copy.deepcopy(model)
|
| 114 |
+
|
| 115 |
+
peft_config_0 = peft_config(modules_to_save=["0.post_attention_layernorm"])
|
| 116 |
+
peft_config_1 = peft_config(modules_to_save=["0.post_attention_layernorm"])
|
| 117 |
+
peft_config_2 = peft_config(modules_to_save=["1.post_attention_layernorm"])
|
| 118 |
+
|
| 119 |
+
# Save adapter 0, nothing fancy, should be equal to base model weighs
|
| 120 |
+
peft_model = get_peft_model(copy.deepcopy(original_model), peft_config_0)
|
| 121 |
+
peft_model.save_pretrained(tmp_path / "adapter_0")
|
| 122 |
+
|
| 123 |
+
# Save adapter 1, modules to save weights are modified randomly, should be unique to adapter 1
|
| 124 |
+
peft_model = get_peft_model(copy.deepcopy(original_model), peft_config_1)
|
| 125 |
+
peft_model.model.model.layers[0].post_attention_layernorm.weight.data = torch.rand_like(
|
| 126 |
+
peft_model.model.model.layers[0].post_attention_layernorm.weight.data
|
| 127 |
+
)
|
| 128 |
+
adapter_1_saved = peft_model.model.model.layers[0].post_attention_layernorm.weight.data.clone()
|
| 129 |
+
peft_model.save_pretrained(tmp_path / "adapter_1")
|
| 130 |
+
|
| 131 |
+
# Save adapter 2, modules to save weights are modified randomly, should be unique to adapter 2
|
| 132 |
+
peft_model = get_peft_model(copy.deepcopy(original_model), peft_config_2)
|
| 133 |
+
peft_model.model.model.layers[1].post_attention_layernorm.weight.data = torch.rand_like(
|
| 134 |
+
peft_model.model.model.layers[1].post_attention_layernorm.weight.data
|
| 135 |
+
)
|
| 136 |
+
adapter_2_saved = peft_model.model.model.layers[1].post_attention_layernorm.weight.data.clone()
|
| 137 |
+
peft_model.save_pretrained(tmp_path / "adapter_2")
|
| 138 |
+
|
| 139 |
+
del peft_model
|
| 140 |
+
|
| 141 |
+
combined_model = PeftModel.from_pretrained(original_model, tmp_path / "adapter_0", adapter_name="adapter_0")
|
| 142 |
+
combined_model.load_adapter(tmp_path / "adapter_1", adapter_name="adapter_1")
|
| 143 |
+
combined_model.load_adapter(tmp_path / "adapter_2", adapter_name="adapter_2")
|
| 144 |
+
|
| 145 |
+
# For adapter 0 we expect every mentioned modules to save layer of this test to be equal to the original model
|
| 146 |
+
# since we didn't modify it for adapter 0 and only adapter 0 is active.
|
| 147 |
+
combined_model.set_adapter("adapter_0")
|
| 148 |
+
assert torch.allclose(
|
| 149 |
+
combined_model.model.model.layers[0].post_attention_layernorm.weight,
|
| 150 |
+
original_model.model.layers[0].post_attention_layernorm.weight,
|
| 151 |
+
)
|
| 152 |
+
assert torch.allclose(
|
| 153 |
+
combined_model.model.model.layers[1].post_attention_layernorm.weight,
|
| 154 |
+
original_model.model.layers[1].post_attention_layernorm.weight,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# For adapter 1 we expect that the modified module to save 0.post_attention_layernorm is modified, the other
|
| 158 |
+
# module to save layers mentioned above should be untouched.
|
| 159 |
+
combined_model.set_adapter("adapter_1")
|
| 160 |
+
assert torch.allclose(
|
| 161 |
+
combined_model.model.model.layers[0].post_attention_layernorm.weight,
|
| 162 |
+
adapter_1_saved,
|
| 163 |
+
)
|
| 164 |
+
assert torch.allclose(
|
| 165 |
+
combined_model.model.model.layers[1].post_attention_layernorm.weight,
|
| 166 |
+
original_model.model.layers[1].post_attention_layernorm.weight,
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
# For adapter 2 we expect its module to save layer (1.post_attention_layernorm) to be modified but the other
|
| 170 |
+
# module to save weights should be kept original.
|
| 171 |
+
combined_model.set_adapter("adapter_2")
|
| 172 |
+
assert torch.allclose(
|
| 173 |
+
combined_model.model.model.layers[0].post_attention_layernorm.weight,
|
| 174 |
+
original_model.model.layers[0].post_attention_layernorm.weight,
|
| 175 |
+
)
|
| 176 |
+
assert torch.allclose(
|
| 177 |
+
combined_model.model.model.layers[1].post_attention_layernorm.weight,
|
| 178 |
+
adapter_2_saved,
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class TestModulesToSaveAttributeAccess:
|
| 183 |
+
"""Test attribute access on the ModulesToSaveWrapper class.
|
| 184 |
+
|
| 185 |
+
When we have modules_to_save, the original module is wrapped. As long as only forward was called on this wrapped
|
| 186 |
+
module, we were good. However, if, for instance, model parameters were directly accessed by another module, this
|
| 187 |
+
would typically fail, as the wrapper does not have this attribute. We had special properties for weight and bias,
|
| 188 |
+
but this is not enough. Therefore, attribute access is now transiently delegated to the active adapter (or original
|
| 189 |
+
module, if the adapter is disabled).
|
| 190 |
+
|
| 191 |
+
For one example, see #2099.
|
| 192 |
+
|
| 193 |
+
"""
|
| 194 |
+
|
| 195 |
+
@pytest.fixture
|
| 196 |
+
def mlp(self):
|
| 197 |
+
class MLP(nn.Module):
|
| 198 |
+
def __init__(self):
|
| 199 |
+
super().__init__()
|
| 200 |
+
self.lin0 = nn.Linear(1, 2)
|
| 201 |
+
self.lin1 = nn.Linear(3, 4)
|
| 202 |
+
|
| 203 |
+
return MLP()
|
| 204 |
+
|
| 205 |
+
def test_transient_attribute_access_default_adapter(self, mlp):
|
| 206 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 207 |
+
model = get_peft_model(mlp, config)
|
| 208 |
+
assert model.lin1.weight is model.lin1.modules_to_save["default"].weight
|
| 209 |
+
assert model.lin1.bias is model.lin1.modules_to_save["default"].bias
|
| 210 |
+
|
| 211 |
+
def test_transient_attribute_access_non_default_adapter(self, mlp):
|
| 212 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 213 |
+
model = get_peft_model(mlp, config)
|
| 214 |
+
model.add_adapter("other", config)
|
| 215 |
+
|
| 216 |
+
# at this point, default is still active
|
| 217 |
+
assert model.lin1.weight is model.lin1.modules_to_save["default"].weight
|
| 218 |
+
assert model.lin1.bias is model.lin1.modules_to_save["default"].bias
|
| 219 |
+
assert model.lin1.weight is not model.lin1.modules_to_save["other"].weight
|
| 220 |
+
assert model.lin1.bias is not model.lin1.modules_to_save["other"].bias
|
| 221 |
+
|
| 222 |
+
model.set_adapter("other")
|
| 223 |
+
assert model.lin1.weight is not model.lin1.modules_to_save["default"].weight
|
| 224 |
+
assert model.lin1.bias is not model.lin1.modules_to_save["default"].bias
|
| 225 |
+
assert model.lin1.weight is model.lin1.modules_to_save["other"].weight
|
| 226 |
+
assert model.lin1.bias is model.lin1.modules_to_save["other"].bias
|
| 227 |
+
|
| 228 |
+
def test_transient_attribute_access_disabled_adapter(self, mlp):
|
| 229 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 230 |
+
model = get_peft_model(mlp, config)
|
| 231 |
+
|
| 232 |
+
# at this point, default is still active
|
| 233 |
+
assert model.lin1.weight is model.lin1.modules_to_save["default"].weight
|
| 234 |
+
assert model.lin1.bias is model.lin1.modules_to_save["default"].bias
|
| 235 |
+
assert model.lin1.weight is not model.lin1.original_module.weight
|
| 236 |
+
assert model.lin1.bias is not model.lin1.original_module.bias
|
| 237 |
+
|
| 238 |
+
with model.disable_adapter():
|
| 239 |
+
assert model.lin1.weight is not model.lin1.modules_to_save["default"].weight
|
| 240 |
+
assert model.lin1.bias is not model.lin1.modules_to_save["default"].bias
|
| 241 |
+
assert model.lin1.weight is model.lin1.original_module.weight
|
| 242 |
+
assert model.lin1.bias is model.lin1.original_module.bias
|
| 243 |
+
|
| 244 |
+
def test_transient_attribute_access_uninitialized_adapter(self, mlp):
|
| 245 |
+
# ensure that there is no weird infinite recursion when accessing a non-existing attribute on the class itself
|
| 246 |
+
with pytest.raises(AttributeError, match="has no attribute 'original_module'"):
|
| 247 |
+
ModulesToSaveWrapper.original_module
|
| 248 |
+
|
| 249 |
+
def test_transient_attribute_access_attr_does_not_exist_on_modules_to_save(self, mlp):
|
| 250 |
+
# ensure that there is no weird infinite recursion when accessing a non-existing attribute on the
|
| 251 |
+
# ModelToSaveWrapper instance
|
| 252 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 253 |
+
model = get_peft_model(mlp, config)
|
| 254 |
+
|
| 255 |
+
with pytest.raises(AttributeError, match="has no attribute 'foo'"):
|
| 256 |
+
model.lin1.foo
|
| 257 |
+
|
| 258 |
+
def test_transient_attribute_access_attr_does_not_exist_on_original_module(self, mlp):
|
| 259 |
+
# ensure that there is no weird infinite recursion when accessing a non-existing attribute on the
|
| 260 |
+
# original module of the ModelToSaveWrapper instance
|
| 261 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 262 |
+
model = get_peft_model(mlp, config)
|
| 263 |
+
|
| 264 |
+
with pytest.raises(AttributeError, match="has no attribute 'foo'"):
|
| 265 |
+
with model.disable_adapter():
|
| 266 |
+
model.lin1.foo
|
| 267 |
+
|
| 268 |
+
def test_transient_attribute_access_non_existing_adapter(self, mlp):
|
| 269 |
+
# This should normally never happen, as the active adapter should always exist, but it's a failsafe
|
| 270 |
+
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
|
| 271 |
+
model = get_peft_model(mlp, config)
|
| 272 |
+
model.base_model.model.lin1._active_adapter = "does-not-exist"
|
| 273 |
+
with pytest.raises(AttributeError, match="has no attribute 'weight'"):
|
| 274 |
+
model.lin1.weight
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
class TestModulesToSaveNameSubstringBug:
|
| 278 |
+
"""Test a bug that could occur with multiple modules to save where one adapter's name is a substring of another
|
| 279 |
+
adapter's name.
|
| 280 |
+
|
| 281 |
+
This bug was the result of an error in the logic of modifying the state_dict for modules_to_save in
|
| 282 |
+
set_peft_model_state_dict. The error in the logic was that it was checked if an entry from modules_to_save (a set
|
| 283 |
+
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
|
| 284 |
+
state_dict, which would allow to load the weight later.
|
| 285 |
+
|
| 286 |
+
The issue that stems from the substring check occurs if there are multiple modules_to_save, and one of them has a
|
| 287 |
+
name that is a substring of another. So e.g. if one is named "classifier" and the other is named "classifier2",
|
| 288 |
+
there could be a false match.
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
This bug was reported in #2289.
|
| 292 |
+
|
| 293 |
+
"""
|
| 294 |
+
|
| 295 |
+
def get_model(self):
|
| 296 |
+
class MyModule(nn.Module):
|
| 297 |
+
def __init__(self):
|
| 298 |
+
super().__init__()
|
| 299 |
+
self.lin = nn.Linear(5, 4)
|
| 300 |
+
# important: "classifier" is a substring of "classifier2", "classifier3", "classifier4"
|
| 301 |
+
self.classifier = nn.Linear(4, 2)
|
| 302 |
+
self.classifier2 = nn.Linear(4, 2)
|
| 303 |
+
self.classifier3 = nn.Linear(4, 2)
|
| 304 |
+
self.classifier4 = nn.Linear(4, 2)
|
| 305 |
+
|
| 306 |
+
def forward(self, x):
|
| 307 |
+
x = self.lin(x)
|
| 308 |
+
return self.classifier(x) + self.classifier2(x) + self.classifier3(x) + self.classifier4(x)
|
| 309 |
+
|
| 310 |
+
torch.manual_seed(0)
|
| 311 |
+
return MyModule()
|
| 312 |
+
|
| 313 |
+
@pytest.fixture
|
| 314 |
+
def path_merged_and_unmerged(self, tmp_path):
|
| 315 |
+
# Create 2 checkpoints:
|
| 316 |
+
# 1. merged: the model after calling merge_and_unload
|
| 317 |
+
# 2. unmerged: the PEFT model saved without calling merge_and_unload
|
| 318 |
+
path = tmp_path / "model.pt"
|
| 319 |
+
|
| 320 |
+
lora_config = LoraConfig(
|
| 321 |
+
target_modules=["lin"],
|
| 322 |
+
# important: "classifier" is a substring of "classifier2", "classifier3", "classifier4"
|
| 323 |
+
modules_to_save=["classifier", "classifier2", "classifier3", "classifier4"],
|
| 324 |
+
)
|
| 325 |
+
model = get_peft_model(self.get_model(), lora_config)
|
| 326 |
+
# mock training
|
| 327 |
+
for _ in range(5):
|
| 328 |
+
optimizer = torch.optim.SGD(model.parameters(), lr=0.01)
|
| 329 |
+
output = model(torch.randn(10, 5))
|
| 330 |
+
loss = output.sum()
|
| 331 |
+
loss.backward()
|
| 332 |
+
optimizer.step()
|
| 333 |
+
|
| 334 |
+
# save the peft model without merging
|
| 335 |
+
path_unmerged = tmp_path / "unmerged"
|
| 336 |
+
model.save_pretrained(path_unmerged)
|
| 337 |
+
|
| 338 |
+
# merge the model and save state_dict
|
| 339 |
+
path_merged = tmp_path / "merged"
|
| 340 |
+
merged = model.merge_and_unload()
|
| 341 |
+
state_dict = merged.state_dict()
|
| 342 |
+
torch.save(state_dict, path_merged)
|
| 343 |
+
|
| 344 |
+
return path_merged, path_unmerged
|
| 345 |
+
|
| 346 |
+
def test_load_merged_and_unmerged_same_weights(self, path_merged_and_unmerged):
|
| 347 |
+
# Note that this test is quasi flaky, it has a 1 in 4 chance of passing even without the bugfix. It passes when
|
| 348 |
+
# "classifier" happens to be the last element of the set model.modules_to_save. The order of the set is random.
|
| 349 |
+
# It is not possible just run this test multiple times to minimize the probability of this happening, because
|
| 350 |
+
# within the same process, the hash order is consistent. With the bug fix, this doesn't matter, as the test will
|
| 351 |
+
# always pass, but if there is a regression, there is a 1 in 4 chance of not catching it. Since the CI runs many
|
| 352 |
+
# tests, it is overall very unlikely that none will catch it though. If you see this test failing in CI, thus be
|
| 353 |
+
# aware that some of the passing tests may just pass owing to randomness.
|
| 354 |
+
path_merged, path_unmerged = path_merged_and_unmerged
|
| 355 |
+
|
| 356 |
+
# load the merged model directly
|
| 357 |
+
state_dict = torch.load(path_merged, weights_only=True)
|
| 358 |
+
model = self.get_model()
|
| 359 |
+
model.load_state_dict(state_dict)
|
| 360 |
+
sd_merged = model.state_dict()
|
| 361 |
+
del model
|
| 362 |
+
|
| 363 |
+
# load the unmerged model and merge it
|
| 364 |
+
unmerged = PeftModel.from_pretrained(self.get_model(), path_unmerged)
|
| 365 |
+
sd_unmerged = unmerged.merge_and_unload().state_dict()
|
| 366 |
+
|
| 367 |
+
assert sd_merged.keys() == sd_unmerged.keys()
|
| 368 |
+
for key in sd_merged.keys():
|
| 369 |
+
param_merged = sd_merged[key]
|
| 370 |
+
param_unmerged = sd_unmerged[key]
|
| 371 |
+
assert torch.allclose(param_merged, param_unmerged)
|
| 372 |
+
|
| 373 |
+
|
| 374 |
+
class TestTargetingAuxiliaryTrainingWrapper:
|
| 375 |
+
"""AuxiliaryTrainingWrapper such as ModulesToSaveWrapper and TrainableTokensWrapper are
|
| 376 |
+
in general not to be targeted by PEFT methods such as adapters. For example, a ModulesToSaveWrapper's children
|
| 377 |
+
modules should not be targeted by `LoraConfig(target_modules='all-linear')`, among other things.
|
| 378 |
+
"""
|
| 379 |
+
|
| 380 |
+
@pytest.fixture
|
| 381 |
+
def plain_model_cls(self):
|
| 382 |
+
class PlainModel(nn.Module):
|
| 383 |
+
def __init__(self, i, o):
|
| 384 |
+
super().__init__()
|
| 385 |
+
self.layer1 = nn.Linear(i, o)
|
| 386 |
+
|
| 387 |
+
def forward(self, x):
|
| 388 |
+
return self.layer1(x)
|
| 389 |
+
|
| 390 |
+
return PlainModel
|
| 391 |
+
|
| 392 |
+
@pytest.fixture
|
| 393 |
+
def nested_model_cls(self, plain_model_cls):
|
| 394 |
+
class NestedModel(nn.Module):
|
| 395 |
+
def __init__(self):
|
| 396 |
+
super().__init__()
|
| 397 |
+
self.layer1 = nn.Linear(10, 20)
|
| 398 |
+
self.layer2 = nn.Linear(20, 5)
|
| 399 |
+
self.layer3 = plain_model_cls(5, 10)
|
| 400 |
+
|
| 401 |
+
def forward(self, x):
|
| 402 |
+
x = self.layer1(x)
|
| 403 |
+
x = self.layer2(x)
|
| 404 |
+
x = self.layer3(x)
|
| 405 |
+
return x
|
| 406 |
+
|
| 407 |
+
return NestedModel
|
| 408 |
+
|
| 409 |
+
def test_nested_ignores_modules_to_save(self, nested_model_cls, plain_model_cls):
|
| 410 |
+
# Make sure that `target_modules` is not targeting the nested modules of a module marked as module to save.
|
| 411 |
+
model = nested_model_cls()
|
| 412 |
+
config = LoraConfig(
|
| 413 |
+
target_modules=["layer1"],
|
| 414 |
+
modules_to_save=["layer3"],
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
peft_model = get_peft_model(model, config)
|
| 418 |
+
assert isinstance(peft_model.model.layer3.modules_to_save.default, plain_model_cls)
|
| 419 |
+
|
| 420 |
+
def test_targeting_module_to_save_raises(self, nested_model_cls):
|
| 421 |
+
model = nested_model_cls()
|
| 422 |
+
config = LoraConfig(
|
| 423 |
+
target_modules=["layer1"],
|
| 424 |
+
modules_to_save=["layer1"],
|
| 425 |
+
)
|
| 426 |
+
msg = "No modules were targeted for adaptation. This might be caused by a combination"
|
| 427 |
+
with pytest.raises(ValueError, match=msg):
|
| 428 |
+
get_peft_model(model, config)
|
| 429 |
+
|
| 430 |
+
def test_modules_to_save_targets_tuner_layer_raises(self):
|
| 431 |
+
# See e.g. issue 2027 and 2477
|
| 432 |
+
# Prevent users from (accidentally) targeting the same layer both with a tuner and modules_to_save. Normally, PEFT
|
| 433 |
+
# will not target the same layer with both a tuner and ModulesToSaveWrapper. However, if modules_to_save is
|
| 434 |
+
# automatically inferred, e.g. when using AutoModelForSequenceClassification, the ModulesToSaveWrapper is applied ex
|
| 435 |
+
# post, which can lead to the double wrapping.
|
| 436 |
+
model_id = "peft-internal-testing/tiny-random-OPTForCausalLM"
|
| 437 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id)
|
| 438 |
+
|
| 439 |
+
# Note: target_modules="all-linear" would also work and is closer to the original issue, but let's explicitly target
|
| 440 |
+
# "score" here in case that "all-linear" will be fixed to no longer target the score layer.
|
| 441 |
+
peft_config = LoraConfig(target_modules=["score"], task_type="SEQ_CLS")
|
| 442 |
+
|
| 443 |
+
# Since the `score` layer is in `model.modules_to_save` it should be ignored when targeted,
|
| 444 |
+
# therefore the layer should not be adapted.
|
| 445 |
+
msg = "No modules were targeted for adaptation. This might be caused by a combination"
|
| 446 |
+
with pytest.raises(ValueError, match=msg) as e:
|
| 447 |
+
get_peft_model(model, peft_config)
|
| 448 |
+
|
| 449 |
+
def test_targeting_trainable_tokens_raises(self):
|
| 450 |
+
model_id = "peft-internal-testing/tiny-random-OPTForCausalLM"
|
| 451 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_id)
|
| 452 |
+
|
| 453 |
+
peft_config = LoraConfig(target_modules=["embed_tokens"], task_type="SEQ_CLS", trainable_token_indices=[0, 1])
|
| 454 |
+
|
| 455 |
+
# While this message might not be the most helpful message, at least it is not silently failing
|
| 456 |
+
msg = "trainable_token_indices cannot be applied to modules of type <class 'peft.tuners.lora.layer.Embedding'>"
|
| 457 |
+
with pytest.raises(TypeError, match=msg) as e:
|
| 458 |
+
get_peft_model(model, peft_config)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
class TestAdapterTargeting:
|
| 462 |
+
"""Make sure that already existing adapters cannot be targeted to avoid conflicts."""
|
| 463 |
+
|
| 464 |
+
@pytest.fixture
|
| 465 |
+
def base_model_cls(self):
|
| 466 |
+
class M(torch.nn.Module):
|
| 467 |
+
def __init__(self):
|
| 468 |
+
super().__init__()
|
| 469 |
+
self.l1 = torch.nn.Linear(10, 20)
|
| 470 |
+
self.l2 = torch.nn.Conv2d(1, 1, 2)
|
| 471 |
+
|
| 472 |
+
def forward(self, x):
|
| 473 |
+
return self.l2(self.l1(x))
|
| 474 |
+
|
| 475 |
+
return M
|
| 476 |
+
|
| 477 |
+
@pytest.mark.parametrize(
|
| 478 |
+
"config_cls, config_kwargs",
|
| 479 |
+
[
|
| 480 |
+
(LoraConfig, {"target_modules": "l1.*"}),
|
| 481 |
+
(LoraConfig, {"target_modules": "l2.*"}),
|
| 482 |
+
(VeraConfig, {"target_modules": "l1.*"}),
|
| 483 |
+
(VeraConfig, {"target_modules": "(l1|vera_A).*"}), # also target the shared layer
|
| 484 |
+
],
|
| 485 |
+
)
|
| 486 |
+
def test_self_targeting_is_ignored(self, base_model_cls, config_cls, config_kwargs):
|
| 487 |
+
base_model = base_model_cls()
|
| 488 |
+
config1 = config_cls(**config_kwargs)
|
| 489 |
+
config2 = config_cls(**config_kwargs)
|
| 490 |
+
|
| 491 |
+
adapter1_name = "ADAPTER_1_512858" # sufficiently unique names to make reliable testing easier
|
| 492 |
+
adapter2_name = "ADAPTER_2_845781"
|
| 493 |
+
|
| 494 |
+
peft_model = get_peft_model(base_model, config1, adapter_name=adapter1_name)
|
| 495 |
+
state_dict_keys_1 = peft_model.state_dict().keys()
|
| 496 |
+
|
| 497 |
+
peft_model.add_adapter(adapter2_name, config2)
|
| 498 |
+
state_dict_keys_2 = peft_model.state_dict().keys()
|
| 499 |
+
|
| 500 |
+
# Ideally there should be no new modules targeted beyond existing ModuleDicts. Therefore the keys
|
| 501 |
+
# of the new state dict should only differ after the adapter name portion of the keys - not before.
|
| 502 |
+
# Expected:
|
| 503 |
+
# - a.b.<adapter_name_1>.xyz
|
| 504 |
+
# - a.b.<adapter_name_2>.xyz
|
| 505 |
+
# We're not expecting this to happen and test against it:
|
| 506 |
+
# - a.b.<adapter_name_1>.xyz
|
| 507 |
+
# - a.<adapter_name_2>.xyz
|
| 508 |
+
def remove_adapter_portion(adapter_name, key):
|
| 509 |
+
if key.endswith(f".{adapter_name}"):
|
| 510 |
+
return key.removesuffix(f".{adapter_name}")
|
| 511 |
+
return key.split(f".{adapter_name}.")[0]
|
| 512 |
+
|
| 513 |
+
adapter_invariant_keys1 = {remove_adapter_portion(adapter1_name, key) for key in state_dict_keys_1}
|
| 514 |
+
adapter_invariant_keys2 = {
|
| 515 |
+
remove_adapter_portion(adapter2_name, remove_adapter_portion(adapter1_name, key))
|
| 516 |
+
for key in state_dict_keys_2
|
| 517 |
+
}
|
| 518 |
+
|
| 519 |
+
assert adapter_invariant_keys1 == adapter_invariant_keys2
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
class TestGetNoSplitModules:
|
| 523 |
+
# Ensure that children are considered when determining _no_split_modules
|
| 524 |
+
# see https://github.com/huggingface/transformers/pull/38141
|
| 525 |
+
|
| 526 |
+
def test_get_no_split_modules_simple(self):
|
| 527 |
+
# choose a model where recursively visiting children is *not* required
|
| 528 |
+
model_id = "peft-internal-testing/opt-125m"
|
| 529 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 530 |
+
assert list(model._no_split_modules) == ["OPTDecoderLayer"]
|
| 531 |
+
no_split_modules = _get_no_split_modules(model)
|
| 532 |
+
assert no_split_modules == {"OPTDecoderLayer"}
|
| 533 |
+
|
| 534 |
+
def test_get_no_split_modules_recursive(self):
|
| 535 |
+
# choose a model where recursively visiting children is required
|
| 536 |
+
model_id = "hf-internal-testing/tiny-random-LlavaForConditionalGeneration"
|
| 537 |
+
model = LlavaForConditionalGeneration.from_pretrained(model_id)
|
| 538 |
+
|
| 539 |
+
# model._no_split_modules is recursively generated as of transformers 5.1.0 so
|
| 540 |
+
# depending on which transformers version we have in the test environment the
|
| 541 |
+
# attribute will deliver either the same result as `_get_no_split_modules`
|
| 542 |
+
# or an empty list.
|
| 543 |
+
#
|
| 544 |
+
# TODO remove this distinction once transformers <5.1.0 is not supported anymore
|
| 545 |
+
if not is_transformers_ge_v5_1_0:
|
| 546 |
+
# sanity check: just visiting the model itself is not enough:
|
| 547 |
+
assert model._no_split_modules == []
|
| 548 |
+
else:
|
| 549 |
+
assert model._no_split_modules == {"CLIPEncoderLayer", "LlamaDecoderLayer"}
|
| 550 |
+
|
| 551 |
+
no_split_modules = _get_no_split_modules(model)
|
| 552 |
+
assert no_split_modules == {"CLIPEncoderLayer", "LlamaDecoderLayer"}
|
| 553 |
+
|
| 554 |
+
|
| 555 |
+
class TestGetModuleNamesTiedWithEmbedding:
|
| 556 |
+
# TODO remove mapping when transformers <5 is not supported anymore as it is the default
|
| 557 |
+
# from there on. also remove the 'list' tied weights type
|
| 558 |
+
model_tied_weights_mapping = {
|
| 559 |
+
"peft-internal-testing/tiny-random-BertModel": {
|
| 560 |
+
"cls.predictions.decoder.weight": "bert.embeddings.word_embeddings.weight",
|
| 561 |
+
"cls.predictions.decoder.bias": "bert.embeddings.word_embeddings.bias",
|
| 562 |
+
},
|
| 563 |
+
"peft-internal-testing/opt-125m": {
|
| 564 |
+
"lm_head.weight": "model.decoder.embed_tokens.weight",
|
| 565 |
+
},
|
| 566 |
+
"peft-internal-testing/tiny-random-t5": {
|
| 567 |
+
"lm_head.weight": "shared.weight",
|
| 568 |
+
"encoder.embed_tokens.weight": "shared.weight",
|
| 569 |
+
"decoder.embed_tokens.weight": "shared.weight",
|
| 570 |
+
},
|
| 571 |
+
}
|
| 572 |
+
|
| 573 |
+
model_ids = [
|
| 574 |
+
"peft-internal-testing/opt-125m",
|
| 575 |
+
"peft-internal-testing/tiny-random-BertModel",
|
| 576 |
+
"peft-internal-testing/tiny-random-t5",
|
| 577 |
+
]
|
| 578 |
+
|
| 579 |
+
@contextmanager
|
| 580 |
+
def patch_model(self, model_id, tied_weights_type):
|
| 581 |
+
with hub_online_once(model_id):
|
| 582 |
+
if "t5" in model_id:
|
| 583 |
+
model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
| 584 |
+
else:
|
| 585 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 586 |
+
|
| 587 |
+
tied_weights_keys = list(self.model_tied_weights_mapping[model_id].keys())
|
| 588 |
+
expected_module_names = sorted({k.rpartition(".")[0] for k in tied_weights_keys})
|
| 589 |
+
|
| 590 |
+
if tied_weights_type == "list":
|
| 591 |
+
# for transformers >=5 this tests compatibility with transformers <5
|
| 592 |
+
with patch.object(model, "_tied_weights_keys", list(tied_weights_keys)):
|
| 593 |
+
yield model, expected_module_names
|
| 594 |
+
|
| 595 |
+
elif tied_weights_type == "mapping":
|
| 596 |
+
# for transformers <5 this tests compatibility with transformers >=5
|
| 597 |
+
mapping = self.model_tied_weights_mapping[model_id]
|
| 598 |
+
|
| 599 |
+
with patch.object(model, "_tied_weights_keys", mapping):
|
| 600 |
+
yield model, expected_module_names
|
| 601 |
+
|
| 602 |
+
else:
|
| 603 |
+
raise RuntimeError("Invalid fixture request")
|
| 604 |
+
|
| 605 |
+
@pytest.mark.parametrize("tied_weights_type", ["list", "mapping"])
|
| 606 |
+
@pytest.mark.parametrize("model_id", model_ids)
|
| 607 |
+
def test_get_modules_tied_to_embedding(self, model_id, tied_weights_type):
|
| 608 |
+
with self.patch_model(model_id, tied_weights_type) as (model, expected):
|
| 609 |
+
if tied_weights_type == "mapping":
|
| 610 |
+
assert isinstance(model._tied_weights_keys, dict)
|
| 611 |
+
|
| 612 |
+
# transformers defines the bias as tied even if it doesn't exist, filter out in that case
|
| 613 |
+
if not hasattr(model.get_input_embeddings(), "bias"):
|
| 614 |
+
expected = list(filter(lambda k: "bias" not in k, expected))
|
| 615 |
+
|
| 616 |
+
modules = _get_module_names_tied_with_embedding(model)
|
| 617 |
+
|
| 618 |
+
assert expected == modules
|
| 619 |
+
|
| 620 |
+
@pytest.mark.parametrize("tied_weights_type", ["list", "mapping"])
|
| 621 |
+
@pytest.mark.parametrize("model_id", model_ids)
|
| 622 |
+
def test_get_modules_tied_to_embedding_peft(self, model_id, tied_weights_type):
|
| 623 |
+
with self.patch_model(model_id, tied_weights_type) as (model, expected):
|
| 624 |
+
if tied_weights_type == "mapping":
|
| 625 |
+
assert isinstance(model._tied_weights_keys, dict)
|
| 626 |
+
|
| 627 |
+
# transformers defines the bias as tied even if it doesn't exist, filter out in that case
|
| 628 |
+
if not hasattr(model.get_input_embeddings(), "bias"):
|
| 629 |
+
expected = list(filter(lambda k: "bias" not in k, expected))
|
| 630 |
+
|
| 631 |
+
peft_model = get_peft_model(model, LoraConfig())
|
| 632 |
+
|
| 633 |
+
modules = peft_model._get_module_names_tied_with_embedding()
|
| 634 |
+
|
| 635 |
+
assert expected == modules
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
# TODO for PEFT 0.20 remove this
|
| 639 |
+
class TestLoftQDeprecation:
|
| 640 |
+
def test_nfquantizer_deprecation(self):
|
| 641 |
+
from peft.utils.loftq_utils import NFQuantizer
|
| 642 |
+
|
| 643 |
+
with pytest.warns(match="NFQuantizer is deprecated") as record:
|
| 644 |
+
_ = NFQuantizer(device="cpu")
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_poly.py
ADDED
|
@@ -0,0 +1,103 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
from .testing_utils import hub_online_once
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class TestPoly(unittest.TestCase):
|
| 31 |
+
def test_poly(self):
|
| 32 |
+
torch.manual_seed(0)
|
| 33 |
+
model_name_or_path = "google/flan-t5-small"
|
| 34 |
+
|
| 35 |
+
with hub_online_once(model_name_or_path):
|
| 36 |
+
atol, rtol = 1e-6, 1e-6
|
| 37 |
+
r = 8 # rank of lora in poly
|
| 38 |
+
n_tasks = 3 # number of tasks
|
| 39 |
+
n_skills = 2 # number of skills (loras)
|
| 40 |
+
n_splits = 4 # number of heads
|
| 41 |
+
lr = 1e-2
|
| 42 |
+
num_epochs = 10
|
| 43 |
+
|
| 44 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name_or_path)
|
| 45 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
|
| 46 |
+
|
| 47 |
+
peft_config = PolyConfig(
|
| 48 |
+
task_type=TaskType.SEQ_2_SEQ_LM,
|
| 49 |
+
poly_type="poly",
|
| 50 |
+
r=r,
|
| 51 |
+
n_tasks=n_tasks,
|
| 52 |
+
n_skills=n_skills,
|
| 53 |
+
n_splits=n_splits,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
model = get_peft_model(base_model, peft_config)
|
| 57 |
+
|
| 58 |
+
# generate some dummy data
|
| 59 |
+
text = os.__doc__.splitlines()
|
| 60 |
+
assert len(text) > 10
|
| 61 |
+
inputs = tokenizer(text, return_tensors="pt", padding=True)
|
| 62 |
+
inputs["task_ids"] = torch.arange(len(text)) % n_tasks
|
| 63 |
+
inputs["labels"] = tokenizer((["A", "B"] * 100)[: len(text)], return_tensors="pt")["input_ids"]
|
| 64 |
+
|
| 65 |
+
# simple training loop
|
| 66 |
+
model.train()
|
| 67 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
|
| 68 |
+
losses = []
|
| 69 |
+
for _ in range(num_epochs):
|
| 70 |
+
outputs = model(**inputs)
|
| 71 |
+
loss = outputs.loss
|
| 72 |
+
loss.backward()
|
| 73 |
+
optimizer.step()
|
| 74 |
+
optimizer.zero_grad()
|
| 75 |
+
losses.append(loss.item())
|
| 76 |
+
|
| 77 |
+
# loss improved by at least 50%
|
| 78 |
+
assert losses[-1] < (0.5 * losses[0])
|
| 79 |
+
|
| 80 |
+
# check that saving and loading works
|
| 81 |
+
torch.manual_seed(0)
|
| 82 |
+
model.eval()
|
| 83 |
+
logits_before = model(**inputs).logits
|
| 84 |
+
tokens_before = model.generate(**inputs)
|
| 85 |
+
|
| 86 |
+
with model.disable_adapter():
|
| 87 |
+
logits_disabled = model(**inputs).logits
|
| 88 |
+
tokens_disabled = model.generate(**inputs)
|
| 89 |
+
|
| 90 |
+
assert not torch.allclose(logits_before, logits_disabled, atol=atol, rtol=rtol)
|
| 91 |
+
assert not torch.allclose(tokens_before, tokens_disabled, atol=atol, rtol=rtol)
|
| 92 |
+
|
| 93 |
+
# saving and loading
|
| 94 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 95 |
+
model.save_pretrained(tmp_dir)
|
| 96 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(model_name_or_path)
|
| 97 |
+
loaded = PeftModel.from_pretrained(base_model, tmp_dir)
|
| 98 |
+
|
| 99 |
+
torch.manual_seed(0)
|
| 100 |
+
output_after = loaded(**inputs).logits
|
| 101 |
+
tokens_after = loaded.generate(**inputs)
|
| 102 |
+
assert torch.allclose(logits_before, output_after, atol=atol, rtol=rtol)
|
| 103 |
+
assert torch.allclose(tokens_before, tokens_after, atol=atol, rtol=rtol)
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_pvera.py
ADDED
|
@@ -0,0 +1,244 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 based on the VeRA test file, since both methods are very close.
|
| 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, PveraConfig, 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 TestPVeRA:
|
| 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 = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 62 |
+
# creates a default PVeRA adapter
|
| 63 |
+
peft_model = get_peft_model(mlp, config)
|
| 64 |
+
config2 = PveraConfig(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.pvera_A["default"]
|
| 72 |
+
is mlp_same_prng.base_model.model.lin1.pvera_A["other"]
|
| 73 |
+
)
|
| 74 |
+
assert (
|
| 75 |
+
mlp_same_prng.base_model.model.lin1.pvera_B["default"]
|
| 76 |
+
is mlp_same_prng.base_model.model.lin1.pvera_B["other"]
|
| 77 |
+
)
|
| 78 |
+
assert (
|
| 79 |
+
mlp_same_prng.base_model.model.lin2.pvera_A["default"]
|
| 80 |
+
is mlp_same_prng.base_model.model.lin2.pvera_A["other"]
|
| 81 |
+
)
|
| 82 |
+
assert (
|
| 83 |
+
mlp_same_prng.base_model.model.lin2.pvera_B["default"]
|
| 84 |
+
is mlp_same_prng.base_model.model.lin2.pvera_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 = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 98 |
+
# creates a default PVeRA adapter
|
| 99 |
+
peft_model = get_peft_model(model, config)
|
| 100 |
+
config2 = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False, projection_prng_key=123)
|
| 101 |
+
|
| 102 |
+
msg = (
|
| 103 |
+
r"PVeRA 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_false(self, mlp, tmp_path):
|
| 110 |
+
# check saving and loading works with multiple adapters without saved projection weights
|
| 111 |
+
torch.manual_seed(1)
|
| 112 |
+
config = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 113 |
+
# creates a default PVeRA adapter
|
| 114 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 115 |
+
config2 = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 116 |
+
peft_model.add_adapter("second", config2)
|
| 117 |
+
peft_model.eval()
|
| 118 |
+
|
| 119 |
+
input = torch.randn(5, 10)
|
| 120 |
+
peft_model.set_adapter("first")
|
| 121 |
+
output_first = peft_model(input)
|
| 122 |
+
peft_model.set_adapter("second")
|
| 123 |
+
output_second = peft_model(input)
|
| 124 |
+
|
| 125 |
+
# sanity check
|
| 126 |
+
assert not torch.allclose(output_first, output_second, atol=1e-3, rtol=1e-3)
|
| 127 |
+
|
| 128 |
+
save_path = tmp_path / "pvera"
|
| 129 |
+
peft_model.save_pretrained(save_path)
|
| 130 |
+
assert os.path.exists(save_path / "first" / "adapter_config.json")
|
| 131 |
+
assert os.path.exists(save_path / "second" / "adapter_config.json")
|
| 132 |
+
|
| 133 |
+
torch.manual_seed(0)
|
| 134 |
+
mlp = MLP()
|
| 135 |
+
peft_model = PeftModel.from_pretrained(mlp, save_path / "first", adapter_name="first")
|
| 136 |
+
peft_model.load_adapter(save_path / "second", "second")
|
| 137 |
+
peft_model.eval()
|
| 138 |
+
|
| 139 |
+
peft_model.set_adapter("first")
|
| 140 |
+
output_first_loaded = peft_model(input)
|
| 141 |
+
peft_model.set_adapter("second")
|
| 142 |
+
output_second_loaded = peft_model(input)
|
| 143 |
+
|
| 144 |
+
assert torch.allclose(output_first, output_first_loaded, atol=1e-3, rtol=1e-3)
|
| 145 |
+
assert torch.allclose(output_second, output_second_loaded, atol=1e-3, rtol=1e-3)
|
| 146 |
+
|
| 147 |
+
def test_multiple_adapters_save_projection_false_contains_no_pvera_A_pvera_B(self, mlp, tmp_path):
|
| 148 |
+
torch.manual_seed(1)
|
| 149 |
+
config = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 150 |
+
# creates a default PVeRA adapter
|
| 151 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 152 |
+
config2 = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 153 |
+
peft_model.add_adapter("second", config2)
|
| 154 |
+
|
| 155 |
+
save_path = tmp_path / "pvera"
|
| 156 |
+
peft_model.save_pretrained(save_path)
|
| 157 |
+
|
| 158 |
+
sd_default = {}
|
| 159 |
+
with safe_open(save_path / "first" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 160 |
+
for key in f.keys():
|
| 161 |
+
sd_default[key] = f.get_tensor(key)
|
| 162 |
+
|
| 163 |
+
assert not any("pvera_A" in key for key in sd_default)
|
| 164 |
+
assert not any("pvera_B" in key for key in sd_default)
|
| 165 |
+
|
| 166 |
+
sd_other = {}
|
| 167 |
+
with safe_open(save_path / "second" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 168 |
+
for key in f.keys():
|
| 169 |
+
sd_other[key] = f.get_tensor(key)
|
| 170 |
+
|
| 171 |
+
assert not any("pvera_A" in key for key in sd_other)
|
| 172 |
+
assert not any("pvera_B" in key for key in sd_other)
|
| 173 |
+
|
| 174 |
+
def test_pvera_A_pvera_B_share_memory(self, mlp_same_prng):
|
| 175 |
+
pvera_A = mlp_same_prng.pvera_A["default"]
|
| 176 |
+
pvera_B = mlp_same_prng.pvera_B["default"]
|
| 177 |
+
|
| 178 |
+
# these tensors should share the same data
|
| 179 |
+
assert pvera_A.data_ptr() == mlp_same_prng.base_model.model.lin1.pvera_A["default"].data_ptr()
|
| 180 |
+
assert pvera_B.data_ptr() == mlp_same_prng.base_model.model.lin1.pvera_B["default"].data_ptr()
|
| 181 |
+
assert pvera_A.data_ptr() == mlp_same_prng.base_model.model.lin2.pvera_A["default"].data_ptr()
|
| 182 |
+
assert pvera_B.data_ptr() == mlp_same_prng.base_model.model.lin2.pvera_B["default"].data_ptr()
|
| 183 |
+
# sanity check: these tensors shouldn't share the same data
|
| 184 |
+
assert pvera_A.data_ptr() != pvera_B.data_ptr()
|
| 185 |
+
|
| 186 |
+
def test_pvera_lambda_dont_share_memory(self, mlp_same_prng):
|
| 187 |
+
# sanity check: these tensors shouldn't share the same data
|
| 188 |
+
assert (
|
| 189 |
+
mlp_same_prng.base_model.model.lin1.pvera_lambda_b["default"].data_ptr()
|
| 190 |
+
!= mlp_same_prng.base_model.model.lin1.pvera_lambda_b["other"].data_ptr()
|
| 191 |
+
)
|
| 192 |
+
assert (
|
| 193 |
+
mlp_same_prng.base_model.model.lin1.pvera_lambda_b["default"].data_ptr()
|
| 194 |
+
!= mlp_same_prng.base_model.model.lin2.pvera_lambda_b["default"].data_ptr()
|
| 195 |
+
)
|
| 196 |
+
assert (
|
| 197 |
+
mlp_same_prng.base_model.model.lin1.pvera_lambda_b["other"].data_ptr()
|
| 198 |
+
!= mlp_same_prng.base_model.model.lin2.pvera_lambda_b["other"].data_ptr()
|
| 199 |
+
)
|
| 200 |
+
assert (
|
| 201 |
+
mlp_same_prng.base_model.model.lin1.pvera_lambda_d["default"].data_ptr()
|
| 202 |
+
!= mlp_same_prng.base_model.model.lin1.pvera_lambda_d["other"].data_ptr()
|
| 203 |
+
)
|
| 204 |
+
assert (
|
| 205 |
+
mlp_same_prng.base_model.model.lin1.pvera_lambda_d["default"].data_ptr()
|
| 206 |
+
!= mlp_same_prng.base_model.model.lin2.pvera_lambda_d["default"].data_ptr()
|
| 207 |
+
)
|
| 208 |
+
assert (
|
| 209 |
+
mlp_same_prng.base_model.model.lin1.pvera_lambda_d["other"].data_ptr()
|
| 210 |
+
!= mlp_same_prng.base_model.model.lin2.pvera_lambda_d["other"].data_ptr()
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
def test_pvera_different_shapes(self, mlp):
|
| 214 |
+
config = PveraConfig(target_modules=["lin0", "lin3"], init_weights=False)
|
| 215 |
+
mlp_different_shapes = get_peft_model(mlp, config)
|
| 216 |
+
|
| 217 |
+
pvera_A = mlp_different_shapes.pvera_A["default"]
|
| 218 |
+
pvera_B = mlp_different_shapes.pvera_B["default"]
|
| 219 |
+
|
| 220 |
+
# sanity check
|
| 221 |
+
assert mlp.lin0.base_layer.weight.shape != mlp.lin3.base_layer.weight.shape
|
| 222 |
+
|
| 223 |
+
# lin0 has the largest output dimension, lin3 has the largest input dimension
|
| 224 |
+
# pvera_A should have the shape of (rank*2, largest_in), pvera_B should have the shape of (largest_out, rank)
|
| 225 |
+
assert pvera_A.shape == (config.r * 2, mlp.lin3.in_features)
|
| 226 |
+
assert pvera_B.shape == (mlp.lin0.out_features, config.r)
|
| 227 |
+
|
| 228 |
+
# should not raise
|
| 229 |
+
input = torch.randn(5, 10)
|
| 230 |
+
mlp_different_shapes(input)
|
| 231 |
+
|
| 232 |
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
| 233 |
+
def test_pvera_dtypes(self, dtype):
|
| 234 |
+
if dtype == torch.bfloat16:
|
| 235 |
+
# skip if bf16 is not supported on hardware, see #1872
|
| 236 |
+
if not is_bf16_available():
|
| 237 |
+
pytest.skip("bfloat16 not supported on this system, skipping the test")
|
| 238 |
+
|
| 239 |
+
model = MLP().to(dtype)
|
| 240 |
+
config = PveraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 241 |
+
peft_model = get_peft_model(model, config)
|
| 242 |
+
inputs = torch.randn(5, 10).to(dtype)
|
| 243 |
+
output = peft_model(inputs) # should not raise
|
| 244 |
+
assert output.dtype == dtype
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_randlora.py
ADDED
|
@@ -0,0 +1,245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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_false(self, mlp, tmp_path):
|
| 113 |
+
# check saving and loading works with multiple adapters without saved projection weights
|
| 114 |
+
torch.manual_seed(1)
|
| 115 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 116 |
+
# creates a default RandLora adapter
|
| 117 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 118 |
+
config2 = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 119 |
+
peft_model.add_adapter("second", config2)
|
| 120 |
+
|
| 121 |
+
input = torch.randn(5, 10)
|
| 122 |
+
peft_model.set_adapter("first")
|
| 123 |
+
output_first = peft_model(input)
|
| 124 |
+
peft_model.set_adapter("second")
|
| 125 |
+
output_second = peft_model(input)
|
| 126 |
+
|
| 127 |
+
# sanity check
|
| 128 |
+
assert not torch.allclose(output_first, output_second, atol=1e-3, rtol=1e-3)
|
| 129 |
+
|
| 130 |
+
save_path = tmp_path / "randlora"
|
| 131 |
+
peft_model.save_pretrained(save_path)
|
| 132 |
+
assert os.path.exists(save_path / "first" / "adapter_config.json")
|
| 133 |
+
assert os.path.exists(save_path / "second" / "adapter_config.json")
|
| 134 |
+
|
| 135 |
+
torch.manual_seed(0)
|
| 136 |
+
mlp = MLP()
|
| 137 |
+
peft_model = PeftModel.from_pretrained(mlp, save_path / "first", adapter_name="first")
|
| 138 |
+
peft_model.load_adapter(save_path / "second", "second")
|
| 139 |
+
|
| 140 |
+
peft_model.set_adapter("first")
|
| 141 |
+
output_first_loaded = peft_model(input)
|
| 142 |
+
peft_model.set_adapter("second")
|
| 143 |
+
output_second_loaded = peft_model(input)
|
| 144 |
+
|
| 145 |
+
assert torch.allclose(output_first, output_first_loaded, atol=1e-3, rtol=1e-3)
|
| 146 |
+
assert torch.allclose(output_second, output_second_loaded, atol=1e-3, rtol=1e-3)
|
| 147 |
+
|
| 148 |
+
def test_multiple_adapters_save_projection_false_contains_no_randlora_A_randlora_B(self, mlp, tmp_path):
|
| 149 |
+
torch.manual_seed(1)
|
| 150 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 151 |
+
# creates a default RandLora adapter
|
| 152 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 153 |
+
config2 = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 154 |
+
peft_model.add_adapter("second", config2)
|
| 155 |
+
|
| 156 |
+
save_path = tmp_path / "randlora"
|
| 157 |
+
peft_model.save_pretrained(save_path)
|
| 158 |
+
|
| 159 |
+
sd_default = {}
|
| 160 |
+
with safe_open(save_path / "first" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 161 |
+
for key in f.keys():
|
| 162 |
+
sd_default[key] = f.get_tensor(key)
|
| 163 |
+
|
| 164 |
+
assert not any("randlora_A" in key for key in sd_default)
|
| 165 |
+
assert not any("randlora_B" in key for key in sd_default)
|
| 166 |
+
|
| 167 |
+
sd_other = {}
|
| 168 |
+
with safe_open(save_path / "second" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 169 |
+
for key in f.keys():
|
| 170 |
+
sd_other[key] = f.get_tensor(key)
|
| 171 |
+
|
| 172 |
+
assert not any("randlora_A" in key for key in sd_other)
|
| 173 |
+
assert not any("randlora_B" in key for key in sd_other)
|
| 174 |
+
|
| 175 |
+
def test_randlora_A_randlora_B_share_memory(self, mlp_same_prng):
|
| 176 |
+
randlora_A = mlp_same_prng.randlora_A["default"]
|
| 177 |
+
randlora_B = mlp_same_prng.randlora_B["default"]
|
| 178 |
+
|
| 179 |
+
# these tensors should share the same data
|
| 180 |
+
assert randlora_A.data_ptr() == mlp_same_prng.base_model.model.lin1.randlora_A["default"].data_ptr()
|
| 181 |
+
assert randlora_B.data_ptr() == mlp_same_prng.base_model.model.lin1.randlora_B["default"].data_ptr()
|
| 182 |
+
assert randlora_A.data_ptr() == mlp_same_prng.base_model.model.lin2.randlora_A["default"].data_ptr()
|
| 183 |
+
assert randlora_B.data_ptr() == mlp_same_prng.base_model.model.lin2.randlora_B["default"].data_ptr()
|
| 184 |
+
# sanity check: these tensors shouldn't share the same data
|
| 185 |
+
assert randlora_A.data_ptr() != randlora_B.data_ptr()
|
| 186 |
+
|
| 187 |
+
def test_randlora_lambda_dont_share_memory(self, mlp_same_prng):
|
| 188 |
+
# sanity check: these tensors shouldn't share the same data
|
| 189 |
+
assert (
|
| 190 |
+
mlp_same_prng.base_model.model.lin1.randlora_lambda["default"].data_ptr()
|
| 191 |
+
!= mlp_same_prng.base_model.model.lin1.randlora_lambda["other"].data_ptr()
|
| 192 |
+
)
|
| 193 |
+
assert (
|
| 194 |
+
mlp_same_prng.base_model.model.lin1.randlora_lambda["default"].data_ptr()
|
| 195 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_lambda["default"].data_ptr()
|
| 196 |
+
)
|
| 197 |
+
assert (
|
| 198 |
+
mlp_same_prng.base_model.model.lin1.randlora_lambda["other"].data_ptr()
|
| 199 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_lambda["other"].data_ptr()
|
| 200 |
+
)
|
| 201 |
+
assert (
|
| 202 |
+
mlp_same_prng.base_model.model.lin1.randlora_gamma["default"].data_ptr()
|
| 203 |
+
!= mlp_same_prng.base_model.model.lin1.randlora_gamma["other"].data_ptr()
|
| 204 |
+
)
|
| 205 |
+
assert (
|
| 206 |
+
mlp_same_prng.base_model.model.lin1.randlora_gamma["default"].data_ptr()
|
| 207 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_gamma["default"].data_ptr()
|
| 208 |
+
)
|
| 209 |
+
assert (
|
| 210 |
+
mlp_same_prng.base_model.model.lin1.randlora_gamma["other"].data_ptr()
|
| 211 |
+
!= mlp_same_prng.base_model.model.lin2.randlora_gamma["other"].data_ptr()
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
def test_randlora_different_shapes(self, mlp):
|
| 215 |
+
config = RandLoraConfig(target_modules=["lin0", "lin3"], init_weights=False)
|
| 216 |
+
mlp_different_shapes = get_peft_model(mlp, config)
|
| 217 |
+
|
| 218 |
+
randlora_A = mlp_different_shapes.randlora_A["default"]
|
| 219 |
+
randlora_B = mlp_different_shapes.randlora_B["default"]
|
| 220 |
+
|
| 221 |
+
# sanity check
|
| 222 |
+
assert mlp.lin0.base_layer.weight.shape != mlp.lin3.base_layer.weight.shape
|
| 223 |
+
|
| 224 |
+
# lin0 has the largest output dimension, lin3 has the largest input dimension
|
| 225 |
+
# randlora_A should have the shape of (rank, largest_in), randlora_B should have the shape of (largest_out, rank)
|
| 226 |
+
assert randlora_A.shape == (config.r, 1, mlp.lin3.in_features)
|
| 227 |
+
assert randlora_B.shape == (mlp.lin0.out_features, 1, config.r)
|
| 228 |
+
|
| 229 |
+
# should not raise
|
| 230 |
+
input = torch.randn(5, 10)
|
| 231 |
+
mlp_different_shapes(input)
|
| 232 |
+
|
| 233 |
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
| 234 |
+
def test_randlora_dtypes(self, dtype):
|
| 235 |
+
if dtype == torch.bfloat16:
|
| 236 |
+
# skip if bf16 is not supported on hardware, see #1872
|
| 237 |
+
if not is_bf16_available():
|
| 238 |
+
pytest.skip("bfloat16 not supported on this system, skipping the test")
|
| 239 |
+
|
| 240 |
+
model = MLP().to(dtype)
|
| 241 |
+
config = RandLoraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 242 |
+
peft_model = get_peft_model(model, config)
|
| 243 |
+
inputs = torch.randn(5, 10).to(dtype)
|
| 244 |
+
output = peft_model(inputs) # should not raise
|
| 245 |
+
assert output.dtype == dtype
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_seq_classifier.py
ADDED
|
@@ -0,0 +1,347 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 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 |
+
C3AConfig,
|
| 22 |
+
DeloraConfig,
|
| 23 |
+
FourierFTConfig,
|
| 24 |
+
GraloraConfig,
|
| 25 |
+
HRAConfig,
|
| 26 |
+
IA3Config,
|
| 27 |
+
LilyConfig,
|
| 28 |
+
LoraConfig,
|
| 29 |
+
MissConfig,
|
| 30 |
+
OFTConfig,
|
| 31 |
+
PeanutConfig,
|
| 32 |
+
PrefixTuningConfig,
|
| 33 |
+
PromptEncoderConfig,
|
| 34 |
+
PromptTuningConfig,
|
| 35 |
+
PromptTuningInit,
|
| 36 |
+
PsoftConfig,
|
| 37 |
+
RoadConfig,
|
| 38 |
+
ShiraConfig,
|
| 39 |
+
VBLoRAConfig,
|
| 40 |
+
VeraConfig,
|
| 41 |
+
WaveFTConfig,
|
| 42 |
+
get_peft_model,
|
| 43 |
+
)
|
| 44 |
+
from peft.utils.other import ModulesToSaveWrapper
|
| 45 |
+
|
| 46 |
+
from .testing_common import PeftCommonTester
|
| 47 |
+
from .testing_utils import hub_online_once, set_init_weights_false
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
# Note: models from peft-internal-testing are just the safetensors versions of hf-internal-testing
|
| 51 |
+
PEFT_SEQ_CLS_MODELS_TO_TEST = [
|
| 52 |
+
"peft-internal-testing/tiny-random-BertForSequenceClassification",
|
| 53 |
+
"peft-internal-testing/tiny-random-RobertaForSequenceClassification",
|
| 54 |
+
"trl-internal-testing/tiny-LlamaForSequenceClassification-3.2",
|
| 55 |
+
]
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
ALL_CONFIGS = [
|
| 59 |
+
(
|
| 60 |
+
AdaLoraConfig,
|
| 61 |
+
{
|
| 62 |
+
"task_type": "SEQ_CLS",
|
| 63 |
+
"target_modules": None,
|
| 64 |
+
"total_step": 1,
|
| 65 |
+
},
|
| 66 |
+
),
|
| 67 |
+
(
|
| 68 |
+
BOFTConfig,
|
| 69 |
+
{
|
| 70 |
+
"task_type": "SEQ_CLS",
|
| 71 |
+
"target_modules": None,
|
| 72 |
+
},
|
| 73 |
+
),
|
| 74 |
+
(
|
| 75 |
+
MissConfig,
|
| 76 |
+
{
|
| 77 |
+
"task_type": "SEQ_CLS",
|
| 78 |
+
"target_modules": None,
|
| 79 |
+
"r": 2,
|
| 80 |
+
},
|
| 81 |
+
),
|
| 82 |
+
(
|
| 83 |
+
DeloraConfig,
|
| 84 |
+
{
|
| 85 |
+
"task_type": "SEQ_CLS",
|
| 86 |
+
"target_modules": None,
|
| 87 |
+
"r": 2,
|
| 88 |
+
},
|
| 89 |
+
),
|
| 90 |
+
(
|
| 91 |
+
FourierFTConfig,
|
| 92 |
+
{
|
| 93 |
+
"task_type": "SEQ_CLS",
|
| 94 |
+
"n_frequency": 10,
|
| 95 |
+
"target_modules": None,
|
| 96 |
+
},
|
| 97 |
+
),
|
| 98 |
+
(
|
| 99 |
+
GraloraConfig,
|
| 100 |
+
{
|
| 101 |
+
"task_type": "SEQ_CLS",
|
| 102 |
+
"target_modules": None,
|
| 103 |
+
},
|
| 104 |
+
),
|
| 105 |
+
(
|
| 106 |
+
HRAConfig,
|
| 107 |
+
{
|
| 108 |
+
"task_type": "SEQ_CLS",
|
| 109 |
+
"target_modules": None,
|
| 110 |
+
},
|
| 111 |
+
),
|
| 112 |
+
(
|
| 113 |
+
IA3Config,
|
| 114 |
+
{
|
| 115 |
+
"task_type": "SEQ_CLS",
|
| 116 |
+
"target_modules": None,
|
| 117 |
+
"feedforward_modules": None,
|
| 118 |
+
},
|
| 119 |
+
),
|
| 120 |
+
(
|
| 121 |
+
LilyConfig,
|
| 122 |
+
{
|
| 123 |
+
"task_type": "SEQ_CLS",
|
| 124 |
+
"target_modules": None,
|
| 125 |
+
"r": 8,
|
| 126 |
+
"stride_A": 1,
|
| 127 |
+
"num_B": 2,
|
| 128 |
+
},
|
| 129 |
+
),
|
| 130 |
+
(
|
| 131 |
+
LoraConfig,
|
| 132 |
+
{
|
| 133 |
+
"task_type": "SEQ_CLS",
|
| 134 |
+
"r": 8,
|
| 135 |
+
"lora_alpha": 32,
|
| 136 |
+
"target_modules": None,
|
| 137 |
+
"lora_dropout": 0.05,
|
| 138 |
+
"bias": "none",
|
| 139 |
+
},
|
| 140 |
+
),
|
| 141 |
+
# LoRA + trainable tokens
|
| 142 |
+
(
|
| 143 |
+
LoraConfig,
|
| 144 |
+
{
|
| 145 |
+
"task_type": "SEQ_CLS",
|
| 146 |
+
"r": 8,
|
| 147 |
+
"lora_alpha": 32,
|
| 148 |
+
"target_modules": None,
|
| 149 |
+
"lora_dropout": 0.05,
|
| 150 |
+
"bias": "none",
|
| 151 |
+
"trainable_token_indices": [0, 1, 3],
|
| 152 |
+
},
|
| 153 |
+
),
|
| 154 |
+
(
|
| 155 |
+
OFTConfig,
|
| 156 |
+
{
|
| 157 |
+
"task_type": "SEQ_CLS",
|
| 158 |
+
"target_modules": None,
|
| 159 |
+
},
|
| 160 |
+
),
|
| 161 |
+
(
|
| 162 |
+
PrefixTuningConfig,
|
| 163 |
+
{
|
| 164 |
+
"task_type": "SEQ_CLS",
|
| 165 |
+
"num_virtual_tokens": 10,
|
| 166 |
+
},
|
| 167 |
+
),
|
| 168 |
+
(
|
| 169 |
+
PromptEncoderConfig,
|
| 170 |
+
{
|
| 171 |
+
"task_type": "SEQ_CLS",
|
| 172 |
+
"num_virtual_tokens": 10,
|
| 173 |
+
"encoder_hidden_size": 32,
|
| 174 |
+
},
|
| 175 |
+
),
|
| 176 |
+
(
|
| 177 |
+
PromptTuningConfig,
|
| 178 |
+
{
|
| 179 |
+
"task_type": "SEQ_CLS",
|
| 180 |
+
"num_virtual_tokens": 10,
|
| 181 |
+
},
|
| 182 |
+
),
|
| 183 |
+
(
|
| 184 |
+
PsoftConfig,
|
| 185 |
+
{
|
| 186 |
+
"task_type": "SEQ_CLS",
|
| 187 |
+
"r": 32,
|
| 188 |
+
"psoft_alpha": 32,
|
| 189 |
+
"target_modules": None,
|
| 190 |
+
},
|
| 191 |
+
),
|
| 192 |
+
(
|
| 193 |
+
PeanutConfig,
|
| 194 |
+
{
|
| 195 |
+
"r": 8,
|
| 196 |
+
"depth": 1,
|
| 197 |
+
"act_fn": "relu",
|
| 198 |
+
"task_type": "SEQ_CLS",
|
| 199 |
+
"target_modules": None,
|
| 200 |
+
},
|
| 201 |
+
),
|
| 202 |
+
(
|
| 203 |
+
RoadConfig,
|
| 204 |
+
{
|
| 205 |
+
"task_type": "SEQ_CLS",
|
| 206 |
+
"variant": "road_1",
|
| 207 |
+
"group_size": 2,
|
| 208 |
+
},
|
| 209 |
+
),
|
| 210 |
+
(
|
| 211 |
+
ShiraConfig,
|
| 212 |
+
{
|
| 213 |
+
"r": 1,
|
| 214 |
+
"task_type": "SEQ_CLS",
|
| 215 |
+
"target_modules": None,
|
| 216 |
+
"init_weights": False,
|
| 217 |
+
},
|
| 218 |
+
),
|
| 219 |
+
(
|
| 220 |
+
VBLoRAConfig,
|
| 221 |
+
{
|
| 222 |
+
"task_type": "SEQ_CLS",
|
| 223 |
+
"target_modules": None,
|
| 224 |
+
"vblora_dropout": 0.05,
|
| 225 |
+
"vector_length": 1,
|
| 226 |
+
"num_vectors": 2,
|
| 227 |
+
},
|
| 228 |
+
),
|
| 229 |
+
(
|
| 230 |
+
VeraConfig,
|
| 231 |
+
{
|
| 232 |
+
"task_type": "SEQ_CLS",
|
| 233 |
+
"r": 8,
|
| 234 |
+
"target_modules": None,
|
| 235 |
+
"vera_dropout": 0.05,
|
| 236 |
+
"projection_prng_key": 0xFF,
|
| 237 |
+
"d_initial": 0.1,
|
| 238 |
+
"save_projection": True,
|
| 239 |
+
"bias": "none",
|
| 240 |
+
},
|
| 241 |
+
),
|
| 242 |
+
(
|
| 243 |
+
C3AConfig,
|
| 244 |
+
{
|
| 245 |
+
"task_type": "SEQ_CLS",
|
| 246 |
+
"block_size": 1,
|
| 247 |
+
"target_modules": None,
|
| 248 |
+
},
|
| 249 |
+
),
|
| 250 |
+
(
|
| 251 |
+
WaveFTConfig,
|
| 252 |
+
{
|
| 253 |
+
"task_type": "SEQ_CLS",
|
| 254 |
+
"n_frequency": 8,
|
| 255 |
+
"target_modules": None,
|
| 256 |
+
},
|
| 257 |
+
),
|
| 258 |
+
]
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class TestSequenceClassificationModels(PeftCommonTester):
|
| 262 |
+
r"""
|
| 263 |
+
Tests for basic coverage of AutoModelForSequenceClassification and classification-specific cases. Most of the
|
| 264 |
+
functionality is probably already covered by other tests.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
transformers_class = AutoModelForSequenceClassification
|
| 268 |
+
|
| 269 |
+
def prepare_inputs_for_testing(self):
|
| 270 |
+
input_ids = torch.tensor([[1, 1, 1], [1, 2, 1]]).to(self.torch_device)
|
| 271 |
+
attention_mask = torch.tensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 272 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 273 |
+
|
| 274 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 275 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 276 |
+
def test_attributes_parametrized(self, model_id, config_cls, config_kwargs):
|
| 277 |
+
self._test_model_attr(model_id, config_cls, config_kwargs.copy())
|
| 278 |
+
|
| 279 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 280 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 281 |
+
def test_adapter_name(self, model_id, config_cls, config_kwargs):
|
| 282 |
+
self._test_adapter_name(model_id, config_cls, config_kwargs.copy())
|
| 283 |
+
|
| 284 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 285 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 286 |
+
def test_prepare_for_training_parametrized(self, model_id, config_cls, config_kwargs):
|
| 287 |
+
self._test_prepare_for_training(model_id, config_cls, config_kwargs.copy())
|
| 288 |
+
|
| 289 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 290 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 291 |
+
def test_prompt_tuning_text_prepare_for_training(self, model_id, config_cls, config_kwargs):
|
| 292 |
+
if config_cls != PromptTuningConfig:
|
| 293 |
+
pytest.skip(f"This test does not apply to {config_cls}")
|
| 294 |
+
config_kwargs = config_kwargs.copy()
|
| 295 |
+
config_kwargs["prompt_tuning_init"] = PromptTuningInit.TEXT
|
| 296 |
+
config_kwargs["prompt_tuning_init_text"] = "This is a test prompt."
|
| 297 |
+
config_kwargs["tokenizer_name_or_path"] = model_id
|
| 298 |
+
self._test_prepare_for_training(model_id, config_cls, config_kwargs.copy())
|
| 299 |
+
|
| 300 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 301 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 302 |
+
def test_save_pretrained(self, model_id, config_cls, config_kwargs):
|
| 303 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 304 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy())
|
| 305 |
+
|
| 306 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 307 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 308 |
+
def test_save_pretrained_pickle(self, model_id, config_cls, config_kwargs):
|
| 309 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 310 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy(), safe_serialization=False)
|
| 311 |
+
|
| 312 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 313 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 314 |
+
def test_save_pretrained_selected_adapters(self, model_id, config_cls, config_kwargs):
|
| 315 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 316 |
+
self._test_save_pretrained_selected_adapters(model_id, config_cls, config_kwargs.copy())
|
| 317 |
+
|
| 318 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 319 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 320 |
+
def test_save_pretrained_selected_adapters_pickle(self, model_id, config_cls, config_kwargs):
|
| 321 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 322 |
+
self._test_save_pretrained_selected_adapters(
|
| 323 |
+
model_id, config_cls, config_kwargs.copy(), safe_serialization=False
|
| 324 |
+
)
|
| 325 |
+
|
| 326 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 327 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 328 |
+
def test_from_pretrained_config_construction(self, model_id, config_cls, config_kwargs):
|
| 329 |
+
self._test_from_pretrained_config_construction(model_id, config_cls, config_kwargs.copy())
|
| 330 |
+
|
| 331 |
+
@pytest.mark.parametrize("model_id", PEFT_SEQ_CLS_MODELS_TO_TEST)
|
| 332 |
+
@pytest.mark.parametrize("config_cls,config_kwargs", ALL_CONFIGS)
|
| 333 |
+
def test_modules_to_save_correctly_set(self, model_id, config_cls, config_kwargs):
|
| 334 |
+
# tests for a regression, introduced via #2220, where modules_to_save was not applied to prompt learning methods
|
| 335 |
+
with hub_online_once(model_id):
|
| 336 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 337 |
+
config = config_cls(
|
| 338 |
+
base_model_name_or_path=model_id,
|
| 339 |
+
**config_kwargs,
|
| 340 |
+
)
|
| 341 |
+
model = get_peft_model(model, config)
|
| 342 |
+
base_model = model.get_base_model()
|
| 343 |
+
# classifier layer is called either "classifier" or "score"
|
| 344 |
+
classifier = getattr(base_model, "classifier", getattr(base_model, "score", None))
|
| 345 |
+
if classifier is None:
|
| 346 |
+
raise ValueError(f"Could not determine classifier layer name for {model_id}, please fix the test")
|
| 347 |
+
assert isinstance(classifier, ModulesToSaveWrapper)
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_shira.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 |
+
# 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-a27f5bd16532/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-a27f5bd16532/tests/source/tests/test_target_parameters.py
ADDED
|
@@ -0,0 +1,600 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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025-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 |
+
from peft.tuners.lora.layer import ParamWrapper
|
| 23 |
+
|
| 24 |
+
from .testing_common import PeftCommonTester
|
| 25 |
+
from .testing_utils import hub_online_once, set_init_weights_false
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
ALL_CONFIGS = [
|
| 29 |
+
##########
|
| 30 |
+
# Llama4 #
|
| 31 |
+
##########
|
| 32 |
+
# target down_proj
|
| 33 |
+
(
|
| 34 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 35 |
+
LoraConfig,
|
| 36 |
+
{
|
| 37 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 38 |
+
"target_modules": [],
|
| 39 |
+
"lora_dropout": 0.0,
|
| 40 |
+
"target_parameters": [
|
| 41 |
+
"feed_forward.experts.down_proj",
|
| 42 |
+
],
|
| 43 |
+
},
|
| 44 |
+
),
|
| 45 |
+
# target gate_up_proj and down_proj, but not on the same module
|
| 46 |
+
(
|
| 47 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 48 |
+
LoraConfig,
|
| 49 |
+
{
|
| 50 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 51 |
+
"target_modules": [],
|
| 52 |
+
"lora_dropout": 0.0,
|
| 53 |
+
"target_parameters": [
|
| 54 |
+
"0.feed_forward.experts.gate_up_proj",
|
| 55 |
+
"1.feed_forward.experts.down_proj",
|
| 56 |
+
],
|
| 57 |
+
},
|
| 58 |
+
),
|
| 59 |
+
# target down_proj and gate_up_proj on the same module
|
| 60 |
+
(
|
| 61 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 62 |
+
LoraConfig,
|
| 63 |
+
{
|
| 64 |
+
"task_type": "CAUSAL_LM",
|
| 65 |
+
"r": 8,
|
| 66 |
+
"lora_alpha": 32,
|
| 67 |
+
"target_modules": None,
|
| 68 |
+
"lora_dropout": 0.0,
|
| 69 |
+
"bias": "none",
|
| 70 |
+
"target_parameters": [
|
| 71 |
+
"feed_forward.experts.down_proj",
|
| 72 |
+
"feed_forward.experts.gate_up_proj",
|
| 73 |
+
],
|
| 74 |
+
},
|
| 75 |
+
),
|
| 76 |
+
# target q_proj, v_proj as modules, and down_proj as parameter
|
| 77 |
+
(
|
| 78 |
+
"trl-internal-testing/tiny-Llama4ForCausalLM",
|
| 79 |
+
LoraConfig,
|
| 80 |
+
{
|
| 81 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 82 |
+
"target_modules": ["q_proj", "v_proj"],
|
| 83 |
+
"lora_dropout": 0.0,
|
| 84 |
+
"target_parameters": [
|
| 85 |
+
"feed_forward.experts.down_proj",
|
| 86 |
+
],
|
| 87 |
+
},
|
| 88 |
+
),
|
| 89 |
+
###########
|
| 90 |
+
# gpt-oss #
|
| 91 |
+
###########
|
| 92 |
+
# target down_proj
|
| 93 |
+
(
|
| 94 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 95 |
+
LoraConfig,
|
| 96 |
+
{
|
| 97 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 98 |
+
"target_modules": [],
|
| 99 |
+
"lora_dropout": 0.0,
|
| 100 |
+
"target_parameters": [
|
| 101 |
+
"mlp.experts.down_proj",
|
| 102 |
+
],
|
| 103 |
+
},
|
| 104 |
+
),
|
| 105 |
+
# target gate_up_proj and down_proj, but not on the same module
|
| 106 |
+
(
|
| 107 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 108 |
+
LoraConfig,
|
| 109 |
+
{
|
| 110 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 111 |
+
"target_modules": [],
|
| 112 |
+
"lora_dropout": 0.0,
|
| 113 |
+
"target_parameters": [
|
| 114 |
+
"0.mlp.experts.gate_up_proj",
|
| 115 |
+
"1.mlp.experts.down_proj",
|
| 116 |
+
],
|
| 117 |
+
},
|
| 118 |
+
),
|
| 119 |
+
# target down_proj and gate_up_proj on the same module
|
| 120 |
+
(
|
| 121 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 122 |
+
LoraConfig,
|
| 123 |
+
{
|
| 124 |
+
"task_type": "CAUSAL_LM",
|
| 125 |
+
"r": 8,
|
| 126 |
+
"lora_alpha": 32,
|
| 127 |
+
"target_modules": None,
|
| 128 |
+
"lora_dropout": 0.0,
|
| 129 |
+
"bias": "none",
|
| 130 |
+
"target_parameters": [
|
| 131 |
+
"mlp.experts.down_proj",
|
| 132 |
+
"mlp.experts.gate_up_proj",
|
| 133 |
+
],
|
| 134 |
+
},
|
| 135 |
+
),
|
| 136 |
+
# target q_proj, v_proj as modules, and down_proj as parameter
|
| 137 |
+
(
|
| 138 |
+
"trl-internal-testing/tiny-GptOssForCausalLM",
|
| 139 |
+
LoraConfig,
|
| 140 |
+
{
|
| 141 |
+
"task_type": TaskType.CAUSAL_LM,
|
| 142 |
+
"target_modules": ["q_proj", "v_proj"],
|
| 143 |
+
"lora_dropout": 0.0,
|
| 144 |
+
"target_parameters": [
|
| 145 |
+
"mlp.experts.down_proj",
|
| 146 |
+
],
|
| 147 |
+
},
|
| 148 |
+
),
|
| 149 |
+
]
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
class MyAutoModelForCausalLM(AutoModelForCausalLM):
|
| 153 |
+
@classmethod
|
| 154 |
+
def from_pretrained(cls, *args, **kwargs):
|
| 155 |
+
torch.manual_seed(0)
|
| 156 |
+
model = AutoModelForCausalLM.from_pretrained(*args, **kwargs)
|
| 157 |
+
|
| 158 |
+
# check that we load the original model, not, say, a trained checkpoint
|
| 159 |
+
if args[0] == "trl-internal-testing/tiny-Llama4ForCausalLM":
|
| 160 |
+
# model contains weights with values ~1e36 or nan, so we need to reinitialize with sane values
|
| 161 |
+
with torch.no_grad():
|
| 162 |
+
for param in model.parameters():
|
| 163 |
+
param.data = torch.randn(param.shape)
|
| 164 |
+
return model
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def test_rank_pattern_for_moe_target_parameters(tmp_path):
|
| 168 |
+
model_id = "trl-internal-testing/tiny-Llama4ForCausalLM"
|
| 169 |
+
with hub_online_once(model_id):
|
| 170 |
+
model = MyAutoModelForCausalLM.from_pretrained(model_id)
|
| 171 |
+
num_experts = getattr(model.config, "num_local_experts", None) or getattr(model.config, "num_experts", None)
|
| 172 |
+
assert num_experts is not None
|
| 173 |
+
r = 8
|
| 174 |
+
effective_r = max(1, r // num_experts)
|
| 175 |
+
config = LoraConfig(
|
| 176 |
+
r=r,
|
| 177 |
+
lora_alpha=32,
|
| 178 |
+
target_modules=["q_proj", "v_proj"],
|
| 179 |
+
target_parameters=["feed_forward.experts.gate_up_proj"],
|
| 180 |
+
rank_pattern={
|
| 181 |
+
"experts.gate_up_proj": effective_r,
|
| 182 |
+
},
|
| 183 |
+
init_lora_weights=False,
|
| 184 |
+
)
|
| 185 |
+
model = get_peft_model(model, config)
|
| 186 |
+
|
| 187 |
+
wrappers = [
|
| 188 |
+
module
|
| 189 |
+
for module in model.modules()
|
| 190 |
+
if isinstance(module, ParamWrapper) and module.parameter_name == "gate_up_proj"
|
| 191 |
+
]
|
| 192 |
+
assert wrappers, "Expected to find ParamWrapper for gate_up_proj."
|
| 193 |
+
lora_module = wrappers[0]
|
| 194 |
+
assert lora_module.r["default"] == effective_r
|
| 195 |
+
assert lora_module.lora_A["default"].weight.shape[0] == effective_r * num_experts
|
| 196 |
+
assert lora_module.scaling["default"] == config.lora_alpha / effective_r
|
| 197 |
+
assert config.r == r
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
class TestDecoderModelsTargetParameters(PeftCommonTester):
|
| 201 |
+
# This is more or less a copy of TestDecoderModels at the time of the PR being added. Unnecessary code is removed,
|
| 202 |
+
# like code required for testing non-LoRA methods. The tests being included are not selected to test specific
|
| 203 |
+
# functionality of targeting nn.Parameters, they (together with the tests in test_custom_models.py) just ensure that
|
| 204 |
+
# generally, nothing is broken.
|
| 205 |
+
transformers_class = MyAutoModelForCausalLM
|
| 206 |
+
|
| 207 |
+
def prepare_inputs_for_testing(self):
|
| 208 |
+
input_ids = torch.tensor([[1, 1, 1], [1, 2, 1]]).to(self.torch_device)
|
| 209 |
+
attention_mask = torch.tensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 210 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 211 |
+
|
| 212 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 213 |
+
def test_attributes_parametrized(self, model_id, config_cls, config_kwargs):
|
| 214 |
+
self._test_model_attr(model_id, config_cls, config_kwargs.copy())
|
| 215 |
+
|
| 216 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 217 |
+
def test_adapter_name(self, model_id, config_cls, config_kwargs):
|
| 218 |
+
self._test_adapter_name(model_id, config_cls, config_kwargs.copy())
|
| 219 |
+
|
| 220 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 221 |
+
def test_prepare_for_training_parametrized(self, model_id, config_cls, config_kwargs):
|
| 222 |
+
self._test_prepare_for_training(model_id, config_cls, config_kwargs.copy())
|
| 223 |
+
|
| 224 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 225 |
+
def test_save_pretrained(self, model_id, config_cls, config_kwargs):
|
| 226 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 227 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy())
|
| 228 |
+
|
| 229 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 230 |
+
def test_save_pretrained_pickle(self, model_id, config_cls, config_kwargs):
|
| 231 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 232 |
+
self._test_save_pretrained(model_id, config_cls, config_kwargs.copy(), safe_serialization=False)
|
| 233 |
+
|
| 234 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 235 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 236 |
+
def test_save_pretrained_selected_adapters(self, model_id, config_cls, config_kwargs):
|
| 237 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 238 |
+
self._test_save_pretrained_selected_adapters(model_id, config_cls, config_kwargs.copy())
|
| 239 |
+
|
| 240 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 241 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 242 |
+
def test_save_pretrained_selected_adapters_pickle(self, model_id, config_cls, config_kwargs):
|
| 243 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 244 |
+
self._test_save_pretrained_selected_adapters(
|
| 245 |
+
model_id, config_cls, config_kwargs.copy(), safe_serialization=False
|
| 246 |
+
)
|
| 247 |
+
|
| 248 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 249 |
+
def test_from_pretrained_config_construction(self, model_id, config_cls, config_kwargs):
|
| 250 |
+
self._test_from_pretrained_config_construction(model_id, config_cls, config_kwargs.copy())
|
| 251 |
+
|
| 252 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 253 |
+
def test_merge_layers(self, model_id, config_cls, config_kwargs):
|
| 254 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 255 |
+
self._test_merge_layers(model_id, config_cls, config_kwargs.copy())
|
| 256 |
+
|
| 257 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 258 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 259 |
+
def test_merge_layers_multi(self, model_id, config_cls, config_kwargs):
|
| 260 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 261 |
+
self._test_merge_layers_multi(model_id, config_cls, config_kwargs.copy())
|
| 262 |
+
|
| 263 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 264 |
+
def test_merge_layers_nan(self, model_id, config_cls, config_kwargs):
|
| 265 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 266 |
+
self._test_merge_layers_nan(model_id, config_cls, config_kwargs.copy())
|
| 267 |
+
|
| 268 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 269 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 270 |
+
def test_mixed_adapter_batches(self, model_id, config_cls, config_kwargs):
|
| 271 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 272 |
+
msg = "lora.ParamWrapper does not support mixed adapter batches yet."
|
| 273 |
+
with pytest.raises(ValueError, match=msg):
|
| 274 |
+
self._test_mixed_adapter_batches(model_id, config_cls, config_kwargs.copy())
|
| 275 |
+
|
| 276 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 277 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 278 |
+
def test_generate_with_mixed_adapter_batches(self, model_id, config_cls, config_kwargs):
|
| 279 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 280 |
+
msg = "lora.ParamWrapper does not support mixed adapter batches yet."
|
| 281 |
+
with pytest.raises(ValueError, match=msg):
|
| 282 |
+
self._test_generate_with_mixed_adapter_batches_and_beam_search(model_id, config_cls, config_kwargs.copy())
|
| 283 |
+
|
| 284 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 285 |
+
def test_generate(self, model_id, config_cls, config_kwargs):
|
| 286 |
+
self._test_generate(model_id, config_cls, config_kwargs.copy())
|
| 287 |
+
|
| 288 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 289 |
+
def test_generate_pos_args(self, model_id, config_cls, config_kwargs):
|
| 290 |
+
self._test_generate_pos_args(model_id, config_cls, config_kwargs.copy(), raises_err=False)
|
| 291 |
+
|
| 292 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 293 |
+
def test_merge_layers_fp16(self, model_id, config_cls, config_kwargs):
|
| 294 |
+
self._test_merge_layers_fp16(model_id, config_cls, config_kwargs.copy())
|
| 295 |
+
|
| 296 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 297 |
+
def test_generate_half_prec(self, model_id, config_cls, config_kwargs):
|
| 298 |
+
self._test_generate_half_prec(model_id, config_cls, config_kwargs.copy())
|
| 299 |
+
|
| 300 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 301 |
+
def test_training_decoders(self, model_id, config_cls, config_kwargs):
|
| 302 |
+
self._test_training(model_id, config_cls, config_kwargs.copy())
|
| 303 |
+
|
| 304 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 305 |
+
def test_training_decoders_gradient_checkpointing(self, model_id, config_cls, config_kwargs):
|
| 306 |
+
self._test_training_gradient_checkpointing(model_id, config_cls, config_kwargs.copy())
|
| 307 |
+
|
| 308 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 309 |
+
def test_inference_safetensors(self, model_id, config_cls, config_kwargs):
|
| 310 |
+
self._test_inference_safetensors(model_id, config_cls, config_kwargs.copy())
|
| 311 |
+
|
| 312 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 313 |
+
def test_peft_model_device_map(self, model_id, config_cls, config_kwargs):
|
| 314 |
+
self._test_peft_model_device_map(model_id, config_cls, config_kwargs.copy())
|
| 315 |
+
|
| 316 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 317 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 318 |
+
def test_delete_adapter(self, model_id, config_cls, config_kwargs):
|
| 319 |
+
self._test_delete_adapter(model_id, config_cls, config_kwargs.copy())
|
| 320 |
+
|
| 321 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 322 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 323 |
+
def test_delete_inactive_adapter(self, model_id, config_cls, config_kwargs):
|
| 324 |
+
self._test_delete_inactive_adapter(model_id, config_cls, config_kwargs.copy())
|
| 325 |
+
|
| 326 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 327 |
+
def test_adding_multiple_adapters_with_bias_raises(self, model_id, config_cls, config_kwargs):
|
| 328 |
+
self._test_adding_multiple_adapters_with_bias_raises(model_id, config_cls, config_kwargs.copy())
|
| 329 |
+
|
| 330 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 331 |
+
def test_unload_adapter(self, model_id, config_cls, config_kwargs):
|
| 332 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 333 |
+
self._test_unload_adapter(model_id, config_cls, config_kwargs.copy())
|
| 334 |
+
|
| 335 |
+
@pytest.mark.skip(reason="Multiple adapters with target_parameters are not supported yet.")
|
| 336 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 337 |
+
def test_weighted_combination_of_adapters(self, model_id, config_cls, config_kwargs):
|
| 338 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 339 |
+
msg = "add_weighted_adapter does not support targeting nn.Parameter"
|
| 340 |
+
with pytest.raises(ValueError, match=msg):
|
| 341 |
+
self._test_weighted_combination_of_adapters(model_id, config_cls, config_kwargs.copy())
|
| 342 |
+
|
| 343 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 344 |
+
def test_training_prompt_learning_tasks(self, model_id, config_cls, config_kwargs):
|
| 345 |
+
self._test_training_prompt_learning_tasks(model_id, config_cls, config_kwargs.copy())
|
| 346 |
+
|
| 347 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 348 |
+
def test_disable_adapter(self, model_id, config_cls, config_kwargs):
|
| 349 |
+
config_kwargs = set_init_weights_false(config_cls, config_kwargs)
|
| 350 |
+
self._test_disable_adapter(model_id, config_cls, config_kwargs.copy())
|
| 351 |
+
|
| 352 |
+
@pytest.mark.parametrize("model_id,config_cls,config_kwargs", ALL_CONFIGS)
|
| 353 |
+
def test_passing_input_embeds_works(self, model_id, config_cls, config_kwargs):
|
| 354 |
+
self._test_passing_input_embeds_works("", model_id, config_cls, config_kwargs.copy())
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
class TestTargetParameters:
|
| 358 |
+
# Tests specifically designed for target_parameters
|
| 359 |
+
def test_targeting_module_and_targeting_param_equivalent(self):
|
| 360 |
+
# Test that using LoRA with target_modules vs target_parameters yields identical results.
|
| 361 |
+
# note: we purposely target the gate_proj because its weight is not square (unlike q_proj, ...), this makes it
|
| 362 |
+
# easier to catch shape errors
|
| 363 |
+
torch.manual_seed(0)
|
| 364 |
+
model_id = "hf-internal-testing/tiny-random-LlamaForCausalLM"
|
| 365 |
+
with hub_online_once(model_id):
|
| 366 |
+
model0 = AutoModelForCausalLM.from_pretrained(model_id)
|
| 367 |
+
x = torch.arange(10).view(2, 5)
|
| 368 |
+
with torch.inference_mode():
|
| 369 |
+
out_base = model0(x, output_hidden_states=True).hidden_states[-1]
|
| 370 |
+
|
| 371 |
+
# targeting the module
|
| 372 |
+
config0 = LoraConfig(target_modules=["gate_proj"], init_lora_weights=False)
|
| 373 |
+
model0 = get_peft_model(model0, config0)
|
| 374 |
+
|
| 375 |
+
# targeting the parameter
|
| 376 |
+
model1 = AutoModelForCausalLM.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
|
| 377 |
+
config1 = LoraConfig(target_modules=[], target_parameters=["gate_proj.weight"], init_lora_weights=False)
|
| 378 |
+
model1 = get_peft_model(model1, config1)
|
| 379 |
+
|
| 380 |
+
gate_proj_0_0 = model0.base_model.model.model.layers[0].mlp.gate_proj
|
| 381 |
+
gate_proj_0_1 = model0.base_model.model.model.layers[1].mlp.gate_proj
|
| 382 |
+
gate_proj_1_0 = model1.base_model.model.model.layers[0].mlp.gate_proj
|
| 383 |
+
gate_proj_1_1 = model1.base_model.model.model.layers[1].mlp.gate_proj
|
| 384 |
+
|
| 385 |
+
# ensure that the randomly initialized LoRA weights are identical
|
| 386 |
+
gate_proj_1_0.lora_A.default.weight.data.copy_(gate_proj_0_0.lora_A.default.weight.data)
|
| 387 |
+
gate_proj_1_1.lora_A.default.weight.data.copy_(gate_proj_0_1.lora_A.default.weight.data)
|
| 388 |
+
gate_proj_1_0.lora_B.default.weight.data.copy_(gate_proj_0_0.lora_B.default.weight.data)
|
| 389 |
+
gate_proj_1_1.lora_B.default.weight.data.copy_(gate_proj_0_1.lora_B.default.weight.data)
|
| 390 |
+
|
| 391 |
+
with torch.inference_mode():
|
| 392 |
+
out_lora_0 = model0(x, output_hidden_states=True).hidden_states[-1]
|
| 393 |
+
out_lora_1 = model1(x, output_hidden_states=True).hidden_states[-1]
|
| 394 |
+
|
| 395 |
+
# sanity check: basemodel outputs should be different
|
| 396 |
+
atol, rtol = 1e-6, 1e-6
|
| 397 |
+
assert not torch.allclose(out_base, out_lora_0, atol=atol, rtol=rtol)
|
| 398 |
+
|
| 399 |
+
# LoRA outputs should be the same
|
| 400 |
+
assert torch.allclose(out_lora_0, out_lora_1, atol=atol, rtol=rtol)
|
| 401 |
+
|
| 402 |
+
def test_target_multiple_parameters_on_same_module(self, monkeypatch):
|
| 403 |
+
# test that if we target multiple nn.Parameters on the same module, all of them are being used during the
|
| 404 |
+
# forward pass
|
| 405 |
+
torch.manual_seed(0)
|
| 406 |
+
model_id = "trl-internal-testing/tiny-Llama4ForCausalLM"
|
| 407 |
+
with hub_online_once(model_id):
|
| 408 |
+
x = torch.arange(10).view(2, 5)
|
| 409 |
+
model = MyAutoModelForCausalLM.from_pretrained(model_id)
|
| 410 |
+
shape_gate_up_proj = model.model.layers[0].feed_forward.experts.gate_up_proj.shape
|
| 411 |
+
shape_down_proj = model.model.layers[0].feed_forward.experts.down_proj.shape
|
| 412 |
+
num_layers = len(model.model.layers)
|
| 413 |
+
|
| 414 |
+
target_parameters = ["feed_forward.experts.gate_up_proj", "feed_forward.experts.down_proj"]
|
| 415 |
+
num_params = len(target_parameters)
|
| 416 |
+
config = LoraConfig(target_parameters=target_parameters, init_lora_weights=False)
|
| 417 |
+
model = get_peft_model(model, config)
|
| 418 |
+
|
| 419 |
+
# CHECK FORWARD CALLS
|
| 420 |
+
|
| 421 |
+
# log the weights seen during the forward call
|
| 422 |
+
weights = []
|
| 423 |
+
|
| 424 |
+
def mock_forward(self, W):
|
| 425 |
+
weights.append(W)
|
| 426 |
+
return orig_forward(self, W)
|
| 427 |
+
|
| 428 |
+
from peft.tuners.lora.layer import _LoraParameterProxy
|
| 429 |
+
|
| 430 |
+
orig_forward = _LoraParameterProxy.forward
|
| 431 |
+
monkeypatch.setattr(_LoraParameterProxy, "forward", mock_forward)
|
| 432 |
+
|
| 433 |
+
num_steps = 3
|
| 434 |
+
with torch.inference_mode():
|
| 435 |
+
for _ in range(num_steps):
|
| 436 |
+
out_base = model(x, output_hidden_states=True).hidden_states[-1]
|
| 437 |
+
|
| 438 |
+
actual_call_count = len(weights)
|
| 439 |
+
# Note: We call forward twice per step, once to create the parametrization and once for the actual forward
|
| 440 |
+
# step. This may be a bit wasteful but it's not clear how to prevent this and overall is probably negligible
|
| 441 |
+
num_forward_per_step = 2
|
| 442 |
+
# Since https://github.com/huggingface/transformers/pull/39501, one of the parameters is accessed twice per
|
| 443 |
+
# forward call, but we cache all calls after the first.
|
| 444 |
+
expected_call_count = num_steps * num_layers * num_params * num_forward_per_step
|
| 445 |
+
assert actual_call_count == expected_call_count
|
| 446 |
+
|
| 447 |
+
actual_shapes = {W.shape for W in weights}
|
| 448 |
+
expected_shapes = {shape_gate_up_proj, shape_down_proj}
|
| 449 |
+
assert actual_shapes == expected_shapes
|
| 450 |
+
|
| 451 |
+
# CHECK WEIGHT UPDATES
|
| 452 |
+
|
| 453 |
+
lora_weights_before = {
|
| 454 |
+
k: v.clone() for k, v in model.named_parameters() if "lora_A.default" in k or "lora_B.default" in k
|
| 455 |
+
}
|
| 456 |
+
# sanity check:
|
| 457 |
+
assert len(lora_weights_before) == 2 * num_layers * num_params
|
| 458 |
+
# train
|
| 459 |
+
optim = torch.optim.SGD(model.parameters(), lr=0.01)
|
| 460 |
+
for _ in range(10):
|
| 461 |
+
optim.zero_grad()
|
| 462 |
+
out = model(x)
|
| 463 |
+
loss = out.logits.sum()
|
| 464 |
+
loss.backward()
|
| 465 |
+
optim.step()
|
| 466 |
+
|
| 467 |
+
lora_weights_after = {
|
| 468 |
+
k: v for k, v in model.named_parameters() if "lora_A.default" in k or "lora_B.default" in k
|
| 469 |
+
}
|
| 470 |
+
assert lora_weights_before.keys() == lora_weights_after.keys()
|
| 471 |
+
atol, rtol = 0.1, 0.1
|
| 472 |
+
for key in lora_weights_before.keys():
|
| 473 |
+
assert not torch.allclose(lora_weights_before[key], lora_weights_after[key], atol=atol, rtol=rtol)
|
| 474 |
+
|
| 475 |
+
def test_target_parameters_works_with_existing_parametrization(self):
|
| 476 |
+
# When a parameter is already parametrized, we want the LoRA parametrization to work with it correctly.
|
| 477 |
+
class MyLinear(nn.Linear):
|
| 478 |
+
# For testing purposes, define a linear layer with 2 parameters: weight and other_weight.
|
| 479 |
+
def __init__(self, *args, **kwargs):
|
| 480 |
+
super().__init__(*args, **kwargs)
|
| 481 |
+
nn.init.ones_(self.weight)
|
| 482 |
+
self.other_weight = nn.Parameter(torch.ones(self.weight.shape))
|
| 483 |
+
|
| 484 |
+
class MyModule(nn.Module):
|
| 485 |
+
def __init__(self):
|
| 486 |
+
super().__init__()
|
| 487 |
+
self.lin = MyLinear(2, 2, bias=False)
|
| 488 |
+
|
| 489 |
+
def forward(self, x):
|
| 490 |
+
return self.lin(x)
|
| 491 |
+
|
| 492 |
+
class MyParametrization(nn.Module):
|
| 493 |
+
def __init__(self):
|
| 494 |
+
super().__init__()
|
| 495 |
+
|
| 496 |
+
def forward(self, x):
|
| 497 |
+
return x + 1
|
| 498 |
+
|
| 499 |
+
# base model
|
| 500 |
+
model = MyModule()
|
| 501 |
+
x = torch.ones((2, 2))
|
| 502 |
+
|
| 503 |
+
# sanity check: result should be 1*1 + 1*1 == 2
|
| 504 |
+
output_base = model(x)
|
| 505 |
+
assert torch.all(output_base == 2)
|
| 506 |
+
|
| 507 |
+
# add parametrization to the weight
|
| 508 |
+
nn.utils.parametrize.register_parametrization(model.lin, "weight", MyParametrization())
|
| 509 |
+
|
| 510 |
+
# result should be (1+1)*1 + (1+1)*1 == 4
|
| 511 |
+
output_parametrized = model(x)
|
| 512 |
+
assert torch.all(output_parametrized == 4)
|
| 513 |
+
|
| 514 |
+
# add LoRA parametrization to the weight
|
| 515 |
+
config = LoraConfig(r=2, lora_alpha=6, target_parameters=["lin.weight"], init_lora_weights=False)
|
| 516 |
+
model = get_peft_model(model, config)
|
| 517 |
+
# manually set LoRA weights to ones
|
| 518 |
+
nn.init.ones_(model.base_model.model.lin.lora_A["default"].weight)
|
| 519 |
+
nn.init.ones_(model.base_model.model.lin.lora_B["default"].weight)
|
| 520 |
+
|
| 521 |
+
output_lora = model(x)
|
| 522 |
+
# delta_weight should be: (1+1) * lora_scale = (1+1) * (alpha / rank) = 2 * (6 / 2) = 6
|
| 523 |
+
# result should be: (1+1+6)*1 + (1+1+6)*1 == 8 + 8 == 16
|
| 524 |
+
assert torch.all(output_lora == 16)
|
| 525 |
+
|
| 526 |
+
# calling twice should yield the same result
|
| 527 |
+
output_lora2 = model(x)
|
| 528 |
+
assert torch.allclose(output_lora, output_lora2)
|
| 529 |
+
|
| 530 |
+
# add another LoRA parametrization to other_weight, should have no effect on the output
|
| 531 |
+
config = LoraConfig(r=2, lora_alpha=6, target_parameters=["lin.other_weight"], init_lora_weights=False)
|
| 532 |
+
model.add_adapter("other", config)
|
| 533 |
+
|
| 534 |
+
output_other_lora = model(x)
|
| 535 |
+
# delta_weight should be: (1+1) * lora_scale = (1+1) * (alpha / rank) = 2 * (6 / 2) = 6
|
| 536 |
+
# result should be: (1+1+6)*1 + (1+1+6)*1 == 8 + 8 == 16
|
| 537 |
+
assert torch.all(output_other_lora == output_lora)
|
| 538 |
+
|
| 539 |
+
# after unloading, the output should be the same as before LoRA was applied
|
| 540 |
+
unloaded = model.unload()
|
| 541 |
+
output_unloaded = unloaded(x)
|
| 542 |
+
assert torch.all(output_unloaded == output_parametrized)
|
| 543 |
+
|
| 544 |
+
def test_target_parameter_result_caching_works(self, monkeypatch):
|
| 545 |
+
# See 2912
|
| 546 |
+
# There was an issue with the caching of _LoraParameterProxy not working correctly. This test checks that the
|
| 547 |
+
# results returned from the forward call are all identical to ensure they're not recomputed each time.
|
| 548 |
+
torch.manual_seed(0)
|
| 549 |
+
model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
|
| 550 |
+
|
| 551 |
+
tensor_storage = []
|
| 552 |
+
|
| 553 |
+
def store_tensors_deco(fn):
|
| 554 |
+
def wrapper(*args, **kwargs):
|
| 555 |
+
result = fn(*args, **kwargs)
|
| 556 |
+
tensor_storage.append(result)
|
| 557 |
+
return result
|
| 558 |
+
|
| 559 |
+
return wrapper
|
| 560 |
+
|
| 561 |
+
monkeypatch.setattr(
|
| 562 |
+
peft.tuners.lora.layer._LoraParameterProxy,
|
| 563 |
+
"forward",
|
| 564 |
+
store_tensors_deco(peft.tuners.lora.layer._LoraParameterProxy.forward),
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
with hub_online_once(model_id):
|
| 568 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 569 |
+
config = LoraConfig(
|
| 570 |
+
target_modules=[],
|
| 571 |
+
# for simplicity, only target a single layer
|
| 572 |
+
target_parameters=["0.mlp.experts.gate_up_proj"],
|
| 573 |
+
)
|
| 574 |
+
model = get_peft_model(model, config)
|
| 575 |
+
x = torch.arange(100).view(2, 50) # larger input to hit many experts
|
| 576 |
+
|
| 577 |
+
# forward is called twice, once at initialization of the parametrization and once during the forward pass,
|
| 578 |
+
# after which it is cached; without caching, it would be called 25 times.
|
| 579 |
+
output = model(x, output_hidden_states=True)
|
| 580 |
+
assert len(set(map(id, tensor_storage))) == 2
|
| 581 |
+
|
| 582 |
+
# sanity check: a second forward call _does_ trigger a new forward
|
| 583 |
+
output = model(x, output_hidden_states=True)
|
| 584 |
+
assert len(set(map(id, tensor_storage))) == 4
|
| 585 |
+
|
| 586 |
+
def test_target_parameter_init_does_not_warn_about_unknown_layer_type(self, recwarn):
|
| 587 |
+
# For target parameters, the layer type is not known. This is fine, as the in_features and out_features are
|
| 588 |
+
# derived from the targeted parameter shape. But we need to ensure that there is no warning about the unknown
|
| 589 |
+
# layer type.
|
| 590 |
+
model_id = "trl-internal-testing/tiny-GptOssForCausalLM"
|
| 591 |
+
with hub_online_once(model_id):
|
| 592 |
+
model0 = AutoModelForCausalLM.from_pretrained(model_id)
|
| 593 |
+
config = LoraConfig(
|
| 594 |
+
target_modules=[],
|
| 595 |
+
target_parameters=["0.mlp.experts.gate_up_proj"],
|
| 596 |
+
)
|
| 597 |
+
model = get_peft_model(model0, config)
|
| 598 |
+
warn_messages = (w.message.args[0] for w in recwarn.list)
|
| 599 |
+
msg_start = "Unsupported layer type"
|
| 600 |
+
assert not any(msg.startswith(msg_start) for msg in warn_messages)
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_torch_compile.py
ADDED
|
@@ -0,0 +1,593 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
HRAConfig,
|
| 42 |
+
IA3Config,
|
| 43 |
+
LNTuningConfig,
|
| 44 |
+
LoHaConfig,
|
| 45 |
+
LoKrConfig,
|
| 46 |
+
LoraConfig,
|
| 47 |
+
MissConfig,
|
| 48 |
+
OFTConfig,
|
| 49 |
+
PeftModel,
|
| 50 |
+
TaskType,
|
| 51 |
+
VBLoRAConfig,
|
| 52 |
+
VeraConfig,
|
| 53 |
+
get_peft_model,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
from .testing_utils import load_dataset_english_quotes, require_bitsandbytes
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
# only run (very slow) torch.compile tests when explicitly asked to
|
| 60 |
+
if os.environ.get("PEFT_DEBUG_WITH_TORCH_COMPILE") != "1":
|
| 61 |
+
pytest.skip(allow_module_level=True)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
# Mapping: name of the setting -> (Peft config instance, torch.compile kwargs)
|
| 65 |
+
SETTINGS = {
|
| 66 |
+
"adalora": (AdaLoraConfig(task_type=TaskType.CAUSAL_LM, total_step=5), {}),
|
| 67 |
+
"boft": (BOFTConfig(task_type=TaskType.CAUSAL_LM), {}),
|
| 68 |
+
"dora": (LoraConfig(task_type=TaskType.CAUSAL_LM, use_dora=True), {}),
|
| 69 |
+
"ia3": (IA3Config(task_type=TaskType.CAUSAL_LM), {}),
|
| 70 |
+
"ln_tuning": (LNTuningConfig(task_type=TaskType.CAUSAL_LM, target_modules=["final_layer_norm"]), {}),
|
| 71 |
+
"loha": (LoHaConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 72 |
+
"lokr": pytest.param(
|
| 73 |
+
(LoKrConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 74 |
+
),
|
| 75 |
+
"lora": (LoraConfig(task_type=TaskType.CAUSAL_LM), {}),
|
| 76 |
+
"lora-target-embeddings": pytest.param(
|
| 77 |
+
(LoraConfig(task_type=TaskType.CAUSAL_LM, target_modules=["embed_tokens"]), {}),
|
| 78 |
+
),
|
| 79 |
+
"lora-with-modules-to-save": (LoraConfig(task_type=TaskType.CAUSAL_LM, modules_to_save=["embed_tokens"]), {}),
|
| 80 |
+
"oft": (OFTConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 81 |
+
"vblora": (VBLoRAConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], vector_length=2), {}),
|
| 82 |
+
"vera": (VeraConfig(task_type=TaskType.CAUSAL_LM), {}),
|
| 83 |
+
"hra": (HRAConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"]), {}),
|
| 84 |
+
"miss": (MissConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2), {}),
|
| 85 |
+
"miss-bat": (
|
| 86 |
+
MissConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2, init_weights="bat"),
|
| 87 |
+
{},
|
| 88 |
+
),
|
| 89 |
+
"miss-mini": (
|
| 90 |
+
MissConfig(task_type=TaskType.CAUSAL_LM, target_modules=["q_proj", "v_proj"], r=2, init_weights="mini"),
|
| 91 |
+
{},
|
| 92 |
+
),
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@pytest.mark.single_gpu_tests
|
| 97 |
+
class TestTorchCompileCausalLM:
|
| 98 |
+
"""
|
| 99 |
+
Tests for using torch.compile with causal LM.
|
| 100 |
+
|
| 101 |
+
Tip: When adding a new test, set `fake_compile = True` below. With this setting, torch.compile is being skipped.
|
| 102 |
+
This is useful for two reasons:
|
| 103 |
+
|
| 104 |
+
- compile is slow, so to quickly iterate on the test, it's best to disable it and only enable it at the very end
|
| 105 |
+
- even if you expect the test to fail with compile, as compile does not work with every PEFT feature, it still MUST
|
| 106 |
+
succeed without compile, otherwise the test is incorrect.
|
| 107 |
+
|
| 108 |
+
Before creating the PR, disable `fake_compile`.
|
| 109 |
+
"""
|
| 110 |
+
|
| 111 |
+
fake_compile = False
|
| 112 |
+
model_id = "peft-internal-testing/tiny-random-OPTForCausalLM"
|
| 113 |
+
max_train_loss = 15.0 # generous threshold for maximum loss after training
|
| 114 |
+
|
| 115 |
+
@pytest.fixture(autouse=True)
|
| 116 |
+
def teardown(self):
|
| 117 |
+
r"""
|
| 118 |
+
Efficient mechanism to free GPU memory after each test. Based on
|
| 119 |
+
https://github.com/huggingface/transformers/issues/21094
|
| 120 |
+
"""
|
| 121 |
+
clear_device_cache(garbage_collection=True)
|
| 122 |
+
gc.collect()
|
| 123 |
+
|
| 124 |
+
@pytest.fixture(scope="class")
|
| 125 |
+
def tokenizer(self):
|
| 126 |
+
return AutoTokenizer.from_pretrained(self.model_id)
|
| 127 |
+
|
| 128 |
+
@pytest.fixture(scope="class")
|
| 129 |
+
def data(self, tokenizer):
|
| 130 |
+
def tokenize(samples):
|
| 131 |
+
# For some reason, the max sequence length is not honored by the tokenizer, resulting in IndexErrors. Thus,
|
| 132 |
+
# manually ensure that sequences are not too long.
|
| 133 |
+
tokenized = tokenizer(samples["quote"])
|
| 134 |
+
tokenized["input_ids"] = [input_ids[: tokenizer.model_max_length] for input_ids in tokenized["input_ids"]]
|
| 135 |
+
tokenized["attention_mask"] = [
|
| 136 |
+
input_ids[: tokenizer.model_max_length] for input_ids in tokenized["attention_mask"]
|
| 137 |
+
]
|
| 138 |
+
return tokenized
|
| 139 |
+
|
| 140 |
+
data = load_dataset_english_quotes()
|
| 141 |
+
data = data.map(tokenize, batched=True)
|
| 142 |
+
# We need to manually remove unused columns. This is because we cannot use remove_unused_columns=True in the
|
| 143 |
+
# Trainer, as this leads to errors with torch.compile. We also cannot just leave them in, as they contain
|
| 144 |
+
# strings. Therefore, manually remove all unused columns.
|
| 145 |
+
data = data.remove_columns(["quote", "author", "tags"])
|
| 146 |
+
return data
|
| 147 |
+
|
| 148 |
+
def compile(self, model, compile_kwargs):
|
| 149 |
+
compile_kwargs = compile_kwargs.copy()
|
| 150 |
+
# those are only for the Trainer arguments
|
| 151 |
+
compile_kwargs.pop("torch_compile_backend", None)
|
| 152 |
+
compile_kwargs.pop("torch_compile_mode", None)
|
| 153 |
+
if self.fake_compile:
|
| 154 |
+
return model
|
| 155 |
+
return torch.compile(model, **compile_kwargs)
|
| 156 |
+
|
| 157 |
+
@pytest.mark.parametrize("settings", SETTINGS.values(), ids=SETTINGS.keys())
|
| 158 |
+
def test_causal_lm_training_trainer_compile(self, settings, tokenizer, data, tmp_path):
|
| 159 |
+
r"""Train a PEFT model with torch.compile using Trainer"""
|
| 160 |
+
tmp_dir = tmp_path / "model"
|
| 161 |
+
config, compile_kwargs = settings
|
| 162 |
+
|
| 163 |
+
torch.manual_seed(0)
|
| 164 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 165 |
+
self.model_id,
|
| 166 |
+
device_map="auto",
|
| 167 |
+
)
|
| 168 |
+
model = get_peft_model(model, config)
|
| 169 |
+
|
| 170 |
+
# record outputs before training
|
| 171 |
+
model.eval()
|
| 172 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 173 |
+
with torch.inference_mode():
|
| 174 |
+
output_before = model(sample)
|
| 175 |
+
model.train()
|
| 176 |
+
|
| 177 |
+
train_kwargs = {
|
| 178 |
+
"per_device_train_batch_size": 4,
|
| 179 |
+
"max_steps": 5,
|
| 180 |
+
"learning_rate": 1e-3,
|
| 181 |
+
"logging_steps": 1,
|
| 182 |
+
"output_dir": tmp_dir,
|
| 183 |
+
"seed": 0,
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
if isinstance(config, AdaLoraConfig):
|
| 187 |
+
train_kwargs["learning_rate"] = 1e-2
|
| 188 |
+
|
| 189 |
+
training_args = TrainingArguments(
|
| 190 |
+
torch_compile=not self.fake_compile,
|
| 191 |
+
torch_compile_backend=compile_kwargs.get("torch_compile_backend", None),
|
| 192 |
+
torch_compile_mode=compile_kwargs.get("torch_compile_mode", None),
|
| 193 |
+
**train_kwargs,
|
| 194 |
+
)
|
| 195 |
+
trainer = Trainer(
|
| 196 |
+
model=model,
|
| 197 |
+
train_dataset=data["train"],
|
| 198 |
+
args=training_args,
|
| 199 |
+
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
|
| 200 |
+
)
|
| 201 |
+
model.config.use_cache = False
|
| 202 |
+
|
| 203 |
+
if isinstance(config, AdaLoraConfig):
|
| 204 |
+
|
| 205 |
+
class OptimizerStepCallback(TrainerCallback):
|
| 206 |
+
def on_optimizer_step(self, args, state, control, **kwargs):
|
| 207 |
+
model.update_and_allocate(state.global_step)
|
| 208 |
+
|
| 209 |
+
trainer.add_callback(OptimizerStepCallback())
|
| 210 |
+
|
| 211 |
+
trainer.train()
|
| 212 |
+
|
| 213 |
+
model.eval()
|
| 214 |
+
atol, rtol = 1e-4, 1e-4
|
| 215 |
+
with torch.inference_mode():
|
| 216 |
+
output_after = model(sample)
|
| 217 |
+
tokens_after = model.generate(sample)
|
| 218 |
+
assert torch.isfinite(output_after.logits).all()
|
| 219 |
+
# sanity check: model was updated
|
| 220 |
+
assert not torch.allclose(output_before.logits, output_after.logits, atol=atol, rtol=rtol)
|
| 221 |
+
assert trainer.state.log_history[-1]["train_loss"] < self.max_train_loss
|
| 222 |
+
|
| 223 |
+
# check saving the model and loading it without compile
|
| 224 |
+
model.save_pretrained(tmp_path)
|
| 225 |
+
del model
|
| 226 |
+
torch.manual_seed(0)
|
| 227 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map="auto")
|
| 228 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 229 |
+
with torch.inference_mode():
|
| 230 |
+
output_loaded = model(sample)
|
| 231 |
+
tokens_loaded = model.generate(sample)
|
| 232 |
+
assert torch.allclose(output_after.logits, output_loaded.logits, atol=atol, rtol=rtol)
|
| 233 |
+
assert (tokens_after == tokens_loaded).all()
|
| 234 |
+
|
| 235 |
+
@pytest.mark.parametrize("settings", SETTINGS.values(), ids=SETTINGS.keys())
|
| 236 |
+
def test_causal_lm_training_pytorch_compile(self, settings, tokenizer, data, tmp_path):
|
| 237 |
+
r"""Train a PEFT model with torch.compile using PyTorch training loop"""
|
| 238 |
+
torch.manual_seed(0)
|
| 239 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 240 |
+
self.model_id,
|
| 241 |
+
device_map="auto",
|
| 242 |
+
)
|
| 243 |
+
config, compile_kwargs = settings
|
| 244 |
+
model = get_peft_model(model, config)
|
| 245 |
+
if isinstance(config, AdaLoraConfig):
|
| 246 |
+
model.base_model.peft_config["default"].total_step = 5
|
| 247 |
+
model = self.compile(model, compile_kwargs)
|
| 248 |
+
|
| 249 |
+
# record outputs before training
|
| 250 |
+
model.eval()
|
| 251 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 252 |
+
with torch.inference_mode():
|
| 253 |
+
output_before = model(sample)
|
| 254 |
+
model.train()
|
| 255 |
+
|
| 256 |
+
model.config.use_cache = False
|
| 257 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 258 |
+
batch_size = 4
|
| 259 |
+
losses = []
|
| 260 |
+
max_steps = 5 * batch_size
|
| 261 |
+
for i in range(0, max_steps, batch_size):
|
| 262 |
+
batch = tokenizer.pad(data["train"][i : i + batch_size], return_tensors="pt").to(model.device)
|
| 263 |
+
# add targets
|
| 264 |
+
batch["labels"] = batch["input_ids"].clone()
|
| 265 |
+
optimizer.zero_grad()
|
| 266 |
+
outputs = model(**batch)
|
| 267 |
+
loss = outputs.loss
|
| 268 |
+
loss.backward()
|
| 269 |
+
optimizer.step()
|
| 270 |
+
losses.append(loss.item())
|
| 271 |
+
if isinstance(config, AdaLoraConfig):
|
| 272 |
+
model.base_model.update_and_allocate(i)
|
| 273 |
+
|
| 274 |
+
model.eval()
|
| 275 |
+
with torch.inference_mode():
|
| 276 |
+
output_after = model(sample)
|
| 277 |
+
tokens_after = model.generate(sample)
|
| 278 |
+
assert torch.isfinite(output_after.logits).all()
|
| 279 |
+
atol, rtol = 1e-4, 1e-4
|
| 280 |
+
# sanity check: model was updated
|
| 281 |
+
assert not torch.allclose(output_before.logits, output_after.logits, atol=atol, rtol=rtol)
|
| 282 |
+
assert losses[-1] < self.max_train_loss
|
| 283 |
+
|
| 284 |
+
# check saving the model and loading it without compile
|
| 285 |
+
model.save_pretrained(tmp_path)
|
| 286 |
+
del model
|
| 287 |
+
torch.manual_seed(0)
|
| 288 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id, device_map="auto")
|
| 289 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 290 |
+
with torch.inference_mode():
|
| 291 |
+
output_loaded = model(sample)
|
| 292 |
+
tokens_loaded = model.generate(sample)
|
| 293 |
+
assert torch.allclose(output_after.logits, output_loaded.logits, atol=atol, rtol=rtol)
|
| 294 |
+
assert (tokens_after == tokens_loaded).all()
|
| 295 |
+
|
| 296 |
+
@require_bitsandbytes
|
| 297 |
+
def test_causal_lm_training_lora_bnb_compile(self, tokenizer, data, tmp_path):
|
| 298 |
+
r"""Train a bnb quantized LoRA model with torch.compile using PyTorch training loop"""
|
| 299 |
+
torch.manual_seed(0)
|
| 300 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 301 |
+
self.model_id,
|
| 302 |
+
device_map="auto",
|
| 303 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 304 |
+
)
|
| 305 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM)
|
| 306 |
+
model = get_peft_model(model, config)
|
| 307 |
+
model = self.compile(model, {})
|
| 308 |
+
|
| 309 |
+
# record outputs before training
|
| 310 |
+
model.eval()
|
| 311 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 312 |
+
with torch.inference_mode():
|
| 313 |
+
output_before = model(sample)
|
| 314 |
+
model.train()
|
| 315 |
+
|
| 316 |
+
model.config.use_cache = False
|
| 317 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 318 |
+
batch_size = 4
|
| 319 |
+
losses = []
|
| 320 |
+
max_steps = 5 * batch_size
|
| 321 |
+
for i in range(0, max_steps, batch_size):
|
| 322 |
+
batch = tokenizer.pad(data["train"][i : i + batch_size], return_tensors="pt").to(model.device)
|
| 323 |
+
# add targets
|
| 324 |
+
batch["labels"] = batch["input_ids"].clone()
|
| 325 |
+
optimizer.zero_grad()
|
| 326 |
+
outputs = model(**batch)
|
| 327 |
+
loss = outputs.loss
|
| 328 |
+
loss.backward()
|
| 329 |
+
optimizer.step()
|
| 330 |
+
losses.append(loss.item())
|
| 331 |
+
|
| 332 |
+
model.eval()
|
| 333 |
+
with torch.inference_mode():
|
| 334 |
+
output_after = model(sample)
|
| 335 |
+
assert torch.isfinite(output_after.logits).all()
|
| 336 |
+
atol, rtol = 5e-4, 5e-4
|
| 337 |
+
# sanity check: model was updated
|
| 338 |
+
assert not torch.allclose(output_before.logits, output_after.logits, atol=atol, rtol=rtol)
|
| 339 |
+
assert losses[-1] < self.max_train_loss
|
| 340 |
+
|
| 341 |
+
# check saving the model and loading it without compile
|
| 342 |
+
model.save_pretrained(tmp_path)
|
| 343 |
+
del model
|
| 344 |
+
torch.manual_seed(0)
|
| 345 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 346 |
+
self.model_id, device_map="auto", quantization_config=BitsAndBytesConfig(load_in_4bit=True)
|
| 347 |
+
)
|
| 348 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 349 |
+
|
| 350 |
+
with torch.inference_mode():
|
| 351 |
+
# after loading, outputs are float32 for some reason
|
| 352 |
+
output_loaded = model(sample)
|
| 353 |
+
assert torch.allclose(output_after.logits, output_loaded.logits, atol=atol, rtol=rtol)
|
| 354 |
+
|
| 355 |
+
@require_bitsandbytes
|
| 356 |
+
def test_causal_lm_multiple_lora_adapter_compile(self, tokenizer, data):
|
| 357 |
+
torch.manual_seed(0)
|
| 358 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 359 |
+
self.model_id,
|
| 360 |
+
device_map="auto",
|
| 361 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 362 |
+
).eval()
|
| 363 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 364 |
+
with torch.inference_mode():
|
| 365 |
+
output_base = model(sample)
|
| 366 |
+
|
| 367 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 368 |
+
model = get_peft_model(model, config)
|
| 369 |
+
model.add_adapter("other", config)
|
| 370 |
+
model = self.compile(model, {})
|
| 371 |
+
model.eval()
|
| 372 |
+
|
| 373 |
+
with torch.inference_mode():
|
| 374 |
+
output_default_adapter = model(sample)
|
| 375 |
+
model.set_adapter("other")
|
| 376 |
+
with torch.inference_mode():
|
| 377 |
+
output_other_adapter = model(sample)
|
| 378 |
+
|
| 379 |
+
atol, rtol = 1e-4, 1e-4
|
| 380 |
+
# outputs of the base model != output of default adapter != output of other adapter
|
| 381 |
+
assert not torch.allclose(output_base.logits, output_default_adapter.logits, atol=atol, rtol=rtol)
|
| 382 |
+
assert not torch.allclose(output_base.logits, output_other_adapter.logits, atol=atol, rtol=rtol)
|
| 383 |
+
assert not torch.allclose(output_default_adapter.logits, output_other_adapter.logits, atol=atol, rtol=rtol)
|
| 384 |
+
|
| 385 |
+
# now delete the other adapter
|
| 386 |
+
model.delete_adapter("other")
|
| 387 |
+
model.set_adapter("default")
|
| 388 |
+
with torch.inference_mode():
|
| 389 |
+
output_after_delete = model(sample)
|
| 390 |
+
|
| 391 |
+
# outputs after delete == output of default adapter
|
| 392 |
+
assert torch.allclose(output_default_adapter.logits, output_after_delete.logits, atol=atol, rtol=rtol)
|
| 393 |
+
|
| 394 |
+
def test_causal_lm_disable_lora_adapter_compile(self, tokenizer, data):
|
| 395 |
+
torch.manual_seed(0)
|
| 396 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 397 |
+
self.model_id,
|
| 398 |
+
device_map="auto",
|
| 399 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 400 |
+
).eval()
|
| 401 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 402 |
+
with torch.inference_mode():
|
| 403 |
+
output_base = model(sample)
|
| 404 |
+
|
| 405 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 406 |
+
model = get_peft_model(model, config).eval()
|
| 407 |
+
model = self.compile(model, {})
|
| 408 |
+
output_lora = model(sample)
|
| 409 |
+
|
| 410 |
+
with model.disable_adapter():
|
| 411 |
+
with torch.inference_mode():
|
| 412 |
+
output_disabled = model(sample)
|
| 413 |
+
|
| 414 |
+
atol, rtol = 5e-4, 5e-4
|
| 415 |
+
# outputs of the base model == output disabled adapter != output of lora adapter
|
| 416 |
+
assert torch.allclose(output_base.logits, output_disabled.logits, atol=atol, rtol=rtol)
|
| 417 |
+
assert not torch.allclose(output_base.logits, output_lora.logits, atol=atol, rtol=rtol)
|
| 418 |
+
|
| 419 |
+
@require_bitsandbytes
|
| 420 |
+
def test_causal_lm_merging_lora_adapter_compile(self, tokenizer, data):
|
| 421 |
+
# merge the adapter
|
| 422 |
+
torch.manual_seed(0)
|
| 423 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 424 |
+
self.model_id,
|
| 425 |
+
device_map="auto",
|
| 426 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 427 |
+
).eval()
|
| 428 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 429 |
+
with torch.inference_mode():
|
| 430 |
+
output_base = model(sample)
|
| 431 |
+
|
| 432 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 433 |
+
model = get_peft_model(model, config).eval()
|
| 434 |
+
with torch.inference_mode():
|
| 435 |
+
output_lora = model(sample)
|
| 436 |
+
|
| 437 |
+
model.merge_adapter()
|
| 438 |
+
with torch.inference_mode():
|
| 439 |
+
output_merged = model(sample)
|
| 440 |
+
|
| 441 |
+
# merging is less precise, be more tolerant
|
| 442 |
+
atol, rtol = 1e-1, 1e-1
|
| 443 |
+
# outputs of the base model != output of lora adapter == output of merged adapter
|
| 444 |
+
assert not torch.allclose(output_base.logits, output_lora.logits, atol=atol, rtol=rtol)
|
| 445 |
+
assert torch.allclose(output_lora.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 446 |
+
|
| 447 |
+
@require_bitsandbytes
|
| 448 |
+
def test_causal_lm_merging_multiple_lora_adapters_compile(self, tokenizer, data):
|
| 449 |
+
# merge multiple adapters at once
|
| 450 |
+
torch.manual_seed(0)
|
| 451 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 452 |
+
self.model_id,
|
| 453 |
+
device_map="auto",
|
| 454 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 455 |
+
).eval()
|
| 456 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 457 |
+
with torch.inference_mode():
|
| 458 |
+
output_base = model(sample)
|
| 459 |
+
|
| 460 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 461 |
+
model = get_peft_model(model, config).eval()
|
| 462 |
+
model.add_adapter("other", config)
|
| 463 |
+
with torch.inference_mode():
|
| 464 |
+
output_default = model(sample)
|
| 465 |
+
|
| 466 |
+
model.set_adapter("other")
|
| 467 |
+
with torch.inference_mode():
|
| 468 |
+
output_other = model(sample)
|
| 469 |
+
|
| 470 |
+
model.base_model.merge_adapter(["default", "other"])
|
| 471 |
+
with torch.inference_mode():
|
| 472 |
+
output_merged = model(sample)
|
| 473 |
+
|
| 474 |
+
# merging is less precise, be more tolerant
|
| 475 |
+
atol, rtol = 1e-1, 1e-1
|
| 476 |
+
# outputs of the base model != output of default adapter != output of other adapter
|
| 477 |
+
assert not torch.allclose(output_base.logits, output_default.logits, atol=atol, rtol=rtol)
|
| 478 |
+
assert not torch.allclose(output_base.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 479 |
+
assert not torch.allclose(output_default.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 480 |
+
# outputs of merged adapter != all others
|
| 481 |
+
assert not torch.allclose(output_base.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 482 |
+
assert not torch.allclose(output_default.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 483 |
+
assert not torch.allclose(output_other.logits, output_merged.logits, atol=atol, rtol=rtol)
|
| 484 |
+
|
| 485 |
+
@require_bitsandbytes
|
| 486 |
+
def test_causal_lm_merge_and_unload_lora_adapter_compile(self, tokenizer, data):
|
| 487 |
+
torch.manual_seed(0)
|
| 488 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 489 |
+
self.model_id,
|
| 490 |
+
device_map="auto",
|
| 491 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 492 |
+
).eval()
|
| 493 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 494 |
+
with torch.inference_mode():
|
| 495 |
+
output_base = model(sample)
|
| 496 |
+
|
| 497 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 498 |
+
model = get_peft_model(model, config).eval()
|
| 499 |
+
model = self.compile(model, {})
|
| 500 |
+
with torch.inference_mode():
|
| 501 |
+
output_lora = model(sample)
|
| 502 |
+
|
| 503 |
+
unloaded = model.merge_and_unload()
|
| 504 |
+
with torch.inference_mode():
|
| 505 |
+
output_unloaded = unloaded(sample)
|
| 506 |
+
|
| 507 |
+
# merging is less precise, be more tolerant
|
| 508 |
+
atol, rtol = 1e-1, 1e-1
|
| 509 |
+
# outputs of the base model != output of lora adapter == output of unloaded adapter
|
| 510 |
+
assert not torch.allclose(output_base.logits, output_lora.logits, atol=atol, rtol=rtol)
|
| 511 |
+
assert torch.allclose(output_lora.logits, output_unloaded.logits, atol=atol, rtol=rtol)
|
| 512 |
+
|
| 513 |
+
@require_bitsandbytes
|
| 514 |
+
def test_causal_lm_mixed_batch_lora_adapter_compile(self, tokenizer, data):
|
| 515 |
+
torch.manual_seed(0)
|
| 516 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 517 |
+
self.model_id,
|
| 518 |
+
device_map="auto",
|
| 519 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 520 |
+
).eval()
|
| 521 |
+
|
| 522 |
+
# we need at least 3 samples for this to work!
|
| 523 |
+
sample = {
|
| 524 |
+
"input_ids": torch.arange(12).reshape(3, 4).to("cuda"),
|
| 525 |
+
"attention_mask": torch.ones(3, 4).long().to("cuda"),
|
| 526 |
+
}
|
| 527 |
+
|
| 528 |
+
with torch.inference_mode():
|
| 529 |
+
output_base = model(**sample)
|
| 530 |
+
|
| 531 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 532 |
+
model = get_peft_model(model, config).eval()
|
| 533 |
+
with torch.inference_mode():
|
| 534 |
+
output_default = model(**sample)
|
| 535 |
+
|
| 536 |
+
model.add_adapter("other", config)
|
| 537 |
+
model.set_adapter("other")
|
| 538 |
+
with torch.inference_mode():
|
| 539 |
+
output_other = model(**sample)
|
| 540 |
+
|
| 541 |
+
model = self.compile(model, {})
|
| 542 |
+
|
| 543 |
+
# set adapter_indices so that it alternates between 0 (base), lora 1, and lora 2
|
| 544 |
+
adapter_names = ["__base__", "default", "other"]
|
| 545 |
+
with torch.inference_mode():
|
| 546 |
+
output_mixed = model(**sample, adapter_names=adapter_names)
|
| 547 |
+
|
| 548 |
+
atol, rtol = 5e-4, 5e-4
|
| 549 |
+
# outputs of the base model != output of lora adapter 1 != output of other adapter
|
| 550 |
+
assert not torch.allclose(output_base.logits, output_default.logits, atol=atol, rtol=rtol)
|
| 551 |
+
assert not torch.allclose(output_default.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 552 |
+
assert not torch.allclose(output_other.logits, output_mixed.logits, atol=atol, rtol=rtol)
|
| 553 |
+
# outputs of mixed adapter is mix of all 3
|
| 554 |
+
assert torch.allclose(output_base.logits[0], output_mixed.logits[0], atol=atol, rtol=rtol)
|
| 555 |
+
assert torch.allclose(output_default.logits[1], output_mixed.logits[1], atol=atol, rtol=rtol)
|
| 556 |
+
assert torch.allclose(output_other.logits[2], output_mixed.logits[2], atol=atol, rtol=rtol)
|
| 557 |
+
|
| 558 |
+
@require_bitsandbytes
|
| 559 |
+
def test_causal_lm_add_weighted_adapter_lora_adapter_compile(self, tokenizer, data):
|
| 560 |
+
torch.manual_seed(0)
|
| 561 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 562 |
+
self.model_id,
|
| 563 |
+
device_map="auto",
|
| 564 |
+
quantization_config=BitsAndBytesConfig(load_in_4bit=True),
|
| 565 |
+
).eval()
|
| 566 |
+
sample = torch.tensor(data["train"][:1]["input_ids"]).to(model.device)
|
| 567 |
+
with torch.inference_mode():
|
| 568 |
+
output_base = model(sample)
|
| 569 |
+
|
| 570 |
+
config = LoraConfig(task_type=TaskType.CAUSAL_LM, init_lora_weights=False)
|
| 571 |
+
model = get_peft_model(model, config).eval()
|
| 572 |
+
model.add_adapter("other", config)
|
| 573 |
+
with torch.inference_mode():
|
| 574 |
+
output_default = model(sample)
|
| 575 |
+
|
| 576 |
+
model.set_adapter("other")
|
| 577 |
+
with torch.inference_mode():
|
| 578 |
+
output_other = model(sample)
|
| 579 |
+
|
| 580 |
+
model.add_weighted_adapter(["default", "other"], [0.5, 0.5], adapter_name="combined")
|
| 581 |
+
model.set_adapter("combined")
|
| 582 |
+
with torch.inference_mode():
|
| 583 |
+
output_combined = model(sample)
|
| 584 |
+
|
| 585 |
+
atol, rtol = 1e-4, 1e-4
|
| 586 |
+
# outputs of the base model != output of default adapter != output of other adapter
|
| 587 |
+
assert not torch.allclose(output_base.logits, output_default.logits, atol=atol, rtol=rtol)
|
| 588 |
+
assert not torch.allclose(output_base.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 589 |
+
assert not torch.allclose(output_default.logits, output_other.logits, atol=atol, rtol=rtol)
|
| 590 |
+
# outputs of combined adapter != all others
|
| 591 |
+
assert not torch.allclose(output_base.logits, output_combined.logits, atol=atol, rtol=rtol)
|
| 592 |
+
assert not torch.allclose(output_default.logits, output_combined.logits, atol=atol, rtol=rtol)
|
| 593 |
+
assert not torch.allclose(output_other.logits, output_combined.logits, atol=atol, rtol=rtol)
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_trainable_tokens.py
ADDED
|
@@ -0,0 +1,1389 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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.import_utils import is_transformers_ge_v5
|
| 27 |
+
from peft.tuners.trainable_tokens.layer import TrainableTokensLayer
|
| 28 |
+
from peft.utils import TrainableTokensWrapper, get_peft_model_state_dict
|
| 29 |
+
|
| 30 |
+
from .testing_utils import hub_online_once
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
class ModelEmb(torch.nn.Module):
|
| 34 |
+
def __init__(self):
|
| 35 |
+
super().__init__()
|
| 36 |
+
self.emb = torch.nn.Embedding(100, 10)
|
| 37 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 38 |
+
|
| 39 |
+
def forward(self, x):
|
| 40 |
+
return self.lin0(self.emb(x))
|
| 41 |
+
|
| 42 |
+
def get_input_embeddings(self):
|
| 43 |
+
return self.emb
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class ModelEmbedIn(torch.nn.Module):
|
| 47 |
+
def __init__(self):
|
| 48 |
+
super().__init__()
|
| 49 |
+
self.embed_in = torch.nn.Embedding(100, 10)
|
| 50 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 51 |
+
|
| 52 |
+
def forward(self, x):
|
| 53 |
+
return self.lin0(self.embed_in(x))
|
| 54 |
+
|
| 55 |
+
def get_input_embeddings(self):
|
| 56 |
+
return self.embed_in
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
class ModelEmbedMultiple(torch.nn.Module):
|
| 60 |
+
def __init__(self):
|
| 61 |
+
super().__init__()
|
| 62 |
+
self.embed_in = torch.nn.Embedding(100, 10)
|
| 63 |
+
self.embed_in_2 = torch.nn.Embedding(100, 10)
|
| 64 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 65 |
+
|
| 66 |
+
def forward(self, x):
|
| 67 |
+
return self.lin0(self.embed_in(x) + self.embed_in_2(x))
|
| 68 |
+
|
| 69 |
+
def get_input_embeddings(self):
|
| 70 |
+
return self.embed_in
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ModelEmbedInNoGet(torch.nn.Module):
|
| 74 |
+
def __init__(self):
|
| 75 |
+
super().__init__()
|
| 76 |
+
self.embed_in = torch.nn.Embedding(100, 10)
|
| 77 |
+
self.lin0 = torch.nn.Linear(10, 1)
|
| 78 |
+
|
| 79 |
+
def forward(self, x):
|
| 80 |
+
return self.lin0(self.embed_in(x))
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class TestTrainableTokens:
|
| 84 |
+
@pytest.fixture
|
| 85 |
+
def model_id(self):
|
| 86 |
+
return "trl-internal-testing/tiny-random-LlamaForCausalLM"
|
| 87 |
+
|
| 88 |
+
@pytest.fixture
|
| 89 |
+
def model_multi_embedding(self):
|
| 90 |
+
class MultiEmbeddingMLP(torch.nn.Module):
|
| 91 |
+
def __init__(self):
|
| 92 |
+
super().__init__()
|
| 93 |
+
self.emb_text = torch.nn.Embedding(10, 5)
|
| 94 |
+
self.emb_image = torch.nn.Embedding(8, 5)
|
| 95 |
+
self.lin0 = torch.nn.Linear(5, 10)
|
| 96 |
+
self.lin1 = torch.nn.Linear(10, 20)
|
| 97 |
+
|
| 98 |
+
def forward(self, x_text, x_image):
|
| 99 |
+
x_text = self.emb_text(x_text)
|
| 100 |
+
x_image = self.emb_image(x_image)
|
| 101 |
+
y = self.lin0(torch.concat([x_text, x_image], dim=1).view(-1, 5))
|
| 102 |
+
y = self.lin1(y)
|
| 103 |
+
return y, (x_text, x_image)
|
| 104 |
+
|
| 105 |
+
return MultiEmbeddingMLP()
|
| 106 |
+
|
| 107 |
+
@pytest.fixture
|
| 108 |
+
def model(self, model_id):
|
| 109 |
+
with hub_online_once(model_id):
|
| 110 |
+
# This must not be a yield fixture so that we don't carry the hub_online_once
|
| 111 |
+
# behavior over to the rest of the test that uses this fixture
|
| 112 |
+
return AutoModelForCausalLM.from_pretrained(model_id)
|
| 113 |
+
|
| 114 |
+
@pytest.fixture
|
| 115 |
+
def tokenizer(self, model_id):
|
| 116 |
+
return AutoTokenizer.from_pretrained(model_id)
|
| 117 |
+
|
| 118 |
+
def simulate_training(self, trainable_tokens_layer, adapter_name="default"):
|
| 119 |
+
"""Simulates training of trainable_tokens adapter layer by assigning random
|
| 120 |
+
values to the delta tokens.
|
| 121 |
+
"""
|
| 122 |
+
trainable_tokens_layer.trainable_tokens_delta[adapter_name].data = torch.rand_like(
|
| 123 |
+
trainable_tokens_layer.trainable_tokens_delta[adapter_name].data
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
def test_stand_alone_usage(self, model, tokenizer, tmp_path):
|
| 127 |
+
original_model = copy.deepcopy(model)
|
| 128 |
+
|
| 129 |
+
peft_config = TrainableTokensConfig(target_modules=["embed_tokens"], token_indices=[0, 1, 3])
|
| 130 |
+
peft_model = get_peft_model(model, peft_config)
|
| 131 |
+
save_path = tmp_path / "stand_alone_usage"
|
| 132 |
+
|
| 133 |
+
# simulate normal use but take care to use the tokens that we expect to be modified
|
| 134 |
+
# (+1 that we don't expect to be modified)
|
| 135 |
+
X = {
|
| 136 |
+
"input_ids": torch.tensor([[0, 1, 2, 3]]),
|
| 137 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1]]),
|
| 138 |
+
}
|
| 139 |
+
|
| 140 |
+
idcs_to_modify = peft_config.token_indices
|
| 141 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 142 |
+
|
| 143 |
+
self.simulate_training(peft_model.model.model.embed_tokens)
|
| 144 |
+
output_train = peft_model(output_hidden_states=True, **X)
|
| 145 |
+
|
| 146 |
+
peft_model.save_pretrained(save_path)
|
| 147 |
+
peft_model_org = peft_model
|
| 148 |
+
|
| 149 |
+
# check whether the token indices differ from the base model after loading the model
|
| 150 |
+
# from the checkpoint.
|
| 151 |
+
peft_model = AutoPeftModel.from_pretrained(save_path)
|
| 152 |
+
output_load = peft_model(output_hidden_states=True, **X)
|
| 153 |
+
output_orig = original_model(output_hidden_states=True, **X)
|
| 154 |
+
|
| 155 |
+
# on the way, make sure that the embedding matrix itself was not modified
|
| 156 |
+
assert torch.allclose(
|
| 157 |
+
peft_model.model.model.embed_tokens.weight,
|
| 158 |
+
peft_model_org.model.model.embed_tokens.weight,
|
| 159 |
+
)
|
| 160 |
+
|
| 161 |
+
W_load = output_load.hidden_states[0]
|
| 162 |
+
W_orig = output_orig.hidden_states[0]
|
| 163 |
+
W_train = output_train.hidden_states[0]
|
| 164 |
+
|
| 165 |
+
# all PEFT model embed outputs must equal the outputs during 'training' to make sure
|
| 166 |
+
# that saving/loading works properly.
|
| 167 |
+
assert torch.allclose(W_load, W_train)
|
| 168 |
+
|
| 169 |
+
assert not torch.allclose(W_load[:, idcs_to_modify], W_orig[:, idcs_to_modify])
|
| 170 |
+
assert torch.allclose(W_load[:, idcs_to_keep], W_orig[:, idcs_to_keep])
|
| 171 |
+
|
| 172 |
+
@pytest.mark.parametrize(
|
| 173 |
+
"peft_config",
|
| 174 |
+
[
|
| 175 |
+
LoraConfig(
|
| 176 |
+
target_modules="all-linear",
|
| 177 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 178 |
+
),
|
| 179 |
+
],
|
| 180 |
+
)
|
| 181 |
+
def test_combined_with_peft_method_usage(self, model, tokenizer, peft_config, tmp_path):
|
| 182 |
+
original_model = copy.deepcopy(model)
|
| 183 |
+
peft_model = get_peft_model(model, peft_config)
|
| 184 |
+
save_path = tmp_path / "combined_usage"
|
| 185 |
+
|
| 186 |
+
# simulate normal use but take care to use the tokens that we expect to be modified
|
| 187 |
+
# (+2 that we don't expect to be modified)
|
| 188 |
+
X = {
|
| 189 |
+
"input_ids": torch.tensor([[0, 1, 2, 3, 4]]),
|
| 190 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1, 1]]),
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
idcs_to_modify = peft_config.trainable_token_indices["embed_tokens"]
|
| 194 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 195 |
+
|
| 196 |
+
self.simulate_training(peft_model.model.model.embed_tokens.token_adapter)
|
| 197 |
+
output_train = peft_model(output_hidden_states=True, **X)
|
| 198 |
+
|
| 199 |
+
peft_model.save_pretrained(save_path)
|
| 200 |
+
peft_model_org = peft_model
|
| 201 |
+
|
| 202 |
+
# check whether the token indices differ from the base model
|
| 203 |
+
peft_model = AutoPeftModel.from_pretrained(save_path)
|
| 204 |
+
output_load = peft_model(output_hidden_states=True, **X)
|
| 205 |
+
output_orig = original_model(output_hidden_states=True, **X)
|
| 206 |
+
|
| 207 |
+
W_load = output_load.hidden_states[0]
|
| 208 |
+
W_orig = output_orig.hidden_states[0]
|
| 209 |
+
W_train = output_train.hidden_states[0]
|
| 210 |
+
|
| 211 |
+
# all PEFT model embed outputs must equal the outputs during 'training' to make sure
|
| 212 |
+
# that saving/loading works properly.
|
| 213 |
+
assert torch.allclose(W_load, W_train)
|
| 214 |
+
|
| 215 |
+
assert not torch.allclose(W_load[:, idcs_to_modify], W_orig[:, idcs_to_modify])
|
| 216 |
+
assert torch.allclose(W_load[:, idcs_to_keep], W_orig[:, idcs_to_keep])
|
| 217 |
+
|
| 218 |
+
def test_basic_training(self, model, tokenizer):
|
| 219 |
+
# ensure that the model can be trained and backpropagation works
|
| 220 |
+
config = TrainableTokensConfig(
|
| 221 |
+
target_modules=["embed_tokens"],
|
| 222 |
+
token_indices=[0, 10],
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
model = get_peft_model(model, config)
|
| 226 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1)
|
| 227 |
+
|
| 228 |
+
initial_delta = model.model.model.embed_tokens.trainable_tokens_delta.default.clone()
|
| 229 |
+
initial_originals = model.model.model.embed_tokens.trainable_tokens_original.default.clone()
|
| 230 |
+
|
| 231 |
+
X = {
|
| 232 |
+
"input_ids": torch.tensor([[0, 1, 2, 3, 4]]),
|
| 233 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1, 1]]),
|
| 234 |
+
}
|
| 235 |
+
|
| 236 |
+
for step in range(3):
|
| 237 |
+
optimizer.zero_grad()
|
| 238 |
+
y_pred = model(**X)
|
| 239 |
+
loss = y_pred.logits.mean()
|
| 240 |
+
loss.backward()
|
| 241 |
+
optimizer.step()
|
| 242 |
+
|
| 243 |
+
assert torch.allclose(
|
| 244 |
+
model.model.model.embed_tokens.trainable_tokens_original.default,
|
| 245 |
+
initial_originals,
|
| 246 |
+
)
|
| 247 |
+
assert not torch.allclose(
|
| 248 |
+
model.model.model.embed_tokens.trainable_tokens_delta.default,
|
| 249 |
+
initial_delta,
|
| 250 |
+
)
|
| 251 |
+
|
| 252 |
+
@pytest.mark.parametrize(
|
| 253 |
+
"peft_config",
|
| 254 |
+
[
|
| 255 |
+
LoraConfig(
|
| 256 |
+
target_modules="all-linear",
|
| 257 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 258 |
+
),
|
| 259 |
+
],
|
| 260 |
+
)
|
| 261 |
+
def test_disable_adapters_with_merging(self, model, tokenizer, peft_config):
|
| 262 |
+
X = {
|
| 263 |
+
"input_ids": torch.tensor([[0, 1, 2, 3, 4]]),
|
| 264 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1, 1]]),
|
| 265 |
+
}
|
| 266 |
+
|
| 267 |
+
model = get_peft_model(model, peft_config)
|
| 268 |
+
model.eval()
|
| 269 |
+
|
| 270 |
+
outputs_before = model(**X).logits
|
| 271 |
+
|
| 272 |
+
model.train()
|
| 273 |
+
lr = 0.01
|
| 274 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=lr)
|
| 275 |
+
|
| 276 |
+
# train at least 3 steps for all parameters to be updated (probably this is required because of symmetry
|
| 277 |
+
# breaking of some LoRA layers that are initialized with constants)
|
| 278 |
+
for _ in range(3):
|
| 279 |
+
optimizer.zero_grad()
|
| 280 |
+
y_pred = model(**X)
|
| 281 |
+
loss = y_pred.logits.mean()
|
| 282 |
+
loss.backward()
|
| 283 |
+
optimizer.step()
|
| 284 |
+
|
| 285 |
+
model.eval()
|
| 286 |
+
outputs_unmerged = model(**X).logits
|
| 287 |
+
model.merge_adapter()
|
| 288 |
+
outputs_after = model(**X).logits
|
| 289 |
+
|
| 290 |
+
with model.disable_adapter():
|
| 291 |
+
outputs_disabled = model(**X).logits
|
| 292 |
+
|
| 293 |
+
# check that after leaving the disable_adapter context, everything is enabled again
|
| 294 |
+
outputs_enabled_after_disable = model(**X).logits
|
| 295 |
+
|
| 296 |
+
atol, rtol = 1e-5, 1e-5 # tolerances higher than defaults since merging introduces some numerical instability
|
| 297 |
+
|
| 298 |
+
# check that there is a difference in results after training
|
| 299 |
+
assert not torch.allclose(outputs_before, outputs_after, atol=atol, rtol=rtol)
|
| 300 |
+
|
| 301 |
+
# unmerged or merged should make no difference
|
| 302 |
+
assert torch.allclose(outputs_after, outputs_unmerged, atol=atol, rtol=rtol)
|
| 303 |
+
|
| 304 |
+
# check that disabling adapters gives the same results as before training
|
| 305 |
+
assert torch.allclose(outputs_before, outputs_disabled, atol=atol, rtol=rtol)
|
| 306 |
+
|
| 307 |
+
# check that enabling + disabling adapters does not change the results
|
| 308 |
+
assert torch.allclose(outputs_after, outputs_enabled_after_disable, atol=atol, rtol=rtol)
|
| 309 |
+
|
| 310 |
+
@pytest.mark.parametrize(
|
| 311 |
+
"peft_config",
|
| 312 |
+
[
|
| 313 |
+
LoraConfig(
|
| 314 |
+
target_modules="all-linear",
|
| 315 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 316 |
+
),
|
| 317 |
+
],
|
| 318 |
+
)
|
| 319 |
+
def test_safe_merge_with_adapter(self, model, tokenizer, peft_config):
|
| 320 |
+
X = {
|
| 321 |
+
"input_ids": torch.tensor([[0, 1, 2, 3]]),
|
| 322 |
+
"attention_mask": torch.tensor([[1, 1, 1, 1]]),
|
| 323 |
+
}
|
| 324 |
+
|
| 325 |
+
model = model.eval()
|
| 326 |
+
logits_base = model(**X).logits
|
| 327 |
+
|
| 328 |
+
model = get_peft_model(model, peft_config).eval()
|
| 329 |
+
logits_peft = model(**X).logits
|
| 330 |
+
|
| 331 |
+
atol, rtol = 1e-6, 1e-6 # default
|
| 332 |
+
|
| 333 |
+
model_unloaded = model.merge_and_unload(safe_merge=True)
|
| 334 |
+
logits_unloaded = model_unloaded(**X).logits
|
| 335 |
+
|
| 336 |
+
# check that the logits are the same after unloading
|
| 337 |
+
assert torch.allclose(logits_peft, logits_unloaded, atol=atol, rtol=rtol)
|
| 338 |
+
|
| 339 |
+
@pytest.mark.parametrize(
|
| 340 |
+
"peft_config",
|
| 341 |
+
[
|
| 342 |
+
LoraConfig(
|
| 343 |
+
target_modules="all-linear",
|
| 344 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 345 |
+
),
|
| 346 |
+
],
|
| 347 |
+
)
|
| 348 |
+
def test_load_multiple_adapters(self, model, peft_config, tmp_path):
|
| 349 |
+
# tests if having more than one adpater (even with just the same config) works
|
| 350 |
+
original_model = copy.deepcopy(model)
|
| 351 |
+
model = get_peft_model(model, peft_config)
|
| 352 |
+
|
| 353 |
+
model.save_pretrained(tmp_path)
|
| 354 |
+
del model
|
| 355 |
+
|
| 356 |
+
model = original_model
|
| 357 |
+
model = PeftModel.from_pretrained(model, tmp_path)
|
| 358 |
+
load_result1 = model.load_adapter(tmp_path, adapter_name="other")
|
| 359 |
+
load_result2 = model.load_adapter(tmp_path, adapter_name="yet-another")
|
| 360 |
+
|
| 361 |
+
assert load_result1.missing_keys == []
|
| 362 |
+
assert load_result2.missing_keys == []
|
| 363 |
+
|
| 364 |
+
@pytest.mark.parametrize(
|
| 365 |
+
"peft_config_factory",
|
| 366 |
+
[
|
| 367 |
+
lambda token_indices: LoraConfig(
|
| 368 |
+
target_modules="all-linear",
|
| 369 |
+
trainable_token_indices={"embed_tokens": token_indices},
|
| 370 |
+
),
|
| 371 |
+
],
|
| 372 |
+
)
|
| 373 |
+
def test_multiple_adapters_different_token_indices(self, model, peft_config_factory, tmp_path):
|
| 374 |
+
# tests if multiple adapters with different token indices work
|
| 375 |
+
original_model = copy.deepcopy(model)
|
| 376 |
+
|
| 377 |
+
token_indices_1 = [0, 1, 2]
|
| 378 |
+
token_indices_2 = [2, 3, 4]
|
| 379 |
+
|
| 380 |
+
peft_config_1 = peft_config_factory(token_indices_1)
|
| 381 |
+
peft_config_2 = peft_config_factory(token_indices_2)
|
| 382 |
+
|
| 383 |
+
model = get_peft_model(model, peft_config_1, adapter_name="adapter_1")
|
| 384 |
+
model.add_adapter("adapter_2", peft_config_2)
|
| 385 |
+
|
| 386 |
+
# "train" adapter 1
|
| 387 |
+
model.set_adapter("adapter_1")
|
| 388 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_1")
|
| 389 |
+
|
| 390 |
+
# "train" adapter 2
|
| 391 |
+
model.set_adapter("adapter_2")
|
| 392 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_2")
|
| 393 |
+
|
| 394 |
+
# now we infer on adapter 1 and on adapter 2 and check if the requested indices are changed for
|
| 395 |
+
# each adapter. e.g., for adapter 1, only token indices 1 should be changed.
|
| 396 |
+
X = {
|
| 397 |
+
"input_ids": torch.tensor([list(set(token_indices_1 + token_indices_2))]),
|
| 398 |
+
"attention_mask": torch.tensor([[1] * (len(set(token_indices_1 + token_indices_2)))]),
|
| 399 |
+
}
|
| 400 |
+
|
| 401 |
+
original_output = original_model(output_hidden_states=True, **X).hidden_states[0]
|
| 402 |
+
|
| 403 |
+
# infer with adapter 1, embeddings for token indices 1 should be changed, no others.
|
| 404 |
+
model.set_adapter("adapter_1")
|
| 405 |
+
adapter_1_output = model(output_hidden_states=True, **X).hidden_states[0]
|
| 406 |
+
|
| 407 |
+
idcs_to_modify = token_indices_1
|
| 408 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 409 |
+
|
| 410 |
+
assert not torch.allclose(adapter_1_output[:, idcs_to_modify], original_output[:, idcs_to_modify])
|
| 411 |
+
assert torch.allclose(adapter_1_output[:, idcs_to_keep], original_output[:, idcs_to_keep])
|
| 412 |
+
|
| 413 |
+
# infer with adapter 2, embeddings for token indices 2 should be changed, no others.
|
| 414 |
+
model.set_adapter("adapter_2")
|
| 415 |
+
adapter_2_output = model(output_hidden_states=True, **X).hidden_states[0]
|
| 416 |
+
|
| 417 |
+
idcs_to_modify = token_indices_2
|
| 418 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 419 |
+
|
| 420 |
+
assert not torch.allclose(adapter_2_output[:, idcs_to_modify], original_output[:, idcs_to_modify])
|
| 421 |
+
assert torch.allclose(adapter_2_output[:, idcs_to_keep], original_output[:, idcs_to_keep])
|
| 422 |
+
|
| 423 |
+
@pytest.mark.parametrize(
|
| 424 |
+
"peft_config_factory",
|
| 425 |
+
[
|
| 426 |
+
lambda token_indices: LoraConfig(
|
| 427 |
+
target_modules="all-linear",
|
| 428 |
+
trainable_token_indices={"embed_tokens": token_indices},
|
| 429 |
+
),
|
| 430 |
+
],
|
| 431 |
+
)
|
| 432 |
+
def test_multiple_adapters_overlapping_token_indices_merging(self, model, peft_config_factory, tmp_path):
|
| 433 |
+
# tests that merging multiple adapters that have overlapping indices is not defined at the moment
|
| 434 |
+
# and would yield undefined behavior. note that merging a single adapter is fine.
|
| 435 |
+
original_model = copy.deepcopy(model)
|
| 436 |
+
|
| 437 |
+
token_indices_1 = [0, 1, 2]
|
| 438 |
+
token_indices_2 = [2, 3, 4]
|
| 439 |
+
|
| 440 |
+
peft_config_1 = peft_config_factory(token_indices_1)
|
| 441 |
+
peft_config_2 = peft_config_factory(token_indices_2)
|
| 442 |
+
|
| 443 |
+
model = get_peft_model(model, peft_config_1, adapter_name="adapter_1")
|
| 444 |
+
model.add_adapter("adapter_2", peft_config_2)
|
| 445 |
+
|
| 446 |
+
with pytest.raises(ValueError) as e:
|
| 447 |
+
model.merge_and_unload(adapter_names=["adapter_1", "adapter_2"])
|
| 448 |
+
assert "are already defined and would result in undefined merging behavior" in str(e)
|
| 449 |
+
|
| 450 |
+
@pytest.mark.parametrize(
|
| 451 |
+
"peft_config_factory",
|
| 452 |
+
[
|
| 453 |
+
lambda targets, token_indices: LoraConfig(
|
| 454 |
+
target_modules=targets,
|
| 455 |
+
trainable_token_indices={"embed_tokens": token_indices},
|
| 456 |
+
),
|
| 457 |
+
],
|
| 458 |
+
)
|
| 459 |
+
def test_multiple_adapters_mixed_forward(self, model, peft_config_factory, tmp_path):
|
| 460 |
+
# tests if multiple adapters with different token indices work
|
| 461 |
+
original_model = copy.deepcopy(model)
|
| 462 |
+
|
| 463 |
+
token_indices_1 = [0, 1, 2]
|
| 464 |
+
token_indices_2 = [2, 3, 4]
|
| 465 |
+
|
| 466 |
+
peft_config_1 = peft_config_factory(".*q_proj", token_indices_1)
|
| 467 |
+
peft_config_2 = peft_config_factory(".*o_proj", token_indices_2)
|
| 468 |
+
|
| 469 |
+
model = get_peft_model(model, peft_config_1, adapter_name="adapter_1")
|
| 470 |
+
model.add_adapter("adapter_2", peft_config_2)
|
| 471 |
+
|
| 472 |
+
# "train" adapter 1
|
| 473 |
+
model.set_adapter("adapter_1")
|
| 474 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_1")
|
| 475 |
+
|
| 476 |
+
# "train" adapter 2
|
| 477 |
+
model.set_adapter("adapter_2")
|
| 478 |
+
self.simulate_training(model.model.model.embed_tokens.token_adapter, "adapter_2")
|
| 479 |
+
|
| 480 |
+
# forward(adapter_names=...) is not available in train mode
|
| 481 |
+
model.eval()
|
| 482 |
+
|
| 483 |
+
# Build a batch of 2 items, each the same input sequence but each sequence will be passed to a different
|
| 484 |
+
# adapter via mixed batch forward.
|
| 485 |
+
input_sequence = list(set(token_indices_1 + token_indices_2))
|
| 486 |
+
X = {
|
| 487 |
+
"input_ids": torch.tensor([input_sequence, input_sequence]),
|
| 488 |
+
"attention_mask": torch.tensor([[1] * len(input_sequence), [1] * len(input_sequence)]),
|
| 489 |
+
}
|
| 490 |
+
batch_adapter_names = ["adapter_1", "adapter_2"]
|
| 491 |
+
|
| 492 |
+
original_output = original_model(output_hidden_states=True, **X)
|
| 493 |
+
mixed_output = model(output_hidden_states=True, adapter_names=batch_adapter_names, **X)
|
| 494 |
+
|
| 495 |
+
# check that the active adapter is still the last activated adapter, adapter_2
|
| 496 |
+
assert model.model.model.embed_tokens.token_adapter.active_adapter == ["adapter_2"]
|
| 497 |
+
|
| 498 |
+
adapter_1_output = mixed_output.hidden_states[0][0:1]
|
| 499 |
+
original_output_1 = original_output.hidden_states[0][0:1]
|
| 500 |
+
adapter_2_output = mixed_output.hidden_states[0][1:2]
|
| 501 |
+
original_output_2 = original_output.hidden_states[0][1:2]
|
| 502 |
+
|
| 503 |
+
idcs_to_modify = token_indices_1
|
| 504 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 505 |
+
|
| 506 |
+
assert not torch.allclose(adapter_1_output[:, idcs_to_modify], original_output_1[:, idcs_to_modify])
|
| 507 |
+
assert torch.allclose(adapter_1_output[:, idcs_to_keep], original_output_1[:, idcs_to_keep])
|
| 508 |
+
|
| 509 |
+
idcs_to_modify = token_indices_2
|
| 510 |
+
idcs_to_keep = [i for i in X["input_ids"][0].tolist() if i not in idcs_to_modify]
|
| 511 |
+
|
| 512 |
+
assert not torch.allclose(adapter_2_output[:, idcs_to_modify], original_output_2[:, idcs_to_modify])
|
| 513 |
+
assert torch.allclose(adapter_2_output[:, idcs_to_keep], original_output_2[:, idcs_to_keep])
|
| 514 |
+
|
| 515 |
+
def test_stand_alone_raises_target_layer_not_found(self, model):
|
| 516 |
+
config = TrainableTokensConfig(target_modules=["doesnt_exist"], token_indices=[0, 1, 3])
|
| 517 |
+
with pytest.raises(ValueError) as e:
|
| 518 |
+
model = get_peft_model(model, config)
|
| 519 |
+
assert "Target modules ['doesnt_exist'] not found in the base model." in str(e)
|
| 520 |
+
|
| 521 |
+
@pytest.mark.parametrize(
|
| 522 |
+
"peft_config, target_layer_name",
|
| 523 |
+
[
|
| 524 |
+
(LoraConfig(trainable_token_indices={"does-not-exist": [0, 1, 2]}), "does-not-exist"),
|
| 525 |
+
],
|
| 526 |
+
)
|
| 527 |
+
def test_combined_with_peft_raises_target_layer_not_found(self, model, peft_config, target_layer_name):
|
| 528 |
+
# same as test_stand_alone_raises_target_layer_not_found but tests the peft method integration
|
| 529 |
+
with pytest.raises(ValueError) as e:
|
| 530 |
+
model = get_peft_model(model, peft_config)
|
| 531 |
+
assert f"Target modules {{{repr(target_layer_name)}}} not found in the base model." in str(e)
|
| 532 |
+
|
| 533 |
+
def test_multiple_targets(self, model_multi_embedding):
|
| 534 |
+
# tests the ability of targeting two modules with the same token indices
|
| 535 |
+
original_model = copy.deepcopy(model_multi_embedding)
|
| 536 |
+
config = TrainableTokensConfig(target_modules=["emb_text", "emb_image"], token_indices=[0, 1])
|
| 537 |
+
peft_model = get_peft_model(model_multi_embedding, config)
|
| 538 |
+
|
| 539 |
+
self.simulate_training(peft_model.model.emb_text)
|
| 540 |
+
self.simulate_training(peft_model.model.emb_image)
|
| 541 |
+
|
| 542 |
+
X = {
|
| 543 |
+
"x_text": torch.tensor([[0, 1, 2]]),
|
| 544 |
+
"x_image": torch.tensor([[0, 1, 2]]),
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
_, (emb_text_orig, emb_image_orig) = original_model(**X)
|
| 548 |
+
_, (emb_text_peft, emb_image_peft) = peft_model(**X)
|
| 549 |
+
|
| 550 |
+
assert not torch.allclose(emb_text_orig[:, [0, 1]], emb_text_peft[:, [0, 1]])
|
| 551 |
+
assert torch.allclose(emb_text_orig[:, [2]], emb_text_peft[:, [2]])
|
| 552 |
+
assert not torch.allclose(emb_image_orig[:, [0, 1]], emb_image_peft[:, [0, 1]])
|
| 553 |
+
assert torch.allclose(emb_image_orig[:, [2]], emb_image_peft[:, [2]])
|
| 554 |
+
|
| 555 |
+
@pytest.mark.parametrize(
|
| 556 |
+
"peft_config",
|
| 557 |
+
[
|
| 558 |
+
LoraConfig(
|
| 559 |
+
target_modules="all-linear",
|
| 560 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 561 |
+
),
|
| 562 |
+
],
|
| 563 |
+
)
|
| 564 |
+
def test_no_embeddings_in_save_with_combined_usage(self, model, tokenizer, peft_config, tmp_path):
|
| 565 |
+
# make sure that in combined use the only state dict key is that of the token deltas and nothing more
|
| 566 |
+
|
| 567 |
+
peft_model = get_peft_model(model, peft_config)
|
| 568 |
+
state_dict = get_peft_model_state_dict(
|
| 569 |
+
model=peft_model,
|
| 570 |
+
state_dict=None,
|
| 571 |
+
adapter_name="default",
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
embedding_keys = [n for n in state_dict.keys() if "embed_tokens" in n]
|
| 575 |
+
assert embedding_keys == ["base_model.model.model.embed_tokens.token_adapter.trainable_tokens_delta"]
|
| 576 |
+
|
| 577 |
+
@pytest.fixture()
|
| 578 |
+
def model_weight_untied(self, model):
|
| 579 |
+
return model
|
| 580 |
+
|
| 581 |
+
@pytest.fixture()
|
| 582 |
+
def model_id_weight_tied(self):
|
| 583 |
+
return "peft-internal-testing/opt-125m"
|
| 584 |
+
|
| 585 |
+
@pytest.fixture()
|
| 586 |
+
def model_weight_tied(self, request, model_id_weight_tied):
|
| 587 |
+
model_weight_tied = AutoModelForCausalLM.from_pretrained(model_id_weight_tied)
|
| 588 |
+
tied_keys = model_weight_tied._tied_weights_keys
|
| 589 |
+
|
| 590 |
+
# TODO remove when transformers <5 is not supported anymore
|
| 591 |
+
if not hasattr(request, "param") or request.param == "list":
|
| 592 |
+
if isinstance(tied_keys, list):
|
| 593 |
+
# transformers <5, list is already the default
|
| 594 |
+
yield model_weight_tied
|
| 595 |
+
else:
|
| 596 |
+
# simulate transformers <5 for backward compatibility testing
|
| 597 |
+
with patch.object(model_weight_tied, "_tied_weights_keys", list(tied_keys.keys())):
|
| 598 |
+
yield model_weight_tied
|
| 599 |
+
|
| 600 |
+
elif request.param == "mapping":
|
| 601 |
+
if isinstance(tied_keys, dict):
|
| 602 |
+
# transformers >=5, mapping is already the default
|
| 603 |
+
yield model_weight_tied
|
| 604 |
+
else:
|
| 605 |
+
# simulate transformers >=5
|
| 606 |
+
mapping = {"lm_head.weight": "model.decoder.embed_tokens.weight"}
|
| 607 |
+
|
| 608 |
+
with patch.object(model_weight_tied, "_tied_weights_keys", mapping):
|
| 609 |
+
yield model_weight_tied
|
| 610 |
+
|
| 611 |
+
else:
|
| 612 |
+
raise RuntimeError("Invalid request")
|
| 613 |
+
|
| 614 |
+
@pytest.mark.parametrize(
|
| 615 |
+
"peft_config",
|
| 616 |
+
[
|
| 617 |
+
LoraConfig(
|
| 618 |
+
target_modules="all-linear",
|
| 619 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 620 |
+
),
|
| 621 |
+
],
|
| 622 |
+
)
|
| 623 |
+
def test_weight_tying_noop_when_model_is_untied(self, model_weight_untied, peft_config, tmp_path):
|
| 624 |
+
# test if the weight tying is affected as well when we modified the embedding.
|
| 625 |
+
assert model_weight_untied._tied_weights_keys
|
| 626 |
+
assert not model_weight_untied.config.tie_word_embeddings
|
| 627 |
+
|
| 628 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 629 |
+
assert hasattr(peft_model.model.model.embed_tokens, "token_adapter")
|
| 630 |
+
assert not hasattr(peft_model.model.lm_head, "token_adapter")
|
| 631 |
+
|
| 632 |
+
@pytest.mark.parametrize(
|
| 633 |
+
"peft_config, model_weight_tied",
|
| 634 |
+
[
|
| 635 |
+
(
|
| 636 |
+
LoraConfig(
|
| 637 |
+
target_modules="all-linear",
|
| 638 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 639 |
+
),
|
| 640 |
+
"list",
|
| 641 |
+
),
|
| 642 |
+
(
|
| 643 |
+
LoraConfig(
|
| 644 |
+
target_modules="all-linear",
|
| 645 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 646 |
+
),
|
| 647 |
+
"mapping",
|
| 648 |
+
),
|
| 649 |
+
],
|
| 650 |
+
indirect=["model_weight_tied"],
|
| 651 |
+
)
|
| 652 |
+
def test_weight_tying_applied_when_model_is_tied(self, model_weight_tied, peft_config, tmp_path):
|
| 653 |
+
# test if the weight tying is affected as well when we modified the embedding.
|
| 654 |
+
assert model_weight_tied._tied_weights_keys
|
| 655 |
+
assert model_weight_tied.config.tie_word_embeddings
|
| 656 |
+
|
| 657 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 658 |
+
|
| 659 |
+
# make it so that the input embeddings diverge. when the weights are tied this should
|
| 660 |
+
# reflect in the output embeddings as well.
|
| 661 |
+
self.simulate_training(peft_model.model.model.decoder.embed_tokens.token_adapter)
|
| 662 |
+
|
| 663 |
+
# we have to find out if the input embedding tying is doing its job during forward.
|
| 664 |
+
# for this we can leverage the fact that emb_out(1/emb_in(x)) is embed_dim on the
|
| 665 |
+
# diagonal iff emb_in.weight == emb_out.weight.
|
| 666 |
+
token_indices = [0, 1, 2, 3]
|
| 667 |
+
emb_dim = 768
|
| 668 |
+
emb_in = peft_model.model.model.decoder.embed_tokens(torch.tensor([token_indices]))
|
| 669 |
+
emb_out = peft_model.model.lm_head(1 / emb_in)
|
| 670 |
+
|
| 671 |
+
assert torch.allclose(torch.diag(emb_out[0]), torch.tensor([emb_dim] * len(token_indices)).float())
|
| 672 |
+
|
| 673 |
+
# make sure that the state dict does not include weight-tied weights.
|
| 674 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 675 |
+
assert not [key for key in state_dict if any(tied_key in key for tied_key in peft_model._tied_weights_keys)]
|
| 676 |
+
|
| 677 |
+
# make sure that merging and unloading restores the weight-tying.
|
| 678 |
+
merged_model = peft_model.merge_and_unload()
|
| 679 |
+
|
| 680 |
+
assert merged_model.model.decoder.embed_tokens.weight.data_ptr() == merged_model.lm_head.weight.data_ptr()
|
| 681 |
+
|
| 682 |
+
@pytest.mark.parametrize("model_weight_tied", ["list", "mapping"], indirect=["model_weight_tied"])
|
| 683 |
+
def test_weight_tying_applied_when_model_is_tied_standalone(self, model_weight_tied):
|
| 684 |
+
# since weight tying is currently not supported make sure that an error is raised when attempting
|
| 685 |
+
# to use a model that has tied input/output embeddings
|
| 686 |
+
assert model_weight_tied._tied_weights_keys
|
| 687 |
+
assert model_weight_tied.config.tie_word_embeddings
|
| 688 |
+
|
| 689 |
+
peft_config = TrainableTokensConfig(
|
| 690 |
+
target_modules=["embed_tokens"],
|
| 691 |
+
token_indices=[0, 1, 3],
|
| 692 |
+
)
|
| 693 |
+
|
| 694 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 695 |
+
|
| 696 |
+
# make it so that the input embeddings diverge. when the weights are tied this should
|
| 697 |
+
# reflect in the output embeddings as well.
|
| 698 |
+
self.simulate_training(peft_model.model.model.decoder.embed_tokens)
|
| 699 |
+
|
| 700 |
+
# we have to find out if the input embedding tying is doing its job during forward.
|
| 701 |
+
# for this we can leverage the fact that emb_out(1/emb_in(x)) is embed_dim on the
|
| 702 |
+
# diagonal iff emb_in.weight == emb_out.weight.
|
| 703 |
+
token_indices = [0, 1, 2, 3]
|
| 704 |
+
emb_dim = 768
|
| 705 |
+
emb_in = peft_model.model.model.decoder.embed_tokens(torch.tensor([token_indices]))
|
| 706 |
+
emb_out = peft_model.model.lm_head(1 / emb_in)
|
| 707 |
+
|
| 708 |
+
assert torch.allclose(torch.diag(emb_out[0]), torch.tensor([emb_dim] * len(token_indices)).float())
|
| 709 |
+
|
| 710 |
+
# make sure that the state dict does not include weight-tied weights.
|
| 711 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 712 |
+
assert not [key for key in state_dict if any(tied_key in key for tied_key in peft_model._tied_weights_keys)]
|
| 713 |
+
|
| 714 |
+
# make sure that merging and unloading restores the weight-tying.
|
| 715 |
+
merged_model = peft_model.merge_and_unload()
|
| 716 |
+
|
| 717 |
+
assert merged_model.model.decoder.embed_tokens.weight.data_ptr() == merged_model.lm_head.weight.data_ptr()
|
| 718 |
+
|
| 719 |
+
def test_weight_tying_state_dict_ignores_tied_weights(self, model_weight_tied):
|
| 720 |
+
# since weight tying is currently not supported make sure that an error is raised when attempting
|
| 721 |
+
# to use a model that has tied input/output embeddings
|
| 722 |
+
assert model_weight_tied._tied_weights_keys
|
| 723 |
+
assert model_weight_tied.config.tie_word_embeddings
|
| 724 |
+
|
| 725 |
+
peft_config = TrainableTokensConfig(
|
| 726 |
+
target_modules=["embed_tokens"],
|
| 727 |
+
token_indices=[0, 1, 3],
|
| 728 |
+
)
|
| 729 |
+
|
| 730 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 731 |
+
|
| 732 |
+
state_dict = peft_model.state_dict()
|
| 733 |
+
peft_state_dict = get_peft_model_state_dict(peft_model)
|
| 734 |
+
|
| 735 |
+
# the state dict or the peft model state dict must not include tied adapter weights
|
| 736 |
+
state_dict_keys = [n for n, _ in state_dict.items() if "tied_adapter." in n]
|
| 737 |
+
peft_state_dict_keys = [n for n, _ in peft_state_dict.items() if "tied_adapter." in n]
|
| 738 |
+
|
| 739 |
+
assert not state_dict_keys
|
| 740 |
+
assert not peft_state_dict_keys
|
| 741 |
+
|
| 742 |
+
@pytest.mark.parametrize(
|
| 743 |
+
"peft_config",
|
| 744 |
+
[
|
| 745 |
+
LoraConfig(
|
| 746 |
+
target_modules="all-linear",
|
| 747 |
+
trainable_token_indices={"shared": [0, 1, 3]},
|
| 748 |
+
),
|
| 749 |
+
],
|
| 750 |
+
)
|
| 751 |
+
def test_weight_tying_applied_when_model_is_tied_encoder_decoder(self, peft_config):
|
| 752 |
+
model_id = "peft-internal-testing/tiny-random-t5"
|
| 753 |
+
base_model = AutoModelForSeq2SeqLM.from_pretrained(model_id)
|
| 754 |
+
|
| 755 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 756 |
+
|
| 757 |
+
# make it so that the input embeddings diverge. when the weights are tied this should
|
| 758 |
+
# reflect in the output embeddings as well.
|
| 759 |
+
self.simulate_training(peft_model.model.shared.token_adapter)
|
| 760 |
+
|
| 761 |
+
# we have to find out if the input embedding tying is doing its job during forward.
|
| 762 |
+
# for this we can leverage the fact that emb_out(1/emb_in(x)) is embed_dim on the
|
| 763 |
+
# diagonal iff emb_in.weight == emb_out.weight.
|
| 764 |
+
token_indices = [0, 1, 2, 3]
|
| 765 |
+
emb_dim = base_model.config.d_model
|
| 766 |
+
emb_in = peft_model.model.encoder.embed_tokens(torch.tensor([token_indices]))
|
| 767 |
+
emb_out = peft_model.model.lm_head(1 / emb_in)
|
| 768 |
+
|
| 769 |
+
assert torch.allclose(torch.diag(emb_out[0]), torch.tensor([emb_dim] * len(token_indices)).float())
|
| 770 |
+
|
| 771 |
+
# T5 has a decoder embedding layer, we can simply check if it's forward is equal to the encoder
|
| 772 |
+
# embedding forward.
|
| 773 |
+
emb_out = peft_model.model.decoder.embed_tokens(torch.tensor([token_indices]))
|
| 774 |
+
|
| 775 |
+
assert torch.allclose(emb_in, emb_out)
|
| 776 |
+
|
| 777 |
+
# make sure that the state dict does not include weight-tied weights.
|
| 778 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 779 |
+
assert not [key for key in state_dict if any(tied_key in key for tied_key in peft_model._tied_weights_keys)]
|
| 780 |
+
|
| 781 |
+
# make sure that merging and unloading restores the weight-tying.
|
| 782 |
+
merged_model = peft_model.merge_and_unload()
|
| 783 |
+
|
| 784 |
+
assert merged_model.encoder.embed_tokens.weight.data_ptr() == merged_model.lm_head.weight.data_ptr()
|
| 785 |
+
assert (
|
| 786 |
+
merged_model.encoder.embed_tokens.weight.data_ptr() == merged_model.decoder.embed_tokens.weight.data_ptr()
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
@pytest.mark.parametrize(
|
| 790 |
+
"peft_config",
|
| 791 |
+
[
|
| 792 |
+
LoraConfig(
|
| 793 |
+
target_modules="all-linear",
|
| 794 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 795 |
+
modules_to_save=["embed_tokens"],
|
| 796 |
+
),
|
| 797 |
+
],
|
| 798 |
+
)
|
| 799 |
+
def test_modules_to_save_excludes_trainable_tokens(self, model, peft_config):
|
| 800 |
+
with pytest.raises(ValueError) as e:
|
| 801 |
+
get_peft_model(model, peft_config)
|
| 802 |
+
assert "The embedding layer is already marked to be trained fully" in str(e)
|
| 803 |
+
|
| 804 |
+
def test_merge_and_unload_standalone(self, model):
|
| 805 |
+
# test basic functionality of merge_and_unload for standalone TrainableTokens
|
| 806 |
+
token_indices = [0, 1, 3]
|
| 807 |
+
|
| 808 |
+
peft_config = TrainableTokensConfig(
|
| 809 |
+
target_modules=["embed_tokens"],
|
| 810 |
+
token_indices=token_indices,
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
peft_model = get_peft_model(model, peft_config)
|
| 814 |
+
|
| 815 |
+
self.simulate_training(peft_model.model.model.embed_tokens)
|
| 816 |
+
expected_changed_weights = peft_model.model.model.embed_tokens.trainable_tokens_delta.default.data.clone()
|
| 817 |
+
|
| 818 |
+
# make sure no TrainableTokensLayer is in the module
|
| 819 |
+
merged_model = peft_model.merge_and_unload()
|
| 820 |
+
for _, module in merged_model.named_modules():
|
| 821 |
+
assert not isinstance(module, TrainableTokensLayer)
|
| 822 |
+
|
| 823 |
+
# make sure that deltas are applied to the embedding matrix
|
| 824 |
+
assert torch.allclose(merged_model.model.embed_tokens.weight.data[token_indices], expected_changed_weights)
|
| 825 |
+
|
| 826 |
+
def test_original_module_not_in_state_dict(self, model):
|
| 827 |
+
# Every AuxiliaryTrainingWrapper has an original_module attribute. Since the TrainableTokensWrapper is wrapping
|
| 828 |
+
# a TrainableTokensLayer and it already has a base layer which serves as the original module, we don't need that
|
| 829 |
+
# and so it should not come up in the state dict to save memory.
|
| 830 |
+
|
| 831 |
+
peft_config = LoraConfig(
|
| 832 |
+
target_modules="all-linear",
|
| 833 |
+
trainable_token_indices={"embed_tokens": [0, 1, 3]},
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
peft_model = get_peft_model(model, peft_config)
|
| 837 |
+
|
| 838 |
+
# make sure that the original module is present and accessible even though
|
| 839 |
+
# we want to exclude it from the state dict.
|
| 840 |
+
assert peft_model.model.model.embed_tokens.original_module
|
| 841 |
+
|
| 842 |
+
state_dict = get_peft_model_state_dict(peft_model)
|
| 843 |
+
|
| 844 |
+
assert not [k for k in state_dict if ".original_module.weight" in k]
|
| 845 |
+
|
| 846 |
+
state_dict = peft_model.state_dict()
|
| 847 |
+
assert not [k for k in state_dict if ".original_module.weight" in k]
|
| 848 |
+
|
| 849 |
+
@pytest.fixture
|
| 850 |
+
def model_emb(self):
|
| 851 |
+
return ModelEmb()
|
| 852 |
+
|
| 853 |
+
@pytest.fixture
|
| 854 |
+
def model_embed_in(self):
|
| 855 |
+
return ModelEmbedIn()
|
| 856 |
+
|
| 857 |
+
@pytest.fixture
|
| 858 |
+
def model_embed_in_no_get(self):
|
| 859 |
+
return ModelEmbedInNoGet()
|
| 860 |
+
|
| 861 |
+
@pytest.fixture
|
| 862 |
+
def model_embed_multiple(self):
|
| 863 |
+
return ModelEmbedMultiple()
|
| 864 |
+
|
| 865 |
+
@pytest.mark.parametrize(
|
| 866 |
+
"model_fixture_name, getter",
|
| 867 |
+
[
|
| 868 |
+
("model_emb", lambda model: model.emb),
|
| 869 |
+
("model_embed_in", lambda model: model.embed_in),
|
| 870 |
+
("model", lambda model: model.model.model.embed_tokens),
|
| 871 |
+
],
|
| 872 |
+
)
|
| 873 |
+
def test_default_embedding_name_is_inferred_standalone(self, model_fixture_name, getter, request):
|
| 874 |
+
# make sure that the auto targeting works when `target_module=None`
|
| 875 |
+
base_model = request.getfixturevalue(model_fixture_name)
|
| 876 |
+
|
| 877 |
+
peft_config = TrainableTokensConfig(target_modules=None, token_indices=[0, 1, 3])
|
| 878 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 879 |
+
|
| 880 |
+
assert isinstance(getter(peft_model), TrainableTokensLayer)
|
| 881 |
+
|
| 882 |
+
@pytest.mark.parametrize(
|
| 883 |
+
"model_fixture_name, getter",
|
| 884 |
+
[
|
| 885 |
+
("model_emb", lambda model: model.emb),
|
| 886 |
+
("model_embed_in", lambda model: model.embed_in),
|
| 887 |
+
("model", lambda model: model.model.model.embed_tokens),
|
| 888 |
+
],
|
| 889 |
+
)
|
| 890 |
+
def test_default_embedding_name_is_inferred_combined(self, model_fixture_name, getter, request):
|
| 891 |
+
# make sure that the auto targeting works when `target_module=None`
|
| 892 |
+
base_model = request.getfixturevalue(model_fixture_name)
|
| 893 |
+
|
| 894 |
+
peft_config = LoraConfig(target_modules="all-linear", trainable_token_indices=[0, 1, 3])
|
| 895 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 896 |
+
|
| 897 |
+
assert isinstance(getter(peft_model), TrainableTokensWrapper)
|
| 898 |
+
|
| 899 |
+
def test_default_embedding_name_cannot_be_inferred(self, model_embed_in_no_get):
|
| 900 |
+
# should default to default value `embed_tokens` which is not present in this model
|
| 901 |
+
base_model = model_embed_in_no_get
|
| 902 |
+
|
| 903 |
+
peft_config = TrainableTokensConfig(target_modules=None, token_indices=[0, 1, 3])
|
| 904 |
+
|
| 905 |
+
with pytest.raises(ValueError) as e:
|
| 906 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 907 |
+
|
| 908 |
+
assert "Target modules embed_tokens not found in the base model." in str(e)
|
| 909 |
+
|
| 910 |
+
def test_embedding_name_is_used_when_given_standalone(self, model_embed_multiple):
|
| 911 |
+
peft_config = TrainableTokensConfig(target_modules="embed_in_2", token_indices=[0, 1, 3])
|
| 912 |
+
peft_model = get_peft_model(model_embed_multiple, peft_config)
|
| 913 |
+
|
| 914 |
+
assert isinstance(peft_model.model.embed_in_2, TrainableTokensLayer)
|
| 915 |
+
assert not isinstance(peft_model.model.embed_in, TrainableTokensLayer)
|
| 916 |
+
|
| 917 |
+
def test_embedding_name_is_used_when_given_combined(self, model_embed_multiple):
|
| 918 |
+
peft_config = LoraConfig(target_modules="all-linear", trainable_token_indices={"embed_in_2": [0, 1, 3]})
|
| 919 |
+
peft_model = get_peft_model(model_embed_multiple, peft_config)
|
| 920 |
+
|
| 921 |
+
assert isinstance(peft_model.model.embed_in_2, TrainableTokensWrapper)
|
| 922 |
+
assert not isinstance(peft_model.model.embed_in, TrainableTokensWrapper)
|
| 923 |
+
|
| 924 |
+
@pytest.mark.parametrize("resize_embedding", [True, False])
|
| 925 |
+
@pytest.mark.parametrize(
|
| 926 |
+
"peft_config",
|
| 927 |
+
[
|
| 928 |
+
LoraConfig(target_modules="all-linear", trainable_token_indices=[1, 2, 3]),
|
| 929 |
+
TrainableTokensConfig(target_modules=None, token_indices=[1, 2, 3]),
|
| 930 |
+
],
|
| 931 |
+
)
|
| 932 |
+
def test_save_pretrained_auto(self, model, resize_embedding, peft_config, tmp_path):
|
| 933 |
+
# make sure that embeddings are saved alongside trainable token weights but only when
|
| 934 |
+
# the we detect the embedding to be resized (as detected by save_embedding_layers="auto")
|
| 935 |
+
if resize_embedding:
|
| 936 |
+
model.resize_token_embeddings(model.config.vocab_size + 2)
|
| 937 |
+
peft_model = get_peft_model(model, peft_config)
|
| 938 |
+
|
| 939 |
+
peft_model.save_pretrained(tmp_path, save_embedding_layers="auto")
|
| 940 |
+
state_dict = safe_load_file(tmp_path / "adapter_model.safetensors")
|
| 941 |
+
|
| 942 |
+
if isinstance(peft_config, TrainableTokensConfig):
|
| 943 |
+
contains_embedding = "base_model.model.model.embed_tokens.base_layer.weight" in state_dict
|
| 944 |
+
else:
|
| 945 |
+
contains_embedding = "base_model.model.model.embed_tokens.token_adapter.base_layer.weight" in state_dict
|
| 946 |
+
|
| 947 |
+
if resize_embedding:
|
| 948 |
+
assert contains_embedding
|
| 949 |
+
else:
|
| 950 |
+
assert not contains_embedding
|
| 951 |
+
|
| 952 |
+
def test_embed_scale_is_applied(self):
|
| 953 |
+
"""Test that TrainableTokens correctly handles embeddings with scaling (e.g., Gemma3)."""
|
| 954 |
+
model_id = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"
|
| 955 |
+
with hub_online_once(model_id):
|
| 956 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 957 |
+
orig_embedding = base_model.get_input_embeddings()
|
| 958 |
+
|
| 959 |
+
peft_config = TrainableTokensConfig(target_modules=["embed_tokens"], token_indices=[0, 1, 3])
|
| 960 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 961 |
+
|
| 962 |
+
# sanity check: with the default embed_scale, the embedding output should be reasonably sized
|
| 963 |
+
peft_embedding = peft_model.base_model.model.get_input_embeddings()
|
| 964 |
+
max_embedding_output = peft_embedding(torch.arange(10)).abs().max(0)[0]
|
| 965 |
+
assert (max_embedding_output < 100.0).all()
|
| 966 |
+
|
| 967 |
+
# set embed_scale to an absurdly high value, then check that the embedding output is also scaled to a high
|
| 968 |
+
# value
|
| 969 |
+
orig_embedding.embed_scale.fill_(10000.0)
|
| 970 |
+
max_embedding_output = peft_embedding(torch.arange(10)).abs().max(0)[0]
|
| 971 |
+
assert (max_embedding_output > 100.0).all()
|
| 972 |
+
|
| 973 |
+
# set embed_scale to zero, then check that the embedding output is also zero
|
| 974 |
+
orig_embedding.embed_scale.fill_(0)
|
| 975 |
+
embedding_output = peft_embedding(torch.arange(10))
|
| 976 |
+
assert (embedding_output == 0.0).all()
|
| 977 |
+
|
| 978 |
+
def test_scaled_embedding_with_lora(self):
|
| 979 |
+
"""
|
| 980 |
+
Test that TrainableTokens works with LoRA on scaled embeddings when both are active simultaneously.
|
| 981 |
+
"""
|
| 982 |
+
model_id = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"
|
| 983 |
+
with hub_online_once(model_id):
|
| 984 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 985 |
+
orig_embedding = base_model.get_input_embeddings()
|
| 986 |
+
|
| 987 |
+
# Apply both TrainableTokens and LoRA to the same model
|
| 988 |
+
peft_config = LoraConfig(target_modules=["q_proj"], trainable_token_indices={"embed_tokens": [0, 1, 3]})
|
| 989 |
+
peft_model = get_peft_model(base_model, peft_config)
|
| 990 |
+
|
| 991 |
+
x = torch.arange(10)
|
| 992 |
+
peft_embedding = peft_model.base_model.model.get_input_embeddings()
|
| 993 |
+
embedding_output = peft_embedding(x)
|
| 994 |
+
max_embedding_output = embedding_output.abs().max(0)[0]
|
| 995 |
+
assert (max_embedding_output < 100.0).all()
|
| 996 |
+
peft_model.merge_adapter()
|
| 997 |
+
embedding_merged = peft_embedding(x)
|
| 998 |
+
assert torch.allclose(embedding_output, embedding_merged)
|
| 999 |
+
peft_model.unmerge_adapter()
|
| 1000 |
+
|
| 1001 |
+
# set embed_scale to an absurdly high value, then check that the embedding output is also scaled to a high
|
| 1002 |
+
# value
|
| 1003 |
+
orig_embedding.embed_scale.fill_(10000.0)
|
| 1004 |
+
max_embedding_output = peft_embedding(x).abs().max(0)[0]
|
| 1005 |
+
assert (max_embedding_output > 100.0).all()
|
| 1006 |
+
|
| 1007 |
+
# set embed_scale to zero, then check that the embedding output is also zero
|
| 1008 |
+
orig_embedding.embed_scale.fill_(0)
|
| 1009 |
+
embedding_output = peft_embedding(x)
|
| 1010 |
+
assert (embedding_output == 0.0).all()
|
| 1011 |
+
|
| 1012 |
+
# Tests for ensure_weight_tying parameter with trainable_token_indices
|
| 1013 |
+
# See #2864 for details on the expected behavior
|
| 1014 |
+
@pytest.mark.parametrize(
|
| 1015 |
+
"trainable_token_indices",
|
| 1016 |
+
[
|
| 1017 |
+
[1, 2, 3], # list format
|
| 1018 |
+
{"embed_tokens": [1, 2, 3]}, # dict format - single layer
|
| 1019 |
+
{"lm_head": [1, 2], "embed_tokens": [1, 2]}, # dict format - same indices
|
| 1020 |
+
{"lm_head": [1, 2], "embed_tokens": [3, 4]}, # dict format - different indices
|
| 1021 |
+
],
|
| 1022 |
+
)
|
| 1023 |
+
def test_ensure_weight_tying_warns_when_model_not_tied(
|
| 1024 |
+
self, model_weight_untied, recwarn, trainable_token_indices
|
| 1025 |
+
):
|
| 1026 |
+
"""Should warn when ensure_weight_tying=True but model doesn't have tied weights"""
|
| 1027 |
+
peft_config = LoraConfig(
|
| 1028 |
+
target_modules="all-linear",
|
| 1029 |
+
trainable_token_indices=trainable_token_indices,
|
| 1030 |
+
ensure_weight_tying=True,
|
| 1031 |
+
)
|
| 1032 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 1033 |
+
|
| 1034 |
+
warnings_list = [w.message.args[0] for w in recwarn]
|
| 1035 |
+
expected = "ensure_weight_tying=True but the model does not have tied weights"
|
| 1036 |
+
assert any(expected in msg for msg in warnings_list)
|
| 1037 |
+
|
| 1038 |
+
# Verify adapters are not tied (model doesn't have tied weights)
|
| 1039 |
+
if isinstance(trainable_token_indices, dict) and len(trainable_token_indices) > 1:
|
| 1040 |
+
embed_adapter = peft_model.model.model.embed_tokens.token_adapter
|
| 1041 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1042 |
+
assert embed_adapter is not None
|
| 1043 |
+
assert lm_head_adapter is not None
|
| 1044 |
+
assert embed_adapter.trainable_tokens_delta is not lm_head_adapter.trainable_tokens_delta
|
| 1045 |
+
|
| 1046 |
+
def test_weight_tying_bc_different_indices_treated_separately(self, model_weight_tied):
|
| 1047 |
+
"""Backwards compatibility: different indices should be treated separately when ensure_weight_tying=False"""
|
| 1048 |
+
peft_config = LoraConfig(
|
| 1049 |
+
target_modules="all-linear",
|
| 1050 |
+
trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]},
|
| 1051 |
+
ensure_weight_tying=False, # BC behavior
|
| 1052 |
+
)
|
| 1053 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1054 |
+
|
| 1055 |
+
# Check that both layers have token adapters but they're NOT tied
|
| 1056 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1057 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1058 |
+
|
| 1059 |
+
assert embed_adapter is not None
|
| 1060 |
+
assert lm_head_adapter is not None
|
| 1061 |
+
# They should NOT share the same delta parameters (treated as separate)
|
| 1062 |
+
assert embed_adapter.trainable_tokens_delta is not lm_head_adapter.trainable_tokens_delta
|
| 1063 |
+
# They should have different token indices
|
| 1064 |
+
assert embed_adapter.token_indices["default"] == [3, 4]
|
| 1065 |
+
assert lm_head_adapter.token_indices["default"] == [1, 2]
|
| 1066 |
+
|
| 1067 |
+
def test_ensure_weight_tying_errors_with_different_indices(self, model_weight_tied):
|
| 1068 |
+
"""Should raise error when ensure_weight_tying=True with different indices for embedding and lm_head"""
|
| 1069 |
+
peft_config = LoraConfig(
|
| 1070 |
+
target_modules="all-linear",
|
| 1071 |
+
trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [3, 4]},
|
| 1072 |
+
ensure_weight_tying=True,
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
msg = "Cannot ensure weight tying when different token indices are specified"
|
| 1076 |
+
with pytest.raises(ValueError, match=msg):
|
| 1077 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1078 |
+
|
| 1079 |
+
@pytest.mark.parametrize(
|
| 1080 |
+
"trainable_token_indices, ensure_weight_tying",
|
| 1081 |
+
[
|
| 1082 |
+
([1, 2], True),
|
| 1083 |
+
([1, 2], False),
|
| 1084 |
+
({"lm_head": [1, 2], "embed_tokens": [1, 2]}, True),
|
| 1085 |
+
({"lm_head": [1, 2], "embed_tokens": [1, 2]}, False),
|
| 1086 |
+
],
|
| 1087 |
+
)
|
| 1088 |
+
def test_ensure_weight_tying_applied_with_same_indices(
|
| 1089 |
+
self, model_weight_tied, trainable_token_indices, ensure_weight_tying
|
| 1090 |
+
):
|
| 1091 |
+
"""Should apply weight tying when ensure_weight_tying=True with same indices"""
|
| 1092 |
+
peft_config = LoraConfig(
|
| 1093 |
+
target_modules="all-linear",
|
| 1094 |
+
trainable_token_indices=trainable_token_indices,
|
| 1095 |
+
ensure_weight_tying=ensure_weight_tying,
|
| 1096 |
+
)
|
| 1097 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1098 |
+
|
| 1099 |
+
# Check that weight tying is properly applied
|
| 1100 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1101 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1102 |
+
|
| 1103 |
+
# They should share the same delta parameters (weight tying)
|
| 1104 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1105 |
+
# They should have the same token indices
|
| 1106 |
+
assert embed_adapter.token_indices["default"] == [1, 2]
|
| 1107 |
+
assert lm_head_adapter.token_indices["default"] == [1, 2]
|
| 1108 |
+
|
| 1109 |
+
def test_weight_tying_bc_same_indices_applied(self, model_weight_tied):
|
| 1110 |
+
"""When indices are the same, weight tying should be applied even when ensure_weight_tying=False"""
|
| 1111 |
+
peft_config = LoraConfig(
|
| 1112 |
+
target_modules="all-linear",
|
| 1113 |
+
trainable_token_indices={"lm_head": [1, 2], "embed_tokens": [1, 2]},
|
| 1114 |
+
ensure_weight_tying=False, # BC: still applies tying when indices are the same
|
| 1115 |
+
)
|
| 1116 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1117 |
+
|
| 1118 |
+
# Even with ensure_weight_tying=False, BC behavior should still tie when indices are same
|
| 1119 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1120 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1121 |
+
|
| 1122 |
+
# They should share the same delta parameters (BC behavior)
|
| 1123 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1124 |
+
|
| 1125 |
+
def test_ensure_weight_tying_with_single_layer(self, model_weight_tied):
|
| 1126 |
+
"""ensure_weight_tying should work with single layer (list format)"""
|
| 1127 |
+
peft_config = LoraConfig(
|
| 1128 |
+
target_modules="all-linear",
|
| 1129 |
+
trainable_token_indices=[1, 2, 3],
|
| 1130 |
+
ensure_weight_tying=True,
|
| 1131 |
+
)
|
| 1132 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1133 |
+
|
| 1134 |
+
# Should apply weight tying to tied layers automatically
|
| 1135 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1136 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1137 |
+
|
| 1138 |
+
# They should share the same delta parameters
|
| 1139 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1140 |
+
|
| 1141 |
+
def test_untied_model_list_format_no_ensure(self, model_weight_untied):
|
| 1142 |
+
"""Untied model with list format, ensure_weight_tying=False - trainable tokens on embeddings only"""
|
| 1143 |
+
peft_config = LoraConfig(
|
| 1144 |
+
target_modules="all-linear",
|
| 1145 |
+
trainable_token_indices=[1, 2, 3],
|
| 1146 |
+
ensure_weight_tying=False,
|
| 1147 |
+
)
|
| 1148 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 1149 |
+
|
| 1150 |
+
# Only embed_tokens should have token adapter
|
| 1151 |
+
assert hasattr(peft_model.model.model.embed_tokens, "token_adapter")
|
| 1152 |
+
assert not hasattr(peft_model.model.lm_head, "token_adapter")
|
| 1153 |
+
|
| 1154 |
+
def test_tied_model_list_format_no_ensure(self, model_weight_tied):
|
| 1155 |
+
"""Tied model with list format, ensure_weight_tying=False - tied trainable tokens"""
|
| 1156 |
+
peft_config = LoraConfig(
|
| 1157 |
+
target_modules="all-linear",
|
| 1158 |
+
trainable_token_indices=[1, 2, 3],
|
| 1159 |
+
ensure_weight_tying=False,
|
| 1160 |
+
)
|
| 1161 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1162 |
+
|
| 1163 |
+
# Both should have token adapters and be tied
|
| 1164 |
+
embed_adapter = peft_model.model.model.decoder.embed_tokens.token_adapter
|
| 1165 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1166 |
+
|
| 1167 |
+
# They should share the same delta parameters (BC behavior)
|
| 1168 |
+
assert embed_adapter.trainable_tokens_delta is lm_head_adapter.trainable_tokens_delta
|
| 1169 |
+
|
| 1170 |
+
@pytest.mark.parametrize(
|
| 1171 |
+
"trainable_token_indices",
|
| 1172 |
+
[
|
| 1173 |
+
{"lm_head": [1, 2], "embed_tokens": [1, 2]}, # same indices
|
| 1174 |
+
{"lm_head": [1, 2], "embed_tokens": [3, 4]}, # different indices
|
| 1175 |
+
],
|
| 1176 |
+
)
|
| 1177 |
+
def test_untied_model_dict_no_ensure(self, model_weight_untied, trainable_token_indices):
|
| 1178 |
+
"""Untied model with dict format, ensure_weight_tying=False - treat as separate"""
|
| 1179 |
+
peft_config = LoraConfig(
|
| 1180 |
+
target_modules="all-linear",
|
| 1181 |
+
trainable_token_indices=trainable_token_indices,
|
| 1182 |
+
ensure_weight_tying=False,
|
| 1183 |
+
)
|
| 1184 |
+
peft_model = get_peft_model(model_weight_untied, peft_config)
|
| 1185 |
+
|
| 1186 |
+
# Both should have token adapters but NOT tied (since model doesn't have tied weights)
|
| 1187 |
+
embed_adapter = peft_model.model.model.embed_tokens.token_adapter
|
| 1188 |
+
lm_head_adapter = peft_model.model.lm_head.token_adapter
|
| 1189 |
+
|
| 1190 |
+
assert embed_adapter is not None
|
| 1191 |
+
assert lm_head_adapter is not None
|
| 1192 |
+
# They should NOT share delta parameters (model doesn't have tied weights)
|
| 1193 |
+
assert embed_adapter.trainable_tokens_delta is not lm_head_adapter.trainable_tokens_delta
|
| 1194 |
+
|
| 1195 |
+
@pytest.mark.skipif(
|
| 1196 |
+
not is_transformers_ge_v5, reason="Test requires transformers v5+ dict format for _tied_weights_keys"
|
| 1197 |
+
)
|
| 1198 |
+
def test_composite_model_multiple_embed_tokens_specific_targeting(self):
|
| 1199 |
+
"""Test that users can specify full paths to disambiguate multiple embed_tokens layers.
|
| 1200 |
+
|
| 1201 |
+
This tests the scenario where a composite model has multiple sub-models, each with their own embed_tokens, and
|
| 1202 |
+
users need to target them independently with different token indices.
|
| 1203 |
+
"""
|
| 1204 |
+
|
| 1205 |
+
# Create a composite model with two BART sub-models
|
| 1206 |
+
class CompositeModel(torch.nn.Module):
|
| 1207 |
+
def __init__(self):
|
| 1208 |
+
super().__init__()
|
| 1209 |
+
config1 = BartConfig(
|
| 1210 |
+
vocab_size=100,
|
| 1211 |
+
d_model=32,
|
| 1212 |
+
encoder_layers=1,
|
| 1213 |
+
decoder_layers=1,
|
| 1214 |
+
encoder_attention_heads=2,
|
| 1215 |
+
decoder_attention_heads=2,
|
| 1216 |
+
encoder_ffn_dim=64,
|
| 1217 |
+
decoder_ffn_dim=64,
|
| 1218 |
+
)
|
| 1219 |
+
self.m1 = BartModel(config1)
|
| 1220 |
+
|
| 1221 |
+
config2 = BartConfig(
|
| 1222 |
+
vocab_size=100,
|
| 1223 |
+
d_model=32,
|
| 1224 |
+
encoder_layers=1,
|
| 1225 |
+
decoder_layers=1,
|
| 1226 |
+
encoder_attention_heads=2,
|
| 1227 |
+
decoder_attention_heads=2,
|
| 1228 |
+
encoder_ffn_dim=64,
|
| 1229 |
+
decoder_ffn_dim=64,
|
| 1230 |
+
)
|
| 1231 |
+
config2.tie_word_embeddings = False # m2 doesn't tie weights
|
| 1232 |
+
self.m2 = BartModel(config2)
|
| 1233 |
+
|
| 1234 |
+
# Add a config attribute for PEFT
|
| 1235 |
+
self.config = config1
|
| 1236 |
+
|
| 1237 |
+
# Use dict format to correctly represent independent tied weights within each sub-model
|
| 1238 |
+
self._tied_weights_keys = {
|
| 1239 |
+
"m1.decoder.embed_tokens.weight": "m1.encoder.embed_tokens.weight",
|
| 1240 |
+
"m2.decoder.embed_tokens.weight": "m2.encoder.embed_tokens.weight",
|
| 1241 |
+
}
|
| 1242 |
+
|
| 1243 |
+
def get_input_embeddings(self):
|
| 1244 |
+
return self.m1.encoder.embed_tokens
|
| 1245 |
+
|
| 1246 |
+
model = CompositeModel()
|
| 1247 |
+
|
| 1248 |
+
# User specifies different token indices for each sub-model's embed_tokens
|
| 1249 |
+
# This should NOT raise an error because they are distinct sub-models
|
| 1250 |
+
# With ensure_weight_tying=True, m1's internal tying should still work
|
| 1251 |
+
peft_config = LoraConfig(
|
| 1252 |
+
target_modules="all-linear",
|
| 1253 |
+
trainable_token_indices={
|
| 1254 |
+
"m1.encoder.embed_tokens": [1, 2, 3],
|
| 1255 |
+
"m2.encoder.embed_tokens": [4, 5, 6],
|
| 1256 |
+
},
|
| 1257 |
+
ensure_weight_tying=True, # Verify that weight tying works correctly
|
| 1258 |
+
)
|
| 1259 |
+
|
| 1260 |
+
# This should work without errors - the key is that it doesn't raise ValueError
|
| 1261 |
+
# about conflicting indices because m1 and m2 are independent
|
| 1262 |
+
peft_model = get_peft_model(model, peft_config)
|
| 1263 |
+
|
| 1264 |
+
# Verify that both layers got their adapters with correct indices
|
| 1265 |
+
m1_encoder_adapter = peft_model.m1.encoder.embed_tokens.token_adapter
|
| 1266 |
+
m2_adapter = peft_model.m2.encoder.embed_tokens.token_adapter
|
| 1267 |
+
|
| 1268 |
+
assert m1_encoder_adapter is not None
|
| 1269 |
+
assert m2_adapter is not None
|
| 1270 |
+
|
| 1271 |
+
# They should have different token indices as specified
|
| 1272 |
+
assert m1_encoder_adapter.token_indices["default"] == [1, 2, 3]
|
| 1273 |
+
assert m2_adapter.token_indices["default"] == [4, 5, 6]
|
| 1274 |
+
|
| 1275 |
+
# They should NOT share the same delta parameters (they're independent sub-models)
|
| 1276 |
+
assert m1_encoder_adapter.trainable_tokens_delta is not m2_adapter.trainable_tokens_delta
|
| 1277 |
+
|
| 1278 |
+
# m1's decoder should be tied to m1's encoder (internal weight tying within m1)
|
| 1279 |
+
m1_decoder_adapter = peft_model.m1.decoder.embed_tokens.token_adapter
|
| 1280 |
+
assert m1_decoder_adapter is not None
|
| 1281 |
+
assert m1_encoder_adapter.trainable_tokens_delta is m1_decoder_adapter.trainable_tokens_delta
|
| 1282 |
+
|
| 1283 |
+
# m2's decoder should NOT have an adapter since it's not tied and we didn't target it
|
| 1284 |
+
assert not hasattr(peft_model.m2.decoder.embed_tokens, "token_adapter")
|
| 1285 |
+
|
| 1286 |
+
def test_composite_model_short_name_matching(self):
|
| 1287 |
+
"""Test that short names like 'embed_tokens' still work but match the input embedding."""
|
| 1288 |
+
|
| 1289 |
+
class CompositeModel(torch.nn.Module):
|
| 1290 |
+
def __init__(self):
|
| 1291 |
+
super().__init__()
|
| 1292 |
+
config = BartConfig(
|
| 1293 |
+
vocab_size=100,
|
| 1294 |
+
d_model=32,
|
| 1295 |
+
encoder_layers=1,
|
| 1296 |
+
decoder_layers=1,
|
| 1297 |
+
encoder_attention_heads=2,
|
| 1298 |
+
decoder_attention_heads=2,
|
| 1299 |
+
encoder_ffn_dim=64,
|
| 1300 |
+
decoder_ffn_dim=64,
|
| 1301 |
+
)
|
| 1302 |
+
self.m1 = BartModel(config)
|
| 1303 |
+
self.config = config
|
| 1304 |
+
|
| 1305 |
+
def get_input_embeddings(self):
|
| 1306 |
+
return self.m1.encoder.embed_tokens
|
| 1307 |
+
|
| 1308 |
+
model = CompositeModel()
|
| 1309 |
+
|
| 1310 |
+
# User specifies just "embed_tokens" - should match m1.encoder.embed_tokens via endswith
|
| 1311 |
+
peft_config = LoraConfig(
|
| 1312 |
+
target_modules="all-linear",
|
| 1313 |
+
trainable_token_indices={"embed_tokens": [1, 2, 3]},
|
| 1314 |
+
ensure_weight_tying=True,
|
| 1315 |
+
)
|
| 1316 |
+
|
| 1317 |
+
peft_model = get_peft_model(model, peft_config)
|
| 1318 |
+
|
| 1319 |
+
# Should work and apply to the input embeddings
|
| 1320 |
+
assert hasattr(peft_model.m1.encoder.embed_tokens, "token_adapter")
|
| 1321 |
+
assert peft_model.m1.encoder.embed_tokens.token_adapter.token_indices["default"] == [1, 2, 3]
|
| 1322 |
+
|
| 1323 |
+
def test_targeting_both_embedding_and_tied_layer_explicitly(self, model_weight_tied):
|
| 1324 |
+
"""Test that explicitly targeting both embedding and tied layers works correctly.
|
| 1325 |
+
|
| 1326 |
+
When target_modules includes both "embed_tokens" and "lm_head" (which are tied in the model), both layers get
|
| 1327 |
+
wrapped and weight tying is properly applied between them.
|
| 1328 |
+
"""
|
| 1329 |
+
peft_config = TrainableTokensConfig(
|
| 1330 |
+
target_modules=["model.decoder.embed_tokens", "lm_head"], # Explicitly target both
|
| 1331 |
+
token_indices=[1, 2, 3],
|
| 1332 |
+
)
|
| 1333 |
+
peft_model = get_peft_model(model_weight_tied, peft_config)
|
| 1334 |
+
|
| 1335 |
+
# Both should have been wrapped as TrainableTokensLayer
|
| 1336 |
+
embed_layer = peft_model.model.model.decoder.embed_tokens
|
| 1337 |
+
lm_head_layer = peft_model.model.lm_head
|
| 1338 |
+
|
| 1339 |
+
assert isinstance(embed_layer, TrainableTokensLayer)
|
| 1340 |
+
assert isinstance(lm_head_layer, TrainableTokensLayer)
|
| 1341 |
+
|
| 1342 |
+
# They should share the same delta parameters (tied)
|
| 1343 |
+
assert embed_layer.trainable_tokens_delta["default"] is lm_head_layer.trainable_tokens_delta["default"]
|
| 1344 |
+
|
| 1345 |
+
# Both should have the same token indices
|
| 1346 |
+
assert embed_layer.token_indices["default"] == [1, 2, 3]
|
| 1347 |
+
assert lm_head_layer.token_indices["default"] == [1, 2, 3]
|
| 1348 |
+
|
| 1349 |
+
def test_multiple_trainable_token_adapters_same_model(self, model_weight_tied):
|
| 1350 |
+
"""Test adding multiple trainable token adapters to the same model with tied layers.
|
| 1351 |
+
|
| 1352 |
+
This verifies that adding multiple adapters to the same tied layers (embed_tokens and lm_head) works correctly,
|
| 1353 |
+
with each adapter maintaining its own token indices while preserving weight tying.
|
| 1354 |
+
"""
|
| 1355 |
+
# Add first adapter with both embed_tokens and lm_head targeted
|
| 1356 |
+
peft_config1 = TrainableTokensConfig(
|
| 1357 |
+
target_modules=["model.decoder.embed_tokens", "lm_head"],
|
| 1358 |
+
token_indices=[1, 2, 3],
|
| 1359 |
+
)
|
| 1360 |
+
peft_model = get_peft_model(model_weight_tied, peft_config1)
|
| 1361 |
+
|
| 1362 |
+
# Add second adapter to the same layers
|
| 1363 |
+
peft_config2 = TrainableTokensConfig(
|
| 1364 |
+
target_modules=["model.decoder.embed_tokens", "lm_head"],
|
| 1365 |
+
token_indices=[4, 5, 6],
|
| 1366 |
+
)
|
| 1367 |
+
peft_model.add_adapter("adapter2", peft_config2)
|
| 1368 |
+
|
| 1369 |
+
# Get the wrapped layers
|
| 1370 |
+
embed_layer = peft_model.model.model.decoder.embed_tokens
|
| 1371 |
+
lm_head_layer = peft_model.model.lm_head
|
| 1372 |
+
|
| 1373 |
+
# Check first adapter
|
| 1374 |
+
assert "default" in embed_layer.token_indices
|
| 1375 |
+
assert "default" in lm_head_layer.token_indices
|
| 1376 |
+
assert embed_layer.token_indices["default"] == [1, 2, 3]
|
| 1377 |
+
assert lm_head_layer.token_indices["default"] == [1, 2, 3]
|
| 1378 |
+
|
| 1379 |
+
# First adapter should maintain tying
|
| 1380 |
+
assert embed_layer.trainable_tokens_delta["default"] is lm_head_layer.trainable_tokens_delta["default"]
|
| 1381 |
+
|
| 1382 |
+
# Check second adapter
|
| 1383 |
+
assert "adapter2" in embed_layer.token_indices
|
| 1384 |
+
assert "adapter2" in lm_head_layer.token_indices
|
| 1385 |
+
assert embed_layer.token_indices["adapter2"] == [4, 5, 6]
|
| 1386 |
+
assert lm_head_layer.token_indices["adapter2"] == [4, 5, 6]
|
| 1387 |
+
|
| 1388 |
+
# Second adapter should also maintain tying
|
| 1389 |
+
assert embed_layer.trainable_tokens_delta["adapter2"] is lm_head_layer.trainable_tokens_delta["adapter2"]
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_tuners_utils.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/test_vblora.py
ADDED
|
@@ -0,0 +1,269 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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-a27f5bd16532/tests/source/tests/test_vera.py
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
# 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_false(self, mlp, tmp_path):
|
| 110 |
+
# check saving and loading works with multiple adapters without saved projection weights
|
| 111 |
+
torch.manual_seed(1)
|
| 112 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 113 |
+
# creates a default VeRA adapter
|
| 114 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 115 |
+
config2 = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 116 |
+
peft_model.add_adapter("second", config2)
|
| 117 |
+
|
| 118 |
+
input = torch.randn(5, 10)
|
| 119 |
+
peft_model.set_adapter("first")
|
| 120 |
+
output_first = peft_model(input)
|
| 121 |
+
peft_model.set_adapter("second")
|
| 122 |
+
output_second = peft_model(input)
|
| 123 |
+
|
| 124 |
+
# sanity check
|
| 125 |
+
assert not torch.allclose(output_first, output_second, atol=1e-3, rtol=1e-3)
|
| 126 |
+
|
| 127 |
+
save_path = tmp_path / "vera"
|
| 128 |
+
peft_model.save_pretrained(save_path)
|
| 129 |
+
assert os.path.exists(save_path / "first" / "adapter_config.json")
|
| 130 |
+
assert os.path.exists(save_path / "second" / "adapter_config.json")
|
| 131 |
+
|
| 132 |
+
torch.manual_seed(0)
|
| 133 |
+
mlp = MLP()
|
| 134 |
+
peft_model = PeftModel.from_pretrained(mlp, save_path / "first", adapter_name="first")
|
| 135 |
+
peft_model.load_adapter(save_path / "second", "second")
|
| 136 |
+
|
| 137 |
+
peft_model.set_adapter("first")
|
| 138 |
+
output_first_loaded = peft_model(input)
|
| 139 |
+
peft_model.set_adapter("second")
|
| 140 |
+
output_second_loaded = peft_model(input)
|
| 141 |
+
|
| 142 |
+
assert torch.allclose(output_first, output_first_loaded, atol=1e-3, rtol=1e-3)
|
| 143 |
+
assert torch.allclose(output_second, output_second_loaded, atol=1e-3, rtol=1e-3)
|
| 144 |
+
|
| 145 |
+
def test_multiple_adapters_save_projection_false_contains_no_vera_A_vera_B(self, mlp, tmp_path):
|
| 146 |
+
torch.manual_seed(1)
|
| 147 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 148 |
+
# creates a default VeRA adapter
|
| 149 |
+
peft_model = get_peft_model(mlp, config, adapter_name="first")
|
| 150 |
+
config2 = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False, save_projection=False)
|
| 151 |
+
peft_model.add_adapter("second", config2)
|
| 152 |
+
|
| 153 |
+
save_path = tmp_path / "vera"
|
| 154 |
+
peft_model.save_pretrained(save_path)
|
| 155 |
+
|
| 156 |
+
sd_default = {}
|
| 157 |
+
with safe_open(save_path / "first" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 158 |
+
for key in f.keys():
|
| 159 |
+
sd_default[key] = f.get_tensor(key)
|
| 160 |
+
|
| 161 |
+
assert not any("vera_A" in key for key in sd_default)
|
| 162 |
+
assert not any("vera_B" in key for key in sd_default)
|
| 163 |
+
|
| 164 |
+
sd_other = {}
|
| 165 |
+
with safe_open(save_path / "second" / "adapter_model.safetensors", framework="pt", device="cpu") as f:
|
| 166 |
+
for key in f.keys():
|
| 167 |
+
sd_other[key] = f.get_tensor(key)
|
| 168 |
+
|
| 169 |
+
assert not any("vera_A" in key for key in sd_other)
|
| 170 |
+
assert not any("vera_B" in key for key in sd_other)
|
| 171 |
+
|
| 172 |
+
def test_vera_A_vera_B_share_memory(self, mlp_same_prng):
|
| 173 |
+
vera_A = mlp_same_prng.vera_A["default"]
|
| 174 |
+
vera_B = mlp_same_prng.vera_B["default"]
|
| 175 |
+
|
| 176 |
+
# these tensors should share the same data
|
| 177 |
+
assert vera_A.data_ptr() == mlp_same_prng.base_model.model.lin1.vera_A["default"].data_ptr()
|
| 178 |
+
assert vera_B.data_ptr() == mlp_same_prng.base_model.model.lin1.vera_B["default"].data_ptr()
|
| 179 |
+
assert vera_A.data_ptr() == mlp_same_prng.base_model.model.lin2.vera_A["default"].data_ptr()
|
| 180 |
+
assert vera_B.data_ptr() == mlp_same_prng.base_model.model.lin2.vera_B["default"].data_ptr()
|
| 181 |
+
# sanity check: these tensors shouldn't share the same data
|
| 182 |
+
assert vera_A.data_ptr() != vera_B.data_ptr()
|
| 183 |
+
|
| 184 |
+
def test_vera_lambda_dont_share_memory(self, mlp_same_prng):
|
| 185 |
+
# sanity check: these tensors shouldn't share the same data
|
| 186 |
+
assert (
|
| 187 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_b["default"].data_ptr()
|
| 188 |
+
!= mlp_same_prng.base_model.model.lin1.vera_lambda_b["other"].data_ptr()
|
| 189 |
+
)
|
| 190 |
+
assert (
|
| 191 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_b["default"].data_ptr()
|
| 192 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_b["default"].data_ptr()
|
| 193 |
+
)
|
| 194 |
+
assert (
|
| 195 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_b["other"].data_ptr()
|
| 196 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_b["other"].data_ptr()
|
| 197 |
+
)
|
| 198 |
+
assert (
|
| 199 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_d["default"].data_ptr()
|
| 200 |
+
!= mlp_same_prng.base_model.model.lin1.vera_lambda_d["other"].data_ptr()
|
| 201 |
+
)
|
| 202 |
+
assert (
|
| 203 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_d["default"].data_ptr()
|
| 204 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_d["default"].data_ptr()
|
| 205 |
+
)
|
| 206 |
+
assert (
|
| 207 |
+
mlp_same_prng.base_model.model.lin1.vera_lambda_d["other"].data_ptr()
|
| 208 |
+
!= mlp_same_prng.base_model.model.lin2.vera_lambda_d["other"].data_ptr()
|
| 209 |
+
)
|
| 210 |
+
|
| 211 |
+
def test_vera_different_shapes(self, mlp):
|
| 212 |
+
config = VeraConfig(target_modules=["lin0", "lin3"], init_weights=False)
|
| 213 |
+
mlp_different_shapes = get_peft_model(mlp, config)
|
| 214 |
+
|
| 215 |
+
vera_A = mlp_different_shapes.vera_A["default"]
|
| 216 |
+
vera_B = mlp_different_shapes.vera_B["default"]
|
| 217 |
+
|
| 218 |
+
# sanity check
|
| 219 |
+
assert mlp.lin0.base_layer.weight.shape != mlp.lin3.base_layer.weight.shape
|
| 220 |
+
|
| 221 |
+
# lin0 has the largest output dimension, lin3 has the largest input dimension
|
| 222 |
+
# vera_A should have the shape of (rank, largest_in), vera_B should have the shape of (largest_out, rank)
|
| 223 |
+
assert vera_A.shape == (config.r, mlp.lin3.in_features)
|
| 224 |
+
assert vera_B.shape == (mlp.lin0.out_features, config.r)
|
| 225 |
+
|
| 226 |
+
# should not raise
|
| 227 |
+
input = torch.randn(5, 10)
|
| 228 |
+
mlp_different_shapes(input)
|
| 229 |
+
|
| 230 |
+
@pytest.mark.parametrize("dtype", [torch.float32, torch.float16, torch.bfloat16])
|
| 231 |
+
def test_vera_dtypes(self, dtype):
|
| 232 |
+
if dtype == torch.bfloat16:
|
| 233 |
+
# skip if bf16 is not supported on hardware, see #1872
|
| 234 |
+
if not is_bf16_available():
|
| 235 |
+
pytest.skip("bfloat16 not supported on this system, skipping the test")
|
| 236 |
+
|
| 237 |
+
model = MLP().to(dtype)
|
| 238 |
+
config = VeraConfig(target_modules=["lin1", "lin2"], init_weights=False)
|
| 239 |
+
peft_model = get_peft_model(model, config)
|
| 240 |
+
inputs = torch.randn(5, 10).to(dtype)
|
| 241 |
+
output = peft_model(inputs) # should not raise
|
| 242 |
+
assert output.dtype == dtype
|
tasks/tasksmith-a27f5bd16532/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-a27f5bd16532/tests/source/tests/test_xlora.py
ADDED
|
@@ -0,0 +1,480 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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/tiny-random-OPTForCausalLM"
|
| 55 |
+
num_loras = 4
|
| 56 |
+
|
| 57 |
+
@pytest.fixture
|
| 58 |
+
def base_model(self):
|
| 59 |
+
with hub_online_once(self.model_id):
|
| 60 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 61 |
+
yield model
|
| 62 |
+
|
| 63 |
+
@pytest.fixture(scope="class")
|
| 64 |
+
def lora_dir(self, tmp_path_factory):
|
| 65 |
+
return tmp_path_factory.mktemp("lora")
|
| 66 |
+
|
| 67 |
+
@pytest.fixture(scope="class")
|
| 68 |
+
def lora_embedding_dir(self, tmp_path_factory):
|
| 69 |
+
return tmp_path_factory.mktemp("lora_embedding")
|
| 70 |
+
|
| 71 |
+
@pytest.fixture(scope="class")
|
| 72 |
+
def saved_lora_adapters(self, lora_dir):
|
| 73 |
+
file_names = []
|
| 74 |
+
|
| 75 |
+
lora_configs = [
|
| 76 |
+
LoraConfig(task_type="CAUSAL_LM", target_modules=["q_proj", "v_proj"], init_lora_weights=False)
|
| 77 |
+
for _ in range(self.num_loras)
|
| 78 |
+
]
|
| 79 |
+
# have 1 LoRA with different target modules
|
| 80 |
+
lora_configs[-1] = LoraConfig(
|
| 81 |
+
task_type="CAUSAL_LM", target_modules=["k_proj", "q_proj", "v_proj"], init_lora_weights=False
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
with hub_online_once(self.model_id):
|
| 85 |
+
for i, lora_config in enumerate(lora_configs, start=1):
|
| 86 |
+
torch.manual_seed(i)
|
| 87 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 88 |
+
peft_model = get_peft_model(model, lora_config)
|
| 89 |
+
file_name = os.path.join(lora_dir, f"checkpoint-{i}")
|
| 90 |
+
peft_model.save_pretrained(file_name)
|
| 91 |
+
file_names.append(file_name)
|
| 92 |
+
return file_names
|
| 93 |
+
|
| 94 |
+
@pytest.fixture(scope="class")
|
| 95 |
+
def saved_lora_embedding_adapters(self, lora_embedding_dir):
|
| 96 |
+
file_names = []
|
| 97 |
+
with hub_online_once(self.model_id):
|
| 98 |
+
for i in range(1, self.num_loras + 1):
|
| 99 |
+
torch.manual_seed(i)
|
| 100 |
+
lora_config = LoraConfig(
|
| 101 |
+
task_type="CAUSAL_LM", init_lora_weights=False, target_modules=["embed_tokens"]
|
| 102 |
+
)
|
| 103 |
+
model = AutoModelForCausalLM.from_pretrained(self.model_id)
|
| 104 |
+
peft_model = get_peft_model(model, lora_config)
|
| 105 |
+
file_name = os.path.join(lora_embedding_dir, f"checkpoint-{i}")
|
| 106 |
+
peft_model.save_pretrained(file_name)
|
| 107 |
+
file_names.append(file_name)
|
| 108 |
+
return file_names
|
| 109 |
+
|
| 110 |
+
@pytest.fixture(scope="class")
|
| 111 |
+
def tokenizer(self):
|
| 112 |
+
tokenizer = AutoTokenizer.from_pretrained(self.model_id, trust_remote_code=True, device_map=self.torch_device)
|
| 113 |
+
return tokenizer
|
| 114 |
+
|
| 115 |
+
@pytest.fixture(scope="function")
|
| 116 |
+
def embedding_model(self, base_model, saved_lora_embedding_adapters):
|
| 117 |
+
base_model.config.use_cache = False
|
| 118 |
+
adapters = {str(i): file_name for i, file_name in enumerate(saved_lora_embedding_adapters)}
|
| 119 |
+
|
| 120 |
+
peft_config = XLoraConfig(
|
| 121 |
+
task_type=TaskType.CAUSAL_LM,
|
| 122 |
+
peft_type=PeftType.XLORA,
|
| 123 |
+
hidden_size=base_model.config.hidden_size,
|
| 124 |
+
xlora_depth=8,
|
| 125 |
+
adapters=adapters,
|
| 126 |
+
)
|
| 127 |
+
model = get_peft_model(base_model, peft_config).to(self.torch_device)
|
| 128 |
+
return model
|
| 129 |
+
|
| 130 |
+
@pytest.fixture(scope="function")
|
| 131 |
+
def model(self, base_model, saved_lora_adapters):
|
| 132 |
+
base_model.config.use_cache = False
|
| 133 |
+
adapters = {str(i): file_name for i, file_name in enumerate(saved_lora_adapters)}
|
| 134 |
+
|
| 135 |
+
peft_config = XLoraConfig(
|
| 136 |
+
task_type=TaskType.CAUSAL_LM,
|
| 137 |
+
peft_type=PeftType.XLORA,
|
| 138 |
+
hidden_size=base_model.config.hidden_size,
|
| 139 |
+
xlora_depth=8,
|
| 140 |
+
adapters=adapters,
|
| 141 |
+
)
|
| 142 |
+
model = get_peft_model(base_model, peft_config).to(self.torch_device)
|
| 143 |
+
return model
|
| 144 |
+
|
| 145 |
+
@pytest.fixture(scope="function")
|
| 146 |
+
def model_layerwise(self, base_model, saved_lora_adapters):
|
| 147 |
+
base_model.config.use_cache = False
|
| 148 |
+
adapters = {str(i): file_name for i, file_name in enumerate(saved_lora_adapters)}
|
| 149 |
+
|
| 150 |
+
peft_config = XLoraConfig(
|
| 151 |
+
task_type=TaskType.CAUSAL_LM,
|
| 152 |
+
peft_type=PeftType.XLORA,
|
| 153 |
+
hidden_size=base_model.config.hidden_size,
|
| 154 |
+
xlora_depth=8,
|
| 155 |
+
adapters=adapters,
|
| 156 |
+
layerwise_scalings=True,
|
| 157 |
+
)
|
| 158 |
+
model = get_peft_model(base_model, peft_config).to(self.torch_device)
|
| 159 |
+
return model
|
| 160 |
+
|
| 161 |
+
def test_functional(self, tokenizer, model):
|
| 162 |
+
model.enable_scalings_logging()
|
| 163 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 164 |
+
outputs = model.generate(
|
| 165 |
+
input_ids=inputs.to(self.torch_device),
|
| 166 |
+
max_new_tokens=32,
|
| 167 |
+
)
|
| 168 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 169 |
+
|
| 170 |
+
def test_forward_hooks_are_cleaned_up(self, tokenizer, model):
|
| 171 |
+
# There was an issue that forward hooks would accumulate during generation, since one hook per forward step was
|
| 172 |
+
# being registered and generate would call forward multiple times. This is already undesirable, but to make it
|
| 173 |
+
# worse, only the last hook was removed, resulting in hooks accumulating.
|
| 174 |
+
# See https://github.com/huggingface/peft/issues/1472#issuecomment-3235817807
|
| 175 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 176 |
+
model.generate(input_ids=inputs.to(self.torch_device), max_new_tokens=10)
|
| 177 |
+
num_hooks_gen1 = len(model.base_model.model.model.decoder.layers[0].self_attn.k_proj._forward_pre_hooks)
|
| 178 |
+
|
| 179 |
+
model.generate(input_ids=inputs.to(self.torch_device), max_new_tokens=10)
|
| 180 |
+
num_hooks_gen2 = len(model.base_model.model.model.decoder.layers[0].self_attn.k_proj._forward_pre_hooks)
|
| 181 |
+
assert num_hooks_gen1 == num_hooks_gen2 == 0
|
| 182 |
+
|
| 183 |
+
def test_scalings_logging_methods(self, tokenizer, model):
|
| 184 |
+
model.enable_scalings_logging()
|
| 185 |
+
|
| 186 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 187 |
+
outputs = model.generate(
|
| 188 |
+
input_ids=inputs.to(self.torch_device),
|
| 189 |
+
max_new_tokens=32,
|
| 190 |
+
)
|
| 191 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 192 |
+
|
| 193 |
+
_ = model.get_latest_scalings()
|
| 194 |
+
# 32 is the numeber of max scalings. 3 is the number of prompt tokens.
|
| 195 |
+
assert 32 + 3 >= len(model.get_scalings_log()) > 0
|
| 196 |
+
|
| 197 |
+
model.disable_scalings_logging()
|
| 198 |
+
|
| 199 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 200 |
+
outputs = model.generate(
|
| 201 |
+
input_ids=inputs.to(self.torch_device),
|
| 202 |
+
max_new_tokens=32,
|
| 203 |
+
)
|
| 204 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 205 |
+
|
| 206 |
+
assert 32 >= len(model.get_scalings_log()) > 0
|
| 207 |
+
|
| 208 |
+
bucketed = model.get_bucketed_scalings_log()
|
| 209 |
+
keys = bucketed.keys()
|
| 210 |
+
# Once bucket for each token as we aren't using cache
|
| 211 |
+
assert len(bucketed) == 32 == len(keys)
|
| 212 |
+
seq_len = inputs.shape[1]
|
| 213 |
+
for key in keys:
|
| 214 |
+
assert len(bucketed[key][0]) == 1
|
| 215 |
+
assert len(bucketed[key][1]) == 1
|
| 216 |
+
assert bucketed[key][0][0] == key - seq_len
|
| 217 |
+
|
| 218 |
+
model.clear_scalings_log()
|
| 219 |
+
assert len(model.get_scalings_log()) == 0
|
| 220 |
+
|
| 221 |
+
def test_misc_methods(self, tokenizer, model):
|
| 222 |
+
model.set_global_scaling_weight(1.5)
|
| 223 |
+
assert model.internal_xlora_classifier.config.global_scaling_weight == 1.5
|
| 224 |
+
assert model.get_global_scaling_weight() == 1.5
|
| 225 |
+
|
| 226 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 227 |
+
outputs = model.generate(
|
| 228 |
+
input_ids=inputs.to(self.torch_device),
|
| 229 |
+
max_new_tokens=32,
|
| 230 |
+
)
|
| 231 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 232 |
+
|
| 233 |
+
assert str(model) is not None
|
| 234 |
+
|
| 235 |
+
# On CI (but not locally), this test is flaky since transformers v4.45.0.
|
| 236 |
+
@flaky(num_tries=5)
|
| 237 |
+
def test_save_load_functional(self, tokenizer, base_model, model, tmp_path):
|
| 238 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 239 |
+
outputs = model.generate(
|
| 240 |
+
input_ids=inputs.to(self.torch_device),
|
| 241 |
+
max_new_tokens=32,
|
| 242 |
+
)
|
| 243 |
+
before_logits = outputs[: inputs.shape[1] :]
|
| 244 |
+
assert torch.isfinite(before_logits).all()
|
| 245 |
+
|
| 246 |
+
model.save_pretrained(save_directory=tmp_path)
|
| 247 |
+
|
| 248 |
+
del model
|
| 249 |
+
|
| 250 |
+
base_model.config.use_cache = False
|
| 251 |
+
model = PeftModel.from_pretrained(model=base_model, model_id=tmp_path).to(self.torch_device)
|
| 252 |
+
|
| 253 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 254 |
+
outputs = model.generate(
|
| 255 |
+
input_ids=inputs.to(self.torch_device),
|
| 256 |
+
max_new_tokens=32,
|
| 257 |
+
)
|
| 258 |
+
after_logits = outputs[: inputs.shape[1] :]
|
| 259 |
+
assert torch.isfinite(after_logits).all()
|
| 260 |
+
assert torch.equal(after_logits, before_logits)
|
| 261 |
+
|
| 262 |
+
def test_save_load_functional_pt(self, tokenizer, base_model, model, tmp_path):
|
| 263 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 264 |
+
outputs = model.generate(
|
| 265 |
+
input_ids=inputs.to(self.torch_device),
|
| 266 |
+
max_new_tokens=32,
|
| 267 |
+
)
|
| 268 |
+
before_logits = outputs[: inputs.shape[1] :]
|
| 269 |
+
assert torch.isfinite(before_logits).all()
|
| 270 |
+
|
| 271 |
+
model.save_pretrained(save_directory=tmp_path, safe_serialization=False)
|
| 272 |
+
|
| 273 |
+
del model
|
| 274 |
+
|
| 275 |
+
base_model.config.use_cache = False
|
| 276 |
+
model = PeftModel.from_pretrained(model=base_model, model_id=tmp_path, safe_serialization=False).to(
|
| 277 |
+
self.torch_device
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 281 |
+
outputs = model.generate(
|
| 282 |
+
input_ids=inputs.to(self.torch_device),
|
| 283 |
+
max_new_tokens=32,
|
| 284 |
+
)
|
| 285 |
+
after_logits = outputs[: inputs.shape[1] :]
|
| 286 |
+
assert torch.isfinite(after_logits).all()
|
| 287 |
+
assert torch.equal(after_logits, before_logits), (after_logits, before_logits)
|
| 288 |
+
|
| 289 |
+
def test_topk_lora(self, tokenizer, model):
|
| 290 |
+
model.set_topk_lora(2)
|
| 291 |
+
assert model.internal_xlora_classifier.config.top_k_lora == 2
|
| 292 |
+
|
| 293 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 294 |
+
outputs = model.generate(
|
| 295 |
+
input_ids=inputs.to(self.torch_device),
|
| 296 |
+
max_new_tokens=32,
|
| 297 |
+
)
|
| 298 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 299 |
+
|
| 300 |
+
def test_softmax_topk(self, tokenizer, model):
|
| 301 |
+
# Just reach in to set the config
|
| 302 |
+
model.internal_xlora_classifier.config.top_k_lora = 2
|
| 303 |
+
model.internal_xlora_classifier.config.enable_softmax = False
|
| 304 |
+
model.internal_xlora_classifier.config.enable_softmax_topk = True
|
| 305 |
+
|
| 306 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 307 |
+
outputs = model.generate(
|
| 308 |
+
input_ids=inputs.to(self.torch_device),
|
| 309 |
+
max_new_tokens=32,
|
| 310 |
+
)
|
| 311 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 312 |
+
|
| 313 |
+
def test_set_override_scaling_pass_value(self, model):
|
| 314 |
+
# Defaults to 0
|
| 315 |
+
assert model.internal_xlora_classifier.override_scaling_pass_value == 0.0
|
| 316 |
+
|
| 317 |
+
# Set it to 2 and make sure it actually is
|
| 318 |
+
model.set_scaling_pass_value(2)
|
| 319 |
+
assert model.internal_xlora_classifier.override_scaling_pass_value == 2
|
| 320 |
+
assert model.internal_xlora_classifier.config.scaling_pass_value == 2
|
| 321 |
+
|
| 322 |
+
# Set it to None and make sure it is 1/n
|
| 323 |
+
model.set_scaling_pass_value(None)
|
| 324 |
+
assert model.internal_xlora_classifier.override_scaling_pass_value == 1 / self.num_loras
|
| 325 |
+
assert model.internal_xlora_classifier.config.scaling_pass_value == 1 / self.num_loras
|
| 326 |
+
|
| 327 |
+
def test_functional_layerwise(self, tokenizer, model_layerwise):
|
| 328 |
+
model_layerwise.enable_scalings_logging()
|
| 329 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 330 |
+
outputs = model_layerwise.generate(
|
| 331 |
+
input_ids=inputs.to(self.torch_device),
|
| 332 |
+
max_new_tokens=32,
|
| 333 |
+
)
|
| 334 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 335 |
+
|
| 336 |
+
def test_disable_adapter(self, tokenizer, model):
|
| 337 |
+
model.enable_scalings_logging()
|
| 338 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 339 |
+
with model.disable_adapter():
|
| 340 |
+
outputs_disabled = model.generate(
|
| 341 |
+
input_ids=inputs.to(self.torch_device),
|
| 342 |
+
max_new_tokens=32,
|
| 343 |
+
)
|
| 344 |
+
outputs = model.generate(
|
| 345 |
+
input_ids=inputs.to(self.torch_device),
|
| 346 |
+
max_new_tokens=32,
|
| 347 |
+
)
|
| 348 |
+
assert torch.isfinite(outputs_disabled[: inputs.shape[1] :]).all()
|
| 349 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 350 |
+
assert not torch.equal(outputs, outputs_disabled)
|
| 351 |
+
|
| 352 |
+
def test_functional_embedding(self, tokenizer, embedding_model):
|
| 353 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 354 |
+
outputs = embedding_model.generate(
|
| 355 |
+
input_ids=inputs.to(self.torch_device),
|
| 356 |
+
max_new_tokens=32,
|
| 357 |
+
)
|
| 358 |
+
assert torch.isfinite(outputs[: inputs.shape[1] :]).all()
|
| 359 |
+
|
| 360 |
+
def test_xlora_loading_valid(self):
|
| 361 |
+
# This test also simulatenously tests the loading-from-hub functionality!
|
| 362 |
+
torch.manual_seed(123)
|
| 363 |
+
|
| 364 |
+
model_id = "peft-internal-testing/opt-125m"
|
| 365 |
+
with hub_online_once(model_id):
|
| 366 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 367 |
+
# note: exit the caching context to allow download of the LoRA adapters below
|
| 368 |
+
model.config.use_cache = False
|
| 369 |
+
|
| 370 |
+
adapters = [
|
| 371 |
+
"peft-internal-testing/opt-125m-dummy-lora",
|
| 372 |
+
"peft-internal-testing/opt-125m-dummy-lora",
|
| 373 |
+
]
|
| 374 |
+
adapters = {str(i): file_name for i, file_name in enumerate(adapters)}
|
| 375 |
+
|
| 376 |
+
peft_config = XLoraConfig(
|
| 377 |
+
task_type=TaskType.CAUSAL_LM,
|
| 378 |
+
peft_type=PeftType.XLORA,
|
| 379 |
+
hidden_size=model.config.hidden_size,
|
| 380 |
+
adapters=adapters,
|
| 381 |
+
xlora_depth=8,
|
| 382 |
+
xlora_size=2048,
|
| 383 |
+
layerwise_scalings=True,
|
| 384 |
+
xlora_dropout_p=0.2,
|
| 385 |
+
)
|
| 386 |
+
model = get_peft_model(model, peft_config)
|
| 387 |
+
|
| 388 |
+
downloaded = huggingface_hub.hf_hub_download(repo_id=adapters["0"], filename="adapter_model.safetensors")
|
| 389 |
+
sd = load_file(downloaded)
|
| 390 |
+
w0 = model.base_model.model.model.decoder.layers[0].self_attn.q_proj.lora_A["0"].weight
|
| 391 |
+
w1 = sd["base_model.model.model.decoder.layers.0.self_attn.q_proj.lora_A.weight"]
|
| 392 |
+
|
| 393 |
+
assert torch.allclose(w0, w1)
|
| 394 |
+
|
| 395 |
+
def test_scalings_storage(self, tokenizer, model):
|
| 396 |
+
model.enable_scalings_logging()
|
| 397 |
+
inputs = tokenizer.encode("Python is a", add_special_tokens=False, return_tensors="pt")
|
| 398 |
+
outputs = model.generate(
|
| 399 |
+
input_ids=inputs.to(self.torch_device),
|
| 400 |
+
max_new_tokens=10,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
latest_scalings = model.get_latest_scalings()
|
| 404 |
+
assert latest_scalings is not None, "get_latest_scalings() should not return None after generation"
|
| 405 |
+
assert isinstance(latest_scalings, torch.Tensor)
|
| 406 |
+
assert torch.isfinite(latest_scalings).all(), "Scalings should contain finite values"
|
| 407 |
+
|
| 408 |
+
def test_per_token_normalization_with_softmax_topk(self, tokenizer, model, monkeypatch):
|
| 409 |
+
model.internal_xlora_classifier.config.top_k_lora = 2
|
| 410 |
+
model.internal_xlora_classifier.config.enable_softmax = False
|
| 411 |
+
model.internal_xlora_classifier.config.enable_softmax_topk = True
|
| 412 |
+
|
| 413 |
+
captured_data = []
|
| 414 |
+
orig_get_maybe_topk_scalings = XLoraLayer.get_maybe_topk_scalings
|
| 415 |
+
|
| 416 |
+
def mock_get_maybe_topk_scalings(self, scalings):
|
| 417 |
+
result = orig_get_maybe_topk_scalings(self, scalings)
|
| 418 |
+
if getattr(model, "internal_xlora_scalings", None) is not None:
|
| 419 |
+
captured_data.append(result)
|
| 420 |
+
return result
|
| 421 |
+
|
| 422 |
+
monkeypatch.setattr(XLoraLayer, "get_maybe_topk_scalings", mock_get_maybe_topk_scalings)
|
| 423 |
+
|
| 424 |
+
model.enable_scalings_logging()
|
| 425 |
+
inputs = tokenizer.encode("Test per token normalization", add_special_tokens=False, return_tensors="pt")
|
| 426 |
+
outputs = model.generate(
|
| 427 |
+
input_ids=inputs.to(self.torch_device),
|
| 428 |
+
max_new_tokens=1,
|
| 429 |
+
)
|
| 430 |
+
|
| 431 |
+
for scaling in captured_data:
|
| 432 |
+
weight_sums = scaling.sum(dim=-1)
|
| 433 |
+
assert torch.allclose(weight_sums, torch.ones_like(weight_sums), atol=1e-5), (
|
| 434 |
+
"Per-token scaling weights are not normalized to sum to 1."
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
def test_xlora_embed_scale_is_applied(self, tmp_path):
|
| 438 |
+
"""Test that X-LoRA correctly handles embeddings with scaling (e.g., Gemma3)."""
|
| 439 |
+
model_id = "hf-internal-testing/tiny-random-Gemma3ForCausalLM"
|
| 440 |
+
with hub_online_once(model_id):
|
| 441 |
+
# Create and save Gemma3-compatible LoRA adapters
|
| 442 |
+
adapters = {}
|
| 443 |
+
for i in range(2):
|
| 444 |
+
torch.manual_seed(i + 1)
|
| 445 |
+
lora_config = LoraConfig(
|
| 446 |
+
task_type="CAUSAL_LM", init_lora_weights=False, target_modules=["embed_tokens"]
|
| 447 |
+
)
|
| 448 |
+
model = AutoModelForCausalLM.from_pretrained(model_id)
|
| 449 |
+
peft_model = get_peft_model(model, lora_config)
|
| 450 |
+
adapter_path = os.path.join(tmp_path, f"checkpoint-{i + 1}")
|
| 451 |
+
peft_model.save_pretrained(adapter_path)
|
| 452 |
+
adapters[str(i)] = adapter_path
|
| 453 |
+
|
| 454 |
+
# Load base model and test X-LoRA with embed_scale
|
| 455 |
+
base_model = AutoModelForCausalLM.from_pretrained(model_id).to(self.torch_device)
|
| 456 |
+
base_model.config.use_cache = False
|
| 457 |
+
orig_embedding = base_model.get_input_embeddings()
|
| 458 |
+
|
| 459 |
+
xlora_config = XLoraConfig(
|
| 460 |
+
task_type=TaskType.CAUSAL_LM,
|
| 461 |
+
hidden_size=base_model.config.hidden_size,
|
| 462 |
+
adapters=adapters,
|
| 463 |
+
)
|
| 464 |
+
xlora_model = get_peft_model(base_model, xlora_config)
|
| 465 |
+
|
| 466 |
+
x = torch.arange(10).to(self.torch_device)
|
| 467 |
+
xlora_embedding = xlora_model.base_model.model.get_input_embeddings()
|
| 468 |
+
max_embedding_output = xlora_embedding(x).abs().max(0)[0]
|
| 469 |
+
assert (max_embedding_output < 100.0).all()
|
| 470 |
+
|
| 471 |
+
# set embed_scale to an absurdly high value, then check that the embedding output is also scaled to a high
|
| 472 |
+
# value
|
| 473 |
+
orig_embedding.embed_scale.fill_(10000.0)
|
| 474 |
+
max_embedding_output = xlora_embedding(x).abs().max(0)[0]
|
| 475 |
+
assert (max_embedding_output > 100.0).all()
|
| 476 |
+
|
| 477 |
+
# set embed_scale to zero, then check that the embedding output is also zero
|
| 478 |
+
orig_embedding.embed_scale.fill_(0)
|
| 479 |
+
embedding_output = xlora_embedding(x)
|
| 480 |
+
assert (embedding_output == 0.0).all()
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/testing_common.py
ADDED
|
@@ -0,0 +1,1876 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 |
+
LilyConfig,
|
| 40 |
+
LNTuningConfig,
|
| 41 |
+
LoHaConfig,
|
| 42 |
+
LoKrConfig,
|
| 43 |
+
LoraConfig,
|
| 44 |
+
OSFConfig,
|
| 45 |
+
PeftModel,
|
| 46 |
+
PrefixTuningConfig,
|
| 47 |
+
PromptEncoderConfig,
|
| 48 |
+
PromptLearningConfig,
|
| 49 |
+
PromptTuningConfig,
|
| 50 |
+
PveraConfig,
|
| 51 |
+
RoadConfig,
|
| 52 |
+
VBLoRAConfig,
|
| 53 |
+
VeraConfig,
|
| 54 |
+
convert_to_lora,
|
| 55 |
+
get_peft_model,
|
| 56 |
+
get_peft_model_state_dict,
|
| 57 |
+
inject_adapter_in_model,
|
| 58 |
+
prepare_model_for_kbit_training,
|
| 59 |
+
set_peft_model_state_dict,
|
| 60 |
+
)
|
| 61 |
+
from peft.import_utils import is_transformers_ge_v5
|
| 62 |
+
from peft.tuners._buffer_dict import BufferDict
|
| 63 |
+
from peft.tuners.lora import LoraLayer
|
| 64 |
+
from peft.tuners.tuners_utils import BaseTunerLayer
|
| 65 |
+
from peft.utils import (
|
| 66 |
+
AuxiliaryTrainingWrapper,
|
| 67 |
+
ModulesToSaveWrapper,
|
| 68 |
+
TrainableTokensWrapper,
|
| 69 |
+
_get_submodules,
|
| 70 |
+
infer_device,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
from .testing_utils import get_state_dict, hub_online_once
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def _skip_if_merging_not_supported(model_id, config_cls, config_kwargs):
|
| 77 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 78 |
+
pytest.skip("Prompt learning does not support merging, skipping this test.")
|
| 79 |
+
if config_kwargs.get("alora_invocation_tokens") is not None:
|
| 80 |
+
pytest.skip("Test not applicable for Activated LoRA")
|
| 81 |
+
if issubclass(config_cls, OSFConfig):
|
| 82 |
+
pytest.skip(f"Skipping test for {model_id} with {config_cls} as OSF adapter merge/unload are not implemented.")
|
| 83 |
+
if model_id.startswith("Conv2dGroups") and (config_cls == LoraConfig):
|
| 84 |
+
# note: right now, only LoRA supports groups>1, if other PEFT methods add support, they might also need to skip
|
| 85 |
+
pytest.skip("Merging conv layers with groups>1 and LoRA is not supported.")
|
| 86 |
+
if issubclass(config_cls, LilyConfig):
|
| 87 |
+
pytest.skip("Lily does not support merging adapters, skipping this test.")
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _skip_if_adding_weighted_adapters_not_supported(config):
|
| 91 |
+
if not isinstance(config, (IA3Config, LoraConfig)):
|
| 92 |
+
pytest.skip("This PEFT method does not support adding weighted adapters, skipping this test.")
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _skip_if_deleting_adapter_not_supported(config_cls, config_kwargs):
|
| 96 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 97 |
+
pytest.skip("Prompt learning does not support deletion of adapters, skipping this test.")
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs):
|
| 101 |
+
if "gpt2" not in model_id.lower():
|
| 102 |
+
return
|
| 103 |
+
|
| 104 |
+
if config_cls not in (IA3Config, LoHaConfig, LoKrConfig, LoraConfig):
|
| 105 |
+
pytest.skip("This PEFT method does not support Conv1D layers, skipping this test.")
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class PeftCommonTester:
|
| 109 |
+
r"""
|
| 110 |
+
A large testing suite for testing common functionality of the PEFT models.
|
| 111 |
+
|
| 112 |
+
Attributes:
|
| 113 |
+
torch_device (`torch.device`):
|
| 114 |
+
The device on which the tests will be run.
|
| 115 |
+
transformers_class (`transformers.PreTrainedModel`):
|
| 116 |
+
The transformers class that is being tested.
|
| 117 |
+
"""
|
| 118 |
+
|
| 119 |
+
torch_device = infer_device()
|
| 120 |
+
transformers_class = None
|
| 121 |
+
|
| 122 |
+
def prepare_inputs_for_common(self):
|
| 123 |
+
raise NotImplementedError
|
| 124 |
+
|
| 125 |
+
def check_modelcard(self, tmp_dirname, model):
|
| 126 |
+
# check the generated README.md
|
| 127 |
+
filename = os.path.join(tmp_dirname, "README.md")
|
| 128 |
+
assert os.path.exists(filename)
|
| 129 |
+
with open(filename, encoding="utf-8") as f:
|
| 130 |
+
readme = f.read()
|
| 131 |
+
metainfo = re.search(r"---\n(.*?)\n---", readme, re.DOTALL).group(1)
|
| 132 |
+
dct = yaml.safe_load(metainfo)
|
| 133 |
+
assert dct["library_name"] == "peft"
|
| 134 |
+
|
| 135 |
+
if hasattr(model, "config"):
|
| 136 |
+
assert dct["base_model"] == model.config.to_dict()["_name_or_path"]
|
| 137 |
+
else: # a custom model
|
| 138 |
+
assert "base_model" not in dct
|
| 139 |
+
|
| 140 |
+
# The Hub expects the lora tag to be set for PEFT LoRA models since they
|
| 141 |
+
# have explicit support for things like inference.
|
| 142 |
+
if model.active_peft_config.peft_type.value == "LORA":
|
| 143 |
+
assert "lora" in dct["tags"]
|
| 144 |
+
|
| 145 |
+
def check_config_json(self, tmp_dirname, model):
|
| 146 |
+
# check the generated config.json
|
| 147 |
+
filename = os.path.join(tmp_dirname, "adapter_config.json")
|
| 148 |
+
assert os.path.exists(filename)
|
| 149 |
+
with open(filename, encoding="utf-8") as f:
|
| 150 |
+
config = json.load(f)
|
| 151 |
+
|
| 152 |
+
if hasattr(model, "config"): # custom models don't have a config attribute
|
| 153 |
+
assert config["base_model_name_or_path"] == model.config.to_dict()["_name_or_path"]
|
| 154 |
+
|
| 155 |
+
def perturb_trainable_token_weights_if_used(self, model, config_kwargs, adapter_name="default", scale=1.0):
|
| 156 |
+
"""TrainableTokensLayer is initialized to be a no-op by default. Since there's currently no way to pass
|
| 157 |
+
`init_weights=False` to the trainable tokens layer when used in conjunction with LoRA, we have to do it like
|
| 158 |
+
this to make sure that it is *not* a no-op (essentially simulating "training" of the adapter).
|
| 159 |
+
"""
|
| 160 |
+
if "trainable_token_indices" not in config_kwargs:
|
| 161 |
+
return
|
| 162 |
+
|
| 163 |
+
token_wrapper = None
|
| 164 |
+
|
| 165 |
+
if hasattr(model, "get_input_embeddings"):
|
| 166 |
+
token_wrapper = model.get_input_embeddings()
|
| 167 |
+
else:
|
| 168 |
+
for module in model.modules():
|
| 169 |
+
if isinstance(module, TrainableTokensWrapper):
|
| 170 |
+
token_wrapper = module
|
| 171 |
+
break
|
| 172 |
+
|
| 173 |
+
# for a model with trainable_token_indices there should always be a trainable token wrapper somewhere.
|
| 174 |
+
# if not, then there's something broken.
|
| 175 |
+
assert token_wrapper is not None
|
| 176 |
+
|
| 177 |
+
token_wrapper.token_adapter.trainable_tokens_delta[adapter_name].data = (
|
| 178 |
+
torch.rand_like(token_wrapper.token_adapter.trainable_tokens_delta[adapter_name].data) * scale
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
def _test_model_attr(self, model_id, config_cls, config_kwargs):
|
| 182 |
+
with hub_online_once(model_id):
|
| 183 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 184 |
+
config = config_cls(
|
| 185 |
+
base_model_name_or_path=model_id,
|
| 186 |
+
**config_kwargs,
|
| 187 |
+
)
|
| 188 |
+
model = get_peft_model(model, config)
|
| 189 |
+
|
| 190 |
+
assert hasattr(model, "save_pretrained")
|
| 191 |
+
assert hasattr(model, "from_pretrained")
|
| 192 |
+
assert hasattr(model, "push_to_hub")
|
| 193 |
+
|
| 194 |
+
def _test_adapter_name(self, model_id, config_cls, config_kwargs):
|
| 195 |
+
with hub_online_once(model_id):
|
| 196 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 197 |
+
config = config_cls(
|
| 198 |
+
base_model_name_or_path=model_id,
|
| 199 |
+
**config_kwargs,
|
| 200 |
+
)
|
| 201 |
+
model = get_peft_model(model, config, adapter_name="test-adapter")
|
| 202 |
+
correctly_converted = False
|
| 203 |
+
for n, _ in model.named_parameters():
|
| 204 |
+
if "test-adapter" in n:
|
| 205 |
+
correctly_converted = True
|
| 206 |
+
break
|
| 207 |
+
|
| 208 |
+
assert correctly_converted
|
| 209 |
+
|
| 210 |
+
def _test_prepare_for_training(self, model_id, config_cls, config_kwargs):
|
| 211 |
+
if config_kwargs.get("trainable_token_indices", None) is not None:
|
| 212 |
+
# incompatible because trainable tokens is marking embeddings as trainable
|
| 213 |
+
pytest.skip("Trainable tokens is incompatible with this test.")
|
| 214 |
+
|
| 215 |
+
# some tests require specific tokenizers, make sure that they can be fetched as well
|
| 216 |
+
with hub_online_once(model_id + config_kwargs.get("tokenizer_name_or_path", "")):
|
| 217 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 218 |
+
config = config_cls(
|
| 219 |
+
base_model_name_or_path=model_id,
|
| 220 |
+
**config_kwargs,
|
| 221 |
+
)
|
| 222 |
+
model = get_peft_model(model, config)
|
| 223 |
+
|
| 224 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 225 |
+
dummy_output = model.get_input_embeddings()(dummy_input["input_ids"])
|
| 226 |
+
|
| 227 |
+
assert not dummy_output.requires_grad
|
| 228 |
+
|
| 229 |
+
# load with `prepare_model_for_kbit_training`
|
| 230 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 231 |
+
model = prepare_model_for_kbit_training(model)
|
| 232 |
+
|
| 233 |
+
for param in model.parameters():
|
| 234 |
+
assert not param.requires_grad
|
| 235 |
+
|
| 236 |
+
config = config_cls(
|
| 237 |
+
base_model_name_or_path=model_id,
|
| 238 |
+
**config_kwargs,
|
| 239 |
+
)
|
| 240 |
+
model = get_peft_model(model, config)
|
| 241 |
+
|
| 242 |
+
# For backward compatibility
|
| 243 |
+
if hasattr(model, "enable_input_require_grads"):
|
| 244 |
+
model.enable_input_require_grads()
|
| 245 |
+
else:
|
| 246 |
+
|
| 247 |
+
def make_inputs_require_grad(module, input, output):
|
| 248 |
+
output.requires_grad_(True)
|
| 249 |
+
|
| 250 |
+
model.get_input_embeddings().register_forward_hook(make_inputs_require_grad)
|
| 251 |
+
|
| 252 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 253 |
+
dummy_output = model.get_input_embeddings()(dummy_input["input_ids"])
|
| 254 |
+
|
| 255 |
+
assert dummy_output.requires_grad
|
| 256 |
+
|
| 257 |
+
def _test_load_model_low_cpu_mem_usage(self, model_id, config_cls, config_kwargs):
|
| 258 |
+
# Ensure that low_cpu_mem_usage=True works for from_pretrained and load_adapter and that the resulting model's
|
| 259 |
+
# parameters are on the correct device.
|
| 260 |
+
with hub_online_once(model_id):
|
| 261 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 262 |
+
config = config_cls(
|
| 263 |
+
base_model_name_or_path=model_id,
|
| 264 |
+
**config_kwargs,
|
| 265 |
+
)
|
| 266 |
+
model = get_peft_model(model, config)
|
| 267 |
+
|
| 268 |
+
# note: not using the context manager here because it fails on Windows CI for some reason
|
| 269 |
+
tmp_dirname = tempfile.mkdtemp()
|
| 270 |
+
try:
|
| 271 |
+
model.save_pretrained(tmp_dirname)
|
| 272 |
+
|
| 273 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 274 |
+
model = PeftModel.from_pretrained(
|
| 275 |
+
model, tmp_dirname, torch_device=self.torch_device, low_cpu_mem_usage=True
|
| 276 |
+
)
|
| 277 |
+
assert {p.device.type for p in model.parameters()} == {self.torch_device}
|
| 278 |
+
|
| 279 |
+
model.load_adapter(tmp_dirname, adapter_name="other", low_cpu_mem_usage=True)
|
| 280 |
+
assert {p.device.type for p in model.parameters()} == {self.torch_device}
|
| 281 |
+
finally:
|
| 282 |
+
try:
|
| 283 |
+
shutil.rmtree(tmp_dirname)
|
| 284 |
+
except PermissionError:
|
| 285 |
+
# windows error
|
| 286 |
+
pass
|
| 287 |
+
|
| 288 |
+
# also test injecting directly
|
| 289 |
+
del model
|
| 290 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 291 |
+
inject_adapter_in_model(config, model, low_cpu_mem_usage=True) # check that there is no error
|
| 292 |
+
|
| 293 |
+
if not isinstance(config, LNTuningConfig):
|
| 294 |
+
# LN tuning does not add adapter layers that could be on meta device, it only changes the requires_grad.
|
| 295 |
+
# Therefore, there is no meta device for LN tuning.
|
| 296 |
+
assert "meta" in {p.device.type for p in model.parameters()}
|
| 297 |
+
|
| 298 |
+
def _test_save_pretrained(self, model_id, config_cls, config_kwargs, safe_serialization=True):
|
| 299 |
+
with hub_online_once(model_id):
|
| 300 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 301 |
+
config = config_cls(
|
| 302 |
+
base_model_name_or_path=model_id,
|
| 303 |
+
**config_kwargs,
|
| 304 |
+
)
|
| 305 |
+
model = get_peft_model(model, config)
|
| 306 |
+
model = model.to(self.torch_device)
|
| 307 |
+
|
| 308 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 309 |
+
if safe_serialization:
|
| 310 |
+
model.save_pretrained(tmp_dirname)
|
| 311 |
+
else:
|
| 312 |
+
model.save_pretrained(tmp_dirname, safe_serialization=False)
|
| 313 |
+
|
| 314 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 315 |
+
with warnings.catch_warnings(record=True) as recs:
|
| 316 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 317 |
+
# ensure that there is no warning
|
| 318 |
+
assert not any("Found missing adapter keys" in str(rec.message) for rec in recs)
|
| 319 |
+
|
| 320 |
+
# check if the state dicts are equal
|
| 321 |
+
if issubclass(config_cls, PromptEncoderConfig):
|
| 322 |
+
# For prompt encoding, when loading the whole state_dict, there are differences, therefore, only load
|
| 323 |
+
# adapter-specific weights for comparison.
|
| 324 |
+
# TODO: is this expected?
|
| 325 |
+
state_dict = get_peft_model_state_dict(model, unwrap_compiled=True)
|
| 326 |
+
state_dict_from_pretrained = get_peft_model_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 327 |
+
else:
|
| 328 |
+
state_dict = get_state_dict(model, unwrap_compiled=True)
|
| 329 |
+
state_dict_from_pretrained = get_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 330 |
+
|
| 331 |
+
# check if tensors equal
|
| 332 |
+
for key in state_dict.keys():
|
| 333 |
+
assert torch.allclose(
|
| 334 |
+
state_dict[key].to(self.torch_device), state_dict_from_pretrained[key].to(self.torch_device)
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
target_adapter_filename = "adapter_model.safetensors" if safe_serialization else "adapter_model.bin"
|
| 338 |
+
|
| 339 |
+
# check if `adapter_model.safetensors` is present
|
| 340 |
+
assert os.path.exists(os.path.join(tmp_dirname, target_adapter_filename))
|
| 341 |
+
|
| 342 |
+
# check if `adapter_config.json` is present
|
| 343 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_config.json"))
|
| 344 |
+
|
| 345 |
+
# check if `model.safetensors` is not present
|
| 346 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "model.safetensors"))
|
| 347 |
+
|
| 348 |
+
# check if `config.json` is not present
|
| 349 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "config.json"))
|
| 350 |
+
|
| 351 |
+
self.check_modelcard(tmp_dirname, model)
|
| 352 |
+
self.check_config_json(tmp_dirname, model)
|
| 353 |
+
|
| 354 |
+
def _test_save_pretrained_selected_adapters(self, model_id, config_cls, config_kwargs, safe_serialization=True):
|
| 355 |
+
if issubclass(config_cls, AdaLoraConfig):
|
| 356 |
+
# AdaLora does not support adding more than 1 adapter
|
| 357 |
+
pytest.skip(f"Test not applicable for {config_cls}")
|
| 358 |
+
|
| 359 |
+
with hub_online_once(model_id):
|
| 360 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 361 |
+
config = config_cls(
|
| 362 |
+
base_model_name_or_path=model_id,
|
| 363 |
+
**config_kwargs,
|
| 364 |
+
)
|
| 365 |
+
model = get_peft_model(model, config)
|
| 366 |
+
model = model.to(self.torch_device)
|
| 367 |
+
|
| 368 |
+
new_adapter_config = config_cls(
|
| 369 |
+
base_model_name_or_path=model_id,
|
| 370 |
+
**config_kwargs,
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
model.add_adapter("new_adapter", new_adapter_config)
|
| 374 |
+
|
| 375 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 376 |
+
if safe_serialization:
|
| 377 |
+
model.save_pretrained(tmp_dirname)
|
| 378 |
+
else:
|
| 379 |
+
model.save_pretrained(tmp_dirname, safe_serialization=False)
|
| 380 |
+
|
| 381 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 382 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 383 |
+
|
| 384 |
+
new_adapter_dir = os.path.join(tmp_dirname, "new_adapter")
|
| 385 |
+
model_from_pretrained.load_adapter(new_adapter_dir, "new_adapter")
|
| 386 |
+
|
| 387 |
+
# check if the state dicts are equal
|
| 388 |
+
if issubclass(config_cls, PromptEncoderConfig):
|
| 389 |
+
# For prompt encoding, when loading the whole state_dict, there are differences, therefore, only load
|
| 390 |
+
# adapter-specific weights for comparison.
|
| 391 |
+
# TODO: is this expected?
|
| 392 |
+
state_dict = get_peft_model_state_dict(model, unwrap_compiled=True)
|
| 393 |
+
state_dict_from_pretrained = get_peft_model_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 394 |
+
else:
|
| 395 |
+
state_dict = get_state_dict(model, unwrap_compiled=True)
|
| 396 |
+
state_dict_from_pretrained = get_state_dict(model_from_pretrained, unwrap_compiled=True)
|
| 397 |
+
|
| 398 |
+
# check if same keys
|
| 399 |
+
assert state_dict.keys() == state_dict_from_pretrained.keys()
|
| 400 |
+
|
| 401 |
+
# check if tensors equal
|
| 402 |
+
for key in state_dict.keys():
|
| 403 |
+
assert torch.allclose(
|
| 404 |
+
state_dict[key].to(self.torch_device), state_dict_from_pretrained[key].to(self.torch_device)
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
target_adapter_filename = "adapter_model.safetensors" if safe_serialization else "adapter_model.bin"
|
| 408 |
+
|
| 409 |
+
# check if `adapter_model.safetensors` is present
|
| 410 |
+
assert os.path.exists(os.path.join(tmp_dirname, target_adapter_filename))
|
| 411 |
+
assert os.path.exists(os.path.join(new_adapter_dir, target_adapter_filename))
|
| 412 |
+
|
| 413 |
+
# check if `adapter_config.json` is present
|
| 414 |
+
assert os.path.exists(os.path.join(tmp_dirname, "adapter_config.json"))
|
| 415 |
+
assert os.path.exists(os.path.join(new_adapter_dir, "adapter_config.json"))
|
| 416 |
+
|
| 417 |
+
# check if `model.safetensors` is not present
|
| 418 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "model.safetensors"))
|
| 419 |
+
assert not os.path.exists(os.path.join(new_adapter_dir, "model.safetensors"))
|
| 420 |
+
|
| 421 |
+
# check if `config.json` is not present
|
| 422 |
+
assert not os.path.exists(os.path.join(tmp_dirname, "config.json"))
|
| 423 |
+
assert not os.path.exists(os.path.join(new_adapter_dir, "config.json"))
|
| 424 |
+
|
| 425 |
+
self.check_modelcard(tmp_dirname, model)
|
| 426 |
+
self.check_config_json(tmp_dirname, model)
|
| 427 |
+
|
| 428 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 429 |
+
model.save_pretrained(tmp_dirname, selected_adapters=["default"])
|
| 430 |
+
|
| 431 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 432 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname)
|
| 433 |
+
|
| 434 |
+
assert "default" in model_from_pretrained.peft_config.keys()
|
| 435 |
+
assert "new_adapter" not in model_from_pretrained.peft_config.keys()
|
| 436 |
+
|
| 437 |
+
def _test_from_pretrained_config_construction(self, model_id, config_cls, config_kwargs):
|
| 438 |
+
with hub_online_once(model_id):
|
| 439 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 440 |
+
config = config_cls(base_model_name_or_path=model_id, **config_kwargs)
|
| 441 |
+
model = get_peft_model(model, config)
|
| 442 |
+
model = model.to(self.torch_device)
|
| 443 |
+
|
| 444 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 445 |
+
model.save_pretrained(tmp_dirname)
|
| 446 |
+
|
| 447 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 448 |
+
model_from_pretrained = PeftModel.from_pretrained(
|
| 449 |
+
model_from_pretrained, tmp_dirname, is_trainable=False, config=config
|
| 450 |
+
)
|
| 451 |
+
|
| 452 |
+
assert model_from_pretrained.peft_config["default"].inference_mode
|
| 453 |
+
assert model_from_pretrained.peft_config["default"] is config
|
| 454 |
+
|
| 455 |
+
def _test_load_multiple_adapters(self, model_id, config_cls, config_kwargs):
|
| 456 |
+
# just ensure that this works and raises no error
|
| 457 |
+
with hub_online_once(model_id):
|
| 458 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 459 |
+
config = config_cls(
|
| 460 |
+
base_model_name_or_path=model_id,
|
| 461 |
+
**config_kwargs,
|
| 462 |
+
)
|
| 463 |
+
model = get_peft_model(model, config)
|
| 464 |
+
|
| 465 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 466 |
+
model.save_pretrained(tmp_dirname)
|
| 467 |
+
del model
|
| 468 |
+
|
| 469 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 470 |
+
model = PeftModel.from_pretrained(model, tmp_dirname, torch_device=self.torch_device)
|
| 471 |
+
load_result1 = model.load_adapter(tmp_dirname, adapter_name="other")
|
| 472 |
+
load_result2 = model.load_adapter(tmp_dirname, adapter_name="yet-another")
|
| 473 |
+
|
| 474 |
+
# VBLoRA uses a shared "vblora_vector_bank" across all layers, causing it to appear
|
| 475 |
+
# in the missing keys list, which leads to failed test cases. So
|
| 476 |
+
# skipping the missing keys check for VBLoRA.
|
| 477 |
+
if config.peft_type != "VBLORA":
|
| 478 |
+
assert load_result1.missing_keys == []
|
| 479 |
+
assert load_result2.missing_keys == []
|
| 480 |
+
|
| 481 |
+
def _test_merge_layers_fp16(self, model_id, config_cls, config_kwargs):
|
| 482 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 483 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 484 |
+
if (self.torch_device in ["cpu"]) and (version.parse(torch.__version__) <= version.parse("2.1")):
|
| 485 |
+
pytest.skip("PyTorch 2.1 not supported for Half of addmm_impl_cpu_ ")
|
| 486 |
+
|
| 487 |
+
with hub_online_once(model_id):
|
| 488 |
+
model = self.transformers_class.from_pretrained(model_id, dtype=torch.float16)
|
| 489 |
+
config = config_cls(
|
| 490 |
+
base_model_name_or_path=model_id,
|
| 491 |
+
**config_kwargs,
|
| 492 |
+
)
|
| 493 |
+
model = get_peft_model(model, config)
|
| 494 |
+
model = model.to(device=self.torch_device, dtype=torch.float16)
|
| 495 |
+
|
| 496 |
+
model.eval()
|
| 497 |
+
|
| 498 |
+
# This should simply work
|
| 499 |
+
_ = model.merge_and_unload()
|
| 500 |
+
|
| 501 |
+
def _test_merge_layers_nan(self, model_id, config_cls, config_kwargs):
|
| 502 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 503 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 504 |
+
|
| 505 |
+
with hub_online_once(model_id):
|
| 506 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 507 |
+
config = config_cls(
|
| 508 |
+
base_model_name_or_path=model_id,
|
| 509 |
+
**config_kwargs,
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
model = get_peft_model(model, config)
|
| 513 |
+
model = model.to(self.torch_device)
|
| 514 |
+
|
| 515 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 516 |
+
|
| 517 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 518 |
+
|
| 519 |
+
model.eval()
|
| 520 |
+
|
| 521 |
+
# This should work
|
| 522 |
+
logits_unmerged = model(**dummy_input)[0]
|
| 523 |
+
|
| 524 |
+
model = model.merge_and_unload()
|
| 525 |
+
logits_merged = model(**dummy_input)[0]
|
| 526 |
+
|
| 527 |
+
assert torch.allclose(logits_unmerged, logits_merged, atol=1e-3, rtol=1e-3)
|
| 528 |
+
|
| 529 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 530 |
+
config = config_cls(
|
| 531 |
+
base_model_name_or_path=model_id,
|
| 532 |
+
**config_kwargs,
|
| 533 |
+
)
|
| 534 |
+
model = get_peft_model(model, config)
|
| 535 |
+
model = model.to(self.torch_device)
|
| 536 |
+
|
| 537 |
+
for name, module in model.named_parameters():
|
| 538 |
+
if model.prefix in name:
|
| 539 |
+
module.data[0] = torch.nan
|
| 540 |
+
|
| 541 |
+
with pytest.raises(
|
| 542 |
+
ValueError, match="NaNs detected in the merged weights. The adapter default seems to be broken"
|
| 543 |
+
):
|
| 544 |
+
model = model.merge_and_unload(safe_merge=True)
|
| 545 |
+
|
| 546 |
+
for name, module in model.named_parameters():
|
| 547 |
+
if (
|
| 548 |
+
"lora_A" in name
|
| 549 |
+
or "ia3" in name
|
| 550 |
+
or "lora_E" in name
|
| 551 |
+
or "lora_B" in name
|
| 552 |
+
or "vera_lambda" in name
|
| 553 |
+
or "fourierft_spectrum" in name
|
| 554 |
+
):
|
| 555 |
+
module.data[0] = torch.inf
|
| 556 |
+
|
| 557 |
+
with pytest.raises(
|
| 558 |
+
ValueError, match="NaNs detected in the merged weights. The adapter default seems to be broken"
|
| 559 |
+
):
|
| 560 |
+
model = model.merge_and_unload(safe_merge=True)
|
| 561 |
+
|
| 562 |
+
def _test_merge_layers(self, model_id, config_cls, config_kwargs):
|
| 563 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 564 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 565 |
+
|
| 566 |
+
with hub_online_once(model_id):
|
| 567 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 568 |
+
config = config_cls(
|
| 569 |
+
base_model_name_or_path=model_id,
|
| 570 |
+
**config_kwargs,
|
| 571 |
+
)
|
| 572 |
+
|
| 573 |
+
model = get_peft_model(model, config)
|
| 574 |
+
model = model.to(self.torch_device)
|
| 575 |
+
|
| 576 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 577 |
+
|
| 578 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 579 |
+
model.eval()
|
| 580 |
+
logits = model(**dummy_input)[0]
|
| 581 |
+
|
| 582 |
+
model.merge_adapter()
|
| 583 |
+
logits_merged = model(**dummy_input)[0]
|
| 584 |
+
model.unmerge_adapter()
|
| 585 |
+
logits_unmerged = model(**dummy_input)[0]
|
| 586 |
+
|
| 587 |
+
model = model.merge_and_unload()
|
| 588 |
+
|
| 589 |
+
# check that PEFT layers are completely removed
|
| 590 |
+
assert not any(isinstance(module, BaseTunerLayer) for module in model.modules())
|
| 591 |
+
assert not hasattr(model, "peft_config")
|
| 592 |
+
logits_merged_unloaded = model(**dummy_input)[0]
|
| 593 |
+
|
| 594 |
+
conv_ids = ["Conv2d", "Conv3d", "Conv2d2"]
|
| 595 |
+
is_decoder = getattr(getattr(model, "config", None), "is_decoder", False)
|
| 596 |
+
atol, rtol = 1e-4, 1e-4
|
| 597 |
+
if self.torch_device in ["mlu"]:
|
| 598 |
+
atol, rtol = 1e-3, 1e-3 # MLU
|
| 599 |
+
if model_id == "trl-internal-testing/tiny-GptOssForCausalLM":
|
| 600 |
+
# this tolerance issue with the target_parameters test only occurrs on CI with transformers v5
|
| 601 |
+
atol, rtol = 1e-3, 1e-3
|
| 602 |
+
if config.peft_type in ("ADALORA", "OFT"):
|
| 603 |
+
# these methods require a bit higher tolerance
|
| 604 |
+
atol, rtol = 1e-2, 1e-2
|
| 605 |
+
if (config.peft_type in {"IA3", "LORA", "OFT"}) and (model_id in conv_ids):
|
| 606 |
+
# for some reason, the Conv introduces a larger error
|
| 607 |
+
atol, rtol = 0.3, 0.01
|
| 608 |
+
if (config.peft_type == "OFT") and not is_decoder:
|
| 609 |
+
atol, rtol = 0.3, 0.01
|
| 610 |
+
if model_id == "trl-internal-testing/tiny-Llama4ForCausalLM":
|
| 611 |
+
# also getting larger errors here, not exactly sure why
|
| 612 |
+
atol, rtol = 0.3, 0.01
|
| 613 |
+
assert torch.allclose(logits, logits_merged, atol=atol, rtol=rtol)
|
| 614 |
+
assert torch.allclose(logits, logits_unmerged, atol=atol, rtol=rtol)
|
| 615 |
+
assert torch.allclose(logits, logits_merged_unloaded, atol=atol, rtol=rtol)
|
| 616 |
+
|
| 617 |
+
# For this test to work, weights should not be initialized to identity transform (e.g.
|
| 618 |
+
# init_lora_weights should be False).
|
| 619 |
+
transformers_model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 620 |
+
logits_transformers = transformers_model(**dummy_input)[0]
|
| 621 |
+
assert not torch.allclose(logits_merged, logits_transformers, atol=1e-10, rtol=1e-10)
|
| 622 |
+
|
| 623 |
+
# test that the logits are identical after a save-load-roundtrip
|
| 624 |
+
if hasattr(model, "save_pretrained"):
|
| 625 |
+
# model is a transformers model
|
| 626 |
+
tmp_dirname = tempfile.mkdtemp()
|
| 627 |
+
# note: not using the context manager here because it fails on Windows CI for some reason
|
| 628 |
+
try:
|
| 629 |
+
model.save_pretrained(tmp_dirname)
|
| 630 |
+
model_from_pretrained = self.transformers_class.from_pretrained(tmp_dirname).to(self.torch_device)
|
| 631 |
+
finally:
|
| 632 |
+
try:
|
| 633 |
+
shutil.rmtree(tmp_dirname)
|
| 634 |
+
except PermissionError:
|
| 635 |
+
# windows error
|
| 636 |
+
pass
|
| 637 |
+
else:
|
| 638 |
+
# model is not a transformers model
|
| 639 |
+
model_from_pretrained = pickle.loads(pickle.dumps(model))
|
| 640 |
+
|
| 641 |
+
logits_merged_from_pretrained = model_from_pretrained(**dummy_input)[0]
|
| 642 |
+
assert torch.allclose(logits_merged, logits_merged_from_pretrained, atol=atol, rtol=rtol)
|
| 643 |
+
|
| 644 |
+
def _test_merge_layers_multi(self, model_id, config_cls, config_kwargs):
|
| 645 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 646 |
+
if issubclass(config_cls, AdaLoraConfig):
|
| 647 |
+
# AdaLora does not support adding more than 1 adapter
|
| 648 |
+
pytest.skip("AdaLoRA does not support multiple adapters, skipping this test.")
|
| 649 |
+
if config_kwargs.get("trainable_token_indices", None) is not None:
|
| 650 |
+
pytest.skip(
|
| 651 |
+
"Merging two adapters with trainable tokens is tested elsewhere since adapters with "
|
| 652 |
+
"the same token indices cannot be merged."
|
| 653 |
+
)
|
| 654 |
+
|
| 655 |
+
config = config_cls(
|
| 656 |
+
base_model_name_or_path=model_id,
|
| 657 |
+
**config_kwargs,
|
| 658 |
+
)
|
| 659 |
+
if config_cls == VBLoRAConfig:
|
| 660 |
+
# for VBLoRA, increase this value or else the two adapters are too similar
|
| 661 |
+
config.init_logits_std *= 100
|
| 662 |
+
config.init_vector_bank_bound *= 100
|
| 663 |
+
|
| 664 |
+
with hub_online_once(model_id):
|
| 665 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 666 |
+
torch.manual_seed(0)
|
| 667 |
+
model = get_peft_model(model, config)
|
| 668 |
+
model = model.to(self.torch_device)
|
| 669 |
+
|
| 670 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 671 |
+
model.eval()
|
| 672 |
+
|
| 673 |
+
with torch.inference_mode():
|
| 674 |
+
logits_adapter_1 = model(**dummy_input)[0]
|
| 675 |
+
|
| 676 |
+
torch.manual_seed(1)
|
| 677 |
+
model.add_adapter("adapter-2", config)
|
| 678 |
+
model.set_adapter("adapter-2")
|
| 679 |
+
model.eval()
|
| 680 |
+
|
| 681 |
+
# sanity check: each adapter layer with a 'default' adapter should also have 'adapter-2'
|
| 682 |
+
containers = (torch.nn.ModuleDict, torch.nn.ParameterDict, BufferDict)
|
| 683 |
+
num_default = len([m for m in model.modules() if isinstance(m, containers) and "default" in m])
|
| 684 |
+
num_adapter2 = len([m for m in model.modules() if isinstance(m, containers) and "adapter-2" in m])
|
| 685 |
+
assert num_default > 0
|
| 686 |
+
assert num_default == num_adapter2
|
| 687 |
+
|
| 688 |
+
with torch.inference_mode():
|
| 689 |
+
logits_adapter_2 = model(**dummy_input)[0]
|
| 690 |
+
|
| 691 |
+
assert not torch.allclose(logits_adapter_1, logits_adapter_2, atol=1e-3, rtol=1e-3)
|
| 692 |
+
|
| 693 |
+
model.set_adapter("default")
|
| 694 |
+
|
| 695 |
+
with torch.inference_mode():
|
| 696 |
+
logits_adapter_1_after_set = model(**dummy_input)[0]
|
| 697 |
+
|
| 698 |
+
assert torch.allclose(logits_adapter_1_after_set, logits_adapter_1, atol=1e-3, rtol=1e-3)
|
| 699 |
+
|
| 700 |
+
model_copy = copy.deepcopy(model)
|
| 701 |
+
model_copy_2 = copy.deepcopy(model)
|
| 702 |
+
model_merged_all = model.merge_and_unload(adapter_names=["adapter-2", "default"])
|
| 703 |
+
|
| 704 |
+
with torch.inference_mode():
|
| 705 |
+
logits_merged_all = model_merged_all(**dummy_input)[0]
|
| 706 |
+
|
| 707 |
+
assert not torch.allclose(logits_merged_all, logits_adapter_2, atol=1e-3, rtol=1e-3)
|
| 708 |
+
assert not torch.allclose(logits_merged_all, logits_adapter_1, atol=1e-3, rtol=1e-3)
|
| 709 |
+
|
| 710 |
+
model_merged_adapter_2 = model_copy.merge_and_unload(adapter_names=["adapter-2"])
|
| 711 |
+
|
| 712 |
+
with torch.inference_mode():
|
| 713 |
+
logits_merged_adapter_2 = model_merged_adapter_2(**dummy_input)[0]
|
| 714 |
+
|
| 715 |
+
assert torch.allclose(logits_merged_adapter_2, logits_adapter_2, atol=1e-3, rtol=1e-3)
|
| 716 |
+
|
| 717 |
+
model_merged_adapter_default = model_copy_2.merge_and_unload(adapter_names=["default"])
|
| 718 |
+
|
| 719 |
+
with torch.inference_mode():
|
| 720 |
+
logits_merged_adapter_default = model_merged_adapter_default(**dummy_input)[0]
|
| 721 |
+
|
| 722 |
+
assert torch.allclose(logits_merged_adapter_default, logits_adapter_1, atol=1e-3, rtol=1e-3)
|
| 723 |
+
|
| 724 |
+
def _test_merge_layers_is_idempotent(self, model_id, config_cls, config_kwargs):
|
| 725 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 726 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 727 |
+
|
| 728 |
+
with hub_online_once(model_id):
|
| 729 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 730 |
+
config = config_cls(
|
| 731 |
+
base_model_name_or_path=model_id,
|
| 732 |
+
**config_kwargs,
|
| 733 |
+
)
|
| 734 |
+
model = get_peft_model(model, config)
|
| 735 |
+
model = model.to(self.torch_device)
|
| 736 |
+
model.eval()
|
| 737 |
+
torch.manual_seed(0)
|
| 738 |
+
model.merge_adapter()
|
| 739 |
+
logits_0 = model(**self.prepare_inputs_for_testing())[0]
|
| 740 |
+
|
| 741 |
+
# merging again should not change anything
|
| 742 |
+
# also check warning:
|
| 743 |
+
with pytest.warns(UserWarning, match="All adapters are already merged, nothing to do"):
|
| 744 |
+
model.merge_adapter()
|
| 745 |
+
logits_1 = model(**self.prepare_inputs_for_testing())[0]
|
| 746 |
+
|
| 747 |
+
assert torch.allclose(logits_0, logits_1, atol=1e-6, rtol=1e-6)
|
| 748 |
+
|
| 749 |
+
def _test_safe_merge(self, model_id, config_cls, config_kwargs):
|
| 750 |
+
_skip_if_merging_not_supported(model_id, config_cls, config_kwargs)
|
| 751 |
+
torch.manual_seed(0)
|
| 752 |
+
|
| 753 |
+
with hub_online_once(model_id):
|
| 754 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 755 |
+
config = config_cls(
|
| 756 |
+
base_model_name_or_path=model_id,
|
| 757 |
+
**config_kwargs,
|
| 758 |
+
)
|
| 759 |
+
model = model.to(self.torch_device).eval()
|
| 760 |
+
|
| 761 |
+
inputs = self.prepare_inputs_for_testing()
|
| 762 |
+
logits_base = model(**inputs)[0]
|
| 763 |
+
|
| 764 |
+
model = get_peft_model(model, config).eval()
|
| 765 |
+
logits_peft = model(**inputs)[0]
|
| 766 |
+
|
| 767 |
+
atol, rtol = 1e-6, 1e-6 # default
|
| 768 |
+
# Initializing with LN tuning cannot be configured to change the outputs (unlike init_lora_weights=False)
|
| 769 |
+
if not issubclass(config_cls, LNTuningConfig):
|
| 770 |
+
# sanity check that the logits are different
|
| 771 |
+
assert not torch.allclose(logits_base, logits_peft, atol=atol, rtol=rtol)
|
| 772 |
+
|
| 773 |
+
model_unloaded = model.merge_and_unload(safe_merge=True)
|
| 774 |
+
logits_unloaded = model_unloaded(**inputs)[0]
|
| 775 |
+
|
| 776 |
+
if self.torch_device in ["mlu"]:
|
| 777 |
+
atol, rtol = 1e-3, 1e-3 # MLU
|
| 778 |
+
|
| 779 |
+
conv_ids = ["Conv2d", "Conv3d", "Conv2d2"]
|
| 780 |
+
if issubclass(config_cls, (IA3Config, LoraConfig)) and model_id in conv_ids: # more instability with Conv
|
| 781 |
+
atol, rtol = 1e-3, 1e-3
|
| 782 |
+
elif issubclass(config_cls, PveraConfig):
|
| 783 |
+
atol, rtol = 1e-5, 1e-5
|
| 784 |
+
|
| 785 |
+
# check that the logits are the same after unloading
|
| 786 |
+
assert torch.allclose(logits_peft, logits_unloaded, atol=atol, rtol=rtol)
|
| 787 |
+
|
| 788 |
+
# Ensure that serializing with safetensors works, there was an error when weights were not contiguous
|
| 789 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 790 |
+
# serializing with torch.save works
|
| 791 |
+
torch.save(model_unloaded.state_dict(), os.path.join(tmp_dirname, "model.bin"))
|
| 792 |
+
|
| 793 |
+
# serializing with safetensors works
|
| 794 |
+
save_file(model_unloaded.state_dict(), os.path.join(tmp_dirname, "model.safetensors"))
|
| 795 |
+
|
| 796 |
+
def _test_mixed_adapter_batches(self, model_id, config_cls, config_kwargs):
|
| 797 |
+
# Test for mixing different adapters in a single batch by passing the adapter_names argument
|
| 798 |
+
if config_cls not in (LoraConfig, RoadConfig):
|
| 799 |
+
pytest.skip(f"Mixed adapter batches not supported for {config_cls}")
|
| 800 |
+
|
| 801 |
+
config = config_cls(
|
| 802 |
+
base_model_name_or_path=model_id,
|
| 803 |
+
**config_kwargs,
|
| 804 |
+
)
|
| 805 |
+
|
| 806 |
+
torch.manual_seed(0)
|
| 807 |
+
with hub_online_once(model_id):
|
| 808 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 809 |
+
model = get_peft_model(model, config, adapter_name="adapter0").eval()
|
| 810 |
+
model.add_adapter("adapter1", config)
|
| 811 |
+
model = model.to(self.torch_device).eval()
|
| 812 |
+
|
| 813 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs, adapter_name="adapter0")
|
| 814 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs, adapter_name="adapter1")
|
| 815 |
+
|
| 816 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 817 |
+
# ensure that we have at least 3 samples for this test
|
| 818 |
+
dummy_input = {k: torch.cat([v for _ in range(3)]) for k, v in dummy_input.items()}
|
| 819 |
+
with torch.inference_mode(), model.disable_adapter():
|
| 820 |
+
output_base = model(**dummy_input)[0]
|
| 821 |
+
logits_base = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 822 |
+
|
| 823 |
+
model.set_adapter("adapter0")
|
| 824 |
+
with torch.inference_mode():
|
| 825 |
+
output_adapter0 = model(**dummy_input)[0]
|
| 826 |
+
logits_adapter0 = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 827 |
+
|
| 828 |
+
model.set_adapter("adapter1")
|
| 829 |
+
with torch.inference_mode():
|
| 830 |
+
output_adapter1 = model(**dummy_input)[0]
|
| 831 |
+
logits_adapter1 = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 832 |
+
|
| 833 |
+
atol, rtol = 1e-4, 1e-4
|
| 834 |
+
# sanity check that there are enough outputs and that they are different
|
| 835 |
+
assert len(output_base) == len(output_adapter0) == len(output_adapter1) >= 3
|
| 836 |
+
assert len(logits_base) == len(logits_adapter0) == len(logits_adapter1) >= 3
|
| 837 |
+
assert not torch.allclose(output_base, output_adapter0, atol=atol, rtol=rtol)
|
| 838 |
+
assert not torch.allclose(output_base, output_adapter1, atol=atol, rtol=rtol)
|
| 839 |
+
assert not torch.allclose(output_adapter0, output_adapter1, atol=atol, rtol=rtol)
|
| 840 |
+
assert not torch.allclose(logits_base, logits_adapter0, atol=atol, rtol=rtol)
|
| 841 |
+
assert not torch.allclose(logits_base, logits_adapter1, atol=atol, rtol=rtol)
|
| 842 |
+
assert not torch.allclose(logits_adapter0, logits_adapter1, atol=atol, rtol=rtol)
|
| 843 |
+
|
| 844 |
+
# alternate between base model, adapter0, and adapter1
|
| 845 |
+
adapters = ["__base__", "adapter0", "adapter1"]
|
| 846 |
+
dummy_input["adapter_names"] = [adapters[i % 3] for i in (range(len(dummy_input["input_ids"])))]
|
| 847 |
+
with torch.inference_mode():
|
| 848 |
+
output_mixed = model(**dummy_input)[0]
|
| 849 |
+
logits_mixed = model.generate(**dummy_input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 850 |
+
|
| 851 |
+
assert torch.allclose(output_base[::3], output_mixed[::3], atol=atol, rtol=rtol)
|
| 852 |
+
assert torch.allclose(output_adapter0[1::3], output_mixed[1::3], atol=atol, rtol=rtol)
|
| 853 |
+
assert torch.allclose(output_adapter1[2::3], output_mixed[2::3], atol=atol, rtol=rtol)
|
| 854 |
+
assert torch.allclose(logits_base[::3], logits_mixed[::3], atol=atol, rtol=rtol)
|
| 855 |
+
assert torch.allclose(logits_adapter0[1::3], logits_mixed[1::3], atol=atol, rtol=rtol)
|
| 856 |
+
assert torch.allclose(logits_adapter1[2::3], logits_mixed[2::3], atol=atol, rtol=rtol)
|
| 857 |
+
|
| 858 |
+
def _test_generate_with_mixed_adapter_batches_and_beam_search(self, model_id, config_cls, config_kwargs):
|
| 859 |
+
# Test generating with beam search and with mixing different adapters in a single batch by passing the
|
| 860 |
+
# adapter_names argument. See #2283.
|
| 861 |
+
if config_cls not in (LoraConfig,):
|
| 862 |
+
# note: RoAD supports mixed adapter batches but not beam search
|
| 863 |
+
pytest.skip(f"Mixed adapter batches not supported for {config_cls}")
|
| 864 |
+
if config_kwargs.get("alora_invocation_tokens") is not None:
|
| 865 |
+
pytest.skip("Beam search not yet supported for aLoRA") # beam search not yet fully supported
|
| 866 |
+
if config_kwargs.get("trainable_token_indices", None) is not None:
|
| 867 |
+
# for some configurations this test will fail since the adapter values don't differ.
|
| 868 |
+
# this is probably a problem with the test setup and not with the implementation.
|
| 869 |
+
pytest.skip("Trainable token indices is not supported here (yet).")
|
| 870 |
+
|
| 871 |
+
config = config_cls(
|
| 872 |
+
base_model_name_or_path=model_id,
|
| 873 |
+
**config_kwargs,
|
| 874 |
+
)
|
| 875 |
+
|
| 876 |
+
torch.manual_seed(0)
|
| 877 |
+
with hub_online_once(model_id):
|
| 878 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 879 |
+
model = get_peft_model(model, config, adapter_name="adapter0").eval()
|
| 880 |
+
model.add_adapter("adapter1", config)
|
| 881 |
+
|
| 882 |
+
# In contrast to forward, for generate, it can sometimes happen that we get the same results as the base model
|
| 883 |
+
# even with LoRA applied because the impact of LoRA is not big enough. Therefore, use this "trick" to make LoRA
|
| 884 |
+
# stronger.
|
| 885 |
+
for name, param in model.named_parameters():
|
| 886 |
+
if model.base_model.prefix in name:
|
| 887 |
+
param.data.mul_(10.0)
|
| 888 |
+
|
| 889 |
+
model = model.to(self.torch_device).eval()
|
| 890 |
+
|
| 891 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 892 |
+
# ensure that we have at least 3 samples for this test
|
| 893 |
+
dummy_input = {k: torch.cat([v for _ in range(3)]) for k, v in dummy_input.items()}
|
| 894 |
+
gen_kwargs = {**dummy_input, "max_length": 20, "num_beams": 10, "early_stopping": True}
|
| 895 |
+
with torch.inference_mode(), model.disable_adapter():
|
| 896 |
+
gen_base = model.generate(**gen_kwargs)
|
| 897 |
+
|
| 898 |
+
model.set_adapter("adapter0")
|
| 899 |
+
with torch.inference_mode():
|
| 900 |
+
gen_adapter0 = model.generate(**gen_kwargs)
|
| 901 |
+
|
| 902 |
+
model.set_adapter("adapter1")
|
| 903 |
+
with torch.inference_mode():
|
| 904 |
+
gen_adapter1 = model.generate(**gen_kwargs)
|
| 905 |
+
|
| 906 |
+
def remove_padding(seq, pad_value):
|
| 907 |
+
lst = list(seq)
|
| 908 |
+
while lst and (lst[-1] == pad_value):
|
| 909 |
+
lst.pop()
|
| 910 |
+
return lst
|
| 911 |
+
|
| 912 |
+
def gens_are_same(gen0, gen1):
|
| 913 |
+
# Special function to compare generations. We cannot use torch.allclose it will raise an error when sequence
|
| 914 |
+
# lengths differ. Morevoer, we need to remove the padding from the sequences. This is because, even though
|
| 915 |
+
# normally identical sequences should have the same length, when we do mixed adapter batches, each sample
|
| 916 |
+
# will be padded to the longest sequence in that mixed batch, which can be different from the longest
|
| 917 |
+
# sequence without mixed adapter batches.
|
| 918 |
+
pad_value = model.config.eos_token_id
|
| 919 |
+
for sample0, sample1 in zip(gen0, gen1):
|
| 920 |
+
sample0 = remove_padding(sample0, pad_value)
|
| 921 |
+
sample1 = remove_padding(sample1, pad_value)
|
| 922 |
+
if (len(sample0) != len(sample1)) or (sample0 != sample1):
|
| 923 |
+
# at least one sample differs, the generations are not identical
|
| 924 |
+
return False
|
| 925 |
+
return True
|
| 926 |
+
|
| 927 |
+
# sanity check that there are enough outputs and that they are different
|
| 928 |
+
assert len(gen_base) == len(gen_adapter0) == len(gen_adapter1)
|
| 929 |
+
assert len(gen_adapter1) >= 3
|
| 930 |
+
assert not gens_are_same(gen_base, gen_adapter0)
|
| 931 |
+
assert not gens_are_same(gen_base, gen_adapter1)
|
| 932 |
+
assert not gens_are_same(gen_adapter0, gen_adapter1)
|
| 933 |
+
|
| 934 |
+
# alternate between base model, adapter0, and adapter1
|
| 935 |
+
adapters = ["__base__", "adapter0", "adapter1"]
|
| 936 |
+
gen_kwargs["adapter_names"] = [adapters[i % 3] for i in (range(len(dummy_input["input_ids"])))]
|
| 937 |
+
|
| 938 |
+
with torch.inference_mode():
|
| 939 |
+
gen_mixed = model.generate(**gen_kwargs)
|
| 940 |
+
|
| 941 |
+
assert gens_are_same(gen_base[::3], gen_mixed[::3])
|
| 942 |
+
assert gens_are_same(gen_adapter0[1::3], gen_mixed[1::3])
|
| 943 |
+
assert gens_are_same(gen_adapter1[2::3], gen_mixed[2::3])
|
| 944 |
+
|
| 945 |
+
def _test_generate(self, model_id, config_cls, config_kwargs):
|
| 946 |
+
with hub_online_once(model_id):
|
| 947 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 948 |
+
config = config_cls(
|
| 949 |
+
base_model_name_or_path=model_id,
|
| 950 |
+
**config_kwargs,
|
| 951 |
+
)
|
| 952 |
+
model = get_peft_model(model, config)
|
| 953 |
+
model = model.to(self.torch_device)
|
| 954 |
+
|
| 955 |
+
inputs = self.prepare_inputs_for_testing()
|
| 956 |
+
|
| 957 |
+
# check if `generate` works
|
| 958 |
+
_ = model.generate(**inputs)
|
| 959 |
+
|
| 960 |
+
def _test_generate_pos_args(self, model_id, config_cls, config_kwargs, raises_err: bool):
|
| 961 |
+
with hub_online_once(model_id):
|
| 962 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 963 |
+
config = config_cls(
|
| 964 |
+
base_model_name_or_path=model_id,
|
| 965 |
+
**config_kwargs,
|
| 966 |
+
)
|
| 967 |
+
model = get_peft_model(model, config)
|
| 968 |
+
model = model.to(self.torch_device)
|
| 969 |
+
|
| 970 |
+
inputs = self.prepare_inputs_for_testing()
|
| 971 |
+
if raises_err:
|
| 972 |
+
with pytest.raises(TypeError):
|
| 973 |
+
# check if `generate` raises an error if positional arguments are passed
|
| 974 |
+
_ = model.generate(inputs["input_ids"])
|
| 975 |
+
else:
|
| 976 |
+
# check if `generate` works if positional arguments are passed
|
| 977 |
+
_ = model.generate(inputs["input_ids"])
|
| 978 |
+
|
| 979 |
+
def _test_generate_half_prec(self, model_id, config_cls, config_kwargs):
|
| 980 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 981 |
+
|
| 982 |
+
with hub_online_once(model_id):
|
| 983 |
+
model = self.transformers_class.from_pretrained(model_id, dtype=torch.bfloat16)
|
| 984 |
+
config = config_cls(
|
| 985 |
+
base_model_name_or_path=model_id,
|
| 986 |
+
**config_kwargs,
|
| 987 |
+
)
|
| 988 |
+
model = get_peft_model(model, config)
|
| 989 |
+
model = model.to(self.torch_device)
|
| 990 |
+
|
| 991 |
+
input_ids = torch.LongTensor([[1, 1, 1], [2, 1, 2]]).to(self.torch_device)
|
| 992 |
+
attention_mask = torch.LongTensor([[1, 1, 1], [1, 0, 1]]).to(self.torch_device)
|
| 993 |
+
|
| 994 |
+
# check if `generate` works
|
| 995 |
+
_ = model.generate(input_ids=input_ids, attention_mask=attention_mask)
|
| 996 |
+
|
| 997 |
+
def _test_training(self, model_id, config_cls, config_kwargs):
|
| 998 |
+
if (config_cls == AdaLoraConfig) and ("roberta" in model_id.lower()):
|
| 999 |
+
# TODO: no gradients on the "dense" layer, other layers work, not sure why
|
| 1000 |
+
pytest.skip("AdaLora with RoBERTa does not work correctly")
|
| 1001 |
+
if (config_cls == PrefixTuningConfig) and ("bert" in model_id.lower()):
|
| 1002 |
+
# TODO: prefix tuning fails with roberta, deberta, etc., requires investigation
|
| 1003 |
+
pytest.skip("Prefix tuning fails with Bert* type models.")
|
| 1004 |
+
|
| 1005 |
+
with hub_online_once(model_id):
|
| 1006 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1007 |
+
config = config_cls(
|
| 1008 |
+
base_model_name_or_path=model_id,
|
| 1009 |
+
**config_kwargs,
|
| 1010 |
+
)
|
| 1011 |
+
model = get_peft_model(model, config)
|
| 1012 |
+
model = model.to(self.torch_device)
|
| 1013 |
+
|
| 1014 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1015 |
+
|
| 1016 |
+
# check if `training` works
|
| 1017 |
+
output = model(**inputs)[0]
|
| 1018 |
+
loss = output.sum()
|
| 1019 |
+
loss.backward()
|
| 1020 |
+
|
| 1021 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 1022 |
+
# we cannot reliably identify the trainable part of the prompt learning method, thus skipping this check
|
| 1023 |
+
return
|
| 1024 |
+
|
| 1025 |
+
for n, param in model.named_parameters():
|
| 1026 |
+
if (model.prefix in n) or ("modules_to_save" in n) or ("token_adapter.trainable_tokens" in n):
|
| 1027 |
+
assert param.grad is not None
|
| 1028 |
+
else:
|
| 1029 |
+
assert param.grad is None
|
| 1030 |
+
|
| 1031 |
+
def _test_inference_safetensors(self, model_id, config_cls, config_kwargs):
|
| 1032 |
+
if (config_cls == PrefixTuningConfig) and ("deberta" in model_id.lower()):
|
| 1033 |
+
# TODO: raises an error:
|
| 1034 |
+
# TypeError: DebertaModel.forward() got an unexpected keyword argument 'past_key_values'
|
| 1035 |
+
pytest.skip("DeBERTa with PrefixTuning does not work correctly")
|
| 1036 |
+
|
| 1037 |
+
config = config_cls(
|
| 1038 |
+
base_model_name_or_path=model_id,
|
| 1039 |
+
**config_kwargs,
|
| 1040 |
+
)
|
| 1041 |
+
with hub_online_once(model_id):
|
| 1042 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1043 |
+
model = get_peft_model(model, config)
|
| 1044 |
+
model = model.to(self.torch_device)
|
| 1045 |
+
|
| 1046 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1047 |
+
|
| 1048 |
+
# check if `training` works
|
| 1049 |
+
output = model(**inputs)[0]
|
| 1050 |
+
logits = output[0]
|
| 1051 |
+
|
| 1052 |
+
loss = output.sum()
|
| 1053 |
+
loss.backward()
|
| 1054 |
+
|
| 1055 |
+
# set to eval mode, since things like dropout can affect the output otherwise
|
| 1056 |
+
model.eval()
|
| 1057 |
+
logits = model(**inputs)[0][0]
|
| 1058 |
+
|
| 1059 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1060 |
+
model.save_pretrained(tmp_dirname, safe_serialization=True)
|
| 1061 |
+
assert "adapter_model.safetensors" in os.listdir(tmp_dirname)
|
| 1062 |
+
assert "adapter_model.bin" not in os.listdir(tmp_dirname)
|
| 1063 |
+
|
| 1064 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 1065 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname).to(
|
| 1066 |
+
self.torch_device
|
| 1067 |
+
)
|
| 1068 |
+
|
| 1069 |
+
logits_from_pretrained = model_from_pretrained(**inputs)[0][0]
|
| 1070 |
+
assert torch.allclose(logits, logits_from_pretrained, atol=1e-4, rtol=1e-4)
|
| 1071 |
+
|
| 1072 |
+
def _test_training_layer_indexing(self, model_id, config_cls, config_kwargs):
|
| 1073 |
+
if config_cls in (VBLoRAConfig, VeraConfig):
|
| 1074 |
+
# TODO investigate why these two are flaky
|
| 1075 |
+
# pytest tests/test_decoder_models.py tests/test_feature_extraction_models.py -k "layer_indexing and (vera
|
| 1076 |
+
# or vblora)"
|
| 1077 |
+
pytest.skip("VBLoRA and VeRA are flaky with layer indexing, possibly because of shared weights.")
|
| 1078 |
+
try:
|
| 1079 |
+
config = config_cls(
|
| 1080 |
+
base_model_name_or_path=model_id,
|
| 1081 |
+
layers_to_transform=[0],
|
| 1082 |
+
**config_kwargs,
|
| 1083 |
+
)
|
| 1084 |
+
except TypeError:
|
| 1085 |
+
pytest.skip("This PEFT method does not support layers_to_transform, skipping it.")
|
| 1086 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 1087 |
+
|
| 1088 |
+
with hub_online_once(model_id):
|
| 1089 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1090 |
+
model = get_peft_model(model, config)
|
| 1091 |
+
model = model.to(self.torch_device)
|
| 1092 |
+
|
| 1093 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1094 |
+
|
| 1095 |
+
# check if `training` works
|
| 1096 |
+
output = model(**inputs)[0]
|
| 1097 |
+
|
| 1098 |
+
loss = output.sum()
|
| 1099 |
+
loss.backward()
|
| 1100 |
+
|
| 1101 |
+
has_trainable_tokens = config_kwargs.get("trainable_token_indices", None) is not None
|
| 1102 |
+
nb_trainable = 0
|
| 1103 |
+
|
| 1104 |
+
for n, param in model.named_parameters():
|
| 1105 |
+
if model.prefix in n or (has_trainable_tokens and "trainable_tokens" in n):
|
| 1106 |
+
assert param.grad is not None
|
| 1107 |
+
nb_trainable += 1
|
| 1108 |
+
else:
|
| 1109 |
+
assert param.grad is None
|
| 1110 |
+
|
| 1111 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1112 |
+
model.eval()
|
| 1113 |
+
logits = model(**inputs)[0][0]
|
| 1114 |
+
|
| 1115 |
+
model.save_pretrained(tmp_dirname)
|
| 1116 |
+
|
| 1117 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 1118 |
+
model_from_pretrained = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname).to(
|
| 1119 |
+
self.torch_device
|
| 1120 |
+
)
|
| 1121 |
+
|
| 1122 |
+
logits_from_pretrained = model_from_pretrained(**inputs)[0][0]
|
| 1123 |
+
atol, rtol = 1e-4, 1e-4
|
| 1124 |
+
assert torch.allclose(logits, logits_from_pretrained, atol=atol, rtol=rtol)
|
| 1125 |
+
|
| 1126 |
+
# check the nb of trainable params again but without layers_to_transform
|
| 1127 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1128 |
+
config = config_cls(
|
| 1129 |
+
base_model_name_or_path=model_id,
|
| 1130 |
+
**config_kwargs,
|
| 1131 |
+
)
|
| 1132 |
+
model = get_peft_model(model, config)
|
| 1133 |
+
nb_trainable_all = 0
|
| 1134 |
+
|
| 1135 |
+
for n, param in model.named_parameters():
|
| 1136 |
+
if model.prefix in n or (has_trainable_tokens and "trainable_tokens" in n):
|
| 1137 |
+
nb_trainable_all += 1
|
| 1138 |
+
|
| 1139 |
+
mod_list = next((m for m in model.modules() if isinstance(m, torch.nn.ModuleList)), None)
|
| 1140 |
+
if mod_list and len(mod_list) == 1:
|
| 1141 |
+
# there is only a single layer
|
| 1142 |
+
assert nb_trainable == nb_trainable_all
|
| 1143 |
+
else:
|
| 1144 |
+
# more than 1 layer, i.e. setting layers_to_transform=[0] should target fewer layers
|
| 1145 |
+
assert nb_trainable < nb_trainable_all
|
| 1146 |
+
|
| 1147 |
+
def _test_training_gradient_checkpointing(self, model_id, config_cls, config_kwargs, use_reentrant=True):
|
| 1148 |
+
# Note that certain configurations, such as activated lora with 'alora_invocation_tokens': [1000], do not
|
| 1149 |
+
# generate gradients since the adapter is never activated so this will be a no-op for this test. It is still
|
| 1150 |
+
# a valid test but it might be confusing to see a test pass if it is not supposed to.
|
| 1151 |
+
|
| 1152 |
+
if config_cls == PrefixTuningConfig:
|
| 1153 |
+
pytest.skip("Prefix Tuning does not support gradient checkpointing, skipping this test.")
|
| 1154 |
+
if (config_cls == AdaLoraConfig) and ("roberta" in model_id.lower()):
|
| 1155 |
+
# TODO: no gradients on the "dense" layer, other layers work, not sure why
|
| 1156 |
+
pytest.skip("AdaLora with RoBERTa does not work correctly")
|
| 1157 |
+
|
| 1158 |
+
if not is_transformers_ge_v5:
|
| 1159 |
+
# TODO: remove once transformers < 5.0 no longer supported
|
| 1160 |
+
if "gptbigcode" in model_id.lower():
|
| 1161 |
+
pytest.skip("GPTBigCode doesn't implement gradient checkpointing correctly in transformers < 5.0.")
|
| 1162 |
+
if "bart" in model_id.lower():
|
| 1163 |
+
pytest.skip(
|
| 1164 |
+
"Bart in transformers < 5.0 doesn't handle input sharing well enough. See transformers#41821"
|
| 1165 |
+
)
|
| 1166 |
+
|
| 1167 |
+
with hub_online_once(model_id):
|
| 1168 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1169 |
+
|
| 1170 |
+
if not getattr(model, "supports_gradient_checkpointing", False):
|
| 1171 |
+
pytest.skip(f"Model {model_id} does not support gradient checkpointing")
|
| 1172 |
+
|
| 1173 |
+
# Disable lora_dropout and friends to remove non-determinism in gradient creation
|
| 1174 |
+
for key in list(config_kwargs.keys()):
|
| 1175 |
+
if key.endswith("dropout"):
|
| 1176 |
+
del config_kwargs[key]
|
| 1177 |
+
|
| 1178 |
+
config = config_cls(
|
| 1179 |
+
base_model_name_or_path=model_id,
|
| 1180 |
+
**config_kwargs,
|
| 1181 |
+
)
|
| 1182 |
+
model = get_peft_model(model, config)
|
| 1183 |
+
model = model.to(self.torch_device)
|
| 1184 |
+
params = [(n, p) for n, p in model.named_parameters() if p.requires_grad]
|
| 1185 |
+
|
| 1186 |
+
# if we don't set this, gradient checkpointing is not activated.
|
| 1187 |
+
model.train(True)
|
| 1188 |
+
|
| 1189 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1190 |
+
|
| 1191 |
+
# invocation to get the reference non-zero grads that are supposed to exist without gradient checkpointing;
|
| 1192 |
+
# note we're squaring the output for bigger gradients
|
| 1193 |
+
output = model(**inputs)[0] ** 2
|
| 1194 |
+
|
| 1195 |
+
loss = output.sum()
|
| 1196 |
+
loss.backward()
|
| 1197 |
+
|
| 1198 |
+
non_zero_grad_params_normal = {n for n, p in params if p.grad.abs().sum() > 0}
|
| 1199 |
+
|
| 1200 |
+
for name, param in params:
|
| 1201 |
+
param.grad = None
|
| 1202 |
+
|
| 1203 |
+
# invocation with gradient checkpointing for comparison
|
| 1204 |
+
model.prepare_model_for_gradient_checkpointing(model)
|
| 1205 |
+
model.gradient_checkpointing_enable({"use_reentrant": use_reentrant})
|
| 1206 |
+
|
| 1207 |
+
output = model(**inputs)[0] ** 2
|
| 1208 |
+
|
| 1209 |
+
loss = output.sum()
|
| 1210 |
+
loss.backward()
|
| 1211 |
+
|
| 1212 |
+
non_zero_grad_params_checkpointing = {n for n, p in params if p.grad.abs().sum() > 0}
|
| 1213 |
+
assert non_zero_grad_params_normal == non_zero_grad_params_checkpointing
|
| 1214 |
+
|
| 1215 |
+
for n, param in model.named_parameters():
|
| 1216 |
+
if "prompt_encoder." in n: # prompt tuning methods
|
| 1217 |
+
if not issubclass(config_cls, CPTConfig):
|
| 1218 |
+
assert param.grad is not None
|
| 1219 |
+
elif (
|
| 1220 |
+
"delta_embedding" in n
|
| 1221 |
+
): # delta_embedding is the embedding that should be updated with grads in CPT
|
| 1222 |
+
assert param.grad is not None
|
| 1223 |
+
elif hasattr(model, "prefix") and (model.prefix in n): # non-prompt tuning methods
|
| 1224 |
+
assert param.grad is not None
|
| 1225 |
+
elif "trainable_tokens_" in n: # trainable tokens layer
|
| 1226 |
+
assert param.grad is not None
|
| 1227 |
+
else:
|
| 1228 |
+
assert param.grad is None
|
| 1229 |
+
|
| 1230 |
+
def _test_peft_model_device_map(self, model_id, config_cls, config_kwargs):
|
| 1231 |
+
_skip_if_conv1d_not_supported(model_id, config_cls, config_kwargs)
|
| 1232 |
+
config = config_cls(
|
| 1233 |
+
base_model_name_or_path=model_id,
|
| 1234 |
+
**config_kwargs,
|
| 1235 |
+
)
|
| 1236 |
+
|
| 1237 |
+
with hub_online_once(model_id):
|
| 1238 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1239 |
+
|
| 1240 |
+
model = get_peft_model(model, config)
|
| 1241 |
+
model = model.to(self.torch_device)
|
| 1242 |
+
|
| 1243 |
+
with tempfile.TemporaryDirectory() as tmp_dirname:
|
| 1244 |
+
model.save_pretrained(tmp_dirname)
|
| 1245 |
+
|
| 1246 |
+
model_from_pretrained = self.transformers_class.from_pretrained(model_id)
|
| 1247 |
+
_ = PeftModel.from_pretrained(model_from_pretrained, tmp_dirname, device_map={"": "cpu"}).to(
|
| 1248 |
+
self.torch_device
|
| 1249 |
+
)
|
| 1250 |
+
|
| 1251 |
+
def _test_training_prompt_learning_tasks(self, model_id, config_cls, config_kwargs):
|
| 1252 |
+
if not issubclass(config_cls, PromptLearningConfig):
|
| 1253 |
+
pytest.skip(f"Test not applicable for {config_cls}")
|
| 1254 |
+
|
| 1255 |
+
with hub_online_once(model_id):
|
| 1256 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1257 |
+
config = config_cls(
|
| 1258 |
+
base_model_name_or_path=model_id,
|
| 1259 |
+
**config_kwargs,
|
| 1260 |
+
)
|
| 1261 |
+
model = get_peft_model(model, config)
|
| 1262 |
+
model = model.to(self.torch_device)
|
| 1263 |
+
|
| 1264 |
+
inputs = self.prepare_inputs_for_testing()
|
| 1265 |
+
|
| 1266 |
+
# check if `training` works
|
| 1267 |
+
output = model(**inputs)[0]
|
| 1268 |
+
loss = output.sum()
|
| 1269 |
+
loss.backward()
|
| 1270 |
+
|
| 1271 |
+
if issubclass(config_cls, CPTConfig):
|
| 1272 |
+
parameters = []
|
| 1273 |
+
for name, param in model.prompt_encoder.named_parameters():
|
| 1274 |
+
if name != "default.embedding.weight":
|
| 1275 |
+
parameters.append(param)
|
| 1276 |
+
else:
|
| 1277 |
+
parameters = model.prompt_encoder.parameters()
|
| 1278 |
+
|
| 1279 |
+
# check that prompt encoder has grads
|
| 1280 |
+
for param in parameters:
|
| 1281 |
+
assert param.grad is not None
|
| 1282 |
+
|
| 1283 |
+
def _test_delete_adapter(self, model_id, config_cls, config_kwargs):
|
| 1284 |
+
_skip_if_deleting_adapter_not_supported(config_cls, config_kwargs)
|
| 1285 |
+
if config_cls == AdaLoraConfig:
|
| 1286 |
+
pytest.skip("AdaLoRA does not support multiple adapters")
|
| 1287 |
+
|
| 1288 |
+
config = config_cls(
|
| 1289 |
+
base_model_name_or_path=model_id,
|
| 1290 |
+
**config_kwargs,
|
| 1291 |
+
)
|
| 1292 |
+
|
| 1293 |
+
with hub_online_once(model_id):
|
| 1294 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1295 |
+
adapter_to_delete = "delete_me"
|
| 1296 |
+
model = get_peft_model(model, config)
|
| 1297 |
+
model.add_adapter(adapter_to_delete, config)
|
| 1298 |
+
model.set_adapter(adapter_to_delete)
|
| 1299 |
+
model = model.to(self.torch_device)
|
| 1300 |
+
model.delete_adapter(adapter_to_delete)
|
| 1301 |
+
assert adapter_to_delete not in model.peft_config
|
| 1302 |
+
assert model.active_adapters == ["default"]
|
| 1303 |
+
|
| 1304 |
+
key_list = [key for key, _ in model.named_modules()]
|
| 1305 |
+
for key in key_list:
|
| 1306 |
+
_, target, _ = _get_submodules(model, key)
|
| 1307 |
+
attributes_to_check = getattr(target, "adapter_layer_names", []) + getattr(
|
| 1308 |
+
target, "other_param_names", []
|
| 1309 |
+
)
|
| 1310 |
+
for attr in attributes_to_check:
|
| 1311 |
+
assert adapter_to_delete not in attrgetter(attr)(target)
|
| 1312 |
+
|
| 1313 |
+
# check auxiliary modules
|
| 1314 |
+
for module in model.modules():
|
| 1315 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1316 |
+
assert adapter_to_delete not in module._adapters
|
| 1317 |
+
assert module.active_adapters == ["default"]
|
| 1318 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1319 |
+
assert adapter_to_delete not in module.modules_to_save
|
| 1320 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1321 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_delta
|
| 1322 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_original
|
| 1323 |
+
|
| 1324 |
+
# check that we can also delete the last remaining adapter
|
| 1325 |
+
model.delete_adapter("default")
|
| 1326 |
+
assert "default" not in model.peft_config
|
| 1327 |
+
assert model.active_adapters == []
|
| 1328 |
+
|
| 1329 |
+
for module in model.modules():
|
| 1330 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1331 |
+
assert "default" not in module._adapters
|
| 1332 |
+
assert module.active_adapters == []
|
| 1333 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1334 |
+
assert "default" not in module.modules_to_save
|
| 1335 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1336 |
+
assert "default" not in module.token_adapter.trainable_tokens_delta
|
| 1337 |
+
assert "default" not in module.token_adapter.trainable_tokens_original
|
| 1338 |
+
|
| 1339 |
+
input = self.prepare_inputs_for_testing()
|
| 1340 |
+
# note: we cannot call model(**input) because PeftModel always expects there to be at least one adapter
|
| 1341 |
+
model.base_model(**input) # should not raise an error
|
| 1342 |
+
|
| 1343 |
+
def _test_delete_inactive_adapter(self, model_id, config_cls, config_kwargs):
|
| 1344 |
+
if config_cls == AdaLoraConfig:
|
| 1345 |
+
pytest.skip("AdaLoRA does not support multiple adapters")
|
| 1346 |
+
_skip_if_deleting_adapter_not_supported(config_cls, config_kwargs)
|
| 1347 |
+
|
| 1348 |
+
config = config_cls(
|
| 1349 |
+
base_model_name_or_path=model_id,
|
| 1350 |
+
**config_kwargs,
|
| 1351 |
+
)
|
| 1352 |
+
|
| 1353 |
+
with hub_online_once(model_id):
|
| 1354 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1355 |
+
adapter_to_delete = "delete_me"
|
| 1356 |
+
model = get_peft_model(model, config)
|
| 1357 |
+
model.add_adapter(adapter_to_delete, config)
|
| 1358 |
+
# "delete_me" is added but not activated
|
| 1359 |
+
model = model.to(self.torch_device)
|
| 1360 |
+
model.delete_adapter(adapter_to_delete)
|
| 1361 |
+
assert adapter_to_delete not in model.peft_config
|
| 1362 |
+
assert model.active_adapters == ["default"]
|
| 1363 |
+
|
| 1364 |
+
key_list = [key for key, _ in model.named_modules()]
|
| 1365 |
+
for key in key_list:
|
| 1366 |
+
_, target, _ = _get_submodules(model, key)
|
| 1367 |
+
attributes_to_check = getattr(target, "adapter_layer_names", []) + getattr(
|
| 1368 |
+
target, "other_param_names", []
|
| 1369 |
+
)
|
| 1370 |
+
for attr in attributes_to_check:
|
| 1371 |
+
assert adapter_to_delete not in attrgetter(attr)(target)
|
| 1372 |
+
|
| 1373 |
+
# check auxiliary modules
|
| 1374 |
+
for module in model.modules():
|
| 1375 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1376 |
+
assert adapter_to_delete not in module._adapters
|
| 1377 |
+
assert module.active_adapters == ["default"]
|
| 1378 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1379 |
+
assert adapter_to_delete not in module.modules_to_save
|
| 1380 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1381 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_delta
|
| 1382 |
+
assert adapter_to_delete not in module.token_adapter.trainable_tokens_original
|
| 1383 |
+
|
| 1384 |
+
# check that we can also delete the last remaining adapter
|
| 1385 |
+
model.delete_adapter("default")
|
| 1386 |
+
assert "default" not in model.peft_config
|
| 1387 |
+
assert model.active_adapters == []
|
| 1388 |
+
|
| 1389 |
+
for module in model.modules():
|
| 1390 |
+
if isinstance(module, AuxiliaryTrainingWrapper):
|
| 1391 |
+
assert "default" not in module._adapters
|
| 1392 |
+
assert module.active_adapters == []
|
| 1393 |
+
if isinstance(module, ModulesToSaveWrapper):
|
| 1394 |
+
assert "default" not in module.modules_to_save
|
| 1395 |
+
elif isinstance(module, TrainableTokensWrapper):
|
| 1396 |
+
assert "default" not in module.token_adapter.trainable_tokens_delta
|
| 1397 |
+
assert "default" not in module.token_adapter.trainable_tokens_original
|
| 1398 |
+
|
| 1399 |
+
input = self.prepare_inputs_for_testing()
|
| 1400 |
+
# note: we cannot call model(**input) because PeftModel always expects there to be at least one adapter
|
| 1401 |
+
model.base_model(**input) # should not raise an error
|
| 1402 |
+
|
| 1403 |
+
def _test_delete_unknown_adapter_raises(self, model_id, config_cls, config_kwargs):
|
| 1404 |
+
# Check that we get a nice error message when trying to delete an adapter that does not exist.
|
| 1405 |
+
config = config_cls(base_model_name_or_path=model_id, **config_kwargs)
|
| 1406 |
+
with hub_online_once(model_id):
|
| 1407 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1408 |
+
adapter_to_delete = "delete_me"
|
| 1409 |
+
model = get_peft_model(model, config)
|
| 1410 |
+
|
| 1411 |
+
msg = "Adapter unknown-adapter does not exist"
|
| 1412 |
+
with pytest.raises(ValueError, match=msg):
|
| 1413 |
+
model.delete_adapter("unknown-adapter")
|
| 1414 |
+
|
| 1415 |
+
def _test_unload_adapter(self, model_id, config_cls, config_kwargs):
|
| 1416 |
+
with hub_online_once(model_id):
|
| 1417 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1418 |
+
num_params_base = len(model.state_dict())
|
| 1419 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1420 |
+
with torch.inference_mode():
|
| 1421 |
+
logits_transformers = model(**dummy_input)[0]
|
| 1422 |
+
|
| 1423 |
+
config = config_cls(
|
| 1424 |
+
base_model_name_or_path=model_id,
|
| 1425 |
+
**config_kwargs,
|
| 1426 |
+
)
|
| 1427 |
+
model = get_peft_model(model, config)
|
| 1428 |
+
model = model.to(self.torch_device)
|
| 1429 |
+
|
| 1430 |
+
if isinstance(config, PromptLearningConfig):
|
| 1431 |
+
# prompt learning does not support unloading
|
| 1432 |
+
with pytest.raises(AttributeError):
|
| 1433 |
+
model = model.unload()
|
| 1434 |
+
else:
|
| 1435 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 1436 |
+
with torch.inference_mode():
|
| 1437 |
+
logits_with_adapter = model(**dummy_input)[0]
|
| 1438 |
+
|
| 1439 |
+
model.eval()
|
| 1440 |
+
model = model.unload()
|
| 1441 |
+
num_params_unloaded = len(model.state_dict())
|
| 1442 |
+
with torch.inference_mode():
|
| 1443 |
+
logits_unload = model(**dummy_input)[0]
|
| 1444 |
+
|
| 1445 |
+
# check that PEFT layers are completely removed
|
| 1446 |
+
assert not any(isinstance(module, BaseTunerLayer) for module in model.modules())
|
| 1447 |
+
assert not hasattr(model, "peft_config")
|
| 1448 |
+
assert not torch.allclose(logits_with_adapter, logits_unload, atol=1e-10, rtol=1e-10)
|
| 1449 |
+
assert torch.allclose(logits_transformers, logits_unload, atol=1e-4, rtol=1e-4)
|
| 1450 |
+
assert num_params_base == num_params_unloaded
|
| 1451 |
+
|
| 1452 |
+
def _test_weighted_combination_of_adapters_lora(self, model, config, adapter_list, weight_list):
|
| 1453 |
+
_skip_if_adding_weighted_adapters_not_supported(config)
|
| 1454 |
+
model.add_adapter(adapter_list[1], config)
|
| 1455 |
+
model.add_adapter(adapter_list[2], replace(config, r=20))
|
| 1456 |
+
model = model.to(self.torch_device)
|
| 1457 |
+
|
| 1458 |
+
# test re-weighting single adapter
|
| 1459 |
+
model.add_weighted_adapter([adapter_list[0]], [weight_list[0]], "single_adapter_reweighting")
|
| 1460 |
+
|
| 1461 |
+
# test svd re-weighting with multiple adapters
|
| 1462 |
+
model.add_weighted_adapter(adapter_list[1:], weight_list[1:], "multi_adapter_svd_reweighting")
|
| 1463 |
+
|
| 1464 |
+
# test ties_svd re-weighting with multiple adapters
|
| 1465 |
+
model.add_weighted_adapter(
|
| 1466 |
+
adapter_list[1:],
|
| 1467 |
+
weight_list[1:],
|
| 1468 |
+
"multi_adapter_ties_svd_reweighting",
|
| 1469 |
+
combination_type="ties_svd",
|
| 1470 |
+
density=0.5,
|
| 1471 |
+
)
|
| 1472 |
+
|
| 1473 |
+
# test dare_linear_svd re-weighting with multiple adapters
|
| 1474 |
+
model.add_weighted_adapter(
|
| 1475 |
+
adapter_list[1:],
|
| 1476 |
+
weight_list[1:],
|
| 1477 |
+
"multi_adapter_dare_linear_svd_reweighting",
|
| 1478 |
+
combination_type="dare_linear_svd",
|
| 1479 |
+
density=0.5,
|
| 1480 |
+
)
|
| 1481 |
+
|
| 1482 |
+
# test dare_ties_svd re-weighting with multiple adapters
|
| 1483 |
+
model.add_weighted_adapter(
|
| 1484 |
+
adapter_list[1:],
|
| 1485 |
+
weight_list[1:],
|
| 1486 |
+
"multi_adapter_dare_ties_svd_reweighting",
|
| 1487 |
+
combination_type="dare_ties_svd",
|
| 1488 |
+
density=0.5,
|
| 1489 |
+
)
|
| 1490 |
+
|
| 1491 |
+
# test magnitude_prune_svd re-weighting with multiple adapters
|
| 1492 |
+
model.add_weighted_adapter(
|
| 1493 |
+
adapter_list[1:],
|
| 1494 |
+
weight_list[1:],
|
| 1495 |
+
"multi_adapter_magnitude_prune_svd_reweighting",
|
| 1496 |
+
combination_type="magnitude_prune_svd",
|
| 1497 |
+
density=0.5,
|
| 1498 |
+
)
|
| 1499 |
+
|
| 1500 |
+
# test cat re-weighting with multiple adapters
|
| 1501 |
+
model.add_weighted_adapter(
|
| 1502 |
+
adapter_list[1:], weight_list[1:], "multi_adapter_cat_reweighting", combination_type="cat"
|
| 1503 |
+
)
|
| 1504 |
+
|
| 1505 |
+
# test linear re-weighting with multiple adapters
|
| 1506 |
+
model.add_weighted_adapter(
|
| 1507 |
+
adapter_list[:2], weight_list[:2], "multi_adapter_linear_reweighting", combination_type="linear"
|
| 1508 |
+
)
|
| 1509 |
+
|
| 1510 |
+
# test ties re-weighting with multiple adapters
|
| 1511 |
+
model.add_weighted_adapter(
|
| 1512 |
+
adapter_list[:2], weight_list[:2], "multi_adapter_ties_reweighting", combination_type="ties", density=0.5
|
| 1513 |
+
)
|
| 1514 |
+
|
| 1515 |
+
# test dare_linear re-weighting with multiple adapters
|
| 1516 |
+
model.add_weighted_adapter(
|
| 1517 |
+
adapter_list[:2],
|
| 1518 |
+
weight_list[:2],
|
| 1519 |
+
"multi_adapter_dare_linear_reweighting",
|
| 1520 |
+
combination_type="dare_linear",
|
| 1521 |
+
density=0.5,
|
| 1522 |
+
)
|
| 1523 |
+
|
| 1524 |
+
# test dare_ties re-weighting with multiple adapters
|
| 1525 |
+
model.add_weighted_adapter(
|
| 1526 |
+
adapter_list[:2],
|
| 1527 |
+
weight_list[:2],
|
| 1528 |
+
"multi_adapter_dare_ties_reweighting",
|
| 1529 |
+
combination_type="dare_ties",
|
| 1530 |
+
density=0.5,
|
| 1531 |
+
)
|
| 1532 |
+
|
| 1533 |
+
# test magnitude_prune re-weighting with multiple adapters
|
| 1534 |
+
model.add_weighted_adapter(
|
| 1535 |
+
adapter_list[:2],
|
| 1536 |
+
weight_list[:2],
|
| 1537 |
+
"multi_adapter_magnitude_prune_reweighting",
|
| 1538 |
+
combination_type="magnitude_prune",
|
| 1539 |
+
density=0.5,
|
| 1540 |
+
)
|
| 1541 |
+
|
| 1542 |
+
# test linear re-weighting with multiple adapters with only first adapter having non zero weight
|
| 1543 |
+
model.add_weighted_adapter(
|
| 1544 |
+
adapter_list[:2],
|
| 1545 |
+
[weight_list[0], 0],
|
| 1546 |
+
"multi_adapter_linear_reweighting_single_enabled",
|
| 1547 |
+
combination_type="linear",
|
| 1548 |
+
)
|
| 1549 |
+
|
| 1550 |
+
with pytest.raises(ValueError):
|
| 1551 |
+
model.add_weighted_adapter(
|
| 1552 |
+
adapter_list[1:],
|
| 1553 |
+
weight_list[1:],
|
| 1554 |
+
"multi_adapter_linear_reweighting_uneven_r",
|
| 1555 |
+
combination_type="linear",
|
| 1556 |
+
)
|
| 1557 |
+
|
| 1558 |
+
with pytest.raises(ValueError):
|
| 1559 |
+
model.add_weighted_adapter(
|
| 1560 |
+
adapter_list[1:],
|
| 1561 |
+
weight_list[1:],
|
| 1562 |
+
"multi_adapter_ties_reweighting_uneven_r",
|
| 1563 |
+
combination_type="ties",
|
| 1564 |
+
density=0.5,
|
| 1565 |
+
)
|
| 1566 |
+
|
| 1567 |
+
with pytest.raises(ValueError):
|
| 1568 |
+
model.add_weighted_adapter(
|
| 1569 |
+
adapter_list[1:],
|
| 1570 |
+
weight_list[1:],
|
| 1571 |
+
"multi_adapter_dare_linear_reweighting_uneven_r",
|
| 1572 |
+
combination_type="dare_linear",
|
| 1573 |
+
density=0.5,
|
| 1574 |
+
)
|
| 1575 |
+
|
| 1576 |
+
with pytest.raises(ValueError):
|
| 1577 |
+
model.add_weighted_adapter(
|
| 1578 |
+
adapter_list[1:],
|
| 1579 |
+
weight_list[1:],
|
| 1580 |
+
"multi_adapter_dare_ties_reweighting_uneven_r",
|
| 1581 |
+
combination_type="dare_ties",
|
| 1582 |
+
density=0.5,
|
| 1583 |
+
)
|
| 1584 |
+
|
| 1585 |
+
with pytest.raises(ValueError):
|
| 1586 |
+
model.add_weighted_adapter(
|
| 1587 |
+
adapter_list[1:],
|
| 1588 |
+
weight_list[1:],
|
| 1589 |
+
"multi_adapter_magnitude_prune_reweighting_uneven_r",
|
| 1590 |
+
combination_type="magnitude_prune",
|
| 1591 |
+
density=0.5,
|
| 1592 |
+
)
|
| 1593 |
+
|
| 1594 |
+
new_adapters = [
|
| 1595 |
+
"single_adapter_reweighting",
|
| 1596 |
+
"multi_adapter_svd_reweighting",
|
| 1597 |
+
"multi_adapter_ties_svd_reweighting",
|
| 1598 |
+
"multi_adapter_dare_linear_svd_reweighting",
|
| 1599 |
+
"multi_adapter_dare_ties_svd_reweighting",
|
| 1600 |
+
"multi_adapter_magnitude_prune_svd_reweighting",
|
| 1601 |
+
"multi_adapter_cat_reweighting",
|
| 1602 |
+
"multi_adapter_linear_reweighting",
|
| 1603 |
+
"multi_adapter_linear_reweighting_single_enabled",
|
| 1604 |
+
"multi_adapter_ties_reweighting",
|
| 1605 |
+
"multi_adapter_dare_linear_reweighting",
|
| 1606 |
+
"multi_adapter_dare_ties_reweighting",
|
| 1607 |
+
"multi_adapter_magnitude_prune_reweighting",
|
| 1608 |
+
]
|
| 1609 |
+
for new_adapter in new_adapters:
|
| 1610 |
+
assert new_adapter in model.peft_config
|
| 1611 |
+
|
| 1612 |
+
key_list = [key for key, _ in model.named_modules()]
|
| 1613 |
+
for key in key_list:
|
| 1614 |
+
_, target, _ = _get_submodules(model, key)
|
| 1615 |
+
if isinstance(target, LoraLayer):
|
| 1616 |
+
for adapter_name in new_adapters:
|
| 1617 |
+
if "single" in adapter_name:
|
| 1618 |
+
new_delta_weight = target.get_delta_weight(adapter_name)
|
| 1619 |
+
weighted_original_delta_weights = target.get_delta_weight(adapter_list[0]) * weight_list[0]
|
| 1620 |
+
sign = 1 if weight_list[0] > 0 else -1
|
| 1621 |
+
weighted_original_delta_weights = sign * weighted_original_delta_weights
|
| 1622 |
+
assert torch.allclose(new_delta_weight, weighted_original_delta_weights, atol=1e-4, rtol=1e-4)
|
| 1623 |
+
elif "svd" in adapter_name:
|
| 1624 |
+
assert target.r[adapter_name] == 20
|
| 1625 |
+
elif "linear" in adapter_name:
|
| 1626 |
+
assert target.r[adapter_name] == 8
|
| 1627 |
+
elif "cat" in adapter_name:
|
| 1628 |
+
assert target.r[adapter_name] == 28
|
| 1629 |
+
|
| 1630 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1631 |
+
model.eval()
|
| 1632 |
+
for adapter_name in new_adapters:
|
| 1633 |
+
# ensuring new adapters pass the forward loop
|
| 1634 |
+
model.set_adapter(adapter_name)
|
| 1635 |
+
assert model.active_adapter == adapter_name
|
| 1636 |
+
assert model.active_adapters == [adapter_name]
|
| 1637 |
+
model(**dummy_input)[0]
|
| 1638 |
+
|
| 1639 |
+
def _test_weighted_combination_of_adapters_ia3(self, model, config, adapter_list, weight_list):
|
| 1640 |
+
model.add_adapter(adapter_list[1], config)
|
| 1641 |
+
model.add_adapter(adapter_list[2], config)
|
| 1642 |
+
model = model.to(self.torch_device)
|
| 1643 |
+
|
| 1644 |
+
# test re-weighting single adapter
|
| 1645 |
+
model.add_weighted_adapter([adapter_list[0]], [weight_list[0]], "single_adapter_reweighting")
|
| 1646 |
+
|
| 1647 |
+
# test re-weighting with multiple adapters
|
| 1648 |
+
model.add_weighted_adapter(adapter_list[1:], weight_list[1:], "multi_adapter_reweighting")
|
| 1649 |
+
|
| 1650 |
+
new_adapters = [
|
| 1651 |
+
"single_adapter_reweighting",
|
| 1652 |
+
"multi_adapter_reweighting",
|
| 1653 |
+
]
|
| 1654 |
+
for new_adapter in new_adapters:
|
| 1655 |
+
assert new_adapter in model.peft_config
|
| 1656 |
+
|
| 1657 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1658 |
+
model.eval()
|
| 1659 |
+
for adapter_name in new_adapters:
|
| 1660 |
+
# ensuring new adapters pass the forward loop
|
| 1661 |
+
model.set_adapter(adapter_name)
|
| 1662 |
+
assert model.active_adapter == adapter_name
|
| 1663 |
+
assert model.active_adapters == [adapter_name]
|
| 1664 |
+
model(**dummy_input)[0]
|
| 1665 |
+
|
| 1666 |
+
def _test_weighted_combination_of_adapters(self, model_id, config_cls, config_kwargs):
|
| 1667 |
+
if issubclass(config_cls, AdaLoraConfig):
|
| 1668 |
+
# AdaLora does not support adding more than 1 adapter
|
| 1669 |
+
return pytest.skip(f"Test not applicable for {config_cls}")
|
| 1670 |
+
if model_id.endswith("qwen2"):
|
| 1671 |
+
# Qwen2 fails with weighted adapter combinations using SVD
|
| 1672 |
+
return pytest.skip(f"Test does not work with model {model_id}")
|
| 1673 |
+
if "gemma" in model_id.lower():
|
| 1674 |
+
return pytest.skip("Combining Gemma adapters with SVD is currently failing")
|
| 1675 |
+
|
| 1676 |
+
adapter_list = ["adapter1", "adapter_2", "adapter_3"]
|
| 1677 |
+
weight_list = [0.5, 1.5, 1.5]
|
| 1678 |
+
negative_weight_list = [-0.5, -0.8, -1.2]
|
| 1679 |
+
# Initialize the config
|
| 1680 |
+
config = config_cls(
|
| 1681 |
+
base_model_name_or_path=model_id,
|
| 1682 |
+
**config_kwargs,
|
| 1683 |
+
)
|
| 1684 |
+
|
| 1685 |
+
if not isinstance(config, (LoraConfig, IA3Config)):
|
| 1686 |
+
# This test is only applicable for Lora and IA3 configs
|
| 1687 |
+
return pytest.skip(f"Test not applicable for {config}")
|
| 1688 |
+
|
| 1689 |
+
with hub_online_once(model_id):
|
| 1690 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1691 |
+
model = get_peft_model(model, config, adapter_list[0])
|
| 1692 |
+
|
| 1693 |
+
if isinstance(config, LoraConfig):
|
| 1694 |
+
self._test_weighted_combination_of_adapters_lora(model, config, adapter_list, weight_list)
|
| 1695 |
+
self._test_weighted_combination_of_adapters_lora(model, config, adapter_list, negative_weight_list)
|
| 1696 |
+
elif isinstance(config, IA3Config):
|
| 1697 |
+
self._test_weighted_combination_of_adapters_ia3(model, config, adapter_list, weight_list)
|
| 1698 |
+
self._test_weighted_combination_of_adapters_ia3(model, config, adapter_list, negative_weight_list)
|
| 1699 |
+
else:
|
| 1700 |
+
pytest.skip(f"Test not applicable for {config}")
|
| 1701 |
+
|
| 1702 |
+
def _test_disable_adapter(self, model_id, config_cls, config_kwargs):
|
| 1703 |
+
task_type = config_kwargs.get("task_type")
|
| 1704 |
+
if (task_type == "SEQ_2_SEQ_LM") and (config_cls in (PromptTuningConfig, PromptEncoderConfig)):
|
| 1705 |
+
pytest.skip("Seq2Seq + prompt tuning/prompt encoder does not work with disabling adapters")
|
| 1706 |
+
|
| 1707 |
+
def get_output(model):
|
| 1708 |
+
# helper function that works with different model types
|
| 1709 |
+
torch.manual_seed(0)
|
| 1710 |
+
|
| 1711 |
+
if hasattr(model, "generate"):
|
| 1712 |
+
# let's check the scores, not the output ids, since the latter can easily be identical even if the
|
| 1713 |
+
# weights are slightly changed
|
| 1714 |
+
output = model.generate(**input, return_dict_in_generate=True, output_scores=True).scores[0]
|
| 1715 |
+
# take element 0, as output is a tuple
|
| 1716 |
+
else:
|
| 1717 |
+
output = model(**input)
|
| 1718 |
+
|
| 1719 |
+
if hasattr(output, "images"): # for SD
|
| 1720 |
+
import numpy as np
|
| 1721 |
+
|
| 1722 |
+
img = output.images[0]
|
| 1723 |
+
return torch.from_numpy(np.array(img))
|
| 1724 |
+
|
| 1725 |
+
return output
|
| 1726 |
+
|
| 1727 |
+
# initialize model
|
| 1728 |
+
with hub_online_once(model_id):
|
| 1729 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1730 |
+
|
| 1731 |
+
# output from BASE MODEL
|
| 1732 |
+
input = self.prepare_inputs_for_testing()
|
| 1733 |
+
output_before = get_output(model)
|
| 1734 |
+
|
| 1735 |
+
# output from PEFT MODEL
|
| 1736 |
+
if hasattr(self, "instantiate_sd_peft"):
|
| 1737 |
+
# SD models are instantiated differently
|
| 1738 |
+
peft_model = self.instantiate_sd_peft(model_id, config_cls, config_kwargs)
|
| 1739 |
+
else:
|
| 1740 |
+
config = config_cls(
|
| 1741 |
+
base_model_name_or_path=model_id,
|
| 1742 |
+
**config_kwargs,
|
| 1743 |
+
)
|
| 1744 |
+
peft_model = get_peft_model(model, config)
|
| 1745 |
+
|
| 1746 |
+
# trainable_token_indices doesn't have support for `init_weights` so we have to do this manually
|
| 1747 |
+
self.perturb_trainable_token_weights_if_used(model, config_kwargs)
|
| 1748 |
+
|
| 1749 |
+
output_peft = get_output(peft_model)
|
| 1750 |
+
|
| 1751 |
+
# first check trivial case is not true that peft does not affect the output; for this to work, init_weight
|
| 1752 |
+
# must be False (if the config supports it)
|
| 1753 |
+
if isinstance(peft_model, StableDiffusionPipeline):
|
| 1754 |
+
# for SD, check that most pixels have different values
|
| 1755 |
+
assert (output_before != output_peft).float().mean() > 0.8
|
| 1756 |
+
else:
|
| 1757 |
+
assert not torch.allclose(output_before, output_peft)
|
| 1758 |
+
|
| 1759 |
+
# output with DISABLED ADAPTER
|
| 1760 |
+
if isinstance(peft_model, StableDiffusionPipeline):
|
| 1761 |
+
with peft_model.unet.disable_adapter(), peft_model.text_encoder.disable_adapter():
|
| 1762 |
+
output_peft_disabled = get_output(peft_model)
|
| 1763 |
+
# for SD, very rarely, a pixel can differ
|
| 1764 |
+
assert (output_before != output_peft_disabled).float().mean() < 1e-4
|
| 1765 |
+
else:
|
| 1766 |
+
atol, rtol = 1e-6, 1e-6
|
| 1767 |
+
if (platform.system() == "Windows") and (model_id == "trl-internal-testing/tiny-Llama4ForCausalLM"):
|
| 1768 |
+
# for some reason, Windows CI fails with stricter tolerance
|
| 1769 |
+
atol, rtol = 1e-5, 1e-5
|
| 1770 |
+
|
| 1771 |
+
with peft_model.disable_adapter():
|
| 1772 |
+
output_peft_disabled = get_output(peft_model)
|
| 1773 |
+
assert torch.allclose(output_before, output_peft_disabled, atol=atol, rtol=rtol)
|
| 1774 |
+
|
| 1775 |
+
# after leaving the disable_adapter context, the output should be the same as with enabled adapter again
|
| 1776 |
+
# see #1501
|
| 1777 |
+
output_peft_after_disabled = get_output(peft_model)
|
| 1778 |
+
assert torch.allclose(output_peft, output_peft_after_disabled, atol=atol, rtol=rtol)
|
| 1779 |
+
|
| 1780 |
+
# TODO: add tests to check if disabling adapters works after calling merge_adapter
|
| 1781 |
+
|
| 1782 |
+
def _test_adding_multiple_adapters_with_bias_raises(self, model_id, config_cls, config_kwargs):
|
| 1783 |
+
config_kwargs = config_kwargs.copy()
|
| 1784 |
+
config_kwargs["bias"] = "all"
|
| 1785 |
+
try:
|
| 1786 |
+
config = config_cls(
|
| 1787 |
+
base_model_name_or_path=model_id,
|
| 1788 |
+
**config_kwargs,
|
| 1789 |
+
)
|
| 1790 |
+
except TypeError:
|
| 1791 |
+
pytest.skip(f"{config_cls} does not support the 'bias' argument, skipping this test.")
|
| 1792 |
+
|
| 1793 |
+
with hub_online_once(model_id):
|
| 1794 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1795 |
+
model = get_peft_model(model, config, "adapter0")
|
| 1796 |
+
|
| 1797 |
+
if config_cls == LoraConfig or config_cls == AdaLoraConfig:
|
| 1798 |
+
with pytest.raises(ValueError):
|
| 1799 |
+
model.add_adapter("adapter1", replace(config, r=20))
|
| 1800 |
+
|
| 1801 |
+
if config_cls == BOFTConfig:
|
| 1802 |
+
with pytest.raises(ValueError):
|
| 1803 |
+
model.add_adapter("adapter1", replace(config, boft_block_num=1, boft_block_size=0))
|
| 1804 |
+
|
| 1805 |
+
# (superficial) test that the model is not left in a half-initialized state when adding an adapter fails
|
| 1806 |
+
assert "adapter1" not in model.peft_config
|
| 1807 |
+
assert "adapter1" not in model.base_model.peft_config
|
| 1808 |
+
|
| 1809 |
+
def _test_passing_input_embeds_works(self, test_name, model_id, config_cls, config_kwargs):
|
| 1810 |
+
# https://github.com/huggingface/peft/issues/727
|
| 1811 |
+
with hub_online_once(model_id):
|
| 1812 |
+
model = self.transformers_class.from_pretrained(model_id)
|
| 1813 |
+
config = config_cls(
|
| 1814 |
+
base_model_name_or_path=model_id,
|
| 1815 |
+
**config_kwargs,
|
| 1816 |
+
)
|
| 1817 |
+
model = get_peft_model(model, config, adapter_name="test-adapter").to(self.torch_device)
|
| 1818 |
+
dummy_input = self.prepare_inputs_for_testing()
|
| 1819 |
+
inputs_embeds = model.get_input_embeddings()(dummy_input["input_ids"])
|
| 1820 |
+
# just check that no error is raised
|
| 1821 |
+
model.forward(inputs_embeds=inputs_embeds)
|
| 1822 |
+
|
| 1823 |
+
def _test_lora_conversion(self, model_id, config_cls, config_kwargs):
|
| 1824 |
+
# This is a simple test that converting a non-LoRA adapter to LoRA works. If the model doesn't support
|
| 1825 |
+
# conversion, the test is skipped. For detailed tests of this functionality, check test_lora_conversion.py,
|
| 1826 |
+
# which provides depper tests. The purpose of this test is only provide a broad check across PEFT methods.
|
| 1827 |
+
torch.manual_seed(0)
|
| 1828 |
+
if "qwen2" in model_id: # dummy qwen2 has very small weights
|
| 1829 |
+
rank = 4
|
| 1830 |
+
else:
|
| 1831 |
+
rank = 8
|
| 1832 |
+
|
| 1833 |
+
if config_cls == GraloraConfig:
|
| 1834 |
+
# GraLoRA exhibits higher conversion error
|
| 1835 |
+
max_mse = 1.0
|
| 1836 |
+
else:
|
| 1837 |
+
# relatively high upper limit for MSE since we have to work with a low LoRA rank for dummy models
|
| 1838 |
+
max_mse = 0.5
|
| 1839 |
+
|
| 1840 |
+
with hub_online_once(model_id):
|
| 1841 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1842 |
+
config = config_cls(
|
| 1843 |
+
base_model_name_or_path=model_id,
|
| 1844 |
+
**config_kwargs,
|
| 1845 |
+
)
|
| 1846 |
+
model = get_peft_model(model, config).eval()
|
| 1847 |
+
|
| 1848 |
+
if not model.supports_lora_conversion():
|
| 1849 |
+
return
|
| 1850 |
+
if ("OPT" in model_id) and ("fc1" in config.target_modules):
|
| 1851 |
+
# the fc1 and fc2 layers in OPT have size (16, 4), thus choose smaller rank
|
| 1852 |
+
rank = 4
|
| 1853 |
+
|
| 1854 |
+
X = self.prepare_inputs_for_testing()
|
| 1855 |
+
with torch.no_grad():
|
| 1856 |
+
with model.disable_adapter():
|
| 1857 |
+
output_base = model(**X, output_hidden_states=True)
|
| 1858 |
+
output_before = model(**X, output_hidden_states=True)
|
| 1859 |
+
|
| 1860 |
+
# create the converted lora adapter
|
| 1861 |
+
lora_config, state_dict = convert_to_lora(model, rank=rank)
|
| 1862 |
+
del model
|
| 1863 |
+
|
| 1864 |
+
# load the converted LoRA model
|
| 1865 |
+
model = self.transformers_class.from_pretrained(model_id).to(self.torch_device)
|
| 1866 |
+
model = get_peft_model(model, lora_config).eval()
|
| 1867 |
+
load_result = set_peft_model_state_dict(model, state_dict)
|
| 1868 |
+
assert not load_result.unexpected_keys
|
| 1869 |
+
|
| 1870 |
+
with torch.no_grad():
|
| 1871 |
+
output_after = model(**X, output_hidden_states=True)
|
| 1872 |
+
|
| 1873 |
+
diff1 = output_before.hidden_states[-1] - output_base.hidden_states[-1]
|
| 1874 |
+
diff2 = output_after.hidden_states[-1] - output_base.hidden_states[-1]
|
| 1875 |
+
mse = torch.nn.functional.mse_loss(diff1, diff2).item()
|
| 1876 |
+
assert mse < max_mse, f"LoRA conversion MSE too high, {mse:.4f}, only {max_mse:.1f} allowed"
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/testing_utils.py
ADDED
|
@@ -0,0 +1,373 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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_eetq_available,
|
| 36 |
+
is_gptqmodel_available,
|
| 37 |
+
is_hqq_available,
|
| 38 |
+
is_optimum_available,
|
| 39 |
+
is_torchao_available,
|
| 40 |
+
is_transformers_ge_v5,
|
| 41 |
+
)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
# Globally shared model cache used by `hub_online_once`.
|
| 45 |
+
_HUB_MODEL_ACCESSES = {}
|
| 46 |
+
# Some tests with multi GPU require specific device maps to ensure that the models are loaded in two devices
|
| 47 |
+
DEVICE_MAP_MAP: dict[str, dict[str, int]] = {
|
| 48 |
+
"facebook/opt-6.7b": {
|
| 49 |
+
"model.decoder.embed_tokens": 0,
|
| 50 |
+
"model.decoder.embed_positions": 0,
|
| 51 |
+
"model.decoder.final_layer_norm": 0,
|
| 52 |
+
"model.decoder.layers.0": 0,
|
| 53 |
+
"model.decoder.layers.1": 0,
|
| 54 |
+
"model.decoder.layers.2": 0,
|
| 55 |
+
"model.decoder.layers.3": 0,
|
| 56 |
+
"model.decoder.layers.4": 0,
|
| 57 |
+
"model.decoder.layers.5": 0,
|
| 58 |
+
"model.decoder.layers.6": 0,
|
| 59 |
+
"model.decoder.layers.7": 0,
|
| 60 |
+
"model.decoder.layers.8": 0,
|
| 61 |
+
"model.decoder.layers.9": 0,
|
| 62 |
+
"model.decoder.layers.10": 0,
|
| 63 |
+
"model.decoder.layers.11": 0,
|
| 64 |
+
"model.decoder.layers.12": 0,
|
| 65 |
+
"model.decoder.layers.13": 0,
|
| 66 |
+
"model.decoder.layers.14": 0,
|
| 67 |
+
"model.decoder.layers.15": 0,
|
| 68 |
+
"model.decoder.layers.16": 1,
|
| 69 |
+
"model.decoder.layers.17": 1,
|
| 70 |
+
"model.decoder.layers.18": 1,
|
| 71 |
+
"model.decoder.layers.19": 1,
|
| 72 |
+
"model.decoder.layers.20": 1,
|
| 73 |
+
"model.decoder.layers.21": 1,
|
| 74 |
+
"model.decoder.layers.22": 1,
|
| 75 |
+
"model.decoder.layers.23": 1,
|
| 76 |
+
"model.decoder.layers.24": 1,
|
| 77 |
+
"model.decoder.layers.25": 1,
|
| 78 |
+
"model.decoder.layers.26": 1,
|
| 79 |
+
"model.decoder.layers.27": 1,
|
| 80 |
+
"model.decoder.layers.28": 1,
|
| 81 |
+
"model.decoder.layers.29": 1,
|
| 82 |
+
"model.decoder.layers.30": 1,
|
| 83 |
+
"model.decoder.layers.31": 1,
|
| 84 |
+
"lm_head": 0, # tied with embed_tokens
|
| 85 |
+
},
|
| 86 |
+
"peft-internal-testing/opt-125m": {
|
| 87 |
+
"model.decoder.embed_tokens": 0,
|
| 88 |
+
"model.decoder.embed_positions": 0,
|
| 89 |
+
"model.decoder.final_layer_norm": 1,
|
| 90 |
+
"model.decoder.layers.0": 0,
|
| 91 |
+
"model.decoder.layers.1": 0,
|
| 92 |
+
"model.decoder.layers.2": 0,
|
| 93 |
+
"model.decoder.layers.3": 0,
|
| 94 |
+
"model.decoder.layers.4": 0,
|
| 95 |
+
"model.decoder.layers.5": 0,
|
| 96 |
+
"model.decoder.layers.6": 1,
|
| 97 |
+
"model.decoder.layers.7": 1,
|
| 98 |
+
"model.decoder.layers.8": 1,
|
| 99 |
+
"model.decoder.layers.9": 1,
|
| 100 |
+
"model.decoder.layers.10": 1,
|
| 101 |
+
"model.decoder.layers.11": 1,
|
| 102 |
+
"lm_head": 0,
|
| 103 |
+
},
|
| 104 |
+
"marcsun13/opt-350m-gptq-4bit": {
|
| 105 |
+
"model.decoder.embed_tokens": 0,
|
| 106 |
+
"model.decoder.embed_positions": 0,
|
| 107 |
+
"model.decoder.layers.0": 0,
|
| 108 |
+
"model.decoder.layers.1": 0,
|
| 109 |
+
"model.decoder.layers.2": 0,
|
| 110 |
+
"model.decoder.layers.3": 0,
|
| 111 |
+
"model.decoder.layers.4": 0,
|
| 112 |
+
"model.decoder.layers.5": 0,
|
| 113 |
+
"model.decoder.layers.6": 1,
|
| 114 |
+
"model.decoder.layers.7": 1,
|
| 115 |
+
"model.decoder.layers.8": 1,
|
| 116 |
+
"model.decoder.layers.9": 1,
|
| 117 |
+
"model.decoder.layers.10": 1,
|
| 118 |
+
"model.decoder.layers.11": 1,
|
| 119 |
+
"model.decoder.final_layer_norm": 1,
|
| 120 |
+
"lm_head": 0, # tied with embed_tokens
|
| 121 |
+
},
|
| 122 |
+
"google/flan-t5-base": {
|
| 123 |
+
"shared": 0,
|
| 124 |
+
"encoder": 0,
|
| 125 |
+
"decoder": 1,
|
| 126 |
+
"final_layer_norm": 1,
|
| 127 |
+
"decoder.embed_tokens": 0, # tied with encoder.embed_tokens
|
| 128 |
+
"lm_head": 0, # tied with encoder.embed_tokens
|
| 129 |
+
},
|
| 130 |
+
}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
torch_device, device_count, memory_allocated_func = get_backend()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def require_non_cpu(test_case):
|
| 137 |
+
"""
|
| 138 |
+
Decorator marking a test that requires a hardware accelerator backend. These tests are skipped when there are no
|
| 139 |
+
hardware accelerator available.
|
| 140 |
+
"""
|
| 141 |
+
return pytest.mark.skipif(torch_device == "cpu", reason="test requires a hardware accelerator")(test_case)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def require_non_xpu(test_case):
|
| 145 |
+
"""
|
| 146 |
+
Decorator marking a test that should be skipped for XPU.
|
| 147 |
+
"""
|
| 148 |
+
return pytest.mark.skipif(torch_device == "xpu", reason="test requires a non-XPU")(test_case)
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def require_torch_gpu(test_case):
|
| 152 |
+
"""
|
| 153 |
+
Decorator marking a test that requires a GPU. Will be skipped when no GPU is available.
|
| 154 |
+
"""
|
| 155 |
+
return pytest.mark.skipif(not torch.cuda.is_available(), reason="test requires GPU")(test_case)
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def require_torch_multi_gpu(test_case):
|
| 159 |
+
"""
|
| 160 |
+
Decorator marking a test that requires multiple GPUs. Will be skipped when less than 2 GPUs are available.
|
| 161 |
+
"""
|
| 162 |
+
multi_cuda_unavailable = not torch.cuda.is_available() or (device_count < 2)
|
| 163 |
+
return pytest.mark.skipif(multi_cuda_unavailable, reason="test requires multiple GPUs")(test_case)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def require_torch_multi_accelerator(test_case):
|
| 167 |
+
"""
|
| 168 |
+
Decorator marking a test that requires multiple hardware accelerators. These tests are skipped on a machine without
|
| 169 |
+
multiple accelerators.
|
| 170 |
+
"""
|
| 171 |
+
multi_device_unavailable = (torch_device == "cpu") or (device_count < 2)
|
| 172 |
+
return pytest.mark.skipif(multi_device_unavailable, reason="test requires multiple hardware accelerators")(
|
| 173 |
+
test_case
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def require_bitsandbytes(test_case):
|
| 178 |
+
"""
|
| 179 |
+
Decorator marking a test that requires the bitsandbytes library. Will be skipped when the library is not installed.
|
| 180 |
+
"""
|
| 181 |
+
try:
|
| 182 |
+
import bitsandbytes # noqa: F401
|
| 183 |
+
|
| 184 |
+
test_case = pytest.mark.bitsandbytes(test_case)
|
| 185 |
+
except ImportError:
|
| 186 |
+
test_case = pytest.mark.skip(reason="test requires bitsandbytes")(test_case)
|
| 187 |
+
return test_case
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
def require_gptqmodel(test_case):
|
| 191 |
+
"""
|
| 192 |
+
Decorator marking a test that requires gptqmodel. These tests are skipped when gptqmodel isn't installed.
|
| 193 |
+
"""
|
| 194 |
+
return pytest.mark.skipif(not is_gptqmodel_available(), reason="test requires gptqmodel")(test_case)
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def require_aqlm(test_case):
|
| 198 |
+
"""
|
| 199 |
+
Decorator marking a test that requires aqlm. These tests are skipped when aqlm isn't installed.
|
| 200 |
+
"""
|
| 201 |
+
return pytest.mark.skipif(not is_aqlm_available(), reason="test requires aqlm")(test_case)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def require_hqq(test_case):
|
| 205 |
+
"""
|
| 206 |
+
Decorator marking a test that requires aqlm. These tests are skipped when aqlm isn't installed.
|
| 207 |
+
"""
|
| 208 |
+
return pytest.mark.skipif(not is_hqq_available(), reason="test requires hqq")(test_case)
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def require_eetq(test_case):
|
| 212 |
+
"""
|
| 213 |
+
Decorator marking a test that requires eetq. These tests are skipped when eetq isn't installed.
|
| 214 |
+
"""
|
| 215 |
+
return pytest.mark.skipif(not is_eetq_available(), reason="test requires eetq")(test_case)
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
def require_optimum(test_case):
|
| 219 |
+
"""
|
| 220 |
+
Decorator marking a test that requires optimum. These tests are skipped when optimum isn't installed.
|
| 221 |
+
"""
|
| 222 |
+
return pytest.mark.skipif(not is_optimum_available(), reason="test requires optimum")(test_case)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def require_torchao(test_case):
|
| 226 |
+
"""
|
| 227 |
+
Decorator marking a test that requires torchao. These tests are skipped when torchao isn't installed.
|
| 228 |
+
"""
|
| 229 |
+
return pytest.mark.skipif(not is_torchao_available(), reason="test requires torchao")(test_case)
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
def require_deterministic_for_xpu(test_case):
|
| 233 |
+
@wraps(test_case)
|
| 234 |
+
def wrapper(*args, **kwargs):
|
| 235 |
+
if torch_device == "xpu":
|
| 236 |
+
original_state = torch.are_deterministic_algorithms_enabled()
|
| 237 |
+
try:
|
| 238 |
+
torch.use_deterministic_algorithms(True)
|
| 239 |
+
return test_case(*args, **kwargs)
|
| 240 |
+
finally:
|
| 241 |
+
torch.use_deterministic_algorithms(original_state)
|
| 242 |
+
else:
|
| 243 |
+
return test_case(*args, **kwargs)
|
| 244 |
+
|
| 245 |
+
return wrapper
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
@contextmanager
|
| 249 |
+
def temp_seed(seed: int):
|
| 250 |
+
"""Temporarily set the random seed. This works for python numpy, pytorch."""
|
| 251 |
+
|
| 252 |
+
np_state = np.random.get_state()
|
| 253 |
+
np.random.seed(seed)
|
| 254 |
+
|
| 255 |
+
torch_state = torch.random.get_rng_state()
|
| 256 |
+
torch.random.manual_seed(seed)
|
| 257 |
+
|
| 258 |
+
if torch.cuda.is_available():
|
| 259 |
+
torch_cuda_states = torch.cuda.get_rng_state_all()
|
| 260 |
+
torch.cuda.manual_seed_all(seed)
|
| 261 |
+
|
| 262 |
+
try:
|
| 263 |
+
yield
|
| 264 |
+
finally:
|
| 265 |
+
np.random.set_state(np_state)
|
| 266 |
+
|
| 267 |
+
torch.random.set_rng_state(torch_state)
|
| 268 |
+
if torch.cuda.is_available():
|
| 269 |
+
torch.cuda.set_rng_state_all(torch_cuda_states)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def get_state_dict(model, unwrap_compiled=True):
|
| 273 |
+
"""
|
| 274 |
+
Get the state dict of a model. If the model is compiled, unwrap it first.
|
| 275 |
+
"""
|
| 276 |
+
if unwrap_compiled:
|
| 277 |
+
model = getattr(model, "_orig_mod", model)
|
| 278 |
+
return model.state_dict()
|
| 279 |
+
|
| 280 |
+
|
| 281 |
+
@lru_cache
|
| 282 |
+
def load_dataset_english_quotes():
|
| 283 |
+
# can't use pytest fixtures for now because of unittest style tests
|
| 284 |
+
data = load_dataset("ybelkada/english_quotes_copy")
|
| 285 |
+
return data
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@lru_cache
|
| 289 |
+
def load_cat_image():
|
| 290 |
+
# can't use pytest fixtures for now because of unittest style tests
|
| 291 |
+
dataset = load_dataset("huggingface/cats-image", trust_remote_code=True)
|
| 292 |
+
image = dataset["test"]["image"][0]
|
| 293 |
+
return image
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def set_init_weights_false(config_cls, kwargs):
|
| 297 |
+
# helper function that sets the config kwargs such that the model is *not* initialized as an identity transform
|
| 298 |
+
kwargs = kwargs.copy()
|
| 299 |
+
|
| 300 |
+
if issubclass(config_cls, PromptLearningConfig):
|
| 301 |
+
return kwargs
|
| 302 |
+
if config_cls in (LNTuningConfig, VBLoRAConfig):
|
| 303 |
+
return kwargs
|
| 304 |
+
|
| 305 |
+
if config_cls in (LoraConfig, AdaLoraConfig):
|
| 306 |
+
kwargs["init_lora_weights"] = False
|
| 307 |
+
elif config_cls == IA3Config:
|
| 308 |
+
kwargs["init_ia3_weights"] = False
|
| 309 |
+
else:
|
| 310 |
+
kwargs["init_weights"] = False
|
| 311 |
+
return kwargs
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
@contextmanager
|
| 315 |
+
def hub_online_once(model_id: str):
|
| 316 |
+
"""Set env[HF_HUB_OFFLINE]=1 (and patch transformers/hugging_face_hub to think that it was always that way)
|
| 317 |
+
for model ids that were already to avoid contacting the hub twice for the same model id in the context. The global
|
| 318 |
+
variable `_HUB_MODEL_ACCESSES` tracks the number of hits per model id between `hub_online_once` calls.
|
| 319 |
+
|
| 320 |
+
The reason for doing a context manager and not patching specific methods (e.g., `from_pretrained`) is that there
|
| 321 |
+
are a lot of places (`PeftConfig.from_pretrained`, `get_peft_state_dict`, `load_adapter`, ...) that possibly
|
| 322 |
+
communicate with the hub to download files / check versions / etc.
|
| 323 |
+
|
| 324 |
+
Note that using this context manager can cause problems when used in code sections that access different resources.
|
| 325 |
+
Example:
|
| 326 |
+
|
| 327 |
+
```
|
| 328 |
+
def test_something(model_id, config_kwargs):
|
| 329 |
+
with hub_online_once(model_id):
|
| 330 |
+
model = ...from_pretrained(model_id)
|
| 331 |
+
self.do_something_specific_with_model(model)
|
| 332 |
+
```
|
| 333 |
+
It is assumed that `do_something_specific_with_model` is an absract method that is implement by several tests.
|
| 334 |
+
Imagine the first test simply does `model.generate([1,2,3])`. The second call from another test suite however uses
|
| 335 |
+
a tokenizer (`AutoTokenizer.from_pretrained(model_id)`) - this will fail since the first pass was online but didn't
|
| 336 |
+
use the tokenizer and we're now in offline mode and cannot fetch the tokenizer. The recommended workaround is to
|
| 337 |
+
extend the cache key (`model_id` passed to `hub_online_once` in this case) by something in case the tokenizer is
|
| 338 |
+
used, so that these tests don't share a cache pool with the tests that don't use a tokenizer.
|
| 339 |
+
|
| 340 |
+
It is best to avoid using this context manager in *yield* fixtures (normal fixtures are fine) as this is equivalent
|
| 341 |
+
to wrapping the whole test in the context manager without explicitly writing it out, leading to unexpected
|
| 342 |
+
`HF_HUB_OFFLINE` behavior in the test body.
|
| 343 |
+
"""
|
| 344 |
+
global _HUB_MODEL_ACCESSES
|
| 345 |
+
override = {}
|
| 346 |
+
|
| 347 |
+
try:
|
| 348 |
+
if model_id in _HUB_MODEL_ACCESSES:
|
| 349 |
+
override = {"HF_HUB_OFFLINE": "1"}
|
| 350 |
+
_HUB_MODEL_ACCESSES[model_id] += 1
|
| 351 |
+
elif model_id not in _HUB_MODEL_ACCESSES:
|
| 352 |
+
_HUB_MODEL_ACCESSES[model_id] = 0
|
| 353 |
+
is_offline = override.get("HF_HUB_OFFLINE", False) == "1"
|
| 354 |
+
|
| 355 |
+
with (
|
| 356 |
+
# strictly speaking it is not necessary to set the environment variable since most code that's out there
|
| 357 |
+
# is evaluating it at import time and we'd have to reload the modules for it to take effect. It's
|
| 358 |
+
# probably still a good idea to have it if there's some dynamic code that checks it.
|
| 359 |
+
mock.patch.dict(os.environ, override),
|
| 360 |
+
mock.patch("huggingface_hub.constants.HF_HUB_OFFLINE", is_offline),
|
| 361 |
+
):
|
| 362 |
+
if is_transformers_ge_v5:
|
| 363 |
+
with mock.patch("transformers.utils.hub.is_offline_mode", lambda: is_offline):
|
| 364 |
+
yield
|
| 365 |
+
else: # TODO remove if transformers <= 4 no longer supported
|
| 366 |
+
with mock.patch("transformers.utils.hub._is_offline_mode", is_offline):
|
| 367 |
+
yield
|
| 368 |
+
except Exception:
|
| 369 |
+
# in case of an error we have to assume that we didn't access the model properly from the hub
|
| 370 |
+
# for the first time, so the next call cannot be considered cached.
|
| 371 |
+
if _HUB_MODEL_ACCESSES.get(model_id) == 0:
|
| 372 |
+
del _HUB_MODEL_ACCESSES[model_id]
|
| 373 |
+
raise
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/training/adapters.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
Script to test FSDP adapter operations (disable_adapters, set_adapter, etc.) in a distributed environment.
|
| 17 |
+
|
| 18 |
+
This script is designed to be run with `accelerate launch` to properly test FSDP behavior while running one pass with
|
| 19 |
+
autograd and another with adapters being disabled.
|
| 20 |
+
|
| 21 |
+
Usage:
|
| 22 |
+
accelerate launch --config_file tests/training/fsdp_config.yaml tests/training/adapters.py
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
import argparse
|
| 26 |
+
import tempfile
|
| 27 |
+
|
| 28 |
+
import torch
|
| 29 |
+
from accelerate import PartialState
|
| 30 |
+
from datasets import load_dataset
|
| 31 |
+
from torch import nn
|
| 32 |
+
from torch.distributed.fsdp import FullyShardedDataParallel as FSDP
|
| 33 |
+
from transformers import (
|
| 34 |
+
AutoModelForCausalLM,
|
| 35 |
+
AutoTokenizer,
|
| 36 |
+
DataCollatorForLanguageModeling,
|
| 37 |
+
Trainer,
|
| 38 |
+
TrainingArguments,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from peft import LoraConfig, get_peft_model
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def get_base_model_weights(peft_model):
|
| 45 |
+
"""Extract base model weights (non-LoRA weights)."""
|
| 46 |
+
base_weights = {}
|
| 47 |
+
for name, param in peft_model.named_parameters():
|
| 48 |
+
if "lora" not in name.lower() and "modules_to_save" not in name:
|
| 49 |
+
base_weights[name] = param.detach().clone()
|
| 50 |
+
return base_weights
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_adapter_weights(peft_model, adapter_name):
|
| 54 |
+
"""Extract weights for a specific adapter."""
|
| 55 |
+
adapter_weights = {}
|
| 56 |
+
for name, param in peft_model.named_parameters():
|
| 57 |
+
if adapter_name in name:
|
| 58 |
+
adapter_weights[name] = param.detach().clone()
|
| 59 |
+
return adapter_weights
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def verify_weights_unchanged(initial_weights, final_weights, weight_type):
|
| 63 |
+
"""Verify that weights have not changed during training."""
|
| 64 |
+
for name in initial_weights:
|
| 65 |
+
if name not in final_weights:
|
| 66 |
+
raise AssertionError(f"{weight_type} weight missing after training: {name}")
|
| 67 |
+
torch.testing.assert_close(
|
| 68 |
+
initial_weights[name].to(device=final_weights[name].device, dtype=final_weights[name].dtype),
|
| 69 |
+
final_weights[name],
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class Model(nn.Module):
|
| 74 |
+
def __init__(self, model_id):
|
| 75 |
+
super().__init__()
|
| 76 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 77 |
+
model_id,
|
| 78 |
+
dtype=torch.bfloat16,
|
| 79 |
+
)
|
| 80 |
+
self.tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 81 |
+
|
| 82 |
+
peft_config = LoraConfig(
|
| 83 |
+
r=16,
|
| 84 |
+
lora_alpha=32,
|
| 85 |
+
target_modules=["q_proj", "v_proj"],
|
| 86 |
+
modules_to_save=["lm_head"],
|
| 87 |
+
lora_dropout=0.05,
|
| 88 |
+
bias="none",
|
| 89 |
+
task_type="CAUSAL_LM",
|
| 90 |
+
)
|
| 91 |
+
self.peft_model = get_peft_model(model, peft_config)
|
| 92 |
+
|
| 93 |
+
# Second adapter config (will remain disabled/unused throughout training)
|
| 94 |
+
peft_config_second = LoraConfig(
|
| 95 |
+
r=8,
|
| 96 |
+
lora_alpha=16,
|
| 97 |
+
target_modules=["q_proj", "v_proj"],
|
| 98 |
+
modules_to_save=["lm_head"],
|
| 99 |
+
lora_dropout=0.05,
|
| 100 |
+
bias="none",
|
| 101 |
+
task_type="CAUSAL_LM",
|
| 102 |
+
)
|
| 103 |
+
self.peft_model.add_adapter("second_adapter", peft_config_second)
|
| 104 |
+
|
| 105 |
+
self.peft_model.set_adapter("default")
|
| 106 |
+
self.peft_model.to(torch.bfloat16)
|
| 107 |
+
|
| 108 |
+
self.peft_model.set_requires_grad("default", requires_grad=True)
|
| 109 |
+
self.peft_model.set_requires_grad("second_adapter", requires_grad=False)
|
| 110 |
+
|
| 111 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None):
|
| 112 |
+
out1 = self.peft_model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
|
| 113 |
+
with self.peft_model.disable_adapter():
|
| 114 |
+
out2 = self.peft_model(input_ids=input_ids, attention_mask=attention_mask, labels=labels)
|
| 115 |
+
combined_loss = out1.loss + out2.loss
|
| 116 |
+
return (combined_loss,)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def test_training(model_id: str):
|
| 120 |
+
state = PartialState()
|
| 121 |
+
torch.manual_seed(42)
|
| 122 |
+
model = Model(model_id)
|
| 123 |
+
|
| 124 |
+
initial_base_weights = get_base_model_weights(model.peft_model)
|
| 125 |
+
initial_second_adapter_weights = get_adapter_weights(model.peft_model, "second_adapter")
|
| 126 |
+
|
| 127 |
+
if state.is_main_process:
|
| 128 |
+
print(f"Number of base model weight tensors: {len(initial_base_weights)}")
|
| 129 |
+
print(f"Number of second_adapter weight tensors: {len(initial_second_adapter_weights)}")
|
| 130 |
+
|
| 131 |
+
data = load_dataset("ybelkada/english_quotes_copy")
|
| 132 |
+
data = data.map(lambda samples: model.tokenizer(samples["quote"]), batched=True)
|
| 133 |
+
|
| 134 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 135 |
+
trainer = Trainer(
|
| 136 |
+
model=model,
|
| 137 |
+
train_dataset=data["train"],
|
| 138 |
+
optimizer_cls_and_kwargs=(torch.optim.SGD, {"lr": 2e-4}),
|
| 139 |
+
args=TrainingArguments(
|
| 140 |
+
per_device_train_batch_size=4,
|
| 141 |
+
gradient_accumulation_steps=4,
|
| 142 |
+
warmup_steps=2,
|
| 143 |
+
max_steps=5,
|
| 144 |
+
learning_rate=2e-4,
|
| 145 |
+
bf16=True,
|
| 146 |
+
logging_steps=1,
|
| 147 |
+
output_dir=tmp_dir,
|
| 148 |
+
),
|
| 149 |
+
data_collator=DataCollatorForLanguageModeling(model.tokenizer, mlm=False),
|
| 150 |
+
)
|
| 151 |
+
trainer.train()
|
| 152 |
+
with FSDP.summon_full_params(trainer.model):
|
| 153 |
+
final_base_weights = get_base_model_weights(model.peft_model)
|
| 154 |
+
final_second_adapter_weights = get_adapter_weights(model.peft_model, "second_adapter")
|
| 155 |
+
|
| 156 |
+
# Test to make sure that through this FSDP setup the base weights remain unchanged
|
| 157 |
+
# (i.e. adapter training doesn't somehow influence the base weights)
|
| 158 |
+
verify_weights_unchanged(initial_base_weights, final_base_weights, "Base model")
|
| 159 |
+
verify_weights_unchanged(initial_second_adapter_weights, final_second_adapter_weights, "second_adapter")
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def main(model_id: str):
|
| 163 |
+
test_training(model_id)
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
if __name__ == "__main__":
|
| 167 |
+
parser = argparse.ArgumentParser()
|
| 168 |
+
parser.add_argument("--model_id", type=str, required=False, default="Qwen/Qwen3-0.6B")
|
| 169 |
+
args = parser.parse_args()
|
| 170 |
+
main(model_id=args.model_id)
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/training/deepspeed_config.yaml
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
deepspeed_config:
|
| 4 |
+
deepspeed_multinode_launcher: standard
|
| 5 |
+
offload_optimizer_device: none
|
| 6 |
+
offload_param_device: none
|
| 7 |
+
zero3_init_flag: true
|
| 8 |
+
zero3_save_16bit_model: true
|
| 9 |
+
zero_stage: 3
|
| 10 |
+
distributed_type: DEEPSPEED
|
| 11 |
+
downcast_bf16: 'no'
|
| 12 |
+
machine_rank: 0
|
| 13 |
+
main_training_function: main
|
| 14 |
+
mixed_precision: bf16
|
| 15 |
+
num_machines: 1
|
| 16 |
+
num_processes: 2
|
| 17 |
+
rdzv_backend: static
|
| 18 |
+
same_network: true
|
| 19 |
+
tpu_env: []
|
| 20 |
+
tpu_use_cluster: false
|
| 21 |
+
tpu_use_sudo: false
|
| 22 |
+
use_cpu: false
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/training/fsdp2_config.yaml
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
distributed_type: FSDP
|
| 4 |
+
downcast_bf16: 'no'
|
| 5 |
+
fsdp_config:
|
| 6 |
+
fsdp_version: 2
|
| 7 |
+
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
|
| 8 |
+
fsdp_cpu_ram_efficient_loading: false
|
| 9 |
+
fsdp_offload_params: false
|
| 10 |
+
fsdp_reshard_after_forward: true
|
| 11 |
+
fsdp_state_dict_type: SHARDED_STATE_DICT
|
| 12 |
+
machine_rank: 0
|
| 13 |
+
main_training_function: main
|
| 14 |
+
mixed_precision: bf16
|
| 15 |
+
num_machines: 1
|
| 16 |
+
num_processes: 2
|
| 17 |
+
rdzv_backend: static
|
| 18 |
+
same_network: true
|
| 19 |
+
tpu_env: []
|
| 20 |
+
tpu_use_cluster: false
|
| 21 |
+
tpu_use_sudo: false
|
| 22 |
+
use_cpu: false
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/training/fsdp_config.yaml
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
distributed_type: FSDP
|
| 4 |
+
downcast_bf16: 'no'
|
| 5 |
+
fsdp_config:
|
| 6 |
+
fsdp_auto_wrap_policy: TRANSFORMER_BASED_WRAP
|
| 7 |
+
fsdp_backward_prefetch: BACKWARD_PRE
|
| 8 |
+
fsdp_cpu_ram_efficient_loading: false
|
| 9 |
+
fsdp_forward_prefetch: false
|
| 10 |
+
fsdp_offload_params: false
|
| 11 |
+
fsdp_sharding_strategy: FULL_SHARD
|
| 12 |
+
fsdp_state_dict_type: SHARDED_STATE_DICT
|
| 13 |
+
fsdp_sync_module_states: true
|
| 14 |
+
fsdp_use_orig_params: true
|
| 15 |
+
machine_rank: 0
|
| 16 |
+
main_training_function: main
|
| 17 |
+
mixed_precision: bf16
|
| 18 |
+
num_machines: 1
|
| 19 |
+
num_processes: 2
|
| 20 |
+
rdzv_backend: static
|
| 21 |
+
same_network: true
|
| 22 |
+
tpu_env: []
|
| 23 |
+
tpu_use_cluster: false
|
| 24 |
+
tpu_use_sudo: false
|
| 25 |
+
use_cpu: false
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/training/lora_tp.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2026-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 |
+
Test that a LoRA model on a tensor-parallel base model can overfit a fixed batch.
|
| 17 |
+
|
| 18 |
+
Run with:
|
| 19 |
+
torchrun --nproc_per_node=2 tests/training/lora_tp.py --model_id <model_id>
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
import argparse
|
| 23 |
+
import logging
|
| 24 |
+
import sys
|
| 25 |
+
import time
|
| 26 |
+
|
| 27 |
+
import torch
|
| 28 |
+
import torch.distributed as dist
|
| 29 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, set_seed
|
| 30 |
+
from transformers.testing_utils import ColoredFormatter, Colors
|
| 31 |
+
|
| 32 |
+
from peft import LoraConfig, get_peft_model
|
| 33 |
+
from peft.import_utils import is_transformers_ge_v5_4_0
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
TINY_MODEL_ID = "peft-internal-testing/zephyr-smol_llama-100m-sft-full"
|
| 37 |
+
TARGET_MODULES = ["q_proj", "k_proj", "v_proj", "o_proj"]
|
| 38 |
+
STEPS = 20
|
| 39 |
+
BATCH_SIZE = 4
|
| 40 |
+
LEARNING_RATE = 1e-3
|
| 41 |
+
LOSS_REDUCTION_THRESHOLD = 0.9
|
| 42 |
+
GRAD_NORM_REDUCTION_THRESHOLD = 0.9
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def init_test_logger(rank):
|
| 46 |
+
# Taken from transformers.testing_utils.init_test_logger but modified:
|
| 47 |
+
# 1. To use the proper logger name for this test file
|
| 48 |
+
# 2. To handle multiprocessing without duplicate logs
|
| 49 |
+
logger = logging.getLogger("peft.training_test")
|
| 50 |
+
level = logging.INFO if rank == 0 else 100 # Higher than CRITICAL to suppress logs from non-master processes
|
| 51 |
+
logger.setLevel(level)
|
| 52 |
+
|
| 53 |
+
# Only add handler if not already present (avoid duplicate handlers on repeated calls)
|
| 54 |
+
if not logger.handlers:
|
| 55 |
+
# Use stderr instead of stdout - pytest-xdist captures stdout which can cause deadlocks
|
| 56 |
+
ch = logging.StreamHandler(sys.stderr)
|
| 57 |
+
ch.setLevel(logging.INFO)
|
| 58 |
+
|
| 59 |
+
# Use colored formatter if terminal supports it, plain otherwise
|
| 60 |
+
if sys.stderr.isatty():
|
| 61 |
+
formatter = ColoredFormatter(datefmt="%Y-%m-%d %H:%M:%S")
|
| 62 |
+
else:
|
| 63 |
+
formatter = logging.Formatter(
|
| 64 |
+
"%(asctime)s - %(name)s - %(levelname)s - %(message)s", datefmt="%Y-%m-%d %H:%M:%S"
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
ch.setFormatter(formatter)
|
| 68 |
+
logger.addHandler(ch)
|
| 69 |
+
|
| 70 |
+
logger.propagate = False # Don't propagate to root logger to avoid duplicate output
|
| 71 |
+
return logger
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def main(model_id: str, target_modules: list[str]):
|
| 75 |
+
dist.init_process_group(backend="nccl")
|
| 76 |
+
rank = dist.get_rank()
|
| 77 |
+
logger = init_test_logger(rank)
|
| 78 |
+
set_seed(42)
|
| 79 |
+
|
| 80 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 81 |
+
model = AutoModelForCausalLM.from_pretrained(model_id, tp_plan="auto")
|
| 82 |
+
config = model.config
|
| 83 |
+
|
| 84 |
+
torch.cuda.set_device(rank)
|
| 85 |
+
device = torch.device("cuda", rank)
|
| 86 |
+
model = model.to(device)
|
| 87 |
+
|
| 88 |
+
lora_config = LoraConfig(r=4, target_modules=target_modules)
|
| 89 |
+
model = get_peft_model(model, lora_config)
|
| 90 |
+
model.train()
|
| 91 |
+
|
| 92 |
+
sample_input = tokenizer("Paris is the most beautiful city in the world.", return_tensors="pt")
|
| 93 |
+
batch = {k: v.repeat(BATCH_SIZE, 1).to(device) for k, v in sample_input.items()}
|
| 94 |
+
batch["labels"] = batch["input_ids"].clone()
|
| 95 |
+
|
| 96 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE, weight_decay=0.0, betas=(0.9, 0.999))
|
| 97 |
+
|
| 98 |
+
initial_loss = None
|
| 99 |
+
final_loss = None
|
| 100 |
+
initial_grad_norm = None
|
| 101 |
+
final_grad_norm = None
|
| 102 |
+
training_start = time.perf_counter()
|
| 103 |
+
|
| 104 |
+
for step in range(1, STEPS + 1):
|
| 105 |
+
step_start = time.perf_counter()
|
| 106 |
+
|
| 107 |
+
optimizer.zero_grad()
|
| 108 |
+
outputs = model(**batch)
|
| 109 |
+
loss = outputs.loss
|
| 110 |
+
|
| 111 |
+
if initial_loss is None:
|
| 112 |
+
initial_loss = loss.item()
|
| 113 |
+
final_loss = loss.item()
|
| 114 |
+
|
| 115 |
+
loss.backward()
|
| 116 |
+
|
| 117 |
+
grad_norm = torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
|
| 118 |
+
|
| 119 |
+
if initial_grad_norm is None:
|
| 120 |
+
initial_grad_norm = grad_norm.item()
|
| 121 |
+
final_grad_norm = grad_norm.item()
|
| 122 |
+
|
| 123 |
+
optimizer.step()
|
| 124 |
+
|
| 125 |
+
step_time = time.perf_counter() - step_start
|
| 126 |
+
logger.info(
|
| 127 |
+
f"{Colors.CYAN}step:{Colors.RESET} {step} "
|
| 128 |
+
f"{Colors.GREEN}loss:{Colors.RESET} {loss.item():7.4f} "
|
| 129 |
+
f"{Colors.YELLOW}grad_norm:{Colors.RESET} {grad_norm.item():6.4f} "
|
| 130 |
+
f"{Colors.DIM}step_time:{Colors.RESET} {step_time:.3f}s"
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
training_time = time.perf_counter() - training_start
|
| 134 |
+
|
| 135 |
+
logger.info("-" * 70)
|
| 136 |
+
logger.info(f"{Colors.BOLD}Training completed{Colors.RESET}")
|
| 137 |
+
logger.info(f"Total training time: {training_time:.2f}s")
|
| 138 |
+
logger.info(f"Total steps: {STEPS}")
|
| 139 |
+
|
| 140 |
+
loss_reduction = (initial_loss - final_loss) / initial_loss * 100
|
| 141 |
+
logger.info(f"{Colors.BOLD}Loss metrics:{Colors.RESET}")
|
| 142 |
+
logger.info(f" {Colors.CYAN}initial_loss:{Colors.RESET} {initial_loss:.4f}")
|
| 143 |
+
logger.info(f" {Colors.CYAN}final_loss:{Colors.RESET} {final_loss:.4f}")
|
| 144 |
+
logger.info(f" {Colors.CYAN}loss_reduction:{Colors.RESET} {loss_reduction:.1f}%")
|
| 145 |
+
|
| 146 |
+
grad_norm_reduction = (initial_grad_norm - final_grad_norm) / initial_grad_norm * 100
|
| 147 |
+
logger.info(f"{Colors.BOLD}Grad norm metrics:{Colors.RESET}")
|
| 148 |
+
logger.info(f" {Colors.CYAN}initial_grad_norm:{Colors.RESET} {initial_grad_norm:.4f}")
|
| 149 |
+
logger.info(f" {Colors.CYAN}final_grad_norm:{Colors.RESET} {final_grad_norm:.4f}")
|
| 150 |
+
logger.info(f" {Colors.CYAN}grad_norm_reduction:{Colors.RESET} {grad_norm_reduction:.1f}%")
|
| 151 |
+
|
| 152 |
+
logger.info("-" * 70)
|
| 153 |
+
logger.info(f"{Colors.BOLD}Testing generation{Colors.RESET}")
|
| 154 |
+
|
| 155 |
+
model.eval()
|
| 156 |
+
expected_tokens = batch["input_ids"][0].tolist()
|
| 157 |
+
prompt_ids = torch.tensor([[expected_tokens[0]]], dtype=torch.long)
|
| 158 |
+
prompt_ids = prompt_ids.to(device)
|
| 159 |
+
num_tokens_to_generate = len(expected_tokens) - 1
|
| 160 |
+
|
| 161 |
+
logger.info(f"Prompt: {tokenizer.decode([expected_tokens[0]])}")
|
| 162 |
+
|
| 163 |
+
with torch.no_grad():
|
| 164 |
+
generated_ids = model.generate(
|
| 165 |
+
prompt_ids,
|
| 166 |
+
max_new_tokens=num_tokens_to_generate,
|
| 167 |
+
do_sample=False,
|
| 168 |
+
pad_token_id=config.pad_token_id if hasattr(config, "pad_token_id") else 0,
|
| 169 |
+
eos_token_id=0,
|
| 170 |
+
use_cache=False,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
generated_tokens = generated_ids[0].tolist()
|
| 174 |
+
generation_matches = generated_tokens == expected_tokens
|
| 175 |
+
|
| 176 |
+
if generation_matches:
|
| 177 |
+
logger.info(f"Expected: {Colors.GREEN}{tokenizer.decode(expected_tokens)}{Colors.RESET}")
|
| 178 |
+
logger.info(f"Generated: {Colors.GREEN}{tokenizer.decode(generated_tokens)}{Colors.RESET}")
|
| 179 |
+
logger.info(f"{Colors.GREEN}✓ Generation matches training sequence!{Colors.RESET}")
|
| 180 |
+
else:
|
| 181 |
+
logger.info(f"Expected: {Colors.GREEN}{tokenizer.decode(expected_tokens)}{Colors.RESET}")
|
| 182 |
+
logger.info(f"Generated: {Colors.RED}{tokenizer.decode(generated_tokens)}{Colors.RESET}")
|
| 183 |
+
matches = sum(1 for g, e in zip(generated_tokens, expected_tokens) if g == e)
|
| 184 |
+
logger.info(
|
| 185 |
+
f"{Colors.YELLOW}✗ Generation mismatch: {matches}/{len(expected_tokens)} tokens match{Colors.RESET}"
|
| 186 |
+
)
|
| 187 |
+
|
| 188 |
+
logger.info("-" * 70)
|
| 189 |
+
logger.info(f"{Colors.BOLD}Running assertions{Colors.RESET}")
|
| 190 |
+
|
| 191 |
+
loss_reduction_ratio = (initial_loss - final_loss) / initial_loss
|
| 192 |
+
assert loss_reduction_ratio >= LOSS_REDUCTION_THRESHOLD, (
|
| 193 |
+
f"Expected loss to decrease by at least {LOSS_REDUCTION_THRESHOLD * 100:.0f}%, got {loss_reduction:.1f}%"
|
| 194 |
+
)
|
| 195 |
+
logger.info(f"{Colors.GREEN}✓ Loss decreased by more than {LOSS_REDUCTION_THRESHOLD * 100:.0f}%{Colors.RESET}")
|
| 196 |
+
|
| 197 |
+
grad_norm_reduction_ratio = (initial_grad_norm - final_grad_norm) / initial_grad_norm
|
| 198 |
+
assert grad_norm_reduction_ratio >= GRAD_NORM_REDUCTION_THRESHOLD, (
|
| 199 |
+
f"Expected grad_norm to decrease by at least {GRAD_NORM_REDUCTION_THRESHOLD * 100:.0f}%, "
|
| 200 |
+
f"got {grad_norm_reduction:.1f}%"
|
| 201 |
+
)
|
| 202 |
+
logger.info(
|
| 203 |
+
f"{Colors.GREEN}✓ Grad norm decreased by more than {GRAD_NORM_REDUCTION_THRESHOLD * 100:.0f}%{Colors.RESET}"
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
assert generation_matches, "Expected model to generate the training sequence after overfitting"
|
| 207 |
+
logger.info(f"{Colors.GREEN}✓ Generated sequence matches training sequence{Colors.RESET}")
|
| 208 |
+
|
| 209 |
+
dist.destroy_process_group()
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
if __name__ == "__main__":
|
| 213 |
+
parser = argparse.ArgumentParser()
|
| 214 |
+
parser.add_argument("--model_id", type=str, required=False, default=TINY_MODEL_ID)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--target_modules",
|
| 217 |
+
type=str,
|
| 218 |
+
nargs="+",
|
| 219 |
+
required=False,
|
| 220 |
+
default=TARGET_MODULES,
|
| 221 |
+
help="List of target modules for LoRA adaptation",
|
| 222 |
+
)
|
| 223 |
+
args = parser.parse_args()
|
| 224 |
+
if not is_transformers_ge_v5_4_0:
|
| 225 |
+
print("This test requires transformers v5.4.0 or higher")
|
| 226 |
+
else:
|
| 227 |
+
main(model_id=args.model_id, target_modules=args.target_modules)
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/training/tp_config.yaml
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
compute_environment: LOCAL_MACHINE
|
| 2 |
+
debug: false
|
| 3 |
+
distributed_type: MULTI_GPU
|
| 4 |
+
machine_rank: 0
|
| 5 |
+
main_training_function: main
|
| 6 |
+
mixed_precision: bf16
|
| 7 |
+
num_machines: 1
|
| 8 |
+
num_processes: 2
|
| 9 |
+
use_cpu: false
|
tasks/tasksmith-a27f5bd16532/tests/source/tests/training/training.py
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 is a simple example of training a model with QLoRA.
|
| 17 |
+
"""
|
| 18 |
+
|
| 19 |
+
import argparse
|
| 20 |
+
import os
|
| 21 |
+
import tempfile
|
| 22 |
+
from typing import Literal
|
| 23 |
+
|
| 24 |
+
import torch
|
| 25 |
+
from accelerate import PartialState
|
| 26 |
+
from datasets import load_dataset
|
| 27 |
+
from transformers import (
|
| 28 |
+
AutoModelForCausalLM,
|
| 29 |
+
AutoTokenizer,
|
| 30 |
+
BitsAndBytesConfig,
|
| 31 |
+
DataCollatorForLanguageModeling,
|
| 32 |
+
Trainer,
|
| 33 |
+
TrainingArguments,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
from peft import LoraConfig, get_peft_model
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def print_if_process_zero(*args, **kwargs):
|
| 40 |
+
PartialState().print(*args, **kwargs)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def main(
|
| 44 |
+
model_id: str,
|
| 45 |
+
quant: Literal["4bit", "8bit"] | None,
|
| 46 |
+
target_modules: list[str] | None,
|
| 47 |
+
target_parameters: list[str] | None,
|
| 48 |
+
):
|
| 49 |
+
if target_modules == ["all-linear"]:
|
| 50 |
+
target_modules = "all-linear"
|
| 51 |
+
|
| 52 |
+
print_if_process_zero("=" * 50)
|
| 53 |
+
print_if_process_zero(f"{model_id=}, {quant=}, {target_modules=} {target_parameters=}")
|
| 54 |
+
print_if_process_zero("=" * 50)
|
| 55 |
+
|
| 56 |
+
data = load_dataset("ybelkada/english_quotes_copy")
|
| 57 |
+
|
| 58 |
+
is_fsdp = "FSDP_VERSION" in os.environ
|
| 59 |
+
if quant == "4bit":
|
| 60 |
+
quant_config = BitsAndBytesConfig(
|
| 61 |
+
load_in_4bit=True,
|
| 62 |
+
bnb_4bit_quant_type="nf4",
|
| 63 |
+
bnb_4bit_compute_type="bfloat16",
|
| 64 |
+
bnb_4bit_quant_storage="bfloat16",
|
| 65 |
+
bnb_4bit_use_double_quant=True,
|
| 66 |
+
)
|
| 67 |
+
elif quant == "8bit":
|
| 68 |
+
if is_fsdp:
|
| 69 |
+
raise ValueError("QLoRA with 8bit bnb is not supported for FSDP.")
|
| 70 |
+
quant_config = BitsAndBytesConfig(load_in_8bit=True)
|
| 71 |
+
elif quant is None:
|
| 72 |
+
quant_config = None
|
| 73 |
+
else:
|
| 74 |
+
raise ValueError(f"Unsupported quantization: {quant}, expected one of '4bit', '8bit', or None")
|
| 75 |
+
|
| 76 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
| 77 |
+
if not tokenizer.pad_token:
|
| 78 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 79 |
+
|
| 80 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 81 |
+
model_id, quantization_config=quant_config, dtype=torch.bfloat16, device_map={"": PartialState().process_index}
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
peft_config = LoraConfig(
|
| 85 |
+
r=16,
|
| 86 |
+
lora_alpha=32,
|
| 87 |
+
target_modules=target_modules,
|
| 88 |
+
target_parameters=target_parameters,
|
| 89 |
+
lora_dropout=0.05,
|
| 90 |
+
bias="none",
|
| 91 |
+
task_type="CAUSAL_LM",
|
| 92 |
+
)
|
| 93 |
+
model = get_peft_model(model, peft_config)
|
| 94 |
+
print_if_process_zero(model)
|
| 95 |
+
if PartialState().is_local_main_process:
|
| 96 |
+
model.print_trainable_parameters()
|
| 97 |
+
|
| 98 |
+
data = data.map(lambda samples: tokenizer(samples["quote"]), batched=True)
|
| 99 |
+
|
| 100 |
+
with tempfile.TemporaryDirectory() as tmp_dir:
|
| 101 |
+
trainer = Trainer(
|
| 102 |
+
model=model,
|
| 103 |
+
train_dataset=data["train"],
|
| 104 |
+
optimizer_cls_and_kwargs=(torch.optim.SGD, {"lr": 2e-4}),
|
| 105 |
+
# FSDP with AdamW:
|
| 106 |
+
# > RuntimeError: output with shape [] doesn't match the broadcast shape [1]
|
| 107 |
+
args=TrainingArguments(
|
| 108 |
+
per_device_train_batch_size=4,
|
| 109 |
+
gradient_accumulation_steps=4,
|
| 110 |
+
warmup_steps=2,
|
| 111 |
+
max_steps=15,
|
| 112 |
+
learning_rate=2e-4,
|
| 113 |
+
bf16=True,
|
| 114 |
+
logging_steps=5,
|
| 115 |
+
output_dir=tmp_dir,
|
| 116 |
+
),
|
| 117 |
+
data_collator=DataCollatorForLanguageModeling(tokenizer, mlm=False),
|
| 118 |
+
)
|
| 119 |
+
trainer.train()
|
| 120 |
+
|
| 121 |
+
if trainer.is_fsdp_enabled:
|
| 122 |
+
trainer.accelerator.state.fsdp_plugin.set_state_dict_type("FULL_STATE_DICT")
|
| 123 |
+
trainer.save_model(tmp_dir)
|
| 124 |
+
|
| 125 |
+
# some checks
|
| 126 |
+
if PartialState().is_local_main_process:
|
| 127 |
+
files = os.listdir(tmp_dir)
|
| 128 |
+
assert "adapter_model.safetensors" in files
|
| 129 |
+
assert "adapter_config.json" in files
|
| 130 |
+
|
| 131 |
+
final_log = trainer.state.log_history[-1]
|
| 132 |
+
assert final_log["train_loss"] < 10.0, f"Final loss is too high: {final_log['loss']}"
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
if __name__ == "__main__":
|
| 136 |
+
parser = argparse.ArgumentParser()
|
| 137 |
+
parser.add_argument("--model_id", type=str, required=False, default="Qwen/Qwen3-0.6B")
|
| 138 |
+
parser.add_argument("--quant", type=str, choices=["4bit", "8bit"], required=False, default=None)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--target_modules",
|
| 141 |
+
type=str,
|
| 142 |
+
nargs="+",
|
| 143 |
+
required=False,
|
| 144 |
+
default=None,
|
| 145 |
+
help="List of target modules for LoRA adaptation",
|
| 146 |
+
)
|
| 147 |
+
parser.add_argument(
|
| 148 |
+
"--target_parameters",
|
| 149 |
+
type=str,
|
| 150 |
+
nargs="+",
|
| 151 |
+
required=False,
|
| 152 |
+
default=None,
|
| 153 |
+
help="List of target modules for LoRA adaptation",
|
| 154 |
+
)
|
| 155 |
+
args = parser.parse_args()
|
| 156 |
+
main(
|
| 157 |
+
model_id=args.model_id,
|
| 158 |
+
quant=args.quant,
|
| 159 |
+
target_modules=args.target_modules,
|
| 160 |
+
target_parameters=args.target_parameters,
|
| 161 |
+
)
|
tasks/tasksmith-a27f5bd16532/tests/test.sh
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/bin/sh
|
| 2 |
+
set -eu
|
| 3 |
+
exec /opt/tasksmith-venv/bin/python -I /tests/grade.py
|
tasks/tasksmith-a27f5bd16532/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-a27f5bd16532/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-ae8f12dc63d0/environment/Dockerfile
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
WORKDIR /workspace
|
| 3 |
+
RUN python -m pip install --no-cache-dir setuptools==78.1.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu torch==2.11.0+cpu numpy==2.5.3 packaging==26.3 psutil==7.2.2 parameterized==0.9.0 pytest==8.4.2
|
| 4 |
+
COPY source /workspace
|
| 5 |
+
RUN python -m pip install --no-cache-dir -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-ae8f12dc63d0/environment/source/.devcontainer/devcontainer.json
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// File only needed for VSCode users to have proper Docker based interpreters
|
| 2 |
+
{
|
| 3 |
+
"name": "accelerate_dev_environment",
|
| 4 |
+
"build": {
|
| 5 |
+
// ACTION NEEDED: comment/uncomment the relevant line depending on whether you are in a CPU/GPU environment
|
| 6 |
+
"dockerfile": "../docker/accelerate-cpu/Dockerfile"
|
| 7 |
+
// "dockerfile": "../docker/accelerate-gpu/Dockerfile"
|
| 8 |
+
},
|
| 9 |
+
"runArgs": [
|
| 10 |
+
// ACTION NEEDED: uncomment the next line if your local machine has GPUs available
|
| 11 |
+
// "--gpus", "all",
|
| 12 |
+
// Enable the docker container to access system resources
|
| 13 |
+
"--ipc", "host"
|
| 14 |
+
],
|
| 15 |
+
"remoteEnv": {
|
| 16 |
+
"PYTHONPATH": "${containerEnv:PATH}:${containerWorkspaceFolder}"
|
| 17 |
+
},
|
| 18 |
+
"customizations": {
|
| 19 |
+
"vscode": {
|
| 20 |
+
"extensions": [
|
| 21 |
+
// Ensure we have IntelliSense in VSCode when running inside container
|
| 22 |
+
"ms-python.python"
|
| 23 |
+
]
|
| 24 |
+
}
|
| 25 |
+
},
|
| 26 |
+
"workspaceFolder": "/workspaces/accelerate",
|
| 27 |
+
// Need git for VSCode to color code modifications. Only runs when building environment.
|
| 28 |
+
"onCreateCommand": "apt-get update && apt-get install -y git && pip install -e '.[dev]'"
|
| 29 |
+
}
|
tasks/tasksmith-ae8f12dc63d0/environment/source/.gitignore
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
# ruff
|
| 144 |
+
.ruff_cache
|
tasks/tasksmith-ae8f12dc63d0/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.2.1
|
| 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.5.0
|
| 11 |
+
hooks:
|
| 12 |
+
- id: check-merge-conflict
|
| 13 |
+
- id: check-yaml
|
tasks/tasksmith-ae8f12dc63d0/environment/source/CODE_OF_CONDUCT.md
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
# Contributor Covenant Code of Conduct
|
| 3 |
+
|
| 4 |
+
## Our Pledge
|
| 5 |
+
|
| 6 |
+
We as members, contributors, and leaders pledge to make participation in our
|
| 7 |
+
community a harassment-free experience for everyone, regardless of age, body
|
| 8 |
+
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
| 9 |
+
identity and expression, level of experience, education, socio-economic status,
|
| 10 |
+
nationality, personal appearance, race, religion, or sexual identity
|
| 11 |
+
and orientation.
|
| 12 |
+
|
| 13 |
+
We pledge to act and interact in ways that contribute to an open, welcoming,
|
| 14 |
+
diverse, inclusive, and healthy community.
|
| 15 |
+
|
| 16 |
+
## Our Standards
|
| 17 |
+
|
| 18 |
+
Examples of behavior that contributes to a positive environment for our
|
| 19 |
+
community include:
|
| 20 |
+
|
| 21 |
+
* Demonstrating empathy and kindness toward other people
|
| 22 |
+
* Being respectful of differing opinions, viewpoints, and experiences
|
| 23 |
+
* Giving and gracefully accepting constructive feedback
|
| 24 |
+
* Accepting responsibility and apologizing to those affected by our mistakes,
|
| 25 |
+
and learning from the experience
|
| 26 |
+
* Focusing on what is best not just for us as individuals, but for the
|
| 27 |
+
overall community
|
| 28 |
+
|
| 29 |
+
Examples of unacceptable behavior include:
|
| 30 |
+
|
| 31 |
+
* The use of sexualized language or imagery, and sexual attention or
|
| 32 |
+
advances of any kind
|
| 33 |
+
* Trolling, insulting or derogatory comments, and personal or political attacks
|
| 34 |
+
* Public or private harassment
|
| 35 |
+
* Publishing others' private information, such as a physical or email
|
| 36 |
+
address, without their explicit permission
|
| 37 |
+
* Other conduct which could reasonably be considered inappropriate in a
|
| 38 |
+
professional setting
|
| 39 |
+
|
| 40 |
+
## Enforcement Responsibilities
|
| 41 |
+
|
| 42 |
+
Community leaders are responsible for clarifying and enforcing our standards of
|
| 43 |
+
acceptable behavior and will take appropriate and fair corrective action in
|
| 44 |
+
response to any behavior that they deem inappropriate, threatening, offensive,
|
| 45 |
+
or harmful.
|
| 46 |
+
|
| 47 |
+
Community leaders have the right and responsibility to remove, edit, or reject
|
| 48 |
+
comments, commits, code, wiki edits, issues, and other contributions that are
|
| 49 |
+
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
| 50 |
+
decisions when appropriate.
|
| 51 |
+
|
| 52 |
+
## Scope
|
| 53 |
+
|
| 54 |
+
This Code of Conduct applies within all community spaces, and also applies when
|
| 55 |
+
an individual is officially representing the community in public spaces.
|
| 56 |
+
Examples of representing our community include using an official e-mail address,
|
| 57 |
+
posting via an official social media account, or acting as an appointed
|
| 58 |
+
representative at an online or offline event.
|
| 59 |
+
|
| 60 |
+
## Enforcement
|
| 61 |
+
|
| 62 |
+
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
| 63 |
+
reported to the community leaders responsible for enforcement at
|
| 64 |
+
feedback@huggingface.co.
|
| 65 |
+
All complaints will be reviewed and investigated promptly and fairly.
|
| 66 |
+
|
| 67 |
+
All community leaders are obligated to respect the privacy and security of the
|
| 68 |
+
reporter of any incident.
|
| 69 |
+
|
| 70 |
+
## Enforcement Guidelines
|
| 71 |
+
|
| 72 |
+
Community leaders will follow these Community Impact Guidelines in determining
|
| 73 |
+
the consequences for any action they deem in violation of this Code of Conduct:
|
| 74 |
+
|
| 75 |
+
### 1. Correction
|
| 76 |
+
|
| 77 |
+
**Community Impact**: Use of inappropriate language or other behavior deemed
|
| 78 |
+
unprofessional or unwelcome in the community.
|
| 79 |
+
|
| 80 |
+
**Consequence**: A private, written warning from community leaders, providing
|
| 81 |
+
clarity around the nature of the violation and an explanation of why the
|
| 82 |
+
behavior was inappropriate. A public apology may be requested.
|
| 83 |
+
|
| 84 |
+
### 2. Warning
|
| 85 |
+
|
| 86 |
+
**Community Impact**: A violation through a single incident or series
|
| 87 |
+
of actions.
|
| 88 |
+
|
| 89 |
+
**Consequence**: A warning with consequences for continued behavior. No
|
| 90 |
+
interaction with the people involved, including unsolicited interaction with
|
| 91 |
+
those enforcing the Code of Conduct, for a specified period of time. This
|
| 92 |
+
includes avoiding interactions in community spaces as well as external channels
|
| 93 |
+
like social media. Violating these terms may lead to a temporary or
|
| 94 |
+
permanent ban.
|
| 95 |
+
|
| 96 |
+
### 3. Temporary Ban
|
| 97 |
+
|
| 98 |
+
**Community Impact**: A serious violation of community standards, including
|
| 99 |
+
sustained inappropriate behavior.
|
| 100 |
+
|
| 101 |
+
**Consequence**: A temporary ban from any sort of interaction or public
|
| 102 |
+
communication with the community for a specified period of time. No public or
|
| 103 |
+
private interaction with the people involved, including unsolicited interaction
|
| 104 |
+
with those enforcing the Code of Conduct, is allowed during this period.
|
| 105 |
+
Violating these terms may lead to a permanent ban.
|
| 106 |
+
|
| 107 |
+
### 4. Permanent Ban
|
| 108 |
+
|
| 109 |
+
**Community Impact**: Demonstrating a pattern of violation of community
|
| 110 |
+
standards, including sustained inappropriate behavior, harassment of an
|
| 111 |
+
individual, or aggression toward or disparagement of classes of individuals.
|
| 112 |
+
|
| 113 |
+
**Consequence**: A permanent ban from any sort of public interaction within
|
| 114 |
+
the community.
|
| 115 |
+
|
| 116 |
+
## Attribution
|
| 117 |
+
|
| 118 |
+
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
| 119 |
+
version 2.0, available at
|
| 120 |
+
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
| 121 |
+
|
| 122 |
+
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
| 123 |
+
enforcement ladder](https://github.com/mozilla/diversity).
|
| 124 |
+
|
| 125 |
+
[homepage]: https://www.contributor-covenant.org
|
| 126 |
+
|
| 127 |
+
For answers to common questions about this code of conduct, see the FAQ at
|
| 128 |
+
https://www.contributor-covenant.org/faq. Translations are available at
|
| 129 |
+
https://www.contributor-covenant.org/translations.
|
tasks/tasksmith-ae8f12dc63d0/environment/source/CONTRIBUTING.md
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!---
|
| 2 |
+
Copyright 2022 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 |
+
# How to contribute to 🤗 Accelerate?
|
| 18 |
+
|
| 19 |
+
Everyone is welcome to contribute, and we value everybody's contribution. Code
|
| 20 |
+
is thus not the only way to help the community. Answering questions, helping
|
| 21 |
+
others, reaching out and improving the documentations are immensely valuable to
|
| 22 |
+
the community.
|
| 23 |
+
|
| 24 |
+
It also helps us if you spread the word: reference the library from blog posts
|
| 25 |
+
on the awesome projects it made possible, shout out on Twitter every time it has
|
| 26 |
+
helped you, or simply star the repo to say "thank you".
|
| 27 |
+
|
| 28 |
+
Whichever way you choose to contribute, please be mindful to respect our
|
| 29 |
+
[code of conduct](https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md).
|
| 30 |
+
|
| 31 |
+
## You can contribute in so many ways!
|
| 32 |
+
|
| 33 |
+
Some of the ways you can contribute to Accelerate:
|
| 34 |
+
* Fixing outstanding issues with the existing code;
|
| 35 |
+
* Contributing to the examples or to the documentation;
|
| 36 |
+
* Submitting issues related to bugs or desired new features.
|
| 37 |
+
|
| 38 |
+
## Submitting a new issue or feature request
|
| 39 |
+
|
| 40 |
+
Do your best to follow these guidelines when submitting an issue or a feature
|
| 41 |
+
request. It will make it easier for us to come back to you quickly and with good
|
| 42 |
+
feedback.
|
| 43 |
+
|
| 44 |
+
### Did you find a bug?
|
| 45 |
+
|
| 46 |
+
The 🤗 Accelerate library is robust and reliable thanks to the users who notify us of
|
| 47 |
+
the problems they encounter. So thank you for reporting an issue.
|
| 48 |
+
|
| 49 |
+
First, we would really appreciate it if you could **make sure the bug was not
|
| 50 |
+
already reported** (use the search bar on Github under Issues).
|
| 51 |
+
|
| 52 |
+
Did not find it? :( So we can act quickly on it, please follow these steps:
|
| 53 |
+
|
| 54 |
+
* Include your **OS type and version**, the versions of **Python** and **PyTorch**.
|
| 55 |
+
* A short, self-contained, code snippet that allows us to reproduce the bug in
|
| 56 |
+
less than 30s;
|
| 57 |
+
* Provide the with your Accelerate configuration (located by default in `~/.cache/huggingface/accelerate/default_config.yaml`)
|
| 58 |
+
|
| 59 |
+
### Do you want a new feature?
|
| 60 |
+
|
| 61 |
+
A good feature request addresses the following points:
|
| 62 |
+
|
| 63 |
+
1. Motivation first:
|
| 64 |
+
* Is it related to a problem/frustration with the library? If so, please explain
|
| 65 |
+
why. Providing a code snippet that demonstrates the problem is best.
|
| 66 |
+
* Is it related to something you would need for a project? We'd love to hear
|
| 67 |
+
about it!
|
| 68 |
+
* Is it something you worked on and think could benefit the community?
|
| 69 |
+
Awesome! Tell us what problem it solved for you.
|
| 70 |
+
2. Write a *full paragraph* describing the feature;
|
| 71 |
+
3. Provide a **code snippet** that demonstrates its future use;
|
| 72 |
+
4. In case this is related to a paper, please attach a link;
|
| 73 |
+
5. Attach any additional information (drawings, screenshots, etc.) you think may help.
|
| 74 |
+
|
| 75 |
+
If your issue is well written we're already 80% of the way there by the time you
|
| 76 |
+
post it.
|
| 77 |
+
|
| 78 |
+
## Submitting a pull request (PR)
|
| 79 |
+
|
| 80 |
+
Before writing code, we strongly advise you to search through the existing PRs or
|
| 81 |
+
issues to make sure that nobody is already working on the same thing. If you are
|
| 82 |
+
unsure, it is always a good idea to open an issue to get some feedback.
|
| 83 |
+
|
| 84 |
+
You will need basic `git` proficiency to be able to contribute to
|
| 85 |
+
🤗 Accelerate. `git` is not the easiest tool to use but it has the greatest
|
| 86 |
+
manual. Type `git --help` in a shell and enjoy. If you prefer books, [Pro
|
| 87 |
+
Git](https://git-scm.com/book/en/v2) is a very good reference.
|
| 88 |
+
|
| 89 |
+
Follow these steps to start contributing:
|
| 90 |
+
|
| 91 |
+
1. Fork the [repository](https://github.com/huggingface/accelerate) by
|
| 92 |
+
clicking on the 'Fork' button on the repository's page. This creates a copy of the code
|
| 93 |
+
under your GitHub user account.
|
| 94 |
+
|
| 95 |
+
2. Clone your fork to your local disk, and add the base repository as a remote. The following command
|
| 96 |
+
assumes you have your public SSH key uploaded to GitHub. See the following guide for more
|
| 97 |
+
[information](https://docs.github.com/en/repositories/creating-and-managing-repositories/cloning-a-repository).
|
| 98 |
+
|
| 99 |
+
```bash
|
| 100 |
+
$ git clone git@github.com:<your Github handle>/accelerate.git
|
| 101 |
+
$ cd accelerate
|
| 102 |
+
$ git remote add upstream https://github.com/huggingface/accelerate.git
|
| 103 |
+
```
|
| 104 |
+
|
| 105 |
+
3. Create a new branch to hold your development changes, and do this for every new PR you work on.
|
| 106 |
+
|
| 107 |
+
Start by synchronizing your `main` branch with the `upstream/main` branch (ore details in the [GitHub Docs](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/syncing-a-fork)):
|
| 108 |
+
|
| 109 |
+
```bash
|
| 110 |
+
$ git checkout main
|
| 111 |
+
$ git fetch upstream
|
| 112 |
+
$ git merge upstream/main
|
| 113 |
+
```
|
| 114 |
+
|
| 115 |
+
Once your `main` branch is synchronized, create a new branch from it:
|
| 116 |
+
|
| 117 |
+
```bash
|
| 118 |
+
$ git checkout -b a-descriptive-name-for-my-changes
|
| 119 |
+
```
|
| 120 |
+
|
| 121 |
+
**Do not** work on the `main` branch.
|
| 122 |
+
|
| 123 |
+
4. Set up a development environment by running the following command in a conda or a virtual environment you've created for working on this library:
|
| 124 |
+
|
| 125 |
+
```bash
|
| 126 |
+
$ pip install -e ".[dev]"
|
| 127 |
+
```
|
| 128 |
+
|
| 129 |
+
This will install all testing and linting/code quality dependencies for the library (see `quality`, `test_dev`,
|
| 130 |
+
`test_prod` targets in [`setup.py`](./setup.py)).
|
| 131 |
+
|
| 132 |
+
(If accelerate was already installed in the virtual environment, remove
|
| 133 |
+
it with `pip uninstall accelerate` before reinstalling it in editable
|
| 134 |
+
mode with the `-e` flag).
|
| 135 |
+
|
| 136 |
+
Alternatively, if you are using [Visual Studio Code](https://code.visualstudio.com/Download), the fastest way to get set up is by using
|
| 137 |
+
the provided Dev Container. Documentation on how to get started with dev containers is available [here](https://code.visualstudio.com/docs/remote/containers).
|
| 138 |
+
|
| 139 |
+
5. Develop the features on your branch.
|
| 140 |
+
|
| 141 |
+
As you work on the features, you should make sure that the test suite
|
| 142 |
+
passes. You should run the tests impacted by your changes like this (see
|
| 143 |
+
below an explanation regarding the environment variable):
|
| 144 |
+
|
| 145 |
+
```bash
|
| 146 |
+
$ pytest tests/<TEST_TO_RUN>.py
|
| 147 |
+
```
|
| 148 |
+
|
| 149 |
+
> For the following commands leveraging the `make` utility, we recommend using the WSL system when running on
|
| 150 |
+
> Windows. More information [here](https://docs.microsoft.com/en-us/windows/wsl/about).
|
| 151 |
+
|
| 152 |
+
You can also run the full suite with the following command.
|
| 153 |
+
|
| 154 |
+
```bash
|
| 155 |
+
$ make test
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
`accelerate` relies on `ruff` to format its source code
|
| 159 |
+
consistently. After you make changes, apply automatic style corrections and code verifications
|
| 160 |
+
that can't be automated in one go with:
|
| 161 |
+
|
| 162 |
+
This target is also optimized to only work with files modified by the PR you're working on.
|
| 163 |
+
|
| 164 |
+
If you prefer to run the checks one after the other, the following command apply the
|
| 165 |
+
style corrections:
|
| 166 |
+
|
| 167 |
+
```bash
|
| 168 |
+
$ make style
|
| 169 |
+
```
|
| 170 |
+
|
| 171 |
+
`accelerate` also uses a few custom scripts to check for coding mistakes. Quality
|
| 172 |
+
control runs in CI, however you can also run the same checks with:
|
| 173 |
+
|
| 174 |
+
```bash
|
| 175 |
+
$ make quality
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
You can also set up [`pre-commit`](https://pre-commit.com/) to run these checks
|
| 179 |
+
automatically as Git commit hooks.
|
| 180 |
+
|
| 181 |
+
```bash
|
| 182 |
+
$ pip install pre-commit
|
| 183 |
+
$ pre-commit install
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
Once you're happy with your changes, add changed files using `git add` and
|
| 187 |
+
make a commit with `git commit` to record your changes locally:
|
| 188 |
+
|
| 189 |
+
```bash
|
| 190 |
+
$ git add modified_file.py
|
| 191 |
+
$ git commit
|
| 192 |
+
```
|
| 193 |
+
|
| 194 |
+
Please write [good commit messages](https://chris.beams.io/posts/git-commit/).
|
| 195 |
+
|
| 196 |
+
It is a good idea to sync your copy of the code with the original
|
| 197 |
+
repository regularly. This way you can quickly account for changes:
|
| 198 |
+
|
| 199 |
+
```bash
|
| 200 |
+
$ git fetch upstream
|
| 201 |
+
$ git rebase upstream/main
|
| 202 |
+
```
|
| 203 |
+
|
| 204 |
+
Push the changes to your account using:
|
| 205 |
+
|
| 206 |
+
```bash
|
| 207 |
+
$ git push -u origin a-descriptive-name-for-my-changes
|
| 208 |
+
```
|
| 209 |
+
|
| 210 |
+
6. Once you are satisfied (**and the checklist below is happy too**), go to the
|
| 211 |
+
webpage of your fork on GitHub. Click on 'Pull request' to send your changes
|
| 212 |
+
to the project maintainers for review.
|
| 213 |
+
|
| 214 |
+
7. It's ok if maintainers ask you for changes. It happens to core contributors
|
| 215 |
+
too! So everyone can see the changes in the Pull request, work in your local
|
| 216 |
+
branch and push the changes to your fork. They will automatically appear in
|
| 217 |
+
the pull request.
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
### Checklist
|
| 221 |
+
|
| 222 |
+
1. The title of your pull request should be a summary of its contribution;
|
| 223 |
+
2. If your pull request addresses an issue, please mention the issue number in
|
| 224 |
+
the pull request description to make sure they are linked (and people
|
| 225 |
+
consulting the issue know you are working on it);
|
| 226 |
+
3. To indicate a work in progress please prefix the title with `[WIP]`, or mark
|
| 227 |
+
the PR as a draft PR. These are useful to avoid duplicated work, and to differentiate
|
| 228 |
+
it from PRs ready to be merged;
|
| 229 |
+
4. Make sure existing tests pass;
|
| 230 |
+
5. Add high-coverage tests. No quality testing = no merge.
|
| 231 |
+
|
| 232 |
+
See an example of a good PR here: https://github.com/huggingface/accelerate/pull/255
|
| 233 |
+
|
| 234 |
+
### Tests
|
| 235 |
+
|
| 236 |
+
An extensive test suite is included to test the library behavior and several examples. Library tests can be found in
|
| 237 |
+
the [tests folder](https://github.com/huggingface/accelerate/tree/main/tests).
|
| 238 |
+
|
| 239 |
+
We use `pytest` in order to run the tests. From the root of the
|
| 240 |
+
repository, here's how to run tests with `pytest` for the library:
|
| 241 |
+
|
| 242 |
+
```bash
|
| 243 |
+
$ python -m pytest -sv ./tests
|
| 244 |
+
```
|
| 245 |
+
|
| 246 |
+
In fact, that's how `make test` is implemented (sans the `pip install` line)!
|
| 247 |
+
|
| 248 |
+
You can specify a smaller set of tests in order to test only the feature
|
| 249 |
+
you're working on.
|
tasks/tasksmith-ae8f12dc63d0/environment/source/Dockerfile
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
WORKDIR /workspace
|
| 3 |
+
RUN python -m pip install --no-cache-dir setuptools==78.1.0 wheel==0.48.0 --extra-index-url https://download.pytorch.org/whl/cpu torch==2.11.0+cpu numpy==2.5.3 packaging==26.3 psutil==7.2.2 parameterized==0.9.0 pytest==8.4.2
|
| 4 |
+
COPY . /workspace
|
| 5 |
+
RUN python -m pip install --no-cache-dir -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-ae8f12dc63d0/environment/source/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/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-ae8f12dc63d0/environment/source/Makefile
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
.PHONY: quality style test docs utils
|
| 2 |
+
|
| 3 |
+
check_dirs := .
|
| 4 |
+
|
| 5 |
+
# Check that source code meets quality standards
|
| 6 |
+
|
| 7 |
+
extra_quality_checks:
|
| 8 |
+
python utils/check_copies.py
|
| 9 |
+
python utils/check_dummies.py
|
| 10 |
+
python utils/check_repo.py
|
| 11 |
+
doc-builder style src/accelerate docs/source --max_len 119
|
| 12 |
+
|
| 13 |
+
# this target runs checks on all files
|
| 14 |
+
quality:
|
| 15 |
+
ruff check $(check_dirs)
|
| 16 |
+
ruff format --check $(check_dirs)
|
| 17 |
+
doc-builder style src/accelerate docs/source --max_len 119 --check_only
|
| 18 |
+
|
| 19 |
+
# Format source code automatically and check is there are any problems left that need manual fixing
|
| 20 |
+
style:
|
| 21 |
+
ruff check $(check_dirs) --fix
|
| 22 |
+
ruff format $(check_dirs)
|
| 23 |
+
doc-builder style src/accelerate docs/source --max_len 119
|
| 24 |
+
|
| 25 |
+
# Run tests for the library
|
| 26 |
+
test_big_modeling:
|
| 27 |
+
python -m pytest -s -v ./tests/test_big_modeling.py ./tests/test_modeling_utils.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_big_modeling.log",)
|
| 28 |
+
|
| 29 |
+
test_core:
|
| 30 |
+
python -m pytest -s -v ./tests/ --ignore=./tests/test_examples.py --ignore=./tests/deepspeed --ignore=./tests/test_big_modeling.py \
|
| 31 |
+
--ignore=./tests/fsdp --ignore=./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_core.log",)
|
| 32 |
+
|
| 33 |
+
test_cli:
|
| 34 |
+
python -m pytest -s -v ./tests/test_cli.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_cli.log",)
|
| 35 |
+
|
| 36 |
+
test_deepspeed:
|
| 37 |
+
python -m pytest -s -v ./tests/deepspeed $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_deepspeed.log",)
|
| 38 |
+
|
| 39 |
+
test_fsdp:
|
| 40 |
+
python -m pytest -s -v ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_fsdp.log",)
|
| 41 |
+
|
| 42 |
+
# Since the new version of pytest will *change* how things are collected, we need `deepspeed` to
|
| 43 |
+
# run after test_core and test_cli
|
| 44 |
+
test:
|
| 45 |
+
$(MAKE) test_core
|
| 46 |
+
$(MAKE) test_cli
|
| 47 |
+
$(MAKE) test_big_modeling
|
| 48 |
+
$(MAKE) test_deepspeed
|
| 49 |
+
$(MAKE) test_fsdp
|
| 50 |
+
|
| 51 |
+
test_examples:
|
| 52 |
+
python -m pytest -s -v ./tests/test_examples.py $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_examples.log",)
|
| 53 |
+
|
| 54 |
+
# Broken down example tests for the CI runners
|
| 55 |
+
test_integrations:
|
| 56 |
+
python -m pytest -s -v ./tests/deepspeed ./tests/fsdp $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_integrations.log",)
|
| 57 |
+
|
| 58 |
+
test_example_differences:
|
| 59 |
+
python -m pytest -s -v ./tests/test_examples.py::ExampleDifferenceTests $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_example_diff.log",)
|
| 60 |
+
|
| 61 |
+
test_checkpoint_epoch:
|
| 62 |
+
python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_epoch.log",)
|
| 63 |
+
|
| 64 |
+
test_checkpoint_step:
|
| 65 |
+
python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "by_step" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_checkpoint_step.log",)
|
| 66 |
+
|
| 67 |
+
# Same as test but used to install only the base dependencies
|
| 68 |
+
test_prod:
|
| 69 |
+
$(MAKE) test_core
|
| 70 |
+
|
| 71 |
+
test_rest:
|
| 72 |
+
python -m pytest -s -v ./tests/test_examples.py::FeatureExamplesTests -k "not by_step and not by_epoch" $(if $(IS_GITHUB_CI),--report-log "$(PYTORCH_VERSION)_rest.log",)
|
tasks/tasksmith-ae8f12dc63d0/environment/source/README.md
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!---
|
| 2 |
+
Copyright 2021 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 |
+
<p align="center">
|
| 18 |
+
<br>
|
| 19 |
+
<img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/accelerate_logo.png" width="400"/>
|
| 20 |
+
<br>
|
| 21 |
+
<p>
|
| 22 |
+
|
| 23 |
+
<p align="center">
|
| 24 |
+
<!-- Uncomment when CircleCI is set up
|
| 25 |
+
<a href="https://circleci.com/gh/huggingface/accelerate"><img alt="Build" src="https://img.shields.io/circleci/build/github/huggingface/transformers/master"></a>
|
| 26 |
+
-->
|
| 27 |
+
<a href="https://github.com/huggingface/accelerate/blob/main/LICENSE"><img alt="License" src="https://img.shields.io/github/license/huggingface/accelerate.svg?color=blue"></a>
|
| 28 |
+
<a href="https://huggingface.co/docs/accelerate/index.html"><img alt="Documentation" src="https://img.shields.io/website/http/huggingface.co/docs/accelerate/index.html.svg?down_color=red&down_message=offline&up_message=online"></a>
|
| 29 |
+
<a href="https://github.com/huggingface/accelerate/releases"><img alt="GitHub release" src="https://img.shields.io/github/release/huggingface/accelerate.svg"></a>
|
| 30 |
+
<a href="https://github.com/huggingface/accelerate/blob/main/CODE_OF_CONDUCT.md"><img alt="Contributor Covenant" src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg"></a>
|
| 31 |
+
</p>
|
| 32 |
+
|
| 33 |
+
<h3 align="center">
|
| 34 |
+
<p>Run your *raw* PyTorch training script on any kind of device
|
| 35 |
+
</h3>
|
| 36 |
+
|
| 37 |
+
<h3 align="center">
|
| 38 |
+
<a href="https://hf.co/course"><img src="https://raw.githubusercontent.com/huggingface/accelerate/main/docs/source/imgs/course_banner.png"></a>
|
| 39 |
+
</h3>
|
| 40 |
+
|
| 41 |
+
## Easy to integrate
|
| 42 |
+
|
| 43 |
+
🤗 Accelerate was created for PyTorch users who like to write the training loop of PyTorch models but are reluctant to write and maintain the boilerplate code needed to use multi-GPUs/TPU/fp16.
|
| 44 |
+
|
| 45 |
+
🤗 Accelerate abstracts exactly and only the boilerplate code related to multi-GPUs/TPU/fp16 and leaves the rest of your code unchanged.
|
| 46 |
+
|
| 47 |
+
Here is an example:
|
| 48 |
+
|
| 49 |
+
```diff
|
| 50 |
+
import torch
|
| 51 |
+
import torch.nn.functional as F
|
| 52 |
+
from datasets import load_dataset
|
| 53 |
+
+ from accelerate import Accelerator
|
| 54 |
+
|
| 55 |
+
+ accelerator = Accelerator()
|
| 56 |
+
- device = 'cpu'
|
| 57 |
+
+ device = accelerator.device
|
| 58 |
+
|
| 59 |
+
model = torch.nn.Transformer().to(device)
|
| 60 |
+
optimizer = torch.optim.Adam(model.parameters())
|
| 61 |
+
|
| 62 |
+
dataset = load_dataset('my_dataset')
|
| 63 |
+
data = torch.utils.data.DataLoader(dataset, shuffle=True)
|
| 64 |
+
|
| 65 |
+
+ model, optimizer, data = accelerator.prepare(model, optimizer, data)
|
| 66 |
+
|
| 67 |
+
model.train()
|
| 68 |
+
for epoch in range(10):
|
| 69 |
+
for source, targets in data:
|
| 70 |
+
source = source.to(device)
|
| 71 |
+
targets = targets.to(device)
|
| 72 |
+
|
| 73 |
+
optimizer.zero_grad()
|
| 74 |
+
|
| 75 |
+
output = model(source)
|
| 76 |
+
loss = F.cross_entropy(output, targets)
|
| 77 |
+
|
| 78 |
+
- loss.backward()
|
| 79 |
+
+ accelerator.backward(loss)
|
| 80 |
+
|
| 81 |
+
optimizer.step()
|
| 82 |
+
```
|
| 83 |
+
|
| 84 |
+
As you can see in this example, by adding 5-lines to any standard PyTorch training script you can now run on any kind of single or distributed node setting (single CPU, single GPU, multi-GPUs and TPUs) as well as with or without mixed precision (fp8, fp16, bf16).
|
| 85 |
+
|
| 86 |
+
In particular, the same code can then be run without modification on your local machine for debugging or your training environment.
|
| 87 |
+
|
| 88 |
+
🤗 Accelerate even handles the device placement for you (which requires a few more changes to your code, but is safer in general), so you can even simplify your training loop further:
|
| 89 |
+
|
| 90 |
+
```diff
|
| 91 |
+
import torch
|
| 92 |
+
import torch.nn.functional as F
|
| 93 |
+
from datasets import load_dataset
|
| 94 |
+
+ from accelerate import Accelerator
|
| 95 |
+
|
| 96 |
+
- device = 'cpu'
|
| 97 |
+
+ accelerator = Accelerator()
|
| 98 |
+
|
| 99 |
+
- model = torch.nn.Transformer().to(device)
|
| 100 |
+
+ model = torch.nn.Transformer()
|
| 101 |
+
optimizer = torch.optim.Adam(model.parameters())
|
| 102 |
+
|
| 103 |
+
dataset = load_dataset('my_dataset')
|
| 104 |
+
data = torch.utils.data.DataLoader(dataset, shuffle=True)
|
| 105 |
+
|
| 106 |
+
+ model, optimizer, data = accelerator.prepare(model, optimizer, data)
|
| 107 |
+
|
| 108 |
+
model.train()
|
| 109 |
+
for epoch in range(10):
|
| 110 |
+
for source, targets in data:
|
| 111 |
+
- source = source.to(device)
|
| 112 |
+
- targets = targets.to(device)
|
| 113 |
+
|
| 114 |
+
optimizer.zero_grad()
|
| 115 |
+
|
| 116 |
+
output = model(source)
|
| 117 |
+
loss = F.cross_entropy(output, targets)
|
| 118 |
+
|
| 119 |
+
- loss.backward()
|
| 120 |
+
+ accelerator.backward(loss)
|
| 121 |
+
|
| 122 |
+
optimizer.step()
|
| 123 |
+
```
|
| 124 |
+
|
| 125 |
+
Want to learn more? Check out the [documentation](https://huggingface.co/docs/accelerate) or have a look at our [examples](https://github.com/huggingface/accelerate/tree/main/examples).
|
| 126 |
+
|
| 127 |
+
## Launching script
|
| 128 |
+
|
| 129 |
+
🤗 Accelerate also provides an optional CLI tool that allows you to quickly configure and test your training environment before launching the scripts. No need to remember how to use `torch.distributed.run` or to write a specific launcher for TPU training!
|
| 130 |
+
On your machine(s) just run:
|
| 131 |
+
|
| 132 |
+
```bash
|
| 133 |
+
accelerate config
|
| 134 |
+
```
|
| 135 |
+
|
| 136 |
+
and answer the questions asked. This will generate a config file that will be used automatically to properly set the default options when doing
|
| 137 |
+
|
| 138 |
+
```bash
|
| 139 |
+
accelerate launch my_script.py --args_to_my_script
|
| 140 |
+
```
|
| 141 |
+
|
| 142 |
+
For instance, here is how you would run the GLUE example on the MRPC task (from the root of the repo):
|
| 143 |
+
|
| 144 |
+
```bash
|
| 145 |
+
accelerate launch examples/nlp_example.py
|
| 146 |
+
```
|
| 147 |
+
|
| 148 |
+
This CLI tool is **optional**, and you can still use `python my_script.py` or `python -m torchrun my_script.py` at your convenience.
|
| 149 |
+
|
| 150 |
+
You can also directly pass in the arguments you would to `torchrun` as arguments to `accelerate launch` if you wish to not run` accelerate config`.
|
| 151 |
+
|
| 152 |
+
For example, here is how to launch on two GPUs:
|
| 153 |
+
|
| 154 |
+
```bash
|
| 155 |
+
accelerate launch --multi_gpu --num_processes 2 examples/nlp_example.py
|
| 156 |
+
```
|
| 157 |
+
|
| 158 |
+
To learn more, check the CLI documentation available [here](https://huggingface.co/docs/accelerate/package_reference/cli).
|
| 159 |
+
|
| 160 |
+
Or view the configuration zoo [here](https://github.com/huggingface/accelerate/blob/main/examples/config_yaml_templates/)
|
| 161 |
+
|
| 162 |
+
## Launching multi-CPU run using MPI
|
| 163 |
+
|
| 164 |
+
🤗 Here is another way to launch multi-CPU run using MPI. You can learn how to install Open MPI on [this page](https://www.open-mpi.org/faq/?category=building#easy-build). You can use Intel MPI or MVAPICH as well.
|
| 165 |
+
Once you have MPI setup on your cluster, just run:
|
| 166 |
+
```bash
|
| 167 |
+
accelerate config
|
| 168 |
+
```
|
| 169 |
+
Answer the questions that are asked, selecting to run using multi-CPU, and answer "yes" when asked if you want accelerate to launch mpirun.
|
| 170 |
+
Then, use `accelerate launch` with your script like:
|
| 171 |
+
```bash
|
| 172 |
+
accelerate launch examples/nlp_example.py
|
| 173 |
+
```
|
| 174 |
+
Alternatively, you can use mpirun directly, without using the CLI like:
|
| 175 |
+
```bash
|
| 176 |
+
mpirun -np 2 python examples/nlp_example.py
|
| 177 |
+
```
|
| 178 |
+
|
| 179 |
+
## Launching training using DeepSpeed
|
| 180 |
+
|
| 181 |
+
🤗 Accelerate supports training on single/multiple GPUs using DeepSpeed. To use it, you don't need to change anything in your training code; you can set everything using just `accelerate config`. However, if you desire to tweak your DeepSpeed related args from your Python script, we provide you the `DeepSpeedPlugin`.
|
| 182 |
+
|
| 183 |
+
```python
|
| 184 |
+
from accelerate import Accelerator, DeepSpeedPlugin
|
| 185 |
+
|
| 186 |
+
# deepspeed needs to know your gradient accumulation steps beforehand, so don't forget to pass it
|
| 187 |
+
# Remember you still need to do gradient accumulation by yourself, just like you would have done without deepspeed
|
| 188 |
+
deepspeed_plugin = DeepSpeedPlugin(zero_stage=2, gradient_accumulation_steps=2)
|
| 189 |
+
accelerator = Accelerator(mixed_precision='fp16', deepspeed_plugin=deepspeed_plugin)
|
| 190 |
+
|
| 191 |
+
# How to save your 🤗 Transformer?
|
| 192 |
+
accelerator.wait_for_everyone()
|
| 193 |
+
unwrapped_model = accelerator.unwrap_model(model)
|
| 194 |
+
unwrapped_model.save_pretrained(save_dir, save_function=accelerator.save, state_dict=accelerator.get_state_dict(model))
|
| 195 |
+
```
|
| 196 |
+
|
| 197 |
+
Note: DeepSpeed support is experimental for now. In case you get into some problem, please open an issue.
|
| 198 |
+
|
| 199 |
+
## Launching your training from a notebook
|
| 200 |
+
|
| 201 |
+
🤗 Accelerate also provides a `notebook_launcher` function you can use in a notebook to launch a distributed training. This is especially useful for Colab or Kaggle notebooks with a TPU backend. Just define your training loop in a `training_function` then in your last cell, add:
|
| 202 |
+
|
| 203 |
+
```python
|
| 204 |
+
from accelerate import notebook_launcher
|
| 205 |
+
|
| 206 |
+
notebook_launcher(training_function)
|
| 207 |
+
```
|
| 208 |
+
|
| 209 |
+
An example can be found in [this notebook](https://github.com/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb). [](https://colab.research.google.com/github/huggingface/notebooks/blob/main/examples/accelerate_examples/simple_nlp_example.ipynb)
|
| 210 |
+
|
| 211 |
+
## Why should I use 🤗 Accelerate?
|
| 212 |
+
|
| 213 |
+
You should use 🤗 Accelerate when you want to easily run your training scripts in a distributed environment without having to renounce full control over your training loop. This is not a high-level framework above PyTorch, just a thin wrapper so you don't have to learn a new library. In fact, the whole API of 🤗 Accelerate is in one class, the `Accelerator` object.
|
| 214 |
+
|
| 215 |
+
## Why shouldn't I use 🤗 Accelerate?
|
| 216 |
+
|
| 217 |
+
You shouldn't use 🤗 Accelerate if you don't want to write a training loop yourself. There are plenty of high-level libraries above PyTorch that will offer you that, 🤗 Accelerate is not one of them.
|
| 218 |
+
|
| 219 |
+
## Frameworks using 🤗 Accelerate
|
| 220 |
+
|
| 221 |
+
If you like the simplicity of 🤗 Accelerate but would prefer a higher-level abstraction around its capabilities, some frameworks and libraries that are built on top of 🤗 Accelerate are listed below:
|
| 222 |
+
|
| 223 |
+
* [Amphion](https://github.com/open-mmlab/Amphion) is a toolkit for Audio, Music, and Speech Generation. Its purpose is to support reproducible research and help junior researchers and engineers get started in the field of audio, music, and speech generation research and development.
|
| 224 |
+
* [Animus](https://github.com/Scitator/animus) is a minimalistic framework to run machine learning experiments. Animus highlights common "breakpoints" in ML experiments and provides a unified interface for them within [IExperiment](https://github.com/Scitator/animus/blob/main/animus/core.py#L76).
|
| 225 |
+
* [Catalyst](https://github.com/catalyst-team/catalyst#getting-started) is a PyTorch framework for Deep Learning Research and Development. It focuses on reproducibility, rapid experimentation, and codebase reuse so you can create something new rather than write yet another train loop. Catalyst provides a [Runner](https://catalyst-team.github.io/catalyst/api/core.html#runner) to connect all parts of the experiment: hardware backend, data transformations, model training, and inference logic.
|
| 226 |
+
* [fastai](https://github.com/fastai/fastai#installing) is a PyTorch framework for Deep Learning that simplifies training fast and accurate neural nets using modern best practices. fastai provides a [Learner](https://docs.fast.ai/learner.html#Learner) to handle the training, fine-tuning, and inference of deep learning algorithms.
|
| 227 |
+
* [Finetuner](https://github.com/jina-ai/finetuner) is a service that enables models to create higher-quality embeddings for semantic search, visual similarity search, cross-modal text<->image search, recommendation systems, clustering, duplication detection, anomaly detection, or other uses.
|
| 228 |
+
* [InvokeAI](https://github.com/invoke-ai/InvokeAI) is a creative engine for Stable Diffusion models, offering industry-leading WebUI, terminal usage support, and serves as the foundation for many commercial products.
|
| 229 |
+
* [Kornia](https://kornia.readthedocs.io/en/latest/get-started/introduction.html) is a differentiable library that allows classical computer vision to be integrated into deep learning models. Kornia provides a [Trainer](https://kornia.readthedocs.io/en/latest/x.html#kornia.x.Trainer) with the specific purpose to train and fine-tune the supported deep learning algorithms within the library.
|
| 230 |
+
* [Open Assistant](https://projects.laion.ai/Open-Assistant/) is a chat-based assistant that understands tasks, can interact with their party systems, and retrieve information dynamically to do so.
|
| 231 |
+
* [pytorch-accelerated](https://github.com/Chris-hughes10/pytorch-accelerated) is a lightweight training library, with a streamlined feature set centered around a general-purpose [Trainer](https://pytorch-accelerated.readthedocs.io/en/latest/trainer.html), that places a huge emphasis on simplicity and transparency; enabling users to understand exactly what is going on under the hood, but without having to write and maintain the boilerplate themselves!
|
| 232 |
+
* [Stable Diffusion web UI](https://github.com/AUTOMATIC1111/stable-diffusion-webui) is an open-source browser-based easy-to-use interface based on the Gradio library for Stable Diffusion.
|
| 233 |
+
* [torchkeras](https://github.com/lyhue1991/torchkeras) is a simple tool for training pytorch model just in a keras style, a dynamic and beautiful plot is provided in notebook to monitor your loss or metric.
|
| 234 |
+
* [transformers](https://github.com/huggingface/transformers) as a tool for helping train state-of-the-art machine learning models in PyTorch, Tensorflow, and JAX. (Accelerate is the backend for the PyTorch side).
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
## Installation
|
| 238 |
+
|
| 239 |
+
This repository is tested on Python 3.8+ and PyTorch 1.10.0+
|
| 240 |
+
|
| 241 |
+
You should install 🤗 Accelerate in a [virtual environment](https://docs.python.org/3/library/venv.html). If you're unfamiliar with Python virtual environments, check out the [user guide](https://packaging.python.org/guides/installing-using-pip-and-virtual-environments/).
|
| 242 |
+
|
| 243 |
+
First, create a virtual environment with the version of Python you're going to use and activate it.
|
| 244 |
+
|
| 245 |
+
Then, you will need to install PyTorch: refer to the [official installation page](https://pytorch.org/get-started/locally/#start-locally) regarding the specific install command for your platform. Then 🤗 Accelerate can be installed using pip as follows:
|
| 246 |
+
|
| 247 |
+
```bash
|
| 248 |
+
pip install accelerate
|
| 249 |
+
```
|
| 250 |
+
|
| 251 |
+
## Supported integrations
|
| 252 |
+
|
| 253 |
+
- CPU only
|
| 254 |
+
- multi-CPU on one node (machine)
|
| 255 |
+
- multi-CPU on several nodes (machines)
|
| 256 |
+
- single GPU
|
| 257 |
+
- multi-GPU on one node (machine)
|
| 258 |
+
- multi-GPU on several nodes (machines)
|
| 259 |
+
- TPU
|
| 260 |
+
- FP16/BFloat16 mixed precision
|
| 261 |
+
- FP8 mixed precision with [Transformer Engine](https://github.com/NVIDIA/TransformerEngine) or [MS-AMP](https://github.com/Azure/MS-AMP/)
|
| 262 |
+
- DeepSpeed support (Experimental)
|
| 263 |
+
- PyTorch Fully Sharded Data Parallel (FSDP) support (Experimental)
|
| 264 |
+
- Megatron-LM support (Experimental)
|
| 265 |
+
|
| 266 |
+
## Citing 🤗 Accelerate
|
| 267 |
+
|
| 268 |
+
If you use 🤗 Accelerate in your publication, please cite it by using the following BibTeX entry.
|
| 269 |
+
|
| 270 |
+
```bibtex
|
| 271 |
+
@Misc{accelerate,
|
| 272 |
+
title = {Accelerate: Training and inference at scale made simple, efficient and adaptable.},
|
| 273 |
+
author = {Sylvain Gugger and Lysandre Debut and Thomas Wolf and Philipp Schmid and Zachary Mueller and Sourab Mangrulkar and Marc Sun and Benjamin Bossan},
|
| 274 |
+
howpublished = {\url{https://github.com/huggingface/accelerate}},
|
| 275 |
+
year = {2022}
|
| 276 |
+
}
|
| 277 |
+
```
|
tasks/tasksmith-ae8f12dc63d0/environment/source/docker/README.md
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!---
|
| 2 |
+
Copyright 2024 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 |
+
# Official Hugging Face Accelerate Docker Images
|
| 18 |
+
|
| 19 |
+
Accelerate publishes a variety of docker versions as part of our CI that users can also use. These are stable images that Accelerate can run off of which comes with a variety of different setup configurations, all of which are officially hosted on [Docker Hub](https://hub.docker.com/r/huggingface/accelerate).
|
| 20 |
+
|
| 21 |
+
A breakdown of each are given below
|
| 22 |
+
|
| 23 |
+
## Naming Conventions
|
| 24 |
+
|
| 25 |
+
Accelerate docker images follow a tagging convention of:
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
huggingface/accelerate:{accelerator}-{nightly,release}
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
`accelerator` in this instance is one of many applical pre-configured backend supports:
|
| 32 |
+
* `gpu`: Comes compiled off of the `nvidia/cuda` image and includes core parts like `bitsandbytes`. Runs off python 3.9.
|
| 33 |
+
* `cpu`: Comes compiled off of `python:3.9-slim` and is designed for non-CUDA based workloads.
|
| 34 |
+
* More to come soon
|
| 35 |
+
* `gpu-deepspeed`: Comes compiled off of the `nvidia/cuda` image and includes core parts like `bitsandbytes` as well as the latest `deepspeed` version. Runs off python 3.10.
|
| 36 |
+
* `gpu-fp8-transformerengine`: Comes compiled off of `nvcr.io/nvidia/pytorch` and is specifically for running the `benchmarks/fp8` scripts on devices which support FP8 operations using the `TransformerEngine` library (RTX 4090, H100, etc)
|
| 37 |
+
|
| 38 |
+
## Nightlies vs Releases
|
| 39 |
+
|
| 40 |
+
Each release a new build is pushed with a version number included in the name. For a GPU-supported image of version 0.28.0 for instance, it would look like the following:
|
| 41 |
+
|
| 42 |
+
```bash
|
| 43 |
+
huggingface/accelerate:gpu-release-0.28.0
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Nightlies contain two different image tags. There is a general `nightly` tag which is built each night, and a `nightly-YYYY-MM-DD` which corresponds to a build from a particular date.
|
| 47 |
+
|
| 48 |
+
For instance, here is an example nightly CPU image from 3/14/2024
|
| 49 |
+
|
| 50 |
+
```bash
|
| 51 |
+
huggingface/accelerate:cpu-nightly-2024-03-14
|
| 52 |
+
```
|
| 53 |
+
|
| 54 |
+
## Running the images
|
| 55 |
+
|
| 56 |
+
Each image comes compiled with `conda` and an `accelerate` environment contains all of the installed dependencies.
|
| 57 |
+
|
| 58 |
+
To pull down the latest nightly run:
|
| 59 |
+
|
| 60 |
+
```bash
|
| 61 |
+
docker pull huggingface/accelerate:gpu-nightly
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
To then run it in interactive mode with GPU-memory available, run:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
docker container run --gpus all -it huggingface/accelerate:gpu-nightly
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
## DEPRECATED IMAGES
|
| 71 |
+
|
| 72 |
+
CPU and GPU docker images were hosted at `huggingface/accelerate-gpu` and `huggingface/accelerate-cpu`. These builds are now outdated and will not receive updates.
|
| 73 |
+
|
| 74 |
+
The builds at the corresponding `huggingface/accelerate:{gpu,cpu}` contain the same `Dockerfile`, so it's as simple as changing the docker image to the desired ones from above. We will not be deleting these images for posterity, but they will not be receiving updates going forward.
|
tasks/tasksmith-ae8f12dc63d0/environment/source/docker/accelerate-cpu/Dockerfile
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Builds CPU-only Docker image of PyTorch
|
| 2 |
+
# Uses multi-staged approach to reduce size
|
| 3 |
+
# Stage 1
|
| 4 |
+
FROM python:3.8-slim as compile-image
|
| 5 |
+
|
| 6 |
+
ARG DEBIAN_FRONTEND=noninteractive
|
| 7 |
+
|
| 8 |
+
RUN apt update
|
| 9 |
+
RUN apt-get install -y --no-install-recommends \
|
| 10 |
+
build-essential \
|
| 11 |
+
git \
|
| 12 |
+
gcc
|
| 13 |
+
|
| 14 |
+
# Setup virtual environment for Docker
|
| 15 |
+
ENV VIRTUAL_ENV=/opt/venv
|
| 16 |
+
RUN python3 -m venv ${VIRTUAL_ENV}
|
| 17 |
+
# Make sure we use the virtualenv
|
| 18 |
+
ENV PATH="${VIRTUAL_ENV}/bin:$PATH"
|
| 19 |
+
WORKDIR /workspace
|
| 20 |
+
# Install specific CPU torch wheel to save on space
|
| 21 |
+
RUN python3 -m pip install --upgrade --no-cache-dir pip
|
| 22 |
+
RUN python3 -m pip install --no-cache-dir \
|
| 23 |
+
jupyter \
|
| 24 |
+
git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers] \
|
| 25 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 26 |
+
|
| 27 |
+
# Stage 2
|
| 28 |
+
FROM python:3.8-slim AS build-image
|
| 29 |
+
COPY --from=compile-image /opt/venv /opt/venv
|
| 30 |
+
RUN useradd -ms /bin/bash user
|
| 31 |
+
USER user
|
| 32 |
+
|
| 33 |
+
# Make sure we use the virtualenv
|
| 34 |
+
ENV PATH="/opt/venv/bin:$PATH"
|
| 35 |
+
CMD ["/bin/bash"]
|
tasks/tasksmith-ae8f12dc63d0/environment/source/docker/accelerate-gpu-deepspeed/Dockerfile
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Builds GPU docker image of PyTorch specifically
|
| 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 |
+
# Note: DeepSpeed beyond v0.12.6 requires py 3.10
|
| 8 |
+
ENV PYTHON_VERSION=3.10
|
| 9 |
+
# Install apt libs
|
| 10 |
+
RUN apt-get update && \
|
| 11 |
+
apt-get install -y curl git wget && \
|
| 12 |
+
apt-get clean && \
|
| 13 |
+
rm -rf /var/lib/apt/lists*
|
| 14 |
+
|
| 15 |
+
# Create our conda env
|
| 16 |
+
RUN conda create --name accelerate python=${PYTHON_VERSION} ipython jupyter pip
|
| 17 |
+
# We don't install pytorch here yet since CUDA isn't available
|
| 18 |
+
# instead we use the direct torch wheel
|
| 19 |
+
ENV PATH /opt/conda/envs/accelerate/bin:$PATH
|
| 20 |
+
# Activate our bash shell
|
| 21 |
+
RUN chsh -s /bin/bash
|
| 22 |
+
SHELL ["/bin/bash", "-c"]
|
| 23 |
+
# Activate the conda env, install mpy4pi, and install torch + accelerate
|
| 24 |
+
RUN source activate accelerate && conda install -c conda-forge mpi4py
|
| 25 |
+
RUN source activate accelerate && \
|
| 26 |
+
python3 -m pip install --no-cache-dir \
|
| 27 |
+
git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers,deepspeed] \
|
| 28 |
+
--extra-index-url https://download.pytorch.org/whl/cu117
|
| 29 |
+
|
| 30 |
+
RUN python3 -m pip install --no-cache-dir bitsandbytes
|
| 31 |
+
|
| 32 |
+
# Stage 2
|
| 33 |
+
FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu20.04 AS build-image
|
| 34 |
+
COPY --from=compile-image /opt/conda /opt/conda
|
| 35 |
+
ENV PATH /opt/conda/bin:$PATH
|
| 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 accelerate" >> ~/.profile
|
| 44 |
+
|
| 45 |
+
# Activate the virtualenv
|
| 46 |
+
CMD ["/bin/bash"]
|
tasks/tasksmith-ae8f12dc63d0/environment/source/docker/accelerate-gpu/Dockerfile
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Builds GPU docker image of PyTorch specifically
|
| 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.9
|
| 8 |
+
# Install apt libs
|
| 9 |
+
RUN apt-get update && \
|
| 10 |
+
apt-get install -y curl git wget && \
|
| 11 |
+
apt-get clean && \
|
| 12 |
+
rm -rf /var/lib/apt/lists*
|
| 13 |
+
|
| 14 |
+
# Create our conda env
|
| 15 |
+
RUN conda create --name accelerate python=${PYTHON_VERSION} ipython jupyter pip
|
| 16 |
+
# We don't install pytorch here yet since CUDA isn't available
|
| 17 |
+
# instead we use the direct torch wheel
|
| 18 |
+
ENV PATH /opt/conda/envs/accelerate/bin:$PATH
|
| 19 |
+
# Activate our bash shell
|
| 20 |
+
RUN chsh -s /bin/bash
|
| 21 |
+
SHELL ["/bin/bash", "-c"]
|
| 22 |
+
# Activate the conda env, install mpy4pi, and install torch + accelerate
|
| 23 |
+
RUN source activate accelerate && conda install -c conda-forge mpi4py
|
| 24 |
+
RUN source activate accelerate && \
|
| 25 |
+
python3 -m pip install --no-cache-dir \
|
| 26 |
+
git+https://github.com/huggingface/accelerate#egg=accelerate[testing,test_trackers] \
|
| 27 |
+
--extra-index-url https://download.pytorch.org/whl/cu117
|
| 28 |
+
|
| 29 |
+
RUN python3 -m pip install --no-cache-dir bitsandbytes
|
| 30 |
+
|
| 31 |
+
# Stage 2
|
| 32 |
+
FROM nvidia/cuda:12.1.0-cudnn8-devel-ubuntu20.04 AS build-image
|
| 33 |
+
COPY --from=compile-image /opt/conda /opt/conda
|
| 34 |
+
ENV PATH /opt/conda/bin:$PATH
|
| 35 |
+
|
| 36 |
+
# Install apt libs
|
| 37 |
+
RUN apt-get update && \
|
| 38 |
+
apt-get install -y curl git wget && \
|
| 39 |
+
apt-get clean && \
|
| 40 |
+
rm -rf /var/lib/apt/lists*
|
| 41 |
+
|
| 42 |
+
RUN echo "source activate accelerate" >> ~/.profile
|
| 43 |
+
|
| 44 |
+
# Activate the virtualenv
|
| 45 |
+
CMD ["/bin/bash"]
|
tasks/tasksmith-ae8f12dc63d0/environment/source/examples/README.md
ADDED
|
@@ -0,0 +1,276 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!---
|
| 2 |
+
Copyright 2021 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 |
+
# In this folder we showcase various full examples using 🤗 Accelerate
|
| 18 |
+
|
| 19 |
+
## Simple NLP example
|
| 20 |
+
|
| 21 |
+
The [nlp_example.py](./nlp_example.py) script is a simple example to train a Bert model on a classification task ([GLUE's MRPC](https://www.microsoft.com/en-us/download/details.aspx?id=52398)).
|
| 22 |
+
|
| 23 |
+
Prior to running it you should install 🤗 Dataset and 🤗 Transformers:
|
| 24 |
+
|
| 25 |
+
```bash
|
| 26 |
+
pip install datasets evaluate transformers
|
| 27 |
+
```
|
| 28 |
+
|
| 29 |
+
The same script can be run in any of the following configurations:
|
| 30 |
+
- single CPU or single GPU
|
| 31 |
+
- multi CPUs
|
| 32 |
+
- multi GPUs (using PyTorch distributed mode)
|
| 33 |
+
- (multi) TPUs
|
| 34 |
+
- fp16 (mixed-precision) or fp32 (normal precision)
|
| 35 |
+
|
| 36 |
+
To run it in each of these various modes, use the following commands:
|
| 37 |
+
- single CPU:
|
| 38 |
+
* from a server without GPU
|
| 39 |
+
```bash
|
| 40 |
+
python ./nlp_example.py
|
| 41 |
+
```
|
| 42 |
+
* from any server by passing `cpu=True` to the `Accelerator`.
|
| 43 |
+
```bash
|
| 44 |
+
python ./nlp_example.py --cpu
|
| 45 |
+
```
|
| 46 |
+
* from any server with Accelerate launcher
|
| 47 |
+
```bash
|
| 48 |
+
accelerate launch --cpu ./nlp_example.py
|
| 49 |
+
```
|
| 50 |
+
- single GPU:
|
| 51 |
+
```bash
|
| 52 |
+
python ./nlp_example.py # from a server with a GPU
|
| 53 |
+
```
|
| 54 |
+
- with fp16 (mixed-precision)
|
| 55 |
+
* from any server by passing `mixed_precison=fp16` to the `Accelerator`.
|
| 56 |
+
```bash
|
| 57 |
+
python ./nlp_example.py --mixed_precision fp16
|
| 58 |
+
```
|
| 59 |
+
* from any server with Accelerate launcher
|
| 60 |
+
```bash
|
| 61 |
+
accelerate launch --mixed_precision fp16 ./nlp_example.py
|
| 62 |
+
- multi CPUs (requires Open MPI, Intel MPI, or MVAPICH)
|
| 63 |
+
* With Accelerate config and launcher, execute the following from node 0:
|
| 64 |
+
```bash
|
| 65 |
+
accelerate config # Select to have accelerate launch mpirun
|
| 66 |
+
accelerate launch ./nlp_example.py # This will run the script on each server
|
| 67 |
+
```
|
| 68 |
+
* With Intel MPI:
|
| 69 |
+
```bash
|
| 70 |
+
export CCL_WORKER_COUNT=1
|
| 71 |
+
export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
|
| 72 |
+
mpirun -f hostfile -n 16 -ppn 4 python ./nlp_example.py
|
| 73 |
+
```
|
| 74 |
+
- multi GPUs (using PyTorch distributed mode)
|
| 75 |
+
* With Accelerate config and launcher
|
| 76 |
+
```bash
|
| 77 |
+
accelerate config # This will create a config file on your server
|
| 78 |
+
accelerate launch ./nlp_example.py # This will run the script on your server
|
| 79 |
+
```
|
| 80 |
+
* With traditional PyTorch launcher (`python -m torch.distributed.run` can be used instead of `torchrun`)
|
| 81 |
+
```bash
|
| 82 |
+
torchrun --nproc_per_node 2 ./nlp_example.py
|
| 83 |
+
```
|
| 84 |
+
- multi GPUs, multi node (several machines, using PyTorch distributed mode)
|
| 85 |
+
* With Accelerate config and launcher, on each machine:
|
| 86 |
+
```bash
|
| 87 |
+
accelerate config # This will create a config file on each server
|
| 88 |
+
accelerate launch ./nlp_example.py # This will run the script on each server
|
| 89 |
+
```
|
| 90 |
+
* With PyTorch launcher only (`python -m torch.distributed.run` can be used instead of `torchrun`). Run this command on each node:
|
| 91 |
+
```bash
|
| 92 |
+
torchrun \ # python -m torch.distributed.run
|
| 93 |
+
--nproc_per_node 2 \
|
| 94 |
+
--nnodes 2 \
|
| 95 |
+
--rdzv_id 2299 \ # A unique job id
|
| 96 |
+
--rdzv_backend c10d \
|
| 97 |
+
--rdzv_endpoint master_node_ip_address:29500 \
|
| 98 |
+
./nlp_example.py
|
| 99 |
+
```
|
| 100 |
+
- (multi) TPUs
|
| 101 |
+
* With Accelerate config and launcher
|
| 102 |
+
```bash
|
| 103 |
+
accelerate config # This will create a config file on your TPU server
|
| 104 |
+
accelerate launch ./nlp_example.py # This will run the script on each server
|
| 105 |
+
```
|
| 106 |
+
* In PyTorch:
|
| 107 |
+
Add an `xmp.spawn` line in your script as you usually do.
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
## Simple vision example
|
| 111 |
+
|
| 112 |
+
The [cv_example.py](./cv_example.py) script is a simple example to fine-tune a ResNet-50 on a classification task ([Ofxord-IIT Pet Dataset](https://www.robots.ox.ac.uk/~vgg/data/pets/)).
|
| 113 |
+
|
| 114 |
+
The same script can be run in any of the following configurations:
|
| 115 |
+
- single CPU or single GPU
|
| 116 |
+
- multi CPUs
|
| 117 |
+
- multi GPUs (using PyTorch distributed mode)
|
| 118 |
+
- (multi) TPUs
|
| 119 |
+
- fp16 (mixed-precision) or fp32 (normal precision)
|
| 120 |
+
|
| 121 |
+
Prior to running it you should install timm and torchvision:
|
| 122 |
+
|
| 123 |
+
```bash
|
| 124 |
+
pip install timm torchvision
|
| 125 |
+
```
|
| 126 |
+
|
| 127 |
+
and you should download the data with the following commands:
|
| 128 |
+
|
| 129 |
+
```bash
|
| 130 |
+
wget https://www.robots.ox.ac.uk/~vgg/data/pets/data/images.tar.gz
|
| 131 |
+
tar -xzf images.tar.gz
|
| 132 |
+
```
|
| 133 |
+
|
| 134 |
+
To run it in each of these various modes, use the following commands:
|
| 135 |
+
- single CPU:
|
| 136 |
+
* from a server without GPU
|
| 137 |
+
```bash
|
| 138 |
+
python ./cv_example.py --data_dir path_to_data
|
| 139 |
+
```
|
| 140 |
+
* from any server by passing `cpu=True` to the `Accelerator`.
|
| 141 |
+
```bash
|
| 142 |
+
python ./cv_example.py --data_dir path_to_data --cpu
|
| 143 |
+
```
|
| 144 |
+
* from any server with Accelerate launcher
|
| 145 |
+
```bash
|
| 146 |
+
accelerate launch --cpu ./cv_example.py --data_dir path_to_data
|
| 147 |
+
```
|
| 148 |
+
- single GPU:
|
| 149 |
+
```bash
|
| 150 |
+
python ./cv_example.py # from a server with a GPU
|
| 151 |
+
```
|
| 152 |
+
- with fp16 (mixed-precision)
|
| 153 |
+
* from any server by passing `mixed_precison=fp16` to the `Accelerator`.
|
| 154 |
+
```bash
|
| 155 |
+
python ./cv_example.py --data_dir path_to_data --mixed_precison fp16
|
| 156 |
+
```
|
| 157 |
+
* from any server with Accelerate launcher
|
| 158 |
+
```bash
|
| 159 |
+
accelerate launch --mixed_precison fp16 ./cv_example.py --data_dir path_to_data
|
| 160 |
+
- multi CPUs (requires Open MPI, Intel MPI, or MVAPICH)
|
| 161 |
+
* With Accelerate config and launcher, run the following from node 0:
|
| 162 |
+
```bash
|
| 163 |
+
accelerate config --config_file config.yaml # Select to have accelerate launch mpirun
|
| 164 |
+
accelerate launch ./cv_example.py --data_dir path_to_data # This will run the script on each server
|
| 165 |
+
```
|
| 166 |
+
* With Intel MPI, execute mpirun from node 0:
|
| 167 |
+
```bash
|
| 168 |
+
export CCL_WORKER_COUNT=1
|
| 169 |
+
export MASTER_ADDR=xxx.xxx.xxx.xxx #node0 ip
|
| 170 |
+
mpirun -f hostfile -n 16 -ppn 4 python ./cv_example.py --data_dir path_to_data
|
| 171 |
+
```
|
| 172 |
+
- multi GPUs (using PyTorch distributed mode)
|
| 173 |
+
* With Accelerate config and launcher
|
| 174 |
+
```bash
|
| 175 |
+
accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml`
|
| 176 |
+
accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on your server
|
| 177 |
+
```
|
| 178 |
+
* With traditional PyTorch launcher (`python -m torch.distributed.run` can be used instead of `torchrun`)
|
| 179 |
+
```bash
|
| 180 |
+
torchrun --nproc_per_node 2 ./cv_example.py --data_dir path_to_data
|
| 181 |
+
```
|
| 182 |
+
- multi GPUs, multi node (several machines, using PyTorch distributed mode)
|
| 183 |
+
* With Accelerate config and launcher, on each machine:
|
| 184 |
+
```bash
|
| 185 |
+
accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml`
|
| 186 |
+
accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on each server
|
| 187 |
+
```
|
| 188 |
+
* With PyTorch launcher only (`python -m torch.distributed.run` can be used instead of `torchrun`). Run this command on each node:
|
| 189 |
+
```bash
|
| 190 |
+
torchrun \ # python -m torch.distributed.run
|
| 191 |
+
--nproc_per_node 2 \
|
| 192 |
+
--nnodes 2 \
|
| 193 |
+
--rdzv_id 2299 \ # A unique job id
|
| 194 |
+
--rdzv_backend c10d \
|
| 195 |
+
--rdzv_endpoint master_node_ip_address:29500 \
|
| 196 |
+
./cv_example.py --data_dir path_to_data
|
| 197 |
+
```
|
| 198 |
+
- (multi) TPUs
|
| 199 |
+
* With Accelerate config and launcher
|
| 200 |
+
```bash
|
| 201 |
+
accelerate config --config_file config.yaml # This will create a config file on your server to `config.yaml`
|
| 202 |
+
accelerate launch --config_file config.yaml ./cv_example.py --data_dir path_to_data # This will run the script on each server
|
| 203 |
+
```
|
| 204 |
+
* In PyTorch:
|
| 205 |
+
Add an `xmp.spawn` line in your script as you usually do.
|
| 206 |
+
|
| 207 |
+
### Simple vision example (GANs)
|
| 208 |
+
|
| 209 |
+
- [huggan project](https://github.com/huggingface/community-events/tree/main/huggan)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
### Using AWS SageMaker integration
|
| 213 |
+
- [Examples showcasing AWS SageMaker integration of 🤗 Accelerate.](https://github.com/pacman100/accelerate-aws-sagemaker)
|
| 214 |
+
|
| 215 |
+
## Configuration zoo
|
| 216 |
+
In [/config_yaml_templates](./config_yaml_templates/) we have a variety of *minimal* `config.yaml` templates and examples to help you learn
|
| 217 |
+
how to create your own configuration files depending on the scenario.
|
| 218 |
+
|
| 219 |
+
## SLURM Scripts
|
| 220 |
+
In [/slurm/submit_multigpu.sh](./slurm/submit_multigpu.sh) and [/slurm/submit_multinode.sh](./slurm/submit_multinode.sh) we present two scripts for running the examples on a machine with [SLURM](https://slurm.schedmd.com/documentation.html) workload manager.
|
| 221 |
+
|
| 222 |
+
In [/slurm/submit_multigpu.sh](./slurm/submit_multigpu.sh) the only parameter in the launcher that needs to be modified is `--num_processes`, which determines the number of GPUs we will use. In this case, using the environment variable `$SLURM_GPUS`, we indicate that we want to utilize all the GPUs available on the node we have requested.
|
| 223 |
+
|
| 224 |
+
In [/slurm/submit_multinode.sh](./slurm/submit_multinode.sh) we must specify the number of nodes that will be part of the training (`--num_machines`), how many GPUs we will use in total (`--num_processes`), the [`backend`](https://pytorch.org/docs/stable/elastic/run.html#note-on-rendezvous-backend), `--main_process_ip` which will be the address the master node and the `--main_process_port`.
|
| 225 |
+
|
| 226 |
+
In [/slurm/submit_multicpu.sh](./slurm/submit_multicpu.sh) we must specify the number of nodes that will be part of the training (`--num_machines`), how many CPU processes we will use in total (`--num_processes`), the [`backend`](https://pytorch.org/docs/stable/elastic/run.html#note-on-rendezvous-backend), `--main_process_ip` which will be the address the master node and the `--main_process_port`. `mpirun_hostfile` specifies to run the job using MPIRun.
|
| 227 |
+
|
| 228 |
+
In both scripts, we run `activateEnviroment.sh` at the beginning. This script should contain the necessary instructions to initialize the environment for execution. Below, we show an example that loads the necessary libraries ([Environment modules](https://github.com/cea-hpc/modules)), activates the Python environment, and sets up various environment variables, most of them to run the scripts in offline mode in case we don't have internet connection from the cluster.
|
| 229 |
+
|
| 230 |
+
```bash
|
| 231 |
+
# activateEnvironment.sh
|
| 232 |
+
module purge
|
| 233 |
+
module load anaconda3/2020.02 cuda/10.2 cudnn/8.0.5 nccl/2.9.9 arrow/7.0.0 openmpi
|
| 234 |
+
source activate /home/nct01/nct01328/pytorch_antoni_local
|
| 235 |
+
|
| 236 |
+
export HF_HOME=/gpfs/projects/nct01/nct01328/
|
| 237 |
+
export HF_LOCAL_HOME=/gpfs/projects/nct01/nct01328/HF_LOCAL
|
| 238 |
+
export HF_DATASETS_OFFLINE=1
|
| 239 |
+
export TRANSFORMERS_OFFLINE=1
|
| 240 |
+
export PYTHONPATH=/home/nct01/nct01328/transformers-in-supercomputers:$PYTHONPATH
|
| 241 |
+
export GPUS_PER_NODE=4
|
| 242 |
+
```
|
| 243 |
+
|
| 244 |
+
## Simple Multi-GPU Hardware Launcher (using an external platform)
|
| 245 |
+
|
| 246 |
+
[multigpu_remote_launcher.py](./multigpu_remote_launcher.py) is a minimal script that demonstrates launching accelerate
|
| 247 |
+
on multiple remote GPUs, and with automatic hardware environment and dependency setup for reproducibility. You can
|
| 248 |
+
easily customize the training function used, training arguments, hyperparameters, and type of compute hardware, and then
|
| 249 |
+
run the script to automatically launch multi GPU training on remote hardware.
|
| 250 |
+
|
| 251 |
+
This script uses [Runhouse](https://github.com/run-house/runhouse) to launch on self-hosted hardware (e.g. in your own
|
| 252 |
+
cloud account or on-premise cluster) but there are other options for running remotely as well. Runhouse can be installed
|
| 253 |
+
with `pip install runhouse`, and you can refer to
|
| 254 |
+
[hardware setup](https://runhouse-docs.readthedocs-hosted.com/en/latest/api/python/cluster.html#hardware-setup)
|
| 255 |
+
for hardware setup instructions, or this
|
| 256 |
+
[Colab tutorial](https://colab.research.google.com/drive/1qVwYyLTCPYPSdz9ZX7BZl9Qm0A3j7RJe) for a more in-depth walkthrough.
|
| 257 |
+
|
| 258 |
+
## Finer Examples
|
| 259 |
+
|
| 260 |
+
While the first two scripts are extremely barebones when it comes to what you can do with accelerate, more advanced features are documented in two other locations.
|
| 261 |
+
|
| 262 |
+
### `by_feature` examples
|
| 263 |
+
|
| 264 |
+
These scripts are *individual* examples highlighting one particular feature or use-case within Accelerate. They all stem from the [nlp_example.py](./nlp_example.py) script, and any changes or modifications is denoted with a `# New Code #` comment.
|
| 265 |
+
|
| 266 |
+
Read the README.md file located in the `by_feature` folder for more information.
|
| 267 |
+
|
| 268 |
+
### `complete_*` examples
|
| 269 |
+
|
| 270 |
+
These two scripts contain *every* single feature currently available in Accelerate in one place, as one giant script.
|
| 271 |
+
|
| 272 |
+
New arguments that can be passed include:
|
| 273 |
+
|
| 274 |
+
- `checkpointing_steps`, whether the various states should be saved at the end of every `n` steps, or `"epoch"` for each epoch. States are then saved to folders named `step_{n}` or `epoch_{n}`
|
| 275 |
+
- `resume_from_checkpoint`, should be used if you want to resume training off of a previous call to the script and passed a `checkpointing_steps` to it.
|
| 276 |
+
- `with_tracking`, should be used if you want to log the training run using all available experiment trackers in your environment. Currently supported trackers include TensorBoard, Weights and Biases, and CometML.
|
tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/README.md
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# What are these scripts?
|
| 2 |
+
|
| 3 |
+
All scripts in this folder originate from the `nlp_example.py` file, as it is a very simplistic NLP training example using Accelerate with zero extra features.
|
| 4 |
+
|
| 5 |
+
From there, each further script adds in just **one** feature of Accelerate, showing how you can quickly modify your own scripts to implement these capabilities.
|
| 6 |
+
|
| 7 |
+
A full example with all of these parts integrated together can be found in the `complete_nlp_example.py` script and `complete_cv_example.py` script.
|
| 8 |
+
|
| 9 |
+
Adjustments to each script from the base `nlp_example.py` file can be found quickly by searching for "# New Code #"
|
| 10 |
+
|
| 11 |
+
## Example Scripts by Feature and their Arguments
|
| 12 |
+
|
| 13 |
+
### Base Example (`../nlp_example.py`)
|
| 14 |
+
|
| 15 |
+
- Shows how to use `Accelerator` in an extremely simplistic PyTorch training loop
|
| 16 |
+
- Arguments available:
|
| 17 |
+
- `mixed_precision`, whether to use mixed precision. ("no", "fp16", or "bf16")
|
| 18 |
+
- `cpu`, whether to train using only the CPU. (yes/no/1/0)
|
| 19 |
+
|
| 20 |
+
All following scripts also accept these arguments in addition to their added ones.
|
| 21 |
+
|
| 22 |
+
These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torch.distributed.run`), such as:
|
| 23 |
+
|
| 24 |
+
```bash
|
| 25 |
+
accelerate launch ../nlp_example.py --mixed_precision fp16 --cpu 0
|
| 26 |
+
```
|
| 27 |
+
|
| 28 |
+
### Checkpointing and Resuming Training (`checkpointing.py`)
|
| 29 |
+
|
| 30 |
+
- Shows how to use `Accelerator.save_state` and `Accelerator.load_state` to save or continue training
|
| 31 |
+
- **It is assumed you are continuing off the same training script**
|
| 32 |
+
- Arguments available:
|
| 33 |
+
- `checkpointing_steps`, after how many steps the various states should be saved. ("epoch", 1, 2, ...)
|
| 34 |
+
- `output_dir`, where saved state folders should be saved to, default is current working directory
|
| 35 |
+
- `resume_from_checkpoint`, what checkpoint folder to resume from. ("epoch_0", "step_22", ...)
|
| 36 |
+
|
| 37 |
+
These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
|
| 38 |
+
|
| 39 |
+
(Note, `resume_from_checkpoint` assumes that we've ran the script for one epoch with the `--checkpointing_steps epoch` flag)
|
| 40 |
+
|
| 41 |
+
```bash
|
| 42 |
+
accelerate launch ./checkpointing.py --checkpointing_steps epoch output_dir "checkpointing_tutorial" --resume_from_checkpoint "checkpointing_tutorial/epoch_0"
|
| 43 |
+
```
|
| 44 |
+
|
| 45 |
+
### Cross Validation (`cross_validation.py`)
|
| 46 |
+
|
| 47 |
+
- Shows how to use `Accelerator.free_memory` and run cross validation efficiently with `datasets`.
|
| 48 |
+
- Arguments available:
|
| 49 |
+
- `num_folds`, the number of folds the training dataset should be split into.
|
| 50 |
+
|
| 51 |
+
These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
|
| 52 |
+
|
| 53 |
+
```bash
|
| 54 |
+
accelerate launch ./cross_validation.py --num_folds 2
|
| 55 |
+
```
|
| 56 |
+
|
| 57 |
+
### Experiment Tracking (`tracking.py`)
|
| 58 |
+
|
| 59 |
+
- Shows how to use `Accelerate.init_trackers` and `Accelerator.log`
|
| 60 |
+
- Can be used with Weights and Biases, TensorBoard, or CometML.
|
| 61 |
+
- Arguments available:
|
| 62 |
+
- `with_tracking`, whether to load in all available experiment trackers from the environment.
|
| 63 |
+
|
| 64 |
+
These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
|
| 65 |
+
|
| 66 |
+
```bash
|
| 67 |
+
accelerate launch ./tracking.py --with_tracking
|
| 68 |
+
```
|
| 69 |
+
|
| 70 |
+
### Gradient Accumulation (`gradient_accumulation.py`)
|
| 71 |
+
|
| 72 |
+
- Shows how to use `Accelerator.no_sync` to prevent gradient averaging in a distributed setup.
|
| 73 |
+
- Arguments available:
|
| 74 |
+
- `gradient_accumulation_steps`, the number of steps to perform before the gradients are accumulated and the optimizer and scheduler are stepped + zero_grad
|
| 75 |
+
|
| 76 |
+
These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
|
| 77 |
+
|
| 78 |
+
```bash
|
| 79 |
+
accelerate launch ./gradient_accumulation.py --gradient_accumulation_steps 5
|
| 80 |
+
```
|
| 81 |
+
|
| 82 |
+
### LocalSGD (`local_sgd.py`)
|
| 83 |
+
- Shows how to use `Accelerator.no_sync` to prevent gradient averaging in a distributed setup. However, unlike gradient accumulation, this method does not change the effective batch size. Local SGD can be combined with gradient accumulation.
|
| 84 |
+
|
| 85 |
+
These arguments should be added at the end of any method for starting the python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
|
| 86 |
+
|
| 87 |
+
```bash
|
| 88 |
+
accelerate launch ./local_sgd.py --local_sgd_steps 4
|
| 89 |
+
```
|
| 90 |
+
|
| 91 |
+
### DDP Communication Hook (`ddp_comm_hook.py`)
|
| 92 |
+
|
| 93 |
+
- Shows how to use DDP Communication Hooks to control and optimize gradient communication across workers in a DistributedDataParallel setup.
|
| 94 |
+
- Arguments available:
|
| 95 |
+
- `ddp_comm_hook`, the type of DDP communication hook to use. Choose between `no`, `fp16`, `bf16`, `power_sgd`, and `batched_power_sgd`.
|
| 96 |
+
|
| 97 |
+
These arguments should be added at the end of any method for starting the python script (such as `accelerate launch`, `python -m torch.distributed.run`), such as:
|
| 98 |
+
|
| 99 |
+
```bash
|
| 100 |
+
accelerate launch ./ddp_comm_hook.py --mixed_precision fp16 --ddp_comm_hook power_sgd
|
| 101 |
+
```
|
| 102 |
+
|
| 103 |
+
### Profiler (`profiler.py`)
|
| 104 |
+
|
| 105 |
+
- Shows how to use the profiling capabilities of `Accelerate` to profile PyTorch models during training.
|
| 106 |
+
- Uses the `ProfileKwargs` handler to customize profiling options, including activities, scheduling, and additional profiling options.
|
| 107 |
+
- Can generate and save profiling traces in JSON format for visualization in Chrome's tracing tool.
|
| 108 |
+
|
| 109 |
+
Arguments available:
|
| 110 |
+
- `--record_shapes`: If passed, records shapes for profiling.
|
| 111 |
+
- `--profile_memory`: If passed, profiles memory usage.
|
| 112 |
+
- `--with_stack`: If passed, profiles stack traces.
|
| 113 |
+
- `--with_flops`: If passed, profiles floating point operations (FLOPS).
|
| 114 |
+
- `--output_trace_dir`: If specified, saves the profiling trace to the given dir in JSON format.
|
| 115 |
+
- `--cpu`: If passed, trains on the CPU instead of GPU.
|
| 116 |
+
|
| 117 |
+
These arguments should be added at the end of any method for starting the Python script (such as `python`, `accelerate launch`, `python -m torchrun`), such as:
|
| 118 |
+
|
| 119 |
+
```bash
|
| 120 |
+
accelerate launch ./profiler.py --record_shapes --profile_memory --with_flops --output_trace_dir "profiler"
|
| 121 |
+
```
|
tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/automatic_gradient_accumulation.py
ADDED
|
@@ -0,0 +1,243 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2022 The HuggingFace Team. All rights reserved.
|
| 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 argparse
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
# New Code #
|
| 18 |
+
import evaluate
|
| 19 |
+
import torch
|
| 20 |
+
from datasets import load_dataset
|
| 21 |
+
from torch.optim import AdamW
|
| 22 |
+
from torch.utils.data import DataLoader
|
| 23 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
|
| 24 |
+
|
| 25 |
+
from accelerate import Accelerator
|
| 26 |
+
from accelerate.utils import find_executable_batch_size
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
########################################################################
|
| 30 |
+
# This is a fully working simple example to use Accelerate,
|
| 31 |
+
# specifically showcasing how to combine both the gradient accumulation
|
| 32 |
+
# and automatic batch size finder utilities of Accelerate to perfrom
|
| 33 |
+
# automatic gradient accumulation
|
| 34 |
+
#
|
| 35 |
+
# This example trains a Bert base model on GLUE MRPC
|
| 36 |
+
# in any of the following settings (with the same script):
|
| 37 |
+
# - single CPU or single GPU
|
| 38 |
+
# - multi GPUS (using PyTorch distributed mode)
|
| 39 |
+
# - (multi) TPUs
|
| 40 |
+
# - fp16 (mixed-precision) or fp32 (normal precision)
|
| 41 |
+
#
|
| 42 |
+
# New additions from the base script can be found quickly by
|
| 43 |
+
# looking for the # New Code # tags
|
| 44 |
+
#
|
| 45 |
+
# To run it in each of these various modes, follow the instructions
|
| 46 |
+
# in the readme for examples:
|
| 47 |
+
# https://github.com/huggingface/accelerate/tree/main/examples
|
| 48 |
+
#
|
| 49 |
+
########################################################################
|
| 50 |
+
|
| 51 |
+
EVAL_BATCH_SIZE = 32
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
|
| 55 |
+
"""
|
| 56 |
+
Creates a set of `DataLoader`s for the `glue` dataset,
|
| 57 |
+
using "bert-base-cased" as the tokenizer.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
accelerator (`Accelerator`):
|
| 61 |
+
An `Accelerator` object
|
| 62 |
+
batch_size (`int`, *optional*):
|
| 63 |
+
The batch size for the train and validation DataLoaders.
|
| 64 |
+
"""
|
| 65 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
| 66 |
+
datasets = load_dataset("glue", "mrpc")
|
| 67 |
+
|
| 68 |
+
def tokenize_function(examples):
|
| 69 |
+
# max_length=None => use the model max length (it's actually the default)
|
| 70 |
+
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
|
| 71 |
+
return outputs
|
| 72 |
+
|
| 73 |
+
# Apply the method we just defined to all the examples in all the splits of the dataset
|
| 74 |
+
# starting with the main process first:
|
| 75 |
+
with accelerator.main_process_first():
|
| 76 |
+
tokenized_datasets = datasets.map(
|
| 77 |
+
tokenize_function,
|
| 78 |
+
batched=True,
|
| 79 |
+
remove_columns=["idx", "sentence1", "sentence2"],
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
|
| 83 |
+
# transformers library
|
| 84 |
+
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
|
| 85 |
+
|
| 86 |
+
def collate_fn(examples):
|
| 87 |
+
# When using mixed precision we want round multiples of 8/16
|
| 88 |
+
if accelerator.mixed_precision == "fp8":
|
| 89 |
+
pad_to_multiple_of = 16
|
| 90 |
+
elif accelerator.mixed_precision != "no":
|
| 91 |
+
pad_to_multiple_of = 8
|
| 92 |
+
else:
|
| 93 |
+
pad_to_multiple_of = None
|
| 94 |
+
|
| 95 |
+
return tokenizer.pad(
|
| 96 |
+
examples,
|
| 97 |
+
padding="longest",
|
| 98 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 99 |
+
return_tensors="pt",
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# Instantiate dataloaders.
|
| 103 |
+
train_dataloader = DataLoader(
|
| 104 |
+
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
|
| 105 |
+
)
|
| 106 |
+
eval_dataloader = DataLoader(
|
| 107 |
+
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
return train_dataloader, eval_dataloader
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# For testing only
|
| 114 |
+
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
|
| 115 |
+
from accelerate.test_utils.training import mocked_dataloaders
|
| 116 |
+
|
| 117 |
+
get_dataloaders = mocked_dataloaders # noqa: F811
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def training_function(config, args):
|
| 121 |
+
# For testing only
|
| 122 |
+
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
|
| 123 |
+
config["num_epochs"] = 2
|
| 124 |
+
# Initialize accelerator
|
| 125 |
+
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
|
| 126 |
+
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
|
| 127 |
+
lr = config["lr"]
|
| 128 |
+
num_epochs = int(config["num_epochs"])
|
| 129 |
+
seed = int(config["seed"])
|
| 130 |
+
observed_batch_size = int(config["batch_size"])
|
| 131 |
+
|
| 132 |
+
metric = evaluate.load("glue", "mrpc")
|
| 133 |
+
|
| 134 |
+
# New Code #
|
| 135 |
+
# We use the `find_executable_batch_size` decorator, passing in the desired observed batch size
|
| 136 |
+
# to train on. If a CUDA OOM error occurs, it will retry this loop cutting the batch size in
|
| 137 |
+
# half each time. From this, we can calculate the number of gradient accumulation steps needed
|
| 138 |
+
# and modify the Accelerator object as a result
|
| 139 |
+
@find_executable_batch_size(starting_batch_size=int(observed_batch_size))
|
| 140 |
+
def inner_training_loop(batch_size):
|
| 141 |
+
# Since we need to modify the outside accelerator object, we need to bring it
|
| 142 |
+
# to the local scope
|
| 143 |
+
nonlocal accelerator
|
| 144 |
+
|
| 145 |
+
# We can calculate the number of gradient accumulation steps based on the current
|
| 146 |
+
# batch size vs the starting batch size
|
| 147 |
+
num_gradient_accumulation_steps = observed_batch_size // batch_size
|
| 148 |
+
|
| 149 |
+
# And then set it in the Accelerator directly:
|
| 150 |
+
accelerator.gradient_accumulation_steps = num_gradient_accumulation_steps
|
| 151 |
+
|
| 152 |
+
# Next we need to free all of the stored model references in the Accelerator each time
|
| 153 |
+
accelerator.free_memory()
|
| 154 |
+
|
| 155 |
+
# And set the seed so our results are reproducable each reset
|
| 156 |
+
set_seed(seed)
|
| 157 |
+
|
| 158 |
+
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
|
| 159 |
+
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
|
| 160 |
+
|
| 161 |
+
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
|
| 162 |
+
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
|
| 163 |
+
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
|
| 164 |
+
model = model.to(accelerator.device)
|
| 165 |
+
|
| 166 |
+
# Instantiate optimizer
|
| 167 |
+
optimizer = AdamW(params=model.parameters(), lr=lr)
|
| 168 |
+
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
|
| 169 |
+
|
| 170 |
+
# Instantiate scheduler
|
| 171 |
+
lr_scheduler = get_linear_schedule_with_warmup(
|
| 172 |
+
optimizer=optimizer,
|
| 173 |
+
num_warmup_steps=100,
|
| 174 |
+
num_training_steps=(len(train_dataloader) * num_epochs),
|
| 175 |
+
)
|
| 176 |
+
|
| 177 |
+
# Prepare everything
|
| 178 |
+
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
|
| 179 |
+
# prepare method.
|
| 180 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
|
| 181 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# Now we train the model
|
| 185 |
+
for epoch in range(num_epochs):
|
| 186 |
+
model.train()
|
| 187 |
+
for step, batch in enumerate(train_dataloader):
|
| 188 |
+
# And perform gradient accumulation
|
| 189 |
+
with accelerator.accumulate(model):
|
| 190 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 191 |
+
batch.to(accelerator.device)
|
| 192 |
+
outputs = model(**batch)
|
| 193 |
+
loss = outputs.loss
|
| 194 |
+
accelerator.backward(loss)
|
| 195 |
+
optimizer.step()
|
| 196 |
+
lr_scheduler.step()
|
| 197 |
+
optimizer.zero_grad()
|
| 198 |
+
|
| 199 |
+
model.eval()
|
| 200 |
+
for step, batch in enumerate(eval_dataloader):
|
| 201 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 202 |
+
batch.to(accelerator.device)
|
| 203 |
+
with torch.no_grad():
|
| 204 |
+
outputs = model(**batch)
|
| 205 |
+
predictions = outputs.logits.argmax(dim=-1)
|
| 206 |
+
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
|
| 207 |
+
metric.add_batch(
|
| 208 |
+
predictions=predictions,
|
| 209 |
+
references=references,
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
eval_metric = metric.compute()
|
| 213 |
+
# Use accelerator.print to print only on the main process.
|
| 214 |
+
accelerator.print(f"epoch {epoch}:", eval_metric)
|
| 215 |
+
|
| 216 |
+
# New Code #
|
| 217 |
+
# And call it at the end with no arguments
|
| 218 |
+
# Note: You could also refactor this outside of your training loop function
|
| 219 |
+
inner_training_loop()
|
| 220 |
+
accelerator.end_training()
|
| 221 |
+
|
| 222 |
+
|
| 223 |
+
def main():
|
| 224 |
+
parser = argparse.ArgumentParser(description="Simple example of training script.")
|
| 225 |
+
parser.add_argument(
|
| 226 |
+
"--mixed_precision",
|
| 227 |
+
type=str,
|
| 228 |
+
default=None,
|
| 229 |
+
choices=["no", "fp16", "bf16", "fp8"],
|
| 230 |
+
help="Whether to use mixed precision. Choose"
|
| 231 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 232 |
+
"and an Nvidia Ampere GPU.",
|
| 233 |
+
)
|
| 234 |
+
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
|
| 235 |
+
args = parser.parse_args()
|
| 236 |
+
# New Code #
|
| 237 |
+
# We modify the starting batch size to be an observed batch size of 256, to guarentee an initial CUDA OOM
|
| 238 |
+
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 256}
|
| 239 |
+
training_function(config, args)
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
if __name__ == "__main__":
|
| 243 |
+
main()
|
tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/checkpointing.py
ADDED
|
@@ -0,0 +1,326 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 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 argparse
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
import evaluate
|
| 18 |
+
import torch
|
| 19 |
+
from datasets import load_dataset
|
| 20 |
+
from torch.optim import AdamW
|
| 21 |
+
from torch.utils.data import DataLoader
|
| 22 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup
|
| 23 |
+
|
| 24 |
+
from accelerate import Accelerator, DataLoaderConfiguration, DistributedType
|
| 25 |
+
from accelerate.utils import set_seed
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
########################################################################
|
| 29 |
+
# This is a fully working simple example to use Accelerate,
|
| 30 |
+
# specifically showcasing the checkpointing capability,
|
| 31 |
+
# and builds off the `nlp_example.py` script.
|
| 32 |
+
#
|
| 33 |
+
# This example trains a Bert base model on GLUE MRPC
|
| 34 |
+
# in any of the following settings (with the same script):
|
| 35 |
+
# - single CPU or single GPU
|
| 36 |
+
# - multi GPUS (using PyTorch distributed mode)
|
| 37 |
+
# - (multi) TPUs
|
| 38 |
+
# - fp16 (mixed-precision) or fp32 (normal precision)
|
| 39 |
+
#
|
| 40 |
+
# To help focus on the differences in the code, building `DataLoaders`
|
| 41 |
+
# was refactored into its own function.
|
| 42 |
+
# New additions from the base script can be found quickly by
|
| 43 |
+
# looking for the # New Code # tags
|
| 44 |
+
#
|
| 45 |
+
# To run it in each of these various modes, follow the instructions
|
| 46 |
+
# in the readme for examples:
|
| 47 |
+
# https://github.com/huggingface/accelerate/tree/main/examples
|
| 48 |
+
#
|
| 49 |
+
########################################################################
|
| 50 |
+
|
| 51 |
+
MAX_GPU_BATCH_SIZE = 16
|
| 52 |
+
EVAL_BATCH_SIZE = 32
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
|
| 56 |
+
"""
|
| 57 |
+
Creates a set of `DataLoader`s for the `glue` dataset,
|
| 58 |
+
using "bert-base-cased" as the tokenizer.
|
| 59 |
+
|
| 60 |
+
Args:
|
| 61 |
+
accelerator (`Accelerator`):
|
| 62 |
+
An `Accelerator` object
|
| 63 |
+
batch_size (`int`, *optional*):
|
| 64 |
+
The batch size for the train and validation DataLoaders.
|
| 65 |
+
"""
|
| 66 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
| 67 |
+
datasets = load_dataset("glue", "mrpc")
|
| 68 |
+
|
| 69 |
+
def tokenize_function(examples):
|
| 70 |
+
# max_length=None => use the model max length (it's actually the default)
|
| 71 |
+
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
|
| 72 |
+
return outputs
|
| 73 |
+
|
| 74 |
+
# Apply the method we just defined to all the examples in all the splits of the dataset
|
| 75 |
+
# starting with the main process first:
|
| 76 |
+
with accelerator.main_process_first():
|
| 77 |
+
tokenized_datasets = datasets.map(
|
| 78 |
+
tokenize_function,
|
| 79 |
+
batched=True,
|
| 80 |
+
remove_columns=["idx", "sentence1", "sentence2"],
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
|
| 84 |
+
# transformers library
|
| 85 |
+
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
|
| 86 |
+
|
| 87 |
+
def collate_fn(examples):
|
| 88 |
+
# On TPU it's best to pad everything to the same length or training will be very slow.
|
| 89 |
+
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
|
| 90 |
+
# When using mixed precision we want round multiples of 8/16
|
| 91 |
+
if accelerator.mixed_precision == "fp8":
|
| 92 |
+
pad_to_multiple_of = 16
|
| 93 |
+
elif accelerator.mixed_precision != "no":
|
| 94 |
+
pad_to_multiple_of = 8
|
| 95 |
+
else:
|
| 96 |
+
pad_to_multiple_of = None
|
| 97 |
+
|
| 98 |
+
return tokenizer.pad(
|
| 99 |
+
examples,
|
| 100 |
+
padding="longest",
|
| 101 |
+
max_length=max_length,
|
| 102 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 103 |
+
return_tensors="pt",
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
# Instantiate dataloaders.
|
| 107 |
+
train_dataloader = DataLoader(
|
| 108 |
+
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
|
| 109 |
+
)
|
| 110 |
+
eval_dataloader = DataLoader(
|
| 111 |
+
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
return train_dataloader, eval_dataloader
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
# For testing only
|
| 118 |
+
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
|
| 119 |
+
from accelerate.test_utils.training import mocked_dataloaders
|
| 120 |
+
|
| 121 |
+
get_dataloaders = mocked_dataloaders # noqa: F811
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def training_function(config, args):
|
| 125 |
+
# For testing only
|
| 126 |
+
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
|
| 127 |
+
config["num_epochs"] = 2
|
| 128 |
+
# Initialize accelerator
|
| 129 |
+
dataloader_config = DataLoaderConfiguration(use_stateful_dataloader=args.use_stateful_dataloader)
|
| 130 |
+
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, dataloader_config=dataloader_config)
|
| 131 |
+
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
|
| 132 |
+
lr = config["lr"]
|
| 133 |
+
num_epochs = int(config["num_epochs"])
|
| 134 |
+
seed = int(config["seed"])
|
| 135 |
+
batch_size = int(config["batch_size"])
|
| 136 |
+
|
| 137 |
+
# New Code #
|
| 138 |
+
# Parse out whether we are saving every epoch or after a certain number of batches
|
| 139 |
+
if hasattr(args.checkpointing_steps, "isdigit"):
|
| 140 |
+
if args.checkpointing_steps == "epoch":
|
| 141 |
+
checkpointing_steps = args.checkpointing_steps
|
| 142 |
+
elif args.checkpointing_steps.isdigit():
|
| 143 |
+
checkpointing_steps = int(args.checkpointing_steps)
|
| 144 |
+
else:
|
| 145 |
+
raise ValueError(
|
| 146 |
+
f"Argument `checkpointing_steps` must be either a number or `epoch`. `{args.checkpointing_steps}` passed."
|
| 147 |
+
)
|
| 148 |
+
else:
|
| 149 |
+
checkpointing_steps = None
|
| 150 |
+
|
| 151 |
+
set_seed(seed)
|
| 152 |
+
|
| 153 |
+
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
|
| 154 |
+
metric = evaluate.load("glue", "mrpc")
|
| 155 |
+
|
| 156 |
+
# If the batch size is too big we use gradient accumulation
|
| 157 |
+
gradient_accumulation_steps = 1
|
| 158 |
+
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
|
| 159 |
+
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
|
| 160 |
+
batch_size = MAX_GPU_BATCH_SIZE
|
| 161 |
+
|
| 162 |
+
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
|
| 163 |
+
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
|
| 164 |
+
|
| 165 |
+
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
|
| 166 |
+
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
|
| 167 |
+
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
|
| 168 |
+
model = model.to(accelerator.device)
|
| 169 |
+
|
| 170 |
+
# Instantiate optimizer
|
| 171 |
+
optimizer = AdamW(params=model.parameters(), lr=lr)
|
| 172 |
+
|
| 173 |
+
# Instantiate scheduler
|
| 174 |
+
lr_scheduler = get_linear_schedule_with_warmup(
|
| 175 |
+
optimizer=optimizer,
|
| 176 |
+
num_warmup_steps=100,
|
| 177 |
+
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
# Prepare everything
|
| 181 |
+
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
|
| 182 |
+
# prepare method.
|
| 183 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
|
| 184 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
|
| 185 |
+
)
|
| 186 |
+
|
| 187 |
+
# New Code #
|
| 188 |
+
# We need to keep track of how many total steps we have iterated over
|
| 189 |
+
overall_step = 0
|
| 190 |
+
# We also need to keep track of the stating epoch so files are named properly
|
| 191 |
+
starting_epoch = 0
|
| 192 |
+
|
| 193 |
+
# We need to load the checkpoint back in before training here with `load_state`
|
| 194 |
+
# The total number of epochs is adjusted based on where the state is being loaded from,
|
| 195 |
+
# as we assume continuation of the same training script
|
| 196 |
+
if args.resume_from_checkpoint:
|
| 197 |
+
if args.resume_from_checkpoint is not None or args.resume_from_checkpoint != "":
|
| 198 |
+
accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
|
| 199 |
+
accelerator.load_state(args.resume_from_checkpoint)
|
| 200 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 201 |
+
else:
|
| 202 |
+
# Get the most recent checkpoint
|
| 203 |
+
dirs = [f.name for f in os.scandir(os.getcwd()) if f.is_dir()]
|
| 204 |
+
dirs.sort(key=os.path.getctime)
|
| 205 |
+
path = dirs[-1] # Sorts folders by date modified, most recent checkpoint is the last
|
| 206 |
+
# Extract `epoch_{i}` or `step_{i}`
|
| 207 |
+
training_difference = os.path.splitext(path)[0]
|
| 208 |
+
|
| 209 |
+
if "epoch" in training_difference:
|
| 210 |
+
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
|
| 211 |
+
resume_step = None
|
| 212 |
+
else:
|
| 213 |
+
resume_step = int(training_difference.replace("step_", ""))
|
| 214 |
+
starting_epoch = resume_step // len(train_dataloader)
|
| 215 |
+
resume_step -= starting_epoch * len(train_dataloader)
|
| 216 |
+
|
| 217 |
+
# Now we train the model
|
| 218 |
+
for epoch in range(starting_epoch, num_epochs):
|
| 219 |
+
model.train()
|
| 220 |
+
# New Code #
|
| 221 |
+
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
|
| 222 |
+
# We need to skip steps until we reach the resumed step only if we are not using a stateful dataloader
|
| 223 |
+
if not args.use_stateful_dataloader:
|
| 224 |
+
active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
|
| 225 |
+
else:
|
| 226 |
+
active_dataloader = train_dataloader
|
| 227 |
+
overall_step += resume_step
|
| 228 |
+
else:
|
| 229 |
+
# After the first iteration though, we need to go back to the original dataloader
|
| 230 |
+
active_dataloader = train_dataloader
|
| 231 |
+
for step, batch in enumerate(active_dataloader):
|
| 232 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 233 |
+
batch.to(accelerator.device)
|
| 234 |
+
outputs = model(**batch)
|
| 235 |
+
loss = outputs.loss
|
| 236 |
+
loss = loss / gradient_accumulation_steps
|
| 237 |
+
accelerator.backward(loss)
|
| 238 |
+
if step % gradient_accumulation_steps == 0:
|
| 239 |
+
optimizer.step()
|
| 240 |
+
lr_scheduler.step()
|
| 241 |
+
optimizer.zero_grad()
|
| 242 |
+
# New Code #
|
| 243 |
+
overall_step += 1
|
| 244 |
+
|
| 245 |
+
# New Code #
|
| 246 |
+
# We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
|
| 247 |
+
# These are saved to folders named `step_{overall_step}`
|
| 248 |
+
# Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
|
| 249 |
+
# If mixed precision was used, will also save a "scalar.bin" file
|
| 250 |
+
if isinstance(checkpointing_steps, int):
|
| 251 |
+
output_dir = f"step_{overall_step}"
|
| 252 |
+
if overall_step % checkpointing_steps == 0:
|
| 253 |
+
if args.output_dir is not None:
|
| 254 |
+
output_dir = os.path.join(args.output_dir, output_dir)
|
| 255 |
+
accelerator.save_state(output_dir)
|
| 256 |
+
model.eval()
|
| 257 |
+
for step, batch in enumerate(eval_dataloader):
|
| 258 |
+
# We could avoid this line since we set the accelerator with `device_placement=True` (the default).
|
| 259 |
+
batch.to(accelerator.device)
|
| 260 |
+
with torch.no_grad():
|
| 261 |
+
outputs = model(**batch)
|
| 262 |
+
predictions = outputs.logits.argmax(dim=-1)
|
| 263 |
+
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
|
| 264 |
+
metric.add_batch(
|
| 265 |
+
predictions=predictions,
|
| 266 |
+
references=references,
|
| 267 |
+
)
|
| 268 |
+
eval_metric = metric.compute()
|
| 269 |
+
# Use accelerator.print to print only on the main process.
|
| 270 |
+
accelerator.print(f"epoch {epoch}:", eval_metric)
|
| 271 |
+
|
| 272 |
+
# New Code #
|
| 273 |
+
# We save the model, optimizer, lr_scheduler, and seed states by calling `save_state`
|
| 274 |
+
# These are saved to folders named `epoch_{epoch}`
|
| 275 |
+
# Will contain files: "pytorch_model.bin", "optimizer.bin", "scheduler.bin", and "random_states.pkl"
|
| 276 |
+
# If mixed precision was used, will also save a "scalar.bin" file
|
| 277 |
+
if checkpointing_steps == "epoch":
|
| 278 |
+
output_dir = f"epoch_{epoch}"
|
| 279 |
+
if args.output_dir is not None:
|
| 280 |
+
output_dir = os.path.join(args.output_dir, output_dir)
|
| 281 |
+
accelerator.save_state(output_dir)
|
| 282 |
+
accelerator.end_training()
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
def main():
|
| 286 |
+
parser = argparse.ArgumentParser(description="Simple example of training script.")
|
| 287 |
+
parser.add_argument(
|
| 288 |
+
"--mixed_precision",
|
| 289 |
+
type=str,
|
| 290 |
+
default=None,
|
| 291 |
+
choices=["no", "fp16", "bf16", "fp8"],
|
| 292 |
+
help="Whether to use mixed precision. Choose"
|
| 293 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 294 |
+
"and an Nvidia Ampere GPU.",
|
| 295 |
+
)
|
| 296 |
+
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
|
| 297 |
+
parser.add_argument(
|
| 298 |
+
"--checkpointing_steps",
|
| 299 |
+
type=str,
|
| 300 |
+
default=None,
|
| 301 |
+
help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
|
| 302 |
+
)
|
| 303 |
+
parser.add_argument(
|
| 304 |
+
"--output_dir",
|
| 305 |
+
type=str,
|
| 306 |
+
default=".",
|
| 307 |
+
help="Optional save directory where all checkpoint folders will be stored. Default is the current working directory.",
|
| 308 |
+
)
|
| 309 |
+
parser.add_argument(
|
| 310 |
+
"--resume_from_checkpoint",
|
| 311 |
+
type=str,
|
| 312 |
+
default=None,
|
| 313 |
+
help="If the training should continue from a checkpoint folder.",
|
| 314 |
+
)
|
| 315 |
+
parser.add_argument(
|
| 316 |
+
"--use_stateful_dataloader",
|
| 317 |
+
action="store_true",
|
| 318 |
+
help="If the dataloader should be a resumable stateful dataloader.",
|
| 319 |
+
)
|
| 320 |
+
args = parser.parse_args()
|
| 321 |
+
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
|
| 322 |
+
training_function(config, args)
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
if __name__ == "__main__":
|
| 326 |
+
main()
|
tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/cross_validation.py
ADDED
|
@@ -0,0 +1,281 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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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 argparse
|
| 15 |
+
from typing import List
|
| 16 |
+
|
| 17 |
+
import evaluate
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from datasets import DatasetDict, load_dataset
|
| 21 |
+
|
| 22 |
+
# New Code #
|
| 23 |
+
# We'll be using StratifiedKFold for this example
|
| 24 |
+
from sklearn.model_selection import StratifiedKFold
|
| 25 |
+
from torch.optim import AdamW
|
| 26 |
+
from torch.utils.data import DataLoader
|
| 27 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
|
| 28 |
+
|
| 29 |
+
from accelerate import Accelerator, DistributedType
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
########################################################################
|
| 33 |
+
# This is a fully working simple example to use Accelerate,
|
| 34 |
+
# specifically showcasing how to perform Cross Validation,
|
| 35 |
+
# and builds off the `nlp_example.py` script.
|
| 36 |
+
#
|
| 37 |
+
# This example trains a Bert base model on GLUE MRPC
|
| 38 |
+
# in any of the following settings (with the same script):
|
| 39 |
+
# - single CPU or single GPU
|
| 40 |
+
# - multi GPUS (using PyTorch distributed mode)
|
| 41 |
+
# - (multi) TPUs
|
| 42 |
+
# - fp16 (mixed-precision) or fp32 (normal precision)
|
| 43 |
+
#
|
| 44 |
+
# To help focus on the differences in the code, building `DataLoaders`
|
| 45 |
+
# was refactored into its own function.
|
| 46 |
+
# New additions from the base script can be found quickly by
|
| 47 |
+
# looking for the # New Code # tags
|
| 48 |
+
#
|
| 49 |
+
# To run it in each of these various modes, follow the instructions
|
| 50 |
+
# in the readme for examples:
|
| 51 |
+
# https://github.com/huggingface/accelerate/tree/main/examples
|
| 52 |
+
#
|
| 53 |
+
########################################################################
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
MAX_GPU_BATCH_SIZE = 16
|
| 57 |
+
EVAL_BATCH_SIZE = 32
|
| 58 |
+
|
| 59 |
+
# New Code #
|
| 60 |
+
# We need a different `get_dataloaders` function that will build dataloaders by index
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def get_fold_dataloaders(
|
| 64 |
+
accelerator: Accelerator, dataset: DatasetDict, train_idxs: List[int], valid_idxs: List[int], batch_size: int = 16
|
| 65 |
+
):
|
| 66 |
+
"""
|
| 67 |
+
Gets a set of train, valid, and test dataloaders for a particular fold
|
| 68 |
+
|
| 69 |
+
Args:
|
| 70 |
+
accelerator (`Accelerator`):
|
| 71 |
+
The main `Accelerator` object
|
| 72 |
+
train_idxs (list of `int`):
|
| 73 |
+
The split indices for the training dataset
|
| 74 |
+
valid_idxs (list of `int`):
|
| 75 |
+
The split indices for the validation dataset
|
| 76 |
+
batch_size (`int`):
|
| 77 |
+
The size of the minibatch. Default is 16
|
| 78 |
+
"""
|
| 79 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
| 80 |
+
datasets = DatasetDict(
|
| 81 |
+
{
|
| 82 |
+
"train": dataset["train"].select(train_idxs),
|
| 83 |
+
"validation": dataset["train"].select(valid_idxs),
|
| 84 |
+
"test": dataset["validation"],
|
| 85 |
+
}
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
def tokenize_function(examples):
|
| 89 |
+
# max_length=None => use the model max length (it's actually the default)
|
| 90 |
+
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
|
| 91 |
+
return outputs
|
| 92 |
+
|
| 93 |
+
# Apply the method we just defined to all the examples in all the splits of the dataset
|
| 94 |
+
# starting with the main process first:
|
| 95 |
+
with accelerator.main_process_first():
|
| 96 |
+
tokenized_datasets = datasets.map(
|
| 97 |
+
tokenize_function,
|
| 98 |
+
batched=True,
|
| 99 |
+
remove_columns=["idx", "sentence1", "sentence2"],
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
|
| 103 |
+
# transformers library
|
| 104 |
+
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
|
| 105 |
+
|
| 106 |
+
def collate_fn(examples):
|
| 107 |
+
# On TPU it's best to pad everything to the same length or training will be very slow.
|
| 108 |
+
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
|
| 109 |
+
# When using mixed precision we want round multiples of 8/16
|
| 110 |
+
if accelerator.mixed_precision == "fp8":
|
| 111 |
+
pad_to_multiple_of = 16
|
| 112 |
+
elif accelerator.mixed_precision != "no":
|
| 113 |
+
pad_to_multiple_of = 8
|
| 114 |
+
else:
|
| 115 |
+
pad_to_multiple_of = None
|
| 116 |
+
|
| 117 |
+
return tokenizer.pad(
|
| 118 |
+
examples,
|
| 119 |
+
padding="longest",
|
| 120 |
+
max_length=max_length,
|
| 121 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 122 |
+
return_tensors="pt",
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
# Instantiate dataloaders.
|
| 126 |
+
train_dataloader = DataLoader(
|
| 127 |
+
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
|
| 128 |
+
)
|
| 129 |
+
eval_dataloader = DataLoader(
|
| 130 |
+
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
|
| 131 |
+
)
|
| 132 |
+
|
| 133 |
+
test_dataloader = DataLoader(
|
| 134 |
+
tokenized_datasets["test"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
return train_dataloader, eval_dataloader, test_dataloader
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def training_function(config, args):
|
| 141 |
+
# New Code #
|
| 142 |
+
test_predictions = []
|
| 143 |
+
# Download the dataset
|
| 144 |
+
datasets = load_dataset("glue", "mrpc")
|
| 145 |
+
# Create our splits
|
| 146 |
+
kfold = StratifiedKFold(n_splits=int(args.num_folds))
|
| 147 |
+
# Initialize accelerator
|
| 148 |
+
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
|
| 149 |
+
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
|
| 150 |
+
lr = config["lr"]
|
| 151 |
+
num_epochs = int(config["num_epochs"])
|
| 152 |
+
seed = int(config["seed"])
|
| 153 |
+
batch_size = int(config["batch_size"])
|
| 154 |
+
|
| 155 |
+
metric = evaluate.load("glue", "mrpc")
|
| 156 |
+
|
| 157 |
+
# If the batch size is too big we use gradient accumulation
|
| 158 |
+
gradient_accumulation_steps = 1
|
| 159 |
+
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
|
| 160 |
+
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
|
| 161 |
+
batch_size = MAX_GPU_BATCH_SIZE
|
| 162 |
+
|
| 163 |
+
set_seed(seed)
|
| 164 |
+
|
| 165 |
+
# New Code #
|
| 166 |
+
# Create our folds:
|
| 167 |
+
folds = kfold.split(np.zeros(datasets["train"].num_rows), datasets["train"]["label"])
|
| 168 |
+
test_references = []
|
| 169 |
+
# Iterate over them
|
| 170 |
+
for i, (train_idxs, valid_idxs) in enumerate(folds):
|
| 171 |
+
train_dataloader, eval_dataloader, test_dataloader = get_fold_dataloaders(
|
| 172 |
+
accelerator,
|
| 173 |
+
datasets,
|
| 174 |
+
train_idxs,
|
| 175 |
+
valid_idxs,
|
| 176 |
+
)
|
| 177 |
+
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
|
| 178 |
+
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
|
| 179 |
+
|
| 180 |
+
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
|
| 181 |
+
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
|
| 182 |
+
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
|
| 183 |
+
model = model.to(accelerator.device)
|
| 184 |
+
|
| 185 |
+
# Instantiate optimizer
|
| 186 |
+
optimizer = AdamW(params=model.parameters(), lr=lr)
|
| 187 |
+
|
| 188 |
+
# Instantiate scheduler
|
| 189 |
+
lr_scheduler = get_linear_schedule_with_warmup(
|
| 190 |
+
optimizer=optimizer,
|
| 191 |
+
num_warmup_steps=100,
|
| 192 |
+
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
# Prepare everything
|
| 196 |
+
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
|
| 197 |
+
# prepare method.
|
| 198 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
|
| 199 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
# Now we train the model
|
| 203 |
+
for epoch in range(num_epochs):
|
| 204 |
+
model.train()
|
| 205 |
+
for step, batch in enumerate(train_dataloader):
|
| 206 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 207 |
+
batch.to(accelerator.device)
|
| 208 |
+
outputs = model(**batch)
|
| 209 |
+
loss = outputs.loss
|
| 210 |
+
loss = loss / gradient_accumulation_steps
|
| 211 |
+
accelerator.backward(loss)
|
| 212 |
+
if step % gradient_accumulation_steps == 0:
|
| 213 |
+
optimizer.step()
|
| 214 |
+
lr_scheduler.step()
|
| 215 |
+
optimizer.zero_grad()
|
| 216 |
+
|
| 217 |
+
model.eval()
|
| 218 |
+
for step, batch in enumerate(eval_dataloader):
|
| 219 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 220 |
+
batch.to(accelerator.device)
|
| 221 |
+
with torch.no_grad():
|
| 222 |
+
outputs = model(**batch)
|
| 223 |
+
predictions = outputs.logits.argmax(dim=-1)
|
| 224 |
+
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
|
| 225 |
+
metric.add_batch(
|
| 226 |
+
predictions=predictions,
|
| 227 |
+
references=references,
|
| 228 |
+
)
|
| 229 |
+
|
| 230 |
+
eval_metric = metric.compute()
|
| 231 |
+
# Use accelerator.print to print only on the main process.
|
| 232 |
+
accelerator.print(f"epoch {epoch}:", eval_metric)
|
| 233 |
+
|
| 234 |
+
# New Code #
|
| 235 |
+
# We also run predictions on the test set at the very end
|
| 236 |
+
fold_predictions = []
|
| 237 |
+
for step, batch in enumerate(test_dataloader):
|
| 238 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 239 |
+
batch.to(accelerator.device)
|
| 240 |
+
with torch.no_grad():
|
| 241 |
+
outputs = model(**batch)
|
| 242 |
+
predictions = outputs.logits
|
| 243 |
+
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
|
| 244 |
+
fold_predictions.append(predictions.cpu())
|
| 245 |
+
if i == 0:
|
| 246 |
+
# We need all of the test predictions
|
| 247 |
+
test_references.append(references.cpu())
|
| 248 |
+
# Use accelerator.print to print only on the main process.
|
| 249 |
+
test_predictions.append(torch.cat(fold_predictions, dim=0))
|
| 250 |
+
# We now need to release all our memory and get rid of the current model, optimizer, etc
|
| 251 |
+
model, optimizer = accelerator.free_memory(model, optimizer)
|
| 252 |
+
# New Code #
|
| 253 |
+
# Finally we check the accuracy of our folded results:
|
| 254 |
+
test_references = torch.cat(test_references, dim=0)
|
| 255 |
+
preds = torch.stack(test_predictions, dim=0).sum(dim=0).div(int(args.num_folds)).argmax(dim=-1)
|
| 256 |
+
test_metric = metric.compute(predictions=preds, references=test_references)
|
| 257 |
+
accelerator.print("Average test metrics from all folds:", test_metric)
|
| 258 |
+
accelerator.end_training()
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def main():
|
| 262 |
+
parser = argparse.ArgumentParser(description="Simple example of training script.")
|
| 263 |
+
parser.add_argument(
|
| 264 |
+
"--mixed_precision",
|
| 265 |
+
type=str,
|
| 266 |
+
default=None,
|
| 267 |
+
choices=["no", "fp16", "bf16", "fp8"],
|
| 268 |
+
help="Whether to use mixed precision. Choose"
|
| 269 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 270 |
+
"and an Nvidia Ampere GPU.",
|
| 271 |
+
)
|
| 272 |
+
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
|
| 273 |
+
# New Code #
|
| 274 |
+
parser.add_argument("--num_folds", type=int, default=3, help="The number of splits to perform across the dataset")
|
| 275 |
+
args = parser.parse_args()
|
| 276 |
+
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
|
| 277 |
+
training_function(config, args)
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
if __name__ == "__main__":
|
| 281 |
+
main()
|
tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/ddp_comm_hook.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 The HuggingFace Inc. team. All rights reserved.
|
| 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 argparse
|
| 15 |
+
import os
|
| 16 |
+
|
| 17 |
+
import evaluate
|
| 18 |
+
import torch
|
| 19 |
+
from datasets import load_dataset
|
| 20 |
+
from torch.optim import AdamW
|
| 21 |
+
from torch.utils.data import DataLoader
|
| 22 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
|
| 23 |
+
|
| 24 |
+
from accelerate import Accelerator, DistributedType
|
| 25 |
+
from accelerate.utils import DDPCommunicationHookType, DistributedDataParallelKwargs
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
########################################################################
|
| 29 |
+
# This is a fully working simple example to use Accelerate
|
| 30 |
+
# and perform ddp communication hook
|
| 31 |
+
#
|
| 32 |
+
# This example trains a Bert base model on GLUE MRPC
|
| 33 |
+
# in any of the following settings (with the same script):
|
| 34 |
+
# - single CPU or single GPU
|
| 35 |
+
# - multi GPUS (using PyTorch distributed mode)
|
| 36 |
+
# - (multi) TPUs
|
| 37 |
+
# - fp16 (mixed-precision) or fp32 (normal precision)
|
| 38 |
+
#
|
| 39 |
+
# To run it in each of these various modes, follow the instructions
|
| 40 |
+
# in the readme for examples:
|
| 41 |
+
# https://github.com/huggingface/accelerate/tree/main/examples
|
| 42 |
+
#
|
| 43 |
+
########################################################################
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
MAX_GPU_BATCH_SIZE = 16
|
| 47 |
+
EVAL_BATCH_SIZE = 32
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
|
| 51 |
+
"""
|
| 52 |
+
Creates a set of `DataLoader`s for the `glue` dataset,
|
| 53 |
+
using "bert-base-cased" as the tokenizer.
|
| 54 |
+
|
| 55 |
+
Args:
|
| 56 |
+
accelerator (`Accelerator`):
|
| 57 |
+
An `Accelerator` object
|
| 58 |
+
batch_size (`int`, *optional*):
|
| 59 |
+
The batch size for the train and validation DataLoaders.
|
| 60 |
+
"""
|
| 61 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
| 62 |
+
datasets = load_dataset("glue", "mrpc")
|
| 63 |
+
|
| 64 |
+
def tokenize_function(examples):
|
| 65 |
+
# max_length=None => use the model max length (it's actually the default)
|
| 66 |
+
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
|
| 67 |
+
return outputs
|
| 68 |
+
|
| 69 |
+
# Apply the method we just defined to all the examples in all the splits of the dataset
|
| 70 |
+
# starting with the main process first:
|
| 71 |
+
with accelerator.main_process_first():
|
| 72 |
+
tokenized_datasets = datasets.map(
|
| 73 |
+
tokenize_function,
|
| 74 |
+
batched=True,
|
| 75 |
+
remove_columns=["idx", "sentence1", "sentence2"],
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
|
| 79 |
+
# transformers library
|
| 80 |
+
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
|
| 81 |
+
|
| 82 |
+
def collate_fn(examples):
|
| 83 |
+
# On TPU it's best to pad everything to the same length or training will be very slow.
|
| 84 |
+
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
|
| 85 |
+
# When using mixed precision we want round multiples of 8/16
|
| 86 |
+
if accelerator.mixed_precision == "fp8":
|
| 87 |
+
pad_to_multiple_of = 16
|
| 88 |
+
elif accelerator.mixed_precision != "no":
|
| 89 |
+
pad_to_multiple_of = 8
|
| 90 |
+
else:
|
| 91 |
+
pad_to_multiple_of = None
|
| 92 |
+
|
| 93 |
+
return tokenizer.pad(
|
| 94 |
+
examples,
|
| 95 |
+
padding="longest",
|
| 96 |
+
max_length=max_length,
|
| 97 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 98 |
+
return_tensors="pt",
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
# Instantiate dataloaders.
|
| 102 |
+
train_dataloader = DataLoader(
|
| 103 |
+
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size
|
| 104 |
+
)
|
| 105 |
+
eval_dataloader = DataLoader(
|
| 106 |
+
tokenized_datasets["validation"], shuffle=False, collate_fn=collate_fn, batch_size=EVAL_BATCH_SIZE
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
return train_dataloader, eval_dataloader
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# For testing only
|
| 113 |
+
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
|
| 114 |
+
from accelerate.test_utils.training import mocked_dataloaders
|
| 115 |
+
|
| 116 |
+
get_dataloaders = mocked_dataloaders # noqa: F811
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def training_function(config, args):
|
| 120 |
+
# For testing only
|
| 121 |
+
if os.environ.get("TESTING_MOCKED_DATALOADERS", None) == "1":
|
| 122 |
+
config["num_epochs"] = 2
|
| 123 |
+
# New Code #
|
| 124 |
+
ddp_comm_hook_type = DDPCommunicationHookType(args.ddp_comm_hook)
|
| 125 |
+
ddp_comm_wrapper = DDPCommunicationHookType(args.ddp_comm_wrapper)
|
| 126 |
+
ddp_kwargs = DistributedDataParallelKwargs(comm_hook=ddp_comm_hook_type, comm_wrapper=ddp_comm_wrapper)
|
| 127 |
+
# Initialize accelerator
|
| 128 |
+
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision, kwargs_handlers=[ddp_kwargs])
|
| 129 |
+
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
|
| 130 |
+
lr = config["lr"]
|
| 131 |
+
num_epochs = int(config["num_epochs"])
|
| 132 |
+
seed = int(config["seed"])
|
| 133 |
+
batch_size = int(config["batch_size"])
|
| 134 |
+
|
| 135 |
+
metric = evaluate.load("glue", "mrpc")
|
| 136 |
+
|
| 137 |
+
set_seed(seed)
|
| 138 |
+
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
|
| 139 |
+
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
|
| 140 |
+
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
|
| 141 |
+
|
| 142 |
+
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
|
| 143 |
+
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
|
| 144 |
+
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
|
| 145 |
+
model = model.to(accelerator.device)
|
| 146 |
+
|
| 147 |
+
# Instantiate optimizer
|
| 148 |
+
optimizer = AdamW(params=model.parameters(), lr=lr)
|
| 149 |
+
|
| 150 |
+
# Instantiate scheduler
|
| 151 |
+
lr_scheduler = get_linear_schedule_with_warmup(
|
| 152 |
+
optimizer=optimizer,
|
| 153 |
+
num_warmup_steps=100,
|
| 154 |
+
num_training_steps=(len(train_dataloader) * num_epochs),
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
# Prepare everything
|
| 158 |
+
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
|
| 159 |
+
# prepare method.
|
| 160 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
|
| 161 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
# Now we train the model
|
| 165 |
+
for epoch in range(num_epochs):
|
| 166 |
+
model.train()
|
| 167 |
+
for step, batch in enumerate(train_dataloader):
|
| 168 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 169 |
+
batch.to(accelerator.device)
|
| 170 |
+
# We use the new `accumulate` context manager to perform gradient accumulation
|
| 171 |
+
with accelerator.accumulate(model):
|
| 172 |
+
output = model(**batch)
|
| 173 |
+
loss = output.loss
|
| 174 |
+
accelerator.backward(loss)
|
| 175 |
+
optimizer.step()
|
| 176 |
+
lr_scheduler.step()
|
| 177 |
+
optimizer.zero_grad()
|
| 178 |
+
|
| 179 |
+
model.eval()
|
| 180 |
+
for step, batch in enumerate(eval_dataloader):
|
| 181 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 182 |
+
batch.to(accelerator.device)
|
| 183 |
+
with torch.no_grad():
|
| 184 |
+
outputs = model(**batch)
|
| 185 |
+
predictions = outputs.logits.argmax(dim=-1)
|
| 186 |
+
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
|
| 187 |
+
metric.add_batch(
|
| 188 |
+
predictions=predictions,
|
| 189 |
+
references=references,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
eval_metric = metric.compute()
|
| 193 |
+
# Use accelerator.print to print only on the main process.
|
| 194 |
+
accelerator.print(f"epoch {epoch}:", eval_metric)
|
| 195 |
+
accelerator.end_training()
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
def main():
|
| 199 |
+
parser = argparse.ArgumentParser(description="Simple example of training script.")
|
| 200 |
+
parser.add_argument(
|
| 201 |
+
"--mixed_precision",
|
| 202 |
+
type=str,
|
| 203 |
+
default=None,
|
| 204 |
+
choices=["no", "fp16", "bf16", "fp8"],
|
| 205 |
+
help="Whether to use mixed precision. Choose"
|
| 206 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 207 |
+
"and an Nvidia Ampere GPU.",
|
| 208 |
+
)
|
| 209 |
+
# New Code #
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--ddp_comm_hook",
|
| 212 |
+
type=str,
|
| 213 |
+
default="no",
|
| 214 |
+
choices=["no", "fp16", "bf16", "power_sgd", "batched_power_sgd"],
|
| 215 |
+
help="DDP Communication hook to use. Choose between `no`, `fp16`, `bf16`, `power_sgd`, and `batched_power_sgd`.",
|
| 216 |
+
)
|
| 217 |
+
# New Code #
|
| 218 |
+
parser.add_argument(
|
| 219 |
+
"--ddp_comm_wrapper",
|
| 220 |
+
type=str,
|
| 221 |
+
default="no",
|
| 222 |
+
choices=["no", "fp16", "bf16"],
|
| 223 |
+
help="DDP Communication wrapper to use. Choose between `no`, `fp16`, and `bf16`.",
|
| 224 |
+
)
|
| 225 |
+
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
|
| 226 |
+
args = parser.parse_args()
|
| 227 |
+
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
|
| 228 |
+
training_function(config, args)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
if __name__ == "__main__":
|
| 232 |
+
main()
|
tasks/tasksmith-ae8f12dc63d0/environment/source/examples/by_feature/deepspeed_with_config_support.py
ADDED
|
@@ -0,0 +1,723 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# Copyright 2022 The HuggingFace Inc. 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 |
+
Fine-tuning the library models for causal language modeling (GPT, GPT-2, CTRL, ...)
|
| 17 |
+
on a text file or a dataset without using HuggingFace Trainer.
|
| 18 |
+
|
| 19 |
+
Here is the full list of checkpoints on the hub that can be fine-tuned by this script:
|
| 20 |
+
https://huggingface.co/models?filter=text-generation
|
| 21 |
+
"""
|
| 22 |
+
# You can also adapt this script on your own causal language modeling task. Pointers for this are left as comments.
|
| 23 |
+
|
| 24 |
+
import argparse
|
| 25 |
+
import json
|
| 26 |
+
import logging
|
| 27 |
+
import math
|
| 28 |
+
import os
|
| 29 |
+
import random
|
| 30 |
+
from itertools import chain
|
| 31 |
+
from pathlib import Path
|
| 32 |
+
|
| 33 |
+
import datasets
|
| 34 |
+
import torch
|
| 35 |
+
import transformers
|
| 36 |
+
from datasets import load_dataset
|
| 37 |
+
from huggingface_hub import HfApi
|
| 38 |
+
from torch.utils.data import DataLoader
|
| 39 |
+
from tqdm.auto import tqdm
|
| 40 |
+
from transformers import (
|
| 41 |
+
CONFIG_MAPPING,
|
| 42 |
+
MODEL_MAPPING,
|
| 43 |
+
AutoConfig,
|
| 44 |
+
AutoModelForCausalLM,
|
| 45 |
+
AutoTokenizer,
|
| 46 |
+
SchedulerType,
|
| 47 |
+
default_data_collator,
|
| 48 |
+
get_scheduler,
|
| 49 |
+
)
|
| 50 |
+
from transformers.utils.versions import require_version
|
| 51 |
+
|
| 52 |
+
from accelerate import Accelerator, DistributedType
|
| 53 |
+
from accelerate.logging import get_logger
|
| 54 |
+
from accelerate.utils import DummyOptim, DummyScheduler, set_seed
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
logger = get_logger(__name__)
|
| 58 |
+
|
| 59 |
+
require_version("datasets>=1.8.0", "To fix: pip install -r examples/pytorch/language-modeling/requirements.txt")
|
| 60 |
+
|
| 61 |
+
MODEL_CONFIG_CLASSES = list(MODEL_MAPPING.keys())
|
| 62 |
+
MODEL_TYPES = tuple(conf.model_type for conf in MODEL_CONFIG_CLASSES)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def parse_args():
|
| 66 |
+
parser = argparse.ArgumentParser(description="Finetune a transformers model on a causal language modeling task")
|
| 67 |
+
parser.add_argument(
|
| 68 |
+
"--dataset_name",
|
| 69 |
+
type=str,
|
| 70 |
+
default=None,
|
| 71 |
+
help="The name of the dataset to use (via the datasets library).",
|
| 72 |
+
)
|
| 73 |
+
parser.add_argument(
|
| 74 |
+
"--dataset_config_name",
|
| 75 |
+
type=str,
|
| 76 |
+
default=None,
|
| 77 |
+
help="The configuration name of the dataset to use (via the datasets library).",
|
| 78 |
+
)
|
| 79 |
+
parser.add_argument(
|
| 80 |
+
"--train_file", type=str, default=None, help="A csv or a json file containing the training data."
|
| 81 |
+
)
|
| 82 |
+
parser.add_argument(
|
| 83 |
+
"--validation_file", type=str, default=None, help="A csv or a json file containing the validation data."
|
| 84 |
+
)
|
| 85 |
+
parser.add_argument(
|
| 86 |
+
"--validation_split_percentage",
|
| 87 |
+
default=5,
|
| 88 |
+
help="The percentage of the train set used as validation set in case there's no validation split",
|
| 89 |
+
)
|
| 90 |
+
parser.add_argument(
|
| 91 |
+
"--model_name_or_path",
|
| 92 |
+
type=str,
|
| 93 |
+
help="Path to pretrained model or model identifier from huggingface.co/models.",
|
| 94 |
+
required=False,
|
| 95 |
+
)
|
| 96 |
+
parser.add_argument(
|
| 97 |
+
"--config_name",
|
| 98 |
+
type=str,
|
| 99 |
+
default=None,
|
| 100 |
+
help="Pretrained config name or path if not the same as model_name",
|
| 101 |
+
)
|
| 102 |
+
parser.add_argument(
|
| 103 |
+
"--tokenizer_name",
|
| 104 |
+
type=str,
|
| 105 |
+
default=None,
|
| 106 |
+
help="Pretrained tokenizer name or path if not the same as model_name",
|
| 107 |
+
)
|
| 108 |
+
parser.add_argument(
|
| 109 |
+
"--use_slow_tokenizer",
|
| 110 |
+
action="store_true",
|
| 111 |
+
help="If passed, will use a slow tokenizer (not backed by the 🤗 Tokenizers library).",
|
| 112 |
+
)
|
| 113 |
+
parser.add_argument(
|
| 114 |
+
"--per_device_train_batch_size",
|
| 115 |
+
type=int,
|
| 116 |
+
default=8,
|
| 117 |
+
help="Batch size (per device) for the training dataloader.",
|
| 118 |
+
)
|
| 119 |
+
parser.add_argument(
|
| 120 |
+
"--per_device_eval_batch_size",
|
| 121 |
+
type=int,
|
| 122 |
+
default=8,
|
| 123 |
+
help="Batch size (per device) for the evaluation dataloader.",
|
| 124 |
+
)
|
| 125 |
+
parser.add_argument(
|
| 126 |
+
"--learning_rate",
|
| 127 |
+
type=float,
|
| 128 |
+
default=5e-5,
|
| 129 |
+
help="Initial learning rate (after the potential warmup period) to use.",
|
| 130 |
+
)
|
| 131 |
+
parser.add_argument("--weight_decay", type=float, default=0.0, help="Weight decay to use.")
|
| 132 |
+
parser.add_argument("--num_train_epochs", type=int, default=3, help="Total number of training epochs to perform.")
|
| 133 |
+
parser.add_argument(
|
| 134 |
+
"--max_train_steps",
|
| 135 |
+
type=int,
|
| 136 |
+
default=None,
|
| 137 |
+
help="Total number of training steps to perform. If provided, overrides num_train_epochs.",
|
| 138 |
+
)
|
| 139 |
+
parser.add_argument(
|
| 140 |
+
"--gradient_accumulation_steps",
|
| 141 |
+
type=int,
|
| 142 |
+
default=1,
|
| 143 |
+
help="Number of updates steps to accumulate before performing a backward/update pass.",
|
| 144 |
+
)
|
| 145 |
+
parser.add_argument(
|
| 146 |
+
"--lr_scheduler_type",
|
| 147 |
+
type=SchedulerType,
|
| 148 |
+
default="linear",
|
| 149 |
+
help="The scheduler type to use.",
|
| 150 |
+
choices=["linear", "cosine", "cosine_with_restarts", "polynomial", "constant", "constant_with_warmup"],
|
| 151 |
+
)
|
| 152 |
+
parser.add_argument(
|
| 153 |
+
"--num_warmup_steps", type=int, default=0, help="Number of steps for the warmup in the lr scheduler."
|
| 154 |
+
)
|
| 155 |
+
parser.add_argument("--output_dir", type=str, default=None, help="Where to store the final model.")
|
| 156 |
+
parser.add_argument("--seed", type=int, default=None, help="A seed for reproducible training.")
|
| 157 |
+
parser.add_argument(
|
| 158 |
+
"--model_type",
|
| 159 |
+
type=str,
|
| 160 |
+
default=None,
|
| 161 |
+
help="Model type to use if training from scratch.",
|
| 162 |
+
choices=MODEL_TYPES,
|
| 163 |
+
)
|
| 164 |
+
parser.add_argument(
|
| 165 |
+
"--block_size",
|
| 166 |
+
type=int,
|
| 167 |
+
default=None,
|
| 168 |
+
help=(
|
| 169 |
+
"Optional input sequence length after tokenization. The training dataset will be truncated in block of"
|
| 170 |
+
" this size for training. Default to the model max input length for single sentence inputs (take into"
|
| 171 |
+
" account special tokens)."
|
| 172 |
+
),
|
| 173 |
+
)
|
| 174 |
+
parser.add_argument(
|
| 175 |
+
"--preprocessing_num_workers",
|
| 176 |
+
type=int,
|
| 177 |
+
default=None,
|
| 178 |
+
help="The number of processes to use for the preprocessing.",
|
| 179 |
+
)
|
| 180 |
+
parser.add_argument(
|
| 181 |
+
"--overwrite_cache", type=bool, default=False, help="Overwrite the cached training and evaluation sets"
|
| 182 |
+
)
|
| 183 |
+
parser.add_argument(
|
| 184 |
+
"--no_keep_linebreaks", action="store_true", help="Do not keep line breaks when using TXT files."
|
| 185 |
+
)
|
| 186 |
+
parser.add_argument("--push_to_hub", action="store_true", help="Whether or not to push the model to the Hub.")
|
| 187 |
+
parser.add_argument(
|
| 188 |
+
"--hub_model_id", type=str, help="The name of the repository to keep in sync with the local `output_dir`."
|
| 189 |
+
)
|
| 190 |
+
parser.add_argument("--hub_token", type=str, help="The token to use to push to the Model Hub.")
|
| 191 |
+
parser.add_argument(
|
| 192 |
+
"--checkpointing_steps",
|
| 193 |
+
type=str,
|
| 194 |
+
default=None,
|
| 195 |
+
help="Whether the various states should be saved at the end of every n steps, or 'epoch' for each epoch.",
|
| 196 |
+
)
|
| 197 |
+
parser.add_argument(
|
| 198 |
+
"--resume_from_checkpoint",
|
| 199 |
+
type=str,
|
| 200 |
+
default=None,
|
| 201 |
+
help="If the training should continue from a checkpoint folder.",
|
| 202 |
+
)
|
| 203 |
+
# New Code #
|
| 204 |
+
# Whether to load the best model at the end of training
|
| 205 |
+
parser.add_argument(
|
| 206 |
+
"--load_best_model",
|
| 207 |
+
action="store_true",
|
| 208 |
+
help="Whether to load the best model at the end of training",
|
| 209 |
+
)
|
| 210 |
+
parser.add_argument(
|
| 211 |
+
"--with_tracking",
|
| 212 |
+
action="store_true",
|
| 213 |
+
help="Whether to enable experiment trackers for logging.",
|
| 214 |
+
)
|
| 215 |
+
parser.add_argument(
|
| 216 |
+
"--report_to",
|
| 217 |
+
type=str,
|
| 218 |
+
default="all",
|
| 219 |
+
help=(
|
| 220 |
+
'The integration to report the results and logs to. Supported platforms are `"tensorboard"`,'
|
| 221 |
+
' `"wandb"`, `"comet_ml"`, and `"dvclive"`. Use `"all"` (default) to report to all integrations.'
|
| 222 |
+
"Only applicable when `--with_tracking` is passed."
|
| 223 |
+
),
|
| 224 |
+
)
|
| 225 |
+
args = parser.parse_args()
|
| 226 |
+
|
| 227 |
+
# Sanity checks
|
| 228 |
+
if args.dataset_name is None and args.train_file is None and args.validation_file is None:
|
| 229 |
+
raise ValueError("Need either a dataset name or a training/validation file.")
|
| 230 |
+
else:
|
| 231 |
+
if args.train_file is not None:
|
| 232 |
+
extension = args.train_file.split(".")[-1]
|
| 233 |
+
assert extension in ["csv", "json", "txt"], "`train_file` should be a csv, json or txt file."
|
| 234 |
+
if args.validation_file is not None:
|
| 235 |
+
extension = args.validation_file.split(".")[-1]
|
| 236 |
+
assert extension in ["csv", "json", "txt"], "`validation_file` should be a csv, json or txt file."
|
| 237 |
+
|
| 238 |
+
if args.push_to_hub:
|
| 239 |
+
assert args.output_dir is not None, "Need an `output_dir` to create a repo when `--push_to_hub` is passed."
|
| 240 |
+
|
| 241 |
+
return args
|
| 242 |
+
|
| 243 |
+
|
| 244 |
+
# New Code #
|
| 245 |
+
def evaluate(args, model, eval_dataloader, accelerator, eval_dataset):
|
| 246 |
+
model.eval()
|
| 247 |
+
losses = []
|
| 248 |
+
for step, batch in enumerate(eval_dataloader):
|
| 249 |
+
with torch.no_grad():
|
| 250 |
+
outputs = model(**batch)
|
| 251 |
+
|
| 252 |
+
loss = outputs.loss
|
| 253 |
+
losses.append(accelerator.gather_for_metrics(loss.repeat(args.per_device_eval_batch_size)))
|
| 254 |
+
|
| 255 |
+
losses = torch.cat(losses)
|
| 256 |
+
try:
|
| 257 |
+
eval_loss = torch.mean(losses)
|
| 258 |
+
perplexity = math.exp(eval_loss)
|
| 259 |
+
except OverflowError:
|
| 260 |
+
perplexity = float("inf")
|
| 261 |
+
return perplexity, eval_loss
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
def main():
|
| 265 |
+
args = parse_args()
|
| 266 |
+
|
| 267 |
+
# Initialize the accelerator. We will let the accelerator handle device placement for us in this example.
|
| 268 |
+
# If we're using tracking, we also need to initialize it here and it will by default pick up all supported trackers
|
| 269 |
+
# in the environment
|
| 270 |
+
|
| 271 |
+
# when using DeepSpeed, the `gradient_accumulation_steps` is properly set from the DeepSpeed plugin/config
|
| 272 |
+
# or from `accelerate launch` via `--gradient_accumulation_steps` else
|
| 273 |
+
# defaulting to the passed `args.gradient_accumulation_steps`
|
| 274 |
+
accelerator = (
|
| 275 |
+
Accelerator(
|
| 276 |
+
log_with=args.report_to,
|
| 277 |
+
project_dir=args.output_dir,
|
| 278 |
+
gradient_accumulation_steps=args.gradient_accumulation_steps,
|
| 279 |
+
)
|
| 280 |
+
if args.with_tracking
|
| 281 |
+
else Accelerator(gradient_accumulation_steps=args.gradient_accumulation_steps)
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
# Make one log on every process with the configuration for debugging.
|
| 285 |
+
logging.basicConfig(
|
| 286 |
+
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
|
| 287 |
+
datefmt="%m/%d/%Y %H:%M:%S",
|
| 288 |
+
level=logging.INFO,
|
| 289 |
+
)
|
| 290 |
+
logger.info(accelerator.state, main_process_only=False)
|
| 291 |
+
if accelerator.is_local_main_process:
|
| 292 |
+
datasets.utils.logging.set_verbosity_warning()
|
| 293 |
+
transformers.utils.logging.set_verbosity_info()
|
| 294 |
+
else:
|
| 295 |
+
datasets.utils.logging.set_verbosity_error()
|
| 296 |
+
transformers.utils.logging.set_verbosity_error()
|
| 297 |
+
|
| 298 |
+
# If passed along, set the training seed now.
|
| 299 |
+
if args.seed is not None:
|
| 300 |
+
set_seed(args.seed)
|
| 301 |
+
|
| 302 |
+
# Handle the repository creation
|
| 303 |
+
if accelerator.is_main_process:
|
| 304 |
+
if args.push_to_hub:
|
| 305 |
+
api = HfApi(token=args.hub_token)
|
| 306 |
+
|
| 307 |
+
# Create repo (repo_name from args or inferred)
|
| 308 |
+
repo_name = args.hub_model_id
|
| 309 |
+
if repo_name is None:
|
| 310 |
+
repo_name = Path(args.output_dir).absolute().name
|
| 311 |
+
repo_id = api.create_repo(repo_name, exist_ok=True).repo_id
|
| 312 |
+
|
| 313 |
+
with open(os.path.join(args.output_dir, ".gitignore"), "w+") as gitignore:
|
| 314 |
+
if "step_*" not in gitignore:
|
| 315 |
+
gitignore.write("step_*\n")
|
| 316 |
+
if "epoch_*" not in gitignore:
|
| 317 |
+
gitignore.write("epoch_*\n")
|
| 318 |
+
elif args.output_dir is not None:
|
| 319 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 320 |
+
accelerator.wait_for_everyone()
|
| 321 |
+
|
| 322 |
+
# Get the datasets: you can either provide your own CSV/JSON/TXT training and evaluation files (see below)
|
| 323 |
+
# or just provide the name of one of the public datasets available on the hub at https://huggingface.co/datasets/
|
| 324 |
+
# (the dataset will be downloaded automatically from the datasets Hub).
|
| 325 |
+
#
|
| 326 |
+
# For CSV/JSON files, this script will use the column called 'text' or the first column if no column called
|
| 327 |
+
# 'text' is found. You can easily tweak this behavior (see below).
|
| 328 |
+
#
|
| 329 |
+
# In distributed training, the load_dataset function guarantee that only one local process can concurrently
|
| 330 |
+
# download the dataset.
|
| 331 |
+
if args.dataset_name is not None:
|
| 332 |
+
# Downloading and loading a dataset from the hub.
|
| 333 |
+
raw_datasets = load_dataset(args.dataset_name, args.dataset_config_name)
|
| 334 |
+
if "validation" not in raw_datasets.keys():
|
| 335 |
+
raw_datasets["validation"] = load_dataset(
|
| 336 |
+
args.dataset_name,
|
| 337 |
+
args.dataset_config_name,
|
| 338 |
+
split=f"train[:{args.validation_split_percentage}%]",
|
| 339 |
+
)
|
| 340 |
+
raw_datasets["train"] = load_dataset(
|
| 341 |
+
args.dataset_name,
|
| 342 |
+
args.dataset_config_name,
|
| 343 |
+
split=f"train[{args.validation_split_percentage}%:]",
|
| 344 |
+
)
|
| 345 |
+
else:
|
| 346 |
+
data_files = {}
|
| 347 |
+
dataset_args = {}
|
| 348 |
+
if args.train_file is not None:
|
| 349 |
+
data_files["train"] = args.train_file
|
| 350 |
+
if args.validation_file is not None:
|
| 351 |
+
data_files["validation"] = args.validation_file
|
| 352 |
+
extension = args.train_file.split(".")[-1]
|
| 353 |
+
if extension == "txt":
|
| 354 |
+
extension = "text"
|
| 355 |
+
dataset_args["keep_linebreaks"] = not args.no_keep_linebreaks
|
| 356 |
+
raw_datasets = load_dataset(extension, data_files=data_files, **dataset_args)
|
| 357 |
+
# If no validation data is there, validation_split_percentage will be used to divide the dataset.
|
| 358 |
+
if "validation" not in raw_datasets.keys():
|
| 359 |
+
raw_datasets["validation"] = load_dataset(
|
| 360 |
+
extension,
|
| 361 |
+
data_files=data_files,
|
| 362 |
+
split=f"train[:{args.validation_split_percentage}%]",
|
| 363 |
+
**dataset_args,
|
| 364 |
+
)
|
| 365 |
+
raw_datasets["train"] = load_dataset(
|
| 366 |
+
extension,
|
| 367 |
+
data_files=data_files,
|
| 368 |
+
split=f"train[{args.validation_split_percentage}%:]",
|
| 369 |
+
**dataset_args,
|
| 370 |
+
)
|
| 371 |
+
|
| 372 |
+
# See more about loading any type of standard or custom dataset (from files, python dict, pandas DataFrame, etc) at
|
| 373 |
+
# https://huggingface.co/docs/datasets/loading_datasets.html.
|
| 374 |
+
|
| 375 |
+
# Load pretrained model and tokenizer
|
| 376 |
+
#
|
| 377 |
+
# In distributed training, the .from_pretrained methods guarantee that only one local process can concurrently
|
| 378 |
+
# download model & vocab.
|
| 379 |
+
if args.config_name:
|
| 380 |
+
config = AutoConfig.from_pretrained(args.config_name)
|
| 381 |
+
elif args.model_name_or_path:
|
| 382 |
+
config = AutoConfig.from_pretrained(args.model_name_or_path)
|
| 383 |
+
else:
|
| 384 |
+
config = CONFIG_MAPPING[args.model_type]()
|
| 385 |
+
logger.warning("You are instantiating a new config instance from scratch.")
|
| 386 |
+
|
| 387 |
+
if args.tokenizer_name:
|
| 388 |
+
tokenizer = AutoTokenizer.from_pretrained(args.tokenizer_name, use_fast=not args.use_slow_tokenizer)
|
| 389 |
+
elif args.model_name_or_path:
|
| 390 |
+
tokenizer = AutoTokenizer.from_pretrained(args.model_name_or_path, use_fast=not args.use_slow_tokenizer)
|
| 391 |
+
else:
|
| 392 |
+
raise ValueError(
|
| 393 |
+
"You are instantiating a new tokenizer from scratch. This is not supported by this script."
|
| 394 |
+
"You can do it from another script, save it, and load it from here, using --tokenizer_name."
|
| 395 |
+
)
|
| 396 |
+
|
| 397 |
+
if args.model_name_or_path:
|
| 398 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 399 |
+
args.model_name_or_path,
|
| 400 |
+
from_tf=bool(".ckpt" in args.model_name_or_path),
|
| 401 |
+
config=config,
|
| 402 |
+
)
|
| 403 |
+
else:
|
| 404 |
+
logger.info("Training new model from scratch")
|
| 405 |
+
model = AutoModelForCausalLM.from_config(config)
|
| 406 |
+
|
| 407 |
+
model.resize_token_embeddings(len(tokenizer))
|
| 408 |
+
|
| 409 |
+
# Preprocessing the datasets.
|
| 410 |
+
# First we tokenize all the texts.
|
| 411 |
+
column_names = raw_datasets["train"].column_names
|
| 412 |
+
text_column_name = "text" if "text" in column_names else column_names[0]
|
| 413 |
+
|
| 414 |
+
def tokenize_function(examples):
|
| 415 |
+
return tokenizer(examples[text_column_name])
|
| 416 |
+
|
| 417 |
+
with accelerator.main_process_first():
|
| 418 |
+
tokenized_datasets = raw_datasets.map(
|
| 419 |
+
tokenize_function,
|
| 420 |
+
batched=True,
|
| 421 |
+
num_proc=args.preprocessing_num_workers,
|
| 422 |
+
remove_columns=column_names,
|
| 423 |
+
load_from_cache_file=not args.overwrite_cache,
|
| 424 |
+
desc="Running tokenizer on dataset",
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
if args.block_size is None:
|
| 428 |
+
block_size = tokenizer.model_max_length
|
| 429 |
+
if block_size > 1024:
|
| 430 |
+
logger.warning(
|
| 431 |
+
f"The tokenizer picked seems to have a very large `model_max_length` ({tokenizer.model_max_length}). "
|
| 432 |
+
"Picking 1024 instead. You can change that default value by passing --block_size xxx."
|
| 433 |
+
)
|
| 434 |
+
block_size = 1024
|
| 435 |
+
else:
|
| 436 |
+
if args.block_size > tokenizer.model_max_length:
|
| 437 |
+
logger.warning(
|
| 438 |
+
f"The block_size passed ({args.block_size}) is larger than the maximum length for the model"
|
| 439 |
+
f"({tokenizer.model_max_length}). Using block_size={tokenizer.model_max_length}."
|
| 440 |
+
)
|
| 441 |
+
block_size = min(args.block_size, tokenizer.model_max_length)
|
| 442 |
+
|
| 443 |
+
# Main data processing function that will concatenate all texts from our dataset and generate chunks of block_size.
|
| 444 |
+
def group_texts(examples):
|
| 445 |
+
# Concatenate all texts.
|
| 446 |
+
concatenated_examples = {k: list(chain(*examples[k])) for k in examples.keys()}
|
| 447 |
+
total_length = len(concatenated_examples[list(examples.keys())[0]])
|
| 448 |
+
# We drop the small remainder, we could add padding if the model supported it instead of this drop, you can
|
| 449 |
+
# customize this part to your needs.
|
| 450 |
+
if total_length >= block_size:
|
| 451 |
+
total_length = (total_length // block_size) * block_size
|
| 452 |
+
# Split by chunks of max_len.
|
| 453 |
+
result = {
|
| 454 |
+
k: [t[i : i + block_size] for i in range(0, total_length, block_size)]
|
| 455 |
+
for k, t in concatenated_examples.items()
|
| 456 |
+
}
|
| 457 |
+
result["labels"] = result["input_ids"].copy()
|
| 458 |
+
return result
|
| 459 |
+
|
| 460 |
+
# Note that with `batched=True`, this map processes 1,000 texts together, so group_texts throws away a remainder
|
| 461 |
+
# for each of those groups of 1,000 texts. You can adjust that batch_size here but a higher value might be slower
|
| 462 |
+
# to preprocess.
|
| 463 |
+
#
|
| 464 |
+
# To speed up this part, we use multiprocessing. See the documentation of the map method for more information:
|
| 465 |
+
# https://huggingface.co/docs/datasets/package_reference/main_classes.html#datasets.Dataset.map
|
| 466 |
+
|
| 467 |
+
with accelerator.main_process_first():
|
| 468 |
+
lm_datasets = tokenized_datasets.map(
|
| 469 |
+
group_texts,
|
| 470 |
+
batched=True,
|
| 471 |
+
num_proc=args.preprocessing_num_workers,
|
| 472 |
+
load_from_cache_file=not args.overwrite_cache,
|
| 473 |
+
desc=f"Grouping texts in chunks of {block_size}",
|
| 474 |
+
)
|
| 475 |
+
|
| 476 |
+
train_dataset = lm_datasets["train"]
|
| 477 |
+
eval_dataset = lm_datasets["validation"]
|
| 478 |
+
|
| 479 |
+
# Log a few random samples from the training set:
|
| 480 |
+
for index in random.sample(range(len(train_dataset)), 3):
|
| 481 |
+
logger.info(f"Sample {index} of the training set: {train_dataset[index]}.")
|
| 482 |
+
|
| 483 |
+
# DataLoaders creation:
|
| 484 |
+
train_dataloader = DataLoader(
|
| 485 |
+
train_dataset, shuffle=True, collate_fn=default_data_collator, batch_size=args.per_device_train_batch_size
|
| 486 |
+
)
|
| 487 |
+
eval_dataloader = DataLoader(
|
| 488 |
+
eval_dataset, collate_fn=default_data_collator, batch_size=args.per_device_eval_batch_size
|
| 489 |
+
)
|
| 490 |
+
|
| 491 |
+
# Optimizer
|
| 492 |
+
# Split weights in two groups, one with weight decay and the other not.
|
| 493 |
+
no_decay = ["bias", "LayerNorm.weight"]
|
| 494 |
+
optimizer_grouped_parameters = [
|
| 495 |
+
{
|
| 496 |
+
"params": [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)],
|
| 497 |
+
"weight_decay": args.weight_decay,
|
| 498 |
+
},
|
| 499 |
+
{
|
| 500 |
+
"params": [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)],
|
| 501 |
+
"weight_decay": 0.0,
|
| 502 |
+
},
|
| 503 |
+
]
|
| 504 |
+
# New Code #
|
| 505 |
+
# Creates Dummy Optimizer if `optimizer` was specified in the config file else creates Adam Optimizer
|
| 506 |
+
optimizer_cls = (
|
| 507 |
+
torch.optim.AdamW
|
| 508 |
+
if accelerator.state.deepspeed_plugin is None
|
| 509 |
+
or "optimizer" not in accelerator.state.deepspeed_plugin.deepspeed_config
|
| 510 |
+
else DummyOptim
|
| 511 |
+
)
|
| 512 |
+
optimizer = optimizer_cls(optimizer_grouped_parameters, lr=args.learning_rate)
|
| 513 |
+
|
| 514 |
+
# On TPU, the tie weights in our model have been disconnected, so we need to restore the ties.
|
| 515 |
+
if accelerator.distributed_type == DistributedType.XLA:
|
| 516 |
+
model.tie_weights()
|
| 517 |
+
|
| 518 |
+
# Scheduler and math around the number of training steps.
|
| 519 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps)
|
| 520 |
+
overrode_max_train_steps = False
|
| 521 |
+
if args.max_train_steps is None:
|
| 522 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 523 |
+
overrode_max_train_steps = True
|
| 524 |
+
else:
|
| 525 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 526 |
+
|
| 527 |
+
# New Code #
|
| 528 |
+
# Creates Dummy Scheduler if `scheduler` was specified in the config file else creates `args.lr_scheduler_type` Scheduler
|
| 529 |
+
if (
|
| 530 |
+
accelerator.state.deepspeed_plugin is None
|
| 531 |
+
or "scheduler" not in accelerator.state.deepspeed_plugin.deepspeed_config
|
| 532 |
+
):
|
| 533 |
+
lr_scheduler = get_scheduler(
|
| 534 |
+
name=args.lr_scheduler_type,
|
| 535 |
+
optimizer=optimizer,
|
| 536 |
+
num_warmup_steps=args.num_warmup_steps,
|
| 537 |
+
num_training_steps=args.max_train_steps,
|
| 538 |
+
)
|
| 539 |
+
else:
|
| 540 |
+
lr_scheduler = DummyScheduler(
|
| 541 |
+
optimizer, total_num_steps=args.max_train_steps, warmup_num_steps=args.num_warmup_steps
|
| 542 |
+
)
|
| 543 |
+
|
| 544 |
+
# Prepare everything with our `accelerator`.
|
| 545 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
|
| 546 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
|
| 547 |
+
)
|
| 548 |
+
|
| 549 |
+
# We need to recalculate our total training steps as the size of the training dataloader may have changed.
|
| 550 |
+
num_update_steps_per_epoch = math.ceil(len(train_dataloader) / accelerator.gradient_accumulation_steps)
|
| 551 |
+
if overrode_max_train_steps:
|
| 552 |
+
args.max_train_steps = args.num_train_epochs * num_update_steps_per_epoch
|
| 553 |
+
# Afterwards we recalculate our number of training epochs
|
| 554 |
+
args.num_train_epochs = math.ceil(args.max_train_steps / num_update_steps_per_epoch)
|
| 555 |
+
|
| 556 |
+
# Figure out how many steps we should save the Accelerator states
|
| 557 |
+
checkpointing_steps = args.checkpointing_steps
|
| 558 |
+
if checkpointing_steps is not None and checkpointing_steps.isdigit():
|
| 559 |
+
checkpointing_steps = int(checkpointing_steps)
|
| 560 |
+
|
| 561 |
+
# We need to initialize the trackers we use, and also store our configuration.
|
| 562 |
+
# The trackers initializes automatically on the main process.
|
| 563 |
+
if args.with_tracking:
|
| 564 |
+
experiment_config = vars(args)
|
| 565 |
+
# TensorBoard cannot log Enums, need the raw value
|
| 566 |
+
experiment_config["lr_scheduler_type"] = experiment_config["lr_scheduler_type"].value
|
| 567 |
+
accelerator.init_trackers("clm_no_trainer", experiment_config)
|
| 568 |
+
|
| 569 |
+
# Train!
|
| 570 |
+
total_batch_size = (
|
| 571 |
+
args.per_device_train_batch_size * accelerator.num_processes * accelerator.gradient_accumulation_steps
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
logger.info("***** Running training *****")
|
| 575 |
+
logger.info(f" Num examples = {len(train_dataset)}")
|
| 576 |
+
logger.info(f" Num Epochs = {args.num_train_epochs}")
|
| 577 |
+
logger.info(f" Instantaneous batch size per device = {args.per_device_train_batch_size}")
|
| 578 |
+
logger.info(f" Total train batch size (w. parallel, distributed & accumulation) = {total_batch_size}")
|
| 579 |
+
logger.info(f" Gradient Accumulation steps = {accelerator.gradient_accumulation_steps}")
|
| 580 |
+
logger.info(f" Total optimization steps = {args.max_train_steps}")
|
| 581 |
+
# Only show the progress bar once on each machine.
|
| 582 |
+
progress_bar = tqdm(range(args.max_train_steps), disable=not accelerator.is_local_main_process)
|
| 583 |
+
completed_steps = 0
|
| 584 |
+
starting_epoch = 0
|
| 585 |
+
best_metric = None
|
| 586 |
+
best_metric_checkpoint = None
|
| 587 |
+
|
| 588 |
+
# Potentially load in the weights and states from a previous save
|
| 589 |
+
if args.resume_from_checkpoint:
|
| 590 |
+
accelerator.load_state(args.resume_from_checkpoint)
|
| 591 |
+
accelerator.print(f"Resumed from checkpoint: {args.resume_from_checkpoint}")
|
| 592 |
+
path = os.path.basename(args.resume_from_checkpoint)
|
| 593 |
+
training_difference = os.path.splitext(path)[0]
|
| 594 |
+
|
| 595 |
+
if "epoch" in training_difference:
|
| 596 |
+
starting_epoch = int(training_difference.replace("epoch_", "")) + 1
|
| 597 |
+
resume_step = None
|
| 598 |
+
completed_steps = starting_epoch * num_update_steps_per_epoch
|
| 599 |
+
else:
|
| 600 |
+
resume_step = int(training_difference.replace("step_", ""))
|
| 601 |
+
starting_epoch = resume_step // num_update_steps_per_epoch
|
| 602 |
+
resume_step -= starting_epoch * num_update_steps_per_epoch
|
| 603 |
+
completed_steps = resume_step
|
| 604 |
+
|
| 605 |
+
# update progress bar if resumed from checkpoint
|
| 606 |
+
progress_bar.update(completed_steps)
|
| 607 |
+
|
| 608 |
+
for epoch in range(starting_epoch, args.num_train_epochs):
|
| 609 |
+
model.train()
|
| 610 |
+
if args.with_tracking:
|
| 611 |
+
total_loss = 0
|
| 612 |
+
|
| 613 |
+
# skip new `skip_first_batches` to skip the batches when resuming from ckpt
|
| 614 |
+
if args.resume_from_checkpoint and epoch == starting_epoch and resume_step is not None:
|
| 615 |
+
# We need to skip steps until we reach the resumed step
|
| 616 |
+
active_dataloader = accelerator.skip_first_batches(train_dataloader, resume_step)
|
| 617 |
+
else:
|
| 618 |
+
# After the first iteration though, we need to go back to the original dataloader
|
| 619 |
+
active_dataloader = train_dataloader
|
| 620 |
+
for step, batch in enumerate(active_dataloader):
|
| 621 |
+
# In particular, DeepSpeed handles `gradient_accumulation` via `DeepSpeedEngine`.
|
| 622 |
+
# Below, we use `accelerator.accumulate` if the user
|
| 623 |
+
# wants to switch to other approaches such as plain DDP, PyTorch FSDP ...
|
| 624 |
+
# This avoids having to change any code as things are all handled across different distributed setups.
|
| 625 |
+
with accelerator.accumulate(model):
|
| 626 |
+
outputs = model(**batch)
|
| 627 |
+
loss = outputs.loss
|
| 628 |
+
accelerator.backward(loss)
|
| 629 |
+
optimizer.step()
|
| 630 |
+
lr_scheduler.step()
|
| 631 |
+
optimizer.zero_grad()
|
| 632 |
+
|
| 633 |
+
if accelerator.sync_gradients:
|
| 634 |
+
progress_bar.update(1)
|
| 635 |
+
completed_steps += 1
|
| 636 |
+
|
| 637 |
+
# We keep track of the loss at each epoch
|
| 638 |
+
if args.with_tracking:
|
| 639 |
+
step_loss = accelerator.reduce(loss.detach().clone()).item()
|
| 640 |
+
total_loss += step_loss
|
| 641 |
+
|
| 642 |
+
if isinstance(checkpointing_steps, int):
|
| 643 |
+
if completed_steps % checkpointing_steps == 0:
|
| 644 |
+
output_dir = f"step_{completed_steps}"
|
| 645 |
+
if args.output_dir is not None:
|
| 646 |
+
output_dir = os.path.join(args.output_dir, output_dir)
|
| 647 |
+
accelerator.save_state(output_dir)
|
| 648 |
+
if completed_steps >= args.max_train_steps:
|
| 649 |
+
break
|
| 650 |
+
|
| 651 |
+
perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset)
|
| 652 |
+
logger.info(f"epoch {epoch}: perplexity: {perplexity} eval_loss: {eval_loss}")
|
| 653 |
+
|
| 654 |
+
if args.with_tracking:
|
| 655 |
+
accelerator.log(
|
| 656 |
+
{
|
| 657 |
+
"perplexity": perplexity,
|
| 658 |
+
"eval_loss": eval_loss,
|
| 659 |
+
"train_loss": total_loss / len(train_dataloader),
|
| 660 |
+
"epoch": epoch,
|
| 661 |
+
"step": completed_steps,
|
| 662 |
+
},
|
| 663 |
+
step=completed_steps,
|
| 664 |
+
)
|
| 665 |
+
|
| 666 |
+
if isinstance(checkpointing_steps, str) and checkpointing_steps == "epoch":
|
| 667 |
+
accelerator.save_state(os.path.join(args.output_dir, f"epoch_{epoch}"))
|
| 668 |
+
|
| 669 |
+
# New Code #
|
| 670 |
+
# Tracks the best checkpoint and best metric
|
| 671 |
+
if best_metric is None or best_metric > perplexity:
|
| 672 |
+
best_metric = perplexity
|
| 673 |
+
best_metric_checkpoint = os.path.join(args.output_dir, "best_checkpoint")
|
| 674 |
+
accelerator.save_state(best_metric_checkpoint)
|
| 675 |
+
accelerator.print(f"New best metric: {best_metric} at epoch {epoch}")
|
| 676 |
+
accelerator.print(f"best_metric_checkpoint: {best_metric_checkpoint}")
|
| 677 |
+
|
| 678 |
+
# New Code #
|
| 679 |
+
# Loads the best checkpoint after the training is finished
|
| 680 |
+
if args.load_best_model:
|
| 681 |
+
accelerator.load_state(best_metric_checkpoint)
|
| 682 |
+
|
| 683 |
+
# New Code #
|
| 684 |
+
# Evaluates using the best checkpoint
|
| 685 |
+
perplexity, eval_loss = evaluate(args, model, eval_dataloader, accelerator, eval_dataset)
|
| 686 |
+
logger.info(f"Best model metrics: perplexity: {perplexity} eval_loss: {eval_loss}")
|
| 687 |
+
if perplexity != best_metric:
|
| 688 |
+
raise AssertionError(
|
| 689 |
+
f"Best metric {best_metric} does not match the metric {perplexity} of the loaded best model."
|
| 690 |
+
)
|
| 691 |
+
|
| 692 |
+
if args.output_dir is not None:
|
| 693 |
+
accelerator.wait_for_everyone()
|
| 694 |
+
unwrapped_model = accelerator.unwrap_model(model)
|
| 695 |
+
|
| 696 |
+
# New Code #
|
| 697 |
+
# Saves the whole/unpartitioned fp16 model when in ZeRO Stage-3 to the output directory if
|
| 698 |
+
# `stage3_gather_16bit_weights_on_model_save` is True in DeepSpeed Config file or
|
| 699 |
+
# `zero3_save_16bit_model` is True in DeepSpeed Plugin.
|
| 700 |
+
# For Zero Stages 1 and 2, models are saved as usual in the output directory.
|
| 701 |
+
# The model name saved is `pytorch_model.bin`
|
| 702 |
+
unwrapped_model.save_pretrained(
|
| 703 |
+
args.output_dir,
|
| 704 |
+
is_main_process=accelerator.is_main_process,
|
| 705 |
+
save_function=accelerator.save,
|
| 706 |
+
state_dict=accelerator.get_state_dict(model),
|
| 707 |
+
)
|
| 708 |
+
if accelerator.is_main_process:
|
| 709 |
+
tokenizer.save_pretrained(args.output_dir)
|
| 710 |
+
if args.push_to_hub:
|
| 711 |
+
api.upload_folder(
|
| 712 |
+
repo_id=repo_id,
|
| 713 |
+
folder_path=args.output_dir,
|
| 714 |
+
commit_message="End of training",
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
with open(os.path.join(args.output_dir, "all_results.json"), "w") as f:
|
| 718 |
+
json.dump({"perplexity": perplexity, "eval_loss": eval_loss.item()}, f)
|
| 719 |
+
accelerator.end_training()
|
| 720 |
+
|
| 721 |
+
|
| 722 |
+
if __name__ == "__main__":
|
| 723 |
+
main()
|
tasks/tasksm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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
|
| 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 argparse
|
| 15 |
+
|
| 16 |
+
import evaluate
|
| 17 |
+
import torch
|
| 18 |
+
from datasets import load_dataset
|
| 19 |
+
from torch.optim import AdamW
|
| 20 |
+
from torch.utils.data import DataLoader
|
| 21 |
+
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed
|
| 22 |
+
|
| 23 |
+
from accelerate import Accelerator, DistributedType
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
########################################################################
|
| 27 |
+
# This is a fully working simple example to use Accelerate
|
| 28 |
+
# specifically showcasing how to perform early stopping,
|
| 29 |
+
# and builds off the `nlp_example.py` script
|
| 30 |
+
#
|
| 31 |
+
# This example trains a Bert base model on GLUE MRPC
|
| 32 |
+
# in any of the following settings (with the same script):
|
| 33 |
+
# - single CPU or single GPU
|
| 34 |
+
# - multi GPUS (using PyTorch distributed mode)
|
| 35 |
+
# - (multi) TPUs
|
| 36 |
+
# - fp16 (mixed-precision) or fp32 (normal precision)
|
| 37 |
+
#
|
| 38 |
+
# To run it in each of these various modes, follow the instructions
|
| 39 |
+
# in the readme for examples:
|
| 40 |
+
# https://github.com/huggingface/accelerate/tree/main/examples
|
| 41 |
+
#
|
| 42 |
+
########################################################################
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
MAX_GPU_BATCH_SIZE = 16
|
| 46 |
+
EVAL_BATCH_SIZE = 32
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def get_dataloaders(accelerator: Accelerator, batch_size: int = 16):
|
| 50 |
+
"""
|
| 51 |
+
Creates a set of `DataLoader`s for the `glue` dataset,
|
| 52 |
+
using "bert-base-cased" as the tokenizer.
|
| 53 |
+
|
| 54 |
+
Args:
|
| 55 |
+
accelerator (`Accelerator`):
|
| 56 |
+
An `Accelerator` object
|
| 57 |
+
batch_size (`int`, *optional*):
|
| 58 |
+
The batch size for the train and validation DataLoaders.
|
| 59 |
+
"""
|
| 60 |
+
tokenizer = AutoTokenizer.from_pretrained("bert-base-cased")
|
| 61 |
+
datasets = load_dataset("glue", "mrpc")
|
| 62 |
+
|
| 63 |
+
def tokenize_function(examples):
|
| 64 |
+
# max_length=None => use the model max length (it's actually the default)
|
| 65 |
+
outputs = tokenizer(examples["sentence1"], examples["sentence2"], truncation=True, max_length=None)
|
| 66 |
+
return outputs
|
| 67 |
+
|
| 68 |
+
# Apply the method we just defined to all the examples in all the splits of the dataset
|
| 69 |
+
# starting with the main process first:
|
| 70 |
+
with accelerator.main_process_first():
|
| 71 |
+
tokenized_datasets = datasets.map(
|
| 72 |
+
tokenize_function,
|
| 73 |
+
batched=True,
|
| 74 |
+
remove_columns=["idx", "sentence1", "sentence2"],
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
|
| 78 |
+
# transformers library
|
| 79 |
+
tokenized_datasets = tokenized_datasets.rename_column("label", "labels")
|
| 80 |
+
|
| 81 |
+
def collate_fn(examples):
|
| 82 |
+
# On TPU it's best to pad everything to the same length or training will be very slow.
|
| 83 |
+
max_length = 128 if accelerator.distributed_type == DistributedType.XLA else None
|
| 84 |
+
# When using mixed precision we want round multiples of 8/16
|
| 85 |
+
if accelerator.mixed_precision == "fp8":
|
| 86 |
+
pad_to_multiple_of = 16
|
| 87 |
+
elif accelerator.mixed_precision != "no":
|
| 88 |
+
pad_to_multiple_of = 8
|
| 89 |
+
else:
|
| 90 |
+
pad_to_multiple_of = None
|
| 91 |
+
|
| 92 |
+
return tokenizer.pad(
|
| 93 |
+
examples,
|
| 94 |
+
padding="longest",
|
| 95 |
+
max_length=max_length,
|
| 96 |
+
pad_to_multiple_of=pad_to_multiple_of,
|
| 97 |
+
return_tensors="pt",
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
# Instantiate dataloaders.
|
| 101 |
+
train_dataloader = DataLoader(
|
| 102 |
+
tokenized_datasets["train"], shuffle=True, collate_fn=collate_fn, batch_size=batch_size, drop_last=True
|
| 103 |
+
)
|
| 104 |
+
eval_dataloader = DataLoader(
|
| 105 |
+
tokenized_datasets["validation"],
|
| 106 |
+
shuffle=False,
|
| 107 |
+
collate_fn=collate_fn,
|
| 108 |
+
batch_size=EVAL_BATCH_SIZE,
|
| 109 |
+
drop_last=(accelerator.mixed_precision == "fp8"),
|
| 110 |
+
)
|
| 111 |
+
|
| 112 |
+
return train_dataloader, eval_dataloader
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
# New code
|
| 116 |
+
class EarlyStoppingCallback:
|
| 117 |
+
"A callback class that helps with early stopping"
|
| 118 |
+
|
| 119 |
+
def __init__(self, min_delta=0, patience=5):
|
| 120 |
+
self.min_delta = min_delta
|
| 121 |
+
self.patience = patience
|
| 122 |
+
self.counter = 0
|
| 123 |
+
self.lowest_loss = float("inf")
|
| 124 |
+
|
| 125 |
+
def check_early_stopping(self, eval_loss):
|
| 126 |
+
delta = self.lowest_loss - eval_loss
|
| 127 |
+
if delta >= self.min_delta:
|
| 128 |
+
self.lowest_loss = eval_loss
|
| 129 |
+
self.counter = 0
|
| 130 |
+
else:
|
| 131 |
+
self.counter += 1
|
| 132 |
+
if self.counter >= self.patience:
|
| 133 |
+
return True
|
| 134 |
+
return False
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
callback = EarlyStoppingCallback()
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def training_function(config, args):
|
| 141 |
+
# Initialize accelerator
|
| 142 |
+
accelerator = Accelerator(cpu=args.cpu, mixed_precision=args.mixed_precision)
|
| 143 |
+
# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
|
| 144 |
+
lr = config["lr"]
|
| 145 |
+
num_epochs = int(config["num_epochs"])
|
| 146 |
+
seed = int(config["seed"])
|
| 147 |
+
batch_size = int(config["batch_size"])
|
| 148 |
+
|
| 149 |
+
metric = evaluate.load("glue", "mrpc")
|
| 150 |
+
|
| 151 |
+
# If the batch size is too big we use gradient accumulation
|
| 152 |
+
gradient_accumulation_steps = 1
|
| 153 |
+
if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.XLA:
|
| 154 |
+
gradient_accumulation_steps = batch_size // MAX_GPU_BATCH_SIZE
|
| 155 |
+
batch_size = MAX_GPU_BATCH_SIZE
|
| 156 |
+
|
| 157 |
+
set_seed(seed)
|
| 158 |
+
train_dataloader, eval_dataloader = get_dataloaders(accelerator, batch_size)
|
| 159 |
+
# Instantiate the model (we build the model here so that the seed also control new weights initialization)
|
| 160 |
+
model = AutoModelForSequenceClassification.from_pretrained("bert-base-cased", return_dict=True)
|
| 161 |
+
|
| 162 |
+
# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
|
| 163 |
+
# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
|
| 164 |
+
# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
|
| 165 |
+
model = model.to(accelerator.device)
|
| 166 |
+
# Instantiate optimizer
|
| 167 |
+
optimizer = AdamW(params=model.parameters(), lr=lr)
|
| 168 |
+
|
| 169 |
+
# Instantiate scheduler
|
| 170 |
+
lr_scheduler = get_linear_schedule_with_warmup(
|
| 171 |
+
optimizer=optimizer,
|
| 172 |
+
num_warmup_steps=100,
|
| 173 |
+
num_training_steps=(len(train_dataloader) * num_epochs) // gradient_accumulation_steps,
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
# Prepare everything
|
| 177 |
+
# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
|
| 178 |
+
# prepare method.
|
| 179 |
+
|
| 180 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler = accelerator.prepare(
|
| 181 |
+
model, optimizer, train_dataloader, eval_dataloader, lr_scheduler
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
# Now we train the model
|
| 185 |
+
for epoch in range(num_epochs):
|
| 186 |
+
model.train()
|
| 187 |
+
for step, batch in enumerate(train_dataloader):
|
| 188 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 189 |
+
batch.to(accelerator.device)
|
| 190 |
+
outputs = model(**batch)
|
| 191 |
+
loss = outputs.loss
|
| 192 |
+
loss = loss / gradient_accumulation_steps
|
| 193 |
+
accelerator.backward(loss)
|
| 194 |
+
if step % gradient_accumulation_steps == 0:
|
| 195 |
+
optimizer.step()
|
| 196 |
+
lr_scheduler.step()
|
| 197 |
+
optimizer.zero_grad()
|
| 198 |
+
|
| 199 |
+
# New code
|
| 200 |
+
# Check if we should stop the training on any processes
|
| 201 |
+
if callback.check_early_stopping(loss.item()):
|
| 202 |
+
accelerator.set_trigger()
|
| 203 |
+
|
| 204 |
+
# If so, we break the loop
|
| 205 |
+
if accelerator.check_trigger():
|
| 206 |
+
break
|
| 207 |
+
|
| 208 |
+
model.eval()
|
| 209 |
+
for step, batch in enumerate(eval_dataloader):
|
| 210 |
+
# We could avoid this line since we set the accelerator with `device_placement=True`.
|
| 211 |
+
batch.to(accelerator.device)
|
| 212 |
+
with torch.no_grad():
|
| 213 |
+
outputs = model(**batch)
|
| 214 |
+
predictions = outputs.logits.argmax(dim=-1)
|
| 215 |
+
predictions, references = accelerator.gather_for_metrics((predictions, batch["labels"]))
|
| 216 |
+
metric.add_batch(
|
| 217 |
+
predictions=predictions,
|
| 218 |
+
references=references,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
eval_metric = metric.compute()
|
| 222 |
+
|
| 223 |
+
# Use accelerator.print to print only on the main process.
|
| 224 |
+
accelerator.print(f"epoch {epoch}:", eval_metric)
|
| 225 |
+
accelerator.end_training()
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def main():
|
| 229 |
+
parser = argparse.ArgumentParser(description="Simple example of training script.")
|
| 230 |
+
parser.add_argument(
|
| 231 |
+
"--mixed_precision",
|
| 232 |
+
type=str,
|
| 233 |
+
default=None,
|
| 234 |
+
choices=["no", "fp16", "bf16", "fp8"],
|
| 235 |
+
help="Whether to use mixed precision. Choose"
|
| 236 |
+
"between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."
|
| 237 |
+
"and an Nvidia Ampere GPU.",
|
| 238 |
+
)
|
| 239 |
+
parser.add_argument("--cpu", action="store_true", help="If passed, will train on the CPU.")
|
| 240 |
+
args = parser.parse_args()
|
| 241 |
+
config = {"lr": 2e-5, "num_epochs": 3, "seed": 42, "batch_size": 16}
|
| 242 |
+
training_function(config, args)
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
if __name__ == "__main__":
|
| 246 |
+
main()
|