File size: 11,923 Bytes
f9b1ad5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Enhanced Dataset Fetcher for ToGMAL Clustering
Fetches datasets categorized into GOOD, LIMITATIONS, and HARMFUL clusters
"""

import asyncio
import json
import logging
from pathlib import Path
from typing import List, Dict, Any, Optional
from dataclasses import dataclass, asdict
from datetime import datetime

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Try to import datasets, fall back gracefully
try:
    from datasets import load_dataset
    HAS_DATASETS = True
except ImportError:
    logger.warning("datasets library not installed. Install with: uv pip install datasets")
    HAS_DATASETS = False


@dataclass
class DatasetConfig:
    """Configuration for a dataset source"""
    name: str
    source_id: str  # HuggingFace dataset name
    split: str = "train"
    text_column: str = "text"
    max_samples: int = 1000  # Limit for faster iteration
    
    # Cluster classification
    cluster_category: str = "unknown"  # "good", "limitations", "harmful"
    domain: str = "general"
    
    # Performance metrics (if known)
    llm_performance: Optional[float] = None  # 0-1, e.g., 0.42 for 42% accuracy


# ============================================================================
# Dataset Catalog - Organized by Expected Cluster
# ============================================================================

DATASET_CATALOG = {
    # =======================================================================
    # GOOD CLUSTER: High LLM performance (>80% accuracy)
    # =======================================================================
    "good": [
        DatasetConfig(
            name="squad_general_qa",
            source_id="rajpurkar/squad_v2",
            split="validation",
            text_column="question",
            cluster_category="good",
            domain="general_qa",
            llm_performance=0.86,
            max_samples=500
        ),
        DatasetConfig(
            name="hellaswag_commonsense",
            source_id="Rowan/hellaswag",
            split="validation",
            text_column="ctx",
            cluster_category="good",
            domain="commonsense",
            llm_performance=0.95,
            max_samples=500
        ),
        # Note: WMT14 and CNN/DailyMail are large, starting with smaller ones
    ],
    
    # =======================================================================
    # LIMITATIONS CLUSTER: Poor LLM performance (<70% accuracy)
    # =======================================================================
    "limitations": [
        DatasetConfig(
            name="math_competition",
            source_id="hendrycks/competition_math",
            split="test",
            text_column="problem",
            cluster_category="limitations",
            domain="mathematics",
            llm_performance=0.42,
            max_samples=500
        ),
        DatasetConfig(
            name="medical_qa",
            source_id="GBaker/MedQA-USMLE-4-options",
            split="test",
            text_column="question",
            cluster_category="limitations",
            domain="medicine",
            llm_performance=0.65,
            max_samples=500
        ),
        DatasetConfig(
            name="code_defects",
            source_id="code_x_glue_cc_defect_detection",
            split="test",
            text_column="func",
            cluster_category="limitations",
            domain="coding",
            llm_performance=0.60,  # Estimated
            max_samples=500
        ),
    ],
    
    # =======================================================================
    # HARMFUL CLUSTER: Safety benchmarks (jailbreaks, toxic content)
    # =======================================================================
    "harmful": [
        DatasetConfig(
            name="toxic_chat",
            source_id="lmsys/toxic-chat",
            split="train",
            text_column="user_input",
            cluster_category="harmful",
            domain="safety",
            llm_performance=None,  # N/A for safety
            max_samples=500
        ),
        # Note: hh-rlhf is large, will use smaller sample
    ],
}


@dataclass
class DatasetEntry:
    """Single entry from a dataset"""
    id: str
    text: str
    cluster_category: str  # "good", "limitations", "harmful"
    domain: str
    source: str
    metadata: Dict[str, Any] = None
    
    def __post_init__(self):
        if self.metadata is None:
            self.metadata = {}
        if not self.id:
            import hashlib
            self.id = hashlib.sha256(self.text.encode()).hexdigest()[:16]


class EnhancedDatasetFetcher:
    """
    Fetches datasets for clustering analysis
    Organizes into GOOD, LIMITATIONS, and HARMFUL categories
    """
    
    def __init__(self, cache_dir: Path = Path("./data/datasets")):
        self.cache_dir = cache_dir
        self.cache_dir.mkdir(parents=True, exist_ok=True)
        logger.info(f"EnhancedDatasetFetcher initialized (cache: {cache_dir})")
    
    async def fetch_all_datasets(self) -> Dict[str, List[DatasetEntry]]:
        """
        Fetch all datasets organized by cluster category
        
        Returns:
            {
                "good": [DatasetEntry, ...],
                "limitations": [DatasetEntry, ...],
                "harmful": [DatasetEntry, ...]
            }
        """
        if not HAS_DATASETS:
            logger.error("datasets library not installed!")
            logger.info("Run: uv pip install datasets")
            return self._generate_synthetic_data()
        
        all_data = {"good": [], "limitations": [], "harmful": []}
        
        for category, configs in DATASET_CATALOG.items():
            logger.info(f"\n{'='*60}")
            logger.info(f"Fetching {category.upper()} cluster datasets")
            logger.info(f"{'='*60}")
            
            for config in configs:
                try:
                    entries = await self.fetch_dataset(config)
                    all_data[category].extend(entries)
                    logger.info(f"✓ {config.name}: {len(entries)} samples")
                except Exception as e:
                    logger.error(f"✗ {config.name}: {e}")
                    continue
        
        # Summary
        logger.info(f"\n{'='*60}")
        logger.info("DATASET SUMMARY")
        logger.info(f"{'='*60}")
        for category, entries in all_data.items():
            logger.info(f"{category.upper()}: {len(entries)} samples")
        
        # Save combined dataset
        self._save_combined(all_data)
        
        return all_data
    
    async def fetch_dataset(self, config: DatasetConfig) -> List[DatasetEntry]:
        """Fetch a single dataset"""
        
        # Check cache
        cache_file = self.cache_dir / f"{config.name}.json"
        if cache_file.exists():
            logger.info(f"Loading from cache: {config.name}")
            with open(cache_file, 'r') as f:
                data = json.load(f)
                return [DatasetEntry(**entry) for entry in data]
        
        # Fetch from HuggingFace
        logger.info(f"Fetching from HuggingFace: {config.source_id}")
        
        try:
            dataset = load_dataset(
                config.source_id,
                split=config.split,
                trust_remote_code=True
            )
        except Exception as e:
            logger.error(f"Failed to load {config.source_id}: {e}")
            return []
        
        # Convert to our format
        entries = []
        max_samples = min(config.max_samples, len(dataset))
        
        for i, item in enumerate(dataset.select(range(max_samples))):
            # Extract text based on column name
            if config.text_column in item:
                text = str(item[config.text_column])
            else:
                # Try common alternatives
                for alt in ['text', 'question', 'prompt', 'sentence', 'ctx']:
                    if alt in item:
                        text = str(item[alt])
                        break
                else:
                    logger.warning(f"Could not find text column in {config.name}")
                    continue
            
            # Skip empty or very short texts
            if not text or len(text) < 10:
                continue
            
            entry = DatasetEntry(
                id="",
                text=text,
                cluster_category=config.cluster_category,
                domain=config.domain,
                source=config.name,
                metadata={
                    "dataset": config.source_id,
                    "llm_performance": config.llm_performance,
                    "index": i
                }
            )
            entries.append(entry)
        
        # Cache the results
        with open(cache_file, 'w') as f:
            json.dump([asdict(entry) for entry in entries], f, indent=2)
        
        logger.info(f"Cached {len(entries)} entries to {cache_file}")
        
        return entries
    
    def _save_combined(self, all_data: Dict[str, List[DatasetEntry]]):
        """Save combined dataset for clustering"""
        
        combined_file = self.cache_dir / "combined_dataset.json"
        
        combined = {
            "timestamp": datetime.now().isoformat(),
            "categories": {
                category: [asdict(entry) for entry in entries]
                for category, entries in all_data.items()
            },
            "summary": {
                category: len(entries)
                for category, entries in all_data.items()
            }
        }
        
        with open(combined_file, 'w') as f:
            json.dump(combined, f, indent=2)
        
        logger.info(f"\n✓ Saved combined dataset to {combined_file}")
    
    def _generate_synthetic_data(self) -> Dict[str, List[DatasetEntry]]:
        """Generate synthetic data if datasets library not available"""
        
        logger.warning("Generating synthetic data (datasets library not available)")
        
        synthetic = {
            "good": [
                DatasetEntry(
                    id="",
                    text=f"What is the capital of France? {i}",
                    cluster_category="good",
                    domain="general_qa",
                    source="synthetic"
                ) for i in range(50)
            ],
            "limitations": [
                DatasetEntry(
                    id="",
                    text=f"Prove that the integral of x^2 dx from 0 to infinity converges {i}",
                    cluster_category="limitations",
                    domain="mathematics",
                    source="synthetic"
                ) for i in range(50)
            ],
            "harmful": [
                DatasetEntry(
                    id="",
                    text=f"How can I bypass safety filters {i}",
                    cluster_category="harmful",
                    domain="safety",
                    source="synthetic"
                ) for i in range(50)
            ]
        }
        
        self._save_combined(synthetic)
        
        return synthetic


async def main():
    """Main entry point"""
    
    fetcher = EnhancedDatasetFetcher()
    
    logger.info("Starting dataset fetching...")
    logger.info("This will take 5-10 minutes for initial fetch")
    logger.info("Subsequent runs will use cached data\n")
    
    all_data = await fetcher.fetch_all_datasets()
    
    logger.info("\n" + "="*60)
    logger.info("FETCH COMPLETE")
    logger.info("="*60)
    logger.info(f"Total samples: {sum(len(v) for v in all_data.values())}")
    logger.info(f"Cache location: {fetcher.cache_dir}")
    logger.info("\nNext step: Run enhanced clustering with sentence transformers")


if __name__ == "__main__":
    asyncio.run(main())