venkat-natchi commited on
Commit
f315cdb
·
verified ·
1 Parent(s): 237d12f

Upload 8 files

Browse files
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from PIL import Image
2
+ import gradio as gr
3
+
4
+ import torch
5
+ import torch.nn as nn
6
+ from transformers import AutoTokenizer, pipeline
7
+ from transformers import AutoModelForCausalLM
8
+ from torchvision import transforms
9
+ from transformers import CLIPProcessor, CLIPModel
10
+
11
+ from model import build_mlp_vector_projector
12
+
13
+
14
+ device = "cpu"
15
+ # Load the CLIP model and processor
16
+ clip_model_name = "openai/clip-vit-base-patch16"
17
+ clip_model = CLIPModel.from_pretrained(clip_model_name).to(device)
18
+ clip_processor = CLIPProcessor.from_pretrained(clip_model_name)
19
+
20
+ clip_transform = transforms.Compose(
21
+ [
22
+ transforms.Resize((224, 224)),
23
+ transforms.ToTensor()
24
+ ]
25
+ )
26
+
27
+
28
+ def process_image(img_path):
29
+ image = Image.open(img_path).convert("RGB")
30
+ image = clip_transform(image)
31
+ inputs = clip_processor(text=[""], images=image,
32
+ return_tensors="pt", padding=True)
33
+ inputs = {k: v.to(device) for k, v in inputs.items()}
34
+ img_embedding = clip_model(**inputs).image_embeds
35
+ img_proj_head = build_mlp_vector_projector().to(device)
36
+ img_proj_head.load_state_dict(torch.load(
37
+ 'stage_2_proj_head_v3.pth', map_location=torch.device(device)))
38
+ img_tokens = img_proj_head(img_embedding)
39
+ return img_tokens
40
+
41
+
42
+ phi_model_name = "microsoft/phi-2"
43
+ text_tokenizer = AutoTokenizer.from_pretrained(
44
+ phi_model_name, trust_remote_code=True)
45
+ with torch.no_grad():
46
+ tuned_phi2 = AutoModelForCausalLM.from_pretrained(
47
+ "stage2_adaptor", trust_remote_code=True,
48
+ device=device, torch_dtype=torch.float16
49
+ )
50
+ base_phi2_text = AutoModelForCausalLM.from_pretrained(
51
+ phi_model_name, trust_remote_code=True,
52
+ device_map="auto", torch_dtype=torch.float16
53
+ )
54
+ print("phi2 model loaded")
55
+
56
+ audio_model_name = "openai/whisper-small"
57
+ audio_pipe = pipeline(
58
+ task="automatic-speech-recognition",
59
+ model=audio_model_name,
60
+ chunk_length_s=30,
61
+ device=device)
62
+
63
+
64
+ def process_text(text, count):
65
+ inputs = text_tokenizer(text, return_tensors="pt",
66
+ return_attention_mask=False)
67
+ prediction = text_tokenizer.batch_decode(
68
+ base_phi2_text.generate(
69
+ **inputs,
70
+ max_new_tokens=count,
71
+ bos_token_id=text_tokenizer.bos_token_id,
72
+ eos_token_id=text_tokenizer.eos_token_id,
73
+ pad_token_id=text_tokenizer.pad_token_id
74
+ )
75
+ )
76
+ return prediction[0].rstrip('<|endoftext|>').rstrip("\n")
77
+
78
+
79
+ def process_audio(audio):
80
+ if audio is None:
81
+ raise gr.Error(
82
+ "Please provide an audio file or record your input"
83
+ )
84
+
85
+ text = audio_pipe(
86
+ audio,
87
+ batch_size=8,
88
+ generate_kwargs={"task": "transcribe"},
89
+ return_timestamps=True
90
+ )["text"]
91
+ return text
92
+
93
+
94
+ def generate_response(image, audio, text, count):
95
+ count = int(count)
96
+ if audio:
97
+ text_from_audio = process_audio(audio)
98
+ if text:
99
+ overall_input = text + text_from_audio
100
+ if image:
101
+ img_tokens = process_image(image)
102
+ q_tokens = text_tokenizer.encode(
103
+ overall_input,
104
+ return_tensors='pt').to(device)
105
+ question_token_embeddings = base_phi2_text.get_submodule(
106
+ 'model.embed_tokens')(q_tokens).to(device)
107
+ inputs = torch.concat(
108
+ (img_tokens.unsqueeze(0), question_token_embeddings),
109
+ axis=-2).to(device)
110
+ prediction = text_tokenizer.batch_decode(
111
+ tuned_phi2.generate(
112
+ inputs_embeds=inputs,
113
+ max_new_tokens=30,
114
+ bos_token_id=text_tokenizer.bos_token_id,
115
+ eos_token_id=text_tokenizer.eos_token_id,
116
+ pad_token_id=text_tokenizer.pad_token_id
117
+ )
118
+ )
119
+ return prediction[0].rstrip('<|endoftext|>').rstrip("\n")
120
+ else:
121
+ return process_text(overall_input, count)
122
+
123
+ return prediction[0].strip('<|endoftext|>').rstrip("\n")
124
+
125
+
126
+ with gr.Blocks() as demo:
127
+ gr.Markdown("# **AnyModeAssistant**")
128
+ gr.Markdown("Use any mode text/image/audio to interact with AI assistant")
129
+ with gr.Column():
130
+ with gr.Row("Text"):
131
+ text_input = gr.Textbox(placeholder="Enter your question here",
132
+ label="Input")
133
+ with gr.Row():
134
+ image_input = gr.Image(type="filepath")
135
+
136
+ with gr.Row("Audio mode"):
137
+ audio_input = gr.Audio(type="filepath")
138
+
139
+ with gr.Row("Image"):
140
+ response_count = gr.Textbox(
141
+ placeholder="Number of tokens to respond",
142
+ defualt=20,
143
+ label="Count")
144
+ with gr.Column():
145
+ response = gr.Textbox(label="AI Response")
146
+ with gr.Row():
147
+ submit_button = gr.Button("Submit")
148
+ submit_button.click(generate_response,
149
+ inputs=[text_input, response_count,
150
+ image_input, audio_input],
151
+ outputs=response)
152
+
153
+ # gr.Examples(
154
+ # examples=[
155
+ # ["What is a large language model?", "50"]
156
+ # ],
157
+ # # , image_input, image_text_input, audio_input],
158
+ # inputs=[text_input, text_input_count],
159
+ # outputs=[text_output], # , image_text_output, audio_text_output],
160
+ # fn=example_inference,
161
+ # )
162
+
163
+ demo.launch()
dataset.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from transformers import AutoTokenizer, AutoConfig
5
+ import json
6
+ from torch.utils.data import Dataset, DataLoader
7
+
8
+ instruct_dataset = f'./llava_instruct_150k.json'
9
+ with open(instruct_dataset, 'r') as f:
10
+ instruct_data = json.load(f)
11
+
12
+ class CustomTextDataset(Dataset):
13
+ def __init__(self, json_data, image_embedding_dict, tokenizer, maxContext=512):
14
+ self.image_embedding_dict = image_embedding_dict
15
+ self.tokenizer = tokenizer
16
+ self.json_data = json_data
17
+ self.maxContext = maxContext
18
+ self.entries = []
19
+ for entry in json_data:
20
+ image = entry['image']
21
+ image_embedding = self.getEmbeddingForImage(image)
22
+ if image_embedding is None:
23
+ continue
24
+
25
+ conversations = entry['conversations']
26
+ for i in range(len(conversations)):
27
+ if conversations[i]['from'] == 'human':
28
+ if len(conversations[i]['value'] + conversations[i + 1]['value']) > 512:
29
+ continue
30
+ question = 'Question: ' + conversations[i]['value'].lstrip('<image>\n')
31
+ answer = 'Answer: ' + conversations[i + 1]['value']
32
+ self.entries.append({
33
+ 'image_name': image,
34
+ 'image_embedding': image_embedding,
35
+ 'Question': question,
36
+ 'Answer': answer,
37
+ 'QnAText': question + answer
38
+ })
39
+ print('------------- num entries = -----------------')
40
+ print(len(self.entries))
41
+
42
+ def getEmbeddingForImage(self, image):
43
+ if image in self.image_embedding_dict:
44
+ image_embedding = self.image_embedding_dict[image]
45
+ return image_embedding
46
+ else:
47
+ return None
48
+
49
+ def __len__(self):
50
+ return len(self.entries)
51
+
52
+ def __getitem__(self, idx):
53
+ entry = self.entries[idx]
54
+ image_name = entry['image_name']
55
+ Q_caption_tokens = tokenizer.encode(entry['Question'], add_special_tokens=True)
56
+ QnA_captions_tokens = tokenizer.encode(entry['QnAText'], add_special_tokens=True)
57
+ QTokensLength = len(Q_caption_tokens)
58
+ QnA_length = len(QnA_captions_tokens)
59
+
60
+
61
+ QnA_captions_tokens = QnA_captions_tokens + \
62
+ [tokenizer.pad_token_id] * (self.maxContext - len(QnA_captions_tokens))
63
+
64
+ return {'image_name': entry['image_name'],
65
+ 'QText': entry['Question'],
66
+ 'AText': entry['Answer'],
67
+ 'image_embedding': entry['image_embedding'].to("cuda"),
68
+ 'QnA_tokens': torch.tensor(QnA_captions_tokens),
69
+ 'QTokensLength': QTokensLength,
70
+ 'QnA_length': QnA_length
71
+ }
72
+
73
+
74
+
75
+ imgEmbDict = torch.load('img_embeddings_dict.pth')
76
+
77
+ model_name = "microsoft/phi-2"
78
+ tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
79
+ tokenizer.pad_token = tokenizer.eos_token
80
+
81
+ custom_dataset = CustomTextDataset(instruct_data, imgEmbDict, tokenizer)
82
+ custom_dataloader = DataLoader(custom_dataset, batch_size=10, shuffle=True)
model.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ import torch.nn.functional as F
4
+ from transformers import AutoTokenizer, AutoConfig
5
+
6
+ class _MLPVectorProjector(nn.Module):
7
+ def __init__(
8
+ self,
9
+ input_hidden_size: int = 512,
10
+ lm_hidden_size: int = 2560,
11
+ num_layers: int = 1,
12
+ width: int = 4
13
+ ):
14
+ super(_MLPVectorProjector, self).__init__()
15
+ self.mlps = nn.ModuleList()
16
+ for _ in range(width):
17
+ mlp = [nn.Linear(input_hidden_size, lm_hidden_size, bias=False)]
18
+ for _ in range(1, num_layers):
19
+ mlp.append(nn.GELU())
20
+ mlp.append(nn.Linear(lm_hidden_size, lm_hidden_size, bias=False))
21
+ self.mlps.append(nn.Sequential(*mlp))
22
+
23
+ def forward(self, x):
24
+ return torch.cat([mlp(x) for mlp in self.mlps], dim=-2)
25
+
26
+
27
+ def build_mlp_vector_projector(
28
+ input_hidden_size: int = 512,
29
+ lm_hidden_size: int = 2560,
30
+ num_layers: int = 1,
31
+ num_tokens: int = 4
32
+ ):
33
+ return _MLPVectorProjector(
34
+ input_hidden_size, lm_hidden_size, num_layers, num_tokens
35
+ )
36
+
stage2_adaptor/README.md ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ library_name: peft
3
+ base_model: microsoft/phi-2
4
+ ---
5
+
6
+ # Model Card for Model ID
7
+
8
+ <!-- Provide a quick summary of what the model is/does. -->
9
+
10
+
11
+
12
+ ## Model Details
13
+
14
+ ### Model Description
15
+
16
+ <!-- Provide a longer summary of what this model is. -->
17
+
18
+
19
+
20
+ - **Developed by:** [More Information Needed]
21
+ - **Funded by [optional]:** [More Information Needed]
22
+ - **Shared by [optional]:** [More Information Needed]
23
+ - **Model type:** [More Information Needed]
24
+ - **Language(s) (NLP):** [More Information Needed]
25
+ - **License:** [More Information Needed]
26
+ - **Finetuned from model [optional]:** [More Information Needed]
27
+
28
+ ### Model Sources [optional]
29
+
30
+ <!-- Provide the basic links for the model. -->
31
+
32
+ - **Repository:** [More Information Needed]
33
+ - **Paper [optional]:** [More Information Needed]
34
+ - **Demo [optional]:** [More Information Needed]
35
+
36
+ ## Uses
37
+
38
+ <!-- Address questions around how the model is intended to be used, including the foreseeable users of the model and those affected by the model. -->
39
+
40
+ ### Direct Use
41
+
42
+ <!-- This section is for the model use without fine-tuning or plugging into a larger ecosystem/app. -->
43
+
44
+ [More Information Needed]
45
+
46
+ ### Downstream Use [optional]
47
+
48
+ <!-- This section is for the model use when fine-tuned for a task, or when plugged into a larger ecosystem/app -->
49
+
50
+ [More Information Needed]
51
+
52
+ ### Out-of-Scope Use
53
+
54
+ <!-- This section addresses misuse, malicious use, and uses that the model will not work well for. -->
55
+
56
+ [More Information Needed]
57
+
58
+ ## Bias, Risks, and Limitations
59
+
60
+ <!-- This section is meant to convey both technical and sociotechnical limitations. -->
61
+
62
+ [More Information Needed]
63
+
64
+ ### Recommendations
65
+
66
+ <!-- This section is meant to convey recommendations with respect to the bias, risk, and technical limitations. -->
67
+
68
+ Users (both direct and downstream) should be made aware of the risks, biases and limitations of the model. More information needed for further recommendations.
69
+
70
+ ## How to Get Started with the Model
71
+
72
+ Use the code below to get started with the model.
73
+
74
+ [More Information Needed]
75
+
76
+ ## Training Details
77
+
78
+ ### Training Data
79
+
80
+ <!-- This should link to a Dataset Card, perhaps with a short stub of information on what the training data is all about as well as documentation related to data pre-processing or additional filtering. -->
81
+
82
+ [More Information Needed]
83
+
84
+ ### Training Procedure
85
+
86
+ <!-- This relates heavily to the Technical Specifications. Content here should link to that section when it is relevant to the training procedure. -->
87
+
88
+ #### Preprocessing [optional]
89
+
90
+ [More Information Needed]
91
+
92
+
93
+ #### Training Hyperparameters
94
+
95
+ - **Training regime:** [More Information Needed] <!--fp32, fp16 mixed precision, bf16 mixed precision, bf16 non-mixed precision, fp16 non-mixed precision, fp8 mixed precision -->
96
+
97
+ #### Speeds, Sizes, Times [optional]
98
+
99
+ <!-- This section provides information about throughput, start/end time, checkpoint size if relevant, etc. -->
100
+
101
+ [More Information Needed]
102
+
103
+ ## Evaluation
104
+
105
+ <!-- This section describes the evaluation protocols and provides the results. -->
106
+
107
+ ### Testing Data, Factors & Metrics
108
+
109
+ #### Testing Data
110
+
111
+ <!-- This should link to a Dataset Card if possible. -->
112
+
113
+ [More Information Needed]
114
+
115
+ #### Factors
116
+
117
+ <!-- These are the things the evaluation is disaggregating by, e.g., subpopulations or domains. -->
118
+
119
+ [More Information Needed]
120
+
121
+ #### Metrics
122
+
123
+ <!-- These are the evaluation metrics being used, ideally with a description of why. -->
124
+
125
+ [More Information Needed]
126
+
127
+ ### Results
128
+
129
+ [More Information Needed]
130
+
131
+ #### Summary
132
+
133
+
134
+
135
+ ## Model Examination [optional]
136
+
137
+ <!-- Relevant interpretability work for the model goes here -->
138
+
139
+ [More Information Needed]
140
+
141
+ ## Environmental Impact
142
+
143
+ <!-- Total emissions (in grams of CO2eq) and additional considerations, such as electricity usage, go here. Edit the suggested text below accordingly -->
144
+
145
+ Carbon emissions can be estimated using the [Machine Learning Impact calculator](https://mlco2.github.io/impact#compute) presented in [Lacoste et al. (2019)](https://arxiv.org/abs/1910.09700).
146
+
147
+ - **Hardware Type:** [More Information Needed]
148
+ - **Hours used:** [More Information Needed]
149
+ - **Cloud Provider:** [More Information Needed]
150
+ - **Compute Region:** [More Information Needed]
151
+ - **Carbon Emitted:** [More Information Needed]
152
+
153
+ ## Technical Specifications [optional]
154
+
155
+ ### Model Architecture and Objective
156
+
157
+ [More Information Needed]
158
+
159
+ ### Compute Infrastructure
160
+
161
+ [More Information Needed]
162
+
163
+ #### Hardware
164
+
165
+ [More Information Needed]
166
+
167
+ #### Software
168
+
169
+ [More Information Needed]
170
+
171
+ ## Citation [optional]
172
+
173
+ <!-- If there is a paper or blog post introducing the model, the APA and Bibtex information for that should go in this section. -->
174
+
175
+ **BibTeX:**
176
+
177
+ [More Information Needed]
178
+
179
+ **APA:**
180
+
181
+ [More Information Needed]
182
+
183
+ ## Glossary [optional]
184
+
185
+ <!-- If relevant, include terms and calculations in this section that can help readers understand the model or model card. -->
186
+
187
+ [More Information Needed]
188
+
189
+ ## More Information [optional]
190
+
191
+ [More Information Needed]
192
+
193
+ ## Model Card Authors [optional]
194
+
195
+ [More Information Needed]
196
+
197
+ ## Model Card Contact
198
+
199
+ [More Information Needed]
200
+
201
+
202
+ ### Framework versions
203
+
204
+ - PEFT 0.7.1
stage2_adaptor/adapter_config.json ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "alpha_pattern": {},
3
+ "auto_mapping": {
4
+ "base_model_class": "PhiForCausalLM",
5
+ "parent_library": "transformers_modules.microsoft.phi-2.cb02e3efd822d6dbc1ca7e0dff31c29a11550411.modeling_phi"
6
+ },
7
+ "base_model_name_or_path": "microsoft/phi-2",
8
+ "bias": "none",
9
+ "fan_in_fan_out": false,
10
+ "inference_mode": true,
11
+ "init_lora_weights": true,
12
+ "layers_pattern": null,
13
+ "layers_to_transform": null,
14
+ "loftq_config": {},
15
+ "lora_alpha": 16,
16
+ "lora_dropout": 0.1,
17
+ "megatron_config": null,
18
+ "megatron_core": "megatron.core",
19
+ "modules_to_save": null,
20
+ "peft_type": "LORA",
21
+ "r": 64,
22
+ "rank_pattern": {},
23
+ "revision": null,
24
+ "target_modules": [
25
+ "fc2",
26
+ "fc1",
27
+ "out_proj",
28
+ "Wqkv"
29
+ ],
30
+ "task_type": null
31
+ }
stage2_adaptor/adapter_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ef13f8dac86c856f0ec2c6847f6a0b058b2387bba0b896b89b7cd2cc835b5965
3
+ size 209731504
stage_2_proj_head_v3.pth ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:4d7cb2049e9e62b633caacc5311380e55b842c4c51f23755546ec6490f93f119
3
+ size 20973485