File size: 10,651 Bytes
40fd3fa | 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 | """Data Validation and Split Module
Validates and splits datasets for training/validation/testing.
"""
import json
import random
import hashlib
from pathlib import Path
from typing import List, Dict, Tuple, Optional, Callable
from dataclasses import dataclass
from enum import Enum
import re
class SplitType(Enum):
"""Dataset split types."""
TRAIN = "train"
VALIDATION = "validation"
TEST = "test"
@dataclass
class DatasetItem:
"""Single dataset item."""
system: str
instruction: str
response: str
metadata: Dict
@dataclass
class ValidationResult:
"""Validation result."""
valid: bool
errors: List[str]
warnings: List[str]
class DataValidator:
"""Validate dataset items."""
MIN_RESPONSE_LENGTH = 10
MAX_RESPONSE_LENGTH = 10000
MIN_INSTRUCTION_LENGTH = 3
@classmethod
def validate_item(cls, item: Dict) -> ValidationResult:
"""Validate a single dataset item."""
errors = []
warnings = []
# Check required fields
required_fields = ["system", "instruction", "response"]
for field in required_fields:
if field not in item:
errors.append(f"Missing required field: {field}")
elif not isinstance(item[field], str):
errors.append(f"Field '{field}' must be a string")
if errors:
return ValidationResult(valid=False, errors=errors, warnings=warnings)
# Validate lengths
if len(item["response"]) < cls.MIN_RESPONSE_LENGTH:
errors.append(f"Response too short: {len(item['response'])} chars")
if len(item["response"]) > cls.MAX_RESPONSE_LENGTH:
warnings.append(f"Response very long: {len(item['response'])} chars")
if len(item["instruction"]) < cls.MIN_INSTRUCTION_LENGTH:
errors.append(f"Instruction too short: {len(item['instruction'])} chars")
# Check for code blocks
if "```" not in item["response"]:
warnings.append("Response contains no code blocks")
# Check for Myanmar content
myanmar_pattern = re.compile(r"[\u1000-\u109f]+")
has_myanmar = bool(myanmar_pattern.search(item["instruction"]))
if not has_myanmar and not has_myanmar:
warnings.append("No Myanmar text found")
return ValidationResult(
valid=len(errors) == 0,
errors=errors,
warnings=warnings
)
@classmethod
def validate_dataset(cls, items: List[Dict]) -> Tuple[List[Dict], List[Dict]]:
"""Validate entire dataset, return valid and invalid items."""
valid = []
invalid = []
for item in items:
result = cls.validate_item(item)
if result.valid:
valid.append(item)
else:
invalid.append({**item, "validation_errors": result.errors})
return valid, invalid
class DataSplitter:
"""Split dataset into train/validation/test sets."""
def __init__(self, train_ratio: float = 0.7, val_ratio: float = 0.15, test_ratio: float = 0.15):
self.train_ratio = train_ratio
self.val_ratio = val_ratio
self.test_ratio = test_ratio
assert abs(train_ratio + val_ratio + test_ratio - 1.0) < 0.001, "Ratios must sum to 1.0"
def split(
self,
items: List[Dict],
stratify_by: Optional[Callable] = None
) -> Dict[SplitType, List[Dict]]:
"""Split dataset with optional stratification."""
if stratify_by:
return self._stratified_split(items, stratify_by)
else:
return self._random_split(items)
def _random_split(self, items: List[Dict]) -> Dict[SplitType, List[Dict]]:
"""Randomly split dataset."""
shuffled = items.copy()
random.shuffle(shuffled)
total = len(shuffled)
train_size = int(total * self.train_ratio)
val_size = int(total * self.val_ratio)
return {
SplitType.TRAIN: shuffled[:train_size],
SplitType.VALIDATION: shuffled[train_size:train_size + val_size],
SplitType.TEST: shuffled[train_size + val_size:]
}
def _stratified_split(
self,
items: List[Dict],
stratify_by: Callable
) -> Dict[SplitType, List[Dict]]:
"""Split with stratification by a key function."""
buckets: Dict[str, List[Dict]] = {}
for item in items:
key = stratify_by(item)
if key not in buckets:
buckets[key] = []
buckets[key].append(item)
train_buckets = {k: [] for k in buckets}
val_buckets = {k: [] for k in buckets}
test_buckets = {k: [] for k in buckets}
for key, bucket_items in buckets.items():
random.shuffle(bucket_items)
total = len(bucket_items)
train_size = int(total * self.train_ratio)
val_size = int(total * self.val_ratio)
train_buckets[key] = bucket_items[:train_size]
val_buckets[key] = bucket_items[train_size:train_size + val_size]
test_buckets[key] = bucket_items[train_size + val_size:]
return {
SplitType.TRAIN: [item for bucket in train_buckets.values() for item in bucket],
SplitType.VALIDATION: [item for bucket in val_buckets.values() for item in bucket],
SplitType.TEST: [item for bucket in test_buckets.values() for item in bucket],
}
def hash_split(self, items: List[Dict], salt: str = "") -> Dict[SplitType, List[Dict]]:
"""Split based on hash for reproducibility."""
result = {SplitType.TRAIN: [], SplitType.VALIDATION: [], SplitType.TEST: []}
for item in items:
hash_val = hashlib.md5(
f"{json.dumps(item, sort_keys=True)}{salt}".encode()
).hexdigest()
hash_num = int(hash_val[:8], 16)
normalized = hash_num / 0xFFFFFFFF
if normalized < self.train_ratio:
result[SplitType.TRAIN].append(item)
elif normalized < self.train_ratio + self.val_ratio:
result[SplitType.VALIDATION].append(item)
else:
result[SplitType.TEST].append(item)
return result
class DatasetManager:
"""Manage dataset operations."""
@staticmethod
def load_jsonl(file_path: str) -> List[Dict]:
"""Load data from JSONL file."""
items = []
with open(file_path, "r", encoding="utf-8") as f:
for line in f:
if line.strip():
items.append(json.loads(line))
return items
@staticmethod
def save_jsonl(file_path: str, items: List[Dict]):
"""Save data to JSONL file."""
Path(file_path).parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
for item in items:
f.write(json.dumps(item, ensure_ascii=False) + "\n")
@staticmethod
def load_json(file_path: str) -> List[Dict]:
"""Load data from JSON file."""
with open(file_path, "r", encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, list) else data.get("data", data.get("items", [data]))
@staticmethod
def save_json(file_path: str, items: List[Dict]):
"""Save data to JSON file."""
Path(file_path).parent.mkdir(parents=True, exist_ok=True)
with open(file_path, "w", encoding="utf-8") as f:
json.dump(items, f, indent=2, ensure_ascii=False)
@staticmethod
def save_split(
output_dir: str,
splits: Dict[SplitType, List[Dict]],
format: str = "jsonl"
):
"""Save split datasets to files."""
output_path = Path(output_dir)
output_path.mkdir(parents=True, exist_ok=True)
for split_type, items in splits.items():
file_path = output_path / f"{split_type.value}.jsonl"
DatasetManager.save_jsonl(str(file_path), items)
@staticmethod
def get_dataset_stats(items: List[Dict]) -> Dict:
"""Get statistics about a dataset."""
if not items:
return {"count": 0}
response_lengths = [len(item.get("response", "")) for item in items]
instruction_lengths = [len(item.get("instruction", "")) for item in items]
systems = [item.get("system", "") for item in items]
unique_systems = len(set(systems))
return {
"count": len(items),
"avg_response_length": sum(response_lengths) / len(response_lengths),
"min_response_length": min(response_lengths),
"max_response_length": max(response_lengths),
"avg_instruction_length": sum(instruction_lengths) / len(instruction_lengths),
"unique_systems": unique_systems,
}
def main():
"""Demo the data validation and split module."""
print("=" * 50)
print("📊 Data Validation and Split Demo")
print("=" * 50)
# Sample data
sample_data = [
{
"system": "Expert Python programmer",
"instruction": "Python decorator hta ya py",
"response": "# Python Decorator\n```python\ndef decorator(func):\n return func\n```"
},
{
"system": "Expert JavaScript developer",
"instruction": "JavaScript async/await hta ya",
"response": "// Async/Await\nasync function fetch() {\n const data = await fetch('/api');\n}"
},
{
"system": "Database expert",
"instruction": "SQL JOIN operations",
"response": "-- SQL JOIN\nSELECT * FROM a INNER JOIN b ON a.id = b.id;"
},
] * 10 # Multiply for demo
print(f"\n📁 Sample data: {len(sample_data)} items")
# Validate
print("\n🔍 Validating data...")
validator = DataValidator()
valid, invalid = validator.validate_dataset(sample_data)
print(f" ✓ Valid: {len(valid)}")
print(f" ✗ Invalid: {len(invalid)}")
# Split
print("\n✂️ Splitting data (70/15/15)...")
splitter = DataSplitter()
splits = splitter.hash_split(sample_data, salt="burme-coder-v1")
for split_type, items in splits.items():
print(f" {split_type.value}: {len(items)} items")
# Stats
print("\n📈 Dataset statistics:")
stats = DatasetManager.get_dataset_stats(valid)
for key, value in stats.items():
print(f" {key}: {value:.2f}" if isinstance(value, float) else f" {key}: {value}")
if __name__ == "__main__":
main()
|