|
| 1 | +from typing import TYPE_CHECKING, Dict |
| 2 | + |
| 3 | +import torch |
| 4 | +from transformers.utils import cached_file |
| 5 | + |
| 6 | +from ...extras.constants import V_HEAD_SAFE_WEIGHTS_NAME, V_HEAD_WEIGHTS_NAME |
| 7 | +from ...extras.logging import get_logger |
| 8 | + |
| 9 | + |
| 10 | +if TYPE_CHECKING: |
| 11 | + from transformers import PretrainedConfig, PreTrainedModel |
| 12 | + |
| 13 | + from ...hparams import ModelArguments |
| 14 | + |
| 15 | + |
| 16 | +logger = get_logger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +def configure_valuehead(config: "PretrainedConfig") -> None: |
| 20 | + if getattr(config, "model_type", None) == "llava": |
| 21 | + setattr(config, "hidden_size", getattr(config.vision_config, "intermediate_size", None)) |
| 22 | + |
| 23 | + |
| 24 | +def load_valuehead_params(path_or_repo_id: str, model_args: "ModelArguments") -> Dict[str, torch.Tensor]: |
| 25 | + r""" |
| 26 | + Loads value head parameters from Hugging Face Hub or local disk. |
| 27 | +
|
| 28 | + Returns: dict with keys `v_head.summary.weight` and `v_head.summary.bias`. |
| 29 | + """ |
| 30 | + kwargs = {"path_or_repo_id": path_or_repo_id, "cache_dir": model_args.cache_dir, "token": model_args.hf_hub_token} |
| 31 | + |
| 32 | + try: |
| 33 | + from safetensors import safe_open |
| 34 | + |
| 35 | + vhead_file = cached_file(filename=V_HEAD_SAFE_WEIGHTS_NAME, **kwargs) |
| 36 | + with safe_open(vhead_file, framework="pt", device="cpu") as f: |
| 37 | + return {key: f.get_tensor(key) for key in f.keys()} |
| 38 | + except Exception as err: |
| 39 | + logger.info("Failed to load {}: {}".format(V_HEAD_SAFE_WEIGHTS_NAME, str(err))) |
| 40 | + |
| 41 | + try: |
| 42 | + vhead_file = cached_file(filename=V_HEAD_WEIGHTS_NAME, **kwargs) |
| 43 | + return torch.load(vhead_file, map_location="cpu") |
| 44 | + except Exception as err: |
| 45 | + logger.info("Failed to load {}: {}".format(V_HEAD_WEIGHTS_NAME, str(err))) |
| 46 | + |
| 47 | + logger.info("Provided path ({}) does not contain value head weights.".format(path_or_repo_id)) |
| 48 | + logger.info("Ignore these messages if you are not resuming the training of a value head model.") |
| 49 | + return None |
| 50 | + |
| 51 | + |
| 52 | +def prepare_valuehead_model(model: "PreTrainedModel") -> None: |
| 53 | + if getattr(model.config, "model_type", None) == "llava": |
| 54 | + setattr(model, "lm_head", model.language_model.get_output_embeddings()) |
| 55 | + setattr(model, "_keys_to_ignore_on_save", ["lm_head.weight"]) |
| 56 | + |
| 57 | + if getattr(model.config, "model_type", None) == "chatglm": |
| 58 | + setattr(model, "lm_head", model.transformer.output_layer) |
| 59 | + setattr(model, "_keys_to_ignore_on_save", ["lm_head.weight"]) |
0 commit comments