Integrated Pipeline with Specialized Non-LLM AI Agent Framework for ARM64 and Windows architecture
pip install AbstractIntegratedModule==1.2.6 Copy PIP instructions
The library also includes precompiled binaries for:
aarch64 manylinux (accepts version 2.17+) architecture, accepts python version 3.10, 3.11 only.
aarch64 musllinux (accepts version 1.2+) architecture, accepts python version 3.10, 3.11 only.
Windows 64 bit architecture (python 3.10, 3.11, 3.12, 3.13 only)
single tarball file for Users who want to test the library up to Python version 3.12 or 3.13+.
Library installation if you dont have aarch64 setup, you can download the correct wheel for your setup in this repository or by using pip:
Consider using this Optimization library by using:
pip install abstract-weights-core Note: This Optimization would help AbstractIntegratedModule with faster JSON parsing and much more flexible database handling handled efficiently using Rust programming language. Proven Capabilities:
Note: if you want to see the Changelog history of the library Older versions consider visiting this link:
Go to IntegratedPipeline-Specialized-AI-Agent-library
Go to Performance in ARM64 Environment/Container
[=] 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 Model Dictionary where it can finnaly recall its memory when input condition matched with memory.
[=] AWE is a specialized custom weight shaping or encoding method Specifically designed for MLP Architecture that excels in Quantization-Aware-Training method in MLP dense Layers, using eigenvalue and spectral methods as base equations to calculate covariance inside a given input data, and calibrate 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 especially during Quantization-Aware-Training.
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.
B. Transformer: Transformers are the modern standard for AI, introduced in 2017 with the famous "Attention Is All You Need" paper.
[~] For a much In-Depth Explanation You can visit This repository to learn more about AWE and its performance results:
[~] IntegratedPipeline is a great choice for a sophisticated Non-LLM AI Model Program for The Main Orchestrator of a Distributed MANN-Type Model Agent Working in Edge-device/Consumer-Based machine Where LLM isn't a great fit for Messy, Unpredictable environments. while still run efficiently on High-end Embedded systems in single-instance or as a distributed network during multi Agent cooperation.
different from LLM that is static and cannot improve beyond its given training condition, AI Models 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 as a Memory, allowing it to recall its memory during processing and find matching known prediction given if input matched with the stored input inside the database. User can control this behavior such as:
memory_name = 'agent1_memory' memory_loaded = load_memory(memory_name) if memory_is_loaded: stop_training() else: continue_training() Benefit of this approach:
Allow flexible Training and model task allocation better:
Deterministic behavior for Pragmatic Continual learning behavior for MANN type Models.
agent_1 with memory_name 'A' -> task A (Classification task) change memory_name to 'B" agent_1 with memory_name 'B" -> task B (Regression task) regression task requires slight modification to match the required samples and argument (Easy modification) Example 2: Worflow (Multiple models):
Tradeoff: This approach is deterministic and Memory modification or removal requires Manual audit directly to the Model's SQlite database (Named activity_log.db).
Robust Specialized MLP, Transformer and LSTM Architecture with ensemble weighting architecture:
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 allows MLP performance to improve Even during Quantization-Aware-Training, 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.
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.
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.
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.
Specialized SNN helps for sensor based motion prediction, and Neuromorphic computing.
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.
flexible and secure Peer-to-Peer Coordination (Multi-Agent):
[=] With its Specialized Multi-Layer-Perceptron (using AWE Encoder) and Optimized Transformer module with optimized Embedding, IntegratedPipeline can directly improve overtime, including in ambiguous data, using Weighted Confidence assembling from both specialized MLP and Transformer for better reliability during training and prediction over Unpredictable environments, such as:
[1.] User data's : User data is often messy and ambiguous, Specialized MLP with AWE will do the job for shaping and calibrating the necessary Weight to complement for the Ambiguous pattern, AWE MLP is proven to help in Quantization-Aware-Training in MLP that helps reduce Memory usage -> 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.
[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.
[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.
[~] To run and execute IntegratedPipeline, Requirement's include Or see Requirements:
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:
(Optional) Libraries needed (For using Compiled binary, not python wheels):
(Optional) Install AbstractIntegratedModule Compiled binaries from release section:
See Docker_installation_Section for an in-depth explanation, or Quick_Docker_start for a quick start.
docker run -it -v $(pwd):/app/data integrated-pipeline:latest python /app/data/main.py To use a .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. .env is used for environment setup in entrypoint.sh, this file must be in the same folder with Dockerfile and entrypoint.sh after its downloaded. Build Image:
git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework Download:
# remove .txt extension mv Dockerfile.txt Dockerfile mv env.txt .env mv dockerignore.txt .dockerignore Navigate to the folder: Use the cd command to enter the directory containing the Dockerfile and entrypoint.sh file.
sudo docker build -t integrated-agent. Download library dependencies for binaries usage:
Install AbstractIntegratedModule via PIP or Compiled binaries:
from AbstractIntegratedModule import IntegratedPipeline, PipelinePredictionManager model = IntegratedPipeline('agent_memory') print("✓ IntegratedPipeline initialized successfully!") Run script:
# Mount your local directory and run a script docker run -it -v $(pwd)/data:/app/data integrated-agent:latest python main.py # main.py could be replaced For Single Agent and Multi-Agent P2P: [=] Single agent:
# Build image docker build -t integrated-agent:latest . # Run single agent docker run -it -v $(pwd)/data:/app/data integrated-agent:latest python [=] Multi agent P2P (Consider docker-compose) :
cd /path/to/your/folder run this command to run docker-compose.yml: # Start multiple agents docker-compose up -d # View logs docker-compose logs -f # Stop all agents docker-compose down Performance in linux ARM64 Docker Environment/Container A. [=] [OLD DATA] Computational performance results during Training with Transformer included in regular classification tasks (Not regression).
== TIME == | CPU % | RAM / RAM LIMIT || 14:50:08.762 0.00% 25.52MiB / 3.71GiB 14:50:10.339 5.56% 25.52MiB / 3.71GiB 14:50:12.428 0.17% 25.52MiB / 3.71GiB 14:50:15.835 103.60% 38.8MiB / 3.71GiB 14:50:17.844 438.11% 60.15MiB / 3.71GiB 14:50:19.896 419.36% 68.32MiB / 3.71GiB 14:50:22.022 434.15% 73.2MiB / 3.71GiB 14:50:23.969 436.47% 78.18MiB / 3.71GiB 14:50:25.966 435.85% 80.22MiB / 3.71GiB 14:50:28.018 430.47% 92.12MiB / 3.71GiB 14:50:30.029 450.55% 99.5MiB / 3.71GiB 14:50:32.065 438.06% 105.4MiB / 3.71GiB 14:50:34.100 469.52% 115.2MiB / 3.71GiB 14:50:36.109 449.89% 116.8MiB / 3.71GiB 14:50:38.123 423.56% 119MiB / 3.71GiB [=] Note: To read the full logs (For included Transformer performance): performance_log_with_TF [=] Explanation: Average CPU Usage = 420% - 430% , Sustained roughlt 4.20 - 4.30 CPU Cores Meaning = - Compute-Intensive workload - reduced guaranteed of experiencing deadlocks, thread starvation, and major stalls - numerical backend is parallelizing efficiently Average RAM Usage = 180 - 195 Mib, Roughly 4.5 - 5% usage of available RAM Meaning = - Very efficient RAM Usage - Repeated 269 MiB suggests allocator settled, ndarray pools stabilized, workload reached steady state - gradual, safe and steady batch accumulation, reduced possibility of leak explosion. B. [=] Advanced Prediction without Transformer, Only Specialized MLP + LSTM using AWE during Training.
== TIME == | CPU % | RAM \ RAM LIMIT | 10:01:37.456 100.44% 269.8MiB / 3.71GiB # initial round 1 training started 10:01:38.686 101.93% 279.8MiB / 3.71GiB 10:01:40.694 101.94% 293.2MiB / 3.71GiB 10:01:42.703 99.90% 302.9MiB / 3.71GiB 10:01:44.712 99.34% 319.8MiB / 3.71GiB 10:01:46.721 100.15% 319.7MiB / 3.71GiB 10:01:48.727 101.91% 319.7MiB / 3.71GiB 10:01:50.734 100.86% 319.7MiB / 3.71GiB 10:01:52.742 136.43% 322.9MiB / 3.71GiB 10:01:54.751 101.91% 324.9MiB / 3.71GiB 10:01:56.758 100.29% 324.9MiB / 3.71GiB 10:01:58.769 102.42% 327.1MiB / 3.71GiB 10:02:00.775 0.00% 329.6MiB / 3.71GiB # First Training and prediction round 1 finished 10:02:02.788 19.55% 330.1MiB / 3.71GiB # round 2 training 10:02:04.798 134.23% 332.2MiB / 3.71GiB 10:02:06.803 108.80% 332.2MiB / 3.71GiB 10:02:08.811 107.85% 332.2MiB / 3.71GiB 10:02:10.857 104.43% 332.2MiB / 3.71GiB 10:02:12.854 101.14% 332.2MiB / 3.71GiB 10:02:14.858 0.00% 332.3MiB / 3.71GiB 10:02:16.873 98.84% 333.8MiB / 3.71GiB 10:02:18.869 0.00% 132.7MiB / 3.71GiB # container stopped and round 2 finished [=] Note: See full performance log in here: performance_log_only_MLP [=] Explanation: Average CPU Usage = 85-90% Used, sustained roughly 1 CPU Core saturated on average Meaning: - Very efficient computation - Much lighter CPU Usage than Transformer. - Stable and less parallelizing behavior (Efficient computation) - 4.7x lower CPU usage than transformer included - Average RAM usage = 314 MiB / 3.71 GiB, Roughly 8.5% usage of available RAM. Meaning: - Slightly larger MiB used than Transformer. - Model allocation growth is stable, - training buffers stable - temporary ndarray growth. Both performance Overview _______________________________________ - Note: - 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, MLP And LSTM stays the same and still fully optimized. Source code of AbstractIntegratedModule Note: The source code is provided in the repository. [=] Full Monolithic extensively-documented source code (12K+ Lines): AbstractIntegratedModule.py [=] Separated Modules of AbstractIntegratedModule With proper Documentation: separated_module [=] up-to-date Source code: AbstractIntegratedModule.pyx and 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. lib.rs that contains Rust optimization for Models weight handling. [~] Note: The source code is open and Free to anyone who: Use it: Run the software for any personal, academic, or commercial purpose. Modify it: Change the source code to fit their needs. Distribute it: Share the original or modified code with others. Commercialize it: Package, brand, and sell the software for profit. [=] Step's for library in-depth Usage Download via PIP:
# Clone immediately for Windows and x86_64 only without prerequisites git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework Install the library via pip:
# prerequisites (for Raspberry pi OS Only) # Update system sudo apt-get update sudo apt-get upgrade -y # Install Python 3.x and development tools # Version 3.x means you can install python 3.10 to 3.13 only, # choose one version specified for your needs (3.10 or 3.11 or 3.12 ...). sudo apt-get install python3.x python3.x-dev python3.x-venv -y # Install additional build tools sudo apt-get install build-essential libatlas-base-dev libjasper-dev -y # Clone immediately for Windows and x86_64 only without prerequisites git clone https://github.com/Micro-Novelty/IntegratedPipeline-Continous-Learning-AI-Agent-library-framework.git cd IntegratedPipeline-Continous-Learning-AI-Agent-library-framework Install System Dependencies (for x86_64 installation):
# Ubuntu/Debian # example with Version 3.10: sudo apt-get update sudo apt-get install python3.10 python3.10-dev python3.10-venv # CentOS/RHEL sudo yum install python310 python310-devel # Fedora sudo dnf install python3.10 python3.10-devel Create a virtual environment:
# Create virtual environment (windows) # example with python 3.10 python -m venv venv # Activate virtual environment venv\Scripts\activate # Create virtual environment (x86_64) (ARM64 / raspberry pi) python3.10 -m venv venv # Activate virtual environment source venv/bin/activate Verify Installation:
python -c "from AbstractIntegratedModule import IntegratedPipeline; print('✓ Installation successful!')" Run main.py for quick test of successful imports:
# run this for quick import test. python main.py Create CSV file that contains training labels and titles (Optional for training using texts):
window_title,label "Thesis.docx",focused_work "Microsoft Excel",work "YouTube -> Google Chrome",distracted "Slack",communication "VSCode", focused_work "netflix.com -> Google Chrome",break "Outlook",work "System Settings",system designing "GitHub",creating-and-editing-repo "README.md -> VS Code",focused_work "Amazon.com -> Chrome",personal-work Note = window_title is target_title and label is target_label, check step below to use it. NOTE: There must be no space between ',' and words to prevent missing labels during label_map extraction. A. Use IntegratedPipeline as in this example:
# if you want to use the IntegratedPipeline Transformer only, you can use this setup: # 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. vocab_size = main_model.vocab_size# . model_transformer = Transformer( vocab_size=vocab_size d_model=main_model.transformer_d_model, n_heads=pipeline.transformer_heads, num_classes=num_classes n_features=None, # set to len(feature_cols) for regression. task='classification' ) # or just get your old Transformer: # model_transformer = main_model.model2 sequence_inputs = main_model._features_to_sequence(X, d_model=pipeline.transformer_d_model) # Converts X samples into sequences that the Transformer can recognize. # embedded=True will ensure that Transformer forward method will put a correct mask for the samples. # mode='dynamic_backward' helps Transformer to gains better accuracy for Complex vocabularies. model_transformer.train(sequence_inputs, y, epochs=100, mode='dynamic_backward', lr=0.1, embedded=True, batch_size=2) # save Transformer weights tf = model_transformer json_data = { 'token_embedding': tf.token_embedding, 'pos_embedding': tf.pos_embedding, 'W_q': tf.W_q, 'W_k': tf.W_k, 'W_v': tf.W_v, 'W_q_fixed': tf.W_q_fixed, 'W_k_fixed': tf.W_k_fixed, 'W_v_fixed': tf.W_v_fixed, 'W_o': tf.W_o, 'ffn1': tf.ffn1, 'ffn2': tf.ffn2, 'ln1_scale': tf.ln1_scale, 'ln1_shift': tf.ln1_shift, 'ln2_scale': tf.ln2_scale, 'ln2_shift': tf.ln2_shift, 'output': tf.output, 'output_bias': tf.output_bias } serializable_data = {key: val.tolist() for key, val in json_data.items()} with open("transformer_weights.json", "w") as file: json.dump(serializable_data, file, indent=4) # indent adds readable formatting #load Transformer weights # in here transformer_model a new IntegratedPipeline Transformer instance: with open('transformer_weights.json', 'r') as file: loaded_data = json.load(file) transformer_model.W_q = loaded_data['token_embedding'] ... # and so on until output_bias. Note: script setup can be downloaded here: transformer_usage C. Use kNN-Augmented Transformer: 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:
# Initialize kNN Transformer: knn_tf = sec_main_prediction.initialize_knn_transformer( vocab_size=1, task=' ', num_classes=num_classes, d_model=32, n_heads=4, n_features=len(feature_cols), # pass len(feature_cols) if your task is regression, set to None if classification memory_capacity=10000, memory_k=5, memory_metric='euclidian') # NOTE: - vocab_size and num_classes is a MUST, meaning you have to pass the number of classes of your samples, and vocab_size of your data (can be set to vocab_size=1 for regression task) - memory_capacity = the amount of memory for the kNN to hold - memory_k = "K" is the central hyperparameter that defines the number of nearby training data points the algorithm looks at to make a prediction, more memory_k => more nearby training points the model can look up. # knn_forward_inference() lives inside PipelinePredictionManager, so you need to call this class to initiate the knn_forward_inference() function. losses, accs, _ = main_prediction.knn_forward_inference(X, y, label_map=None, # Label map can be safely set to None during Training phase. memory_metric='euclidean', training=True, batch_size=2, train_mode='dynamic_backward', lr=0.1) # for Training kNN Transformer only transformer_probs, attn_weights, prediction = main_prediction.knn_forward_inference(X, y, label_map=label_map, # Label map can be inserted in here, or you Can set this to None, if set to None this function will only returns Transformer prob and attn_weights. memory_metric='euclidean', training=False) # for returning kNN Transformer probabilities and attention weights only. # 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. # - 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. # - 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. # ==== SAVING MEMORY BLOCK ===== 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. 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. # Get binary blob to save target memory: blob = main_model.model2.target_memory_to_bytes() main_model.storage.save_target_memory_row(memory_name, blob) # Save target memory row for kNN Transformer usage later # === LOADING MEMORY BLOCK === 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. 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. main_model.storage.load_target_memory_row(memory_name) # load target memory row for kNN Transformer # .... # your own custom kNN prediction block. To use IntegratedPipeline prediction without Transformer, Only Specialized MLP: Note: IntegratedPipeline without Transformer is'nt recommended due to it being weak at certain contextual prediction's, excel's at classification task's.
prediction_result = main_prediction.advanced_prediction_method( [t[0] for t in test_titles], # titles is enough for MLP Classification. label_map, example_rules, show_proba=True ) Asynchronous prediction:
# Step 2 from AbstractIntegratedModule import PipelineAsyncManager from AbstractIntegratedModule import SecurityConfig from AbstractIntegratedModule import SecurityLevel # NOTE: # All the three Models (MLP, Transformer, LSTM MUST be Initialized, Trained before initiating Asynchronous Prediction, the Initialization workflow can be seen above.) # Replace the regular advanced_prediction_method() with this asynchronous setups: print(" = TESTING ASYNCHRONOUS PREDICTION MANAGER = ") # Set discovery secret (in production, use environment variable) secret_key = 'my-ultra-safe-secret-key-for-authentication' # you can customize this key # max_text_length: the maximum length of the text you want to allow for prediction, in this case we use 10000 (changeable). # max_queue_size: the maximum number of requests you want to allow in the queue, in this case we use 100 (changeable). # rate_limit_requests: the maximum number of requests you want to allow per minute, in this case we use 60 (changeable). # require_api_key: whether to require an API key for prediction or not, in this case we use True for safety (changeable). security_config = SecurityConfig( max_text_length=10000, # can be extended max_queue_size=100, # can be extended rate_limit_requests=60, # 60 per minute require_api_key=True, # max_pending_tasks=50, request_timeout=60.0, # Start with no IP restrictions, you can add allowed IPs for asynchronous prediction externally, boothstrap_auth for better security allowed_ips=[], blocklisted_ips=[], require_bootstrap_auth = False # true for better security (Not recommended, cause less flexibility) ) # NOTE: # Asynchronous Prediction Block: This is where you set up the PipelineAsyncManager for asynchronous predictions, this will allow you to make predictions without blocking the main thread and allows you to handle multiple requests concurrently. # pass the PipelinePredictionManager of yours (main_prediction in this case), and the IntegratedPipeline of yours (here its main_model), # the SecurityConfig as config, and the api_key as api_key, and the max_workers of 4, more worker, means more concurrent requests (changeable), # the task_timeout as 30 (changeable), and the max_retries as 3 (changeable). async_manager = PipelineAsyncManager(main_model, main_prediction, # your previous initialized PipelinePredictionManager config=security_config, state_file=None, # state file is used to load known security logs ex: ip used, ip blacklisted, etc. security_level=SecurityLevel.PRODUCTION, # production level security initiated api_key=secret_key #set secret key you initialized max_workers=4, # workers to initiate asynchronous tasks, more workers, lower memory usage. task_timeout=30, max_retries=3) # retries after failure during prediction async_manager.start(method='Transformer_included', bootstrap_token=None) # boothstrap token is optional for better security # NOTE: # Asynchronous Prediction Example: This is where you make an asynchronous prediction using the PipelineAsyncManager, this will allow you to make predictions without blocking the main thread and allows you to handle multiple requests concurrently. # payloads: this is the dictionary of payloads you want to send to the PipelineAsyncManager for prediction, in this case we use the test_titles, label_map, rules, and use_transformer as True (changeable). # pass X and y samples for prediction, in this case we use the X and y we created earlier (Not changeable and X and y samples are must be passed here). # api_key can be passed or set to None, if you set require_api_key to True in the SecurityConfig, then you must pass the api_key here. # chunk_size: this is the chunk size you want to use for the prediction, in this case we use 1000 because our sample is large, and we require larger chunks to save memory and prevent memory overhead (changeable). # client_ip (optional): this is the client IP you want to use for the prediction, in this case we set it to None (changeable, client_ip is a string, not listsor dicts). # max_predictions: this is the maximum number of predictions you want to allow for the model to predict on each samples you have provided, in this case we use 3 max predictions, after that the model will abort all predictions (changeable). # stop_on_error: this is the boolean flag you want to use for the prediction, in this case we set it to False, meaning if its False, when the model encounters an error during prediction, it will continue to predict the next sample, set to True if you want the model to stop on the first error (changeable). # overall_timeout: this is the overall timeout you want to use for the prediction, in this case we set it to 20000 seconds, meaning if the model takes longer than 20000 seconds to predict, it will abort the prediction (changeable). # IMPORTANT NOTE: the async_predict variable will return all the prediction results, prediction success, failures, so you can directly see how the model predicts each batch of the given sample. # test_titles and rules are needed for asynchonous prediction. payloads = {'test_titles': test_titles, 'label_map': label_map, 'rules': rules, 'use_transformer': True} async_predict = wrapper.prediction_method(payloads, X, y_samples=y, chunk_size=1000, max_predictions=3, task="auto", timeout=1000, api_key=api_key, client_ip=None, overall_timeout=20000, stop_on_error=False) print(f'[=] Results: {async_predict}') # NOTE: This function below MUST require test_titles or titles, label_map and example rules: print('[==] Initiating advanced batch prediction') predicted_output = async_manager.advanced_batch_prediction(test_titles, label_map, example_rules, X=None, y=None, # provide your initialized X and y samples (Also Optional, can be set to None) secret_key=secret_key, client_ip=None) # you can add client_ip to provide a robust authentication paired with secret_key # for better and faster advanced prediction when using titles and rules, consider using advanced batch prediction like in the above example [=] Note:
# step 3 # NOTE: # All three Models (MLP, Transformer and LSTM) must be Initialized and Trained first before initiating P2P. from AbstractIntegratedModule import CohesiveAgentDeployment from AbstractIntegratedModule import PipelinePredictionManager import asyncio import traceback prediction_manager = PipelinePredictionManager(main_model, label_csv= , target_title= , label= ) secondary_model = IntegratedPipeline(memory_name=memory_name, use_async=True, agent_port=8080, ssl_cert_file=cert_file, ssl_key_file=key_file) # provide cert_file path or key_file path (optional) # secondary model of integrated pipeline is critical for ARM64 environment to prevent socket conflict during P2P with the first Integrated pipeline instance. # make sure that the agent_port in secondary_model must be different from agent_port in first IntegratedPipeline instance you initialized to prevent address already in use error [Errno 48]. print("=== SECURE PEER-TO-PEER CLUSTER ===") # CohesiveAgentDeployment is deeply tied and coupled with AgentDistributedInference, # if you already set an SSL cert and key, CohesiveAgentDeployment will use the SSL directly from AgentDistributedInference # allowing secure socket to be used directly by CohesiveAgentDeployment # example task (change to regression if yours are regression task) # function must be async to use the await syntax (Non-blocking) async def p2p_tasks(task='classification') 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) secondary_model.distribution.enable_ssl = False # NOTE: # shared_auth_token : the secret_key you have alread made # trusted networks is a list (must be list), that contain allowed IPs for networking. # pass IntegratedPipeline (here its main_model), and PipelinePredictionManager (here its main_prediction). # agent memory_name can be anything you want. # pass target_titles and label_name (matches the target_title you used during loading your label_map inside your .txt file.) # enable_peers : allow an agent to communicate with other agent. # security_level: # PRODUCTION: secure for P2P networking, # DEVELOPMENT: not-secure for P2P networking (use this for testing) # Agent 1 - Primary (Port 5555) agent1 = CohesiveAgentDeployment( pipeline=main_model, # main_model is your initialized integrated pipeline memory_name="agent_primary", # any name you want for the agent. filename= , # name of your .txt file that contains the CSV format and training labels target_title= , label_name= , security_level="PRODUCTION", # production level security enable_peers=True, # allow peer discovery 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. peer_discovery_port=5555, # peer port to start P2P shared_auth_token=secret_key, # your previous initialized secret_key predict_manager=prediction_manager, # your prediction manager peer_config = # you need to create .json file that contains your peer IP and Port lists consecutive_peer_config = # same for this one too, but for fallback. ) # Agent 2 - Secondary (Port 5556) agent2 = CohesiveAgentDeployment( pipeline=secondary_model, memory_name="agent_secondary", filename= , target_title= , label_name= , security_level="PRODUCTION", enable_peers=True, # agent is allowed to find peers trusted_networks=['127.0.0.1/32', '192.168.1.0/24'], peer_discovery_port=5556, shared_auth_token=secret_key, predict_manager=prediction_manager, peer_config = # you need to create .json file that contains your peer IP and Port lists consecutive_peer_config = # same for this one too, but for fallback. ) # Note: CohesiveAgentDeployment contains ConsecutivePeerAgent that can start a server once ensemble prediction from peer is started # be advised to stop the server too before shutdown-ing CohesiveAgentDeployment cluster # example peer_Ip_lists_config.json (de-comment to use) # { # you must put "known_peers" in the config so python can identify the list of IPs and Ports # "known_peers": [ # ["127.0.0.1", 5555], can be modified using real IP or local IP. # ["127.0.0.1", 5556], # more ip and port lists... # ] # } try: # Start both agents print("\n🚀 Starting Agent 1...") await agent1.start() print("✅ Agent 1 started on port 5555") print("\n🚀 Starting Agent 2...") await agent2.start() print("✅ Agent 2 started on port 5556") # Give servers time to fully bind await asyncio.sleep(2) # Get API keys api_key = agent1.get_api_key() print(f"\n🔑 Using API Key: {api_key[:20]}...") texts = {"test_titles": test_titles, "label_map": label_map, "rules": rules, # test_titles and rules are Optional samples, can be set to None. 'X': None, "y":None, "use_transformer": True, "agent_id": agent_id} # (X and y are optional samples here too) # 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. # texts dictionary must contain test_titles, label_map, and rules that you can assign, # agent ID can be strings, int, or floats, recommendded to make it long for better security. agent1.pipeline.use_transformer = False # set agent1 pipeline to not use transformer for efficient processing in ARM64 env. agent2.pipeline.use_transformer = False # Make prediction with peer ensemble # Connection will be guaranteed successfull during discovery. result = await agent1.multi_modal_peer_ensemble_prediction( texts=texts, api_key=api_key, method='advanced', disable_sync=True ) # await using asyncio, multi_modal_peer_ensemble is already async by design (Inside ConsecutivePeerAgent), no need to put asyncio.run() # must have agent2 peer ensemble function after agent1 peer ensemble prediction function, # so agent1 can receive agent2 peer ensemble prediction request. result2 = await agent2.multi_modal_peer_ensemble_prediction( texts=texts, api_key=api_key, method='advanced', disable_sync=True ) print(f"\n📊 Ensemble Result for Agent 1:") print(f" Prediction: {result.get('prediction', 'N/A')}") print(f" Confidence: {result.get('confidence', 0):.2%}") print(f"\n📊 Ensemble Result for Agent 2:") print(f" Prediction: {result2.get('prediction', 'N/A')}") print(f" Confidence: {result2.get('confidence', 0):.2%}") # Keep running briefly print("\n⏳ Cluster stable. Waiting 5 seconds before shutdown...") # 5 seconds before shutdown. # stop ConsecutivePeerAgent servers inside CohesiveAgentDeployment. agent1._peer_agent.stop_server() # ._peer_agent is ConsecutivePeerAgent agent2._peer_agent.stop_server() await asyncio.sleep(5) except Exception as e: print(f"\n❌ Error in cluster: {e}") traceback.print_exc() finally: print("\n🛑 Shutting down cluster...") await agent1.shutdown() await agent2.shutdown() print("✅ Cluster shutdown complete") # Initiate tasks: if __name__ == '__main__': # match to your own task (classification or regression based on your samples) p2p_tasks(task='classification') [=] Important Note: - This setup outputs the given predicted label of an input directly, making P2P more flexible and fast. - 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: - 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.
[=] You can download this setup here for a direct test: P2PDirectTest.py
# step 4 # X_generated is an X samples generated from using dataset converted into Vectors. dataset, X_generated = main_model.data_preparation(test_titles, label_map) # sequence inputs for Transformer sequence_inputs = main_model.sequence_encoding(dataset) # NOTE: # if you have X samples: # sequence_inputs = main_model._features_to_sequence(X) # ignore the dataset version. # type='Hybrid' = Transformer probabilities will be present for ensemble weighting with MLp probabilities # type='others' = Transformer probabilities will be ignored, and ensemble weighting will not be initiated as MLP probs will be used. peer_probability_calibration = main_model.predict_proba(sequence_inputs, X, type='Hybrid', embedded=True) # peer-to-peer calibration is inside this function [~] 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:
SNN Prediction Usage (Separated from IntegratedPipeline):
main_model._cross_session_availability() # cross session capability function 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. [+] Troubleshooting Issue 1: "ModuleNotFoundError: No module named 'AbstractIntegratedModule'" When using the binary version of the library, Solution:
ls -la AbstractIntegratedModule*.so # Linux dir AbstractIntegratedModule.pyd # Windows [=] Check Python path: python -c "import sys; print('\n'.join(sys.path))" [~] Note: - Move binary to project root if not already there Ensure you're using Python 3.13 of the supported version. Issue 2: "ImportError: DLL load failed" when using binary version of the library (For Windows) Solution:
Issue 3: "Permission denied" when using binary version of the library (for Linux/Raspberry Pi) [=] Solution:
# Make sure you have read permissions chmod 644 AbstractIntegratedModule.cpython-39-*.so # If in virtual environment, ensure it's activated source venv/bin/activate Issue 4: Missing Dependencies when using binary [=] Solution:
# Reinstall all dependencies pip install --upgrade pip setuptools wheel pip install numpy pandas scikit-learn matplotlib scipy requests # Verify installation pip list Issue 5: Virtual Environment Issues [=] Solution:
# Deactivate current environment deactivate # Create a fresh virtual environment python -m venv fresh_venv # Activate it source fresh_venv/bin/activate # Linux/Raspberry Pi # or fresh_venv\Scripts\activate # Windows # Reinstall pip install --upgrade pip pip install numpy pandas scikit-learn matplotlib scipy Issue 6: Raspberry Pi - "Bus error" or Performance Issues Solution:
free -h # Check current swap sudo nano /etc/dphys-swapfile # Increase if needed Close unnecessary applications before running Consider using a faster SD card (UHS-I or better) Issue 7: P2P Undefined Connection: If you get this warning:
[❌] Failed to connect to : : Nonetype object has no attribute .accept() [=] Solution: # initiate socket first main_model.distribution.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) main_model.distribution.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) main_model.distribution.socket.bind(('0.0.0.0', self.port)) # self.port could be changed with other ports main_model.distribution.socket.listen(5) # listens for 5 seconds Issue 8: Cannot compare using '<' with str and float data:
Issue 9: Failed authentication during asynchronous prediction:
async_manager = PipelineAsyncManager(main_model, main_prediction, # your previous initialized PipelinePredictionManager config=security_config, state_file=None, # state file is used to load known security logs ex: ip used, ip blacklisted, etc. security_level=SecurityLevel.PRODUCTION, # production level security initiated api_key=secret_key # set secret key you initialized <- THIS IS IMPORTANT max_workers=4, # workers to initiate prediction, more workers, more capabilities to process prediction requests. task_timeout=30, max_retries=3 ) # retries after failure during prediction And make sure you also initialized api_key in the predict function that requires api_key: async_manager.predict(...., ...., api_key=api_key, ...) [=] Detailed process of Alpha-computing 🧠 What Alpha-Based Computation Actually Does At its core, alpha (α) is a control parameter that blends two different information paths inside a given transformer: A_final = α · A_fixed + (1 − α) · A_learned. [~] Where:
[~] Forward Pass -> Controlling Information Flow: During the forward pass, alpha determines what representation the model uses. If α is high (e.g., 0.8–1.0): Model relies mostly on stable attention → 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. So in forward propagation, alpha is essentially, “How much do I trust learned attention vs safe attention?”
[~] Backward Pass -> Controlling Gradient Flow: When gradients flow backward:
- dA_final → splits into two paths - Mathematically: - dA_fixed = α · dA_final - dA_learned = (1 − α) · dA_final [~] Simple Explanation:
[=] 1. - Consider checking and run: IntegratedPipeline_Flow.html regarding each function of the whole components and deep-dive mechanism. 2. - consider checking ARCHITECTURE.md for more explanation about the main components.
[=] With 23 total architectures working together as a standalone library that is efficient and robust, Main components include:
[=] LICENSE: - MIT (2026) || See LICENSE for more information.
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Enable javascript to be able to filter the list of wheel files.




