import os
import warnings
import pandas as pd
import time
from PIL import Image
import requests
from io import BytesIO
import torch
from torch.utils.data import DataLoader
from torch import nn, optim
from transformers import DonutProcessor, VisionEncoderDecoderModel
import pytorch_lightning as pl
from torch.utils.data.dataloader import default_collate
def __len__(self):
return len(self.data_list)
def __getitem__(self, idx):
sample = self.data_list[idx]
image_url = sample['image_url']
prompt = sample['text']
# Retry logic for downloading the image
max_retries = 4
num_retries = 0
success = False
while num_retries < max_retries and not success:
try:
response = requests.get(image_url, timeout=10)
response.raise_for_status()
image = Image.open(BytesIO(response.content)).convert("RGB")
image = image.resize((32, 32)) # Change resolution here
success = True
except Exception as e:
num_retries += 1
print(f"Error loading image from {image_url} on attempt {num_retries}: {e}")
if num_retries >= max_retries:
print(f"Skipping image {image_url} after {max_retries} failed attempts.")
return None
else:
time.sleep(1) # Optional delay between retries
pixel_values = self.processor(image, return_tensors="pt").pixel_values.squeeze()
labels = self.processor.tokenizer(
prompt,
max_length=self.max_length,
padding="max_length",
truncation=True,
return_tensors="pt",
).input_ids.squeeze()
labels[labels == self.processor.tokenizer.pad_token_id] = self.ignore_id
return {"pixel_values": pixel_values, "labels": labels}
Assistant
Custom collate function to filter None samples
def collate_fn(batch):
batch = [sample for sample in batch if sample is not None]
if len(batch) == 0:
return None # Skip this batch
else:
return default_collate(batch)
Training model class
class DonutModel(pl.LightningModule):
def init(self, processor, model, lr=1e-5):
super().init()
self.processor = processor
self.model = model
self.lr = lr
code
def on_train_start(self):
self.model.train()
for param in self.model.parameters():
param.requires_grad = True
num_train = sum(1 for m in self.model.modules() if m.training)
num_eval = sum(1 for m in self.model.modules() if not m.training)
print(f"Modules in train mode: {num_train}, eval mode: {num_eval}")
def training_step(self, batch, batch_idx):
if batch is None:
return None
outputs = self.model(pixel_values=batch["pixel_values"], labels=batch["labels"])
loss = outputs.loss
self.log('train_loss', loss, on_step=True, on_epoch=True, prog_bar=True, logger=True)
return loss
def configure_optimizers(self):
return torch.optim.Adam(self.parameters(), lr=self.lr)
for epoch in range(epochs):
optimizer.zero_grad()
for step, batch in enumerate(train_dataloader):
if batch is None:
continue
pixel_values = batch.get("pixel_values")
labels = batch.get("labels")
if pixel_values is None or labels is None:
raise ValueError("Expected 'pixel_values' and 'labels' in batch but found None.")
pixel_values = pixel_values.to('cuda').float() # Ensure float32
labels = labels.to('cuda')
# Forward pass with autocast
with autocast():
outputs = model(pixel_values=pixel_values, labels=labels)
loss = outputs.loss
# Scale loss and backward pass
loss = loss / accumulation_steps
scaler.scale(loss).backward()
# Update weights
if (step + 1) % accumulation_steps == 0:
scaler.step(optimizer)
scaler.update()
optimizer.zero_grad()
# Print progress
if step % 10 == 0:
print(f"Epoch {epoch+1}/{epochs}, Step {step}, Loss: {loss.item()}")
# Clear GPU cache
torch.cuda.empty_cache()
def main():
import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
code
train_csv = 'shortened_dataset.csv'
print("Loading training data...")
train_df = pd.read_csv(train_csv)
print("Creating training annotations...")
train_annotations = create_train_annotations(train_df)
print("Loading Donut processor and model...")
processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base")
model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base")
for name, param in model.named_parameters():
if not param.requires_grad:
param.requires_grad = True
model.train()
special_tokens = ["<s>", "</s>"]
processor.tokenizer.add_special_tokens({"additional_special_tokens": special_tokens})
model.decoder.resize_token_embeddings(len(processor.tokenizer))
model.config.decoder_start_token_id = processor.tokenizer.convert_tokens_to_ids("<s>")
model.config.eos_token_id = processor.tokenizer.convert_tokens_to_ids("</s>")
model.config.pad_token_id = processor.tokenizer.pad_token_id
model.gradient_checkpointing_enable()
model.config.use_cache = False
model.config.gradient_checkpointing = True # Enable gradient checkpointing
print("Initializing dataset and dataloader...")
dataset = DonutDataset(train_annotations, processor)
train_dataloader = DataLoader(dataset, batch_size=1, shuffle=True, collate_fn=collate_fn, num_workers=2)
print("Starting training...")
try:
train_model(model, train_dataloader, processor, nn.CrossEntropyLoss(), optim.AdamW(model.parameters(), lr=1e-4), epochs=3, accumulation_steps=4)
except RuntimeError as e:
print(f"RuntimeError: {e}")
torch.cuda.empty_cache()
print("Training interrupted. Please check the GPU memory usage.")
print("Saving trained model and processor...")
model.save_pretrained('trained_model')
processor.save_pretrained('trained_model')
print("Model and processor saved successfully.")
if name == "main":
main()
RuntimeError: CUDA error: out of memory
Compile with TORCH_USE_CUDA_DSA to enable device-side assertions.
The RuntimeError: CUDA error: out of memory indicates that your GPU doesn't have enough memory to handle the computations required by your current model configuration during training. This is a common issue when working with large models or large batch sizes. Let's delve into the possible causes and provide actionable solutions to address this error.
Understanding the Problem
Model Size: The naver-clova-ix/donut-base model is relatively large, which can consume significant GPU memory, especially during training when gradients need to be stored.
Batch Size and Accumulation Steps: Even though you're using a batch_size of 1, you're accumulating gradients over 4 steps (accumulation_steps=4), which effectively increases the memory usage.
Image Processing: The images are resized to (32, 32), but the DonutProcessor might be rescaling them back to a default size internally, negating any memory savings from downsampling.
Sequence Length: The max_length=512 for token sequences can contribute to high memory usage if the actual sequences are much shorter.
DataLoader Workers: Using multiple workers (num_workers=2) can increase memory usage due to duplicated data across subprocesses.
Automatic Mixed Precision (AMP): While you are using torch.cuda.amp.autocast, additional configurations may optimize memory usage further.
Solutions
1. Reduce the Model Size
Explanation: The model you're using might be too large for your GPU's memory capacity. Using a smaller model will inherently reduce memory consumption.
Action:
Use a Smaller Pre-trained Model: If available, switch to a smaller version of the Donut model.
python
processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-small")
model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-small")
Alternative Models: If a smaller Donut model isn't available, consider alternative models that fit your task and have a smaller footprint.
2. Adjust Batch Size and Accumulation Steps
Explanation: Accumulating gradients increases memory usage because the gradients from multiple forward passes are stored before an optimizer step.
Action:
Set accumulation_steps to 1: This means you'll perform an optimizer step after each batch, reducing memory usage.
python
train_model(..., accumulation_steps=1)
Monitor Memory Usage: Use tools like nvidia-smi to monitor GPU memory during training.
3. Optimize Image Processing
Explanation: The processor might be rescaling images to a larger default size, increasing memory usage.
Action:
Customize the Processor's Image Size:
python
processor.feature_extractor.size = [224, 224] # Set to a smaller size
processor.feature_extractor.do_resize = True
processor.feature_extractor.resample = Image.BICUBIC # Or any preferred resampling method
Verify Image Sizes: Ensure that the images processed by the model are indeed the smaller sizes you expect.
4. Reduce Sequence Length
Explanation: Setting max_length=512 might be unnecessary if your sequences are shorter, leading to wasted padding and increased memory usage.
Action:
Adjust max_length: Set max_length to the maximum length needed for your data.
python
dataset = DonutDataset(train_annotations, processor, max_length=128) # Adjust as appropriate
Dynamic Padding: Use dynamic padding based on the longest sequence in the batch.
Note: Since you're currently not using PyTorch Lightning for training, this would require refactoring your training loop.
7. Clean Up GPU Memory
Explanation: Manually clearing cache can sometimes help avoid memory leaks or fragmentation.
Action:
Empty Cache More Frequently:
python
torch.cuda.empty_cache()
Place this at appropriate points in your training loop, such as after each batch or step, but use it judiciously.
Delete Unnecessary Variables: Ensure that any variables you don't need are deleted using del variable_name to free up memory.
8. Check for Memory Leaks
Explanation: Unintentional storage of tensors that require gradients can lead to increased memory usage over time.
Action:
Avoid Storing Computation Graphs: Make sure you're not appending tensors that require gradients to lists or storing them in ways that prevent garbage collection.
Use torch.no_grad() When Appropriate: For validation steps or any computation that doesn't require gradients.
9. Verify GPU Memory Availability
Explanation: Ensure that the GPU has enough memory to handle the model even after optimizations.
Action:
Check GPU Memory:
bash
nvidia-smi
Close Other Processes: Ensure no other processes are using the GPU.
Reduce Other GPU Usage: If on a shared system, try to allocate more memory or use a GPU with more memory.
10. Use CPU for Training (Last Resort)
Explanation: If none of the above solutions work and training on GPU isn't feasible due to memory constraints, you might consider training on CPU.
Here's how you might incorporate some of the above suggestions into your code:
python
def main():
import os
os.environ["PYTORCH_CUDA_ALLOC_CONF"] = "expandable_segments:True"
train_csv = 'shortened_dataset.csv'
print("Loading training data...")
train_df = pd.read_csv(train_csv)
print("Creating training annotations...")
train_annotations = create_train_annotations(train_df)
print("Loading Donut processor and model...")
processor = DonutProcessor.from_pretrained("naver-clova-ix/donut-base")
# Adjust image size in the processor
processor.feature_extractor.size = [224, 224]
processor.feature_extractor.do_resize = True
model = VisionEncoderDecoderModel.from_pretrained("naver-clova-ix/donut-base")
# Enable gradient checkpointing
model.gradient_checkpointing_enable()
model.config.use_cache = False
# Resize token embeddings
special_tokens = ["<s>", "</s>"]
processor.tokenizer.add_special_tokens({"additional_special_tokens": special_tokens})
model.decoder.resize_token_embeddings(len(processor.tokenizer))
# Set decoder parameters
model.config.decoder_start_token_id = processor.tokenizer.convert_tokens_to_ids("<s>")
model.config.eos_token_id = processor.tokenizer.convert_tokens_to_ids("</s>")
model.config.pad_token_id = processor.tokenizer.pad_token_id
print("Initializing dataset and dataloader...")
dataset = DonutDataset(train_annotations, processor, max_length=128) # Reduced max_length
train_dataloader = DataLoader(dataset, batch_size=1, shuffle=True, collate_fn=collate_fn, num_workers=0)
print("Starting training...")
try:
train_model(
model,
train_dataloader,
processor,
nn.CrossEntropyLoss(),
optim.AdamW(model.parameters(), lr=1e-4),
epochs=3,
accumulation_steps=1 # Reduced accumulation steps
)
except RuntimeError as e:
print(f"RuntimeError: {e}")
torch.cuda.empty_cache()
print("Training interrupted. Please check the GPU memory usage.")
print("Saving trained model and processor...")
model.save_pretrained('trained_model')
processor.save_pretrained('trained_model')
print("Model and processor saved successfully.")
if __name__ == "__main__":
main()
Additional Tips
Monitor Training: Keep an eye on the GPU memory usage during training to see if changes have the desired effect.
Experiment Incrementally: Make one change at a time to isolate the impact of each modification.
Use Profiling Tools: Tools like PyTorch's profiler can help identify bottlenecks and memory usage hotspots.
python
with torch.profiler.profile(
activities=[torch.profiler.ProfilerActivity.CPU, torch.profiler.ProfilerActivity.CUDA],
record_shapes=True
) as prof:
... # Your training loop
print(prof.key_averages().table(sort_by="cuda_memory_usage", row_limit=10))
Consider Distributed Training: If possible, distribute your training across multiple GPUs.
Conclusion
The CUDA out of memory error is a common challenge when training deep learning models. By adjusting model size, batch size, sequence length, and utilizing memory-saving techniques, you can often overcome this hurdle. Implement the suggested changes, and you should see a reduction in memory usage, allowing your model to train without running into memory issues.
Feel free to reach out if you have further questions or need assistance with implementing these solutions!