AbstractIntegratedModule 1.3.4__tar.gz → 1.3.6__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.
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractIntegratedModule.egg-info/PKG-INFO +1 -1
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractIntegratedModule.py +395 -53
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractOptimizedModules.c +6 -6
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/PKG-INFO +1 -1
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/pyproject.toml +1 -1
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/setup.py +1 -1
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractIntegratedModule.egg-info/SOURCES.txt +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractIntegratedModule.egg-info/dependency_links.txt +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractIntegratedModule.egg-info/requires.txt +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractIntegratedModule.egg-info/top_level.txt +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractOptimizedModules.pyx +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/MANIFEST.in +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/README.md +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/Cargo.toml +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/pyproject.toml +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/src/lib.rs +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/target/debug/build/libsqlite3-sys-ed07b882cd2aa5e2/out/bindgen.rs +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/target/debug/build/serde_core-ebc15f2e9cad7f5f/out/private.rs +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/target/debug/build/target-lexicon-08527f45de28143d/out/host.rs +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/target/release/build/libsqlite3-sys-bf0400df4523274c/out/bindgen.rs +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/target/release/build/serde_core-5cdb76131825e4af/out/private.rs +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/target/release/build/target-lexicon-43eb95a0588bf457/out/host.rs +0 -0
- {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/setup.cfg +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: AbstractIntegratedModule
|
|
3
|
-
Version: 1.3.
|
|
3
|
+
Version: 1.3.6
|
|
4
4
|
Summary: IntegratedPipeline Specifically provide a Framework to build Stateful continual learning Machine Learning Models optimized for Edge devices (ARM64).
|
|
5
5
|
Author: Micro-Novelty
|
|
6
6
|
Author-email: Micro-Novelty <hernikpuspita5@gmail.com>
|
{abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractIntegratedModule.py
RENAMED
|
@@ -2528,6 +2528,270 @@ class TargetMemoryMixin:
|
|
|
2528
2528
|
return False
|
|
2529
2529
|
return True
|
|
2530
2530
|
|
|
2531
|
+
# ======================================================================
|
|
2532
|
+
# JEPA PRETRAINING (replaces the broken STDP pretrain phase)
|
|
2533
|
+
# Needs: copy, np, LIFDenseLayer, SpikeDropout, ReadoutLayer, SNNNetwork,
|
|
2534
|
+
# Adam, mse_loss, SNNUtility, ThresholdHomeostasis (all defined above it).
|
|
2535
|
+
# ======================================================================
|
|
2536
|
+
import copy
|
|
2537
|
+
|
|
2538
|
+
|
|
2539
|
+
def _jepa_layer_norm(z, eps=1e-5):
|
|
2540
|
+
mu = z.mean(axis=1, keepdims=True)
|
|
2541
|
+
var = z.var(axis=1, keepdims=True)
|
|
2542
|
+
return (z - mu) / np.sqrt(var + eps)
|
|
2543
|
+
|
|
2544
|
+
|
|
2545
|
+
def _jepa_var_cov_reg(z, gamma=1.0, eps=1e-4):
|
|
2546
|
+
"""VICReg-style anti-collapse terms on a (B, D) batch.
|
|
2547
|
+
Returns (v_loss, c_loss, grad_v, grad_c), grads wrt z."""
|
|
2548
|
+
B, D = z.shape
|
|
2549
|
+
zc = z - z.mean(axis=0, keepdims=True)
|
|
2550
|
+
|
|
2551
|
+
std = np.sqrt(zc.var(axis=0) + eps)
|
|
2552
|
+
v_loss = np.mean(np.maximum(0.0, gamma - std))
|
|
2553
|
+
active = (std < gamma).astype(z.dtype)
|
|
2554
|
+
grad_v = -(active / D)[None, :] * zc / (B * std[None, :])
|
|
2555
|
+
|
|
2556
|
+
cov = zc.T @ zc / (B - 1)
|
|
2557
|
+
off = cov - np.diag(np.diag(cov))
|
|
2558
|
+
c_loss = np.sum(off ** 2) / D
|
|
2559
|
+
g = zc @ (4.0 * off / D) / (B - 1)
|
|
2560
|
+
grad_c = g - g.mean(axis=0, keepdims=True)
|
|
2561
|
+
return v_loss, c_loss, grad_v, grad_c
|
|
2562
|
+
|
|
2563
|
+
|
|
2564
|
+
def _jepa_effective_rank(z, eps=1e-12):
|
|
2565
|
+
"""exp(entropy of singular values): ~1 = collapsed, ~D = fully spread."""
|
|
2566
|
+
s = np.linalg.svd(z - z.mean(axis=0), compute_uv=False)
|
|
2567
|
+
p = s / (s.sum() + eps)
|
|
2568
|
+
return float(np.exp(-np.sum(p * np.log(p + eps))))
|
|
2569
|
+
|
|
2570
|
+
|
|
2571
|
+
class _JEPALinear:
|
|
2572
|
+
"""Tiny dense layer exposing parameters() -> (params, grads) so Adam / clip work."""
|
|
2573
|
+
def __init__(self, n_in, n_out, rng):
|
|
2574
|
+
self.W = rng.normal(0.0, np.sqrt(2.0 / n_in), size=(n_in, n_out))
|
|
2575
|
+
self.b = np.zeros(n_out)
|
|
2576
|
+
self.grad_W = np.zeros_like(self.W)
|
|
2577
|
+
self.grad_b = np.zeros_like(self.b)
|
|
2578
|
+
self._x = None
|
|
2579
|
+
|
|
2580
|
+
def forward(self, x):
|
|
2581
|
+
self._x = x
|
|
2582
|
+
return x @ self.W + self.b
|
|
2583
|
+
|
|
2584
|
+
def backward(self, g):
|
|
2585
|
+
self.grad_W = self._x.T @ g
|
|
2586
|
+
self.grad_b = g.sum(axis=0)
|
|
2587
|
+
return g @ self.W.T
|
|
2588
|
+
|
|
2589
|
+
def parameters(self):
|
|
2590
|
+
return {"W": self.W, "b": self.b}, {"W": self.grad_W, "b": self.grad_b}
|
|
2591
|
+
|
|
2592
|
+
|
|
2593
|
+
class _JEPAPredictor:
|
|
2594
|
+
"""[context embedding, mask condition] -> ReLU hidden -> predicted target embedding."""
|
|
2595
|
+
def __init__(self, emb_dim, cond_dim, hidden, rng):
|
|
2596
|
+
self.emb_dim = emb_dim
|
|
2597
|
+
self.fc1 = _JEPALinear(emb_dim + cond_dim, hidden, rng)
|
|
2598
|
+
self.fc2 = _JEPALinear(hidden, emb_dim, rng)
|
|
2599
|
+
self.layers = [self.fc1, self.fc2]
|
|
2600
|
+
self._relu = None
|
|
2601
|
+
|
|
2602
|
+
def forward(self, z, cond):
|
|
2603
|
+
h = self.fc1.forward(np.concatenate([z, cond], axis=1))
|
|
2604
|
+
self._relu = h > 0
|
|
2605
|
+
return self.fc2.forward(h * self._relu)
|
|
2606
|
+
|
|
2607
|
+
def backward(self, g_out):
|
|
2608
|
+
g = self.fc2.backward(g_out) * self._relu
|
|
2609
|
+
return self.fc1.backward(g)[:, :self.emb_dim] # gradient wrt the context embedding only
|
|
2610
|
+
|
|
2611
|
+
|
|
2612
|
+
def _jepa_group_ids(n_in, n_groups, rng, mode='contiguous'):
|
|
2613
|
+
"""feature index -> group id, shape (n_in,).
|
|
2614
|
+
'contiguous': neighbouring columns share a group (right for flattened (W, F)
|
|
2615
|
+
time-series windows or any ordered features).
|
|
2616
|
+
'random' : columns are assigned to groups at random (right for TF-IDF /
|
|
2617
|
+
bag-of-words, where column order means nothing)."""
|
|
2618
|
+
G = int(min(n_groups, n_in))
|
|
2619
|
+
if G < 2:
|
|
2620
|
+
raise ValueError('[>] JEPA needs at least 2 feature groups (n_in >= 2)')
|
|
2621
|
+
gid = np.concatenate([np.full(len(c), g) for g, c in enumerate(np.array_split(np.arange(n_in), G))])
|
|
2622
|
+
if mode == 'random':
|
|
2623
|
+
gid = rng.permutation(gid)
|
|
2624
|
+
elif mode != 'contiguous':
|
|
2625
|
+
raise ValueError("group_mode must be 'contiguous' or 'random'")
|
|
2626
|
+
return gid, G
|
|
2627
|
+
|
|
2628
|
+
|
|
2629
|
+
def _jepa_block_masks(B, G, rng, K=2, min_size=1, max_size=None, max_hidden=0.6):
|
|
2630
|
+
"""K target blocks per sample -> (K, B, G) bool. A block is a run of 1..max_size
|
|
2631
|
+
neighbouring groups. A sample is redrawn (up to 10x) if the union of its K
|
|
2632
|
+
blocks hides more than `max_hidden` of the groups."""
|
|
2633
|
+
max_size = max(min_size, max_size if max_size is not None else G // 4)
|
|
2634
|
+
out = np.zeros((K, B, G), dtype=bool)
|
|
2635
|
+
for i in range(B):
|
|
2636
|
+
for _ in range(10):
|
|
2637
|
+
m = np.zeros((K, G), dtype=bool)
|
|
2638
|
+
for k in range(K):
|
|
2639
|
+
s = int(rng.integers(min_size, max_size + 1))
|
|
2640
|
+
a = int(rng.integers(0, G - s + 1))
|
|
2641
|
+
m[k, a:a + s] = True
|
|
2642
|
+
if m.any(axis=0).mean() <= max_hidden:
|
|
2643
|
+
break
|
|
2644
|
+
out[:, i] = m
|
|
2645
|
+
return out
|
|
2646
|
+
|
|
2647
|
+
|
|
2648
|
+
def jepa_pretrain(layer, encoder, X_unlabeled, rng, n_steps=200, batch_size=32,
|
|
2649
|
+
emb_dim=32, n_groups=8, n_targets=2, pred_hidden=128,
|
|
2650
|
+
lr=2e-3, lam_var=1.0, lam_cov=1.0,
|
|
2651
|
+
ema_start=0.96, ema_end=0.998, dropout=0.1,
|
|
2652
|
+
group_mode='contiguous', max_grad_norm=5.0,
|
|
2653
|
+
homeostasis='auto', homeostasis_every=20, revive_dead=True,
|
|
2654
|
+
verbose=True):
|
|
2655
|
+
"""
|
|
2656
|
+
Label-free pretraining of ONE LIFDenseLayer with a JEPA objective.
|
|
2657
|
+
Drop-in replacement for stdp_pretrain(layer, encoder, X_unlabeled, rng, n_steps, batch_size).
|
|
2658
|
+
|
|
2659
|
+
How it works
|
|
2660
|
+
* The input features are split into `n_groups` groups. Each step, `n_targets`
|
|
2661
|
+
blocks of neighbouring groups are chosen per sample.
|
|
2662
|
+
* context encoder (trainable, wraps `layer` itself): sees the spikes with ALL
|
|
2663
|
+
chosen blocks hidden.
|
|
2664
|
+
* target encoder (EMA copy, no grad): sees the spikes of ONE block.
|
|
2665
|
+
* predictor : from the context embedding + which block/union is hidden,
|
|
2666
|
+
it predicts the target embedding. Loss = MSE + variance/covariance terms
|
|
2667
|
+
so the embedding cannot collapse.
|
|
2668
|
+
* Spikes are encoded ONCE per step and masked in spike space.
|
|
2669
|
+
|
|
2670
|
+
Only `layer` is kept: its W, b and threshold are updated IN PLACE. The readout,
|
|
2671
|
+
predictor and EMA target are thrown away afterwards, so the layer plugs straight
|
|
2672
|
+
into build_snn_network(...) with no shape constraint (n_in need not equal n_hidden).
|
|
2673
|
+
|
|
2674
|
+
homeostasis : 'auto' (ThresholdHomeostasis, target rate 0.15, stepped every
|
|
2675
|
+
`homeostasis_every` steps), None (off), or your own instance.
|
|
2676
|
+
revive_dead : after training, neurons that never fire (<1e-4) or fire at every step
|
|
2677
|
+
(>0.99) are re-initialised. JEPA's surrogate gradient cannot bring a
|
|
2678
|
+
silent neuron back, and without this ~20% of the layer was lost in tests.
|
|
2679
|
+
|
|
2680
|
+
X_unlabeled : (N, n_in) array, values in [0, 1] (the Poisson encoder clips anyway).
|
|
2681
|
+
Returns a dict: history (list of per-log dicts), effective_rank, emb_dim, revived.
|
|
2682
|
+
"""
|
|
2683
|
+
X = np.asarray(X_unlabeled, dtype=np.float64)
|
|
2684
|
+
if X.ndim > 2:
|
|
2685
|
+
X = X.reshape(X.shape[0], -1)
|
|
2686
|
+
if X.ndim != 2 or X.shape[1] != layer.in_features:
|
|
2687
|
+
raise ValueError(f'[>] JEPA pretrain: X must be (N, {layer.in_features}), got {X.shape}')
|
|
2688
|
+
n = X.shape[0]
|
|
2689
|
+
if n < 8:
|
|
2690
|
+
print(f'[⚠️] JEPA pretrain skipped: only {n} unlabeled samples (need >= 8)')
|
|
2691
|
+
return {'history': [], 'effective_rank': None, 'emb_dim': emb_dim}
|
|
2692
|
+
batch_size = int(min(max(batch_size, 8), n))
|
|
2693
|
+
|
|
2694
|
+
gid, G = _jepa_group_ids(layer.in_features, n_groups, rng, group_mode)
|
|
2695
|
+
K = int(n_targets)
|
|
2696
|
+
|
|
2697
|
+
readout = ReadoutLayer(layer.out_features, emb_dim, decay=0.95, rng=rng)
|
|
2698
|
+
context = SNNNetwork([layer, SpikeDropout(p=dropout, rng=rng), readout],
|
|
2699
|
+
readout_reduction='mean', rng=rng)
|
|
2700
|
+
target = copy.deepcopy(context) # EMA copy: starts identical, never gets gradients
|
|
2701
|
+
target.eval()
|
|
2702
|
+
predictor = _JEPAPredictor(emb_dim, 2 * G, pred_hidden, rng)
|
|
2703
|
+
|
|
2704
|
+
trainable = context.layers + predictor.layers
|
|
2705
|
+
opt = Adam(lr=lr, weight_decay=1e-5)
|
|
2706
|
+
util = SNNUtility()
|
|
2707
|
+
if isinstance(homeostasis, str) and homeostasis == 'auto':
|
|
2708
|
+
homeostasis = ThresholdHomeostasis(target_rate=0.15, adjust_rate=0.05)
|
|
2709
|
+
|
|
2710
|
+
history, acc = [], []
|
|
2711
|
+
log_every = max(n_steps // 5, 1)
|
|
2712
|
+
for step in range(n_steps):
|
|
2713
|
+
xb = X[rng.integers(0, n, size=batch_size)]
|
|
2714
|
+
B = xb.shape[0]
|
|
2715
|
+
mom = ema_start + (ema_end - ema_start) * step / max(n_steps - 1, 1)
|
|
2716
|
+
|
|
2717
|
+
pm_k = _jepa_block_masks(B, G, rng, K) # (K, B, G)
|
|
2718
|
+
pm_u = pm_k.any(axis=0) # (B, G) union
|
|
2719
|
+
pix_u = pm_u[:, gid] # (B, n_in)
|
|
2720
|
+
|
|
2721
|
+
spk = encoder.encode(xb) # (T, B, n_in): ONE Poisson draw
|
|
2722
|
+
spk_ctx = np.where(pix_u[None], 0.0, spk) # hide every chosen block
|
|
2723
|
+
|
|
2724
|
+
target.eval()
|
|
2725
|
+
t = [_jepa_layer_norm(target.forward(np.where(pm_k[k][:, gid][None], spk, 0.0)))
|
|
2726
|
+
for k in range(K)]
|
|
2727
|
+
t = np.concatenate(t, axis=0) # (K*B, D)
|
|
2728
|
+
|
|
2729
|
+
context.train()
|
|
2730
|
+
z = context.forward(spk_ctx) # (B, D)
|
|
2731
|
+
rate = float(layer._cache['spike_hist'].mean())
|
|
2732
|
+
cond = np.concatenate([pm_k.reshape(K * B, G), np.tile(pm_u, (K, 1))],
|
|
2733
|
+
axis=1).astype(np.float64)
|
|
2734
|
+
z_hat = predictor.forward(np.tile(z, (K, 1)), cond)
|
|
2735
|
+
|
|
2736
|
+
loss_pred, g_hat = mse_loss(z_hat, t)
|
|
2737
|
+
v_loss, c_loss, g_v, g_c = _jepa_var_cov_reg(z)
|
|
2738
|
+
|
|
2739
|
+
opt.zero_grad(trainable)
|
|
2740
|
+
g_z = predictor.backward(g_hat).reshape(K, B, -1).sum(axis=0)
|
|
2741
|
+
g_z = g_z + lam_var * g_v + lam_cov * g_c
|
|
2742
|
+
context.backward(g_z) # BPTT through the SNN
|
|
2743
|
+
util.clip_grad_norm(trainable, max_grad_norm)
|
|
2744
|
+
opt.step(trainable)
|
|
2745
|
+
|
|
2746
|
+
# EMA target <- context
|
|
2747
|
+
for lt, lc in zip(target.layers, context.layers):
|
|
2748
|
+
pt, _ = lt.parameters()
|
|
2749
|
+
pc, _ = lc.parameters()
|
|
2750
|
+
for k_ in pt:
|
|
2751
|
+
pt[k_] *= mom
|
|
2752
|
+
pt[k_] += (1.0 - mom) * pc[k_]
|
|
2753
|
+
if hasattr(lc, 'threshold'):
|
|
2754
|
+
lt.threshold = lc.threshold
|
|
2755
|
+
|
|
2756
|
+
if homeostasis is not None and (step + 1) % homeostasis_every == 0:
|
|
2757
|
+
homeostasis.step([layer])
|
|
2758
|
+
|
|
2759
|
+
acc.append((loss_pred + lam_var * v_loss + lam_cov * c_loss,
|
|
2760
|
+
loss_pred, v_loss, c_loss, rate, float(z.std(axis=0).mean())))
|
|
2761
|
+
if (step + 1) % log_every == 0 or step == n_steps - 1:
|
|
2762
|
+
a = np.mean(acc, axis=0)
|
|
2763
|
+
acc = []
|
|
2764
|
+
row = dict(step=step + 1, loss=a[0], pred=a[1], var=a[2], cov=a[3], rate=a[4], z_std=a[5])
|
|
2765
|
+
history.append(row)
|
|
2766
|
+
if verbose:
|
|
2767
|
+
print(f"[JEPA] step {step + 1:4d}/{n_steps} || loss={a[0]:.4f} pred={a[1]:.4f} "
|
|
2768
|
+
f"var={a[2]:.3f} cov={a[3]:.3f} || rate={a[4]:.3f} z_std={a[5]:.3f}")
|
|
2769
|
+
|
|
2770
|
+
n_revived = 0
|
|
2771
|
+
if revive_dead:
|
|
2772
|
+
layer.forward(encoder.encode(X[:min(256, n)]))
|
|
2773
|
+
r = layer._cache['spike_hist'].mean(axis=(0, 1))
|
|
2774
|
+
bad = np.where((r < 1e-4) | (r > 0.99))[0]
|
|
2775
|
+
if len(bad):
|
|
2776
|
+
lim = np.sqrt(1.0 / layer.in_features)
|
|
2777
|
+
layer.W[:, bad] = rng.uniform(-lim, lim, size=(layer.in_features, len(bad)))
|
|
2778
|
+
if layer.use_bias:
|
|
2779
|
+
layer.b[bad] = 0.0
|
|
2780
|
+
n_revived = int(len(bad))
|
|
2781
|
+
|
|
2782
|
+
context.eval()
|
|
2783
|
+
probe = X[:min(256, n)]
|
|
2784
|
+
eff_rank = _jepa_effective_rank(context.forward(encoder.encode(probe)))
|
|
2785
|
+
context.train()
|
|
2786
|
+
if verbose:
|
|
2787
|
+
print(f"[JEPA] hidden layer pretrained || effective rank {eff_rank:.1f} / {emb_dim} "
|
|
2788
|
+
f"|| threshold={layer.threshold:.3f} || re-initialised {n_revived}/{layer.out_features} dead/saturated neurons")
|
|
2789
|
+
if eff_rank < 2.0:
|
|
2790
|
+
print('[⚠️] JEPA embedding looks collapsed (effective rank < 2): '
|
|
2791
|
+
'raise lam_var, lower lr, or check that X has real variance.')
|
|
2792
|
+
return {'history': history, 'effective_rank': eff_rank, 'emb_dim': emb_dim, 'revived': n_revived}
|
|
2793
|
+
|
|
2794
|
+
|
|
2531
2795
|
class Transformer(TargetMemoryMixin):
|
|
2532
2796
|
def __init__(self, vocab_size, d_model=8, n_heads=2, num_classes=7, learning_rate=0.01,
|
|
2533
2797
|
attn_dropout=0.0, ffn_dropout=0.0, weight_decay=1e-4,
|
|
@@ -4905,6 +5169,10 @@ class MLP:
|
|
|
4905
5169
|
def continuous_predictive_correction(self, manager, prob, predicted_index, AME=None, anisotropy=None):
|
|
4906
5170
|
eps = 1e-5
|
|
4907
5171
|
label_map = manager.label_map
|
|
5172
|
+
if label_map is None:
|
|
5173
|
+
print('[>] Label map is None, returning probabilities as is...')
|
|
5174
|
+
return prob
|
|
5175
|
+
|
|
4908
5176
|
n_classes = len(label_map)
|
|
4909
5177
|
manager._repair_class_counters(n_classes) # guarantees valid 1-D counters
|
|
4910
5178
|
|
|
@@ -8619,16 +8887,20 @@ class ModelStorage:
|
|
|
8619
8887
|
|
|
8620
8888
|
# dynamic corruption check
|
|
8621
8889
|
if isinstance(value, list):
|
|
8622
|
-
|
|
8623
|
-
|
|
8624
|
-
|
|
8625
|
-
f'
|
|
8626
|
-
|
|
8627
|
-
|
|
8628
|
-
|
|
8629
|
-
|
|
8630
|
-
|
|
8631
|
-
f'
|
|
8890
|
+
try:
|
|
8891
|
+
arr = np.asarray(value)
|
|
8892
|
+
if arr.ndim > 2:
|
|
8893
|
+
print(f'[!] Corrupted value for key {key} '
|
|
8894
|
+
f'(ndim={arr.ndim}), removing')
|
|
8895
|
+
continue
|
|
8896
|
+
|
|
8897
|
+
if num_classes > 0 and arr.ndim == 1 and \
|
|
8898
|
+
len(arr) not in (num_classes, num_classes * 2):
|
|
8899
|
+
print(f'[!] Suspicious shape for key {key}: '
|
|
8900
|
+
f'{arr.shape}, expected {num_classes} — removing')
|
|
8901
|
+
continue
|
|
8902
|
+
except Exception as e:
|
|
8903
|
+
print(f'[>] Cannot determine value: {e}')
|
|
8632
8904
|
continue
|
|
8633
8905
|
|
|
8634
8906
|
# None values — skipped silently
|
|
@@ -13176,6 +13448,7 @@ class IntegratedPipeline:
|
|
|
13176
13448
|
self.peer_assistance_threshold = 0.0
|
|
13177
13449
|
self.n_hash_dim = 2**8
|
|
13178
13450
|
self.agent_id = random.randint(0, 10000)
|
|
13451
|
+
self._prob_save_count = 0
|
|
13179
13452
|
|
|
13180
13453
|
self.vocab = {}
|
|
13181
13454
|
self.cache = {}
|
|
@@ -13701,7 +13974,7 @@ class IntegratedPipeline:
|
|
|
13701
13974
|
def _validate_dict_memory(self, memory: dict, num_classes: int) -> tuple:
|
|
13702
13975
|
"""Validate dict memory — expected primary format."""
|
|
13703
13976
|
if not memory:
|
|
13704
|
-
return (False, "Empty dict (no memory
|
|
13977
|
+
return (False, "Empty dict (no memory)", None)
|
|
13705
13978
|
|
|
13706
13979
|
valid_keys = {'TW', 'MW', 'TP', 'MP', 'TA', 'local',
|
|
13707
13980
|
'_cached_probs', '_data'}
|
|
@@ -15405,10 +15678,20 @@ class IntegratedPipeline:
|
|
|
15405
15678
|
|
|
15406
15679
|
try:
|
|
15407
15680
|
if needs_prediction:
|
|
15408
|
-
|
|
15409
|
-
|
|
15681
|
+
if len(needs_prediction) <= len(batch_input_ids):
|
|
15682
|
+
fresh_input_ids = batch_input_ids[needs_prediction]
|
|
15683
|
+
else:
|
|
15684
|
+
fresh_input_ids = batch_input_ids[needs_prediction[len(batch_input_ids) - 1]]
|
|
15685
|
+
if len(needs_prediction) <= len(batch_X):
|
|
15686
|
+
fresh_X = batch_X[needs_prediction]
|
|
15687
|
+
else:
|
|
15688
|
+
fresh_X = batch_X[needs_prediction[len(batch_X) - 1]]
|
|
15689
|
+
|
|
15690
|
+
try:
|
|
15691
|
+
transformer_pred, fresh_probs, attn_weights = self.model2.predict(fresh_input_ids, embedded=True)
|
|
15692
|
+
except:
|
|
15693
|
+
transformer_pred, fresh_probs, attn_weights = self.model2.predict(fresh_input_ids, embedded=False)
|
|
15410
15694
|
|
|
15411
|
-
transformer_pred, fresh_probs, attn_weights = self.model2.predict(fresh_input_ids)
|
|
15412
15695
|
mlp_pred = self.model3.forward(fresh_X)
|
|
15413
15696
|
|
|
15414
15697
|
# coerce indices to int
|
|
@@ -15418,8 +15701,12 @@ class IntegratedPipeline:
|
|
|
15418
15701
|
for i, idx in enumerate(needs_prediction):
|
|
15419
15702
|
|
|
15420
15703
|
# validate indices in range before use
|
|
15421
|
-
|
|
15422
|
-
|
|
15704
|
+
if i < len(mlp_pred_indices) and i < len(trans_pred_indices):
|
|
15705
|
+
mlp_cls = int(mlp_pred_indices[i])
|
|
15706
|
+
trans_cls = int(trans_pred_indices[i])
|
|
15707
|
+
else:
|
|
15708
|
+
mlp_cls = int(mlp_pred_indices[len(mlp_pred_indices) - 1])
|
|
15709
|
+
trans_cls = int(trans_pred_indices[len(trans_pred_indices) - 1])
|
|
15423
15710
|
|
|
15424
15711
|
mlp_cls = mlp_cls if 0 <= mlp_cls < num_classes else 0
|
|
15425
15712
|
trans_cls = trans_cls if 0 <= trans_cls < num_classes else 0
|
|
@@ -15449,12 +15736,13 @@ class IntegratedPipeline:
|
|
|
15449
15736
|
|
|
15450
15737
|
# instance-level save counter, not local idx_total
|
|
15451
15738
|
if getattr(self, '_prob_save_count', 0) < 2:
|
|
15452
|
-
|
|
15739
|
+
if i < len(fresh_input_ids) and i < len(fresh_X) and idx < len(batch_probs):
|
|
15740
|
+
self.modular_probability_saving(
|
|
15453
15741
|
fresh_input_ids[i:i+1],
|
|
15454
15742
|
fresh_X[i:i+1],
|
|
15455
15743
|
np.array([batch_probs[idx]])
|
|
15456
|
-
|
|
15457
|
-
|
|
15744
|
+
)
|
|
15745
|
+
self._prob_save_count = getattr(self, '_prob_save_count', 0) + 1
|
|
15458
15746
|
|
|
15459
15747
|
else:
|
|
15460
15748
|
raise Warning('[!] Data is None before batching!')
|
|
@@ -15492,6 +15780,7 @@ class IntegratedPipeline:
|
|
|
15492
15780
|
return valid_probs
|
|
15493
15781
|
except Exception as e:
|
|
15494
15782
|
print(f'[⚠️] Error occured in probabilities batching: {e}')
|
|
15783
|
+
traceback.print_exc()
|
|
15495
15784
|
return None
|
|
15496
15785
|
|
|
15497
15786
|
|
|
@@ -18239,23 +18528,29 @@ class AccurateAnswerCache:
|
|
|
18239
18528
|
'added_at' : datetime.now().isoformat(),
|
|
18240
18529
|
'last_hit' : None
|
|
18241
18530
|
}
|
|
18242
|
-
|
|
18243
|
-
|
|
18244
|
-
|
|
18531
|
+
if self.cache is not None:
|
|
18532
|
+
if isinstance(self.cache, dict):
|
|
18533
|
+
self.cache[key] = entry
|
|
18534
|
+
print(f'[💎] Verified answer successfully cached: {prediction} (source={source})')
|
|
18535
|
+
else:
|
|
18536
|
+
print(f'[!] cache is not a dictionary! possible corruption during memory retrieval!')
|
|
18537
|
+
|
|
18245
18538
|
# maintain O(1) exact match index
|
|
18246
18539
|
if ids_hash is not None:
|
|
18247
18540
|
self.exact_hash_index[ids_hash] = key
|
|
18248
18541
|
|
|
18249
|
-
if
|
|
18250
|
-
self.
|
|
18542
|
+
if self.cache is not None and isinstance(self.cache, dict):
|
|
18543
|
+
if len(self.cache) > self.max_size:
|
|
18544
|
+
self._evict_lru()
|
|
18251
18545
|
|
|
18252
|
-
|
|
18253
|
-
|
|
18254
|
-
|
|
18255
|
-
|
|
18256
|
-
|
|
18546
|
+
if self.cache is not None and isinstance(self.cache, dict):
|
|
18547
|
+
if self.cache[key]['source'] != 'automatic_verified' and not source.startswith('automatic'):
|
|
18548
|
+
self.pipeline.storage.save_accurate_cache_dict(self.memory_name, self.cache)
|
|
18549
|
+
|
|
18257
18550
|
except Exception as e:
|
|
18258
18551
|
print(f'[!] Failed to add samples and answer to Answer cache due to: {e}')
|
|
18552
|
+
|
|
18553
|
+
|
|
18259
18554
|
|
|
18260
18555
|
|
|
18261
18556
|
def lookup(self, x_mlp, input_ids=None):
|
|
@@ -19437,8 +19732,8 @@ class PipelineAsyncManager:
|
|
|
19437
19732
|
# Generate initial API key if enabled
|
|
19438
19733
|
if self.config.require_api_key:
|
|
19439
19734
|
self._default_api_key = api_key if api_key else self.api_key_manager.generate_key({'type': 'default'})
|
|
19440
|
-
print(f"[🔑] Default API Key: {self._default_api_key}")
|
|
19441
|
-
print("[!] Store
|
|
19735
|
+
print(f"[🔑] Default API Key used: {self._default_api_key}")
|
|
19736
|
+
print("[!] Store the key securely - it won't be shown again!")
|
|
19442
19737
|
|
|
19443
19738
|
self.state_file = state_file if state_file is not None else 'security_state.json'
|
|
19444
19739
|
self.admin_keys: Dict[str, dict] = {} # admin_token -> {role, created_at}
|
|
@@ -21504,12 +21799,41 @@ def initialize_snn_network(X=None, y=None, label_map=None, n_hidden=64, n_in=Non
|
|
|
21504
21799
|
print(f'[>] Error initializing SNN Network and hidden layer: {e}')
|
|
21505
21800
|
return None, None, None
|
|
21506
21801
|
|
|
21802
|
+
def infer_target_type(y=None, max_classes_ratio=0.05, max_unique_absolute=50):
|
|
21803
|
+
score = 0
|
|
21804
|
+
y_flat = None
|
|
21805
|
+
if y is not None:
|
|
21806
|
+
y = np.asarray(y)
|
|
21807
|
+
y_flat = y.flatten()
|
|
21808
|
+
|
|
21809
|
+
unique_vals = np.unique(y_flat)
|
|
21810
|
+
n_unique = len(unique_vals)
|
|
21811
|
+
n_samples = len(y_flat)
|
|
21812
|
+
|
|
21813
|
+
unique_ratio = n_unique / n_samples
|
|
21814
|
+
if n_unique > max_unique_absolute or unique_ratio > max_classes_ratio:
|
|
21815
|
+
score += 1
|
|
21816
|
+
|
|
21817
|
+
if y_flat is not None:
|
|
21818
|
+
if not np.all(np.equal(np.mod(y_flat, 1), 0)):
|
|
21819
|
+
score += 1
|
|
21820
|
+
|
|
21821
|
+
if score <= 1:
|
|
21822
|
+
return "classification"
|
|
21823
|
+
else:
|
|
21824
|
+
return "regression"
|
|
21825
|
+
|
|
21826
|
+
|
|
21827
|
+
|
|
21507
21828
|
def train_snn_network(X=None, y=None, net=None, hidden_layer=None, utility=None, task='classification', label_map=None,
|
|
21508
21829
|
epochs=50, batch_size=32, n_steps=20,
|
|
21509
21830
|
n_hidden=64, lr=2e-3, seed=0, pretrain_steps=200, unsupervised_stdp=False,
|
|
21510
|
-
random_state=42, ):
|
|
21831
|
+
random_state=42, jepa_pretrain_enabled=False, X_unlabeled=None, jepa_kwargs=None):
|
|
21511
21832
|
tracker = DiagnosticsTracker()
|
|
21512
21833
|
cache = {}
|
|
21834
|
+
if task is None or not isinstance(task, str):
|
|
21835
|
+
task = infer_target_type(y=y)
|
|
21836
|
+
|
|
21513
21837
|
reg = (task == 'regression')
|
|
21514
21838
|
if utility is None:
|
|
21515
21839
|
utility = SNNUtility()
|
|
@@ -21540,7 +21864,10 @@ def train_snn_network(X=None, y=None, net=None, hidden_layer=None, utility=None,
|
|
|
21540
21864
|
|
|
21541
21865
|
X_train, X_test, y_train, y_test, X_val, y_val = _prepare_train_val_split(X=X, y=y, random_state=random_state)
|
|
21542
21866
|
y_train_net = y_train
|
|
21543
|
-
|
|
21867
|
+
if label_map is not None:
|
|
21868
|
+
n_classes = max(len(label_map), int(y_train.max() + 1))
|
|
21869
|
+
else:
|
|
21870
|
+
n_classes = int(y_train.max() + 1)
|
|
21544
21871
|
|
|
21545
21872
|
n_in = X_train.shape[1]
|
|
21546
21873
|
if net is None or hidden_layer is None:
|
|
@@ -21554,19 +21881,21 @@ def train_snn_network(X=None, y=None, net=None, hidden_layer=None, utility=None,
|
|
|
21554
21881
|
homeostasis = ThresholdHomeostasis(target_rate=0.15, adjust_rate=0.05)
|
|
21555
21882
|
|
|
21556
21883
|
# ---- Phase 1: unsupervised STDP pretraining (labels NOT used) ----
|
|
21557
|
-
if unsupervised_stdp:
|
|
21558
|
-
|
|
21559
|
-
|
|
21560
|
-
|
|
21561
|
-
|
|
21562
|
-
|
|
21563
|
-
|
|
21564
|
-
|
|
21565
|
-
|
|
21566
|
-
|
|
21567
|
-
|
|
21568
|
-
|
|
21569
|
-
|
|
21884
|
+
if jepa_pretrain_enabled or unsupervised_stdp:
|
|
21885
|
+
X_pre = X_train
|
|
21886
|
+
if X_unlabeled is not None: # extra unlabeled rows: this is where JEPA pays off
|
|
21887
|
+
Xu = np.asarray(X_unlabeled, dtype=np.float64)
|
|
21888
|
+
Xu = Xu.reshape(len(Xu), -1)
|
|
21889
|
+
if reg:
|
|
21890
|
+
Xu = scale_x(Xu) # same train-stat [0,1] scaling as X_train
|
|
21891
|
+
X_pre = np.concatenate([X_train, Xu], axis=0)
|
|
21892
|
+
jp = dict(n_steps=pretrain_steps, batch_size=batch_size)
|
|
21893
|
+
jp.update(jepa_kwargs or {})
|
|
21894
|
+
jepa_info = jepa_pretrain(hidden_layer, encoder, X_pre, rng, **jp)
|
|
21895
|
+
per_neuron_rate = hidden_layer._cache["spike_hist"].mean(axis=(0, 1))
|
|
21896
|
+
print(f"[=] Dead neurons after JEPA: {(per_neuron_rate < 1e-4).sum()} / {len(per_neuron_rate)} || "
|
|
21897
|
+
f"rate min={per_neuron_rate.min():.3f} max={per_neuron_rate.max():.3f}")
|
|
21898
|
+
|
|
21570
21899
|
# ---- Phase 2: supervised BPTT fine-tuning of the whole network ----
|
|
21571
21900
|
for epoch in range(1, epochs + 1):
|
|
21572
21901
|
net.train()
|
|
@@ -21636,7 +21965,9 @@ def _snn_predict_regression(X, net, encoder, n_mc=20):
|
|
|
21636
21965
|
def snn_predict(X=None, y=None, task='classification', label_map=None, encoder=None, net=None, random_state=42, max_print_threshold=50):
|
|
21637
21966
|
utility = SNNUtility()
|
|
21638
21967
|
reverse_map = None
|
|
21639
|
-
|
|
21968
|
+
if task is None or not isinstance(task, str):
|
|
21969
|
+
task = infer_target_type(y=y)
|
|
21970
|
+
|
|
21640
21971
|
if X is not None and y is not None:
|
|
21641
21972
|
print(f"[🔍] Processing X and y samples for Spiking Neural Network...")
|
|
21642
21973
|
if isinstance(X, (str, np.str_)):
|
|
@@ -21889,13 +22220,14 @@ class PipelinePredictionManager:
|
|
|
21889
22220
|
trans_probs = None
|
|
21890
22221
|
attn_weights = None
|
|
21891
22222
|
use_embedded = True
|
|
22223
|
+
reverse_map=None
|
|
21892
22224
|
results = []
|
|
21893
22225
|
|
|
21894
22226
|
task = task.lower()
|
|
21895
22227
|
if task is None or task != 'classification' or task != 'regression':
|
|
21896
22228
|
task = self.pipeline.infer_target_type(self.pipeline.vocab_size, y)
|
|
21897
22229
|
|
|
21898
|
-
if label_map and isinstance(label_map, dict):
|
|
22230
|
+
if label_map is not None and isinstance(label_map, dict):
|
|
21899
22231
|
reverse_map = {v: k for k, v in label_map.items()}
|
|
21900
22232
|
|
|
21901
22233
|
if self.pipeline.knn_tf is None:
|
|
@@ -23343,7 +23675,10 @@ class PipelinePredictionManager:
|
|
|
23343
23675
|
if self.pipeline.use_transformer and self.pipeline.model2 is not None:
|
|
23344
23676
|
print("\n[🔄] Running Transformer forward method (Transformer)")
|
|
23345
23677
|
if X is not None and y is not None:
|
|
23346
|
-
|
|
23678
|
+
if infer_y == 'classification':
|
|
23679
|
+
sequence_ids = self.pipeline._features_to_sequence(X_train)
|
|
23680
|
+
else:
|
|
23681
|
+
sequence_ids = X.copy()
|
|
23347
23682
|
else:
|
|
23348
23683
|
sequence_ids = self.pipeline.sequence_encoding(dataset, label_map=label_map)
|
|
23349
23684
|
|
|
@@ -23432,8 +23767,13 @@ class PipelinePredictionManager:
|
|
|
23432
23767
|
|
|
23433
23768
|
# Validate all MLP predictions at once
|
|
23434
23769
|
mlp_pred_indices = np.argmax(mlp_probs, axis=1)
|
|
23435
|
-
if num_classes
|
|
23436
|
-
|
|
23770
|
+
if num_classes is None:
|
|
23771
|
+
if y is not None and len(y) > 1:
|
|
23772
|
+
num_classes = int(np.max(y)) + 1
|
|
23773
|
+
if label_map is not None:
|
|
23774
|
+
num_classes = len(label_map)
|
|
23775
|
+
else:
|
|
23776
|
+
num_classes = self.pipeline._get_num_classes(mlp_probs=mlp_probs)
|
|
23437
23777
|
|
|
23438
23778
|
valid_mask = mlp_pred_indices < num_classes
|
|
23439
23779
|
if not np.all(valid_mask):
|
|
@@ -23493,7 +23833,10 @@ class PipelinePredictionManager:
|
|
|
23493
23833
|
|
|
23494
23834
|
use_embedded = True
|
|
23495
23835
|
|
|
23496
|
-
|
|
23836
|
+
if X is not None:
|
|
23837
|
+
target_probs = self.pipeline.predict_proba(input_ids, X, type='Hybrid', embedded=use_embedded)
|
|
23838
|
+
else:
|
|
23839
|
+
target_probs = mlp_probs.copy()
|
|
23497
23840
|
else:
|
|
23498
23841
|
target_probs = mlp_probs.copy()
|
|
23499
23842
|
|
|
@@ -26632,4 +26975,3 @@ if __name__ == "__main__":
|
|
|
26632
26975
|
traceback.print_exc()
|
|
26633
26976
|
pass
|
|
26634
26977
|
|
|
26635
|
-
|
{abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractOptimizedModules.c
RENAMED
|
@@ -4,14 +4,14 @@
|
|
|
4
4
|
{
|
|
5
5
|
"distutils": {
|
|
6
6
|
"depends": [
|
|
7
|
-
"/tmp/build-env-
|
|
8
|
-
"/tmp/build-env-
|
|
9
|
-
"/tmp/build-env-
|
|
10
|
-
"/tmp/build-env-
|
|
11
|
-
"/tmp/build-env-
|
|
7
|
+
"/tmp/build-env-o0tc6imy/lib/python3.12/site-packages/numpy/_core/include/numpy/arrayobject.h",
|
|
8
|
+
"/tmp/build-env-o0tc6imy/lib/python3.12/site-packages/numpy/_core/include/numpy/arrayscalars.h",
|
|
9
|
+
"/tmp/build-env-o0tc6imy/lib/python3.12/site-packages/numpy/_core/include/numpy/ndarrayobject.h",
|
|
10
|
+
"/tmp/build-env-o0tc6imy/lib/python3.12/site-packages/numpy/_core/include/numpy/ndarraytypes.h",
|
|
11
|
+
"/tmp/build-env-o0tc6imy/lib/python3.12/site-packages/numpy/_core/include/numpy/ufuncobject.h"
|
|
12
12
|
],
|
|
13
13
|
"include_dirs": [
|
|
14
|
-
"/tmp/build-env-
|
|
14
|
+
"/tmp/build-env-o0tc6imy/lib/python3.12/site-packages/numpy/_core/include"
|
|
15
15
|
],
|
|
16
16
|
"name": "AbstractOptimizedModules",
|
|
17
17
|
"sources": [
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: AbstractIntegratedModule
|
|
3
|
-
Version: 1.3.
|
|
3
|
+
Version: 1.3.6
|
|
4
4
|
Summary: IntegratedPipeline Specifically provide a Framework to build Stateful continual learning Machine Learning Models optimized for Edge devices (ARM64).
|
|
5
5
|
Author: Micro-Novelty
|
|
6
6
|
Author-email: Micro-Novelty <hernikpuspita5@gmail.com>
|
|
@@ -24,7 +24,7 @@ extensions = [
|
|
|
24
24
|
|
|
25
25
|
setup(
|
|
26
26
|
name="AbstractIntegratedModule",
|
|
27
|
-
version="1.3.
|
|
27
|
+
version="1.3.6",
|
|
28
28
|
description="IntegratedPipeline Specifically provide a Framework to build Stateful continual learning Machine Learning Models optimized for Edge devices (ARM64).",
|
|
29
29
|
readme="README.md",
|
|
30
30
|
long_description=long_description,
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
{abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/AbstractOptimizedModules.pyx
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
{abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/Cargo.toml
RENAMED
|
File without changes
|
|
File without changes
|
{abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.6}/abstract_model_storage/src/lib.rs
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|