AbstractIntegratedModule 1.3.3__tar.gz → 1.3.4__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 (27) hide show
  1. abstractintegratedmodule-1.3.4/AbstractIntegratedModule.egg-info/PKG-INFO +1378 -0
  2. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/AbstractIntegratedModule.egg-info/SOURCES.txt +0 -1
  3. abstractintegratedmodule-1.3.4/AbstractIntegratedModule.egg-info/requires.txt +8 -0
  4. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/AbstractIntegratedModule.py +26635 -26633
  5. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/AbstractOptimizedModules.c +24688 -24688
  6. abstractintegratedmodule-1.3.4/PKG-INFO +1378 -0
  7. abstractintegratedmodule-1.3.4/README.md +1351 -0
  8. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/pyproject.toml +14 -7
  9. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/setup.cfg +4 -4
  10. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/setup.py +3 -2
  11. abstractintegratedmodule-1.3.3/AbstractIntegratedModule.egg-info/PKG-INFO +0 -19
  12. abstractintegratedmodule-1.3.3/AbstractIntegratedModule.egg-info/requires.txt +0 -1
  13. abstractintegratedmodule-1.3.3/PKG-INFO +0 -19
  14. abstractintegratedmodule-1.3.3/README.md +0 -1951
  15. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/AbstractIntegratedModule.egg-info/dependency_links.txt +0 -0
  16. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/AbstractIntegratedModule.egg-info/top_level.txt +0 -0
  17. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/AbstractOptimizedModules.pyx +0 -0
  18. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/MANIFEST.in +0 -0
  19. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/Cargo.toml +0 -0
  20. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/pyproject.toml +0 -0
  21. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/src/lib.rs +0 -0
  22. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/target/debug/build/libsqlite3-sys-ed07b882cd2aa5e2/out/bindgen.rs +0 -0
  23. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/target/debug/build/serde_core-ebc15f2e9cad7f5f/out/private.rs +0 -0
  24. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/target/debug/build/target-lexicon-08527f45de28143d/out/host.rs +0 -0
  25. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/target/release/build/libsqlite3-sys-bf0400df4523274c/out/bindgen.rs +0 -0
  26. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/target/release/build/serde_core-5cdb76131825e4af/out/private.rs +0 -0
  27. {abstractintegratedmodule-1.3.3 → abstractintegratedmodule-1.3.4}/abstract_model_storage/target/release/build/target-lexicon-43eb95a0588bf457/out/host.rs +0 -0
