Minimal Core Demo#

Introduction#

This example demonstrates the minimal flow of a hyper-causal model using a deterministic demonstration backend (ToyBackend). It focuses on three core parts:

  1. Deterministic backend (ToyBackend).

  2. Forward step and loss computation (minimal_core_demo).

  3. Model consistency verification (HCModel).

General Flow Structure#

The example implements a minimal architecture:

  • Backend (`ToyBackend`): processes the input through a stable and validated \(\tanh(w \cdot x + b)\) transformation.

  • Node (`HCNode`): combines the backend with a decision policy (MeanPolicy) to generate future branches.

  • Loss (`ConsistencyLoss`): compares temporal coherence between past, present, and predicted future states.

How to Run#

# From the project root
python -m examples.ex_minimal_core_demo

# Or directly
python examples/ex_minimal_core_demo.py

Relevant Code Snippets#

Definition of the ToyBackend class#
 1from qmlhc.loss import ConsistencyLoss
 2
 3
 4# ---------------------------------------------------------------------------
 5# 1) Minimal concrete backend (inherits from base and implements run/project_future)
 6# ---------------------------------------------------------------------------
 7
 8class ToyBackend(BaseBackend):
 9    """
10    Demonstrative backend, deterministic and numerically stable.
11
12    This backend defines the minimal deterministic behavior for demonstration
13    purposes. It applies a smooth nonlinear transformation to the encoded
14    input and generates future projections through uniform perturbations.
15
16    Methods
17    -------
18    run(params=None)
19        Applies a tanh-based transformation to the encoded input.
20    project_future(s_t, branches=2)
21        Generates K possible future states.
22    """
23
24    def run(self, params: dict | None = None) -> np.ndarray:
25        """
26        Apply a smooth nonlinear transformation to the last encoded input.
27
28        Parameters
29        ----------
30        params : dict or None, optional
31            Optional parameters (not used in this minimal demo).
32
33        Returns
34        -------
35        np.ndarray
36            The transformed state vector ``s_t``.
37        """
38        # Ensure that encode(x) was called before and fetch the last input.
39        x = self._require_input()
40
41        # Simple and stable transformation (tanh of a small affine bias).
42        w = 0.95
43        b = 0.05
44        s_t = np.tanh(w * x + b)
45
46        # Validate shape against output_dim (for real adapters that may change D at runtime).
47        s_t = self._validate_state(s_t)
48        return s_t
49
50    def project_future(self, s_t: np.ndarray, branches: int = 2) -> np.ndarray:
51        """
52        Generate K future states around the current state.
53
54        Parameters
55        ----------
56        s_t : np.ndarray
57            Current state vector.
58        branches : int, optional
59            Number of future branches (K). Default is 2.
60
61        Returns
62        -------
63        np.ndarray
64            Future states matrix with shape ``(K, D)``.
65        """
66        # Validate current state and K.
67        s = self._validate_state(s_t)
68        k = max(2, int(branches))
69
70        # Uniform deltas in [-span, +span]; added to s_t and passed through tanh.
71        span = 0.25
72        deltas = np.linspace(-span, span, k, dtype=float)
Function minimal_core_demo (main flow and loss computation)#
 1        futures = self._validate_branches(futures)
 2        return futures
 3
 4
 5# ---------------------------------------------------------------------------
 6# 2) Demo: forward pass of a single node + consistency loss
 7# ---------------------------------------------------------------------------
 8
 9def minimal_core_demo() -> None:
