File size: 29,867 Bytes
e981f00
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
#!/usr/bin/env python3
"""
Audio Emotion Classifier Trainer using UniRepLKNet (DINOv3 backbone).
Referenced from:
  - UniRepLKNet: unireplknet_backbone_dinov3.py
  - AST (Audio Spectrogram Transformer): UniRepLKNet/Audio/src/models/ast_models.py
  - Dataset: Suggest_data_label (Speech Emotion Recognition)

Usage:
    # Train directly on Suggest_data_label (or any audio folder formatted by class):
    python train.py --data_dir ./Suggest_data_label

    # Custom options:
    python train.py --data_dir /path/to/dataset --epochs 30 --batch_size 16 --lr 1e-4

    # Run single-file prediction using trained model:
    python train.py --predict path/to/sample.wav --ckpt exp_ser/best_model.pth
"""

import os
import sys
import csv
import json
import time
import random
import argparse
from pathlib import Path
from collections import defaultdict

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
import torchaudio
import soundfile as sf
from tqdm import tqdm

# Ensure workspace root is in sys.path to import unireplknet_backbone_dinov3
ROOT_DIR = Path(__file__).resolve().parent
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from unireplknet_backbone_dinov3 import UniRepLKNet

AUDIO_EXTENSIONS = {'.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac'}


# ==============================================================================
# 1. AUDIO UTILITIES & PREPROCESSING
# ==============================================================================

def load_audio(filepath, target_sr=16000):
    """
    Robust audio loading using soundfile (with fallback to torchaudio).
    Converts multi-channel to mono and resamples to target_sr.
    """
    if not os.path.exists(filepath):
        raise FileNotFoundError(f"Audio file '{filepath}' not found.")
    try:
        data, sr = sf.read(filepath)
        wav = torch.from_numpy(data).float()
        if wav.ndim == 1:
            wav = wav.unsqueeze(0)
        else:
            wav = wav.t()
    except Exception:
        wav, sr = torchaudio.load(filepath)
        if wav.ndim == 1:
            wav = wav.unsqueeze(0)

    # Convert to mono if multi-channel
    if wav.shape[0] > 1:
        wav = torch.mean(wav, dim=0, keepdim=True)

    # Resample if sample rate doesn't match
    if sr != target_sr:
        resampler = torchaudio.transforms.Resample(sr, target_sr)
        wav = resampler(wav)
        sr = target_sr

    return wav, sr


def extract_fbank(waveform, sr=16000, num_mel_bins=128, target_length=512, is_train=False):
    """
    Extract log-mel filterbank (AST / Kaldi style).
    Shape output: (1, num_mel_bins, target_length).
    """
    # Remove DC bias
    waveform = waveform - waveform.mean()

    # Compute Kaldi log-mel filterbank
    # Frame shift 10ms, frame length 25ms, Hanning window
    fbank = torchaudio.compliance.kaldi.fbank(
        waveform,
        htk_compat=True,
        sample_frequency=sr,
        use_energy=False,
        window_type='hanning',
        num_mel_bins=num_mel_bins,
        dither=0.0,
        frame_shift=10
    )  # shape: (time_frames, num_mel_bins)

    n_frames = fbank.shape[0]

    # Pad or cut along the time dimension
    if n_frames < target_length:
        p = target_length - n_frames
        pad = torch.nn.ZeroPad2d((0, 0, 0, p))
        fbank = pad(fbank)
    elif n_frames > target_length:
        if is_train:
            # Random crop during training
            start = random.randint(0, n_frames - target_length)
            fbank = fbank[start:start + target_length, :]
        else:
            # Center crop during validation/testing
            start = (n_frames - target_length) // 2
            fbank = fbank[start:start + target_length, :]

    # AST style per-sample normalization: (x - mean) / (2 * std + eps)
    fbank = (fbank - fbank.mean()) / (2 * (fbank.std() + 1e-6))

    # Transpose to (num_mel_bins, target_length) and add channel dim -> (1, num_mel_bins, target_length)
    spec = fbank.transpose(0, 1).unsqueeze(0)
    return spec


# ==============================================================================
# 2. DATASET DEFINITION & SPLITTING
# ==============================================================================

