AbstractIntegratedModule 0.5.1__tar.gz → 0.5.2__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-0.5.2/AbstractIntegratedModule.cp313-win_amd64.pyd +0 -0
  2. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/AbstractIntegratedModule.cpython-310-aarch64-linux-gnu.so +0 -0
  3. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/AbstractIntegratedModule.cpython-312-x86_64-linux-gnu.so +0 -0
  4. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2/AbstractIntegratedModule.egg-info}/PKG-INFO +8 -6
  5. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/AbstractIntegratedModule.egg-info/SOURCES.txt +7 -1
  6. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/AbstractIntegratedModule.egg-info/top_level.txt +1 -0
  7. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/AbstractIntegratedModule.py +215 -84
  8. abstractintegratedmodule-0.5.2/AbstractOptimizedModules.c +15853 -0
  9. abstractintegratedmodule-0.5.2/AbstractOptimizedModules.cp313-win_amd64.pyd +0 -0
  10. abstractintegratedmodule-0.5.2/AbstractOptimizedModules.cpython-310-aarch64-linux-gnu.so +0 -0
  11. abstractintegratedmodule-0.5.2/AbstractOptimizedModules.cpython-312-x86_64-linux-gnu.so +0 -0
  12. abstractintegratedmodule-0.5.2/AbstractOptimizedModules.pyx +197 -0
  13. abstractintegratedmodule-0.5.2/MANIFEST.in +7 -0
  14. {abstractintegratedmodule-0.5.1/AbstractIntegratedModule.egg-info → abstractintegratedmodule-0.5.2}/PKG-INFO +8 -6
  15. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/README.md +7 -5
  16. abstractintegratedmodule-0.5.2/pyproject.toml +5 -0
  17. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/setup.py +19 -4
  18. abstractintegratedmodule-0.5.1/AbstractIntegratedModule.cp313-win_amd64.pyd +0 -0
  19. abstractintegratedmodule-0.5.1/MANIFEST.in +0 -4
  20. abstractintegratedmodule-0.5.1/pyproject.toml +0 -5
  21. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/AbstractIntegratedModule.egg-info/dependency_links.txt +0 -0
  22. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/AbstractIntegratedModule.egg-info/requires.txt +0 -0
  23. {abstractintegratedmodule-0.5.1 → abstractintegratedmodule-0.5.2}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: AbstractIntegratedModule
3
- Version: 0.5.1
3
+ Version: 0.5.2
4
4
  Summary: Framework for Advanced Integrated Non-LLM AI Module library - Backend Framework For Non-LLM AI Agent
5
5
  Author: Micro-Novelty
6
6
  Author-email: hernikpuspita5@gmail.com
@@ -42,7 +42,7 @@ https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent
42
42
  #### Note: The README here you are reading is a direct copy from my README Repository, to download the necessary files, you can visit my Repository with the provided link above.
43
43
 
44
44
  ### Library Short Description:
45
- - Development Stage: Beta, 0.5.1.
45
+ - Development Stage: Beta, 0.5.2.
46
46
  - Maintainer: Micro-Novelty.
47
47
  - library Source-Code is Open-sourced on github.
48
48
  - Purpose: Specifically Designed for providing Non-LLM AI Agent Framework for edge Devices, Optimized for ARM64 architecture.
@@ -64,11 +64,13 @@ https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent
64
64
  - AWE setup Proven Efficient on Hard-uncontrolled dataset such as Activity Recognition from the given Database.
65
65
  - LSTM is Optimized efficiently for scarce data with AWE method.
66
66
  - Robust Advanced prediction capabilities proven effective on ARM64 Using MLP + LSTM Architectures.
67
+ - Transformer Optimized using Cython, to reduce Memory overhead and Reduce CPU Usage.
67
68
  - Changelog:
68
- - v0.5.1:
69
- [=] New features:
70
- - Added new dynamic gate for Transformer Fixed and dynamic switching condition.
71
- - Added Capabilities for the Model to save the Transformer weights as binaries in local SQlite database.
69
+ - v0.5.2:
70
+ - [=] New features:
71
+ - Transformer is now Optimized using Cython!
72
+ - Refined memory checks to reduce further corruption in IntegratedPipeline memory.
73
+ - Added safety guards for cosine similarity to prevent float cascading through the flow.
72
74
  -----
