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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###########################################################################################################################################
|
| 2 |
+
#||||- - - |6.25.2025| - - - || LIQUID BAYES || - - - |1990two| - - -|||| #
|
| 3 |
+
###########################################################################################################################################
|
| 4 |
+
import torch
|
| 5 |
+
import torch.nn as nn
|
| 6 |
+
import torch.nn.functional as F
|
| 7 |
+
import numpy as np
|
| 8 |
+
import math
|
| 9 |
+
from collections import defaultdict
|
| 10 |
+
from typing import List, Dict, Tuple, Optional
|
| 11 |
+
|
| 12 |
+
SAFE_MIN = -1e6
|
| 13 |
+
SAFE_MAX = 1e6
|
| 14 |
+
EPS = 1e-8
|
| 15 |
+
|
| 16 |
+
#||||- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 𓅸 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -||||#
|
| 17 |
+
|
| 18 |
+
def make_safe(tensor, min_val=SAFE_MIN, max_val=SAFE_MAX):
|
| 19 |
+
tensor = torch.where(torch.isnan(tensor), torch.tensor(0.0, device=tensor.device, dtype=tensor.dtype), tensor)
|
| 20 |
+
tensor = torch.where(torch.isinf(tensor), torch.tensor(max_val, device=tensor.device, dtype=tensor.dtype), tensor)
|
| 21 |
+
return torch.clamp(tensor, min_val, max_val)
|
| 22 |
+
|
| 23 |
+
def safe_softmax(x, dim=-1, temperature=1.0):
|
| 24 |
+
x = x.to(dtype=torch.float32)
|
| 25 |
+
x = make_safe(x, min_val=-50, max_val=50)
|
| 26 |
+
if isinstance(temperature, torch.Tensor):
|
| 27 |
+
temperature = float(temperature.detach().cpu().item())
|
| 28 |
+
temperature = max(float(temperature), EPS)
|
| 29 |
+
x = x / temperature
|
| 30 |
+
x = x - x.amax(dim=dim, keepdim=True)
|
| 31 |
+
return F.softmax(x, dim=dim)
|
| 32 |
+
|
| 33 |
+
###########################################################################################################################################
|
| 34 |
+
#################################################- - - LIQUID DYNAMICS CORE - - -######################################################
|
| 35 |
+
|
| 36 |
+
class LiquidDynamicsCore(nn.Module):
|
| 37 |
+
def __init__(self, state_dim, input_dim, liquid_time_constant=1.0):
|
| 38 |
+
super().__init__()
|
| 39 |
+
self.state_dim = state_dim
|
| 40 |
+
self.input_dim = input_dim
|
| 41 |
+
self.liquid_time_constant = nn.Parameter(torch.tensor(liquid_time_constant))
|
| 42 |
+
|
| 43 |
+
self.W_rec = nn.Parameter(torch.randn(state_dim, state_dim) * 0.1) # Recurrent weights
|
| 44 |
+
self.W_in = nn.Parameter(torch.randn(state_dim, input_dim) * 0.1) # Input weights
|
| 45 |
+
self.bias = nn.Parameter(torch.zeros(state_dim))
|
| 46 |
+
|
| 47 |
+
self.activation = nn.Tanh()
|
| 48 |
+
|
| 49 |
+
self.register_buffer('liquid_state', torch.zeros(1, state_dim))
|
| 50 |
+
|
| 51 |
+
self.noise_scale = nn.Parameter(torch.tensor(0.1))
|
| 52 |
+
self.exploration_rate = nn.Parameter(torch.tensor(0.05))
|
| 53 |
+
|
| 54 |
+
def reset_state(self, batch_size=1):
|
| 55 |
+
with torch.no_grad():
|
| 56 |
+
if self.liquid_state.shape[0] != batch_size:
|
| 57 |
+
self.liquid_state = torch.zeros(
|
| 58 |
+
batch_size, self.state_dim,
|
| 59 |
+
device=self.liquid_state.device,
|
| 60 |
+
dtype=self.liquid_state.dtype,
|
| 61 |
+
)
|
| 62 |
+
else:
|
| 63 |
+
self.liquid_state.zero_()
|
| 64 |
+
|
| 65 |
+
def evolve_liquid(self, input_signal, confidence_weight=1.0, dt=0.1):
|
| 66 |
+
batch_size = input_signal.shape[0]
|
| 67 |
+
|
| 68 |
+
if self.liquid_state.shape[0] != batch_size:
|
| 69 |
+
self.reset_state(batch_size)
|
| 70 |
+
|
| 71 |
+
tau = torch.clamp(self.liquid_time_constant, 0.1, 10.0)
|
| 72 |
+
|
| 73 |
+
recurrent_input = torch.matmul(self.activation(self.liquid_state), self.W_rec.T)
|
| 74 |
+
|
| 75 |
+
external_input = torch.matmul(input_signal, self.W_in.T)
|
| 76 |
+
|
| 77 |
+
dynamics = (-self.liquid_state / tau + recurrent_input + external_input + self.bias)
|
| 78 |
+
|
| 79 |
+
if isinstance(confidence_weight, torch.Tensor):
|
| 80 |
+
if confidence_weight.dim() == 1:
|
| 81 |
+
confidence_weight = confidence_weight.unsqueeze(-1)
|
| 82 |
+
confidence_weight = confidence_weight.to(self.liquid_state.dtype)
|
| 83 |
+
else:
|
| 84 |
+
confidence_weight = torch.tensor(confidence_weight, device=self.liquid_state.device, dtype=self.liquid_state.dtype)
|
| 85 |
+
|
| 86 |
+
exploration_noise = torch.randn_like(self.liquid_state) * self.noise_scale
|
| 87 |
+
exploration_strength = (1.0 - confidence_weight) * self.exploration_rate
|
| 88 |
+
|
| 89 |
+
modulated_dynamics = confidence_weight * dynamics + exploration_strength * exploration_noise
|
| 90 |
+
|
| 91 |
+
self.liquid_state.add_(dt * make_safe(modulated_dynamics))
|
| 92 |
+
|
| 93 |
+
return self.liquid_state.clone()
|
| 94 |
+
|
| 95 |
+
def get_liquid_features(self):
|
| 96 |
+
return {
|
| 97 |
+
'raw_state': self.liquid_state.clone(),
|
| 98 |
+
'activated_state': self.activation(self.liquid_state),
|
| 99 |
+
'state_energy': torch.sum(self.liquid_state ** 2, dim=-1, keepdim=True),
|
| 100 |
+
'state_entropy': self._compute_state_entropy()
|
| 101 |
+
}
|
| 102 |
+
|
| 103 |
+
def _compute_state_entropy(self):
|
| 104 |
+
state_probs = safe_softmax(self.liquid_state, dim=-1, temperature=1.0)
|
| 105 |
+
entropy = -torch.sum(state_probs * torch.log(state_probs + EPS), dim=-1, keepdim=True)
|
| 106 |
+
return entropy
|
| 107 |
+
|
| 108 |
+
###########################################################################################################################################
|
| 109 |
+
############################################- - - BAYESIAN CONFIDENCE NETWORK - - -####################################################
|
| 110 |
+
|
| 111 |
+
class BayesianConfidenceNetwork(nn.Module):
|
| 112 |
+
def __init__(self, state_dim, num_variables=5, num_states_per_var=3):
|
| 113 |
+
super().__init__()
|
| 114 |
+
self.state_dim = state_dim
|
| 115 |
+
self.num_variables = num_variables
|
| 116 |
+
self.num_states_per_var = num_states_per_var
|
| 117 |
+
|
| 118 |
+
self.feature_extractor = nn.Sequential(
|
| 119 |
+
nn.Linear(state_dim, state_dim * 2),
|
| 120 |
+
nn.LayerNorm(state_dim * 2),
|
| 121 |
+
nn.ReLU(),
|
| 122 |
+
nn.Linear(state_dim * 2, num_variables * num_states_per_var)
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
self.conditional_prob_tables = nn.ParameterList([
|
| 126 |
+
nn.Parameter(torch.randn(num_states_per_var, num_states_per_var * (num_variables - 1)) * 0.1)
|
| 127 |
+
for _ in range(num_variables)
|
| 128 |
+
])
|
| 129 |
+
|
| 130 |
+
self.priors = nn.Parameter(torch.ones(num_variables, num_states_per_var))
|
| 131 |
+
|
| 132 |
+
self.confidence_net = nn.Sequential(
|
| 133 |
+
nn.Linear(num_variables, num_variables * 2),
|
| 134 |
+
nn.ReLU(),
|
| 135 |
+
nn.Linear(num_variables * 2, 1),
|
| 136 |
+
nn.Sigmoid()
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
self.uncertainty_estimator = nn.Sequential(
|
| 140 |
+
nn.Linear(state_dim, state_dim),
|
| 141 |
+
nn.ReLU(),
|
| 142 |
+
nn.Linear(state_dim, 1),
|
| 143 |
+
nn.Sigmoid()
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def extract_variable_beliefs(self, liquid_features):
|
| 147 |
+
liquid_state = liquid_features['activated_state']
|
| 148 |
+
|
| 149 |
+
evidence = self.feature_extractor(liquid_state)
|
| 150 |
+
evidence = evidence.view(-1, self.num_variables, self.num_states_per_var)
|
| 151 |
+
|
| 152 |
+
variable_beliefs = safe_softmax(evidence, dim=-1)
|
| 153 |
+
|
| 154 |
+
return variable_beliefs
|
| 155 |
+
|
| 156 |
+
def bayesian_inference(self, variable_beliefs):
|
| 157 |
+
batch_size = variable_beliefs.shape[0]
|
| 158 |
+
device = variable_beliefs.device
|
| 159 |
+
|
| 160 |
+
current_beliefs = safe_softmax(self.priors.unsqueeze(0).expand(batch_size, -1, -1), dim=-1)
|
| 161 |
+
|
| 162 |
+
for iteration in range(3): # Few iterations for efficiency
|
| 163 |
+
new_beliefs = current_beliefs.clone()
|
| 164 |
+
|
| 165 |
+
for var_idx in range(self.num_variables):
|
| 166 |
+
evidence = variable_beliefs[:, var_idx, :]
|
| 167 |
+
|
| 168 |
+
if self.num_variables > 1:
|
| 169 |
+
other_var_beliefs = torch.cat([
|
| 170 |
+
current_beliefs[:, :var_idx].flatten(1),
|
| 171 |
+
current_beliefs[:, var_idx+1:].flatten(1)
|
| 172 |
+
], dim=1)
|
| 173 |
+
else:
|
| 174 |
+
other_var_beliefs = torch.zeros(batch_size, 0, device=device)
|
| 175 |
+
|
| 176 |
+
if other_var_beliefs.shape[1] > 0:
|
| 177 |
+
cond_probs = torch.matmul(other_var_beliefs, self.conditional_prob_tables[var_idx].T)
|
| 178 |
+
cond_probs = safe_softmax(cond_probs, dim=-1)
|
| 179 |
+
else:
|
| 180 |
+
cond_probs = torch.ones_like(evidence) / self.num_states_per_var
|
| 181 |
+
|
| 182 |
+
combined = evidence * cond_probs
|
| 183 |
+
new_beliefs[:, var_idx, :] = safe_softmax(combined, dim=-1)
|
| 184 |
+
|
| 185 |
+
current_beliefs = new_beliefs
|
| 186 |
+
|
| 187 |
+
return current_beliefs
|
| 188 |
+
|
| 189 |
+
def compute_confidence(self, beliefs, liquid_features):
|
| 190 |
+
belief_entropy = -torch.sum(beliefs * torch.log(beliefs + EPS), dim=-1)
|
| 191 |
+
avg_entropy = belief_entropy.mean(dim=-1, keepdim=True)
|
| 192 |
+
|
| 193 |
+
max_entropy = math.log(self.num_states_per_var)
|
| 194 |
+
entropy_confidence = 1.0 - (avg_entropy / max_entropy)
|
| 195 |
+
|
| 196 |
+
nn_confidence = self.confidence_net(belief_entropy)
|
| 197 |
+
|
| 198 |
+
liquid_uncertainty = self.uncertainty_estimator(liquid_features['raw_state'])
|
| 199 |
+
state_confidence = 1.0 - liquid_uncertainty
|
| 200 |
+
|
| 201 |
+
total_confidence = 0.4 * entropy_confidence + 0.3 * nn_confidence + 0.3 * state_confidence
|
| 202 |
+
|
| 203 |
+
return torch.clamp(total_confidence, 0.0, 1.0)
|
| 204 |
+
|
| 205 |
+
def forward(self, liquid_features):
|
| 206 |
+
variable_beliefs = self.extract_variable_beliefs(liquid_features)
|
| 207 |
+
|
| 208 |
+
posterior_beliefs = self.bayesian_inference(variable_beliefs)
|
| 209 |
+
|
| 210 |
+
confidence = self.compute_confidence(posterior_beliefs, liquid_features)
|
| 211 |
+
|
| 212 |
+
return {
|
| 213 |
+
'beliefs': posterior_beliefs,
|
| 214 |
+
'confidence': confidence,
|
| 215 |
+
'variable_beliefs': variable_beliefs
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
###########################################################################################################################################
|
| 219 |
+
############################################- - - LIQUID BAYES CHAIN - - -############################################################
|
| 220 |
+
|
| 221 |
+
class LiquidBayesChain(nn.Module):
|
| 222 |
+
def __init__(self, input_dim, state_dim, output_dim, num_chain_steps=3):
|
| 223 |
+
super().__init__()
|
| 224 |
+
self.input_dim = input_dim
|
| 225 |
+
self.state_dim = state_dim
|
| 226 |
+
self.output_dim = output_dim
|
| 227 |
+
self.num_chain_steps = num_chain_steps
|
| 228 |
+
|
| 229 |
+
self.liquid_core = LiquidDynamicsCore(state_dim, input_dim)
|
| 230 |
+
self.bayesian_confidence = BayesianConfidenceNetwork(state_dim)
|
| 231 |
+
|
| 232 |
+
self.final_predictor = nn.Sequential(
|
| 233 |
+
nn.Linear(state_dim, state_dim * 2),
|
| 234 |
+
nn.LayerNorm(state_dim * 2),
|
| 235 |
+
nn.ReLU(),
|
| 236 |
+
nn.Dropout(0.1),
|
| 237 |
+
nn.Linear(state_dim * 2, output_dim)
|
| 238 |
+
)
|
| 239 |
+
|
| 240 |
+
self.final_bayesian = BayesianConfidenceNetwork(output_dim, num_variables=3, num_states_per_var=4)
|
| 241 |
+
|
| 242 |
+
self.step_weights = nn.Parameter(torch.ones(num_chain_steps))
|
| 243 |
+
|
| 244 |
+
def single_chain_step(self, input_signal, step_idx=0):
|
| 245 |
+
if step_idx == 0:
|
| 246 |
+
liquid_state = self.liquid_core.evolve_liquid(input_signal, confidence_weight=1.0)
|
| 247 |
+
else:
|
| 248 |
+
liquid_features = self.liquid_core.get_liquid_features()
|
| 249 |
+
bayes_output = self.bayesian_confidence(liquid_features)
|
| 250 |
+
confidence = bayes_output['confidence']
|
| 251 |
+
|
| 252 |
+
liquid_state = self.liquid_core.evolve_liquid(input_signal, confidence_weight=confidence)
|
| 253 |
+
|
| 254 |
+
liquid_features = self.liquid_core.get_liquid_features()
|
| 255 |
+
|
| 256 |
+
bayes_output = self.bayesian_confidence(liquid_features)
|
| 257 |
+
|
| 258 |
+
return {
|
| 259 |
+
'liquid_state': liquid_state,
|
| 260 |
+
'liquid_features': liquid_features,
|
| 261 |
+
'bayes_output': bayes_output,
|
| 262 |
+
'confidence': bayes_output['confidence']
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
def forward(self, input_signal, return_chain_states=False):
|
| 266 |
+
batch_size = input_signal.shape[0]
|
| 267 |
+
|
| 268 |
+
self.liquid_core.reset_state(batch_size)
|
| 269 |
+
|
| 270 |
+
chain_states = []
|
| 271 |
+
|
| 272 |
+
for step in range(self.num_chain_steps):
|
| 273 |
+
step_output = self.single_chain_step(input_signal, step_idx=step)
|
| 274 |
+
step_output['step_idx'] = step
|
| 275 |
+
chain_states.append(step_output)
|
| 276 |
+
|
| 277 |
+
final_liquid_state = chain_states[-1]['liquid_features']['activated_state']
|
| 278 |
+
prediction_logits = self.final_predictor(final_liquid_state)
|
| 279 |
+
|
| 280 |
+
prediction_features = {
|
| 281 |
+
'raw_state': prediction_logits,
|
| 282 |
+
'activated_state': torch.tanh(prediction_logits)
|
| 283 |
+
}
|
| 284 |
+
final_bayes = self.final_bayesian(prediction_features)
|
| 285 |
+
|
| 286 |
+
step_weights = safe_softmax(self.step_weights, dim=0)
|
| 287 |
+
weighted_confidence = sum(
|
| 288 |
+
step_weights[i] * chain_states[i]['confidence']
|
| 289 |
+
for i in range(self.num_chain_steps)
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
output = {
|
| 293 |
+
'prediction': prediction_logits,
|
| 294 |
+
'final_confidence': weighted_confidence,
|
| 295 |
+
'final_beliefs': final_bayes['beliefs'],
|
| 296 |
+
'prediction_uncertainty': 1.0 - final_bayes['confidence']
|
| 297 |
+
}
|
| 298 |
+
|
| 299 |
+
if return_chain_states:
|
| 300 |
+
output['chain_states'] = chain_states
|
| 301 |
+
|
| 302 |
+
return output
|
| 303 |
+
|
| 304 |
+
def predict_with_uncertainty(self, input_signal):
|
| 305 |
+
output = self.forward(input_signal, return_chain_states=True)
|
| 306 |
+
|
| 307 |
+
uncertainty_info = {
|
| 308 |
+
'prediction': output['prediction'],
|
| 309 |
+
'confidence': output['final_confidence'],
|
| 310 |
+
'prediction_uncertainty': output['prediction_uncertainty'],
|
| 311 |
+
'chain_confidences': [state['confidence'] for state in output['chain_states']],
|
| 312 |
+
'liquid_entropies': [state['liquid_features']['state_entropy'] for state in output['chain_states']]
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
return uncertainty_info
|
| 316 |
+
|
| 317 |
+
###########################################################################################################################################
|
liquid_bayes_docs.py
ADDED
|
@@ -0,0 +1,763 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
###########################################################################################################################################
|
| 2 |
+
#||||- - - |6.25.2025| - - - || LIQUID BAYES || - - - |1990two| - - -|||| #
|
| 3 |
+
###########################################################################################################################################
|
| 4 |
+
"""
|
| 5 |
+
Mathematical Foundation & Conceptual Documentation
|
| 6 |
+
-------------------------------------------------
|
| 7 |
+
|
| 8 |
+
CORE PRINCIPLE:
|
| 9 |
+
Combines liquid state machines (continuous neural dynamics) with Bayesian inference
|
| 10 |
+
to create adaptive neural systems where probabilistic confidence modulates the
|
| 11 |
+
evolution of continuous dynamical states, enabling exploration-exploitation balance.
|
| 12 |
+
|
| 13 |
+
MATHEMATICAL FOUNDATION:
|
| 14 |
+
=======================
|
| 15 |
+
|
| 16 |
+
1. LIQUID STATE MACHINE DYNAMICS:
|
| 17 |
+
dx/dt = -x/τ + W_rec·σ(x) + W_in·u + b
|
| 18 |
+
|
| 19 |
+
Where:
|
| 20 |
+
- x: liquid state vector (membrane potentials)
|
| 21 |
+
- τ: time constant (liquid viscosity)
|
| 22 |
+
- W_rec: recurrent connection matrix
|
| 23 |
+
- W_in: input weight matrix
|
| 24 |
+
- σ: nonlinear activation function
|
| 25 |
+
- u: external input signal
|
| 26 |
+
- b: bias terms
|
| 27 |
+
|
| 28 |
+
2. CONFIDENCE-MODULATED EVOLUTION:
|
| 29 |
+
dx/dt = c·f(x,u) + (1-c)·ε·η
|
| 30 |
+
|
| 31 |
+
Where:
|
| 32 |
+
- c: Bayesian confidence score ∈ [0,1]
|
| 33 |
+
- f(x,u): standard liquid dynamics
|
| 34 |
+
- ε: exploration rate parameter
|
| 35 |
+
- η: Gaussian noise for exploration
|
| 36 |
+
|
| 37 |
+
High confidence → smooth, deterministic evolution
|
| 38 |
+
Low confidence → exploratory, stochastic behavior
|
| 39 |
+
|
| 40 |
+
3. BAYESIAN CONFIDENCE ESTIMATION:
|
| 41 |
+
P(θ|D) ∝ P(D|θ)·P(θ)
|
| 42 |
+
|
| 43 |
+
Confidence = 1 - H(P(θ|D))
|
| 44 |
+
|
| 45 |
+
Where:
|
| 46 |
+
- H: entropy function
|
| 47 |
+
- Low entropy → high confidence
|
| 48 |
+
- High entropy → low confidence
|
| 49 |
+
|
| 50 |
+
4. BELIEF PROPAGATION:
|
| 51 |
+
For Bayesian network with variables X₁...Xₙ:
|
| 52 |
+
|
| 53 |
+
P(Xi|parents(Xi)) = normalize(evidence(Xi) · ∏ messages)
|
| 54 |
+
|
| 55 |
+
Iterative message passing for approximate inference.
|
| 56 |
+
|
| 57 |
+
5. TEMPORAL INTEGRATION:
|
| 58 |
+
x(t+dt) = x(t) + dt·dx/dt
|
| 59 |
+
|
| 60 |
+
Euler integration for continuous-time dynamics.
|
| 61 |
+
|
| 62 |
+
CONCEPTUAL REASONING:
|
| 63 |
+
====================
|
| 64 |
+
|
| 65 |
+
WHY LIQUID + BAYESIAN?
|
| 66 |
+
- Traditional neural networks lack temporal dynamics
|
| 67 |
+
- Liquid state machines provide rich temporal processing
|
| 68 |
+
- Bayesian inference quantifies uncertainty in decisions
|
| 69 |
+
- Confidence feedback enables adaptive exploration
|
| 70 |
+
|
| 71 |
+
KEY INNOVATIONS:
|
| 72 |
+
1. **Confidence-Modulated Dynamics**: Uncertainty controls exploration
|
| 73 |
+
2. **Temporal Bayesian Networks**: Dynamic probabilistic reasoning
|
| 74 |
+
3. **Adaptive Time Constants**: Liquid viscosity adapts to confidence
|
| 75 |
+
4. **Hierarchical Uncertainty**: Multiple levels of uncertainty quantification
|
| 76 |
+
5. **Exploration-Exploitation Balance**: Automatic trade-off via confidence
|
| 77 |
+
|
| 78 |
+
APPLICATIONS:
|
| 79 |
+
- Adaptive control systems with uncertainty quantification
|
| 80 |
+
- Time-series prediction with confidence bounds
|
| 81 |
+
- Reinforcement learning with liquid state representations
|
| 82 |
+
- Robust decision-making under uncertainty
|
| 83 |
+
- Continuous learning systems
|
| 84 |
+
|
| 85 |
+
COMPLEXITY ANALYSIS:
|
| 86 |
+
- Liquid Evolution: O(d²) where d = state dimension
|
| 87 |
+
- Bayesian Inference: O(n·k²) where n = variables, k = states per variable
|
| 88 |
+
- Chain Execution: O(T·(d² + n·k²)) where T = chain steps
|
| 89 |
+
- Memory: O(d² + n²·k²) for connection matrices
|
| 90 |
+
|
| 91 |
+
BIOLOGICAL INSPIRATION:
|
| 92 |
+
- Membrane potential dynamics in neural circuits
|
| 93 |
+
- Confidence-based neuromodulation (dopamine, norepinephrine)
|
| 94 |
+
- Bayesian brain hypothesis for uncertainty processing
|
| 95 |
+
- Liquid computing in cortical microcircuits
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
from __future__ import annotations
|
| 99 |
+
import torch
|
| 100 |
+
import torch.nn as nn
|
| 101 |
+
import torch.nn.functional as F
|
| 102 |
+
import numpy as np
|
| 103 |
+
import math
|
| 104 |
+
from collections import defaultdict
|
| 105 |
+
from typing import List, Dict, Tuple, Optional
|
| 106 |
+
|
| 107 |
+
SAFE_MIN = -1e6
|
| 108 |
+
SAFE_MAX = 1e6
|
| 109 |
+
EPS = 1e-8
|
| 110 |
+
|
| 111 |
+
#||||- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - 𓅸 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -||||#
|
| 112 |
+
|
| 113 |
+
def make_safe(tensor, min_val=SAFE_MIN, max_val=SAFE_MAX):
|
| 114 |
+
tensor = torch.where(torch.isnan(tensor), torch.tensor(0.0, device=tensor.device, dtype=tensor.dtype), tensor)
|
| 115 |
+
tensor = torch.where(torch.isinf(tensor), torch.tensor(max_val, device=tensor.device, dtype=tensor.dtype), tensor)
|
| 116 |
+
return torch.clamp(tensor, min_val, max_val)
|
| 117 |
+
|
| 118 |
+
def safe_softmax(x, dim=-1, temperature=1.0):
|
| 119 |
+
x = x.to(dtype=torch.float32)
|
| 120 |
+
x = make_safe(x, min_val=-50, max_val=50)
|
| 121 |
+
# Guard temperature and improve numerical stability
|
| 122 |
+
if isinstance(temperature, torch.Tensor):
|
| 123 |
+
temperature = float(temperature.detach().cpu().item())
|
| 124 |
+
temperature = max(float(temperature), EPS)
|
| 125 |
+
x = x / temperature
|
| 126 |
+
x = x - x.amax(dim=dim, keepdim=True)
|
| 127 |
+
return F.softmax(x, dim=dim)
|
| 128 |
+
|
| 129 |
+
###########################################################################################################################################
|
| 130 |
+
#################################################- - - LIQUID DYNAMICS CORE - - -######################################################
|
| 131 |
+
|
| 132 |
+
class LiquidDynamicsCore(nn.Module):
|
| 133 |
+
"""Continuous neural dynamics with confidence-modulated evolution.
|
| 134 |
+
|
| 135 |
+
Implements liquid state machine dynamics where the evolution of continuous
|
| 136 |
+
neural states is modulated by Bayesian confidence estimates, enabling
|
| 137 |
+
adaptive exploration-exploitation behavior.
|
| 138 |
+
|
| 139 |
+
Mathematical Details:
|
| 140 |
+
- Standard dynamics: dx/dt = -x/τ + W_rec·σ(x) + W_in·u + b
|
| 141 |
+
- Confidence modulation: dx/dt = c·standard + (1-c)·exploration
|
| 142 |
+
- Euler integration: x(t+dt) = x(t) + dt·dx/dt
|
| 143 |
+
|
| 144 |
+
The liquid state represents membrane potentials of a continuous neural
|
| 145 |
+
circuit with recurrent connections and external inputs.
|
| 146 |
+
"""
|
| 147 |
+
def __init__(self, state_dim, input_dim, liquid_time_constant=1.0):
|
| 148 |
+
super().__init__()
|
| 149 |
+
self.state_dim = state_dim
|
| 150 |
+
self.input_dim = input_dim
|
| 151 |
+
self.liquid_time_constant = nn.Parameter(torch.tensor(liquid_time_constant))
|
| 152 |
+
|
| 153 |
+
# Liquid dynamics parameters
|
| 154 |
+
self.W_rec = nn.Parameter(torch.randn(state_dim, state_dim) * 0.1) # Recurrent weights
|
| 155 |
+
self.W_in = nn.Parameter(torch.randn(state_dim, input_dim) * 0.1) # Input weights
|
| 156 |
+
self.bias = nn.Parameter(torch.zeros(state_dim))
|
| 157 |
+
|
| 158 |
+
# Nonlinear activation function
|
| 159 |
+
self.activation = nn.Tanh()
|
| 160 |
+
|
| 161 |
+
# Membrane potential (liquid state)
|
| 162 |
+
self.register_buffer('liquid_state', torch.zeros(1, state_dim))
|
| 163 |
+
|
| 164 |
+
# Uncertainty injection parameters
|
| 165 |
+
self.noise_scale = nn.Parameter(torch.tensor(0.1))
|
| 166 |
+
self.exploration_rate = nn.Parameter(torch.tensor(0.05))
|
| 167 |
+
|
| 168 |
+
def reset_state(self, batch_size=1):
|
| 169 |
+
"""Reset the liquid state (preserve buffer & device)."""
|
| 170 |
+
with torch.no_grad():
|
| 171 |
+
if self.liquid_state.shape[0] != batch_size:
|
| 172 |
+
self.liquid_state = torch.zeros(
|
| 173 |
+
batch_size, self.state_dim,
|
| 174 |
+
device=self.liquid_state.device,
|
| 175 |
+
dtype=self.liquid_state.dtype,
|
| 176 |
+
)
|
| 177 |
+
else:
|
| 178 |
+
self.liquid_state.zero_()
|
| 179 |
+
|
| 180 |
+
def evolve_liquid(self, input_signal, confidence_weight=1.0, dt=0.1):
|
| 181 |
+
"""Evolve liquid state with confidence-modulated dynamics.
|
| 182 |
+
|
| 183 |
+
Implements the core liquid state machine evolution with Bayesian
|
| 184 |
+
confidence modulation. High confidence leads to smooth, deterministic
|
| 185 |
+
evolution while low confidence enables exploration through noise injection.
|
| 186 |
+
|
| 187 |
+
Mathematical Details:
|
| 188 |
+
- Decay term: -x/τ
|
| 189 |
+
- Recurrent term: W_rec·tanh(x)
|
| 190 |
+
- Input term: W_in·u
|
| 191 |
+
- Confidence modulation: c·dynamics + (1-c)·exploration
|
| 192 |
+
|
| 193 |
+
Args:
|
| 194 |
+
input_signal: External input to liquid [batch_size, input_dim]
|
| 195 |
+
confidence_weight: Confidence score(s) ∈ [0,1] modulating evolution
|
| 196 |
+
dt: Integration time step
|
| 197 |
+
|
| 198 |
+
Returns:
|
| 199 |
+
Updated liquid state [batch_size, state_dim]
|
| 200 |
+
"""
|
| 201 |
+
batch_size = input_signal.shape[0]
|
| 202 |
+
|
| 203 |
+
if self.liquid_state.shape[0] != batch_size:
|
| 204 |
+
self.reset_state(batch_size)
|
| 205 |
+
|
| 206 |
+
# Compute liquid dynamics: dx/dt = -x/τ + W_rec*σ(x) + W_in*u + b
|
| 207 |
+
tau = torch.clamp(self.liquid_time_constant, 0.1, 10.0)
|
| 208 |
+
|
| 209 |
+
# Recurrent dynamics
|
| 210 |
+
recurrent_input = torch.matmul(self.activation(self.liquid_state), self.W_rec.T)
|
| 211 |
+
|
| 212 |
+
# External input
|
| 213 |
+
external_input = torch.matmul(input_signal, self.W_in.T)
|
| 214 |
+
|
| 215 |
+
# Combined dynamics
|
| 216 |
+
dynamics = (-self.liquid_state / tau + recurrent_input + external_input + self.bias)
|
| 217 |
+
|
| 218 |
+
# Confidence-modulated evolution
|
| 219 |
+
if isinstance(confidence_weight, torch.Tensor):
|
| 220 |
+
if confidence_weight.dim() == 1:
|
| 221 |
+
confidence_weight = confidence_weight.unsqueeze(-1)
|
| 222 |
+
confidence_weight = confidence_weight.to(self.liquid_state.dtype)
|
| 223 |
+
else:
|
| 224 |
+
confidence_weight = torch.tensor(confidence_weight, device=self.liquid_state.device, dtype=self.liquid_state.dtype)
|
| 225 |
+
|
| 226 |
+
# High confidence → smooth evolution, Low confidence → exploration
|
| 227 |
+
exploration_noise = torch.randn_like(self.liquid_state) * self.noise_scale
|
| 228 |
+
exploration_strength = (1.0 - confidence_weight) * self.exploration_rate
|
| 229 |
+
|
| 230 |
+
modulated_dynamics = confidence_weight * dynamics + exploration_strength * exploration_noise
|
| 231 |
+
|
| 232 |
+
# Euler integration (keep buffer identity)
|
| 233 |
+
self.liquid_state.add_(dt * make_safe(modulated_dynamics))
|
| 234 |
+
|
| 235 |
+
return self.liquid_state.clone()
|
| 236 |
+
|
| 237 |
+
def get_liquid_features(self):
|
| 238 |
+
"""Extract multiple feature representations from liquid state.
|
| 239 |
+
|
| 240 |
+
Returns:
|
| 241 |
+
Dictionary containing:
|
| 242 |
+
- raw_state: Raw membrane potentials
|
| 243 |
+
- activated_state: Nonlinearly activated state
|
| 244 |
+
- state_energy: L2 energy of state vector
|
| 245 |
+
- state_entropy: Entropy of state distribution
|
| 246 |
+
"""
|
| 247 |
+
return {
|
| 248 |
+
'raw_state': self.liquid_state.clone(),
|
| 249 |
+
'activated_state': self.activation(self.liquid_state),
|
| 250 |
+
'state_energy': torch.sum(self.liquid_state ** 2, dim=-1, keepdim=True),
|
| 251 |
+
'state_entropy': self._compute_state_entropy()
|
| 252 |
+
}
|
| 253 |
+
|
| 254 |
+
def _compute_state_entropy(self):
|
| 255 |
+
"""Compute entropy of liquid state distribution.
|
| 256 |
+
|
| 257 |
+
Treats liquid state as a probability distribution (after softmax)
|
| 258 |
+
and computes Shannon entropy: H = -Σ p(x)·log(p(x))
|
| 259 |
+
|
| 260 |
+
Returns:
|
| 261 |
+
Entropy values [batch_size, 1]
|
| 262 |
+
"""
|
| 263 |
+
state_probs = safe_softmax(self.liquid_state, dim=-1, temperature=1.0)
|
| 264 |
+
entropy = -torch.sum(state_probs * torch.log(state_probs + EPS), dim=-1, keepdim=True)
|
| 265 |
+
return entropy
|
| 266 |
+
|
| 267 |
+
###########################################################################################################################################
|
| 268 |
+
############################################- - - BAYESIAN CONFIDENCE NETWORK - - -###################################################
|
| 269 |
+
|
| 270 |
+
class BayesianConfidenceNetwork(nn.Module):
|
| 271 |
+
"""Bayesian network for confidence estimation from liquid states.
|
| 272 |
+
|
| 273 |
+
Implements a simplified Bayesian network that performs probabilistic
|
| 274 |
+
inference over discrete variables extracted from continuous liquid states.
|
| 275 |
+
Uses belief propagation for approximate inference and estimates confidence
|
| 276 |
+
based on posterior entropy.
|
| 277 |
+
|
| 278 |
+
Mathematical Framework:
|
| 279 |
+
- Variables: X₁, X₂, ..., Xₙ with discrete states
|
| 280 |
+
- Evidence: E(Xi) from liquid state features
|
| 281 |
+
- Conditional probabilities: P(Xi|parents(Xi))
|
| 282 |
+
- Posterior beliefs: P(Xi|evidence)
|
| 283 |
+
- Confidence: 1 - H(P(Xi|evidence))
|
| 284 |
+
"""
|
| 285 |
+
def __init__(self, state_dim, num_variables=5, num_states_per_var=3):
|
| 286 |
+
super().__init__()
|
| 287 |
+
self.state_dim = state_dim
|
| 288 |
+
self.num_variables = num_variables
|
| 289 |
+
self.num_states_per_var = num_states_per_var
|
| 290 |
+
|
| 291 |
+
# Feature extraction from liquid state
|
| 292 |
+
self.feature_extractor = nn.Sequential(
|
| 293 |
+
nn.Linear(state_dim, state_dim * 2),
|
| 294 |
+
nn.LayerNorm(state_dim * 2),
|
| 295 |
+
nn.ReLU(),
|
| 296 |
+
nn.Linear(state_dim * 2, num_variables * num_states_per_var)
|
| 297 |
+
)
|
| 298 |
+
|
| 299 |
+
# Bayesian network structure (simplified - fully connected for now)
|
| 300 |
+
# Each variable can influence every other variable
|
| 301 |
+
self.conditional_prob_tables = nn.ParameterList([
|
| 302 |
+
nn.Parameter(torch.randn(num_states_per_var, num_states_per_var * (num_variables - 1)) * 0.1)
|
| 303 |
+
for _ in range(num_variables)
|
| 304 |
+
])
|
| 305 |
+
|
| 306 |
+
# Prior probabilities for each variable
|
| 307 |
+
self.priors = nn.Parameter(torch.ones(num_variables, num_states_per_var))
|
| 308 |
+
|
| 309 |
+
# Confidence calibration network
|
| 310 |
+
self.confidence_net = nn.Sequential(
|
| 311 |
+
nn.Linear(num_variables, num_variables * 2),
|
| 312 |
+
nn.ReLU(),
|
| 313 |
+
nn.Linear(num_variables * 2, 1),
|
| 314 |
+
nn.Sigmoid()
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
# Uncertainty quantification
|
| 318 |
+
self.uncertainty_estimator = nn.Sequential(
|
| 319 |
+
nn.Linear(state_dim, state_dim),
|
| 320 |
+
nn.ReLU(),
|
| 321 |
+
nn.Linear(state_dim, 1),
|
| 322 |
+
nn.Sigmoid()
|
| 323 |
+
)
|
| 324 |
+
|
| 325 |
+
def extract_variable_beliefs(self, liquid_features):
|
| 326 |
+
"""Extract discrete variable beliefs from continuous liquid state.
|
| 327 |
+
|
| 328 |
+
Maps high-dimensional continuous liquid state to evidence for
|
| 329 |
+
discrete variables in the Bayesian network.
|
| 330 |
+
|
| 331 |
+
Args:
|
| 332 |
+
liquid_features: Dictionary containing liquid state features
|
| 333 |
+
|
| 334 |
+
Returns:
|
| 335 |
+
Variable beliefs [batch_size, num_variables, num_states_per_var]
|
| 336 |
+
"""
|
| 337 |
+
# Get features from liquid state
|
| 338 |
+
liquid_state = liquid_features['activated_state']
|
| 339 |
+
|
| 340 |
+
# Extract variable evidence
|
| 341 |
+
evidence = self.feature_extractor(liquid_state)
|
| 342 |
+
evidence = evidence.view(-1, self.num_variables, self.num_states_per_var)
|
| 343 |
+
|
| 344 |
+
# Convert to probability distributions
|
| 345 |
+
variable_beliefs = safe_softmax(evidence, dim=-1)
|
| 346 |
+
|
| 347 |
+
return variable_beliefs
|
| 348 |
+
|
| 349 |
+
def bayesian_inference(self, variable_beliefs):
|
| 350 |
+
"""Perform approximate Bayesian inference via belief propagation.
|
| 351 |
+
|
| 352 |
+
Implements simplified belief propagation algorithm to compute
|
| 353 |
+
posterior beliefs over variables given evidence.
|
| 354 |
+
|
| 355 |
+
Mathematical Details:
|
| 356 |
+
- Initialize with priors: P(Xi)
|
| 357 |
+
- Iterate belief updates: P(Xi) ← normalize(evidence(Xi) · ∏ messages)
|
| 358 |
+
- Messages based on conditional probability tables
|
| 359 |
+
|
| 360 |
+
Args:
|
| 361 |
+
variable_beliefs: Evidence for variables [batch_size, num_vars, num_states]
|
| 362 |
+
|
| 363 |
+
Returns:
|
| 364 |
+
Posterior beliefs [batch_size, num_variables, num_states_per_var]
|
| 365 |
+
"""
|
| 366 |
+
batch_size = variable_beliefs.shape[0]
|
| 367 |
+
device = variable_beliefs.device
|
| 368 |
+
|
| 369 |
+
# Initialize with priors
|
| 370 |
+
current_beliefs = safe_softmax(self.priors.unsqueeze(0).expand(batch_size, -1, -1), dim=-1)
|
| 371 |
+
|
| 372 |
+
# Iterative belief propagation (simplified)
|
| 373 |
+
for iteration in range(3): # Few iterations for efficiency
|
| 374 |
+
new_beliefs = current_beliefs.clone()
|
| 375 |
+
|
| 376 |
+
for var_idx in range(self.num_variables):
|
| 377 |
+
# Get evidence for this variable
|
| 378 |
+
evidence = variable_beliefs[:, var_idx, :]
|
| 379 |
+
|
| 380 |
+
# Get conditional probabilities from other variables
|
| 381 |
+
if self.num_variables > 1:
|
| 382 |
+
other_var_beliefs = torch.cat([
|
| 383 |
+
current_beliefs[:, :var_idx].flatten(1),
|
| 384 |
+
current_beliefs[:, var_idx+1:].flatten(1)
|
| 385 |
+
], dim=1)
|
| 386 |
+
else:
|
| 387 |
+
other_var_beliefs = torch.zeros(batch_size, 0, device=device)
|
| 388 |
+
|
| 389 |
+
# Compute conditional probabilities
|
| 390 |
+
if other_var_beliefs.shape[1] > 0:
|
| 391 |
+
cond_probs = torch.matmul(other_var_beliefs, self.conditional_prob_tables[var_idx].T)
|
| 392 |
+
cond_probs = safe_softmax(cond_probs, dim=-1)
|
| 393 |
+
else:
|
| 394 |
+
cond_probs = torch.ones_like(evidence) / self.num_states_per_var
|
| 395 |
+
|
| 396 |
+
# Combine evidence with conditional probabilities
|
| 397 |
+
combined = evidence * cond_probs
|
| 398 |
+
new_beliefs[:, var_idx, :] = safe_softmax(combined, dim=-1)
|
| 399 |
+
|
| 400 |
+
current_beliefs = new_beliefs
|
| 401 |
+
|
| 402 |
+
return current_beliefs
|
| 403 |
+
|
| 404 |
+
def compute_confidence(self, beliefs, liquid_features):
|
| 405 |
+
"""Compute confidence score from Bayesian beliefs and liquid features.
|
| 406 |
+
|
| 407 |
+
Combines multiple sources of confidence information:
|
| 408 |
+
1. Belief sharpness (low entropy = high confidence)
|
| 409 |
+
2. Neural confidence estimation
|
| 410 |
+
3. Liquid state uncertainty
|
| 411 |
+
|
| 412 |
+
Mathematical Details:
|
| 413 |
+
- Entropy confidence: 1 - H(beliefs)/H_max
|
| 414 |
+
- Combined confidence: weighted average of sources
|
| 415 |
+
|
| 416 |
+
Args:
|
| 417 |
+
beliefs: Posterior beliefs [batch_size, num_vars, num_states]
|
| 418 |
+
liquid_features: Dictionary of liquid state features
|
| 419 |
+
|
| 420 |
+
Returns:
|
| 421 |
+
Confidence scores [batch_size, 1]
|
| 422 |
+
"""
|
| 423 |
+
# Confidence based on belief sharpness (low entropy = high confidence)
|
| 424 |
+
belief_entropy = -torch.sum(beliefs * torch.log(beliefs + EPS), dim=-1)
|
| 425 |
+
avg_entropy = belief_entropy.mean(dim=-1, keepdim=True)
|
| 426 |
+
|
| 427 |
+
# Normalize entropy to confidence (low entropy = high confidence)
|
| 428 |
+
max_entropy = math.log(self.num_states_per_var)
|
| 429 |
+
entropy_confidence = 1.0 - (avg_entropy / max_entropy)
|
| 430 |
+
|
| 431 |
+
# Additional confidence from neural network
|
| 432 |
+
nn_confidence = self.confidence_net(belief_entropy)
|
| 433 |
+
|
| 434 |
+
# Uncertainty from liquid state
|
| 435 |
+
liquid_uncertainty = self.uncertainty_estimator(liquid_features['raw_state'])
|
| 436 |
+
state_confidence = 1.0 - liquid_uncertainty
|
| 437 |
+
|
| 438 |
+
# Combine confidence sources
|
| 439 |
+
total_confidence = 0.4 * entropy_confidence + 0.3 * nn_confidence + 0.3 * state_confidence
|
| 440 |
+
|
| 441 |
+
return torch.clamp(total_confidence, 0.0, 1.0)
|
| 442 |
+
|
| 443 |
+
def forward(self, liquid_features):
|
| 444 |
+
"""Complete forward pass: feature extraction → inference → confidence.
|
| 445 |
+
|
| 446 |
+
Args:
|
| 447 |
+
liquid_features: Dictionary containing liquid state features
|
| 448 |
+
|
| 449 |
+
Returns:
|
| 450 |
+
Dictionary containing:
|
| 451 |
+
- beliefs: Posterior beliefs over variables
|
| 452 |
+
- confidence: Overall confidence score
|
| 453 |
+
- variable_beliefs: Raw variable evidence
|
| 454 |
+
"""
|
| 455 |
+
# Extract variable beliefs from liquid state
|
| 456 |
+
variable_beliefs = self.extract_variable_beliefs(liquid_features)
|
| 457 |
+
|
| 458 |
+
# Perform Bayesian inference
|
| 459 |
+
posterior_beliefs = self.bayesian_inference(variable_beliefs)
|
| 460 |
+
|
| 461 |
+
# Compute confidence
|
| 462 |
+
confidence = self.compute_confidence(posterior_beliefs, liquid_features)
|
| 463 |
+
|
| 464 |
+
return {
|
| 465 |
+
'beliefs': posterior_beliefs,
|
| 466 |
+
'confidence': confidence,
|
| 467 |
+
'variable_beliefs': variable_beliefs
|
| 468 |
+
}
|
| 469 |
+
|
| 470 |
+
###########################################################################################################################################
|
| 471 |
+
############################################- - - LIQUID BAYES CHAIN - - -############################################################
|
| 472 |
+
|
| 473 |
+
class LiquidBayesChain(nn.Module):
|
| 474 |
+
"""Complete Liquid-Bayes system with iterative refinement chain.
|
| 475 |
+
|
| 476 |
+
Implements the full Liquid-Bayes architecture where liquid dynamics
|
| 477 |
+
and Bayesian confidence estimation form a feedback loop over multiple
|
| 478 |
+
chain steps, enabling progressive refinement of predictions.
|
| 479 |
+
|
| 480 |
+
Architecture:
|
| 481 |
+
1. Liquid evolution (confidence-modulated)
|
| 482 |
+
2. Bayesian confidence estimation
|
| 483 |
+
3. Feedback to liquid dynamics
|
| 484 |
+
4. Repeat for multiple chain steps
|
| 485 |
+
5. Final prediction with uncertainty quantification
|
| 486 |
+
|
| 487 |
+
The chain allows the system to iteratively improve its predictions
|
| 488 |
+
by using confidence estimates to guide further exploration or exploitation.
|
| 489 |
+
"""
|
| 490 |
+
def __init__(self, input_dim, state_dim, output_dim, num_chain_steps=3):
|
| 491 |
+
super().__init__()
|
| 492 |
+
self.input_dim = input_dim
|
| 493 |
+
self.state_dim = state_dim
|
| 494 |
+
self.output_dim = output_dim
|
| 495 |
+
self.num_chain_steps = num_chain_steps
|
| 496 |
+
|
| 497 |
+
# Core components
|
| 498 |
+
self.liquid_core = LiquidDynamicsCore(state_dim, input_dim)
|
| 499 |
+
self.bayesian_confidence = BayesianConfidenceNetwork(state_dim)
|
| 500 |
+
|
| 501 |
+
# Final prediction network
|
| 502 |
+
self.final_predictor = nn.Sequential(
|
| 503 |
+
nn.Linear(state_dim, state_dim * 2),
|
| 504 |
+
nn.LayerNorm(state_dim * 2),
|
| 505 |
+
nn.ReLU(),
|
| 506 |
+
nn.Dropout(0.1),
|
| 507 |
+
nn.Linear(state_dim * 2, output_dim)
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
# Final Bayesian uncertainty estimation
|
| 511 |
+
self.final_bayesian = BayesianConfidenceNetwork(output_dim, num_variables=3, num_states_per_var=4)
|
| 512 |
+
|
| 513 |
+
# Chain step weights (learnable importance of each step)
|
| 514 |
+
self.step_weights = nn.Parameter(torch.ones(num_chain_steps))
|
| 515 |
+
|
| 516 |
+
def single_chain_step(self, input_signal, step_idx=0):
|
| 517 |
+
"""Execute one step of the Liquid-Bayes feedback chain.
|
| 518 |
+
|
| 519 |
+
Each chain step consists of:
|
| 520 |
+
1. Evolve liquid dynamics (with confidence modulation if not first step)
|
| 521 |
+
2. Extract features from liquid state
|
| 522 |
+
3. Perform Bayesian confidence assessment
|
| 523 |
+
|
| 524 |
+
Args:
|
| 525 |
+
input_signal: External input to liquid [batch_size, input_dim]
|
| 526 |
+
step_idx: Current step index in chain
|
| 527 |
+
|
| 528 |
+
Returns:
|
| 529 |
+
Dictionary containing step outputs and intermediate states
|
| 530 |
+
"""
|
| 531 |
+
# Step 1: Evolve liquid state
|
| 532 |
+
if step_idx == 0:
|
| 533 |
+
# First step - no confidence modulation
|
| 534 |
+
liquid_state = self.liquid_core.evolve_liquid(input_signal, confidence_weight=1.0)
|
| 535 |
+
else:
|
| 536 |
+
# Get confidence from previous step
|
| 537 |
+
liquid_features = self.liquid_core.get_liquid_features()
|
| 538 |
+
bayes_output = self.bayesian_confidence(liquid_features)
|
| 539 |
+
confidence = bayes_output['confidence']
|
| 540 |
+
|
| 541 |
+
# Step 2: Confidence-modulated liquid evolution
|
| 542 |
+
liquid_state = self.liquid_core.evolve_liquid(input_signal, confidence_weight=confidence)
|
| 543 |
+
|
| 544 |
+
# Get updated liquid features
|
| 545 |
+
liquid_features = self.liquid_core.get_liquid_features()
|
| 546 |
+
|
| 547 |
+
# Step 3: Bayesian confidence assessment
|
| 548 |
+
bayes_output = self.bayesian_confidence(liquid_features)
|
| 549 |
+
|
| 550 |
+
return {
|
| 551 |
+
'liquid_state': liquid_state,
|
| 552 |
+
'liquid_features': liquid_features,
|
| 553 |
+
'bayes_output': bayes_output,
|
| 554 |
+
'confidence': bayes_output['confidence']
|
| 555 |
+
}
|
| 556 |
+
|
| 557 |
+
def forward(self, input_signal, return_chain_states=False):
|
| 558 |
+
"""Execute complete Liquid-Bayes chain with iterative refinement.
|
| 559 |
+
|
| 560 |
+
Args:
|
| 561 |
+
input_signal: Input to process [batch_size, input_dim]
|
| 562 |
+
return_chain_states: Whether to return intermediate chain states
|
| 563 |
+
|
| 564 |
+
Returns:
|
| 565 |
+
Dictionary containing:
|
| 566 |
+
- prediction: Final output predictions
|
| 567 |
+
- final_confidence: Weighted confidence across chain
|
| 568 |
+
- final_beliefs: Final Bayesian beliefs
|
| 569 |
+
- prediction_uncertainty: Uncertainty in predictions
|
| 570 |
+
- chain_states: Intermediate states (if requested)
|
| 571 |
+
"""
|
| 572 |
+
batch_size = input_signal.shape[0]
|
| 573 |
+
|
| 574 |
+
# Reset liquid state
|
| 575 |
+
self.liquid_core.reset_state(batch_size)
|
| 576 |
+
|
| 577 |
+
# Store chain states for analysis
|
| 578 |
+
chain_states = []
|
| 579 |
+
|
| 580 |
+
# Execute chain steps
|
| 581 |
+
for step in range(self.num_chain_steps):
|
| 582 |
+
step_output = self.single_chain_step(input_signal, step_idx=step)
|
| 583 |
+
step_output['step_idx'] = step
|
| 584 |
+
chain_states.append(step_output)
|
| 585 |
+
|
| 586 |
+
# Final prediction from last liquid state
|
| 587 |
+
final_liquid_state = chain_states[-1]['liquid_features']['activated_state']
|
| 588 |
+
prediction_logits = self.final_predictor(final_liquid_state)
|
| 589 |
+
|
| 590 |
+
# Final Bayesian uncertainty quantification
|
| 591 |
+
prediction_features = {
|
| 592 |
+
'raw_state': prediction_logits,
|
| 593 |
+
'activated_state': torch.tanh(prediction_logits)
|
| 594 |
+
}
|
| 595 |
+
final_bayes = self.final_bayesian(prediction_features)
|
| 596 |
+
|
| 597 |
+
# Weighted combination of confidence scores across chain
|
| 598 |
+
step_weights = safe_softmax(self.step_weights, dim=0)
|
| 599 |
+
weighted_confidence = sum(
|
| 600 |
+
step_weights[i] * chain_states[i]['confidence']
|
| 601 |
+
for i in range(self.num_chain_steps)
|
| 602 |
+
)
|
| 603 |
+
|
| 604 |
+
output = {
|
| 605 |
+
'prediction': prediction_logits,
|
| 606 |
+
'final_confidence': weighted_confidence,
|
| 607 |
+
'final_beliefs': final_bayes['beliefs'],
|
| 608 |
+
'prediction_uncertainty': 1.0 - final_bayes['confidence']
|
| 609 |
+
}
|
| 610 |
+
|
| 611 |
+
if return_chain_states:
|
| 612 |
+
output['chain_states'] = chain_states
|
| 613 |
+
|
| 614 |
+
return output
|
| 615 |
+
|
| 616 |
+
def predict_with_uncertainty(self, input_signal):
|
| 617 |
+
"""Make predictions with comprehensive uncertainty quantification.
|
| 618 |
+
|
| 619 |
+
Provides detailed uncertainty analysis including:
|
| 620 |
+
- Final prediction confidence
|
| 621 |
+
- Chain-step progression
|
| 622 |
+
- Liquid state entropy evolution
|
| 623 |
+
|
| 624 |
+
Args:
|
| 625 |
+
input_signal: Input to process [batch_size, input_dim]
|
| 626 |
+
|
| 627 |
+
Returns:
|
| 628 |
+
Dictionary with comprehensive uncertainty information
|
| 629 |
+
"""
|
| 630 |
+
output = self.forward(input_signal, return_chain_states=True)
|
| 631 |
+
|
| 632 |
+
# Extract uncertainty information
|
| 633 |
+
uncertainty_info = {
|
| 634 |
+
'prediction': output['prediction'],
|
| 635 |
+
'confidence': output['final_confidence'],
|
| 636 |
+
'prediction_uncertainty': output['prediction_uncertainty'],
|
| 637 |
+
'chain_confidences': [state['confidence'] for state in output['chain_states']],
|
| 638 |
+
'liquid_entropies': [state['liquid_features']['state_entropy'] for state in output['chain_states']]
|
| 639 |
+
}
|
| 640 |
+
|
| 641 |
+
return uncertainty_info
|
| 642 |
+
|
| 643 |
+
###########################################################################################################################################
|
| 644 |
+
##################################################- - - DEMO AND TESTING - - -#########################################################
|
| 645 |
+
|
| 646 |
+
def test_liquid_bayes_chain():
|
| 647 |
+
print(" Testing Liquid Bayes Chain - Probabilistic Control of Continuous Dynamics")
|
| 648 |
+
print("=" * 80)
|
| 649 |
+
|
| 650 |
+
# Create Liquid-Bayes chain
|
| 651 |
+
input_dim = 32
|
| 652 |
+
state_dim = 64
|
| 653 |
+
output_dim = 10
|
| 654 |
+
|
| 655 |
+
model = LiquidBayesChain(
|
| 656 |
+
input_dim=input_dim,
|
| 657 |
+
state_dim=state_dim,
|
| 658 |
+
output_dim=output_dim,
|
| 659 |
+
num_chain_steps=4
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
print(f"Created Liquid-Bayes Chain:")
|
| 663 |
+
print(f" - Input dimension: {input_dim}")
|
| 664 |
+
print(f" - Liquid state dimension: {state_dim}")
|
| 665 |
+
print(f" - Output dimension: {output_dim}")
|
| 666 |
+
print(f" - Chain steps: {model.num_chain_steps}")
|
| 667 |
+
|
| 668 |
+
# Generate test data
|
| 669 |
+
batch_size = 8
|
| 670 |
+
test_input = torch.randn(batch_size, input_dim)
|
| 671 |
+
|
| 672 |
+
print(f"\nTesting with batch size: {batch_size}")
|
| 673 |
+
|
| 674 |
+
# Test forward pass
|
| 675 |
+
print("\nExecuting Liquid-Bayes chain...")
|
| 676 |
+
output = model(test_input, return_chain_states=True)
|
| 677 |
+
|
| 678 |
+
print("Chain execution results:")
|
| 679 |
+
print(f" - Final prediction shape: {output['prediction'].shape}")
|
| 680 |
+
print(f" - Average confidence: {output['final_confidence'].mean():.3f}")
|
| 681 |
+
print(f" - Average uncertainty: {output['prediction_uncertainty'].mean():.3f}")
|
| 682 |
+
|
| 683 |
+
# Analyze chain progression
|
| 684 |
+
print("\nChain step analysis:")
|
| 685 |
+
for i, state in enumerate(output['chain_states']):
|
| 686 |
+
conf = state['confidence'].mean().item()
|
| 687 |
+
entropy = state['liquid_features']['state_entropy'].mean().item()
|
| 688 |
+
print(f" Step {i+1}: Confidence={conf:.3f}, Liquid Entropy={entropy:.3f}")
|
| 689 |
+
|
| 690 |
+
# Test uncertainty prediction
|
| 691 |
+
print("\nTesting uncertainty quantification...")
|
| 692 |
+
uncertainty_output = model.predict_with_uncertainty(test_input[:3])
|
| 693 |
+
|
| 694 |
+
print("Uncertainty analysis:")
|
| 695 |
+
for i in range(3):
|
| 696 |
+
conf = uncertainty_output['confidence'][i].item()
|
| 697 |
+
pred_unc = uncertainty_output['prediction_uncertainty'][i].item()
|
| 698 |
+
print(f" Sample {i+1}: Confidence={conf:.3f}, Prediction Uncertainty={pred_unc:.3f}")
|
| 699 |
+
|
| 700 |
+
# Test adaptive behavior
|
| 701 |
+
print("\nTesting adaptive behavior with different inputs...")
|
| 702 |
+
|
| 703 |
+
# High-confidence input (structured pattern)
|
| 704 |
+
structured_input = torch.ones(1, input_dim) * 0.5
|
| 705 |
+
struct_output = model(structured_input)
|
| 706 |
+
struct_conf = struct_output['final_confidence'].item()
|
| 707 |
+
|
| 708 |
+
# Low-confidence input (random noise)
|
| 709 |
+
noisy_input = torch.randn(1, input_dim) * 2.0
|
| 710 |
+
noisy_output = model(noisy_input)
|
| 711 |
+
noisy_conf = noisy_output['final_confidence'].item()
|
| 712 |
+
|
| 713 |
+
print(f" Structured input confidence: {struct_conf:.3f}")
|
| 714 |
+
print(f" Noisy input confidence: {noisy_conf:.3f}")
|
| 715 |
+
print(f" Confidence difference: {abs(struct_conf - noisy_conf):.3f}")
|
| 716 |
+
|
| 717 |
+
print("\nLiquid-Bayes Chain test completed!")
|
| 718 |
+
print("✓ Liquid dynamics evolve with Bayesian confidence modulation")
|
| 719 |
+
print("✓ Probabilistic feedback loop controls exploration vs exploitation")
|
| 720 |
+
print("✓ Full uncertainty quantification throughout the chain")
|
| 721 |
+
print("✓ Adaptive behavior based on input characteristics")
|
| 722 |
+
|
| 723 |
+
return True
|
| 724 |
+
|
| 725 |
+
def confidence_modulation_demo():
|
| 726 |
+
"""Demonstrate how Bayesian confidence modulates liquid evolution."""
|
| 727 |
+
print("\n" + "="*60)
|
| 728 |
+
print(" CONFIDENCE MODULATION DEMO")
|
| 729 |
+
print("="*60)
|
| 730 |
+
|
| 731 |
+
# Create simplified model
|
| 732 |
+
model = LiquidBayesChain(input_dim=16, state_dim=32, output_dim=5, num_chain_steps=3)
|
| 733 |
+
|
| 734 |
+
# Test with controlled confidence scenarios
|
| 735 |
+
scenarios = [
|
| 736 |
+
("High Confidence Input", torch.ones(1, 16) * 0.3), # Structured
|
| 737 |
+
("Medium Confidence Input", torch.randn(1, 16) * 0.5), # Moderate noise
|
| 738 |
+
("Low Confidence Input", torch.randn(1, 16) * 2.0), # High noise
|
| 739 |
+
]
|
| 740 |
+
|
| 741 |
+
print("Testing confidence-driven adaptation:")
|
| 742 |
+
|
| 743 |
+
for name, test_input in scenarios:
|
| 744 |
+
output = model(test_input, return_chain_states=True)
|
| 745 |
+
|
| 746 |
+
# Extract confidence progression
|
| 747 |
+
confidences = [state['confidence'].item() for state in output['chain_states']]
|
| 748 |
+
entropies = [state['liquid_features']['state_entropy'].item() for state in output['chain_states']]
|
| 749 |
+
|
| 750 |
+
print(f"\n{name}:")
|
| 751 |
+
print(f" Chain confidences: {[f'{c:.3f}' for c in confidences]}")
|
| 752 |
+
print(f" Liquid entropies: {[f'{e:.3f}' for e in entropies]}")
|
| 753 |
+
print(f" Final confidence: {output['final_confidence'].item():.3f}")
|
| 754 |
+
|
| 755 |
+
print("\n Demo shows how liquid dynamics adapt based on Bayesian confidence!")
|
| 756 |
+
print(" High confidence → stable evolution, Low confidence → exploration")
|
| 757 |
+
|
| 758 |
+
if __name__ == "__main__":
|
| 759 |
+
test_liquid_bayes_chain()
|
| 760 |
+
confidence_modulation_demo()
|
| 761 |
+
|
| 762 |
+
###########################################################################################################################################
|
| 763 |
+
###########################################################################################################################################
|