nova-llm 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. nova_llm-0.1.0/PKG-INFO +190 -0
  2. nova_llm-0.1.0/README.md +172 -0
  3. nova_llm-0.1.0/nova/__init__.py +15 -0
  4. nova_llm-0.1.0/nova/architecture/__init__.py +13 -0
  5. nova_llm-0.1.0/nova/architecture/heads.py +80 -0
  6. nova_llm-0.1.0/nova/architecture/model.py +174 -0
  7. nova_llm-0.1.0/nova/architecture/resonance.py +83 -0
  8. nova_llm-0.1.0/nova/architecture/usf.py +92 -0
  9. nova_llm-0.1.0/nova/compression/__init__.py +18 -0
  10. nova_llm-0.1.0/nova/compression/mobile_export.py +69 -0
  11. nova_llm-0.1.0/nova/compression/quantization.py +66 -0
  12. nova_llm-0.1.0/nova/compute/__init__.py +4 -0
  13. nova_llm-0.1.0/nova/compute/ara.py +37 -0
  14. nova_llm-0.1.0/nova/core/__init__.py +19 -0
  15. nova_llm-0.1.0/nova/core/state.py +42 -0
  16. nova_llm-0.1.0/nova/core/tensor_ops.py +49 -0
  17. nova_llm-0.1.0/nova/core/validation.py +30 -0
  18. nova_llm-0.1.0/nova/encoders/__init__.py +5 -0
  19. nova_llm-0.1.0/nova/encoders/mlp.py +29 -0
  20. nova_llm-0.1.0/nova/encoders/multimodal.py +132 -0
  21. nova_llm-0.1.0/nova/learning/__init__.py +11 -0
  22. nova_llm-0.1.0/nova/learning/ecal.py +100 -0
  23. nova_llm-0.1.0/nova/learning/objectives.py +115 -0
  24. nova_llm-0.1.0/nova/learning/regularizer.py +47 -0
  25. nova_llm-0.1.0/nova/memory/__init__.py +5 -0
  26. nova_llm-0.1.0/nova/memory/drm.py +212 -0
  27. nova_llm-0.1.0/nova/memory/storage.py +27 -0
  28. nova_llm-0.1.0/nova/runtime/__init__.py +5 -0
  29. nova_llm-0.1.0/nova/runtime/executor.py +145 -0
  30. nova_llm-0.1.0/nova/runtime/trace.py +59 -0
  31. nova_llm-0.1.0/nova/sdk/__init__.py +7 -0
  32. nova_llm-0.1.0/nova/sdk/dataset.py +83 -0
  33. nova_llm-0.1.0/nova/sdk/engine.py +53 -0
  34. nova_llm-0.1.0/nova/sdk/model.py +238 -0
  35. nova_llm-0.1.0/nova/sdk/multimodal_dataset.py +57 -0
  36. nova_llm-0.1.0/nova/sdk/serialization.py +99 -0
  37. nova_llm-0.1.0/nova/serving/__init__.py +4 -0
  38. nova_llm-0.1.0/nova/serving/app.py +112 -0
  39. nova_llm-0.1.0/nova/serving/schemas.py +36 -0
  40. nova_llm-0.1.0/nova/workflow/__init__.py +6 -0
  41. nova_llm-0.1.0/nova/workflow/graph.py +80 -0
  42. nova_llm-0.1.0/nova/workflow/node.py +18 -0
  43. nova_llm-0.1.0/nova/workflow/pipeline.py +21 -0
  44. nova_llm-0.1.0/nova_llm.egg-info/PKG-INFO +190 -0
  45. nova_llm-0.1.0/nova_llm.egg-info/SOURCES.txt +56 -0
  46. nova_llm-0.1.0/nova_llm.egg-info/dependency_links.txt +1 -0
  47. nova_llm-0.1.0/nova_llm.egg-info/requires.txt +10 -0
  48. nova_llm-0.1.0/nova_llm.egg-info/top_level.txt +1 -0
  49. nova_llm-0.1.0/pyproject.toml +33 -0
  50. nova_llm-0.1.0/setup.cfg +4 -0
  51. nova_llm-0.1.0/tests/test_core.py +47 -0
  52. nova_llm-0.1.0/tests/test_drm.py +37 -0
  53. nova_llm-0.1.0/tests/test_ecal.py +48 -0
  54. nova_llm-0.1.0/tests/test_multimodal_and_compression.py +82 -0
  55. nova_llm-0.1.0/tests/test_sdk.py +58 -0
  56. nova_llm-0.1.0/tests/test_serving.py +66 -0
  57. nova_llm-0.1.0/tests/test_usf.py +42 -0
  58. nova_llm-0.1.0/tests/test_workflow.py +50 -0
