File size: 7,887 Bytes
f50dc54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
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