import os import json import math import numpy as np import pandas as pd import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.utils.data import Dataset, DataLoader from sklearn.model_selection import train_test_split from sklearn.preprocessing import LabelEncoder from multiprocessing import Pool, cpu_count from functools import partial from tqdm import tqdm from collections import Counter # =============================== # GPU CONFIGURATION # =============================== print("=" * 60) print("GPU CONFIGURATION") print("=" * 60) if torch.cuda.is_available(): print(f"✓ CUDA available!") print(f"✓ GPU: {torch.cuda.get_device_name(0)}") device = torch.device('cuda:0') torch.backends.cudnn.benchmark = True torch.backends.cudnn.enabled = True else: print("✗ CUDA not available, using CPU") device = torch.device('cpu') print("=" * 60) # =============================== # DATA LOADING - HANDLES PARTIAL NaN # =============================== def load_kaggle_asl_data(base_path): train_df = pd.read_csv(os.path.join(base_path, "train.csv")) with open(os.path.join(base_path, "sign_to_prediction_index_map.json")) as f: sign_to_idx = json.load(f) return train_df, sign_to_idx def extract_hand_landmarks_from_parquet(path): """Extract hand landmarks - ONLY uses frames with valid (non-NaN) data""" try: df = pd.read_parquet(path) # Get hand data left = df[df["type"] == "left_hand"] right = df[df["type"] == "right_hand"] if len(left) == 0 and len(right) == 0: return None # Count valid (non-NaN) rows for each hand left_valid = 0 right_valid = 0 if len(left) > 0: left_valid = left[['x', 'y', 'z']].notna().all(axis=1).sum() if len(right) > 0: right_valid = right[['x', 'y', 'z']].notna().all(axis=1).sum() # No valid data at all if left_valid == 0 and right_valid == 0: return None # Choose hand with more valid data hand = left if left_valid >= right_valid else right # Get unique frames frames = sorted(hand['frame'].unique()) landmarks_seq = [] for frame in frames: lm_frame = hand[hand['frame'] == frame] # Count how many valid landmarks this frame has valid_count = lm_frame[['x', 'y', 'z']].notna().all(axis=1).sum() # Skip frames with too few valid landmarks if valid_count < 10: continue # Extract landmarks for this frame frame_landmarks = [] valid_landmarks_in_frame = 0 for i in range(21): lm = lm_frame[lm_frame['landmark_index'] == i] if len(lm) == 0: frame_landmarks.append([0.0, 0.0, 0.0]) else: x = float(lm['x'].iloc[0]) y = float(lm['y'].iloc[0]) z = float(lm['z'].iloc[0]) # Check if valid if pd.notna(x) and pd.notna(y) and pd.notna(z): frame_landmarks.append([x, y, z]) valid_landmarks_in_frame += 1 else: frame_landmarks.append([0.0, 0.0, 0.0]) # Only add frame if it has enough valid landmarks if valid_landmarks_in_frame >= 10: landmarks_seq.append(frame_landmarks) # Need at least 3 valid frames if len(landmarks_seq) < 3: return None return np.array(landmarks_seq, dtype=np.float32) except Exception as e: return None def get_features_sequence(landmarks_seq, max_frames=100): """Extract features from landmark sequence""" if landmarks_seq is None or len(landmarks_seq) == 0: return None, None # Center on wrist (landmark 0) wrist = landmarks_seq[:, 0:1, :].copy() landmarks_seq = landmarks_seq - wrist # Scale normalization using wrist to middle finger MCP (landmark 9) scale = np.linalg.norm(landmarks_seq[:, 9, :] - np.zeros(3), axis=1, keepdims=True) scale = np.maximum(scale, 1e-6) # Avoid division by zero landmarks_seq = landmarks_seq / scale[:, np.newaxis, :] # Clean up any remaining NaN/Inf landmarks_seq = np.nan_to_num(landmarks_seq, nan=0.0, posinf=0.0, neginf=0.0) # Clip extreme values landmarks_seq = np.clip(landmarks_seq, -10, 10) # Calculate finger curl features tips = [4, 8, 12, 16, 20] # Thumb, index, middle, ring, pinky tips bases = [1, 5, 9, 13, 17] # Corresponding base joints curl_features = [] for b, t in zip(bases, tips): curl = np.linalg.norm(landmarks_seq[:, t] - landmarks_seq[:, b], axis=1) curl_features.append(curl) curl_features = np.stack(curl_features, axis=1) # (T, 5) # Temporal deltas (motion) deltas = np.zeros_like(landmarks_seq) if len(landmarks_seq) > 1: deltas[1:] = landmarks_seq[1:] - landmarks_seq[:-1] # Flatten each component separately, then concatenate landmarks_flat = landmarks_seq.reshape(landmarks_seq.shape[0], -1) # (T, 63) deltas_flat = deltas.reshape(deltas.shape[0], -1) # (T, 63) # curl_features is already (T, 5) # Combine: 63 + 63 + 5 = 131 features per frame seq = np.concatenate([ landmarks_flat, deltas_flat, curl_features ], axis=1) # Pad or truncate to max_frames T, F = seq.shape if T < max_frames: # Pad with zeros pad = np.zeros((max_frames - T, F), dtype=np.float32) seq = np.concatenate([seq, pad], axis=0) elif T > max_frames: # Truncate seq = seq[:max_frames, :] # Create attention mask (True for valid positions) valid_mask = np.zeros(max_frames, dtype=bool) valid_mask[:min(T, max_frames)] = True return seq.astype(np.float32), valid_mask def process_row(row, base_path, max_frames=100): """Process a single row - worker function for multiprocessing""" path = os.path.join(base_path, row["path"]) if not os.path.exists(path): return None, None, None try: # Extract landmarks lm = extract_hand_landmarks_from_parquet(path) if lm is None: return None, None, None # Get features feat, mask = get_features_sequence(lm, max_frames) if feat is None: return None, None, None # Final safety check if np.isnan(feat).any() or np.isinf(feat).any(): return None, None, None return feat, mask, row["sign"] except Exception as e: return None, None, None # =============================== # TRANSFORMER MODEL # =============================== class PositionalEncoding(nn.Module): def __init__(self, d_model, max_len=128): super().__init__() pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) self.register_buffer('pe', pe.unsqueeze(0)) def forward(self, x): return x + self.pe[:, :x.size(1)] class TransformerASL(nn.Module): def __init__(self, input_dim, num_classes, d_model=256, nhead=8, num_layers=4): super().__init__() # Input projection self.proj = nn.Linear(input_dim, d_model) self.norm_in = nn.LayerNorm(d_model) self.pos = PositionalEncoding(d_model, max_len=128) # Transformer encoder enc_layer = nn.TransformerEncoderLayer( d_model=d_model, nhead=nhead, dim_feedforward=d_model * 4, dropout=0.15, activation='gelu', batch_first=True, norm_first=True ) self.encoder = nn.TransformerEncoder(enc_layer, num_layers=num_layers) # Classification head self.head = nn.Sequential( nn.LayerNorm(d_model), nn.Dropout(0.25), nn.Linear(d_model, num_classes) ) def forward(self, x, key_padding_mask=None): # x: (batch, seq_len, input_dim) # key_padding_mask: (batch, seq_len) - True for padding positions x = self.proj(x) x = self.norm_in(x) x = self.pos(x) x = self.encoder(x, src_key_padding_mask=key_padding_mask) # Global average pooling over valid positions x = x.mean(dim=1) return self.head(x) # =============================== # MAIN TRAINING # =============================== def main(): base_path = "asl_kaggle" max_frames = 100 MIN_SAMPLES_PER_CLASS = 5 print("\nLoading metadata...") train_df, sign_to_idx = load_kaggle_asl_data(base_path) print(f"Total sequences: {len(train_df)}") rows = [row for _, row in train_df.iterrows()] print("\nProcessing sequences (this will take a few minutes)...") print("Expected: ~36,000 valid sequences based on diagnostic") # Process with multiprocessing with Pool(cpu_count()) as pool: results = list(tqdm( pool.imap( partial(process_row, base_path=base_path, max_frames=max_frames), rows, chunksize=100 ), total=len(rows), desc="Extracting landmarks" )) # Filter valid results X_list, masks_list, y_list = [], [], [] for feat, mask, sign in results: if feat is not None and mask is not None and sign is not None: if feat.shape[0] == max_frames: X_list.append(feat) masks_list.append(mask) y_list.append(sign) print(f"\n✓ Successfully extracted: {len(X_list)} valid sequences") print(f" Success rate: {len(X_list) / len(train_df) * 100:.1f}%") if len(X_list) < 100: print("❌ Too few valid sequences found!") print(" This shouldn't happen - please share this output for debugging") return # Stack into arrays X = np.stack(X_list) masks = np.stack(masks_list) print(f"\nData shape: {X.shape}") print(f"Feature dimension: {X.shape[2]}") # Global normalization print("Normalizing features...") X = np.clip(X, -10.0, 10.0) mean = X.mean(axis=(0, 1), keepdims=True) std = X.std(axis=(0, 1), keepdims=True) + 1e-8 X = (X - mean) / std # Encode labels le = LabelEncoder() y = le.fit_transform(y_list) # Filter classes with too few samples counts = Counter(y) valid_classes = [cls for cls, cnt in counts.items() if cnt >= MIN_SAMPLES_PER_CLASS] mask_valid = np.isin(y, valid_classes) X = X[mask_valid] masks = masks[mask_valid] y = y[mask_valid] # Re-encode after filtering le = LabelEncoder() y = le.fit_transform(y) print(f"\nFinal dataset after filtering:") print(f" Samples: {len(X):,}") print(f" Classes: {len(le.classes_)}") print(f" Sign examples: {list(le.classes_[:10])}") # Train-test split X_train, X_test, masks_train, masks_test, y_train, y_test = train_test_split( X, masks, y, test_size=0.15, stratify=y, random_state=42 ) print(f"\nTrain set: {len(X_train):,} samples") print(f"Test set: {len(X_test):,} samples") # Dataset wrapper class ASLSequenceDataset(Dataset): def __init__(self, X, masks, y): self.X = torch.from_numpy(X).float() self.masks = torch.from_numpy(masks) self.y = torch.from_numpy(y).long() def __len__(self): return len(self.X) def __getitem__(self, idx): return self.X[idx], self.masks[idx], self.y[idx] # DataLoaders batch_size = 128 if device.type == 'cuda' else 64 train_loader = DataLoader( ASLSequenceDataset(X_train, masks_train, y_train), batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True if device.type == 'cuda' else False ) test_loader = DataLoader( ASLSequenceDataset(X_test, masks_test, y_test), batch_size=batch_size * 2, shuffle=False, num_workers=4, pin_memory=True if device.type == 'cuda' else False ) # Initialize model print("\nInitializing model...") model = TransformerASL( input_dim=X.shape[2], num_classes=len(le.classes_), d_model=256, nhead=8, num_layers=4 ).to(device) total_params = sum(p.numel() for p in model.parameters()) print(f"Model parameters: {total_params:,}") # Training setup criterion = nn.CrossEntropyLoss(label_smoothing=0.05) optimizer = optim.AdamW(model.parameters(), lr=5e-4, weight_decay=1e-4) scheduler = optim.lr_scheduler.CosineAnnealingWarmRestarts(optimizer, T_0=10, T_mult=2) # Training loop best_acc = 0.0 patience = 15 wait = 0 epochs = 60 print("\n" + "=" * 60) print("STARTING TRAINING") print("=" * 60) for epoch in range(epochs): # Train model.train() total_loss = 0 correct = total = 0 for x, mask, yb in tqdm(train_loader, desc=f"Epoch {epoch + 1}/{epochs}", leave=False): x, mask, yb = x.to(device), mask.to(device), yb.to(device) # Invert mask: True for padding positions key_mask = ~mask optimizer.zero_grad(set_to_none=True) logits = model(x, key_padding_mask=key_mask) loss = criterion(logits, yb) loss.backward() torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0) optimizer.step() total_loss += loss.item() correct += (logits.argmax(-1) == yb).sum().item() total += yb.size(0) train_acc = correct / total * 100 # Evaluate model.eval() correct = total = 0 with torch.no_grad(): for x, mask, yb in test_loader: x, mask, yb = x.to(device), mask.to(device), yb.to(device) key_mask = ~mask logits = model(x, key_padding_mask=key_mask) correct += (logits.argmax(-1) == yb).sum().item() total += yb.size(0) test_acc = correct / total * 100 # Print progress print(f"[{epoch + 1:2d}/{epochs}] Loss: {total_loss / len(train_loader):.4f} | " f"Train: {train_acc:.2f}% | Test: {test_acc:.2f}%", end="") scheduler.step() # Save best model if test_acc > best_acc: best_acc = test_acc wait = 0 torch.save({ 'model': model.state_dict(), 'optimizer': optimizer.state_dict(), 'label_encoder_classes': le.classes_, 'acc': best_acc, 'epoch': epoch, 'input_dim': X.shape[2], 'num_classes': len(le.classes_), 'd_model': 256, 'nhead': 8, 'num_layers': 4 }, "best_asl_transformer.pth") print(f" → New best: {best_acc:.2f}% ✓") else: wait += 1 print() if wait >= patience: print(f"\nEarly stopping triggered at epoch {epoch + 1}") break print("\n" + "=" * 60) print(f"✓ Training complete!") print(f"✓ Best test accuracy: {best_acc:.2f}%") print(f"✓ Model saved: best_asl_transformer.pth") print("=" * 60) if __name__ == "__main__": main()