AbstractIntegratedModule 1.3.1__tar.gz → 1.3.3__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.1 → abstractintegratedmodule-1.3.3}/AbstractIntegratedModule.egg-info/PKG-INFO +2 -2
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractIntegratedModule.py +163 -131
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractOptimizedModules.c +567 -451
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractOptimizedModules.pyx +6 -10
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/PKG-INFO +2 -2
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/README.md +125 -103
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/pyproject.toml +2 -2
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/setup.py +2 -2
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractIntegratedModule.egg-info/SOURCES.txt +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractIntegratedModule.egg-info/dependency_links.txt +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractIntegratedModule.egg-info/requires.txt +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractIntegratedModule.egg-info/top_level.txt +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/MANIFEST.in +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/Cargo.toml +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/pyproject.toml +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/src/lib.rs +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/target/debug/build/libsqlite3-sys-ed07b882cd2aa5e2/out/bindgen.rs +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/target/debug/build/serde_core-ebc15f2e9cad7f5f/out/private.rs +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/target/debug/build/target-lexicon-08527f45de28143d/out/host.rs +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/target/release/build/libsqlite3-sys-bf0400df4523274c/out/bindgen.rs +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/target/release/build/serde_core-5cdb76131825e4af/out/private.rs +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/abstract_model_storage/target/release/build/target-lexicon-43eb95a0588bf457/out/host.rs +0 -0
- {abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/setup.cfg +0 -0
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: AbstractIntegratedModule
|
|
3
|
-
Version: 1.3.
|
|
4
|
-
Summary:
|
|
3
|
+
Version: 1.3.3
|
|
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>
|
|
7
7
|
License-Expression: MIT
|
{abstractintegratedmodule-1.3.1 → abstractintegratedmodule-1.3.3}/AbstractIntegratedModule.py
RENAMED
|
@@ -2725,11 +2725,22 @@ class Transformer(TargetMemoryMixin):
|
|
|
2725
2725
|
|
|
2726
2726
|
# Optimized Project heads with Cython implementation.
|
|
2727
2727
|
if _OPT_AVAILABLE:
|
|
2728
|
-
|
|
2729
|
-
|
|
2730
|
-
|
|
2731
|
-
|
|
2732
|
-
|
|
2728
|
+
try:
|
|
2729
|
+
x_c = np.ascontiguousarray(x, dtype=np.float64)
|
|
2730
|
+
Wq_c = np.ascontiguousarray(W_q_mix, dtype=np.float64)
|
|
2731
|
+
Wk_c = np.ascontiguousarray(W_k_mix, dtype=np.float64)
|
|
2732
|
+
Wv_c = np.ascontiguousarray(W_v_mix, dtype=np.float64)
|
|
2733
|
+
|
|
2734
|
+
B, S, D = batch_size, seq_len, d_model
|
|
2735
|
+
M = D // self.n_heads
|
|
2736
|
+
Q = optimized_project_heads(x_c, Wq_c, B, S, self.n_heads, D, M)
|
|
2737
|
+
K = optimized_project_heads(x_c, Wk_c, B, S, self.n_heads, D, M)
|
|
2738
|
+
V = optimized_project_heads(x_c, Wv_c, B, S, self.n_heads, D, M)
|
|
2739
|
+
except Exception as e:
|
|
2740
|
+
print(f'[TRANSFORMER] Error in optimize project head: {e}')
|
|
2741
|
+
Q = np.einsum('bsd,hdm->bhsm', x, W_q_mix)
|
|
2742
|
+
K = np.einsum('bsd,hdm->bhsm', x, W_k_mix)
|
|
2743
|
+
V = np.einsum('bsd,hdm->bhsm', x, W_v_mix)
|
|
2733
2744
|
|
|
2734
2745
|
else:
|
|
2735
2746
|
Q = np.einsum('bsd,hdm->bhsm', x, W_q_mix)
|
|
@@ -2880,13 +2891,12 @@ class Transformer(TargetMemoryMixin):
|
|
|
2880
2891
|
def forward(self, input_ids, AME=None, _update_quality_matrix=None, embedded=False, pad_token_id=0, training=True, attn_dropout=0.1, ffn_dropout=0.1):
|
|
2881
2892
|
eps = 1e-3
|
|
2882
2893
|
self._forward_count += 1
|
|
2883
|
-
|
|
2884
2894
|
|
|
2885
2895
|
# Clean up old cache entries before storing new ones
|
|
2886
2896
|
self._clear_forward_cache(keep_essential=True, max_age_forward_passes=5)
|
|
2887
2897
|
|
|
2888
2898
|
if embedded:
|
|
2889
|
-
x = self._handle_indices(input_ids, dtype=np.
|
|
2899
|
+
x = self._handle_indices(input_ids, dtype=np.float64)
|
|
2890
2900
|
if x.ndim == 2:
|
|
2891
2901
|
x = x[np.newaxis, ...]
|
|
2892
2902
|
batch_size, seq_len, _ = x.shape
|
|
@@ -2894,7 +2904,7 @@ class Transformer(TargetMemoryMixin):
|
|
|
2894
2904
|
self.cache['input_ids'] = None
|
|
2895
2905
|
mask = None
|
|
2896
2906
|
else:
|
|
2897
|
-
input_ids = self._handle_indices(input_ids, dtype=np.
|
|
2907
|
+
input_ids = self._handle_indices(input_ids, dtype=np.float32)
|
|
2898
2908
|
if input_ids.ndim == 1:
|
|
2899
2909
|
input_ids = input_ids[np.newaxis, :]
|
|
2900
2910
|
|
|
@@ -7992,11 +8002,11 @@ class ExplainabilityModule:
|
|
|
7992
8002
|
})
|
|
7993
8003
|
|
|
7994
8004
|
print('=== DECISION HISTORY REPORT ===')
|
|
7995
|
-
print(f
|
|
7996
|
-
print(f
|
|
7997
|
-
print(f
|
|
7998
|
-
print(f
|
|
7999
|
-
print(f
|
|
8005
|
+
print(f"[=] ID: {history['id']}")
|
|
8006
|
+
print(f"[=] Timestamp: {history['timestamp']}")
|
|
8007
|
+
print(f"[=] Processed Input: {history['input']}")
|
|
8008
|
+
print(f"[=] Prediction: {history['prediction']}")
|
|
8009
|
+
print(f"[=] Confidence: {history['confidence']}")
|
|
8000
8010
|
|
|
8001
8011
|
return history
|
|
8002
8012
|
|
|
@@ -10384,6 +10394,7 @@ class AgentDistributedInference:
|
|
|
10384
10394
|
self._health_check_interval = 30 # seconds
|
|
10385
10395
|
|
|
10386
10396
|
self.use_async = use_async
|
|
10397
|
+
self.agent_id = id(self)
|
|
10387
10398
|
|
|
10388
10399
|
# Register message handlers
|
|
10389
10400
|
print('[=++=] Initiating message Queue')
|
|
@@ -11372,7 +11383,12 @@ class AgentDistributedInference:
|
|
|
11372
11383
|
|
|
11373
11384
|
if not text and not test_titles:
|
|
11374
11385
|
print('[INFO] No text or test_titles in message payload.')
|
|
11375
|
-
|
|
11386
|
+
|
|
11387
|
+
if test_titles is not None and self.predict_manager is None:
|
|
11388
|
+
raise RuntimeError('[>] predict manager not set; cannot run advanced prediction method')
|
|
11389
|
+
if text is None and test_titles is None:
|
|
11390
|
+
raise ValueError('[>] Payload has neither text or titles.')
|
|
11391
|
+
|
|
11376
11392
|
# Run the actual prediction
|
|
11377
11393
|
print(f'[=] Initiating prediction method')
|
|
11378
11394
|
try:
|
|
@@ -11405,8 +11421,10 @@ class AgentDistributedInference:
|
|
|
11405
11421
|
|
|
11406
11422
|
else:
|
|
11407
11423
|
print('[=] Iniatiting basic prediction...')
|
|
11408
|
-
result = await asyncio.to_thread(self.pipeline.
|
|
11409
|
-
|
|
11424
|
+
result = await asyncio.to_thread(self.pipeline.predict_text, text)
|
|
11425
|
+
if not isinstance(result, dict):
|
|
11426
|
+
raise TypeError(f"[>] Predict single returned {type(result).__name__}: {result!r}")
|
|
11427
|
+
|
|
11410
11428
|
return {
|
|
11411
11429
|
'type': self.MSG_TYPES['PREDICT_RESPONSE'],
|
|
11412
11430
|
'prediction': result.get('prediction'),
|
|
@@ -11418,7 +11436,7 @@ class AgentDistributedInference:
|
|
|
11418
11436
|
else:
|
|
11419
11437
|
|
|
11420
11438
|
print('[=] Basic prediction method')
|
|
11421
|
-
result = await asyncio.to_thread(self.pipeline.
|
|
11439
|
+
result = await asyncio.to_thread(self.pipeline.predict_text, text)
|
|
11422
11440
|
|
|
11423
11441
|
return {
|
|
11424
11442
|
'type': self.MSG_TYPES['PREDICT_RESPONSE'],
|
|
@@ -11799,7 +11817,7 @@ class AgentDistributedInference:
|
|
|
11799
11817
|
msg_len = int.from_bytes(data_len, 'big')
|
|
11800
11818
|
if msg_len > self.max_message_size:
|
|
11801
11819
|
print('[=] message size exceeds maximum to be handled')
|
|
11802
|
-
self.
|
|
11820
|
+
self._log_security_event('message_too_large', {'size': msg_len})
|
|
11803
11821
|
return None
|
|
11804
11822
|
|
|
11805
11823
|
data = b''
|
|
@@ -13736,6 +13754,17 @@ class IntegratedPipeline:
|
|
|
13736
13754
|
self.tfidf.fit_transform(text).toarray()
|
|
13737
13755
|
vocab_size = len(self.tfidf.get_feature_names_out())
|
|
13738
13756
|
self.vocab_size = vocab_size
|
|
13757
|
+
|
|
13758
|
+
def predict_text(self, text):
|
|
13759
|
+
probs = np.asarray(self.predict_single(text), dtype=np.float64).ravel()
|
|
13760
|
+
idx = int(np.argmax(probs))
|
|
13761
|
+
label_map = getattr(self.manager, 'label_map')
|
|
13762
|
+
reverse = {v: k for k, v in label_map.items()}
|
|
13763
|
+
return {
|
|
13764
|
+
'prediction': reverse.get(idx, f'class_{idx}'),
|
|
13765
|
+
'confidence': float(probs[idx]),
|
|
13766
|
+
'probabilities': probs.tolist(),
|
|
13767
|
+
}
|
|
13739
13768
|
|
|
13740
13769
|
|
|
13741
13770
|
def initialize_model_encoding(self, X, y_raw):
|
|
@@ -14856,40 +14885,37 @@ class IntegratedPipeline:
|
|
|
14856
14885
|
return None
|
|
14857
14886
|
|
|
14858
14887
|
def prediction_batch(self, texts):
|
|
14859
|
-
|
|
14888
|
+
"""Returns an ndarray of shape (len(texts), num_classes) with probabilities."""
|
|
14889
|
+
# normalise input
|
|
14890
|
+
if texts is None:
|
|
14891
|
+
return np.zeros((0, self._get_num_classes() or 1))
|
|
14892
|
+
if isinstance(texts, (str, np.str_)):
|
|
14893
|
+
texts = [texts]
|
|
14894
|
+
texts = [t[0] if isinstance(t, tuple) else t for t in texts]
|
|
14895
|
+
texts = ['' if t is None else str(t) for t in texts]
|
|
14860
14896
|
if not texts:
|
|
14861
|
-
return
|
|
14862
|
-
|
|
14863
|
-
# Prepare batch inputs
|
|
14897
|
+
return np.zeros((0, self._get_num_classes() or 1))
|
|
14864
14898
|
|
|
14865
|
-
|
|
14866
|
-
|
|
14899
|
+
if self.model3 is None:
|
|
14900
|
+
raise RuntimeError('[>] MLP model is not initialized/trained; cannot predict')
|
|
14867
14901
|
|
|
14868
|
-
|
|
14869
|
-
|
|
14870
|
-
|
|
14871
|
-
input_ids_list.append(input_ids)
|
|
14872
|
-
|
|
14873
|
-
# Prepare MLP input
|
|
14874
|
-
if not hasattr(self, 'tfidf') or self.tfidf is None:
|
|
14875
|
-
self.initialize_fitting([text])
|
|
14876
|
-
X_raw = self.tfidf.transform([text]).toarray()
|
|
14877
|
-
X_raw_list.append(X_raw)
|
|
14878
|
-
|
|
14879
|
-
# Stack into batches
|
|
14880
|
-
batch_input_ids = np.vstack(input_ids_list) # (batch_size, seq_len)
|
|
14881
|
-
batch_X_raw = np.vstack(X_raw_list) # (batch_size, features)
|
|
14882
|
-
|
|
14883
|
-
if self.labels is None and self.titles is None:
|
|
14884
|
-
_, y_true = self.input_encoding(list(zip(texts, texts))) # No-value labels for y_true
|
|
14885
|
-
else:
|
|
14886
|
-
dataset, _ = self.data_preparation(self.titles, self.labels)
|
|
14887
|
-
y_true = self.input_encoding(dataset)
|
|
14888
|
-
|
|
14889
|
-
# Run batch prediction through your existing logic
|
|
14890
|
-
return self._batch_prediction_core(batch_input_ids, batch_X_raw, y_true)
|
|
14902
|
+
# MLP features: same hashing vectorizer as training, never refit on request text
|
|
14903
|
+
_, X_raw = self.data_preparation(texts)
|
|
14904
|
+
X_raw = np.asarray(X_raw, dtype=np.float64)
|
|
14891
14905
|
|
|
14906
|
+
first = self.model3.layers[0] if self.model3.layers else None
|
|
14907
|
+
input_dim = getattr(first, 'input_size', None)
|
|
14908
|
+
if input_dim and X_raw.shape[1] != input_dim:
|
|
14909
|
+
X_raw = self.shape_adaptation(X_raw, input_dim)
|
|
14892
14910
|
|
|
14911
|
+
# transformer token ids
|
|
14912
|
+
if not self.vocab:
|
|
14913
|
+
self.text_encoder(texts)
|
|
14914
|
+
ids = np.array([self.encode(t, self.vocab) for t in texts], dtype=np.int64)
|
|
14915
|
+
if self.model2 is not None and hasattr(self.model2, 'token_embedding'):
|
|
14916
|
+
ids = np.clip(ids, 0, self.model2.token_embedding.shape[0] - 1)
|
|
14917
|
+
|
|
14918
|
+
return self._batch_prediction_core(ids, X_raw, batch_size=None, show_progress=False)
|
|
14893
14919
|
|
|
14894
14920
|
def _batch_model_memory_gate(self, batch_input_ids, batch_X_raw):
|
|
14895
14921
|
batch_probs = [None] * len(batch_input_ids)
|
|
@@ -15080,10 +15106,8 @@ class IntegratedPipeline:
|
|
|
15080
15106
|
fresh_mlp_confidence = fresh_probs.max(axis=1, keepdims=True)
|
|
15081
15107
|
fresh_trans_confidence = fresh_trans_probs.max(axis=1, keepdims=True)
|
|
15082
15108
|
|
|
15083
|
-
|
|
15084
|
-
|
|
15085
|
-
else:
|
|
15086
|
-
fresh_probs = fresh_trans_probs.copy()
|
|
15109
|
+
use_mlp = (fresh_mlp_confidence >= fresh_trans_confidence)
|
|
15110
|
+
fresh_probs = np.where(use_mlp, fresh_probs, fresh_trans_probs)
|
|
15087
15111
|
|
|
15088
15112
|
if np.std(fresh_probs) < 0.3 or np.mean(fresh_probs) < 0.3:
|
|
15089
15113
|
fresh_probs = self.predict_proba(
|
|
@@ -15215,18 +15239,20 @@ class IntegratedPipeline:
|
|
|
15215
15239
|
return None
|
|
15216
15240
|
|
|
15217
15241
|
|
|
15218
|
-
def predict_single(self, text):
|
|
15242
|
+
def predict_single(self, text, timeout=250):
|
|
15219
15243
|
result = [None]
|
|
15244
|
+
done = threading.Event()
|
|
15220
15245
|
|
|
15221
15246
|
def callback(r):
|
|
15222
15247
|
result[0] = r
|
|
15248
|
+
done.set()
|
|
15223
15249
|
|
|
15224
15250
|
self.predict_async(text, callback)
|
|
15225
|
-
|
|
15251
|
+
if not done.wait(timeout):
|
|
15252
|
+
raise TimeoutError('[>] Single async prediction timed out.')
|
|
15226
15253
|
# Wait for result
|
|
15227
|
-
|
|
15228
|
-
|
|
15229
|
-
|
|
15254
|
+
if isinstance(result[0], BaseException):
|
|
15255
|
+
raise result[0]
|
|
15230
15256
|
return result[0]
|
|
15231
15257
|
|
|
15232
15258
|
|
|
@@ -15276,10 +15302,8 @@ class IntegratedPipeline:
|
|
|
15276
15302
|
fresh_mlp_confidence = fresh_probs.max(axis=1, keepdims=True)
|
|
15277
15303
|
fresh_trans_confidence = fresh_trans_probs.max(axis=1, keepdims=True)
|
|
15278
15304
|
|
|
15279
|
-
|
|
15280
|
-
|
|
15281
|
-
else:
|
|
15282
|
-
fresh_probs = fresh_trans_probs.copy()
|
|
15305
|
+
use_mlp = (fresh_mlp_confidence >= fresh_trans_confidence)
|
|
15306
|
+
fresh_probs = np.where(use_mlp, fresh_probs, fresh_trans_probs)
|
|
15283
15307
|
|
|
15284
15308
|
if np.std(fresh_probs) < 0.3 or np.mean(fresh_probs) < 0.3:
|
|
15285
15309
|
fresh_probs, _ = self.ensemble.predict_ensemble(
|
|
@@ -15577,12 +15601,12 @@ class IntegratedPipeline:
|
|
|
15577
15601
|
list_probs.append(peer_probs)
|
|
15578
15602
|
|
|
15579
15603
|
for vote in votes:
|
|
15580
|
-
print(f'[+] Prediction: {vote[
|
|
15581
|
-
print(f'[+] Confidence: {vote[
|
|
15582
|
-
print(f'[+] Trust: {vote[
|
|
15583
|
-
if vote[
|
|
15604
|
+
print(f'[+] Prediction: {vote["prediction"]}')
|
|
15605
|
+
print(f'[+] Confidence: {vote["confidence"]}')
|
|
15606
|
+
print(f'[+] Trust: {vote["trust_score"]}')
|
|
15607
|
+
if vote["confidence"] > self.confidence_threshold:
|
|
15584
15608
|
for i in range(len(probs)):
|
|
15585
|
-
probs = probs[i] * (1.0 + vote[
|
|
15609
|
+
probs = probs[i] * (1.0 + vote["trust_score"] * vote["confidence"])
|
|
15586
15610
|
probs = probs.copy() / np.sum(probs) # Normalize after adjustment
|
|
15587
15611
|
else:
|
|
15588
15612
|
print(f'[-] No alive agents found, Total: {alive_agents} Agent found. Using local prediction only.')
|
|
@@ -19360,6 +19384,9 @@ class PipelineAsyncManager:
|
|
|
19360
19384
|
self.max_workers = max_workers
|
|
19361
19385
|
self.default_timeout = task_timeout
|
|
19362
19386
|
self.max_retries = max_retries
|
|
19387
|
+
|
|
19388
|
+
self.pipeline.manager = self.prediction_manager
|
|
19389
|
+
self.pipeline.distribution.predict_manager = self.prediction_manager
|
|
19363
19390
|
|
|
19364
19391
|
self.security_level = security_level
|
|
19365
19392
|
self.config = self._get_config_for_level(security_level) or SecurityConfig()
|
|
@@ -23443,7 +23470,7 @@ class PipelinePredictionManager:
|
|
|
23443
23470
|
|
|
23444
23471
|
return result, cached['prediction'], cached['confidence']
|
|
23445
23472
|
else:
|
|
23446
|
-
print(f'[!] Similarity: {cached[
|
|
23473
|
+
print(f'[!] Similarity: {cached["similarity"]} is low, Cannot pick label due to low certainty, Initiating advanced prediction...')
|
|
23447
23474
|
target_probs = mlp_probs.copy()
|
|
23448
23475
|
else:
|
|
23449
23476
|
print('[=] No verified output from cache available that matched samples, starting advanced prediction...')
|
|
@@ -24282,73 +24309,77 @@ class PipelinePredictionManager:
|
|
|
24282
24309
|
total_with_expected = 0
|
|
24283
24310
|
X_samples, input_ids = payload['X_samples'], payload['input_ids']
|
|
24284
24311
|
|
|
24285
|
-
if
|
|
24312
|
+
if self.error_counts is None and self.label_map is not None:
|
|
24286
24313
|
self.error_counts = np.zeros(len(self.label_map), dtype=np.float32)
|
|
24287
24314
|
|
|
24288
|
-
|
|
24289
|
-
|
|
24290
|
-
|
|
24291
|
-
|
|
24292
|
-
|
|
24293
|
-
|
|
24294
|
-
|
|
24295
|
-
|
|
24296
|
-
|
|
24297
|
-
|
|
24298
|
-
|
|
24299
|
-
|
|
24300
|
-
|
|
24301
|
-
|
|
24302
|
-
|
|
24303
|
-
|
|
24304
|
-
|
|
24315
|
+
if self.error_counts is not None and self.label_map is not None:
|
|
24316
|
+
for idx, result in enumerate(results):
|
|
24317
|
+
print(f"\n{idx+1}. 📌 '{result['title']}'")
|
|
24318
|
+
if result.get('expected'):
|
|
24319
|
+
total_with_expected += 1
|
|
24320
|
+
status = ": ✅" if result['predicted'] == result['expected'] else ": ❌"
|
|
24321
|
+
print(f"[=] First Expectation: {result['expected']} || Model Answer: {status}")
|
|
24322
|
+
|
|
24323
|
+
if 'sec_predicted' in result:
|
|
24324
|
+
sec_status = ": ✅" if result['sec_predicted'] == result['expected'] else ": ❌"
|
|
24325
|
+
print(f"[=] Second Expectation: {result['expected']} || Model Answer: {sec_status}")
|
|
24326
|
+
if 'sec_predicted' in result and 'sec_confidence' in result and result['sec_predicted'] == result['expected']:
|
|
24327
|
+
self.pipeline.accurate_cache_lookup.add_verified(
|
|
24328
|
+
X_samples, input_ids,
|
|
24329
|
+
result['sec_predicted'], result['sec_confidence'], result['sec_index'],
|
|
24330
|
+
source='automatic_verified')
|
|
24331
|
+
|
|
24332
|
+
sec_correct += 1
|
|
24333
|
+
else:
|
|
24334
|
+
error += 1
|
|
24335
|
+
if result.get('predicted_idx') < len(self.error_counts):
|
|
24336
|
+
if isinstance(self.error_counts[result.get('predicted_idx')], (int, float)):
|
|
24337
|
+
self.error_counts[result.get('predicted_idx')] += 1.0
|
|
24338
|
+
|
|
24339
|
+
if result['predicted'] == result['expected']:
|
|
24340
|
+
if 'sec_index' in result and result['sec_index'] is None:
|
|
24341
|
+
result['sec_index'] = None
|
|
24342
|
+
|
|
24343
|
+
if 'predicted_idx' in result and 'confidence' in result and 'predicted' in result:
|
|
24344
|
+
self.pipeline.accurate_cache_lookup.add_verified(
|
|
24345
|
+
X_samples, input_ids,
|
|
24346
|
+
result['predicted'], result['confidence'], result['predicted_idx'],
|
|
24347
|
+
source='automatic_verified')
|
|
24348
|
+
correct += 1
|
|
24305
24349
|
else:
|
|
24306
24350
|
error += 1
|
|
24307
24351
|
if result.get('predicted_idx') < len(self.error_counts):
|
|
24308
|
-
if isinstance(self.error_counts[result.get('predicted_idx')], (int, float)):
|
|
24352
|
+
if len(self.error_counts) > 0 and isinstance(self.error_counts[result.get('predicted_idx')], (int, float)):
|
|
24309
24353
|
self.error_counts[result.get('predicted_idx')] += 1.0
|
|
24354
|
+
|
|
24355
|
+
# Agreement indicator
|
|
24356
|
+
agree_symbol = "✓" if result.get('models_agree', True) else "⚠️"
|
|
24357
|
+
print(f"[=] {agree_symbol} FINAL: {result['predicted']} ({result['confidence']:.1%})")
|
|
24310
24358
|
|
|
24311
|
-
|
|
24312
|
-
|
|
24313
|
-
|
|
24314
|
-
|
|
24315
|
-
|
|
24316
|
-
|
|
24317
|
-
|
|
24318
|
-
|
|
24319
|
-
|
|
24320
|
-
|
|
24321
|
-
|
|
24322
|
-
|
|
24323
|
-
|
|
24324
|
-
|
|
24325
|
-
|
|
24326
|
-
|
|
24327
|
-
|
|
24328
|
-
|
|
24329
|
-
|
|
24330
|
-
|
|
24331
|
-
|
|
24332
|
-
|
|
24333
|
-
|
|
24334
|
-
|
|
24335
|
-
print(f" └─ [🌀] Transformer: {result['transformer_prediction']} ({result['transformer_confidence']:.1%}) {arrow}")
|
|
24336
|
-
|
|
24337
|
-
# Top predictions
|
|
24338
|
-
if 'top_predictions' in result:
|
|
24339
|
-
print(f"\n [🔍] Top {top_k} possibilities:")
|
|
24340
|
-
for j, pred in enumerate(result['top_predictions'][:top_k], 1):
|
|
24341
|
-
bar = '█' * int(pred['confidence'] * 20)
|
|
24342
|
-
print(f" {j}. {pred['label']:20s} {bar} {pred['confidence']:.1%}")
|
|
24343
|
-
|
|
24344
|
-
if total_with_expected > 0:
|
|
24345
|
-
accuracy = correct / total_with_expected
|
|
24346
|
-
print(f"\n📊 Accuracy: {correct}/{total_with_expected} = {accuracy:.1%}")
|
|
24347
|
-
if accuracy > acc_threshold:
|
|
24348
|
-
if self.pipeline.lstm_engine:
|
|
24349
|
-
self.pipeline.storage.save_weights(self.pipeline.memory_name, model_type='Pipeline')
|
|
24350
|
-
|
|
24351
|
-
return correct, sec_correct
|
|
24359
|
+
# MLP vs Transformer
|
|
24360
|
+
print(f" ├─ [⚡] MLP: {result['mlp_prediction']} ({result['mlp_confidence']:.1%})")
|
|
24361
|
+
if result.get('transformer_prediction'):
|
|
24362
|
+
arrow = "⬆️" if result['transformer_confidence'] > result['mlp_confidence'] else "⬇️"
|
|
24363
|
+
print(f" └─ [🌀] Transformer: {result['transformer_prediction']} ({result['transformer_confidence']:.1%}) {arrow}")
|
|
24364
|
+
|
|
24365
|
+
# Top predictions
|
|
24366
|
+
if 'top_predictions' in result:
|
|
24367
|
+
print(f"\n [🔍] Top {top_k} possibilities:")
|
|
24368
|
+
for j, pred in enumerate(result['top_predictions'][:top_k], 1):
|
|
24369
|
+
bar = '█' * int(pred['confidence'] * 20)
|
|
24370
|
+
print(f" {j}. {pred['label']:20s} {bar} {pred['confidence']:.1%}")
|
|
24371
|
+
|
|
24372
|
+
if total_with_expected > 0:
|
|
24373
|
+
accuracy = correct / total_with_expected
|
|
24374
|
+
print(f"\n📊 Accuracy: {correct}/{total_with_expected} = {accuracy:.1%}")
|
|
24375
|
+
if accuracy > acc_threshold:
|
|
24376
|
+
if self.pipeline.lstm_engine:
|
|
24377
|
+
self.pipeline.storage.save_weights(self.pipeline.memory_name, model_type='Pipeline')
|
|
24378
|
+
|
|
24379
|
+
return correct, sec_correct
|
|
24380
|
+
else:
|
|
24381
|
+
print('[>] Display hybrid results is skipped due to unmet conditions.')
|
|
24382
|
+
return correct, sec_correct
|
|
24352
24383
|
|
|
24353
24384
|
class ConsecutivePeerAgent:
|
|
24354
24385
|
"""
|
|
@@ -24473,7 +24504,7 @@ class ConsecutivePeerAgent:
|
|
|
24473
24504
|
print(f'[ConsecutivePeerAgent] Received a message!')
|
|
24474
24505
|
except (json.JSONDecodeError, UnicodeDecodeError) as e:
|
|
24475
24506
|
logger.warning(f'[=] Invalid JSON from peer: {e}')
|
|
24476
|
-
self._log_security_event('invalid_json', {})
|
|
24507
|
+
self.pipeline.distribution._log_security_event('invalid_json', {})
|
|
24477
24508
|
return None
|
|
24478
24509
|
|
|
24479
24510
|
message = self._decode_arrays_from_wire(message)
|
|
@@ -24698,8 +24729,8 @@ class ConsecutivePeerAgent:
|
|
|
24698
24729
|
peer_results.append(result)
|
|
24699
24730
|
|
|
24700
24731
|
print(f"[ConsecutivePeerAgent] Peer {host}:{port}: {result['prediction']} ({result['confidence']:.1%})")
|
|
24701
|
-
print(f
|
|
24702
|
-
print(f'[==] Peer result: {result[
|
|
24732
|
+
print(f"[==] Local result: {local_result['prediction']} With Confidence: {local_result['confidence']}")
|
|
24733
|
+
print(f'[==] Peer result: {result["prediction"]} With Confidence: {result["confidence"]}')
|
|
24703
24734
|
|
|
24704
24735
|
if peer_results:
|
|
24705
24736
|
best_peer = max(peer_results, key=lambda x: x['confidence'])
|
|
@@ -24902,6 +24933,9 @@ class CohesiveAgentDeployment:
|
|
|
24902
24933
|
target_title=target_title,
|
|
24903
24934
|
label=label_name
|
|
24904
24935
|
)
|
|
24936
|
+
self.pipeline.manager = self.manager
|
|
24937
|
+
self.pipeline.distribution.predict_manager = self.manager
|
|
24938
|
+
|
|
24905
24939
|
if self.manager.config is None and predict_manager is not None:
|
|
24906
24940
|
self.manager.config = predict_manager.config
|
|
24907
24941
|
|
|
@@ -26126,8 +26160,6 @@ async def run_secure_agent_cluster(pipeline,test_titles, label_map, rules, X=Non
|
|
|
26126
26160
|
|
|
26127
26161
|
# Get API keys
|
|
26128
26162
|
api_key = agent1.get_api_key()
|
|
26129
|
-
print(f"\n🔑 Using API Key: {api_key[:20]}...")
|
|
26130
|
-
|
|
26131
26163
|
texts = {"test_titles": test_titles, "label_map": label_map, "rules": rules, "X":X, "y":y, "use_transformer": True, "agent_id": agent_id}
|
|
26132
26164
|
|
|
26133
26165
|
if daily is not None:
|