File size: 32,071 Bytes
c39225b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
750
751
"""
v2/src/dataset.py

Dataset Loader, Frame-Budget Dynamic Batch Sampler, and Zero-Sync Collate for V2 Multi-Directory Audio Features:
1. SentencePieceCTCTokenizer:
   - Wraps ko_bpe_2048.model (2,048 BPE Vocab, CTC blank_id=0, unk_id=1)
   - CTC collapse_repeats and remove_blank decoding
2. CachedAudioFeatureDataset:
   - Reads cached .pt representations from multiple directories
   - Zero-RAM shared-memory indexing across DataLoader workers
   - Caches exact boundary-verified frame lengths (`frame_lengths_buf`, int16) in `multi_feature_index.pt`
     while preserving exact dataset ordering so deterministic train/val splits never leak
3. LengthBucketBatchSampler:
   - Supports both fixed `batch_size` and dynamic `frame_budget` (`max_padded_t * B <= frame_budget`)
   - Supports exact exclusion mask for seamless mid-epoch migration from legacy fixed-batch checkpoints
4. PadCollate:
   - 8-frame aligned BF16 dynamic padding, optional zero-GPU-cost CPU SpecAugment, and single-DMA
     packed int32 CTC metadata (`packed_ctc_meta`)
"""

from __future__ import annotations

from concurrent.futures import ThreadPoolExecutor
import os
import random
import re
import struct
from pathlib import Path
from typing import List, Dict, Any, Tuple, Optional, Union

import torch
from torch.utils.data import Dataset
import sentencepiece as spm

_PUNCT_RE = re.compile(r"[?!.,\"~:;()\[\]{}<>@#$%^&*_+=\/\\|`·…“”‘’]")
_NOISE_TAG_RE = re.compile(r"\([^)]*\)")
_SPACE_RE = re.compile(r"\s+")


def normalize_text(text: str) -> str:
    """Normalizes spoken Korean text by stripping punctuation and tags, condensing whitespace."""
    if not text:
        return ""
    t = _NOISE_TAG_RE.sub(" ", text)
    t = _PUNCT_RE.sub(" ", t)
    return _SPACE_RE.sub(" ", t).strip()


# ==============================================================================
# 1. 2,048 BPE SentencePiece CTC Tokenizer
# ==============================================================================

class SentencePieceCTCTokenizer:
    """
    2,048 BPE SentencePiece Tokenizer wrapper for CTC decoding:
    - blank_id = 0 (<blank>)
    - unk_id = 1 (<unk>)
    - Handles CTC repeat collapsing and blank removal
    """
    def __init__(self, model_path: Optional[Union[str, Path]] = None, model_bytes: Optional[bytes] = None):
        self.sp = spm.SentencePieceProcessor()
        if model_bytes is not None:
            self.sp.load_from_serialized_proto(model_bytes)
            self.model_path = None
        elif model_path is not None:
            self.model_path = Path(model_path)
            if not self.model_path.exists():
                cand1 = Path(__file__).resolve().parent.parent / self.model_path
                cand2 = Path(__file__).resolve().parent.parent.parent / self.model_path
                cand3 = Path(__file__).resolve().parent.parent / "tokenizer" / self.model_path.name
                if cand1.exists():
                    self.model_path = cand1
                elif cand2.exists():
                    self.model_path = cand2
                elif cand3.exists():
                    self.model_path = cand3
                else:
                    raise FileNotFoundError(f"SentencePiece model not found at {self.model_path}")
            self.sp.load(str(self.model_path))
        else:
            raise ValueError("Either model_path or model_bytes must be provided")

        self.blank_id = 0
        self.blank_token = "<blank>"
        self.unk_id = 1
        self.unk_token = "<unk>"
        self.vocab_size = self.sp.get_piece_size()

    def encode(self, text: str) -> List[int]:
        """Normalizes and encodes text into token IDs."""
        clean = normalize_text(text)
        if not clean:
            return []
        return self.sp.encode_as_ids(clean)

    def decode(self, token_ids: List[int], remove_blank: bool = True, collapse_repeats: bool = True) -> str:
        """
        Decodes a sequence of token IDs into clean Korean text:
        - collapse_repeats: collapses consecutive duplicates (CTC output requirement)
        - remove_blank: removes blank_id (0)
        """
        if collapse_repeats:
            collapsed: List[int] = []
            prev: Optional[int] = None
            for tid in token_ids:
                if tid != prev:
                    collapsed.append(tid)
                    prev = tid
            token_ids = collapsed

        filtered = [tid for tid in token_ids if not (remove_blank and tid == self.blank_id) and tid != self.unk_id]
        if not filtered:
            return ""

        return self.sp.decode_ids(filtered).strip()

    def id_to_piece(self, tid: int) -> str:
        return self.sp.id_to_piece(tid)

    def piece_to_id(self, piece: str) -> int:
        return self.sp.piece_to_id(piece)


