diff --git a/training.py b/training.py index f176e51..a8ffa99 100644 --- a/training.py +++ b/training.py @@ -1,6 +1,3 @@ -# =============================== -# IMPORTS -# =============================== import os import json import math @@ -20,7 +17,26 @@ from tqdm import tqdm from collections import Counter # =============================== -# DATA LOADING +# 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 +else: + print("✗ CUDA not available, using CPU") + device = torch.device('cpu') + +print("=" * 60) + + +# =============================== +# DATA LOADING WITH NaN HANDLING # =============================== def load_kaggle_asl_data(base_path): train_df = pd.read_csv(os.path.join(base_path, "train.csv")) @@ -30,39 +46,70 @@ def load_kaggle_asl_data(base_path): def extract_hand_landmarks_from_parquet(path): + """Extract hand landmarks, handling NaN values properly""" try: df = pd.read_parquet(path) + + # Get hand data left = df[df["type"] == "left_hand"] right = df[df["type"] == "right_hand"] - hand = left if len(left) >= len(right) else right + # Choose hand with more non-NaN data + left_valid = left[['x', 'y', 'z']].notna().all(axis=1).sum() + right_valid = right[['x', 'y', 'z']].notna().all(axis=1).sum() + + if left_valid == 0 and right_valid == 0: + return None # No valid hand data + + hand = left if left_valid >= right_valid else right + if len(hand) == 0: return None + # Get frames with valid data frames = sorted(hand['frame'].unique()) landmarks_seq = [] for frame in frames: lm_frame = hand[hand['frame'] == frame] + + # Check if this frame has valid data + valid_rows = lm_frame[['x', 'y', 'z']].notna().all(axis=1) + if valid_rows.sum() < 10: # Need at least 10 valid landmarks + continue + lm_list = [] + frame_has_data = False + for i in range(21): lm = lm_frame[lm_frame['landmark_index'] == i] if len(lm) == 0: lm_list.append([0.0, 0.0, 0.0]) else: - lm_list.append([ - float(lm['x'].iloc[0]), - float(lm['y'].iloc[0]), - float(lm['z'].iloc[0]) - ]) - landmarks_seq.append(lm_list) + x = lm['x'].iloc[0] + y = lm['y'].iloc[0] + z = lm['z'].iloc[0] + + # Check for NaN + if pd.isna(x) or pd.isna(y) or pd.isna(z): + lm_list.append([0.0, 0.0, 0.0]) + else: + lm_list.append([float(x), float(y), float(z)]) + frame_has_data = True + + if frame_has_data: + landmarks_seq.append(lm_list) + + if len(landmarks_seq) == 0: + return None return np.array(landmarks_seq, dtype=np.float32) - except: + 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 @@ -74,23 +121,27 @@ def get_features_sequence(landmarks_seq, max_frames=100): scale = np.maximum(scale, 1e-6) landmarks_seq = landmarks_seq / scale[:, np.newaxis, :] + # Replace any remaining NaN/Inf with 0 + landmarks_seq = np.nan_to_num(landmarks_seq, nan=0.0, posinf=0.0, neginf=0.0) + # Finger curl distances tips = [4, 8, 12, 16, 20] bases = [1, 5, 9, 13, 17] curl_features = [] for b, t in zip(bases, tips): - curl_features.append(np.linalg.norm(landmarks_seq[:, t] - landmarks_seq[:, b], axis=1)) - curl_features = np.stack(curl_features, axis=1) # (T,5) + curl = np.linalg.norm(landmarks_seq[:, t] - landmarks_seq[:, b], axis=1) + curl_features.append(curl) + curl_features = np.stack(curl_features, axis=1) # Temporal deltas deltas = np.zeros_like(landmarks_seq) deltas[1:] = landmarks_seq[1:] - landmarks_seq[:-1] - # Flatten features along last axis + # Flatten features seq = np.concatenate([landmarks_seq, deltas, curl_features[:, :, np.newaxis]], axis=2) - seq = seq.reshape(seq.shape[0], -1) # (T, feature_dim) + seq = seq.reshape(seq.shape[0], -1) - # Pad or truncate to max_frames + # Pad or truncate T, F = seq.shape if T < max_frames: pad = np.zeros((max_frames - T, F), dtype=np.float32) @@ -98,7 +149,7 @@ def get_features_sequence(landmarks_seq, max_frames=100): elif T > max_frames: seq = seq[:max_frames, :] - # Mask + # Create mask valid_mask = np.zeros(max_frames, dtype=bool) valid_mask[:min(T, max_frames)] = True @@ -106,20 +157,29 @@ def get_features_sequence(landmarks_seq, max_frames=100): def process_row(row, base_path, max_frames=100): + """Process a single row""" path = os.path.join(base_path, row["path"]) if not os.path.exists(path): return None, None, None + try: lm = extract_hand_landmarks_from_parquet(path) if lm is None: return None, None, None + feat, mask = get_features_sequence(lm, max_frames) if feat is None: return None, None, None + + # Final NaN check + if np.isnan(feat).any() or np.isinf(feat).any(): + return None, None, None + return feat, mask, row["sign"] except: return None, None, None + # =============================== # TRANSFORMER MODEL # =============================== @@ -138,7 +198,7 @@ class PositionalEncoding(nn.Module): class TransformerASL(nn.Module): - def __init__(self, input_dim=63, num_classes=250, d_model=192, nhead=6, num_layers=4): + def __init__(self, input_dim=68, num_classes=250, d_model=256, nhead=8, num_layers=4): super().__init__() self.proj = nn.Linear(input_dim, d_model) self.norm_in = nn.LayerNorm(d_model) @@ -170,37 +230,33 @@ class TransformerASL(nn.Module): return self.head(x) -def create_padding_mask(lengths, max_len): - return torch.arange(max_len, device=lengths.device)[None, :] >= lengths[:, None] - # =============================== # MAIN TRAINING # =============================== def main(): - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - print(f"Using device: {device}") - if device.type == "cuda": - print("GPU:", torch.cuda.get_device_name(0)) - - base_path = "asl_kaggle" # ← set your dataset path + base_path = "asl_kaggle" max_frames = 100 MIN_SAMPLES_PER_CLASS = 6 - print("Loading metadata...") + 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("Processing landmark sequences...") + print("\nProcessing sequences with NaN handling...") with Pool(cpu_count()) as pool: results = list(tqdm( pool.imap( partial(process_row, base_path=base_path, max_frames=max_frames), - rows + 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 feat.shape[0] == max_frames: @@ -208,13 +264,19 @@ def main(): masks_list.append(mask) y_list.append(sign) + print(f"\n✓ Valid sequences: {len(X_list)} out of {len(train_df)}") + if not X_list: - print("No valid sequences found. Check parquet files / paths.") + print("❌ No valid sequences found!") + print("\nPossible issues:") + print(" 1. Most files contain only NaN hand landmarks") + print(" 2. Hand detection failed in most videos") + print(" 3. Dataset might be corrupted") return X = np.stack(X_list) masks = np.stack(masks_list) - print(f"Loaded {len(X)} sequences | shape: {X.shape}") + print(f"Data shape: {X.shape}") # Global normalization X = np.clip(X, -5.0, 5.0) @@ -222,9 +284,11 @@ def main(): 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) @@ -232,9 +296,11 @@ def main(): masks = masks[mask_valid] y = y[mask_valid] + # Re-encode le = LabelEncoder() y = le.fit_transform(y) - print(f"{len(X)} samples | {len(le.classes_)} classes after filtering") + + print(f"Final dataset: {len(X)} samples | {len(le.classes_)} classes") # Train-test split X_train, X_test, masks_train, masks_test, y_train, y_test = train_test_split( @@ -254,23 +320,28 @@ def main(): def __getitem__(self, idx): return self.X[idx], self.masks[idx], self.y[idx] + batch_size = 128 if device.type == 'cuda' else 64 + train_loader = DataLoader( ASLSequenceDataset(X_train, masks_train, y_train), - batch_size=64, shuffle=True, num_workers=4, pin_memory=True + batch_size=batch_size, shuffle=True, num_workers=4, pin_memory=True ) test_loader = DataLoader( ASLSequenceDataset(X_test, masks_test, y_test), - batch_size=96, shuffle=False, num_workers=4, pin_memory=True + batch_size=batch_size * 2, shuffle=False, num_workers=4, pin_memory=True ) + # Model model = TransformerASL( input_dim=X.shape[2], num_classes=len(le.classes_), - d_model=192, - nhead=6, + d_model=256, + nhead=8, num_layers=4 ).to(device) - print(f"Model parameters: {sum(p.numel() for p in model.parameters()):,}") + + total_params = sum(p.numel() for p in model.parameters()) + print(f"\nModel parameters: {total_params:,}") criterion = nn.CrossEntropyLoss(label_smoothing=0.05) optimizer = optim.AdamW(model.parameters(), lr=5e-4, weight_decay=1e-4) @@ -282,22 +353,29 @@ def main(): wait = 0 epochs = 70 + print("\nStarting training...") + print("=" * 60) + for epoch in range(epochs): model.train() total_loss = 0 correct = total = 0 - for x, mask, yb in tqdm(train_loader, desc="Train"): + + for x, mask, yb in tqdm(train_loader, desc=f"Epoch {epoch + 1}/{epochs}"): x, mask, yb = x.to(device), mask.to(device), yb.to(device) - key_mask = ~mask # True where padding + 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=0.8) optimizer.step() + total_loss += loss.item() correct += (logits.argmax(-1) == yb).sum().item() total += yb.size(0) + train_acc = correct / total * 100 # Eval @@ -310,12 +388,14 @@ def main(): 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(f"[{epoch+1:2d}/{epochs}] Loss: {total_loss/len(train_loader):.4f} | " + print(f"[{epoch + 1:2d}/{epochs}] Loss: {total_loss / len(train_loader):.4f} | " f"Train: {train_acc:.2f}% | Test: {test_acc:.2f}%") scheduler.step() + if test_acc > best_acc: best_acc = test_acc wait = 0 @@ -324,16 +404,22 @@ def main(): 'optimizer': optimizer.state_dict(), 'label_encoder_classes': le.classes_, 'acc': best_acc, - 'epoch': epoch + 'epoch': epoch, + 'input_dim': X.shape[2], + 'num_classes': len(le.classes_) }, "best_asl_transformer.pth") - print(" → New best saved") + print(f" → New best: {best_acc:.2f}%") else: wait += 1 if wait >= patience: print("Early stopping") break - print(f"\nBest test accuracy: {best_acc:.2f}%") + print("=" * 60) + print(f"\n✓ Training complete!") + print(f"✓ Best test accuracy: {best_acc:.2f}%") + print(f"✓ Model saved: best_asl_transformer.pth") + if __name__ == "__main__": - main() + main() \ No newline at end of file