#!/usr/bin/env python3 # -*- coding: utf-8 -*- """Publica o KHTST v22 no HuggingFace — UM ÚNICO COMMIT COMPLETO (anti-bloqueio do Hub: `upload_folder` + `delete_patterns=["*"]` substitui ATOMICAMENTE todo o conteúdo; nunca há uploads parciais em sequência curta — requisito do usuário). INCLUI: README (card v22) · LICENSE · requirements · configs/ · src/khtst/ (otimizadores com acumuladores/produtor_v22, mixin treinador_v22.py, autorregulacao_estendida com appliers, SOMs com contadores, ipc com .so real) · scripts/ (33 teste v22, 34 gráficos) · docs/matematica/ (00–34, doc 34 NOVO) · tests/ (v1–v22) · patches/ · PLANO_KHMAMBAJEPA.md · RELATORIO_KHTST.md · graficos/ (v22 incluso). EXCLUI: venv/ · __pycache__ · cache_dados · telemetria_out · cache_hub_tmp · .git · build · estados*/ · stage*/ · qualquer `.pt/.pth/.ckpt/.safetensors/.bin` (REQUISITO: nenhum estado de treino no Hub) · qualquer arquivo com padrão de token hf_... SEGURANÇA: token EXCLUSIVAMENTE da variável de ambiente HF_TOKEN — nunca gravado em arquivo, log, repo ou remote URL. Uso: HF_TOKEN=hf_... python3 scripts/35_publicar_v22.py [--repo ...] """ import argparse import os import re import shutil import sys RAIZ = "/home/z/my-project/khtst" STAGE = "/home/z/my-project/khtst/stage_publicar_v22" IGNORAR_DIRS = {"__pycache__", "cache_dados", "telemetria_out", "cache_hub_tmp", ".git", "build", "venv", ".venv", "estados_local", "estados_local_teste", "estados", "stage_publicar", "stage_publicar_v17", "stage_publicar_v18", "stage_publicar_v19", "stage_publicar_v20", "stage_publicar_v21", "stage_publicar_v22", "hf_stage", "download", "upload", "node_modules"} IGNORAR_NOMES = {"resultados_v21.json", "resultados_v20.json"} IGNORAR_EXT = (".pt", ".pth", ".ckpt", ".safetensors", ".pyc", ".pt.tmp", ".bin") PADRAO_TOKEN = re.compile(r"hf_[A-Za-z0-9]{30,}") RESIDUOS_PROIBIDOS = ("bugwatch",) def preparar_stage() -> int: if os.path.exists(STAGE): shutil.rmtree(STAGE) n = 0 for raiz, dirs, arquivos in os.walk(RAIZ): dirs[:] = [d for d in dirs if d not in IGNORAR_DIRS] rel = os.path.relpath(raiz, RAIZ) alvo_raiz = os.path.join(STAGE, rel) if rel != "." else STAGE os.makedirs(alvo_raiz, exist_ok=True) for a in arquivos: if a.endswith(IGNORAR_EXT) or a.startswith("."): continue if a in IGNORAR_NOMES: continue if any(r in a.lower() for r in RESIDUOS_PROIBIDOS): print(f" [RESÍDUO] ignorado: {a}") continue origem = os.path.join(raiz, a) destino = os.path.join(alvo_raiz, a) shutil.copy2(origem, destino) n += 1 return n def auditar_stage() -> int: """Auditoria: 0 estados de treino, 0 tokens, 0 resíduos.""" problemas = 0 n_arq = 0 for raiz, dirs, arquivos in os.walk(STAGE): for a in arquivos: n_arq += 1 cam = os.path.join(raiz, a) if a.endswith(IGNORAR_EXT): print(f" [ESTADO] {cam}"); problemas += 1 continue try: with open(cam, "rb") as f: dados = f.read() except OSError: continue if PADRAO_TOKEN.search(dados.decode("utf-8", errors="ignore")): print(f" [TOKEN] {cam}"); problemas += 1 print(f"stage: {n_arq} arquivos | problemas: {problemas}") return problemas def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("--repo", default="PowerMachine/khtst-multimodal-ptbr") args = ap.parse_args() token = os.environ.get("HF_TOKEN") if not token: print("ERRO: HF_TOKEN ausente no ambiente"); return 1 from huggingface_hub import HfApi, upload_folder api = HfApi(token=token) print("== preparando stage ==") n = preparar_stage() print(f"{n} arquivos copiados para o stage") print("== auditando stage (estados/tokens/resíduos) ==") if auditar_stage() > 0: print("ERRO: stage contém itens proibidos — abortando"); return 1 print("== commit ÚNICO no Hub (upload_folder + delete_patterns) ==") upload_folder( repo_id=args.repo, repo_type="model", folder_path=STAGE, commit_message=( "KHTST v22 — fechamento 18/18 da tabela v17: os 10 produtores " "restantes com MEDIÇÕES REAIS (estado do otimizador via " "acumuladores opt-in bit-a-bit Teo 34.1; razao_update_grad com " "cota de Jensen Teo 34.2; razao_momentum_grad com correção " "estacionária sqrt(1-b^2) Teo 34.3; deriva do 2º momento " "calibrada pivotal Teo 34.4; RMS mecanismos Teo 34.5; folga " "ABMO cap/lr Teo 34.6; aceitação CIAR Teo 34.7; contadores " "reais de crescimento GG/GCS/GSOM Teo 34.8; tau_qk fresco " "Teo 34.9); APLIERS novos com nascimento neutro por base " "capturada (margem ABMO, kappa_ext, lambda_insercao/util_poda " "com poda invertida, peso_som) Teo 34.10; ciclo no mixin " "treinador_v22.py (Teo 34.11, limite <80KB v18 restaurado); " "corpus real fresco 1015 registros (7 fontes) + tokenizador " "16384; A/B pareado 48 passos: 10/10 controladores novos " "movem, appliers escrevem nos alvos reais; doc 34 + PLANO/" "RELATORIO/README; suíte v22 46/46, regressão v1-v21 zero, " "verificar_tudo 49✓"), delete_patterns=["*"], token=token, ) print("== auditoria pós-upload ==") info = api.repo_info(args.repo, files_metadata=False) arq_hub = [s.rfilename for s in info.siblings] estados = [a for a in arq_hub if a.endswith(IGNORAR_EXT)] resid = [a for a in arq_hub if any(r in a.lower() for r in RESIDUOS_PROIBIDOS)] chaves_v22 = [a for a in arq_hub if "34-v22-fechamento-18-18" in a or a.endswith("treinador_v22.py") or a.endswith("33_teste_v22.py") or a.endswith("34_graficos_v22.py") or a.endswith("test_khtst_v22.py") or a.endswith("v22_evidencias.png")] estados_locais = [a for a in arq_hub if a.startswith("cache_dados/") or a.startswith("telemetria_out/")] print(f"arquivos no Hub: {len(arq_hub)}") print(f"estados de treino no Hub: {len(estados)} {estados[:5]}") print(f"resíduos: {len(resid)}") print(f"cache_dados/telemetria vazados: {len(estados_locais)}") print(f"chaves v22 presentes: {len(chaves_v22)} -> {chaves_v22}") ok = (len(estados) == 0 and len(resid) == 0 and len(estados_locais) == 0 and len(chaves_v22) == 6) print("PUBLICAÇÃO v22 " + ("OK ✓" if ok else "COM PROBLEMAS ✗")) return 0 if ok else 1 if __name__ == "__main__": raise SystemExit(main())