@@ -0,0 +1,1378 @@
1
+ Metadata-Version: 2.4
2
+ Name: AbstractIntegratedModule
3
+ Version: 1.3.4
4
+ Summary: IntegratedPipeline Specifically provide a Framework to build Stateful continual learning Machine Learning Models optimized for Edge devices (ARM64).
5
+ Author: Micro-Novelty
6
+ Author-email: Micro-Novelty <hernikpuspita5@gmail.com>
7
+ License-Expression: MIT
8
+ Project-URL: Main-Repository, https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent-Framework
9
+ Project-URL: Second-Repository, https://github.com/Micro-Novelty/abstract-modules
10
+ Project-URL: Releases, https://github.com/Micro-Novelty/abstract-modules/releases
11
+ Project-URL: Issues, https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent-Framework/issues
12
+ Project-URL: Open-PRs, https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent-Framework/pulls
13
+ Project-URL: Architecture-Docs, https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent-Framework/blob/main/ARCHITECTURE.md
14
+ Project-URL: Patched-Vulnerabilities, https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent-Framework/blob/main/SECURITY.md
15
+ Requires-Python: > 3.9
16
+ Description-Content-Type: text/markdown
17
+ Requires-Dist: numpy>=1.23.2
18
+ Requires-Dist: pandas>=1.5
19
+ Requires-Dist: scikit-learn>=1.1.3
20
+ Requires-Dist: joblib>=1.1
21
+ Requires-Dist: cryptography>=3.1
22
+ Requires-Dist: aiohttp>=3.8.3
23
+ Requires-Dist: psutil>=5.9
24
+ Requires-Dist: aiofiles>=0.8
25
+ Dynamic: author
26
+ Dynamic: requires-python
27
+
28
+ # [=] AbstractIntegratedModule, Specialized-AI-Agent-framework for Non-LLM Continual-learning edge AI Models.
29
+
30
+ [~] Introduction:
31
+ - AbstractIntegratedModule or IntegratedPipeline in short, is a standalone Specialized AI Agent Library for Non-LLM memory Augmented Agentic Framework orchestrator - Specifically designed to provide Agentic capability for any Autonomous Agentic Framework locally and Coordinatively that runs efficiently from consumer based machine to High-end embedded systems, where the AI Can directly and continously learn, with minimal and efficient compute, built-in augmented memory, Secure Peer-To-Peer (Multi-Agent) Coordination with security layers as an option, And Explainability capability based on proof from in it's internal metrics, reducing Black-Box condition necessary for reliability.
32
+ - AbstractIntegratedModule Contains specialized MLP using Its Own specialized geometric Weight shaping (AWE), Specialized efficient Transformer and LSTM (Long-short term memory) architecture for Scarce Data with Alpha-based computation, specifically designed for low-amount samples environment or Messy environments.
33
+ - IntegratedPipeline Use-Case:
34
+ - Tabular Data Prediction: Finding patterns in structured spreadsheets or rows of numerical and categorical features.
35
+ - Classification Tasks: Separating data into groups, such as spam detection, customer churn, or disease diagnosis.
36
+ - Regression Tasks: Predicting continuous numerical values like house prices, sensors output, sales numbers, or weather metrics.
37
+
38
+ ___________________________________________________________________________________________________________________
39
+ ### [+] Framework's Purpose
40
+ - This framework is intended for Engineers who is early in ML Engineering in order to provide a Clearer picture of How edge AI Should operate, Low memory management, and Also how it can be Made continuously learn using Pragmatic solution by using SQLite to save Weights to prevent continuous catasthropic forgetting, IntegratedPipeline source code is open-sourced and can be found in our github repository, Meaning you can modify the Source code however You liked it to be, and help Us Grow the first Community!
41
+
42
+ ____________________________________________________________________________________________________________________
43
+ ### Library Short Description
44
+ - Development Stage on PyPi: 1.2.0 Official Release.
45
+ - Author and Maintainer: Micro-Novelty and EpsitronNet-bot.
46
+ - library Source-Code is Open-sourced with MIT License.
47
+ - Purpose: Specifically Designed for providing Non-LLM AI Agent Framework for edge Devices, Optimized for ARM64 architecture.
48
+ - Library installation:
49
+ ```bash
50
+ pip install AbstractIntegratedModule
51
+ python -m install AbstractIntegratedModule
52
+ ```
53
+
54
+ ### Github Link (for Visiting and cloning)
55
+ - https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent-Framework
56
+
57
+ - The library also includes precompiled binaries for:
58
+ - aarch64 manylinux (accepts version 2.17+) architecture, accepts python version 3.10, 3.11 only.
59
+ - aarch64 musllinux (accepts version 1.2+) architecture, accepts python version 3.10, 3.11 only.
60
+ - Windows 64 bit architecture (python 3.10, 3.11, 3.12, 3.13 only)
61
+ - single tarball file for Users who want to test the library up to Python version 3.12 or 3.13+.
62
+ ____________________________________________________________________________________________________
63
+ - Library installation if you dont have aarch64 setup, you can download the correct wheel for your setup in this repository or by using pip:
64
+ - ✨ use pip for downloading the correct wheels for your setup:
65
+ - ```bash
66
+ pip install abstractintegratedmodule --extra-index-url https://Micro-Novelty.github.io/abstract-modules/whl/ --break-system-packages
67
+ # ensures proper installation by bypassing pip strict external download setup.
68
+ ```
69
+ - Note: Using the above installation --extra-index method provides Python Wheels for:
70
+ - x86_64 and aarch64 with manylinux (v. 2.17+) and musllinux (v. 1.2+) architecture.
71
+ - macOS with aarch64 and x86_64 architecture. (v. 10.9+)
72
+ - All of this Wheels provided in the Repository Only Provides Wheels for python with version 3.10 3.11 and 3.12.
73
+ - This setup will automatically download the correct wheel Based on your python/pip version and OS / hardware architecture setup.
74
+
75
+ - For specific module in Rust for handling and loading Weights and Parsing JSON values with reduced memory lookup overhead.
76
+ - Consider using this Optimization library by using:
77
+ - ```bash
78
+ pip install abstract-weights-core
79
+ ```
80
+ - Note: This Optimization would help AbstractIntegratedModule with faster JSON parsing and much more flexible database handling handled efficiently using Rust programming language.
81
+
82
+ - Proven Capabilities:
83
+ - The library has been thoroughly tested in Multiple Environments from Windows to ARM64 Environment. The library is now Robust for Wider use and Deployment.
84
+ - Proven Works on ARM64 Environment, Training and Prediction works efficient on Docker ARM64 environment with QEMU, good parallelizing behavior is guaranteed.
85
+ - P2P Works efficiently in ARM64 Docker + QEMU, No conflicting socket and all prediction works efficiently.
86
+ - AWE setup Proven Efficient on Hard-uncontrolled dataset such as Activity Recognition from the given Database.
87
+ - LSTM is Optimized efficiently for scarce data with AWE method.
88
+ - Robust Advanced prediction capabilities proven effective on ARM64 Using MLP + LSTM Architectures.
89
+ - Transformer Optimized using Cython, reduced Memory overhead and Reduce CPU Usage, With Reduced Training Time is guaranteed.
90
+ -----
91
+ - Changelog:
92
+ - v1.2.0:
93
+ - [=] New features:
94
+ - Added new Architecture module separate from Main Pipeline usage (This modules is'nt used inside Pipeline prediction):
95
+ - Small-HNSW (Hierarchical Navigable Small World).
96
+ - kNN-Augmented Transformer.
97
+ - PerHeadMemory class to Apply memory to each Transformers Head.
98
+ - Added new Functions to call the kNN-Augmented Transformer for separate usage.
99
+
100
+
101
+ - Note: if you want to see the Changelog history of the library Older versions consider visiting this link:
102
+ - PyPi history: https://pypi.org/project/AbstractIntegratedModule/#history
103
+
104
+ ________________________________________________________________________________________________________________________
105
+ ### [>] Full Documentation Features
106
+ - [Go to IntegratedPipeline-Specialized-AI-Agent-library](#[=]-abstractintegratedmodule-specialized-ai-agent-framework-for-non-llm-continual-learning-edge-ai-models)
107
+ - [Go to Framework purpose](#framework's-purpose)
108
+ - [Go to Library short description](#library-short-description)
109
+ - [Go to MANN Intro](#-MANN-Intro)
110
+ - [Go to Performance Overview](#both-performance-overview)
111
+ - [Go to Abstract Weight Encoder (AWE) Intro](#-abstract-weight-encoder-awe-intro)
112
+ - [Go to LSTM And Transformer Intro](#-lstm-and-transformer-intro)
113
+ - [Go to Why IntegratedPipeline?](#-why-integratedpipeline)
114
+ - [Go to Requirements](#-requirements)
115
+ - [Go to System-Specific-Notes](#-system-specific-notes)
116
+ - [Go to Quickstart with Docker](#-docker-container-application)
117
+ - [Go to Performance in ARM64 Environment/Container](#performance-in-linux-arm64-docker-environmentcontainer)
118
+ - [Go to Step's to use IntegratedPipeline](#-steps-for-library-in-depth-usage)
119
+ - [Go to Troubleshooting](#-troubleshooting)
120
+ - [Go to Detailed process of Alpha-computing](#-detailed-process-of-alpha-computing)
121
+ - [Go to Main Components](#main-components)
122
+ - [Go to Source code](#source-code-of-abstractintegratedmodule)
123
+
124
+ Consider checking:
125
+ - [ROADMAP.md](ROADMAP.md)
126
+ - [SECURITY.md](SECURITY.md)
127
+ - [Contributing.md](Contributing.md)
128
+ - [changelog.md](changelog.md)
129
+ - [requirements-For-Dev](dev_needs.txt) for contributors requirements.
130
+ - [architecture_diagram.js](architecture_diagram.js).
131
+
132
+ ___________________________________________________________________________________________________
133
+ <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" />
134
+
135
+ ## [+] MANN Intro
136
+ [=] Memory augmented Neural network (MANN) is a neural network architecture coupled with an external, dynamic memory module, allowing it to store, retrieve, and update information similarly to a computer's RAM. Unlike traditional networks that store knowledge only in weight parameters, MANNs excel at fast learning, long-term dependency handling, and episodic recall, In IntegratedPipeline, Its memory is stored in a custom database inside your local machine, then later used for memory retrieval, transfered to the AI Dictionary where it can finnaly recall its memory when input condition matched with memory.
137
+
138
+ ## [+] Abstract Weight Encoder (AWE) Intro
139
+ [=] AWE is a specialized custom weight shaping or encoding method Specifically designed for MLP Architecture, using eigenvalue and spectral methods as base equations to calculate covariance inside a given input data, and shape the correct Weight from the given eigenvalue, AWE Works by processing input and then captures the necessary eigenvalue to shape a properly initialized Weight that aligns with input data complexity, With this approach, MLP training will be much more consistent and robust against noise.
140
+
141
+ ## [+] LSTM And Transformer Intro:
142
+ A. LSTMs (Long Short-Term Memory) and Transformers are foundational deep learning architectures built to process sequential data (like text or time series). While both handle the flow of time and context, they do so using completely different mechanisms.
143
+ - LSTM (Long Short-Term Memory):
144
+ - LSTMs are an advanced class of Recurrent Neural Networks (RNNs) introduced to solve the problem of traditional RNNs forgetting earlier data.
145
+ - How it works: LSTMs process data sequentially—one word or time-step at a time. They regulate information using "gates" (forget, input, and output) that determine what information from the sequence to keep or discard.
146
+ - Use Cases: Ideal for tasks with strictly continuous chronological data like time-series forecasting (e.g., stock market or weather prediction) or speech recognition.
147
+ - Limitations: Because they process data in a strict chain, it is difficult to parallelize training, making them slow and prone to forgetting long contexts.
148
+
149
+ B. Transformer:
150
+ Transformers are the modern standard for AI, introduced in 2017 with the famous "Attention Is All You Need" paper.
151
+ - How it works: Instead of reading sequences linearly, Transformers read the entire sequence all at once. They utilize a self-attention mechanism, which calculates how much "attention" or weight every part of the sequence should give to every other part, understanding the global context instantly.
152
+ - Use Cases: The backbone of Large Language Models (LLMs) like ChatGPT or BERT, making them perfect for machine translation, text generation, and summarization.
153
+ - Limitations: Transformers require massive amounts of training data and computing power to work effectively.
154
+ - Data Hungry when Analyzing Images.
155
+
156
+
157
+ [~] For a much In-Depth Explanation You can visit This repository to learn more about AWE and its performance results:
158
+ - Link: https://github.com/Micro-Novelty/Specialized-MLP-for-noise-robustness
159
+
160
+ ## [+] Why IntegratedPipeline?
161
+ [~] IntegratedPipeline is a great choice for a sophisticated Non-LLM AI Program for The Main Orchestrator of a Distributed MANN-Type AI Agent Working in Edge-device/Consumer-Based machine Where LLM is'nt a great fit for Messy, Noisy environments. while still run efficiently on High-end Embedded systems in single-instance or as a distributed network during multi Agent cooperation.
162
+
163
+ [=] IntegratedPipeline offers:
164
+ 1. Local-Based AI Orchestrator:
165
+ - IntegratedPipeline Creates its own SQLite Database inside Your Computer once the library is executed, This database is used directly to store the AI Memory, Attention weights, predicted Output, and identified peer, all without leaving the machine, The Database will be created Automatically once you run the library, database name saved as activity_log.db.
166
+
167
+ 2. Continously Learning behavior for an Agent:
168
+ - different from LLM that is static and cannot improve beyond its given training condition, AI Agent using IntegratedPipeline has a dynamic, flexible continously learning behavior with conditional training algorithms included in the library that has both supervised and unsupervised learning present, The learned input and predicted Output will be stored in the database, allowing it to recall its memory during processing and find matching known prediction given if input matched with the stored input inside the database. this Continous learning behavior is efficient because its not relying on weights for memory, allowing flexible and predictable behavior inside a given environment.
169
+
170
+ 3. Robust Specialized MLP, Transformer and LSTM Architecture with ensemble weighting architecture:
171
+ - IntegratedPipeline usually used 1 Model for regular prediction, but in some Conditions, it used 2 Different type's of AI Architecture stacked together, and one architecture to weight their confidence and probability fairly (ensemble method) to get the final prediction for the problem it faced, Specialized MLP for Noise robustness And Specialized Transformer that used Alpha-based Computing algorithm for contextual reasoning, LSTM architecture to provides proof-of-credibility over a certain output, acting as a support mechanism rather than Main orchestrator like MLP and Transformer. The reason why those Models complement and used together:
172
+ - Specialized MLP Provides synchronous robust classification Against noise with its specialized Weight Encoder (AWE) to handle noise using eigenvalue based computing that is lightweight and efficient. This Method can't be replicated Inside Transformer FFN (Feed-forward-network) because of Transformer dynamic brute force computing where AWE-Based generated weight's get diluted over time by Transformer dynamic projection embedding, making AWE Generated weight causes inefficient inside Transformer dynamic FFN/QKV projection.
173
+ - Specialized Transformer provides robust synchronous advanced contextual relationships, efficient data processing using Alpha based computing, The Transformer is tuned towards to be as flexible as possible to provide dynamic projection or fixed FFN projection training with minimal head's and dimension's to reduce computational power.
174
+ - Our library also provides setup for kNN (k-Nearest-neighbor) Augmented Transformer for Users who Wants to use a much More Advanced Transformer, This Transformer is'nt used in the Main prediction flow inside IntegratedPipeline due to it being Memory heavy to run, instead this Transformer can be used separately if You have Larger Dataset and wants A small Transformer Model that can Remember longer contexts Using HNSW (Hierarchical Navigable Small World) Architecture and apply it on edge Devices.
175
+ - Honest Limitation: Our Transformer can still analyze Images, by receiving Input that is an Image converted into X samples, its accuracy is expected to be much lower since Analyzing images requires larger datasets.
176
+
177
+ - LSTM doesn't act as a Main orchestrator, instead it Provides coherent Short-term memory for the Ensemble architecture, acting as a support mechanism to provides proof-of-credibility of a given answer from past previous context input, this allows flexible and achievable Aggreement between Transformer and MLP over a short period of time.
178
+ - Ensemble weighting provides the model a much more robust classification best from both worlds perspective, weighting both MLP and Transformer confidence and probability, combined with Attention quality from the transformer to get the final prediction of an input if transformer is allowed and permitted to be in use.
179
+
180
+
181
+ 4. flexible and secure Peer-to-Peer Coordination (Multi-Agent):
182
+ - IntegratedPipeline offers Peer to Peer communication capabilities asynchronously, Where IntegratedPipeline directly checks for other Peer presence directly to the local database present in the local computer or system (Synchronous prediction from peer previous data in the database), or externally, by using asynchronous request for initiating prediction, P2P is secured Using:
183
+ - secure socket using user provided SSL CERT. on both client and server,
184
+ - API key for requesting,
185
+ - Alpha rate limiting,
186
+ - HMAC secret key for authentication,
187
+ - and IP validation.
188
+ [~] Each agent has double roles during P2P:
189
+ - Server provider: the peer Agent can start a server to listen for peer client's
190
+ - Connecting Agent: the peer Agent which happens to connect to other peer that has or have opened and provided a server listener to act as a receiver.
191
+
192
+ 5. Cross-Session memory availability:
193
+ - IntegratedPipeline offers share-able Memory capability, included capability below:
194
+ - Exportable memory: this allows a flexible memory saving for later use, such as cross transfer memory between model, the memory is saved as .json file after exporting.
195
+ - Importable Memory: allowing to import memory from the exported .json file directly for the model to use.
196
+ - syncing with other model: socket-based communication to export memory to other external machine.
197
+ - [=] Note: socket Syncing is unsecure witout additional security layer wrapped, For a safer syncing, directly transfer the .json file memory to the target machine via other ways such as manual send.
198
+ - list sessions: listing available sessions using model's memory name.
199
+
200
+ [=] With its Specialized Multi-Layer-Perceptron (using AWE Encoder) and Optimized Transformer module with optimized Embedding, IntegratedPipeline can directly tolerate low samples-amount of Data, including noisy ambiguous data, using Weighted Confidence assembling from both specialized MLP and Transformer for better reliability during training and prediction over Messy, noisy environments, such as:
201
+
202
+ [1.] User data's : User data is often messy and ambiguous, Specialized MLP with AWE will do the job for shaping the necessary Weight to complement for the Ambiguous noisy pattern, AWE MLP is highly robust to noise, proven in synthetic Environment such as scikit-learn Make-Classification scarce and Noisy Input robustness during generalization test. making it a great fit for messy, Scarce data.
203
+
204
+ [2.] Small Dataset's : We often don't have enough Dataset to train a Transformer Model, Thats Why IntegratedPipeline Offers a Highly optimized Transformer that supports scarce dataset processing, Using Alpha-Based computing as a Warm-up for training, it provides a direct Boost for the transformer to be efficient during training in scarce-data Environment.
205
+
206
+ [3.] Non-Representative data (Undersampled) : IntegratedPipeline Support's ambiguous data that come's from file with format such as CSV Format to extract title's and label's necessary to create automatic Dataset for Later use in Training, making it optimized for specific task's and easier dataset creation with lower overfitting rate for reliability.
207
+
208
+ _____________________________________________________________________________________________________________
209
+ [=] Architectural-Overview
210
+ <img width="1600" height="859" alt="New Arch" src="https://github.com/user-attachments/assets/a5db1ed2-9149-4635-8d95-d022ad6e8608" />
211
+ ---
212
+ [=] Contextual meaning:
213
+ 1. - Sequence encoding is a machine learning technique that transforms a sequential input (like text, time-series data, or audio) into a compact, fixed-length numerical vector, often called a context vector
214
+ 2. - TF-IDF (Term Frequency-Inverse Document Frequency) is a numerical statistic used in machine learning and NLP to evaluate how important a word is to a document within a collection (corpus). It boosts rare words and penalizes common words (like "the", "and") by multiplying two metrics: how often a word appears in a document (TF) and the inverse frequency of the word across all documents (IDF).
215
+ 3. - Explainability provides deeper transparency of why a model thought about a detail by showing its internal metrics like attention quality, from distributed peer memory or Ensemble prediction result's.
216
+
217
+
218
+ ### Important Note:
219
+ - All of the files provided here can be found in the github repository, if you are seeing this on PyPi and wanted to Try out the provided .py, .sh or Dockerfile scripts below, consider visiting the official github repository link Above.
220
+
221
+ ### Introduction and demo
222
+ - Video Documentation: [![Introduction and demo:](https://youtube.com)](https://youtu.be/RmWvwDHU_QY?si=Lvl8mt8c_BnFypS_)
223
+ - Quick demo start: [main.py](main.py)
224
+ - purpose: let you demonstrate the advanced prediction method and asynchronous prediction directly.
225
+ - Quick test of P2P:
226
+ - [multi_agent_client.py](P2P_Setups/multi_agent_client.py)
227
+ - [multi_agent_server.py](P2P_Setups/multi_agent_server.py)
228
+ - [P2PDirectTest.py](P2P_Setups/P2PDirectTest.py)
229
+ - Purpose: let you demonstrate simple P2P using AbstractIntegratedModule quickly, there may be bugs in this P2P setup so feel free to share it in issues.
230
+
231
+ ____________________________________________________________________________________________________________________
232
+ ## [=] Requirements
233
+ [~] To run and execute IntegratedPipeline, Requirement's include Or see [Requirements](installation_guides/usage_needs.txt):
234
+ - pip install for quick usage:
235
+ - ```bash
236
+ pip install AbstractIntegratedModule # or
237
+ python -m pip install AbstractIntegratedModule
238
+ ```
239
+
240
+ - (Optional) Download AbstractIntegratedModule Compiled Binary file extension manually in the repository for Users who can't use pip install (Choose one minimal, specified for your needs):
241
+ - AbstractOptimizedModules for Optimizing Transformer using Cython (Optional)
242
+ - AbstractIntegratedModule (Main library)
243
+ - Compiled Binaries can be downloaded from release section in the Main repo or You can use this link:
244
+ - Release section: https://github.com/Micro-Novelty/IntegratedPipeline-Specialized-Non-LLM-AI-Agent-Framework/releases
245
+ - Supported OS: Mac-Os, linux x86-64 and Windows.
246
+
247
+ - NOTE: for Mac-OS or linux x86-64 Users, consider downloading the correct python wheel for your setup in here for a much flexible installation:
248
+ - ```bash
249
+ pip install abstractintegratedmodule --extra-index-url https://Micro-Novelty.github.io/abstract-modules/whl/ --break-system-packages
250
+ ```
251
+ Note: using this installation method grants you a much safer, predictable behavior, and more secure AbstractIntegratedModule library rather than a pure binary file.
252
+
253
+ - (Optional) Libraries needed (For using Compiled binary, not python wheels):
254
+ - Pandas
255
+ - aiohttp
256
+ - scikit-learn
257
+ - numpy
258
+ - psutil
259
+ - cryptography
260
+ - (Optional) Install AbstractIntegratedModule Compiled binaries from release section:
261
+
262
+ [=] for labels assignation:
263
+ - CSV file that contains training labels and titles used for training and prediction label map, example will be provided below, Go to Step's for in-depth Usage below.
264
+
265
+ _______________________________________________________________________________________________________________________
266
+ ### [=] Requirements for Docker container
267
+ - Dockerfile (For Container assembler)
268
+ - Python scripts (Such as main.py for Dockerfile usage).
269
+ - entrypoint.sh (for smart entry point for Dockerfile container usage).
270
+
271
+ ## [=] System-Specific Notes
272
+ 1. Windows:
273
+ - Requires Visual C++ Build Tools for compatibility
274
+ - Use PowerShell or CMD (not WSL bash for best results)
275
+
276
+ 2. Linux:
277
+ - Ensure gcc and build-essential are installed
278
+ - Different distributions may require different package managers
279
+
280
+ 3. ARM64 - Raspberry Pi
281
+ - Installation may take 30+ minutes due to ARM architecture
282
+ - Monitor system resources during installation
283
+ - Consider using faster storage (USB SSD) for better performance
284
+
285
+ ## [=] Docker Container Application
286
+ 0. See [Docker_installation_Section](docker-setups/Docker_installation_Section.md) for an in-depth explanation, or [Quick_Docker_start](docker-setups/Quick_Docker_start.sh) for a quick start.
287
+ - Note Consider checking:
288
+ - [Dockerfile](docker-setups/Dockerfile) contains all the instructions need to assemble a Docker container.
289
+ - [start.sh](docker-setups/start.sh) for Quick single agent start in Docker container.
290
+ - [entrypoint.sh](docker-setups/entrypoint.sh) for a Smart entrypoint used in Dockerfile (Must be downloaded too along with Dockerfile and put in the same folder with Dockerfile after its downloaded)
291
+ - [start-multi-agent-cluster.sh](P2P_Setups/start-multi-agent-cluster.sh) for Multi-agent cluster start in Docker container, What it does:
292
+ - Starts a multi-agent Docker cluster — runs docker-compose up -d in detached mode (background), scaling the agent-client service to 5 simultaneous instances, alongside whatever server is defined in the docker-compose.yml.
293
+ - Tails the logs — runs docker-compose logs -f which streams live logs from all containers (server + all 5 clients) to your terminal until you hit Ctrl+C.
294
+ - [main.py](main.py) for executing a python script in the Docker container that used main.py, like in this code:
295
+ - ```bash
296
+ docker run -it -v $(pwd):/app/data integrated-pipeline:latest python /app/data/main.py
297
+ ```
298
+ - To use a [.dockerignore](docker-setups/.dockerignore) file, place it in your build context directory (the same location as your Dockerfile) to specify which files and folders should be excluded when building your image.
299
+ - [.env](.env) is used for environment setup in [entrypoint.sh](docker-setups/entrypoint.sh), this file must be in the same folder with Dockerfile and entrypoint.sh after its downloaded.
300
+
301
+ 1. Build Image:
302
+ - Clone repository:
303
+ - ```bash
304
+ git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git
305
+ cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework
306
+ ```
307
+ - Download:
308
+ - [Dockerfile](docker-setups/Dockerfile),
309
+ - [entrypoint.sh](docker-setups/entrypoint.sh)
310
+ - [.env](docker-setups/.env)
311
+ - In the code or release section.
312
+
313
+ - If the downloaded Dockerfile or .dockerignore or .env has .txt extension, remove the extension:
314
+ - ```bash
315
+ # remove .txt extension
316
+ mv Dockerfile.txt Dockerfile
317
+ mv env.txt .env
318
+ mv dockerignore.txt .dockerignore
319
+ ```
320
+ - Navigate to the folder: Use the cd command to enter the directory containing the Dockerfile and entrypoint.sh file.
321
+ - ```
322
+ cd /path/to/your/folder
323
+ ```
324
+ - build image:
325
+ - ```bash
326
+ sudo docker build -t integrated-agent.
327
+ ```
328
+ 2. Download library dependencies for binaries usage:
329
+ - [Optional]: Required libraries (when using binary, not python wheel provided in the library):
330
+ - Numpy
331
+ - Scikit-learn
332
+ - pandas
333
+ - aiohttp
334
+ - psutil
335
+
336
+ 4. Run IntegratedPipeline in a Container:
337
+ - Install AbstractIntegratedModule via PIP or Compiled binaries:
338
+ - ```bash
339
+ pip install AbstractIntegratedModule # or
340
+ python -m pip install AbstractIntegratedModule
341
+ ```
342
+
343
+ - ```bash
344
+ docker run -it --name ai-agent integrated-agent:latest python
345
+ ```
346
+ - In python shell:
347
+ - ```
348
+ from AbstractIntegratedModule import IntegratedPipeline, PipelinePredictionManager
349
+ model = IntegratedPipeline('agent_memory')
350
+ print("✓ IntegratedPipeline initialized successfully!")
351
+ ```
352
+
353
+ 5. Run script:
354
+ ```bash
355
+ # Mount your local directory and run a script
356
+ docker run -it -v $(pwd)/data:/app/data integrated-agent:latest python main.py # main.py could be replaced
357
+ ```
358
+
359
+ 6. Run with GPU Support (Optional):
360
+ - ```bash
361
+ # For NVIDIA GPU support
362
+ docker run -it --gpus all -v $(pwd)/data:/app/data integrated-agent:latest python main.py
363
+ ```
364
+
365
+ 7. For Single Agent and Multi-Agent P2P:
366
+
367
+ [=] Single agent:
368
+ ```bash
369
+ # Build image
370
+ docker build -t integrated-agent:latest .
371
+
372
+ # Run single agent
373
+ docker run -it -v $(pwd)/data:/app/data integrated-agent:latest python
374
+ ```
375
+
376
+ [=] Multi agent P2P (Consider docker-compose) :
377
+ - Note: Use the provided [docker-compose.yml](docker-setups/docker-compose.yml) for Quick multi-agent.
378
+ - Navigate to the folder: Use the cd command to enter the directory containing the docker-compose.yml file.
379
+ - ```
380
+ cd /path/to/your/folder
381
+ ```
382
+ - run this command to run docker-compose.yml:
383
+ - ```bash
384
+ # Start multiple agents
385
+ docker-compose up -d
386
+
387
+ # View logs
388
+ docker-compose logs -f
389
+
390
+ # Stop all agents
391
+ docker-compose down
392
+ ```
393
+
394
+ ________________________________________________________________________________________________________________________
395
+ ## Performance in linux ARM64 Docker Environment/Container
396
+ A. [=] Computational performance results with Transformer included during Advanced prediction method.
397
+ ```txt
398
+ == TIME == | CPU % | RAM / RAM LIMIT ||
399
+
400
+ 14:50:08.762 0.00% 25.52MiB / 3.71GiB
401
+ 14:50:10.339 5.56% 25.52MiB / 3.71GiB
402
+ 14:50:12.428 0.17% 25.52MiB / 3.71GiB
403
+ 14:50:15.835 103.60% 38.8MiB / 3.71GiB
404
+ 14:50:17.844 438.11% 60.15MiB / 3.71GiB
405
+ 14:50:19.896 419.36% 68.32MiB / 3.71GiB
406
+ 14:50:22.022 434.15% 73.2MiB / 3.71GiB
407
+ 14:50:23.969 436.47% 78.18MiB / 3.71GiB
408
+ 14:50:25.966 435.85% 80.22MiB / 3.71GiB
409
+ 14:50:28.018 430.47% 92.12MiB / 3.71GiB
410
+ 14:50:30.029 450.55% 99.5MiB / 3.71GiB
411
+ 14:50:32.065 438.06% 105.4MiB / 3.71GiB
412
+ 14:50:34.100 469.52% 115.2MiB / 3.71GiB
413
+ 14:50:36.109 449.89% 116.8MiB / 3.71GiB
414
+ 14:50:38.123 423.56% 119MiB / 3.71GiB
415
+ ```
416
+ - [=] Note: To read the full logs (For included Transformer performance): [performance_log_with_TF](performance_logs/performance_log_with_TF.txt)
417
+ - [=] Explanation:
418
+ - Average CPU Usage = 420% - 430% , Sustained roughlt 4.20 - 4.30 CPU Cores
419
+ - Meaning = - Compute-Intensive workload
420
+ - reduced guaranteed of experiencing deadlocks, thread starvation, and major stalls
421
+ - numerical backend is parallelizing efficiently
422
+ - Average RAM Usage = 180 - 195 Mib, Roughly 4.5 - 5% usage of available RAM
423
+ - Meaning = - Very efficient RAM Usage
424
+ - Repeated 269 MiB suggests allocator settled, ndarray pools stabilized, workload reached steady state
425
+ - gradual, safe and steady batch accumulation, reduced possibility of leak explosion.
426
+
427
+ B. [=] Advanced Prediction without Transformer, Only Specialized MLP + LSTM using AWE.
428
+ ```txt
429
+ == TIME == | CPU % | RAM \ RAM LIMIT |
430
+ 10:01:37.456 100.44% 269.8MiB / 3.71GiB # initial round 1 training started
431
+ 10:01:38.686 101.93% 279.8MiB / 3.71GiB
432
+ 10:01:40.694 101.94% 293.2MiB / 3.71GiB
433
+ 10:01:42.703 99.90% 302.9MiB / 3.71GiB
434
+ 10:01:44.712 99.34% 319.8MiB / 3.71GiB
435
+ 10:01:46.721 100.15% 319.7MiB / 3.71GiB
436
+ 10:01:48.727 101.91% 319.7MiB / 3.71GiB
437
+ 10:01:50.734 100.86% 319.7MiB / 3.71GiB
438
+ 10:01:52.742 136.43% 322.9MiB / 3.71GiB
439
+ 10:01:54.751 101.91% 324.9MiB / 3.71GiB
440
+ 10:01:56.758 100.29% 324.9MiB / 3.71GiB
441
+ 10:01:58.769 102.42% 327.1MiB / 3.71GiB
442
+ 10:02:00.775 0.00% 329.6MiB / 3.71GiB # First Training and prediction round 1 finished
443
+ 10:02:02.788 19.55% 330.1MiB / 3.71GiB # round 2 training
444
+ 10:02:04.798 134.23% 332.2MiB / 3.71GiB
445
+ 10:02:06.803 108.80% 332.2MiB / 3.71GiB
446
+ 10:02:08.811 107.85% 332.2MiB / 3.71GiB
447
+ 10:02:10.857 104.43% 332.2MiB / 3.71GiB
448
+ 10:02:12.854 101.14% 332.2MiB / 3.71GiB
449
+ 10:02:14.858 0.00% 332.3MiB / 3.71GiB
450
+ 10:02:16.873 98.84% 333.8MiB / 3.71GiB
451
+ 10:02:18.869 0.00% 132.7MiB / 3.71GiB # container stopped and round 2 finished
452
+ ```
453
+ - [=] Note: See full performance log in here: [performance_log_only_MLP](performance_logs/performance_log_only_MLP.txt)
454
+ - [=] Explanation:
455
+ - Average CPU Usage = 85-90% Used, sustained roughly 1 CPU Core saturated on average
456
+ - Meaning: - Very efficient computation
457
+ - Much lighter CPU Usage than Transformer.
458
+ - Stable and less parallelizing behavior (Efficient computation)
459
+ - 4.7x lower CPU usage than transformer included
460
+ - Average RAM usage = 314 MiB / 3.71 GiB, Roughly 8.5% usage of available RAM.
461
+ - Meaning: - Slightly larger MiB used than Transformer.
462
+ - Model allocation growth is stable,
463
+ - training buffers stable
464
+ - temporary ndarray growth.
465
+
466
+ ### Both performance Overview
467
+ <img width="1536" height="1024" alt="WhatsApp Image 2026-05-24 at 10 27 00" src="https://github.com/user-attachments/assets/9404277f-281f-4893-8367-e494833230ea" />
468
+ _______________________________________
469
+ - Note:
470
+ - This performance metric was calculated in older versions, With newer Transformers that has more, newer modules, The resulting cpu consumed may Increase 1.5 - 2x much more in Docker ARM64 Environment + QEMU,
471
+ MLP And LSTM stays the same and still fully optimized.
472
+
473
+ ## Source code of AbstractIntegratedModule
474
+ - Note: The source code is provided in the repository.
475
+ - [=] Full Monolithic extensively-documented source code (12K+ Lines): [AbstractIntegratedModule.py](src/AbstractIntegratedModule.py)
476
+ - [=] Separated Modules of AbstractIntegratedModule With proper Documentation: [separated_module](separated_module)
477
+ - [=] up-to-date Source code: [AbstractIntegratedModule.pyx](src/AbstractIntegratedModule.pyx) and [AbstractOptimizedModules.pyx](src/AbstractOptimizedModules.pyx) files for independent compilation or direct compiling on real ARM64 device or if you want to see the up-to-date, undocumented version of AbstractIntegratedModule library.
478
+ - [lib.rs](rust_optimization_setups/lib.rs) that contains Rust optimization for Models weight handling.
479
+ - [~] Note:
480
+ - The source code is open and Free to anyone who:
481
+ - Use it: Run the software for any personal, academic, or commercial purpose.
482
+ - Modify it: Change the source code to fit their needs.
483
+ - Distribute it: Share the original or modified code with others.
484
+ - Commercialize it: Package, brand, and sell the software for profit.
485
+
486
+ ______________________________________________________________________________________________________________________
487
+ ## [=] Step's for library in-depth Usage
488
+ 0. Download via PIP:
489
+ - Clone repository first:
490
+ ```bash
491
+ # Clone immediately for Windows and x86_64 only without prerequisites
492
+ git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git
493
+ cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework
494
+ ```
495
+
496
+ - Install the library via pip:
497
+ ```bash
498
+ pip install AbstractIntegratedModule #or
499
+ python -m pip install AbstractIntegratedModule
500
+ ```
501
+
502
+ 1. Clone repository:
503
+
504
+ - ```
505
+ # prerequisites (for Raspberry pi OS Only)
506
+ # Update system
507
+ sudo apt-get update
508
+ sudo apt-get upgrade -y
509
+
510
+ # Install Python 3.x and development tools
511
+ # Version 3.x means you can install python 3.10 to 3.13 only,
512
+ # choose one version specified for your needs (3.10 or 3.11 or 3.12 ...).
513
+ sudo apt-get install python3.x python3.x-dev python3.x-venv -y
514
+
515
+ # Install additional build tools
516
+ sudo apt-get install build-essential libatlas-base-dev libjasper-dev -y
517
+
518
+ # Clone immediately for Windows and x86_64 only without prerequisites
519
+ git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git
520
+ cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework
521
+ ```
522
+ 2. Install System Dependencies (for x86_64 installation):
523
+ ```
524
+ # Ubuntu/Debian
525
+ # example with Version 3.10:
526
+ sudo apt-get update
527
+ sudo apt-get install python3.10 python3.10-dev python3.10-venv
528
+
529
+ # CentOS/RHEL
530
+ sudo yum install python310 python310-devel
531
+
532
+ # Fedora
533
+ sudo dnf install python3.10 python3.10-devel
534
+ ```
535
+
536
+ 3. Create a virtual environment:
537
+ - ```
538
+ # Create virtual environment (windows)
539
+ # example with python 3.10
540
+ python -m venv venv
541
+ # Activate virtual environment
542
+ venv\Scripts\activate
543
+
544
+ # Create virtual environment (x86_64) (ARM64 / raspberry pi)
545
+ python3.10 -m venv venv
546
+ # Activate virtual environment
547
+ source venv/bin/activate
548
+ ```
549
+
550
+
551
+ 4. Verify Installation:
552
+ - ```
553
+ python -c "from AbstractIntegratedModule import IntegratedPipeline; print('✓ Installation successful!')"
554
+ ```
555
+
556
+ 5. Run main.py for quick test of successful imports:
557
+ - Download main.py in our repository code section: [main.py](main.py)
558
+ - ```
559
+ # run this for quick import test.
560
+ python main.py
561
+ ```
562
+
563
+
564
+
565
+ 3. Create CSV file that contains training labels and titles (Optional for training using texts):
566
+ - Example format:
567
+ ```txt
568
+ window_title,label
569
+ "Thesis.docx",focused_work,high,writing-thesis
570
+ "Microsoft Excel",work,medium,data-analysis
571
+ "YouTube -> Google Chrome",distracted,high,watching-videos
572
+ "Slack",communication,high,team-chat
573
+ "VSCode", focused_work,high,coding
574
+ "netflix.com -> Google Chrome",break,high,Netflix-break
575
+ "Outlook",work,medium,checking-email
576
+ "System Settings",system designing,low,configuring-computer
577
+ "GitHub",creating-and-editing-repo,research
578
+ "README.md -> VS Code",focused_work,medium,reading-docs
579
+ "Amazon.com -> Chrome",personal-work,high,shopping
580
+ ```
581
+ Note = window_title is target_title and label is target_label, check step below to use it.
582
+
583
+
584
+ 4. A. Use IntegratedPipeline as in this example:
585
+ ```python
586
+ from AbstractIntegratedModule import IntegratedPipeline
587
+ from AbstractIntegratedModule import PipelinePredictionManager
588
+ import numpy as np
589
+
590
+ # SETUP BLOCK.
591
+ memory_name = 'agent_memory'
592
+ cert_file = <your_cert_file_dir> # your .crt file
593
+ key_file = <your_key_file_dir> # your .key file
594
+
595
+ # SSL Setup for users who used Lets encrypt / Public CA cert:
596
+ # Server context
597
+ server_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
598
+ server_ctx.load_cert_chain('your_server.crt', 'your_server.key') # No load_verify_locations needed — OS trust store handles public CA
599
+
600
+ # Client context
601
+ client_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
602
+ client_ctx.load_cert_chain('your_client.crt', 'your_client.key') # no load_verify_locations — OS trust store handles it
603
+
604
+ # for enterprise and internal CA:
605
+ '''
606
+ server_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
607
+ server_ctx.load_cert_chain('their.crt', 'their.key')
608
+ server_ctx.load_verify_locations('company_ca.crt') # internal CA not in OS store
609
+ server_ctx.verify_mode = ssl.CERT_REQUIRED
610
+ server_ctx.check_hostname = False
611
+
612
+ client_ctx = ssl.create_default_context(ssl.Purpose.SERVER_AUTH)
613
+ client_ctx.load_cert_chain('their.crt', 'their.key')
614
+ client_ctx.load_verify_locations('company_ca.crt')
615
+ client_ctx.verify_mode = ssl.CERT_REQUIRED
616
+ client_ctx.check_hostname = False
617
+ ''' # uncomment to use
618
+
619
+ # Note: The Above setup is Important for Users who wants to do Secure P2P In deployment case, for local P2P the above setup is optional and automatic self-signed CERT will be used for local-device P2P.
620
+
621
+ main_model = IntegratedPipeline(
622
+ memory_name=memory_name, # memory name for the AI you already initialized
623
+ use_async=True, # local asynchronous prediction is permitted, if not PipelineAsyncManager wont start asynchronous prediction.
624
+ agent_port=5001, # this port is used to set AgentDistributedInference server (optional)
625
+ ssl_cert_file=cert_file, ssl_key_file=key_file,# provide your cert_file path or key_file path (optional)
626
+ ssl_context=server_ctx, # used by the Agent server. (optional)
627
+ client_ssl_context=client_ctx # used by the client. (optional)
628
+ )
629
+
630
+ main_prediction = PipelinePredictionManager(
631
+ main_model, # your initialized pipeline
632
+ label_csv='example_manual_training.txt',
633
+ # your filename that contains the .txt file and contains the CSV format.
634
+ # the Agent will automatically searched the nearby folder like: downloads, data, and desktop folder.
635
+ target_title='window_title', label='label')
636
+
637
+ # example_manual_training is a .txt file that contain csv format like above example.
638
+
639
+ # rules will be used to create automatic dataset for IntegratedPipeline.
640
+ example_rules = [
641
+ # === WORK / PRODUCTIVITY ===
642
+ (r'code|programming|develop|debug|compile|script', 'focused_work'),
643
+ (r'vscode|visual_studio|ide|terminal|shell', 'focused_work'),
644
+ (r'notion|evernote|onenote|notes|todo|task', 'productive'),
645
+ (r'slack|teams|discord|zoom|meeting|call', 'communication'),
646
+ (r'email|gmail|outlook|inbox|mail', 'communication'),
647
+
648
+ # === ENTERTAINMENT ===
649
+ (r'youtube|netflix|twitch|stream|video', 'entertainment'),
650
+ (r'music|spotify|soundcloud|audio|player', 'entertainment'),
651
+ (r'game|gaming|steam|epic|play', 'gaming'),
652
+ (r'facebook|instagram|tiktok|social|post', 'social_media'),
653
+
654
+ # === BROWSING ===
655
+ (r'chrome|firefox|edge|safari|browser', 'browsing'),
656
+ (r'google|search|wiki|wiki|article', 'information'),
657
+ (r'stackoverflow|github|docs|documentation', 'research'),
658
+
659
+ # more rules
660
+ ]
661
+
662
+ # activate explainability capability to explain uncertainty:
663
+ main_model.show_explainability_details = True
664
+ main_model.distribution.predict_manager = main_prediction # set PipelinePredictionManager to AgentDistributedInference for asynchronous prediction later (Very important for asynchronous prediction)
665
+ # main_model.use_transformer = True if you want to use transformer, this will notify all modules that used advanced_prediction_method will initiate prediction with both transformer and MLP.
666
+
667
+ # set IntegratedPipeline Penalty rate when it output wrong answer:
668
+ main_model.error_decay = 0.75
669
+ # error_rate > 0.5 means old errors fade quickly — a class that was wrong 3 predictions ago matters less than one wrong just now, making the model less likely to output repetitive wrong answer.
670
+ # this a flexible tunable-knob for the model judgement regarding wrong answer, this will propagate through prediction layers to inform about the model repetitive answer and calibrate it immediately.
671
+
672
+ # (Optional manual setup) if you want to Cuztomize the Model setup.
673
+ main_model.mlp_training_epochs = 2000
674
+ main_model.transformer_training_epochs = 200
675
+ main_model.transformer_lr = 0.25
676
+ main_model.mlp_lr = 0.5
677
+ main_model.lstm_training_epochs = 200
678
+ main_model.lstm_lr = 5e-1
679
+ main_model.lstm_hidden_dim = 64 # LSTM Hidden dim can be set manually, MLP and Transformer hidden dim are already set automatically based on the samples input they have received.
680
+ # Transformer heads and d_model manual setup
681
+ main_model.transformer_heads = 4
682
+ main_model.transformer_d_model = 64
683
+ # You can set how much epochs are needed to Train your MLP, LSTM and Transformer for your Models, along with their Learning rates. (lr).
684
+
685
+ # test samples with more sophisticated rules and more complex titles for prediction
686
+ # (title, intent)
687
+ test_titles = [
688
+ ("Opening Thesis.docx", "slight_work"),
689
+ ("Watching YouTube and Google Chrome", "distracted"),
690
+ ("Watching Slack", "communication"),
691
+ ("Programming in Visual Studio Code", "focused_work"),
692
+ ("Watching netflix.com - Chrome", "break"),
693
+ # more titles
694
+ ]
695
+
696
+ titles, y, label_map = main_prediction.load_labels_from_csv(
697
+ <your_filename.>, # the name of your .txt file with CSV format.
698
+ <target_title>, <target_label>)
699
+
700
+ # OPTIONAL TRAINING BLOCK
701
+ # (Training will happens in the advanced prediction method below, but if you want separate Training for MLP, you can use this setup: )
702
+ # small training with simple titles first
703
+ main_model.train(titles, y)
704
+
705
+ # main_model.freeze_learning = True
706
+ # prevent the model from training and make weights unchanged for static prediction.
707
+
708
+ # SIMULATION BLOCK:
709
+ # This function below allows you to create A continuous Training simulations using K-fold split to evaluate MLP Training performance using your provided X and Y samples, This function helps to diagnose if Your samples are appropriate for MLP and make It generalize instead of severely Overfitting.
710
+ # This function will create a fresh instance of MLP every k-amount you have set (the k=5), and also prints a Confusion matrix that helps diagnose Your MLP Training Accuracy Performance.
711
+ # This function is great to help you diagnose Further degradation of MLP performance and also Its consistency, And also helps validate our AWE Method at how well it makes MLP Training performance Consistent Accross different Seeds for better Reliability performance.
712
+ main_model.evaluate_mlp_performance(X, y, label_map, k=5, seed=42)
713
+
714
+ # PREDICTION BLOCK:
715
+ # the below section called advanced_prediction_method(...) is a prediction method that will output a single answer of a problem you have given to it, it will output a single answer from the label_map you have given as its final prediction.
716
+ # meaning advanced_prediction method is only used to predict an answer based on the given label_map and only output a single answer, not in batches.
717
+ # this prediction method is also where training, ensemble and final prediction happens.
718
+ # Use case: - classification problems that requires a model to only output a single answer.
719
+ results, chosen_label, confidence = main_prediction.advanced_prediction_method(
720
+ titles=test_titles, label_map=label_map, rules=example_rules, # titles and rules can be set to None (Optional samples), but label_map must NOT be None.
721
+ X=None, y=None # you could create your own X and y samples and put it here (Optional, y sample must already be one hot encoded first).
722
+ show_proba=False, top_k=3,
723
+ use_transformer=True,
724
+ return_attention=False,
725
+ batch_size=2)
726
+ # Important Note: If you set titles and rules to None, you must provide X and y samples for prediction, otherwise the models cant predict anything.
727
+ # Note: The X and y samples will be organized and processed using train_test_split() scikit-learn function for creating better generalization behavior for the model, so when you pass the X and y samples, you must pass the raw X sample (Not modified, just raw X) and the already y hot-encoded sample,
728
+ # batch size=2 is needed during transformer training for batching, if you have larger samples consider using batch_size > 8, for medium amount of samples (>10 -> <50 samples) consider using 2 or 4 batch_size.
729
+
730
+ # This setup below would allow you to save the Accurate answer (if the model guessed a specific problem correct) directly to the database,
731
+ # without initiating prediction over the sample repeatedly.
732
+ input_ids = main_model.model2.cache['input_ids'] # input indices the transformer used as input (model2 is Transformer).
733
+ index = results.get('index') # predicted index where the Model have chosen the label.
734
+ confidence = results.get('confidence') # the model confidence over the predicted Output from advanced prediction method.
735
+ main_model.accurate_cache_lookup.add_verified(X, input_ids, chosen_label, confidence, index,
736
+ source='Correctly-Answered') # You can modify the the source with "Answered-Correctly" (fit to your needs)
737
+
738
+ # ... more features you can add
739
+ ```
740
+ - Note: This script setup can be downloaded here: [usage_script](scripts/usage_scripts.py)
741
+
742
+ 4. B. Using Standalone IntegratedPipeline Transformer:
743
+ ```python
744
+ # if you want to use the IntegratedPipeline Transformer only, you can use this setup:
745
+ # ideal when you want blazing Fast Transformer Training and prediction, and the Transformer weights are loaded using JSON, this made Transformer Training much more feasible and easily intuitive for Beginners who wants Complex abstraction models that can run on cheap Edge devices.
746
+
747
+ vocab_size = # <your actual vocab size>.
748
+ model_transformer = Transformer(
749
+ vocab_size=vocab_size
750
+ d_model=main_model.transformer_d_model,
751
+ n_heads=pipeline.transformer_heads,
752
+ num_classes=num_classes
753
+ )
754
+
755
+ sequence_inputs = main_model._features_to_sequence(X, d_model=pipeline.transformer_d_model) # Converts X samples into sequences that the Transformer can recognize.
756
+ # embedded=True will ensure that Transformer forward method will put a correct mask for the samples.
757
+ # mode='dynamic_backward' helps Transformer to gains better accuracy for Complex vocabularies.
758
+ model_transformer.train(sequence_inputs, y, epochs=100, mode='dynamic_backward', lr=0.1, embedded=True, batch_size=2)
759
+
760
+ # save Transformer weights
761
+ tf = model_transformer
762
+ json_data = {
763
+ 'token_embedding': tf.token_embedding,
764
+ 'pos_embedding': tf.pos_embedding,
765
+ 'W_q': tf.W_q,
766
+ 'W_k': tf.W_k,
767
+ 'W_v': tf.W_v,
768
+ 'W_q_fixed': tf.W_q_fixed,
769
+ 'W_k_fixed': tf.W_k_fixed,
770
+ 'W_v_fixed': tf.W_v_fixed,
771
+ 'W_o': tf.W_o,
772
+ 'ffn1': tf.ffn1,
773
+ 'ffn2': tf.ffn2,
774
+ 'ln1_scale': tf.ln1_scale,
775
+ 'ln1_shift': tf.ln1_shift,
776
+ 'ln2_scale': tf.ln2_scale,
777
+ 'ln2_shift': tf.ln2_shift,
778
+ 'output': tf.output,
779
+ 'output_bias': tf.output_bias
780
+ }
781
+ serializable_data = {key: val.tolist() for key, val in json_data.items()}
782
+ with open("transformer_weights.json", "w") as file:
783
+ json.dump(serializable_data, file, indent=4) # indent adds readable formatting
784
+
785
+ #load Transformer weights
786
+ # in here transformer_model a new IntegratedPipeline Transformer instance:
787
+ with open('transformer_weights.json', 'r') as file:
788
+ loaded_data = json.load(file)
789
+ transformer_model.W_q = loaded_data['token_embedding']
790
+ ... # and so on until output_bias.
791
+ ```
792
+ - Note: script setup can be downloaded here: [transformer_usage](scripts/transformer_usage.py)
793
+
794
+ 5. C. Use kNN-Augmented Transformer:
795
+ Note: kNN-Augmented Transformer doesn't have its own Prediction pipeline flow, meaning after the Transformer forward method is called, the probabilities of the kNN Transformer will be returned and no prediction is made, We decided to be better this way because it grants Flexibility over how Prediction will be made in your favour:
796
+ - Example Code:
797
+ - ```python
798
+ # knn_forward_inference() lives inside PipelinePredictionManager, so you need to call this class to initiate the knn_forward_inference() function.
799
+ losses, accs = main_prediction.knn_forward_inference(X, y, memory_metric='euclidean', training=True, batch_size=2, train_mode='dynamic_backward', lr=0.1) # for Training kNN Transformer only
800
+ transformer_probs, attn_weights = main_prediction.knn_forward_inference(X, y, memory_metric='euclidean', training=False) # for returning kNN Transformer probabilities and attention weights only.
801
+ # Note: - train_mode can be set to 'dynamic_backward' if you have very large dataset, this makes Transformer Q, K, V be much more dynamic and grants flexible learning behavior for large dataset.
802
+ # - train_mode can be set to 'fixed_backward' if you have small dataset, this makes Transformer Q, K, V to stay frozen so the FFN flow will handle the Training, making Learning in very little samples possible and deterministic in behavior.
803
+ # - y sample must be one-hot encoded manually before its passed to the function, since the function above will not automatically one-hot encode the y-sample.
804
+
805
+ main_prediction.pipeline.storage.save_hnsw_memory(memory_name) # This function saves the HNSW setup inside KNNAugmentedTransformer class to the the same database (activity_log.db) so it can be retrieved as Retrievable Memory later.
806
+ main_prediction.pipeline.storage.save_memory_head(memory_name) # This function saves the Per-Head memory setup inside KNNAugmentedTransformer class to the the same database (activity_log.db) so it can be retrieved as Retrievable Memory later.
807
+
808
+ main_prediction.pipeline.storage.load_hnsw_setup(memory_name) # This function is used to load the saved HNSW Memory inside your (activity_log.db) database, and automatically apply the Old Memory back to the knn-augmented Transformer.
809
+ main_prediction.pipeline.storage.load_head_memory_setup(memory_name) # This function is used to load the saved HNSW Memory inside your (activity_log.db) database, and automatically apply the Old Memory back to the knn-augmented Transformer.
810
+
811
+ # .... # your own custom prediction block.
812
+ ```
813
+
814
+
815
+ 7. To use IntegratedPipeline prediction without Transformer, Only Specialized MLP:
816
+ Note: IntegratedPipeline without Transformer is'nt recommended due to it being weak at certain contextual prediction's, excel's at classification task's.
817
+ - Example without transformer:
818
+ ```python
819
+ prediction_result = main_prediction.advanced_prediction_method(
820
+ [t[0] for t in test_titles], # titles is enough for MLP Classification.
821
+ label_map,
822
+ example_rules,
823
+ show_proba=True
824
+ )
825
+
826
+ ```
827
+ 8. Asynchronous prediction:
828
+ - Asynchronous prediction request is important and is critical because it keeps prediction interfaces responsive, maximizes local hardware efficiency, and enables apps to handle background tasks seamlessly without waiting on remote server responses,
829
+ - for asynchronous prediction handling, consider using this setup
830
+ ```python
831
+ # Step 2
832
+ from AbstractIntegratedModule import PipelineAsyncManager
833
+ from AbstractIntegratedModule import SecurityConfig
834
+ from AbstractIntegratedModule import SecurityLevel
835
+
836
+ print(" = TESTING ASYNCHRONOUS PREDICTION MANAGER = ")
837
+ # Set discovery secret (in production, use environment variable)
838
+ secret_key = 'my-ultra-safe-secret-key-for-authentication' # you can customize this key
839
+
840
+
841
+ security_config = SecurityConfig(
842
+ max_text_length=10000, # can be extended
843
+ max_queue_size=100, # can be extended
844
+ rate_limit_requests=60, # 60 per minute
845
+ require_api_key=True, #
846
+ max_pending_tasks=50,
847
+ request_timeout=60.0,
848
+
849
+ # Start with no IP restrictions, you can add allowed IPs for asynchronous prediction externally, boothstrap_auth for better security
850
+ allowed_ips=[],
851
+ blocklisted_ips=[],
852
+ require_bootstrap_auth = False # true for better security (Not recommended, cause less flexibility)
853
+ )
854
+
855
+ async_manager = PipelineAsyncManager(main_model,
856
+ main_prediction, # your previous initialized PipelinePredictionManager
857
+ config=security_config,
858
+ state_file=None, # state file is used to load known security logs ex: ip used, ip blacklisted, etc.
859
+ security_level=SecurityLevel.PRODUCTION, # production level security initiated
860
+ api_key=secret_key #set secret key you initialized
861
+ max_workers=4, # workers to initiate asynchronous tasks, more workers, more capabilities to process asynchronous prediction requests.
862
+ task_timeout=30,
863
+ max_retries=3 ) # retries after failure during prediction
864
+
865
+ async_manager.start(method='Transformer_included', bootstrap_token=None) # boothstrap token is optional for better security
866
+
867
+ texts = {'test_titles': test_titles, 'label_map': label_map, 'rules': example_rules, # test_titles and rules can be set to None here since they are Optional samples.
868
+ # but label_map must not be None.
869
+ 'X': None, 'y':None, 'use_transformer': True} # all samples needed for advanced prediction method. (X and y are optional samples)
870
+ # Important Note: If you set titles and rules to None, you must provide X and y samples for prediction, otherwise the models cant predict anything.
871
+
872
+ regular_predict = async_manager.predict(
873
+ texts=texts,
874
+ timeout=60,
875
+ retries=None,
876
+ api_key=secret_key) # advanced prediction method for asynchronous prediction.
877
+
878
+ # with retries: async_manager.predict(texts, timeout=60, retries=5, api_key=secret_key) # 5 times retry if failed
879
+
880
+ # NOTE: This function below must require test_titles or titles, label_map and example rules:
881
+ print('[==] Initiating advanced batch prediction')
882
+ predicted_output = async_manager.advanced_batch_prediction(test_titles, label_map, example_rules,
883
+ X=None, y=None, # provide your initialized X and y samples (Also Optional, can be set to None)
884
+ secret_key=secret_key, client_ip=None) # you can add client_ip to provide a robust authentication paired with secret_key
885
+ # for better and faster advanced prediction when using titles and rules, consider using advanced batch prediction like in the above example
886
+
887
+ ```
888
+ [=] Note:
889
+ - Asynchronous prediction used Event loop that handles incoming request, There are conditions where event loop will not start and can't accet requests:
890
+ - CPU Above > 95% - Disk space is < 100 MB
891
+ - RAM above > 95%
892
+ - When event loop is not triggered, Asynchronous prediction can't be initiated and must be restarted/retried.
893
+ - Script setup can be downloaded here: [async_script](scripts/async_script.py)
894
+
895
+ 8. Peer-to-Peer Probability coordination:
896
+ - Each peer is both server and client simultaneously for robustness and resilience during during P2P.
897
+ - To Make the Agent cooperate with other peers, consider using this setup:
898
+ - [=] for ensemble prediction from multiple peers, exchanging predicted label with each other, consider using this setup:
899
+ ```python
900
+
901
+ # step 3
902
+ from AbstractIntegratedModule import CohesiveAgentDeployment
903
+ from AbstractIntegratedModule import PipelinePredictionManager
904
+ import asyncio
905
+ import traceback
906
+
907
+ prediction_manager = PipelinePredictionManager(main_model, label_csv=<your_training_labels.txt>, target_title=<target_title>, label=<target_label>)
908
+
909
+ secondary_model = IntegratedPipeline(memory_name=memory_name,
910
+ use_async=True, agent_port=8080,
911
+ ssl_cert_file=cert_file, ssl_key_file=key_file) # provide cert_file path or key_file path (optional)
912
+ # secondary model of integrated pipeline is critical for ARM64 environment to prevent socket conflict during P2P with the first Integrated pipeline instance.
913
+ # make sure that the agent_port in secondary_model must be different from agent_port in first IntegratedPipeline instance you initialized.
914
+
915
+ print("=== SECURE PEER-TO-PEER CLUSTER ===")
916
+
917
+ # CohesiveAgentDeployment is deeply tied and coupled with AgentDistributedInference,
918
+ # if you already set an SSL cert and key, CohesiveAgentDeployment will use the SSL directly from AgentDistributedInference
919
+ # allowing secure socket to be used directly by CohesiveAgentDeployment
920
+
921
+ main_model.distribution.enable_ssl = False # set to false if you dont have SSL key and CERT, this code would instruct AgentDistributedInference that you don't have SSL, and provide you a regular unsecured socket (Not necessary for production)
922
+ secondary_model.distribution.enable_ssl = False
923
+
924
+ # Agent 1 - Primary (Port 5555)
925
+ agent1 = CohesiveAgentDeployment(
926
+ pipeline=main_model, # main_model is your initialized integrated pipeline
927
+ memory_name="agent_primary", # any name you want for the agent.
928
+ filename=<filename>, # name of your .txt file that contains the CSV format and training labels
929
+ target_title=<title_name>,
930
+ label_name=<label_name>,
931
+ security_level="PRODUCTION", # production level security
932
+ enable_peers=True, # allow peer discovery
933
+ trusted_networks=['127.0.0.1/32', '192.168.1.0/24'], # for trusted networks, you need to provide the list of IPs of your peers.
934
+ peer_discovery_port=5555, # peer port to start P2P
935
+ secret_key=secret_key, # your secret key
936
+ shared_auth_token=secret_key, # your previous initialized secret_key
937
+ predict_manager=prediction_manager, # your prediction manager
938
+ peer_config = <'your_peer_ip_lists.json'> # you need to create .json file that contains your peer IP and Port lists
939
+ consecutive_peer_config = <'your_second_fallback_peer_ip_lists.json'> # same for this one too, but for fallback.
940
+ )
941
+
942
+ # Agent 2 - Secondary (Port 5556)
943
+ agent2 = CohesiveAgentDeployment(
944
+ pipeline=secondary_model,
945
+ memory_name="agent_secondary",
946
+ filename=<filename>,
947
+ target_title=<title_name>,
948
+ label_name=<label_name>,
949
+ security_level="PRODUCTION",
950
+ enable_peers=True, # agent is allowed to find peers
951
+ trusted_networks=['127.0.0.1/32', '192.168.1.0/24'],
952
+ peer_discovery_port=5556,
953
+ secret_key=secret_key,
954
+ shared_auth_token=secret_key,
955
+ predict_manager=prediction_manager,
956
+ peer_config = <'your_peer_ip_lists.json'> # you need to create .json file that contains your peer IP and Port lists
957
+ consecutive_peer_config = <'your_second_fallback_peer_ip_lists.json'> # same for this one too, but for fallback.
958
+ )
959
+
960
+ # Note: CohesiveAgentDeployment contains ConsecutivePeerAgent that can start a server once ensemble prediction from peer is started
961
+ # be advised to stop the server too before shutdown-ing CohesiveAgentDeployment cluster
962
+
963
+ # example peer_Ip_lists_config.json (de-comment to use)
964
+ # {
965
+ # you must put "known_peers" in the config so python can identify the list of IPs and Ports
966
+ # "known_peers": [
967
+ # ["127.0.0.1", 5555], can be modified using real IP or local IP.
968
+ # ["127.0.0.1", 5556],
969
+ # more ip and port lists...
970
+ # ]
971
+ # }
972
+
973
+
974
+ try:
975
+ # Start both agents
976
+ print("\n🚀 Starting Agent 1...")
977
+ await agent1.start()
978
+ print("✅ Agent 1 started on port 5555")
979
+
980
+ print("\n🚀 Starting Agent 2...")
981
+ await agent2.start()
982
+ print("✅ Agent 2 started on port 5556")
983
+
984
+ # Give servers time to fully bind
985
+ await asyncio.sleep(2)
986
+
987
+ # Get API keys
988
+ api_key = agent1.get_api_key()
989
+ print(f"\n🔑 Using API Key: {api_key[:20]}...")
990
+
991
+ texts = {"test_titles": test_titles, "label_map": label_map, "rules": rules, # test_titles and rules are Optional samples, can be set to None.
992
+ 'X': None, "y":None, "use_transformer": True, "agent_id": agent_id} # (X and y are optional samples here too)
993
+ # Important Note: If you set titles and rules to None, you must provide X and y samples for prediction, otherwise the models cant predict anything.
994
+
995
+ # texts dictionary must contain test_titles, label_map, and rules that you can assign,
996
+ # agent ID can be strings, int, or floats, recommendded to make it long for better security.
997
+ agent1.pipeline.use_transformer = False # set agent1 pipeline to not use transformer for efficient processing in ARM64 env.
998
+ agent2.pipeline.use_transformer = False
999
+
1000
+ # Make prediction with peer ensemble
1001
+ # Connection will be guaranteed successfull during discovery.
1002
+ result = await agent1.multi_modal_peer_ensemble_prediction(
1003
+ texts=texts,
1004
+ api_key=api_key,
1005
+ method='advanced',
1006
+ disable_sync=True
1007
+ ) # await using asyncio, multi_modal_peer_ensemble is already async by design (Inside ConsecutivePeerAgent), no need to put asyncio.run()
1008
+
1009
+ # must have agent2 peer ensemble function after agent1 peer ensemble prediction function,
1010
+ # so agent1 can receive agent2 peer ensemble prediction request.
1011
+ result2 = await agent2.multi_modal_peer_ensemble_prediction(
1012
+ texts=texts,
1013
+ api_key=api_key,
1014
+ method='advanced',
1015
+ disable_sync=True
1016
+ )
1017
+
1018
+ print(f"\n📊 Ensemble Result for Agent 1:")
1019
+ print(f" Prediction: {result.get('prediction', 'N/A')}")
1020
+ print(f" Confidence: {result.get('confidence', 0):.2%}")
1021
+
1022
+ print(f"\n📊 Ensemble Result for Agent 2:")
1023
+ print(f" Prediction: {result2.get('prediction', 'N/A')}")
1024
+ print(f" Confidence: {result2.get('confidence', 0):.2%}")
1025
+
1026
+ # Keep running briefly
1027
+ print("\n⏳ Cluster stable. Waiting 5 seconds before shutdown...") # 5 seconds before shutdown.
1028
+
1029
+ # stop ConsecutivePeerAgent servers inside CohesiveAgentDeployment.
1030
+ agent1._peer_agent.stop_server() # ._peer_agent is ConsecutivePeerAgent
1031
+ agent2._peer_agent.stop_server()
1032
+
1033
+ await asyncio.sleep(5)
1034
+
1035
+ except Exception as e:
1036
+ print(f"\n❌ Error in cluster: {e}")
1037
+ traceback.print_exc()
1038
+
1039
+ finally:
1040
+ print("\n🛑 Shutting down cluster...")
1041
+ await agent1.shutdown()
1042
+ await agent2.shutdown()
1043
+ print("✅ Cluster shutdown complete")
1044
+
1045
+ ```
1046
+ [=] Important Note:
1047
+ - This setup outputs the given predicted label of an input directly, making P2P more flexible and fast.
1048
+ - This setup used Hybrid feature in prediction handling, Asynchronous prediction request, and Synchronous prediction handling. Synchronous prediction does block code execution for a few seconds, it was used for a few reason here, such as:
1049
+ - allowing a more slower traffic between agents, preventing other agent to get the same peer prediction over time, making each interaction equals and each peer can receive different peer prediction output.
1050
+
1051
+ [=] You can download this setup here for a direct test: [P2PDirectTest.py](P2P_Setups/P2PDirectTest.py)
1052
+
1053
+ - [=] for probability coordination, locally, get peers data from database or via socket.
1054
+ ```python
1055
+ # step 4
1056
+ dataset, _ = main_model.data_preparation(test_titles, label_map)
1057
+ sequence_inputs = main_model.sequence_encoding(dataset)
1058
+ X_raw_generation, y, n_classes, input_dim = main_model.mlp_training_features(example_rules, dataset)
1059
+
1060
+ main_model.initialize_fitting(dataset)
1061
+ X_raw_features = main_model.tfidf.transform(X_raw_generation).toarray()
1062
+ transformer_features = main_model.transformer_pooled_features(sequence_inputs)
1063
+ X_features = np.concatenate([X_raw_features, transformer_features], axis=-1)
1064
+
1065
+ peer_probability_calibration = main_model.predict_proba(sequence_inputs, X_features, type='Hybrid', embedded=True) # peer-to-peer calibration is inside this function
1066
+ ```
1067
+ [~] Note: the peer calibration coordination has a chance of triggering if both MLP and Transformer prediction doesn't agree on certain output. Consider using this setup below for using stand-alone peer-to-peer main function without being wrapped in other parent function, allowing flexible and auditable peer-to-peer sharing for probability coordination:
1068
+ ```python
1069
+ from AbstractIntegratedModule import WeightedEnsemblePredictor
1070
+ from AbstractIntegratedModule import Transformer
1071
+
1072
+ num_classes = len(label_map)
1073
+ # if you haven't fit the Tfidf:
1074
+ # main_model.initialize_fitting(dataset)
1075
+
1076
+ ensemble_method = WeightedEnsemblePredictor(main_model, memory_name) # consider using the same memory name used in your previous pipeline
1077
+ transformer = Transformer(main_model.vocab_size, d_model=32, n_heads=4, num_classes=num_classes) # you can audit how much parameter the transformer needs.
1078
+ main_model.model2 = transformer # overwrite previous transformer initialization
1079
+
1080
+ # main_model.distribution is AgentDistributedInference() class
1081
+ # consider using ssl for secure peer to peer coordination
1082
+ main_model.distribution.ssl_cert_file = <path_to_your_ssl_cert_file>
1083
+ main_model.distribution.ssl_key_file = <path_to_your_ssl_key_file>
1084
+
1085
+ dataset, _ = main_model.data_preparation(titles, label_map)
1086
+ sequence_input = main_model.sequence_encoding(dataset)
1087
+ _, attn_weights = transformer.forward(sequence_input)
1088
+
1089
+ probs = ensemble_method.predict_ensemble(sequence_input, X_features, y, method='dynamic', embedded=True)
1090
+ # 3 options for ensemble weighting method:
1091
+ # 1. dynamic: allow flexible, efficient weighting from both transformer and MLP,
1092
+ # 2. meta: for a much more in-depth weighting from both model,
1093
+ # 3. calibration: allow calibrating probability for both model outputs based on both best weights assembling.
1094
+
1095
+ agreement = main_model.agreement
1096
+
1097
+ # start server to initiate socket for P2P listener
1098
+ main_model.distribution.start_server()
1099
+
1100
+ # set connection timeout (Optional)
1101
+ main_model.distribution.connection_timeout = 30 # 30 seconds before timeout
1102
+ calibrated_probability = main_model._handle_distributed_connections(probs, attn_weights, sequence_input, agreement)
1103
+
1104
+ # if an Agent experience a failure on tasks, consider using this function to reduce peer trust for safer flexible coordination:
1105
+ # main_model.distribution.report_failure(id(main_model), '<task_name>', reason='<unknown>') # you can add the task_name and reason
1106
+ # main_model.distribution.print_network_status() # to show other peers info.
1107
+ ```
1108
+ [~] Note: this calibrated_probability is later used to calculate confidence and chosen output based on given label_map.
1109
+ - Consider checking:
1110
+ - [multi_agent_client.py](P2P_Setups/multi_agent_client.py) for a In-depth start for client testing.
1111
+ - [multi_agent_server.py](P2P_Setups/multi_agent_server.py) for a In-depth start for server testing.
1112
+ - If you get undefined NoneType Behavior when using .accept(), consider see [Troubleshooting](#Troubleshooting) Issue 7 for a Quick fix.
1113
+
1114
+ 6. Cross-Session availability:
1115
+ - To use Cross-session avialability to transfer or import memory, consider using this setup:
1116
+ - ```python
1117
+ main_model._cross_session_availability() # cross session capability function
1118
+ ```
1119
+
1120
+ 7. As an option, You can add more feature's directly to what it should predict, behave using rules you have given, Create a visual dashboard, create a distributed mesh of this agent, and much more features you can try.
1121
+
1122
+ ________________________________________________________________________________________
1123
+ ## [+] Troubleshooting
1124
+ 1. Issue 1: "ModuleNotFoundError: No module named 'AbstractIntegratedModule'" When using the binary version of the library,
1125
+ Solution:
1126
+
1127
+ - [=] Verify the binary file is in the correct location:
1128
+ ```
1129
+ ls -la AbstractIntegratedModule*.so # Linux
1130
+ dir AbstractIntegratedModule.pyd # Windows
1131
+ ```
1132
+
1133
+
1134
+ - [=] Check Python path:
1135
+ ```
1136
+ python -c "import sys; print('\n'.join(sys.path))"
1137
+ ```
1138
+ - [~] Note: - Move binary to project root if not already there
1139
+ - Ensure you're using Python 3.13 of the supported version.
1140
+
1141
+ 2. Issue 2: "ImportError: DLL load failed" when using binary version of the library (For Windows)
1142
+ Solution:
1143
+
1144
+ - 1. Ensure AbstractIntegratedModule.pyd is in your project root
1145
+ - 2. Install Visual C++ redistributables:
1146
+ Download from: https://support.microsoft.com/en-us/help/2977003
1147
+ - 3. Verify Python architecture (32-bit vs 64-bit) matches the .pyd file
1148
+
1149
+
1150
+ 3. Issue 3: "Permission denied" when using binary version of the library (for Linux/Raspberry Pi)
1151
+ [=] Solution:
1152
+ - ```
1153
+ # Make sure you have read permissions
1154
+ chmod 644 AbstractIntegratedModule.cpython-39-*.so
1155
+ # If in virtual environment, ensure it's activated
1156
+ source venv/bin/activate
1157
+ ```
1158
+
1159
+ 4. Issue 4: Missing Dependencies when using binary
1160
+ [=] Solution:
1161
+ - ```
1162
+ # Reinstall all dependencies
1163
+ pip install --upgrade pip setuptools wheel
1164
+ pip install numpy pandas scikit-learn matplotlib scipy requests
1165
+
1166
+ # Verify installation
1167
+ pip list
1168
+ ```
1169
+
1170
+ 5. Issue 5: Virtual Environment Issues
1171
+ [=] Solution:
1172
+ - ```
1173
+ # Deactivate current environment
1174
+ deactivate
1175
+
1176
+ # Create a fresh virtual environment
1177
+ python -m venv fresh_venv
1178
+
1179
+ # Activate it
1180
+ source fresh_venv/bin/activate # Linux/Raspberry Pi
1181
+ # or
1182
+ fresh_venv\Scripts\activate # Windows
1183
+
1184
+ # Reinstall
1185
+ pip install --upgrade pip
1186
+ pip install numpy pandas scikit-learn matplotlib scipy
1187
+ ```
1188
+
1189
+ 6. Issue 6: Raspberry Pi - "Bus error" or Performance Issues
1190
+ Solution:
1191
+ - [=] Ensure adequate swap space:
1192
+ ```
1193
+ free -h # Check current swap
1194
+ sudo nano /etc/dphys-swapfile # Increase if needed
1195
+ ```
1196
+ - Close unnecessary applications before running
1197
+ - Consider using a faster SD card (UHS-I or better)
1198
+
1199
+ 7. Issue 7: P2P Undefined Connection:
1200
+ If you get this warning:
1201
+ - ```
1202
+ [❌] Failed to connect to <host>:<port>: Nonetype object has no attribute .accept()
1203
+ ```
1204
+ - [=] Solution:
1205
+ - ```
1206
+ # initiate socket first
1207
+ main_model.distribution.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
1208
+ main_model.distribution.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1209
+ main_model.distribution.socket.bind(('0.0.0.0', self.port)) # self.port could be changed with other ports
1210
+ main_model.distribution.socket.listen(5) # listens for 5 seconds
1211
+ ```
1212
+ 8. Issue 8: Cannot compare using '<' with str and float data:
1213
+ - This happens when one of the labels extracted from your CSV file has NaN value, consider replace NaN with actual labels.
1214
+
1215
+ 9. Issue 9: Failed authentication during asynchronous prediction:
1216
+ - Solution: Ensure API_KEY is initialized inside PipelineAsyncManager like this:
1217
+ - ```python
1218
+ async_manager = PipelineAsyncManager(main_model,
1219
+ main_prediction, # your previous initialized PipelinePredictionManager
1220
+ config=security_config,
1221
+ state_file=None, # state file is used to load known security logs ex: ip used, ip blacklisted, etc.
1222
+ security_level=SecurityLevel.PRODUCTION, # production level security initiated
1223
+ api_key=secret_key # set secret key you initialized <- THIS IS IMPORTANT
1224
+ max_workers=4, # workers to initiate prediction, more workers, more capabilities to process prediction requests.
1225
+ task_timeout=30,
1226
+ max_retries=3 ) # retries after failure during prediction
1227
+ ```
1228
+ - And make sure you also initialized api_key in the predict function that requires api_key:
1229
+ ```
1230
+ async_manager.predict(...., ...., api_key=api_key, ...)
1231
+ ```
1232
+
1233
+ ## [=] Detailed process of Alpha-computing
1234
+
1235
+ <img width="720" height="338" alt="WhatsApp Image 2026-05-04 at 17 43 35" src="https://github.com/user-attachments/assets/3d149dce-cf3b-44c9-80b0-fa68290a2019" />
1236
+
1237
+ <img width="720" height="388" alt="WhatsApp Image 2026-05-04 at 17 44 04" src="https://github.com/user-attachments/assets/b1efedf6-5aa1-431e-89da-5f422549b453" />
1238
+ 🧠 What Alpha-Based Computation Actually Does
1239
+
1240
+ At its core, alpha (α) is a control parameter that blends two different information paths inside a given transformer:
1241
+ A_final = α · A_fixed + (1 − α) · A_learned.
1242
+ [~] Where:
1243
+ - A_fixed → stable, non-trainable (or minimally changing) attention
1244
+ - A_learned → dynamic, trainable attention (Q, K, V)
1245
+ - α ∈ [0, 1] → controls how much each path contributes
1246
+
1247
+ [~] Forward Pass -> Controlling Information Flow:
1248
+ During the forward pass, alpha determines what representation the model uses.
1249
+ If α is high (e.g., 0.8–1.0): Model relies mostly on stable attention
1250
+ → outputs are consistent → less noise → safer early training, If α is low (e.g., 0.0–0.3), Model relies mostly on learned attention, → more expressive → but unstable early on.
1251
+ So in forward propagation, alpha is essentially, “How much do I trust learned attention vs safe attention?”
1252
+
1253
+ [~] Backward Pass -> Controlling Gradient Flow:
1254
+ When gradients flow backward:
1255
+ ```
1256
+ - dA_final → splits into two paths
1257
+ - Mathematically:
1258
+ - dA_fixed = α · dA_final
1259
+ - dA_learned = (1 − α) · dA_final
1260
+ ```
1261
+
1262
+ [~] Simple Explanation:
1263
+ 1. If α (alpha) is high: → most gradient goes to fixed path → learned attention gets very little update → training is stable but slow
1264
+ 2. If α is low: → most gradient goes to learned attention → fast learning → but noisy / unstable
1265
+
1266
+ [=] Why This Matters for Training
1267
+ 1. Without alpha: attention starts random → gradients noisy → model stuck (~10% accuracy)
1268
+ 2. With alpha: early stage -> rely on stable structure → meaningful gradients
1269
+
1270
+
1271
+ _____________________________________________________________________________________________________________
1272
+ ## Main Components
1273
+ [=] 1. - Consider checking and run: [IntegratedPipeline_Flow.html](IntegratedPipeline_Flow.html) regarding each function of the whole components and deep-dive mechanism.
1274
+ 2. - consider checking [ARCHITECTURE.md](ARCHITECTURE.md) for more explanation about the main components.
1275
+
1276
+ [=] With 23 total architectures working together as a standalone library that is efficient and robust, Main components include:
1277
+
1278
+ 1. GeometricWeightShaping
1279
+ Purpose: Analyzes the geometric structure of data (anisotropy, spectral properties, complexity) and generates optimal weight matrices based on that geometry. Essentially teaches the model how to "understand" the shape of data before processing it, Highly robust to noise, making it an excellent fit for messy environment.
1280
+ ---
1281
+ 2. Activation
1282
+ Purpose: Provides standard neural network activation functions (ReLU, sigmoid, softmax) and their derivatives for backpropagation for MLP Class.
1283
+ ---
1284
+ 3. Loss
1285
+ Purpose: Implements categorical crossentropy loss and its gradient for training classification models for both MLP and The Transformer
1286
+ ---
1287
+ 4. Transformer
1288
+ Purpose: A complete transformer implementation with multi-head attention, positional embeddings, feed-forward networks, layer normalization, and custom backpropagation. Includes both fixed (stable) and dynamic (adaptive) training modes necessary for Scarce data environment using algorithm such as Alpha based computing directly during forward pass.
1289
+ ---
1290
+ 5. Dense
1291
+ Purpose: A geometric-aware dense layer that adapts its weights based on input data geometry and handles variable input dimensions automatically.
1292
+ ---
1293
+ 6. SoftmaxOutput
1294
+ Purpose: A simple wrapper around softmax activation that stores the output and passes gradients through unchanged (since softmax + crossentropy gradient is handled elsewhere).
1295
+ ---
1296
+ 7. MLP
1297
+ Purpose: A multi-layer perceptron that can switch between standard training and "focused" training (using feed-forward layers only) based on data complexity. Includes prediction, scoring, and geometric measurement methods.
1298
+ ---
1299
+ 8. WeightedEnsemblePredictor
1300
+ Purpose: Combines Transformer and MLP predictions using dynamic weighting based on attention quality, model confidence, and agreement. Also manages memory storage, explainability, and peer agent communication.
1301
+ ---
1302
+ 9. CrossSessionAutomation
1303
+ Purpose: Manages exporting, importing, and syncing model sessions across different devices or time periods. Allows saving entire model states to JSON and transferring them over network sockets.
1304
+ ---
1305
+ 10. ExplainabilityModule
1306
+ Purpose: Generates human-readable explanations for predictions, learns from user feedback, maintains decision history, and batch-trains on corrections. The transparency layer for the AI agent.
1307
+ ---
1308
+ 11. ModelStorage
1309
+ Purpose: SQLite-based persistence for models, attention weights, node memories, and agent data. Handles serialization/deserialization of numpy arrays and model dictionaries.
1310
+ ---
1311
+ 12. AgentDistributedInference
1312
+ Purpose: The distributed agent system - can act as a server or client, handles SSL/TLS security, rate limiting, authentication, peer-to-peer prediction requests, memory synchronization, ensemble voting, and trust management between agents.
1313
+ ---
1314
+ 14. QueryNode
1315
+ Purpose: Manages trust relationships and identity verification between nodes. Evaluates node agreement, establishes connections, performs safety checks, and maintains the network of trusted peers.
1316
+ ---
1317
+ 14. AutoBatcherAutomation
1318
+ Purpose: Automatically batches incoming prediction requests to optimize throughput. Collects requests up to a maximum batch size or time window, then processes them together.
1319
+ ---
1320
+ 15. IntegratedPipeline
1321
+ Purpose: The main orchestration class that ties everything together - handles text encoding, model initialization, training, prediction, memory management, hybrid predictions, and distributed inference coordination.
1322
+ ---
1323
+ 16. PipelinePredictionManager
1324
+ Purpose: High-level prediction interface that loads labels from CSV, performs regular/advanced/hybrid predictions, displays results, and calculates entropy for uncertainty estimation.
1325
+ ---
1326
+ 17. ThreadedMessageQueue
1327
+ purpose: Handles message queue in thread for asynchronous message handling. (Queue based)
1328
+ ---
1329
+ 18. AsyncMessageQueue
1330
+ purpose: Handles incoming message from Asychronous peer request (Queue based)
1331
+ ---
1332
+ 19. CohesiveAgentDeployment
1333
+ purpose: Handles both synchronous prediction, and P2P Asynchronous prediction request, acts as a server and a listener simultaneously.
1334
+ ---
1335
+ 20. ConsecutivePeerAgent
1336
+ purpose: handles ensemble weighting from received output from peer, managed server and acts as a listener simultaneously.
1337
+ ---
1338
+ 21. LSTMCell
1339
+ purpose: handles LSTM Core equations In Numpy.
1340
+ ---
1341
+ 22. LSTMNetwork
1342
+ purpose: handling LSTM Feed-forward layer, Training and Samples handling.
1343
+ ---
1344
+ 23. LSTMEngine
1345
+ purpose: handles Proper LSTM Confidence and calibration layer.
1346
+
1347
+ ## Full Documentation Features
1348
+ - [Go to IntegratedPipeline-Specialized-AI-Agent-library](#IntegratedPipeline-Specialized-AI-Agent-library)
1349
+ - [Go to MANN Intro](#MANN-Intro)
1350
+ - [Go to Abstract Weight Encoder (AWE) Intro](#Abstract-Weight-Encoder-(AWE)-Intro)
1351
+ - [Go to LSTM And Transformer Into](#-lstm-and-transformer-intro)
1352
+ - [Go to Why IntegratedPipeline?](#Why-IntegratedPipeline?)
1353
+ - [Go to Requirements](#Requirements)
1354
+ - [Go to System-Specific-Notes](#System-Specific-Notes)
1355
+ - [Go to Quickstart with Docker](#Quickstart-with-Docker)
1356
+ - [Go to Performance in ARM64 Environment/Container](#Performance-in-ARM64-Environment/Container)
1357
+ - [Go to Step's for in-depth Usage](#Step's-for-in-depth-Usage)
1358
+ - [Go to Troubleshooting](#Troubleshooting)
1359
+ - [Go to Detailed process of Alpha-computing](#Detailed-process-of-Alpha-computing)
1360
+ - [Go to Main Components](#Components)
1361
+ - [Go to Source code](#Source-code-of-AbstractIntegratedModule)
1362
+ - Consider checking:
1363
+ - [ROADMAP.md](ROADMAP.md)
1364
+ - [Contributing.md](Contributing.md)
1365
+ - [changelog.md](changelog.md)
1366
+ - [requirements-For-Dev](dev_needs.txt) for contributors requirements.
1367
+ - [architecture_diagram.js](architecture_diagram.js).
1368
+
1369
+ ## License
1370
+ [=] LICENSE: - MIT (2026) || See [LICENSE](LICENSE) for more information.
1371
+
1372
+
1373
+
1374
+
1375
+
1376
+
1377
+
1378
+