nova-llm 0.1.0__py3-none-any.whl
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.
- nova/__init__.py +15 -0
- nova/architecture/__init__.py +13 -0
- nova/architecture/heads.py +80 -0
- nova/architecture/model.py +174 -0
- nova/architecture/resonance.py +83 -0
- nova/architecture/usf.py +92 -0
- nova/compression/__init__.py +18 -0
- nova/compression/mobile_export.py +69 -0
- nova/compression/quantization.py +66 -0
- nova/compute/__init__.py +4 -0
- nova/compute/ara.py +37 -0
- nova/core/__init__.py +19 -0
- nova/core/state.py +42 -0
- nova/core/tensor_ops.py +49 -0
- nova/core/validation.py +30 -0
- nova/encoders/__init__.py +5 -0
- nova/encoders/mlp.py +29 -0
- nova/encoders/multimodal.py +132 -0
- nova/learning/__init__.py +11 -0
- nova/learning/ecal.py +100 -0
- nova/learning/objectives.py +115 -0
- nova/learning/regularizer.py +47 -0
- nova/memory/__init__.py +5 -0
- nova/memory/drm.py +212 -0
- nova/memory/storage.py +27 -0
- nova/runtime/__init__.py +5 -0
- nova/runtime/executor.py +145 -0
- nova/runtime/trace.py +59 -0
- nova/sdk/__init__.py +7 -0
- nova/sdk/dataset.py +83 -0
- nova/sdk/engine.py +53 -0
- nova/sdk/model.py +238 -0
- nova/sdk/multimodal_dataset.py +57 -0
- nova/sdk/serialization.py +99 -0
- nova/serving/__init__.py +4 -0
- nova/serving/app.py +112 -0
- nova/serving/schemas.py +36 -0
- nova/workflow/__init__.py +6 -0
- nova/workflow/graph.py +80 -0
- nova/workflow/node.py +18 -0
- nova/workflow/pipeline.py +21 -0
- nova_llm-0.1.0.dist-info/METADATA +190 -0
- nova_llm-0.1.0.dist-info/RECORD +45 -0
- nova_llm-0.1.0.dist-info/WHEEL +5 -0
- nova_llm-0.1.0.dist-info/top_level.txt +1 -0
nova/__init__.py
ADDED
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from typing import Tuple, Optional
|
|
4
|
+
from nova.core.validation import check_finite, EPSILON
|
|
5
|
+
|
|
6
|
+
class ResonanceOperator(nn.Module):
|
|
7
|
+
"""
|
|
8
|
+
Resonance and Memory Association Operator (PRD Section 5.7):
|
|
9
|
+
q_t = W_q s_t
|
|
10
|
+
k_i = W_k m_i
|
|
11
|
+
d(t, i) = ||q_t - k_i||^2 / (tau_i + eps)
|
|
12
|
+
a(t, i) = exp(-d(t, i)) * c_i
|
|
13
|
+
w(t, i) = a(t, i) / (sum_j a(t, j) + eps)
|
|
14
|
+
r_t = sum_i w(t, i) v_i
|
|
15
|
+
"""
|
|
16
|
+
def __init__(self, state_dim: int, memory_dim: int, query_dim: Optional[int] = None):
|
|
17
|
+
super().__init__()
|
|
18
|
+
self.state_dim = state_dim
|
|
19
|
+
self.memory_dim = memory_dim
|
|
20
|
+
self.query_dim = query_dim or state_dim
|
|
21
|
+
|
|
22
|
+
self.W_q = nn.Linear(state_dim, self.query_dim)
|
|
23
|
+
self.W_k = nn.Linear(memory_dim, self.query_dim)
|
|
24
|
+
self.temperature = nn.Parameter(torch.ones(1))
|
|
25
|
+
|
|
26
|
+
def compute_associations(
|
|
27
|
+
self,
|
|
28
|
+
s_t: torch.Tensor,
|
|
29
|
+
memory_keys: torch.Tensor,
|
|
30
|
+
memory_values: torch.Tensor,
|
|
31
|
+
memory_confidences: torch.Tensor,
|
|
32
|
+
memory_scales: Optional[torch.Tensor] = None
|
|
33
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
34
|
+
"""
|
|
35
|
+
Args:
|
|
36
|
+
s_t: (batch, state_dim)
|
|
37
|
+
memory_keys: (K, memory_dim)
|
|
38
|
+
memory_values: (K, memory_dim)
|
|
39
|
+
memory_confidences: (K,) or (batch, K)
|
|
40
|
+
memory_scales: (K,) or (batch, K) positive scale tau_i
|
|
41
|
+
Returns:
|
|
42
|
+
r_t: (batch, memory_dim) retrieved context
|
|
43
|
+
weights: (batch, K) association weights
|
|
44
|
+
"""
|
|
45
|
+
check_finite(s_t, "resonance_s_t")
|
|
46
|
+
batch_size = s_t.shape[0]
|
|
47
|
+
k_slots = memory_keys.shape[0]
|
|
48
|
+
|
|
49
|
+
if k_slots == 0:
|
|
50
|
+
zeros_r = torch.zeros(batch_size, self.memory_dim, device=s_t.device, dtype=s_t.dtype)
|
|
51
|
+
zeros_w = torch.zeros(batch_size, 0, device=s_t.device, dtype=s_t.dtype)
|
|
52
|
+
return zeros_r, zeros_w
|
|
53
|
+
|
|
54
|
+
# q_t: (batch, query_dim)
|
|
55
|
+
q_t = self.W_q(s_t)
|
|
56
|
+
# k: (k_slots, query_dim)
|
|
57
|
+
k = self.W_k(memory_keys)
|
|
58
|
+
|
|
59
|
+
# Distance: ||q_t - k_i||^2
|
|
60
|
+
# Expand shapes: q_t: (batch, 1, query_dim), k: (1, k_slots, query_dim)
|
|
61
|
+
diff = q_t.unsqueeze(1) - k.unsqueeze(0) # (batch, k_slots, query_dim)
|
|
62
|
+
sq_dist = torch.sum(diff ** 2, dim=-1) # (batch, k_slots)
|
|
63
|
+
|
|
64
|
+
if memory_scales is not None:
|
|
65
|
+
tau = memory_scales.view(1, -1) + EPSILON
|
|
66
|
+
else:
|
|
67
|
+
tau = torch.ones(1, k_slots, device=s_t.device, dtype=s_t.dtype)
|
|
68
|
+
|
|
69
|
+
scaled_dist = sq_dist / (tau * torch.clamp(self.temperature, min=0.1) + EPSILON)
|
|
70
|
+
|
|
71
|
+
# Confidence weighting: a(t, i) = exp(-d(t, i)) * c_i
|
|
72
|
+
conf = memory_confidences.view(1, -1) if memory_confidences.dim() == 1 else memory_confidences
|
|
73
|
+
affinity = torch.exp(-torch.clamp(scaled_dist, max=20.0)) * conf
|
|
74
|
+
|
|
75
|
+
# Normalize weights
|
|
76
|
+
sum_affinity = torch.sum(affinity, dim=-1, keepdim=True)
|
|
77
|
+
weights = affinity / torch.clamp(sum_affinity, min=1e-8) # (batch, k_slots)
|
|
78
|
+
|
|
79
|
+
# Retrieved context r_t = sum_i w(t, i) v_i
|
|
80
|
+
# weights: (batch, k_slots, 1), memory_values: (1, k_slots, memory_dim)
|
|
81
|
+
r_t = torch.sum(weights.unsqueeze(-1) * memory_values.unsqueeze(0), dim=1)
|
|
82
|
+
check_finite(r_t, "retrieved_context")
|
|
83
|
+
return r_t, weights
|
nova/architecture/usf.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from typing import Optional, Tuple
|
|
4
|
+
from nova.core.validation import check_finite, EPSILON
|
|
5
|
+
|
|
6
|
+
class UnifiedStateCell(nn.Module):
|
|
7
|
+
"""
|
|
8
|
+
Unified State Field (USF) Cell from PRD Section 5.3:
|
|
9
|
+
z_t = W_x x_t + W_s s_t + W_r r_t + b
|
|
10
|
+
s~_{t+1} = sigma(z_t) (bounded elementwise nonlinearity: tanh)
|
|
11
|
+
s_{t+1} = (1 - rho_t) s_t + rho_t s~_{t+1}
|
|
12
|
+
with rho_t in [rho_min, 1.0] gating rate.
|
|
13
|
+
"""
|
|
14
|
+
def __init__(
|
|
15
|
+
self,
|
|
16
|
+
input_dim: int,
|
|
17
|
+
state_dim: int,
|
|
18
|
+
memory_dim: int,
|
|
19
|
+
rho_min: float = 0.05,
|
|
20
|
+
spectral_norm: bool = False
|
|
21
|
+
):
|
|
22
|
+
super().__init__()
|
|
23
|
+
self.input_dim = input_dim
|
|
24
|
+
self.state_dim = state_dim
|
|
25
|
+
self.memory_dim = memory_dim
|
|
26
|
+
self.rho_min = rho_min
|
|
27
|
+
|
|
28
|
+
# Linear projections
|
|
29
|
+
linear_x = nn.Linear(input_dim, state_dim)
|
|
30
|
+
linear_s = nn.Linear(state_dim, state_dim, bias=False)
|
|
31
|
+
linear_r = nn.Linear(memory_dim, state_dim, bias=False)
|
|
32
|
+
|
|
33
|
+
if spectral_norm:
|
|
34
|
+
self.W_s = nn.utils.spectral_norm(linear_s)
|
|
35
|
+
else:
|
|
36
|
+
self.W_s = linear_s
|
|
37
|
+
|
|
38
|
+
self.W_x = linear_x
|
|
39
|
+
self.W_r = linear_r
|
|
40
|
+
|
|
41
|
+
# State update gate network rho_t in [rho_min, 1.0]
|
|
42
|
+
self.gate_net = nn.Sequential(
|
|
43
|
+
nn.Linear(input_dim + state_dim + memory_dim, state_dim),
|
|
44
|
+
nn.Sigmoid()
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
self._init_weights()
|
|
48
|
+
|
|
49
|
+
def _init_weights(self):
|
|
50
|
+
# Orthogonal init for recurrent weights to ensure stable spectrum
|
|
51
|
+
nn.init.orthogonal_(self.W_s.weight, gain=0.9)
|
|
52
|
+
nn.init.xavier_uniform_(self.W_x.weight)
|
|
53
|
+
nn.init.xavier_uniform_(self.W_r.weight)
|
|
54
|
+
|
|
55
|
+
def forward(
|
|
56
|
+
self,
|
|
57
|
+
x_t: torch.Tensor,
|
|
58
|
+
s_t: torch.Tensor,
|
|
59
|
+
r_t: Optional[torch.Tensor] = None
|
|
60
|
+
) -> Tuple[torch.Tensor, torch.Tensor]:
|
|
61
|
+
"""
|
|
62
|
+
Args:
|
|
63
|
+
x_t: (batch, input_dim)
|
|
64
|
+
s_t: (batch, state_dim)
|
|
65
|
+
r_t: (batch, memory_dim) or None (zeros used if None)
|
|
66
|
+
Returns:
|
|
67
|
+
s_next: (batch, state_dim)
|
|
68
|
+
rho_t: (batch, state_dim) gate activations
|
|
69
|
+
"""
|
|
70
|
+
check_finite(x_t, "x_t")
|
|
71
|
+
check_finite(s_t, "s_t")
|
|
72
|
+
|
|
73
|
+
batch_size = x_t.shape[0]
|
|
74
|
+
if r_t is None:
|
|
75
|
+
r_t = torch.zeros(batch_size, self.memory_dim, device=x_t.device, dtype=x_t.dtype)
|
|
76
|
+
check_finite(r_t, "r_t")
|
|
77
|
+
|
|
78
|
+
# Candidate transition equation
|
|
79
|
+
z_t = self.W_x(x_t) + self.W_s(s_t) + self.W_r(r_t)
|
|
80
|
+
s_tilde = torch.tanh(z_t)
|
|
81
|
+
|
|
82
|
+
# Gate computation
|
|
83
|
+
gate_input = torch.cat([x_t, s_t, r_t], dim=-1)
|
|
84
|
+
raw_rho = self.gate_net(gate_input)
|
|
85
|
+
# Constrain to [rho_min, 1.0]
|
|
86
|
+
rho_t = self.rho_min + (1.0 - self.rho_min) * raw_rho
|
|
87
|
+
|
|
88
|
+
# Leaky state update
|
|
89
|
+
s_next = (1.0 - rho_t) * s_t + rho_t * s_tilde
|
|
90
|
+
check_finite(s_next, "s_{t+1}")
|
|
91
|
+
return s_next, rho_t
|
|
92
|
+
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
from nova.compression.quantization import (
|
|
2
|
+
quantize_tensor_int8,
|
|
3
|
+
dequantize_tensor_int8,
|
|
4
|
+
quantize_tensor_int4,
|
|
5
|
+
dequantize_tensor_int4,
|
|
6
|
+
QuantizedLinear
|
|
7
|
+
)
|
|
8
|
+
from nova.compression.mobile_export import EdgeMobileExporter
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"quantize_tensor_int8",
|
|
12
|
+
"dequantize_tensor_int8",
|
|
13
|
+
"quantize_tensor_int4",
|
|
14
|
+
"dequantize_tensor_int4",
|
|
15
|
+
"QuantizedLinear",
|
|
16
|
+
"EdgeMobileExporter"
|
|
17
|
+
]
|
|
18
|
+
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import os
|
|
2
|
+
import json
|
|
3
|
+
import torch
|
|
4
|
+
import torch.nn as nn
|
|
5
|
+
from typing import Dict, Any
|
|
6
|
+
from nova.compression.quantization import quantize_tensor_int8, quantize_tensor_int4
|
|
7
|
+
|
|
8
|
+
class EdgeMobileExporter:
|
|
9
|
+
"""
|
|
10
|
+
Exports a trained NOVA model into a compact, ultra-lightweight mobile package.
|
|
11
|
+
Applies:
|
|
12
|
+
1. INT8 / INT4 Weight Quantization (4x - 8x memory reduction)
|
|
13
|
+
2. Memory bank compact serialization
|
|
14
|
+
3. Mobile runner manifest with execution footprint diagnostics
|
|
15
|
+
"""
|
|
16
|
+
def __init__(self, model_obj: Any):
|
|
17
|
+
self.model = model_obj
|
|
18
|
+
|
|
19
|
+
def export_for_mobile(self, output_dir: str, bits: int = 8) -> Dict[str, Any]:
|
|
20
|
+
os.makedirs(output_dir, exist_ok=True)
|
|
21
|
+
mobile_manifest_path = os.path.join(output_dir, "mobile_manifest.json")
|
|
22
|
+
mobile_weights_path = os.path.join(output_dir, f"weights_int{bits}.pt")
|
|
23
|
+
|
|
24
|
+
quantized_state = {}
|
|
25
|
+
scales = {}
|
|
26
|
+
raw_float_bytes = 0
|
|
27
|
+
quantized_bytes = 0
|
|
28
|
+
|
|
29
|
+
# Quantize all parameter tensors
|
|
30
|
+
for name, param in self.model.network.named_parameters():
|
|
31
|
+
p_data = param.detach().cpu()
|
|
32
|
+
raw_float_bytes += p_data.nelement() * 4 # float32 = 4 bytes
|
|
33
|
+
|
|
34
|
+
if "weight" in name and p_data.dim() >= 2:
|
|
35
|
+
if bits == 8:
|
|
36
|
+
q_tensor, s = quantize_tensor_int8(p_data)
|
|
37
|
+
quantized_bytes += p_data.nelement() * 1 # int8 = 1 byte
|
|
38
|
+
else:
|
|
39
|
+
q_tensor, s = quantize_tensor_int4(p_data)
|
|
40
|
+
quantized_bytes += int(p_data.nelement() * 0.5) # int4 = 0.5 byte
|
|
41
|
+
quantized_state[name] = q_tensor
|
|
42
|
+
scales[name] = s
|
|
43
|
+
else:
|
|
44
|
+
# Keep 1D biases and small vectors in FP16 for precision
|
|
45
|
+
fp16_data = p_data.to(torch.float16)
|
|
46
|
+
quantized_state[name] = fp16_data
|
|
47
|
+
quantized_bytes += fp16_data.nelement() * 2
|
|
48
|
+
|
|
49
|
+
# Save quantized weights & scale factors
|
|
50
|
+
torch.save({"weights": quantized_state, "scales": scales, "bits": bits}, mobile_weights_path)
|
|
51
|
+
|
|
52
|
+
compression_ratio = raw_float_bytes / max(quantized_bytes, 1)
|
|
53
|
+
|
|
54
|
+
manifest = {
|
|
55
|
+
"model_id": getattr(self.model, "name", "nova_mobile_model"),
|
|
56
|
+
"architecture": "NOVA-UAC-Edge",
|
|
57
|
+
"quantization": f"INT{bits}",
|
|
58
|
+
"raw_size_mb": round(raw_float_bytes / (1024 * 1024), 3),
|
|
59
|
+
"quantized_size_mb": round(quantized_bytes / (1024 * 1024), 3),
|
|
60
|
+
"compression_ratio": round(compression_ratio, 2),
|
|
61
|
+
"target_platforms": ["Android (NPU/CPU)", "iOS (Apple Neural Engine)", "Embedded Linux"],
|
|
62
|
+
"mobile_ready": True
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
with open(mobile_manifest_path, "w", encoding="utf-8") as f:
|
|
66
|
+
json.dump(manifest, f, indent=2)
|
|
67
|
+
|
|
68
|
+
return manifest
|
|
69
|
+
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from typing import Dict, Any, Tuple
|
|
4
|
+
|
|
5
|
+
def quantize_tensor_int8(tensor: torch.Tensor) -> Tuple[torch.Tensor, float]:
|
|
6
|
+
"""
|
|
7
|
+
Symmetric INT8 Post-Training Quantization (PTQ).
|
|
8
|
+
Maps float32 weights in [-max_val, max_val] to int8 [-127, 127].
|
|
9
|
+
Scale: s = max(|tensor|) / 127.
|
|
10
|
+
"""
|
|
11
|
+
max_val = float(torch.max(torch.abs(tensor)).item())
|
|
12
|
+
scale = max_val / 127.0 if max_val > 1e-8 else 1.0
|
|
13
|
+
q_int8 = torch.clamp(torch.round(tensor / scale), -127, 127).to(torch.int8)
|
|
14
|
+
return q_int8, scale
|
|
15
|
+
|
|
16
|
+
def dequantize_tensor_int8(q_tensor: torch.Tensor, scale: float) -> torch.Tensor:
|
|
17
|
+
"""Restores float32 tensor from int8 representation."""
|
|
18
|
+
return q_tensor.to(torch.float32) * scale
|
|
19
|
+
|
|
20
|
+
def quantize_tensor_int4(tensor: torch.Tensor) -> Tuple[torch.Tensor, float]:
|
|
21
|
+
"""
|
|
22
|
+
Symmetric INT4 Quantization.
|
|
23
|
+
Maps float32 weights to 4-bit signed integers [-7, 7].
|
|
24
|
+
Yields an 8x memory reduction compared to float32.
|
|
25
|
+
"""
|
|
26
|
+
max_val = float(torch.max(torch.abs(tensor)).item())
|
|
27
|
+
scale = max_val / 7.0 if max_val > 1e-8 else 1.0
|
|
28
|
+
q_int4 = torch.clamp(torch.round(tensor / scale), -7, 7).to(torch.int8)
|
|
29
|
+
return q_int4, scale
|
|
30
|
+
|
|
31
|
+
def dequantize_tensor_int4(q_tensor: torch.Tensor, scale: float) -> torch.Tensor:
|
|
32
|
+
return q_tensor.to(torch.float32) * scale
|
|
33
|
+
|
|
34
|
+
class QuantizedLinear(nn.Module):
|
|
35
|
+
"""
|
|
36
|
+
Edge-optimized Linear layer holding INT8/INT4 weights with runtime scaling.
|
|
37
|
+
"""
|
|
38
|
+
def __init__(self, in_features: int, out_features: int, bits: int = 8):
|
|
39
|
+
super().__init__()
|
|
40
|
+
self.in_features = in_features
|
|
41
|
+
self.out_features = out_features
|
|
42
|
+
self.bits = bits
|
|
43
|
+
self.register_buffer("weight_quantized", torch.zeros(out_features, in_features, dtype=torch.int8))
|
|
44
|
+
self.register_buffer("scale", torch.tensor(1.0))
|
|
45
|
+
self.bias = nn.Parameter(torch.zeros(out_features))
|
|
46
|
+
|
|
47
|
+
@classmethod
|
|
48
|
+
def from_float(cls, linear_layer: nn.Linear, bits: int = 8) -> "QuantizedLinear":
|
|
49
|
+
q_layer = cls(linear_layer.in_features, linear_layer.out_features, bits=bits)
|
|
50
|
+
if bits == 8:
|
|
51
|
+
q_w, s = quantize_tensor_int8(linear_layer.weight.data)
|
|
52
|
+
elif bits == 4:
|
|
53
|
+
q_w, s = quantize_tensor_int4(linear_layer.weight.data)
|
|
54
|
+
else:
|
|
55
|
+
raise ValueError(f"Unsupported bit width: {bits}")
|
|
56
|
+
|
|
57
|
+
q_layer.weight_quantized.copy_(q_w)
|
|
58
|
+
q_layer.scale.copy_(torch.tensor(s))
|
|
59
|
+
if linear_layer.bias is not None:
|
|
60
|
+
q_layer.bias.data.copy_(linear_layer.bias.data)
|
|
61
|
+
return q_layer
|
|
62
|
+
|
|
63
|
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
|
64
|
+
w_float = self.weight_quantized.to(torch.float32) * self.scale
|
|
65
|
+
return torch.matmul(x, w_float.t()) + self.bias
|
|
66
|
+
|
nova/compute/__init__.py
ADDED
nova/compute/ara.py
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from typing import Tuple
|
|
4
|
+
|
|
5
|
+
class AdaptiveResourceAllocator(nn.Module):
|
|
6
|
+
"""
|
|
7
|
+
Adaptive Resource Allocation (ARA) Policy (PRD Section 5.11):
|
|
8
|
+
c*_t = argmax_{c in {0, 1, 2}} [ E(Delta Q_t | c) - lambda_cost * C(c) ]
|
|
9
|
+
Dynamically routes compute budget (refinement passes) based on novelty and uncertainty.
|
|
10
|
+
"""
|
|
11
|
+
def __init__(self, lambda_cost: float = 0.25):
|
|
12
|
+
super().__init__()
|
|
13
|
+
self.lambda_cost = lambda_cost
|
|
14
|
+
# Simple policy predictor: maps [novelty, uncertainty] -> predicted quality gain
|
|
15
|
+
self.gain_predictor = nn.Sequential(
|
|
16
|
+
nn.Linear(2, 8),
|
|
17
|
+
nn.Tanh(),
|
|
18
|
+
nn.Linear(8, 3) # predicted gains for c = 0, 1, 2
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
def choose_action(self, novelty: float, uncertainty: float) -> Tuple[int, float]:
|
|
22
|
+
"""
|
|
23
|
+
Chooses extra computation steps c* in {0, 1, 2}.
|
|
24
|
+
Returns (action, net_expected_value).
|
|
25
|
+
"""
|
|
26
|
+
# Feature input
|
|
27
|
+
x = torch.tensor([[novelty, uncertainty]], dtype=torch.float32)
|
|
28
|
+
with torch.no_grad():
|
|
29
|
+
gains = self.gain_predictor(x).squeeze(0) # (3,)
|
|
30
|
+
# Costs: C(c) = c
|
|
31
|
+
costs = torch.tensor([0.0, 1.0, 2.0], dtype=torch.float32)
|
|
32
|
+
net_values = gains + torch.tensor([0.0, novelty * 0.8, (novelty + uncertainty) * 1.2]) - self.lambda_cost * costs
|
|
33
|
+
best_action = int(torch.argmax(net_values).item())
|
|
34
|
+
best_value = float(net_values[best_action].item())
|
|
35
|
+
|
|
36
|
+
return best_action, best_value
|
|
37
|
+
|
nova/core/__init__.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
from nova.core.state import StateField, ControllerState
|
|
2
|
+
from nova.core.validation import check_finite, check_shape, ValidationError
|
|
3
|
+
from nova.core.tensor_ops import (
|
|
4
|
+
scale_normalized_residual,
|
|
5
|
+
gradient_conflict,
|
|
6
|
+
check_contraction_bound
|
|
7
|
+
)
|
|
8
|
+
|
|
9
|
+
__all__ = [
|
|
10
|
+
"StateField",
|
|
11
|
+
"ControllerState",
|
|
12
|
+
"check_finite",
|
|
13
|
+
"check_shape",
|
|
14
|
+
"ValidationError",
|
|
15
|
+
"scale_normalized_residual",
|
|
16
|
+
"gradient_conflict",
|
|
17
|
+
"check_contraction_bound"
|
|
18
|
+
]
|
|
19
|
+
|