V6.5-7ds cleanup: remove legacy scripts/train.py
Browse files- scripts/train.py +0 -235
scripts/train.py
DELETED
|
@@ -1,235 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""train.py — Treino de bug-detection para BiGRU_T_version (2 épocas).
|
| 3 |
-
|
| 4 |
-
Especificações do usuário atendidas:
|
| 5 |
-
- 2 épocas fixas (não mudar sem permissão)
|
| 6 |
-
- Sem dados inventados (apenas datasets do repo + HF públicos)
|
| 7 |
-
- Monitorar RAM, disco, loss, perplexidade
|
| 8 |
-
- Kill-switch: matar se loss não diminuir ou RAM explodir
|
| 9 |
-
- Estados temporários salvos durante treino e APAGADOS ao final
|
| 10 |
-
- Parâmetros do modelo aprendidos automaticamente (sem inserção manual)
|
| 11 |
-
- Ambiente otimizado para Xeon (AVX512, OpenMP, MKL)
|
| 12 |
-
- HF_TOKEN apagado ao final (se usado para datasets privados)
|
| 13 |
-
|
| 14 |
-
Uso:
|
| 15 |
-
export HF_TOKEN="hf_xxx" # opcional para datasets públicos
|
| 16 |
-
python scripts/train.py \\
|
| 17 |
-
--datasets CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1,Madras1/corpus-ptbr-v2 \\
|
| 18 |
-
--max-samples 30 \\
|
| 19 |
-
--epochs 2
|
| 20 |
-
"""
|
| 21 |
-
from __future__ import annotations
|
| 22 |
-
|
| 23 |
-
import argparse
|
| 24 |
-
import logging
|
| 25 |
-
import os
|
| 26 |
-
import sys
|
| 27 |
-
import time
|
| 28 |
-
from pathlib import Path
|
| 29 |
-
|
| 30 |
-
# Adiciona src/ ao path
|
| 31 |
-
sys.path.insert(0, str(Path(__file__).parent.parent / "src"))
|
| 32 |
-
|
| 33 |
-
# Otimização Xeon (deve vir ANTES de importar torch)
|
| 34 |
-
os.environ.setdefault("OMP_NUM_THREADS", "2")
|
| 35 |
-
os.environ.setdefault("MKL_NUM_THREADS", "2")
|
| 36 |
-
os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
|
| 37 |
-
os.environ.setdefault("TORCH_NUM_THREADS", "2")
|
| 38 |
-
|
| 39 |
-
import torch
|
| 40 |
-
torch.set_num_threads(2)
|
| 41 |
-
|
| 42 |
-
# Tenta otimizar ambiente Xeon (do módulo reaproveitado)
|
| 43 |
-
try:
|
| 44 |
-
from bigru_t.utils.xeon_runtime import optimize_xeon_environment
|
| 45 |
-
optimize_xeon_environment()
|
| 46 |
-
except Exception as e:
|
| 47 |
-
logging.warning(f"Could not apply Xeon optimization: {e}")
|
| 48 |
-
|
| 49 |
-
from bigru_t import (
|
| 50 |
-
UnifiedModel, UnifiedModelConfig, create_unified_model,
|
| 51 |
-
BiGRU_T_Trainer, TrainerConfig,
|
| 52 |
-
)
|
| 53 |
-
from bigru_t.data.streaming_datasets import stream_dataset
|
| 54 |
-
|
| 55 |
-
logging.basicConfig(
|
| 56 |
-
level=logging.INFO,
|
| 57 |
-
format="%(asctime)s [%(levelname)s] %(message)s",
|
| 58 |
-
datefmt="%H:%M:%S",
|
| 59 |
-
handlers=[logging.StreamHandler()],
|
| 60 |
-
)
|
| 61 |
-
logger = logging.getLogger(__name__)
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
def load_tokenizer(path: str):
|
| 65 |
-
"""Carrega tokenizer BBPE 16K."""
|
| 66 |
-
from tokenizers import Tokenizer
|
| 67 |
-
return Tokenizer.from_file(path)
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
def load_samples(
|
| 71 |
-
datasets: str,
|
| 72 |
-
max_samples_per_dataset: int,
|
| 73 |
-
hf_token: str | None,
|
| 74 |
-
) -> list:
|
| 75 |
-
"""Carrega amostras via streaming (reaproveita streaming_datasets_v13_9)."""
|
| 76 |
-
samples = []
|
| 77 |
-
datasets_list = [d.strip() for d in datasets.split(",") if d.strip()]
|
| 78 |
-
logger.info(f"Loading samples from {len(datasets_list)} datasets...")
|
| 79 |
-
for ds_name in datasets_list:
|
| 80 |
-
ds_start = time.time()
|
| 81 |
-
ds_count = 0
|
| 82 |
-
try:
|
| 83 |
-
for sample in stream_dataset(
|
| 84 |
-
ds_name,
|
| 85 |
-
max_samples=max_samples_per_dataset,
|
| 86 |
-
hf_token=hf_token,
|
| 87 |
-
):
|
| 88 |
-
samples.append(sample)
|
| 89 |
-
ds_count += 1
|
| 90 |
-
if ds_count >= max_samples_per_dataset:
|
| 91 |
-
break
|
| 92 |
-
if time.time() - ds_start > 300:
|
| 93 |
-
logger.warning(f" timeout em {ds_name} após {ds_count} amostras")
|
| 94 |
-
break
|
| 95 |
-
except Exception as e:
|
| 96 |
-
logger.error(f"Erro carregando {ds_name}: {e}")
|
| 97 |
-
continue
|
| 98 |
-
logger.info(f" {ds_name}: {ds_count} amostras em {time.time()-ds_start:.1f}s")
|
| 99 |
-
return samples
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
def main():
|
| 103 |
-
parser = argparse.ArgumentParser(description="BiGRU_T_version — Bug-detection training (2 epochs)")
|
| 104 |
-
parser.add_argument(
|
| 105 |
-
"--datasets",
|
| 106 |
-
type=str,
|
| 107 |
-
default="CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1,Madras1/corpus-ptbr-v2,dominguesm/restore-punctuation-ptbr-dataset",
|
| 108 |
-
help="Lista separada por vírgulas de datasets HF",
|
| 109 |
-
)
|
| 110 |
-
parser.add_argument("--max-samples", type=int, default=30, help="Amostras POR dataset (default 30)")
|
| 111 |
-
parser.add_argument("--epochs", type=int, default=2, help="Nº de épocas (default 2)")
|
| 112 |
-
parser.add_argument("--batch-size", type=int, default=1)
|
| 113 |
-
parser.add_argument("--grad-accum", type=int, default=4)
|
| 114 |
-
parser.add_argument("--lr", type=float, default=1e-3)
|
| 115 |
-
parser.add_argument("--max-seq-len", type=int, default=64)
|
| 116 |
-
parser.add_argument("--output-dir", type=str, default="/home/z/my-project/BiGRU_T_version/model_final")
|
| 117 |
-
parser.add_argument("--temp-dir", type=str, default="/home/z/my-project/BiGRU_T_version/_temp_checkpoints")
|
| 118 |
-
parser.add_argument(
|
| 119 |
-
"--tokenizer-path",
|
| 120 |
-
type=str,
|
| 121 |
-
default="/home/z/my-project/source/model_final/tokenizer/tokenizer.json",
|
| 122 |
-
)
|
| 123 |
-
parser.add_argument("--no-hypothesis", action="store_true", help="Desativar hipótese (Lema 3)")
|
| 124 |
-
parser.add_argument("--keep-temp", action="store_true", help="Manter checkpoints temporários")
|
| 125 |
-
parser.add_argument("--smoke-test", action="store_true", help="Smoke test: 5 samples, 1 epoch")
|
| 126 |
-
args = parser.parse_args()
|
| 127 |
-
|
| 128 |
-
if args.smoke_test:
|
| 129 |
-
logger.info("SMOKE TEST MODE — 5 samples/dataset, 1 epoch")
|
| 130 |
-
args.max_samples = 5
|
| 131 |
-
args.epochs = 1
|
| 132 |
-
args.grad_accum = 2
|
| 133 |
-
args.datasets = "CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1"
|
| 134 |
-
|
| 135 |
-
# HF token (opcional para datasets públicos)
|
| 136 |
-
hf_token = os.environ.get("HF_TOKEN") or None
|
| 137 |
-
|
| 138 |
-
# Configuração do modelo
|
| 139 |
-
model_config = UnifiedModelConfig(
|
| 140 |
-
vocab_size=16384,
|
| 141 |
-
d_model=128,
|
| 142 |
-
max_seq_len=args.max_seq_len,
|
| 143 |
-
# input_dim é automaticamente = d_model via __post_init__
|
| 144 |
-
# Para bug-detection, reduzimos max_modules (64 é caro)
|
| 145 |
-
max_modules=8, # 8 módulos em vez de 64
|
| 146 |
-
bigru_hidden=32,
|
| 147 |
-
d_transformer=64,
|
| 148 |
-
nhead_tu=4,
|
| 149 |
-
d_ff_tu=128,
|
| 150 |
-
output_dim_u8cell=64,
|
| 151 |
-
cache_len=16,
|
| 152 |
-
d_cache=128,
|
| 153 |
-
nhead_orq=8,
|
| 154 |
-
d_ff_orq=256,
|
| 155 |
-
trainT_dim=128,
|
| 156 |
-
nhead_train=4,
|
| 157 |
-
d_ff_train=256,
|
| 158 |
-
num_layers_train=2,
|
| 159 |
-
hypT_dim=128,
|
| 160 |
-
nhead_hyp=4,
|
| 161 |
-
d_ff_hyp=256,
|
| 162 |
-
num_layers_hyp=2,
|
| 163 |
-
num_bits=8,
|
| 164 |
-
dropout=0.1,
|
| 165 |
-
)
|
| 166 |
-
|
| 167 |
-
# Cria modelo
|
| 168 |
-
logger.info("Criando UnifiedModel...")
|
| 169 |
-
model, _ = create_unified_model(model_config)
|
| 170 |
-
params = model.count_parameters()
|
| 171 |
-
logger.info(f" params: {params['total']:,} ({params['total_M']:.2f}M)")
|
| 172 |
-
|
| 173 |
-
# Carrega tokenizer
|
| 174 |
-
tokenizer = load_tokenizer(args.tokenizer_path)
|
| 175 |
-
|
| 176 |
-
# Carrega datasets
|
| 177 |
-
samples = load_samples(args.datasets, args.max_samples, hf_token)
|
| 178 |
-
n = len(samples)
|
| 179 |
-
if n == 0:
|
| 180 |
-
logger.error("Nenhuma amostra carregada — abortando")
|
| 181 |
-
sys.exit(1)
|
| 182 |
-
logger.info(f"Total: {n} amostras carregadas")
|
| 183 |
-
|
| 184 |
-
# Split 90/10 treino/val
|
| 185 |
-
import random
|
| 186 |
-
random.seed(42)
|
| 187 |
-
random.shuffle(samples)
|
| 188 |
-
split = max(1, int(0.9 * n))
|
| 189 |
-
train_samples = samples[:split]
|
| 190 |
-
val_samples = samples[split:] or samples[:1] # fallback: 1 amostra
|
| 191 |
-
logger.info(f" train: {len(train_samples)} | val: {len(val_samples)}")
|
| 192 |
-
|
| 193 |
-
# Configuração do trainer
|
| 194 |
-
trainer_config = TrainerConfig(
|
| 195 |
-
epochs=args.epochs,
|
| 196 |
-
datasets=args.datasets,
|
| 197 |
-
max_samples_per_dataset=args.max_samples,
|
| 198 |
-
max_seq_len=args.max_seq_len,
|
| 199 |
-
per_device_batch_size=args.batch_size,
|
| 200 |
-
grad_accum=args.grad_accum,
|
| 201 |
-
lr=args.lr,
|
| 202 |
-
use_hypothesis=not args.no_hypothesis,
|
| 203 |
-
output_dir=args.output_dir,
|
| 204 |
-
temp_dir=args.temp_dir,
|
| 205 |
-
keep_temp=args.keep_temp,
|
| 206 |
-
)
|
| 207 |
-
|
| 208 |
-
# Trainer
|
| 209 |
-
trainer = BiGRU_T_Trainer(
|
| 210 |
-
model=model,
|
| 211 |
-
tokenizer=tokenizer,
|
| 212 |
-
config=trainer_config,
|
| 213 |
-
train_samples=train_samples,
|
| 214 |
-
val_samples=val_samples,
|
| 215 |
-
)
|
| 216 |
-
|
| 217 |
-
# Treina
|
| 218 |
-
result = trainer.train()
|
| 219 |
-
|
| 220 |
-
# Print resultado
|
| 221 |
-
import json
|
| 222 |
-
print("\n=== Resultado Final ===")
|
| 223 |
-
print(json.dumps(result, indent=2, default=str))
|
| 224 |
-
|
| 225 |
-
# Apaga HF token do ambiente (especificação do usuário)
|
| 226 |
-
if "HF_TOKEN" in os.environ:
|
| 227 |
-
del os.environ["HF_TOKEN"]
|
| 228 |
-
logger.info("HF_TOKEN apagado do ambiente")
|
| 229 |
-
|
| 230 |
-
# Exit code: 0 se OK, 1 se morto pelo kill-switch
|
| 231 |
-
sys.exit(0 if not result.get("killed") else 1)
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
if __name__ == "__main__":
|
| 235 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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