File size: 9,411 Bytes
250e8de
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
"""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"]