BiGRU_T_version / README.md
PowerMachine's picture
Upload README.md with huggingface_hub
64ae428 verified
|
Raw History Blame Contribute Delete
10 kB
# BiGRU_T_version — Refatoração formal do GRU-RING v13.9.2
Refatoração matemática do modelo [PowerMachine/gru-ring-v13-9-2](https://huggingface.co/PowerMachine/gru-ring-v13-9-2) em torno de **4 lemas formais** que tornam explícitos os mecanismos de desacoplamento, cirurgia de gradiente, cancelamento de ruído de quantização e auto-configuração.
## Lemas
### Lema 1 — Desacoplamento via atenção hierárquica
Seleção dos módulos `u8cell_T` por softmax com temperatura controlada (α). Durante o treino, a temperatura é meta-ajustada e a entropia dos pesos é minimizada indiretamente pela regularização de agudeza, forçando especialização e reduzindo o produto interno dos gradientes (disputa).
**Implementação**: `src/bigru_t/model/module_selector.py` — `ModuleSelector`
- `module_logits: nn.Parameter(torch.zeros(K))` — logits aprendíveis
- `alpha = F.softmax(module_logits / T, dim=0)` no forward
- `entropy_reg = -lambda_ent * (alpha * log(alpha + eps)).sum()`
### Lema 2 — Gradiente cirúrgico
`apply_gradient_surgery` implementa a projeção ortogonal quando os gradientes da tarefa principal e da hipótese são conflitantes (produto interno negativo). Garante que ambas as perdas possam ser reduzidas sem interferência destrutiva.
**Implementação**: `src/bigru_t/training/gradient_surgery.py`
- `orthogonalize_gradient(g_main, g_hyp)`: projeção vetorial
- `apply_gradient_surgery(model, loss_main, loss_hyp)`: calcula gradientes independentes via `torch.autograd.grad`, aplica projeção e atribui `p.grad = g_main + g_hyp_perp`
### Lema 3 — Cancelamento de ruído de quantização
A hipótese (`hyp_T`) é treinada com a perda sobre `y_final = y_hat + delta`, aprendendo a corrigir o viés e variância introduzidos pela quantização W8A8 (simulada no forward pelas camadas `QuantizedLinear`). `stop_grad_hyp=True` isola o sinal de correção do gradiente principal, e a cirurgia gerencia os parâmetros compartilhados.
**Implementação**: `src/bigru_t/quantization/quantized_linear.py` + `src/bigru_t/model/hyp_t.py`
- `QuantizedLinear(nn.Linear)`: fake quant W8A8 no forward (STE backward)
- `HypT.forward(o, stop_grad=True)`: aplica `o.detach()` quando stop_grad
- Ativação condicional: hipótese só é calculada quando `loss_main > tau`
### Lema 4 — Auto-configuração e suavização
`MetaConfigurator` ajusta temperatura e limiar τ, e penaliza a agudeza da perda (norma do gradiente), empurrando o modelo para mínimos planos onde o ruído de gradiente é menor. A quantidade de módulos ativos é implicitamente controlada pela softmax com temperatura.
**Implementação**: `src/bigru_t/training/meta_configurator.py`
- `log_temperature: nn.Parameter` — `T = exp(log_temperature)` (positivo)
- `log_tau: nn.Parameter` — `τ = exp(log_tau)` (positivo)
- `forward_with_meta(x_val, y_val)`: meta-loss = `L_val + λ_s * ||∇_θ L_val||²`
## Arquitetura
```
x (batch, T, input_dim)
│
├──→ u8cell_T_1 ─→ h_1 ─┐
├──→ u8cell_T_2 ─→ h_2 ─┤ Lema 1: alpha = softmax(logits / T)
├──→ ... ├─→ H = stack([alpha_k * h_k]) → OrqCell
└──→ u8cell_T_K ─→ h_K ─┘ │
↓
o (batch, d_cache)
│
┌──────────────┴──────────────┐
↓ ↓
TrainT(o) HypT(o, stop_grad=True)
│ │
↓ ↓
y_hat delta
│ │
└──────→ y_final = y_hat + delta * use_hyp ←── Lema 3
Lema 2: gradient_surgery(g_main, g_hyp) → projeção ortogonal
Lema 4: MetaConfigurator ajusta T (temperatura) e τ (limiar de ativação da hipótese)
```
### Componentes
| Componente | Arquivo | Descrição |
|---|---|---|
| `BiGRU4` | `model/bigru4.py` | 4 camadas BiGRU sequenciais |
| `TransformerUnit` | `model/transformer_unit.py` | Self-attention + FFN para 8 representações |
| `u8cell_T` | `model/u8cell_t.py` | 8 BiGRU4 paralelas + TransformerUnit |
| `OrqCell` | `model/orq_cell.py` | Cache aprendível + cross-attention |
| `TrainT` | `model/train_t.py` | Cabeça de predição principal |
| `HypT` | `model/hyp_t.py` | Cabeça de hipótese (correção delta) |
| `ModuleSelector` | `model/module_selector.py` | Lema 1: softmax + entropia |
| `UnifiedModel` | `model/unified_model.py` | Orquestra todos os componentes |
| `QuantizedLinear` | `quantization/quantized_linear.py` | Lema 3: W8A8 fake quant |
| `apply_gradient_surgery` | `training/gradient_surgery.py` | Lema 2: projeção ortogonal |
| `MetaConfigurator` | `training/meta_configurator.py` | Lema 4: auto-configuração |
| `KillSwitch` | `training/kill_switch.py` | Monitor RAM/disk/loss + kill automático |
| `BiGRU_T_Trainer` | `training/trainer.py` | Loop de treino (2 épocas) |
## Reaproveitamento do source (PowerMachine/gru-ring-v13-9-2)
| Componente | Source | Target |
|---|---|---|
| BBPE Tokenizer | `flexnet/bbpe_tokenizer.py` | `tokenizer/bbpe_tokenizer.py` |
| Streaming datasets (9 base + 3 PT-BR) | `scripts/streaming_datasets_v13_9.py` | `data/streaming_datasets.py` |
| W8A8 QOperator (inferência) | `flexnet/w8a8_qoperator.py` | `quantization/w8a8_qoperator.py` |
| Hardware detector | `flexnet/hardware_detector.py` | `utils/hardware_detector.py` |
| Xeon runtime | `flexnet/xeon_runtime.py` | `utils/xeon_runtime.py` |
| OOM guard | `flexnet/oom_guard.py` | `utils/oom_guard.py` |
| Memory monitor | `flexnet/memory_monitor.py` | `utils/memory_monitor.py` |
| Tensor ops | `xavante/utils/tensor_ops.py` | `utils/tensor_ops.py` |
| Validators | `xavante/utils/validators.py` | `utils/validators.py` |
| Logging utils | `xavante/utils/logging_utils.py` | `utils/logging_utils.py` |
| Hamiltonian-Wasserstein optimizer | `flexnet/hamiltonian_wasserstein_optimizer.py` | `optim/hamiltonian_wasserstein.py` |
| Multimodal: text/image/audio/video encoders | `xavante/multimodal/*` | `multimodal/*` |
## Datasets (12, PT-BR)
**9 base (v13.9.2)**:
1. `CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1`
2. `Madras1/corpus-ptbr-v2`
3. `rhaymison/multmodal_175k_portuguese`
4. `TucanoBR/GigaVerbo`
5. `nvidia/OpenMathReasoning`
6. `MathLLMs/MathVision`
7. `nvidia/OpenMathInstruct-2`
8. `dominguesm/restore-punctuation-ptbr-dataset`
9. `carolina-c4ai/corpus-carolina`
**3 PT-BR finetune**:
10. `orion-research/translations-en_US-pt_BR` (format: `### Instruction:/### Response:`)
11. `cnmoro/Instruct-PTBR-10M` (format: `### Instruction:/### Response:`)
12. `strak2005/corpus-ptbr-v1` (plain text)
## Instalação
```bash
cd BiGRU_T_version
pip install -r requirements.txt
pip install -e .
```
## Uso — Treino de bug-detection (2 épocas)
```bash
export HF_TOKEN="hf_xxx" # para datasets públicos, opcional
python scripts/train.py \
--datasets CEIA-POSITIVO/ultrachat_br_clustred_balanced_v1,Madras1/corpus-ptbr-v2 \
--max-samples 30 \
--epochs 2 \
--output-dir model_final
```
## Uso — Inferência
```python
import torch
from bigru_t import create_unified_model
from tokenizers import Tokenizer
model, config = create_unified_model()
state = torch.load("model_final/pytorch_model.bin", map_location="cpu")
model.load_state_dict(state, strict=False)
model.eval()
tokenizer = Tokenizer.from_file("model_final/tokenizer/tokenizer.json")
input_ids = torch.tensor([tokenizer.encode("O presidente anunciou que").ids])
y_hat, delta = model(input_ids, temperature=1.0, use_hypothesis=False)
next_token = y_hat.argmax(dim=-1)
print(tokenizer.decode([next_token.item()]))
```
## Configuração Xeon
O ambiente é automaticamente configurado para Xeon com AVX512/VNNI/AMX:
- `OMP_NUM_THREADS=2`, `MKL_NUM_THREADS=2`
- `torch.set_num_threads(2)`
- `optimize_xeon_environment()` (de `utils/xeon_runtime.py`) chamado no startup
## Estrutura
```
BiGRU_T_version/
├── README.md
├── requirements.txt
├── src/
│ ├── setup.py
│ └── bigru_t/
│ ├── __init__.py
│ ├── model/ # BiGRU4, TransformerUnit, u8cell_T, OrqCell, TrainT, HypT, ModuleSelector, UnifiedModel
│ ├── quantization/ # QuantizedLinear (Lema 3), w8a8_qoperator (reaproveitado)
│ ├── training/ # gradient_surgery (Lema 2), meta_configurator (Lema 4), kill_switch, trainer
│ ├── data/ # streaming_datasets (reaproveitado, 12 datasets)
│ ├── multimodal/ # text/image/audio/video encoders (reaproveitado)
│ ├── optim/ # hamiltonian_wasserstein (reaproveitado)
│ ├── utils/ # hardware_detector, xeon_runtime, oom_guard, memory_monitor, tensor_ops, validators, logging_utils
│ └── tokenizer/ # bbpe_tokenizer (reaproveitado)
├── scripts/
│ ├── train.py # Treino de bug-detection (2 épocas)
│ ├── smoke_test.py # Smoke test do pipeline
│ └── upload_to_hf.py # Upload para HF
├── tests/
│ ├── test_model.py
│ ├── test_gradient_surgery.py
│ ├── test_meta_configurator.py
│ └── test_w8a8.py
├── docs/
│ ├── analysis.md # Análise matemática dos 4 lemas
│ └── architecture.md
├── configs/
│ └── default.yaml
└── model_final/ # Artefatos treinados
├── config.json
├── pytorch_model.bin
└── tokenizer/
```
## Licença
MIT (herdado do source PowerMachine/gru-ring-v13-9-2).