Skip to content

Orca (full model shield)

Orca protects a whole model: it cleans the input before the model sees it, runs the model, and checks that the model's answer is not broken either.

Armor protects one series. But if you have a model — any callable that takes a tensor and returns a tensor — the corruption can happen twice: once on the way in (garbage input) and once on the way out (the model itself producing a wrong response). Orca shields both sides in one call: it purifies the input, runs the model, and checks that the response itself isn't corrupted.

The model and the input

A small model, the identity times two, and a 4×200 batch of sine waves with one absurd value at (0, 50); ref is a clean reference of the same shape.

1. Protect the forward pass

import numpy as np
from dense_armor.core.online.protect.orca import Orca

rng = np.random.default_rng(0)
ref = np.sin(np.linspace(0, 6, 200))[None, :] + 0.01 * rng.standard_normal((4, 200))
data = ref.copy()
data[0, 50] = 999.0
orca = Orca(min_free_ram_percentage=0.05)
out = orca.protect_and_forward(lambda z: 2.0 * z, data, x_reference=ref)
print(out.shape, round(float(out[0, 50]), 4), round(float(2 * ref[0, 50]), 4))
(4, 200) 2.0074 2.0031

out is the model's output on the cleaned input. The spike at (0, 50) never reaches the model: the output there is 2.0074, next to twice the clean value (2.0031), instead of 1998. min_free_ram_percentage lowers Orca's memory guard (default: 15 % free RAM required).

The four phases of protect_and_forward, in order:

  1. Input shield — purify x_corrupted against x_reference (use_input_shield).
  2. Model call — run the callable on the purified tensor (use_model_injection).
  3. Output shield — check the model's response against its expected response to the clean reference (use_output_shield).
  4. Report — return the protected output.

Every phase can be disabled individually: use_input_shield=False, use_model_injection=False, use_output_shield=False. All three default to True.

2. What each argument does

  • ai_model_callable — any callable z -> z_out. In the example it is the identity scaled by two, chosen so the shield is the only thing acting on the tensor.
  • x_corrupted — the tensor that would be passed to the model. It is cleaned before the model sees it.
  • x_reference — optional but recommended. A clean tensor of the same shape as x_corrupted. When present, the input shield compares each sample against the corresponding reference sample instead of falling back to a robust blind estimate.
  • use_arbiter=True — routes each point through the per-point classifier described in Arbiter: clean passes through whatever the standard shield produced, spike gets hard-rejected to the window median, regime passes through raw. Off by default.

3. Where the two stages come from

Orca's pipeline has two stages:

  1. Stage 1 — AdaptiveSignalStabilizer: a causal recursive filter with a sigmoid damping curve. This is the adaptive engine. It does the actual purification of the input and the response.
  2. Stage 2 — constant gate: a weighted mean of the Stage 1 result and the clean reference, 0.15 * stage1 + 0.85 * reference. Where the raw value differs from the reference by more than hard_clamp_threshold (0.05), the weight of the reference is 0.99.

With use_arbiter=True, a third layer runs after the two stages and decides, point by point: a spike is replaced by the window median, a regime change passes raw, a clean point keeps the result of the two stages.

4. What the shield saw, after the fact

import numpy as np
from dense_armor.core.online.protect.orca import Orca

rng = np.random.default_rng(0)
ref = np.sin(np.linspace(0, 6, 200))[None, :] + 0.01 * rng.standard_normal((4, 200))
data = ref.copy()
data[0, 50] = 999.0
orca = Orca(min_free_ram_percentage=0.05)
orca.protect_and_forward(lambda z: 2.0 * z, data, x_reference=ref, use_arbiter=True)
print(orca.tipi_corruzione_visti(data.shape[1:]))
Counter({'clean': 721, 'regime': 75, 'spike': 4})

