import os import polars as pl import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from torch.utils.data import Dataset, DataLoader from tqdm import tqdm from sklearn.model_selection import train_test_split from concurrent.futures import ProcessPoolExecutor # --- CONFIG --- BASE_PATH = "asl_kaggle" CACHE_DIR = "asl_cache" TARGET_FRAMES = 22 device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # --- PREPROCESSING (RUN ONCE) --- def process_single_file(args): """Process a single file - designed for multiprocessing""" i, path, base_path, cache_dir = args cache_path = os.path.join(cache_dir, f"sample_{i}.npy") if os.path.exists(cache_path): return # Skip if already cached try: parquet_path = os.path.join(base_path, path) df = pl.read_parquet(parquet_path) # Global Anchor (Nose) anchors = ( df.filter((pl.col("type") == "face") & (pl.col("landmark_index") == 0)) .select([ pl.col("frame"), pl.col("x").alias("nx"), pl.col("y").alias("ny"), pl.col("z").alias("nz") ]) ) # Local Anchors (Wrists) wrists = ( df.filter(pl.col("landmark_index").is_in([468, 522])) .select([ pl.col("frame"), pl.col("landmark_index"), pl.col("x").alias("wx"), pl.col("y").alias("wy") ]) ) processed = df.join(anchors, on="frame", how="left") processed = ( processed.join(wrists, on=["frame", "landmark_index"], how="left") .with_columns([ (pl.col("x") - pl.col("nx")).alias("x_g"), (pl.col("y") - pl.col("ny")).alias("y_g"), (pl.col("z") - pl.col("nz")).alias("z_g"), (pl.col("x") - pl.col("wx")).fill_null(pl.col("x") - pl.col("nx")).alias("x_l"), (pl.col("y") - pl.col("wy")).fill_null(pl.col("y") - pl.col("ny")).alias("y_l"), ]) .sort(["frame", "type", "landmark_index"]) ) n_frames = processed["frame"].n_unique() tensor = processed.select(["x_g", "y_g", "z_g", "x_l", "y_l"]).to_numpy().reshape(n_frames, 543, 5) # Temporal Resampling indices = np.linspace(0, n_frames - 1, num=TARGET_FRAMES).round().astype(int) result = tensor[indices] # Save to cache np.save(cache_path, result) except Exception: # Save zero tensor for failed files np.save(cache_path, np.zeros((TARGET_FRAMES, 543, 5))) def preprocess_and_cache(paths, base_path=BASE_PATH, cache_dir=CACHE_DIR): """Preprocess all files in parallel and save as numpy arrays""" os.makedirs(cache_dir, exist_ok=True) # Check if already cached all_cached = all(os.path.exists(os.path.join(cache_dir, f"sample_{i}.npy")) for i in range(len(paths))) if all_cached: print("All files already cached, skipping preprocessing...") return print(f"Preprocessing {len(paths)} files in parallel...") # Create arguments for each file args_list = [(i, path, base_path, cache_dir) for i, path in enumerate(paths)] # Process in parallel with ProcessPoolExecutor() as executor: list(tqdm(executor.map(process_single_file, args_list), total=len(args_list))) print("Preprocessing complete!") # --- FAST DATASET (LOADS FROM CACHE) --- class CachedASLDataset(Dataset): """Fast dataset that loads from preprocessed numpy files""" def __init__(self, indices, labels, cache_dir=CACHE_DIR): self.indices = indices self.labels = labels self.cache_dir = cache_dir def __len__(self): return len(self.indices) def __getitem__(self, idx): sample_idx = self.indices[idx] cache_path = os.path.join(self.cache_dir, f"sample_{sample_idx}.npy") # Fast numpy load data = np.load(cache_path) label = self.labels[idx] return torch.tensor(data, dtype=torch.float32), torch.tensor(label, dtype=torch.long) # --- MODEL --- class ASLClassifier(nn.Module): def __init__(self, num_classes): super().__init__() self.feat_dim = 543 * 5 self.conv1 = nn.Conv1d(self.feat_dim, 512, kernel_size=3, padding=1) self.bn1 = nn.BatchNorm1d(512) self.conv2 = nn.Conv1d(512, 512, kernel_size=3, padding=1) self.bn2 = nn.BatchNorm1d(512) self.pool = nn.MaxPool1d(2) self.dropout = nn.Dropout(0.4) self.fc = nn.Sequential( nn.Linear(512, 1024), nn.ReLU(), nn.Dropout(0.2), nn.Linear(1024, num_classes) ) def forward(self, x): b, t, l, f = x.shape x = x.view(b, t, -1).transpose(1, 2) x = F.relu(self.bn1(self.conv1(x))) x = self.pool(x) x = F.relu(self.bn2(self.conv2(x))) x = self.pool(x) x = F.adaptive_avg_pool1d(x, 1).squeeze(-1) return self.fc(self.dropout(x)) # --- EXECUTION --- if __name__ == "__main__": # 1. Setup Metadata metadata = pl.read_csv(os.path.join(BASE_PATH, "train.csv")) unique_signs = sorted(metadata["sign"].unique().to_list()) sign_to_idx = {sign: i for i, sign in enumerate(unique_signs)} paths = metadata["path"].to_list() labels = [sign_to_idx[s] for s in metadata["sign"].to_list()] # 2. Preprocess and cache (parallelized, only runs if cache doesn't exist) preprocess_and_cache(paths) # 3. Create index mapping for train/val split all_indices = list(range(len(paths))) train_indices, val_indices, train_labels, val_labels = train_test_split( all_indices, labels, test_size=0.1, stratify=labels, random_state=42 ) # 4. Create datasets from cached files train_dataset = CachedASLDataset(train_indices, train_labels) val_dataset = CachedASLDataset(val_indices, val_labels) # Increase batch size and workers since loading is now fast train_loader = DataLoader(train_dataset, batch_size=64, shuffle=True, num_workers=4, pin_memory=True) val_loader = DataLoader(val_dataset, batch_size=64, num_workers=4, pin_memory=True) print(f"Train samples: {len(train_dataset)}, Val samples: {len(val_dataset)}") # 5. Train model = ASLClassifier(len(unique_signs)).to(device) optimizer = torch.optim.Adam(model.parameters(), lr=0.001) scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(optimizer, patience=3, factor=0.5) criterion = nn.CrossEntropyLoss(label_smoothing=0.1) best_acc = 0.0 print(f"Starting training on {device}...") for epoch in range(25): # Training model.train() train_loss = 0 train_correct = 0 train_total = 0 pbar = tqdm(train_loader, desc=f"Epoch {epoch + 1}/25 [Train]") for batch_x, batch_y in pbar: batch_x, batch_y = batch_x.to(device), batch_y.to(device) optimizer.zero_grad() output = model(batch_x) loss = criterion(output, batch_y) loss.backward() optimizer.step() train_loss += loss.item() _, predicted = torch.max(output, 1) train_total += batch_y.size(0) train_correct += (predicted == batch_y).sum().item() pbar.set_postfix({'loss': f'{loss.item():.4f}', 'acc': f'{100 * train_correct / train_total:.1f}%'}) # Validation model.eval() val_correct, val_total = 0, 0 val_loss = 0 with torch.no_grad(): for vx, vy in tqdm(val_loader, desc=f"Epoch {epoch + 1}/25 [Val]"): vx, vy = vx.to(device), vy.to(device) output = model(vx) val_loss += criterion(output, vy).item() pred = output.argmax(1) val_correct += (pred == vy).sum().item() val_total += vy.size(0) avg_train_loss = train_loss / len(train_loader) avg_val_loss = val_loss / len(val_loader) train_acc = 100 * train_correct / train_total val_acc = 100 * val_correct / val_total scheduler.step(avg_val_loss) print(f"\nEpoch {epoch + 1}/25:") print(f" Train Loss: {avg_train_loss:.4f} | Train Acc: {train_acc:.2f}%") print(f" Val Loss: {avg_val_loss:.4f} | Val Acc: {val_acc:.2f}%") # Save best model if val_acc > best_acc: best_acc = val_acc torch.save(model.state_dict(), "best_asl_model.pth") print(f" ✓ Best model saved! (Val Acc: {val_acc:.2f}%)\n") # Checkpoint every 5 epochs if (epoch + 1) % 5 == 0: torch.save(model.state_dict(), f"asl_model_e{epoch + 1}.pth") print(f"\nTraining complete! Best validation accuracy: {best_acc:.2f}%")