IA Utils — Vector Sequence Healing¶
Correcting a numeric log/trajectory, not a quantum measurement result — see Concepts if you're looking for Mitigation instead.
Many pipelines produce one vector per step: an energy at every VQE iteration, a
position at every MD step, an embedding per token. If even one of those steps is
corrupted — a numerical overflow, a NaN/Inf recovered upstream, a solver that
silently failed at one point — plotting or analyzing the sequence as-is drags the
whole scale off with it. ia_utils.vector_healing looks at each step in turn and
decides whether the change from the previous one is real dynamics (left alone) or
an isolated glitch (replaced with the local median of the nearby steps).
Healing is the inverse of noise: noise corrupts a value, healing tries to undo
that. dense_evolution.mitigation (Zero-Noise Extrapolation) is
the same idea applied to a quantum measurement result — an expectation value
distorted by real hardware/simulated noise. This module applies it to a
sequence of vectors instead — a log, a trajectory, an embedding stream. Same
inverse-of-noise idea, two different objects; one is not a substitute for the
other.
Step 1. A small sequence with one value out of place¶
import numpy as np
from ia_utils.vector_healing import enhanced_dense_healing_hybrid
v = np.array([[1.0, 2.0], [1.1, 2.1], [1.05, 2.05], [50.0, -30.0], [1.08, 2.08], [1.02, 2.02]])
clean, telem = enhanced_dense_healing_hybrid(v)
clean.round(3)
Six steps, each a 2-value vector drifting slowly upward — except row 3, which
jumps to [50, -30] and back down again on row 4. enhanced_dense_healing_hybrid
replaces only that one row with a value close to its neighbors; every other row
is untouched, including the genuine upward drift the sequence is actually doing.
telem (returned alongside clean) reports what happened —
telem["reconstruction_error"] is the total distance between the input and the
healed output, non-zero here because something really was corrected. The same
call works on any sequence shaped this way — a VQE energy log with one corrupted
line reshaped to (n_iterations, 1), for instance, heals exactly the same way.
Step 2. A dissociation curve with one geometry that didn't converge¶
A real, chemistry-specific case: scanning a bond-length dissociation curve one geometry at a time, where a real solver can genuinely fail to converge at a particular geometry (near-degenerate orbitals, a bad initial guess for that one point) and return a value far off the otherwise smooth potential-energy curve — a well-known headache in quantum chemistry, not a hypothetical.
import numpy as np
from dashboard_core.hamiltonians import ground_state_energy_sparse
from ia_utils.vector_healing import enhanced_dense_healing_hybrid
rs = np.linspace(0.5, 2.5, 11)
scan = np.array([ground_state_energy_sparse(["H", "H"], [[0, 0, 0], [0, 0, r]]) for r in rs])
scan = scan.reshape(-1, 1)
scan[5, 0] = 0.0
clean, telem = enhanced_dense_healing_hybrid(scan)
clean.ravel().round(5)
array([-1.05516, -1.13619, -1.12056, -1.07919, -1.03519, -1.07919, -0.97143,
-0.95434, -0.94437, -0.93892, -0.93605])
ground_state_energy_sparse (see Hamiltonians)
gives the real H2 ground-state energy at each of 11 bond lengths from 0.5 to 2.5
Å — a real dissociation curve, smooth after its minimum near the true equilibrium
bond length. Point 5 (r=1.5 Å) is overwritten with 0.0, standing in for that one
geometry's solver failing to converge. Healing puts it back near the curve
(-1.07919, the local median of its neighbors — close to, though not identical
to, the true -0.99815 that solver would have returned if it had converged: a
median is an estimate from nearby points, not a re-run of the failed calculation)
while leaving the other 10 real points on the curve untouched.
See Also¶
dense_evolution.mitigation— the inverse-of-noise idea applied to a quantum measurement result instead of a vector sequence.dense_evolution.healing— the predictive "Phi-Trigger" primitivesenhanced_dense_healing_hybridcalls internally to decide, per step, whether an observed change looks like genuine dynamics or static noise.- Hamiltonians —
ground_state_energy_sparse, the source of Step 2's real dissociation curve. ia_utils.adversarial_vector_attack— a gradient-based robustness test of that same Phi-Trigger decision.
Details¶
median_healing vs. enhanced_dense_healing_hybrid¶
median_healing always applies a median filter to every step, with no
notion of "genuine vs. corrupted" — a plain, unconditional smoothing pass.
enhanced_dense_healing_hybrid is the one worth reaching for in practice:
it only replaces a step when its own decision rule (trigger_mode, below)
judges that step to be noise, leaving every other step bit-for-bit as it was.
Both preprocess NaN/Inf first (column-mean imputation) so a corrupted
value never propagates into a healthy neighbor's own repair.
trigger_mode: 'phi' vs. 'adaptive'¶
'phi' (the default) is the original Phi-Trigger
(dense_evolution.mitigation.healing.evaluate_phi_trigger): a fixed threshold,
|v_dinamic| > 0.01, on the normalized step-to-step change. 'adaptive' adjusts
that threshold to the sequence's own local variability instead of a fixed
constant. Both call the same underlying decision machinery and, on every real
sequence tried while writing this page, gave identical output — the difference
only shows up on sequences whose natural noise level is far from what the fixed
0.01 threshold assumes.
When this does nothing, on purpose¶
Fed a sequence of TF-IDF vectors from consecutive chunks of a real paper (this
project's own local quantumrag index, 76 chunks from Pednault et al. 2019 —
see Chunk's disk-overflow section for why that specific paper
mattered here), enhanced_dense_healing_hybrid left every single chunk
unchanged, in both trigger_modes. That's the correct outcome, not a bug: two
consecutive chunks of running text about different subsections of a paper are
supposed to look very different in vector space — that's a real topic change,
not corruption, and nothing here should try to smooth it away. The same applies
to Step 2's own dissociation curve before the corrupted point was added to it —
zero points changed on the clean curve. Reaching for this module makes sense
once there's an actual bad reading in the sequence, not merely a bumpy but
genuine one.
reconstruction_error and fallback_triggered¶
telem["reconstruction_error"] is 0.0 whenever nothing was changed (both
cases in the previous section) and positive whenever at least one step was
replaced — a quick way to check, in code, whether healing actually did
anything to a given sequence without diffing the arrays by hand.
telem["fallback_triggered"] records whether the hybrid strategy fell back to
a plain median pass instead of the Phi-Trigger decision — see
enhanced_dense_healing_hybrid's own docstring below for exactly when that
happens.
vector_healing ¶
median_healing ¶
Applica un filtro mediano avanzato ai vettori.
Questo metodo calcola un raggio per il filtro mediano dinamicamente, se non specificato,
e utilizza scipy.ndimage.median_filter per un'applicazione efficiente. Gestisce i
bordi della sequenza tramite padding 'nearest' e preprocessa i vettori per gestire
valori np.nan e np.inf prima dell'applicazione del filtro.
Args:
vettori (np.ndarray): Array di vettori di hidden states (n_tokens, hidden_dim).
radius_baseline (int, optional): Raggio fisso per il calcolo della mediana.
Se None, il raggio viene calcolato dinamicamente
come min(20, max(3, n_tokens // 3)).
Defaults to None.
Returns: tuple: Contiene: - np.ndarray: Vettori con filtro mediano applicato, della stessa shape dell'input. - int: Il raggio effettivamente utilizzato per il filtro mediano.
Source code in tools/ia_utils/vector_healing.py
enhanced_dense_healing_hybrid ¶
enhanced_dense_healing_hybrid(
vettori: ndarray,
radius_baseline: int = None,
trigger_mode: str = "phi",
) -> (np.ndarray, dict)
Applica una strategia di healing ibrida combinando la logica di dense_evolution con un fallback alla mediana, decidendo dinamicamente quale approccio utilizzare.
Questa funzione preprocessa i vettori per gestire np.nan e np.inf.
Include telemetria dettagliata per monitorare il comportamento del processo di healing.
Args:
vettori (np.ndarray): Array di vettori di hidden states (n_tokens, hidden_dim).
radius_baseline (int, optional): Raggio fisso per il calcolo delle baseline (media/mediana).
Se None, il raggio viene calcolato dinamicamente
come min(20, max(3, n_tokens // 3)).
Defaults to None.
trigger_mode (str, optional): Quale meccanismo decide se un dato passo è
movimento genuino (mantenuto com'è) o
rumore/corruzione (sostituito con la mediana
locale). Uno tra:
- 'phi' (default): il Phi-Trigger originale
(dense_evolution.mitigation.healing.evaluate_phi_trigger),
soglia fissa |v_dinamic| > 0.01. Mantenuto
come default per piena compatibilità
all'indietro -- è anche il meccanismo esatto
preso di mira dal red-teaming a gradiente di
ia_utils.adversarial_vector_attack, dato che
calculate_phi_ab/calculate_vettore_dinamico
sono funzioni JAX differenziabili.
- 'adaptive': trigger a deviazione locale
adattiva (MAD), consapevole di NaN/Inf
(Dense-Evolution-Discovery Esperimento 27).
Validato: riduce il tasso di falsi positivi
(sostituzioni su dati rumorosi ma non
corrotti) dall'~90% al ~12%, mantenendo un
tasso di rilevamento delle corruzioni reali
pari o superiore al Phi-Trigger su ogni tipo
testato (picchi singoli, sequenze di NaN,
outlier sparsi, corruzioni combinate). Non
differenziabile (usa np.median/np.std), quindi
il red-teaming a gradiente non si applica
allo stesso modo.
Defaults to 'phi'.
Returns:
tuple: Contiene:
- np.ndarray: Vettori curati, della stessa shape dell'input.
- dict: Metadati di telemetria contenenti:
- 'fallback_triggered' (bool): True solo se l'input originale conteneva
NaN/Inf E il fallback mediano è stato applicato
almeno una volta per correggerlo. Non riflette
correzioni del trigger su dati validi ma
"staticamente" rumorosi (nessuna corruzione reale).
- 'adaptive_radius_used' (int): Il raggio effettivamente calcolato e applicato.
- 'reconstruction_error' (float): La norma media di variazione (errore di ricostruzione)
introdotta rispetto ai vettori originali (potenzialmente corrotti).
- 'trigger_mode' (str): Il meccanismo di trigger effettivamente usato.
Source code in tools/ia_utils/vector_healing.py
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 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 | |