Hi! Write FULL code without comments to create text generation based on gpt-2, a model for working with images and text.
Use a prompt-based adapter(like LlaVa), find a dataset on hugging face where there is an image markup, a text description, and train the adapter. Use python. The model must accept either text, or an image, or all at once! Write inference code!
Assistant
python
import torch
from torch import nn
from torch.utils.data import DataLoader
from transformers import GPT2Tokenizer, GPT2LMHeadModel, CLIPProcessor, CLIPModel, AdamW
from datasets import load_dataset
from PIL import Image
class MultimodalGPT2(nn.Module):
def __init__(self, gpt2_model_name, clip_model_name):
super(MultimodalGPT2, self).__init__()
self.clip = CLIPModel.from_pretrained(clip_model_name)
self.gpt2 = GPT2LMHeadModel.from_pretrained(gpt2_model_name)
self.adapter = nn.Linear(self.clip.config.projection_dim, self.gpt2.config.n_embd)
def forward(self, input_ids, attention_mask, image=None):
if image is not None:
image_features = self.clip.get_image_features(pixel_values=image)
adapter_features = self.adapter(image_features)
adapter_features = adapter_features.unsqueeze(1).expand(-1, input_ids.size(1), -1)
inputs_embeds = self.gpt2.transformer.wte(input_ids) + adapter_features
outputs = self.gpt2(inputs_embeds=inputs_embeds, attention_mask=attention_mask, labels=input_ids)
else:
outputs = self.gpt2(input_ids=input_ids, attention_mask=attention_mask, labels=input_ids)
return outputs
def preprocess_data(example, processor, tokenizer):
if 'image' in example:
image = example['image'].convert('RGB')
image = processor(images=image, return_tensors="pt")['pixel_values'].squeeze()
else:
image = None
text = example['caption'] if 'caption' in example else example.get('text', '')
encoding = tokenizer(text, truncation=True, padding='max_length', max_length=128)
return {'input_ids': encoding['input_ids'], 'attention_mask': encoding['attention_mask'], 'image': image}
def collate_fn(batch):
input_ids = torch.tensor([item['input_ids'] for item in batch])
attention_mask = torch.tensor([item['attention_mask'] for item in batch])
images = torch.stack([item['image'] for item in batch if item['image'] is not None]) if any(item['image'] is not None for item in batch) else None
return {'input_ids': input_ids, 'attention_mask': attention_mask, 'image': images}
def main():
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
dataset = load_dataset('coco_captions', split='train')
tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
tokenizer.pad_token = tokenizer.eos_token
processor = CLIPProcessor.from_pretrained('openai/clip-vit-base-patch32')
processed_dataset = dataset.map(lambda x: preprocess_data(x, processor, tokenizer), remove_columns=dataset.column_names)
dataloader = DataLoader(processed_dataset, batch_size=8, shuffle=True, collate_fn=collate_fn)
model = MultimodalGPT2('gpt2', 'openai/clip-vit-base-patch32').to(device)
optimizer = AdamW(model.parameters(), lr=5e-5)
model.train()
for epoch in range(1):
for batch in dataloader:
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
images = batch['image'].to(device) if batch['image'] is not None else None
outputs = model(input_ids=input_ids, attention_mask=attention_mask, image=images)
loss = outputs.loss
loss.backward()
optimizer.step()
optimizer.zero_grad()
print(loss.item())
torch.save(model.state_dict(), 'multimodal_gpt2.pth')
model.eval()
def generate(prompt_text=None, image_path=None):
if prompt_text is not None:
input_ids = tokenizer.encode(prompt_text, return_tensors='pt').to(device)
attention_mask = torch.ones_like(input_ids).to(device)
else:
input_ids = torch.tensor([[tokenizer.eos_token_id]]).to(device)
attention_mask = torch.ones_like(input_ids).to(device)
if image_path is not None:
image = Image.open(image_path).convert('RGB')
image = processor(images=image, return_tensors="pt")['pixel_values'].to(device)
else:
image = None
with torch.no_grad():
if image is not None:
image_features = model.clip.get_image_features(pixel_values=image)
adapter_features = model.adapter(image_features).unsqueeze(1)
inputs_embeds = model.gpt2.transformer.wte(input_ids) + adapter_features
outputs = model.gpt2.generate(inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_length=50)
else:
outputs = model.gpt2.generate(input_ids=input_ids, attention_mask=attention_mask, max_length=50)
return tokenizer.decode(outputs[0], skip_special_tokens=True)
print(generate(prompt_text="A photo of a"))
print(generate(image_path='example.jpg'))
print(generate(prompt_text="A photo of a", image_path='example.jpg'))
if __name__ == "__main__":
main()