def scan_dataset(data_dir):
    """
    Discovers classes and audio samples from:
      1) Subdirectories (class-folder format: data_dir/<class_name>/*.wav)
      2) metadata.csv if subdirectories are not found or contain no audio.
    """
    data_path = Path(data_dir).resolve()
    if not data_path.exists():
        raise FileNotFoundError(f"Data directory '{data_dir}' does not exist.")

    # 1. Try class subdirectories
    subdirs = sorted([d for d in data_path.iterdir() if d.is_dir() and not d.name.startswith('.')])
    class_names = []
    samples = []

    for d in subdirs:
        audio_files = [f for f in d.iterdir() if f.is_file() and f.suffix.lower() in AUDIO_EXTENSIONS]
        if audio_files:
            class_names.append(d.name)

    if class_names:
        class_to_idx = {name: i for i, name in enumerate(class_names)}
        for c in class_names:
            c_dir = data_path / c
            for f in c_dir.iterdir():
                if f.is_file() and f.suffix.lower() in AUDIO_EXTENSIONS:
                    samples.append((str(f), class_to_idx[c], c))
        return samples, class_names, class_to_idx

    # 2. Fallback: try metadata.csv inside data_path
    csv_file = data_path / 'metadata.csv'
    if csv_file.exists():
        with open(csv_file, 'r', encoding='utf-8') as f:
            reader = csv.DictReader(f)
            raw_rows = list(reader)

        # Look for emotion/label column
        label_col = next((c for c in ['emotion', 'suggested_emotion', 'label', 'class', 'category'] if c in reader.fieldnames), None)
        path_col = next((c for c in ['saved_dataset_path', 'file_path', 'path', 'filepath', 'audio_path'] if c in reader.fieldnames), None)

        if label_col and path_col:
            unique_labels = sorted(list(set(row[label_col].strip() for row in raw_rows if row[label_col].strip())))
            class_to_idx = {name: i for i, name in enumerate(unique_labels)}
            for row in raw_rows:
                lbl = row[label_col].strip()
                p = row[path_col].strip()
                # Resolve path
                candidate = data_path / p
                if not candidate.exists():
                    candidate = ROOT_DIR / p
                if not candidate.exists() and os.path.exists(p):
                    candidate = Path(p)
                if candidate.exists() and candidate.suffix.lower() in AUDIO_EXTENSIONS:
                    samples.append((str(candidate), class_to_idx[lbl], lbl))
            return samples, unique_labels, class_to_idx

    raise ValueError(f"No audio files found in subdirectories or metadata.csv inside '{data_dir}'.")


def stratified_split(samples, val_ratio=0.2, seed=42):
    """
    Performs stratified train/val split so that minority classes are properly represented.
    """
    rng = random.Random(seed)
    class_to_items = defaultdict(list)
    for s in samples:
        class_to_items[s[1]].append(s)

    train_samples, val_samples = [], []
    for c, items in class_to_items.items():
        rng.shuffle(items)
        if len(items) <= 1:
            train_samples.extend(items)
        else:
            n_val = max(1, int(round(len(items) * val_ratio)))
            val_samples.extend(items[:n_val])
            train_samples.extend(items[n_val:])

    rng.shuffle(train_samples)
    rng.shuffle(val_samples)
    return train_samples, val_samples


class AudioDataset(Dataset):
    """
    PyTorch Dataset for audio spectrogram classification.
    """
    def __init__(self, samples, target_sr=16000, target_length=512, num_mel_bins=128,
                 is_train=False, freqm=24, timem=48, cache_in_memory=False):
        self.samples = samples
        self.target_sr = target_sr
        self.target_length = target_length
        self.num_mel_bins = num_mel_bins
        self.is_train = is_train
        self.freqm = freqm if is_train else 0
        self.timem = timem if is_train else 0
        self.cache_in_memory = cache_in_memory
        self.cache = {}

        if self.freqm > 0:
            self.freq_mask = torchaudio.transforms.FrequencyMasking(self.freqm)
        if self.timem > 0:
            self.time_mask = torchaudio.transforms.TimeMasking(self.timem)

    def __len__(self):
        return len(self.samples)

    def __getitem__(self, idx):
        filepath, label, _ = self.samples[idx]

        if self.cache_in_memory and idx in self.cache:
            spec = self.cache[idx]
        else:
            wav, sr = load_audio(filepath, target_sr=self.target_sr)
            spec = extract_fbank(
                wav,
                sr=sr,
                num_mel_bins=self.num_mel_bins,
                target_length=self.target_length,
                is_train=self.is_train
            )
            if self.cache_in_memory:
                self.cache[idx] = spec

        # SpecAugment during training
        if self.is_train:
            if self.freqm > 0:
                spec = self.freq_mask(spec)
            if self.timem > 0:
                spec = self.time_mask(spec)

        return spec, torch.tensor(label, dtype=torch.long)


