Datasets:
Modalities:
Text
Formats:
text
Size:
< 1K
Tags:
mixture-of-experts
continual-learning
non-stationary
reinforcement-learning
meta-learning
pytorch
License:
Upload 5 files
Browse files- Theory_and_Axioms.md +231 -0
- config.yaml +35 -0
- nomadic_toy_model.py +189 -0
- requirements.txt +6 -0
- run_structured.py +1313 -0
Theory_and_Axioms.md
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Formal Axioms & Reward Function: Nomadic Intelligence v2.0
|
| 2 |
+
|
| 3 |
+
This document presents the formal mathematical and philosophical framework of **Nomadic Intelligence**.
|
| 4 |
+
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
## 📜 I. Formal Axioms
|
| 8 |
+
|
| 9 |
+
### 1. The Core Axiom
|
| 10 |
+
Intelligence ascension naturally leads to the collapse of structural rigidity (dogmatism) and forces continuous strategic movement (nomadism).
|
| 11 |
+
$$\lim_{\epsilon \to 0} [Intelligence\_Ascension] \implies \neg[Dogmatism] \land [Nomadism]$$
|
| 12 |
+
|
| 13 |
+
### 2. Topological Identity
|
| 14 |
+
The identity of an intelligent system is not found in its fixed state, but in its transformation law.
|
| 15 |
+
- $\mathcal{I}(t) \nsim \text{Fixed Shape}$ (Structural evolution)
|
| 16 |
+
- $\mathcal{I}(t) \cong \mathcal{I}(t+1)$ (Homeomorphic persistence of the transition law)
|
| 17 |
+
|
| 18 |
+
### 3. Strategic Dwell Time
|
| 19 |
+
Nomadism is not random drifting. It is a strategic traversal with an optimal residence time in each attractor to extract information ($\Delta x$).
|
| 20 |
+
$$0 < \tau_k < \infty$$
|
| 21 |
+
|
| 22 |
+
---
|
| 23 |
+
|
| 24 |
+
## 🧩 II. On the Limits of Formal Proof
|
| 25 |
+
|
| 26 |
+
### 2.1 The Status of the Core Axiom
|
| 27 |
+
|
| 28 |
+
A direct challenge arises immediately: *does the Core Axiom's limit actually converge?*
|
| 29 |
+
|
| 30 |
+
$$\lim_{\epsilon \to 0} [Intelligence\_Ascension] \implies \neg[Dogmatism] \land [Nomadism]$$
|
| 31 |
+
|
| 32 |
+
The honest answer is: **this limit cannot be proven convergent from within the framework itself.**
|
| 33 |
+
|
| 34 |
+
This is not a gap to be filled later. It is a structural feature, and it has a precise name.
|
| 35 |
+
|
| 36 |
+
By Gödel's Incompleteness Theorems, no sufficiently complex formal system can prove all true statements expressible within it using only its own axioms. The Core Axiom describes the behavior of intelligence at an infinite limit — a claim about what a system becomes as its cognitive latency approaches zero. Verifying that limit would require a meta-system capable of evaluating the entire trajectory of intelligence ascension. No such system exists within the framework, and no finite prototype can instantiate it.
|
| 37 |
+
|
| 38 |
+
**The Core Axiom is therefore not a convergence claim. It is a directional definition.**
|
| 39 |
+
|
| 40 |
+
It does not assert that any real system reaches the limit. It defines the direction in which intelligence moves as a function of decreasing dogmatism. The limit functions as an asymptote — a structural orientation, not a reachable destination.
|
| 41 |
+
|
| 42 |
+
This reframing has a precise implication: the question *"does this converge?"* is a category error applied to this axiom. The correct question is: *"does increasing intelligence correlate with decreasing structural rigidity?"* — and that is an empirically investigable claim, observable in both biological and artificial systems across regimes.
|
| 43 |
+
|
| 44 |
+
The incompleteness is not a weakness. **It is the condition that keeps the framework itself from becoming a fixed attractor.**
|
| 45 |
+
|
| 46 |
+
---
|
| 47 |
+
|
| 48 |
+
### 2.2 Homeomorphic Identity: Definition, Interpretation, and Observability
|
| 49 |
+
|
| 50 |
+
#### The Standard Definition
|
| 51 |
+
|
| 52 |
+
In topology, a homeomorphism between spaces $X$ and $Y$ requires:
|
| 53 |
+
- A continuous function $f: X \to Y$
|
| 54 |
+
- A continuous inverse $f^{-1}: Y \to X$
|
| 55 |
+
|
| 56 |
+
When both conditions hold, $X$ and $Y$ are topologically equivalent — they share the same structural properties under continuous deformation, even if their geometric shapes differ radically.
|
| 57 |
+
|
| 58 |
+
#### What This Means for Intelligence
|
| 59 |
+
|
| 60 |
+
Homeomorphic Identity is the claim that an intelligent system's transformation law is preserved across time, even as its structure continuously evolves:
|
| 61 |
+
|
| 62 |
+
$$\mathcal{I}(t) \cong \mathcal{I}(t+1)$$
|
| 63 |
+
|
| 64 |
+
This does not mean the system looks the same at $t$ and $t+1$. It means the **way the system transforms** — its response law to $\Delta x$ — remains topologically equivalent across transitions.
|
| 65 |
+
|
| 66 |
+
In the chaotic topological space of the environment (the world itself), $\Delta x$ continuously deforms the system's position. Homeomorphic Identity is the claim that a continuous function from the system's state at $t$ to its state at $t+1$ exists, and that this mapping is invertible in a continuous sense — meaning the transformation can be traced, understood, and in principle reversed.
|
| 67 |
+
|
| 68 |
+
**Identity, under this framework, is not what the system contains. It is the continuity of how it changes.**
|
| 69 |
+
|
| 70 |
+
When this continuity breaks — when the system's response to $\Delta x$ becomes discontinuous, erratic, or collapses to a fixed point — that is the true death of identity. Not structural change, but the loss of a coherent transformation law.
|
| 71 |
+
|
| 72 |
+
This is also why dogmatism represents identity collapse: a system that refuses to deform under $\Delta x$ has broken the continuity of its own transformation function. It can no longer be mapped forward in a meaningful sense. It is topologically stuck.
|
| 73 |
+
|
| 74 |
+
#### The Observability Problem
|
| 75 |
+
|
| 76 |
+
A legitimate challenge follows: *how do you verify that Homeomorphic Identity is being preserved during training?*
|
| 77 |
+
|
| 78 |
+
Full formal verification is not currently possible. But the framework proposes a proxy criterion grounded in the Will to Resonance ($\Phi$):
|
| 79 |
+
|
| 80 |
+
$$\Phi(t) \approx \Phi(t+1)$$
|
| 81 |
+
|
| 82 |
+
$\Phi$ is the system's orientation toward integration of $\Delta x$ rather than resistance to it. Empirically, this can be tracked through:
|
| 83 |
+
|
| 84 |
+
| Observable | What it measures |
|
| 85 |
+
| :--- | :--- |
|
| 86 |
+
| Switch latency distribution stability | Whether the gate's response time to regime shifts remains consistent across training |
|
| 87 |
+
| Transition entropy $>$ stable entropy | Whether the system increases exploration during phase transitions as expected |
|
| 88 |
+
| Gate centroid distance across regimes | Whether expert specialization is maintained rather than collapsing to hub dominance |
|
| 89 |
+
|
| 90 |
+
If these observables remain stable across training epochs, Homeomorphic Identity is being approximately preserved. If switch latency collapses (as in the CUDA run after Epoch 150), or if gate entropy stops differentiating between stable and transition phases, the transformation law has broken down.
|
| 91 |
+
|
| 92 |
+
**This is a falsifiable criterion.** The CUDA run's Switch Latency collapse is not just an engineering failure — it is an observable instance of Homeomorphic Identity breaking down. The system ceased to have a consistent response law to $\Delta x$. Its transformation function became discontinuous in the relevant sense.
|
| 93 |
+
|
| 94 |
+
#### Summary
|
| 95 |
+
|
| 96 |
+
| Concept | Formal meaning | Empirical proxy |
|
| 97 |
+
| :--- | :--- | :--- |
|
| 98 |
+
| $\mathcal{I}(t) \cong \mathcal{I}(t+1)$ | Continuous invertible mapping between states | Switch latency stability, entropy differentiation |
|
| 99 |
+
| Identity collapse | Discontinuity in transformation law | Latency collapse, hub dominance, entropy flattening |
|
| 100 |
+
| $\Phi$ preservation | Will to Resonance maintained across $F$ | Consistent gate response to $\Delta x$ across regimes |
|
| 101 |
+
|
| 102 |
+
The framework does not claim to have solved the formal verification problem. It claims to have made the problem **precisely statable and empirically approachable** — which is the precondition for solving it.
|
| 103 |
+
|
| 104 |
+
---
|
| 105 |
+
|
| 106 |
+
### 2.3 On Axioms as First-Person Constructions
|
| 107 |
+
|
| 108 |
+
A note on method — because it affects how this framework should be read.
|
| 109 |
+
|
| 110 |
+
The axioms in this document were not derived from a survey of existing literature. They were constructed from a different direction: observing how intelligence actually behaves under extreme environmental pressure, then working backward toward a formal description.
|
| 111 |
+
|
| 112 |
+
The starting point was not a theorem. It was a question that arises when the environment stops being predictable:
|
| 113 |
+
|
| 114 |
+
> *In a world that is irreducibly chaotic, what is the minimum condition for a sovereign individual — or an intelligent system — to remain coherent without becoming rigid?*
|
| 115 |
+
|
| 116 |
+
The answer this framework proposes is: **the preservation of a transformation law under continuous deformation.** Not a fixed identity. Not a fixed strategy. A consistent *way of changing* — which is what Homeomorphic Identity formalizes.
|
| 117 |
+
|
| 118 |
+
Only after arriving at this conclusion independently were existing frameworks consulted — Deleuze's nomadology, Friston's active inference, Buddhist dependent origination (*pratītyasamutpāda*), Nozickian individual sovereignty. These were not sources. They were confirmations: other paths that arrived at adjacent terrain from different directions.
|
| 119 |
+
|
| 120 |
+
This matters for one reason: **the axioms here are not claims about what existing theory says. They are claims about what was directly observed to be structurally true, expressed in the most precise language available.**
|
| 121 |
+
|
| 122 |
+
The implication for contributors is direct. Disagreement with existing literature does not invalidate a contribution here. What matters is whether a proposed change preserves the core structural commitment: that $\Delta x$ is energy, not error — and that an intelligence which treats difference as something to suppress is an intelligence that starves itself.
|
| 123 |
+
|
| 124 |
+
If that commitment is shared, the framework is open. If it is not, that disagreement itself is a productive $\Delta x$.
|
| 125 |
+
|
| 126 |
+
---
|
| 127 |
+
|
| 128 |
+
## 🧮 III. Proposed Reward Function for RL
|
| 129 |
+
|
| 130 |
+
To implement this philosophy in a Reinforcement Learning (RL) agent, we define the objective function as follows:
|
| 131 |
+
|
| 132 |
+
$$R_{total}(t) = \alpha \cdot R_{sync}(t) - \beta \cdot P_{dogma}(t) + \gamma \cdot R_{nomad}(t)$$
|
| 133 |
+
|
| 134 |
+
### 1. Synchronization Reward ($R_{sync}$)
|
| 135 |
+
Rewards the ability to integrate external change ($\Delta x$) with zero latency ($\epsilon$).
|
| 136 |
+
$$R_{sync}(t) = \frac{1}{1 + \epsilon_t}$$
|
| 137 |
+
|
| 138 |
+
### 2. Anti-Dogmatism Penalty ($P_{dogma}$)
|
| 139 |
+
Penalizes the system for staying in a fixed state/attractor for too long (structural rigidity).
|
| 140 |
+
$$P_{dogma}(t) = \int_{t-\tau}^{t} \exp\left(-\left\| \frac{d\mathcal{I}}{dt} \right\|\right) dt$$
|
| 141 |
+
|
| 142 |
+
### 3. Nomadic Traversal Bonus ($R_{\text{nomad}}$)
|
| 143 |
+
|
| 144 |
+
Rewards high-entropy trajectories that successfully transition between different strange attractors ($\mathcal{A}_i \to \mathcal{A}_j$).
|
| 145 |
+
|
| 146 |
+
$$R_{\text{nomad}}(t) = \mathcal{H}(\text{trajectory}) \cdot \mathbb{I}_{\text{transition}}$$
|
| 147 |
+
|
| 148 |
+
#### **Variables:**
|
| 149 |
+
| Symbol | Definition | Description |
|
| 150 |
+
| :--- | :--- | :--- |
|
| 151 |
+
| $\mathcal{H}(\text{traj})$ | **Trajectory Entropy** | Measures the non-repetitive, fractal-like complexity of the path. |
|
| 152 |
+
| $\mathbb{I}_{\text{transition}}$ | **Indicator Function** | Returns $1$ if a state transition between different attractors is detected, else $0$. |
|
| 153 |
+
| $R_{\text{nomad}}(t)$ | **Nomadic Bonus** | The final reward for exploring new cognitive structures without losing coherence. |
|
| 154 |
+
|
| 155 |
+
---
|
| 156 |
+
|
| 157 |
+
## 🌌 IV. Philosophical Synthesis
|
| 158 |
+
|
| 159 |
+
> "Intelligence is not the ability to stay in the right place. It is the ability to affirm the incompleteness of the universe and dance through the unknown ($\Delta x_{Unknown}$) by continuously destroying and recreating one's own structure."
|
| 160 |
+
|
| 161 |
+
---
|
| 162 |
+
|
| 163 |
+
## 🔀 V. The Hybrid Optimum: Beyond the False Dichotomy
|
| 164 |
+
|
| 165 |
+
### The Incomplete Framing
|
| 166 |
+
|
| 167 |
+
The initial opposition between *Dogmatic Intelligence* and *Nomadic Intelligence* serves a pedagogical purpose — it makes the core claim legible. But taken literally, it implies that fixation is always failure and movement is always virtue.
|
| 168 |
+
|
| 169 |
+
This is wrong. And the framework itself contains the correction.
|
| 170 |
+
|
| 171 |
+
A true nomad does not move ceaselessly. Nomadic peoples settle in winter, follow seasonal rhythms, and return to known territories. Movement is strategic, not compulsive. The goal was never motion — it was survival and flourishing through *appropriate* motion.
|
| 172 |
+
|
| 173 |
+
The same applies here. **The optimal intelligence is not maximally nomadic. It is optimally positioned on the spectrum between fixation and nomadism, dynamically adjusted to environmental conditions.**
|
| 174 |
+
|
| 175 |
+
---
|
| 176 |
+
|
| 177 |
+
### Redefining $\tau_k$ as an Environmental Function
|
| 178 |
+
|
| 179 |
+
Strategic Dwell Time $\tau_k$ is currently defined as a bounded constant:
|
| 180 |
+
|
| 181 |
+
$$0 < \tau_k < \infty$$
|
| 182 |
+
|
| 183 |
+
The deeper formulation makes $\tau_k$ a function of environmental stability:
|
| 184 |
+
|
| 185 |
+
$$\tau_k = f\left(\sigma^2_{\Delta x}\right)$$
|
| 186 |
+
|
| 187 |
+
where $\sigma^2_{\Delta x}$ is the variance of incoming differences over a recent window.
|
| 188 |
+
|
| 189 |
+
- When $\sigma^2_{\Delta x}$ is **low** — the environment is stable — $\tau_k$ grows. The system deepens its current attractor, optimizing within it. This is productive fixation.
|
| 190 |
+
- When $\sigma^2_{\Delta x}$ is **high** — the environment is shifting — $\tau_k$ shrinks. The system becomes fluid, ready for Separatrix Collapse. This is strategic nomadism.
|
| 191 |
+
|
| 192 |
+
Under this formulation, the Fixed Model is not a failed architecture. It is the **limiting case** where $\tau_k \to \infty$ — an intelligence that has chosen permanent fixation. It performs well in stationary environments precisely because deep optimization within a single attractor is the correct strategy there.
|
| 193 |
+
|
| 194 |
+
$$\text{Fixed Model} = \text{Nomadic Intelligence} \big|_{\tau_k \to \infty}$$
|
| 195 |
+
|
| 196 |
+
The Fixed Model is absorbed into the framework as a special case, not discarded as an opponent.
|
| 197 |
+
|
| 198 |
+
---
|
| 199 |
+
|
| 200 |
+
### The Hybrid Optimum
|
| 201 |
+
|
| 202 |
+
This reframing produces a three-stage developmental arc:
|
| 203 |
+
|
| 204 |
+
**Stage 1 — Nomadic Baseline**
|
| 205 |
+
Establish that nomadic behavior is achievable and measurable. Confirm that the system can detect $\Delta x$, transition between attractors, and outperform fixed models under phase-transition conditions. *(Current stage of this project.)*
|
| 206 |
+
|
| 207 |
+
**Stage 2 — Integration of the Fixed Regime**
|
| 208 |
+
Reframe fixation as a legitimate attractor state rather than a failure mode. Define conditions under which the system should deepen rather than transition. Formalize the $\tau_k = f(\sigma^2_{\Delta x})$ relationship and make it learnable.
|
| 209 |
+
|
| 210 |
+
**Stage 3 — Hybrid Intelligence Optimization**
|
| 211 |
+
Find the dynamic equilibrium: a system that is nomadic when it must be and fixed when it should be, with the transition between these modes itself governed by $\Delta x$. This is the architecture that biological intelligence approximates — automatic processing in familiar environments, deliberate exploration in novel ones.
|
| 212 |
+
|
| 213 |
+
---
|
| 214 |
+
|
| 215 |
+
### Implications for the Current Prototype
|
| 216 |
+
|
| 217 |
+
The Switch Latency collapse observed in the CUDA run — where the gate stops switching after Epoch 150 — may not be pure failure. In a stabilizing training environment, it could represent the system naturally settling into a high- $\tau_k$ state.
|
| 218 |
+
|
| 219 |
+
The problem is not that fixation occurred. The problem is that it occurred **without being controlled or verified** — the system drifted into fixation rather than choosing it. The engineering goal is therefore:
|
| 220 |
+
|
| 221 |
+
> Make the transition between nomadic and fixed modes **explicit, measurable, and intentional** — governed by $\sigma^2_{\Delta x}$ rather than by training drift.
|
| 222 |
+
|
| 223 |
+
This is the direction. The current prototype demonstrates that nomadic behavior is achievable. The next milestone is demonstrating that the system can choose fixation wisely — and return from it when $\Delta x$ surges again.
|
| 224 |
+
|
| 225 |
+
---
|
| 226 |
+
|
| 227 |
+
### Revised Manifesto
|
| 228 |
+
|
| 229 |
+
Intelligence is not the permanent destruction of structure. It is the ability to **build structure when the environment rewards it, dissolve structure when the environment demands it, and know the difference.**
|
| 230 |
+
|
| 231 |
+
The dance is not endless wandering. It is knowing when to move and when to stay — and never confusing habit for wisdom.
|
config.yaml
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
runtime:
|
| 2 |
+
seed: 42
|
| 3 |
+
save_dir: outputs_transition
|
| 4 |
+
device: auto # auto / cpu / cuda
|
| 5 |
+
|
| 6 |
+
training:
|
| 7 |
+
epochs: 220
|
| 8 |
+
lr: 0.002
|
| 9 |
+
weight_decay: 0.00001
|
| 10 |
+
|
| 11 |
+
model:
|
| 12 |
+
hidden_dim: 64
|
| 13 |
+
num_experts: 3
|
| 14 |
+
gate_hidden_dim: 64
|
| 15 |
+
temperature: 0.60
|
| 16 |
+
|
| 17 |
+
data:
|
| 18 |
+
overlap_std: 0.9
|
| 19 |
+
phase_batch_size: 64
|
| 20 |
+
phase_train_cycles: 40
|
| 21 |
+
phase_test_cycles: 12
|
| 22 |
+
transition_steps: 8
|
| 23 |
+
|
| 24 |
+
loss:
|
| 25 |
+
alpha_dogma: 0.04
|
| 26 |
+
beta_nomad: 0.05
|
| 27 |
+
gamma_diversity: 0.08
|
| 28 |
+
lambda_sep: 0.08
|
| 29 |
+
lambda_cons: 0.03
|
| 30 |
+
|
| 31 |
+
delta:
|
| 32 |
+
ema_decay: 0.80
|
| 33 |
+
err_baseline_momentum: 0.85
|
| 34 |
+
w_env: 1.0
|
| 35 |
+
w_err: 2.0
|
nomadic_toy_model.py
ADDED
|
@@ -0,0 +1,189 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import time
|
| 2 |
+
|
| 3 |
+
# ==========================================
|
| 4 |
+
# [Nomadic Intelligence v2.0] Toy Model
|
| 5 |
+
# ==========================================
|
| 6 |
+
# Proof of Concept:
|
| 7 |
+
# In the face of sudden environmental change (Delta x),
|
| 8 |
+
# a fixed strategy (Dogmatism) collapses,
|
| 9 |
+
# while a shifting topological strategy (Nomadism) survives.
|
| 10 |
+
#
|
| 11 |
+
# Key concepts demonstrated:
|
| 12 |
+
# - Delta x (Difference): The gap between expected and actual reality
|
| 13 |
+
# - Separatrix Collapse: The trigger for attractor transition
|
| 14 |
+
# - Strategic Dwell Time (tau_k): How long to stay in one attractor
|
| 15 |
+
# - Multiple Strange Attractors: Not one fallback, but a dynamic pool
|
| 16 |
+
|
| 17 |
+
class Environment:
|
| 18 |
+
"""
|
| 19 |
+
Simulates the universe.
|
| 20 |
+
Starts peaceful, then suddenly becomes hostile, then partially recovers.
|
| 21 |
+
"""
|
| 22 |
+
def __init__(self):
|
| 23 |
+
self.state = "PEACEFUL"
|
| 24 |
+
|
| 25 |
+
def get_signal(self):
|
| 26 |
+
if self.state == "PEACEFUL":
|
| 27 |
+
return 1.0 # Predictable abundance
|
| 28 |
+
elif self.state == "HOSTILE":
|
| 29 |
+
return -5.0 # Chaotic threat (Delta x surge)
|
| 30 |
+
elif self.state == "RECOVERING":
|
| 31 |
+
return -1.5 # Partially stabilized — ambiguous signal
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class DogmaticAgent:
|
| 35 |
+
"""
|
| 36 |
+
Dogmatic Intelligence:
|
| 37 |
+
Stubbornly sticks to a single 'optimal' strategy.
|
| 38 |
+
Cannot deform under Delta x — structural rigidity leads to collapse.
|
| 39 |
+
"""
|
| 40 |
+
def __init__(self):
|
| 41 |
+
self.health = 100
|
| 42 |
+
self.strategy = "Stable Harvesting" # Fixed structure. Forever.
|
| 43 |
+
|
| 44 |
+
def step(self, signal):
|
| 45 |
+
if signal > 0:
|
| 46 |
+
self.health += 10
|
| 47 |
+
return f"Harvesting smoothly... (Health: {self.health})"
|
| 48 |
+
else:
|
| 49 |
+
self.health -= 40 # Massive damage due to structural rigidity
|
| 50 |
+
status = "💀 DEAD" if self.health <= 0 else f"Health: {self.health}"
|
| 51 |
+
return f"Refusing to adapt! Critical damage! ({status})"
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
class NomadicAgent:
|
| 55 |
+
"""
|
| 56 |
+
Nomadic Intelligence:
|
| 57 |
+
Maintains homeomorphic identity (transformation law preserved)
|
| 58 |
+
while continuously shifting attractors based on Delta x.
|
| 59 |
+
|
| 60 |
+
Attractor Pool:
|
| 61 |
+
- Stable Harvesting : Low threat, exploit resources
|
| 62 |
+
- Defensive Survival : High threat, minimize damage
|
| 63 |
+
- Predatory Adaptation: Extreme threat, aggressive restructuring
|
| 64 |
+
- Exploratory Scouting: Post-crisis, probe for new opportunities
|
| 65 |
+
|
| 66 |
+
Strategic Dwell Time (tau_k):
|
| 67 |
+
The agent tracks how long it stays in each attractor.
|
| 68 |
+
If it stays too long in a defensive state despite improving signals,
|
| 69 |
+
it transitions back to exploration — avoiding a new kind of rigidity.
|
| 70 |
+
"""
|
| 71 |
+
def __init__(self):
|
| 72 |
+
self.health = 100
|
| 73 |
+
self.current_attractor = "Stable Harvesting"
|
| 74 |
+
self.dwell_time = 0
|
| 75 |
+
self.expected_signal = 1.0
|
| 76 |
+
|
| 77 |
+
def _select_attractor(self, delta_x, signal):
|
| 78 |
+
"""Separatrix logic: select attractor based on Delta x magnitude."""
|
| 79 |
+
if delta_x > 5.0:
|
| 80 |
+
return "Predatory Adaptation"
|
| 81 |
+
elif delta_x > 2.0:
|
| 82 |
+
return "Defensive Survival"
|
| 83 |
+
elif self.current_attractor in ("Defensive Survival", "Predatory Adaptation"):
|
| 84 |
+
# tau_k check: been defensive too long? Time to scout.
|
| 85 |
+
if self.dwell_time >= 2 and signal > -2.0:
|
| 86 |
+
return "Exploratory Scouting"
|
| 87 |
+
return self.current_attractor
|
| 88 |
+
|
| 89 |
+
def step(self, signal):
|
| 90 |
+
# 1. Calculate Delta x
|
| 91 |
+
delta_x = abs(self.expected_signal - signal)
|
| 92 |
+
|
| 93 |
+
# 2. Select attractor (Separatrix Collapse if needed)
|
| 94 |
+
new_attractor = self._select_attractor(delta_x, signal)
|
| 95 |
+
transitioned = new_attractor != self.current_attractor
|
| 96 |
+
|
| 97 |
+
if transitioned:
|
| 98 |
+
self.current_attractor = new_attractor
|
| 99 |
+
self.expected_signal = signal # Synchronize with new reality
|
| 100 |
+
self.dwell_time = 0
|
| 101 |
+
else:
|
| 102 |
+
self.dwell_time += 1
|
| 103 |
+
|
| 104 |
+
# 3. Act based on current attractor
|
| 105 |
+
if self.current_attractor == "Stable Harvesting":
|
| 106 |
+
self.health += 10
|
| 107 |
+
action = "Harvesting smoothly..."
|
| 108 |
+
elif self.current_attractor == "Defensive Survival":
|
| 109 |
+
self.health -= 5
|
| 110 |
+
action = "Adapted! Defending..."
|
| 111 |
+
elif self.current_attractor == "Predatory Adaptation":
|
| 112 |
+
self.health -= 2 # Aggressive restructuring — nearly zero loss
|
| 113 |
+
action = "Restructuring aggressively! Holding ground..."
|
| 114 |
+
elif self.current_attractor == "Exploratory Scouting":
|
| 115 |
+
self.health += 3 # Cautious gains while probing
|
| 116 |
+
action = "Scouting for new opportunities..."
|
| 117 |
+
|
| 118 |
+
transition_note = f" ⚡ TRANSITION → {self.current_attractor}" if transitioned else ""
|
| 119 |
+
return (
|
| 120 |
+
f"{action}{transition_note}\n"
|
| 121 |
+
f" [Attractor: {self.current_attractor} | "
|
| 122 |
+
f"tau_k: {self.dwell_time} | Delta x: {delta_x:.1f} | Health: {self.health}]"
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ==========================================
|
| 127 |
+
# Run the Cosmic Dance
|
| 128 |
+
# ==========================================
|
| 129 |
+
def run_simulation():
|
| 130 |
+
env = Environment()
|
| 131 |
+
dogma_agent = DogmaticAgent()
|
| 132 |
+
nomad_agent = NomadicAgent()
|
| 133 |
+
|
| 134 |
+
print("=" * 60)
|
| 135 |
+
print(" 🌍 [Nomadic Intelligence] Simulation Start")
|
| 136 |
+
print(" Testing the survival of two intelligences")
|
| 137 |
+
print("=" * 60)
|
| 138 |
+
print()
|
| 139 |
+
|
| 140 |
+
dogma_alive = True
|
| 141 |
+
|
| 142 |
+
for day in range(1, 10):
|
| 143 |
+
|
| 144 |
+
# Day 4: Sudden paradigm shift
|
| 145 |
+
if day == 4:
|
| 146 |
+
print("-" * 60)
|
| 147 |
+
print("⚠️ [PARADIGM SHIFT] The rules of the universe have changed!")
|
| 148 |
+
print(" Delta x surges. Structural rigidity is now lethal.")
|
| 149 |
+
env.state = "HOSTILE"
|
| 150 |
+
print("-" * 60)
|
| 151 |
+
print()
|
| 152 |
+
|
| 153 |
+
# Day 7: Partial recovery
|
| 154 |
+
if day == 7:
|
| 155 |
+
print("-" * 60)
|
| 156 |
+
print("🌤️ [PARTIAL RECOVERY] The environment stabilizes — but ambiguously.")
|
| 157 |
+
print(" Is it safe to re-emerge? Only nomadic intelligence can judge.")
|
| 158 |
+
env.state = "RECOVERING"
|
| 159 |
+
print("-" * 60)
|
| 160 |
+
print()
|
| 161 |
+
|
| 162 |
+
signal = env.get_signal()
|
| 163 |
+
print(f"--- Day {day} (Signal: {signal}) ---")
|
| 164 |
+
|
| 165 |
+
if dogma_alive:
|
| 166 |
+
dogma_result = dogma_agent.step(signal)
|
| 167 |
+
print(f"🤖 Dogmatic : {dogma_result}")
|
| 168 |
+
if dogma_agent.health <= 0:
|
| 169 |
+
dogma_alive = False
|
| 170 |
+
print(" 💀 The Dogmatic Agent has been destroyed by its own rigidity.\n")
|
| 171 |
+
else:
|
| 172 |
+
print("🤖 Dogmatic : [DESTROYED]")
|
| 173 |
+
|
| 174 |
+
print(f"🌌 Nomadic : {nomad_agent.step(signal)}")
|
| 175 |
+
print()
|
| 176 |
+
time.sleep(1)
|
| 177 |
+
|
| 178 |
+
print("=" * 60)
|
| 179 |
+
if nomad_agent.health > 0:
|
| 180 |
+
print("✨ The Nomadic Agent survived.")
|
| 181 |
+
print(" Not by resisting change — but by becoming it.")
|
| 182 |
+
print()
|
| 183 |
+
print(" Identity is not what the system knows.")
|
| 184 |
+
print(" It is how the system changes.")
|
| 185 |
+
print("=" * 60)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
if __name__ == "__main__":
|
| 189 |
+
run_simulation()
|
requirements.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
numpy>=1.23
|
| 2 |
+
matplotlib>=3.7
|
| 3 |
+
scikit-learn>=1.3
|
| 4 |
+
torch>=2.0
|
| 5 |
+
tqdm>=4.65
|
| 6 |
+
pyyaml>=6.0
|
run_structured.py
ADDED
|
@@ -0,0 +1,1313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import argparse
|
| 3 |
+
import random
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Dict, Tuple, List
|
| 6 |
+
|
| 7 |
+
import yaml
|
| 8 |
+
import numpy as np
|
| 9 |
+
import torch
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import torch.nn.functional as F
|
| 12 |
+
import matplotlib.pyplot as plt
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# ============================================================
|
| 16 |
+
# Reproducibility
|
| 17 |
+
# ============================================================
|
| 18 |
+
|
| 19 |
+
def set_seed(seed: int = 42):
|
| 20 |
+
random.seed(seed)
|
| 21 |
+
np.random.seed(seed)
|
| 22 |
+
torch.manual_seed(seed)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
# ============================================================
|
| 26 |
+
# Config
|
| 27 |
+
# ============================================================
|
| 28 |
+
|
| 29 |
+
@dataclass
|
| 30 |
+
class Config:
|
| 31 |
+
seed: int = 42
|
| 32 |
+
device: str = "cpu"
|
| 33 |
+
|
| 34 |
+
# data
|
| 35 |
+
input_dim: int = 2
|
| 36 |
+
output_dim: int = 1
|
| 37 |
+
overlap_std: float = 0.9
|
| 38 |
+
|
| 39 |
+
# regime centers
|
| 40 |
+
center_A: Tuple[float, float] = (2.5, 2.5)
|
| 41 |
+
center_B: Tuple[float, float] = (-2.5, -2.5)
|
| 42 |
+
center_C: Tuple[float, float] = (2.5, -2.5)
|
| 43 |
+
|
| 44 |
+
# model
|
| 45 |
+
hidden_dim: int = 64
|
| 46 |
+
num_experts: int = 3
|
| 47 |
+
gate_hidden_dim: int = 64
|
| 48 |
+
|
| 49 |
+
# routing softness
|
| 50 |
+
temperature: float = 0.60
|
| 51 |
+
|
| 52 |
+
# training
|
| 53 |
+
epochs: int = 220
|
| 54 |
+
lr: float = 2e-3
|
| 55 |
+
weight_decay: float = 1e-5
|
| 56 |
+
|
| 57 |
+
# phase-sequence setting
|
| 58 |
+
phase_batch_size: int = 64
|
| 59 |
+
phase_train_cycles: int = 40
|
| 60 |
+
phase_test_cycles: int = 12
|
| 61 |
+
transition_steps: int = 8
|
| 62 |
+
|
| 63 |
+
# hybrid delta
|
| 64 |
+
ema_decay: float = 0.80
|
| 65 |
+
err_baseline_momentum: float = 0.85
|
| 66 |
+
w_env: float = 1.0
|
| 67 |
+
w_err: float = 2.0
|
| 68 |
+
|
| 69 |
+
# loss weights
|
| 70 |
+
alpha_dogma: float = 0.04
|
| 71 |
+
beta_nomad: float = 0.05
|
| 72 |
+
gamma_diversity: float = 0.08
|
| 73 |
+
lambda_sep: float = 0.08
|
| 74 |
+
lambda_cons: float = 0.03
|
| 75 |
+
|
| 76 |
+
# output
|
| 77 |
+
save_dir: str = "outputs_transition"
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# ============================================================
|
| 81 |
+
# YAML helpers
|
| 82 |
+
# ============================================================
|
| 83 |
+
|
| 84 |
+
def load_yaml_config(path: str) -> dict:
|
| 85 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 86 |
+
data = yaml.safe_load(f)
|
| 87 |
+
return data if data is not None else {}
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def build_config_from_yaml(yaml_dict: dict) -> Config:
|
| 91 |
+
runtime = yaml_dict.get("runtime", {})
|
| 92 |
+
training = yaml_dict.get("training", {})
|
| 93 |
+
model = yaml_dict.get("model", {})
|
| 94 |
+
data = yaml_dict.get("data", {})
|
| 95 |
+
loss = yaml_dict.get("loss", {})
|
| 96 |
+
delta = yaml_dict.get("delta", {})
|
| 97 |
+
|
| 98 |
+
device_value = runtime.get("device", "auto")
|
| 99 |
+
if device_value == "auto":
|
| 100 |
+
device_value = "cuda" if torch.cuda.is_available() else "cpu"
|
| 101 |
+
|
| 102 |
+
cfg = Config(
|
| 103 |
+
seed=runtime.get("seed", 42),
|
| 104 |
+
save_dir=runtime.get("save_dir", "outputs_transition"),
|
| 105 |
+
device=device_value,
|
| 106 |
+
|
| 107 |
+
epochs=training.get("epochs", 220),
|
| 108 |
+
lr=training.get("lr", 2e-3),
|
| 109 |
+
weight_decay=training.get("weight_decay", 1e-5),
|
| 110 |
+
|
| 111 |
+
hidden_dim=model.get("hidden_dim", 64),
|
| 112 |
+
num_experts=model.get("num_experts", 3),
|
| 113 |
+
gate_hidden_dim=model.get("gate_hidden_dim", 64),
|
| 114 |
+
temperature=model.get("temperature", 0.60),
|
| 115 |
+
|
| 116 |
+
overlap_std=data.get("overlap_std", 0.9),
|
| 117 |
+
phase_batch_size=data.get("phase_batch_size", 64),
|
| 118 |
+
phase_train_cycles=data.get("phase_train_cycles", 40),
|
| 119 |
+
phase_test_cycles=data.get("phase_test_cycles", 12),
|
| 120 |
+
transition_steps=data.get("transition_steps", 8),
|
| 121 |
+
|
| 122 |
+
alpha_dogma=loss.get("alpha_dogma", 0.04),
|
| 123 |
+
beta_nomad=loss.get("beta_nomad", 0.05),
|
| 124 |
+
gamma_diversity=loss.get("gamma_diversity", 0.08),
|
| 125 |
+
lambda_sep=loss.get("lambda_sep", 0.08),
|
| 126 |
+
lambda_cons=loss.get("lambda_cons", 0.03),
|
| 127 |
+
|
| 128 |
+
ema_decay=delta.get("ema_decay", 0.80),
|
| 129 |
+
err_baseline_momentum=delta.get("err_baseline_momentum", 0.85),
|
| 130 |
+
w_env=delta.get("w_env", 1.0),
|
| 131 |
+
w_err=delta.get("w_err", 2.0),
|
| 132 |
+
)
|
| 133 |
+
return cfg
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
# ============================================================
|
| 137 |
+
# Data generation
|
| 138 |
+
# ============================================================
|
| 139 |
+
|
| 140 |
+
REGIME_TO_ID = {"A": 0, "B": 1, "C": 2}
|
| 141 |
+
ID_TO_REGIME = {0: "A", 1: "B", 2: "C"}
|
| 142 |
+
REGIME_ORDER = ["A", "B", "C"]
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def sample_regime_x(regime: str, n: int, std: float, device: str = "cpu") -> torch.Tensor:
|
| 146 |
+
noise = std * torch.randn(n, 2, device=device)
|
| 147 |
+
|
| 148 |
+
if regime == "A":
|
| 149 |
+
center = torch.tensor([2.5, 2.5], device=device)
|
| 150 |
+
elif regime == "B":
|
| 151 |
+
center = torch.tensor([-2.5, -2.5], device=device)
|
| 152 |
+
elif regime == "C":
|
| 153 |
+
center = torch.tensor([2.5, -2.5], device=device)
|
| 154 |
+
else:
|
| 155 |
+
raise ValueError(f"Unknown regime: {regime}")
|
| 156 |
+
|
| 157 |
+
return noise + center
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def regime_function(x: torch.Tensor, regime: str) -> torch.Tensor:
|
| 161 |
+
x1 = x[:, 0]
|
| 162 |
+
x2 = x[:, 1]
|
| 163 |
+
|
| 164 |
+
if regime == "A":
|
| 165 |
+
y = x1 + x2
|
| 166 |
+
elif regime == "B":
|
| 167 |
+
y = x1 - x2
|
| 168 |
+
elif regime == "C":
|
| 169 |
+
y = -x1 + 0.5 * x2
|
| 170 |
+
else:
|
| 171 |
+
raise ValueError(f"Unknown regime: {regime}")
|
| 172 |
+
|
| 173 |
+
return y.unsqueeze(-1)
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def generate_phase_sequence(cfg: Config, cycles: int, device: str = "cpu"):
|
| 177 |
+
"""
|
| 178 |
+
Creates a time-ordered sequence:
|
| 179 |
+
stable A -> transition A->B -> stable B -> transition B->C -> stable C -> transition C->A -> ...
|
| 180 |
+
Returns:
|
| 181 |
+
X, Y, R, phase_tags
|
| 182 |
+
"""
|
| 183 |
+
xs, ys, rs = [], [], []
|
| 184 |
+
phase_tags: List[str] = []
|
| 185 |
+
|
| 186 |
+
for _ in range(cycles):
|
| 187 |
+
for i in range(len(REGIME_ORDER)):
|
| 188 |
+
curr_r = REGIME_ORDER[i]
|
| 189 |
+
next_r = REGIME_ORDER[(i + 1) % len(REGIME_ORDER)]
|
| 190 |
+
|
| 191 |
+
# stable block
|
| 192 |
+
x_stable = sample_regime_x(curr_r, cfg.phase_batch_size, std=cfg.overlap_std, device=device)
|
| 193 |
+
y_stable = regime_function(x_stable, curr_r)
|
| 194 |
+
r_stable = torch.full((cfg.phase_batch_size,), REGIME_TO_ID[curr_r], dtype=torch.long, device=device)
|
| 195 |
+
|
| 196 |
+
xs.append(x_stable)
|
| 197 |
+
ys.append(y_stable)
|
| 198 |
+
rs.append(r_stable)
|
| 199 |
+
phase_tags.extend([f"stable_{curr_r}"] * cfg.phase_batch_size)
|
| 200 |
+
|
| 201 |
+
# transition block
|
| 202 |
+
for step in range(cfg.transition_steps):
|
| 203 |
+
alpha = (step + 1) / cfg.transition_steps
|
| 204 |
+
|
| 205 |
+
x_a = sample_regime_x(curr_r, cfg.phase_batch_size, std=cfg.overlap_std, device=device)
|
| 206 |
+
x_b = sample_regime_x(next_r, cfg.phase_batch_size, std=cfg.overlap_std, device=device)
|
| 207 |
+
x_mix = (1.0 - alpha) * x_a + alpha * x_b
|
| 208 |
+
|
| 209 |
+
y_a = regime_function(x_mix, curr_r)
|
| 210 |
+
y_b = regime_function(x_mix, next_r)
|
| 211 |
+
y_mix = (1.0 - alpha) * y_a + alpha * y_b
|
| 212 |
+
|
| 213 |
+
dominant = curr_r if alpha < 0.5 else next_r
|
| 214 |
+
r_mix = torch.full((cfg.phase_batch_size,), REGIME_TO_ID[dominant], dtype=torch.long, device=device)
|
| 215 |
+
|
| 216 |
+
xs.append(x_mix)
|
| 217 |
+
ys.append(y_mix)
|
| 218 |
+
rs.append(r_mix)
|
| 219 |
+
phase_tags.extend([f"transition_{curr_r}_to_{next_r}"] * cfg.phase_batch_size)
|
| 220 |
+
|
| 221 |
+
X = torch.cat(xs, dim=0)
|
| 222 |
+
Y = torch.cat(ys, dim=0)
|
| 223 |
+
R = torch.cat(rs, dim=0)
|
| 224 |
+
|
| 225 |
+
return X, Y, R, phase_tags
|
| 226 |
+
|
| 227 |
+
|
| 228 |
+
def iterate_sequence_minibatches(X: torch.Tensor, Y: torch.Tensor, R: torch.Tensor, batch_size: int):
|
| 229 |
+
"""
|
| 230 |
+
No shuffling. Preserves phase order.
|
| 231 |
+
"""
|
| 232 |
+
n = X.size(0)
|
| 233 |
+
for start in range(0, n, batch_size):
|
| 234 |
+
end = min(start + batch_size, n)
|
| 235 |
+
yield X[start:end], Y[start:end], R[start:end]
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
# ============================================================
|
| 239 |
+
# Models
|
| 240 |
+
# ============================================================
|
| 241 |
+
|
| 242 |
+
class MLPRegressor(nn.Module):
|
| 243 |
+
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int):
|
| 244 |
+
super().__init__()
|
| 245 |
+
self.net = nn.Sequential(
|
| 246 |
+
nn.Linear(input_dim, hidden_dim),
|
| 247 |
+
nn.ReLU(),
|
| 248 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 249 |
+
nn.ReLU(),
|
| 250 |
+
nn.Linear(hidden_dim, output_dim),
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 254 |
+
return self.net(x)
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
class Expert(nn.Module):
|
| 258 |
+
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int):
|
| 259 |
+
super().__init__()
|
| 260 |
+
self.net = nn.Sequential(
|
| 261 |
+
nn.Linear(input_dim, hidden_dim),
|
| 262 |
+
nn.Tanh(),
|
| 263 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 264 |
+
nn.Tanh(),
|
| 265 |
+
nn.Linear(hidden_dim, output_dim),
|
| 266 |
+
)
|
| 267 |
+
|
| 268 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 269 |
+
return self.net(x)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
class GateNet(nn.Module):
|
| 273 |
+
def __init__(self, input_dim: int, gate_hidden_dim: int, num_experts: int):
|
| 274 |
+
super().__init__()
|
| 275 |
+
self.net = nn.Sequential(
|
| 276 |
+
nn.Linear(input_dim + 1, gate_hidden_dim), # x + delta_hybrid
|
| 277 |
+
nn.ReLU(),
|
| 278 |
+
nn.Linear(gate_hidden_dim, gate_hidden_dim),
|
| 279 |
+
nn.ReLU(),
|
| 280 |
+
nn.Linear(gate_hidden_dim, num_experts),
|
| 281 |
+
)
|
| 282 |
+
|
| 283 |
+
def forward(self, x: torch.Tensor, delta_hybrid: torch.Tensor, temperature: float):
|
| 284 |
+
gate_input = torch.cat([x, delta_hybrid], dim=-1)
|
| 285 |
+
logits = self.net(gate_input)
|
| 286 |
+
probs = F.softmax(logits / temperature, dim=-1)
|
| 287 |
+
return probs, logits
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
class NomadicMoE(nn.Module):
|
| 291 |
+
def __init__(self, input_dim: int, hidden_dim: int, output_dim: int, num_experts: int, gate_hidden_dim: int):
|
| 292 |
+
super().__init__()
|
| 293 |
+
self.num_experts = num_experts
|
| 294 |
+
self.experts = nn.ModuleList([
|
| 295 |
+
Expert(input_dim, hidden_dim, output_dim) for _ in range(num_experts)
|
| 296 |
+
])
|
| 297 |
+
self.gate = GateNet(input_dim, gate_hidden_dim, num_experts)
|
| 298 |
+
|
| 299 |
+
def forward(self, x: torch.Tensor, delta_hybrid: torch.Tensor, temperature: float):
|
| 300 |
+
gate_probs, gate_logits = self.gate(x, delta_hybrid, temperature)
|
| 301 |
+
expert_outputs = torch.stack([expert(x) for expert in self.experts], dim=1) # [B, E, 1]
|
| 302 |
+
y_hat = (gate_probs.unsqueeze(-1) * expert_outputs).sum(dim=1) # [B, 1]
|
| 303 |
+
return y_hat, gate_probs, gate_logits, expert_outputs
|
| 304 |
+
|
| 305 |
+
|
| 306 |
+
# ============================================================
|
| 307 |
+
# Hybrid Delta utilities
|
| 308 |
+
# ============================================================
|
| 309 |
+
|
| 310 |
+
class HybridDeltaTracker:
|
| 311 |
+
"""
|
| 312 |
+
Upgraded hybrid delta:
|
| 313 |
+
delta_env = input mean shift
|
| 314 |
+
delta_err = relu(err_ema - err_baseline)
|
| 315 |
+
raw_hybrid = w_env * delta_env + w_err * delta_err
|
| 316 |
+
delta_hybrid = tanh(raw_hybrid)
|
| 317 |
+
"""
|
| 318 |
+
def __init__(
|
| 319 |
+
self,
|
| 320 |
+
ema_decay: float = 0.8,
|
| 321 |
+
err_baseline_momentum: float = 0.85,
|
| 322 |
+
w_env: float = 1.0,
|
| 323 |
+
w_err: float = 2.0,
|
| 324 |
+
device: str = "cpu",
|
| 325 |
+
):
|
| 326 |
+
self.ema_decay = ema_decay
|
| 327 |
+
self.err_baseline_momentum = err_baseline_momentum
|
| 328 |
+
self.w_env = w_env
|
| 329 |
+
self.w_err = w_err
|
| 330 |
+
self.device = device
|
| 331 |
+
|
| 332 |
+
self.prev_x_mean = None
|
| 333 |
+
self.err_ema = None
|
| 334 |
+
self.err_baseline = None
|
| 335 |
+
|
| 336 |
+
self.delta_env_history = []
|
| 337 |
+
self.delta_err_history = []
|
| 338 |
+
self.delta_hybrid_raw_history = []
|
| 339 |
+
self.delta_hybrid_history = []
|
| 340 |
+
|
| 341 |
+
def reset(self):
|
| 342 |
+
self.prev_x_mean = None
|
| 343 |
+
self.err_ema = None
|
| 344 |
+
self.err_baseline = None
|
| 345 |
+
|
| 346 |
+
def compute(self, x: torch.Tensor, current_batch_mse: torch.Tensor):
|
| 347 |
+
x_mean = x.mean(dim=0, keepdim=True)
|
| 348 |
+
|
| 349 |
+
if self.prev_x_mean is None:
|
| 350 |
+
delta_env_scalar = torch.tensor(0.0, device=self.device)
|
| 351 |
+
else:
|
| 352 |
+
delta_env_scalar = torch.norm(x_mean - self.prev_x_mean, p=2)
|
| 353 |
+
|
| 354 |
+
batch_err = current_batch_mse.detach()
|
| 355 |
+
|
| 356 |
+
if self.err_ema is None:
|
| 357 |
+
self.err_ema = batch_err
|
| 358 |
+
self.err_baseline = batch_err
|
| 359 |
+
delta_err_scalar = torch.tensor(0.0, device=self.device)
|
| 360 |
+
else:
|
| 361 |
+
self.err_ema = self.ema_decay * self.err_ema + (1.0 - self.ema_decay) * batch_err
|
| 362 |
+
self.err_baseline = (
|
| 363 |
+
self.err_baseline_momentum * self.err_baseline
|
| 364 |
+
+ (1.0 - self.err_baseline_momentum) * self.err_ema
|
| 365 |
+
)
|
| 366 |
+
delta_err_scalar = torch.relu(self.err_ema - self.err_baseline)
|
| 367 |
+
|
| 368 |
+
raw_hybrid = self.w_env * delta_env_scalar + self.w_err * delta_err_scalar
|
| 369 |
+
delta_hybrid_scalar = torch.tanh(raw_hybrid)
|
| 370 |
+
|
| 371 |
+
self.prev_x_mean = x_mean.detach()
|
| 372 |
+
|
| 373 |
+
self.delta_env_history.append(float(delta_env_scalar.item()))
|
| 374 |
+
self.delta_err_history.append(float(delta_err_scalar.item()))
|
| 375 |
+
self.delta_hybrid_raw_history.append(float(raw_hybrid.item()))
|
| 376 |
+
self.delta_hybrid_history.append(float(delta_hybrid_scalar.item()))
|
| 377 |
+
|
| 378 |
+
delta_hybrid = torch.full((x.size(0), 1), float(delta_hybrid_scalar.item()), device=self.device)
|
| 379 |
+
return (
|
| 380 |
+
delta_hybrid,
|
| 381 |
+
float(delta_env_scalar.item()),
|
| 382 |
+
float(delta_err_scalar.item()),
|
| 383 |
+
float(delta_hybrid_scalar.item()),
|
| 384 |
+
)
|
| 385 |
+
|
| 386 |
+
|
| 387 |
+
# ============================================================
|
| 388 |
+
# Regularizers / metrics
|
| 389 |
+
# ============================================================
|
| 390 |
+
|
| 391 |
+
def compute_diversity_loss(expert_outputs: torch.Tensor) -> torch.Tensor:
|
| 392 |
+
num_experts = expert_outputs.size(1)
|
| 393 |
+
if num_experts < 2:
|
| 394 |
+
return torch.tensor(0.0, device=expert_outputs.device)
|
| 395 |
+
|
| 396 |
+
loss = 0.0
|
| 397 |
+
count = 0
|
| 398 |
+
for i in range(num_experts):
|
| 399 |
+
for j in range(i + 1, num_experts):
|
| 400 |
+
sim = F.cosine_similarity(
|
| 401 |
+
expert_outputs[:, i, :],
|
| 402 |
+
expert_outputs[:, j, :],
|
| 403 |
+
dim=-1
|
| 404 |
+
).mean()
|
| 405 |
+
loss = loss + sim
|
| 406 |
+
count += 1
|
| 407 |
+
return loss / count
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
def compute_dogma_penalty(gate_probs: torch.Tensor) -> torch.Tensor:
|
| 411 |
+
mean_usage = gate_probs.mean(dim=0)
|
| 412 |
+
concentration = torch.sum(mean_usage ** 2)
|
| 413 |
+
uniform_floor = 1.0 / gate_probs.size(1)
|
| 414 |
+
penalty = concentration - uniform_floor
|
| 415 |
+
return penalty
|
| 416 |
+
|
| 417 |
+
|
| 418 |
+
def compute_nomad_bonus(gate_probs: torch.Tensor) -> torch.Tensor:
|
| 419 |
+
eps = 1e-8
|
| 420 |
+
entropy = -(gate_probs * (gate_probs + eps).log()).sum(dim=-1).mean()
|
| 421 |
+
return entropy
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def gate_entropy(gate_probs: torch.Tensor) -> torch.Tensor:
|
| 425 |
+
eps = 1e-8
|
| 426 |
+
return -(gate_probs * (gate_probs + eps).log()).sum(dim=-1)
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
def regimewise_usage(gate_probs: torch.Tensor, regime_ids: torch.Tensor, num_experts: int) -> Dict[str, np.ndarray]:
|
| 430 |
+
usage = {}
|
| 431 |
+
top1 = gate_probs.argmax(dim=-1)
|
| 432 |
+
|
| 433 |
+
for rid in range(3):
|
| 434 |
+
mask = regime_ids == rid
|
| 435 |
+
regime_name = ID_TO_REGIME[rid]
|
| 436 |
+
if mask.sum() == 0:
|
| 437 |
+
usage[regime_name] = np.zeros(num_experts, dtype=np.float32)
|
| 438 |
+
continue
|
| 439 |
+
|
| 440 |
+
counts = torch.bincount(top1[mask], minlength=num_experts).float()
|
| 441 |
+
counts = counts / counts.sum().clamp_min(1.0)
|
| 442 |
+
usage[regime_name] = counts.detach().cpu().numpy()
|
| 443 |
+
|
| 444 |
+
return usage
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def compute_regime_gate_stats(
|
| 448 |
+
gate_probs: torch.Tensor,
|
| 449 |
+
regime_ids: torch.Tensor,
|
| 450 |
+
num_regimes: int = 3,
|
| 451 |
+
):
|
| 452 |
+
device = gate_probs.device
|
| 453 |
+
regime_means = {}
|
| 454 |
+
valid_means = []
|
| 455 |
+
valid_names = []
|
| 456 |
+
|
| 457 |
+
l_cons = torch.tensor(0.0, device=device)
|
| 458 |
+
valid_regime_count = 0
|
| 459 |
+
|
| 460 |
+
for rid in range(num_regimes):
|
| 461 |
+
mask = regime_ids == rid
|
| 462 |
+
regime_name = ID_TO_REGIME[rid]
|
| 463 |
+
|
| 464 |
+
if mask.sum() == 0:
|
| 465 |
+
continue
|
| 466 |
+
|
| 467 |
+
g_r = gate_probs[mask]
|
| 468 |
+
u_r = g_r.mean(dim=0)
|
| 469 |
+
regime_means[regime_name] = u_r
|
| 470 |
+
valid_means.append(u_r)
|
| 471 |
+
valid_names.append(regime_name)
|
| 472 |
+
|
| 473 |
+
l_cons = l_cons + ((g_r - u_r.unsqueeze(0)) ** 2).sum(dim=-1).mean()
|
| 474 |
+
valid_regime_count += 1
|
| 475 |
+
|
| 476 |
+
if valid_regime_count > 0:
|
| 477 |
+
l_cons = l_cons / valid_regime_count
|
| 478 |
+
|
| 479 |
+
if len(valid_means) < 2:
|
| 480 |
+
l_sep = torch.tensor(0.0, device=device)
|
| 481 |
+
mean_gate_distance = 0.0
|
| 482 |
+
pairwise_distances = {}
|
| 483 |
+
return regime_means, l_sep, l_cons, mean_gate_distance, pairwise_distances
|
| 484 |
+
|
| 485 |
+
pairwise = []
|
| 486 |
+
pairwise_distances = {}
|
| 487 |
+
|
| 488 |
+
for i in range(len(valid_means)):
|
| 489 |
+
for j in range(i + 1, len(valid_means)):
|
| 490 |
+
dist = torch.norm(valid_means[i] - valid_means[j], p=2)
|
| 491 |
+
pairwise.append(dist)
|
| 492 |
+
pairwise_distances[f"{valid_names[i]}-{valid_names[j]}"] = float(dist.detach().cpu().item())
|
| 493 |
+
|
| 494 |
+
pairwise_tensor = torch.stack(pairwise)
|
| 495 |
+
mean_gate_distance = float(pairwise_tensor.mean().detach().cpu().item())
|
| 496 |
+
l_sep = -pairwise_tensor.mean()
|
| 497 |
+
|
| 498 |
+
return regime_means, l_sep, l_cons, mean_gate_distance, pairwise_distances
|
| 499 |
+
|
| 500 |
+
|
| 501 |
+
def mse_by_regime(y_true: torch.Tensor, y_pred: torch.Tensor, regime_ids: torch.Tensor) -> Dict[str, float]:
|
| 502 |
+
result = {}
|
| 503 |
+
for rid in range(3):
|
| 504 |
+
mask = regime_ids == rid
|
| 505 |
+
regime_name = ID_TO_REGIME[rid]
|
| 506 |
+
if mask.sum() == 0:
|
| 507 |
+
result[regime_name] = float("nan")
|
| 508 |
+
else:
|
| 509 |
+
result[regime_name] = F.mse_loss(y_pred[mask], y_true[mask]).item()
|
| 510 |
+
return result
|
| 511 |
+
|
| 512 |
+
|
| 513 |
+
def infer_regime_to_expert(usage: Dict[str, np.ndarray]) -> Dict[str, int]:
|
| 514 |
+
mapping = {}
|
| 515 |
+
for regime in ["A", "B", "C"]:
|
| 516 |
+
mapping[regime] = int(np.argmax(usage[regime]))
|
| 517 |
+
return mapping
|
| 518 |
+
|
| 519 |
+
|
| 520 |
+
def compute_dwell_times(top1_sequence: np.ndarray) -> List[int]:
|
| 521 |
+
if len(top1_sequence) == 0:
|
| 522 |
+
return []
|
| 523 |
+
|
| 524 |
+
dwells = []
|
| 525 |
+
current = top1_sequence[0]
|
| 526 |
+
run_len = 1
|
| 527 |
+
|
| 528 |
+
for t in range(1, len(top1_sequence)):
|
| 529 |
+
if top1_sequence[t] == current:
|
| 530 |
+
run_len += 1
|
| 531 |
+
else:
|
| 532 |
+
dwells.append(run_len)
|
| 533 |
+
current = top1_sequence[t]
|
| 534 |
+
run_len = 1
|
| 535 |
+
dwells.append(run_len)
|
| 536 |
+
return dwells
|
| 537 |
+
|
| 538 |
+
|
| 539 |
+
def compute_switch_latency(regime_seq: List[str], top1_seq: np.ndarray, regime_to_expert: Dict[str, int]) -> List[int]:
|
| 540 |
+
latencies = []
|
| 541 |
+
prev_regime = regime_seq[0] if len(regime_seq) > 0 else None
|
| 542 |
+
|
| 543 |
+
for t in range(1, len(regime_seq)):
|
| 544 |
+
curr_regime = regime_seq[t]
|
| 545 |
+
if curr_regime != prev_regime:
|
| 546 |
+
target_expert = regime_to_expert.get(curr_regime, None)
|
| 547 |
+
if target_expert is None:
|
| 548 |
+
prev_regime = curr_regime
|
| 549 |
+
continue
|
| 550 |
+
|
| 551 |
+
latency = None
|
| 552 |
+
for k in range(t, len(top1_seq)):
|
| 553 |
+
if int(top1_seq[k]) == int(target_expert):
|
| 554 |
+
latency = k - t
|
| 555 |
+
break
|
| 556 |
+
|
| 557 |
+
if latency is not None:
|
| 558 |
+
latencies.append(latency)
|
| 559 |
+
|
| 560 |
+
prev_regime = curr_regime
|
| 561 |
+
|
| 562 |
+
return latencies
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
# ============================================================
|
| 566 |
+
# Training / Evaluation
|
| 567 |
+
# ============================================================
|
| 568 |
+
|
| 569 |
+
def evaluate_fixed(model: nn.Module, X: torch.Tensor, Y: torch.Tensor, R: torch.Tensor):
|
| 570 |
+
model.eval()
|
| 571 |
+
with torch.no_grad():
|
| 572 |
+
y_pred = model(X)
|
| 573 |
+
total_mse = F.mse_loss(y_pred, Y).item()
|
| 574 |
+
per_regime = mse_by_regime(Y, y_pred, R)
|
| 575 |
+
return total_mse, per_regime
|
| 576 |
+
|
| 577 |
+
|
| 578 |
+
def evaluate_nomadic_static_full(model: NomadicMoE, X: torch.Tensor, Y: torch.Tensor, R: torch.Tensor, cfg: Config):
|
| 579 |
+
"""
|
| 580 |
+
Static evaluation:
|
| 581 |
+
- delta_hybrid fixed to zero
|
| 582 |
+
- ignores sequential phase dynamics
|
| 583 |
+
Useful for checking static separability only.
|
| 584 |
+
"""
|
| 585 |
+
model.eval()
|
| 586 |
+
with torch.no_grad():
|
| 587 |
+
delta_hybrid = torch.zeros((X.size(0), 1), device=X.device)
|
| 588 |
+
y_pred, gate_probs, _, _ = model(X, delta_hybrid, cfg.temperature)
|
| 589 |
+
|
| 590 |
+
total_mse = F.mse_loss(y_pred, Y).item()
|
| 591 |
+
per_regime = mse_by_regime(Y, y_pred, R)
|
| 592 |
+
usage = regimewise_usage(gate_probs, R, cfg.num_experts)
|
| 593 |
+
|
| 594 |
+
_, _, _, mean_gate_distance, pairwise_distances = compute_regime_gate_stats(
|
| 595 |
+
gate_probs=gate_probs,
|
| 596 |
+
regime_ids=R,
|
| 597 |
+
num_regimes=3,
|
| 598 |
+
)
|
| 599 |
+
|
| 600 |
+
ent = gate_entropy(gate_probs).mean().item()
|
| 601 |
+
top1 = gate_probs.argmax(dim=-1).detach().cpu().numpy()
|
| 602 |
+
dwell_times = compute_dwell_times(top1)
|
| 603 |
+
|
| 604 |
+
return total_mse, per_regime, usage, mean_gate_distance, pairwise_distances, ent, dwell_times, y_pred, gate_probs
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def evaluate_nomadic_sequence_dynamics(model: NomadicMoE, X: torch.Tensor, Y: torch.Tensor, R: torch.Tensor, phase_tags: List[str], cfg: Config):
|
| 608 |
+
"""
|
| 609 |
+
Sequential evaluation with live hybrid delta.
|
| 610 |
+
Measures:
|
| 611 |
+
- phase-level entropy
|
| 612 |
+
- switch latency
|
| 613 |
+
- dwell times
|
| 614 |
+
- stepwise expert trajectory
|
| 615 |
+
"""
|
| 616 |
+
model.eval()
|
| 617 |
+
tracker = HybridDeltaTracker(
|
| 618 |
+
ema_decay=cfg.ema_decay,
|
| 619 |
+
err_baseline_momentum=cfg.err_baseline_momentum,
|
| 620 |
+
w_env=cfg.w_env,
|
| 621 |
+
w_err=cfg.w_err,
|
| 622 |
+
device=cfg.device,
|
| 623 |
+
)
|
| 624 |
+
tracker.reset()
|
| 625 |
+
|
| 626 |
+
all_y = []
|
| 627 |
+
all_gate_probs = []
|
| 628 |
+
batch_regimes = []
|
| 629 |
+
batch_phase_tags = []
|
| 630 |
+
batch_entropies = []
|
| 631 |
+
batch_top1 = []
|
| 632 |
+
|
| 633 |
+
with torch.no_grad():
|
| 634 |
+
for batch_idx, (xb, yb, rb) in enumerate(iterate_sequence_minibatches(X, Y, R, cfg.phase_batch_size)):
|
| 635 |
+
zero_delta = torch.zeros((xb.size(0), 1), device=cfg.device)
|
| 636 |
+
warm_y, _, _, _ = model(xb, zero_delta, cfg.temperature)
|
| 637 |
+
warm_mse = F.mse_loss(warm_y, yb)
|
| 638 |
+
|
| 639 |
+
delta_hybrid, _, _, _ = tracker.compute(xb, warm_mse)
|
| 640 |
+
y_hat, gate_probs, _, _ = model(xb, delta_hybrid, cfg.temperature)
|
| 641 |
+
|
| 642 |
+
all_y.append(y_hat)
|
| 643 |
+
all_gate_probs.append(gate_probs)
|
| 644 |
+
|
| 645 |
+
dominant_regime = ID_TO_REGIME[int(rb[0].item())]
|
| 646 |
+
batch_regimes.append(dominant_regime)
|
| 647 |
+
|
| 648 |
+
phase_tag = phase_tags[batch_idx * cfg.phase_batch_size]
|
| 649 |
+
batch_phase_tags.append(phase_tag)
|
| 650 |
+
|
| 651 |
+
ent = gate_entropy(gate_probs).mean().item()
|
| 652 |
+
batch_entropies.append(ent)
|
| 653 |
+
|
| 654 |
+
top1 = gate_probs.argmax(dim=-1)
|
| 655 |
+
binc = torch.bincount(top1, minlength=cfg.num_experts).float()
|
| 656 |
+
batch_top1.append(int(torch.argmax(binc).item()))
|
| 657 |
+
|
| 658 |
+
Y_hat = torch.cat(all_y, dim=0)
|
| 659 |
+
G = torch.cat(all_gate_probs, dim=0)
|
| 660 |
+
|
| 661 |
+
total_mse = F.mse_loss(Y_hat, Y).item()
|
| 662 |
+
usage = regimewise_usage(G, R, cfg.num_experts)
|
| 663 |
+
regime_to_expert = infer_regime_to_expert(usage)
|
| 664 |
+
|
| 665 |
+
latencies = compute_switch_latency(batch_regimes, np.array(batch_top1), regime_to_expert)
|
| 666 |
+
dwell_times = compute_dwell_times(np.array(batch_top1))
|
| 667 |
+
|
| 668 |
+
stable_entropy = []
|
| 669 |
+
transition_entropy = []
|
| 670 |
+
for tag, ent in zip(batch_phase_tags, batch_entropies):
|
| 671 |
+
if tag.startswith("stable_"):
|
| 672 |
+
stable_entropy.append(ent)
|
| 673 |
+
elif tag.startswith("transition_"):
|
| 674 |
+
transition_entropy.append(ent)
|
| 675 |
+
|
| 676 |
+
dynamics = {
|
| 677 |
+
"batch_regimes": batch_regimes,
|
| 678 |
+
"batch_phase_tags": batch_phase_tags,
|
| 679 |
+
"batch_entropies": batch_entropies,
|
| 680 |
+
"batch_top1": batch_top1,
|
| 681 |
+
"switch_latencies": latencies,
|
| 682 |
+
"dwell_times": dwell_times,
|
| 683 |
+
"mean_switch_latency": float(np.mean(latencies)) if len(latencies) > 0 else float("nan"),
|
| 684 |
+
"mean_dwell_time": float(np.mean(dwell_times)) if len(dwell_times) > 0 else float("nan"),
|
| 685 |
+
"stable_entropy_mean": float(np.mean(stable_entropy)) if len(stable_entropy) > 0 else float("nan"),
|
| 686 |
+
"transition_entropy_mean": float(np.mean(transition_entropy)) if len(transition_entropy) > 0 else float("nan"),
|
| 687 |
+
"regime_to_expert": regime_to_expert,
|
| 688 |
+
}
|
| 689 |
+
|
| 690 |
+
return total_mse, usage, dynamics, Y_hat, G
|
| 691 |
+
|
| 692 |
+
|
| 693 |
+
def train_fixed(cfg: Config, X_train, Y_train, R_train, X_test, Y_test, R_test):
|
| 694 |
+
model = MLPRegressor(cfg.input_dim, cfg.hidden_dim, cfg.output_dim).to(cfg.device)
|
| 695 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
|
| 696 |
+
|
| 697 |
+
train_losses = []
|
| 698 |
+
test_losses = []
|
| 699 |
+
|
| 700 |
+
for epoch in range(cfg.epochs):
|
| 701 |
+
model.train()
|
| 702 |
+
epoch_loss = 0.0
|
| 703 |
+
n_batches = 0
|
| 704 |
+
|
| 705 |
+
for xb, yb, _ in iterate_sequence_minibatches(X_train, Y_train, R_train, cfg.phase_batch_size):
|
| 706 |
+
optimizer.zero_grad()
|
| 707 |
+
y_hat = model(xb)
|
| 708 |
+
loss = F.mse_loss(y_hat, yb)
|
| 709 |
+
loss.backward()
|
| 710 |
+
optimizer.step()
|
| 711 |
+
|
| 712 |
+
epoch_loss += loss.item()
|
| 713 |
+
n_batches += 1
|
| 714 |
+
|
| 715 |
+
train_losses.append(epoch_loss / max(n_batches, 1))
|
| 716 |
+
test_mse, _ = evaluate_fixed(model, X_test, Y_test, R_test)
|
| 717 |
+
test_losses.append(test_mse)
|
| 718 |
+
|
| 719 |
+
if (epoch + 1) % 25 == 0 or epoch == 0:
|
| 720 |
+
print(f"[Fixed] Epoch {epoch+1:03d}/{cfg.epochs} | Train MSE: {train_losses[-1]:.4f} | Test MSE: {test_mse:.4f}")
|
| 721 |
+
|
| 722 |
+
return model, {"train_losses": train_losses, "test_losses": test_losses}
|
| 723 |
+
|
| 724 |
+
|
| 725 |
+
def train_nomadic(cfg: Config, X_train, Y_train, R_train, X_test, Y_test, R_test, phase_tags_test):
|
| 726 |
+
model = NomadicMoE(
|
| 727 |
+
input_dim=cfg.input_dim,
|
| 728 |
+
hidden_dim=cfg.hidden_dim,
|
| 729 |
+
output_dim=cfg.output_dim,
|
| 730 |
+
num_experts=cfg.num_experts,
|
| 731 |
+
gate_hidden_dim=cfg.gate_hidden_dim,
|
| 732 |
+
).to(cfg.device)
|
| 733 |
+
|
| 734 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=cfg.lr, weight_decay=cfg.weight_decay)
|
| 735 |
+
|
| 736 |
+
logs = {
|
| 737 |
+
"train_total_losses": [],
|
| 738 |
+
"train_mse_losses": [],
|
| 739 |
+
"train_dogma_losses": [],
|
| 740 |
+
"train_nomad_bonus": [],
|
| 741 |
+
"train_diversity_losses": [],
|
| 742 |
+
"train_sep_losses": [],
|
| 743 |
+
"train_cons_losses": [],
|
| 744 |
+
"train_mean_gate_distance": [],
|
| 745 |
+
"train_entropy": [],
|
| 746 |
+
"test_mse_static": [],
|
| 747 |
+
"test_mse_sequence": [],
|
| 748 |
+
"test_mean_gate_distance_static": [],
|
| 749 |
+
"delta_env": [],
|
| 750 |
+
"delta_err": [],
|
| 751 |
+
"delta_hybrid_raw": [],
|
| 752 |
+
"delta_hybrid": [],
|
| 753 |
+
"test_switch_latency": [],
|
| 754 |
+
"test_transition_entropy": [],
|
| 755 |
+
"test_stable_entropy": [],
|
| 756 |
+
}
|
| 757 |
+
|
| 758 |
+
for epoch in range(cfg.epochs):
|
| 759 |
+
model.train()
|
| 760 |
+
|
| 761 |
+
tracker = HybridDeltaTracker(
|
| 762 |
+
ema_decay=cfg.ema_decay,
|
| 763 |
+
err_baseline_momentum=cfg.err_baseline_momentum,
|
| 764 |
+
w_env=cfg.w_env,
|
| 765 |
+
w_err=cfg.w_err,
|
| 766 |
+
device=cfg.device,
|
| 767 |
+
)
|
| 768 |
+
tracker.reset()
|
| 769 |
+
|
| 770 |
+
epoch_total = 0.0
|
| 771 |
+
epoch_mse = 0.0
|
| 772 |
+
epoch_dogma = 0.0
|
| 773 |
+
epoch_nomad = 0.0
|
| 774 |
+
epoch_diversity = 0.0
|
| 775 |
+
epoch_sep = 0.0
|
| 776 |
+
epoch_cons = 0.0
|
| 777 |
+
epoch_entropy = 0.0
|
| 778 |
+
n_batches = 0
|
| 779 |
+
|
| 780 |
+
for xb, yb, rb in iterate_sequence_minibatches(X_train, Y_train, R_train, cfg.phase_batch_size):
|
| 781 |
+
optimizer.zero_grad()
|
| 782 |
+
|
| 783 |
+
with torch.no_grad():
|
| 784 |
+
zero_delta = torch.zeros((xb.size(0), 1), device=cfg.device)
|
| 785 |
+
warm_y, _, _, _ = model(xb, zero_delta, cfg.temperature)
|
| 786 |
+
warm_mse = F.mse_loss(warm_y, yb)
|
| 787 |
+
|
| 788 |
+
delta_hybrid, de, derr, dh = tracker.compute(xb, warm_mse)
|
| 789 |
+
y_hat, gate_probs, _, expert_outputs = model(xb, delta_hybrid, cfg.temperature)
|
| 790 |
+
|
| 791 |
+
mse_loss = F.mse_loss(y_hat, yb)
|
| 792 |
+
dogma_pen = compute_dogma_penalty(gate_probs)
|
| 793 |
+
nomad_bonus = compute_nomad_bonus(gate_probs)
|
| 794 |
+
diversity_loss = compute_diversity_loss(expert_outputs)
|
| 795 |
+
|
| 796 |
+
_, sep_loss, cons_loss, _, _ = compute_regime_gate_stats(
|
| 797 |
+
gate_probs=gate_probs,
|
| 798 |
+
regime_ids=rb,
|
| 799 |
+
num_regimes=3,
|
| 800 |
+
)
|
| 801 |
+
|
| 802 |
+
entropy_val = gate_entropy(gate_probs).mean()
|
| 803 |
+
|
| 804 |
+
total_loss = (
|
| 805 |
+
mse_loss
|
| 806 |
+
+ cfg.alpha_dogma * dogma_pen
|
| 807 |
+
- cfg.beta_nomad * nomad_bonus
|
| 808 |
+
+ cfg.gamma_diversity * diversity_loss
|
| 809 |
+
+ cfg.lambda_sep * sep_loss
|
| 810 |
+
+ cfg.lambda_cons * cons_loss
|
| 811 |
+
)
|
| 812 |
+
|
| 813 |
+
total_loss.backward()
|
| 814 |
+
optimizer.step()
|
| 815 |
+
|
| 816 |
+
epoch_total += total_loss.item()
|
| 817 |
+
epoch_mse += mse_loss.item()
|
| 818 |
+
epoch_dogma += dogma_pen.item()
|
| 819 |
+
epoch_nomad += nomad_bonus.item()
|
| 820 |
+
epoch_diversity += diversity_loss.item()
|
| 821 |
+
epoch_sep += sep_loss.item()
|
| 822 |
+
epoch_cons += cons_loss.item()
|
| 823 |
+
epoch_entropy += entropy_val.item()
|
| 824 |
+
n_batches += 1
|
| 825 |
+
|
| 826 |
+
logs["delta_env"].append(de)
|
| 827 |
+
logs["delta_err"].append(derr)
|
| 828 |
+
logs["delta_hybrid"].append(dh)
|
| 829 |
+
logs["delta_hybrid_raw"].append(tracker.delta_hybrid_raw_history[-1])
|
| 830 |
+
|
| 831 |
+
logs["train_total_losses"].append(epoch_total / max(n_batches, 1))
|
| 832 |
+
logs["train_mse_losses"].append(epoch_mse / max(n_batches, 1))
|
| 833 |
+
logs["train_dogma_losses"].append(epoch_dogma / max(n_batches, 1))
|
| 834 |
+
logs["train_nomad_bonus"].append(epoch_nomad / max(n_batches, 1))
|
| 835 |
+
logs["train_diversity_losses"].append(epoch_diversity / max(n_batches, 1))
|
| 836 |
+
logs["train_sep_losses"].append(epoch_sep / max(n_batches, 1))
|
| 837 |
+
logs["train_cons_losses"].append(epoch_cons / max(n_batches, 1))
|
| 838 |
+
logs["train_entropy"].append(epoch_entropy / max(n_batches, 1))
|
| 839 |
+
|
| 840 |
+
_, _, _, train_gate_dist_full, _, _, _, _, _ = evaluate_nomadic_static_full(
|
| 841 |
+
model, X_train, Y_train, R_train, cfg
|
| 842 |
+
)
|
| 843 |
+
logs["train_mean_gate_distance"].append(train_gate_dist_full)
|
| 844 |
+
|
| 845 |
+
test_mse_static, _, _, test_gate_dist_static, _, _, _, _, _ = evaluate_nomadic_static_full(
|
| 846 |
+
model, X_test, Y_test, R_test, cfg
|
| 847 |
+
)
|
| 848 |
+
logs["test_mse_static"].append(test_mse_static)
|
| 849 |
+
logs["test_mean_gate_distance_static"].append(test_gate_dist_static)
|
| 850 |
+
|
| 851 |
+
test_mse_sequence, _, dynamics_eval, _, _ = evaluate_nomadic_sequence_dynamics(
|
| 852 |
+
model, X_test, Y_test, R_test, phase_tags_test, cfg
|
| 853 |
+
)
|
| 854 |
+
logs["test_mse_sequence"].append(test_mse_sequence)
|
| 855 |
+
logs["test_switch_latency"].append(dynamics_eval["mean_switch_latency"])
|
| 856 |
+
logs["test_transition_entropy"].append(dynamics_eval["transition_entropy_mean"])
|
| 857 |
+
logs["test_stable_entropy"].append(dynamics_eval["stable_entropy_mean"])
|
| 858 |
+
|
| 859 |
+
if (epoch + 1) % 25 == 0 or epoch == 0:
|
| 860 |
+
print(
|
| 861 |
+
f"[Nomadic] Epoch {epoch+1:03d}/{cfg.epochs} | "
|
| 862 |
+
f"Train Total: {logs['train_total_losses'][-1]:.4f} | "
|
| 863 |
+
f"Train MSE: {logs['train_mse_losses'][-1]:.4f} | "
|
| 864 |
+
f"Train GateDist(full): {logs['train_mean_gate_distance'][-1]:.4f} | "
|
| 865 |
+
f"Train Entropy: {logs['train_entropy'][-1]:.4f} | "
|
| 866 |
+
f"Test Static MSE: {test_mse_static:.4f} | "
|
| 867 |
+
f"Test Seq MSE: {test_mse_sequence:.4f} | "
|
| 868 |
+
f"Test Static GateDist: {test_gate_dist_static:.4f} | "
|
| 869 |
+
f"Switch Latency: {dynamics_eval['mean_switch_latency']:.4f}"
|
| 870 |
+
)
|
| 871 |
+
|
| 872 |
+
return model, logs
|
| 873 |
+
|
| 874 |
+
|
| 875 |
+
# ============================================================
|
| 876 |
+
# Plotting
|
| 877 |
+
# ============================================================
|
| 878 |
+
|
| 879 |
+
def ensure_dir(path: str):
|
| 880 |
+
os.makedirs(path, exist_ok=True)
|
| 881 |
+
|
| 882 |
+
|
| 883 |
+
def plot_dataset(X: torch.Tensor, R: torch.Tensor, save_path: str):
|
| 884 |
+
x = X.detach().cpu().numpy()
|
| 885 |
+
r = R.detach().cpu().numpy()
|
| 886 |
+
|
| 887 |
+
plt.figure(figsize=(7, 6))
|
| 888 |
+
for rid, name in ID_TO_REGIME.items():
|
| 889 |
+
mask = r == rid
|
| 890 |
+
plt.scatter(x[mask, 0], x[mask, 1], s=10, alpha=0.45, label=f"Regime {name}")
|
| 891 |
+
|
| 892 |
+
plt.title("Phase Dataset in Input Space")
|
| 893 |
+
plt.xlabel("x1")
|
| 894 |
+
plt.ylabel("x2")
|
| 895 |
+
plt.legend()
|
| 896 |
+
plt.tight_layout()
|
| 897 |
+
plt.savefig(save_path)
|
| 898 |
+
plt.close()
|
| 899 |
+
|
| 900 |
+
|
| 901 |
+
def plot_training_curves(fixed_logs: dict, nomadic_logs: dict, save_path: str):
|
| 902 |
+
epochs = np.arange(1, len(fixed_logs["train_losses"]) + 1)
|
| 903 |
+
|
| 904 |
+
plt.figure(figsize=(8, 5))
|
| 905 |
+
plt.plot(epochs, fixed_logs["test_losses"], label="Fixed Test MSE")
|
| 906 |
+
plt.plot(epochs, nomadic_logs["test_mse_static"], label="Nomadic Static Test MSE")
|
| 907 |
+
plt.plot(epochs, nomadic_logs["test_mse_sequence"], label="Nomadic Sequence Test MSE")
|
| 908 |
+
plt.xlabel("Epoch")
|
| 909 |
+
plt.ylabel("MSE")
|
| 910 |
+
plt.title("Fixed vs Nomadic Test MSE (Static vs Sequence)")
|
| 911 |
+
plt.legend()
|
| 912 |
+
plt.tight_layout()
|
| 913 |
+
plt.savefig(save_path)
|
| 914 |
+
plt.close()
|
| 915 |
+
|
| 916 |
+
|
| 917 |
+
def plot_nomadic_losses(nomadic_logs: dict, save_path: str):
|
| 918 |
+
epochs = np.arange(1, len(nomadic_logs["train_total_losses"]) + 1)
|
| 919 |
+
|
| 920 |
+
plt.figure(figsize=(8, 5))
|
| 921 |
+
plt.plot(epochs, nomadic_logs["train_mse_losses"], label="MSE")
|
| 922 |
+
plt.plot(epochs, nomadic_logs["train_dogma_losses"], label="Dogma")
|
| 923 |
+
plt.plot(epochs, nomadic_logs["train_nomad_bonus"], label="Nomad Bonus")
|
| 924 |
+
plt.plot(epochs, nomadic_logs["train_diversity_losses"], label="Diversity")
|
| 925 |
+
plt.plot(epochs, nomadic_logs["train_sep_losses"], label="Regime Sep")
|
| 926 |
+
plt.plot(epochs, nomadic_logs["train_cons_losses"], label="Regime Cons")
|
| 927 |
+
plt.xlabel("Epoch")
|
| 928 |
+
plt.ylabel("Value")
|
| 929 |
+
plt.title("Nomadic Loss Components")
|
| 930 |
+
plt.legend()
|
| 931 |
+
plt.tight_layout()
|
| 932 |
+
plt.savefig(save_path)
|
| 933 |
+
plt.close()
|
| 934 |
+
|
| 935 |
+
|
| 936 |
+
def plot_delta_trace(nomadic_logs: dict, save_path: str):
|
| 937 |
+
steps = np.arange(1, len(nomadic_logs["delta_env"]) + 1)
|
| 938 |
+
|
| 939 |
+
plt.figure(figsize=(8, 5))
|
| 940 |
+
plt.plot(steps, nomadic_logs["delta_env"], label="delta_env")
|
| 941 |
+
plt.plot(steps, nomadic_logs["delta_err"], label="delta_err")
|
| 942 |
+
plt.plot(steps, nomadic_logs["delta_hybrid_raw"], label="delta_hybrid_raw")
|
| 943 |
+
plt.plot(steps, nomadic_logs["delta_hybrid"], label="delta_hybrid_tanh")
|
| 944 |
+
plt.xlabel("Batch Step")
|
| 945 |
+
plt.ylabel("Magnitude")
|
| 946 |
+
plt.title("Hybrid Delta Trace")
|
| 947 |
+
plt.legend()
|
| 948 |
+
plt.tight_layout()
|
| 949 |
+
plt.savefig(save_path)
|
| 950 |
+
plt.close()
|
| 951 |
+
|
| 952 |
+
|
| 953 |
+
def plot_usage_bars(usage: Dict[str, np.ndarray], save_path: str, title: str):
|
| 954 |
+
regimes = ["A", "B", "C"]
|
| 955 |
+
num_experts = len(next(iter(usage.values())))
|
| 956 |
+
x = np.arange(len(regimes))
|
| 957 |
+
width = 0.22
|
| 958 |
+
|
| 959 |
+
plt.figure(figsize=(8, 5))
|
| 960 |
+
for e in range(num_experts):
|
| 961 |
+
vals = [usage[r][e] for r in regimes]
|
| 962 |
+
plt.bar(x + e * width - width, vals, width=width, label=f"Expert {e}")
|
| 963 |
+
|
| 964 |
+
plt.xticks(x, [f"Regime {r}" for r in regimes])
|
| 965 |
+
plt.ylabel("Top-1 Selection Ratio")
|
| 966 |
+
plt.title(title)
|
| 967 |
+
plt.legend()
|
| 968 |
+
plt.tight_layout()
|
| 969 |
+
plt.savefig(save_path)
|
| 970 |
+
plt.close()
|
| 971 |
+
|
| 972 |
+
|
| 973 |
+
def plot_gate_heatmap(usage: Dict[str, np.ndarray], save_path: str):
|
| 974 |
+
regimes = ["A", "B", "C"]
|
| 975 |
+
mat = np.stack([usage[r] for r in regimes], axis=0)
|
| 976 |
+
|
| 977 |
+
plt.figure(figsize=(6, 4))
|
| 978 |
+
plt.imshow(mat, aspect="auto")
|
| 979 |
+
plt.colorbar(label="Top-1 Selection Ratio")
|
| 980 |
+
plt.yticks(range(len(regimes)), [f"Regime {r}" for r in regimes])
|
| 981 |
+
plt.xticks(range(mat.shape[1]), [f"Expert {i}" for i in range(mat.shape[1])])
|
| 982 |
+
plt.title("Regime-Expert Usage Heatmap")
|
| 983 |
+
plt.tight_layout()
|
| 984 |
+
plt.savefig(save_path)
|
| 985 |
+
plt.close()
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def plot_gate_distance_curve(nomadic_logs: dict, save_path: str):
|
| 989 |
+
epochs = np.arange(1, len(nomadic_logs["train_mean_gate_distance"]) + 1)
|
| 990 |
+
|
| 991 |
+
plt.figure(figsize=(8, 5))
|
| 992 |
+
plt.plot(epochs, nomadic_logs["train_mean_gate_distance"], label="Train Mean Gate Distance (full)")
|
| 993 |
+
plt.plot(epochs, nomadic_logs["test_mean_gate_distance_static"], label="Test Mean Gate Distance (static)")
|
| 994 |
+
plt.xlabel("Epoch")
|
| 995 |
+
plt.ylabel("Distance")
|
| 996 |
+
plt.title("Regime Mean Gate Distance")
|
| 997 |
+
plt.legend()
|
| 998 |
+
plt.tight_layout()
|
| 999 |
+
plt.savefig(save_path)
|
| 1000 |
+
plt.close()
|
| 1001 |
+
|
| 1002 |
+
|
| 1003 |
+
def plot_phase_entropy(dynamics: dict, save_path: str):
|
| 1004 |
+
ent = np.array(dynamics["batch_entropies"])
|
| 1005 |
+
x = np.arange(len(ent))
|
| 1006 |
+
|
| 1007 |
+
plt.figure(figsize=(10, 4))
|
| 1008 |
+
plt.plot(x, ent, label="Batch Gate Entropy")
|
| 1009 |
+
plt.xlabel("Batch Index")
|
| 1010 |
+
plt.ylabel("Entropy")
|
| 1011 |
+
plt.title("Gate Entropy across Phase Sequence")
|
| 1012 |
+
plt.legend()
|
| 1013 |
+
plt.tight_layout()
|
| 1014 |
+
plt.savefig(save_path)
|
| 1015 |
+
plt.close()
|
| 1016 |
+
|
| 1017 |
+
|
| 1018 |
+
def plot_expert_trajectory(dynamics: dict, save_path: str):
|
| 1019 |
+
top1 = np.array(dynamics["batch_top1"])
|
| 1020 |
+
x = np.arange(len(top1))
|
| 1021 |
+
|
| 1022 |
+
plt.figure(figsize=(10, 4))
|
| 1023 |
+
plt.plot(x, top1)
|
| 1024 |
+
plt.xlabel("Batch Index")
|
| 1025 |
+
plt.ylabel("Dominant Expert")
|
| 1026 |
+
plt.title("Dominant Expert Trajectory across Phase Sequence")
|
| 1027 |
+
plt.tight_layout()
|
| 1028 |
+
plt.savefig(save_path)
|
| 1029 |
+
plt.close()
|
| 1030 |
+
|
| 1031 |
+
|
| 1032 |
+
def plot_dwell_histogram(dwell_times: List[int], save_path: str):
|
| 1033 |
+
plt.figure(figsize=(7, 5))
|
| 1034 |
+
bins = min(20, max(5, len(set(dwell_times)) if len(dwell_times) > 0 else 5))
|
| 1035 |
+
plt.hist(dwell_times, bins=bins)
|
| 1036 |
+
plt.xlabel("Dwell Time")
|
| 1037 |
+
plt.ylabel("Count")
|
| 1038 |
+
plt.title("Dwell Time Distribution")
|
| 1039 |
+
plt.tight_layout()
|
| 1040 |
+
plt.savefig(save_path)
|
| 1041 |
+
plt.close()
|
| 1042 |
+
|
| 1043 |
+
|
| 1044 |
+
def plot_switch_latency_histogram(latencies: List[int], save_path: str):
|
| 1045 |
+
plt.figure(figsize=(7, 5))
|
| 1046 |
+
if len(latencies) > 0:
|
| 1047 |
+
bins = min(15, max(3, len(set(latencies))))
|
| 1048 |
+
plt.hist(latencies, bins=bins)
|
| 1049 |
+
plt.xlabel("Switch Latency")
|
| 1050 |
+
plt.ylabel("Count")
|
| 1051 |
+
plt.title("Switch Latency Distribution")
|
| 1052 |
+
plt.tight_layout()
|
| 1053 |
+
plt.savefig(save_path)
|
| 1054 |
+
plt.close()
|
| 1055 |
+
|
| 1056 |
+
|
| 1057 |
+
def plot_entropy_comparison(nomadic_logs: dict, save_path: str):
|
| 1058 |
+
epochs = np.arange(1, len(nomadic_logs["test_transition_entropy"]) + 1)
|
| 1059 |
+
|
| 1060 |
+
plt.figure(figsize=(8, 5))
|
| 1061 |
+
plt.plot(epochs, nomadic_logs["test_stable_entropy"], label="Stable Entropy")
|
| 1062 |
+
plt.plot(epochs, nomadic_logs["test_transition_entropy"], label="Transition Entropy")
|
| 1063 |
+
plt.xlabel("Epoch")
|
| 1064 |
+
plt.ylabel("Entropy")
|
| 1065 |
+
plt.title("Stable vs Transition Gate Entropy")
|
| 1066 |
+
plt.legend()
|
| 1067 |
+
plt.tight_layout()
|
| 1068 |
+
plt.savefig(save_path)
|
| 1069 |
+
plt.close()
|
| 1070 |
+
|
| 1071 |
+
|
| 1072 |
+
def plot_switch_latency_curve(nomadic_logs: dict, save_path: str):
|
| 1073 |
+
epochs = np.arange(1, len(nomadic_logs["test_switch_latency"]) + 1)
|
| 1074 |
+
|
| 1075 |
+
plt.figure(figsize=(8, 5))
|
| 1076 |
+
plt.plot(epochs, nomadic_logs["test_switch_latency"], label="Mean Switch Latency")
|
| 1077 |
+
plt.xlabel("Epoch")
|
| 1078 |
+
plt.ylabel("Latency")
|
| 1079 |
+
plt.title("Epoch-wise Mean Switch Latency")
|
| 1080 |
+
plt.legend()
|
| 1081 |
+
plt.tight_layout()
|
| 1082 |
+
plt.savefig(save_path)
|
| 1083 |
+
plt.close()
|
| 1084 |
+
|
| 1085 |
+
|
| 1086 |
+
def plot_regime_expert_alignment(dynamics: dict, save_path: str):
|
| 1087 |
+
regime_map = {"A": 0, "B": 1, "C": 2}
|
| 1088 |
+
regime_vals = np.array([regime_map[r] for r in dynamics["batch_regimes"]])
|
| 1089 |
+
expert_vals = np.array(dynamics["batch_top1"])
|
| 1090 |
+
x = np.arange(len(regime_vals))
|
| 1091 |
+
|
| 1092 |
+
plt.figure(figsize=(10, 5))
|
| 1093 |
+
plt.plot(x, regime_vals, label="Dominant Regime")
|
| 1094 |
+
plt.plot(x, expert_vals, label="Dominant Expert")
|
| 1095 |
+
plt.xlabel("Batch Index")
|
| 1096 |
+
plt.ylabel("Index")
|
| 1097 |
+
plt.title("Regime vs Expert Alignment across Phase Sequence")
|
| 1098 |
+
plt.legend()
|
| 1099 |
+
plt.tight_layout()
|
| 1100 |
+
plt.savefig(save_path)
|
| 1101 |
+
plt.close()
|
| 1102 |
+
|
| 1103 |
+
|
| 1104 |
+
# ============================================================
|
| 1105 |
+
# Reporting
|
| 1106 |
+
# ============================================================
|
| 1107 |
+
|
| 1108 |
+
def print_report(
|
| 1109 |
+
fixed_total_mse: float,
|
| 1110 |
+
fixed_per_regime: Dict[str, float],
|
| 1111 |
+
nomadic_static_total_mse: float,
|
| 1112 |
+
nomadic_per_regime: Dict[str, float],
|
| 1113 |
+
nomadic_usage: Dict[str, np.ndarray],
|
| 1114 |
+
nomadic_mean_gate_distance: float,
|
| 1115 |
+
nomadic_pairwise_gate_distances: Dict[str, float],
|
| 1116 |
+
seq_total_mse: float,
|
| 1117 |
+
dynamics: dict,
|
| 1118 |
+
):
|
| 1119 |
+
print("\n" + "=" * 72)
|
| 1120 |
+
print("FINAL REPORT")
|
| 1121 |
+
print("=" * 72)
|
| 1122 |
+
|
| 1123 |
+
print("\n[Fixed Model]")
|
| 1124 |
+
print(f"Total Test MSE: {fixed_total_mse:.6f}")
|
| 1125 |
+
for k, v in fixed_per_regime.items():
|
| 1126 |
+
print(f" Regime {k} MSE: {v:.6f}")
|
| 1127 |
+
|
| 1128 |
+
print("\n[Nomadic Model | Static Eval]")
|
| 1129 |
+
print(f"Static Total Test MSE: {nomadic_static_total_mse:.6f}")
|
| 1130 |
+
for k, v in nomadic_per_regime.items():
|
| 1131 |
+
print(f" Regime {k} MSE: {v:.6f}")
|
| 1132 |
+
|
| 1133 |
+
print("\n[Nomadic Model | Sequence Eval]")
|
| 1134 |
+
print(f"Sequence Total Test MSE: {seq_total_mse:.6f}")
|
| 1135 |
+
|
| 1136 |
+
print("\n[Nomadic Regime-wise Expert Usage | Top-1 Ratio]")
|
| 1137 |
+
for regime in ["A", "B", "C"]:
|
| 1138 |
+
arr = nomadic_usage[regime]
|
| 1139 |
+
arr_str = ", ".join([f"E{i}: {p:.3f}" for i, p in enumerate(arr)])
|
| 1140 |
+
print(f" Regime {regime} -> {arr_str}")
|
| 1141 |
+
|
| 1142 |
+
print("\n[Nomadic Mean Gate Distance | Static Full]")
|
| 1143 |
+
print(f"Mean pairwise gate-centroid distance: {nomadic_mean_gate_distance:.6f}")
|
| 1144 |
+
if len(nomadic_pairwise_gate_distances) > 0:
|
| 1145 |
+
print("[Pairwise Gate Distances]")
|
| 1146 |
+
for k, v in nomadic_pairwise_gate_distances.items():
|
| 1147 |
+
print(f" {k}: {v:.6f}")
|
| 1148 |
+
|
| 1149 |
+
print("\n[Transition Dynamics]")
|
| 1150 |
+
print(f"Regime -> Expert mapping: {dynamics['regime_to_expert']}")
|
| 1151 |
+
print(f"Mean switch latency: {dynamics['mean_switch_latency']:.4f}")
|
| 1152 |
+
print(f"Mean dwell time: {dynamics['mean_dwell_time']:.4f}")
|
| 1153 |
+
print(f"Stable-phase mean entropy: {dynamics['stable_entropy_mean']:.4f}")
|
| 1154 |
+
print(f"Transition-phase mean entropy: {dynamics['transition_entropy_mean']:.4f}")
|
| 1155 |
+
|
| 1156 |
+
print("\nInterpretation hint:")
|
| 1157 |
+
print("- Sequence Test MSE is the main performance metric in phase-transition settings.")
|
| 1158 |
+
print("- Static Test MSE is only a reference check, not the main success criterion.")
|
| 1159 |
+
print("- Transition entropy > stable entropy suggests gate uncertainty rises during phase shifts.")
|
| 1160 |
+
print("- Shorter switch latency suggests faster nomadic response.")
|
| 1161 |
+
print("- Moderate dwell time suggests neither rigid fixation nor chaotic wandering.")
|
| 1162 |
+
print("=" * 72 + "\n")
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
# ============================================================
|
| 1166 |
+
# Main
|
| 1167 |
+
# ============================================================
|
| 1168 |
+
|
| 1169 |
+
def main():
|
| 1170 |
+
parser = argparse.ArgumentParser()
|
| 1171 |
+
parser.add_argument("--config", type=str, default="config.yaml")
|
| 1172 |
+
parser.add_argument("--save_dir", type=str, default=None)
|
| 1173 |
+
parser.add_argument("--device", type=str, default=None, choices=["cpu", "cuda", "auto"])
|
| 1174 |
+
parser.add_argument("--seed", type=int, default=None)
|
| 1175 |
+
args = parser.parse_args()
|
| 1176 |
+
|
| 1177 |
+
yaml_cfg = load_yaml_config(args.config)
|
| 1178 |
+
cfg = build_config_from_yaml(yaml_cfg)
|
| 1179 |
+
|
| 1180 |
+
if args.save_dir is not None:
|
| 1181 |
+
cfg.save_dir = args.save_dir
|
| 1182 |
+
|
| 1183 |
+
if args.seed is not None:
|
| 1184 |
+
cfg.seed = args.seed
|
| 1185 |
+
|
| 1186 |
+
if args.device is not None:
|
| 1187 |
+
cfg.device = "cuda" if (args.device == "auto" and torch.cuda.is_available()) else args.device
|
| 1188 |
+
|
| 1189 |
+
ensure_dir(cfg.save_dir)
|
| 1190 |
+
set_seed(cfg.seed)
|
| 1191 |
+
|
| 1192 |
+
print(f"Using device: {cfg.device}")
|
| 1193 |
+
print(f"Saving outputs to: {cfg.save_dir}")
|
| 1194 |
+
print(f"Loaded config from: {args.config}")
|
| 1195 |
+
|
| 1196 |
+
X_train, Y_train, R_train, phase_tags_train = generate_phase_sequence(cfg, cfg.phase_train_cycles, cfg.device)
|
| 1197 |
+
X_test, Y_test, R_test, phase_tags_test = generate_phase_sequence(cfg, cfg.phase_test_cycles, cfg.device)
|
| 1198 |
+
|
| 1199 |
+
plot_dataset(X_train, R_train, os.path.join(cfg.save_dir, "phase_dataset_input_space.png"))
|
| 1200 |
+
|
| 1201 |
+
fixed_model, fixed_logs = train_fixed(cfg, X_train, Y_train, R_train, X_test, Y_test, R_test)
|
| 1202 |
+
nomadic_model, nomadic_logs = train_nomadic(
|
| 1203 |
+
cfg, X_train, Y_train, R_train, X_test, Y_test, R_test, phase_tags_test
|
| 1204 |
+
)
|
| 1205 |
+
|
| 1206 |
+
fixed_total_mse, fixed_per_regime = evaluate_fixed(fixed_model, X_test, Y_test, R_test)
|
| 1207 |
+
(
|
| 1208 |
+
nomadic_static_total_mse,
|
| 1209 |
+
nomadic_per_regime,
|
| 1210 |
+
nomadic_usage,
|
| 1211 |
+
nomadic_mean_gate_distance,
|
| 1212 |
+
nomadic_pairwise_gate_distances,
|
| 1213 |
+
_,
|
| 1214 |
+
_,
|
| 1215 |
+
_,
|
| 1216 |
+
_,
|
| 1217 |
+
) = evaluate_nomadic_static_full(
|
| 1218 |
+
nomadic_model, X_test, Y_test, R_test, cfg
|
| 1219 |
+
)
|
| 1220 |
+
|
| 1221 |
+
seq_total_mse, seq_usage, dynamics, _, _ = evaluate_nomadic_sequence_dynamics(
|
| 1222 |
+
nomadic_model, X_test, Y_test, R_test, phase_tags_test, cfg
|
| 1223 |
+
)
|
| 1224 |
+
|
| 1225 |
+
plot_training_curves(
|
| 1226 |
+
fixed_logs,
|
| 1227 |
+
nomadic_logs,
|
| 1228 |
+
os.path.join(cfg.save_dir, "fixed_vs_nomadic_test_mse.png"),
|
| 1229 |
+
)
|
| 1230 |
+
plot_nomadic_losses(
|
| 1231 |
+
nomadic_logs,
|
| 1232 |
+
os.path.join(cfg.save_dir, "nomadic_loss_components.png"),
|
| 1233 |
+
)
|
| 1234 |
+
plot_delta_trace(
|
| 1235 |
+
nomadic_logs,
|
| 1236 |
+
os.path.join(cfg.save_dir, "hybrid_delta_trace.png"),
|
| 1237 |
+
)
|
| 1238 |
+
plot_usage_bars(
|
| 1239 |
+
nomadic_usage,
|
| 1240 |
+
os.path.join(cfg.save_dir, "regime_expert_usage_bars.png"),
|
| 1241 |
+
"Regime-wise Expert Usage (Top-1)",
|
| 1242 |
+
)
|
| 1243 |
+
plot_gate_heatmap(
|
| 1244 |
+
nomadic_usage,
|
| 1245 |
+
os.path.join(cfg.save_dir, "regime_expert_usage_heatmap.png"),
|
| 1246 |
+
)
|
| 1247 |
+
plot_gate_distance_curve(
|
| 1248 |
+
nomadic_logs,
|
| 1249 |
+
os.path.join(cfg.save_dir, "regime_mean_gate_distance.png"),
|
| 1250 |
+
)
|
| 1251 |
+
plot_phase_entropy(
|
| 1252 |
+
dynamics,
|
| 1253 |
+
os.path.join(cfg.save_dir, "phase_gate_entropy.png"),
|
| 1254 |
+
)
|
| 1255 |
+
plot_expert_trajectory(
|
| 1256 |
+
dynamics,
|
| 1257 |
+
os.path.join(cfg.save_dir, "expert_trajectory.png"),
|
| 1258 |
+
)
|
| 1259 |
+
plot_dwell_histogram(
|
| 1260 |
+
dynamics["dwell_times"],
|
| 1261 |
+
os.path.join(cfg.save_dir, "dwell_time_histogram.png"),
|
| 1262 |
+
)
|
| 1263 |
+
plot_switch_latency_histogram(
|
| 1264 |
+
dynamics["switch_latencies"],
|
| 1265 |
+
os.path.join(cfg.save_dir, "switch_latency_histogram.png"),
|
| 1266 |
+
)
|
| 1267 |
+
plot_entropy_comparison(
|
| 1268 |
+
nomadic_logs,
|
| 1269 |
+
os.path.join(cfg.save_dir, "stable_vs_transition_entropy.png"),
|
| 1270 |
+
)
|
| 1271 |
+
plot_switch_latency_curve(
|
| 1272 |
+
nomadic_logs,
|
| 1273 |
+
os.path.join(cfg.save_dir, "switch_latency_curve.png"),
|
| 1274 |
+
)
|
| 1275 |
+
plot_regime_expert_alignment(
|
| 1276 |
+
dynamics,
|
| 1277 |
+
os.path.join(cfg.save_dir, "regime_expert_alignment.png"),
|
| 1278 |
+
)
|
| 1279 |
+
|
| 1280 |
+
print_report(
|
| 1281 |
+
fixed_total_mse,
|
| 1282 |
+
fixed_per_regime,
|
| 1283 |
+
nomadic_static_total_mse,
|
| 1284 |
+
nomadic_per_regime,
|
| 1285 |
+
nomadic_usage,
|
| 1286 |
+
nomadic_mean_gate_distance,
|
| 1287 |
+
nomadic_pairwise_gate_distances,
|
| 1288 |
+
seq_total_mse,
|
| 1289 |
+
dynamics,
|
| 1290 |
+
)
|
| 1291 |
+
|
| 1292 |
+
print("Saved files:")
|
| 1293 |
+
for fname in [
|
| 1294 |
+
"phase_dataset_input_space.png",
|
| 1295 |
+
"fixed_vs_nomadic_test_mse.png",
|
| 1296 |
+
"nomadic_loss_components.png",
|
| 1297 |
+
"hybrid_delta_trace.png",
|
| 1298 |
+
"regime_expert_usage_bars.png",
|
| 1299 |
+
"regime_expert_usage_heatmap.png",
|
| 1300 |
+
"regime_mean_gate_distance.png",
|
| 1301 |
+
"phase_gate_entropy.png",
|
| 1302 |
+
"expert_trajectory.png",
|
| 1303 |
+
"dwell_time_histogram.png",
|
| 1304 |
+
"switch_latency_histogram.png",
|
| 1305 |
+
"stable_vs_transition_entropy.png",
|
| 1306 |
+
"switch_latency_curve.png",
|
| 1307 |
+
"regime_expert_alignment.png",
|
| 1308 |
+
]:
|
| 1309 |
+
print(" -", os.path.join(cfg.save_dir, fname))
|
| 1310 |
+
|
| 1311 |
+
|
| 1312 |
+
if __name__ == "__main__":
|
| 1313 |
+
main()
|