gru-ring-v13-9-2 / xavante_work /flexnet /granularity_optimizer.py
PowerMachine's picture
GRU-RING v13.9.2: trained model + bug fixes (A-F)
250e8de verified
Raw History Blame Contribute Delete
22.7 kB
"""
granularity_optimizer — Otimização por granularidade de tarefas.
Modelo matemático
-----------------
Seja um conjunto de T tarefas com custos {c_1, ..., c_T} e P unidades de
processamento (cores/SMs/threads). Queremos encontrar a partição
π = {S_1, ..., S_P} que minimiza o makespan:
min_π max_j Σ_{t ∈ S_j} c_t
Este é o problema de bin-packing / multiway number partitioning (NP-hard).
Aproximamos via:
1. LPT (Longest Processing Time first): ordena tarefas por custo descrescente,
atribui cada à unidade menos carregada. Aproximação 4/3 - ótima.
2. Refinamento local: troca tarefas entre unidades para reduzir makespan.
3. Para tarefas com custo similar (granularidade fina), usa round-robin.
Para o FlexNet:
- Tarefas = forward de módulos (ExternalFlexibleNetwork, sub-orchestrators, etc.)
- Unidades = threads (CPU) ou streams (GPU)
- Custo = tempo estimado via cost model
Integração:
- Substitui o round-robin/sequencial do parallel_map por atribuição LPT
- Remove fallback single-thread (sempre paralelo, mesmo para N=1)
- Aplica a todos os níveis: fnhyp, auto-trainer, orquestradores
"""
from __future__ import annotations
import heapq
import math
import os
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple
import torch
import torch.nn as nn
from concurrent.futures import ThreadPoolExecutor, as_completed
# ============================================================================
# 1. Cost estimation — estima custo de cada tarefa
# ============================================================================
@dataclass
class TaskCost:
"""Custo estimado de uma tarefa (módulo)."""
name: str
module: nn.Module
estimated_flops: float = 0.0
estimated_ms: float = 0.0
input_size: Tuple[int, ...] = ()
metadata: Dict[str, Any] = field(default_factory=dict)
def estimate_module_cost(
module: nn.Module,
input_shape: Tuple[int, ...],
name: str = "",
) -> TaskCost:
"""Estima custo de um módulo baseado em parâmetros e input shape.
Heurística: FLOPs ≈ 2 · n_params · prod(input_shape[:-1]) para camadas
lineares; para attention, 2 · N² · d · H.
"""
n_params = sum(p.numel() for p in module.parameters())
# Estimativa de FLOPs.
if len(input_shape) >= 2:
B_T = 1
for dim in input_shape[:-1]:
B_T *= dim
flops = 2 * n_params * B_T
else:
flops = 2 * n_params
# Estimativa de ms (assume 1 GFLOP/s em CPU single-core).
estimated_ms = flops / 1e9 * 1000 # ms
return TaskCost(
name=name or module.__class__.__name__,
module=module,
estimated_flops=flops,
estimated_ms=estimated_ms,
input_size=input_shape,
)
# ============================================================================
# 2. LPT Scheduler — Longest Processing Time first
# ============================================================================
@dataclass
class ScheduleAssignment:
"""Atribuição de uma tarefa a uma unidade."""
task_idx: int
unit_idx: int
task: TaskCost
@dataclass
class Schedule:
"""Plano de execução: partição de tarefas por unidade."""
assignments: List[ScheduleAssignment] = field(default_factory=list)
unit_loads: List[float] = field(default_factory=list)
makespan: float = 0.0
n_units: int = 0
method: str = "lpt"
def get_tasks_for_unit(self, unit_idx: int) -> List[int]:
"""Retorna índices das tarefas atribuídas a uma unidade."""
return [a.task_idx for a in self.assignments if a.unit_idx == unit_idx]
def summary(self) -> str:
lines = [f"Schedule ({self.method}, {self.n_units} units, makespan={self.makespan:.2f}ms):"]
for u in range(self.n_units):
tasks = self.get_tasks_for_unit(u)
load = self.unit_loads[u] if u < len(self.unit_loads) else 0
lines.append(f" Unit {u}: {len(tasks)} tasks, load={load:.2f}ms")
return "\n".join(lines)
def lpt_schedule(
tasks: List[TaskCost],
n_units: int,
refine: bool = True,
) -> Schedule:
"""LPT (Longest Processing Time first) scheduling.
Algoritmo:
1. Ordena tarefas por custo decrescente.
2. Para cada tarefa, atribui à unidade com menor carga atual.
3. (Opcional) Refina via troca local.
Aproximação: makespan ≤ (4/3) · OPT (Graham 1969).
Args:
tasks: lista de TaskCost
n_units: número de unidades de processamento
refine: se True, aplica refinamento local
Retorna: Schedule com atribuições.
"""
if n_units < 1:
n_units = 1
if not tasks:
return Schedule(n_units=n_units, unit_loads=[0.0] * n_units)
# 1. Ordena por custo decrescente.
indexed = sorted(enumerate(tasks), key=lambda x: -x[1].estimated_ms)
# 2. Atribui via min-heap (unidade com menor carga).
# Heap: (load, unit_idx)
heap = [(0.0, u) for u in range(n_units)]
heapq.heapify(heap)
assignments = []
unit_loads = [0.0] * n_units
for task_idx, task in indexed:
load, unit_idx = heapq.heappop(heap)
assignments.append(ScheduleAssignment(
task_idx=task_idx, unit_idx=unit_idx, task=task,
))
new_load = load + task.estimated_ms
unit_loads[unit_idx] = new_load
heapq.heappush(heap, (new_load, unit_idx))
makespan = max(unit_loads) if unit_loads else 0.0
schedule = Schedule(
assignments=assignments,
unit_loads=unit_loads,
makespan=makespan,
n_units=n_units,
method="lpt",
)
# 3. Refinamento local (opcional).
if refine and n_units > 1 and len(tasks) > n_units:
schedule = _refine_schedule(schedule, tasks)
return schedule
def _refine_schedule(
schedule: Schedule,
tasks: List[TaskCost],
max_iter: int = 10,
) -> Schedule:
"""Refina schedule via troca local (hill climbing).
Tenta trocar tarefas entre a unidade mais carregada e a menos carregada
para reduzir makespan.
"""
for _ in range(max_iter):
# Encontra unidade mais carregada e menos carregada.
max_unit = schedule.unit_loads.index(max(schedule.unit_loads))
min_unit = schedule.unit_loads.index(min(schedule.unit_loads))
max_load = schedule.unit_loads[max_unit]
min_load = schedule.unit_loads[min_unit]
if max_load - min_load < 1e-6:
break # balanceado
# Tenta mover a tarefa mais cara da unidade max para min.
max_tasks = schedule.get_tasks_for_unit(max_unit)
if not max_tasks:
break
# Encontra tarefa com maior custo que pode ser movida.
best_task = None
best_improvement = 0.0
for t_idx in max_tasks:
task = tasks[t_idx]
new_max = max_load - task.estimated_ms
new_min = min_load + task.estimated_ms
new_makespan = max(new_max, new_min, max(l for i, l in enumerate(schedule.unit_loads) if i not in (max_unit, min_unit)) if len(schedule.unit_loads) > 2 else 0)
improvement = max_load - new_makespan
if improvement > best_improvement and new_max >= min_load:
best_improvement = improvement
best_task = t_idx
if best_task is None or best_improvement <= 0:
break
# Move tarefa.
task = tasks[best_task]
schedule.unit_loads[max_unit] -= task.estimated_ms
schedule.unit_loads[min_unit] += task.estimated_ms
for a in schedule.assignments:
if a.task_idx == best_task:
a.unit_idx = min_unit
break
schedule.makespan = max(schedule.unit_loads)
return schedule
# ============================================================================
# 3. GranularTaskExecutor — executa tarefas conforme schedule
# ============================================================================
class GranularTaskExecutor:
"""Executor que distribui tarefas via LPT scheduling.
Diferença vs parallel_map:
- parallel_map: round-robin (cada thread pega próxima tarefa da fila)
- GranularTaskExecutor: LPT (tarefa mais cara vai para unidade menos carregada)
Vantagem: melhor balanceamento de carga, menor makespan.
Uso:
>>> executor = GranularTaskExecutor(n_units=4)
>>> results = executor.execute(tasks, X)
"""
def __init__(
self,
n_units: Optional[int] = None,
refine: bool = True,
verbose: bool = False,
):
if n_units is None:
n_units = min(os.cpu_count() or 4, 8)
self.n_units = n_units
self.refine = refine
self.verbose = verbose
self.last_schedule: Optional[Schedule] = None
def execute(
self,
tasks: List[TaskCost],
X: torch.Tensor,
masks: Optional[List[Optional[torch.Tensor]]] = None,
) -> List[Any]:
"""Executa tarefas conforme schedule LPT.
Args:
tasks: lista de TaskCost (cada um tem .module)
X: input compartilhado
masks: máscaras opcionais (uma por tarefa)
Retorna: lista de resultados (mesma ordem que tasks).
"""
import os
if masks is None:
masks = [None] * len(tasks)
# 1. Computa schedule.
schedule = lpt_schedule(tasks, self.n_units, refine=self.refine)
self.last_schedule = schedule
if self.verbose:
print(schedule.summary())
# 2. Executa: cada unidade processa suas tarefas sequencialmente,
# unidades em paralelo via ThreadPoolExecutor.
results: List[Any] = [None] * len(tasks)
# Agrupa tarefas por unidade.
unit_tasks: Dict[int, List[Tuple[int, TaskCost]]] = {u: [] for u in range(self.n_units)}
for a in schedule.assignments:
unit_tasks[a.unit_idx].append((a.task_idx, a.task))
# Função que processa todas as tarefas de uma unidade.
def process_unit(unit_idx: int) -> List[Tuple[int, Any]]:
task_list = unit_tasks[unit_idx]
out = []
for task_idx, task_cost in task_list:
try:
mod = task_cost.module
mask = masks[task_idx]
if mask is not None:
y = mod(X, mask=mask)
else:
y = mod(X)
out.append((task_idx, y))
except Exception as e:
out.append((task_idx, e))
return out
# Executa unidades em paralelo.
with ThreadPoolExecutor(max_workers=self.n_units) as executor:
futures = {executor.submit(process_unit, u): u for u in range(self.n_units)}
for fut in as_completed(futures):
try:
for task_idx, result in fut.result():
results[task_idx] = result
except Exception as e:
if self.verbose:
print(f" Unit {futures[fut]} failed: {e}")
return results
def get_stats(self) -> Dict[str, Any]:
"""Retorna estatísticas do último schedule."""
if self.last_schedule is None:
return {}
s = self.last_schedule
loads = s.unit_loads
return {
"n_units": s.n_units,
"makespan_ms": s.makespan,
"max_load_ms": max(loads) if loads else 0,
"min_load_ms": min(loads) if loads else 0,
"load_imbalance": (max(loads) - min(loads)) / max(max(loads), 1e-8) if loads else 0,
"method": s.method,
}
# ============================================================================
# 4. OptimizeFlexGRU — aplica granularity ao FlexGRU
# ============================================================================
def optimize_flexgru_with_granularity(
flex_gru: nn.Module,
X: torch.Tensor,
n_units: Optional[int] = None,
) -> GranularTaskExecutor:
"""Cria executor otimizado para FlexGRU.
Analisa custo de cada componente (gates, fnhyp, trust agent) e
distribui via LPT.
"""
# Estima custos de cada componente.
tasks = []
# Gate reset.
gate_r_cost = estimate_module_cost(
flex_gru.cells[0].W_r, X.shape, "gate_r"
) if hasattr(flex_gru, 'cells') and flex_gru.cells else None
# Para FlexGRU, os componentes são internos ao forward.
# Aqui criamos tasks para cada passo temporal (granularidade fina).
B, T, _ = X.shape if X.dim() == 3 else (1, X.shape[0], X.shape[1])
for t in range(T):
tasks.append(TaskCost(
name=f"step_{t}",
module=flex_gru, # mesmo módulo, mas input diferente
estimated_ms=1.0, # custo uniforme por passo
input_size=(B, 1, X.shape[-1]) if X.dim() == 3 else (1, X.shape[-1]),
metadata={"timestep": t},
))
executor = GranularTaskExecutor(n_units=n_units, verbose=False)
return executor
# ============================================================================
# 5. OptimizeOrchestrator — aplica granularity a orquestradores
# ============================================================================
def optimize_orchestrator_with_granularity(
orchestrator: nn.Module,
X: torch.Tensor,
n_units: Optional[int] = None,
) -> GranularTaskExecutor:
"""Cria executor LPT para redes externas de um orquestrador.
Estima custo de cada ExternalFlexibleNetwork e distribui via LPT.
"""
tasks = []
if hasattr(orchestrator, 'externals'):
for i, ext in enumerate(orchestrator.externals):
cost = estimate_module_cost(ext, X.shape, f"ext_{i}")
tasks.append(cost)
elif hasattr(orchestrator, 'sub_orchestrators'):
for i, sub in enumerate(orchestrator.sub_orchestrators):
cost = estimate_module_cost(sub, X.shape, f"sub_{i}")
tasks.append(cost)
elif hasattr(orchestrator, 'meta_orchestrators'):
for i, meta in enumerate(orchestrator.meta_orchestrators):
cost = estimate_module_cost(meta, X.shape, f"meta_{i}")
tasks.append(cost)
executor = GranularTaskExecutor(n_units=n_units, verbose=False)
# Pré-computa schedule para análise.
if tasks:
executor.last_schedule = lpt_schedule(tasks, executor.n_units)
return executor
# ============================================================================
# 6. OptimizeAutoTrainer — aplica granularity ao auto-trainer
# ============================================================================
def optimize_auto_trainer_with_granularity(
auto_trainer: nn.Module,
n_units: Optional[int] = None,
) -> GranularTaskExecutor:
"""Cria executor LPT para componentes do auto-trainer (GAN + kNN + Bayes).
O auto-trainer tem 3 componentes com custos diferentes:
- GAN train_step: ~50ms (pesado)
- kNN impute: ~5ms (médio)
- Bayes update: ~0.1ms (leve)
LPT distribui: GAN em uma unidade, kNN em outra, Bayes agrupado.
"""
tasks = [
TaskCost(name="gan_train", module=auto_trainer, estimated_ms=50.0),
TaskCost(name="knn_impute", module=auto_trainer, estimated_ms=5.0),
TaskCost(name="bayes_update", module=auto_trainer, estimated_ms=0.1),
]
executor = GranularTaskExecutor(n_units=n_units, verbose=False)
executor.last_schedule = lpt_schedule(tasks, executor.n_units)
return executor
# ============================================================================
# 7. OptimizeFNHYP — aplica granularity à fnhyp (K hipóteses paralelas)
# ============================================================================
def optimize_fnhyp_with_granularity(
fnhyp: nn.Module,
X: torch.Tensor,
n_units: Optional[int] = None,
) -> GranularTaskExecutor:
"""Cria executor LPT para as K hipóteses da fnhyp.
Cada hipótese é uma camada independente; LPT distribui baseado em
custo estimado (depende de effort_level).
"""
tasks = []
if hasattr(fnhyp, 'hypotheses'):
for i, hyp in enumerate(fnhyp.hypotheses):
# effort_level afeta custo.
effort = getattr(hyp, 'config', None)
effort_str = getattr(effort, 'effort_level', 'medium') if effort else 'medium'
effort_mult = {'low': 0.5, 'medium': 1.0, 'high': 2.0}.get(effort_str, 1.0)
cost = estimate_module_cost(hyp, X.shape, f"hyp_{i}_{effort_str}")
cost.estimated_ms *= effort_mult
tasks.append(cost)
executor = GranularTaskExecutor(n_units=n_units, verbose=False)
if tasks:
executor.last_schedule = lpt_schedule(tasks, executor.n_units)
return executor
# ============================================================================
# 8. Embedding otimizado — camada de embedding que aproveita otimizações
# ============================================================================
class OptimizedEmbedding(nn.Module):
"""Camada de embedding otimizada com granularity.
Features:
1. Embedding standard (nn.Embedding) para tokens
2. Positional encoding (sinusoidal) opcional
3. LayerNorm + Dropout
4. Projeta para hidden_size via Linear
5. Usa GranularTaskExecutor para forward paralelo em batches grandes
Para testes: usa embedding aleatório (não pré-treinado).
Em produção: carregar de modelo adequado (ex.: BERT, sentence-transformers).
"""
def __init__(
self,
vocab_size: int = 1000,
embed_dim: int = 64,
hidden_size: int = 128,
max_len: int = 512,
pad_token_id: int = 0,
use_positional: bool = True,
use_layer_norm: bool = True,
dropout: float = 0.1,
n_units: Optional[int] = None,
):
super().__init__()
self.vocab_size = vocab_size
self.embed_dim = embed_dim
self.hidden_size = hidden_size
self.max_len = max_len
self.pad_token_id = pad_token_id
self.use_positional = use_positional
# Embedding de token.
self.token_embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_token_id)
# Embedding posicional (sinusoidal, não treinável).
if use_positional:
pos_emb = self._create_positional_encoding(max_len, embed_dim)
self.register_buffer('positional_embedding', pos_emb)
# LayerNorm.
if use_layer_norm:
self.layer_norm = nn.LayerNorm(embed_dim)
else:
self.layer_norm = None
# Dropout.
self.dropout = nn.Dropout(dropout)
# Projeção para hidden_size.
if embed_dim != hidden_size:
self.proj = nn.Linear(embed_dim, hidden_size)
else:
self.proj = None
# Executor para forward paralelo (granularidade por batch chunk).
self.n_units = n_units or min(4, os.cpu_count() or 4)
self._executor: Optional[GranularTaskExecutor] = None
@staticmethod
def _create_positional_encoding(max_len: int, d: int) -> torch.Tensor:
"""Cria positional encoding sinusoidal (Vaswani 2017).
PE(pos, 2i) = sin(pos / 10000^(2i/d))
PE(pos, 2i+1) = cos(pos / 10000^(2i/d))
"""
pe = torch.zeros(max_len, d)
position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1)
div_term = torch.exp(torch.arange(0, d, 2).float() * (-math.log(10000.0) / d))
pe[:, 0::2] = torch.sin(position * div_term)
pe[:, 1::2] = torch.cos(position * div_term)
return pe.unsqueeze(0) # (1, max_len, d)
def forward(self, input_ids: torch.Tensor) -> torch.Tensor:
"""input_ids: (B, T) -> (B, T, hidden_size).
Para B grande, divide em chunks e processa em paralelo via LPT.
"""
B, T = input_ids.shape
# Embedding de token.
X = self.token_embedding(input_ids) # (B, T, embed_dim)
# Positional encoding.
if self.use_positional and T <= self.max_len:
X = X + self.positional_embedding[:, :T, :].to(X.device)
# LayerNorm.
if self.layer_norm is not None:
X = self.layer_norm(X)
# Dropout.
X = self.dropout(X)
# Projeção.
if self.proj is not None:
X = self.proj(X)
return X
def forward_chunked(
self,
input_ids: torch.Tensor,
chunk_size: int = 32,
) -> torch.Tensor:
"""Forward com chunks processados em paralelo via LPT.
Para B > chunk_size, divide em chunks e processa via GranularTaskExecutor.
"""
B, T = input_ids.shape
if B <= chunk_size:
return self.forward(input_ids)
# Divide em chunks.
chunks = torch.split(input_ids, chunk_size, dim=0)
# Cria tasks.
tasks = []
for i, chunk in enumerate(chunks):
tasks.append(TaskCost(
name=f"chunk_{i}",
module=self,
estimated_ms=chunk.shape[0] * T * 0.01, # estimativa
input_size=tuple(chunk.shape),
metadata={"chunk": chunk},
))
# Executa via LPT.
if self._executor is None:
self._executor = GranularTaskExecutor(n_units=self.n_units)
# Processa chunks.
results = [None] * len(chunks)
schedule = lpt_schedule(tasks, self._executor.n_units)
# Agrupa por unidade.
unit_chunks: Dict[int, List[Tuple[int, torch.Tensor]]] = {
u: [] for u in range(self._executor.n_units)
}
for a in schedule.assignments:
unit_chunks[a.unit_idx].append((a.task_idx, chunks[a.task_idx]))
# Executa em paralelo.
def process_unit(unit_idx: int) -> List[Tuple[int, torch.Tensor]]:
out = []
for idx, chunk in unit_chunks[unit_idx]:
out.append((idx, self.forward(chunk)))
return out
with ThreadPoolExecutor(max_workers=self._executor.n_units) as ex:
futures = {ex.submit(process_unit, u): u for u in range(self._executor.n_units)}
for fut in as_completed(futures):
for idx, result in fut.result():
results[idx] = result
return torch.cat(results, dim=0)
def extra_repr(self) -> str:
return (
f"vocab={self.vocab_size}, embed={self.embed_dim}, "
f"hidden={self.hidden_size}, max_len={self.max_len}, "
f"positional={self.use_positional}, n_units={self.n_units}"
)