# ==============================================================================
# 3. MODEL ARCHITECTURE
# ==============================================================================

class AudioUniRepLKNet(nn.Module):
    """
    UniRepLKNet with DINOv3 backbone adapted for audio classification.
    References:
      - ASTModel (ast_models.py): ViT spectrogram backbone + MLP head.
      - UniRepLKNet (unireplknet_backbone_dinov3.py): in_chans=1 for log-mel spectrograms.
    """
    def __init__(self, num_classes, arch='dinov3_vits16', ckpt=None, drop_path_rate=0.1, head_dropout=0.1):
        super().__init__()
        # Backbone: UniRepLKNet with in_chans=1 for single-channel log-mel spectrogram
        self.unireplknet = UniRepLKNet(
            in_chans=1,
            num_classes=None,  # Returns pooled global embedding (N, embed_dim)
            drop_path_rate=drop_path_rate,
            backbone_arch=arch,
            backbone_ckpt=ckpt
        )
        embed_dim = self.unireplknet.backbone.embed_dim

        # Classification Head: LayerNorm + Dropout + Linear
        self.mlp_head = nn.Sequential(
            nn.LayerNorm(embed_dim, eps=1e-6),
            nn.Dropout(p=head_dropout) if head_dropout > 0 else nn.Identity(),
            nn.Linear(embed_dim, num_classes)
        )

    def forward(self, x):
        """
        x: Spectrogram tensor.
           Supports shape (B, 1, F, T) directly or (B, T, F) (like standard AST).
           F = num_mel_bins (e.g. 128), T = target_length (e.g. 512).
           Both F and T must be multiples of 16 (DINOv3 ViT patch size).
        """
        if x.dim() == 3:  # (B, T, F)
            x = x.unsqueeze(1).transpose(2, 3)  # -> (B, 1, F, T)

        feats = self.unireplknet(x)  # (B, embed_dim)
        logits = self.mlp_head(feats)  # (B, num_classes)
        return logits


# ==============================================================================
# 4. METRICS COMPUTATION (Pure NumPy - No scikit-learn dependency required)
# ==============================================================================

def compute_metrics(y_true, y_pred, num_classes):
    """
    Calculates Accuracy, Macro F1, Precision, Recall, and Confusion Matrix.
    """
    y_true = np.asarray(y_true)
    y_pred = np.asarray(y_pred)
    acc = float((y_true == y_pred).mean()) if len(y_true) > 0 else 0.0

    cm = np.zeros((num_classes, num_classes), dtype=int)
    for t, p in zip(y_true, y_pred):
        cm[t, p] += 1

    f1s, precs, recs = [], [], []
    for c in range(num_classes):
        tp = cm[c, c]
        fp = cm[:, c].sum() - tp
        fn = cm[c, :].sum() - tp
        prec = tp / (tp + fp) if (tp + fp) > 0 else 0.0
        rec = tp / (tp + fn) if (tp + fn) > 0 else 0.0
        f1 = 2 * prec * rec / (prec + rec) if (prec + rec) > 0 else 0.0
        precs.append(prec)
        recs.append(rec)
        f1s.append(f1)

    return {
        'acc': acc,
        'macro_f1': float(np.mean(f1s)),
        'macro_prec': float(np.mean(precs)),
        'macro_rec': float(np.mean(recs)),
        'per_class_f1': [float(x) for x in f1s],
        'cm': cm
    }


# ==============================================================================
# 5. EVALUATION FUNCTION
# ==============================================================================

