trainer.py 3.56 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
15
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from types import MethodType
chenych's avatar
chenych committed
16
from typing import TYPE_CHECKING, Optional
chenych's avatar
chenych committed
17

luopl's avatar
luopl committed
18
import torch
chenych's avatar
chenych committed
19
from transformers import Trainer
luopl's avatar
luopl committed
20
from typing_extensions import override
chenych's avatar
chenych committed
21

luopl's avatar
luopl committed
22
23
from ...extras.packages import is_transformers_version_greater_than
from ..callbacks import SaveProcessorCallback
shihm's avatar
uodata  
shihm committed
24
from ..fp8_utils import configure_fp8_environment, verify_fp8_status
chenych's avatar
chenych committed
25
26
27
28
from ..trainer_utils import create_custom_optimizer, create_custom_scheduler


if TYPE_CHECKING:
chenych's avatar
chenych committed
29
    from transformers import ProcessorMixin
chenych's avatar
chenych committed
30

shihm's avatar
uodata  
shihm committed
31
    from ...hparams import FinetuningArguments, ModelArguments
chenych's avatar
chenych committed
32
33
34


class CustomTrainer(Trainer):
chenych's avatar
chenych committed
35
    r"""Inherit Trainer for custom optimizer."""
chenych's avatar
chenych committed
36
37

    def __init__(
shihm's avatar
uodata  
shihm committed
38
39
40
41
42
        self,
        finetuning_args: "FinetuningArguments",
        processor: Optional["ProcessorMixin"],
        model_args: Optional["ModelArguments"] = None,
        **kwargs,
chenych's avatar
chenych committed
43
    ) -> None:
shihm's avatar
uodata  
shihm committed
44
45
46
        # Configure FP8 environment if enabled
        if model_args is not None and model_args.fp8:
            configure_fp8_environment(model_args)
luopl's avatar
luopl committed
47
48
49
        if is_transformers_version_greater_than("4.46"):
            kwargs["processing_class"] = kwargs.pop("tokenizer")

chenych's avatar
chenych committed
50
        super().__init__(**kwargs)
chenych's avatar
chenych committed
51
52
53
54
55
        if processor is not None:
            # avoid wrong loss under gradient accumulation
            # https://github.com/huggingface/transformers/pull/36044#issuecomment-2746657112
            self.model_accepts_loss_kwargs = False

chenych's avatar
chenych committed
56
57
58
59
60
61
        self.finetuning_args = finetuning_args

        if processor is not None:
            self.add_callback(SaveProcessorCallback(processor))

        if finetuning_args.use_badam:
luopl's avatar
luopl committed
62
            from badam import BAdamCallback, clip_grad_norm_old_version  # type: ignore
chenych's avatar
chenych committed
63
64
65
66

            self.accelerator.clip_grad_norm_ = MethodType(clip_grad_norm_old_version, self.accelerator)
            self.add_callback(BAdamCallback)

shihm's avatar
uodata  
shihm committed
67
68
69
70
        # Verify FP8 status after trainer initialization (accelerator should be available)
        if model_args is not None and model_args.fp8 and hasattr(self, "accelerator"):
            verify_fp8_status(self.accelerator, model_args)

luopl's avatar
luopl committed
71
    @override
chenych's avatar
chenych committed
72
73
74
75
76
    def create_optimizer(self) -> "torch.optim.Optimizer":
        if self.optimizer is None:
            self.optimizer = create_custom_optimizer(self.model, self.args, self.finetuning_args)
        return super().create_optimizer()

luopl's avatar
luopl committed
77
    @override
chenych's avatar
chenych committed
78
79
80
81
82
    def create_scheduler(
        self, num_training_steps: int, optimizer: Optional["torch.optim.Optimizer"] = None
    ) -> "torch.optim.lr_scheduler.LRScheduler":
        create_custom_scheduler(self.args, num_training_steps, optimizer)
        return super().create_scheduler(num_training_steps, optimizer)
luopl's avatar
luopl committed
83
84

    @override
chenych's avatar
chenych committed
85
    def _get_train_sampler(self, *args, **kwargs) -> Optional["torch.utils.data.Sampler"]:
luopl's avatar
luopl committed
86
87
88
        if self.finetuning_args.disable_shuffling:
            return torch.utils.data.SequentialSampler(self.train_dataset)

chenych's avatar
chenych committed
89
        return super()._get_train_sampler(*args, **kwargs)
chenych's avatar
chenych committed
90
91
92
93

    @override
    def compute_loss(self, model, inputs, *args, **kwargs):
        return super().compute_loss(model, inputs, *args, **kwargs)