test_utils.py 4.87 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# 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.

chenych's avatar
chenych committed
15
from typing import TYPE_CHECKING, Optional, Union
chenych's avatar
chenych committed
16
17
18
19
20
21

import torch
from peft import PeftModel
from transformers import AutoModelForCausalLM
from trl import AutoModelForCausalLMWithValueHead

luopl's avatar
luopl committed
22
from ..data import get_dataset, get_template_and_fix_tokenizer
chenych's avatar
chenych committed
23
24
25
26
27
28
29
30
31
from ..extras.misc import get_current_device
from ..hparams import get_infer_args, get_train_args
from ..model import load_model, load_tokenizer


if TYPE_CHECKING:
    from peft import LoraModel
    from transformers import PreTrainedModel

chenych's avatar
chenych committed
32
33
    from ..data.data_utils import DatasetModule

chenych's avatar
chenych committed
34

chenych's avatar
chenych committed
35
def compare_model(model_a: "torch.nn.Module", model_b: "torch.nn.Module", diff_keys: list[str] = []) -> None:
chenych's avatar
chenych committed
36
37
38
39
40
    state_dict_a = model_a.state_dict()
    state_dict_b = model_b.state_dict()
    assert set(state_dict_a.keys()) == set(state_dict_b.keys())
    for name in state_dict_a.keys():
        if any(key in name for key in diff_keys):
luopl's avatar
luopl committed
41
            assert torch.allclose(state_dict_a[name], state_dict_b[name], rtol=1e-4, atol=1e-5) is False
chenych's avatar
chenych committed
42
        else:
luopl's avatar
luopl committed
43
            assert torch.allclose(state_dict_a[name], state_dict_b[name], rtol=1e-4, atol=1e-5) is True
chenych's avatar
chenych committed
44
45


chenych's avatar
chenych committed
46
def check_lora_model(model: "LoraModel") -> tuple[set[str], set[str]]:
chenych's avatar
chenych committed
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
    linear_modules, extra_modules = set(), set()
    for name, param in model.named_parameters():
        if any(module in name for module in ["lora_A", "lora_B"]):
            linear_modules.add(name.split(".lora_", maxsplit=1)[0].split(".")[-1])
            assert param.requires_grad is True
            assert param.dtype == torch.float32
        elif "modules_to_save" in name:
            extra_modules.add(name.split(".modules_to_save", maxsplit=1)[0].split(".")[-1])
            assert param.requires_grad is True
            assert param.dtype == torch.float32
        else:
            assert param.requires_grad is False
            assert param.dtype == torch.float16

    return linear_modules, extra_modules


def load_train_model(add_valuehead: bool = False, **kwargs) -> "PreTrainedModel":
    model_args, _, _, finetuning_args, _ = get_train_args(kwargs)
    tokenizer = load_tokenizer(model_args)["tokenizer"]
    return load_model(tokenizer, model_args, finetuning_args, is_trainable=True, add_valuehead=add_valuehead)


def load_infer_model(add_valuehead: bool = False, **kwargs) -> "PreTrainedModel":
    model_args, _, finetuning_args, _ = get_infer_args(kwargs)
    tokenizer = load_tokenizer(model_args)["tokenizer"]
    return load_model(tokenizer, model_args, finetuning_args, is_trainable=False, add_valuehead=add_valuehead)


def load_reference_model(
    model_path: str,
    lora_path: Optional[str] = None,
    use_lora: bool = False,
    use_pissa: bool = False,
    is_trainable: bool = False,
    add_valuehead: bool = False,
) -> Union["PreTrainedModel", "LoraModel"]:
luopl's avatar
luopl committed
84
    current_device = get_current_device()
chenych's avatar
chenych committed
85
    if add_valuehead:
chenych's avatar
chenych committed
86
        model: AutoModelForCausalLMWithValueHead = AutoModelForCausalLMWithValueHead.from_pretrained(
luopl's avatar
luopl committed
87
            model_path, torch_dtype=torch.float16, device_map=current_device
chenych's avatar
chenych committed
88
89
90
91
92
93
        )
        if not is_trainable:
            model.v_head = model.v_head.to(torch.float16)

        return model

luopl's avatar
luopl committed
94
    model = AutoModelForCausalLM.from_pretrained(model_path, torch_dtype=torch.float16, device_map=current_device)
chenych's avatar
chenych committed
95
96
97
98
99
100
101
102
103
104
    if use_lora or use_pissa:
        model = PeftModel.from_pretrained(
            model, lora_path, subfolder="pissa_init" if use_pissa else None, is_trainable=is_trainable
        )
        for param in filter(lambda p: p.requires_grad, model.parameters()):
            param.data = param.data.to(torch.float32)

    return model


chenych's avatar
chenych committed
105
def load_dataset_module(**kwargs) -> "DatasetModule":
chenych's avatar
chenych committed
106
107
    model_args, data_args, training_args, _, _ = get_train_args(kwargs)
    tokenizer_module = load_tokenizer(model_args)
luopl's avatar
luopl committed
108
109
    template = get_template_and_fix_tokenizer(tokenizer_module["tokenizer"], data_args)
    dataset_module = get_dataset(template, model_args, data_args, training_args, kwargs["stage"], **tokenizer_module)
chenych's avatar
chenych committed
110
    return dataset_module
chenych's avatar
chenych committed
111
112


luopl's avatar
luopl committed
113
def patch_valuehead_model() -> None:
chenych's avatar
chenych committed
114
    def post_init(self: "AutoModelForCausalLMWithValueHead", state_dict: dict[str, "torch.Tensor"]) -> None:
chenych's avatar
chenych committed
115
116
117
118
119
        state_dict = {k[7:]: state_dict[k] for k in state_dict.keys() if k.startswith("v_head.")}
        self.v_head.load_state_dict(state_dict, strict=False)
        del state_dict

    AutoModelForCausalLMWithValueHead.post_init = post_init