| 1 | # Copyright 2025 the LlamaFactory 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 types import MethodType |
| 16 | from typing import TYPE_CHECKING, Any |
| 17 | |
| 18 | import torch |
| 19 | from transformers import GenerationMixin, PreTrainedModel, PreTrainedTokenizerBase |
| 20 | from transformers.integrations import is_deepspeed_zero3_enabled |
| 21 | from transformers.utils import is_torch_bf16_gpu_available, is_torch_npu_available |
| 22 | |
| 23 | from . import logging |
| 24 | |
| 25 | try: |
| 26 | _is_bf16_available = is_torch_bf16_gpu_available() or ( |
| 27 | is_torch_npu_available() and torch.npu.is_bf16_supported() |
| 28 | ) |
| 29 | except Exception: |
| 30 | _is_bf16_available = False |
| 31 | |
| 32 | from ..network.attention import configure_attn_implementation |
| 33 | from ..network.checkpointing import prepare_model_for_training |
| 34 | from ..network.rope import configure_rope |
| 35 | |
| 36 | if TYPE_CHECKING: |
| 37 | from transformers import PretrainedConfig, PreTrainedTokenizer, ProcessorMixin |
| 38 | |
| 39 | from ..hparams import ModelArguments |
| 40 | |
| 41 | |
| 42 | logger = logging.get_logger(__name__) |
| 43 | |
| 44 | |
| 45 | def patch_tokenizer( |
| 46 | tokenizer: "PreTrainedTokenizer", model_args: "ModelArguments" |
| 47 | ) -> None: |
| 48 | if "PreTrainedTokenizerBase" not in str(tokenizer._pad.__func__): |
| 49 | tokenizer._pad = MethodType(PreTrainedTokenizerBase._pad, tokenizer) |
| 50 | |
| 51 | if ( |
| 52 | model_args.model_max_length is not None |
| 53 | and tokenizer.model_max_length < model_args.model_max_length |
| 54 | ): |
| 55 | tokenizer.model_max_length = ( |
| 56 | model_args.model_max_length |
| 57 | ) # enlarge the tokenizer max length |
| 58 | |
| 59 | if model_args.add_tokens is not None: |
| 60 | num_added_tokens = tokenizer.add_tokens( |
| 61 | new_tokens=model_args.add_tokens, special_tokens=False |
| 62 | ) |
| 63 | logger.info_rank0( |
| 64 | "Add tokens {} to tokenizer's vocabulary.".format( |
| 65 | ",".join(model_args.add_tokens) |
| 66 | ) |
| 67 | ) |
| 68 | if num_added_tokens > 0 and not model_args.resize_vocab: |
| 69 | model_args.resize_vocab = True |
| 70 | logger.warning_rank0( |
| 71 | "New tokens have been added, changed `resize_vocab` to True." |
| 72 | ) |
| 73 | |
| 74 | if model_args.add_special_tokens is not None: |
| 75 | num_added_special_tokens = tokenizer.add_tokens( |
| 76 | new_tokens=model_args.add_special_tokens, special_tokens=True |
| 77 | ) |
| 78 | logger.info_rank0( |
| 79 | "Add special tokens {} to tokenizer's vocabulary.".format( |
| 80 | ",".join(model_args.add_special_tokens) |
| 81 | ) |
| 82 | ) |
| 83 | if num_added_special_tokens > 0 and not model_args.resize_vocab: |
| 84 | model_args.resize_vocab = True |
| 85 | logger.warning_rank0( |
| 86 | "New special tokens have been added, changed `resize_vocab` to True." |
| 87 | ) |
| 88 | |
| 89 | |
| 90 | def patch_processor( |
| 91 | processor: "ProcessorMixin", |
| 92 | tokenizer: "PreTrainedTokenizer", |
| 93 | ) -> None: |
| 94 | setattr(processor, "tokenizer", tokenizer) |
| 95 | |
| 96 | |
| 97 | def patch_config( |
| 98 | config: "PretrainedConfig", |
| 99 | model_args: "ModelArguments", |
| 100 | init_kwargs: dict[str, Any], |
| 101 | is_trainable: bool, |
| 102 | ) -> None: |
| 103 | if model_args.compute_dtype is None: # priority: bf16 > fp32 |
| 104 | if model_args.infer_dtype != "auto" and not is_trainable: |
| 105 | model_args.compute_dtype = getattr(torch, model_args.infer_dtype) |
| 106 | elif ( |
| 107 | _is_bf16_available |
| 108 | and getattr(config, "torch_dtype", None) == torch.bfloat16 |
| 109 | ): |
| 110 | model_args.compute_dtype = torch.bfloat16 |
| 111 | else: |
| 112 | model_args.compute_dtype = torch.float32 |
| 113 | |
| 114 | configure_attn_implementation(config, model_args) |
| 115 | configure_rope(config, model_args) |
| 116 | |
| 117 | if getattr(config, "model_type", None) == "qwen": |
| 118 | setattr(config, "use_flash_attn", model_args.flash_attn == "fa2") |
| 119 | for dtype_name, dtype in [ |
| 120 | ("bf16", torch.bfloat16), |
| 121 | ("fp32", torch.float32), |
| 122 | ]: |
| 123 | setattr(config, dtype_name, model_args.compute_dtype == dtype) |
| 124 | |
| 125 | # deepspeed zero3 is not compatible with low_cpu_mem_usage |
| 126 | init_kwargs["low_cpu_mem_usage"] = model_args.low_cpu_mem_usage and ( |
| 127 | not is_deepspeed_zero3_enabled() |
| 128 | ) |
| 129 | |
| 130 | |
| 131 | def patch_model( |
| 132 | model: "PreTrainedModel", |
| 133 | model_args: "ModelArguments", |
| 134 | is_trainable: bool, |
| 135 | ) -> None: |
| 136 | gen_config = model.generation_config # check and fix generation config |
| 137 | if not gen_config.do_sample and ( |
| 138 | (gen_config.temperature is not None and gen_config.temperature != 1.0) |
| 139 | or (gen_config.top_p is not None and gen_config.top_p != 1.0) |
| 140 | or (gen_config.typical_p is not None and gen_config.typical_p != 1.0) |
| 141 | ): |
| 142 | gen_config.do_sample = True |
| 143 | |
| 144 | if "GenerationMixin" not in str(model.generate.__func__): |
| 145 | model.generate = MethodType(GenerationMixin.generate, model) |
| 146 | |
| 147 | if is_trainable: |
| 148 | prepare_model_for_training(model, model_args) |
| 149 | |
| 150 | try: |
| 151 | model.add_model_tags(["spatiallm"]) |
| 152 | except Exception: |
| 153 | logger.warning_rank0("Cannot properly tag the model.") |