| 1 | import os |
| 2 | from typing import TYPE_CHECKING, Any, Optional, TypedDict |
| 3 | |
| 4 | import torch |
| 5 | import transformers.dynamic_module_utils |
| 6 | from transformers.dynamic_module_utils import get_relative_imports |
| 7 | from transformers import ( |
| 8 | AutoConfig, |
| 9 | AutoModelForCausalLM, |
| 10 | AutoModelForSeq2SeqLM, |
| 11 | AutoModelForTextToWaveform, |
| 12 | AutoModelForVision2Seq, |
| 13 | AutoProcessor, |
| 14 | AutoTokenizer, |
| 15 | ) |
| 16 | |
| 17 | from . import logging |
| 18 | from .utils import check_version, count_parameters, is_env_enabled |
| 19 | from .patcher import patch_config, patch_model, patch_tokenizer, patch_processor |
| 20 | from .adapter import init_adapter |
| 21 | |
| 22 | if TYPE_CHECKING: |
| 23 | from transformers import ( |
| 24 | PretrainedConfig, |
| 25 | PreTrainedModel, |
| 26 | PreTrainedTokenizer, |
| 27 | ProcessorMixin, |
| 28 | ) |
| 29 | |
| 30 | from ..hparams import DataArguments, ModelArguments, FinetuningArguments |
| 31 | |
| 32 | logger = logging.get_logger(__name__) |
| 33 | |
| 34 | |
| 35 | class TokenizerModule(TypedDict): |
| 36 | tokenizer: "PreTrainedTokenizer" |
| 37 | processor: Optional["ProcessorMixin"] |
| 38 | |
| 39 | |
| 40 | def skip_check_imports() -> None: |
| 41 | r"""Avoid flash attention import error in custom model files.""" |
| 42 | if not is_env_enabled("FORCE_CHECK_IMPORTS"): |
| 43 | transformers.dynamic_module_utils.check_imports = get_relative_imports |
| 44 | |
| 45 | |
| 46 | def use_modelscope() -> bool: |
| 47 | return is_env_enabled("USE_MODELSCOPE_HUB") |
| 48 | |
| 49 | |
| 50 | def try_download_model_from_other_hub(model_args: "ModelArguments") -> str: |
| 51 | if not use_modelscope() or os.path.exists(model_args.model_name_or_path): |
| 52 | return model_args.model_name_or_path |
| 53 | |
| 54 | if use_modelscope(): |
| 55 | check_version("modelscope>=1.11.0", mandatory=True) |
| 56 | from modelscope import snapshot_download # type: ignore |
| 57 | |
| 58 | revision = ( |
| 59 | "master" |
| 60 | if model_args.model_revision == "main" |
| 61 | else model_args.model_revision |
| 62 | ) |
| 63 | return snapshot_download( |
| 64 | model_args.model_name_or_path, |
| 65 | revision=revision, |
| 66 | cache_dir=model_args.cache_dir, |
| 67 | ) |
| 68 | |
| 69 | |
| 70 | def _get_init_kwargs(model_args: "ModelArguments") -> dict[str, Any]: |
| 71 | r"""Get arguments to load config/tokenizer/model. |
| 72 | |
| 73 | Note: including inplace operation of model_args. |
| 74 | """ |
| 75 | model_args.model_name_or_path = try_download_model_from_other_hub(model_args) |
| 76 | return { |
| 77 | "trust_remote_code": model_args.trust_remote_code, |
| 78 | "cache_dir": model_args.cache_dir, |
| 79 | "revision": model_args.model_revision, |
| 80 | "token": model_args.hf_hub_token, |
| 81 | } |
| 82 | |
| 83 | |
| 84 | def load_config(model_args: "ModelArguments") -> "PretrainedConfig": |
| 85 | r"""Load model config.""" |
| 86 | init_kwargs = _get_init_kwargs(model_args) |
| 87 | return AutoConfig.from_pretrained(model_args.model_name_or_path, **init_kwargs) |
| 88 | |
| 89 | |
| 90 | def load_tokenizer(model_args: "ModelArguments") -> "TokenizerModule": |
| 91 | r"""Load pretrained tokenizer and optionally loads processor. |
| 92 | |
| 93 | Note: including inplace operation of model_args. |
| 94 | """ |
| 95 | init_kwargs = _get_init_kwargs(model_args) |
| 96 | try: |
| 97 | tokenizer = AutoTokenizer.from_pretrained( |
| 98 | model_args.model_name_or_path, |
| 99 | use_fast=model_args.use_fast_tokenizer, |
| 100 | split_special_tokens=model_args.split_special_tokens, |
| 101 | padding_side="right", |
| 102 | **init_kwargs, |
| 103 | ) |
| 104 | except ValueError: # try the fast one |
| 105 | tokenizer = AutoTokenizer.from_pretrained( |
| 106 | model_args.model_name_or_path, |
| 107 | use_fast=True, |
| 108 | padding_side="right", |
| 109 | **init_kwargs, |
| 110 | ) |
| 111 | except Exception as e: |
| 112 | raise OSError("Failed to load tokenizer.") from e |
| 113 | |
| 114 | patch_tokenizer(tokenizer, model_args) |
| 115 | |
| 116 | return {"tokenizer": tokenizer} |
| 117 | |
| 118 | |
| 119 | def register_autoclass( |
| 120 | config: "PretrainedConfig", |
| 121 | model: "PreTrainedModel", |
| 122 | tokenizer: "PreTrainedTokenizer", |
| 123 | ): |
| 124 | if "AutoConfig" in getattr(config, "auto_map", {}): |
| 125 | config.__class__.register_for_auto_class() |
| 126 | if "AutoModelForCausalLM" in getattr(config, "auto_map", {}): |
| 127 | model.__class__.register_for_auto_class() |
| 128 | if "AutoTokenizer" in tokenizer.init_kwargs.get("auto_map", {}): |
| 129 | tokenizer.__class__.register_for_auto_class() |
| 130 | |
| 131 | |
| 132 | def load_model( |
| 133 | tokenizer: "PreTrainedTokenizer", |
| 134 | data_args: "DataArguments", |
| 135 | model_args: "ModelArguments", |
| 136 | finetuning_args: "FinetuningArguments", |
| 137 | is_trainable: bool = False, |
| 138 | ) -> "PreTrainedModel": |
| 139 | r"""Load pretrained model.""" |
| 140 | init_kwargs = _get_init_kwargs(model_args) |
| 141 | config = load_config(model_args) |
| 142 | config.point_config["num_bins"] = data_args.num_bins |
| 143 | patch_config(config, model_args, init_kwargs, is_trainable) |
| 144 | |
| 145 | init_kwargs["config"] = config |
| 146 | init_kwargs["pretrained_model_name_or_path"] = model_args.model_name_or_path |
| 147 | |
| 148 | if model_args.train_from_scratch: |
| 149 | model = AutoModelForCausalLM.from_config( |
| 150 | config, trust_remote_code=model_args.trust_remote_code |
| 151 | ) |
| 152 | else: |
| 153 | model = AutoModelForCausalLM.from_pretrained(**init_kwargs) |
| 154 | |
| 155 | patch_model(model, model_args, is_trainable) |
| 156 | register_autoclass(config, model, tokenizer) |
| 157 | model = init_adapter(model, finetuning_args, is_trainable) |
| 158 | |
| 159 | if not is_trainable: |
| 160 | model.requires_grad_(False) |
| 161 | for param in model.parameters(): |
| 162 | if ( |
| 163 | param.data.dtype == torch.float32 |
| 164 | and model_args.compute_dtype != torch.float32 |
| 165 | ): |
| 166 | param.data = param.data.to(model_args.compute_dtype) |
| 167 | |
| 168 | model.eval() |
| 169 | else: |
| 170 | model.train() |
| 171 | |
| 172 | trainable_params, all_param = count_parameters(model) |
| 173 | if is_trainable: |
| 174 | param_stats = ( |
| 175 | f"trainable params: {trainable_params:,} || " |
| 176 | f"all params: {all_param:,} || trainable%: {100 * trainable_params / all_param:.4f}" |
| 177 | ) |
| 178 | else: |
| 179 | param_stats = f"all params: {all_param:,}" |
| 180 | |
| 181 | logger.info_rank0(param_stats) |
| 182 | |
| 183 | if model_args.print_param_status and int(os.getenv("LOCAL_RANK", "0")) == 0: |
| 184 | for name, param in model.named_parameters(): |
| 185 | print( |
| 186 | f"name: {name}, dtype: {param.dtype}, device: {param.device}, trainable: {param.requires_grad}" |
| 187 | ) |
| 188 | |
| 189 | return model |