File size: 4,744 Bytes
c62903f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# Adopted from https://github.com/haotian-liu/LLaVA. We modify the code to support speech input. Below is the original copyright:
#    Copyright 2023 Haotian Liu
#
#    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.

import os
import shutil
import warnings

import torch
import torch.distributed as dist
from transformers import (
    AutoConfig,
    AutoModelForCausalLM,
    AutoTokenizer,
    BitsAndBytesConfig,
)

from egogpt.model import *
from egogpt.model.speech_encoder.builder import build_speech_encoder


def load_pretrained_model(
    model_path,
    model_base=None,
    is_lora=False,
    load_8bit=False,
    load_4bit=False,
    device="cuda",
    use_flash_attn=False,
    **kwargs,
):
    # if dist.is_available() and not dist.is_initialized():
    #     dist.init_process_group(backend='nccl',init_method='env://')
    if load_8bit:
        kwargs["load_in_8bit"] = True
    elif load_4bit:
        kwargs["load_in_4bit"] = True
        kwargs["quantization_config"] = BitsAndBytesConfig(
            load_in_4bit=True,
            bnb_4bit_compute_dtype=torch.float16,
            bnb_4bit_use_double_quant=True,
            bnb_4bit_quant_type="nf4",
        )
    else:
        kwargs["torch_dtype"] = torch.float16

    if use_flash_attn:
        kwargs["attn_implementation"] = "flash_attention_2"

    model_cls = EgoGPTQwenForCausalLM

    # Load EgoGPT model
    if is_lora:
        assert model_base is not None, "model_base is required for LoRA models."
        from egogpt.model.language_model.egogpt_llama import EgoGPTConfig

        lora_cfg_pretrained = EgoGPTConfig.from_pretrained(model_path)
        tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
        print("Loading EgoGPT from base model...")
        model = model_cls.from_pretrained(
            model_base, low_cpu_mem_usage=False, config=lora_cfg_pretrained, **kwargs
        )
        print("Loading additional EgoGPT weights...")
        if os.path.exists(os.path.join(model_path, "non_lora_trainables.bin")):
            non_lora_trainables = torch.load(
                os.path.join(model_path, "non_lora_trainables.bin"), map_location="cpu"
            )
        non_lora_trainables = {
            (k[11:] if k.startswith("base_model.") else k): v
            for k, v in non_lora_trainables.items()
        }
        if any(k.startswith("model.model.") for k in non_lora_trainables):
            non_lora_trainables = {
                (k[6:] if k.startswith("model.") else k): v
                for k, v in non_lora_trainables.items()
            }
        model.load_state_dict(non_lora_trainables, strict=False)

        from peft import PeftModel

        print("Loading LoRA weights...")
        model = PeftModel.from_pretrained(model, model_path)
        print("Merging LoRA weights...")
        model = model.merge_and_unload()
        print("Model is loaded...")
    elif model_base is not None:
        print("Loading EgoGPT from base model...")
        tokenizer = AutoTokenizer.from_pretrained(model_base, use_fast=False)
        cfg_pretrained = AutoConfig.from_pretrained(model_path)
        model = model_cls.from_pretrained(
            model_base, low_cpu_mem_usage=False, config=cfg_pretrained, **kwargs
        )

        speech_projector_weights = torch.load(
            os.path.join(model_path, "speech_projector.bin"), map_location="cpu"
        )
        speech_projector_weights = {
            k: v.to(torch.float16) for k, v in speech_projector_weights.items()
        }
        model.load_state_dict(speech_projector_weights, strict=False)
        model = model.to(device=device)
    else:
        tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=False)
        model = model_cls.from_pretrained(model_path, low_cpu_mem_usage=True, **kwargs)
        model = model.to(device=device)

    context_len = 4096
    # model.get_model().speech_encoder = build_speech_encoder(model.config)
    # model.get_model().speech_encoder.to(device=device, dtype=torch.float16)

    # if hasattr(model.config, "max_sequence_length"):
    #     context_len = model.config.max_sequence_length
    # else:
    #     context_len = 2048

    return tokenizer, model, context_len