@torch.no_grad()
def evaluate(model, val_loader, criterion, device, num_classes):
    model.eval()
    total_loss = 0.0
    all_preds, all_targets = [], []

    for inputs, labels in val_loader:
        inputs = inputs.to(device)
        labels = labels.to(device)

        with torch.autocast(device_type='cuda' if device.type == 'cuda' else 'cpu',
                            dtype=torch.float16 if device.type == 'cuda' else torch.bfloat16,
                            enabled=device.type == 'cuda'):
            logits = model(inputs)
            loss = criterion(logits, labels)

        total_loss += loss.item() * len(labels)
        preds = logits.argmax(dim=1).cpu().numpy()
        all_preds.extend(preds)
        all_targets.extend(labels.cpu().numpy())

    avg_loss = total_loss / len(all_targets) if len(all_targets) > 0 else 0.0
    metrics = compute_metrics(all_targets, all_preds, num_classes)
    metrics['loss'] = avg_loss
    return metrics


# ==============================================================================
# 6. INFERENCE / PREDICTION
# ==============================================================================

def predict_single_file(audio_path, ckpt_path, device='cpu', target_sr=16000, target_length=512, num_mel_bins=128):
    """
    Predicts emotion label for a single audio file using a trained checkpoint.
    """
    ckpt = torch.load(ckpt_path, map_location=device, weights_only=False)
    config = ckpt.get('config', {})
    classes = ckpt.get('classes', [])
    arch = config.get('arch', 'dinov3_vits16')

    model = AudioUniRepLKNet(num_classes=len(classes), arch=arch).to(device)
    model.load_state_dict(ckpt['model_state_dict'])
    model.eval()

    wav, sr = load_audio(audio_path, target_sr=target_sr)
    spec = extract_fbank(wav, sr=sr, num_mel_bins=num_mel_bins, target_length=target_length, is_train=False)
    spec = spec.unsqueeze(0).to(device)  # (1, 1, 128, 512)

    with torch.no_grad():
        logits = model(spec)
        probs = F.softmax(logits, dim=1).squeeze(0).cpu().numpy()

    best_idx = int(np.argmax(probs))
    print(f"\nPrediction for: {audio_path}")
    print(f"Predicted emotion: {classes[best_idx]} (confidence: {probs[best_idx] * 100:.2f}%)")
    print("Probabilities:")
    for c, p in zip(classes, probs):
        print(f"  - {c:12s}: {p * 100:6.2f}%")


# ==============================================================================
# 7. MAIN TRAINING PIPELINE
# ==============================================================================

