""" IPO Group-aware Batch Sampler for TTRLVR 동일한 ipo_group_id를 가진 task들을 같은 배치에 묶는 커스텀 샘플러 이를 통해 동일한 IPO triple에서 생성된 induction/deduction/abduction task들이 함께 학습되도록 보장합니다. """ import torch from torch.utils.data import Sampler, BatchSampler from typing import Iterator, List, Optional import random from collections import defaultdict import pandas as pd import numpy as np class IPOGroupedBatchSampler(Sampler): """동일한 IPO에서 생성된 task들을 같은 배치에 묶는 샘플러""" def __init__(self, dataset, batch_size: int, shuffle: bool = True, drop_last: bool = False, seed: int = 42): """ Args: dataset: ipo_group_id를 가진 데이터셋 (TTRLVRDataset) batch_size: 배치 크기 shuffle: 그룹 순서를 섞을지 여부 drop_last: 마지막 불완전한 배치를 버릴지 여부 seed: 랜덤 시드 """ self.dataset = dataset self.batch_size = batch_size self.shuffle = shuffle self.drop_last = drop_last self.generator = torch.Generator() self.generator.manual_seed(seed) # ipo_group_id별로 인덱스 그룹핑 self.groups = defaultdict(list) self._build_groups() # 배치 생성 self._create_batches() def _build_groups(self): """데이터셋에서 ipo_group_id별로 인덱스를 그룹핑""" for idx in range(len(self.dataset)): # TTRLVRDataset의 dataframe에서 직접 접근 if hasattr(self.dataset, 'dataframe'): row = self.dataset.dataframe.iloc[idx] ipo_group_id = row.get('ipo_group_id', None) # ipo_group_id가 없으면 개별 그룹으로 처리 if not ipo_group_id or ipo_group_id == '': ipo_group_id = f'individual_{idx}' else: # Fallback: 개별 그룹 ipo_group_id = f'individual_{idx}' self.groups[ipo_group_id].append(idx) print(f"[IPOGroupedBatchSampler] Built {len(self.groups)} IPO groups from {len(self.dataset)} samples") # 그룹 크기 통계 group_sizes = [len(indices) for indices in self.groups.values()] if group_sizes: print(f" - Group sizes: min={min(group_sizes)}, max={max(group_sizes)}, avg={np.mean(group_sizes):.2f}") def _create_batches(self): """그룹별로 배치 생성""" self.batches = [] # 모든 인덱스를 수집 (그룹 단위로) all_indices = [] for group_id, indices in self.groups.items(): # 같은 IPO 그룹의 task들을 함께 유지 # 일반적으로 3개 (induction, deduction, abduction) if len(indices) <= self.batch_size: # 그룹이 배치 크기보다 작으면 그대로 사용 all_indices.extend(indices) else: # 그룹이 배치 크기보다 크면 분할 (드물지만 가능) for i in range(0, len(indices), self.batch_size): chunk = indices[i:i + self.batch_size] all_indices.extend(chunk) # 배치 생성 current_batch = [] for idx in all_indices: current_batch.append(idx) if len(current_batch) == self.batch_size: self.batches.append(current_batch) current_batch = [] # 마지막 불완전한 배치 처리 if current_batch and not self.drop_last: self.batches.append(current_batch) elif current_batch and self.drop_last: print(f"[IPOGroupedBatchSampler] Dropped last incomplete batch of size {len(current_batch)}") print(f"[IPOGroupedBatchSampler] Created {len(self.batches)} batches") def __iter__(self) -> Iterator[List[int]]: """배치 반복자""" # 배치 순서 섞기 if self.shuffle: indices = torch.randperm(len(self.batches), generator=self.generator).tolist() shuffled_batches = [self.batches[i] for i in indices] else: shuffled_batches = self.batches # 각 배치 yield for batch in shuffled_batches: # 배치 내부도 섞을 수 있음 (선택적) if self.shuffle: random.shuffle(batch) yield batch def __len__(self) -> int: """전체 배치 수""" return len(self.batches) class IPOGroupPreservingBatchSampler(BatchSampler): """ IPO 그룹을 최대한 보존하면서 배치를 생성하는 샘플러 이 샘플러는 다음 우선순위로 작동합니다: 1. 같은 ipo_group_id를 가진 샘플들을 우선적으로 같은 배치에 배치 2. 배치 크기를 채우기 위해 필요시 다른 그룹의 샘플 추가 3. 모든 샘플이 정확히 한 번씩 사용되도록 보장 """ def __init__(self, dataset, batch_size: int, shuffle: bool = True, drop_last: bool = False, seed: int = 42): """ Args: dataset: TTRLVRDataset 인스턴스 batch_size: 배치 크기 shuffle: 배치 및 그룹 순서 섞기 drop_last: 마지막 불완전한 배치 버리기 seed: 랜덤 시드 """ self.dataset = dataset self.batch_size = batch_size self.shuffle = shuffle self.drop_last = drop_last self.seed = seed # 그룹별 인덱스 구축 self.groups = self._build_groups() def _build_groups(self): """ipo_group_id별로 샘플 인덱스 그룹핑""" groups = defaultdict(list) for idx in range(len(self.dataset)): if hasattr(self.dataset, 'dataframe'): row = self.dataset.dataframe.iloc[idx] ipo_group_id = row.get('ipo_group_id', '') # 빈 값이면 개별 처리 if not ipo_group_id: ipo_group_id = f'single_{idx}' else: ipo_group_id = f'single_{idx}' groups[ipo_group_id].append(idx) return groups def __iter__(self): """배치 생성 및 반복""" # 그룹들을 리스트로 변환 group_list = list(self.groups.items()) # 셔플 if self.shuffle: random.seed(self.seed) random.shuffle(group_list) # 배치 생성 current_batch = [] for group_id, indices in group_list: # 그룹 내 인덱스도 셔플 if self.shuffle: random.shuffle(indices) for idx in indices: current_batch.append(idx) # 배치가 가득 차면 yield if len(current_batch) == self.batch_size: yield current_batch current_batch = [] # 마지막 배치 처리 if current_batch and not self.drop_last: yield current_batch def __len__(self): """전체 배치 수 계산""" total_samples = len(self.dataset) if self.drop_last: return total_samples // self.batch_size else: return (total_samples + self.batch_size - 1) // self.batch_size