AbstractIntegratedModule 1.3.4__tar.gz → 1.3.5__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 (23) hide show
  1. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractIntegratedModule.egg-info/PKG-INFO +1 -1
  2. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractIntegratedModule.py +350 -27
  3. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractOptimizedModules.c +6 -6
  4. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/PKG-INFO +1 -1
  5. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/pyproject.toml +1 -1
  6. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/setup.py +1 -1
  7. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractIntegratedModule.egg-info/SOURCES.txt +0 -0
  8. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractIntegratedModule.egg-info/dependency_links.txt +0 -0
  9. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractIntegratedModule.egg-info/requires.txt +0 -0
  10. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractIntegratedModule.egg-info/top_level.txt +0 -0
  11. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/AbstractOptimizedModules.pyx +0 -0
  12. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/MANIFEST.in +0 -0
  13. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/README.md +0 -0
  14. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/Cargo.toml +0 -0
  15. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/pyproject.toml +0 -0
  16. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/src/lib.rs +0 -0
  17. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/target/debug/build/libsqlite3-sys-ed07b882cd2aa5e2/out/bindgen.rs +0 -0
  18. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/target/debug/build/serde_core-ebc15f2e9cad7f5f/out/private.rs +0 -0
  19. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/target/debug/build/target-lexicon-08527f45de28143d/out/host.rs +0 -0
  20. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/target/release/build/libsqlite3-sys-bf0400df4523274c/out/bindgen.rs +0 -0
  21. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/target/release/build/serde_core-5cdb76131825e4af/out/private.rs +0 -0
  22. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/abstract_model_storage/target/release/build/target-lexicon-43eb95a0588bf457/out/host.rs +0 -0
  23. {abstractintegratedmodule-1.3.4 → abstractintegratedmodule-1.3.5}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: AbstractIntegratedModule
3
- Version: 1.3.4
3
+ Version: 1.3.5
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>
@@ -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,
@@ -13176,6 +13440,7 @@ class IntegratedPipeline:
13176
13440
  self.peer_assistance_threshold = 0.0
13177
13441
  self.n_hash_dim = 2**8
13178
13442
  self.agent_id = random.randint(0, 10000)
13443
+ self._prob_save_count = 0
13179
13444
 
13180
13445
  self.vocab = {}
13181
13446
  self.cache = {}
@@ -15405,10 +15670,20 @@ class IntegratedPipeline:
15405
15670
 
15406
15671
  try:
15407
15672
  if needs_prediction:
15408
- fresh_input_ids = batch_input_ids[needs_prediction]
15409
- fresh_X = batch_X[needs_prediction]
15673
+ if len(needs_prediction) <= len(batch_input_ids):
15674
+ fresh_input_ids = batch_input_ids[needs_prediction]
15675
+ else:
15676
+ fresh_input_ids = batch_input_ids[needs_prediction[len(batch_input_ids) - 1]]
15677
+ if len(needs_prediction) <= len(batch_X):
15678
+ fresh_X = batch_X[needs_prediction]
15679
+ else:
15680
+ fresh_X = batch_X[needs_prediction[len(batch_X) - 1]]
15681
+
15682
+ try:
15683
+ transformer_pred, fresh_probs, attn_weights = self.model2.predict(fresh_input_ids, embedded=True)
15684
+ except:
15685
+ transformer_pred, fresh_probs, attn_weights = self.model2.predict(fresh_input_ids, embedded=False)
15410
15686
 
15411
- transformer_pred, fresh_probs, attn_weights = self.model2.predict(fresh_input_ids)
15412
15687
  mlp_pred = self.model3.forward(fresh_X)
15413
15688
 
15414
15689
  # coerce indices to int
@@ -15418,8 +15693,12 @@ class IntegratedPipeline:
15418
15693
  for i, idx in enumerate(needs_prediction):
15419
15694
 
15420
15695
  # validate indices in range before use