73
75
 
74
76
  <img width="1280" height="600" alt="WhatsApp Image 2026-05-27 at 07 16 32" src="https://github.com/user-attachments/assets/4b58a556-45a3-419b-96fd-9c1b76cac574" />
@@ -2,6 +2,11 @@ AbstractIntegratedModule.cp313-win_amd64.pyd
2
2
  AbstractIntegratedModule.cpython-310-aarch64-linux-gnu.so
3
3
  AbstractIntegratedModule.cpython-312-x86_64-linux-gnu.so
4
4
  AbstractIntegratedModule.py
5
+ AbstractOptimizedModules.c
6
+ AbstractOptimizedModules.cp313-win_amd64.pyd
7
+ AbstractOptimizedModules.cpython-310-aarch64-linux-gnu.so
8
+ AbstractOptimizedModules.cpython-312-x86_64-linux-gnu.so
9
+ AbstractOptimizedModules.pyx
5
10
  MANIFEST.in
6
11
  README.md
7
12
  pyproject.toml
@@ -10,4 +15,5 @@ AbstractIntegratedModule.egg-info/PKG-INFO
10
15
  AbstractIntegratedModule.egg-info/SOURCES.txt
11
16
  AbstractIntegratedModule.egg-info/dependency_links.txt
12
17
  AbstractIntegratedModule.egg-info/requires.txt
13
- AbstractIntegratedModule.egg-info/top_level.txt
18
+ AbstractIntegratedModule.egg-info/top_level.txt
19
+ C:/Users/Dell/OneDrive/Desktop/AIM-PIP-Packaging/AbstractOptimizedModules.c
@@ -1 +1,2 @@
1
1
  AbstractIntegratedModule
2
+ AbstractOptimizedModules
@@ -42,6 +42,22 @@ import psutil
42
42
  from sklearn.preprocessing import StandardScaler
43
43
  import io
44
44
 
45
+ # Optimized Modules In Cython implementation.
46
+ try:
47
+ from AbstractOptimizedModules import (
48
+ optimized_sigmoid,
49
+ optimized_sigmoid_deriv,
50
+ optimized_tanh_deriv,
51
+ optimized_lstm_cell_forward,
52
+ optimized_project_heads,
53
+ optimized_ame_encoder
54
+ )
55
+ _OPT_AVAILABLE = True
56
+ print('[=] Cython acceleration loaded ✅')
57
+ except ImportError:
58
+ _OPT_AVAILABLE = False
59
+ print('[=] Cython not available, using numpy fallback')
60
+
45
61
  # initial Setup logging for AgentDistributedInference and ModelStorage class logger and security logger
46
62
  logger = logging.getLogger(__name__)
47
63
  _integrated_pipeline_lock = threading.Lock()
@@ -611,10 +627,19 @@ class Transformer:
611
627
  W_q_mix = (1 - alpha) * self.W_q_fixed + alpha * self.W_q
612
628
  W_k_mix = (1 - alpha) * self.W_k_fixed + alpha * self.W_k
613
629
  W_v_mix = (1 - alpha) * self.W_v_fixed + alpha * self.W_v
614
-
615
- Q = np.einsum('bsd,hdm->bhsm', x, W_q_mix)
616
- K = np.einsum('bsd,hdm->bhsm', x, W_k_mix)
617
- V = np.einsum('bsd,hdm->bhsm', x, W_v_mix)
630
+
631
+ # Optimized Project heads with Cython implementation.
632
+ if _OPT_AVAILABLE:
633
+ B, S, D = batch_size, seq_len, d_model
634
+ M = D // self.n_heads
635
+
636
+ Q = optimized_project_heads(x, W_q_mix, B, S, self.n_heads, D, M)
637
+ K = optimized_project_heads(x, W_k_mix, B, S, self.n_heads, D, M)
638
+ V = optimized_project_heads(x, W_v_mix, B, S, self.n_heads, D, M)
639
+ else:
640
+ Q = np.einsum('bsd,hdm->bhsm', x, W_q_mix)
641
+ K = np.einsum('bsd,hdm->bhsm', x, W_k_mix)
642
+ V = np.einsum('bsd,hdm->bhsm', x, W_v_mix)
618
643
 
619
644
  # Store for backward
620
645
  self.cache['Q'] = Q