tipi_corruzione_visti(row_shape) returns how many times each Arbiter label was seen for rows of that shape (here (200,)), counted only when use_arbiter=True and x_reference is given. Over the 4 × 200 samples: 721 clean, 75 regime (the sine's own slow changes of level), 4 spikes.

API reference

orca

core/online/protect/orca.py Universal AI Orchestrator Shield (ORCA) -- dynamic, selective, context-aware orchestrator in 4 phases.

Orca

Orca(
    static_threshold: float = 0.15,
    initial_damping: float = 0.85,
    alpha: float = 0.05,
    val_e: float = -4.0,
    chunk_threshold: int | None = None,
    min_free_ram_percentage: float = 0.15,
    reference_memory_size: int = 32,
    reference_recall_min_score: float = 0.9,
    hard_clamp_threshold: float = 0.05,
)

val_e — target scale exponent for the input log10 compression; hard_clamp_threshold — noise |corrupted - reference|, in the units of the RAW data (before the log10 compression), above which the emergency hard clamp is used. The default 0.05 suits data of order 1; for data of a very different scale set it accordingly; chunk_threshold — size beyond which a batch is processed in blocks; None (default) auto-derives it from AIHardwareProfiler (RAM/backend of the current host, see _CHUNK_THRESHOLD_BASELINE* above) instead of the old fixed value, equal for any machine; reference_memory_size — how many past clean references (per shape) to keep in memory for the resonance recall in blind mode (see _recall_reference); reference_recall_min_score — minimum apply_fast_resonance score below which a reference in memory is considered not similar enough and _blind_reference is used instead (empirically calibrated: on correlated vectors the score stays >0.95 even with moderate noise, on uncorrelated vectors it does not exceed ~0.75 — 0.90 leaves margin on both sides).

Source code in dense_armor/core/online/protect/orca.py
def __init__(
    self,
    static_threshold: float = 0.15,
    initial_damping: float = 0.85,
    alpha: float = 0.05,
    val_e: float = -4.0,
    chunk_threshold: int | None = None,
    min_free_ram_percentage: float = 0.15,
    reference_memory_size: int = 32,
    reference_recall_min_score: float = 0.90,
    hard_clamp_threshold: float = 0.05,
) -> None:
    """val_e — target scale exponent for the input log10 compression;
    hard_clamp_threshold — noise |corrupted - reference|, in the units of the
    RAW data (before the log10 compression), above which the emergency
    hard clamp is used. The default 0.05 suits data of order 1; for data of
    a very different scale set it accordingly;
    chunk_threshold — size beyond which a batch is processed in blocks;
    None (default) auto-derives it from AIHardwareProfiler (RAM/backend
    of the current host, see _CHUNK_THRESHOLD_BASELINE* above) instead of the
    old fixed value, equal for any machine;
    reference_memory_size — how many past clean references (per shape) to keep in
    memory for the resonance recall in blind mode (see _recall_reference);
    reference_recall_min_score — minimum apply_fast_resonance score below
    which a reference in memory is considered not similar enough and
    _blind_reference is used instead (empirically calibrated: on correlated vectors the
    score stays >0.95 even with moderate noise, on uncorrelated vectors it does not exceed
    ~0.75 — 0.90 leaves margin on both sides)."""
    self.static_threshold = static_threshold
    self.initial_damping = initial_damping
    self.alpha = alpha
    if chunk_threshold is None:
        profiler = AIHardwareProfiler()
        scale = profiler.max_tensor_dim / self._CHUNK_THRESHOLD_BASELINE_TENSOR_DIM
        chunk_threshold = int(self._CHUNK_THRESHOLD_BASELINE * scale)
        logger.info(
            "chunk_threshold auto-derivato da AIHardwareProfiler: %d (%s)",
            chunk_threshold,
            profiler.get_profile_summary(),
        )
    self.chunk_threshold = int(chunk_threshold)
    self.val_e = float(val_e)
    self.min_free_ram = min_free_ram_percentage
    self.reference_recall_min_score = float(reference_recall_min_score)
    self.hard_clamp_threshold = float(hard_clamp_threshold)
    self.stabilizer = AdaptiveSignalStabilizer(
        static_threshold, initial_damping, alpha
    )
    self.last_kappa = 0.0
    # Shared memory guard (RAM+VRAM), no longer an ad-hoc psutil check
    # duplicated in here (see _gc_se_ram_bassa).
    self._memory_guard = UniversalMemoryGuard(
        min_free_ram_percentage=min_free_ram_percentage
    )
    # Bank of clean references seen in the past, one deque per shape
    # (different shapes are not comparable with each other): when the caller
    # provides x_reference, its rows are remembered here; in blind
    # mode (x_reference=None) a future request with a corrupted input
    # similar to one already seen can reuse the true reference instead of
    # starting from scratch with the local estimate alone (see _recall_reference).
    self._reference_bank: dict = {}
    self._reference_memory_size = int(reference_memory_size)
    # JAX kernels precompiled only once (same principle as the fix
    # to the scan in AdaptiveSignalStabilizer.filter_data_stream): without
    # this, the eager pipeline of _execute_4_phase_*_shield re-dispatches
    # and recompiles every single JAX operation at every call.
    self._compiled_input_shield_kernel = jax.jit(self._run_input_shield_kernel)
    self._compiled_output_shield_kernel = jax.jit(self._run_output_shield_kernel)
    # error margin (like the Kalman covariance, but defined simply
    # as |received_value - corrected_value|: the more the shield had to
    # move a value, the less the result at that point should be trusted)
    self.margine_ingresso = (
        None  # array, same shape as the input: uncertainty in INPUT SPACE
    )
    self.margine_ingresso_medio = 0.0
    self.margine_ingresso_max = 0.0
    self.margine_uscita = (
        None  # array, same shape as the output: uncertainty in OUTPUT SPACE
    )
    self.margine_uscita_medio = 0.0
    self.margine_uscita_max = 0.0

    # Arbiter labels/uncertainty (only if use_arbiter=True in
    # protect_and_forward) -- margine_ingresso already says how much a value
    # was moved; incertezza_arbitro says how unsure the arbiter itself
    # is of having chosen the right classification (near the
    # deviating/clean or spike/regime boundary), not how large the
    # correction was. The two signals are complementary, not redundant:
    # a small correction with high uncertainty is an ambiguous case that
    # went well by chance, not one that is truly safe.
    self.etichette_arbitro = (
        None  # array of strings 'clean'/'spike'/'regime', same shape as the input
    )
    self.incertezza_arbitro = None  # array 0..1, same shape as the input
    self.incertezza_arbitro_media = 0.0
    # Memory of the corruption TYPES already seen for each shape (not just
    # the clean references per shape, already in _reference_bank) -- a
    # Counter of the arbiter labels observed when x_reference
    # was known, so a future call in blind mode on the same
    # shape can know whether that sensor/stream has already shown isolated
    # spikes, regime changes, or both, instead of starting from scratch.
    self._corruption_type_memory: dict = {}

tipi_corruzione_visti

tipi_corruzione_visti(slice_shape: tuple) -> Counter

Which arbiter labels ('clean'/'spike'/'regime') have already been observed for this shape, and how many times -- empty Counter if this shape has never been seen with use_arbiter=True and a known x_reference (the only way the memory is populated, see _aggiorna_memoria_corruzione).

Source code in dense_armor/core/online/protect/orca.py
def tipi_corruzione_visti(self, slice_shape: tuple) -> Counter:
    """Which arbiter labels ('clean'/'spike'/'regime') have already been
    observed for this shape, and how many times -- empty Counter if
    this shape has never been seen with use_arbiter=True and a known
    x_reference (the only way the memory is populated,
    see _aggiorna_memoria_corruzione)."""
    return self._corruption_type_memory.get(slice_shape, Counter())

protect_and_forward

protect_and_forward(
    ai_model_callable: Callable | None,
    x_corrupted: ndarray,
    x_reference: ndarray | None = None,
    use_input_shield: bool = True,
    use_model_injection: bool = True,
    use_output_shield: bool = True,
    use_arbiter: bool = False,
) -> np.ndarray

Runs the 4 phases (input shield -> model -> output shield) and returns the protected output.

use_arbiter — if True, after the standard input shield it routes each point to the right corrector (core/online/protect/arbiter.py): isolated impulse -> hard rejection, sustained regime change -> passes raw, no point anomaly -> the result already produced by the standard shield remains (its soft damping, not a pass-through). Default False: behavior and results identical to before this option on all the existing tests. It populates etichette_arbitro/incertezza_arbitro; if x_reference is known, it also updates tipi_corruzione_visti(slice_shape).

Source code in dense_armor/core/online/protect/orca.py
def protect_and_forward(
    self,
    ai_model_callable: Callable | None,
    x_corrupted: np.ndarray,
    x_reference: np.ndarray | None = None,
    use_input_shield: bool = True,
    use_model_injection: bool = True,
    use_output_shield: bool = True,
    use_arbiter: bool = False,
) -> np.ndarray:
    """Runs the 4 phases (input shield -> model -> output shield) and returns the protected output.

    use_arbiter — if True, after the standard input shield it routes each
    point to the right corrector (core/online/protect/arbiter.py): isolated
    impulse -> hard rejection, sustained regime change -> passes
    raw, no point anomaly -> the result already
    produced by the standard shield remains (its soft damping, not a
    pass-through). Default False: behavior and results identical to
    before this option on all the existing tests. It populates
    etichette_arbitro/incertezza_arbitro; if x_reference is known,
    it also updates tipi_corruzione_visti(slice_shape)."""
    self.etichette_arbitro = None
    self.incertezza_arbitro = None
    self.incertezza_arbitro_media = 0.0
    is_simple_data_test = ai_model_callable is None or not use_model_injection
    if is_simple_data_test:
        logger.info(
            "CONTRAZIONE LOGICA DETECTED: Riconosciuto Test di Protezione Dati Semplice (No IA Model)."
        )
        use_model_injection = False

    # A 1D array (e.g. a single series from a sensor/pipeline) is NOT a
    # batch of N independent scalars: it is ONE instance with N samples
    # correlated in time. Without this promotion, B=N and each sample
    # was processed alone (slice_shape=()), zeroing the context
    # on which blind-mode outlier detection relies (without
    # x_reference) -- the main use case documented in the README.
    was_1d = x_corrupted.ndim == 1
    if was_1d:
        x_corrupted = np.asarray(x_corrupted).reshape(1, -1)
        if x_reference is not None:
            x_reference = np.asarray(x_reference).reshape(1, -1)

    orig_shape = x_corrupted.shape
    B = orig_shape[0]
    slice_shape = orig_shape[1:]
    t_start = time.time()

    if use_input_shield:
        logger.info(
            "Attivazione SCUDO ENTRATA (4 Fasi) su Ipervolume: %s", orig_shape
        )
        x_corrupted_np = np.array(x_corrupted)
        if x_reference is None:
            x_reference_np = np.zeros_like(x_corrupted_np)
            for b in range(B):
                row_flat = x_corrupted_np[b].flatten()
                recalled = self._recall_reference(row_flat, slice_shape)
                if recalled is not None:
                    x_reference_np[b] = recalled.reshape(slice_shape)
                else:
                    x_reference_np[b] = self._blind_reference(row_flat).reshape(
                        slice_shape
                    )
        else:
            x_reference_np = np.array(x_reference)
            self._remember_reference(x_reference_np, slice_shape)
        purified_batch = np.zeros(orig_shape, dtype=get_default_dtype())
        margine_batch = np.zeros(orig_shape, dtype=get_default_dtype())
        flat_cl_all = x_reference_np.reshape(B, -1)
        flat_co_all = x_corrupted_np.reshape(B, -1)
        total_elements = flat_cl_all.shape[1]
        if total_elements <= self.chunk_threshold:
            # Vectorized path: the B rows are processed in ONE
            # call (jax.vmap below, independent calibration per
            # row) instead of B separate JAX dispatches -- see
            # _execute_4_phase_input_shield_batch and CHANGELOG for the
            # measured gain. Each row is completely independent
            # of the others at this stage (no state shared between
            # rows here: _reference_bank/_corruption_type_memory are
            # not touched in this block).
            out_batch, marg_batch = self._execute_4_phase_input_shield_batch(
                flat_cl_all, flat_co_all
            )
            purified_batch = out_batch.reshape(orig_shape)
            margine_batch = marg_batch.reshape(orig_shape)
            self._gc_se_ram_bassa()
        else:
            # Unchanged fallback: a single row exceeds on its own
            # chunk_threshold (rare), it still has to be split into blocks.
            for b in range(B):
                flat_cl, flat_co = flat_cl_all[b], flat_co_all[b]
                out_flat = np.zeros_like(flat_cl)
                margine_flat = np.zeros_like(flat_cl)
                c_size = self.chunk_threshold
                for start_idx in range(0, total_elements, c_size):
                    end_idx = min(start_idx + c_size, total_elements)
                    purified_chunk, margine_chunk = (
                        self._execute_4_phase_input_shield(
                            flat_cl[start_idx:end_idx], flat_co[start_idx:end_idx]
                        )
                    )
                    out_flat[start_idx:end_idx] = purified_chunk
                    margine_flat[start_idx:end_idx] = margine_chunk
                    self._gc_se_ram_bassa()
                purified_batch[b] = out_flat.reshape(slice_shape)
                margine_batch[b] = margine_flat.reshape(slice_shape)

        if use_arbiter:
            etichette_batch = np.empty(orig_shape, dtype=object)
            incertezza_batch = np.zeros(orig_shape, dtype=get_default_dtype())
            for b in range(B):
                co_flat = x_corrupted_np[b].flatten()
                pur_flat = purified_batch[b].flatten()
                corretto_flat, etichette_flat, incertezza_flat = (
                    self._applica_arbitro(co_flat, pur_flat)
                )
                purified_batch[b] = corretto_flat.reshape(slice_shape)
                etichette_batch[b] = etichette_flat.reshape(slice_shape)
                incertezza_batch[b] = incertezza_flat.reshape(slice_shape)
                if x_reference is not None:
                    self._aggiorna_memoria_corruzione(etichette_flat, slice_shape)
            self.etichette_arbitro = etichette_batch
            self.incertezza_arbitro = incertezza_batch
            self.incertezza_arbitro_media = float(np.mean(incertezza_batch))

        x_for_model = jnp.array(purified_batch)
        self.margine_ingresso = margine_batch
        self.margine_ingresso_medio = float(np.mean(margine_batch))
        self.margine_ingresso_max = float(np.max(margine_batch))
        logger.info(
            "Input purificato in %.3fs. Margine d'errore: medio=%.4g, max=%.4g",
            time.time() - t_start,
            self.margine_ingresso_medio,
            self.margine_ingresso_max,
        )
    else:
        logger.info(
            "SCUDO ENTRATA disattivato. I dati transitano senza pre-filtri."
        )
        x_for_model = jnp.array(x_corrupted)
        self.margine_ingresso = None
        self.margine_ingresso_medio = self.margine_ingresso_max = 0.0

    if use_model_injection:
        t_ia = time.time()
        ai_output = ai_model_callable(x_for_model)
        jax.block_until_ready(ai_output)
        logger.info(
            "Risposta IA ottenuta in %.3fs. Shape Output: %s",
            time.time() - t_ia,
            ai_output.shape,
        )
    else:
        logger.info(
            "INIEZIONE MODELLO bypassata. I dati purificati procedono verso la barriera spettrale."
        )
        ai_output = x_for_model

    if use_output_shield:
        t_out = time.time()
        logger.info("Attivazione SCUDO USCITA (4 Fasi) su Spettro Terminale...")
        if use_model_injection and x_reference is not None:
            # reference in OUTPUT SPACE: the model's response to the clean
            # data, not the purified input (different space if the model is
            # transformative, e.g. classifiers/embeddings/non-linear networks)
            output_reference = ai_model_callable(jnp.array(x_reference))
            jax.block_until_ready(output_reference)
        else:
            # no known clean reference: blind self-consistency on the output
            # itself (same stabilizer as Phase 1, applied here to the output)
            output_reference = self.stabilizer.filter_batch_scenarios(
                ai_output.reshape(ai_output.shape[0], -1)
            ).reshape(ai_output.shape)
        x_final, margine_out = self._execute_4_phase_output_shield(
            ai_output, output_reference
        )
        self.margine_uscita = np.array(margine_out)
        self.margine_uscita_medio = float(jnp.mean(margine_out))
        self.margine_uscita_max = float(jnp.max(margine_out))
        logger.info(
            "Output rinormalizzato in %.3fs. Margine d'errore: medio=%.4g, max=%.4g",
            time.time() - t_out,
            self.margine_uscita_medio,
            self.margine_uscita_max,
        )
    else:
        logger.info("SCUDO USCITA disattivato. Emissione del flusso lineare.")
        x_final = ai_output
        self.margine_uscita = None
        self.margine_uscita_medio = self.margine_uscita_max = 0.0

    if was_1d:
        x_final = x_final.reshape(-1)
        if self.margine_ingresso is not None:
            self.margine_ingresso = self.margine_ingresso.reshape(-1)
        if self.margine_uscita is not None:
            self.margine_uscita = np.asarray(self.margine_uscita).reshape(-1)
        if self.etichette_arbitro is not None:
            self.etichette_arbitro = self.etichette_arbitro.reshape(-1)
        if self.incertezza_arbitro is not None:
            self.incertezza_arbitro = self.incertezza_arbitro.reshape(-1)

    logger.info(
        "Transito concluso. Sistema sigillato in %.3f secondi totali.",
        time.time() - t_start,
    )
    return x_final

See also: Adaptive engine — AdaptiveSignalStabilizer, Orca's Stage 1. Arbiter — the per-point classifier used by use_arbiter=True. Armor — if you have a bare series rather than a model.