Analysis and Suggestions for Fixes:
The provided code appears to be an attempt to build and train a vision-language model that maps visual features from a CLIP model to an LLM (Language Model) using an adapter, with the intention to train only the adapter module with k-bit techniques and PEFT (Parameter-Efficient Fine-Tuning). However, there are several critical issues in the code that need to be addressed to make it functional and effective.
Below is a thorough examination of both preprocess_image.py and train_img.py, followed by suggested fixes.
1. preprocess_image.py
Issues and Fixes:
a. Incorrect Method Names in LlavaDataset Class
-
Issue: The methods init, len, and getitem are incorrectly named. In Python, special methods for classes (also known as "dunder" methods or magic methods) need to be defined with double underscores (__) before and after the method name.
-
Fix:
Rename the methods to __init__, __len__, and __getitem__ respectively.
class LlavaDataset(Dataset):
def __init__(self, json_file, image_dir, tokenizer, clip_processor, max_length=512):
# ... rest of the code ...
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
# ... rest of the code ...
b. Unnecessary Dependency on the Model Within the Dataset
-
Issue: The dataset class is currently depending on the model object to access the clip_processor, which is not a good practice. The model should not be passed into the dataset. Instead, any required processors or tokenizers should be passed directly.
-
Fix:
Pass the clip_processor directly to the dataset during initialization.
class LlavaDataset(Dataset):
def __init__(self, json_file, image_dir, tokenizer, clip_processor, max_length=512):
self.clip_processor = clip_processor
# ... rest of the code ...
def __getitem__(self, idx):
# Use self.clip_processor instead of accessing through the model
processed = self.clip_processor(images=image, return_tensors="pt", padding=True)
# ... rest of the code ...
c. Handling Missing Images Appropriately
-
Issue: If an image is missing or the 'image' key is not found in the item, the code sets image_file = None but still attempts to process it, which will result in an error.
-
Fix:
Skip items where the image is missing or cannot be loaded.
def __getitem__(self, idx):
item = self.data[idx]
if 'image' in item:
image_file = os.path.join(self.image_dir, item['image'])
if not os.path.exists(image_file):
print(f"Warning: Image file does not exist: {image_file}")
return None # Skip this item
image = Image.open(image_file).convert('RGB')
else:
print(f"Warning: 'image' key not found in item {idx}")
return None # Skip this item
# ... rest of the code ...
d. Return Consistent Data Types
-
Issue: The __getitem__ method should return consistent data types even when skipping items.
-
Fix:
Ensure that when an item is skipped, None is returned, and the collate_fn in the training script can handle None values.
2. train_img.py
Issues and Fixes:
a. Incorrect Usage of CLIPModel Arguments
-
Issue: In the ImageModel class, the argument attn_implementation="sdpa" is passed to CLIPModel.from_pretrained(), which is not a valid argument for this method.
-
Fix:
Remove the invalid argument. If attention implementation needs to be changed, it should be done through the configuration, not directly in the from_pretrained() method.
self.clip_model = CLIPModel.from_pretrained(clip_model_name, torch_dtype=torch.bfloat16)
b. Hardcoding Hidden Sizes
-
Issue: The hidden sizes for clip_hidden_size and llm_hidden_size are hardcoded, which can lead to mismatches if the models have different sizes.
-
Fix:
Dynamically obtain the hidden sizes from the model configurations.
clip_hidden_size = self.clip_model.config.projection_dim # For CLIP models
llm_hidden_size = 2048 # Replace with actual LLM hidden size if available
# Alternatively, obtain LLM hidden size from tokenizer or model if available
c. Incorrect Method Usage in Forward Pass
-
Issue: The method get_image_features() is called with output_hidden_states=True, which is not a valid argument for this method.
-
Fix:
Use the appropriate method to obtain hidden states. To get hidden states, you need to call the forward() method of the model.
with torch.no_grad():
outputs = self.clip_model(pixel_values=pixel_values, output_hidden_states=True)
image_features = outputs.last_hidden_state # Obtain the desired hidden state
d. Usage of prepare_model_for_kbit_training and PEFT
-
Issue: Applying prepare_model_for_kbit_training() and get_peft_model() to only model.adapter may not be appropriate.
-
Fix:
Apply prepare_model_for_kbit_training() to the entire model if needed, or directly to the adapter if that's the intended behavior. Ensure that modules are properly prepared for k-bit training.
# If intending to train only the adapter
prepare_model_for_kbit_training(model.adapter)
model.adapter = get_peft_model(model.adapter, peft_config)
e. Enabling Gradient Checkpointing
-
Issue: Calling gradient_checkpointing_enable() on the adapter may not work if the adapter does not support it.
-
Fix:
Remove or adjust gradient checkpointing based on whether the adapter supports it.
model.adapter.gradient_checkpointing_enable()
f. Handling Optimizers and Schedulers
-
Issue: The optimizer and scheduler are created but not passed to the Trainer. Also, there might be conflicts between the optimizer specified in TrainingArguments and the one created manually.
-
Fix:
Pass the optimizer and scheduler to the Trainer, or let the Trainer handle optimizer creation.
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
optimizers=(optimizer, scheduler),
data_collator=collate_fn,
)
Also, ensure that only one optimizer is being used and that there are no conflicts.
g. Correctly Using Data Collators
-
Issue: The custom collate_fn is defined but not passed to the Trainer.
-
Fix:
Pass the collate_fn to the Trainer as data_collator.
trainer = Trainer(
# ... other arguments ...
data_collator=collate_fn,
)
h. Multi-GPU Training
-
Issue: Using torch.nn.DataParallel is generally discouraged in favor of DistributedDataParallel, especially when using the Trainer.
-
Fix:
Let the Trainer handle multi-GPU setup by appropriately setting training_args.
training_args = TrainingArguments(
# ... other arguments ...
ddp_find_unused_parameters=False, # Add if necessary
)
Remove torch.nn.DataParallel wrapping.
i. Removing Debugging Prints in Production Code
-
Issue: There are several print statements for debugging purposes, which can clutter the output.
-
Fix:
Remove or comment out print statements or use logging with appropriate log levels.
j. Setting up the Tokenizer Properly
-
Issue: The tokenizer is being modified by adding special tokens but the model embeddings are not resized, which can create issues.
-
Fix:
After adding special tokens to the tokenizer, resize the model embeddings if necessary.
tokenizer.add_special_tokens({'additional_special_tokens': ['[IMAGE]']})
# If the LLM model is being used elsewhere, make sure to resize its embeddings
# model.resize_token_embeddings(len(tokenizer))
k. Correcting Paths and File Existence
Revised Code Snippets with Fixes Applied:
preprocess_image.py:
import json
import torch
from torch.utils.data import Dataset
from PIL import Image
import os
class LlavaDataset(Dataset):
def __init__(self, json_file, image_dir, tokenizer, clip_processor, max_length=512):
with open(json_file, 'r') as f:
self.data = json.load(f)
self.image_dir = image_dir
self.tokenizer = tokenizer
self.clip_processor = clip_processor
self.max_length = max_length
def __len__(self):
return len(self.data)
def __getitem__(self, idx):
item = self.data[idx]
if 'image' in item:
image_file = os.path.join(self.image_dir, item['image'])
if not os.path.exists(image_file):
print(f"Warning: Image file does not exist: {image_file}")
return None
image = Image.open(image_file).convert('RGB')
else:
print(f"Warning: 'image' key not found in item {idx}")
return None
processed = self.clip_processor(images=image, return_tensors="pt", padding=True)
pixel_values = processed['pixel_values'].squeeze(0)
conversation = item.get('conversations', [])
prompt = ""
for turn in conversation:
if turn['from'] == 'human':
prompt += f"Human: {turn['value']}\n"
elif turn['from'] == 'gpt':
prompt += f"Assistant: {turn['value']}\n"
prompt = prompt.replace('<image>', '[IMAGE]')
encoded_prompt = self.tokenizer(
prompt,
truncation=True,
max_length=self.max_length,
padding='max_length',
return_tensors='pt'
)
return {
'pixel_values': pixel_values,
'input_ids': encoded_prompt['input_ids'].squeeze(),
'attention_mask': encoded_prompt['attention_mask'].squeeze()
}
def load_llava_dataset(json_file, image_dir, tokenizer, clip_processor, max_length=2048):
return LlavaDataset(json_file, image_dir, tokenizer, clip_processor, max_length)
train_img.py:
import os
import torch
from torch import nn
from transformers import CLIPModel, CLIPProcessor, Trainer, TrainingArguments, AutoTokenizer
from peft import prepare_model_for_kbit_training, LoraConfig, get_peft_model
import bitsandbytes as bnb
from preprocess_image import load_llava_dataset
class ImageModel(nn.Module):
def __init__(self, clip_model_name):
super().__init__()
self.clip_model = CLIPModel.from_pretrained(clip_model_name, torch_dtype=torch.bfloat16)
self.clip_processor = CLIPProcessor.from_pretrained(clip_model_name)
# Freeze CLIP model
for param in self.clip_model.parameters():
param.requires_grad = False
clip_hidden_size = self.clip_model.config.projection_dim # For CLIP models
llm_hidden_size = 2048 # Adjust this to match your LLM's hidden size
self.adapter = nn.Sequential(
bnb.nn.Linear4bit(clip_hidden_size, llm_hidden_size),
nn.GELU(),
bnb.nn.Linear4bit(llm_hidden_size, llm_hidden_size)
)
def forward(self, pixel_values):
if pixel_values.dim() == 5:
pixel_values = pixel_values.squeeze(1)
device = pixel_values.device
self.clip_model = self.clip_model.to(device)
self.adapter = self.adapter.to(device)
with torch.no_grad():
outputs = self.clip_model(pixel_values=pixel_values)
image_features = outputs.image_embeds # Use the correct attribute
adapter_output = self.adapter(image_features)
return adapter_output
def main():
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print(f"Using device: {device}")
model = ImageModel(clip_model_name="openai/clip-vit-large-patch14-336")
model = model.to(device)
prepare_model_for_kbit_training(model.adapter)
peft_config = LoraConfig(
r=8,
lora_alpha=32,
lora_dropout=0.1,
bias="none",
target_modules=["0", "2"]
)
model.adapter = get_peft_model(model.adapter, peft_config)
tokenizer = AutoTokenizer.from_pretrained("microsoft/phi-2")
tokenizer.add_special_tokens({'additional_special_tokens': ['[IMAGE]']})
train_dataset = load_llava_dataset(
json_file='data/llava_instruct_150k/llava_instruct_150k.json',
image_dir='data/coco/train2017',
tokenizer=tokenizer,
clip_processor=model.clip_processor
)
training_args = TrainingArguments(
output_dir="./results",
num_train_epochs=1,
per_device_train_batch_size=16,
gradient_accumulation_steps=8,
warmup_steps=100,
weight_decay=0.01,
logging_dir='./logs',
logging_steps=10,
save_steps=500,
bf16=True,
optim="adamw_torch",
report_to="tensorboard",
)
def collate_fn(batch):
batch = [item for item in batch if item is not None]
if not batch:
print("Warning: Empty batch encountered")
return None
pixel_values = torch.stack([item['pixel_values'] for item in batch])
input_ids = torch.stack([item['input_ids'] for item in batch])
attention_mask = torch.stack([item['attention_mask'] for item in batch])
return {
'pixel_values': pixel_values,
'input_ids': input_ids,
'attention_mask': attention_mask,
}
trainer = Trainer(
model=model,
args=training_args,
train_dataset=train_dataset,
data_collator=collate_fn,
)
trainer.train()
trainer.save_model("./final_image_model")
if __name__ == "__main__":
main()
Conclusion:
By addressing these issues, the code should function more effectively, making the dataset independent of the model, properly using the CLIP model and PEFT methods, correctly initializing and using the tokenizer, and ensuring that the training loop operates without errors. Additionally, handling missing data and adjusting the code to follow best practices will enhance its robustness and maintainability.