@@ -638,7 +663,7 @@ class Transformer:
638
663
  return output, attn_weights
639
664
 
640
665
 
641
- def forward(self, input_ids, embedded=False, pad_token_id=0, training=True, attn_dropout=0.1, ffn_dropout=0.1):
666
+ def forward(self, input_ids, AME=None, embedded=False, pad_token_id=0, training=True, attn_dropout=0.1, ffn_dropout=0.1):
642
667
  if embedded:
643
668
  x = np.asarray(input_ids)
644
669
  if x.ndim == 2:
@@ -666,7 +691,6 @@ class Transformer:
666
691
  self.cache['x_pos'] = x
667
692
 
668
693
  # Multi-head attention with residual
669
- AME = self.AME_Encoder(x)
670
694
  alpha = 1.0 / (1.0 + np.exp(-AME))
671
695
  attn_out, attn_weights = self.multi_head_attention(x, mask=mask, alpha=alpha)
672
696
 
@@ -1004,7 +1028,7 @@ class Transformer:
1004
1028
  return grads, total_norm # return norm for monitoring
1005
1029
 
1006
1030
 
1007
- def train_step(self, input_ids, epoch, y_true, lr=0.01, mode=None, embedded=False, max_norm=1.0, pad_token_id=0):
1031
+ def train_step(self, input_ids, epoch, y_true, lr=0.01, AME=None, mode=None, embedded=False, max_norm=1.0, pad_token_id=0):
1008
1032
  y_true = np.asarray(y_true)
1009
1033
  if len(y_true.shape) < 2:
1010
1034
  y_true = y_true.reshape(-1, 1)
@@ -1014,7 +1038,7 @@ class Transformer:
1014
1038
  if y_true.ndim == 1:
1015
1039
  y_true = y_true[np.newaxis, :]
1016
1040
 
1017
- probs, attn_weights = self.forward(input_ids, embedded=embedded, pad_token_id=pad_token_id, training=True, attn_dropout=self.attn_dropout_rate, ffn_dropout=self.ffn_dropout_rate)
1041
+ probs, attn_weights = self.forward(input_ids, AME=AME, embedded=embedded, pad_token_id=pad_token_id, training=True, attn_dropout=self.attn_dropout_rate, ffn_dropout=self.ffn_dropout_rate)
1018
1042
  y_true_smooth = self.smoothing_labels_utility(y_true, smoothing=0.1)
1019
1043
 
1020
1044
  if y_true_smooth.shape[0] and y_true_smooth.shape[1] != probs.shape[0] and probs.shape[1]:
@@ -1092,9 +1116,8 @@ class Transformer:
1092
1116
  # input_ids_list is now a list of (B, T) arrays
1093
1117
  # y_true_list is now a list of (B, num_classes) arrays
1094
1118
 
1095
-
1119
+ AME = self.AME_Encoder(input_ids_list)
1096
1120
  print(f"[==] Starting comprehensive training for {epochs} epochs with mode: {mode}, learning rate: {lr}, schedule: {schedule}")
1097
-
1098
1121
  for epoch in range(epochs):
1099
1122
  epoch_losses = []
1100
1123
  epoch_accs = []
@@ -1108,7 +1131,7 @@ class Transformer:
1108
1131
  if y_true.ndim == 1:
1109
1132
  y_true = y_true[np.newaxis, :]
1110
1133
 
