import os import sys import argparse import time import json from pathlib import Path import torch import torch.nn as nn from torch.utils.data import DataLoader from torchvision.datasets import ImageFolder from tqdm import tqdm from sklearn.metrics import classification_report, confusion_matrix, f1_score, accuracy_score # Ensure project root is in sys.path PROJECT_ROOT = Path(__file__).resolve().parent.parent if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) from FoMo4Wheat.models.vision_transformer import vit_base from FoMo4Wheat.utils.utils import load_pretrained_weights from FoMo4Wheat.data.transforms import make_classification_eval_transform CLASSES = [ "0_tillering", "1_jointing", "2_booting", "3_anthesis", "4_grain_filling", "5_maturity", ] class GrowthStageLinearHead(nn.Module): """ Downstream linear probe head mapping pooled representations (1536-D) to 6 WGSP classes. Matches the official FoMo4Wheat / DINOv2 linear probing protocol: features = concat(cls_token [768-D], mean_pooled_patch_tokens [768-D]) -> 1536-D """ def __init__(self, in_features: int = 1536, num_classes: int = 6): super().__init__() self.in_features = in_features self.num_classes = num_classes self.linear = nn.Linear(in_features, num_classes) # Official initialization: normal(0, 0.01) and zero bias nn.init.normal_(self.linear.weight, mean=0.0, std=0.01) nn.init.zeros_(self.linear.bias) def forward(self, x: torch.Tensor) -> torch.Tensor: return self.linear(x) def load_frozen_backbone(weight_path: Path, device: torch.device) -> nn.Module: print(f"\n[1/5] Loading frozen FoMo4Wheat ViT-B/14 backbone from: {weight_path}") if not weight_path.exists(): raise FileNotFoundError(f"Weight file not found at: {weight_path}") model = vit_base( patch_size=14, img_size=518, init_values=1.0, ffn_layer="swiglu", block_chunks=4, num_register_tokens=4, ) raw_obj = torch.load(str(weight_path), map_location="cpu", weights_only=False) sd = raw_obj.state_dict() if isinstance(raw_obj, torch.nn.Module) else raw_obj if isinstance(sd, dict) and "teacher" in sd: sd = sd["teacher"] clean_sd = {k.replace("module.", "").replace("backbone.", ""): v for k, v in sd.items()} msg = model.load_state_dict(clean_sd, strict=True) print(f" ✓ Pretrained weights successfully loaded with strict=True: {msg}") # Strictly freeze all parameters for param in model.parameters(): param.requires_grad = False model = model.to(device).half() model.eval() print(" ✓ Backbone loaded and completely frozen (requires_grad=False, fp16).") return model def extract_features_split( model: nn.Module, dataset: ImageFolder, batch_size: int, device: torch.device, split_name: str, ) -> tuple[torch.Tensor, torch.Tensor]: loader = DataLoader( dataset, batch_size=batch_size, shuffle=False, num_workers=2, pin_memory=False, ) all_features = [] all_labels = [] print(f" • Extracting features for {split_name} ({len(dataset):,} images, batch_size={batch_size})...") with torch.no_grad(): for images, labels in tqdm(loader, desc=f"Extracting {split_name:10s}"): images = images.to(device).half() # Forward pass through frozen backbone feats_dict = model.forward_features(images) cls_tok = feats_dict["x_norm_clstoken"] # [B, 768] patch_toks = feats_dict["x_norm_patchtokens"] # [B, 1369, 768] mean_patch = torch.mean(patch_toks, dim=1) # [B, 768] # Concatenate CLS token and mean patch tokens -> 1536-D pooled = torch.cat([cls_tok, mean_patch], dim=-1).float().cpu() # Keep on CPU in fp32 all_features.append(pooled) all_labels.append(labels) features_tensor = torch.cat(all_features, dim=0) labels_tensor = torch.cat(all_labels, dim=0) print(f" -> Extracted shape: {features_tensor.shape}, labels: {labels_tensor.shape}") return features_tensor, labels_tensor def get_cached_or_extracted_features( model: nn.Module, data_dir: Path, cache_dir: Path, batch_size: int, device: torch.device, force_recompute: bool = False, ): cache_dir.mkdir(parents=True, exist_ok=True) transform = make_classification_eval_transform(resize_size=518, crop_size=518) feature_data = {} for split in ["train", "validation", "test"]: cache_file = cache_dir / f"wgsp_{split}_features_1536d.pt" if cache_file.exists() and not force_recompute: print(f" ✓ Found cached features for {split}: {cache_file}") data = torch.load(cache_file, weights_only=True) feature_data[split] = (data["features"], data["labels"]) else: split_dir = data_dir / split if not split_dir.exists(): raise FileNotFoundError(f"Missing split directory: {split_dir}") dataset = ImageFolder(str(split_dir), transform=transform) feats, labels = extract_features_split(model, dataset, batch_size, device, split) torch.save({"features": feats, "labels": labels, "classes": dataset.classes}, cache_file) print(f" ✓ Saved cached features to: {cache_file}") feature_data[split] = (feats, labels) return feature_data def train_linear_head( train_feats: torch.Tensor, train_labels: torch.Tensor, val_feats: torch.Tensor, val_labels: torch.Tensor, epochs: int = 50, lr: float = 1e-3, weight_decay: float = 1e-4, device: torch.device = torch.device("cuda"), ): print(f"\n[3/5] Training Linear Classifier Head ({epochs} epochs, lr={lr}, weight_decay={weight_decay})...") head = GrowthStageLinearHead(in_features=1536, num_classes=6).to(device) optimizer = torch.optim.AdamW(head.parameters(), lr=lr, weight_decay=weight_decay) scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=epochs) criterion = nn.CrossEntropyLoss() train_dataset = torch.utils.data.TensorDataset(train_feats, train_labels) train_loader = DataLoader(train_dataset, batch_size=128, shuffle=True) val_feats = val_feats.to(device) val_labels = val_labels.to(device) best_val_macro_f1 = 0.0 best_head_state = None best_epoch = 0 for epoch in range(1, epochs + 1): head.train() total_loss = 0.0 for x, y in train_loader: x, y = x.to(device), y.to(device) optimizer.zero_grad() logits = head(x) loss = criterion(logits, y) loss.backward() optimizer.step() total_loss += loss.item() * x.size(0) scheduler.step() epoch_loss = total_loss / len(train_dataset) # Validation evaluation head.eval() with torch.no_grad(): val_logits = head(val_feats) val_preds = torch.argmax(val_logits, dim=-1) val_loss = criterion(val_logits, val_labels).item() val_acc = (val_preds == val_labels).float().mean().item() val_macro_f1 = f1_score(val_labels.cpu().numpy(), val_preds.cpu().numpy(), average="macro") if val_macro_f1 > best_val_macro_f1: best_val_macro_f1 = val_macro_f1 best_head_state = head.state_dict().copy() best_epoch = epoch if epoch % 5 == 0 or epoch == 1 or epoch == epochs: print(f" Epoch {epoch:2d}/{epochs:2d} | Train Loss: {epoch_loss:.4f} | Val Loss: {val_loss:.4f} | " f"Val Acc: {val_acc*100:.2f}% | Val Macro F1: {val_macro_f1:.4f} {'*' if epoch == best_epoch else ''}") print(f"\n ✓ Training finished. Best model at Epoch {best_epoch} (Val Macro F1: {best_val_macro_f1:.4f})") head.load_state_dict(best_head_state) return head, best_epoch, best_val_macro_f1 def evaluate_head_on_test( head: nn.Module, test_feats: torch.Tensor, test_labels: torch.Tensor, device: torch.device, ): print(f"\n[4/5] Evaluating Best Linear Head on Held-Out Test Set ({len(test_feats):,} samples)...") head.eval() with torch.no_grad(): test_logits = head(test_feats.to(device)) test_preds = torch.argmax(test_logits, dim=-1).cpu().numpy() test_labels_np = test_labels.numpy() acc = accuracy_score(test_labels_np, test_preds) macro_f1 = f1_score(test_labels_np, test_preds, average="macro") weighted_f1 = f1_score(test_labels_np, test_preds, average="weighted") print("\n" + "=" * 65) print(f"BENCHMARK TEST RESULTS:") print(f" • Top-1 Accuracy : {acc * 100:.2f}%") print(f" • Macro F1-Score : {macro_f1:.4f}") print(f" • Weighted F1 : {weighted_f1:.4f}") print("=" * 65) print("\nPer-Class Classification Report:") report = classification_report(test_labels_np, test_preds, target_names=CLASSES, digits=4) print(report) print("Confusion Matrix:") cm = confusion_matrix(test_labels_np, test_preds) col_title = "True \\ Pred" header = f"{col_title:18s}" + "".join([f"{c[:10]:>11s}" for c in CLASSES]) print(header) print("-" * len(header)) for idx, row in enumerate(cm): row_str = "".join([f"{val:11d}" for val in row]) print(f"{CLASSES[idx]:18s}{row_str}") print("=" * 65) return { "accuracy": float(acc), "macro_f1": float(macro_f1), "weighted_f1": float(weighted_f1), "confusion_matrix": cm.tolist(), "report": report, } def main(): parser = argparse.ArgumentParser(description="Train FoMo4Wheat Downstream Linear Classifier for WGSP") parser.add_argument("--data-dir", type=str, default="data", help="Root data directory") parser.add_argument("--weight-path", type=str, default="weight/FoMo4Wheat_base.pth", help="Pretrained backbone") parser.add_argument("--save-head", type=str, default="weight/nextgenyeild_wgsp_head_v1.pth", help="Output path for head") parser.add_argument("--cache-dir", type=str, default="data/cache", help="Directory for cached representations") parser.add_argument("--batch-size", type=int, default=32, help="Extraction batch size") parser.add_argument("--epochs", type=int, default=50, help="Linear head training epochs") parser.add_argument("--lr", type=float, default=1e-3, help="Learning rate") parser.add_argument("--weight-decay", type=float, default=1e-4, help="Weight decay") parser.add_argument("--force-recompute", action="store_true", help="Force recomputing cached features") args = parser.parse_args() device = torch.device("cuda" if torch.cuda.is_available() else "cpu") print("=" * 65) print("NextGenYeild: Downstream Linear Probe Pipeline (Phase 5)") print(f"Device: {device} ({torch.cuda.get_device_name(0) if torch.cuda.is_available() else 'CPU'})") print("=" * 65) data_dir = PROJECT_ROOT / args.data_dir weight_path = PROJECT_ROOT / args.weight_path save_head = PROJECT_ROOT / args.save_head cache_dir = PROJECT_ROOT / args.cache_dir # Check if features are already cached cache_complete = all((cache_dir / f"wgsp_{s}_features_1536d.pt").exists() for s in ["train", "validation", "test"]) if not cache_complete or args.force_recompute: model = load_frozen_backbone(weight_path, device) else: print("\n[1/5] All feature caches exist! Skipping backbone loading...") model = None print(f"\n[2/5] Preparing feature representations...") feature_data = get_cached_or_extracted_features( model=model, data_dir=data_dir, cache_dir=cache_dir, batch_size=args.batch_size, device=device, force_recompute=args.force_recompute, ) train_feats, train_labels = feature_data["train"] val_feats, val_labels = feature_data["validation"] test_feats, test_labels = feature_data["test"] # Train linear head best_head, best_epoch, best_val_f1 = train_linear_head( train_feats=train_feats, train_labels=train_labels, val_feats=val_feats, val_labels=val_labels, epochs=args.epochs, lr=args.lr, weight_decay=args.weight_decay, device=device, ) # Evaluate on held-out test set test_metrics = evaluate_head_on_test(best_head, test_feats, test_labels, device) # Save trained checkpoint print(f"\n[5/5] Saving linear probe head weights to: {save_head}") save_head.parent.mkdir(parents=True, exist_ok=True) checkpoint = { "model_name": "nextgenyeild_wgsp_head_v1", "model_version": "fomo4wheat-wgsp-v1", "architecture": "LinearClassifier", "in_features": 1536, "num_classes": 6, "classes": CLASSES, "class_to_idx": {c: i for i, c in enumerate(CLASSES)}, "pooling": "concat(cls_token, mean_patch_token)", "input_img_size": 518, "state_dict": best_head.state_dict(), "best_epoch": best_epoch, "best_val_macro_f1": best_val_f1, "test_metrics": test_metrics, "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"), } torch.save(checkpoint, save_head) print(f" ✓ Checkpoint saved successfully ({save_head.stat().st_size / 1024:.2f} KB).") print("=" * 65) if __name__ == "__main__": main()