10    """
11    Run a minimal demonstration of the hyper-causal model.
12
13    This function performs a full pass through a minimal hyper-causal pipeline:
14    it initializes a backend, defines a node with mean policy, executes the
15    forward step, and computes the triadic consistency loss. The results are
16    printed to the console for inspection.
17
18    Returns
19    -------
20    None
21        Prints the results directly to the console.
22    """
23    # State dimension and configuration.
24    D = 3
25    K = 3
26    cfg = BackendConfig(output_dim=D, seed=42)
27
28    # Instantiate backend and node with mean policy.
29    backend = ToyBackend(cfg)
30    policy = MeanPolicy()
31    node = HCNode(backend=backend, policy=policy)
32
33    # Example data: input x_t and previous state s_{t-1}.
34    x_t = np.array([0.20, -0.10, 0.40], dtype=float)   # (D,)
35    s_tm1 = np.array([0.15, -0.05, 0.35], dtype=float) # (D,)
36
37    # Execute hyper-causal step in the node.
38    s_t, s_tp1_hat, info = node.forward(x_t, s_tm1=s_tm1, branches=K)
39
40    # Triadic consistency loss.
41    consistency = ConsistencyLoss(alpha=1.0, beta=1.0)
42    loss_val = consistency(s_tm1, s_t, s_tp1_hat)
43
44    # Display results.
45    print("=== Minimal Core Demo ===")
46    print(f"output_dim (D):     {D}")
47    print(f"branches (K):       {K}\n")
48
49    print("x_t:                ", x_t)
50    print("S_{t-1} (s_tm1):    ", s_tm1)
51    print("S_t (from run):     ", s_t)
52    print("Ŝ_{t+1} (selected): ", s_tp1_hat)
53    print("\nNode information (summary):")
54    print("  policy:           ", info.get("policy"))
55    branches_mat = info.get("branches")
56    if isinstance(branches_mat, np.ndarray):
57        print("  branches shape:    ", branches_mat.shape)
58        print("  branches[0]:       ", branches_mat[0])
59    print("\nConsistencyLoss:")
60    print("  L = α||S_t - S_{t-1}||^2 + β||S_t - Ŝ_{t+1}||^2")
61    print("  α = 1.0, β = 1.0")
62    print("  loss =", loss_val)
63
64    # (Optional) Validate the same flow through HCModel with a single node.
65    model = HCModel([node])
66    s_t_m, s_tp1_hat_m, info_m = model.forward(x_t, s_tm1=s_tm1, branches=K)
67    assert np.allclose(s_t, s_t_m) and np.allclose(s_tp1_hat, s_tp1_hat_m)
68    print("\nHCModel.forward() matches single-node result ✔")
69
70
71# ---------------------------------------------------------------------------
72# 3) Entry point
73# ---------------------------------------------------------------------------
74
75if __name__ == "__main__":
76    minimal_core_demo()

Functional Explanation#

The minimal hyper-causal flow describes how an input state evolves over time in a simulated quantum-like system. Each component plays a precise mathematical role in maintaining temporal coherence and causal consistency.

  1. State Update — Backend Transformation

    The backend computes the internal system state as a nonlinear and bounded transformation:

    \[s_t = \tanh(w \cdot x_t + b)\]

    Here, \(x_t\) is the input at time \(t\), while \(w\) and \(b\) act as fixed transformation parameters. The hyperbolic tangent ensures the state remains numerically stable within the range \((-1, 1)\), simulating a controlled energy state.

  2. Future Projection — Hypercausal Branches

    The model predicts multiple potential future states (“branches”) by perturbing the current state \(s_t\) with small offsets \(\delta_k\):

    \[S_{t+1}^{(k)} = \tanh(s_t + \delta_k), \quad \delta_k \in [-0.25, 0.25]\]

    Each \(S_{t+1}^{(k)}\) represents a possible trajectory the system could take. This branching behavior emulates quantum superposition, where multiple possible futures exist simultaneously before being collapsed by a selection policy.

  3. Policy Selection — Mean Collapse

    The MeanPolicy acts as the “collapse” function, averaging across branches to select the most coherent and representative state \(\hat{S}_{t+1}\).

  4. Consistency Loss — Temporal Coherence Evaluation

    To ensure the system evolves smoothly, the Consistency Loss penalizes large deviations between consecutive temporal states:

    \[\mathcal{L} = \alpha \| S_t - S_{t-1} \|^2 + \beta \| S_t - \hat{S}_{t+1} \|^2\]
    • The first term (\(\alpha\)) ensures internal continuity between the current and previous states.

    • The second term (\(\beta\)) enforces predictive alignment between the present and the expected next state.

    The lower the loss, the more temporally consistent the hyper-causal chain.

  5. Global Validation — HCModel Check

    Finally, the HCModel wrapper reproduces the single-node computation to confirm equivalence between the modular (node-level) and aggregated (model-level) behaviors, guaranteeing deterministic correctness.

Exact Output#

=== Minimal Core Demo ===
output_dim (D):     3
branches (K):       3

x_t:                 [ 0.2 -0.1  0.4]
S_{t-1} (s_tm1):     [ 0.15 -0.05  0.35]
S_t (from run):      [ 0.23549575 -0.04496965  0.40532131]
Ŝ_{t+1} (selected):  [ 0.22245591 -0.04314564  0.3712728 ]

Node information (summary):
  policy:            MeanPolicy
  branches shape:     (3, 3)
  branches[0]:        [-0.01450323 -0.28670244  0.15408422]

ConsistencyLoss:
  L = α||S_t - S_{t-1}||^2 + β||S_t - Ŝ_{t+1}||^2
  α = 1.0, β = 1.0
  loss = 0.003909313321780935

HCModel.forward() matches single-node result ✔