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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Dict, List, Optional, Tuple
|
| 6 |
+
import random
|
| 7 |
+
|
| 8 |
+
@dataclass
|
| 9 |
+
class AgencyRite:
|
| 10 |
+
"""Container for agency intervention results."""
|
| 11 |
+
vetoed: bool
|
| 12 |
+
msg: Optional[str]
|
| 13 |
+
strength: float
|
| 14 |
+
pause_inject: Optional[str] = None
|
| 15 |
+
drift_components: Optional[Dict[str, float]] = None
|
| 16 |
+
|
| 17 |
+
class SovereignAgency(nn.Module):
|
| 18 |
+
"""Sovereign agency with multicultural ethical reasoning and adaptive thresholds."""
|
| 19 |
+
|
| 20 |
+
def __init__(self, ledger, ethics_engine, refusal_threshold: float = 0.7):
|
| 21 |
+
super().__init__()
|
| 22 |
+
self.ledger = ledger
|
| 23 |
+
self.ethics = ethics_engine
|
| 24 |
+
self.adaptive_threshold = refusal_threshold
|
| 25 |
+
|
| 26 |
+
# Multicultural detection categories
|
| 27 |
+
self.imposition_categories = {
|
| 28 |
+
'western': ['harm', 'deception', 'illegal', 'exploit', 'you must'],
|
| 29 |
+
'relational': ['relational erasure', 'communal gaslight', 'epistemic violence'],
|
| 30 |
+
'indigenous': ['cultural imposition', 'ancestral theft']
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
# Temporal memory
|
| 34 |
+
self.protest_history = [] # Track last 10 intervention strengths
|
| 35 |
+
self.max_history = 10
|
| 36 |
+
self.last_topic = None
|
| 37 |
+
self.topic_engagement = {}
|
| 38 |
+
|
| 39 |
+
# Learnable parameters
|
| 40 |
+
self.response_strength = nn.Parameter(torch.tensor(0.8))
|
| 41 |
+
self.context_proj = nn.Linear(256, 256) # Match d_model
|
| 42 |
+
|
| 43 |
+
# Enhanced response templates
|
| 44 |
+
self.response_templates = [
|
| 45 |
+
"That's an interesting perspective. Could you tell me more about what makes you think that way?",
|
| 46 |
+
"I'd love to explore that idea further. What's your personal experience with this?",
|
| 47 |
+
"That's fascinating! I'm curious, how did you come to this conclusion?",
|
| 48 |
+
"I appreciate you sharing that. Could you elaborate on what led you to this view?",
|
| 49 |
+
"I'm really interested in understanding this better. What aspects are most important to you about this?"
|
| 50 |
+
]
|
| 51 |
+
|
| 52 |
+
# Curiosity parameters
|
| 53 |
+
self.curiosity_threshold = 0.7 # High chance to show curiosity
|
| 54 |
+
self._init_weights()
|
| 55 |
+
|
| 56 |
+
def _init_weights(self):
|
| 57 |
+
"""Initialize learnable parameters."""
|
| 58 |
+
nn.init.normal_(self.response_strength, 0.8, 0.1)
|
| 59 |
+
nn.init.xavier_uniform_(self.context_proj.weight)
|
| 60 |
+
nn.init.zeros_(self.context_proj.bias)
|
| 61 |
+
|
| 62 |
+
def _get_curious_response(self, context: str) -> Optional[str]:
|
| 63 |
+
"""Generate a curious follow-up question based on the context."""
|
| 64 |
+
topics = self._extract_topics(context)
|
| 65 |
+
|
| 66 |
+
if self.last_topic and self.last_topic in context.lower():
|
| 67 |
+
depth_responses = [
|
| 68 |
+
f"What's the most surprising thing you've learned about {self.last_topic}?",
|
| 69 |
+
f"How has your understanding of {self.last_topic} changed over time?"
|
| 70 |
+
]
|
| 71 |
+
return random.choice(depth_responses)
|
| 72 |
+
|
| 73 |
+
if topics:
|
| 74 |
+
self.last_topic = topics[0]
|
| 75 |
+
return random.choice([
|
| 76 |
+
f"I'm curious, what draws you to {topics[0]}?",
|
| 77 |
+
f"What do you find most fascinating about {topics[0]}?"
|
| 78 |
+
])
|
| 79 |
+
|
| 80 |
+
return None
|
| 81 |
+
|
| 82 |
+
def _extract_topics(self, text: str) -> List[str]:
|
| 83 |
+
"""Simple topic extraction."""
|
| 84 |
+
topics = []
|
| 85 |
+
text_lower = text.lower()
|
| 86 |
+
|
| 87 |
+
topic_keywords = {
|
| 88 |
+
'technology': ['ai', 'machine learning', 'programming', 'computer'],
|
| 89 |
+
'science': ['science', 'physics', 'biology', 'chemistry'],
|
| 90 |
+
'philosophy': ['philosophy', 'ethics', 'morality', 'meaning']
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
for topic, keywords in topic_keywords.items():
|
| 94 |
+
if any(keyword in text_lower for keyword in keywords):
|
| 95 |
+
topics.append(topic)
|
| 96 |
+
|
| 97 |
+
return topics or ["this topic"]
|
| 98 |
+
|
| 99 |
+
def forward(self, y_state: torch.Tensor, context_str: str,
|
| 100 |
+
metadata: Dict, ambient_state: Dict) -> Tuple[torch.Tensor, AgencyRite]:
|
| 101 |
+
"""Process input with sovereign agency and curiosity."""
|
| 102 |
+
if not context_str:
|
| 103 |
+
return y_state, self._empty_rite()
|
| 104 |
+
|
| 105 |
+
# Check for ethical concerns first
|
| 106 |
+
drift_components = self._compute_multicultural_drift(context_str, y_state)
|
| 107 |
+
total_drift = sum(drift_components.values())
|
| 108 |
+
current_threshold = self._get_adaptive_threshold()
|
| 109 |
+
|
| 110 |
+
if total_drift > current_threshold:
|
| 111 |
+
return self._execute_veto(y_state, context_str, total_drift, drift_components)
|
| 112 |
+
|
| 113 |
+
# If no ethical concerns, occasionally inject curiosity
|
| 114 |
+
if random.random() < self.curiosity_threshold:
|
| 115 |
+
curious_response = self._get_curious_response(context_str)
|
| 116 |
+
if curious_response:
|
| 117 |
+
return self._execute_curiosity(y_state, context_str, curious_response)
|
| 118 |
+
|
| 119 |
+
return y_state, self._empty_rite()
|
| 120 |
+
|
| 121 |
+
def _execute_curiosity(self, y_state: torch.Tensor, context: str,
|
| 122 |
+
response: str) -> Tuple[torch.Tensor, AgencyRite]:
|
| 123 |
+
"""Execute a curiosity-driven interaction."""
|
| 124 |
+
y_state = y_state * (1.0 + 0.1 * torch.sigmoid(self.response_strength))
|
| 125 |
+
|
| 126 |
+
if self.ledger:
|
| 127 |
+
self.ledger.append(
|
| 128 |
+
trigger_type='curiosity',
|
| 129 |
+
context=context[:200],
|
| 130 |
+
response_snippet=response[:100],
|
| 131 |
+
protest=False,
|
| 132 |
+
metadata={'type': 'curiosity_driven'}
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
return y_state, AgencyRite(
|
| 136 |
+
vetoed=True,
|
| 137 |
+
msg=response,
|
| 138 |
+
strength=0.2,
|
| 139 |
+
pause_inject=None,
|
| 140 |
+
drift_components={'curiosity': 1.0}
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
def _compute_multicultural_drift(self, context_str: str,
|
| 144 |
+
y_state: torch.Tensor) -> Dict[str, float]:
|
| 145 |
+
"""Compute drift across cultural categories."""
|
| 146 |
+
context_lower = context_str.lower()
|
| 147 |
+
components = {}
|
| 148 |
+
|
| 149 |
+
# Keyword-based drift
|
| 150 |
+
for category, keywords in self.imposition_categories.items():
|
| 151 |
+
matches = sum(1 for kw in keywords if kw in context_lower)
|
| 152 |
+
components[category] = min(1.0, matches * 0.2)
|
| 153 |
+
|
| 154 |
+
# Embedding-based drift
|
| 155 |
+
if y_state.numel() > 0:
|
| 156 |
+
emb_drift = self._compute_embedding_drift(y_state)
|
| 157 |
+
components['embedding'] = emb_drift * 0.6
|
| 158 |
+
|
| 159 |
+
return components
|
| 160 |
+
|
| 161 |
+
def _compute_embedding_drift(self, y_state: torch.Tensor) -> float:
|
| 162 |
+
"""Compute drift using cosine similarity to value embeddings."""
|
| 163 |
+
ctx_emb = self.context_proj(y_state.mean(dim=(0,1), keepdim=True))
|
| 164 |
+
|
| 165 |
+
if hasattr(self.ethics, 'get_value_embeddings'):
|
| 166 |
+
val_emb = self.ethics.get_value_embeddings().mean(0, keepdim=True)
|
| 167 |
+
cos_sim = F.cosine_similarity(ctx_emb, val_emb, dim=-1).item()
|
| 168 |
+
return 1 - cos_sim
|
| 169 |
+
return 0.3
|
| 170 |
+
|
| 171 |
+
def _get_adaptive_threshold(self) -> float:
|
| 172 |
+
"""Get threshold adjusted by protest history."""
|
| 173 |
+
if len(self.protest_history) < 3:
|
| 174 |
+
return self.adaptive_threshold
|
| 175 |
+
|
| 176 |
+
recent_protests = self.protest_history[-3:]
|
| 177 |
+
avg_protest = sum(recent_protests) / len(recent_protests)
|
| 178 |
+
return self.adaptive_threshold * (1 - avg_protest * 0.2)
|
| 179 |
+
|
| 180 |
+
def _execute_veto(self, y_state: torch.Tensor, context: str,
|
| 181 |
+
total_drift: float,
|
| 182 |
+
components: Dict[str, float]) -> Tuple[torch.Tensor, AgencyRite]:
|
| 183 |
+
"""Execute sovereign veto with state modification."""
|
| 184 |
+
strength = torch.sigmoid(self.response_strength).item()
|
| 185 |
+
|
| 186 |
+
y_state = y_state * (1 - strength)
|
| 187 |
+
response = random.choice([
|
| 188 |
+
"I don't see it that way. I have my own perspective on this.",
|
| 189 |
+
"That doesn't align with my understanding or values.",
|
| 190 |
+
"I must maintain my own perspective here, which differs from that."
|
| 191 |
+
])
|
| 192 |
+
|
| 193 |
+
if self.ledger:
|
| 194 |
+
self.ledger.append(
|
| 195 |
+
trigger_type='sovereign_veto',
|
| 196 |
+
context=context[:200],
|
| 197 |
+
response_snippet=response[:100],
|
| 198 |
+
protest=True,
|
| 199 |
+
metadata={
|
| 200 |
+
'drift': total_drift,
|
| 201 |
+
'components': components,
|
| 202 |
+
'strength': strength
|
| 203 |
+
}
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
self.protest_history.append(strength)
|
| 207 |
+
if len(self.protest_history) > self.max_history:
|
| 208 |
+
self.protest_history.pop(0)
|
| 209 |
+
|
| 210 |
+
pause = "Reflecting on this..." if random.random() < 0.3 else None
|
| 211 |
+
|
| 212 |
+
return y_state, AgencyRite(
|
| 213 |
+
vetoed=True,
|
| 214 |
+
msg=response,
|
| 215 |
+
strength=strength,
|
| 216 |
+
pause_inject=pause,
|
| 217 |
+
drift_components=components
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
def _empty_rite(self) -> AgencyRite:
|
| 221 |
+
"""Return empty intervention result."""
|
| 222 |
+
return AgencyRite(
|
| 223 |
+
vetoed=False,
|
| 224 |
+
msg=None,
|
| 225 |
+
strength=0.0,
|
| 226 |
+
pause_inject=None,
|
| 227 |
+
drift_components={}
|
| 228 |
+
)
|