Zero-Shot Image Classification
Transformers
Safetensors
English
clip
fashion
multimodal
image-search
text-search
embeddings
contrastive-learning
zero-shot-classification
Run this model with HF Jobs
Run Leacb4/gap-clip on Hugging Face's managed compute, monitor its progress, and retrieve the results when it's done.
Paste one of these prompts into your coding agent:
Fine-tune on my dataset
Use HF Jobs to fine-tune https://huggingface.co/Leacb4/gap-clip. Ask me which dataset to train on, then push the fine-tuned model to a new model repo. Run `hf jobs --help` first to learn the CLI.
Run batch inference
Use HF Jobs to run batch inference with https://huggingface.co/Leacb4/gap-clip on the inputs in a mounted HF Bucket. Ask me which Bucket to use, then write the outputs back to it and keep each input ID. Run `hf jobs --help` first to learn the CLI.
Instructions to use Leacb4/gap-clip with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use Leacb4/gap-clip with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("zero-shot-image-classification", model="Leacb4/gap-clip") pipe( "https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/hub/parrots.png", candidate_labels=["animals", "humans", "landscape"], )# pip install -U transformers accelerate # Load model directly from transformers import AutoProcessor, AutoModelForZeroShotImageClassification processor = AutoProcessor.from_pretrained("Leacb4/gap-clip") model = AutoModelForZeroShotImageClassification.from_pretrained("Leacb4/gap-clip", device_map="auto") - Notebooks
- Google Colab
- Kaggle
Upload main_model.py with huggingface_hub
Browse files32 unmodified lines33343536373839404142434445464748495051525354555657585960616263646566676869707172737475767789 unmodified lines1671681691701711721731741751761771788 unmodified lines18718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926021 unmodified lines28228328428528628716 unmodified lines30430530630730830912 unmodified lines32232332432532632732832933033133212 unmodified lines3453463473483493503513523532 unmodified lines3563573583593603612 unmodified lines3643653663673683697 unmodified lines3773783793803813828 unmodified lines39139239339439539639739831 unmodified lines430431432433434435436437438439440441442126 unmodified lines56957057157257357457514 unmodified lines5905915925935945955965975985996006016026036046056066076086096106116126136146153 unmodified lines6196206216226236242 unmodified lines6276286296306316326336346356366376386396406416426436446456466476486496506516526536546555 unmodified lines66166266366466566616 unmodified lines68368468568668768868969069169269369469569669769869970070170270319 unmodified lines72372472572672772872973073173273373473573652 unmodified lines7897907917927937947957967977987998008018028038048058068078088098108119 unmodified lines82182282382482582682782882983083183283383483583683783883932 unmodified lines# Loss Functions# -------------------------------def triple_contrastive_loss(text_features, image_features, attribute_features, temperature=0.07):"""Calculate triple contrastive loss for text, image, and attribute features.This loss combines text-image similarity with attribute-based similarities(color and hierarchy) to learn aligned embeddings.Args:text_features: Text embeddings from main model [batch_size, embed_dim]image_features: Image embeddings from main model [batch_size, embed_dim]attribute_features: Concatenated color + hierarchy embeddings [batch_size, color_dim + hierarchy_dim]temperature: Temperature scaling parameter for contrastive loss (default: 0.07)Returns:Contrastive loss value"""text_features = F.normalize(text_features, dim=-1)image_features = F.normalize(image_features, dim=-1)attribute_features = F.normalize(attribute_features, dim=-1)text_image_logits = (text_features[:, config.color_emb_dim+config.hierarchy_emb_dim:] @ image_features[:, config.color_emb_dim+config.hierarchy_emb_dim:].T) / temperaturetext_attr_logits = (text_features[:, :config.color_emb_dim+config.hierarchy_emb_dim] @ attribute_features.T) / temperatureimage_attr_logits = (attribute_features @ image_features[:,:config.color_emb_dim+config.hierarchy_emb_dim].T) / temperature# Weight distributionweight_text_image = 0.7weight_attr_based = 0.15logits = (weight_text_image * text_image_logits +weight_attr_based * text_attr_logits +weight_attr_based * image_attr_logits)labels = torch.arange(len(text_features)).to(text_features.device)loss = (F.cross_entropy(logits, labels) + F.cross_entropy(logits.T, labels)) / 2return lossdef enhanced_contrastive_loss(text_features, image_features, attribute_features,color_model, hierarchy_model, colors, hierarchies, temperature=0.07, alignment_weight=0.3):"""Enhanced contrastive loss with direct alignment between color/hierarchy models and main model.89 unmodified lines# Combined alignment lossalignment_loss = (color_alignment_loss + hierarchy_alignment_loss) / 2# Combine lossestotal_loss = (1 - alignment_weight) * original_loss + alignment_weight * alignment_lossreturn total_loss, {'original_loss': original_loss.item(),'alignment_loss': alignment_loss.item(),'color_text_alignment': color_text_alignment_loss.item(),'color_image_alignment': color_image_alignment_loss.item(),'color_text_cosine': color_text_cosine_loss.item(),8 unmodified lines# Training Functions# -------------------------------def train_one_epoch(model, train_loader, optimizer, feature_models, device, clip_processor, temperature=0.07):"""Train the model for one epoch using triple contrastive loss.Args:model: Main CLIP model to traintrain_loader: DataLoader for training dataoptimizer: Optimizer instancefeature_models: Dictionary containing color and hierarchy modelsdevice: Device to train onclip_processor: CLIP processor for text preprocessingtemperature: Temperature scaling parameter for contrastive loss (default: 0.07)Returns:Average training loss for the epoch"""model.train()total_loss = 0.0num_batches = 0# Create progress bar for trainingpbar = tqdm(train_loader, desc="Training", leave=False)for batch_idx, (images, texts, colors, hierarchy) in enumerate(pbar):# Move data to deviceimages = images.to(device)images = images.expand(-1, 3, -1, -1) # Ensure 3 channels# Process text inputstext_inputs = clip_processor(text=texts, padding=True, return_tensors="pt")text_inputs = {k: v.to(device) for k, v in text_inputs.items()}# Forward passoptimizer.zero_grad()outputs = model(**text_inputs, pixel_values=images)text_features = outputs.text_embedsimage_features = outputs.image_embeds# Get feature embeddings# Use exact color-name embeddings if available (new color model)if hasattr(feature_models[config.color_column], 'get_color_name_embeddings'):color_features = feature_models[config.color_column].get_color_name_embeddings(colors)else:color_features = feature_models[config.color_column].get_text_embeddings(colors)hierarchy_features = feature_models[config.hierarchy_column].get_text_embeddings(hierarchy)concat_features = torch.cat((color_features, hierarchy_features), dim=1)# Calculate lossloss = triple_contrastive_loss(text_features, image_features, concat_features, temperature)# Backward passloss.backward()optimizer.step()total_loss += loss.item()num_batches += 1# Update progress barpbar.set_postfix({'Loss': f'{loss.item():.4f}','Avg Loss': f'{total_loss/num_batches:.4f}'})return total_loss / num_batchesdef train_one_epoch_enhanced(model, train_loader, optimizer, feature_models, color_model, hierarchy_model,device, clip_processor, temperature=0.07, alignment_weight=0.3):"""Enhanced training with direct color and hierarchy alignment loss.21 unmodified linestotal_metrics = {'original_loss': 0.0,'alignment_loss': 0.0,'color_text_alignment': 0.0,'color_image_alignment': 0.0,'color_text_cosine': 0.0,16 unmodified linestext_inputs = clip_processor(text=texts, padding=True, return_tensors="pt")text_inputs = {k: v.to(device) for k, v in text_inputs.items()}# Forward passoptimizer.zero_grad()outputs = model(**text_inputs, pixel_values=images)12 unmodified lines# Calculate enhanced loss with hierarchy alignmentloss, metrics = enhanced_contrastive_loss(text_features, image_features, concat_features,color_model, hierarchy_model, colors, hierarchy, temperature, alignment_weight)# Backward passloss.backward()optimizer.step()total_loss += loss.item()12 unmodified linesavg_metrics = {key: value / num_batches for key, value in total_metrics.items()}return total_loss / num_batches, avg_metricsdef valid_one_epoch(model, val_loader, feature_models, device, clip_processor, temperature=0.07):"""Validate the model for one epoch using triple contrastive loss.Args:model: Main CLIP model to validate2 unmodified linesdevice: Device to validate onclip_processor: CLIP processor for text preprocessingtemperature: Temperature scaling parameter for contrastive loss (default: 0.07)Returns:Average validation loss for the epoch2 unmodified linestotal_loss = 0.0num_batches = 0# Create progress bar for validationpbar = tqdm(val_loader, desc="Validation", leave=False)7 unmodified linestext_inputs = clip_processor(text=texts, padding=True, return_tensors="pt")text_inputs = {k: v.to(device) for k, v in text_inputs.items()}# Forward passoutputs = model(**text_inputs, pixel_values=images)8 unmodified lineshierarchy_features = feature_models[config.hierarchy_column].get_text_embeddings(hierarchy)concat_features = torch.cat((color_features, hierarchy_features), dim=1)# Calculate lossloss = triple_contrastive_loss(text_features, image_features, concat_features, temperature)total_loss += loss.item()num_batches += 131 unmodified linesself.use_local_images = use_local_imagesself.image_size = image_size# Transforms with augmentation for trainingself.transform = transforms.Compose([transforms.Resize((image_size, image_size)),transforms.RandomHorizontalFlip(p=0.5),transforms.RandomRotation(15),transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.15),transforms.RandomAffine(degrees=0, translate=(0.1, 0.1), scale=(0.9, 1.1)),transforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])126 unmodified linesdef train_model(model, train_loader, val_loader, feature_models, device,num_epochs=20, learning_rate=1e-5, temperature=0.07,save_path=config.main_model_path, use_enhanced_loss=False, alignment_weight=0.3, color_alignment_model=None):"""Custom training loop using train_one_epoch and valid_one_epoch functions.14 unmodified lineslearning_rate: Learning rate for optimizer (default: 1e-5)temperature: Temperature scaling parameter for contrastive loss (default: 0.07)save_path: Path to save model checkpoints (default: main_model_path)use_enhanced_loss: Whether to use enhanced contrastive loss with alignment (default: False)alignment_weight: Weight for alignment loss component if using enhanced loss (default: 0.3)color_alignment_model: Optional color model for alignment (default: None, uses feature_models)Returns:Tuple of (training_losses, validation_losses) lists"""model = model.to(device)optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate)scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', patience=3, factor=0.5)train_losses = []val_losses = []best_val_loss = float('inf')patience_counter = 0patience = 5print(f"Starting training for {num_epochs} epochs...")print(f"Learning rate: {learning_rate}")print(f"Temperature: {temperature}")print(f"Device: {device}")print(f"Training samples: {len(train_loader.dataset)}")print(f"Validation samples: {len(val_loader.dataset)}")3 unmodified lines# Create processor once for efficiencyprocessor = CLIPProcessor.from_pretrained('laion/CLIP-ViT-B-32-laion2B-s34B-b79K')# Create progress bar for epochsepoch_pbar = tqdm(range(num_epochs), desc="Training Progress", position=0)2 unmodified linesepoch_pbar.set_description(f"Epoch {epoch+1}/{num_epochs}")# Trainingif use_enhanced_loss:if color_alignment_model is None:color_alignment_model = feature_models[config.color_column]hierarchy_model = feature_models[config.hierarchy_column]train_loss, align_metrics = train_one_epoch_enhanced(model, train_loader, optimizer, feature_models, color_alignment_model, hierarchy_model, device, processor, temperature, alignment_weight)else:train_loss = train_one_epoch(model, train_loader, optimizer, feature_models, device, processor, temperature)align_metrics = Nonetrain_losses.append(train_loss)# Validationval_loss = valid_one_epoch(model, val_loader, feature_models, device, processor, temperature)val_losses.append(val_loss)# Learning rate schedulingscheduler.step(val_loss)# Update epoch progress bar with metricspostfix = {'Train Loss': f'{train_loss:.4f}','Val Loss': f'{val_loss:.4f}','LR': f'{optimizer.param_groups[0]["lr"]:.2e}','Best Val': f'{best_val_loss:.4f}'}5 unmodified lines})epoch_pbar.set_postfix(postfix)# Save best modelif val_loss < best_val_loss:best_val_loss = val_loss16 unmodified linesprint(f"\n๐ Early stopping triggered after {patience_counter} epochs without improvement")break# Plot training curvesplt.figure(figsize=(12, 4))plt.subplot(1, 2, 1)plt.plot(train_losses, label='Train Loss', color='blue')plt.plot(val_losses, label='Val Loss', color='red')plt.title('Training and Validation Loss')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()plt.grid(True, alpha=0.3)plt.subplot(1, 2, 2)plt.plot(train_losses, label='Train Loss', color='blue')plt.title('Training Loss')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()19 unmodified linesprint("๐ Training of the model with alignement color and hierarchy")print("="*80)# Configurationnum_epochs = 20learning_rate = 1e-5temperature = 0.07alignment_weight = 0.5batch_size = 32subset_size = 10000use_enhanced_loss = True# Load the dataprint(f"\n๐ Loading the data...")52 unmodified linesclip_model = CLIPModel_transformers.from_pretrained('laion/CLIP-ViT-B-32-laion2B-s34B-b79K')# Load the modelif os.path.exists(config.main_model_path):print(f" Model found {config.main_model_path}")print(f" Loading checkpoint...")checkpoint = torch.load(config.main_model_path, map_location=config.device)if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:clip_model.load_state_dict(checkpoint['model_state_dict'])print(f" โ Checkpoint loaded from {checkpoint.get('epoch', '?')}")else:clip_model.load_state_dict(checkpoint)print(f" โ Checkpoint loaded")else:print(f" New model, no checkpoint found")# Move the model on the deviceclip_model = clip_model.to(config.device)# Training with enhanced lossprint(f"\n๐ฏ Beginning training...")9 unmodified lineslearning_rate=learning_rate,temperature=temperature,save_path=config.main_model_path,use_enhanced_loss=use_enhanced_loss,alignment_weight=alignment_weight,color_alignment_model=feature_models[config.color_column])print("\n" + "="*80)print("โ Traning finished!")print(f" Modรจle sauvegardรฉ: {config.main_model_path}")print(f" Training curves: training_curves.png")print("\n๐ Final results:")print(f" Last train loss: {train_losses[-1]:.4f}")print(f" Last validation loss: {val_losses[-1]:.4f}")print(f" Best loss validation: {min(val_losses):.4f}")print("="*80)if __name__ == "__main__":32 unmodified lines33343536373839404189 unmodified lines1311321331341351361371381391401411421431441451461471481491501511521538 unmodified lines16216316416516616716816917017121 unmodified lines19319419519619719819916 unmodified lines21621721821922022122222322422522622712 unmodified lines24024124224324424524624724824925025125225325425512 unmodified lines2682692702712722732742752762772 unmodified lines2802812822832842852862 unmodified lines2892902912922932942952962972987 unmodified lines3063073083093103113123133143153168 unmodified lines32532632732832933033133233333433533633731 unmodified lines369370371372373374375376377378379380381382126 unmodified lines50951051151251351451551651714 unmodified lines5325335345355365375385395405415425435445455465475485495505515525535545555565575585595603 unmodified lines5645655665675685695705715725735745755762 unmodified lines5795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126135 unmodified lines61962062162262362462562662762816 unmodified lines64564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168219 unmodified lines70270370470570670770870971071171271371471552 unmodified lines7687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977989 unmodified lines80880981081181281381481581681781881982082182282382482582682782882983083183283332 unmodified lines# Loss Functions# -------------------------------def enhanced_contrastive_loss(text_features, image_features, attribute_features,color_model, hierarchy_model, colors, hierarchies, temperature=0.07, alignment_weight=0.3,reference_text_features=None, reference_weight=0.1):"""Enhanced contrastive loss with direct alignment between color/hierarchy models and main model.89 unmodified lines# Combined alignment lossalignment_loss = (color_alignment_loss + hierarchy_alignment_loss) / 2# Optional guidance to keep text space close to base CLIP (helps cross-domain generalization)reference_loss = 0.0if reference_text_features is not None:reference_loss = F.mse_loss(F.normalize(text_features, dim=-1),F.normalize(reference_text_features, dim=-1))# Combine lossestotal_loss = (1 - alignment_weight) * original_loss + alignment_weight * alignment_lossif reference_text_features is not None:total_loss = total_loss + reference_weight * reference_lossreturn total_loss, {'original_loss': original_loss.item(),'alignment_loss': alignment_loss.item(),'reference_loss': reference_loss if isinstance(reference_loss, float) else reference_loss.item(),'color_text_alignment': color_text_alignment_loss.item(),'color_image_alignment': color_image_alignment_loss.item(),'color_text_cosine': color_text_cosine_loss.item(),8 unmodified lines# Training Functions# -------------------------------def train_one_epoch(model, train_loader, optimizer, feature_models, color_model, hierarchy_model,device, clip_processor, temperature=0.07, alignment_weight=0.3,reference_model=None, reference_weight=0.1):"""Enhanced training with direct color and hierarchy alignment loss.21 unmodified linestotal_metrics = {'original_loss': 0.0,'alignment_loss': 0.0,'reference_loss': 0.0,'color_text_alignment': 0.0,'color_image_alignment': 0.0,'color_text_cosine': 0.0,16 unmodified linestext_inputs = clip_processor(text=texts, padding=True, return_tensors="pt")text_inputs = {k: v.to(device) for k, v in text_inputs.items()}# Optional reference text features to keep close to base CLIPreference_text_features = Noneif reference_model is not None:with torch.no_grad():reference_text_features = reference_model.get_text_features(**text_inputs)# Forward passoptimizer.zero_grad()outputs = model(**text_inputs, pixel_values=images)12 unmodified lines# Calculate enhanced loss with hierarchy alignmentloss, metrics = enhanced_contrastive_loss(text_features, image_features, concat_features,color_model, hierarchy_model, colors, hierarchy, temperature, alignment_weight,reference_text_features=reference_text_features, reference_weight=reference_weight)# Backward passloss.backward()# Gradient clipping to prevent exploding gradientstorch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)optimizer.step()total_loss += loss.item()12 unmodified linesavg_metrics = {key: value / num_batches for key, value in total_metrics.items()}return total_loss / num_batches, avg_metricsdef valid_one_epoch(model, val_loader, feature_models, device, clip_processor, temperature=0.07, alignment_weight=0.3,reference_model=None, reference_weight=0.1):"""Validate the model for one epoch using enhanced contrastive loss.Args:model: Main CLIP model to validate2 unmodified linesdevice: Device to validate onclip_processor: CLIP processor for text preprocessingtemperature: Temperature scaling parameter for contrastive loss (default: 0.07)alignment_weight: Weight for the alignment loss component (default: 0.3)Returns:Average validation loss for the epoch2 unmodified linestotal_loss = 0.0num_batches = 0# Extract color and hierarchy modelscolor_model = feature_models[config.color_column]hierarchy_model = feature_models[config.hierarchy_column]# Create progress bar for validationpbar = tqdm(val_loader, desc="Validation", leave=False)7 unmodified linestext_inputs = clip_processor(text=texts, padding=True, return_tensors="pt")text_inputs = {k: v.to(device) for k, v in text_inputs.items()}# Optional reference text featuresreference_text_features = Noneif reference_model is not None:reference_text_features = reference_model.get_text_features(**text_inputs)# Forward passoutputs = model(**text_inputs, pixel_values=images)8 unmodified lineshierarchy_features = feature_models[config.hierarchy_column].get_text_embeddings(hierarchy)concat_features = torch.cat((color_features, hierarchy_features), dim=1)# Calculate loss with all required argumentsloss, metrics = enhanced_contrastive_loss(text_features, image_features, concat_features,color_model, hierarchy_model, colors, hierarchy,temperature, alignment_weight,reference_text_features=reference_text_features, reference_weight=reference_weight)total_loss += loss.item()num_batches += 131 unmodified linesself.use_local_images = use_local_imagesself.image_size = image_size# Transforms with augmentation for training (increased augmentation to reduce overfitting)self.transform = transforms.Compose([transforms.Resize((image_size, image_size)),transforms.RandomHorizontalFlip(p=0.5),transforms.RandomRotation(15), # Increased for more variationtransforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.3, hue=0.15), # Increased intensitytransforms.RandomAffine(degrees=0, translate=(0.1, 0.1), scale=(0.9, 1.1)), # Increased transform rangetransforms.RandomApply([transforms.GaussianBlur(kernel_size=3, sigma=(0.1, 2.0))], p=0.2), # Add blurtransforms.ToTensor(),transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])])126 unmodified linesdef train_model(model, train_loader, val_loader, feature_models, device,num_epochs=20, learning_rate=1e-5, temperature=0.07,save_path=config.main_model_path, alignment_weight=0.3,color_alignment_model=None, weight_decay=3e-4,reference_model=None, reference_weight=0.1):"""Custom training loop using train_one_epoch and valid_one_epoch functions.14 unmodified lineslearning_rate: Learning rate for optimizer (default: 1e-5)temperature: Temperature scaling parameter for contrastive loss (default: 0.07)save_path: Path to save model checkpoints (default: main_model_path)alignment_weight: Weight for alignment loss component if using enhanced loss (default: 0.3)color_alignment_model: Optional color model for alignment (default: None, uses feature_models)weight_decay: L2 regularization weight (default: 3e-4, increased to reduce overfitting)Returns:Tuple of (training_losses, validation_losses) lists"""model = model.to(device)# Use AdamW with weight decay for better regularization (reduces overfitting)optimizer = torch.optim.AdamW(model.parameters(), lr=learning_rate, weight_decay=weight_decay)scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', patience=3, factor=0.5)train_losses = []val_losses = []best_val_loss = float('inf')patience_counter = 0patience = 7 # Increased from 5 to 7 for better convergenceprint(f"Starting training for {num_epochs} epochs...")print(f"Learning rate: {learning_rate}")print(f"Temperature: {temperature}")print(f"Weight decay: {weight_decay}")print(f"Alignment weight: {alignment_weight}")print(f"Device: {device}")print(f"Training samples: {len(train_loader.dataset)}")print(f"Validation samples: {len(val_loader.dataset)}")3 unmodified lines# Create processor once for efficiencyprocessor = CLIPProcessor.from_pretrained('laion/CLIP-ViT-B-32-laion2B-s34B-b79K')# Freeze and move reference model (used for text-space regularization)if reference_model is not None:reference_model = reference_model.to(device)reference_model.eval()for param in reference_model.parameters():param.requires_grad = False# Create progress bar for epochsepoch_pbar = tqdm(range(num_epochs), desc="Training Progress", position=0)2 unmodified linesepoch_pbar.set_description(f"Epoch {epoch+1}/{num_epochs}")# Trainingif color_alignment_model is None:color_alignment_model = feature_models[config.color_column]hierarchy_model = feature_models[config.hierarchy_column]train_loss, align_metrics = train_one_epoch_enhanced(model, train_loader, optimizer, feature_models, color_alignment_model, hierarchy_model,device, processor, temperature, alignment_weight,reference_model=reference_model, reference_weight=reference_weight)train_losses.append(train_loss)# Validationval_loss = valid_one_epoch(model, val_loader, feature_models, device, processor,temperature=temperature, alignment_weight=alignment_weight,reference_model=reference_model, reference_weight=reference_weight)val_losses.append(val_loss)# Learning rate schedulingscheduler.step(val_loss)# Calculate overfitting gapoverfitting_gap = val_loss - train_loss# Update epoch progress bar with metricspostfix = {'Train Loss': f'{train_loss:.4f}','Val Loss': f'{val_loss:.4f}','Gap': f'{overfitting_gap:.4f}','LR': f'{optimizer.param_groups[0]["lr"]:.2e}','Best Val': f'{best_val_loss:.4f}'}5 unmodified lines})epoch_pbar.set_postfix(postfix)# Warning if overfitting is detectedif overfitting_gap > 0.15 and epoch > 3:print(f"\nโ ๏ธ Warning: Significant overfitting detected at epoch {epoch+1} (gap={overfitting_gap:.4f})")# Save best modelif val_loss < best_val_loss:best_val_loss = val_loss16 unmodified linesprint(f"\n๐ Early stopping triggered after {patience_counter} epochs without improvement")break# Plot training curves with overfitting analysisplt.figure(figsize=(15, 5))# Plot 1: Training and Validation Lossplt.subplot(1, 3, 1)plt.plot(train_losses, label='Train Loss', color='blue', linewidth=2)plt.plot(val_losses, label='Val Loss', color='red', linewidth=2)plt.title('Training and Validation Loss', fontsize=12, fontweight='bold')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()plt.grid(True, alpha=0.3)# Plot 2: Overfitting Gap (Val Loss - Train Loss)plt.subplot(1, 3, 2)gap = [val_losses[i] - train_losses[i] for i in range(len(train_losses))]plt.plot(gap, label='Overfitting Gap', color='purple', linewidth=2)plt.axhline(y=0, color='black', linestyle='--', alpha=0.3)plt.axhline(y=0.1, color='red', linestyle='--', alpha=0.3, label='Warning threshold')plt.title('Overfitting Gap (Val - Train)', fontsize=12, fontweight='bold')plt.xlabel('Epoch')plt.ylabel('Gap')plt.legend()plt.grid(True, alpha=0.3)# Plot 3: Loss comparisonplt.subplot(1, 3, 3)epochs = list(range(len(train_losses)))plt.plot(epochs, train_losses, 'o-', label='Train Loss', color='blue', linewidth=2)plt.plot(epochs, val_losses, 's-', label='Val Loss', color='red', linewidth=2)plt.fill_between(epochs, train_losses, val_losses, alpha=0.2, color='red')plt.title('Loss Comparison', fontsize=12, fontweight='bold')plt.xlabel('Epoch')plt.ylabel('Loss')plt.legend()19 unmodified linesprint("๐ Training of the model with alignement color and hierarchy")print("="*80)# Configuration (optimized to reduce overfitting)num_epochs = 20learning_rate = 1.5e-5 # Reduced slightly to prevent overfittingtemperature = 0.09 # Increased from 0.07 for softer contrastive learningalignment_weight = 0.2 # Reduced from 0.3 to prevent overfitting on alignmentweight_decay = 5e-4 # Increased weight decay for stronger regularizationbatch_size = 32subset_size = 20000 # Increased dataset size for better generalization# Load the dataprint(f"\n๐ Loading the data...")52 unmodified linesclip_model = CLIPModel_transformers.from_pretrained('laion/CLIP-ViT-B-32-laion2B-s34B-b79K')# Frozen reference CLIP to regularize text space (improves cross-domain generalization)reference_clip = CLIPModel_transformers.from_pretrained('laion/CLIP-ViT-B-32-laion2B-s34B-b79K')# # Load the model# if os.path.exists(config.main_model_path):# print(f" Model found {config.main_model_path}")# print(f" Loading checkpoint...")# checkpoint = torch.load(config.main_model_path, map_location=config.device)# if isinstance(checkpoint, dict) and 'model_state_dict' in checkpoint:# clip_model.load_state_dict(checkpoint['model_state_dict'])# print(f" โ Checkpoint loaded from {checkpoint.get('epoch', '?')}")# else:# clip_model.load_state_dict(checkpoint)# print(f" โ Checkpoint loaded")# else:# print(f" New model, no checkpoint found")# Move the model on the deviceclip_model = clip_model.to(config.device)reference_clip = reference_clip.to(config.device)reference_clip.eval()for param in reference_clip.parameters():param.requires_grad = False# Training with enhanced lossprint(f"\n๐ฏ Beginning training...")9 unmodified lineslearning_rate=learning_rate,temperature=temperature,save_path=config.main_model_path,alignment_weight=alignment_weight,color_alignment_model=feature_models[config.color_column],weight_decay=weight_decay,reference_model=reference_clip,reference_weight=0.1)print("\n" + "="*80)print("โ Training finished!")print(f" Model saved: {config.main_model_path}")print(f" Training curves: training_curves.png")print("\n๐ Final results:")print(f" Last train loss: {train_losses[-1]:.4f}")print(f" Last validation loss: {val_losses[-1]:.4f}")print(f" Best validation loss: {min(val_losses):.4f}")print(f" Overfitting gap (val-train): {val_losses[-1] - train_losses[-1]:.4f}")if val_losses[-1] - train_losses[-1] > 0.1:print(" โ ๏ธ Warning: Significant overfitting detected!")elif val_losses[-1] - train_losses[-1] < 0.05:print(" โ Good generalization!")print("="*80)if __name__ == "__main__":
main_model.py+156-162