15421
- mlp_cls = int(mlp_pred_indices[i])
15422
- trans_cls = int(trans_pred_indices[i])
15696
+ if i < len(mlp_pred_indices) and i < len(trans_pred_indices):
15697
+ mlp_cls = int(mlp_pred_indices[i])
15698
+ trans_cls = int(trans_pred_indices[i])
15699
+ else:
15700
+ mlp_cls = int(mlp_pred_indices[len(mlp_pred_indices) - 1])
15701
+ trans_cls = int(trans_pred_indices[len(trans_pred_indices) - 1])
15423
15702
 
15424
15703
  mlp_cls = mlp_cls if 0 <= mlp_cls < num_classes else 0
15425
15704
  trans_cls = trans_cls if 0 <= trans_cls < num_classes else 0
@@ -15449,12 +15728,13 @@ class IntegratedPipeline:
15449
15728
 
15450
15729
  # instance-level save counter, not local idx_total
15451
15730
  if getattr(self, '_prob_save_count', 0) < 2:
15452
- self.modular_probability_saving(
15731
+ if i < len(fresh_input_ids) and i < len(fresh_X) and idx < len(batch_probs):
15732
+ self.modular_probability_saving(
15453
15733
  fresh_input_ids[i:i+1],
15454
15734
  fresh_X[i:i+1],
15455
15735
  np.array([batch_probs[idx]])
15456
- )
15457
- self._prob_save_count = getattr(self, '_prob_save_count', 0) + 1
15736
+ )
15737
+ self._prob_save_count = getattr(self, '_prob_save_count', 0) + 1
15458
15738
 
15459
15739
  else:
15460
15740
  raise Warning('[!] Data is None before batching!')
@@ -15492,6 +15772,7 @@ class IntegratedPipeline:
15492
15772
  return valid_probs
15493
15773
  except Exception as e:
15494
15774
  print(f'[⚠️] Error occured in probabilities batching: {e}')
15775
+ traceback.print_exc()
15495
15776
  return None
15496
15777
 
15497
15778
 
@@ -21504,12 +21785,41 @@ def initialize_snn_network(X=None, y=None, label_map=None, n_hidden=64, n_in=Non
21504
21785
  print(f'[>] Error initializing SNN Network and hidden layer: {e}')
21505
21786
  return None, None, None
21506
21787
 
21788
+ def infer_target_type(y=None, max_classes_ratio=0.05, max_unique_absolute=50):
21789
+ score = 0
21790
+ y_flat = None
21791
+ if y is not None:
21792
+ y = np.asarray(y)
21793
+ y_flat = y.flatten()
21794
+
21795
+ unique_vals = np.unique(y_flat)
21796
+ n_unique = len(unique_vals)
21797
+ n_samples = len(y_flat)
21798
+
21799
+ unique_ratio = n_unique / n_samples
21800
+ if n_unique > max_unique_absolute or unique_ratio > max_classes_ratio:
21801
+ score += 1
21802
+
21803
+ if y_flat is not None:
21804
+ if not np.all(np.equal(np.mod(y_flat, 1), 0)):
21805
+ score += 1
21806
+
21807
+ if score <= 1:
21808
+ return "classification"
21809
+ else:
21810
+ return "regression"
21811
+
21812
+
21813
+
21507
21814
  def train_snn_network(X=None, y=None, net=None, hidden_layer=None, utility=None, task='classification', label_map=None,
21508
21815
  epochs=50, batch_size=32, n_steps=20,
21509
21816
  n_hidden=64, lr=2e-3, seed=0, pretrain_steps=200, unsupervised_stdp=False,
21510
- random_state=42, ):
21817
+ random_state=42, jepa_pretrain_enabled=False, X_unlabeled=None, jepa_kwargs=None):
21511
21818
  tracker = DiagnosticsTracker()
21512
21819
  cache = {}
21820
+ if task is None or not isinstance(task, str):
21821
+ task = infer_target_type(y=y)
21822
+
21513
21823
  reg = (task == 'regression')
21514
21824
  if utility is None:
21515
21825
  utility = SNNUtility()