1111
- loss, acc = self.train_step(input_ids, epoch, y_true, current_lr, mode,
1134
+ loss, acc = self.train_step(input_ids, epoch, y_true, current_lr, AME=AME, mode=mode,
1112
1135
  embedded=embedded, max_norm=max_norm, pad_token_id=pad_token_id)
1113
1136
  epoch_losses.append(loss)
1114
1137
  epoch_accs.append(acc)
@@ -1127,14 +1150,19 @@ class Transformer:
1127
1150
  def predict(self, input_ids, embedded=False):
1128
1151
  if not embedded and input_ids.ndim == 1:
1129
1152
  input_ids = input_ids.reshape(1, -1)
1130
-
1131
- probs, attn_weights = self.forward(input_ids, embedded=embedded, training=False, attn_dropout=0.0, ffn_dropout=0.0)
1153
+
1154
+ AME = self.AME_Encoder(input_ids)
1155
+ probs, attn_weights = self.forward(input_ids, AME=AME, embedded=embedded, training=False, attn_dropout=0.0, ffn_dropout=0.0)
1132
1156
  preds = np.argmax(probs, axis=1)
1133
1157
 
1134
1158
  return preds, probs, attn_weights
1135
1159
 
1136
1160
 
1137
1161
  def AME_Encoder(self, x):
1162
+ # Optimized AME_Encoder for Transformer
1163
+ if _OPT_AVAILABLE and np.asarray(x).ndim == 2:
1164
+ return optimized_ame_encoder(np.asarray(x, dtype=np.float64))
1165
+
1138
1166
  X = np.asarray(x)
1139
1167
  # Regular AME Equations, higher AME provides capabilities for the model to experience errors during abstraction
1140
1168
  # Lower AME means lower chance for un optimal abstraction.
@@ -1455,6 +1483,18 @@ class LSTMCell:
1455
1483
 
1456
1484
  # _________ forward method for cell class _____________
1457
1485
  def forward(self, x_seq: np.ndarray, h0=None, c0=None):
1486
+
1487
+ # Optimized LSTM Cell Implementation with Cython based Language.
1488
+ if _OPT_AVAILABLE:
1489
+ hs, cs, cache = optimized_lstm_cell_forward(
1490
+ np.ascontiguousarray(x_seq, dtype=np.float64), # force float64
1491
+ np.ascontiguousarray(self.W, dtype=np.float64),
1492
+ np.ascontiguousarray(self.b, dtype=np.float64),
1493
+ self.input_size,
1494
+ self.hidden_size
1495
+ )
1496
+ return hs, cs, cache
1497
+
1458
1498
  T = x_seq.shape[0]
1459
1499
  H = self.hidden_size
1460
1500
  expected_input = self.input_size
@@ -2407,7 +2447,9 @@ class WeightedEnsemblePredictor:
2407
2447
  print('[=] label_bins cache found!')
2408
2448
  label_bins = self.pipeline.cache['label_bins']
2409
2449
 
2410
- trans_probs, attn_weights = self.pipeline.model2.forward(input_ids, embedded=embedded)
2450
+ AME = self.pipeline.model2.AME_Encoder(input_ids)
2451
+
2452
+ trans_probs, attn_weights = self.pipeline.model2.forward(input_ids, AME=AME, embedded=embedded)
2411
2453
  mlp_probs = self.pipeline.mlp.forward(X_mlp)
2412
2454
  lstm_probs, lstm_weight_hint = self._get_lstm_probs(input_ids, X_mlp, label_bins=label_bins)
2413
2455
 
@@ -2731,9 +2773,11 @@ class WeightedEnsemblePredictor:
2731
2773
  def calibrate_weights(self, input_ids, X_mlp, y_true, step=3):
2732
2774
  print("\n🔧 Calibrating ensemble weights...")
2733
2775
 
2734
- best_weight = 0.1 + self.pipeline.confidence_threshold
2776
+ best_weight = self.pipeline.confidence_threshold + self.pipeline.confidence_threshold
2735
2777
  best_accuracy = 0
2736
-
2778
+
2779
+ AME = self.pipeline.model2.AME_Encoder(input_ids)
2780
+
2737
2781
  # Try different weights
2738
2782
  for w in np.linspace(0, 1, 11):
2739
2783
  self.transformer_weight = w
@@ -2742,7 +2786,7 @@ class WeightedEnsemblePredictor:
2742
2786
  correct = 0
2743
2787
  total = 0
2744
2788
  for i in range(step):
2745
- trans_probs, _ = self.pipeline.model2.forward(input_ids)
2789
+ trans_probs, _ = self.pipeline.model2.forward(input_ids, AME=AME, embedded=True)
2746
2790
  mlp_probs = self.pipeline.mlp.forward(X_mlp)
2747
2791
 
2748
2792
  ensemble = w * trans_probs + (1-w) * mlp_probs
@@ -4016,6 +4060,100 @@ class ModelStorage:
4016
4060
  return [self._prepare_for_serialization(item) for item in obj]
4017
4061
  return obj
4018
4062
 
4063
+ def load_model_dict(self, memory_name):
4064
+ conn = None
4065
+ try:
4066
+ try:
4067
+ conn = sqlite3.connect(self.db_path)
4068
+ except:
4069
+ conn = sqlite3.connect(self.get_database_path())
4070
+
4071
+ c = conn.cursor()
4072
+ c.execute("""
4073
+ SELECT model_data FROM model_storage
4074
+ WHERE memory_name = ? AND is_active = 1
4075
+ ORDER BY id DESC LIMIT 1
4076
+ """, (memory_name,))
4077
+
4078
+ result = c.fetchone()
4079
+ if not result:
4080
+ return None
4081
+
4082
+ data = json.loads(result[0])
4083
+ data = self._validate_and_repair(data, memory_name)
4084
+ return data # actually return data
4085
+
4086
+ except Exception as e:
4087
+ print(f'[!] Error loading model dict: {e}')
4088
+ return None
4089
+ finally:
4090
+ if conn:
4091
+ conn.close()
4092
+
4093
+
4094
+ def _validate_and_repair(self, data, memory_name=None):
4095
+ """Validate loaded data and repair if corrupted."""
4096
+
4097
+ if data is None:
4098
+ return {}
4099
+
4100
+ # get num_classes safely without touching pipeline
4101
+ num_classes = 0
4102
+ try:
4103
+ # try pipeline first
4104
+ if hasattr(self, 'pipeline') and self.pipeline is not None:
4105
+ num_classes = self.pipeline._get_num_classes()
4106
+ # fallback — infer from data itself
4107
+ elif isinstance(data, dict):
4108
+ for v in data.values():
4109
+ if isinstance(v, (list, np.ndarray)):
4110
+ arr = np.asarray(v)
4111
+ if arr.ndim == 1:
4112
+ num_classes = len(arr)
4113
+ break
4114
+ except Exception as e:
4115
+ print(f'[!] Could not determine num_classes: {e}')
4116
+ num_classes = 0
4117
+
4118
+ # handle list data
4119
+ if isinstance(data, list) and len(data) > 0:
4120
+ if num_classes > 0 and len(data) != num_classes:
4121
+ print(f'[!] Shape mismatch: got {len(data)}, expected {num_classes} — repairing')
4122
+ return {}
4123
+
4124
+ if all(isinstance(x, (int, float)) for x in data[:10]):
4125
+ print(f'[!] List appears to be probabilities, wrapping')
4126
+ return {'_cached_probs': np.array(data, dtype=np.float64)}
4127
+
4128
+ # handle dict data
4129
+ if isinstance(data, dict):
4130
+ repaired = {}
4131
+ for key, value in data.items():
4132
+
4133
+ # dynamic corruption check instead of hardcoded 133
4134
+ if isinstance(value, list):
4135
+ arr = np.asarray(value)
4136
+ if arr.ndim > 2:
4137
+ print(f'[!] Corrupted value for key {key} '
4138
+ f'(ndim={arr.ndim}), removing')
4139
+ continue
4140
+
4141
+ if num_classes > 0 and arr.ndim == 1 and \
4142
+ len(arr) not in (num_classes, num_classes * 2):
4143
+ print(f'[!] Suspicious shape for key {key}: '
4144
+ f'{arr.shape}, expected {num_classes} — removing')
4145
+ continue
4146
+
4147
+ # None values — skip silently
4148
+ if value is None:
4149
+ continue
4150
+
4151
+ repaired[key] = value
4152
+
4153
+ return repaired
4154
+
4155
+ return data
4156
+
4019
4157
 
4020
4158
  def _convert_to_arrays(self, data):
4021
4159
  """
@@ -4040,6 +4178,7 @@ class ModelStorage:
4040
4178
  return self._convert_value(data)
4041
4179
 
4042
4180
 
4181
+
4043
4182
  def _convert_value(self, value):
4044
4183
  """
4045
4184
  Convert a single value to appropriate type.
@@ -4207,8 +4346,8 @@ class ModelStorage:
4207
4346
  elif type_func == 'Node':
4208
4347
  data = self._load_node_dict(name)
4209
4348
  else:
4210
- data = self.load_model_dict(name)
4211
-
4349
+ data = self.load_model_dict(memory_name)
4350
+
4212
4351
  if data is None:
4213
4352
  print(f"[-] No memory found: {name}")
4214
4353
  return {}
@@ -4610,56 +4749,7 @@ class ModelStorage:
4610
4749
  print(f'|| Cant load peer request memory due to: {e}')
4611
4750
  return None, None
4612
4751
 
4613
-
4614
- def load_model_dict(self, memory_name):
4615
- try:
4616
- try:
4617
- conn = sqlite3.connect(self.db_path)
4618
- except:
4619
- db_path = self.get_database_path()
4620
- conn = sqlite3.connect(db_path)
4621
- c = conn.cursor()
4622
4752
 
4623
- c.execute("""
4624
- SELECT model_data FROM model_storage
4625
- WHERE memory_name = ? AND is_active = 1
4626
- """, (memory_name,))
4627
-
4628
- result = c.fetchone()
4629
- conn.close()
4630
-
4631
- if result:
4632
- data = json.loads(result[0])
4633
- data = self._validate_and_repair(data)
4634
- except Exception as e:
4635
- print(f'Error handling model dict: {e}')
4636
- return None
4637
-
4638
- def _validate_and_repair(self, data):
4639
- """Validate loaded data and repair if corrupted"""
4640
-
4641
- # If data is an array with wrong shape
4642
- if isinstance(data, list) and len(data) > 0:
4643
- # Check if it's a probability array
4644
- if len(data) != self.pipeline._get_num_classes():
4645
- print(f'[!] Detected corrupted memory with shape {len(data)}, repairing...')
4646
- # Return empty dict to trigger retraining
4647
- return {}
4648
-
4649
- # Try to convert list to dict format
4650
- if all(isinstance(x, (int, float)) for x in data[:10]):
4651
- print(f'[!] List appears to be probabilities, wrapping')
4652
- return {'_cached_probs': np.array(data)}
4653
-
4654
-
4655
- # If data is dict, ensure values are correct
4656
- if isinstance(data, dict):
4657
- for key, value in data.items():
4658
- if isinstance(value, list) and len(value) == 133:
4659
- print(f'[!] Corrupted value for key {key}, removing')
4660
- data[key] = None
4661
-
4662
- return data
4663
4753
 
4664
4754
  def fix_corrupted_memory(self, memory_name):
4665
4755
  # Clear corrupted memory entries
@@ -7771,8 +7861,19 @@ class IntegratedPipeline:
7771
7861
 
7772
7862
 
7773
7863
  def cosine_robust_similarity(self, a, b):
7774
- norm_a = np.linalg.norm(a)
7775
- norm_b = np.linalg.norm(b[0])
7864
+ if isinstance(b, (float, int)) or isinstance(a, (float, int)):
7865
+ print('[!] Value is single scalar! returning 0.0 similarity')
7866
+ return 0.0
7867
+
7868
+ if isinstance(a[0], (np.ndarray, list)):
7869
+ norm_a = np.linalg.norm(a[0])
7870
+ else:
7871
+ norm_a = np.linalg.norm(a)
7872
+
7873
+ if isinstance(b[0], (np.ndarray, list)):
7874
+ norm_b = np.linalg.norm(b[0])
7875
+ else:
7876
+ norm_b = np.linalg.norm(b)
7776
7877
 
7777
7878
  try:
7778
7879
  dot_product = np.dot(a, b)
@@ -7981,6 +8082,10 @@ class IntegratedPipeline:
7981
8082
 
7982
8083
  def cosine_similarity(self, a, b):
7983
8084
  eps = 1e-5
8085
+ if isinstance(b, (float, int)) or isinstance(a, (float, int)):
8086
+ print('[!] Value is single scalar! returning 0.0 similarity')
8087
+ return 0.0
8088
+
7984
8089
  b = b[0]
7985
8090
 
7986
8091
  try:
@@ -8319,20 +8424,42 @@ class IntegratedPipeline:
8319
8424
  return None
8320
8425
 
8321
8426
  def _gate_from_list(self, memory: list, x, x2) -> Optional[np.ndarray]:
8322
- # xtract from list memory (fallback for corrupted storage)
8427
+ print('[=] Extracting from list memory.. handling possible corruption...')
8323
8428
 
8324
- print('[=] Extracting from list memory.. handling possible corruption of data...')
8325
8429
  for item in memory:
8326
- if isinstance(item, (tuple, list)) and len(item) >= 2:
8327
- stored_x = item[0]
8328
- stored_out = item[1]
8329
-
8330
- # Check similarity
8331
- print('[=] checking similarity from stored X data and stored output...')
8332
- if self.cosine_robust_similarity(x, stored_x) >= 0.9:
8430
+ if not isinstance(item, (tuple, list)) or len(item) < 2:
8431
+ continue
8432
+
8433
+ stored_x = item[0]
8434
+ stored_out = item[1]
8435
+
8436
+ # guard against corrupted float entries
8437
+ if isinstance(stored_x, (int, float)):
8438
+ print(f'[!] Skipping corrupted entry — stored_x is scalar: {stored_x}')
8439
+ continue
8440
+
8441
+ # guard against None
8442
+ if stored_x is None or stored_out is None:
8443
+ continue
8444
+
8445
+ # ensure array before similarity
8446
+ try:
8447
+ stored_x_arr = self._to_numpy_array(stored_x)
8448
+ if stored_x_arr is None or stored_x_arr.ndim == 0:
8449
+ continue
8450
+ except Exception as e:
8451
+ print(f'[!] Could not convert stored_x to array: {e}')
8452
+ continue
8453
+
8454
+ try:
8455
+ print('[=] Checking similarity from stored X data...')
8456
+ if self.cosine_robust_similarity(x, stored_x_arr) >= 0.775:
8333
8457
  return self._to_numpy_array(stored_out)
8458
+ except Exception as e:
8459
+ print(f'[!] Similarity check failed: {e}')
8460
+ continue
8334
8461
 
8335
- print('[=] Cant get item from memory, possible dangerous data Corruption!')
8462
+ print('[=] Cant get item from memory, possible dangerous data corruption!')
8336
8463
  return None
8337
8464
 
8338
8465
 
@@ -11775,9 +11902,10 @@ class PipelinePredictionManager:
11775
11902
  input_ids_list.append(np.array(ids))
11776
11903
 
11777
11904
  input_ids = np.array(input_ids_list)
11905
+ AME = self.pipeline.model2.AME_Encoder(input_ids)
11778
11906
 
11779
11907
  # Get transformer probabilities
11780
- trans_probs, attn_weights = self.pipeline.model2.forward(input_ids)
11908
+ trans_probs, attn_weights = self.pipeline.model2.forward(input_ids, AME=AME)
11781
11909
  else:
11782
11910
  print("⚡ Using MLP only for predictions")
11783
11911
  trans_probs = None
@@ -12302,7 +12430,9 @@ class PipelinePredictionManager:
12302
12430
  # Get transformer predictions with attention
12303
12431
  print(f"[⚡] anisotropy rate detected on input: {anisotropy:.1%}.")
12304
12432
  use_embedded = True
12305
- trans_probs, attn_weights = self.pipeline.model2.forward(sequence_ids, embedded=use_embedded)
12433
+
12434
+ AME = self.pipeline.model2.AME_Encoder(sequence_ids)
12435
+ trans_probs, attn_weights = self.pipeline.model2.forward(sequence_ids, AME=AME, embedded=use_embedded)
12306
12436
 
12307
12437
  else:
12308
12438
  print("\n[⚡] Running MLP-only predictions")
@@ -12748,6 +12878,7 @@ class PipelinePredictionManager:
12748
12878
 
12749
12879
  except Exception as e:
12750
12880
  print(f"[!] Error in advanced prediction method: {e}, Initiating regular prediction method...")
12881
+ traceback.print_exc()
12751
12882
  try:
12752
12883
  results = self.regular_prediction_method(titles, label_map, rules, X=X, y=y, show_proba=False, top_k=3, batch_size=2,use_transformer=True)
12753
12884
  chosen_label = results[0]['predicted']
@@ -12796,8 +12927,8 @@ class PipelinePredictionManager:
12796
12927
 
12797
12928
  # Agreement indicator
12798
12929
  agree_symbol = "✓" if result.get('models_agree', True) else "⚠️"
12799
- print(f" {agree_symbol} FINAL: {result['predicted']} ({result['confidence']:.1%})")
12800
-
12930
+ print(f"[=] {agree_symbol} FINAL: {result['predicted']} ({result['confidence']:.1%})")
12931
+
12801
12932
  # MLP vs Transformer
12802
12933
  print(f" ├─ [⚡] MLP: {result['mlp_prediction']} ({result['mlp_confidence']:.1%})")
12803
12934
  if result.get('transformer_prediction'):