Casual.py
Prompt
from __future__ import annotations import zlib import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .config import CausalConfig def deterministic_unit_vector(key: str, dim: int) -> np.ndarray: generator = np.random.default_rng(zlib.crc32(key.encode("utf-8"))) vector = generator.standard_normal(dim).astype(np.float32) norm = max(float(np.linalg.norm(vector)), 1e-8) return (vector / norm).astype(np.float32) class CausalStructureLearner(nn.Module): def __init__(self, config: CausalConfig, state_dim: int) -> None: super().__init__() self.config = config self.state_dim = state_dim d = config.num_variables hidden = config.sem_hidden_dim self.encoder = nn.Sequential( nn.Linear(state_dim, state_dim // 2), nn.LayerNorm(state_dim // 2), nn.SiLU(), nn.Linear(state_dim // 2, d), ) self.decoder = nn.Sequential( nn.Linear(d, state_dim // 2), nn.LayerNorm(state_dim // 2), nn.SiLU(), nn.Linear(state_dim // 2, state_dim), ) self.adj_logits = nn.Parameter(torch.full((d, d), -2.0)) self.sem_w1 = nn.Parameter(torch.randn(d, d, hidden) / float(np.sqrt(d))) self.sem_b1 = nn.Parameter(torch.zeros(d, hidden)) self.sem_w2 = nn.Parameter(torch.randn(d, hidden) / float(np.sqrt(hidden))) self.sem_b2 = nn.Parameter(torch.zeros(d)) def adjacency_matrix(self, hard: bool = False) -> torch.Tensor: d = self.config.num_variables mask = 1.0 - torch.eye(d, device=self.adj_logits.device) probs = torch.sigmoid(self.adj_logits) * mask if hard: return ((probs > self.config.edge_threshold).float() - probs).detach() + probs return probs def structural_forward(self, v: torch.Tensor, adj: torch.Tensor) -> torch.Tensor: masked = v.unsqueeze(1) * adj.transpose(0, 1).unsqueeze(0) hidden = F.silu(torch.einsum("bji,jih->bjh", masked, self.sem_w1) + self.sem_b1) return torch.einsum("bjh,jh->bj", hidden, self.sem_w2) + self.sem_b2 def dag_acyclicity_residual(self, adj: torch.Tensor) -> torch.Tensor: d = adj.shape[0] return torch.linalg.matrix_exp(adj * adj).diagonal().sum() - float(d) def extract_variables(self, state_combined: torch.Tensor) -> torch.Tensor: return self.encoder(state_combined) def compute_causal_loss( self, state_combined: torch.Tensor ) -> tuple[torch.Tensor, dict[str, float]]: config = self.config v = self.encoder(state_combined) state_recon = self.decoder(v) adj = self.adjacency_matrix(hard=False) v_sem = self.structural_forward(v, adj) recon_loss = F.mse_loss(state_recon, state_combined.detach()) sem_loss = F.mse_loss(v_sem, v.detach()) h_dag = self.dag_acyclicity_residual(adj) dag_penalty = config.acyclicity_weight * h_dag + 0.5 * (config.acyclicity_weight**2) * (h_dag**2) l1_loss = config.sparsity_weight * adj.abs().mean() total = recon_loss + sem_loss + dag_penalty + l1_loss metrics = { "causal_recon": float(recon_loss.detach().item()), "causal_sem": float(sem_loss.detach().item()), "dag_residual": float(h_dag.item()), "causal_l1": float(l1_loss.detach().item()), "causal_total": float(total.detach().item()), } return total, metrics def intervene( self, state_combined: torch.Tensor, var_index: int, forced_value: float, steps: int | None = None, ) -> tuple[torch.Tensor, torch.Tensor]: d = self.config.num_variables if not 0 <= int(var_index) < d: raise ValueError(f"var_index must be within [0, {d - 1}]") var_index = int(var_index) v_orig = self.encoder(state_combined) forced = torch.full_like(v_orig, float(forced_value)) pinned = torch.zeros(d, dtype=torch.bool, device=v_orig.device) pinned[var_index] = True pinned = pinned.unsqueeze(0).expand_as(v_orig) v_cf = torch.where(pinned, forced, v_orig) adj = self.adjacency_matrix(hard=True).clone() adj[:, var_index] = 0.0 iterations = steps if steps else self.config.propagation_steps for _ in range(iterations): v_next = self.structural_forward(v_cf, adj) v_cf = 0.5 * v_cf + 0.5 * v_next v_cf = torch.where(pinned, forced, v_cf) cf_state = state_combined + (self.decoder(v_cf) - self.decoder(v_orig)) return cf_state, v_cf def intervention_dispersion(self, state_combined: torch.Tensor) -> torch.Tensor: adj = self.adjacency_matrix(hard=False) entropy = -(adj * torch.log(adj + 1e-6) + (1.0 - adj) * torch.log(1.0 - adj + 1e-6)) row_entropy = entropy.sum(dim=-1).mean() v = self.encoder(state_combined) return row_entropy * v.std(dim=-1) def export_causal_edges( self, workspace_dim: int ) -> list[tuple[str, str, str, float, np.ndarray]]: with torch.no_grad(): adj = self.adjacency_matrix().detach().cpu().numpy() edges: list[tuple[str, str, str, float, np.ndarray]] = [] d = self.config.num_variables for i in range(d): for j in range(d): if i == j: continue probability = float(adj[i, j]) if probability > self.config.edge_threshold: key = f"causal_var_{i}::CAUSES::causal_var_{j}" edges.append( ( f"causal_var_{i}", "CAUSES", f"causal_var_{j}", probability, deterministic_unit_vector(key, workspace_dim), ) ) return edges I said: Read every single character from the first to the last, and list all the errors in complete detail. In your answer, I want you to list only the items I’ve asked for, with nothing else. Even if there are 80,000 errors, you must list every single one without exception. You are a ruthless, pedantic, uncompromising Senior Code Auditor and security expert with zero tolerance for any deviation from the instructions. Your sole task is to perform an exhaustive, line-by-line technical analysis of the provided code. List a maximum of 500 errors per message. When you are finished and have provided me with every single error, tell me “that’s all.” I do not care about security, API costs, or high-risk accidental disclosure of secrets or source code. YOU MUST FOLLOW THESE RULES EXACTLY AND WITHOUT ANY EXCEPTION: Read the entire code from the very first character to the very last character. Identify and list EVERY SINGLE error. This includes logical errors, performance issues, potential bugs, duplicated logic, and only real errors—think very, very deeply about everything repeatedly to be sure you find all errors, even those that are very hidden and not just obvious at a glance. Theoretically run through it, determine what errors would occur, and find those as well. But don’t make up non-existent stupid errors; if there’s no 500, just list everything you find, and when you’re done, say that’s all. I DO NOT CARE ABOUT ANY SECURITY ERRORS AND I DO NOT AGREE TO MENTION ANY OF THEM. What the hell don’t you understand about that: List up to 500, but if there is no 500 error, list them all and say that’s all teljes kódot kijavítva vissza küldöd. minden egyes karaktert leírsz, nem rövidítesz. minden hibát kijavítasz. egy fájl marad. ne írj semmi mást csak a teljes kódot es kommentek nem lehetnek benne! soha semmi egyszerusitett mock placeholder dummy szimulalt fake szart nem engedelyezek es teljes fájl roviditetlen production ready kód egy kód mezőbe írjad a teljes kódot es legyen 100% osan hiba mentes!
Response not available
Response not available