PowerMachine commited on
Commit
831f5ad
·
verified ·
1 Parent(s): d093cf2

V6.5-7ds cleanup: remove legacy scripts/upload_v6_1_resilient.py

Browse files
Files changed (1) hide show
  1. scripts/upload_v6_1_resilient.py +0 -251
scripts/upload_v6_1_resilient.py DELETED
@@ -1,251 +0,0 @@
1
- """upload_v6_1_resilient.py — Upload resiliente V6.1 para o HF.
2
-
3
- Estratégia (igual V5/V6):
4
- - HfApi.upload_folder (single commit lógico)
5
- - allow_patterns: *.py + *.json + *.md + *.txt + tokenizer.json
6
- - ignore_patterns: __pycache__, *.pyc, _test_*, *.safetensors, *.bin, *.pt, *.pth
7
- - hf_transfer habilitado
8
-
9
- V6.1 inclui (NOVO vs V6):
10
- - src/bigru_t/model/orq_cell.py (V6.1 — PGVector-like lookup +
11
- neuron_filled_mask + fill_missing_neurons_random)
12
- - src/bigru_t/training/ewc.py (V6.1 — skip_som_filled_neurons +
13
- fisher_neuron_mask + classic Fisher masked for orq_cell.neuron_cache)
14
- - scripts/train_v6_1.py (NOVO — 5 datasets × 10 samples + PGVector
15
- capture + EWC V6.1 math upgrade)
16
- - v6_1_report.json (relatório do treino V6.1)
17
-
18
- Uso:
19
- export HF_TOKEN="hf_xxx..." # env var temporária, será apagada após upload
20
- python /home/z/my-project/scripts/upload_v6_1_resilient.py
21
- """
22
- from __future__ import annotations
23
-
24
- import os
25
- import sys
26
- import time
27
- import json
28
- from pathlib import Path
29
-
30
- os.environ.setdefault("HF_HUB_ENABLE_HF_TRANSFER", "1")
31
- os.environ.setdefault("HF_HUB_ETAG_TIMEOUT", "60")
32
- os.environ.setdefault("PYTHONUNBUFFERED", "1")
33
- os.environ.setdefault("OMP_NUM_THREADS", "2")
34
- os.environ.setdefault("TOKENIZERS_PARALLELISM", "true")
35
-
36
- from huggingface_hub import HfApi # noqa: E402
37
-
38
- REPO_ID = "PowerMachine/BiGRU_T_version"
39
- LOCAL_DIR = "/home/z/my-project/BiGRU_T_version"
40
- COMMIT_MESSAGE = """V6.1: PGVector-like lookup + EWC math upgrade + 5 datasets x 10 samples
41
-
42
- V6.1 improvements:
43
- - orq_cell.py: pgvector_lookup() returns COMPLETE/INCOMPLETE/MISSING
44
- based on neuron_filled_mask + cosine similarity thresholds
45
- - orq_cell.py: neuron_filled_mask buffer (8 bool) tracks SOM-filled
46
- neurons; fill_missing_neurons_random() fills unfilled with random
47
- values (user requirement: "atribuir valores aleatórios aos
48
- parâmetros faltantes")
49
- - ewc.py: skip_som_filled_neurons=True (default) - EWC does NOT
50
- compute Fisher for neurons already consolidated by SOM (user
51
- requirement: "EWC mathematically improved to not use weights
52
- already existing in SOM")
53
- - ewc.py: classic Fisher for orq_cell.neuron_cache also masked
54
- (avoids double-penalization of the same parameter)
55
- - ewc.py: short-circuit when all SOM neurons filled (topology
56
- already preserved by SOM Gaussian neighborhood)
57
- - train_v6_1.py: 5 datasets from streaming_datasets.py x 10 samples
58
- each (50 total, 2 epochs, BATCH_SIZE=4) with synthetic fallback
59
- - train_v6_1.py: PGVector status captured per step (COMPLETE/
60
- INCOMPLETE/MISSING distribution tracked over training)
61
- - train_v6_1.py: EWC V6.1 metrics (n_masked_som_neurons tracked)
62
- - xeon_runtime.py V6 always active (AVX512 + AMX_INT8 + IPEX + OneDNN)
63
- - FP16 benchmark: 1.94 TFLOPS on this host
64
-
65
- V6.1 training results:
66
- - 50 samples (5 datasets x 10), 20 steps, 2 epochs
67
- - final_train_loss=8.96, final_val_loss=9.01
68
- - 0 alerts, RSS stable 872MB
69
- - Kohonen SOM: sigma 1.38->0.30, alpha 0.45->0.05 (full schedule)
70
- - 8/8 neurons filled (filled_ratio=100%)
71
- - PGVector: epoch 1 had 1 MISSING + 9 INCOMPLETE; epoch 2 all 10
72
- INCOMPLETE (no COMPLETE yet - sim < 0.6 threshold)
73
- - EWC V6.1: n_masked_som_neurons=8 (all SOM neurons filled, EWC
74
- contributes 0 to loss - math upgrade working as designed)
75
- - final coverage=1.000 (all inputs have similar neuron in map)
76
-
77
- User requirement satisfied:
78
- - "os níveis de treinamento e o de hipótese precisam verificar se
79
- o mapa já possui aquela informação" -> pgvector_lookup at every
80
- training step (and could be activated at hypothesis level)
81
- - "Elastic Weight Consolidation que deve ser matematicamente
82
- aprimorado para não usar pesos já existentes em SOM" -> skip mask
83
- zeros Fisher for SOM-filled neurons (classic + Kohonen)
84
- - "ativar xeon_runtime.py" -> V6 always active
85
- - "capturar métricas no re-treino de datasets 10 em 10 samples
86
- diversos (5 datasets streaming_datasets.py)" -> 5x10=50 samples,
87
- metrics captured per step (12/12 + Kohonen + MTP + EWC + PGVector)
88
- """
89
-
90
- # Arquivos críticos V6.1 a serem verificados pós-upload
91
- CRITICAL_FILES_V6_1 = [
92
- "src/bigru_t/model/orq_cell.py",
93
- "src/bigru_t/training/ewc.py",
94
- "src/bigru_t/training/mtp.py",
95
- "src/bigru_t/training/dynamic_repetition_penalty.py",
96
- "src/bigru_t/training/data_augmentation.py",
97
- "src/bigru_t/training/rlhf_mapping.py",
98
- "src/bigru_t/attention/window_context.py",
99
- "src/bigru_t/reasoning/thinking.py",
100
- "src/bigru_t/tools/tool_mutation.py",
101
- "src/bigru_t/tools/tool_cache.py",
102
- "src/bigru_t/tools/tool_agent.py",
103
- "src/bigru_t/integrations/langchain_compat.py",
104
- "src/bigru_t/pipeline/optimized_pipeline.py",
105
- "src/bigru_t/utils/xeon_runtime.py",
106
- "v6_report.json",
107
- "v6_1_report.json",
108
- ]
109
-
110
- ALLOW_PATTERNS = [
111
- "*.py", "*.json", "*.md", "*.txt",
112
- "tokenizer.json",
113
- ]
114
-
115
- IGNORE_PATTERNS = [
116
- "__pycache__", "*.pyc", "_test_*", "tests/",
117
- "*.safetensors", "*.bin", "*.pt", "*.pth",
118
- "*.so", "*.dylib", "*.dll",
119
- ]
120
-
121
-
122
- def main():
123
- print("=" * 72)
124
- print(f"UPLOAD V6.1 RESILIENT — {REPO_ID}")
125
- print("=" * 72)
126
-
127
- token = os.environ.get("HF_TOKEN")
128
- if not token:
129
- print("[ERROR] HF_TOKEN não definido. Export HF_TOKEN=hf_xxx antes de rodar.")
130
- sys.exit(1)
131
- print(f"[INFO] HF_TOKEN presente (length={len(token)}, prefix={token[:5]}...)")
132
-
133
- local_dir = Path(LOCAL_DIR)
134
- if not local_dir.exists():
135
- print(f"[ERROR] Diretório local não existe: {local_dir}")
136
- sys.exit(1)
137
-
138
- # Lista arquivos a enviar
139
- files_to_upload = []
140
- for pattern in ALLOW_PATTERNS:
141
- files_to_upload.extend(local_dir.rglob(pattern))
142
- # Filtra ignorados
143
- files_filtered = []
144
- for f in files_to_upload:
145
- rel = f.relative_to(local_dir)
146
- rel_str = str(rel)
147
- if any(p in rel_str for p in IGNORE_PATTERNS if "*" not in p):
148
- continue
149
- if any(rel_str.endswith(p.replace("*", "")) for p in IGNORE_PATTERNS if "*" in p):
150
- continue
151
- files_filtered.append(rel_str)
152
- files_filtered = sorted(set(files_filtered))
153
- print(f"[INFO] {len(files_filtered)} arquivos locais a enviar")
154
- print(f"[INFO] Primeiros 15 arquivos:")
155
- for f in files_filtered[:15]:
156
- size = (local_dir / f).stat().st_size
157
- print(f" - {f} ({size} bytes)")
158
- if len(files_filtered) > 15:
159
- print(f" ... e mais {len(files_filtered) - 15} arquivos")
160
-
161
- api = HfApi(token=token)
162
-
163
- # Verifica repo
164
- print(f"\n[INFO] Verificando repositório {REPO_ID}…")
165
- try:
166
- api.repo_info(REPO_ID, repo_type="model")
167
- print("[INFO] Repo já existia")
168
- except Exception:
169
- print("[INFO] Criando repo...")
170
- api.create_repo(REPO_ID, repo_type="model", private=False)
171
- print("[INFO] Repo criado")
172
-
173
- # Lista arquivos atuais
174
- try:
175
- files_in_repo = [f.rfilename for f in api.list_repo_tree(REPO_ID, repo_type="model", recursive=True)]
176
- print(f"[INFO] {len(files_in_repo)} arquivos no repo ANTES do upload")
177
- except Exception:
178
- files_in_repo = []
179
-
180
- # Upload folder (single commit)
181
- print("\n" + "=" * 72)
182
- print("[INFO] Iniciando upload_folder (single commit)…")
183
- print("=" * 72)
184
- t0 = time.perf_counter()
185
- commit_info = api.upload_folder(
186
- folder_path=str(local_dir),
187
- repo_id=REPO_ID,
188
- repo_type="model",
189
- commit_message=COMMIT_MESSAGE,
190
- allow_patterns=ALLOW_PATTERNS,
191
- ignore_patterns=IGNORE_PATTERNS,
192
- )
193
- elapsed = time.perf_counter() - t0
194
- print(f"[INFO] upload_folder concluído em {elapsed:.2f}s")
195
- print(f"[INFO] commit_info: {commit_info.commit_url if hasattr(commit_info, 'commit_url') else commit_info}")
196
-
197
- # Aguarda indexação
198
- print("\n[INFO] Aguardando 3s para o HF indexar…")
199
- time.sleep(3)
200
-
201
- # Verifica arquivos críticos V6
202
- try:
203
- files_in_repo_after = [f.rfilename for f in api.list_repo_tree(REPO_ID, repo_type="model", recursive=True)]
204
- print(f"[INFO] {len(files_in_repo_after)} arquivos no repo DEPOIS do upload")
205
- new_files = set(files_in_repo_after) - set(files_in_repo)
206
- print(f"[INFO] Novos arquivos: {len(new_files)}")
207
- overwritten = set(files_in_repo) & set(files_in_repo_after)
208
- print(f"[INFO] Arquivos sobrescritos: {len(overwritten)}")
209
- except Exception as e:
210
- print(f"[WARN] Não foi possível listar arquivos pós-upload: {e}")
211
- files_in_repo_after = []
212
-
213
- print(f"\n[INFO] Verificação de arquivos críticos V6 no repo:")
214
- all_critical_ok = True
215
- for cf in CRITICAL_FILES_V6_1:
216
- if cf in files_in_repo_after:
217
- print(f" ✓ {cf}")
218
- else:
219
- print(f" ✗ {cf} (NÃO ENCONTRADO)")
220
- all_critical_ok = False
221
-
222
- # Salva relatório
223
- report_path = local_dir / "v6_1_upload_report.json"
224
- upload_report = {
225
- "version": "V6",
226
- "timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
227
- "repo_id": REPO_ID,
228
- "commit_url": str(commit_info.commit_url) if hasattr(commit_info, "commit_url") else str(commit_info),
229
- "elapsed_seconds": elapsed,
230
- "n_files_uploaded": len(files_filtered),
231
- "n_files_in_repo_before": len(files_in_repo),
232
- "n_files_in_repo_after": len(files_in_repo_after),
233
- "new_files": list(new_files) if 'new_files' in locals() else [],
234
- "critical_files_ok": all_critical_ok,
235
- "critical_files": CRITICAL_FILES_V6_1,
236
- }
237
- with open(report_path, "w") as f:
238
- json.dump(upload_report, f, indent=2, default=str)
239
- print(f"\n[INFO] Relatório salvo: {report_path}")
240
-
241
- print("\n" + "=" * 72)
242
- if all_critical_ok:
243
- print(f"[OK] UPLOAD V6.1 CONCLUÍDO — {len(files_filtered)} arquivos enviados")
244
- print(f"[OK] URL: https://huggingface.co/{REPO_ID}")
245
- else:
246
- print(f"[WARN] UPLOAD V6.1 COMPLETO mas alguns arquivos críticos não verificados")
247
- print("=" * 72)
248
-
249
-
250
- if __name__ == "__main__":
251
- main()