PowerMachine commited on
Commit
8d91687
Β·
verified Β·
1 Parent(s): 34065b1

v13.9.2-carolina: upload scripts_carolina/streaming_datasets_v13_9.py

Browse files
scripts_carolina/streaming_datasets_v13_9.py ADDED
@@ -0,0 +1,511 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """streaming_datasets_v13_9.py β€” Streaming dataset loader for v13.9.1 training.
2
+
3
+ Carrega os 9 datasets especificados pelo usuΓ‘rio via streaming (IterableDataset),
4
+ um por vez, exaustivamente dentro do limite max_samples_per_dataset.
5
+
6
+ Datasets:
7
+ 1. CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1
8
+ 2. Madras1/corpus-ptbr-v2
9
+ 3. rhaymison/multmodal_175k_portuguese
10
+ 4. TucanoBR/GigaVerbo
11
+ 5. nvidia/OpenMathReasoning
12
+ 6. MathLLMs/MathVision
13
+ 7. nvidia/OpenMathInstruct-2
14
+ 8. dominguesm/restore-punctuation-ptbr-dataset
15
+ 9. carolina-c4ai/corpus-carolina
16
+
17
+ Memory-efficient: streaming=True, no full materialization.
18
+ Returns ProcessedSample with raw_text only (tokenizer handles encoding).
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import logging
23
+ import os
24
+ import time
25
+ import traceback
26
+ from dataclasses import dataclass, field
27
+ from typing import Any, Dict, Iterator, List, Optional, Tuple
28
+
29
+ import torch
30
+
31
+ logger = logging.getLogger(__name__)
32
+
33
+ # Datasets V13.9.1 β€” exatamente os 9 especificados pelo usuΓ‘rio
34
+ DEFAULT_DATASETS = [
35
+ "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1",
36
+ "Madras1/corpus-ptbr-v2",
37
+ "rhaymison/multmodal_175k_portuguese",
38
+ "TucanoBR/GigaVerbo",
39
+ "nvidia/OpenMathReasoning",
40
+ "MathLLMs/MathVision",
41
+ "nvidia/OpenMathInstruct-2",
42
+ "dominguesm/restore-punctuation-ptbr-dataset",
43
+ "carolina-c4ai/corpus-carolina",
44
+ ]
45
+
46
+ # Dataset format descriptors β€” Lista priorizada de campos de texto
47
+ DATASET_FORMATS: Dict[str, Dict[str, Any]] = {
48
+ "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1": {
49
+ "type": "chat",
50
+ "text_fields": ["conversa", "text", "content", "conversation", "messages"],
51
+ "label_fields": [],
52
+ "split": "train",
53
+ "config": None,
54
+ },
55
+ "Madras1/corpus-ptbr-v2": {
56
+ "type": "text",
57
+ "text_fields": ["text", "content", "document", "body"],
58
+ "label_fields": [],
59
+ "split": "train",
60
+ "config": None,
61
+ },
62
+ "rhaymison/multmodal_175k_portuguese": {
63
+ "type": "multimodal",
64
+ "text_fields": ["description", "text", "question", "prompt", "instruction", "input"],
65
+ "image_fields": ["image", "image_url"],
66
+ "label_fields": ["answer", "response", "output"],
67
+ "split": "train",
68
+ "config": None,
69
+ },
70
+ "TucanoBR/GigaVerbo": {
71
+ "type": "text",
72
+ "text_fields": ["text", "content", "document", "body"],
73
+ "label_fields": [],
74
+ "split": "train",
75
+ "config": None,
76
+ },
77
+ "nvidia/OpenMathReasoning": {
78
+ "type": "math",
79
+ "text_fields": ["problem", "question", "input", "prompt"],
80
+ "label_fields": ["solution", "answer", "output", "response"],
81
+ # BUG FIX: OpenMathReasoning has splits ['cot', 'tir', 'genselect', 'additional_problems']
82
+ "split": "cot", # Use 'cot' (chain-of-thought) as primary split
83
+ "config": None,
84
+ },
85
+ "MathLLMs/MathVision": {
86
+ "type": "math_multimodal",
87
+ "text_fields": ["question", "problem", "text", "query"],
88
+ "image_fields": ["image", "image_url"],
89
+ "label_fields": ["answer", "solution", "response"],
90
+ # BUG FIX: MathVision has only 'test' and 'testmini' splits (no train)
91
+ "split": "test",
92
+ "config": None,
93
+ },
94
+ "nvidia/OpenMathInstruct-2": {
95
+ "type": "math",
96
+ "text_fields": ["problem", "question", "input", "prompt"],
97
+ "label_fields": ["solution", "answer", "output", "response"],
98
+ "split": "train",
99
+ "config": None,
100
+ },
101
+ "dominguesm/restore-punctuation-ptbr-dataset": {
102
+ "type": "punctuation",
103
+ "text_fields": ["text", "original", "unpunctuated", "input"],
104
+ "label_fields": ["punctuated", "restored", "target", "output"],
105
+ "split": "train",
106
+ "config": None,
107
+ },
108
+ "carolina-c4ai/corpus-carolina": {
109
+ "type": "text",
110
+ "text_fields": ["text", "content", "document", "body", "xml"],
111
+ "label_fields": [],
112
+ "split": "train",
113
+ "config": None,
114
+ # V13.9.2-carolina: dataset original usa script Python (nΓ£o suportado em
115
+ # datasets 5.0+). Workaround: stream_xml_gz direto via lxml.iterparse,
116
+ # sem usar o script Python. Implementado em _stream_carolina_direct().
117
+ },
118
+ }
119
+
120
+
121
+ # Lista de arquivos XML.gz do Carolina que tentaremos baixar (ordem: menores
122
+ # taxonomias primeiro para minimizar banda e RAM). Selecionamos 2 arquivos
123
+ # por taxonomia para garantir diversidade sem explodir a memΓ³ria.
124
+ CAROLINA_XML_FILES = [
125
+ # taxonomia "datasets_and_other_corpora" (DAT = pt-BR notΓ­cias)
126
+ "corpus/datasets_and_other_corpora/pt-BR/DATa.xml.gz",
127
+ "corpus/datasets_and_other_corpora/pt-BR/DATb.xml.gz",
128
+ # taxonomia "wik" (wikis)
129
+ "corpus/wik/WIKa.xml.gz",
130
+ "corpus/wik/WIKb.xml.gz",
131
+ # taxonomia "uni" (university_domains)
132
+ "corpus/uni/UNIa.xml.gz",
133
+ "corpus/uni/UNIb.xml.gz",
134
+ # taxonomia "pub" (public_domain_works)
135
+ "corpus/pub/PUBa.xml.gz",
136
+ "corpus/pub/PUBb.xml.gz",
137
+ ]
138
+
139
+
140
+ def _stream_carolina_direct(
141
+ max_samples: int,
142
+ hf_token: Optional[str] = None,
143
+ timeout_per_file: int = 60,
144
+ ) -> Iterator[Dict[str, Any]]:
145
+ """Workaround V13.9.2-carolina: carrega Carolina sem usar o script Python.
146
+
147
+ Baixa arquivos XML.gz diretamente do repo e faz parse streaming com
148
+ lxml.etree.iterparse (compatΓ­vel com datasets 5.0+). Cada <TEI> vira um
149
+ documento de texto (concatenaΓ§Γ£o dos <p> dentro de <body>).
150
+
151
+ Args:
152
+ max_samples: nΓΊmero mΓ‘ximo de amostras a retornar
153
+ hf_token: token HF opcional (dataset Γ© pΓΊblico, mas token evita rate limit)
154
+ timeout_per_file: tempo mΓ‘ximo (segundos) por arquivo XML
155
+
156
+ Yields:
157
+ dict com chave "text" (compatΓ­vel com _normalize_sample)
158
+ """
159
+ from huggingface_hub import hf_hub_download
160
+ import gzip
161
+ from lxml import etree
162
+
163
+ TEI_NS = "{http://www.tei-c.org/ns/1.0}"
164
+ BODY_P_TAG = f".//{TEI_NS}body/{TEI_NS}p"
165
+
166
+ count = 0
167
+ for xml_path in CAROLINA_XML_FILES:
168
+ if count >= max_samples:
169
+ return
170
+ try:
171
+ local_path = hf_hub_download(
172
+ repo_id="carolina-c4ai/corpus-carolina",
173
+ filename=xml_path,
174
+ repo_type="dataset",
175
+ token=hf_token,
176
+ )
177
+ except Exception as e:
178
+ logger.warning(f"Carolina: nΓ£o foi possΓ­vel baixar {xml_path}: {e}")
179
+ continue
180
+
181
+ try:
182
+ with gzip.open(local_path, "rb") as gz:
183
+ # iterparse streaming: nΓ£o carrega Γ‘rvore inteira na memΓ³ria
184
+ for _, tei in etree.iterparse(
185
+ gz, huge_tree=True, encoding="utf-8", tag=f"{TEI_NS}TEI"
186
+ ):
187
+ if count >= max_samples:
188
+ tei.clear()
189
+ return
190
+ # Extrai texto dos <p> dentro de <body>
191
+ parts = []
192
+ for p in tei.findall(BODY_P_TAG):
193
+ if p.text:
194
+ parts.append(p.text)
195
+ text = " ".join(parts).strip()
196
+ if text and len(text) >= 10:
197
+ yield {"text": text, "meta": ""}
198
+ tei.clear() # libera memΓ³ria da Γ‘rvore TEI
199
+ count += 1
200
+ except Exception as e:
201
+ logger.warning(f"Carolina: erro processando {xml_path}: {e}")
202
+ continue
203
+
204
+ logger.info(f"Carolina: streamou {count} amostras no total")
205
+
206
+
207
+ @dataclass
208
+ class ProcessedSample:
209
+ """Uma amostra processada: texto bruto + metadados."""
210
+ raw_text: str
211
+ dataset_name: str
212
+ sample_idx: int
213
+ text_field: str = ""
214
+ label_text: str = ""
215
+
216
+
217
+ def _extract_field(sample: Dict[str, Any], candidate_fields: List[str]) -> Optional[str]:
218
+ """Extrai texto da primeira field disponΓ­vel no sample."""
219
+ for field_name in candidate_fields:
220
+ if field_name in sample:
221
+ val = sample[field_name]
222
+ if val is None:
223
+ continue
224
+ if isinstance(val, str):
225
+ if val.strip():
226
+ return val
227
+ elif isinstance(val, list):
228
+ # Para chat: messages = [{role, content}, ...]
229
+ parts = []
230
+ for msg in val:
231
+ if isinstance(msg, dict):
232
+ role = msg.get("role", "")
233
+ content = msg.get("content", "")
234
+ if isinstance(content, str) and content.strip():
235
+ parts.append(f"{role}: {content}")
236
+ elif isinstance(msg, str) and msg.strip():
237
+ parts.append(msg)
238
+ if parts:
239
+ return "\n".join(parts)
240
+ elif isinstance(val, dict):
241
+ # Pode ser nested
242
+ text = val.get("text") or val.get("content") or val.get("body")
243
+ if isinstance(text, str) and text.strip():
244
+ return text
245
+ return None
246
+
247
+
248
+ def _normalize_sample(sample: Dict[str, Any], dataset_name: str, idx: int) -> Optional[ProcessedSample]:
249
+ """Normaliza uma amostra bruta em ProcessedSample."""
250
+ fmt = DATASET_FORMATS.get(dataset_name, {})
251
+ text_fields = fmt.get("text_fields", ["text"])
252
+ label_fields = fmt.get("label_fields", [])
253
+
254
+ text = _extract_field(sample, text_fields)
255
+ if not text or len(text.strip()) < 10: # skip very short
256
+ return None
257
+
258
+ label = ""
259
+ if label_fields:
260
+ label = _extract_field(sample, label_fields) or ""
261
+
262
+ # Se tem label, concatena como contexto de treino
263
+ full_text = text
264
+ if label:
265
+ full_text = f"{text}\n{label}"
266
+
267
+ return ProcessedSample(
268
+ raw_text=full_text,
269
+ dataset_name=dataset_name,
270
+ sample_idx=idx,
271
+ text_field=text_fields[0] if text_fields else "",
272
+ label_text=label,
273
+ )
274
+
275
+
276
+ def _load_dataset_streaming(
277
+ dataset_name: str,
278
+ split: str = "train",
279
+ config: Optional[str] = None,
280
+ hf_token: Optional[str] = None,
281
+ ):
282
+ """Carrega dataset em modo streaming.
283
+
284
+ BUG FIX V13.9.1: Removido trust_remote_code (deprecated).
285
+ Se o dataset nΓ£o carregar com split especificado, tenta 'train' como fallback.
286
+ BUG FIX V13.9.2: Adicionado fallback para datasets com script (carolina-c4ai).
287
+ """
288
+ from datasets import load_dataset
289
+
290
+ # Lista de splits para tentar, em ordem
291
+ splits_to_try = [split]
292
+ if split != "train":
293
+ splits_to_try.append("train")
294
+ # Adiciona outros splits comuns
295
+ for s in ["test", "validation", "cot", "tir"]:
296
+ if s not in splits_to_try:
297
+ splits_to_try.append(s)
298
+
299
+ fmt = DATASET_FORMATS.get(dataset_name, {})
300
+ fallback_name = fmt.get("fallback")
301
+ datasets_to_try = [dataset_name]
302
+ if fallback_name:
303
+ datasets_to_try.append(fallback_name)
304
+
305
+ for try_ds_name in datasets_to_try:
306
+ for try_split in splits_to_try:
307
+ try:
308
+ if config:
309
+ ds = load_dataset(
310
+ try_ds_name, config, split=try_split, streaming=True,
311
+ token=hf_token,
312
+ )
313
+ else:
314
+ ds = load_dataset(
315
+ try_ds_name, split=try_split, streaming=True,
316
+ token=hf_token,
317
+ )
318
+ logger.info(f"Loaded {try_ds_name} split={try_split}")
319
+ return ds
320
+ except Exception as e:
321
+ err_str = str(e).lower()
322
+ # If "Bad split" error, try next split
323
+ if "bad split" in err_str or "available splits" in err_str:
324
+ logger.info(f" Split {try_split} not available for {try_ds_name}, trying next")
325
+ continue
326
+ # If "scripts no longer supported", try next dataset (fallback)
327
+ if "scripts are no longer supported" in err_str and fallback_name:
328
+ logger.info(f" {try_ds_name} uses script β€” trying fallback {fallback_name}")
329
+ break
330
+ # For other errors, log and try next split
331
+ logger.warning(f"Failed to load {try_ds_name} split={try_split}: {str(e)[:120]}")
332
+ continue
333
+
334
+ logger.warning(f"All split attempts failed for {dataset_name} (will be skipped)")
335
+ return None
336
+
337
+
338
+ def stream_dataset(
339
+ dataset_name: str,
340
+ max_samples: int = 500,
341
+ hf_token: Optional[str] = None,
342
+ ) -> Iterator[ProcessedSample]:
343
+ """Faz streaming de um dataset, retornando atΓ© max_samples amostras.
344
+
345
+ Args:
346
+ dataset_name: nome do dataset no HuggingFace
347
+ max_samples: nΓΊmero mΓ‘ximo de amostras a retornar
348
+ hf_token: token HF opcional
349
+
350
+ Yields:
351
+ ProcessedSample
352
+ """
353
+ fmt = DATASET_FORMATS.get(dataset_name)
354
+ if fmt is None:
355
+ logger.error(f"Unknown dataset: {dataset_name}")
356
+ return
357
+
358
+ # ── V13.9.2-carolina: bypass do script Python ─────────────────────────
359
+ # O dataset carolina-c4ai/corpus-carolina usa um script Python como loader,
360
+ # que nΓ£o Γ© suportado por datasets 5.0+. Streamamos os XML.gz diretamente.
361
+ if dataset_name == "carolina-c4ai/corpus-carolina":
362
+ logger.info(f"Carolina: usando carregador direto (bypass do script Python)")
363
+ count = 0
364
+ try:
365
+ for raw_sample in _stream_carolina_direct(
366
+ max_samples=max_samples, hf_token=hf_token
367
+ ):
368
+ processed = _normalize_sample(raw_sample, dataset_name, count)
369
+ if processed is not None:
370
+ yield processed
371
+ count += 1
372
+ except Exception as e:
373
+ logger.warning(f"Carolina direct stream error at sample {count}: {e}")
374
+ return
375
+ logger.info(f"Streamed {count} samples from {dataset_name} (direct XML)")
376
+ return
377
+
378
+ ds = _load_dataset_streaming(
379
+ dataset_name,
380
+ split=fmt.get("split", "train"),
381
+ config=fmt.get("config"),
382
+ hf_token=hf_token,
383
+ )
384
+ if ds is None:
385
+ return
386
+
387
+ count = 0
388
+ try:
389
+ for idx, sample in enumerate(ds):
390
+ if count >= max_samples:
391
+ break
392
+ processed = _normalize_sample(sample, dataset_name, idx)
393
+ if processed is not None:
394
+ yield processed
395
+ count += 1
396
+ except Exception as e:
397
+ logger.warning(f"Error streaming {dataset_name} at sample {idx}: {e}")
398
+ return
399
+
400
+ logger.info(f"Streamed {count} samples from {dataset_name}")
401
+
402
+
403
+ def stream_all_datasets(
404
+ datasets: Optional[List[str]] = None,
405
+ max_samples_per_dataset: int = 500,
406
+ hf_token: Optional[str] = None,
407
+ ) -> Iterator[ProcessedSample]:
408
+ """Faz streaming sequencial de mΓΊltiplos datasets.
409
+
410
+ Args:
411
+ datasets: lista de nomes (default: DEFAULT_DATASETS)
412
+ max_samples_per_dataset: limite por dataset
413
+ hf_token: token HF opcional
414
+
415
+ Yields:
416
+ ProcessedSample
417
+ """
418
+ if datasets is None:
419
+ datasets = DEFAULT_DATASETS
420
+
421
+ for ds_name in datasets:
422
+ logger.info(f"Starting dataset: {ds_name}")
423
+ yield from stream_dataset(
424
+ ds_name,
425
+ max_samples=max_samples_per_dataset,
426
+ hf_token=hf_token,
427
+ )
428
+
429
+
430
+ def collate_samples_to_tensors(
431
+ samples: List[ProcessedSample],
432
+ tokenizer,
433
+ max_seq_len: int = 64,
434
+ pad_token_id: int = 0,
435
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
436
+ """Converte lista de ProcessedSample em tensors para treino.
437
+
438
+ BUG FIX V13.9.1: Tokenizer.encode() retorna 'Encoding' object, nΓ£o list.
439
+ Use .ids attribute to get token IDs.
440
+
441
+ Returns:
442
+ input_ids: (B, T)
443
+ attention_mask: (B, T)
444
+ labels: (B, T) β€” same as input_ids (LM training)
445
+ """
446
+ batch_input_ids = []
447
+ batch_attn_mask = []
448
+
449
+ for sample in samples:
450
+ # Tokenize
451
+ encoding = tokenizer.encode(sample.raw_text, add_special_tokens=True)
452
+
453
+ # BUG FIX: Handle both `tokenizers.Encoding` and `transformers` tokenizer outputs
454
+ if hasattr(encoding, 'ids'):
455
+ tokens = encoding.ids # tokenizers library
456
+ elif isinstance(encoding, list):
457
+ tokens = encoding # already a list of ints
458
+ elif hasattr(encoding, 'input_ids'):
459
+ tokens = encoding.input_ids # transformers BatchEncoding
460
+ else:
461
+ tokens = list(encoding) # fallback
462
+
463
+ # Truncate to max_seq_len
464
+ if len(tokens) > max_seq_len:
465
+ tokens = tokens[:max_seq_len]
466
+ # Pad
467
+ attn_mask = [1] * len(tokens) + [0] * (max_seq_len - len(tokens))
468
+ tokens = list(tokens) + [pad_token_id] * (max_seq_len - len(tokens))
469
+ batch_input_ids.append(tokens)
470
+ batch_attn_mask.append(attn_mask)
471
+
472
+ input_ids = torch.tensor(batch_input_ids, dtype=torch.long)
473
+ attention_mask = torch.tensor(batch_attn_mask, dtype=torch.long)
474
+ labels = input_ids.clone()
475
+
476
+ return input_ids, attention_mask, labels
477
+
478
+
479
+ # ═══════════════════════════════════════════════════════════════════════════
480
+ # Self-test (NÃO enviar para HuggingFace)
481
+ # ═══════════════════════════════════════════════════════════════════════════
482
+ if __name__ == "__main__":
483
+ print("=== Streaming Datasets V13.9.1 Self-Test ===\n")
484
+
485
+ # Test 1: Test field extraction
486
+ print("Test 1: Field extraction")
487
+ sample_chat = {
488
+ "messages": [
489
+ {"role": "user", "content": "OlΓ‘"},
490
+ {"role": "assistant", "content": "Como posso ajudar?"},
491
+ ]
492
+ }
493
+ text = _extract_field(sample_chat, ["messages", "text"])
494
+ print(f" Chat text: {text!r}")
495
+ assert text and "OlΓ‘" in text, "Field extraction failed for chat"
496
+
497
+ sample_text = {"text": "Hello world"}
498
+ text = _extract_field(sample_text, ["text", "content"])
499
+ assert text == "Hello world"
500
+ print(f" Text field: {text!r}")
501
+ print(f" OK\n")
502
+
503
+ # Test 2: Test list of datasets
504
+ print("Test 2: Dataset list")
505
+ print(f" Configured datasets ({len(DEFAULT_DATASETS)}):")
506
+ for i, ds in enumerate(DEFAULT_DATASETS, 1):
507
+ print(f" {i}. {ds}")
508
+ assert len(DEFAULT_DATASETS) == 9
509
+ print(f" OK\n")
510
+
511
+ print("=== ALL STREAMING TESTS PASSED ===")