Download xavante_work/flexnet/dynamic_restructuring.py from PowerMachine/gru-ring-v13-9-2: direct link, hf CLI and curl.
- Browser
- Download file 9.41 kB
-
https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/dynamic_restructuring.py
- Command line
-
hf download hf://PowerMachine/gru-ring-v13-9-2/xavante_work/flexnet/dynamic_restructuring.py
-
curl -L -o dynamic_restructuring.py https://huggingface.co/PowerMachine/gru-ring-v13-9-2/resolve/main/xavante_work/flexnet/dynamic_restructuring.py
9.41 kB
| """dynamic_restructuring.py — Pruning/rewiring via curvatura e informação mútua (V11.24c). | |
| Teorema 3: VC_eff ≤ VC₀·(1 - ρ_pruned/ρ_total), generalização melhora via I(Z;Y). | |
| CORREÇÃO V11.26: | |
| - Bug original: tau_prune=0.01 muito alto → Fisher information média ~1.0, | |
| NENHUM parâmetro era podado (todos passavam do threshold). | |
| - Fix: threshold adaptativo = mediana(Fisher) * factor (default 0.1× mediana). | |
| - Fix: compute_fisher_diagonal agora suporta data_loader como lista de tensores | |
| (não exige dict com keys específicas). | |
| - Adicionado: soft pruning (zero grad) vs hard pruning (zero param) opção. | |
| - Adicionado: tracking de VC_eff antes/depois. | |
| """ | |
| from __future__ import annotations | |
| import math | |
| import torch | |
| import torch.nn as nn | |
| import numpy as np | |
| from typing import Dict, List, Tuple, Optional, Any, Callable | |
| class DynamicRestructurer: | |
| """Reestruturação dinâmica da rede baseada em curvatura e informação mútua. | |
| V11.26: | |
| - Threshold adaptativo (mediana de Fisher * factor) | |
| - Suporte a data_loader como lista de tensores OU dict | |
| - Soft pruning (default) e hard pruning opcional | |
| - Tracking de VC_eff antes/depois | |
| Args: | |
| tau_prune: threshold base (default 0.01) | |
| adaptive_threshold: se True, usa mediana(Fisher) * tau_prune | |
| (default True, muito mais eficaz) | |
| soft_prune: se True, zera gradientes (não remove pesos); False, zera pesos | |
| """ | |
| def __init__(self, tau_prune: float = 0.01, tau_rewire: float = 0.1, | |
| mi_threshold: float = 0.5, adaptive_threshold: bool = True, | |
| soft_prune: bool = True): | |
| self.tau_prune = tau_prune | |
| self.tau_rewire = tau_rewire | |
| self.mi_threshold = mi_threshold | |
| self.adaptive_threshold = adaptive_threshold | |
| self.soft_prune = soft_prune | |
| self.prune_count = 0 | |
| self.rewire_count = 0 | |
| self.vc_history: List[Dict[str, float]] = [] | |
| def compute_fisher_diagonal( | |
| self, | |
| model: nn.Module, | |
| loss_fn: Callable, | |
| data_loader, | |
| n_samples: int = 100, | |
| ) -> Dict[str, torch.Tensor]: | |
| """Computa a diagonal da Fisher information matrix (curvatura local). | |
| ρ_i = E[(∂log p(y|x,θ)/∂θ_i)²] ≈ E[(∂L/∂θ_i)²] | |
| V11.26: suporta data_loader como: | |
| - lista de tensores (forward direto) | |
| - lista de dicts (passa kwargs para loss_fn) | |
| - DataLoader PyTorch (iterável) | |
| """ | |
| fisher: Dict[str, torch.Tensor] = {} | |
| for name, param in model.named_parameters(): | |
| fisher[name] = torch.zeros_like(param.data) | |
| model.eval() | |
| n = 0 | |
| for batch in data_loader: | |
| if n >= n_samples: | |
| break | |
| model.zero_grad() | |
| try: | |
| # V11.26: suporte flexível a diferentes formatos de batch | |
| if isinstance(batch, dict): | |
| loss = loss_fn(model, batch) | |
| elif isinstance(batch, (list, tuple)): | |
| loss = loss_fn(model, *batch) | |
| else: | |
| loss = loss_fn(model, batch) | |
| if loss is None: | |
| continue | |
| loss.backward() | |
| for name, param in model.named_parameters(): | |
| if param.grad is not None: | |
| fisher[name] += param.grad.data ** 2 | |
| n += 1 | |
| except Exception as e: | |
| # Silenciosamente pula batches problemáticos | |
| continue | |
| for name in fisher: | |
| fisher[name] /= max(n, 1) | |
| return fisher | |
| def compute_mutual_information( | |
| self, representations: torch.Tensor, labels: torch.Tensor | |
| ) -> float: | |
| """Estima I(Z;Y) via binning (aproximação discreta). | |
| I(Z;Y) = H(Y) - H(Y|Z) = Σ p(y,z) log(p(y,z)/(p(y)p(z))) | |
| """ | |
| if representations.dim() > 2: | |
| representations = representations.view(representations.size(0), -1) | |
| N, D = representations.shape | |
| # V11.26: usar primeira componente com maior variância | |
| # (antes era sempre primeira coluna, podia ser ruim) | |
| var_per_dim = representations.var(dim=0) | |
| best_dim = int(var_per_dim.argmax().item()) | |
| z = representations[:, best_dim].detach().cpu().numpy() | |
| y = labels.detach().cpu().numpy() | |
| n_bins = min(20, max(N // 10, 2)) | |
| z_bins = np.digitize(z, np.linspace(z.min(), z.max(), n_bins)) | |
| unique_y = np.unique(y) | |
| H_y = 0.0 | |
| for uy in unique_y: | |
| p_y = (y == uy).sum() / N | |
| if p_y > 0: | |
| H_y -= p_y * np.log2(p_y) | |
| H_y_z = 0.0 | |
| for bz in np.unique(z_bins): | |
| mask = z_bins == bz | |
| n_z = mask.sum() | |
| if n_z == 0: | |
| continue | |
| p_z = n_z / N | |
| H_y_given_z = 0.0 | |
| for uy in unique_y: | |
| p_y_z = ((y == uy) & mask).sum() / n_z | |
| if p_y_z > 0: | |
| H_y_given_z -= p_y_z * np.log2(p_y_z) | |
| H_y_z += p_z * H_y_given_z | |
| mi = H_y - H_y_z | |
| return float(max(mi, 0.0)) # MI não pode ser negativo | |
| def prune(self, model: nn.Module, fisher: Dict[str, torch.Tensor]) -> Dict[str, Any]: | |
| """Remove parâmetros com Fisher information abaixo do threshold. | |
| V11.26: threshold adaptativo (mediana * tau_prune) por padrão. | |
| """ | |
| # Calcular threshold | |
| all_fisher = torch.cat([f.flatten() for f in fisher.values()]) | |
| if all_fisher.numel() == 0: | |
| return {"pruned_params": 0, "total_params": 0, "vc_reduction": 0.0} | |
| if self.adaptive_threshold: | |
| # V11.26: threshold = mediana * tau_prune (muito mais eficaz) | |
| median_fisher = float(all_fisher.median().item()) | |
| threshold = max(median_fisher * self.tau_prune, 1e-8) | |
| else: | |
| threshold = self.tau_prune | |
| pruned = 0 | |
| total = 0 | |
| vc_before = total # será atualizado | |
| for name, param in model.named_parameters(): | |
| total += param.numel() | |
| if name not in fisher: | |
| continue | |
| mask = fisher[name] > threshold | |
| n_pruned = (~mask).sum().item() | |
| pruned += n_pruned | |
| if self.soft_prune: | |
| # Soft: zerar gradientes dos parâmetros com baixa Fisher | |
| # (impede atualização sem remover fisicamente) | |
| if param.grad is not None: | |
| param.grad.data.mul_(mask.float()) | |
| # Marcar com atributo (para uso futuro) | |
| if not hasattr(param, "_prune_mask"): | |
| setattr(param, "_prune_mask", mask) | |
| else: | |
| param._prune_mask = param._prune_mask & mask | |
| else: | |
| # Hard: zerar pesos | |
| with torch.no_grad(): | |
| param.data.mul_(mask.float()) | |
| self.prune_count += pruned | |
| vc_reduction = pruned / max(total, 1) | |
| result = { | |
| "pruned_params": pruned, | |
| "total_params": total, | |
| "vc_reduction": vc_reduction, | |
| "threshold_used": threshold, | |
| "median_fisher": float(all_fisher.median().item()), | |
| "mean_fisher": float(all_fisher.mean().item()), | |
| "adaptive": self.adaptive_threshold, | |
| } | |
| self.vc_history.append(result) | |
| return result | |
| def rewire( | |
| self, | |
| model: nn.Module, | |
| representations: torch.Tensor, | |
| labels: torch.Tensor, | |
| ) -> Dict[str, Any]: | |
| """Adiciona conexões baseadas em alta informação mútua I(Z;Y).""" | |
| mi = self.compute_mutual_information(representations, labels) | |
| rewired = 0 | |
| if mi > self.mi_threshold: | |
| for name, param in model.named_parameters(): | |
| if "weight" in name and param.dim() >= 2: | |
| n_new = min(10, param.size(0) * param.size(1) // 100) | |
| if n_new > 0: | |
| idx = torch.randint(0, param.size(0), (n_new,)) | |
| idx2 = torch.randint(0, param.size(1), (n_new,)) | |
| with torch.no_grad(): | |
| param.data[idx, idx2] += torch.randn(n_new) * 0.01 | |
| rewired += n_new | |
| self.rewire_count += rewired | |
| return {"rewired_connections": rewired, "mutual_info": mi} | |
| def restructure( | |
| self, | |
| model: nn.Module, | |
| loss_fn: Callable, | |
| data_loader, | |
| representations: Optional[torch.Tensor] = None, | |
| labels: Optional[torch.Tensor] = None, | |
| ) -> Dict[str, Any]: | |
| """Executa pruning + rewiring completo.""" | |
| fisher = self.compute_fisher_diagonal(model, loss_fn, data_loader) | |
| prune_result = self.prune(model, fisher) | |
| rewire_result = {"rewired_connections": 0, "mutual_info": 0.0} | |
| if representations is not None and labels is not None: | |
| rewire_result = self.rewire(model, representations, labels) | |
| return { | |
| "prune": prune_result, | |
| "rewire": rewire_result, | |
| "total_pruned": self.prune_count, | |
| "total_rewired": self.rewire_count, | |
| "vc_history_len": len(self.vc_history), | |
| } | |
| __all__ = ["DynamicRestructurer"] | |