# Backward compatibility alias
KoreanMorphemeTokenizer = SentencePieceCTCTokenizer


# ==============================================================================
# 2. Multi-Directory Shared-Memory Audio Feature Dataset
# ==============================================================================

def _read_exact_pt_frames(full_path: str) -> int:
    """
    Reads exact time frame count T of a cached (T, 256) bfloat16 .pt file by parsing
    the ZIP Central Directory entry `/data/0` at the tail of the file (<4 KB read, no pickle execution).
    Falls back to `torch.load` only if non-standard serialization is encountered.
    """
    try:
        with open(full_path, "rb") as f:
            f.seek(0, os.SEEK_END)
            fsize = f.tell()
            tail_len = min(fsize, 8192)
            f.seek(fsize - tail_len)
            tail = f.read(tail_len)

        pos = 0
        while True:
            idx = tail.find(b"PK\x01\x02", pos)
            if idx < 0 or idx + 46 > len(tail):
                break
            uncomp_size = struct.unpack_from("<I", tail, idx + 24)[0]
            fname_len, extra_len, comment_len = struct.unpack_from("<HHH", tail, idx + 28)
            name_end = idx + 46 + fname_len
            if name_end <= len(tail):
                entry_name = tail[idx + 46 : name_end]
                if entry_name.endswith(b"/data/0"):
                    return int(uncomp_size // 512)
            pos = name_end + extra_len + comment_len
    except Exception:
        pass

    try:
        d = torch.load(full_path, map_location="cpu", weights_only=False)
        feat = d.get("feature") if isinstance(d, dict) else None
        return int(feat.shape[0]) if feat is not None else 0
    except Exception:
        return 0


class _SharedMultiFilePathAccessor:
    """Zero-RAM sequence wrapper over shared-memory relative file path byte & offset tensors."""
    def __init__(self, base_root: str, names_buf: torch.Tensor, offsets_buf: torch.Tensor):
        self.base_root = base_root
        self.names_buf = names_buf
        self.offsets_buf = offsets_buf

    def __len__(self) -> int:
        return max(0, int(self.offsets_buf.numel()) - 1)

    def get_rel_path(self, idx: int) -> str:
        s = int(self.offsets_buf[idx].item())
        e = int(self.offsets_buf[idx + 1].item())
        return bytes(self.names_buf[s:e].numpy()).decode("utf-8")

    def __getitem__(self, idx: int) -> str:
        rel = self.get_rel_path(idx)
        return os.path.join(self.base_root, rel) if self.base_root else rel


class CachedAudioFeatureDataset(Dataset):
    """
    Multi-Directory Pre-extracted Audio Feature Dataset:
    - Loads (T, 256) bfloat16 audio representations and target token IDs
    - Supports multiple feature folders simultaneously
    - Zero-RAM shared memory index across DataLoader worker processes
    - Caches boundary-exact `frame_lengths` (`int16`) in `multi_feature_index.pt`
    """
    def __init__(
        self,
        cache_dirs: Union[str, Path, List[Union[str, Path]]],
        tokenizer: Optional[SentencePieceCTCTokenizer] = None,
        max_files: Optional[int] = None,
        index_cache_path: Optional[str] = "v2/manifests/multi_feature_index.pt"
    ):
        super().__init__()
        self.tokenizer = tokenizer

        if isinstance(cache_dirs, (str, Path)):
            cache_dirs = [cache_dirs]

        self.resolved_dirs: List[Path] = []
        project_root = Path(__file__).resolve().parent.parent.parent
        for cd in cache_dirs:
            p = Path(cd)
            if not p.is_absolute():
                p = project_root / p
            self.resolved_dirs.append(p)

        self.base_root = str(project_root)

        idx_file: Optional[Path] = None
        if index_cache_path:
            p_idx = Path(index_cache_path)
            idx_file = p_idx if p_idx.is_absolute() else project_root / p_idx
            idx_file.parent.mkdir(parents=True, exist_ok=True)

        loaded_from_cache = False
        cached_frame_lengths: Optional[torch.Tensor] = None

        if max_files is None and idx_file and idx_file.exists():
            try:
                cached_idx = torch.load(idx_file, map_location="cpu", weights_only=False)
                if (
                    isinstance(cached_idx, dict)
                    and cached_idx.get("dirs") == [str(d) for d in self.resolved_dirs]
                    and int(cached_idx.get("count", 0)) > 0
                ):
                    self._names_buf = cached_idx["names_buf"].share_memory_()
                    self._offsets_buf = cached_idx["offsets_buf"].share_memory_()
                    self.file_sizes = cached_idx["sizes_buf"].share_memory_()
                    fl_buf = cached_idx.get("frame_lengths_buf")
                    if isinstance(fl_buf, torch.Tensor) and fl_buf.numel() == self.file_sizes.numel():
                        cached_frame_lengths = fl_buf.to(torch.int16).share_memory_()
                    loaded_from_cache = True
            except Exception:
                loaded_from_cache = False

        if not loaded_from_cache:
            rel_names_list: List[bytes] = []
            sizes_list: List[int] = []

            per_dir_limit = max(1, max_files // len(self.resolved_dirs)) if max_files else None
            for rdir in self.resolved_dirs:
                if not rdir.exists():
                    print(f"[Dataset Warning] Feature directory not found: {rdir} (Skipping)")
                    continue

                entries = []
                for e in os.scandir(rdir):
                    if e.name.endswith(".pt") and not e.name.endswith(".tmp"):
                        entries.append(e)
                        if per_dir_limit is not None and len(entries) >= per_dir_limit:
                            break
                entries.sort(key=lambda e: e.name)
                print(f"[Dataset] Scanned {len(entries):,} .pt vectors from {rdir.name}")

                for e in entries:
                    try:
                        rel_path = os.path.relpath(e.path, self.base_root)
                    except ValueError:
                        rel_path = e.path
                    rel_names_list.append(rel_path.encode("utf-8"))
                    sizes_list.append(e.stat().st_size)

            if max_files is not None and max_files > 0:
                rel_names_list = rel_names_list[:max_files]
                sizes_list = sizes_list[:max_files]

            if rel_names_list:
                lengths = [len(b) for b in rel_names_list]
                offsets = [0]
                acc = 0
                for ln in lengths:
                    acc += ln
                    offsets.append(acc)

                joined = b"".join(rel_names_list)
                self._names_buf = torch.frombuffer(bytearray(joined), dtype=torch.uint8).share_memory_()
                self._offsets_buf = torch.tensor(offsets, dtype=torch.int64).share_memory_()
                self.file_sizes = torch.tensor(sizes_list, dtype=torch.int32).share_memory_()
            else:
                self._names_buf = torch.empty((0,), dtype=torch.uint8).share_memory_()
                self._offsets_buf = torch.zeros((1,), dtype=torch.int64).share_memory_()
                self.file_sizes = torch.empty((0,), dtype=torch.int32).share_memory_()
                print("[Dataset Warning] No cached .pt feature files found across all directories.")

        self.file_accessor = _SharedMultiFilePathAccessor(self.base_root, self._names_buf, self._offsets_buf)

        if cached_frame_lengths is not None:
            self.frame_lengths = cached_frame_lengths
        else:
            self.frame_lengths = self._build_frame_lengths_buf()
            if max_files is None and idx_file and len(self) > 0:
                try:
                    tmp_idx = idx_file.with_suffix(".pt.tmp")
                    torch.save({
                        "dirs": [str(d) for d in self.resolved_dirs],
                        "count": len(self),
                        "names_buf": self._names_buf,
                        "offsets_buf": self._offsets_buf,
                        "sizes_buf": self.file_sizes,
                        "frame_lengths_buf": self.frame_lengths,
                    }, tmp_idx)
                    tmp_idx.replace(idx_file)
                except Exception:
                    pass

        print(f"[Dataset V2] Total indexed samples in unified dataset: {len(self):,}")

    def _build_frame_lengths_buf(self) -> torch.Tensor:
        """
        Computes frame lengths (`int16`) across all `.pt` files:
        - Interior files (`16384 <= st_size < 380000`) are safely inside `29 <= T <= 740` and estimated
          within +/-1 frame via `(st_size - 1312) // 512`.
        - Boundary files near `T < 25` (`st_size < 16384`) or `T >= 750` (`st_size >= 380000`) are
          inspected via parallel ZIP Central Directory reads for 100% exact boundary filtering.
        """
        n = int(self.file_sizes.numel())
        if n == 0:
            return torch.empty((0,), dtype=torch.int16).share_memory_()

        est = torch.clamp((self.file_sizes.to(torch.int32) - 1312) // 512, min=1, max=32000).to(torch.int16)
        boundary_mask = (self.file_sizes < 16384) | (self.file_sizes >= 380000)
        boundary_idxs = torch.nonzero(boundary_mask, as_tuple=False).squeeze(-1).tolist()

        if boundary_idxs:
            print(f"[Dataset V2] Verifying exact frame counts for {len(boundary_idxs):,} boundary files (<1s / >=30s)...")
            paths = [self.file_accessor[i] for i in boundary_idxs]
            with ThreadPoolExecutor(max_workers=8) as ex:
                exact_lens = list(ex.map(_read_exact_pt_frames, paths, chunksize=256))
            est[boundary_idxs] = torch.tensor(exact_lens, dtype=torch.int16)

        return est.share_memory_()

    def __len__(self) -> int:
        return int(self.file_sizes.numel())

    def __getitem__(self, idx: int) -> Dict[str, Any]:
        full_path = self.file_accessor[idx]
        data = torch.load(full_path, map_location="cpu", weights_only=False)
        feature = data["feature"]  # Shape: (Time, 256)
        raw_text = data.get("raw_text", "")

        if self.tokenizer is not None and raw_text:
            tok_ids = self.tokenizer.encode(raw_text)
            targets = torch.tensor(tok_ids, dtype=torch.long)
        elif "targets" in data and isinstance(data["targets"], torch.Tensor):
            targets = data["targets"].to(torch.long)
        else:
            targets = torch.tensor([], dtype=torch.long)

        if not isinstance(feature, torch.Tensor):
            feature = torch.tensor(feature, dtype=torch.bfloat16)
        elif feature.dtype != torch.bfloat16:
            feature = feature.to(torch.bfloat16)

        return {
            "feature": feature,
            "targets": targets,
            "raw_text": raw_text,
            "file_name": os.path.basename(full_path)
        }


# ==============================================================================
# 3. Dynamic Frame-Budget & Fixed-Size Length-Bucketed Batch Sampler
# ==============================================================================

def reconstruct_legacy_trained_mask(
    raw_train_indices: torch.Tensor,
    full_file_sizes: torch.Tensor,
    num_full_samples: int,
    legacy_batch_size: int,
    legacy_pool_batches: int,
    seed: int,
    epoch_idx: int,
    done_batches: int,
) -> torch.Tensor:
    """
    Deterministically reconstructs the exact boolean mask over `full_dataset` (`[num_full_samples]`)
    of samples already trained during `0 .. done_batches - 1` of a legacy fixed-batch epoch.
    Guarantees zero duplicate and zero skipped samples when upgrading mid-epoch to `frame_budget`!
    """
    seen_full = torch.zeros((num_full_samples,), dtype=torch.bool)
    n = int(raw_train_indices.numel())
    if done_batches <= 0 or n == 0:
        return seen_full

    bs = max(1, int(legacy_batch_size))
    pool_size = bs * max(1, int(legacy_pool_batches))
    lengths_t = full_file_sizes[raw_train_indices.to(torch.long)]

    g = torch.Generator()
    g.manual_seed(int(seed) + int(epoch_idx))
    perm = torch.randperm(n, generator=g)

    ordered_chunks: List[torch.Tensor] = []
    for i in range(0, n, pool_size):
        pool = perm[i : i + pool_size]
        sort_idx = torch.argsort(lengths_t[pool])
        ordered_chunks.append(pool[sort_idx])

    sorted_all = torch.cat(ordered_chunks, dim=0)
    total_batches = (n + bs - 1) // bs
    done_b = min(int(done_batches), total_batches)
    batch_perm = torch.randperm(total_batches, generator=g)[:done_b]

    # Map batch IDs to flat positions [b * bs .. min((b + 1) * bs, n)]
    starts = batch_perm * bs
    selected_pos_parts = [
        (starts + k)[(starts + k) < n]
        for k in range(bs)
    ]
    selected_raw_pos = torch.cat(selected_pos_parts, dim=0)
    selected_subset_pos = sorted_all[selected_raw_pos]
    selected_full_ids = raw_train_indices[selected_subset_pos].to(torch.long)
    seen_full[selected_full_ids] = True
    return seen_full


class LengthBucketBatchSampler(torch.utils.data.Sampler[List[int]]):
    """
    Groups sequences of similar frame lengths into batches to minimize CTC padding overhead.
    Supports:
    - Dynamic `frame_budget` mode (`max_padded_t * len(batch) <= frame_budget`, capped at `max_batch_size`)
    - Legacy fixed `batch_size` mode (`frame_budget=None`)
    - Single-epoch `exclude_mask` for lossless mid-epoch resume from legacy fixed-batch checkpoints
    """
    def __init__(
        self,
        dataset: Dataset,
        batch_size: int = 16,
        shuffle: bool = True,
        pool_batches: int = 128,
        seed: int = 42,
        frame_budget: Optional[int] = None,
        max_batch_size: int = 48,
        pad_multiple: int = 8,
        pool_size: Optional[int] = None,
    ):
        super().__init__()
        self.dataset = dataset
        self.batch_size = max(1, int(batch_size))
        self.shuffle = shuffle
        self.seed = int(seed)
        self.frame_budget = int(frame_budget) if (frame_budget is not None and int(frame_budget) > 0) else None
        self.max_batch_size = max(1, int(max_batch_size))
        self.pad_multiple = max(1, int(pad_multiple))
        if pool_size is not None and int(pool_size) > 0:
            self.pool_size = int(pool_size)
        elif self.frame_budget is not None:
            self.pool_size = 16384
        else:
            self.pool_size = self.batch_size * max(1, int(pool_batches))

        self.epoch = 0
        self.start_batch = 0
        self._exclude_epoch: Optional[int] = None
        self._exclude_mask: Optional[torch.Tensor] = None
        self._cached_key: Optional[Tuple[int, bool]] = None
        self._cached_batches: Optional[List[List[int]]] = None

        # Prefer exact/cached frame_lengths over raw byte file_sizes
        if hasattr(dataset, "frame_lengths"):
            fl = dataset.frame_lengths
            self.lengths_t = fl.to(torch.int32) if isinstance(fl, torch.Tensor) else torch.tensor(fl, dtype=torch.int32)
        elif hasattr(dataset, "dataset") and hasattr(dataset, "indices") and hasattr(dataset.dataset, "frame_lengths"):
            base_fl = dataset.dataset.frame_lengths
            idx_t = dataset.indices if isinstance(dataset.indices, torch.Tensor) else torch.tensor(dataset.indices, dtype=torch.long)
            self.lengths_t = base_fl[idx_t.to(torch.long)].to(torch.int32)
        elif hasattr(dataset, "file_sizes"):
            fs = dataset.file_sizes
            raw_s = fs if isinstance(fs, torch.Tensor) else torch.tensor(fs, dtype=torch.int32)
            self.lengths_t = torch.clamp((raw_s.to(torch.int32) - 1312) // 512, min=1)
        elif hasattr(dataset, "dataset") and hasattr(dataset, "indices") and hasattr(dataset.dataset, "file_sizes"):
            base_s = dataset.dataset.file_sizes
            idx_t = dataset.indices if isinstance(dataset.indices, torch.Tensor) else torch.tensor(dataset.indices, dtype=torch.long)
            self.lengths_t = torch.clamp((base_s[idx_t.to(torch.long)].to(torch.int32) - 1312) // 512, min=1)
        else:
            self.lengths_t = torch.full((len(dataset),), 128, dtype=torch.int32)

        pm = self.pad_multiple
        self.padded_lengths_t = ((torch.clamp(self.lengths_t, min=pm) + pm - 1) // pm) * pm

    def set_legacy_epoch_exclude(self, epoch_idx: int, exclude_subset_mask: torch.Tensor) -> None:
        """Excludes already-trained subset positions for `epoch_idx` only, then automatically clears on later epochs."""
        self._exclude_epoch = int(epoch_idx)
        self._exclude_mask = exclude_subset_mask.to(torch.bool)
        self._cached_key = None
        self._cached_batches = None

    def set_epoch(self, epoch: int, start_batch: int = 0) -> None:
        self.epoch = max(0, int(epoch))
        self.start_batch = max(0, int(start_batch))

    def _build_epoch_batches(self, epoch_idx: int, ignore_exclude: bool = False) -> List[List[int]]:
        use_excl = (
            not ignore_exclude
            and self._exclude_epoch is not None
            and self._exclude_mask is not None
            and int(epoch_idx) == int(self._exclude_epoch)
        )
        cache_key = (int(epoch_idx), bool(use_excl))
        if self._cached_key == cache_key and self._cached_batches is not None:
            return self._cached_batches

        n_total = int(self.lengths_t.numel())
        if n_total == 0:
            return []

        if use_excl:
            active_positions = torch.nonzero(~self._exclude_mask, as_tuple=False).squeeze(-1)
        else:
            active_positions = None

        n = int(active_positions.numel()) if active_positions is not None else n_total
        if n == 0:
            return []

        if self.shuffle:
            g = torch.Generator()
            g.manual_seed(self.seed + int(epoch_idx))
            perm_local = torch.randperm(n, generator=g)
            perm = active_positions[perm_local] if active_positions is not None else perm_local

            batches: List[List[int]] = []
            ps = self.pool_size
            fb = self.frame_budget
            mbs = self.max_batch_size
            bs = self.batch_size

            for i in range(0, n, ps):
                pool = perm[i : i + ps]
                pool_lens = self.padded_lengths_t[pool]
                sort_idx = torch.argsort(pool_lens)
                sorted_pool = pool[sort_idx].tolist()

                if fb is None:
                    for b in range(0, len(sorted_pool), bs):
                        batches.append(sorted_pool[b : b + bs])
                else:
                    sorted_plens = pool_lens[sort_idx].tolist()
                    cur_batch: List[int] = []
                    cur_len = 0
                    for item_id, plen in zip(sorted_pool, sorted_plens):
                        if cur_len > 0 and (cur_len >= mbs or plen * (cur_len + 1) > fb):
                            batches.append(cur_batch)
                            cur_batch = [item_id]
                            cur_len = 1
                        else:
                            cur_batch.append(item_id)
                            cur_len += 1
                    if cur_batch:
                        batches.append(cur_batch)

            batch_perm = torch.randperm(len(batches), generator=g).tolist()
            batches = [batches[idx] for idx in batch_perm]
        else:
            base_pos = active_positions if active_positions is not None else torch.arange(n_total, dtype=torch.long)
            sub_plens = self.padded_lengths_t[base_pos]
            sort_idx = torch.argsort(sub_plens)
            sorted_all = base_pos[sort_idx].tolist()

            if self.frame_budget is None:
                batches = [sorted_all[b : b + self.batch_size] for b in range(0, len(sorted_all), self.batch_size)]
            else:
                sorted_plens = sub_plens[sort_idx].tolist()
                fb = self.frame_budget
                mbs = self.max_batch_size
                batches = []
                cur_batch = []
                cur_len = 0
                for item_id, plen in zip(sorted_all, sorted_plens):
                    if cur_len > 0 and (cur_len >= mbs or plen * (cur_len + 1) > fb):
                        batches.append(cur_batch)
                        cur_batch = [item_id]
                        cur_len = 1
                    else:
                        cur_batch.append(item_id)
                        cur_len += 1
                if cur_batch:
                    batches.append(cur_batch)

        self._cached_key = cache_key
        self._cached_batches = batches
        return batches

    def num_full_epoch_batches(self, epoch_idx: int = 0) -> int:
        """Returns exact batch count for a full un-excluded epoch."""
        if self.frame_budget is None:
            n = int(self.lengths_t.numel())
            return (n + self.batch_size - 1) // self.batch_size
        return len(self._build_epoch_batches(epoch_idx, ignore_exclude=True))

    def total_batches_for_epoch(self, epoch_idx: Optional[int] = None) -> int:
        ep = self.epoch if epoch_idx is None else int(epoch_idx)
        return len(self._build_epoch_batches(ep, ignore_exclude=False))

    def __len__(self) -> int:
        total = len(self._build_epoch_batches(self.epoch, ignore_exclude=False))
        return max(0, total - self.start_batch)

    def __iter__(self):
        ep = self.epoch
        start_b = self.start_batch
        self.start_batch = 0
        self.epoch = ep + 1

        batches = self._build_epoch_batches(ep, ignore_exclude=False)
        if start_b > 0:
            batches = batches[start_b:]

        for b in batches:
            yield b


class PadCollate:
    """
    Dynamic padding collate function for audio features and token sequences:
    - 8-frame aligned BF16 padding
    - Optional zero-GPU-cost CPU SpecAugment on freshly padded worker tensors
    - Single-DMA `packed_ctc_meta` (`int32`) bundling `[active_ids, compact_targets, in_lens, tgt_lens, tgt_offs]`
    """
    def __init__(
        self,
        blank_id: int = 0,
        pad_multiple: int = 8,
        max_frames: Optional[int] = None,
        apply_spec_augment: bool = False,
        time_mask_min: int = 5,
        time_mask_max: int = 15,
        num_time_masks: int = 2,
        freq_mask_min: int = 16,
        freq_mask_max: int = 32,
        num_freq_masks: int = 2,
    ):
        self.blank_id = blank_id
        self.pad_multiple = max(1, pad_multiple)
        self.max_frames = max_frames
        self.apply_spec_augment = apply_spec_augment
        self.time_mask_min = time_mask_min
        self.time_mask_max = time_mask_max
        self.num_time_masks = num_time_masks
        self.freq_mask_min = freq_mask_min
        self.freq_mask_max = freq_mask_max
        self.num_freq_masks = num_freq_masks

    def __call__(self, batch: List[Dict[str, Any]]) -> Dict[str, Any]:
        valid_items = [item for item in batch if item["feature"] is not None and item["feature"].size(0) > 0]
        if not valid_items:
            raise ValueError("All batch items are empty or corrupted.")

        features = [item["feature"] for item in valid_items]
        targets = [item["targets"] for item in valid_items]
        raw_texts = [item.get("raw_text", "") for item in valid_items]
        file_names = [item.get("file_name", "") for item in valid_items]

        B = len(features)
        in_lens_list = [f.size(0) for f in features]
        tgt_lens_list = [t.numel() for t in targets]

        max_t = max(in_lens_list)
        if self.max_frames is not None:
            max_t = min(max_t, self.max_frames)
        if self.pad_multiple > 1:
            max_t = ((max_t + self.pad_multiple - 1) // self.pad_multiple) * self.pad_multiple

        clamped_in_lens = [min(l, max_t) for l in in_lens_list]
        input_lengths = torch.tensor(clamped_in_lens, dtype=torch.long)
        target_lengths = torch.tensor(tgt_lens_list, dtype=torch.long)

        feature_dim = features[0].size(-1)
        padded_features = torch.zeros((B, max_t, feature_dim), dtype=torch.bfloat16)
        attention_mask = torch.ones((B, max_t), dtype=torch.bool)

        for i, f in enumerate(features):
            t_len = clamped_in_lens[i]
            padded_features[i, :t_len] = f[:t_len]
            attention_mask[i, :t_len] = False  # False indicates valid non-padded frame

        # Optional CPU SpecAugment inside worker (saves 5 GPU kernels + 1 GPU clone per step!)
        if self.apply_spec_augment and max_t > 1:
            for _ in range(self.num_time_masks):
                t_len = random.randint(self.time_mask_min, min(self.time_mask_max, max(max_t - 1, self.time_mask_min)))
                t_start = random.randint(0, max(0, max_t - t_len))
                padded_features[:, t_start : t_start + t_len, :] = 0.0
            for _ in range(self.num_freq_masks):
                f_len = random.randint(self.freq_mask_min, min(self.freq_mask_max, max(feature_dim - 1, self.freq_mask_min)))
                f_start = random.randint(0, max(0, feature_dim - f_len))
                padded_features[:, :, f_start : f_start + f_len] = 0.0

        tot_toks = sum(tgt_lens_list)
        flat_targets = torch.cat(targets, dim=0) if tot_toks > 0 else torch.empty(0, dtype=torch.long)

        active_ids_cpu = None
        compact_targets = None
        packed_ctc_meta = None
        packed_ctc_sizes = None

        if tot_toks > 0:
            uniq_t, inv_idx = torch.unique(flat_targets, sorted=True, return_inverse=True)
            active_ids_cpu = torch.cat([torch.zeros(1, dtype=torch.int32), uniq_t.to(torch.int32)])
            compact_targets = inv_idx + 1

            U = int(active_ids_cpu.numel())
            sum_L = int(compact_targets.numel())
            max_L = max(tgt_lens_list) if tgt_lens_list else 0

            offs_list = [0] * B
            acc_o = 0
            for i in range(B - 1):
                acc_o += tgt_lens_list[i]
                offs_list[i + 1] = acc_o

            packed_ctc_meta = torch.cat([
                active_ids_cpu,
                compact_targets.to(torch.int32),
                torch.tensor(clamped_in_lens, dtype=torch.int32),
                torch.tensor(tgt_lens_list, dtype=torch.int32),
                torch.tensor(offs_list, dtype=torch.int32),
            ], dim=0)
            packed_ctc_sizes = (U, sum_L, max_L, tot_toks)

        return {
            "features": padded_features,
            "attention_mask": attention_mask,
            "key_padding_mask": attention_mask,
            "input_lengths": input_lengths,
            "targets": flat_targets,
            "flat_targets": flat_targets,
            "target_lengths": target_lengths,
            "raw_texts": raw_texts,
            "file_names": file_names,
            "active_ids": active_ids_cpu,
            "active_ids_cpu": active_ids_cpu,
            "compact_targets": compact_targets,
            "packed_ctc_meta": packed_ctc_meta,
            "packed_ctc_sizes": packed_ctc_sizes,
            "already_augmented": self.apply_spec_augment,
        }