File size: 18,635 Bytes
302920f |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 |
# Copyright 2024-present the HuggingFace Inc. team.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import pytest
import torch
from diffusers import StableDiffusionPipeline
from torch import nn
from transformers import AutoModelForCausalLM, AutoTokenizer
from peft import LoraConfig, get_peft_model
from peft.helpers import check_if_peft_model, disable_input_dtype_casting, rescale_adapter_scale
from peft.tuners.lora.layer import LoraLayer
from peft.utils import infer_device
class TestCheckIsPeftModel:
def test_valid_hub_model(self):
result = check_if_peft_model("peft-internal-testing/gpt2-lora-random")
assert result is True
def test_invalid_hub_model(self):
result = check_if_peft_model("gpt2")
assert result is False
def test_nonexisting_hub_model(self):
result = check_if_peft_model("peft-internal-testing/non-existing-model")
assert result is False
def test_local_model_valid(self, tmp_path):
model = AutoModelForCausalLM.from_pretrained("gpt2")
config = LoraConfig()
model = get_peft_model(model, config)
model.save_pretrained(tmp_path / "peft-gpt2-valid")
result = check_if_peft_model(tmp_path / "peft-gpt2-valid")
assert result is True
def test_local_model_invalid(self, tmp_path):
model = AutoModelForCausalLM.from_pretrained("gpt2")
model.save_pretrained(tmp_path / "peft-gpt2-invalid")
result = check_if_peft_model(tmp_path / "peft-gpt2-invalid")
assert result is False
def test_local_model_broken_config(self, tmp_path):
with open(tmp_path / "adapter_config.json", "w") as f:
f.write('{"foo": "bar"}')
result = check_if_peft_model(tmp_path)
assert result is False
def test_local_model_non_default_name(self, tmp_path):
model = AutoModelForCausalLM.from_pretrained("gpt2")
config = LoraConfig()
model = get_peft_model(model, config, adapter_name="other")
model.save_pretrained(tmp_path / "peft-gpt2-other")
# no default adapter here
result = check_if_peft_model(tmp_path / "peft-gpt2-other")
assert result is False
# with adapter name
result = check_if_peft_model(tmp_path / "peft-gpt2-other" / "other")
assert result is True
class TestScalingAdapters:
@pytest.fixture(scope="class")
def tokenizer(self):
return AutoTokenizer.from_pretrained("facebook/opt-125m")
def get_scale_from_modules(self, model):
layer_to_scale_map = {}
for name, module in model.named_modules():
if isinstance(module, LoraLayer):
layer_to_scale_map[name] = module.scaling
return layer_to_scale_map
def test_rescale_adapter_scale(self, tokenizer):
model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
lora_config = LoraConfig(
r=4,
lora_alpha=4,
target_modules=["k_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
init_lora_weights=False,
)
model = get_peft_model(model, lora_config)
model.eval()
inputs = tokenizer("hello world", return_tensors="pt")
with torch.no_grad():
logits_before_scaling = model(**inputs).logits
scales_before_scaling = self.get_scale_from_modules(model)
with rescale_adapter_scale(model=model, multiplier=0.5):
scales_during_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] != scales_during_scaling[key]
with torch.no_grad():
logits_during_scaling = model(**inputs).logits
assert not torch.allclose(logits_before_scaling, logits_during_scaling)
scales_after_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] == scales_after_scaling[key]
with torch.no_grad():
logits_after_scaling = model(**inputs).logits
assert torch.allclose(logits_before_scaling, logits_after_scaling)
def test_wrong_scaling_datatype(self):
model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
lora_config = LoraConfig(
r=4,
lora_alpha=4,
target_modules=["k_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
init_lora_weights=False,
)
model = get_peft_model(model, lora_config)
# we expect a type error here becuase of wrong datatpye of multiplier
multiplier = "a"
with pytest.raises(TypeError, match=f"Argument multiplier should be of type float, got {type(multiplier)}"):
with rescale_adapter_scale(model=model, multiplier=multiplier):
pass
def test_not_lora_model(self):
model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
# we expect a value error here because the model
# does not have lora layers
with pytest.raises(ValueError, match="scaling is only supported for models with `LoraLayer`s"):
with rescale_adapter_scale(model=model, multiplier=0.5):
pass
def test_scaling_set_to_zero(self, tokenizer):
base_model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
inputs = tokenizer("hello world", return_tensors="pt")
base_model.eval()
with torch.no_grad():
logits_base_model = base_model(**inputs).logits
lora_config = LoraConfig(
r=4,
lora_alpha=4,
target_modules=["k_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
init_lora_weights=False,
)
lora_model = get_peft_model(base_model, lora_config)
lora_model.eval()
with rescale_adapter_scale(model=lora_model, multiplier=0.0):
with torch.no_grad():
logits_lora_model = lora_model(**inputs).logits
assert torch.allclose(logits_base_model, logits_lora_model)
def test_diffusers_pipeline(self):
model_id = "hf-internal-testing/tiny-sd-pipe"
pipeline = StableDiffusionPipeline.from_pretrained(model_id)
text_encoder_kwargs = {
"r": 8,
"lora_alpha": 32,
"target_modules": ["k_proj", "q_proj", "v_proj", "out_proj", "fc1", "fc2"],
"lora_dropout": 0.0,
"bias": "none",
}
unet_kwargs = {
"r": 8,
"lora_alpha": 32,
"target_modules": ["proj_in", "proj_out", "to_k", "to_q", "to_v", "to_out.0", "ff.net.0.proj", "ff.net.2"],
"lora_dropout": 0.0,
"bias": "none",
}
# Instantiate text_encoder adapter
config_text_encoder = LoraConfig(**text_encoder_kwargs)
pipeline.text_encoder = get_peft_model(pipeline.text_encoder, config_text_encoder)
# Instantiate unet adapter
config_unet = LoraConfig(**unet_kwargs)
pipeline.unet = get_peft_model(pipeline.unet, config_unet)
text_scales_before_scaling = self.get_scale_from_modules(pipeline.text_encoder)
unet_scales_before_scaling = self.get_scale_from_modules(pipeline.unet)
with (
rescale_adapter_scale(model=pipeline.text_encoder, multiplier=0.5),
rescale_adapter_scale(model=pipeline.unet, multiplier=0.5),
):
text_scales_during_scaling = self.get_scale_from_modules(pipeline.text_encoder)
unet_scales_during_scaling = self.get_scale_from_modules(pipeline.unet)
for key in text_scales_before_scaling.keys():
assert text_scales_before_scaling[key] != text_scales_during_scaling[key]
for key in unet_scales_before_scaling.keys():
assert unet_scales_before_scaling[key] != unet_scales_during_scaling[key]
text_scales_fter_scaling = self.get_scale_from_modules(pipeline.text_encoder)
unet_scales_after_scaling = self.get_scale_from_modules(pipeline.unet)
for key in text_scales_before_scaling.keys():
assert text_scales_before_scaling[key] == text_scales_fter_scaling[key]
for key in unet_scales_before_scaling.keys():
assert unet_scales_before_scaling[key] == unet_scales_after_scaling[key]
def test_transformers_pipeline(self, tmp_path, tokenizer):
# this uses a transformers model that loads the adapter directly
model_id = "facebook/opt-125m"
model = AutoModelForCausalLM.from_pretrained(model_id)
config = LoraConfig(init_lora_weights=False)
model = get_peft_model(model, config)
model.save_pretrained(tmp_path / "opt-lora")
del model
# load directly into transformers model
model = AutoModelForCausalLM.from_pretrained(model_id)
model.load_adapter(tmp_path / "opt-lora")
inputs = tokenizer("hello world", return_tensors="pt")
model = model.eval()
with torch.no_grad():
logits_before_scaling = model(**inputs).logits
scales_before_scaling = self.get_scale_from_modules(model)
with rescale_adapter_scale(model=model, multiplier=0.5):
scales_during_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] != scales_during_scaling[key]
with torch.no_grad():
logits_during_scaling = model(**inputs).logits
assert not torch.allclose(logits_before_scaling, logits_during_scaling)
scales_after_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] == scales_after_scaling[key]
with torch.no_grad():
logits_after_scaling = model(**inputs).logits
assert torch.allclose(logits_before_scaling, logits_after_scaling)
def test_multi_adapters(self, tokenizer):
model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
lora_config = LoraConfig(
r=4,
lora_alpha=4,
target_modules=["k_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
init_lora_weights=False,
)
model = get_peft_model(model, lora_config)
inputs = tokenizer("hello world", return_tensors="pt")
# add another adaper and activate it
model.add_adapter("other", lora_config)
model.set_adapter("other")
scales_before_scaling = self.get_scale_from_modules(model)
model.eval()
with torch.no_grad():
logits_before = model(**inputs).logits
with rescale_adapter_scale(model=model, multiplier=0.5):
scales_during_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] != scales_during_scaling[key]
with torch.no_grad():
logits_during = model(**inputs).logits
assert not torch.allclose(logits_before, logits_during)
scales_after_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] == scales_after_scaling[key]
with torch.no_grad():
logits_after = model(**inputs).logits
assert torch.allclose(logits_before, logits_after)
def test_rank_alpha_pattern(self, tokenizer):
model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
lora_config = LoraConfig(
r=4,
lora_alpha=4,
target_modules=["k_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
init_lora_weights=False,
rank_pattern={"k_proj": 2},
alpha_pattern={"k_proj": 8},
)
model = get_peft_model(model, lora_config)
model.eval()
inputs = tokenizer("hello world", return_tensors="pt")
with torch.no_grad():
logits_before_scaling = model(**inputs).logits
scales_before_scaling = self.get_scale_from_modules(model)
with rescale_adapter_scale(model=model, multiplier=0.5):
scales_during_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] != scales_during_scaling[key]
with torch.no_grad():
logits_during_scaling = model(**inputs).logits
assert not torch.allclose(logits_before_scaling, logits_during_scaling)
scales_after_scaling = self.get_scale_from_modules(model)
for key in scales_before_scaling.keys():
assert scales_before_scaling[key] == scales_after_scaling[key]
with torch.no_grad():
logits_after_scaling = model(**inputs).logits
assert torch.allclose(logits_before_scaling, logits_after_scaling)
def test_merging_adapter(self, tokenizer):
model = AutoModelForCausalLM.from_pretrained("facebook/opt-125m")
lora_config = LoraConfig(
r=4,
lora_alpha=4,
target_modules=["k_proj", "v_proj"],
lora_dropout=0.1,
bias="none",
init_lora_weights=False,
)
model = get_peft_model(model, lora_config)
model.eval()
inputs = tokenizer("hello world", return_tensors="pt")
with rescale_adapter_scale(model=model, multiplier=0.5):
with torch.no_grad():
logits_unmerged_scaling = model(**inputs).logits
model = model.merge_and_unload()
with torch.no_grad():
logits_merged_scaling = model(**inputs).logits
assert torch.allclose(logits_merged_scaling, logits_unmerged_scaling, atol=1e-4, rtol=1e-4)
class TestDisableInputDtypeCasting:
"""Test the context manager `disable_input_dtype_casting` that temporarily disables input dtype casting
in the model.
The test works as follows:
We create a simple MLP and convert it to a PeftModel. The model dtype is set to float16. Then a pre-foward hook is
added that casts the model parameters to float32. Moreover, a post-forward hook is added that casts the weights
back to float16. The input dtype is float32.
Without the disable_input_dtype_casting context, what would happen is that PEFT detects that the input dtype is
float32 but the weight dtype is float16, so it casts the input to float16. Then the pre-forward hook casts the
weight to float32, which results in a RuntimeError.
With the disable_input_dtype_casting context, the input dtype is left as float32 and there is no error. We also add
a hook to record the dtype of the result from the LoraLayer to ensure that it is indeed float32.
"""
device = infer_device()
dtype_record = []
@torch.no_grad()
def cast_params_to_fp32_pre_hook(self, module, input):
for param in module.parameters(recurse=False):
param.data = param.data.float()
return input
@torch.no_grad()
def cast_params_to_fp16_hook(self, module, input, output):
for param in module.parameters(recurse=False):
param.data = param.data.half()
return output
def record_dtype_hook(self, module, input, output):
self.dtype_record.append(output[0].dtype)
@pytest.fixture
def inputs(self):
return torch.randn(4, 10, device=self.device, dtype=torch.float32)
@pytest.fixture
def base_model(self):
class MLP(nn.Module):
def __init__(self, bias=True):
super().__init__()
self.lin0 = nn.Linear(10, 20, bias=bias)
self.lin1 = nn.Linear(20, 2, bias=bias)
self.sm = nn.LogSoftmax(dim=-1)
def forward(self, X):
X = self.lin0(X)
X = self.lin1(X)
X = self.sm(X)
return X
return MLP()
@pytest.fixture
def model(self, base_model):
config = LoraConfig(target_modules=["lin0"], modules_to_save=["lin1"])
model = get_peft_model(base_model, config).to(device=self.device, dtype=torch.float16)
# Register hooks on the submodule that holds parameters
for module in model.modules():
if sum(p.numel() for p in module.parameters()) > 0:
module.register_forward_pre_hook(self.cast_params_to_fp32_pre_hook)
module.register_forward_hook(self.cast_params_to_fp16_hook)
if isinstance(module, LoraLayer):
module.register_forward_hook(self.record_dtype_hook)
return model
def test_disable_input_dtype_casting_active(self, model, inputs):
self.dtype_record.clear()
with disable_input_dtype_casting(model, active=True):
model(inputs)
assert self.dtype_record == [torch.float32]
def test_no_disable_input_dtype_casting(self, model, inputs):
msg = r"expected m.*1 and m.*2 to have the same dtype"
with pytest.raises(RuntimeError, match=msg):
model(inputs)
def test_disable_input_dtype_casting_inactive(self, model, inputs):
msg = r"expected m.*1 and m.*2 to have the same dtype"
with pytest.raises(RuntimeError, match=msg):
with disable_input_dtype_casting(model, active=False):
model(inputs)
def test_disable_input_dtype_casting_inactive_after_existing_context(self, model, inputs):
# this is to ensure that when the context is left, we return to the previous behavior
with disable_input_dtype_casting(model, active=True):
model(inputs)
# after the context exited, we're back to the error
msg = r"expected m.*1 and m.*2 to have the same dtype"
with pytest.raises(RuntimeError, match=msg):
model(inputs)
|