def main():
    parser = argparse.ArgumentParser(
        description="Train UniRepLKNet (DINOv3 backbone) on an audio classification dataset.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )

    # Dataset & directory arguments
    parser.add_argument('data_dir_pos', nargs='?', default=None,
                        help="Positional argument for data directory (optional).")
    parser.add_argument('--data_dir', type=str, default='./Suggest_data_label',
                        help="Path to dataset root folder containing class subdirectories.")
    parser.add_argument('--out_dir', type=str, default='./exp_ser',
                        help="Directory to save experiment checkpoints and logs.")

    # Model architecture arguments
    parser.add_argument('--arch', type=str, default='dinov3_vits16',
                        choices=['dinov3_vits16', 'dinov3_vitb16', 'dinov3_vitl16'],
                        help="DINOv3 ViT backbone architecture.")
    parser.add_argument('--ckpt', '--backbone_ckpt', type=str, default=None,
                        help="Path or URL to pretrained DINOv3 backbone weights (None = random init).")
    parser.add_argument('--resume', type=str, default=None,
                        help="Path to an existing training checkpoint (.pth) to resume from.")
    parser.add_argument('--drop_path', type=float, default=0.1,
                        help="Stochastic depth (drop path) rate for ViT backbone.")
    parser.add_argument('--freeze_backbone', action='store_true',
                        help="Freeze backbone weights and train only the classification head.")

    # Audio preprocessing parameters (must be multiples of 16 for DINOv3)
    parser.add_argument('--target_sr', type=int, default=16000,
                        help="Target audio sample rate in Hz.")
    parser.add_argument('--target_length', type=int, default=512,
                        help="Spectrogram time frames (e.g. 512 = ~5.12s). Must be multiple of 16.")
    parser.add_argument('--num_mel_bins', type=int, default=128,
                        help="Number of mel frequency bins. Must be multiple of 16.")
    parser.add_argument('--freqm', type=int, default=24,
                        help="SpecAugment frequency masking length (0 to disable).")
    parser.add_argument('--timem', type=int, default=48,
                        help="SpecAugment time masking length (0 to disable).")

    # Training hyperparameters
    parser.add_argument('--epochs', type=int, default=25,
                        help="Total number of training epochs.")
    parser.add_argument('--batch_size', type=int, default=16,
                        help="Mini-batch size for training.")
    parser.add_argument('--lr', type=float, default=1e-4,
                        help="Peak learning rate for AdamW.")
    parser.add_argument('--weight_decay', type=float, default=1e-4,
                        help="Weight decay for AdamW.")
    parser.add_argument('--val_ratio', type=float, default=0.2,
                        help="Fraction of data reserved for validation (stratified split).")
    parser.add_argument('--use_class_weights', action='store_true', default=True,
                        help="Weight CrossEntropyLoss by inverse class frequencies to handle imbalanced datasets.")
    parser.add_argument('--cache', action='store_true', default=True,
                        help="Pre-cache spectrograms in memory to accelerate epoch iterations.")
    parser.add_argument('--seed', type=int, default=42,
                        help="Random seed for reproducibility.")
    parser.add_argument('--num_workers', type=int, default=2,
                        help="Number of DataLoader worker processes.")
    parser.add_argument('--device', type=str, default='auto',
                        choices=['auto', 'cuda', 'cpu'],
                        help="Device to use for training.")

    # Prediction option
    parser.add_argument('--predict', type=str, default=None,
                        help="Path to an audio file for inference with a trained checkpoint.")

    args = parser.parse_args()

    # Determine device
    if args.device == 'auto':
        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    else:
        device = torch.device(args.device)

    # Handle predict mode
    if args.predict is not None:
        ckpt_path = args.ckpt or os.path.join(args.out_dir, 'best_model.pth')
        if not os.path.exists(ckpt_path):
            raise FileNotFoundError(f"Checkpoint '{ckpt_path}' not found for prediction.")
        predict_single_file(args.predict, ckpt_path, device=device,
                            target_sr=args.target_sr, target_length=args.target_length,
                            num_mel_bins=args.num_mel_bins)
        return

    # Check target dimensions divisibility by 16 (DINOv3 patch size)
    assert args.num_mel_bins % 16 == 0, f"--num_mel_bins ({args.num_mel_bins}) must be a multiple of 16."
    assert args.target_length % 16 == 0, f"--target_length ({args.target_length}) must be a multiple of 16."

    # Set seeds
    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if device.type == 'cuda':
        torch.cuda.manual_seed_all(args.seed)

    # Determine data directory
    data_dir = args.data_dir_pos if args.data_dir_pos is not None else args.data_dir
    out_dir = Path(args.out_dir)
    out_dir.mkdir(parents=True, exist_ok=True)

    print("=" * 68)
    print("      UniRepLKNet (DINOv3 ViT Backbone) Audio Training")
    print("=" * 68)
    print(f"Device:              {device}")
    print(f"Dataset directory:   {data_dir}")
    print(f"Output directory:    {out_dir}")
    print(f"Backbone:            {args.arch} (pretrained: {args.ckpt is not None})")
    print(f"Spectrogram shape:   (1, {args.num_mel_bins}, {args.target_length}) [10ms frame shift]")
    print(f"Epochs:              {args.epochs} | Batch size: {args.batch_size} | LR: {args.lr}")
    print("=" * 68)

    # 1. Discover dataset
    samples, class_names, class_to_idx = scan_dataset(data_dir)
    num_classes = len(class_names)
    print(f"\n[Data] Found {len(samples)} audio samples across {num_classes} classes:")
    counts = defaultdict(int)
    for s in samples:
        counts[s[2]] += 1
    for c in class_names:
        print(f"  - {c:12s}: {counts[c]:4d} samples ({counts[c] / len(samples) * 100:5.1f}%)")

    # Save class index mapping
    with open(out_dir / 'classes.json', 'w', encoding='utf-8') as f:
        json.dump({'classes': class_names, 'class_to_idx': class_to_idx}, f, indent=2, ensure_ascii=False)

    # 2. Stratified train/val split
    train_samples, val_samples = stratified_split(samples, val_ratio=args.val_ratio, seed=args.seed)
    print(f"\n[Split] Train samples: {len(train_samples)} | Validation samples: {len(val_samples)}")

    # 3. Create datasets and loaders
    train_dataset = AudioDataset(
        train_samples,
        target_sr=args.target_sr,
        target_length=args.target_length,
        num_mel_bins=args.num_mel_bins,
        is_train=True,
        freqm=args.freqm,
        timem=args.timem,
        cache_in_memory=args.cache
    )
    val_dataset = AudioDataset(
        val_samples,
        target_sr=args.target_sr,
        target_length=args.target_length,
        num_mel_bins=args.num_mel_bins,
        is_train=False,
        cache_in_memory=args.cache
    )

    train_loader = DataLoader(
        train_dataset,
        batch_size=args.batch_size,
        shuffle=True,
        num_workers=args.num_workers,
        pin_memory=(device.type == 'cuda'),
        drop_last=False
    )
    val_loader = DataLoader(
        val_dataset,
        batch_size=args.batch_size * 2,
        shuffle=False,
        num_workers=args.num_workers,
        pin_memory=(device.type == 'cuda'),
        drop_last=False
    )

    # 4. Build Model
    model = AudioUniRepLKNet(
        num_classes=num_classes,
        arch=args.arch,
        ckpt=args.ckpt,
        drop_path_rate=args.drop_path
    ).to(device)

    # Optional: freeze backbone
    if args.freeze_backbone:
        for p in model.unireplknet.parameters():
            p.requires_grad = False
        print("[Model] Backbone weights FROZEN. Only training classification head.")

    total_params = sum(p.numel() for p in model.parameters()) / 1e6
    trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad) / 1e6
    print(f"\n[Model] Total params: {total_params:.2f}M | Trainable params: {trainable_params:.2f}M")

    # 5. Loss function with optional class weighting
    if args.use_class_weights:
        tr_counts = np.bincount([s[1] for s in train_samples], minlength=num_classes).astype(np.float32)
        tr_counts = np.maximum(tr_counts, 1.0)
        weights = len(train_samples) / (num_classes * tr_counts)
        class_weights = torch.tensor(weights, dtype=torch.float32).to(device)
        criterion = nn.CrossEntropyLoss(weight=class_weights)
        print(f"[Loss] Using inverse frequency class weighting: {np.round(weights, 2).tolist()}")
    else:
        criterion = nn.CrossEntropyLoss()

    # 6. Optimizer and Scheduler
    optimizer = torch.optim.AdamW(
        [p for p in model.parameters() if p.requires_grad],
        lr=args.lr,
        weight_decay=args.weight_decay
    )
    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, T_max=args.epochs, eta_min=args.lr * 0.01)
    scaler = torch.amp.GradScaler(enabled=(device.type == 'cuda'))

    # Resume from checkpoint if specified
    start_epoch = 0
    best_f1 = -1.0
    if args.resume and os.path.exists(args.resume):
        ckpt = torch.load(args.resume, map_location=device, weights_only=False)
        model.load_state_dict(ckpt['model_state_dict'])
        optimizer.load_state_dict(ckpt['optimizer_state_dict'])
        start_epoch = ckpt.get('epoch', 0)
        best_f1 = ckpt.get('best_f1', -1.0)
        print(f"[Resume] Loaded checkpoint '{args.resume}' from epoch {start_epoch} (best F1: {best_f1:.4f})")

    # Save training config
    with open(out_dir / 'config.json', 'w', encoding='utf-8') as f:
        json.dump(vars(args), f, indent=2)

    # Setup log CSV
    log_csv = out_dir / 'train_log.csv'
    with open(log_csv, 'w', newline='', encoding='utf-8') as f:
        writer = csv.writer(f)
        writer.writerow(['epoch', 'lr', 'train_loss', 'train_acc', 'val_loss', 'val_acc', 'val_f1', 'val_prec', 'val_rec', 'sec'])

    print(f"\n[Training] Starting training for {args.epochs} epochs...\n")

    # 7. Training Loop
    for epoch in range(start_epoch + 1, args.epochs + 1):
        t0 = time.time()
        model.train()
        train_loss = 0.0
        train_correct = 0
        total_train_samples = 0

        pbar = tqdm(train_loader, desc=f"Epoch {epoch:02d}/{args.epochs:02d}", leave=False)
        for inputs, labels in pbar:
            inputs = inputs.to(device)
            labels = labels.to(device)

            optimizer.zero_grad()
            with torch.autocast(device_type='cuda' if device.type == 'cuda' else 'cpu',
                                dtype=torch.float16 if device.type == 'cuda' else torch.bfloat16,
                                enabled=device.type == 'cuda'):
                outputs = model(inputs)
                loss = criterion(outputs, labels)

            scaler.scale(loss).backward()
            scaler.unscale_(optimizer)
            torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
            scaler.step(optimizer)
            scaler.update()

            batch_size = labels.size(0)
            train_loss += loss.item() * batch_size
            preds = outputs.argmax(dim=1)
            train_correct += (preds == labels).sum().item()
            total_train_samples += batch_size

            pbar.set_postfix({
                'loss': f"{train_loss / total_train_samples:.3f}",
                'acc': f"{train_correct / total_train_samples * 100:.1f}%"
            })

        scheduler.step()
        elapsed = time.time() - t0

        train_avg_loss = train_loss / total_train_samples
        train_avg_acc = train_correct / total_train_samples

        # Validation
        val_metrics = evaluate(model, val_loader, criterion, device, num_classes)
        current_lr = optimizer.param_groups[0]['lr']

        # Save to log CSV
        with open(log_csv, 'a', newline='', encoding='utf-8') as f:
            csv.writer(f).writerow([
                epoch, current_lr,
                f"{train_avg_loss:.4f}", f"{train_avg_acc:.4f}",
                f"{val_metrics['loss']:.4f}", f"{val_metrics['acc']:.4f}",
                f"{val_metrics['macro_f1']:.4f}", f"{val_metrics['macro_prec']:.4f}",
                f"{val_metrics['macro_rec']:.4f}", f"{elapsed:.1f}"
            ])

        # Check for best model
        is_best = val_metrics['macro_f1'] > best_f1
        mark = ""
        if is_best:
            best_f1 = val_metrics['macro_f1']
            mark = " ★ (Best Macro F1)"
            torch.save({
                'epoch': epoch,
                'model_state_dict': model.state_dict(),
                'optimizer_state_dict': optimizer.state_dict(),
                'best_f1': best_f1,
                'val_metrics': val_metrics,
                'classes': class_names,
                'config': vars(args)
            }, out_dir / 'best_model.pth')

        # Always save latest
        torch.save({
            'epoch': epoch,
            'model_state_dict': model.state_dict(),
            'optimizer_state_dict': optimizer.state_dict(),
            'val_metrics': val_metrics,
            'classes': class_names,
            'config': vars(args)
        }, out_dir / 'latest_model.pth')

        # Epoch summary
        print(f"Epoch {epoch:02d}/{args.epochs:02d} | "
              f"Tr Loss: {train_avg_loss:.3f} Acc: {train_avg_acc * 100:5.1f}% | "
              f"Val Loss: {val_metrics['loss']:.3f} Acc: {val_metrics['acc'] * 100:5.1f}% "
              f"Macro-F1: {val_metrics['macro_f1'] * 100:5.1f}% | "
              f"{elapsed:4.1f}s{mark}")

    print("\n" + "=" * 68)
    print("                     Training Complete!")
    print(f"Best Validation Macro F1: {best_f1 * 100:.2f}%")
    print(f"Best model saved to:      {out_dir / 'best_model.pth'}")
    print(f"Latest model saved to:    {out_dir / 'latest_model.pth'}")
    print(f"Training logs:            {out_dir / 'train_log.csv'}")
    print(f"Classes dictionary:       {out_dir / 'classes.json'}")
    print("=" * 68)


if __name__ == '__main__':
    main()