@@ -0,0 +1,190 @@
1
+ Metadata-Version: 2.4
2
+ Name: nova-llm
3
+ Version: 0.1.0
4
+ Summary: NOVA AI: Unified Adaptive Computation (NOVA-UAC) Reference Engine and Developer SDK
5
+ Author: NOVA Research Team
6
+ License: Apache-2.0
7
+ Requires-Python: >=3.10
8
+ Description-Content-Type: text/markdown
9
+ Requires-Dist: torch>=2.0.0
10
+ Requires-Dist: numpy>=1.24.0
11
+ Requires-Dist: scipy>=1.10.0
12
+ Requires-Dist: fastapi>=0.100.0
13
+ Requires-Dist: uvicorn>=0.22.0
14
+ Requires-Dist: pydantic>=2.0.0
15
+ Requires-Dist: safetensors>=0.4.0
16
+ Provides-Extra: dev
17
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
18
+
19
+ # NOVA AI: Unified Adaptive Computation (NOVA-UAC)
20
+ **Research Programme & Autonomous AI Engineering Platform · Version 0.1**
21
+
22
+ NOVA is an independent AI engineering platform and scientific research architecture built around a **Unified Adaptive Computation (NOVA-UAC)** runtime.
23
+
24
+ Unlike traditional LLM systems that require external model APIs or manually assembled RAG, CAG, MAG, and brittle agent pipelines, NOVA couples:
25
+ 1. **Continuous State Evolution** (Unified State Field, USF with Lipschitz contraction dynamics)
26
+ 2. **Universal Multimodal Ingestion** (Real-time streaming of images, videos, documents, and sensor telemetry)
27
+ 3. **Dynamic Resonance Memory** (DRM with transactional confidence, utility decay, and knapsack capacity controls)
28
+ 4. **Experience-Coupled Adaptive Learning** (ECAL with gradient conflict estimation and stability regularization)
29
+ 5. **Adaptive Resource Allocation** (ARA value-of-compute policies)
30
+ 6. **Mobile Edge Compression** (INT8 / INT4 symmetric quantization for on-device smartphone deployment)
31
+ 7. **Native Agentic Workflows** (StateGraph and Pipeline SDKs comparable to LangGraph/LangChain)
32
+ 8. **Local REST Serving API** (FastAPI model serving with telemetry trace inspection)
33
+
34
+ ---
35
+
36
+ ## Architecture Overview
37
+
38
+ ```
39
+ +---------------------------------------+
40
+ | NOVA Python SDK / CLI |
41
+ +---------------------------------------+
42
+ |
43
+ v
44
+ +---------------------------------------+
45
+ | NOVA Runtime & Context |
46
+ +---------------------------------------+
47
+ |
48
+ v
49
+ +---------------------------------------+
50
+ | Universal Multimodal Encoder |
51
+ | [Images | Video | Docs | Telemetry] |
52
+ +---------------------------------------+
53
+ |
54
+ v
55
+ +--------------------> Unified State Field (USF) <----------------+
56
+ | | |
57
+ | +--------------------------+--------------------------+ |
58
+ | | | | |
59
+ v v v v v
60
+ +-------------------------+ +-------------------------+ +-------------------+
61
+ | Resonance Operator | | Ensemble Task Head | | Innovation Head |
62
+ | Association / Retrieval| | Uncertainty Estimator | | Scale Novelty |
63
+ +-------------------------+ +-------------------------+ +-------------------+
64
+ | | |
65
+ v v v
66
+ +-------------------------+ +-------------------------+ +-------------------+
67
+ | Dynamic Resonance Memory| | ECAL Controller | | ARA Compute Policy|
68
+ | DRM (Write Gate & Decay)| | Adaptive Gradient Step | | Refinement Budget |
69
+ +-------------------------+ +-------------------------+ +-------------------+
70
+ |
71
+ v
72
+ +-------------------------+
73
+ | Edge Mobile Exporter |
74
+ | INT8 / INT4 PTQ Bundle |
75
+ +-------------------------+
76
+ ```
77
+
78
+ ---
79
+
80
+ ## Quickstart
81
+
82
+ ### 1. Installation
83
+ Install project dependencies with pip:
84
+ ```powershell
85
+ python -m pip install -r requirements.txt
86
+ ```
87
+
88
+ ### 2. Developer Model API
89
+ ```python
90
+ import nova
91
+ import numpy as np
92
+
93
+ # 1. Initialize NOVA Engine
94
+ engine = nova.Engine(device="cpu", seed=42)
95
+
96
+ # 2. Instantiate Model
97
+ model = engine.create_model(
98
+ name="my_intelligence",
99
+ architecture="nova_uac_v0",
100
+ input_dim=8,
101
+ state_dim=32,
102
+ output_dim=1,
103
+ memory_dim=16
104
+ )
105
+
106
+ # 3. Create Dataset from real numeric dynamics
107
+ x = np.random.randn(200, 8).astype(np.float32)
108
+ y = (np.sin(x[:, :1]) + 0.5 * np.cos(x[:, 1:2])).astype(np.float32)
109
+ dataset = nova.Dataset.from_numpy(x, y)
110
+
111
+ # 4. Train with ECAL and DRM
112
+ model.fit(dataset, epochs=5, batch_size=16)
113
+
114
+ # 5. Evaluate and Save
115
+ metrics = model.evaluate(dataset)
116
+ model.save("./artifacts/my_model")
117
+
118
+ # 6. Load & Predict Deterministically
119
+ loaded = nova.load("./artifacts/my_model")
120
+ pred, trace = loaded.predict(x[:5], return_trace=True)
121
+ print(pred, trace.avg_novelty, trace.avg_uncertainty)
122
+ ```
123
+
124
+ ### 3. Streaming Multimodal Ingestion & Mobile Edge Export
125
+ ```python
126
+ import nova
127
+ from nova.sdk.multimodal_dataset import MultimodalStreamingDataset
128
+ from nova.compression.mobile_export import EdgeMobileExporter
129
+
130
+ # 1. Ingest any folder of images, videos, documents, or data
131
+ dataset = MultimodalStreamingDataset.from_directory("./my_uploads", embed_dim=16)
132
+
133
+ # 2. Train and adapt in real time on the stream
134
+ engine = nova.Engine(seed=42)
135
+ model = engine.create_model(input_dim=16, state_dim=32, output_dim=1, memory_dim=16)
136
+ for batch_x, batch_y in dataset.stream_batches(batch_size=16):
137
+ model.executor.training_step(batch_x, batch_y[:, :1], model.network.init_state(batch_x.shape[0]))
138
+
139
+ # 3. Export compressed INT8 bundle for smartphones (Android / iOS)
140
+ exporter = EdgeMobileExporter(model)
141
+ manifest = exporter.export_for_mobile("./artifacts/mobile_bundle", bits=8)
142
+ print(f"Compressed {manifest['compression_ratio']}x -> {manifest['quantized_size_mb']} MB")
143
+ ```
144
+
145
+ ### 4. Native Agentic StateGraph (LangGraph Alternative)
146
+ ```python
147
+ from nova.workflow import Graph
148
+
149
+ graph = Graph("adaptive_pipeline")
150
+ graph.add_node("ingest", ingest_fn)
151
+ graph.add_node("assess", model_predict_fn)
152
+ graph.add_node("memory_node", consult_drm_fn)
153
+ graph.add_node("decision", finalize_fn)
154
+
155
+ graph.set_entry_point("ingest")
156
+ graph.add_edge("ingest", "assess")
157
+ # Dynamic conditional routing based on NOVA internal novelty & uncertainty
158
+ graph.add_conditional_edge("assess", lambda state: "memory_node" if state["novelty"] > 0.6 else "decision")
159
+ graph.add_edge("memory_node", "decision")
160
+ graph.add_terminal("decision")
161
+
162
+ result = graph.run({"raw_input": [0.5, 0.2, -0.9, 0.4]})
163
+ ```
164
+
165
+ ### 5. Local Model Serving API
166
+ ```bash
167
+ python -m nova.serving.app
168
+ ```
169
+ Endpoints:
170
+ - `GET /health`
171
+ - `GET /v1/model/info`
172
+ - `POST /v1/predict`
173
+ - `GET /v1/memory/inspect`
174
+ - `POST /v1/memory/write`
175
+ - `DELETE /v1/memory/{id}`
176
+
177
+ ---
178
+
179
+ ## Running Benchmarks & Tests
180
+
181
+ ```powershell
182
+ # Run the 22 automated unit and integration tests
183
+ python -m pytest tests/ -v
184
+
185
+ # Run the live multimodal streaming test
186
+ python examples/06_realtime_multimodal_live_test.py
187
+
188
+ # Run empirical benchmark suite (continual learning, memory, ARA)
189
+ python -m benchmarks.run_all_benchmarks
190
+ ```
@@ -0,0 +1,172 @@
1
+ # NOVA AI: Unified Adaptive Computation (NOVA-UAC)
2
+ **Research Programme & Autonomous AI Engineering Platform · Version 0.1**
3
+
4
+ NOVA is an independent AI engineering platform and scientific research architecture built around a **Unified Adaptive Computation (NOVA-UAC)** runtime.
5
+
6
+ Unlike traditional LLM systems that require external model APIs or manually assembled RAG, CAG, MAG, and brittle agent pipelines, NOVA couples:
7
+ 1. **Continuous State Evolution** (Unified State Field, USF with Lipschitz contraction dynamics)
8
+ 2. **Universal Multimodal Ingestion** (Real-time streaming of images, videos, documents, and sensor telemetry)
9
+ 3. **Dynamic Resonance Memory** (DRM with transactional confidence, utility decay, and knapsack capacity controls)
10
+ 4. **Experience-Coupled Adaptive Learning** (ECAL with gradient conflict estimation and stability regularization)
11
+ 5. **Adaptive Resource Allocation** (ARA value-of-compute policies)
12
+ 6. **Mobile Edge Compression** (INT8 / INT4 symmetric quantization for on-device smartphone deployment)
13
+ 7. **Native Agentic Workflows** (StateGraph and Pipeline SDKs comparable to LangGraph/LangChain)
14
+ 8. **Local REST Serving API** (FastAPI model serving with telemetry trace inspection)
15
+
16
+ ---
17
+
18
+ ## Architecture Overview
19
+
20
+ ```
21
+ +---------------------------------------+
22
+ | NOVA Python SDK / CLI |
23
+ +---------------------------------------+
24
+ |
25
+ v
26
+ +---------------------------------------+
27
+ | NOVA Runtime & Context |
28
+ +---------------------------------------+
29
+ |
30
+ v
31
+ +---------------------------------------+
32
+ | Universal Multimodal Encoder |
33
+ | [Images | Video | Docs | Telemetry] |
34
+ +---------------------------------------+
35
+ |
36
+ v
37
+ +--------------------> Unified State Field (USF) <----------------+
38
+ | | |
39
+ | +--------------------------+--------------------------+ |
40
+ | | | | |
41
+ v v v v v
42
+ +-------------------------+ +-------------------------+ +-------------------+
43
+ | Resonance Operator | | Ensemble Task Head | | Innovation Head |
44
+ | Association / Retrieval| | Uncertainty Estimator | | Scale Novelty |
45
+ +-------------------------+ +-------------------------+ +-------------------+
46
+ | | |
47
+ v v v
48
+ +-------------------------+ +-------------------------+ +-------------------+
49
+ | Dynamic Resonance Memory| | ECAL Controller | | ARA Compute Policy|
50
+ | DRM (Write Gate & Decay)| | Adaptive Gradient Step | | Refinement Budget |
51
+ +-------------------------+ +-------------------------+ +-------------------+
52
+ |
53
+ v
54
+ +-------------------------+
55
+ | Edge Mobile Exporter |
56
+ | INT8 / INT4 PTQ Bundle |
57
+ +-------------------------+
58
+ ```
59
+
60
+ ---
61
+
62
+ ## Quickstart
63
+
64
+ ### 1. Installation
65
+ Install project dependencies with pip:
66
+ ```powershell
67
+ python -m pip install -r requirements.txt
68
+ ```
69
+
70
+ ### 2. Developer Model API
71
+ ```python
72
+ import nova
73
+ import numpy as np
74
+
75
+ # 1. Initialize NOVA Engine
76
+ engine = nova.Engine(device="cpu", seed=42)
77
+
78
+ # 2. Instantiate Model
79
+ model = engine.create_model(
80
+ name="my_intelligence",
81
+ architecture="nova_uac_v0",
82
+ input_dim=8,
83
+ state_dim=32,
84
+ output_dim=1,
85
+ memory_dim=16
86
+ )
87
+
88
+ # 3. Create Dataset from real numeric dynamics
89
+ x = np.random.randn(200, 8).astype(np.float32)
90
+ y = (np.sin(x[:, :1]) + 0.5 * np.cos(x[:, 1:2])).astype(np.float32)
91
+ dataset = nova.Dataset.from_numpy(x, y)
92
+
93
+ # 4. Train with ECAL and DRM
94
+ model.fit(dataset, epochs=5, batch_size=16)
95
+
96
+ # 5. Evaluate and Save
97
+ metrics = model.evaluate(dataset)
98
+ model.save("./artifacts/my_model")
99
+
100
+ # 6. Load & Predict Deterministically
101
+ loaded = nova.load("./artifacts/my_model")
102
+ pred, trace = loaded.predict(x[:5], return_trace=True)
103
+ print(pred, trace.avg_novelty, trace.avg_uncertainty)
104
+ ```
105
+
106
+ ### 3. Streaming Multimodal Ingestion & Mobile Edge Export
107
+ ```python
108
+ import nova
109
+ from nova.sdk.multimodal_dataset import MultimodalStreamingDataset
110
+ from nova.compression.mobile_export import EdgeMobileExporter
111
+
112
+ # 1. Ingest any folder of images, videos, documents, or data
113
+ dataset = MultimodalStreamingDataset.from_directory("./my_uploads", embed_dim=16)
114
+
115
+ # 2. Train and adapt in real time on the stream
116
+ engine = nova.Engine(seed=42)
117
+ model = engine.create_model(input_dim=16, state_dim=32, output_dim=1, memory_dim=16)
118
+ for batch_x, batch_y in dataset.stream_batches(batch_size=16):
119
+ model.executor.training_step(batch_x, batch_y[:, :1], model.network.init_state(batch_x.shape[0]))
120
+
121
+ # 3. Export compressed INT8 bundle for smartphones (Android / iOS)
122
+ exporter = EdgeMobileExporter(model)
123
+ manifest = exporter.export_for_mobile("./artifacts/mobile_bundle", bits=8)
124
+ print(f"Compressed {manifest['compression_ratio']}x -> {manifest['quantized_size_mb']} MB")
125
+ ```
126
+
127
+ ### 4. Native Agentic StateGraph (LangGraph Alternative)
128
+ ```python
129
+ from nova.workflow import Graph
130
+
131
+ graph = Graph("adaptive_pipeline")
132
+ graph.add_node("ingest", ingest_fn)
133
+ graph.add_node("assess", model_predict_fn)
134
+ graph.add_node("memory_node", consult_drm_fn)
135
+ graph.add_node("decision", finalize_fn)
136
+
137
+ graph.set_entry_point("ingest")
138
+ graph.add_edge("ingest", "assess")
139
+ # Dynamic conditional routing based on NOVA internal novelty & uncertainty
140
+ graph.add_conditional_edge("assess", lambda state: "memory_node" if state["novelty"] > 0.6 else "decision")
141
+ graph.add_edge("memory_node", "decision")
142
+ graph.add_terminal("decision")
143
+
144
+ result = graph.run({"raw_input": [0.5, 0.2, -0.9, 0.4]})
145
+ ```
146
+
147
+ ### 5. Local Model Serving API
148
+ ```bash
149
+ python -m nova.serving.app
150
+ ```
151
+ Endpoints:
152
+ - `GET /health`
153
+ - `GET /v1/model/info`
154
+ - `POST /v1/predict`
155
+ - `GET /v1/memory/inspect`
156
+ - `POST /v1/memory/write`
157
+ - `DELETE /v1/memory/{id}`
158
+
159
+ ---
160
+
161
+ ## Running Benchmarks & Tests
162
+
163
+ ```powershell
164
+ # Run the 22 automated unit and integration tests
165
+ python -m pytest tests/ -v
166
+
167
+ # Run the live multimodal streaming test
168
+ python examples/06_realtime_multimodal_live_test.py
169
+
170
+ # Run empirical benchmark suite (continual learning, memory, ARA)
171
+ python -m benchmarks.run_all_benchmarks
172
+ ```
@@ -0,0 +1,15 @@
1
+ """NOVA AI: Unified Adaptive Computation (NOVA-UAC)
2
+
3
+ A research-first blueprint and SDK for a new AI architecture,
4
+ learning methodology, memory system, and runtime.
5
+ """
6
+
7
+ from nova.sdk.engine import Engine
8
+ from nova.sdk.dataset import Dataset
9
+ from nova.sdk.model import Model, load
10
+ from nova.sdk.multimodal_dataset import MultimodalStreamingDataset
11
+ import nova.workflow as workflow
12
+
13
+ __version__ = "0.1.0"
14
+ __all__ = ["Engine", "Dataset", "Model", "load", "MultimodalStreamingDataset", "workflow", "__version__"]
15
+
@@ -0,0 +1,13 @@
1
+ from nova.architecture.usf import UnifiedStateCell
2
+ from nova.architecture.resonance import ResonanceOperator
3
+ from nova.architecture.heads import InnovationPredictor, EnsembleTaskHead
4
+ from nova.architecture.model import NOVAArchitecture
5
+
6
+ __all__ = [
7
+ "UnifiedStateCell",
8
+ "ResonanceOperator",
9
+ "InnovationPredictor",
10
+ "EnsembleTaskHead",
11
+ "NOVAArchitecture"
12
+ ]
13
+
@@ -0,0 +1,80 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import Tuple, List
4
+ from nova.core.validation import check_finite, EPSILON
5
+
6
+ class InnovationPredictor(nn.Module):
7
+ """
8
+ Predicts next feature representation x~_{t+1} = D_psi(s_{t+1})
9
+ used to calculate scale-normalized novelty e_t = x_{t+1} - x~_{t+1}.
10
+ """
11
+ def __init__(self, state_dim: int, input_dim: int):
12
+ super().__init__()
13
+ self.decoder = nn.Sequential(
14
+ nn.Linear(state_dim, state_dim),
15
+ nn.GELU(),
16
+ nn.Linear(state_dim, input_dim)
17
+ )
18
+
19
+ def forward(self, s_next: torch.Tensor) -> torch.Tensor:
20
+ check_finite(s_next, "s_next")
21
+ return self.decoder(s_next)
22
+
23
+ class EnsembleTaskHead(nn.Module):
24
+ """
25
+ Ensemble of K task prediction heads for calibrated prediction
26
+ and explicit epistemic & aleatoric uncertainty estimation (PRD Section 5.6):
27
+ mu_t = (1/K) sum_k y~_t^(k)
28
+ u_epi,t = (1/K) sum_k ||y~_t^(k) - mu_t||^2
29
+ """
30
+ def __init__(self, state_dim: int, output_dim: int, num_heads: int = 4, is_classifier: bool = False):
31
+ super().__init__()
32
+ self.output_dim = output_dim
33
+ self.num_heads = num_heads
34
+ self.is_classifier = is_classifier
35
+
36
+ self.heads = nn.ModuleList([
37
+ nn.Sequential(
38
+ nn.Linear(state_dim, state_dim // 2),
39
+ nn.GELU(),
40
+ nn.Linear(state_dim // 2, output_dim)
41
+ ) for _ in range(num_heads)
42
+ ])
43
+
44
+ # Predicted observation noise head for aleatoric uncertainty
45
+ self.aleatoric_head = nn.Sequential(
46
+ nn.Linear(state_dim, state_dim // 4),
47
+ nn.ReLU(),
48
+ nn.Linear(state_dim // 4, 1),
49
+ nn.Softplus()
50
+ )
51
+
52
+ def forward(self, s_t: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
53
+ """
54
+ Returns:
55
+ mu_pred: (batch, output_dim) mean prediction
56
+ u_total: (batch, 1) total uncertainty
57
+ u_epi: (batch, 1) epistemic variance across heads
58
+ u_ale: (batch, 1) predicted aleatoric noise
59
+ """
60
+ check_finite(s_t, "state_for_task_head")
61
+ preds = [head(s_t) for head in self.heads] # list of (batch, output_dim)
62
+ stacked_preds = torch.stack(preds, dim=0) # (K, batch, output_dim)
63
+
64
+ if self.is_classifier:
65
+ probs = torch.softmax(stacked_preds, dim=-1)
66
+ mean_probs = torch.mean(probs, dim=0) # (batch, output_dim)
67
+ # Epistemic variance across heads
68
+ epi_var = torch.mean(torch.sum((probs - mean_probs.unsqueeze(0)) ** 2, dim=-1, keepdim=True), dim=0)
69
+ # Entropy as predictive uncertainty
70
+ entropy = -torch.sum(mean_probs * torch.log(mean_probs + EPSILON), dim=-1, keepdim=True)
71
+ u_total = torch.clamp(epi_var + 0.1 * entropy, 0.0, 1.0)
72
+ u_ale = 0.1 * entropy
73
+ return mean_probs, u_total, epi_var, u_ale
74
+ else:
75
+ mean_pred = torch.mean(stacked_preds, dim=0)
76
+ epi_var = torch.mean(torch.sum((stacked_preds - mean_pred.unsqueeze(0)) ** 2, dim=-1, keepdim=True), dim=0)
77
+ ale_var = self.aleatoric_head(s_t)
78
+ u_total = epi_var + ale_var
79
+ return mean_pred, u_total, epi_var, ale_var
80
+
@@ -0,0 +1,174 @@
1
+ import torch
2
+ import torch.nn as nn
3
+ from typing import Optional, Tuple, Dict, Any, List
4
+ from nova.encoders.mlp import FeatureEncoder
5
+ from nova.architecture.usf import UnifiedStateCell
6
+ from nova.architecture.resonance import ResonanceOperator
7
+ from nova.architecture.heads import InnovationPredictor, EnsembleTaskHead
8
+ from nova.memory.drm import DynamicResonanceMemory
9
+ from nova.compute.ara import AdaptiveResourceAllocator
10
+ from nova.core.tensor_ops import scale_normalized_residual
11
+ from nova.core.validation import check_finite
12
+
13
+ class NOVAArchitecture(nn.Module):
14
+ """
15
+ Unified Adaptive Computation (NOVA-UAC) Neural Architecture.
16
+ Seamlessly binds input encoding, unified continuous state evolution,
17
+ resonance associative memory, innovation prediction, and uncertainty estimation.
18
+ """
19
+ def __init__(
20
+ self,
21
+ input_dim: int,
22
+ state_dim: int = 64,
23
+ output_dim: int = 1,
24
+ memory_dim: int = 32,
25
+ memory_capacity: int = 256,
26
+ num_heads: int = 4,
27
+ is_classifier: bool = False,
28
+ spectral_norm: bool = False,
29
+ rho_min: float = 0.05
30
+ ):
31
+ super().__init__()
32
+ self.input_dim = input_dim
33
+ self.state_dim = state_dim
34
+ self.output_dim = output_dim
35
+ self.memory_dim = memory_dim
36
+ self.is_classifier = is_classifier
37
+
38
+ # 1. Input Encoder & Key Projector
39
+ self.encoder = FeatureEncoder(input_dim=input_dim, embed_dim=input_dim)
40
+ self.key_proj = nn.Linear(input_dim, memory_dim)
41
+
42
+ # 2. Unified State Cell
43
+ self.state_cell = UnifiedStateCell(
44
+ input_dim=input_dim,
45
+ state_dim=state_dim,
46
+ memory_dim=memory_dim,
47
+ rho_min=rho_min,
48
+ spectral_norm=spectral_norm
49
+ )
50
+
51
+ # 3. Resonance & Memory
52
+ self.resonance = ResonanceOperator(state_dim=state_dim, memory_dim=memory_dim)
53
+ self.memory = DynamicResonanceMemory(memory_dim=memory_dim, capacity=memory_capacity)
54
+
55
+ # 4. Innovation Predictor (Autoencoder for next feature)
56
+ self.predictor = InnovationPredictor(state_dim=state_dim, input_dim=input_dim)
57
+
58
+ # 5. Calibrated Task Head with Uncertainty
59
+ self.head = EnsembleTaskHead(
60
+ state_dim=state_dim,
61
+ output_dim=output_dim,
62
+ num_heads=num_heads,
63
+ is_classifier=is_classifier
64
+ )
65
+
66
+ # 6. Adaptive Resource Allocation policy
67
+ self.ara = AdaptiveResourceAllocator()
68
+
69
+ def init_state(self, batch_size: int, device: Optional[torch.device] = None) -> torch.Tensor:
70
+ """Initializes latent state s_0 to zeros."""
71
+ dev = device or next(self.parameters()).device
72
+ return torch.zeros(batch_size, self.state_dim, device=dev)
73
+
74
+ def forward_step(
75
+ self,
76
+ x_raw: torch.Tensor,
77
+ s_prev: torch.Tensor,
78
+ allow_refinement: bool = True
79
+ ) -> Dict[str, Any]:
80
+ """
81
+ Executes a single step of the candidate transition (PRD Section 5.13):
82
+ x_t = E_phi(a_t)
83
+ r_t = Retrieve(M_t, W_q s_t)
84
+ s_{t+1} = (1 - rho_t) s_t + rho_t sigma(W_x x_t + W_s s_t + W_r r_t + b)
85
+ y^_t, u_t = Head(s_{t+1})
86
+ x^_t = Predictor(s_{t+1})
87
+ n_t = Novelty(x_t, x^_t)
88
+ c*_t = ARA(n_t, u_t)
89
+ """
90
+ # Encode
91
+ x_t = self.encoder(x_raw)
92
+ batch_size = x_t.shape[0]
93
+ device = x_t.device
94
+
95
+ # Memory retrieval
96
+ mem_keys, mem_vals, mem_confs, mem_ids = self.memory.get_tensors(device=device)
97
+ r_t, assoc_weights = self.resonance.compute_associations(
98
+ s_t=s_prev,
99
+ memory_keys=mem_keys,
100
+ memory_values=mem_vals,
101
+ memory_confidences=mem_confs
102
+ )
103
+
104
+ # State transition
105
+ s_next, rho = self.state_cell(x_t=x_t, s_t=s_prev, r_t=r_t)
106
+
107
+ # Innovation and task predictions
108
+ x_hat = self.predictor(s_next)
109
+ y_pred, u_total, u_epi, u_ale = self.head(s_next)
110
+
111
+ # Novelty computation
112
+ novelty_tensor = scale_normalized_residual(target=x_t, predicted=x_hat, kappa=1.0)
113
+ novelty_val = float(torch.mean(novelty_tensor).item())
114
+ uncertainty_val = float(torch.mean(u_total).item())
115
+
116
+ # ARA compute action
117
+ action = 0
118
+ if allow_refinement:
119
+ action, _ = self.ara.choose_action(novelty_val, uncertainty_val)
120
+ # Refinement loop: perform 'action' additional iterations through state cell
121
+ for _ in range(action):
122
+ s_next, _ = self.state_cell(x_t=x_t, s_t=s_next, r_t=r_t)
123
+ if action > 0:
124
+ y_pred, u_total, u_epi, u_ale = self.head(s_next)
125
+
126
+ return {
127
+ "x_encoded": x_t,
128
+ "x_hat": x_hat,
129
+ "y_pred": y_pred,
130
+ "s_next": s_next,
131
+ "r_t": r_t,
132
+ "assoc_weights": assoc_weights,
133
+ "novelty": novelty_val,
134
+ "novelty_tensor": novelty_tensor,
135
+ "uncertainty": uncertainty_val,
136
+ "uncertainty_tensor": u_total,
137
+ "epistemic_uncertainty": float(torch.mean(u_epi).item()),
138
+ "aleatoric_uncertainty": float(torch.mean(u_ale).item()),
139
+ "compute_action": action,
140
+ "retrieved_ids": mem_ids,
141
+ "rho": rho
142
+ }
143
+
144
+ def forward_sequence(
145
+ self,
146
+ x_seq: torch.Tensor,
147
+ s_init: Optional[torch.Tensor] = None
148
+ ) -> Dict[str, Any]:
149
+ """Processes sequence of inputs: (batch, seq_len, input_dim)."""
150
+ batch_size, seq_len, _ = x_seq.shape
151
+ state = s_init if s_init is not None else self.init_state(batch_size, x_seq.device)
152
+
153
+ y_preds = []
154
+ states = []
155
+ novelties = []
156
+ uncertainties = []
157
+
158
+ for t in range(seq_len):
159
+ step_out = self.forward_step(x_seq[:, t, :], state, allow_refinement=False)
160
+ state = step_out["s_next"]
161
+ y_preds.append(step_out["y_pred"])
162
+ states.append(state)
163
+ novelties.append(step_out["novelty"])
164
+ uncertainties.append(step_out["uncertainty"])
165
+
166
+ # Stack over time
167
+ return {
168
+ "y_pred_seq": torch.stack(y_preds, dim=1),
169
+ "y_pred_last": y_preds[-1],
170
+ "state_last": states[-1],
171
+ "states_seq": torch.stack(states, dim=1),
172
+ "novelties": novelties,
173
+ "uncertainties": uncertainties
174
+ }