@@ -21554,19 +21864,21 @@ def train_snn_network(X=None, y=None, net=None, hidden_layer=None, utility=None,
21554
21864
  homeostasis = ThresholdHomeostasis(target_rate=0.15, adjust_rate=0.05)
21555
21865
 
21556
21866
  # ---- Phase 1: unsupervised STDP pretraining (labels NOT used) ----
21557
- if unsupervised_stdp:
21558
- if n_in == n_hidden:
21559
- utility.stdp_pretrain(hidden_layer, encoder, X_train, rng, n_steps=pretrain_steps,
21560
- batch_size=batch_size)
21561
- print(f"[=] After STDP pretraining: hidden layer mean firing rate = "
21562
- f"{hidden_layer._cache['spike_hist'].mean():.3f}")
21563
- per_neuron_rate = hidden_layer._cache["spike_hist"].mean(axis=(0, 1)) # shape (n_hidden,)
21564
- print("[=] Dead neurons:", (per_neuron_rate < 1e-4).sum(), "/", len(per_neuron_rate))
21565
- per_neuron_rate = hidden_layer._cache["spike_hist"].mean(axis=(0, 1))
21566
- print("[=] Neuron firing rates - min:", per_neuron_rate.min(), "max:", per_neuron_rate.max(), "std:", per_neuron_rate.std())
21567
- else:
21568
- print('[>] Unsupervised STDP pretraining skipped due to mismatched Input_shapes[1] size with the amount of network hidden layers')
21569
-
21867
+ if jepa_pretrain_enabled or unsupervised_stdp:
21868
+ X_pre = X_train
21869
+ if X_unlabeled is not None: # extra unlabeled rows: this is where JEPA pays off
21870
+ Xu = np.asarray(X_unlabeled, dtype=np.float64)
21871
+ Xu = Xu.reshape(len(Xu), -1)
21872
+ if reg:
21873
+ Xu = scale_x(Xu) # same train-stat [0,1] scaling as X_train
21874
+ X_pre = np.concatenate([X_train, Xu], axis=0)
21875
+ jp = dict(n_steps=pretrain_steps, batch_size=batch_size)
21876
+ jp.update(jepa_kwargs or {})
21877
+ jepa_info = jepa_pretrain(hidden_layer, encoder, X_pre, rng, **jp)
21878
+ per_neuron_rate = hidden_layer._cache["spike_hist"].mean(axis=(0, 1))
21879
+ print(f"[=] Dead neurons after JEPA: {(per_neuron_rate < 1e-4).sum()} / {len(per_neuron_rate)} || "
21880
+ f"rate min={per_neuron_rate.min():.3f} max={per_neuron_rate.max():.3f}")
21881
+
21570
21882
  # ---- Phase 2: supervised BPTT fine-tuning of the whole network ----
21571
21883
  for epoch in range(1, epochs + 1):
21572
21884
  net.train()
@@ -21636,7 +21948,9 @@ def _snn_predict_regression(X, net, encoder, n_mc=20):
21636
21948
  def snn_predict(X=None, y=None, task='classification', label_map=None, encoder=None, net=None, random_state=42, max_print_threshold=50):
21637
21949
  utility = SNNUtility()
21638
21950
  reverse_map = None
21639
-
21951
+ if task is None or not isinstance(task, str):
21952
+ task = infer_target_type(y=y)
21953
+
21640
21954
  if X is not None and y is not None:
21641
21955
  print(f"[🔍] Processing X and y samples for Spiking Neural Network...")
21642
21956
  if isinstance(X, (str, np.str_)):
@@ -21889,13 +22203,14 @@ class PipelinePredictionManager:
21889
22203
  trans_probs = None
21890
22204
  attn_weights = None
21891
22205
  use_embedded = True
22206
+ reverse_map=None
21892
22207
  results = []
21893
22208
 
21894
22209
  task = task.lower()
21895
22210
  if task is None or task != 'classification' or task != 'regression':
21896
22211
  task = self.pipeline.infer_target_type(self.pipeline.vocab_size, y)
21897
22212
 
21898
- if label_map and isinstance(label_map, dict):
22213
+ if label_map is not None and isinstance(label_map, dict):
21899
22214
  reverse_map = {v: k for k, v in label_map.items()}
21900
22215
 
21901
22216
  if self.pipeline.knn_tf is None:
@@ -23432,8 +23747,13 @@ class PipelinePredictionManager:
23432
23747
 
23433
23748
  # Validate all MLP predictions at once
23434
23749
  mlp_pred_indices = np.argmax(mlp_probs, axis=1)
23435
- if num_classes <= 0:
23436
- num_classes = self.pipeline._get_num_classes(mlp_probs=mlp_probs)
23750
+ if num_classes is None:
23751
+ if y is not None and len(y) > 1:
23752
+ num_classes = int(np.max(y)) + 1
23753
+ if label_map is not None:
23754
+ num_classes = len(label_map)
23755
+ else:
23756
+ num_classes = self.pipeline._get_num_classes(mlp_probs=mlp_probs)
23437
23757
 
23438
23758
  valid_mask = mlp_pred_indices < num_classes
23439
23759
  if not np.all(valid_mask):
@@ -23493,7 +23813,10 @@ class PipelinePredictionManager:
23493
23813
 
23494
23814
  use_embedded = True
23495
23815
 
23496
- target_probs = self.pipeline.predict_proba(input_ids, X, type='Hybrid', embedded=use_embedded)
23816
+ if X is not None:
23817
+ target_probs = self.pipeline.predict_proba(input_ids, X, type='Hybrid', embedded=use_embedded)
23818
+ else:
23819
+ target_probs = mlp_probs.copy()
23497
23820
  else:
23498
23821
  target_probs = mlp_probs.copy()
23499
23822
 
@@ -4,14 +4,14 @@
4
4
  {
5
5
  "distutils": {
6
6
  "depends": [
7
- "/tmp/build-env-w782lq3_/lib/python3.12/site-packages/numpy/_core/include/numpy/arrayobject.h",
8
- "/tmp/build-env-w782lq3_/lib/python3.12/site-packages/numpy/_core/include/numpy/arrayscalars.h",
9
- "/tmp/build-env-w782lq3_/lib/python3.12/site-packages/numpy/_core/include/numpy/ndarrayobject.h",
10
- "/tmp/build-env-w782lq3_/lib/python3.12/site-packages/numpy/_core/include/numpy/ndarraytypes.h",
11
- "/tmp/build-env-w782lq3_/lib/python3.12/site-packages/numpy/_core/include/numpy/ufuncobject.h"
7
+ "/tmp/build-env-j9o13rd4/lib/python3.12/site-packages/numpy/_core/include/numpy/arrayobject.h",
8
+ "/tmp/build-env-j9o13rd4/lib/python3.12/site-packages/numpy/_core/include/numpy/arrayscalars.h",
9
+ "/tmp/build-env-j9o13rd4/lib/python3.12/site-packages/numpy/_core/include/numpy/ndarrayobject.h",
10
+ "/tmp/build-env-j9o13rd4/lib/python3.12/site-packages/numpy/_core/include/numpy/ndarraytypes.h",
11
+ "/tmp/build-env-j9o13rd4/lib/python3.12/site-packages/numpy/_core/include/numpy/ufuncobject.h"
12
12
  ],
13
13
  "include_dirs": [
14
- "/tmp/build-env-w782lq3_/lib/python3.12/site-packages/numpy/_core/include"
14
+ "/tmp/build-env-j9o13rd4/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.4
3
+ Version: 1.3.5
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>
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "AbstractIntegratedModule"
7
- version = "1.3.4"
7
+ version = "1.3.5"
8
8
  authors = [
9
9
  {name = "Micro-Novelty", email = "hernikpuspita5@gmail.com"},
10
10
  ]
@@ -24,7 +24,7 @@ extensions = [
24
24
 
25
25
  setup(
26
26
  name="AbstractIntegratedModule",
27
- version="1.3.4",
27
+ version="1.3.5",
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,