Spaces:
No application file
No application file
Upload TrainingSketchOnMsCoco_20000Group.py
Browse filesThis code allows the training of sketch model using 20000 groups of captions.
TrainingSketchOnMsCoco_20000Group.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import random
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 8 |
+
from sentence_transformers import SentenceTransformer
|
| 9 |
+
from datasets import load_dataset
|
| 10 |
+
from google.colab import drive
|
| 11 |
+
|
| 12 |
+
# Fixer la graine pour la reproductibilité
|
| 13 |
+
SEED = 42
|
| 14 |
+
random.seed(SEED)
|
| 15 |
+
np.random.seed(SEED)
|
| 16 |
+
torch.manual_seed(SEED)
|
| 17 |
+
|
| 18 |
+
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 19 |
+
print("Device utilisé :", DEVICE)
|
| 20 |
+
|
| 21 |
+
# Résolution en 400x800 (Hauteur: 400, Largeur: 800) et 1 canal (NG)
|
| 22 |
+
H_SKETCH, W_SKETCH = 400, 800
|
| 23 |
+
C_SKETCH = 1
|
| 24 |
+
print(f"Dimension des sketches configurée à : {H_SKETCH}x{W_SKETCH} avec {C_SKETCH} canal (Niveaux de Gris)")
|
| 25 |
+
|
| 26 |
+
# Création du dossier sample_data
|
| 27 |
+
os.makedirs("sample_data", exist_ok=True)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
# =====================================================================
|
| 31 |
+
# 1. Chargement de MS-COCO (100% pour le Train, pas de test)
|
| 32 |
+
# =====================================================================
|
| 33 |
+
print("Téléchargement de coco_captions_quintets...")
|
| 34 |
+
coco_dataset = load_dataset("embedding-data/coco_captions_quintets", split="train")
|
| 35 |
+
|
| 36 |
+
raw_groups_coco = {}
|
| 37 |
+
for idx, item in enumerate(coco_dataset):
|
| 38 |
+
captions = item["set"]
|
| 39 |
+
if captions and len(captions) >= 3:
|
| 40 |
+
raw_groups_coco[str(idx)] = list(captions)
|
| 41 |
+
|
| 42 |
+
MAX_GROUPS = 20000
|
| 43 |
+
if len(raw_groups_coco) > MAX_GROUPS:
|
| 44 |
+
keep = random.sample(list(raw_groups_coco.keys()), MAX_GROUPS)
|
| 45 |
+
raw_groups_coco = {k: raw_groups_coco[k] for k in keep}
|
| 46 |
+
|
| 47 |
+
# Utilisation de TOUS les groupes pour l'entraînement (pas de test)
|
| 48 |
+
groups_train_coco = raw_groups_coco
|
| 49 |
+
|
| 50 |
+
print(f"Nombre total de groupes pour l'entraînement : {len(groups_train_coco)}")
|
| 51 |
+
|
| 52 |
+
print("Encodage SBERT des captions...")
|
| 53 |
+
sbert = SentenceTransformer("all-MiniLM-L6-v2", device=str(DEVICE))
|
| 54 |
+
all_caps = sorted({c for caps in groups_train_coco.values() for c in caps})
|
| 55 |
+
|
| 56 |
+
with torch.no_grad():
|
| 57 |
+
embs = sbert.encode(all_caps, convert_to_tensor=True, batch_size=64).to(DEVICE)
|
| 58 |
+
caption_to_emb = {c: embs[i] for i, c in enumerate(all_caps)}
|
| 59 |
+
group_names_coco = [n for n, c in groups_train_coco.items() if len(c) >= 2]
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
# =====================================================================
|
| 63 |
+
# 2. Architecture du Modèle avec Espace Latent à 384 dimensions
|
| 64 |
+
# =====================================================================
|
| 65 |
+
class SemanticEncoder(nn.Module):
|
| 66 |
+
def __init__(self, input_dim=384, latent_dim=384):
|
| 67 |
+
super().__init__()
|
| 68 |
+
self.net = nn.Sequential(
|
| 69 |
+
nn.Linear(input_dim, 384), nn.ReLU(), nn.Dropout(0.1),
|
| 70 |
+
nn.Linear(384, latent_dim), nn.LayerNorm(latent_dim),
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
def forward(self, x):
|
| 74 |
+
return self.net(x)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
class GraySketchDecoder(nn.Module):
|
| 78 |
+
def __init__(self, latent_dim=384):
|
| 79 |
+
super().__init__()
|
| 80 |
+
self.fc = nn.Linear(latent_dim, 128 * 13 * 25)
|
| 81 |
+
self.deconv = nn.Sequential(
|
| 82 |
+
nn.BatchNorm2d(128), nn.ReLU(),
|
| 83 |
+
nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
|
| 84 |
+
nn.Conv2d(128, 64, kernel_size=3, padding=1), nn.BatchNorm2d(64), nn.ReLU(),
|
| 85 |
+
nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
|
| 86 |
+
nn.Conv2d(64, 32, kernel_size=3, padding=1), nn.BatchNorm2d(32), nn.ReLU(),
|
| 87 |
+
nn.Upsample(scale_factor=2, mode="bilinear", align_corners=False),
|
| 88 |
+
nn.Conv2d(32, C_SKETCH, kernel_size=3, padding=1),
|
| 89 |
+
nn.Upsample(size=(H_SKETCH, W_SKETCH), mode="bilinear", align_corners=False),
|
| 90 |
+
nn.Sigmoid(),
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
def forward(self, z):
|
| 94 |
+
return self.deconv(self.fc(z).view(-1, 128, 13, 25))
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
class GraySketchEncoder(nn.Module):
|
| 98 |
+
def __init__(self, output_dim=384):
|
| 99 |
+
super().__init__()
|
| 100 |
+
self.conv = nn.Sequential(
|
| 101 |
+
nn.Conv2d(C_SKETCH, 32, 4, 2, 1), nn.ReLU(),
|
| 102 |
+
nn.Conv2d(32, 64, 4, 2, 1), nn.ReLU(),
|
| 103 |
+
nn.Conv2d(64, 128, 4, 2, 1), nn.ReLU(),
|
| 104 |
+
nn.AdaptiveAvgPool2d((4, 8)),
|
| 105 |
+
nn.Flatten(),
|
| 106 |
+
)
|
| 107 |
+
self.fc = nn.Linear(128 * 4 * 8, output_dim)
|
| 108 |
+
|
| 109 |
+
def forward(self, sketch):
|
| 110 |
+
return self.fc(self.conv(sketch))
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class EndToEndGrayPipeline(nn.Module):
|
| 114 |
+
def __init__(self, input_dim=384, latent_dim=384):
|
| 115 |
+
super().__init__()
|
| 116 |
+
self.semantic_encoder = SemanticEncoder(input_dim, latent_dim)
|
| 117 |
+
self.sketch_decoder = GraySketchDecoder(latent_dim)
|
| 118 |
+
self.sketch_encoder = GraySketchEncoder(latent_dim)
|
| 119 |
+
|
| 120 |
+
def forward(self, text_emb):
|
| 121 |
+
z = self.semantic_encoder(text_emb)
|
| 122 |
+
sketch = self.sketch_decoder(z)
|
| 123 |
+
return z, sketch, self.sketch_encoder(sketch)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def info_nce_loss(f1, f2, temp=0.07):
|
| 127 |
+
f1, f2 = F.normalize(f1, dim=1), F.normalize(f2, dim=1)
|
| 128 |
+
sim = torch.matmul(f1, f2.T) / temp
|
| 129 |
+
labels = torch.arange(f1.size(0), device=f1.device)
|
| 130 |
+
return (F.cross_entropy(sim, labels) + F.cross_entropy(sim.T, labels)) / 2.0
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def spatial_variation_loss(sketch, blur_kernel=5):
|
| 134 |
+
blurred = F.avg_pool2d(sketch, kernel_size=blur_kernel, stride=1,
|
| 135 |
+
padding=blur_kernel // 2, count_include_pad=False)
|
| 136 |
+
return -blurred.var(dim=(2, 3)).mean()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
# =====================================================================
|
| 140 |
+
# 3. Entraînement du modèle (Tous les groupes en Train)
|
| 141 |
+
# =====================================================================
|
| 142 |
+
def train_gray_pipeline(caption_to_emb, group_names, groups_train, steps=20000, batch_groups=32,
|
| 143 |
+
variation_weight=0.01, log_every=300):
|
| 144 |
+
model = EndToEndGrayPipeline(input_dim=384, latent_dim=384).to(DEVICE)
|
| 145 |
+
optimizer = torch.optim.AdamW(model.parameters(), lr=1e-3)
|
| 146 |
+
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=steps)
|
| 147 |
+
batch_groups = min(batch_groups, len(group_names))
|
| 148 |
+
|
| 149 |
+
model.train()
|
| 150 |
+
for step in range(1, steps + 1):
|
| 151 |
+
batch = random.sample(group_names, batch_groups)
|
| 152 |
+
anchors, positives = [], []
|
| 153 |
+
for name in batch:
|
| 154 |
+
a_cap, p_cap = random.sample(groups_train[name], 2)
|
| 155 |
+
anchors.append(caption_to_emb[a_cap])
|
| 156 |
+
positives.append(caption_to_emb[p_cap])
|
| 157 |
+
emb_a = torch.stack(anchors, dim=0)
|
| 158 |
+
emb_b = torch.stack(positives, dim=0)
|
| 159 |
+
|
| 160 |
+
optimizer.zero_grad()
|
| 161 |
+
_, sketch_a, feat_a = model(emb_a)
|
| 162 |
+
_, sketch_b, feat_b = model(emb_b)
|
| 163 |
+
loss = info_nce_loss(feat_a, feat_b) + variation_weight * (
|
| 164 |
+
spatial_variation_loss(sketch_a) + spatial_variation_loss(sketch_b))
|
| 165 |
+
loss.backward()
|
| 166 |
+
optimizer.step()
|
| 167 |
+
scheduler.step()
|
| 168 |
+
|
| 169 |
+
if step % log_every == 0 or step == 1:
|
| 170 |
+
print(f"[COCO Gris Train 384-dim] pas {step:5d}/{steps} - loss : {loss.item():.4f}")
|
| 171 |
+
|
| 172 |
+
model.eval()
|
| 173 |
+
return model
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
# =====================================================================
|
| 177 |
+
# 4. Exécution et Sauvegarde sur Google Drive
|
| 178 |
+
# =====================================================================
|
| 179 |
+
drive.mount('/content/drive')
|
| 180 |
+
drive_dir = "/content/drive/My Drive"
|
| 181 |
+
os.makedirs(drive_dir, exist_ok=True)
|
| 182 |
+
|
| 183 |
+
model_path = os.path.join(drive_dir, "model_gray_coco20000captions_384dim.pth")
|
| 184 |
+
|
| 185 |
+
model_gray_coco = EndToEndGrayPipeline(input_dim=384, latent_dim=384).to(DEVICE)
|
| 186 |
+
|
| 187 |
+
if os.path.exists(model_path):
|
| 188 |
+
print(f"Modèle trouvé sur Google Drive. Chargement depuis : {model_path}")
|
| 189 |
+
model_gray_coco.load_state_dict(torch.load(model_path, map_location=DEVICE))
|
| 190 |
+
model_gray_coco.eval()
|
| 191 |
+
print("Modèle chargé avec succès ! (Étape d'apprentissage ignorée)")
|
| 192 |
+
else:
|
| 193 |
+
print("Aucun modèle sauvegardé trouvé. Lancement de l'apprentissage (20k groupes, 384-dim)...")
|
| 194 |
+
# Vous pouvez changer la valeur de 'steps' ici selon vos besoins (ex: 20000)
|
| 195 |
+
model_gray_coco = train_gray_pipeline(
|
| 196 |
+
caption_to_emb, group_names_coco, groups_train_coco, steps=20000
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
torch.save(model_gray_coco.state_dict(), model_path)
|
| 200 |
+
print(f"Apprentissage terminé. Modèle sauvegardé avec succès sur Google Drive : {model_path}")
|