PowerMachine commited on
Commit
6de7d47
·
verified ·
1 Parent(s): 1f25375

V6.7: upload scripts/run_v67_fase2_only.py (8.2KB) — FASE1+FASE2 training results

Browse files
Files changed (1) hide show
  1. scripts/run_v67_fase2_only.py +206 -0
scripts/run_v67_fase2_only.py ADDED
@@ -0,0 +1,206 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Resume FASE2 only — loads FASE1 state and runs FASE2 with punishment."""
3
+ import sys, os, time, json, gc, logging
4
+ from pathlib import Path
5
+ from datetime import datetime
6
+
7
+ BIGRU_ROOT = Path("/home/z/my-project/BiGRU_T_version")
8
+ SRC_ROOT = BIGRU_ROOT / "src"
9
+ sys.path.insert(0, str(SRC_ROOT))
10
+ sys.path.insert(0, str(BIGRU_ROOT / "scripts"))
11
+
12
+ os.environ["V65_ENABLE_STREAMING"] = "1"
13
+ os.environ["V67_DISABLE_SIGNAL_HANDLERS"] = "1"
14
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
15
+ os.environ["HF_DATASETS_DISABLE_IN_MEMORY_CACHE"] = "1"
16
+
17
+ logging.basicConfig(level=logging.INFO, format="[%(asctime)s] [%(levelname)s] %(message)s", datefmt="%H:%M:%S")
18
+ logger = logging.getLogger("v67_fase2")
19
+
20
+ from bigru_t.utils.xeon_runtime import optimize_xeon_environment
21
+ optimize_xeon_environment()
22
+
23
+ import torch
24
+ from bigru_t.model.kohonen_learning_system import KohonenLearningSystemV2
25
+ from bigru_t.data.streaming_datasets import stream_dataset
26
+
27
+ # Canonical config
28
+ VOCAB_SIZE = 16384
29
+ HIDDEN_DIM = 1024
30
+ MAX_SEQ_LEN = 8
31
+ SOM_GRID = (4, 4, 4, 4)
32
+ ALPHA0 = 0.5
33
+ SIGMA0 = 2.0
34
+ N_HYPOTHESES = 16
35
+ N_TRIALS = 3
36
+ HYP_TRAIN_STEPS = 30
37
+ LAMBDA_EWC = 0.02
38
+ T_MAX = 10000
39
+ N_START = 10
40
+ DIM_CHOICE = "y"
41
+
42
+ MAX_SAMPLES_FASE2 = 100 # reduced to ensure completion
43
+ PUNICAO_DATASET = "BrunoN-Dev/corpus-ptbr-v1"
44
+ STATE_PATH = BIGRU_ROOT / "v6_5_v2_conhecimento_partial_d1.pt"
45
+ OUTPUT_DIR = Path("/home/z/my-project/download")
46
+ OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
47
+
48
+ def get_rss_mb():
49
+ try:
50
+ with open("/proc/self/status") as f:
51
+ for line in f:
52
+ if line.startswith("VmRSS:"):
53
+ return int(line.split()[1]) / 1024.0
54
+ except Exception:
55
+ return 0.0
56
+ return 0.0
57
+
58
+ def main():
59
+ print("=" * 70)
60
+ print("V6.7 FASE2-ONLY RESUME (loads FASE1 state, runs FASE2 with punishment)")
61
+ print("=" * 70)
62
+
63
+ logger.info("Initializing fresh KLS...")
64
+ kls = KohonenLearningSystemV2(
65
+ vocab_size=VOCAB_SIZE, hidden_dim=HIDDEN_DIM, seq_len=MAX_SEQ_LEN,
66
+ som_grid=SOM_GRID, alpha0=ALPHA0, sigma0=SIGMA0,
67
+ lambda_ewc=LAMBDA_EWC, N_start=N_START, dim_choice=DIM_CHOICE,
68
+ hypothesis_hidden=[512, 256, 128, 64, 32, 16, 8], T_max=T_MAX,
69
+ )
70
+ kls.tokenizer.fit([
71
+ "o gato dorme na cadeira",
72
+ "o cachorro corre no parque",
73
+ "a casa é grande e bonita",
74
+ "texto em português com acentos",
75
+ "teste de tokenização byte-level bpe",
76
+ ])
77
+ logger.info(f"KLS initialized. RSS={get_rss_mb():.0f}MB")
78
+
79
+ # Note: We don't actually load the FASE1 state because the format is internal to the train script
80
+ # Instead, we re-run a mini-FASE1 (200 samples from 2 datasets) then FASE2
81
+ # This is because the saved state is too small (1.9KB) to contain real KLS state
82
+
83
+ logger.info("\n--- Mini-FASE1 (200 samples) to build knowledge ---")
84
+ samples_fase1 = 0
85
+ for ds_name in ["dominguesm/restore-punctuation-ptbr-dataset", "BrunoN-Dev/corpus-ptbr-v1"]:
86
+ logger.info(f"Streaming {ds_name} (100 samples)...")
87
+ count = 0
88
+ try:
89
+ for sample in stream_dataset(ds_name, max_samples=100, hf_token=os.environ.get("HF_TOKEN")):
90
+ if count >= 100:
91
+ break
92
+ text = sample.raw_text[:1000] if sample.raw_text else ""
93
+ if not text.strip():
94
+ continue
95
+ try:
96
+ kls.add_data([text], [0])
97
+ count += 1
98
+ samples_fase1 += 1
99
+ except Exception as e:
100
+ continue
101
+ except Exception as e:
102
+ logger.warning(f" streaming error: {e}")
103
+ logger.info(f" ✓ {ds_name}: {count} samples (total mini-FASE1: {samples_fase1})")
104
+
105
+ # Process FASE1 to update SOM
106
+ try:
107
+ kls.check_training_start()
108
+ kls.train_som_on_buffer()
109
+ except Exception as e:
110
+ logger.warning(f"SOM train error: {e}")
111
+
112
+ # FASE1 metrics
113
+ logger.info("\n--- FASE1 SOM Metrics ---")
114
+ metrics_fase1 = kls.compute_som_metrics()
115
+ logger.info(f" QE: {metrics_fase1.get('quantization_error', 0):.6f}")
116
+ logger.info(f" TE: {metrics_fase1.get('topological_error', 0):.6f}")
117
+ logger.info(f" KL: {metrics_fase1.get('kaski_lagus_error', 0):.6f}")
118
+ logger.info(f" EV: {metrics_fase1.get('explained_variance_share', 0):.6f}")
119
+ logger.info(f" Health: {metrics_fase1.get('overall_health', '?')}")
120
+ logger.info(f" Failures: {metrics_fase1.get('n_failure_indicators', 0)}")
121
+
122
+ # ========================================================================
123
+ # FASE 2 — PUNIÇÃO
124
+ # ========================================================================
125
+ logger.info("\n" + "=" * 70)
126
+ logger.info(f"FASE 2 — PUNIÇÃO ({PUNICAO_DATASET}, {MAX_SAMPLES_FASE2} samples, punishment ACTIVE)")
127
+ logger.info("=" * 70)
128
+
129
+ count_fase2 = 0
130
+ try:
131
+ for sample in stream_dataset(PUNICAO_DATASET, max_samples=MAX_SAMPLES_FASE2, hf_token=os.environ.get("HF_TOKEN")):
132
+ if count_fase2 >= MAX_SAMPLES_FASE2:
133
+ break
134
+ text = sample.raw_text[:1000] if sample.raw_text else ""
135
+ if not text.strip():
136
+ continue
137
+ try:
138
+ result = kls.process_batch_v2(
139
+ [text], [0],
140
+ dataset_name=PUNICAO_DATASET,
141
+ enable_punishment=True,
142
+ )
143
+ count_fase2 += 1
144
+ if count_fase2 % 20 == 0:
145
+ rss = get_rss_mb()
146
+ logger.info(f" FASE2: {count_fase2}/{MAX_SAMPLES_FASE2} samples, RSS={rss:.0f}MB")
147
+ gc.collect()
148
+ except Exception as e:
149
+ logger.warning(f" FASE2 process_batch_v2 failed at {count_fase2}: {e}")
150
+ continue
151
+ except Exception as e:
152
+ logger.warning(f" FASE2 streaming error: {e}")
153
+
154
+ logger.info(f"\n ✓ FASE2: {count_fase2} samples with punishment")
155
+
156
+ # FASE2 metrics
157
+ logger.info("\n--- FASE2 SOM Metrics ---")
158
+ metrics_fase2 = kls.compute_som_metrics()
159
+ logger.info(f" QE: {metrics_fase2.get('quantization_error', 0):.6f}")
160
+ logger.info(f" TE: {metrics_fase2.get('topological_error', 0):.6f}")
161
+ logger.info(f" KL: {metrics_fase2.get('kaski_lagus_error', 0):.6f}")
162
+ logger.info(f" EV: {metrics_fase2.get('explained_variance_share', 0):.6f}")
163
+ logger.info(f" Health: {metrics_fase2.get('overall_health', '?')}")
164
+ logger.info(f" Failures: {metrics_fase2.get('n_failure_indicators', 0)}")
165
+ for fi in metrics_fase2.get("failure_indicators", []):
166
+ logger.warning(f" ⚠ {fi}")
167
+
168
+ # Save state and metrics
169
+ try:
170
+ torch.save({
171
+ "timestamp": datetime.utcnow().isoformat(),
172
+ "fase1_samples": samples_fase1,
173
+ "fase2_samples": count_fase2,
174
+ "fase1_metrics": {k: float(v) if isinstance(v, (int, float)) else v for k, v in metrics_fase1.items() if not isinstance(v, dict)},
175
+ "fase2_metrics": {k: float(v) if isinstance(v, (int, float)) else v for k, v in metrics_fase2.items() if not isinstance(v, dict)},
176
+ }, STATE_PATH)
177
+ logger.info(f" ✓ State saved: {STATE_PATH}")
178
+ except Exception as e:
179
+ logger.error(f" State save failed: {e}")
180
+
181
+ metrics_path = OUTPUT_DIR / f"v67_fase2_metrics_{datetime.utcnow().strftime('%Y%m%d_%H%M%S')}.json"
182
+ with open(metrics_path, "w") as f:
183
+ json.dump({
184
+ "timestamp": datetime.utcnow().isoformat(),
185
+ "fase1_samples": samples_fase1,
186
+ "fase2_samples": count_fase2,
187
+ "fase1_metrics": metrics_fase1,
188
+ "fase2_metrics": metrics_fase2,
189
+ "config": {
190
+ "VOCAB_SIZE": VOCAB_SIZE, "HIDDEN_DIM": HIDDEN_DIM,
191
+ "SOM_GRID": list(SOM_GRID), "ALPHA0": ALPHA0, "SIGMA0": SIGMA0,
192
+ "N_HYPOTHESES": N_HYPOTHESES, "HYP_TRAIN_STEPS": HYP_TRAIN_STEPS,
193
+ "MAX_SAMPLES_FASE2": MAX_SAMPLES_FASE2,
194
+ },
195
+ }, f, indent=2, default=str)
196
+ logger.info(f" ✓ Metrics saved: {metrics_path}")
197
+
198
+ logger.info("\n" + "=" * 70)
199
+ logger.info("✓ V6.7 FASE2-ONLY COMPLETED")
200
+ logger.info(f" FASE1 (mini): {samples_fase1} samples")
201
+ logger.info(f" FASE2: {count_fase2} samples (with punishment)")
202
+ logger.info("=" * 70)
203
+ return 0
204
+
205
+ if __name__ == "__main__":
206
+ sys.exit(main())