fangedvampire24 commited on
Commit
fcd12e4
·
verified ·
1 Parent(s): 831b646

Create train.py

Browse files
Files changed (1) hide show
  1. train.py +102 -0
train.py ADDED
@@ -0,0 +1,102 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from datasets import load_dataset, load_metric
3
+ from transformers import (
4
+ AutoProcessor,
5
+ BlipForConditionalGeneration,
6
+ TrainingArguments,
7
+ Trainer,
8
+ )
9
+ from PIL import Image
10
+
11
+ # --- 1. CONFIGURATION ---
12
+ MODEL_NAME = "Salesforce/blip-image-captioning-base"
13
+ DATASET_ID = "lambdalabs/pokemon-blip-captions" # Replace with COCO or your specialized dataset
14
+ OUTPUT_DIR = "./blip-image-captioning-finetuned"
15
+ NUM_TRAIN_EPOCHS = 3
16
+ BATCH_SIZE = 16
17
+
18
+ # --- 2. LOAD PROCESSOR AND MODEL ---
19
+ # The processor handles both image feature extraction and text tokenization
20
+ processor = AutoProcessor.from_pretrained(MODEL_NAME)
21
+ model = BlipForConditionalGeneration.from_pretrained(MODEL_NAME)
22
+
23
+ # --- 3. LOAD & PREPARE DATASET ---
24
+ print(f"Loading dataset: {DATASET_ID}")
25
+ ds = load_dataset(DATASET_ID)
26
+ # We'll use the 'train' split and split it further for a validation set
27
+ ds = ds['train'].train_test_split(test_size=0.1)
28
+ train_ds = ds['train']
29
+ eval_ds = ds['test']
30
+
31
+ # Set the maximum sequence length for the captions
32
+ max_caption_length = 50
33
+
34
+ def preprocess_data(examples):
35
+ """Tokenizes captions and processes images."""
36
+ # Process images and captions together
37
+ # BLIP processor handles image resizing, normalization, and text tokenization
38
+ inputs = processor(
39
+ images=[image.convert("RGB") for image in examples["image"]],
40
+ text=examples["text"],
41
+ padding="max_length",
42
+ max_length=max_caption_length,
43
+ truncation=True,
44
+ return_tensors="pt"
45
+ )
46
+
47
+ # The labels for Causal Language Modeling are the input tokens shifted right
48
+ # The tokenizer includes BOS/EOS tokens which are essential here
49
+ inputs["labels"] = inputs["input_ids"]
50
+
51
+ # Delete the original image data since the processor has converted it to pixel_values
52
+ del inputs["input_ids"]
53
+ del inputs["attention_mask"]
54
+
55
+ return inputs
56
+
57
+ # Apply the preprocessing function to the dataset
58
+ print("Applying preprocessing to the dataset...")
59
+ # set_transform is highly efficient as it applies the function on-the-fly
60
+ train_ds.set_transform(preprocess_data)
61
+ eval_ds.set_transform(preprocess_data)
62
+
63
+
64
+ # --- 4. TRAINING SETUP (Trainer API) ---
65
+ # Define evaluation metric (often BLEU or ROUGE, but WER is common for generation)
66
+ # Note: For simplicity, we skip complex metric computation in this basic script.
67
+
68
+ training_args = TrainingArguments(
69
+ output_dir=OUTPUT_DIR,
70
+ num_train_epochs=NUM_TRAIN_EPOCHS,
71
+ per_device_train_batch_size=BATCH_SIZE,
72
+ per_device_eval_batch_size=BATCH_SIZE,
73
+ learning_rate=5e-5,
74
+ evaluation_strategy="epoch",
75
+ logging_dir=f"{OUTPUT_DIR}/logs",
76
+ logging_steps=100,
77
+ save_strategy="epoch",
78
+ load_best_model_at_end=True,
79
+ fp16=torch.cuda.is_available(), # Use mixed precision if a GPU is available
80
+ push_to_hub=True, # Set this to True to push the model to the Hugging Face Hub!
81
+ hub_model_id=f"YOUR_HUGGINGFACE_USERNAME/blip-finetuned-{DATASET_ID.split('/')[-1]}", # Customize this
82
+ )
83
+
84
+ trainer = Trainer(
85
+ model=model,
86
+ args=training_args,
87
+ train_dataset=train_ds,
88
+ eval_dataset=eval_ds,
89
+ tokenizer=processor.tokenizer, # Pass the tokenizer for the Trainer to use
90
+ )
91
+
92
+ # --- 5. START TRAINING ---
93
+ print("Starting training...")
94
+ trainer.train()
95
+ print("Training complete! Pushing model to Hub...")
96
+
97
+ # --- 6. SAVE & PUSH TO HUB ---
98
+ trainer.save_model(OUTPUT_DIR)
99
+ # The push_to_hub=True in TrainingArguments automatically handles the final push.
100
+
101
+ # You will need to log in to your Hugging Face account via the command line
102
+ # (huggingface-cli login) or in a notebook (from huggingface_hub import notebook_login; notebook_login()).