AbstractIntegratedModule 0.7.2__cp310-cp310-musllinux_1_2_aarch64.whl

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.
@@ -0,0 +1,1153 @@
1
+ Metadata-Version: 2.4
2
+ Name: AbstractIntegratedModule
3
+ Version: 0.7.2
4
+ Summary: Integrated Pipeline with Specialized Non-LLM AI Agent Framework
5
+ Author: Micro-Novelty
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: numpy>=2.1.0
10
+ Dynamic: license-file
11
+
12
+ # [=] IntegratedPipeline-Specialized-AI-Agent-library
13
+
14
+ [~] Introduction:
15
+ - IntegratedPipeline is a standalone Specialized AI Agent Library for Non-LLL 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.
16
+ - 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.
17
+
18
+
19
+ ### Library Short Description:
20
+ - Development Stage on PyPi: 0.7.0 Official Release.
21
+ - Author and Maintainer: Micro-Novelty and EpsitronNet-bot.
22
+ - library Source-Code is Open-sourced with MIT License.
23
+ - Purpose: Specifically Designed for providing Non-LLM AI Agent Framework for edge Devices, Optimized for ARM64 architecture.
24
+ - Library installation:
25
+ ```bash
26
+ pip install AbstractIntegratedModule
27
+ python -m install AbstractIntegratedModule
28
+ ```
29
+
30
+ - The library also includes precompiled binaries for:
31
+ - x86_64 linux architecture: only supports python version 3.12.
32
+ - aarch64 linux architecture: only supports python version 3.10.
33
+ - win_amd64 windows 64-bit architecture: only supports python version 3.13.
34
+ if you don't have the necessary python, don't worry since you could use our regular pip download.
35
+
36
+ - Proven Capabilities:
37
+ - The library has been thoroughly tested in Multiple Environments from Windows to ARM64 Environment. The library is now Robust for Wider use and Deployment.
38
+ - Proven Works on ARM64 Environment, Training and Prediction works efficient on Docker ARM64 environment with QEMU, good parallelizing behavior is guaranteed.
39
+ - P2P Works efficiently in ARM64 Docker + QEMU, No conflicting socket and all prediction works efficiently.
40
+ - AWE setup Proven Efficient on Hard-uncontrolled dataset such as Activity Recognition from the given Database.
41
+ - LSTM is Optimized efficiently for scarce data with AWE method.
42
+ - Robust Advanced prediction capabilities proven effective on ARM64 Using MLP + LSTM Architectures.
43
+ - Transformer Optimized using Cython, to reduce Memory overhead and Reduce CPU Usage, With Reduced Training Time.
44
+ -----
45
+
46
+ <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" />
47
+
48
+
49
+ ## [+] MANN Intro
50
+ [=] 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.
51
+
52
+ ## [+] Abstract Weight Encoder (AWE) Intro
53
+ [=] 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.
54
+
55
+ ## [+] LSTM And Transformer Intro:
56
+ 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.
57
+ - LSTM (Long Short-Term Memory):
58
+ - LSTMs are an advanced class of Recurrent Neural Networks (RNNs) introduced to solve the problem of traditional RNNs forgetting earlier data.
59
+ - 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.
60
+ - Use Cases: Ideal for tasks with strictly continuous chronological data like time-series forecasting (e.g., stock market or weather prediction) or speech recognition.
61
+ - Limitations: Because they process data in a strict chain, it is difficult to parallelize training, making them slow and prone to forgetting long contexts.
62
+
63
+ B. Transformer:
64
+ Transformers are the modern standard for AI, introduced in 2017 with the famous "Attention Is All You Need" paper.
65
+ - 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.
66
+ - Use Cases: The backbone of Large Language Models (LLMs) like ChatGPT or BERT, making them perfect for machine translation, text generation, and summarization.
67
+ - Limitations: Transformers require massive amounts of training data and computing power to work effectively.
68
+
69
+
70
+ [~] For a much In-Depth Explanation You can visit This repository to learn more about AWE and its performance results:
71
+ - Link: https://github.com/Micro-Novelty/Specialized-MLP-for-noise-robustness
72
+
73
+ ## [+] Why IntegratedPipeline?
74
+ [~] 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.
75
+
76
+ [=] IntegratedPipeline offers:
77
+ 1. Local-Based AI Orchestrator:
78
+ - 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.
79
+
80
+ 2. Continously Learning behavior for an Agent:
81
+ - 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.
82
+
83
+ 3. Robust Specialized MLP, Transformer and LSTM Architecture with ensemble weighting architecture:
84
+ - IntegratedPipeline has 2 Different type's of AI Architecture stacked together, and one architecture to weight their confidence and probability fairly to get the final prediction, 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:
85
+ - 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.
86
+ - 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.
87
+ - 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.
88
+ - 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.
89
+
90
+
91
+ 4. flexible and secure Peer-to-Peer Coordination (Multi-Agent):
92
+ - 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:
93
+ - secure socket using user provided SSL CERT. on both client and server,
94
+ - API key for requesting,
95
+ - Alpha rate limiting,
96
+ - HMAC secret key for authentication,
97
+ - and IP validation.
98
+ [~] Each agent has double roles during P2P:
99
+ - Server provider: the peer Agent can start a server to listen for peer client's
100
+ - 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.
101
+
102
+ 5. Cross-Session memory availability:
103
+ - IntegratedPipeline offers share-able Memory capability, included capability below:
104
+ - 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.
105
+ - Importable Memory: allowing to import memory from the exported .json file directly for the model to use.
106
+ - syncing with other model: socket-based communication to export memory to other external machine.
107
+ - [=] 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.
108
+ - list sessions: listing available sessions using model's memory name.
109
+
110
+ [=] 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:
111
+
112
+ [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.
113
+
114
+ [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.
115
+
116
+ [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.
117
+
118
+ [=] Architectural-Overview
119
+ <img width="1600" height="859" alt="New Arch" src="https://github.com/user-attachments/assets/a5db1ed2-9149-4635-8d95-d022ad6e8608" />
120
+ ---
121
+ [=] Contextual meaning:
122
+ 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
123
+ 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).
124
+ 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.
125
+
126
+ ### Introduction and demo
127
+ [![Introduction and demo:](https://youtube.com)](https://youtu.be/RmWvwDHU_QY?si=Lvl8mt8c_BnFypS_)
128
+ - Quick demo start: [main.py](main.py)
129
+ - purpose: let you demonstrate the advanced prediction method and asynchronous prediction directly.
130
+ - Quick test of P2P:
131
+ - [multi_agent_client.py](P2P_Setups/multi_agent_client.py)
132
+ - [multi_agent_server.py](P2P_Setups/multi_agent_server.py)
133
+ - [P2PDirectTest.py](P2P_Setups/P2PDirectTest.py)
134
+ - 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.
135
+
136
+ ## [=] Requirements
137
+ [~] To run and execute IntegratedPipeline, Requirement's include Or see [Requirements](installation_guides/usage_needs.txt):
138
+ - pip install for quick usage:
139
+ - ```bash
140
+ pip install AbstractIntegratedModule # or
141
+ python -m pip install AbstractIntegratedModule
142
+ ```
143
+
144
+ - Download binaries manually (Choose one minimal, specified for your needs):
145
+ - AbstractOptimizedModules for Optimizing Transformer using Cython (Optional)
146
+ - AbstractIntegratedModule (Main library binary)
147
+
148
+ - Binaries can be downloaded from release or code section.
149
+ - Windows Native OS -
150
+ - AbstractIntegratedModule.cp313-win_amd64 and its AbstractOptimizedModules.pyd Supports Python 3.13 for Windows Only (Robust, Stable version)
151
+ - Linux x86_64
152
+ - AbstractIntegratedModule.cpython-312-x86_64-linux-gnu.so and its AbstractOptimizedModules.so supports Python 3.12 only.
153
+ - Linux ARM64 - Raspberry Pi (Supports Raspberry pi 3 - 5)
154
+ - AbstractIntegratedModule.cpython-310-aarch64-linux-gnu.so and its AbstractOptimizedModules.so supports Python 3.10 only.
155
+
156
+ - Libraries needed (For binary usage):
157
+ - Pandas
158
+ - aiohttp
159
+ - scikit-learn
160
+ - numpy
161
+ - psutil
162
+
163
+ - Download AbstractIntegratedModule binaries from release section:
164
+ - This file contains:
165
+ - AbstractIntegratedModule.pyd, AbstractOptimizedModules.pyd (For windows machine).
166
+ - AbstractIntegratedModule.cpython-39-x86_64-linux-gnu.so, AbstractOptimizedModules.cpython-39-x86_64-linux-gnu.so (For linux x86_64).
167
+ - AbstractIntegratedModule.cpython-39-aarch64-linux-gnu.so, AbstractOptimizedModules.cpython-39-aarch64-linux-gnu.so (for Linux ARM64 - Raspberry Pi).
168
+
169
+ [=] for labels assignation:
170
+ - 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.
171
+
172
+ ### [=] Requirements for Docker container
173
+ - Dockerfile (For Container assembler)
174
+ - Python scripts (Such as main.py for Dockerfile usage).
175
+ - entrypoint.sh (for smart entry point for Dockerfile container usage).
176
+
177
+ ## [=] System-Specific Notes
178
+ 1. Windows:
179
+ - Requires Visual C++ Build Tools for compatibility
180
+ - Use PowerShell or CMD (not WSL bash for best results)
181
+
182
+ 2. Linux:
183
+ - Ensure gcc and build-essential are installed
184
+ - Different distributions may require different package managers
185
+
186
+ 3. ARM64 - Raspberry Pi
187
+ - Installation may take 30+ minutes due to ARM architecture
188
+ - Monitor system resources during installation
189
+ - Consider using faster storage (USB SSD) for better performance
190
+
191
+ ## [=] Docker Container Application
192
+ 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.
193
+ - Note Consider checking:
194
+ - [Dockerfile](docker-setups/Dockerfile) contains all the instructions need to assemble a Docker container.
195
+ - [start.sh](docker-setups/start.sh) for Quick single agent start in Docker container.
196
+ - [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)
197
+ - [start-multi-agent-cluster.sh](P2P_Setups/start-multi-agent-cluster.sh) for Multi-agent cluster start in Docker container, What it does:
198
+ - 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.
199
+ - 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.
200
+ - [main.py](main.py) for executing a python script in the Docker container that used main.py, like in this code:
201
+ - ```bash
202
+ docker run -it -v $(pwd):/app/data integrated-pipeline:latest python /app/data/main.py
203
+ ```
204
+ - 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.
205
+ - [.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.
206
+
207
+ 1. Build Image:
208
+ - Clone repository:
209
+ - ```bash
210
+ git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git
211
+ cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework
212
+ ```
213
+ - Download:
214
+ - [Dockerfile](docker-setups/Dockerfile),
215
+ - [entrypoint.sh](docker-setups/entrypoint.sh)
216
+ - [.env](docker-setups/.env)
217
+ - In the code or release section.
218
+
219
+ - If the downloaded Dockerfile or .dockerignore or .env has .txt extension, remove the extension:
220
+ - ```bash
221
+ # remove .txt extension
222
+ mv Dockerfile.txt Dockerfile
223
+ mv env.txt .env
224
+ mv dockerignore.txt .dockerignore
225
+ ```
226
+ - Navigate to the folder: Use the cd command to enter the directory containing the Dockerfile and entrypoint.sh file.
227
+ - ```
228
+ cd /path/to/your/folder
229
+ ```
230
+ - build image:
231
+ - ```bash
232
+ sudo docker build -t integrated-agent.
233
+ ```
234
+ 2. Download library dependencies for binaries usage:
235
+ [=] Required libraries (when using binary):
236
+ - Numpy
237
+ - Scikit-learn
238
+ - pandas
239
+ - aiohttp
240
+ - psutil
241
+
242
+ 4. Run IntegratedPipeline in a Container:
243
+ - Install AbstractIntegratedModule via PIP or binaries (for binaries, can be downloaded in release section):
244
+ - ```bash
245
+ pip install AbstractIntegratedModule # or
246
+ python -m pip install AbstractIntegratedModule
247
+ ```
248
+
249
+ - ```bash
250
+ docker run -it --name ai-agent integrated-agent:latest python
251
+ ```
252
+ - In python shell:
253
+ - ```
254
+ from AbstractIntegratedModule import IntegratedPipeline, PipelinePredictionManager
255
+ model = IntegratedPipeline('agent_memory')
256
+ print("✓ IntegratedPipeline initialized successfully!")
257
+ ```
258
+
259
+ 5. Run script:
260
+ ```bash
261
+ # Mount your local directory and run a script
262
+ docker run -it -v $(pwd)/data:/app/data integrated-agent:latest python main.py # main.py could be replaced
263
+ ```
264
+
265
+ 6. Run with GPU Support (Optional):
266
+ - ```bash
267
+ # For NVIDIA GPU support
268
+ docker run -it --gpus all -v $(pwd)/data:/app/data integrated-agent:latest python main.py
269
+ ```
270
+
271
+ 7. For Single Agent and Multi-Agent P2P:
272
+
273
+ [=] Single agent:
274
+ ```bash
275
+ # Build image
276
+ docker build -t integrated-agent:latest .
277
+
278
+ # Run single agent
279
+ docker run -it -v $(pwd)/data:/app/data integrated-agent:latest python
280
+ ```
281
+
282
+ [=] Multi agent P2P (Consider docker-compose) :
283
+ - Note: Use the provided [docker-compose.yml](docker-setups/docker-compose.yml) for Quick multi-agent.
284
+ - Navigate to the folder: Use the cd command to enter the directory containing the docker-compose.yml file.
285
+ - ```
286
+ cd /path/to/your/folder
287
+ ```
288
+ - run this command to run docker-compose.yml:
289
+ - ```bash
290
+ # Start multiple agents
291
+ docker-compose up -d
292
+
293
+ # View logs
294
+ docker-compose logs -f
295
+
296
+ # Stop all agents
297
+ docker-compose down
298
+ ```
299
+
300
+ ## Performance in linux ARM64 Docker Environment/Container
301
+ A. [=] Computational performance results with Transformer included during Advanced prediction method.
302
+ ```txt
303
+ == TIME == | CPU % | RAM / RAM LIMIT ||
304
+
305
+ 14:50:08.762 0.00% 25.52MiB / 3.71GiB
306
+ 14:50:10.339 5.56% 25.52MiB / 3.71GiB
307
+ 14:50:12.428 0.17% 25.52MiB / 3.71GiB
308
+ 14:50:15.835 103.60% 38.8MiB / 3.71GiB
309
+ 14:50:17.844 438.11% 60.15MiB / 3.71GiB
310
+ 14:50:19.896 419.36% 68.32MiB / 3.71GiB
311
+ 14:50:22.022 434.15% 73.2MiB / 3.71GiB
312
+ 14:50:23.969 436.47% 78.18MiB / 3.71GiB
313
+ 14:50:25.966 435.85% 80.22MiB / 3.71GiB
314
+ 14:50:28.018 430.47% 92.12MiB / 3.71GiB
315
+ 14:50:30.029 450.55% 99.5MiB / 3.71GiB
316
+ 14:50:32.065 438.06% 105.4MiB / 3.71GiB
317
+ 14:50:34.100 469.52% 115.2MiB / 3.71GiB
318
+ 14:50:36.109 449.89% 116.8MiB / 3.71GiB
319
+ 14:50:38.123 423.56% 119MiB / 3.71GiB
320
+ ```
321
+ - [=] Note: To read the full logs (For included Transformer performance): [performance_log_with_TF](performance_logs/performance_log_with_TF.txt)
322
+ - [=] Explanation:
323
+ - Average CPU Usage = 420% - 430% , Sustained roughlt 4.20 - 4.30 CPU Cores
324
+ - Meaning = - Compute-Intensive workload
325
+ - reduced guaranteed of experiencing deadlocks, thread starvation, and major stalls
326
+ - numerical backend is parallelizing efficiently
327
+ - Average RAM Usage = 180 - 195 Mib, Roughly 4.5 - 5% usage of available RAM
328
+ - Meaning = - Very efficient RAM Usage
329
+ - Repeated 269 MiB suggests allocator settled, ndarray pools stabilized, workload reached steady state
330
+ - gradual, safe and steady batch accumulation, reduced possibility of leak explosion.
331
+
332
+ B. [=] Advanced Prediction without Transformer, Only Specialized MLP + LSTM using AWE.
333
+ ```txt
334
+ == TIME == | CPU % | RAM \ RAM LIMIT |
335
+ 10:01:37.456 100.44% 269.8MiB / 3.71GiB # initial round 1 training started
336
+ 10:01:38.686 101.93% 279.8MiB / 3.71GiB
337
+ 10:01:40.694 101.94% 293.2MiB / 3.71GiB
338
+ 10:01:42.703 99.90% 302.9MiB / 3.71GiB
339
+ 10:01:44.712 99.34% 319.8MiB / 3.71GiB
340
+ 10:01:46.721 100.15% 319.7MiB / 3.71GiB
341
+ 10:01:48.727 101.91% 319.7MiB / 3.71GiB
342
+ 10:01:50.734 100.86% 319.7MiB / 3.71GiB
343
+ 10:01:52.742 136.43% 322.9MiB / 3.71GiB
344
+ 10:01:54.751 101.91% 324.9MiB / 3.71GiB
345
+ 10:01:56.758 100.29% 324.9MiB / 3.71GiB
346
+ 10:01:58.769 102.42% 327.1MiB / 3.71GiB
347
+ 10:02:00.775 0.00% 329.6MiB / 3.71GiB # First Training and prediction round 1 finished
348
+ 10:02:02.788 19.55% 330.1MiB / 3.71GiB # round 2 training
349
+ 10:02:04.798 134.23% 332.2MiB / 3.71GiB
350
+ 10:02:06.803 108.80% 332.2MiB / 3.71GiB
351
+ 10:02:08.811 107.85% 332.2MiB / 3.71GiB
352
+ 10:02:10.857 104.43% 332.2MiB / 3.71GiB
353
+ 10:02:12.854 101.14% 332.2MiB / 3.71GiB
354
+ 10:02:14.858 0.00% 332.3MiB / 3.71GiB
355
+ 10:02:16.873 98.84% 333.8MiB / 3.71GiB
356
+ 10:02:18.869 0.00% 132.7MiB / 3.71GiB # container stopped and round 2 finished
357
+ ```
358
+ - [=] Note: See full performance log in here: [performance_log_only_MLP](performance_logs/performance_log_only_MLP.txt)
359
+ - [=] Explanation:
360
+ - Average CPU Usage = 85-90% Used, sustained roughly 1 CPU Core saturated on average
361
+ - Meaning: - Very efficient computation
362
+ - Much lighter CPU Usage than Transformer.
363
+ - Stable and less parallelizing behavior (Efficient computation)
364
+ - 4.7x lower CPU usage than transformer included
365
+ - Average RAM usage = 314 MiB / 3.71 GiB, Roughly 8.5% usage of available RAM.
366
+ - Meaning: - Slightly larger MiB used than Transformer.
367
+ - Model allocation growth is stable,
368
+ - training buffers stable
369
+ - temporary ndarray growth.
370
+
371
+ ### Both performance Overview
372
+ <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" />
373
+ _______________________________________
374
+ - Note:
375
+ - 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,
376
+ MLP And LSTM stays the same and still fully optimized.
377
+
378
+ ## Source code of AbstractIntegratedModule
379
+ - Note: The source code is provided in the repository.
380
+ - [=] Full Monolithic extensively-documented source code (12K+ Lines): [AbstractIntegratedPipeline-SourceCode.zip](AbstractIntegratedPipeline-SourceCode.zip)
381
+ - [=] Separated Modules of AbstractIntegratedModule: [separated-modules](separated-modules)
382
+ - [AbstractIntegratedModule.pyx](AbstractIntegratedModule.pyx) and [AbstractOptimizedModules.pyx](AbstractOptimizedModules.pyx) files for independent compilation or direct compiling on real ARM64 device.
383
+ - [lib.rs](rust_optimization_setups/lib.rs) that contains Rust optimization for Models weight handling.
384
+ - [~] Note:
385
+ - The source code is open and Free to anyone who:
386
+ - Use it: Run the software for any personal, academic, or commercial purpose.
387
+ - Modify it: Change the source code to fit their needs.
388
+ - Distribute it: Share the original or modified code with others.
389
+ - Commercialize it: Package, brand, and sell the software for profit.
390
+
391
+ ## [=] Step's for in-depth Usage
392
+ 0. Download via PIP:
393
+ - Clone repository first:
394
+ ```bash
395
+ # Clone immediately for Windows and x86_64 only without prerequisites
396
+ git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git
397
+ cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework
398
+ ```
399
+
400
+ - Install the library via pip:
401
+ ```bash
402
+ pip install AbstractIntegratedModule #or
403
+ python -m pip install AbstractIntegratedModule
404
+ ```
405
+
406
+ 1. Download for binaries:
407
+ - AbstractIntegratedModule.pyd, AbstractOptimizedModules.pyd (For windows machine) (Python 3.13)
408
+ - AbstractIntegratedModule.cpython-39-x86_64-linux-gnu.so, AbstractOptimizedModules.cpython-39-x86_64-linux-gnu.so (For linux x86_64) (Python 3.12)
409
+ - AbstractIntegratedModule.cpython-39-aarch64-linux-gnu.so, AbstractOptimizedModules.cpython-39-aarch64-linux-gnu.so (for Linux ARM64 - Raspberry Pi) (Python 3.10)
410
+ - ```
411
+ # Download from release
412
+ # AbstractIntegratedModule.pyd, AbstractOptimizedModules.pyd (windows) /
413
+ # Abstractcpython-39-x86_64-linux-gnu.so, AbstractOptimizedModules.cpython-39-x86_64-linux-gnu.so (x86_64) /
414
+ # AbstractIntegratedModule.cpython-39-aarch64-linux-gnu.so , AbstractOptimizedModules.cpython-39-aarch64-linux-gnu.so
415
+ ```
416
+
417
+ [=] Steps for installation:
418
+ Note: AbstractIntegratedModule has 5 library dependencies that must be installed on your computer if you use AbstractIntegratedModule binaries:
419
+ - [=] Required Libraries (For binaries usage):
420
+ - Numpy
421
+ - Scikit-learn
422
+ - pandas
423
+ - aiohttp
424
+ - psutil
425
+
426
+ 1. Clone repository:
427
+ - ```
428
+ # prerequisites (for Raspberry pi OS Only)
429
+ # Update system
430
+ sudo apt-get update
431
+ sudo apt-get upgrade -y
432
+
433
+ # Install Python 3.13 and development tools
434
+ sudo apt-get install python3.13 python3.13-dev python3.13-venv -y
435
+
436
+ # Install additional build tools
437
+ sudo apt-get install build-essential libatlas-base-dev libjasper-dev -y
438
+
439
+ # Clone immediately for Windows and x86_64 only without prerequisites
440
+ git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git
441
+ cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework
442
+ ```
443
+ 2. Install System Dependencies (for x86_64 installation):
444
+ ```
445
+ # Ubuntu/Debian
446
+ sudo apt-get update
447
+ sudo apt-get install python3.13 python3.13-dev python3.13-venv
448
+
449
+ # CentOS/RHEL
450
+ sudo yum install python313 python313-devel
451
+
452
+ # Fedora
453
+ sudo dnf install python3.13 python3.13-devel
454
+ ```
455
+
456
+ 3. Create a virtual environment:
457
+ - ```
458
+ # Create virtual environment (windows)
459
+ python -m venv venv
460
+ # Activate virtual environment
461
+ venv\Scripts\activate
462
+
463
+ # Create virtual environment (x86_64) (ARM64 / raspberry pi)
464
+ python3.13 -m venv venv
465
+ # Activate virtual environment
466
+ source venv/bin/activate
467
+ ```
468
+
469
+ 4. Copy AbstractIntegratedModule binary:
470
+ - ```
471
+ # For windows:
472
+ # Copy the .pyd file to your project root
473
+ # AbstractIntegratedModule.pyd
474
+ copy C:\path\to\AbstractIntegratedModule.pyd .\AbstractIntegratedModule.pyd
475
+
476
+ # Copy the .so file to your project root (for x86_64)
477
+ cp /path/to/AbstractIntegratedModule.cpython-39-x86_64-linux-gnu.so ./AbstractIntegratedModule.cpython-39-x86_64-linux-gnu.so
478
+
479
+ # Copy ARM64 / Raspberry pi binary
480
+ cp /path/to/AbstractIntegratedModule.cpython-39-aarch64-linux-gnu.so ./AbstractIntegratedModule.cpython-39-aarch64-linux-gnu.so
481
+
482
+ 5. Verify Installation:
483
+ - ```
484
+ python -c "from AbstractIntegratedModule import IntegratedPipeline; print('✓ Installation successful!')"
485
+ ```
486
+
487
+ 6. Run main.py for quick test of successful imports:
488
+ - ```
489
+ # run this for quick import test.
490
+ python main.py
491
+ ```
492
+
493
+
494
+
495
+ 3. Create CSV file that contains training labels and titles:
496
+ - Example format:
497
+ ```txt
498
+ window_title,label
499
+ "Thesis.docx",focused_work,high,writing-thesis
500
+ "Microsoft Excel",work,medium,data-analysis
501
+ "YouTube -> Google Chrome",distracted,high,watching-videos
502
+ "Slack",communication,high,team-chat
503
+ "VSCode", focused_work,high,coding
504
+ "netflix.com -> Google Chrome",break,high,Netflix-break
505
+ "Outlook",work,medium,checking-email
506
+ "System Settings",system designing,low,configuring-computer
507
+ "GitHub",creating-and-editing-repo,research
508
+ "README.md -> VS Code",focused_work,medium,reading-docs
509
+ "Amazon.com -> Chrome",personal-work,high,shopping
510
+ ```
511
+ Note = window_title is target_title and label is target_label, check step below to use it.
512
+
513
+ 4. Use IntegratedPipeline as in this example:
514
+ ```python
515
+ from AbstractIntegratedModule import IntegratedPipeline
516
+ from AbstractIntegratedModule import PipelinePredictionManager
517
+ import numpy as np
518
+
519
+ memory_name = 'agent_memory'
520
+ cert_file = <your_cert_file_dir> # your .crt file
521
+ key_file = <your_key_file_dir> # your .key file
522
+
523
+ main_model = IntegratedPipeline(
524
+ memory_name=memory_name, # memory name for the AI you already initialized
525
+ use_async=True, # local asynchronous prediction is permitted, if not PipelineAsyncManager wont start asynchronous prediction.
526
+ agent_port=5001, # this port is used to set AgentDistributedInference server (optional)
527
+ ssl_cert_file=cert_file, ssl_key_file=key_file) # provide your cert_file path or key_file path (optional)
528
+
529
+ main_prediction = PipelinePredictionManager(
530
+ main_model, # your initialized pipeline
531
+ label_csv='example_manual_training.txt', # your .txt file that contains CSV format.
532
+ target_title='window_title', label='label')
533
+
534
+ # example_manual_training is a .txt file that contain csv format like above example.
535
+
536
+ # rules will be used to create automatic dataset for IntegratedPipeline.
537
+ example_rules = [
538
+ # === WORK / PRODUCTIVITY ===
539
+ (r'code|programming|develop|debug|compile|script', 'focused_work'),
540
+ (r'vscode|visual_studio|ide|terminal|shell', 'focused_work'),
541
+ (r'notion|evernote|onenote|notes|todo|task', 'productive'),
542
+ (r'slack|teams|discord|zoom|meeting|call', 'communication'),
543
+ (r'email|gmail|outlook|inbox|mail', 'communication'),
544
+
545
+ # === ENTERTAINMENT ===
546
+ (r'youtube|netflix|twitch|stream|video', 'entertainment'),
547
+ (r'music|spotify|soundcloud|audio|player', 'entertainment'),
548
+ (r'game|gaming|steam|epic|play', 'gaming'),
549
+ (r'facebook|instagram|tiktok|social|post', 'social_media'),
550
+
551
+ # === BROWSING ===
552
+ (r'chrome|firefox|edge|safari|browser', 'browsing'),
553
+ (r'google|search|wiki|wiki|article', 'information'),
554
+ (r'stackoverflow|github|docs|documentation', 'research'),
555
+
556
+ # more rules
557
+ ]
558
+
559
+ # activate explainability capability to explain uncertainty:
560
+ main_model.show_explainability_details = True
561
+ main_model.distribution.predict_manager = main_prediction # set PipelinePredictionManager to AgentDistributedInference for asynchronous prediction later (Very important for asynchronous prediction)
562
+ # 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.
563
+
564
+
565
+ # test samples with more sophisticated rules and more complex titles for prediction
566
+ # (title, intent)
567
+ test_titles = [
568
+ ("Opening Thesis.docx", "slight_work"),
569
+ ("Watching YouTube and Google Chrome", "distracted"),
570
+ ("Watching Slack", "communication"),
571
+ ("Programming in Visual Studio Code", "focused_work"),
572
+ ("Watching netflix.com - Chrome", "break"),
573
+ # more titles
574
+ ]
575
+
576
+ titles, y, label_map = main_prediction.load_labels_from_csv(
577
+ <your_filename.>, # the name of your .txt file with CSV format.
578
+ <target_title>, <target_label>)
579
+
580
+ # small training with simple titles first
581
+ main_model.train(titles, y)
582
+
583
+ # main_model.froze_learning = True
584
+ # prevent the model from training and make weights unchanged for static prediction.
585
+
586
+ results, chosen_label, confidence = main_prediction.advanced_prediction_method(
587
+ test_titles, label_map, example_rules,
588
+ X=None, y=None # you could create your own X and y samples and put it here (Optional)
589
+ show_proba=False, top_k=3,
590
+ use_transformer=True,
591
+ return_attention=False,
592
+ save_results=True,
593
+ batch_size=2)
594
+ # 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.
595
+ # ... more features you can add
596
+ ```
597
+
598
+ 5. To use IntegratedPipeline prediction without Transformer, Only Specialized MLP:
599
+ Note: IntegratedPipeline without Transformer is'nt recommended due to it being weak at certain contextual prediction's, excel's at classification task's.
600
+ - Example without transformer:
601
+ ```python
602
+ prediction_result = main_prediction.advanced_prediction_method(
603
+ [t[0] for t in test_titles], # titles is enough for MLP Classification.
604
+ label_map,
605
+ example_rules,
606
+ show_proba=True
607
+ )
608
+
609
+ ```
610
+ 6. Asynchronous prediction:
611
+ - 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,
612
+ - for asynchronous prediction handling, consider using this setup
613
+ ```python
614
+ # Step 2
615
+ from AbstractIntegratedModule import PipelineAsyncManager
616
+ from AbstractIntegratedModule import SecurityConfig
617
+ from AbstractIntegratedModule import SecurityLevel
618
+
619
+ print(" = TESTING ASYNCHRONOUS PREDICTION MANAGER = ")
620
+ # Set discovery secret (in production, use environment variable)
621
+ secret_key = 'my-ultra-safe-secret-key-for-authentication' # you can customize this key
622
+
623
+
624
+ security_config = SecurityConfig(
625
+ max_text_length=10000, # can be extended
626
+ max_queue_size=100, # can be extended
627
+ rate_limit_requests=60, # 60 per minute
628
+ require_api_key=True, #
629
+ max_pending_tasks=50,
630
+ request_timeout=60.0,
631
+
632
+ # Start with no IP restrictions, you can add allowed IPs for asynchronous prediction externally, boothstrap_auth for better security
633
+ allowed_ips=[],
634
+ blocklisted_ips=[],
635
+ require_bootstrap_auth = False # true for better security (Not recommended, cause less flexibility)
636
+ )
637
+
638
+ async_manager = PipelineAsyncManager(main_model,
639
+ main_prediction, # your previous initialized PipelinePredictionManager
640
+ config=security_config,
641
+ state_file=None, # state file is used to load known security logs ex: ip used, ip blacklisted, etc.
642
+ security_level=SecurityLevel.PRODUCTION, # production level security initiated
643
+ api_key=secret_key #set secret key you initialized
644
+ max_workers=4, # workers to initiate asynchronous tasks, more workers, more capabilities to process asynchronous prediction requests.
645
+ task_timeout=30,
646
+ max_retries=3 ) # retries after failure during prediction
647
+
648
+ async_manager.start(method='Transformer_included', bootstrap_token=None) # boothstrap token is optional for better security
649
+
650
+ texts = {'test_titles': test_titles, 'label_map': label_map, 'rules': example_rules, 'X': None, 'y':None, 'use_transformer': True} # all samples needed for advanced prediction method. (X and y are optional samples)
651
+
652
+ regular_predict = async_manager.predict(
653
+ texts=texts,
654
+ timeout=60,
655
+ retries=None,
656
+ api_key=secret_key) # advanced prediction method for asynchronous prediction.
657
+
658
+ # with retries: async_manager.predict(texts, timeout=60, retries=5, api_key=secret_key) # 5 times retry if failed
659
+
660
+ print('[==] Initiating advanced batch prediction')
661
+ predicted_output = async_manager.advanced_batch_prediction(test_titles, label_map, example_rules,
662
+ X=None, y=None, # provide your initialized X and y samples (Also Optional, can be set to None)
663
+ secret_key=secret_key, client_ip=None) # you can add client_ip to provide a robust authentication paired with secret_key
664
+ # for better and faster advanced prediction, consider using advanced batch prediction like in the above example
665
+
666
+ ```
667
+ [=] Note:
668
+ - Asynchronous prediction used Event loop that handles incoming request, There are conditions where event loop will not start and can't accet requests:
669
+ - CPU Above > 95% - Disk space is < 100 MB
670
+ - RAM above > 95%
671
+ - When event loop is not triggered, Asynchronous prediction can't be initiated and must be restarted/retried.
672
+
673
+ 7. Peer-to-Peer Probability coordination:
674
+ - Each peer is both server and client simultaneously for robustness and resilience during during P2P.
675
+ - To Make the Agent cooperate with other peers, consider using this setup:
676
+ - [=] for ensemble prediction from multiple peers, exchanging predicted label with each other, consider using this setup:
677
+ ```python
678
+
679
+ # step 3
680
+ from AbstractIntegratedModule import CohesiveAgentDeployment
681
+ from AbstractIntegratedModule import PipelinePredictionManager
682
+ import asyncio
683
+ import traceback
684
+
685
+ prediction_manager = PipelinePredictionManager(main_model, label_csv=<your_training_labels.txt>, target_title=<target_title>, label=<target_label>)
686
+
687
+ secondary_model = IntegratedPipeline(memory_name=memory_name,
688
+ use_async=True, agent_port=8080,
689
+ ssl_cert_file=cert_file, ssl_key_file=key_file) # provide cert_file path or key_file path (optional)
690
+ # secondary model of integrated pipeline is critical for ARM64 environment to prevent socket conflict during P2P with the first Integrated pipeline instance.
691
+ # make sure that the agent_port in secondary_model must be different from agent_port in first IntegratedPipeline instance you initialized.
692
+
693
+ print("=== SECURE PEER-TO-PEER CLUSTER ===")
694
+
695
+ # CohesiveAgentDeployment is deeply tied and coupled with AgentDistributedInference,
696
+ # if you already set an SSL cert and key, CohesiveAgentDeployment will use the SSL directly from AgentDistributedInference
697
+ # allowing secure socket to be used directly by CohesiveAgentDeployment
698
+
699
+ 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)
700
+ secondary_model.distribution.enable_ssl = False
701
+
702
+ # Agent 1 - Primary (Port 5555)
703
+ agent1 = CohesiveAgentDeployment(
704
+ pipeline=main_model, # main_model is your initialized integrated pipeline
705
+ memory_name="agent_primary", # any name you want for the agent.
706
+ filename=<filename>, # name of your .txt file that contains the CSV format and training labels
707
+ target_title=<title_name>,
708
+ label_name=<label_name>,
709
+ security_level="PRODUCTION", # production level security
710
+ enable_peers=True, # allow peer discovery
711
+ 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.
712
+ peer_discovery_port=5555, # peer port to start P2P
713
+ secret_key=secret_key, # your secret key
714
+ shared_auth_token=secret_key, # your previous initialized secret_key
715
+ predict_manager=prediction_manager, # your prediction manager
716
+ peer_config = <'your_peer_ip_lists.json'> # you need to create .json file that contains your peer IP and Port lists
717
+ consecutive_peer_config = <'your_second_fallback_peer_ip_lists.json'> # same for this one too, but for fallback.
718
+ )
719
+
720
+ # Agent 2 - Secondary (Port 5556)
721
+ agent2 = CohesiveAgentDeployment(
722
+ pipeline=secondary_model,
723
+ memory_name="agent_secondary",
724
+ filename=<filename>,
725
+ target_title=<title_name>,
726
+ label_name=<label_name>,
727
+ security_level="PRODUCTION",
728
+ enable_peers=True, # agent is allowed to find peers
729
+ trusted_networks=['127.0.0.1/32', '192.168.1.0/24'],
730
+ peer_discovery_port=5556,
731
+ secret_key=secret_key,
732
+ shared_auth_token=secret_key,
733
+ predict_manager=prediction_manager,
734
+ peer_config = <'your_peer_ip_lists.json'> # you need to create .json file that contains your peer IP and Port lists
735
+ consecutive_peer_config = <'your_second_fallback_peer_ip_lists.json'> # same for this one too, but for fallback.
736
+ )
737
+
738
+ # Note: CohesiveAgentDeployment contains ConsecutivePeerAgent that can start a server once ensemble prediction from peer is started
739
+ # be advised to stop the server too before shutdown-ing CohesiveAgentDeployment cluster
740
+
741
+ # example peer_Ip_lists_config.json (de-comment to use)
742
+ # {
743
+ # you must put "known_peers" in the config so python can identify the list of IPs and Ports
744
+ # "known_peers": [
745
+ # ["127.0.0.1", 5555], can be modified using real IP or local IP.
746
+ # ["127.0.0.1", 5556],
747
+ # more ip and port lists...
748
+ # ]
749
+ # }
750
+
751
+
752
+ try:
753
+ # Start both agents
754
+ print("\n🚀 Starting Agent 1...")
755
+ await agent1.start()
756
+ print("✅ Agent 1 started on port 5555")
757
+
758
+ print("\n🚀 Starting Agent 2...")
759
+ await agent2.start()
760
+ print("✅ Agent 2 started on port 5556")
761
+
762
+ # Give servers time to fully bind
763
+ await asyncio.sleep(2)
764
+
765
+ # Get API keys
766
+ api_key = agent1.get_api_key()
767
+ print(f"\n🔑 Using API Key: {api_key[:20]}...")
768
+
769
+ texts = {"test_titles": test_titles, "label_map": label_map, "rules": rules, 'X': None, "y":None, "use_transformer": True, "agent_id": agent_id} # (X and y are optional samples here too)
770
+
771
+ # texts dictionary must contain test_titles, label_map, and rules that you can assign,
772
+ # agent ID can be strings, int, or floats, recommendded to make it long for better security.
773
+ agent1.pipeline.use_transformer = False # set agent1 pipeline to not use transformer for efficient processing in ARM64 env.
774
+ agent2.pipeline.use_transformer = False
775
+
776
+ # Make prediction with peer ensemble
777
+ # Connection will be guaranteed successfull during discovery.
778
+ result = await agent1.multi_modal_peer_ensemble_prediction(
779
+ texts=texts,
780
+ api_key=api_key,
781
+ method='advanced',
782
+ disable_sync=True
783
+ ) # await using asyncio, multi_modal_peer_ensemble is already async by design (Inside ConsecutivePeerAgent), no need to put asyncio.run()
784
+
785
+ # must have agent2 peer ensemble function after agent1 peer ensemble prediction function,
786
+ # so agent1 can receive agent2 peer ensemble prediction request.
787
+ result2 = await agent2.multi_modal_peer_ensemble_prediction(
788
+ texts=texts,
789
+ api_key=api_key,
790
+ method='advanced',
791
+ disable_sync=True
792
+ )
793
+
794
+ print(f"\n📊 Ensemble Result for Agent 1:")
795
+ print(f" Prediction: {result.get('prediction', 'N/A')}")
796
+ print(f" Confidence: {result.get('confidence', 0):.2%}")
797
+
798
+ print(f"\n📊 Ensemble Result for Agent 2:")
799
+ print(f" Prediction: {result2.get('prediction', 'N/A')}")
800
+ print(f" Confidence: {result2.get('confidence', 0):.2%}")
801
+
802
+ # Keep running briefly
803
+ print("\n⏳ Cluster stable. Waiting 5 seconds before shutdown...") # 5 seconds before shutdown.
804
+
805
+ # stop ConsecutivePeerAgent servers inside CohesiveAgentDeployment.
806
+ agent1._peer_agent.stop_server() # ._peer_agent is ConsecutivePeerAgent
807
+ agent2._peer_agent.stop_server()
808
+
809
+ await asyncio.sleep(5)
810
+
811
+ except Exception as e:
812
+ print(f"\n❌ Error in cluster: {e}")
813
+ traceback.print_exc()
814
+
815
+ finally:
816
+ print("\n🛑 Shutting down cluster...")
817
+ await agent1.shutdown()
818
+ await agent2.shutdown()
819
+ print("✅ Cluster shutdown complete")
820
+
821
+ ```
822
+ [=] Important Note:
823
+ - This setup outputs the given predicted label of an input directly, making P2P more flexible and fast.
824
+ - 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:
825
+ - 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.
826
+
827
+ [=] You can download this setup here for a direct test: [P2PDirectTest.py](P2P_Setups/P2PDirectTest.py)
828
+
829
+ - [=] for probability coordination, locally, get peers data from database or via socket.
830
+ ```python
831
+ # step 4
832
+ dataset, _ = main_model.data_preparation(test_titles, label_map)
833
+ sequence_inputs = main_model.sequence_encoding(dataset)
834
+ X_raw_generation, y, n_classes, input_dim = main_model.mlp_training_features(example_rules, dataset)
835
+
836
+ main_model.initialize_fitting(dataset)
837
+ X_raw_features = main_model.tfidf.transform(X_raw_generation).toarray()
838
+ transformer_features = main_model.transformer_pooled_features(sequence_inputs)
839
+ X_features = np.concatenate([X_raw_features, transformer_features], axis=-1)
840
+
841
+ peer_probability_calibration = main_model.predict_proba(sequence_inputs, X_features, type='Hybrid', embedded=True) # peer-to-peer calibration is inside this function
842
+ ```
843
+ [~] 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:
844
+ ```python
845
+ from AbstractIntegratedModule import WeightedEnsemblePredictor
846
+ from AbstractIntegratedModule import Transformer
847
+
848
+ num_classes = len(label_map)
849
+ # if you haven't fit the Tfidf:
850
+ # main_model.initialize_fitting(dataset)
851
+
852
+ ensemble_method = WeightedEnsemblePredictor(main_model, memory_name) # consider using the same memory name used in your previous pipeline
853
+ 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.
854
+ main_model.model2 = transformer # overwrite previous transformer initialization
855
+
856
+ # main_model.distribution is AgentDistributedInference() class
857
+ # consider using ssl for secure peer to peer coordination
858
+ main_model.distribution.ssl_cert_file = <path_to_your_ssl_cert_file>
859
+ main_model.distribution.ssl_key_file = <path_to_your_ssl_key_file>
860
+
861
+ dataset, _ = main_model.data_preparation(titles, label_map)
862
+ sequence_input = main_model.sequence_encoding(dataset)
863
+ _, attn_weights = transformer.forward(sequence_input)
864
+
865
+ probs = ensemble_method.predict_ensemble(sequence_input, X_features, y, method='dynamic', embedded=True)
866
+ # 3 options for ensemble weighting method:
867
+ # 1. dynamic: allow flexible, efficient weighting from both transformer and MLP,
868
+ # 2. meta: for a much more in-depth weighting from both model,
869
+ # 3. calibration: allow calibrating probability for both model outputs based on both best weights assembling.
870
+
871
+ agreement = main_model.agreement
872
+
873
+ # start server to initiate socket for P2P listener
874
+ main_model.distribution.start_server()
875
+
876
+ # set connection timeout (Optional)
877
+ main_model.distribution.connection_timeout = 30 # 30 seconds before timeout
878
+ calibrated_probability = main_model._handle_distributed_connections(probs, attn_weights, sequence_input, agreement)
879
+
880
+ # if an Agent experience a failure on tasks, consider using this function to reduce peer trust for safer flexible coordination:
881
+ # main_model.distribution.report_failure(id(main_model), '<task_name>', reason='<unknown>') # you can add the task_name and reason
882
+ # main_model.distribution.print_network_status() # to show other peers info.
883
+ ```
884
+ [~] Note: this calibrated_probability is later used to calculate confidence and chosen output based on given label_map.
885
+ - Consider checking:
886
+ - [multi_agent_client.py](P2P_Setups/multi_agent_client.py) for a In-depth start for client testing.
887
+ - [multi_agent_server.py](P2P_Setups/multi_agent_server.py) for a In-depth start for server testing.
888
+ - If you get undefined NoneType Behavior when using .accept(), consider see [Troubleshooting](#Troubleshooting) Issue 7 for a Quick fix.
889
+
890
+ 6. Cross-Session availability:
891
+ - To use Cross-session avialability to transfer or import memory, consider using this setup:
892
+ - ```python
893
+ main_model._cross_session_availability() # cross session capability function
894
+ ```
895
+
896
+ 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.
897
+
898
+ ## [+] Troubleshooting
899
+ 1. Issue 1: "ModuleNotFoundError: No module named 'AbstractIntegratedModule'" When using the binary version of the library,
900
+ Solution:
901
+
902
+ - [=] Verify the binary file is in the correct location:
903
+ ```
904
+ ls -la AbstractIntegratedModule*.so # Linux
905
+ dir AbstractIntegratedModule.pyd # Windows
906
+ ```
907
+
908
+
909
+ - [=] Check Python path:
910
+ ```
911
+ python -c "import sys; print('\n'.join(sys.path))"
912
+ ```
913
+ - [~] Note: - Move binary to project root if not already there
914
+ - Ensure you're using Python 3.13 of the supported version.
915
+
916
+ 2. Issue 2: "ImportError: DLL load failed" when using binary version of the library (For Windows)
917
+ Solution:
918
+
919
+ - 1. Ensure AbstractIntegratedModule.pyd is in your project root
920
+ - 2. Install Visual C++ redistributables:
921
+ Download from: https://support.microsoft.com/en-us/help/2977003
922
+ - 3. Verify Python architecture (32-bit vs 64-bit) matches the .pyd file
923
+
924
+
925
+ 3. Issue 3: "Permission denied" when using binary version of the library (for Linux/Raspberry Pi)
926
+ [=] Solution:
927
+ - ```
928
+ # Make sure you have read permissions
929
+ chmod 644 AbstractIntegratedModule.cpython-39-*.so
930
+ # If in virtual environment, ensure it's activated
931
+ source venv/bin/activate
932
+ ```
933
+
934
+ 4. Issue 4: Missing Dependencies when using binary
935
+ [=] Solution:
936
+ - ```
937
+ # Reinstall all dependencies
938
+ pip install --upgrade pip setuptools wheel
939
+ pip install numpy pandas scikit-learn matplotlib scipy requests
940
+
941
+ # Verify installation
942
+ pip list
943
+ ```
944
+
945
+ 5. Issue 5: Virtual Environment Issues
946
+ [=] Solution:
947
+ - ```
948
+ # Deactivate current environment
949
+ deactivate
950
+
951
+ # Create a fresh virtual environment
952
+ python -m venv fresh_venv
953
+
954
+ # Activate it
955
+ source fresh_venv/bin/activate # Linux/Raspberry Pi
956
+ # or
957
+ fresh_venv\Scripts\activate # Windows
958
+
959
+ # Reinstall
960
+ pip install --upgrade pip
961
+ pip install numpy pandas scikit-learn matplotlib scipy
962
+ ```
963
+
964
+ 6. Issue 6: Raspberry Pi - "Bus error" or Performance Issues
965
+ Solution:
966
+ - [=] Ensure adequate swap space:
967
+ ```
968
+ free -h # Check current swap
969
+ sudo nano /etc/dphys-swapfile # Increase if needed
970
+ ```
971
+ - Close unnecessary applications before running
972
+ - Consider using a faster SD card (UHS-I or better)
973
+
974
+ 7. Issue 7: P2P Undefined Connection:
975
+ If you get this warning:
976
+ - ```
977
+ [❌] Failed to connect to <host>:<port>: Nonetype object has no attribute .accept()
978
+ ```
979
+ - [=] Solution:
980
+ - ```
981
+ # initiate socket first
982
+ main_model.distribution.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
983
+ main_model.distribution.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
984
+ main_model.distribution.socket.bind(('0.0.0.0', self.port)) # self.port could be changed with other ports
985
+ main_model.distribution.socket.listen(5) # listens for 5 seconds
986
+ ```
987
+ 8. Issue 8: Cannot compare using '<' with str and float data:
988
+ - This happens when one of the labels extracted from your CSV file has NaN value, consider replace NaN with actual labels.
989
+
990
+ 9. Issue 9: Failed authentication during asynchronous prediction:
991
+ - Solution: Ensure API_KEY is initialized inside PipelineAsyncManager like this:
992
+ - ```python
993
+ async_manager = PipelineAsyncManager(main_model,
994
+ main_prediction, # your previous initialized PipelinePredictionManager
995
+ config=security_config,
996
+ state_file=None, # state file is used to load known security logs ex: ip used, ip blacklisted, etc.
997
+ security_level=SecurityLevel.PRODUCTION, # production level security initiated
998
+ api_key=secret_key # set secret key you initialized <- THIS IS IMPORTANT
999
+ max_workers=4, # workers to initiate prediction, more workers, more capabilities to process prediction requests.
1000
+ task_timeout=30,
1001
+ max_retries=3 ) # retries after failure during prediction
1002
+ ```
1003
+ - And make sure you also initialized api_key in the predict function that requires api_key:
1004
+ ```
1005
+ async_manager.predict(...., ...., api_key=api_key, ...)
1006
+ ```
1007
+
1008
+ ## [=] Detailed process of Alpha-computing
1009
+
1010
+ <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" />
1011
+
1012
+ <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" />
1013
+ 🧠 What Alpha-Based Computation Actually Does
1014
+
1015
+ At its core, alpha (α) is a control parameter that blends two different information paths inside a given transformer:
1016
+ A_final = α · A_fixed + (1 − α) · A_learned.
1017
+ [~] Where:
1018
+ - A_fixed → stable, non-trainable (or minimally changing) attention
1019
+ - A_learned → dynamic, trainable attention (Q, K, V)
1020
+ - α ∈ [0, 1] → controls how much each path contributes
1021
+
1022
+ [~] Forward Pass -> Controlling Information Flow:
1023
+ During the forward pass, alpha determines what representation the model uses.
1024
+ If α is high (e.g., 0.8–1.0): Model relies mostly on stable attention
1025
+ → 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.
1026
+ So in forward propagation, alpha is essentially, “How much do I trust learned attention vs safe attention?”
1027
+
1028
+ [~] Backward Pass -> Controlling Gradient Flow:
1029
+ When gradients flow backward:
1030
+ ```
1031
+ - dA_final → splits into two paths
1032
+ - Mathematically:
1033
+ - dA_fixed = α · dA_final
1034
+ - dA_learned = (1 − α) · dA_final
1035
+ ```
1036
+
1037
+ [~] Simple Explanation:
1038
+ 1. If α (alpha) is high: → most gradient goes to fixed path → learned attention gets very little update → training is stable but slow
1039
+ 2. If α is low: → most gradient goes to learned attention → fast learning → but noisy / unstable
1040
+
1041
+ [=] Why This Matters for Training
1042
+ 1. Without alpha: attention starts random → gradients noisy → model stuck (~10% accuracy)
1043
+ 2. With alpha: early stage -> rely on stable structure → meaningful gradients
1044
+
1045
+
1046
+
1047
+ ## Main Components
1048
+ [=] 1. - Consider checking and run: [IntegratedPipeline_Flow.html](IntegratedPipeline_Flow.html) regarding each function of the whole components and deep-dive mechanism.
1049
+ 2. - consider checking [ARCHITECTURE.md](ARCHITECTURE.md) for more explanation about the main components.
1050
+
1051
+ [=] With 23 total architectures working together as a standalone library that is efficient and robust, Main components include:
1052
+
1053
+ 1. GeometricWeightShaping
1054
+ 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.
1055
+ ---
1056
+ 2. Activation
1057
+ Purpose: Provides standard neural network activation functions (ReLU, sigmoid, softmax) and their derivatives for backpropagation for MLP Class.
1058
+ ---
1059
+ 3. Loss
1060
+ Purpose: Implements categorical crossentropy loss and its gradient for training classification models for both MLP and The Transformer
1061
+ ---
1062
+ 4. Transformer
1063
+ 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.
1064
+ ---
1065
+ 5. Dense
1066
+ Purpose: A geometric-aware dense layer that adapts its weights based on input data geometry and handles variable input dimensions automatically.
1067
+ ---
1068
+ 6. SoftmaxOutput
1069
+ Purpose: A simple wrapper around softmax activation that stores the output and passes gradients through unchanged (since softmax + crossentropy gradient is handled elsewhere).
1070
+ ---
1071
+ 7. MLP
1072
+ 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.
1073
+ ---
1074
+ 8. WeightedEnsemblePredictor
1075
+ 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.
1076
+ ---
1077
+ 9. CrossSessionAutomation
1078
+ 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.
1079
+ ---
1080
+ 10. ExplainabilityModule
1081
+ 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.
1082
+ ---
1083
+ 11. ModelStorage
1084
+ Purpose: SQLite-based persistence for models, attention weights, node memories, and agent data. Handles serialization/deserialization of numpy arrays and model dictionaries.
1085
+ ---
1086
+ 12. AgentDistributedInference
1087
+ 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.
1088
+ ---
1089
+ 14. QueryNode
1090
+ Purpose: Manages trust relationships and identity verification between nodes. Evaluates node agreement, establishes connections, performs safety checks, and maintains the network of trusted peers.
1091
+ ---
1092
+ 14. AutoBatcherAutomation
1093
+ Purpose: Automatically batches incoming prediction requests to optimize throughput. Collects requests up to a maximum batch size or time window, then processes them together.
1094
+ ---
1095
+ 15. IntegratedPipeline
1096
+ Purpose: The main orchestration class that ties everything together - handles text encoding, model initialization, training, prediction, memory management, hybrid predictions, and distributed inference coordination.
1097
+ ---
1098
+ 16. PipelinePredictionManager
1099
+ Purpose: High-level prediction interface that loads labels from CSV, performs regular/advanced/hybrid predictions, displays results, and calculates entropy for uncertainty estimation.
1100
+ ---
1101
+ 17. ThreadedMessageQueue
1102
+ purpose: Handles message queue in thread for asynchronous message handling. (Queue based)
1103
+ ---
1104
+ 18. AsyncMessageQueue
1105
+ purpose: Handles incoming message from Asychronous peer request (Queue based)
1106
+ ---
1107
+ 19. CohesiveAgentDeployment
1108
+ purpose: Handles both synchronous prediction, and P2P Asynchronous prediction request, acts as a server and a listener simultaneously.
1109
+ ---
1110
+ 20. ConsecutivePeerAgent
1111
+ purpose: handles ensemble weighting from received output from peer, managed server and acts as a listener simultaneously.
1112
+ ---
1113
+ 21. LSTMCell
1114
+ purpose: handles LSTM Core equations In Numpy.
1115
+ ---
1116
+ 22. LSTMNetwork
1117
+ purpose: handling LSTM Feed-forward layer, Training and Samples handling.
1118
+ ---
1119
+ 23. LSTMEngine
1120
+ purpose: handles Proper LSTM Confidence and calibration layer.
1121
+
1122
+ ## Full Documentation Features
1123
+ - [Go to IntegratedPipeline-Specialized-AI-Agent-library](#IntegratedPipeline-Specialized-AI-Agent-library)
1124
+ - [Go to MANN Intro](#MANN-Intro)
1125
+ - [Go to Abstract Weight Encoder (AWE) Intro](#Abstract-Weight-Encoder-(AWE)-Intro)
1126
+ - [Go to LSTM And Transformer Into](#-lstm-and-transformer-intro)
1127
+ - [Go to Why IntegratedPipeline?](#Why-IntegratedPipeline?)
1128
+ - [Go to Requirements](#Requirements)
1129
+ - [Go to System-Specific-Notes](#System-Specific-Notes)
1130
+ - [Go to Quickstart with Docker](#Quickstart-with-Docker)
1131
+ - [Go to Performance in ARM64 Environment/Container](#Performance-in-ARM64-Environment/Container)
1132
+ - [Go to Step's for in-depth Usage](#Step's-for-in-depth-Usage)
1133
+ - [Go to Troubleshooting](#Troubleshooting)
1134
+ - [Go to Detailed process of Alpha-computing](#Detailed-process-of-Alpha-computing)
1135
+ - [Go to Main Components](#Components)
1136
+ - [Go to Source code](#Source-code-of-AbstractIntegratedModule)
1137
+ - Consider checking:
1138
+ - [ROADMAP.md](ROADMAP.md)
1139
+ - [Contributing.md](Contributing.md)
1140
+ - [changelog.md](changelog.md)
1141
+ - [requirements-For-Dev](dev_needs.txt) for contributors requirements.
1142
+ - [architecture_diagram.js](architecture_diagram.js).
1143
+
1144
+ ## License
1145
+ [=] LICENSE: - MIT (2026) || See [LICENSE](LICENSE) for more information.
1146
+
1147
+
1148
+
1149
+
1150
+
1151
+
1152
+
1153
+
@@ -0,0 +1,7 @@
1
+ AbstractIntegratedModule.cpython-310-aarch64-linux-gnu.so,sha256=NC1fwNZljeW8ed8V6cqfmINxnWpMUBEeeFoyzwr75Fk,40374368
2
+ AbstractOptimizedModules.cpython-310-aarch64-linux-gnu.so,sha256=fcE-Y2PQUxdrzm3VgXJpBD0U8AYclne7CtKclZf7DN0,724464
3
+ abstractintegratedmodule-0.7.2.dist-info/top_level.txt,sha256=66cDeqtV1QfIkcXTqRrnEJCSJOmdHMzhv6V26b_zs_Y,50
4
+ abstractintegratedmodule-0.7.2.dist-info/METADATA,sha256=EQd-Se9kPnYT4FqaPYhmiaKF0bLVkagA1Osyqce5glM,65115
5
+ abstractintegratedmodule-0.7.2.dist-info/WHEEL,sha256=dUrfsb6i0SW2aYZTp5rI3k1YrCNfasClQU6uMGkMpZQ,113
6
+ abstractintegratedmodule-0.7.2.dist-info/RECORD,,
7
+ abstractintegratedmodule-0.7.2.dist-info/licenses/LICENSE,sha256=1cfPMU4WKe4SankqWPTDGg54YMZCC51_8WcG9JZVU6k,1070
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-musllinux_1_2_aarch64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Micro-Novelty
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,2 @@
1
+ AbstractIntegratedModule
2
+ AbstractOptimizedModules