> Agents can also search and read this documentation through its [MCP server](https://docs.nesa.ai/nesa/~gitbook/mcp).

# Introduction to Nesa

The Layer-1 for trusted AI on-chain.

**Nesa** means “miracle”—a tribute to the golden age of AI we are entering. As Arthur C. Clarke famously wrote, “*Any sufficiently advanced technology is indistinguishable from magic*.” Trusted AI should feel the same: powerful, invisible, and reliable by design.

But today's AI infrastructure is none of those things. Centralized providers dominate the landscape, offering AI inference as black-box APIs with no privacy, no verifiability, and no user control. These systems are fragile, opaque, and exclusionary—especially for enterprises with sensitive data or compliance-critical use cases.

***

## What Is Nesa?

**Nesa is a privacy-preserving, verifiable, decentralized AI execution layer.**

It allows users to run powerful AI models—language, vision, and beyond—across a globally distributed network of compute nodes, without trusting any single party. The models remain confidential, the data remains private, and the results are verifiable.

Built as a lightweight Layer-1, Nesa supports **on-chain verification of off-chain inference** using our innovative cryptographic primitives (see [Major Innovations](https://docs.nesa.ai/nesa/major-innovations/private-inference-for-ai)):

* **Equivariant Encryption (EE)**
* **Homomorphic Secret Sharing over Encrypted Embeddings (HSS-EE)**
* **MetaInf**, a meta-learned inference scheduler that dynamically selects the best execution strategy per task and hardware profile, published in *Conference on Language Modeling (COLM) 2025 (Main Conference)*
* (Under development) Model-agnostic hybrid sharding (BSNS) for scalable distributed execution, published in *KDD 2024 — The Fourth International Workshop on Smart Data for Blockchain and Distributed Ledger (SDBD'24)*

The result is a fully decentralized AI network where computation is **secure**, **trustless**, **scalable**, and **adaptively optimized**—across diverse models and hardware.

***

## **DAIs: Decentralized AI Applications**

On top of this execution layer, Nesa introduces [**DAIs (Decentralized AI Applications)**](https://docs.nesa.ai/nesa/major-innovations/decentralized-execution-for-ai/dais-building-decentralized-ai-applications-on-nesa)—AI products that run natively on the Nesa network.

A DAI looks and feels like a real AI application, but is powered by decentralized inference, staking-based credibility, and on-chain coordination. Developers can launch DAIs without operating their own infrastructure, while users gain transparency, verifiability, and aligned incentives by default.

DAIs turn decentralized AI from an infrastructure concept into deployable, user-facing products.

***

## How It Works

Nesa enables users to run AI models in a way that is **private**, **verifiable**, and **decentralized**—without trusting any single server or company.

The figure below illustrates how a query travels through the Nesa network:

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fzehod9LOIoP7F1VR3u6D%2Fimage.png?alt=media&amp;token=b2d8e367-cfd8-46f2-90be-972b8ac5d96f" alt=""><figcaption><p>Overview of Nesa’s decentralized AI inference workflow—verifiable, private, and horizontally scalable.</p></figcaption></figure>

1. **Submit a Query**\
   A user or dApp submits an encrypted AI query through Nesa’s network interface.
2. **Model is Split and Distributed**\
   Nesa breaks the AI model into smaller parts and assigns them to a group of nodes across the network—each node only sees a small piece.
3. **Private Inference is Performed**\
   The network processes the query using encrypted data. No node sees the full input or the full model.
4. **The Result is Verified and Returned**\
   The network generates a cryptographic proof that the result is correct—then returns the answer to the user.

### What Makes Nesa Different

* **Private by default**: No one can see your data, not even the nodes doing the computation.
* **Verifiable**: Every result is backed by cryptographic proof.
* **Scalable**: The workload is spread across a global network—no single node is a bottleneck.
* **Open**: Anyone can contribute models, run nodes, or use the system.

This makes Nesa the first AI platform that is **trustless**, **auditable**, and **built to scale securely**, from chatbots to critical enterprise applications.

***

## Nesa’s Infrastructure and Marketplace

Nesa introduces the first [**decentralized query marketplace**](https://docs.nesa.ai/nesa/major-innovations/decentralized-execution-for-ai/models-on-nesa-playground-and-custom-uploads) for AI:

* A public **model store** that supports both open-source and proprietary models
* Support for LLMs, vision-language models, and other modalities
* Token incentives for developers, model reviewers, validators, and queriers
* Governance and access policies are built into the protocol, not enforced off-chain

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fdg5qTrToGdic2lRYZtyB%2Fimage.png?alt=media&amp;token=5f0ae888-f728-418c-85cd-4fb25374c7fa" alt=""><figcaption><p>Nesa model store supports a large number of AI models.</p></figcaption></figure>

The architecture also allows nodes with limited compute to participate. Model sharding and cryptographic coordination reduce the dependency on top-tier GPUs, **democratizing AI infrastructure** beyond data centers.

## **Model Upload and the Model Playground**

Nesa also provides a **Model Playground** and native **model upload** pipeline. Developers can deploy both open-source and proprietary models—either from the public model catalog or as custom uploads—without managing hosting, scaling, or execution environments.

Uploaded models become first-class assets on the network, with standardized execution, observable performance, and compatibility with DAIs and downstream applications. This allows model builders to focus on capability and differentiation, while Nesa handles decentralized execution and coordination.

***

## What's Next?

This section covers several more core discussions:

1. [**Why Nesa Represents the Future of the AI Economy**](https://docs.nesa.ai/nesa/nesa-docs/why-nesa-represents-the-future-of-the-ai-economy)\
   The case for a decentralized AI system that aligns economic incentives and access.
2. [**Why Centralized AI Infrastructure Is Broken**](https://docs.nesa.ai/nesa/nesa-docs/why-centralized-ai-infrastructure-is-broken)\
   An analysis of the limitations and risks of today’s closed AI platforms.
3. [**Why Existing DeAI Approaches Are Inadequate**](https://docs.nesa.ai/nesa/nesa-docs/why-decentralized-ai-has-not-worked-yet)\
   A critical look at why previous attempts at decentralized AI failed—and how Nesa improves upon them.

In addition, later sections will cover Nesa’s architecture and design innovations in depth, including cryptographic design, execution workflow, node structure, tokenomics, and model integration pipelines.

***

> Nesa is not just a new AI infrastructure—it’s a new AI paradigm. Verifiable, trustless, and built for a world where computation must be both private and public, scalable and secure.


# Why Nesa Represents the Future of the AI Economy

## What Is the AI Economy?

The **AI economy** refers to the growing system of value creation and exchange built around artificial intelligence. It includes:

* **Model creators** — who train, fine-tune, and deploy large models like LLMs or vision transformers
* **Data providers** — who supply datasets, domain-specific corpora, or APIs
* **Compute providers** — who offer GPU power or inference endpoints
* **Consumers and developers** — who integrate AI into applications, services, or research
* **Coordinators and verifiers** — who ensure model execution, accuracy, and privacy through cryptography, consensus, or governance mechanisms

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FfLJO7x1F4qx5770umWqj%2FDiagram-1.png?alt=media&amp;token=ef06b9f0-79f7-4315-889c-9bb340e071c1" alt=""><figcaption><p><em>Source: World Economic Forum,</em> <a href="https://www.weforum.org/stories/2024/02/ai-banking-economy/"><em>https://www.weforum.org/stories/2024/02/ai-banking-economy/</em></a></p></figcaption></figure>

As AI becomes embedded in core sectors—finance, healthcare, governance, science—this economy is expanding rapidly. But today, most of its value is locked inside centralized cloud platforms. The result is:

* **High access barriers** for smaller developers and enterprises
* **Limited control for end-users** over how models are used or verified
* **Few incentives** for open participation or innovation at the infrastructure layer

A key limitation of today’s AI economy is that participation is tightly coupled to a small number of centralized platforms. Even when AI is used by decentralized applications, execution and value capture often occur off-chain, outside the economic and governance context of Web3.

By introducing cross-chain access to AI execution through [AI Link](broken://pages/jUi2j4zcsn0yjOAHzJwU), Nesa extends the AI economy beyond a single network. AI services can be invoked from any blockchain, while execution, verification, and settlement occur within a decentralized and trustless framework. This allows the AI economy to grow across chains, rather than being confined to a single platform or silo.

**Nesa proposes an alternative: a decentralized AI economy.** One where *anyone* can contribute compute, models, or data—and get rewarded for doing so, all while preserving privacy and guaranteeing trustless execution.

***

## The Nesa Framework

**As described in the introduction section, Nesa is a Layer-1 blockchain network purpose-built for AI**, enabling *trustless*, decentralized AI computation at scale. Instead of relying on a single cloud or supercomputer, Nesa **shards AI workloads** across a global node network.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FFhdCYd07lixvRWPMDJQH%2Fimage.png?alt=media&amp;token=26df471f-49e7-4e1f-9bb6-d6c4acbb139a" alt=""><figcaption><p>Nesa's system overview</p></figcaption></figure>

Large models may be broken into smaller, sequential components,  allowing many modest machines to run a large model collaboratively.

> ✅ *Even devices with only 2 GB RAM can participate* — in contrast to conventional AI platforms that demand expensive GPUs like A100s.

By drastically lowering hardware and entry barriers, Nesa creates a **more inclusive AI economy** where developers, users, and small businesses can access or provide advanced AI services *without centralized gatekeepers*.

Importantly, Nesa decouples AI execution from application deployment. While the Nesa network provides the execution, verification, and incentive layer for AI, applications do not need to be deployed on Nesa itself to participate. Through **AI Link**, external blockchains can directly access Nesa’s AI execution capabilities without migrating users, assets, or contracts.

This separation allows the AI economy on Nesa to scale horizontally across ecosystems, while preserving on-chain composability and activity for partner chains.

***

### 🧱 Architectural Advantages

Nesa's infrastructure is engineered to support **secure, performant, and scalable decentralized AI**, built on a cryptographic foundation—not hardware-based trust models.

#### 🔐 Privacy-Preserving Inference with EE and HSS-EE

Instead of relying on TEEs, Nesa uses two modern cryptographic protocols as the backbone of secure inference:

**Equivariant Encryption (EE)**

* Transforms model layers and embeddings into an *encrypted domain* where computations can proceed almost as if they were on plaintext
* Enables **privacy-preserving inference with near-zero latency overhead** and no loss in output quality
* Resistant to brute-force and statistical attacks via model-specific transformations:contentReference\[oaicite:0]{index=0}
* Compatible with LLMs, vision models, and retrieval-augmented pipelines

**HSS-EE (Homomorphic Secret Sharing + EE)**

* Enables two-server inference over encrypted embeddings using **additive secret sharing** on continuous-valued tensors
* Achieves real-time LLaMA-7B inference (sub-second latency), **200×–900× faster** than prior MPC frameworks
* Runs entirely on GPUs, avoiding the need for trusted hardware or full homomorphic encryption
* Fully protects user inputs, intermediate states, and model parameters during inference

> 🧠 *These cryptographic systems ensure that neither inference nodes nor infrastructure operators ever see the raw data.*

***

#### ⚙️ Scalable Execution Across Heterogeneous Devices

Nesa is designed to scale horizontally across globally distributed nodes—whether on datacenter GPUs or edge devices.&#x20;

[**Meta-Learned Inference Optimization**](https://docs.nesa.ai/nesa/major-innovations/decentralized-execution-for-ai/efficient-inference-metainf-and-execution-optimization)

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F0rY2TzZtejKEWaexp10D%2FDiagram-2.png?alt=media&amp;token=5a3727e3-c674-4856-bc7f-5bf24b8cc909" alt=""><figcaption><p>MetaInf overview — Accpted to COLM 2025 main conference</p></figcaption></figure>

* Nesa introduces a **meta-learning scheduler** called `MetaInf` that automatically selects the best acceleration strategies (e.g., prefix caching, chunked prefill) depending on task, model, and hardware
* Learns from past workloads to optimize latency and hardware efficiency in real time
* Outperforms all baselines (SVMs, random forests, heuristic policies) by up to **1.55× acceleration** and 10–20% higher selection accuracy

> 🚀 *This allows Nesa to intelligently adjust to network conditions, node profiles, and workload types—something hardcoded protocols cannot do.*

#### 📦 Standardized Execution Environment

To ensure reliability and compatibility:

* Nesa defines a **uniform containerized runtime** with pinned dependencies, libraries, and kernel versions
* Avoids divergence across nodes and ensures **bit-for-bit reproducibility** of model shards
* Enables model integrity checks and seamless redeployment across machines

***

Together, these systems form a **modular, cryptographically secure, and performance-optimized foundation** for AI that is *not just decentralized—but actually usable* in production.

> 💡 *Nesa is the only framework that offers secure, real-time AI execution without relying on TEEs or full FHE, while also scaling to real-world models and networks.*

***

## Strategic Impact: Building the AI Economy on Nesa

Nesa is not just a platform—it is an **economic protocol** for AI.

By bridging blockchain and AI, Nesa enables:

* **AI services to be consumed on-chain**
  * e.g., a smart contract requesting a prediction with verifiable proof
* **Model creators, node operators, and data providers to be rewarded**
  * via tokenized transactions and reputation
* **Governance to be community-driven**
  * with protocol updates, incentives, and slashing policies governed by stakeholders
* **AI services to operate across chains**
  * e.g., applications on external blockchains invoking AI inference on Nesa while retaining native on-chain activity and fee attribution

#### 📌 Key Properties

* ✅ *No single point of failure*
* ✅ *No need to trust any central actor*
* ✅ *Open participation for compute, models, and data*
* ✅ *Verifiable outputs with cryptographic proofs*

By making AI execution accessible across chains while remaining decentralized, verifiable, and privacy-preserving, Nesa turns AI from a platform-bound service into a shared economic primitive.

Nesa lays the groundwork for an **AI-powered economy** that is as open, decentralized, and user-aligned as the internet itself.

> ✨ *It democratizes access, protects stakeholders, and aligns incentives—where legacy AI platforms fall short.*

***

→ To understand why this future is necessary, we first need to examine [what is broken in today’s AI infrastructure](https://docs.nesa.ai/nesa/nesa-docs/why-centralized-ai-infrastructure-is-broken).


# Why Centralized AI Infrastructure Is Broken

## Why Centralized AI Infrastructure Is Broken

Today’s dominant AI infrastructure is highly centralized — a handful of large tech companies and cloud platforms control the vast majority of compute, models, and access. While this has enabled rapid advances, it comes with **structural flaws** that hinder **scalability**, **privacy**, **competition**, and **trust**.

***

#### ❌ Single Points of Control and Failure

A [2023 UN AI report](https://unctad.org/news/ais-48-trillion-future-un-trade-and-development-alerts-divides-urges-action#:~:text=AI%20is%20expected%20to%20reach,of%20the%20whole%20African%20continent.) highlighted that the $4.8 trillion AI economy is overwhelmingly concentrated in fewer than 100 firms. This consolidation of infrastructure and model access leads to:

* A **monopoly on capabilities**: a few firms control who gets access, at what price, and for what purposes
* **No redundancy**: if a provider changes terms, goes offline, or revokes access, users have no alternatives
* Risk of **centralized censorship** and **geopolitical dependencies**

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FpUdhIklSwZYOMlFNcFN1%2FDiagram-3.png?alt=media&amp;token=59820fe5-6192-4b18-8840-c58ca4bd6f63" alt=""><figcaption><p>Source: United Nation, <a href="https://unctad.org/news/ais-48-trillion-future-un-trade-and-development-alerts-divides-urges-action">https://unctad.org/news/ais-48-trillion-future-un-trade-and-development-alerts-divides-urges-action</a></p></figcaption></figure>

In a truly resilient AI ecosystem, **there would be no single chokepoint**. Centralized systems fail this test by design ([link](https://bryghtpath.com/single-point-failures/#:~:text=A%20single%20point%20of%20failure,This%20ensures%20uninterrupted%20operation.)).

***

#### 💸 High Costs and Barriers to Entry

Training or even hosting modern models like GPT-4, PaLM 2, or Claude 3 requires:

* Thousands of A100-class GPUs
* Tens of millions of dollars in energy and infrastructure
* Deep in-house ML + systems engineering expertise

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FR4EQlzEvjMHGsjX4yh5Y%2FDiagram-4.png?alt=media&amp;token=b49db222-b99e-4789-9283-3fb96a404f17" alt=""><figcaption><p>Source: Bot Penguin, <a href="https://botpenguin.com/blogs/what-is-the-cost-of-training-llm-models">https://botpenguin.com/blogs/what-is-the-cost-of-training-llm-models</a></p></figcaption></figure>

As a result, most developers and startups are **locked into API access** — creating a *model rent economy* where value accrues to platform owners, not the builders or users.

Even for inference, costs are steep: multiple analyses (e.g.,  show per-query pricing at several cents — unsustainable for scaled applications ([link](https://arxiv.org/html/2506.04301v1)).

At the same time, **global idle compute capacity** (laptops, edge nodes, small data centers) remains **untapped**. Centralized AI simply does not scale economically or geographically.

***

#### 🔐 Privacy Risks and Data Ownership

Centralized AI services require users to send data to servers they do not control. This architecture has led to:

* **Known data breaches** at OpenAI, Google, and others ([link](https://www.reuters.com/technology/cybersecurity/openais-internal-ai-details-stolen-2023-breach-nyt-reports-2024-07-05/))
* **Opaque logging** and retention of prompts and outputs
* Lack of enforceable **data deletion** or usage guarantees

For sensitive domains — healthcare, finance, defense, or law — this is often **unacceptable**. Even inference outputs can leak latent information, and few centralized services offer strong guarantees or auditing support ([link](https://medium.com/@anicomanesh/data-leakage-causes-effects-and-solutions-6cc44a149e1c)).

***

#### 🔎 Lack of Transparency and Verifiability

Users of centralized systems face **epistemic opacity**:

* No access to model internals, training data, or configuration
* No way to check whether an inference was performed correctly
* No proof of consistency or fairness across users or inputs

In critical applications — e.g., automated decision-making in loans, hiring, or healthcare — this black-box nature undermines **accountability** and **regulatory compliance**.

By contrast, decentralized and cryptographic methods (e.g., zero-knowledge proofs, multiparty inference) allow **external verification** of correctness without revealing data or models.

***

#### 🧱 Execution Inefficiencies and Scalability Limits

Ironically, centralization also introduces **scalability bottlenecks**:

* Large data centers must overprovision to meet peak load, leading to **low utilization**
* Network latency and **data gravity** make it inefficient to ship large user data to a single region
* Many devices (e.g., mobile, IoT, on-prem compute) cannot be used as **inference endpoints**

This leads to **wasteful compute**, high latency, and regional disparities in access. Models may be “global,” but centralized infrastructure prevents them from being **locally adaptive** or **edge-deployable.**

***

#### 🧨 Summary: Fragile, Exclusive, and Opaque

Centralized AI is:

* **Fragile** — single points of failure and control
* **Exclusive** — access is monetized, restricted, and often subject to opaque terms
* **Opaque** — users cannot inspect, verify, or audit model behavior

As AI becomes foundational to infrastructure, finance, governance, and national security, **this model becomes ethically and strategically untenable**.

> We need systems where trust is grounded in **cryptographic proof**, not corporate goodwill.

***

#### 🌐 The Alternative: Decentralized, Verifiable AI

Nesa offers a radically different architecture:

* **No centralized control** — compute and model access are permissionless
* **Privacy-preserving by default** — users retain custody over data and queries
* **Verifiable inference** — outputs are backed by proofs, not promises
* **Scalable globally** — any node can join the network to serve or verify models

This enables a shift from the opaque, centralized AI cloud to a **transparent, open AI infrastructure** — one aligned with the principles of the internet and Web3.

***

→ Many have tried to fix this by decentralizing AI—but most solutions failed to deliver.\
**Read next:** [**Why Existing Decentralized AI (DeAI) Approaches Are Inadequate**](https://docs.nesa.ai/nesa/nesa-docs/why-decentralized-ai-has-not-worked-yet)


# Why Decentralized AI Has Not Worked (Yet)

Decentralizing AI is not a new idea. Multiple projects and research efforts have attempted to marry AI with blockchain or peer-to-peer networks. However, existing decentralized AI (DeAI) approaches have consistently failed to meet the requirements of **trust**, **security**, and **scalability**. Many have merely replicated the shortcomings of centralized systems, or introduced new ones.

Below, we examine the key limitations of past efforts, and how Nesa’s approach is fundamentally different.

***

#### ❌ Limited Trust and Verification Mechanisms

Most DeAI platforms still rely heavily on **off-chain computation** ([source](https://arxiv.org/abs/2505.07828)), with no robust way to verify results:

* Inference is performed on nodes that users must **trust** to be honest.
* Platforms like [SingularityNET](https://singularitynet.io/) or [Fetch.ai](https://fetch.ai/) may use blockchain for coordination, but the **actual computation happens off-chain**.
* Users have no cryptographic assurance that the output is correct or that the model even ran as claimed.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FnGg8EEj1yL2PkoVgs9Vw%2FDiagram-5.png?alt=media&amp;token=7c7f0ed4-7c70-4619-850d-63ca895c57f1" alt=""><figcaption><p>Visualizing the interactions between offchain and onchain resources. Source: Chain Link, <a href="https://chain.link/education-hub/off-chain-data">https://chain.link/education-hub/off-chain-data</a></p></figcaption></figure>

Some networks attempt mitigation via **reputation systems**, **redundant execution**, or **escrow**, but these mechanisms introduce friction and **still do not guarantee correctness**.

This is the core of the “verification dilemma”:

> *It’s hard to confirm that an AI output is correct without re-running the entire computation—defeating the point of delegation.*

Nesa explicitly addresses this through **zkDPS** (Zero-Knowledge Decentralized Proof System) and consensus-based verification. Either a proof of correct execution is provided, or multiple nodes must independently agree on the output.

***

#### 🔐 Privacy Not Fully Preserved

Many DeAI platforms claim to be privacy-preserving, but fall short in practice:

* Some rely on **federated learning** or **secure multi-party computation (MPC)** to protect training data, but not inference inputs.
* In many cases, users must send **raw input data** to remote nodes for inference—often operated by third parties.
* Approaches based on **homomorphic encryption** remain largely impractical for large, real-time models due to extreme computational overhead.
* Others explore **secure enclaves**, but these introduce hardware trust assumptions and carry performance or deployment constraints.

Nesa avoids these pitfalls with a different strategy:

* It builds on **Equivariant Encryption (EE)** and **HSS-EE**, which allow model inference to be performed on **encrypted embeddings** using **additive secret sharing**, without leaking raw inputs to any server.
* The user locally embeds their input and splits it into shares that are **individually meaningless** to each compute node.
* These shares are processed securely and efficiently, even for deep models, using **GPU-native primitives** and protocols optimized for transformer inference.

> No node ever sees the full input, intermediate activations, or final output—ensuring strict confidentiality throughout the computation pipeline.

This approach offers **end-to-end inference privacy** in a decentralized setting, without requiring trusted hardware or incurring FHE-level latency.

***

#### 🧱 Performance and Scalability Bottlenecks

Early decentralized AI systems have faced major issues scaling up:

* **Blockchain-based computation** is too slow and expensive for real-world inference, so nearly all DeAI projects execute AI off-chain.
* Performing inference redundantly across nodes to gain consensus **multiplies cost and latency**.
* Networks like Bittensor attempt to crowdsource language model training across many participants—but performance still lags far behind centralized infrastructure.

Other limitations include:

* Hardware fragmentation: Many DeAI platforms require participants to run **specialized GPU nodes**, limiting network size.
* Developer friction: Packaging and deploying models often demands **low-level infrastructure knowledge**.

The result: **most DeAI platforms can only support toy workloads or narrow use cases.**

Nesa approaches this differently:

* It uses **sharded execution (BSNS)** to split models into sequential blocks, each small enough to run on modest machines.
* A **uniform execution environment** ensures determinism and compatibility.
* Additional optimizations (e.g., **caching**, **two-phase commit**, **VRF-based node selection**) reduce latency and coordination overhead.

> Nesa is one of the first to make **large-scale, performant decentralized inference practical**, not just possible.

***

#### 🧨 Summary: Why Most DeAI Platforms Fall Short

In theory, decentralization solves many AI problems. In practice, most existing projects:

* Fail to provide **cryptographic trust guarantees**
* Compromise on **privacy** in real-world usage
* Cannot handle large-scale, latency-sensitive workloads
* Rely on **market dynamics** without formal checks and balances

> A 2023 survey found that most “AI token” projects operate off-chain and simply add payments to conventional APIs, delivering **no real architectural innovation**.

***

#### ✅ How Nesa Differs

Nesa is a private, decentralized AI framework designed to address:

* **Trust** — via zk-proofed or consensus-verified inference
* **Privacy** — via SVE + split learning
* **Scalability** — via model sharding and deterministic execution

Nesa does not simply decentralize AI coordination. It **rebuilds AI execution** to be secure, verifiable, and scalable—without trusting any single node.

This is why Nesa is often called:

> *“AI sharding” or “the AI equivalent of a blockchain.”*

By solving the open problems that plagued previous attempts, Nesa moves DeAI from prototype to infrastructure.&#x20;


# Organization of the Documentation

The Nesa documentation is structured into four major parts: concept, core systems, usage, and infrastructure. This allows readers to progress from understanding *why Nesa exists* to *how to build and operate on it*.

***

### Part I: Vision and Foundations

This section introduces the **motivations behind Nesa** and its place in the evolving AI landscape:

* What problems Nesa solves in the AI economy
* Why centralized AI systems are structurally flawed
* Where previous decentralized AI approaches fell short
* How Nesa differs architecturally, economically, and cryptographically

***

### Part II: Core Systems and Innovations

This section presents Nesa’s **technical architecture**, including its novel execution and security primitives. It covers:

* How Nesa distributes and verifies large AI models
* How privacy and correctness are enforced with cryptography
* How performance is optimized across heterogeneous nodes
* How token economics and governance shape participation
* First-party applications showcasing on-chain AI

> 🛠 This section may evolve as we publish new protocol modules (e.g., inference scheduling, multi-agent coordination, on-chain routing) or refine the current ones.

***

### Part III: Using Nesa

This section helps developers and users **interact with the network**, covering:

* Wallet setup, testnet access, and query submission
* Using Nesa via web, SDK, IBC, or bridging tools
* Integrating your models or consuming others’ models trustlessly

***

### Part IV: Operating a Nesa Node

This section guides those who wish to **contribute compute** or run nodes:

* Hardware requirements and installation
* Runtime behavior and lifecycle
* Validator incentives and responsibilities
* Troubleshooting and CLI usage

***

### Additional Resources

* **Community** — Join us via Discord or Twitter
* **Live apps** — Explore applications like DNA X
* **Policy** — Review our terms and privacy policies
* **Glossary** — Find definitions for key protocol terms

***

This structure is designed to support **modular growth**. As Nesa evolves—from a decentralized inference engine to a foundation for verifiable autonomous AI—you’ll find new primitives, agents, and integrations reflected across the documentation.


# Background and Exploratory Notes

We introduce a pioneering new system architecture that is **the new standard for blockchain-powered artificial intelligence**. Around this standardization, we have three primary parties:

* **AI models** that are available on the Nesa system by the model developers
* **Users of Nesa** who need affordable, private inference
* **Node runners** who execute the decentralized jobs on the Nesa system, including validation, inference, and more

At its foundation, the Nesa system is designed to streamline the AI computation process by providing a consistent set of rules and execution protocols, which every participating parties must follow. This not only guarantees that all nodes produce identical results given the same model parameters and input data, but also relieves node operators from the complexity involved in setting up execution environments, facilitating easier adoption and participation in our network.

In this section, we detail how [users who need private inference](https://docs.nesa.ai/nesa/background-and-exploratory-notes/users-why-do-we-need-private-inference) can leverage Nesa to get inference results by [leading AI models](https://docs.nesa.ai/nesa/background-and-exploratory-notes/ai-models-repository-standardization-uniformity), which are powered by our [node runners](https://docs.nesa.ai/nesa/background-and-exploratory-notes/node-runners-doing-inference-and-earning-usdnes).

We will soon provide a flow chart of the system interaction here.


# AI Models: Repository, Standardization, Uniformity

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

On the AI model side, we define **AI Kernel (AIK)**. The kernel encapsulates all of the necessary building blocks for a node to download and correctly execute an AI model. The AI kernel is stored on the blockchain to facilitate transparency and repeatability, providing an immutable and verifiable record of the model’s execution environment and logic.

### Repository

Nesa provides a robust platform designed to support various AI models, catering to various computational needs and inference tasks. Our on-chain repository not only offers access to these models but also encourages active contributions from the community to expand the available tools.&#x20;

Among the models we support are advanced vision-language models like LLaMA 2 and LLaMA 3, which excel in integrating visual content with natural language processing. Additionally, generative models such as Stable Diffusion are included, allowing for creative image synthesis based on textual descriptions. This inclusive approach ensures that users can leverage the right tools for tasks ranging from simple classifications to complex multimodal challenges.&#x20;

More detailed information about the full range of models supported by Nesa will be available on our platform as our repository continues to grow.

***

### Standardized Specifications

To achieve uniform model execution, the configuration must encompass every aspect that could influence the computational outcome. This includes specifying the operating system and compiler versions, along with precise compilation options and flags.

By rigorously defining the execution environment, we eliminate variability that could otherwise arise from different software stacks.

#### **Hardware Specifications**

If a model demands particular hardware characteristics, such as GPU acceleration or specialized processing units like TPUs, its configurations explicitly state these requirements.

Moreover, features provided by the hardware that could potentially lead to inconsistent execution, such as non-deterministic hardware instructions, are either strictly enabled or disabled as appropriate.

This approach ensures that all participating nodes adequately prepare and align their computational capabilities with the model’s needs.

#### Software and Algorithm Specifications

Many AI models introduce randomness during inference, which can challenge achieving deterministic and reproducible results. To mitigate this, we have implemented the strategy of fixing the random seed, which ensures that any pseudo-random number generation during inference leads to the same sequence of numbers across all executions.

In scenarios where public randomness is necessary, we integrate the cryptographic method of Verifiable Random Functions (VRFs) that produce randomness that is both unpredictable and provably unbiased.

This use of VRF in our system not only lends credibility to the random number generation process but also makes it possible to verify the randomness after the fact.

To summarize, each AI model in the Nesa ecosystem comprises four integral components:

* **Model Parameters** are the weights and biases that define the AI model. They are the product of the training process and dictate the model’s behavior and capabilities.
* **Configuration File** functions similar to a Docker file, which contains the above specifications for the virtual environment in which the AI model will execute. It details the dependencies, libraries, and runtime needed to run the model, ensuring that every node sets up an execution environment with identical configurations.
* **Inference Code** is the code that runs the AI model. This includes the logic for processing inputs and generating predictions or outputs. The inference code also comes with necessary compilation information to ensure it can be seamlessly executed.
* **Aggregation Code** is a piece of scripting code that determines how the decentralized participants will aggregate and reach consensus from results returned from different nodes.

***

### Uniformity

The execution protocol within Nesa prescribes a series of steps that every node must follow. This protocol includes initialization procedures, data input conventions, model execution, and output handling. By standardizing the execution flow, we can reliably predict and replicate the behavior of AI models across the network.

Before an AI model is approved and stored on the blockchain, it undergoes rigorous validation to ensure compliance with the specified configuration and to confirm that it yields consistent results across diverse environments. A suite of tests is run in simulated multi-node scenarios to affirm that the kernel’s execution is deterministic and immune to variances in the underlying systems. The measures create a robust framework for model consistency and inference reliability within the Nesa system.

These provisions are critical for maintaining the integrity of our decentralized inference system, guaranteeing that any node, regardless of its individual hardware or software configurations, can reliably participate in the network and contribute to collective AI tasks.

This standard of uniformity enables a diverse ecosystem of nodes to work together seamlessly and trustlessly.


# Users: Why Do We Need Private Inference?

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

\
Private inference is crucial for users who handle sensitive data that must not be exposed during the model inference process, even to the models themselves. This need is prevalent in several key industries:

1. **Finance**: Financial institutions manage highly confidential data, such as personal financial records, investment details, and proprietary trading algorithms. These entities require private inference to ensure that data remains secure while using AI for fraud detection, risk assessment, and personalized banking services.
2. **Healthcare**: In healthcare, patient data is both sensitive and heavily regulated. Healthcare providers and researchers use private inference to analyze medical records, diagnostic images, and genetic information to provide personalized treatment plans and conduct medical research without compromising patient confidentiality.
3. **Legal Sector**: Law firms and legal departments use private inference to handle sensitive case documents, client records, and legal precedents. AI can help in predicting case outcomes, performing document review, or automating legal research while ensuring that the data does not leak or become accessible outside the authorized channels.
4. **Public Sector**: Government agencies often handle sensitive information related to national security, public records, and personal data of citizens. Private inference is employed to utilize AI for public safety applications, policy making, and service delivery without exposing the underlying data.

\
Providing private inference can be challenging for existing centralized platforms like ChatGPT due to several inherent limitations:

1. **Data Centralization**: Centralized systems often collect and process data on central servers, which can create potential points of vulnerability where data might be exposed to unauthorized access or breaches.
2. **Transparency and Trust**: Users must trust that the platform will handle their data securely and according to privacy agreements. In centralized models, it's difficult for users to verify that data handling protocols are followed without the ability to inspect the infrastructure or data flows.
3. **Scalability of Privacy**: As the user base grows, maintaining strict data privacy at scale becomes more complex. Ensuring consistent enforcement of privacy practices across large volumes of data and inference requests is a substantial challenge.
4. **Regulatory Compliance**: Different regions have varying regulations on data privacy (like GDPR in Europe or HIPAA in the U.S.), making it difficult for centralized platforms to uniformly apply the highest standard of data privacy across all jurisdictions.

To fill this gap, we design Nesa, the first platform to provide private inference on the decentralized systems.


# Node Runners: Doing Inference and Earning $NES

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Node runners contribute to the decentralized and distributed nature of Nesa, enhancing its efficiency and security for running AI models. They can be run by individuals, companies, or any other entities interested in supporting the network and earning rewards (which is [$NES](broken://pages/GMVy41K9A91P8NsqgiRq)) for their efforts.

These nodes support the network by performing several critical functions:

1. **Validation**: Nodes validate new transactions and blocks to ensure they follow the network rules. This includes checking that transactions are properly signed and that they do not attempt to spend funds that have already been spent.
2. **Inference**: Node runners execute the actual inference task assigned by the orchestrator, where the aggregated results will be returned to the user who request the job.

Want to join as a node runner? See details in [run a nesa node](https://docs.nesa.ai/nesa/run-a-nesa-node/prerequisites).


# Private Inference for AI

This chapter introduces Nesa's cutting-edge hybrid approach to security and privacy enhancement. The essence of this hybrid design lies in the thoughtful integration of hardware-based and cryptographic-based solutions, each selected and optimized for varying scenarios within our ecosystem.

Our hybrid security and privacy is grounded in the recognition that privacy concerns manifest in different forms—users may wish to conceal their input data or the results of their inferences, while node owners might seek to protect the confidentiality of their model parameters. Our hybrid design acknowledges the unique requirements of these use cases by deploying the most appropriate privacy-preserving technologies.

This chapter elucidates the rationale behind Nesa's hybrid strategy, offering a comprehensive blueprint for achieving the highest standards of security and privacy while maintaining the usability and efficiency of the decentralized inference process.


# Why Privacy Matters in Decentralized AI

In centralized AI systems, users implicitly trust the provider to keep their data and model execution private. But in a decentralized setting, **no such trust can be assumed**. That makes privacy preservation far more difficult—and far more important.

The emergent importance of **private decentralized AI** has caught significant attention and investment, such as Intel's [Private AI Collaborative Research Institute](https://www.intel.com/content/www/us/en/research/blogs/private-ai-collaborative-research-institute-launch.html), which funded research in this direction.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FQMG4ow3MX1DcFMruqAIG%2Fimage.png?alt=media&amp;token=40f397e9-5c5f-47bf-aca7-72be2224c394" alt=""><figcaption><p>Source: Intel Labs, <a href="https://www.intel.com/content/www/us/en/research/blogs/private-ai-collaborative-research-institute-launch.html">https://www.intel.com/content/www/us/en/research/blogs/private-ai-collaborative-research-institute-launch.html</a></p></figcaption></figure>

***

### Why Privacy in Decentralized AI Is Hard

Decentralized AI networks often operate on untrusted, globally distributed hardware. In this setting:

* Anyone can spin up a node and receive user inputs or model fragments
* Data may pass through an **unknown or adversarial infrastructure**
* Model owners often want to keep their weights secret
* Users need strong guarantees that **no intermediate computation leaks sensitive data**

Even if communication is encrypted, once data reaches the node for computation, **exposure risk begins**. Most traditional privacy techniques focus on training—not inference—and assume trusted environments or offline processing.

In decentralized inference, privacy must be enforced:

* **Across untrusted compute**
* **During live inference**
* **Without sacrificing performance or usability**

This requires an entirely different design paradigm—one where **nodes never need to see raw inputs, intermediate states, or full model logic**.

***

### Why Homomorphic Encryption (HE), Trusted Execution Environments (TEEs), Differential Privacy (DP), and Zero-Knowledge Proofs (ZKPs) Alone Don’t Work

Several communities have tackled privacy using specialized tools. But none of them, on their own, solve the challenges of decentralized inference.

***

#### ❌ Homomorphic Encryption (HE)

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F7OzBIPWkq33nyklJtcSg%2FDiagram-6.png?alt=media&amp;token=3df51eba-dbcb-4d8a-8bf6-d5755e9c7eb1" alt=""><figcaption><p>Source: Chainlink, <a href="https://chain.link/education-hub/homomorphic-encryption">https://chain.link/education-hub/homomorphic-encryption</a></p></figcaption></figure>

**Fully Homomorphic Encryption (FHE)** allows arbitrary computation on encrypted data. In theory, this could enable privacy-preserving inference without exposing inputs or model internals.

But in practice:

* Even state-of-the-art FHE schemes introduce **4–6 orders of magnitude overhead** over plaintext execution
* Deep models (e.g., Transformers or ResNets) involve **nonlinear operations** and large matrix multiplications that are **prohibitively slow or unsupported in FHE**
* Most FHE frameworks only support basic arithmetic operations, requiring **approximation of activation functions**, which degrades model fidelity
* Batch sizes are constrained by ciphertext packing limitations, further reducing throughput

> FHE remains **theoretically elegant** but **computationally impractical** for real-time inference on large models.

***

#### ❌ Trusted Execution Environments (TEEs)

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F0DmQaGFdmvEadgv9culT%2FDiagram-7.png?alt=media&amp;token=0fa40c35-9b37-4bc1-9860-088c2850d025" alt=""><figcaption><p>Source: Samsung, <a href="https://developer.samsung.com/blockchain/keystore/understanding-keystore/keystore-architecture.html">https://developer.samsung.com/blockchain/keystore/understanding-keystore/keystore-architecture.html</a></p></figcaption></figure>

TEEs execute code in hardware-isolated memory regions, shielding it from the rest of the system. Intel SGX and AMD SEV are common examples.

However, TEEs are **not well-suited to large-model inference** for several reasons:

* **Limited memory and compute capacity**: most enclaves cannot handle LLMs or vision models due to size constraints (e.g., 128–512MB secure memory)
* **Hardware trust assumptions**: users must trust the CPU vendor, firmware supply chain, and enclave verification process
* **Vulnerability to side-channel and rollback attacks**, especially under concurrent workloads
* **Incompatibility with decentralized networks**, where not all nodes have TEE hardware

> TEEs shift the trust surface from the node operator to the hardware vendor—**not a full solution for adversarial settings**.

***

#### ❌ Differential Privacy (DP)

Differential Privacy introduces controlled randomness to outputs to ensure individual data points are not statistically identifiable. It is widely used in **training-time privacy** (e.g., DP-SGD).

But in decentralized inference:

* DP does **not apply to individual inputs**, which are processed directly
* It **cannot prevent raw input or intermediate leakage** if a node is compromised
* Adding DP noise during inference **can degrade output quality**, especially for deterministic tasks (e.g., document classification, image captioning)

> DP is a training-level guarantee—**not a usable protection for query-time privacy or model confidentiality**.

***

#### ❌ Zero-Knowledge Proofs (ZKPs)

ZKPs can prove that a computation was performed correctly without revealing inputs or model parameters. This is essential for **verifiability**—but not sufficient for privacy:

* ZKPs typically assume **inputs are known** to the prover; they do not hide inputs by default
* Generating ZK proofs for large neural networks (e.g., 100M+ parameters) is **computationally expensive and memory intensive**
* For modern transformers, proving even a few layers takes **seconds to minutes**, making real-time serving infeasible
* ZKPs cannot protect **data in use**—only the final output's correctness

> ZKPs are powerful for validation, but must be **paired with encryption or secure execution** to achieve full privacy.

***

### Summary

| Technique               | Protects Input? | Verifies Correctness? | Scales to LLMs?   | Drawbacks                                  |
| ----------------------- | --------------- | --------------------- | ----------------- | ------------------------------------------ |
| Homomorphic Encryption  | ✅               | ❌                     | ❌                 | 10⁴–10⁶× slowdown; limited ops             |
| Trusted Execution (TEE) | ✅ (assumed)     | ❌                     | ❌                 | Vendor trust, memory limits, side-channels |
| Differential Privacy    | ❌               | ❌                     | ✅ (training only) | Doesn't apply to inference-time privacy    |
| Zero-Knowledge Proofs   | ❌               | ✅                     | ❌                 | Costly; needs external encryption          |

> **No single method solves privacy and verification for large-model decentralized inference.**\
> Only a hybrid stack—combining lightweight encrypted computation with secure sharing and verifiable proofs—can satisfy all constraints.

***

### Summary

Each of these approaches offers partial value, but none alone solve the core challenge of decentralized inference:

> *How can we compute on user data across untrusted nodes—without ever exposing the input, model, or output—and still verify that the result is correct?*

The rest of this section introduces **Nesa’s cryptographic stack**, designed to solve exactly that.


# Practical Approach: Equivariant Encryption (EE)

**Equivariant Encryption (EE)** is Nesa’s core technique for enabling fast, privacy-preserving inference—without relying on heavy cryptography or trusted hardware. It ensures that large models like LLMs and vision transformers can run over encrypted data at near-native speeds, without exposing user inputs, intermediate activations, or model outputs.

***

### 🔒 Why EE?

Most privacy-preserving methods (as discussed [earlier](https://docs.nesa.ai/nesa/major-innovations/private-inference-for-ai/why-privacy-matters-in-decentralized-ai)) fail under the scale and latency constraints of modern AI inference:

| Technique                   | Scales to LLMs?   | Protects Input? | Trust Assumptions    | Drawbacks                                       |
| --------------------------- | ----------------- | --------------- | -------------------- | ----------------------------------------------- |
| Homomorphic Encryption (HE) | ❌                 | ✅               | None                 | 10⁴–10⁶× slowdown, limited nonlinearity support |
| Trusted Execution (TEE)     | ⚠️ (Limited)      | ⚠️              | CPU vendor, firmware | Memory limits, side-channel attacks             |
| Differential Privacy (DP)   | ✅ (Training only) | ❌               | None                 | Not usable at inference time                    |
| Zero-Knowledge Proofs (ZKP) | ⚠️                | ❌ (alone)       | None                 | High prover cost; not private by default        |

**EE fills the gap**: it provides encrypted inference that scales, runs fast, and requires no hardware trust.

***

### ⚙️ What Is Equivariant Encryption?

EE is a lightweight transformation scheme that enables models to operate directly on encrypted data. It ensures:

* **Recoverability**: encrypted inputs can be decoded losslessly
* **Equivariance**: the result of encrypted inference is identical to that of plaintext inference

Formally, for any plaintext input `p`:

* **Recoverability**:\
  `decrypt(encrypt(p)) = p`
* **Equivariance**:\
  `decrypt(F(encrypt(p))) = F(p)`

Where `F` is a supported operation (e.g., linear layers, ReLU, GeLU, LayerNorm).

This allows secure inference pipelines without altering model logic or degrading output quality.

***

### 🧠 How It Works

1. **Offline Transformation**\
   A secure setup phase transforms a model into its EE form by modifying layer operations.
2. **Encrypted Inference**\
   The EE model is deployed to remote nodes. Users submit encrypted queries; servers run inference directly on ciphertext—without ever decrypting.
3. **Decryption**\
   The user decrypts the result using their private key.

📌 All activations and intermediate states remain encrypted throughout the process. Here a high-level overview flowchart is provided.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FkbrrpLbwgZAtG0VrLXjN%2FDiagram-8.png?alt=media&amp;token=338f0d4b-daf9-44f3-abee-9d902b46bb92" alt=""><figcaption><p>Equivariant Encryption (EE) end-to-end workflow.<br>A secure one-time setup phase transforms a trained neural network into its EE-compatible form. The encrypted model is then uploaded to cloud storage and distributed to untrusted inference servers. During inference, user queries remain encrypted throughout processing, with only the client able to decrypt the result. Remote compute resources may assist in sub-tasks, but all activations, parameters, and outputs stay encrypted end to end.</p></figcaption></figure>

***

### ✅ Key Advantages

| Property                     | EE Description                                        |
| ---------------------------- | ----------------------------------------------------- |
| **Server Blindness**         | All inputs, activations, and outputs stay encrypted   |
| **Runtime Speed**            | Near-identical latency to vanilla inference           |
| **Deep Model Compatibility** | Supports transformers, CNNs, RAG, LayerNorm, and more |
| **No Hardware Dependency**   | GPU-native; no enclave or vendor lock-in              |
| **Plug-and-Play**            | Minimal code changes (e.g., replace layer types)      |

***

### 📊 Benchmarking Results

* **Latency overhead**: < 9% (measured on LLaMA-8B, with and without vLLM)
* **Fidelity score**: > 99.99% match with vanilla inference
* **Applications tested**: IMDB classification, MT-Bench QA, ShareGPT prompts, RAG

🧪 EE enables LLMs and RAG pipelines to maintain **full accuracy and response quality**—at production speed.

***

### 🛡️ Threat Model & Attack Resistance

EE is designed for robustness even under full adversarial observability:

* Inputs and outputs are transformed via one-way, high-dimensional mappings
* Reversing EE requires solving combinatorial permutation problems (e.g., 128k! for LLM vocabularies)
* Known attack strategies (brute-force, hill-climbing, LLM-as-a-judge) are computationally infeasible in practice

> EE's security comes from **combinatorial hardness**, not access control or TEE black boxes.

***

### 🧪 Deployment Scenarios

* **LLMs**: Token embeddings remain encrypted during generation
* **Vision Models**: Feature maps remain protected throughout convolutional and attention layers
* **RAG Pipelines**: Queries and retrieved documents are encrypted end-to-end
* **Multi-modal Models**: Encrypted inputs across modalities remain isolated from untrusted nodes

🛠 EE supports these models in sharded and parallelized settings, ensuring no plaintext data is leaked across the network.

***

### 📈 Comparison with Homomorphic Encryption (HE)

| Property             | EE                          | Fully Homomorphic Encryption (FHE) |
| -------------------- | --------------------------- | ---------------------------------- |
| **Latency Overhead** | Near-zero                   | 10⁴–10⁶×                           |
| **Nonlinear Ops**    | Exact (ReLU, GeLU, etc.)    | Approximate only                   |
| **Integration**      | Layer-local transforms      | Full model rewrite                 |
| **Accuracy**         | Matches plaintext inference | May degrade                        |
| **Hardware**         | Commodity GPU               | Often CPU-based                    |
| **Key Management**   | Lightweight, per-user       | Complex, scheme-bound              |

***

### 🧭 Summary

**Equivariant Encryption (EE)** delivers:

* Encrypted inference for large models at production speed
* Compatibility with modern deep learning architectures
* No hardware dependencies
* Mathematically provable correctness and privacy

While EE provides an efficient and blind inference framework over encrypted models, it operates under a single-server assumption. But what if the goal is to split trust between multiple servers—ensuring that **no single machine ever sees even encrypted embeddings alone**?

This is where **HSS-EE** comes in.

HSS-EE combines Equivariant Encryption with **Homomorphic Secret Sharing (HSS)**, enabling secure two-party inference for large models like LLaMA-7B with **sub-second latency** and **zero reliance on trusted hardware**. By splitting each user query into additive shares and computing on both simultaneously, HSS-EE achieves **information-theoretic security** under non-collusion—while still preserving EE’s model-blindness guarantees.

→ *Continue to HSS-EE: Secure Two-Party Inference at Scale*


# Scalable Private Inference with HSS-EE

**HSS-EE (Homomorphic Secret Sharing over Encrypted Embeddings)** is Nesa’s two-party inference protocol that provides stronger privacy than standard encrypted inference. Built on top of [Equivariant Encryption (EE)](https://docs.nesa.ai/nesa/major-innovations/private-inference-for-ai/practical-approach-equivariant-encryption-ee), HSS-EE ensures that **no single server ever sees the full user input, not even in encrypted form**.

This makes HSS-EE ideal for use cases with **high confidentiality demands**, such as medical inference, compliance-constrained applications, or decentralized infrastructure with minimal trust assumptions.

***

### 🔑 Core Idea: Additive Sharing + Encrypted Embeddings

HSS-EE splits an encrypted user input into **two additive shares**, sending each to a separate server. Both servers run the same EE-compatible model but over different shares:

* Neither server can reconstruct the original input
* Activations and outputs remain secret-shared end-to-end
* The user alone combines results to recover the output

This achieves **information-theoretic security under non-collusion** — even if one server is fully compromised.

***

### 🛠️ How HSS-EE Works

1. **Preprocessing (Client-side):**
   * The user embeds their input locally (e.g., token embeddings or image patches)
   * Applies Equivariant Encryption (EE)
   * Splits the encrypted vector into two additive shares: `x = x₁ + x₂`
2. **Distributed Inference (Server-side):**
   * Server A receives `x₁`, Server B receives `x₂`
   * Each server runs the same encrypted model over their share
   * Intermediate activations remain encrypted and secret-shared
3. **Result Reconstruction (Client-side):**
   * Final results are returned as shares
   * The user reconstructs the final output locally: `y = y₁ + y₂`

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FppFkBRoLETXgQa2tE0Nl%2Fimage.png?alt=media&amp;token=4ddc616d-7982-4023-b70e-a0f33801e3a7" alt=""><figcaption><p>High-level diagram of HSS-EE workflow and broadcasting schedule showing minimized</p></figcaption></figure>

***

### 🧠 Why HSS-EE?

| Feature                             | EE                      | HSS-EE              |
| ----------------------------------- | ----------------------- | ------------------- |
| Protects input from server          | ✅                       | ✅                   |
| No server sees full encrypted input | ❌                       | ✅                   |
| Collusion-resistance                | ❌ (single-server trust) | ✅ (two-party model) |
| GPU compatible                      | ✅                       | ✅                   |
| Applicable to large models          | ✅                       | ✅                   |

HSS-EE is particularly valuable in settings where:

* No single party should have full visibility
* Regulators require infrastructure separation (e.g., EU + US)
* Inference is hosted across multi-party environments (e.g., DAO + enterprise)

***

### 📊 Performance Benchmarks

All results are measured using consumer-grade A100 nodes over gRPC with CUDA kernel acceleration.

| Model      | Latency (batch=1) | Throughput (QPS) | Notes                          |
| ---------- | ----------------- | ---------------- | ------------------------------ |
| LLaMA-2 7B | \~700–850 ms      | 3–5 QPS          | Sequence generation (1-token)  |
| ResNet-50  | \~400 ms          | 10–12 QPS        | Image classification           |
| T5-small   | \~540 ms          | 6 QPS            | Text generation, decoder-heavy |

➡ Compared to Equivariant Encryption (EE), HSS-EE adds \~1.5× latency due to dual-server parallelism.\
➡ Compared to vanilla inference, HSS-EE remains **2–3× faster than MPC or HE-based protocols** for similar security guarantees.

***

### 🛡️ Threat Model

HSS-EE assumes:

* **At most one server is compromised** (non-collusion assumption)
* User-side preprocessing is trusted (input embedding and splitting)
* Transport is secure (e.g., TLS or VPN)

Even if one server is malicious:

* It sees only a random-looking vector (a share)
* It cannot reconstruct the plaintext input
* It cannot reverse-engineer intermediate states

> HSS-EE raises the security bar while keeping inference scalable and GPU-compatible.

***

### 🧭 Summary

**HSS-EE enables secure, two-server inference over encrypted inputs** with near-native performance:

* Zero TEE requirement
* No single point of failure
* End-to-end secret-shared encrypted inference
* GPU-native implementation

HSS-EE is the **cryptographic backbone** for strong privacy in decentralized inference, particularly when users demand **split trust**.


# Background and Exploratory Notes

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Split-Flow is an orchestrator protocol that implements a dual-strategy to preserve confidentiality and ensure computation verifiability in Nesa's decentralized inference network. It constitutes an intelligent task-directed allocation system that leverages both hardware and cryptographic composites, whose employment is determined by an automated assessment mechanism based on input sensitivity, computational burden, model-oriented criteria, and consensus conformity parameters.

At its core, the Split-Flow Protocol operates by dissecting the workflow of any given computation into two principal streams: the confidentiality stream and the verifiability stream.

These streams are aligned with security controls that respond dynamically to variable requisites of the data model and inference objectives, yielding an efficient, secure, and verifiable computation cycle.

***

### The Confidentiality Stream <a href="#the-confidentiality-stream" id="the-confidentiality-stream"></a>

The confidentiality stream utilizes a dual-modality operation to tackle the problem that traditional static encryption poses to computation. Upon initial assessment, the model size and computational complexity dictate whether a TEE-hosted enhanced node or cryptographic constructs take precedence, and the extent of composite interplay.

***

### The Verifiability Stream

To buttress the protocol’s trust in computation outcomes, Split-Flow utilizes ZKPs to establish the correctness of computations without any requirement for data disclosure. It does so in a combinative nature, in concert with the confidentiality measures of both composites to ensure a system that maintains user privacy while concurrently producing attestable, accurate results.

***

### Protocol Operation Workflow <a href="#protocol-operation-workflow" id="protocol-operation-workflow"></a>

Upon receiving a query request, the Split-Flow Protocol stratifies and directs the inference task through its security controls:

1. **Automated Evaluation:** The protocol first appraises task characteristics – sensitivity, model size, computational complexity, and desired consensus.
2. **Confidentiality Routing:** Based on the assessment, an optimal privacy approach is selected, engaging either hardware or cryptographic composite or a hybrid blend as warranted by the task.
3. **Verifiability Assurance:** Concurrently, ZKPs are orchestrated to align with the chosen confidentiality mode, ensuring that computations are demonstrably accurate without revealing sensitive data.
4. **Result Synthesis:** The multi-party computations are conducted within the confines of the confidentiality construct, producing aggregate inference data.
5. **Validation:** Results are aggregated and validated to ensure correctness and avert any adversarial influence, at which time they are rolled up for settlement


# Hardware Side: Trusted Execution Environments (TEEs)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Trusted Execution Environments (TEEs) play a crucial role in establishing security and privacy within Nesa's decentralized inference architecture. Through the utilization of TEEs, we create secure isolation zones within the network's nodes, guaranteeing the privacy and accuracy of data and computational operations.

**Ensuring Secure Node Operations Through TEEs**: To ensure the protection of sensitive processes and data within nodes from unauthorized access, including the node operators themselves, TEEs provide an aggressive isolation mechanism. The significance of isolation is of utmost importance in a decentralized setting where the inference of AI models is spread among multiple owners. The establishment of secure enclaves by TEEs effectively mitigates the potential for external entities to see or manipulate computational steps, hence substantially diminishing the likelihood of data breaches or manipulation.

**Enhancing Hardware Security With Diverse TEE Implementations**: Adaptability and resilience in security measures are guaranteed by our dedication to a wide range of TEE technologies. This diversity enables us to leverage the most appropriate TEE technology for each node based on its computational capabilities. This also allows for a more inclusive and resilient AI ecosystem, where even nodes with limited resources can contribute as validators, thereby fostering a more robust and inclusive AI community.

**Achieving End-to-End Encryption Across Nodes**: TEEs facilitate end-to-end encryption, which is an essential component of Nesa's security architecture. In keeping with our commitment to protecting data privacy and security in a decentralized AI environment, this encryption makes sure that data stays private as it moves across the network from input to model output.

**Establishing Trust and Verification Through Attestation**: Nesa's network attestation protocols are essential to establishing decentralized trust. Nodes undergo a consensus protocol to validate their TEEs against predefined security standards. In order to safely integrate new nodes into the network, the attestation process entails producing a report that verifies the node's compliance.

The attestation procedure ensures that nodes distribute secret shares based on:

$$p(x) = s + \sum\_{i=1}^{t} r\_i x^i,$$

where $$s$$ represents the shared secret, and $$r\_i$$'s are randomly selected coefficients.

By keeping only a part of the secret on each node, this cryptographic technique improves network security by preventing any one node from gaining access to the entire key.

**Balancing Security with Inclusivity**: TEEs greatly improve security, but are not always available. Therefore, Nesa's architecture is inclusive, enabling nodes without TEEs to function as validator nodes or take part in certain inference activities with extra encryption protocols. This flexibility fosters a structured and varied decentralized AI environment, balancing inclusivity and security.


# Trusted Execution Environments (TEEs)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

To address the challenges of privacy and verifiability, our system leverages specialized hardware provisioned with enhanced security features for both CPU and GPU to fortify computation nodes. Some nodes in the NES network are designated as enhanced nodes equipped with TEEs, which offer a secure enclave for processing sensitive data. This setup is particularly adept at protecting the user’s input from exposure while still enabling computation.

Complimentary to the hardware requirement, Nesa relies on a threshold cryptosystem, because the user submits a request that is publicly accessible, hence the request should contain encrypted information that can be decrypted (in secure memory) by a randomly selected committee. Basically, in a (t, n)-threshold cryptosystem, we have:

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F5gGU54Sr0ZhYdGJ0csLV%2Fimage.png?alt=media&amp;token=faa0a1b3-e9ae-4585-a1fb-0ce493396397" alt=""><figcaption><p>Nesa’s Hardware Composite. Each participating node in the inference is equipped with advanced hardware with confidential computing capability. A user can submit ciphertext in the request transaction. The ciphertext can be decrypted only inside secure memory in the committee of nodes, through threshold decryption. The decryption reveals the plaintext in the secure memory, enabling each node to continue performing subsequent inference computation.</p></figcaption></figure>

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FghL8agE82fur3quirBjI%2Fimage.png?alt=media&#x26;token=192df944-2769-42ad-b1ff-bff7e6773bda" alt="" width="563">

Here is a step-by-step breakdown of the protocol employed by our system that utilizes hardware-based solutions to ensure privacy-preserving computation shown above:

1. Inference Request Preparation: The user begins by encrypting his input data *m*,

by

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FsdW7akOV0fOHQd3T2MUn%2Fimage.png?alt=media&#x26;token=4ea0a336-a5ac-4201-9870-780ab77b8051" alt="" width="205">

using a public key that is part of a public-secret key pair associated with the enhanced nodes. This key pair is specially designed so that the corresponding secret key is not held by any single node but is rather distributed amongst the computation nodes using secret sharing techniques. The user then creates an inference request transaction, embedding the encrypted input (ciphertext) rather than plaintext data. The user also specifies that this is an inference request with enhanced privacy so that only nodes with proper hardware will participate in the committee selection.

2. Transaction Submission: The inference request transaction, containing the encrypted input, is submitted to the blockchain and queued according to the priority system outlined in Chapter 3.
3. Committee Selection: Upon reaching the head of the queue, an inference committee S is selected using the VRF technique, ensuring a fair and random choice of enhanced nodes from among those equipped with TEEs.
4. Threshold Decryption: The selected committee nodes (withsize|S|>t) retrieve the encrypted input from the transaction. Inside the secure enclaves provided by their TEEs, committee nodes collaborate to perform a threshold decryption operation. Basically, they perform

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FSmT8ec3QkoATpq0GFEIa%2Fimage.png?alt=media&#x26;token=29de1790-f2ec-4064-b0fd-da6f6ceb128d" alt="" width="326">

followed by a threshold combining

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FUPkGxX9aK5pWiXrZjS8C%2Fimage.png?alt=media&#x26;token=b3a6ae34-3972-461c-94b2-8da576b0a4af" alt="" width="326">

This process ensures that only a collective effort by the committee can reconstruct the secret key and decrypt the input, thus no single node has access to the plaintext data.

5. Inference Execution: Once decrypted, the plaintext input remains within the protected memory space of the TEEs, where the inference computation is securely executed. The TEE ensures that the computation process is isolated from the rest of the system, providing a safeguard against potential leaks or attacks.
6. Result Encryption and Submission: The output of the inference computation, still within the TEE, is encrypted with a public key provided by the user.

An encrypted inference result is then generated and submitted to the blockchain as a transaction. This result can only be decrypted by the user, maintaining the confidentiality of the data. This hardware-based solution provides strong security guarantees for user input by combining encryption, threshold decryption within TEEs, and secure computation.

The protocol addresses the dual challenges of confidentiality and verifiability by ensuring that the sensitive data is never exposed in an unencrypted form outside of the secure enclaves and that the computation is performed within an environment that is resilient to tampering.

By maintaining the secrecy of the data throughout the process and leveraging the trusted hardware, the system provides a robust framework for performing privacy-preserving computations on a decentralized network.

***

### TEE Setup and Attestation Protocol <a href="#tee-setup-and-attestation-protocol" id="tee-setup-and-attestation-protocol"></a>

To ensure that enhanced nodes with TEEs are trustworthy and properly configured, we implement an attestation protocol similar to the decentralized trust mechanisms present in Chainlink’s Oracle network. This attestation process is critical as it not only assures that the TEE is genuine and secure but also serves as the initiation protocol for new nodes entering the system. The node admission procedure is shown and discussed below:

1. Node Initialization: When a new computation node equipped with a TEE wishes to join the network, it must first perform a local attestation of its TEE. This step involves generating an attestation report that certifies the authenticity of the TEE and provides details about the environment’s configuration. This is called a quote Qte(hw, env).
2. Network Attestation: The new node then broadcasts its attestation report Qte (hw,env) to the existing nodes in the network. A threshold number (larger than t) of established nodes must validate the newcomer’s attestation report. This is a crucial step as it ensures that no single node can unilaterally admit a new member into the network, thereby decentralizing trust.
3. Secret Share Distribution: Upon successful verification of the attestation report, the existing nodes collaborate to spin up a new share of the secret key for the new node. This process utilizes secure multi-party computation protocols to ensure that the new node receives its share without any single node ever having possession of the complete secret key. The threshold secret sharing is n evaluations of a randomized polynomial

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2Fq2z8vZqAyEWXF4q5RTSQ%2Fimage.png?alt=media&#x26;token=63cfccad-9678-45e4-ab48-a4ad69ade38d" alt="" width="326">

with *s* being the secret, and *x* = 1,2,··· , *n*. Hence, to accept a new node with an index n + 1, a threshold of the existing nodes collectively evaluates the polynomial

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FsX1KatGvekm4XMudjRZs%2Fimage.png?alt=media&amp;token=e27a7474-53bb-4d10-b2b9-97411d1abdbb" alt=""><figcaption><p>New node admission. To admit a new node into the network, the new node has to attest to a number of existing nodes. Upon successful attestations, the existing nodes will collectively generate a new share of the secret key for the new node, enabling it to become a member that is capable of participating in the hardware-based secure inference procedure shown in Nesa’s Hardware Composite</p></figcaption></figure>

on a new point p(n + 1). Basically, the way to perform such an evaluation in a decentralized way is by using a distributed version of the Lagrange interpolation. Suppose we have t + 1 evaluations:

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FytbRcWsTkk4ek9dupYLA%2Fimage.png?alt=media&#x26;token=992a1ee5-c19d-4a85-b8d4-1391d2a76cdb" alt="" width="326">

where ai =p(i) is the secret shared by node i. By applying the Lagrange interpolation formula, we have:

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FfLTjSJZvC3IYZyyZCV7t%2Fimage.png?alt=media&#x26;token=d61525ee-de1f-488b-abbd-a98c9bff8809" alt="" width="326">

where λj is the Lagrange interpolation coefficient:

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2F1MvRhoep5dxnorVDckS2%2Fimage.png?alt=media&#x26;token=53204bcc-abfd-40d6-9857-689901a853a1" alt="" width="326">

Note that *aij λ j can be computed locally by node ij*. Therefore each node can compute a Lagrange interpolation term and send it to the new node that will aggregate and obtain p(n + 1) as a new share of the secret.

4. Key Share Integration: The new node integrates the received share of the secret key into its TEE. With the combination of the key share and the TEE’s secure en- clave, the node is now capable of participating in threshold decryption operations as part of an inference committee.
5. Node Admission: The node is now considered a trusted member of the network and can participate in inference tasks. For ongoing assurance, the attestation process can be periodically repeated to confirm the integrity of the TEE.

The attestation and key share distribution processes are essential for maintaining a secure and decentralized environment, preventing any single point of failure in the security model. Each node’s TEE serves as a strong anchor of trust, with the assurance that it has not been tampered with and is running the correct software.

By distributing the responsibility of attesting and generating secret shares across multiple nodes, we ensure that the system remains resilient and can dynamically adapt as new nodes join or leave the network.

This subsection outlines how TEE attestation is integral to ensuring that all computation nodes meet the stringent security standards required to protect the confidentiality and integrity of user data, resisting any form of participant collusion.


# Software/algorithm Side: Data Encryption

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

In the digital age, where data security and privacy are critical, the need to protect user data within decentralized inference systems like Nesa cannot be overstated. As decentralized systems distribute computational tasks across various nodes, each potentially operated by different entities, the risk of exposing sensitive user data during the inference process intensifies. Therefore, ensuring user data's confidentiality and integrity becomes a cornerstone of trust and reliability in such systems. This section discusses our vision and implementation of homomorphic encryption and split learning to achieve this goal.


# Visioning: Homomorphic Encryption

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Homomorphic Encryption (HE) stands at the frontier of secure data processing, offering the strong capability to perform computations on encrypted data, denoted as $$Enc(data)$$, without decryption. This form of encryption, defined through operations $$\oplus$$ and $$\otimes$$ that correspond to addition and multiplication on encrypted data, ensures that $$Enc(a) \oplus Enc(b) = Enc(a+b)$$ and $$Enc(a) \otimes Enc(b) = Enc(a \times b)$$, for any data $$a$$ and $$b$$. The appeal of HE lies in its ability to maintain data in a secure, encrypted state, $$Enc(data)$$, throughout the computation process, thus safeguarding the confidentiality of sensitive information.

Applying HE within the context of LLMs in decentralized inference systems paints a visionary landscape. In such a setting, HE could enable the privacy and security of data inputs and outputs, represented as $$Enc(x)$$ for inputs and $$Enc(y)$$ for outputs, facilitating complex computations by LLMs without revealing the underlying user data. This capability is particularly crucial in decentralized systems, where ensuring data privacy and security is the key, yet the collaborative nature of training and utilizing LLMs necessitates secure, distributed computation.

However, integrating HE with LLMs for decentralized inference is embryonic and challenging. The foremost obstacle is the computational overhead introduced by HE operations, which, given the voluminous size and computational requisites of LLMs, renders real-time or near-real-time inference an infeasible task. The operations on encrypted data, especially when considering the iterative and complex nature of LLMs, encapsulated by functions $$f\_{\theta}(Enc(x)) = Enc(y)$$, demand significant computational resources. Moreover, adapting HE to accommodate the dynamic, iterative processes inherent in LLM training and inference within decentralized frameworks adds complexity.

Despite these obstacles, the aspiration to leverage HE for ensuring SP in LLM applications within decentralized systems remains a potent driver of innovation. Acknowledging the current practical challenges of implementing HE for LLMs in decentralized settings, the narrative evolves towards exploring pragmatic methodologies for secure data processing. This journey leads to adopting Split Learning as a tangible approach to achieving data privacy and security in decentralized inference systems.


# Implementation: Split Learning (HE)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Recognizing the challenges posed by encrypting data for use in decentralized inference systems, Nesa adopts Split Learning (SL) as a pragmatic solution to facilitate secure and efficient computation on encrypted data. Traditional encryption methods, while securing data at rest and in transit, render it unusable for direct computation by obscuring its format and structure. This limitation is particularly problematic for processing with LLMs within a decentralized framework, where data privacy cannot be compromised.

Split Learning addresses these concerns by partitioning the computational model, allowing for data to be processed in parts without revealing sensitive information. In essence, the user data is protected by not being directly transmitted to any nodes -- only the data embeddings are being passed around, and each node will only be accessing the embeddings of certain layers.

Consider a neural network model ( \mathcal{N} ), such as Llama 2 composed of a sequence of 32 layers ( {L\_1, L\_2, \ldots, L\_{32}} ), each with its own set of parameters ( \Theta\_i ) and activation function ( \sigma\_i ). The input to the network is ( X ), and the output of the (i)-th layer, given input ( x\_i ), can be mathematically described as:

$$
a\_i = L\_i(x\_i; \Theta\_i) = \sigma\_i(W\_i x\_i + b\_i)
$$

where ( W\_i ) and ( b\_i ) are the weight matrix and bias vector of the (i)-th layer, respectively, and ( \sigma\_i ) is a nonlinear activation function such as ReLU, sigmoid, or tanh.

Assuming the model is split at layer ( k ), where the client handles layers ( {L\_1, \ldots, L\_k} ) and the server handles layers ( {L\_{k+1}, \ldots, L\_{32}} ). The client computes the intermediate representation ( Z ) as follows:

$$
Z = \sigma\_k(W\_k \cdot \sigma\_{k-1}( \ldots \sigma\_1(W\_1 X + b\_1) \ldots ) + b\_k)
$$

This intermediate representation ( Z ) is then transmitted to the server, which continues the computation:

$$
Y = \sigma\_{32}(W\_{32} \cdot \sigma\_{31}( \ldots \sigma\_{k+1}(W\_{k+1} Z + b\_{k+1}) \ldots ) + b\_{32})
$$

To include the loss function ( \mathcal{L}(Y, Y\_{true}) ) for computing the error between the network output ( Y ) and the true labels ( Y\_{true} ), and the gradient of the loss with respect to the model's parameters through backpropagation:

$$
\frac{\partial \mathcal{L}}{\partial \Theta\_i} = \text{ChainRule}\left(\frac{\partial \mathcal{L}}{\partial Y}, \frac{\partial Y}{\partial a\_{32}}, \ldots, \frac{\partial a\_i}{\partial \Theta\_i}\right)
$$

For privacy concerns during the transmission of ( Z ) from client to server, differential privacy methods may be applied. Defining a privacy metric ( \mathcal{P} ) that quantifies the information leakage from the intermediate representation ( Z ), a proof of privacy preservation could demonstrate that for any ( \epsilon )-differential privacy guarantee, the information leakage remains below a threshold:

$$
\mathcal{P}(Z) \leq \epsilon
$$

It is noted that by using differential privacy with SL, the security will be improved at the cost of inference quality. Thus, in Nesa's framework, this is defined as a tunable parameter to be decided, given the user requirements.

By leveraging Split Learning, Nesa effectively navigates the complexities of data encryption within its decentralized inference system for LLMs. This approach not only preserves the confidentiality and integrity of user data but also ensures the operational feasibility of complex model computations, demonstrating a sophisticated balance between privacy preservation and computational pragmatism.


# Software/algorithm Side: Model Verification

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

In addition to hardware-level TEE-based solutions for model verification, we will discuss our algorithmic approach to ensure model integrity. In decentralized inference systems, verifying that each node accurately executes the intended model is crucial for maintaining the integrity and reliability of the system. This verification process ensures consistency in inference results across the network, safeguards against malicious modifications of the model, and ensures adherence to privacy protocols and regulatory compliance. Moreover, it optimizes the use of computational resources, preventing wastage on incorrect or unauthorized computations, and helps manage operational costs effectively.

In the following section, we will introduce our use of z**ero-knowledge machine learning (ZKML)** and **consensus-based distribution verification (CDV)** for model verification.


# Zero-knowledge Machine Learning (ZKML)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

### **Zero-Knowledge Proofs**

On the algorithm side, Zero-Knowledge Proofs (ZKPs) are crucial in achieving the above objectives. They provide the means to confirm the authenticity and integrity of the models run by nodes, thereby providing trust among users and stakeholders in the decentralized system. Specifically, a ZKP allows a prover $$\mathcal{P}$$ to convince a verifier $$\mathcal{V}$$ that a statement is true without revealing any information beyond the statement's validity. For model verification, $$\mathcal{P}$$ demonstrates that $$\mathcal{M}$$ executed correctly on input $$x$$ to produce output $$y$$, without revealing $$x$$, $$y$$, or $$\theta$$.

#### Implementation: Zero-Knowledge Machine Learning for Private Models

Nesa supports Zero-Knowledge Machine Learning (ZKML) for selected private models such as Convolutional Neural Networks (CNNs), and we look forward to working on customized solutions for our clients. Applying ZK ML to smaller, private models offers a secure way to maintain the confidentiality of sensitive data and model parameters across decentralized systems.

To apply ZKPs to smaller, private models such as on neural networks, linear models, or decision trees, we can outline the approach as follows:

* **Model Execution**: Consider a simple linear model for demonstration:

  $$
  y = \mathbf{w} \cdot \mathbf{x} + b
  $$

  where $$\mathbf{w}$$ represents the weight vector, $$\mathbf{x}$$ is the input vector, and (b) is the bias.
* **Proof Construction**: The prover $$P$$ constructs a proof that they have calculated $$y$$ correctly using the model parameters $$\mathbf{w}$$ and $$b$$, without revealing these parameters or the input $$\mathbf{x}$$. The proof must demonstrate that:

  $$
  y = \mathbf{w} \cdot \mathbf{x}+ b
  $$

  is computed correctly, aligning with the agreed-upon model structure and parameters.
* **Verification Process**: The verifier $$V$$, upon receiving the proof, checks its validity through a verification algorithm $$\mathcal{V}$$ that confirms whether the provided (y) is consistent with the execution of $$\mathcal{M}$$($$\mathbf{x}$$; $$\mathbf{w}$$, $$b$$) without learning any specifics about $$\mathbf{w}$$, $$\mathbf{x}$$, or $$b$$.
* **Zero-Knowledge Property**: The crucial aspect of ZKPs in this context is ensuring that no knowledge other than the correctness of the model execution is leaked. This is typically achieved by structuring the proof to obfuscate the details using cryptographic techniques such as commitment schemes or garbled circuits.

By leveraging ZKPs, organizations can validate the integrity of computations in sensitive applications without exposing the underlying data or model specifics, enhancing trust and security within decentralized systems. Nesa is committed to expanding its ZK ML capabilities to include more model types and customized solutions tailored to our clients' specific needs.

#### Visioning: Zero-Knowledge Machine Learning for Large, Public Models

First, we argue that since open foundation models' parameters are already accessible from all the parties, the verification can go in a much more efficient way other than ZKML, in which costs increases significantly with model complexity.

Specifically, in the decentralized setting, ZKPs face challenges for large language models (LLMs). The primary challenge stems from the computational complexity and scalability of ZKPs when applied to the vast parameter spaces typical of LLMs, represented by $$\mathcal{M}(\mathbf{x}; \theta) = \mathbf{y}$$. Generating and verifying ZKPs for models with billions of parameters can be prohibitively expensive regarding computational resources and time, making real-time verification impractical. Moreover, the dynamic nature of LLMs, which may require continuous updates and retraining, further complicates the generation of ZKPs.

Additionally, the complexity of the inference tasks performed by LLMs introduces additional challenges in formulating ZKPs. The deep layering and non-linear operations in LLMs, e.g., transformers, represented mathematically as a composition of functions $$\mathcal{M} = f\_n \circ \cdots \circ f\_1$$, require sophisticated ZKP schemes that can efficiently handle such complexities. Existing ZKP protocols may not readily adapt to the specific requirements of verifying LLM inference while preserving privacy guarantees.

**ZKML in the Nesa System**

In summary, ZKPs present an ideal and visionary approach for ensuring model integrity and establishing trust within decentralized inference systems utilizing LLMs. The theoretical appeal of ZKPs lies in their potential to verify computations without revealing the underlying data or the specific operations performed, aligning perfectly with the privacy and security requisites of LLM applications. **Thus, we support ZKML for private models with the highest security ensurance.**

For large public models, the realization of ZKML faces substantial challenges today, primarily due to the computational complexity, scalability issues, and the sophisticated nature of LLMs. As such, while ZKPs remain a compelling direction for future research and development, enabling their use with LLMs and other large models in decentralized systems is a goal we are actively researching and developing.


# Consensus-based Distribution Verification (CDV)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

In addition to hardware-level TEE-based solutions for model verification, we will discuss our algorithmic approach to ensure model integrity. In decentralized inference systems, verifying that each node accurately executes the intended model is crucial for maintaining the integrity and reliability of the system. This verification process ensures consistency in inference results across the network, safeguards against malicious modifications of the model, and ensures adherence to privacy protocols and regulatory compliance. Moreover, it optimizes the use of computational resources, preventing wastage on incorrect or unauthorized computations, and helps manage operational costs effectively.

### **Implementation: consensus-based distribution verification**

Given the computational and scalability challenges associated with Zero-knowledge proofs for verifying the integrity of LLMs in decentralized systems, Nesa proposes a consensus-based distribution verification (CDV) strategy. This strategy leverages the collective agreement of multiple nodes to ensure the correctness and integrity of model execution without revealing sensitive data. To provide a clear picture, we will present the idea by iterating over it step by step.

**Consensus-based Verification**: Consider a decentralized network with $$N$$ nodes, where each node $$i$$ executes the same inference model $$\mathcal{M}$$ with parameters $$\theta$$, on a given input $$x$$. The output of the model on node $$i$$ is denoted by $$y\_i = \mathcal{M}(x; \theta\_i)$$. The goal is to ensure that all nodes accurately execute the model $$\mathcal{M}$$, yielding consistent outputs.

The process can be formalized in the following steps:

1. **Redundant Execution**: A subset of the network nodes, $${1, 2, \ldots, k} \subseteq N$$, independently computes the output $$y\_i$$ for the same input $$x$$.

   $$
   y\_i = \mathcal{M}(x; \theta), \quad \forall i \in {1, 2, \ldots, k}
   $$
2. **Output Collection**: The outputs $${y\_1, y\_2, \ldots, y\_k}$$ are collected for consensus evaluation. This collection phase requires secure and efficient communication protocols to protect the integrity of the transmitted data.
3. **Consensus Determination**: Utilizing a consensus algorithm $$\mathcal{C}$$, the system evaluates the collected outputs to determine the agreed-upon result $$y\_{\text{con}}$$. The consensus result is considered valid if it satisfies a predefined criterion, such as majority agreement or a more sophisticated decision rule based on the specific properties of the outputs.

   $$
   y\_{\text{con}} = \mathcal{C}({y\_1, y\_2, \ldots, y\_k})
   $$
4. **Verification and Finalization**: If the consensus result $$y\_{\text{con}}$$ aligns with the outputs from a sufficiently large subset of nodes, the model's execution is verified. Otherwise, discrepancies indicate potential integrity issues, triggering further investigation or corrective measures.

This consensus-based approach not only facilitates the verification of model integrity across decentralized nodes but also introduces a robust mechanism to detect and mitigate the impact of faulty or malicious nodes. By leveraging mathematical rigor and algorithmic precision, Consensus-based Verification offers a viable solution to ensuring the integrity and correctness of decentralized LLM inference, complementing hardware-based protections and filling the gaps left by the impracticality of ZKPs for LLMs within Nesa's innovative ecosystem.

**Taking Model Sharding into Account**: In Nesa's decentralized system, where LLMs may be sharded across multiple nodes for scalability, each node $$i$$ possesses a unique shard $$\mathcal{M}\_i$$ of the complete model $$\mathcal{M}$$. This partitioning requires a specialized approach to Consensus-based Verification to accommodate the fragmented nature of model execution.

Consider the complete model $$\mathcal{M}$$ being divided into $$k$$ shards, such that $$\mathcal{M} = \bigoplus\_{i=1}^{k} \mathcal{M}\_i$$, where $$\bigoplus$$ denotes the operation of combining the model shards to represent the full model functionality. Given an input $$x$$, the execution of these shards across $$k$$ nodes produces a set of partial outputs $${y\_1, y\_2, \ldots, y\_k}$$, where $$y\_i = \mathcal{M}\_i(x; \theta\_i)$$.

**Verification in the Context of Sharding**:

1. **Shard Redundant Execution**: For each shard $$\mathcal{M}\_i$$ of the complete model $$\mathcal{M}$$, redundant execution is performed by a designated subset of nodes. Each of these nodes, within the subset responsible for shard $$\mathcal{M}*i$$, computes the output $$y*{i,j}$$ for the given input $$x$$, where $$j$$ represents the node within the subset.

   $$
   y\_{i,j} = \mathcal{M}*i(x; \theta*{i,j}), \quad \forall j \in \text{Subset of nodes for } \mathcal{M}\_i
   $$

   This step introduces computational redundancy, where multiple independent computations of the same shard aim to fortify the verification process by cross-verifying results among nodes computing the same shard.
2. **Redundant Output Collection and Verification**: The outputs $${y\_{i,1}, y\_{i,2}, \ldots, y\_{i,m}}$$ for each shard $$i$$ are collected from the nodes in its subset. A consensus mechanism $$\mathcal{C}*i$$ specific to shard $$i$$ then evaluates these collected outputs to determine a shard-specific agreed-upon result $$y*{\text{con},i}$$.

   $$
   y\_{\text{con},i} = \mathcal{C}*i({y*{i,1}, y\_{i,2}, \ldots, y\_{i,m}})
   $$

   Here, $$m$$ denotes the number of nodes executing the shard $$\mathcal{M}\_i$$. The redundancy in computation across these nodes allows for a robust verification mechanism, enhancing the detection of discrepancies or faults.
3. **Shard Verification Completion**: Upon achieving consensus for a shard $$i$$, signified by the result $$y\_{\text{con},i}$$, the process ensures the integrity of the shard's computation before proceeding. This step-by-step verification across shards, with redundancy in each shard's computation, significantly reduces the risk of erroneous or malicious model execution.
4. **Model Reconstruction**: After each shard has been independently verified, the shard-specific consensus results $${y\_{\text{con},1}, y\_{\text{con},2}, \ldots, y\_{\text{con},k}}$$ are combined to reconstruct the final model output $$Y\_{\text{final}}$$. This comprehensive output can ensure the integrity of the complete model execution.

   $$
   Y\_{\text{final}} = \bigoplus\_{i=1}^{k} y\_{\text{con},i}
   $$

**Selective Random Verification**: To optimize the CDV process with model sharding, Nesa employs a strategic, probabilistic method for selecting nodes for verification, termed selective Random verification (SRV). Instead of exhaustively verifying the outputs from all sharded model parts across the network, SRV focuses on a randomly chosen subset of nodes. This significantly reduces the computational overhead and network traffic involved in the verification process, making it more scalable and efficient, particularly suitable for large-scale deployments. The SRV process can be formalized as follows:

1. At each inference task, a verification subset $$V \subset {1, 2, \ldots, k}$$ is randomly selected, where $$k$$ is the total number of nodes (or model shards), and $$V$$ represents the indices of nodes chosen for verification. Note this process can be achieved by our VRF Module (Verifiable Random Function).
2. Only the outputs $$y\_i$$ from nodes $$i \in V$$ undergo the verification process:

   $$
   y\_i = \mathcal{M}\_i(x; \theta\_i), \quad \forall i \in V
   $$
3. A consensus mechanism $$\mathcal{C}$$ evaluates the partial outputs from the selected subset to ascertain the model's integrity:

   $$
   y\_{\text{con}} = \mathcal{C}({y\_i | i \in V})
   $$
4. If the consensus outcome $$y\_{\text{con}}$$ aligns with expected results, the integrity of the model execution within the sampled subset is confirmed. Inconsistent results trigger a more extensive investigation, potentially leading to a wider verification scope.

**Consensus-based Distribution Verification**: Building upon traditional consensus mechanisms, the CDV strategy introduces an advanced layer of verification by assessing the statistical distribution of model outputs across a decentralized network. This approach is ideally suited for scenarios where the model is not monolithic but is instead distributed as shards across multiple nodes.

CDV is based on the understanding that while individual outputs from model shards might exhibit slight variability due to the stochastic nature of ML models and the complexity of input data, the collective output distribution should maintain consistency. This consistency holds true provided that the model and its inputs remain unchanged. By evaluating the aggregated statistical characteristics of these outputs, CDV furnishes a sophisticated and robust framework for affirming the uniformity and integrity of the model's behavior, thereby enhancing SP without direct comparison of individual inference results.

**Detailed Implementation of CDV**: Implementing CDV within Nesa's ecosystem involves a multi-faceted approach:

* **Sharded Execution and Output Synthesis**: In the initial phase, each node, housing a shard $$\mathcal{M}\_i$$ of the overarching model $$\mathcal{M}$$, executes its segment on a shared input $$x$$, generating partial outputs $${y\_1, y\_2, \ldots, y\_k}$$. These outputs are synthesized to construct a comprehensive output profile that reflects the combined inference result of the entire model.
* **Advanced Statistical Aggregation**: Following output synthesis, the system embarks on advanced statistical analysis, deriving metrics such as the mean $$\mu$$, standard deviation $$\sigma$$, and potentially higher-order moments. This stage may also incorporate non-parametric statistics to capture the full essence of the output distribution, offering a nuanced view of the model's performance landscape.
* **Rigorous Distribution Comparison**: Utilizing sophisticated statistical methodologies, the derived metrics are juxtaposed with predefined benchmarks or dynamically established norms. Techniques such as hypothesis testing, divergence measures, or similarity indices evaluate the congruence between the observed and expected output distributions, facilitating an objective assessment of model integrity.
* **Enhanced Consensus Mechanism with Adaptive Thresholding**: The core of CDV lies in its consensus mechanism, where nodes collectively determine the acceptability of the observed distribution's alignment with benchmarks. Adaptive thresholding plays a crucial role here, dynamically adjusting sensitivity based on historical data and operational context to pinpoint deviations that truly signify integrity breaches.

Through its implementation, CDV offers a powerful solution to the challenges of verifying the integrity of distributed LLMs in Nesa's decentralized framework. By focusing on distributional characteristics rather than discrete output values, CDV not only elevates the verification process but also aligns with the goals of enhancing model security and maintaining stringent privacy standards.


# Privacy Technology

This section provides a deeper look at some of the security and privacy technologies mentioned throughout the book.

{% content-ref url="/pages/l1uP0QoJxyx01eN0bEia" %}
[Trusted Execution Environment (TEE)](https://docs.nesa.ai/nesa/major-innovations/private-inference-for-ai/background-and-exploratory-notes/privacy-technology/trusted-execution-environment-tee)
{% endcontent-ref %}

{% content-ref url="/pages/zG4OPaBxWi9dZuQt9egB" %}
[Secure Multi-Party Computation (MPC)](https://docs.nesa.ai/nesa/major-innovations/private-inference-for-ai/background-and-exploratory-notes/privacy-technology/secure-multi-party-computation-mpc)
{% endcontent-ref %}

{% content-ref url="/pages/DRGgNhcrweN5feK6GtmC" %}
[Verifiable Random Function (VRF)](https://docs.nesa.ai/nesa/major-innovations/private-inference-for-ai/background-and-exploratory-notes/privacy-technology/verifiable-random-function-vrf)
{% endcontent-ref %}

{% content-ref url="/pages/Qa7pnQvakXmS0mWZxlXt" %}
[Zero-Knowledge Proof (ZKP)](https://docs.nesa.ai/nesa/major-innovations/private-inference-for-ai/background-and-exploratory-notes/privacy-technology/zero-knowledge-proof-zkp)
{% endcontent-ref %}


# Trusted Execution Environment (TEE)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Central to our project’s commitment to privacy and security in the evaluation of AI models is the integration of TEEs. TEEs provide a secure area within a main processor, ensuring that sensitive data and operations are insulated from the rest of the system. Within our project, this secure environment is utilized to perform computations on encrypted private user data during the AI inference process. By leveraging TEEs, we ensure that the data, although processed by the inference committee, remains confidential and tamper-proof throughout the entire inference lifecycle.

This approach means that none of the sensitive information is exposed to any of the inference nodes to preserve the integrity and secrecy of the data. The inference committee, composed of a pre-selected set of nodes, is responsible for collaboratively conducting AI model inference without having direct access to unencrypted data. This creates a robust framework that facilitates user privacy while enabling secure and reliable model evaluations in a decentralized environment, turning our vision of secure and private AI computation into a tangible reality.

Building upon the concept of the TEE, there are several implementations of TEE technologies designed to cater to different types of processing units and their respective architectures. In the CPU domain, prominent players have advanced their offerings to provide robust security solutions:

* Intel’sTrustedDomainExtensions(TDX) is designed to enhance the security of virtual machines by providing hardware-level isolation capabilities. TDX creates private regions of memory, known as Trusted Domains, which help to protect code and data from external threats and unauthorized system software.
* AMDCPUscountersecuritythreatswithSecureEncryptedVirtualizationwith Secure Nested Paging (SEV-SNP). This technology adds strong memory integrity protection capabilities to the already existing SEV technology, further fortifying virtual machine isolation and helping to prevent malicious hypervisor-based attacks.
* ARMCPUsintroducetheConfidentialComputeArchitecture(CCA), which aims to fortify application security. CCA provides a secure environment for computation, ensuring that sensitive data can be processed without exposure to the risk of interception or tampering by other software, including the operating system.

In the GPU landscape, NVIDIA has made significant strides with their Hopper H100 GPU architecture which supports confidential computing. The H100 GPU integrates with the aforementioned CPU TEE technologies, ensuring a secure and seamless interaction between the processing units. This integration allows for the extension of TEE’s security benefits into the realm of high-performance computing, making it possible to securely process complex AI and machine learning workloads that require the parallel processing power of GPUs.

These TEE technologies form a multi-layered defense strategy, providing a secure computing backbone for models deployed on Nesa. By leveraging the strengths of each technology, we create a hybrid and interoperable secure environment capable of handling a diverse array of computingcompute demands while maintaining a stringent security posture for confidential computing.


# Secure Multi-Party Computation (MPC)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Nesa employs Secure Multiparty Computation (SMPC or MPC) for provable cryptographic security across the network. SMPC is a cryptographic protocol that enables multiple parties to jointly compute a function over their inputs while keeping those inputs private. Each participant in the computation has a piece of the overall data puzzle, yet none can see the other parties’ pieces. This method ensures that intermediate information remains undisclosed to any participating party throughout the process, with only the final output being revealed to the designated recipient.

On Nesa, this is crucial for tasks where both data privacy and collaboration are necessary. However, due to the intensive computational requirements generally associated with SMPC, we have optimized its application to be restricted to lightweight tasks throughout the network. This selective application allows us to benefit from the strong provable cryptographic security guarantees of SMPC where it matters most, without overwhelming the system with undue computational processing demands.

As a result, our project not only adheres to rigorous security standards but also maintains a high level of practicality and performance efficiency when handling the strictest data confidentiality measures.


# Verifiable Random Function (VRF)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

An additional cryptographic primitive utilized in the Nesa Execution layer is the Verifiable Random Function (VRF). VRFs are pivotal for the generation of unbiased and unpredictable random values that are also verifiable by any party with public information. A VRF is a construct that allows its holder to provide proof that a number was generated in a truly random and secure manner, akin to a cryptographic lottery that cannot be rigged.

On Nesa, VRFs are utilized to enhance the security and fairness of node selection processes. When executing AI tasks, the committee of nodes responsible for these tasks must be chosen without any bias or manipulation. VRFs serve this purpose by allowing for the secure and fair selection of the inference committee. Each node generates a random number with its private VRF key and publishes both the number and its proof. The verifiability aspect of VRFs ensures that all other nodes or participants can independently verify the correctness of the random number, ruling out any foul play in the selection process.

This mechanism preserves the decentralization ethos of Nesa by preventing central authorities from controlling the selection process but also instills confidence in the network participants. This ensures that each AI task is processed by a randomly chosen, yet reliably determined, committee of nodes, which upholds the integrity and unpredictability of the selection protocol for the guarantee of increased transparency and security over assumptions of good intent.

We briefly give some more details about VRF below. It consists of three functions: keygen, evaluate, and verify.

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FWnf6dCQxsKPVNNXy16Lo%2Fimage.png?alt=media&#x26;token=bf0ffcba-9d45-41e5-afaf-b70cbb94c04d" alt="" width="100%">


# Zero-Knowledge Proof (ZKP)

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Finally, Zero-Knowledge Proofs (ZKP) is a foundational core cryptographic technique employed in the Nesa network, complimenting hardware-based security implementations. ZKP enables one party, the prover, to demonstrate to another party, the verifier, that a certain statement is true without revealing any information beyond the validity of the statement itself.

There are some notable examples of ZKP adopted in blockchain applications. Zcash, for instance, utilizes ZKP to enable private transactions on a public blockchain. By using zk-SNARKs (zero-knowledge succinct non-interactive arguments of knowledge), Zcash allows users to conceal transaction details such as the sender, receiver, and amount, while still verifying the transaction’s legitimacy.

Ethereum is also exploring the implementation of ZKPs to enhance scalability and privacy on the platform. Other projects like zkSync and Hermez use ZKP to batch transactions off-chain and then settle them on-chain, providing scalability solutions without compromising on security.

**On Nesa, ZKP plays a pivotal role in several key areas:**

* **Interfacing with Smart Contracts:** Drawing inspiration from projects like Chainlink but applying it to small and large-scale AI inference requests, we leverage ZKP to build secure protocols that enable the feeding of off-chain data into on-chain smart contracts. This mechanism ensures that smart contracts can access the necessary data for AI model execution while maintaining the confidentiality of the off-chain data sources.
* **Privacy-Preserving Computation:** We implement ZKP to perform computations on private models and data without revealing any underlying sensitive information. This approach is crucial for preserving the privacy of user data and proprietary AI models throughout the inference process. By employing ZKP, we can provide cryptographic assurance that the computation was executed correctly, without exposing the data to external parties.

The integration of ZKP in our system architecture enables private on-chain interactions and confidential computing while providing an easy and accessible channel where users and enterprises can confidently engage with blockchain technology. This alignment of transparency with confidentiality paves the way for broader adoption and trust in Nesa's decentralized system as it evangelizes AI on-chain around the world.

Split-Flow harmonizes the sometimes simultaneous need for these privacy technologies above through its automated evaluation system that analyzes factors such as input sensitivity, workload, model specifics, and consensus criteria to ascertain whether hardware-based secure enclaves, cryptographic techniques, or a combination of the composites should primarily handle data processing.

The adaptability of the Split-Flow protocol allocates processes between a confidentiality-preserving stream and a verifiability-focused one, with security measures tailored to match the dynamic demands of varying data models and inference goals, as well as the model’s size and computational intensity, creating a balanced and secure operational state across these heavy security technologies.


# Decentralized Execution for AI

Nesa's decentralized inference process is the cornerstone of our autonomous AI oracle network, enabling the first trustless environment where AI computations are performed transparently and reliably on-chain.

This section outlines the design of Nesa's decentralized inference framework, which is composed of several core components: users who submit inference requests, chain contracts responsible for the verification and aggregation of results, and nodes that process these requests.

This framework leverages a two-phase transaction structure, utilizing a commit-reveal paradigm, to safeguard against dishonest behavior and free-riding. This ensures that nodes are incentivized to perform their computations honestly and that users can trust the integrity of the inference results.

The system maintains a decentralized approach by employing smart contracts for the key processes of verification and aggregation, allowing for a scalable network that harnesses the collective computational power of its participants.


# Why Decentralized AI?

The capabilities of foundation models continue to advance rapidly, yet the infrastructure powering them remains highly centralized. Most large-scale AI models today are trained, hosted, and *served by a small number of cloud providers and private labs*. While these centralized systems deliver strong performance, they come with structural limitations that increasingly constrain access, transparency, and trust.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F3fSvB9UgNFibm7Q3kxNF%2Fimage.png?alt=media&amp;token=34d50cad-b335-4533-a7f6-a67badc0a66a" alt=""><figcaption><p>Source : Langchain 2024 State of AI, <a href="https://blog.langchain.com/langchain-state-of-ai-2024/">https://blog.langchain.com/langchain-state-of-ai-2024/</a></p></figcaption></figure>

For many users, even open-source models are effectively out of reach. The infrastructure required to serve LLaMA or Mixtral in production—high-memory GPUs, low-latency scheduling, and scalable batching systems—remains tightly coupled to closed deployments. This creates a growing divide between those who can build with cutting-edge models and those who cannot.

More importantly, centralization introduces serious risks. Users must trust that their data will not be stored or repurposed. Developers cannot audit how a model was hosted, fine-tuned, or changed over time. Access can be revoked without warning, and outages from a single provider can bring down entire applications.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Ff7134jvpxQZmTcspEOTi%2Fimage.png?alt=media&amp;token=90fc2e18-2d8e-4c10-8569-9bb4a923124c" alt=""><figcaption><p>AP News: ChatGPT violated European privacy laws, <a href="https://apnews.com/article/openai-chatgpt-data-privacy-italy-a6ff88b53ae611ca4dee917e872ac278">https://apnews.com/article/openai-chatgpt-data-privacy-italy-a6ff88b53ae611ca4dee917e872ac278</a></p></figcaption></figure>

Decentralized AI offers a compelling alternative. It promises an infrastructure where models are distributed, governance is community-driven, and execution can happen on commodity hardware. In theory, this would enable broader participation, stronger resilience, and more accountable deployment of AI. But in practice, decentralizing AI has proven difficult.

***

### Why Existing Approaches Fall Short

Many decentralized AI proposals to date fall into one of the following categories:

* **Off-chain inference coordination.** These systems use token incentives or protocol wrappers, but the actual model execution happens on opaque servers. There is no way to verify whether the model was run correctly, or at all.
* **Heavyweight cryptographic protocols.** Secure multiparty computation or fully homomorphic encryption can theoretically protect privacy, but they are too slow for real-time inference on models with millions of parameters.
* **Poor system integration.** Even when model execution is distributed, it often requires manual setup, inconsistent runtimes, or high developer overhead. These systems lack orchestration mechanisms that work across nodes and workloads.
* **Incentive misalignment.** Some systems reward output volume without measuring correctness, which encourages junk inference or unverifiable outputs. Others provide no mechanism to penalize bad actors or prioritize quality.

These limitations are not just technical edge cases—they reflect a deeper mismatch between vision and execution. Despite strong theoretical motivation, most decentralized AI systems cannot serve large models at scale, under latency and trust constraints that real users care about.

***

### The Path Forward

To make decentralized AI viable, the system must do more than distribute tasks. It must support:

* **Efficient model partitioning** that enables devices with modest resources to contribute meaningfully
* **Scheduling and routing** that adapts to dynamic node availability and hardware heterogeneity
* **Verification and reproducibility**, so that outputs can be trusted without relying on the executor
* **Robust economic design**, aligning incentives with accuracy, uptime, and throughput

The infrastructure must be capable of hosting real-world models—such as transformers, RAG pipelines, and diffusion architectures—while preserving usability and scalability.

In the following sections, we introduce Nesa’s approach to these challenges, starting with a sharding framework that lowers the hardware barrier to serving large models.


# DAIs: Building Decentralized AI Applications on Nesa

A **DAI (Decentralized AI)** is a fully deployed and operated AI product on Nesa. Rather than exposing users to protocol-level complexity, a DAI presents a familiar product interface while running on decentralized inference, staking, and incentive infrastructure.

Nesa serves as the underlying platform that enables AI teams to launch, operate, and scale AI applications without needing to build blockchain integration, inference orchestration, or incentive mechanisms from scratch.

DAIs are designed to feel like real AI companies, not protocols.

> **Note:** Creating and managing DAIs is currently available to **Pro users only**.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fq7ouq1ix51pzXKkV98Rp%2Fimage.png?alt=media&amp;token=8a7edc91-604d-476d-9256-16a451045da9" alt=""><figcaption><p>An example DAI page on Nesa, showing staking, activity, and on-chain metrics.</p></figcaption></figure>

***

#### Nesa as Infrastructure for AI Companies

Nesa provides end-to-end infrastructure that supports the full lifecycle of a DAI, from initial launch to long-term growth. This includes decentralized inference, on-chain coordination, incentive design, and user-facing product primitives.

By abstracting away infrastructure complexity, Nesa allows teams to focus on **model quality, product experience, and user adoption**, while the platform handles execution, coordination, and trust.

***

### Why Build DAI on Nesa?

Building an AI product is no longer just about model quality. Teams must also solve inference cost, distribution, credibility, and long-term alignment. Nesa provides an integrated platform that addresses these challenges natively, allowing DAIs to launch and grow as real AI businesses rather than standalone demos.

#### Subsidized Inference

Nesa can subsidize inference costs for DAIs during early stages, lowering the barrier to user adoption and experimentation. This allows teams to validate product value, collect usage signals, and iterate with real users before usage-based revenue or token incentives fully materialize—all while running on decentralized inference infrastructure.

#### Visibility and Discovery

DAIs launched on Nesa can be **featured and spotlighted** across the platform, giving them immediate exposure to an existing user base.

Discovery is driven by observable signals such as activity, engagement, and community participation rather than opaque curation. This helps high-quality DAIs reach users faster without relying solely on external marketing channels.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fx9zeGbc6LSsRldCWvMVf%2Fimage.png?alt=media&amp;token=57397d3f-b645-4636-a4db-3a42158a7987" alt=""><figcaption></figcaption></figure>

#### Token Launch (Testnet)

Each DAI can launch its own token on **Nesa’s EVM chain**. All token-related functionality is currently on **testnet** and intended for experimentation and iteration.

Token design is flexible and may support governance, incentives, or future access control, depending on the DAI’s goals and evolution.

#### Staking and Credibility

Users can stake **$NES** (from Nesa’s Cosmos chain) against a DAI to signal confidence in its long-term value.

Staking functions as a public credibility signal:

* Higher stake reflects stronger community confidence
* DAIs with meaningful stake may receive increased visibility or trust signals
* Stakers align their incentives with the long-term success of the DAI

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FlWgFjCgAoPjOXIW4ZYVl%2Fimage.png?alt=media&amp;token=dd98b215-0cf9-4608-87a8-b29e358ebc89" alt=""><figcaption></figcaption></figure>

#### Takeaway

Nesa allows AI teams to combine **decentralized inference, native distribution, token experimentation, and staking-based trust** into a single product surface—without building the underlying infrastructure themselves.

Start building DAI with Nesa today!

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F6tv9UOw1fLymekbMkpN4%2Fimage.png?alt=media&amp;token=c007cb71-8c66-412f-82b7-f99ba2b44697" alt=""><figcaption></figcaption></figure>


# Models on Nesa: Playground and Custom Uploads

## Model Playground & Custom Models

The **Model Playground** is where developers explore, evaluate, and deploy models on Nesa. It combines an extensive on-chain model catalog with the ability to upload and operate custom models directly on the network.

> **Note:** Custom model uploads are currently available to **Nesa Pro users only**. Pro users may have up to **5 custom models** active on the network at any given time.

***

### Model Playground

Nesa maintains a large and continuously growing catalog of on-chain models spanning text, image, video, audio, 3D, bio, and multi-modal tasks.

The Playground allows builders to:

* Browse and compare models by modality and task
* Inspect performance signals such as latency and usage
* Select models for use in DAIs or downstream applications

All models in the Playground run on Nesa’s decentralized inference infrastructure, providing consistent execution and observable performance.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FSjPd3deRU2DPHAOf2zVt%2Fimage.png?alt=media&amp;token=5733e2cb-f759-4c31-9e22-e8bd693eefd1" alt=""><figcaption></figcaption></figure>

***

### Extensive Model Support

The Model Playground provides access to a **large, heterogeneous catalog of production-ready models**, spanning language, vision, audio, and video workloads. Models are exposed as first-class on-chain assets, each with clear metadata, performance signals, and usage characteristics.

Out of the box, the Playground includes:

* **Text and reasoning models**\
  Instruction-tuned and reasoning-focused LLMs (e.g., Llama, Qwen, DeepSeek, GPT-family variants) optimized for dialogue, coding, retrieval, and multi-step reasoning, with visible latency and usage statistics.
* **Image generation models**\
  Diffusion and DiT-based models for artistic, photorealistic, and design-oriented generation (e.g., anime-style illustration, typography-aware posters, fast preview models), supporting a wide range of resolutions and inference speeds.
* **Video generation models**\
  Short- and medium-horizon video models designed for cinematic content, storytelling, and animation, with different trade-offs between quality, latency, and clip length.
* **Audio and speech models**\
  Models for speech synthesis, music generation, and audio understanding, exposed with consistent inference and deployment interfaces.
* **Multi-modal and domain-specific models**\
  Models that combine text, vision, or audio inputs, as well as specialized models tuned for branding, design, reasoning, or creative workflows.

Each model card surfaces **practical signals** such as:

* Average inference latency
* Community usage and ratings
* Supported modality and task
* Selection and deployment status

This allows teams to **compare, prototype, and deploy models quickly** without managing hosting, scaling, or execution pipelines themselves, while retaining the option to upload and operate custom models when needed.

***

### Uploading Custom Models

In addition to the public catalog, Nesa allows developers to **upload custom models** and run them on the network.

Custom models can be registered through the **Build on Nesa** flow and configured using:

* A Docker image or GitHub repository
* Model metadata and description
* Modality and task definitions
* Visibility and access settings

Once uploaded, custom models become first-class citizens on the network and can be used by DAIs or other applications.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fyq52CTvohrIGpHMWyR1F%2Fimage.png?alt=media&amp;token=6cedc13b-ce84-48e7-bb41-425e7e58ad27" alt=""><figcaption></figcaption></figure>

> **Pro access:** Custom model uploads require a **Nesa Pro** account. Each Pro user may register up to **5 active custom models** at a time.

***

### Consistent Execution and Presentation

Uploaded models follow Nesa’s standardized execution and presentation pipeline. This ensures:

* Consistent inference behavior across models
* Unified UI and metadata for discovery
* Compatibility with DAIs, staking, and incentives

Optional features such as encryption, visibility controls, and future access policies can be configured per model.

***

### Summary

The Model Playground gives builders immediate access to a broad ecosystem of on-chain models, while custom model upload enables teams to deploy proprietary or specialized models without operating their own infrastructure.

Together, these capabilities make Nesa a practical environment for building, testing, and scaling decentralized AI applications.


# Trust and Incentives: Miner Reputation

In decentralized inference, miners vary in reliability and responsiveness, and the system cannot know this in advance. Treating all miners equally would reward unreliable behavior and penalize dependable ones.

**Nesa uses incentives to make reliable and efficient behavior consistently more profitable than unreliable behavior.**

***

### Core Principle

> **Miners who deliver correct and timely results should receive more opportunities and higher long-term rewards.**

This principle is implemented through a continuously updated reputation score rather than manual rules or centralized control.

### How Incentives Work

Reputation summarizes observed miner behavior and directly affects outcomes that matter:

* **Task assignment:** higher-reputation miners are selected more often
* **Failure cost:** timeouts and non-responses reduce future opportunities
* **Recovery:** occasional failures are tolerated, persistent issues are deprioritized

From a miner’s perspective:

> Better performance → higher reputation → more tasks → higher rewards

***

### Design Goals

The miner reputation system is designed to be:

* **Fast to compute** (per request)
* **Fair across modalities** (LLMs, diffusion, evolution models, etc.)
* **Robust to failures** (timeouts and non-responses)
* **Recoverable** for miners with temporary issues
* **Extensible** to future validation signals (e.g., output correctness)

***

### Core Reputation Variable

Each miner maintains a reputation score:

* **Reputation** $$R \in \[0.1, 10]$$
* Initialized at $$R = 1$$
* Updated after every inference request

The reputation score directly influences:

* Miner selection priority
* Task routing tier
* Reward and penalty magnitude

***

### Top-Down Reputation Update (Orchestrated Routing)

In orchestrated settings, miners are assigned tasks by an agent or scheduler.\
Reputation is updated primarily based on **completion correctness**.

#### Update Rule

$$
R' = R \cdot \text{Pen}^{M} \cdot \text{Rew}^{1 - M}
$$

**Where:**

* $$R$$: current reputation
* $$R'$$: updated reputation
* $$M \in {0, 1}$$: mistake indicator
  * $$M = 1$$ → timeout or non-response
  * $$M = 0$$ → successful execution
* $$\text{Pen} = 0.8$$: penalty multiplier
* $$\text{Rew} = 1.01$$ (– 1.05 under evaluation): reward multiplier

#### Interpretation

* Correct behavior leads to **gradual exponential growth**
* Failures cause **multiplicative decay**
* Consistently correct miners quickly separate from unreliable ones
* Occasional mistakes are recoverable

***

### Bottom-Up Reputation Update (Bidding / Open Routing)

In decentralized or bidding-based architectures, correctness alone is insufficient.\
The system must also filter out miners that are **consistently slow or underpowered**.

To address this, the reputation update incorporates **performance metrics**.

#### Extended Update Rule

$$
R' = \alpha \cdot R \cdot \text{Pen}^{M} \cdot \text{Rew}^{1 - M}
;+;
\beta \cdot (w\_S S + w\_F F + w\_B B + w\_I I)
$$

**Where:**

* $$\alpha = 0.7$$: weight for correctness history
* $$\beta = 0.3$$: weight for performance
* $$S$$: single-sample inference efficiency (token/s per block)
* $$F$$: forward-pass throughput (batch inference)
* $$B$$: backward-pass throughput (if applicable)
* $$I$$: network responsiveness / bandwidth
* $$w\_S, w\_F, w\_B, w\_I$$: configurable weights

All performance metrics are **min-max normalized**:

$$
x \leftarrow \frac{x - x\_{\text{min}}}{x\_{\text{max}} - x\_{\text{min}}}
$$

#### Design Rationale

* Correctness remains the dominant signal
* Performance differentiates miners with similar accuracy
* Hardware-only advantages cannot overwhelm correctness
* Low-reputation miners can still recover over time

***

### Efficiency Metric $$S$$

Efficiency is measured per request as:

$$
S\_{\text{raw}} = \frac{\text{input\_size} + \text{output\_size}}{\text{actual\_time}}
$$

Normalization bounds:

* Computed **per model**, not per miner
* Window size: last 100 requests for that model
* Strict min/max bounds (percentile-based bounds under evaluation)

A rolling average is maintained per miner:

$$
S\_{\text{rolling}} \leftarrow 0.9 \cdot S\_{\text{rolling}} + 0.1 \cdot S
$$

***

### Timeouts and Mistakes

A request is considered a **mistake** ($$M = 1$$) if:

* Execution time exceeds $$1.5 \times$$ expected time
* No response within $$2 \times$$ expected time

Expected time accounts for:

* Average execution time for the model
* Input and output size scaling

Non-responses incur a **stronger penalty multiplier** than slow responses.

***

### Rewards and Penalties

#### Rewards (Successful Requests)

$$
\text{reward} = \text{base\_reward} \cdot R^{\gamma}
$$

* $$\gamma = 1.2$$ (under evaluation)
* Encourages long-term reliability

#### Penalties (Failures)

$$
\text{penalty} = \frac{\text{base\_penalty}}{R^{\delta}}
$$

* $$\delta = 0.5$$
* Prevents overly harsh punishment of high-reputation miners
* Still discourages repeated failures

***

### Reputation Bounds and Recovery

* Reputation is clamped to $$\[0.1, 10]$$
* A small **catch-up factor** helps low-reputation miners recover:
  * Encourages re-entry after transient issues
  * Prevents permanent exclusion

***

### Empirical Observations

From large-scale inference traces:

* Total response time is strongly correlated with **model loading time**
* Inference time alone correlates weakly with model size
* Performance distributions are heavy-tailed and zero-inflated

These observations motivate:

* Normalization by model size
* Separate accounting of loading vs inference time
* Careful tuning of performance weights

***

### Relationship to Miner Selection

Reputation directly affects:

* Miner tier assignment
* Selection probability in routing
* Reputation-based rewards (RBR)
* Fallback and retry ordering

The system favors **reliable miners**, but does not permanently exclude others.

***

### Summary

The miner reputation system in Nesa:

* Combines correctness and efficiency
* Adapts across models and modalities
* Supports decentralized participation
* Enables recovery from transient failures
* Remains extensible to future validation signals

This framework provides a stable foundation for **trust-aware, incentive-aligned decentralized inference**.


# Efficient Inference: MetaInf and Execution Optimization

> ⚠️ **Note on Implementation Status**
>
> This page includes descriptions of mechanisms and workflows that are **under active development or iterative refinement**. Some components may not yet be fully deployed in the current production system, and are presented to illustrate design intent and potential system directions.

Efficient inference in decentralized AI systems is a fundamental challenge. While many acceleration strategies have been proposed—such as prefix caching, chunked prefill, and continuous batching—no single method consistently performs best across all workloads, models, and hardware profiles. This is especially true in heterogeneous environments where nodes may differ in compute power, memory bandwidth, or latency constraints.

**MetaInf** is our proposed solution: a meta-learning-based scheduler that automatically selects the best inference optimization method based on real-time system and workload signals.

***

### Why Traditional Acceleration Falls Short

Experimental benchmarks show that inference acceleration methods perform variably depending on batch size and hardware. For example:

* *Prefix caching* excels in large-batch regimes.
* *Continuous batching* works better in latency-sensitive settings.
* Combining all techniques does not always yield the best outcome due to overhead.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FsEohOp6jtNN8HPqUmfxz%2Fimage.png?alt=media&amp;token=14a59fd1-789c-47ec-9d0e-7c73337e3a60" alt=""><figcaption><p> <em>Performance comparison of acceleration strategies across batch sizes on LLaMA 3.1 8B. Combining strategies excels at small batch sizes; prefix caching performs best at scale.</em></p></figcaption></figure>

***

### Introducing MetaInf

**MetaInf** is a two-stage meta-learning framework:

1. **Offline Meta-Training**\
   Learns a predictor that maps embeddings of model architecture, hardware configuration, and input data to expected inference performance.
2. **Online Scheduling**\
   Given a new task, hardware, and cost budget, MetaInf selects the method with the highest predicted performance while staying within the budget.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FOEVvV8bqTPptbNVdsLgu%2FDiagram-2.png?alt=media&amp;token=ce061f7e-f49b-467c-8c62-4f757500ca17" alt=""><figcaption><p><em>MetaInf architecture. Top: training a predictor using model, hardware, and dataset embeddings. Bottom: selecting optimal method at inference time.</em></p></figcaption></figure>

***

### Key Capabilities

* **Zero-shot generalization**: No need to re-run all inference methods—MetaInf predicts performance based on embeddings.
* **Budget-aware selection**: Accounts for runtime × hardware cost.
* **Strong empirical performance**:\
  On evaluation across four LLMs and multiple GPU setups, MetaInf outperforms both heuristic and traditional ML baselines.

&#x20;*MetaInf achieves the highest selection accuracy and lowest inference cost across all tested methods.*

***

### Results Summary

| Method             | Accuracy  | F1 Score | Acceleration Ratio |
| ------------------ | --------- | -------- | ------------------ |
| ISAC               | 0.578     | 0.60     | 1.10               |
| ALORS              | 0.725     | 0.71     | 1.20               |
| Random Forest      | 0.742     | 0.69     | 1.25               |
| Gradient Boosting  | 0.815     | 0.78     | 1.30               |
| **MetaInf (Ours)** | **0.898** | **0.85** | **1.55**           |

*MetaInf outperforms all baselines in accuracy and speedup.*

***

### Prompt Engineering & Embedding Study

MetaInf leverages LLM-based semantic embeddings to encode dataset and system features. An ablation study compares:

* One-hot encoding
* Basic descriptors (e.g., “Model: LLaMA-7B”)
* Rich structured templates
* Chain-of-thought (CoT) prompts

Results confirm the value of rich prompts and SVD-based embedding reduction for effective meta-scheduling.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FZKtY9n3fFRPE0xkiL6WN%2Fimage.png?alt=media&amp;token=9cb209db-4dd8-4e55-abe3-8fcfa153f544" alt=""><figcaption><p> <em>MetaInf performs consistently across different embedding schemes; rich prompts and CoT yield the best results.</em></p></figcaption></figure>

***

### Conclusion

**MetaInf** shows that smart scheduling—not brute-force trial and error—can unlock fast inference in complex decentralized settings. By integrating real-time inference metadata and learned representations, MetaInf provides a scalable, adaptive foundation for deploying large models across dynamic infrastructure.


# Background and Exploratory Notes


# Blockchain-based Sequential Neural Sharding (BSNS)

> ⚠️ **Note on Implementation Status**
>
> This page includes descriptions of mechanisms and workflows that are **under active development or iterative refinement**. Some components may not yet be fully deployed in the current production system, and are presented to illustrate design intent and potential system directions.

This page introduces the theoretical and practical foundations of Nesa's model sharding protocol (BSNS), including its recursive swarm assignment formulation, network-aware partitioning strategy, and dynamic rebalancing algorithm. It explains how large models are decomposed and efficiently distributed across heterogeneous infrastructure.

***

## Model Partitioning and Dynamic Sharding

Modern foundation models are massive—often exceeding the memory and compute limits of any single device. To enable distributed inference over commodity nodes, Nesa introduces a scalable, network-aware method called **Blockchain-based Sequential Neural Sharding (BSNS)**.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FLUoh6dONniU2NgMQYXTe%2Fimage.png?alt=media&amp;token=e675c2f5-4655-4e36-8beb-ff5eccdd0bd9" alt=""><figcaption><p>Overview of BSNS model sharding and inference coordination.<br><strong>(A)</strong> Available nodes are selected to form an orchestrated swarm. An orchestrator node is elected, followed by a committee of participants to execute shards.<br><strong>(B)</strong> The orchestrator partitions the computation graph across the selected nodes, assigning model blocks or operator groups to each.<br><strong>(C)</strong> During inference, each node executes its assigned shard and forwards intermediate activations, while the orchestrator ensures data flow and maintains consistency across the swarm.</p></figcaption></figure>

Rather than statically slicing layers or replicating the full model, BSNS partitions the model graph into sharded blocks and routes them across a dynamic swarm of nodes. Each node executes only its assigned segment, and intermediate activations are passed securely downstream.

***

### Sequential Sharding over Transformer Blocks

BSNS begins with a sequential decomposition of the model—usually aligned with transformer blocks. For example, a LLaMA-style model with 80 layers is broken into contiguous block segments. These blocks are assigned to nodes in a specific execution path, ensuring correct ordering and throughput.

Given a list of blocks `{b1, b2, ..., bL}` and a swarm of nodes `{n1, n2, ..., nk}`, the BSNS orchestrator builds a mapping:

> (b1 → n\_i1), (b2 → n\_i2), ..., (bL → n\_iL)

Each assignment considers node memory, available compute, and connection latency. Critically, the selection of the current node depends not only on the block’s cost, but also on where the previous shards were placed—this creates a recursive assignment path that reflects network topology.

***

### Dynamic Rebalancing

Network conditions can change quickly. To avoid bottlenecks, BSNS includes a **dynamic rebalancing function**. This periodically evaluates the current assignment of blocks to nodes and re-routes shards to better candidates based on latency, hardware capacity, and recent throughput.

Let `S` be the current sequence of shard-to-node assignments and `Θ` represent live network parameters. BSNS computes a new optimized path:

> S' = Rebalance(S, Θ)

This allows Nesa to maintain stable performance even if nodes drop, delay, or degrade during inference.

***

### Partitioning Arbitrary Neural Graphs

While BSNS works naturally with transformer stacks, it also supports arbitrary computation graphs (e.g., multimodal, convolutional, or hybrid models). A model is represented as a directed acyclic graph:

* **V**: the operations (e.g., attention layers, matrix multiplications)
* **E**: the data flow edges between them

Each operation `v` has attributes:

* `C(v)`: compute time
* `M(v)`: memory footprint
* `O(v)`: output size

The goal is to divide the graph into `k` blocks `{G1, G2, ..., Gk}` such that:

* Each block can execute independently on one node
* The resulting inter-block graph is still acyclic
* Inter-node communication is minimized

The cost of sending output from block Gi to Gj is the sum of the output sizes of all operations in Gi that are consumed by operations in Gj.

***

### Memory Overflow and Execution Cost

Each block may exceed the fast memory available (e.g., SRAM). If the block’s parameter size `P` exceeds a node’s fast memory limit `F`, overflow cost is incurred by streaming from slower memory.

The **overflow penalty** is proportional to:

> max(0, P - F) × τ

where `τ` is the streaming latency multiplier.

The **total cost of a block** includes:

* Receiving input tensors from upstream
* Local execution cost (including overflow)
* Sending outputs downstream

***

### Max-Throughput Partitioning Problem (MTPP)

The partitioning problem becomes:

> Find a partition of the graph into k blocks that **minimizes the maximum block cost**

This is an NP-hard problem. BSNS approximates the optimal solution using a combination of greedy heuristics, persistent homology metrics, and node scoring.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FXfM9yVBZlgf0LOvWmoNI%2Fimage.png?alt=media&amp;token=1bdec733-2040-41d5-9277-676f2fc1e710" alt=""><figcaption><p>Genetic algorithm-based node selection in BSNS. The orchestrator uses multi-objective optimization to evaluate candidates on distance, bandwidth, compute availability, and reliability. Offspring swarm candidates are generated and scored via crossover and mutation. The objective is to select the optimal swarm sequence for sharding a large model while minimizing cost and latency.</p></figcaption></figure>

***

### Swarm Reconfiguration in Practice

At runtime, the BSNS controller continuously monitors:

* Inference time per block
* Queue depth
* Node health and hardware usage
* Communication latency

If imbalances appear, the system:

* Replaces slow nodes with idle ones
* Reassigns heavy blocks to more capable hardware
* Selects a new sharding plan from a library of precomputed templates

This ensures graceful adaptation without reinitializing the entire inference session

***

### Empirical Performance

While BSNS is designed for scalable model execution, its practicality also depends on the performance of distributed, compressed, and multi-modal models. Below are empirical results from several experimental settings validating Nesa's infrastructure.

***

#### 1. Compression Robustness on Language Tasks

| Model        | Bits | HellaSwag   | Lambada OpenAI | Causal Judgment | Disambiguation QA | Logical Deduction |
| ------------ | ---- | ----------- | -------------- | --------------- | ----------------- | ----------------- |
| LLaMA 8B     | 16   | 0.76 ± 0.01 | 0.75 ± 0.03    | 0.63 ± 0.02     | 0.64 ± 0.04       | 0.40 ± 0.03       |
|              | 8    | 0.76 ± 0.01 | 0.74 ± 0.03    | 0.62 ± 0.03     | 0.63 ± 0.04       | 0.39 ± 0.02       |
| Mixtral 7x8B | 16   | 0.78 ± 0.01 | 0.76 ± 0.03    | 0.65 ± 0.02     | 0.66 ± 0.03       | 0.42 ± 0.02       |
|              | 8    | 0.77 ± 0.01 | 0.75 ± 0.02    | 0.64 ± 0.03     | 0.65 ± 0.03       | 0.41 ± 0.03       |
| Lexi 7B      | 16   | 0.75 ± 0.02 | 0.74 ± 0.02    | 0.62 ± 0.03     | 0.63 ± 0.04       | 0.39 ± 0.02       |
|              | 8    | 0.74 ± 0.02 | 0.73 ± 0.03    | 0.61 ± 0.04     | 0.62 ± 0.03       | 0.38 ± 0.02       |

> **Table:** Accuracy impact from 8-bit quantization is minimal across tasks and models, validating BSNS for efficient distributed inference.

***

#### 2. Latency, Bandwidth, and Token Throughput

| Model        | RTT    | Bandwidth  | Batch Size | Gen. Steps/s (64) | Gen. Steps/s (1024) | Tokens/s (64) | Tokens/s (1024) |
| ------------ | ------ | ---------- | ---------- | ----------------- | ------------------- | ------------- | --------------- |
| LLaMA-3 8B   | <5 ms  | 1 Gbit/s   | 1          | 1.20              | 1.10                | 8             | 6.5             |
|              |        |            | 32         | 1.15              | 1.08                | 28            | 26.4            |
|              |        |            | 64         | 1.10              | 1.05                | 56            | 52.5            |
|              | <10 ms | 100 Mbit/s | 1          | 0.85              | 0.80                | 6             | 5               |
|              |        |            | 32         | 0.80              | 0.75                | 22            | 20              |
|              |        |            | 64         | 0.75              | 0.70                | 44            | 40              |
| Mixtral 7x8B | <5 ms  | 1 Gbit/s   | 1          | 1.30              | 1.25                | 6             | 5.4             |
|              |        |            | 32         | 1.25              | 1.20                | 24            | 22.8            |
|              |        |            | 64         | 1.20              | 1.15                | 49            | 45.5            |
|              | <10 ms | 100 Mbit/s | 1          | 0.90              | 0.85                | 5             | 4.5             |
|              |        |            | 32         | 0.85              | 0.80                | 20            | 18.5            |
|              |        |            | 64         | 0.80              | 0.75                | 40            | 37              |

> **Table:** BSNS supports high-throughput generation across network settings by balancing shard placement and caching.

***

#### 3. Multi-Modal Model Performance (Text-to-Image)

| Category         | Model           | Fairness | Quality | Creativity | Knowledge | Performance |
| ---------------- | --------------- | -------- | ------- | ---------- | --------- | ----------- |
| Stable Diffusion | v1.4            | 0.68     | 0.86    | 0.68       | 0.68      | 0.85        |
|                  | v1.5            | 0.54     | 0.73    | 0.21       | 0.50      | 0.81        |
|                  | v2 base         | 0.51     | 0.85    | 0.20       | 0.39      | 0.88        |
| Anime-Style      | kivotos-xl-2.0  | 0.77     | 0.87    | 0.91       | 0.72      | 0.81        |
|                  | holodayo-xl-2.1 | 0.79     | 0.89    | 0.94       | 0.74      | 0.83        |
| Debiasing        | mobius          | 0.82     | 0.71    | 0.86       | 0.77      | 0.87        |

> **Table:** BSNS accommodates diverse model types. Each model is containerized and tunable for privacy, quality, or application needs.

***

### Summary

BSNS provides a principled method to decompose and distribute large models across dynamic, heterogeneous environments. Its key innovations include:

* Recursively informed shard placement based on topology and cost
* Overflow-aware memory planning for fast-access SRAM
* Graph partitioning for arbitrary architectures
* Real-time rebalancing of shard placement under changing network conditions

This framework enables Nesa to run large-scale inference on decentralized compute networks securely, efficiently, and scalably.


# Model Partitioning and Deep Network Sharding

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Due to the novelty of running deep learning algorithms on the blockchain, Nesa’s partitioning mechanism aims to minimize the amount of data that needs to be transferred between different nodes, thus reducing the latency and bandwidth requirements for both inference and training phases. The overall throughput of the inference and training tasks is limited by the slowest part of the system, known as the bottleneck stage. We therefore introduce mechanisms to balance the workload and avoid bottlenecks. The partitioning must balance the computational load across all nodes to maximize throughput. This balance ensures that all parts of the system work at their full potential without any single stage becoming a drag on performance. For distributed inference and training across multiple nodes, we are using the available fast memory like Static Random-Access Memory (SRAM), which is essential for storing intermediate model outputs, i.e., activations, and parameter weights. SRAM is significantly faster than conventional memory solutions but is also more expensive and limited in size. Each node in the network contributes its SRAM, which effectively multiplies the available fast memory during the distributed inference and training session. This increase allows for caching more model parameters in fast memory, which is critical for enhancing the performance.

### Sequential Deep Neural Network Sharding

Nesa developed a new approach for network topology-informed model sharding, named *Blockchain-based Sequential deep neural network Sharding* (BSNS). Our approach establishes a sequence of nodes, each of which will typically be a repeated block in any architecture. It is crucial that, for each inference session involving block sharding, a chain of nodes is found that can collectively reconstruct the layers of the full model \[19]. The key innovation of our approach is that the selection of nodes for sharding is informed by: (i) the topology of the blockchain; (ii) our persistent homology metrics based on graph embeddings and (iii) network-based variables, including latency and geographical distance between the nodes. Taken together, this will constitute a full end-to-end neural network that performs inference across the blockchain at the optimal speed, fully embedding the topology and the security components of the blockchain.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FUo5IJagwfm8QO6aEDidM%2Fdistributed-inference-1.png?alt=media&amp;token=bf60bc07-0cda-4ae7-8df1-cd7e1ba59363" alt=""><figcaption><p>A) An orchestrator is chosen from the pool of accessible nodes, and that orchestrator further picks nodes to build a whole block set according to the model that is needed. B) To enable direct routing between blocks, each node has a unique section of the computational graph. C) Initiating from the orchestrator, the inference is routed to the first block and then through each remaining block directly in order.</p></figcaption></figure>

#### Swarm Creation and Dynamic Rebalancing

Our approach ensures scalability as the model is distributed across multiple nodes, enabling computation for larger models. The network's resources are optimized, as every node only stores a portion of the full architecture, saving on processing needs. Importantly, our approach ensures that the computational resources are also optimized based on the network structure, which is embedded as a constraint in the node selection process when building the full architecture based on the individual shards. This has strong practical benefits for our clients, as distance and latency heavily affect the performance when computing on a blockchain.

Given a network $$A$$ with $$n$$ nodes that need to execute $$p \leq n$$ shards of a model, and assuming that each block is held by one network node, the task involves finding a sequence $$\mathcal{S}$$ of nodes

$$
\mathcal{S}: (A\_i)\_{i\in{1,\ldots,p}}.
$$

We can model this as a recursive sequence finding problem, where here the selection of each node depends on the previous node(s) selected and on the network parameters:

$$
A(i) = A\_i = f((A\_{i-1-\alpha},\ldots,A\_{i-1}); \ \text{network parameters}(\alpha)),
$$

where $$\alpha < i-1$$ sets the context length for network inference, and affects the computation of the network parameters. Note that, if $$\alpha=0$$, the network parameters only involve distance metrics between the current node and the previous node, while for $$\alpha>0$$, more than one node is considered and therefore topology metrics can be calculated to inform the selection of the current node.

To dynamically adapt to changing network conditions and node performance, the BSNS framework introduces a *dynamic rebalancing algorithm*. This algorithm's core function is to periodically evaluate each node's performance and the prevailing network conditions which facilitates the reallocation of model shards among nodes. The objective is to achieve minimal latency and maximal throughput, which consequently optimizes the distributed system's performance.

This rebalancing operation is provided by the following formula:

$$
\mathcal{R} : \mathcal{S} \times \mathcal{P} \rightarrow \mathcal{S}'.
$$

where $$\mathcal{R}$$ represents the rebalancing function, transforming the current sequence of nodes $$\mathcal{S}$$, given network parameters $$\mathcal{P}$$, into a new, optimized sequence $$\mathcal{S}'$$. These parameters encapsulate essential network characteristics, including node and edge position in the network, hardware capacity, latency and bandwidth, which collectively influence the data transmission speeds between nodes.


# Dynamic Sharding of Arbitrary Neural Networks

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

While the sequential method provides a structured and heuristic-driven approach to partitioning, it operates under the constraints of a linear, predetermined exploration path. This may not fully capture the dynamism and complexity of modern neural network architectures, where computational and memory demands can vary significantly across different layers and segments of the network. Given an arbitrary neural network, our objective is to partition the network's computation graph for optimal execution across multiple nodes. This computation graph, $$G=(V, E)$$, consists of computational unit operations $$V$$ and data flow edges $$E$$, with each operation $$v \in V$$ outputting a tensor consumed by downstream operations $$v$$, forming edges $$(u,v) \in E$$. The graph represents the entirety of the model's computational workload which ranges from simple arithmetic operations to layer-specific matrix multiplications, each associated with specific computational and memory requirements i.e. the running time $$\text{work}(v)$$, the memory footprint of the model parameters $$\text{sizeparam}(v)$$, and the size of the operation's output $$\text{sizeout}(v)$$.

Partitioning this graph involves dividing $$V$$ into $$k$$ distinct blocks such that each block can be processed on a different node in a swarm under the constraint that the induced quotient graph of $$G$$ remains acyclic. This division aims to maximize throughput while minimizing inter-node communication subjected to the bandwidth $$B$$ between nodes, with the I/O cost from node $$S$$ to node $$T$$ given by:

$$
\text{io}(S,T) = \frac{1}{B} \sum\_{v \in N^-(T) \cap S} \text{sizeout}(v),
$$

where $$N^-(T)$$ represents the set of nodes whose outputs are consumed by block $$T$$.

The core challenge lies in efficiently distributing the model's parameters and activations across the available fast memory (e.g., SRAM) of each node. Parameters not fitting in fast memory must be streamed from slower storage which introduces additional latency. The overflow cost which represents the time to stream parameters exceeding the fast memory limit $$M$$ is calculated as:

$$
\text{overflow}(S) = \left(\text{sizeparam}(S) + \text{peak}(S) - M\right) + \frac{\text{peak}(S)}{B},
$$

where $$\text{peak}(S)$$ denotes the peak memory requirement for activations within block $$S$$.

The overall block cost, $$f(S)$$, combines the costs of receiving input tensors, executing the block's operations (including any overflow cost from streaming parameters), and sending output tensors downstream:

$$
f(S) = \text{io}(V\setminus S,S) + \sum\_{v \in S} \text{work}(v) + \text{overflow}(S) + \text{io}(S,V\setminus S).
$$

The goal of partitioning, defined by the Max-Throughput Partitioning Problem (MTPP), is to minimize the maximum cost across all blocks, optimizing the throughput of the entire pipeline. Formally, MTPP seeks a partition $$P^\*$$ that minimizes the bottleneck cost:

$$
P^\* = \text{argmin}*{P \in P\_k(G)} \left{ \max*{i\in\[k]} f(P\_i) \right},
$$

where $$P\_k(G)$$ denotes the set of all possible partitions of $$G$$ into $$k$$ blocks, and $$\text{cost}^\*$$ is the minimum achievable bottleneck cost across these partitions.


# Cache Optimization to Enhance Efficiency

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

In the BSNS framework, optimizing the Key-Value (KV) cache plays an important role in ensuring the efficient and scalable operation of Large Language Models (LLMs) across a distributed network. KV caching is essential for minimizing the computational overhead associated with token generation in LLMs, particularly when dealing with models that operate on a token-by-token basis. The KV cache mechanism leverages the inherent characteristics of transformer models, caching the key and value vectors after their initial computation to prevent redundant calculations in subsequent generations.

KV caching is crucial for managing the computational demands of transformer architectures, especially in a distributed setting like BSNS. By caching the key and value vectors, the system significantly reduces the amount of computation required for each new token generation. This not only accelerates the inference process but also decreases the load on the network's nodes, allowing for the efficient handling of larger models and sequences. Caching improves efficiency by ensuring that each node within the BSNS framework can generate tokens efficiently by utilizing pre-computed key and value vectors, thereby enhancing the overall throughput of the system. Moreover, it enables the system to scale to models with extensive context sizes by mitigating the memory and computational constraints that typically hinder the operation of large LLMs.

$$
\text{Cache Size per Token} = 2 \cdot \text{head\_dim} \cdot n\_heads \cdot n\_layers,
$$

where *head\_dim* represents the dimensionality of the key and value vectors, *n\_heads* is the number of attention heads, and *n\_layers* is the number of transformer layers within the model. This highlights the direct relationship between the model's complexity and the size of the KV cache, showing the need for effective cache management strategies within our BSNS framework.

To optimize the KV cache within the distributed setting of BSNS, the framework introduces caching and rebalancing techniques which align with the dynamic rebalancing algorithm discussed earlier. The optimization process involves:

$$
\mathcal{O}(\mathcal{C}, \mathcal{N}) \rightarrow \mathcal{C}',
$$

where $$\mathcal{O}$$ denotes the optimization function that transforms the current cache configuration $$\mathcal{C}$$, given the network of nodes $$\mathcal{N}$$, into an optimized cache configuration $$\mathcal{C}'$$. This process takes into consideration factors such as the cache size limitations of individual nodes and the network bandwidth available for transferring cached data between nodes. By managing the KV cache, the BSNS framework enhances the performance and scalability of distributed LLM operations. The caching and dynamic rebalancing enable the system to adapt to varying computational and network conditions which ensure that the distributed processing of LLMs remains efficient and responsive to the demands of natural language generation (NLG) tasks.


# Enhanced MTPP Slicing of Topological Order

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

The Max-Throughput Partitioning Problem (MTPP) is fundamental to our goal of optimizing the partitioning of computation graphs for distributed deep neural network inference. Acknowledging MTPP's NP-hardness which initially is established through a reduction from the minimum makespan scheduling problem highlights the impracticality of seeking a fully polynomial time approximation scheme. This emphasizes the need for a heuristic approach to achieve high throughput pipelined inference. We integrate a heuristic algorithm that leverages the strengths of Kahn's algorithm for topological sorting which is enhanced by dynamic programming and segment trees. This approach aims to balance the computational load across the nodes and minimize the communication overhead, which is critical for maintaining high throughput in distributed systems. Kahn's algorithm is chosen for its effectiveness in ensuring a valid topological order, which is essential for acyclic partitioning. Moreover, dynamic programming offers an optimal partition strategy across these ordered segments, and segment trees are utilized for their efficiency in querying segment costs which enables rapid adjustments to partitioning as we explore the solution space for an optimal configuration.

In our approach, the introduction of the *segment cost data structure* is crucial, as it enables the efficient computation of costs for any segment within the topological order. Initialized with a computation graph $$G$$ and a topological order $$\pi$$, it calculates costs that include both computational workload and communication overhead. The *SliceGraph* algorithm plays a central role in our approach, leveraging the segment cost data structure to partition the computation graph into segments that optimize throughput while minimizing latency. It dynamically partitions the graph into a specified number of blocks, ensuring equitable workload distribution and minimizing inter-node communication.

The initialization time complexity of the segment cost data structure is $$O(n^2)$$ for a graph with $$n$$ nodes, enabling the pre-computation of costs associated with all possible segments. This setup is crucial for the efficient execution of the SliceGraph algorithm. The overall time complexity of the SliceGraph algorithm, before applying the convex hull trick, is $$O(n^2k + m\log^2(n))$$ where $$k$$ is the number of blocks into which the graph is partitioned, and $$m$$ is the number of edges in the graph. This complexity takes into account the dynamic programming process and the cost queries facilitated by the segment cost data structure. By applying the convex hull trick, we optimize the dynamic programming aspect of the SliceGraph algorithm, reducing its time complexity to $$O(nk\log n)$$. This optimization significantly enhances the efficiency of partitioning, allowing for quicker determination of the optimal graph partitioning strategy.

#### Biased Random-Key Genetic Algorithm

The integration of the Biased Random-Key Genetic Algorithm (BRKGA) into our approach addresses the inherent limitations of the above heuristic-based methods by introducing a stochastic and evolutionary mechanism. This allows for an expansive exploration of partition configurations, crucial for solving the NP-hard Max-Throughput Partitioning Problem (MTPP) efficiently. BRKGA's capability to evolve partitioning strategies over generations enables the discovery of high-quality solutions that balance the computational load and minimize communication overhead, which deterministic methods alone may not identify, ensuring optimal throughput in distributed deep neural network inference.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FKQ5ZliOjqNoIUBM6xQhs%2Fimage.png?alt=media&amp;token=3fa803b1-0624-4ecc-b941-65f00dfba521" alt=""><figcaption></figcaption></figure>

BRKGA improves this process by evolving vectors of node priorities ($$\mathbf{x} \in \[0,1]^n$$), with each vector's partitioning quality undergoing evaluation. This evaluation creates a direct link between node priorities and partitioning quality, allowing for precise adjustments to optimize partition outcomes. It initiates with generating a starting population of random priority vectors, which are then utilized to establish topological orders, feeding into the SliceGraph algorithm. The partitioning quality of each vector, judged on throughput optimization and latency reduction, determines its fitness. Through iterative processes of selection, crossover ($$\mathit{new} = \alpha \mathit{parent}\_1 + (1 - \alpha) \mathit{parent}\_2$$), and mutation, BRKGA refines the population towards more efficient partitioning strategies. This evolution continues until convergence is achieved, which indicates the discovery of an optimal or near-optimal set of node priorities for our partitioning requirements.

The BRKGA approach to partitioning computation graphs for neural network inference offers several compelling advantages over the sequential sharding methods discussed earlier. Firstly, the sequential approach, while systematic and based on clear heuristic rules, may not adequately explore the vast space of possible shard configurations. It inherently follows a predetermined path through this space, which might overlook more efficient configurations that could significantly enhance computational throughput and minimize inter-node communication latency. In contrast, BRKGA introduces a level of stochastic exploration combined with evolutionary strategies, which allows for a broader and more dynamic search. This adaptability is particularly crucial in distributed environments where network topology and node capabilities vary widely.


# BSNS with Parameter-efficient Fine-tuning via Adapters

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

In the BSNS framework, each node, tasked with a segment of the LLM, incorporates adapter modules designed to fine-tune the model for specific tasks with minimal computational overhead. The adapters are inserted between the transformer layers, allowing for targeted modifications of the model's behavior without retraining the entire network. The operational dynamics of integrating adapters into BSNS can be outlined as follows.

#### Operational framework for adapters in Nesa

Adapters are small neural network modules inserted between the layers of a pre-trained model. They allow for task-specific training with minimal parameter updates. Formally, the operation of an adapter within a transformer layer can be represented as:

$$
h'\_i = \text{LayerNorm}(h\_i + W\_2 \phi(W\_1 h\_i)),
$$

where (h\_i) is the input to the adapter at layer (i), (W\_1) and (W\_2) are trainable weights of the adapter, (\phi) denotes a non-linear activation function, and (h'\_i) is the output of the adapter. LoRA introduces trainable low-rank matrices to adjust the attention and feed-forward networks within transformer layers, offering another parameter-efficient fine-tuning method.

The adaptation of a weight matrix (W) in a transformer can be modeled as:

$$
W' = W + BA,
$$

where (W) is the original weight matrix of the model, (A \in \mathbb{R}^{r \times n}) and (B \in \mathbb{R}^{n \times r}) are the low-rank matrices introduced by LoRA with (r \ll n), and (W') is the adapted weight matrix. Upon initiating a fine-tuning session, each participating node initializes adapter modules according to the specified configuration, aligning with the shard of the LLM it is responsible for. This initialization includes setting up the adapter architecture (e.g., feed-forward layers within the adapter) and integrating it seamlessly with the existing transformer layers.

#### Node synchronization

Nodes engage in a collaborative fine-tuning process, where each node updates its respective adapter modules based on the gradients computed from the task-specific data processed through its shard of the LLM. This process involves three steps:

**Forward pass.** Computing the forward pass through the transformer layers and adapters, generating predictions based on the input data.

**Backward pass.** Computing gradients based on the loss between predictions and true labels, where gradients relevant to the adapter modules are computed and used for updating the adapter parameters.

**Synchronization and update.** After computing the updates for the adapters, nodes synchronize these updates across the network to ensure consistency and convergence of the model. This synchronization step is crucial to maintain the integrity of the fine-tuned model across the distributed environment, ensuring that each node's adapters evolve cohesively towards the fine-tuning objective.

The updates to the adapter parameters within each node can be mathematically formulated as follows. Let (\theta\_i) represent the parameters of the adapter module in the (i)-th node. The update rule for (\theta\_i) can be expressed as:

$$
\theta\_{i}^{(t+1)} = \theta\_{i}^{(t)} - \eta \nabla\_{\theta\_i} L(\theta\_{i}^{(t)}),
$$

where (t) denotes the current fine-tuning iteration, (\eta) is the learning rate, and (L) represents the loss function computed based on the output of the node's segment of the LLM and the corresponding ground truth. This update rule ensures that each node independently optimizes its adapter modules while contributing to the global fine-tuning objective.

Nesa's BSNS enhances the efficiency of this distributed fine-tuning process through effective node coordination, leveraging blockchain technology for secure and transparent operation management. Nodes participate in a consensus mechanism to agree on the fine-tuning objectives, data distribution strategies, and synchronization intervals for adapter updates, ensuring a coordinated approach towards model improvement. The BSNS framework facilitates the sharing and reuse of fine-tuned adapters across the network, enabling nodes to leverage pre-existing adaptations for new tasks or further refine them for enhanced performance. This collaborative dynamic allows a community-driven approach to LLM customization and improvement, maximizing resource utilization and accelerating innovation within the ecosystem of distributed LLM applications.


# Swarm Topology

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

Due to the ever-changing topology of the swarm network, we further extend our computational efficiency by monitoring and classifying changes and the current state of our swarm topology over time. In conjunction, we build several precomputed sharding schemas based on the commonly observed swarm topologies as we monitor our networks. In doing so, we can quickly select among sharding schemes to find one that is near-optimal for the current swarm topology. In the following section, we outline how we monitor and analyze the swarm topology.

#### Topological forecasting and monitoring

Dynamic sharding is computationally expensive as finding an optimal sharding scheme is known to be NP-hard. We mitigate this expense by precomputing highly efficient sharding schemas for different topological states of our network on a per-model basis. As the network topology itself is dynamic, we periodically monitor our network using techniques from (weighted) persistent homology, to give snapshots of topological characteristics to guide the applications of our pre-computed sharding schemas. The main goal of this section will be to introduce many of the concepts behind persistent homology (which is not a mainstream topic) to guide intuition on how this computational tool can be leveraged to make dynamic sharding optimization much more tractable.

As a basic introduction to the implementation of this framework, we briefly illustrate the mathematical technique of simplicial homology. This uses the simplicial complex to calculate the homology groups -- these groups are formally Abelian groups but they can be thought of as vector spaces. A simplicial complex is a collection of simplices that are the convex hull of a group of vertices. More explicitly, an $$n$$-simplex $$\Delta^n$$ contains $$n+1$$ vertices $${v\_0, v\_1, \dots, v\_n}$$ and is the collection of points in $$\mathbb{R}^n$$ such that:

$$
\Delta^n = \left{k\_0v\_0 + \cdots + k\_nv\_n \ \vert\ \sum\_{i=0}^n k\_i =1 \textrm{ and } k\_i \geq 0 \textrm{ for } 0\leq i\leq n \right}.
$$

Thus, a 0-simplex $$\Delta^0$$ is a point, a 1-simplex $$\Delta^1$$ is a line segment, a 2-simplex $$\Delta^2$$ is a triangle, and so on. To build a simplicial complex out of a collection of simplices, we need to define how to glue the pieces together. Mathematically it is given as (linear) boundary maps $$\partial\_n^i: C^n \to C^{n-1}$$ which map each $$n$$-simplex $$\Delta^n\_i$$ to its boundary which lives in one dimension lower (if it exists). Here we are using the notation $$C^n$$ to indicate the collection of all $$n$$-simplices in our complex, sums of which are often referred to as $$n$$-chains or simply chains. In general, we can (abstractly) represent the entire data of the simplicial complex by:

$$
\cdots \xrightarrow\[]{\partial\_{n+2}} C^{n+1} \xrightarrow\[]{\partial\_{n+1}} C^n \xrightarrow\[]{\partial\_{n}} C^{n-1} \xrightarrow\[]{\partial\_{n-1}}\cdots
$$

Referring back to the boundary maps $$\partial\_n^i: C^n \to C^{n-1}$$, the image of $$\partial\_n^i(\Delta^n\_i)$$ will be the (simplicial) boundary of $$\Delta^n\_i$$. We assign an orientation to the simplices to make boundary calculations consistent. For example, with the 1-simple as the convex hull of $${v\_0, v\_1}$$ the image of the boundary map would be defined as $$v\_1 - v\_0$$, with such an orientation induced by imaging the 1-simple is a directed edge from the point $$v\_0$$ to the point $$v\_1$$. More explicitly:

$$
\partial\_1(\Delta\_0^1) = v\_1 - v\_0,
$$

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F6WzVHiNH1G5bXfMynXFF%2Fsimplical_homology.png?alt=media&amp;token=943c2328-6f08-402a-a74e-350f793b7306" alt=""><figcaption><p>Toy example for simplicial homology: the left simplicial complex consists of three vertices (0-simplices) and three edges (1-simplices) whereas the right consists of four vertices and four edges. Topologically, these two complexes are identical from the viewpoint of simplicial homology, but they are distinguishable via persistent homology.</p></figcaption></figure>

where we have intentionally denoted $$\Delta\_0^1$$ as the simplex constructed from the vertices $${v\_0, v\_1}$$. Looking at Figure \ref{fig:simplical\_homology}, and considering the triangle at the left, the collection of 1-chains contains three edges, which are the convex hulls of the sets, $${v\_0, v\_1}$$, $${v\_1, v\_2}$$ and $${v\_0, v\_2}$$. The arrows give the orientation of each edge, which guides the boundary map calculation. We already calculated the boundary map for the first edge. The remaining two edges, $$\Delta\_1^1$$ and $$\Delta\_2^1$$ map can be calculated as:

$$
\begin{aligned} \partial\_1(\Delta\_1^1) &=v\_2 - v\_1\ \partial\_1(\Delta\_2^1) &= v\_0 - v\_2 \end{aligned}
$$

By linearity, we can compute the boundary for the full chain, $$\Delta\_0^1 + \Delta\_1^1 + \Delta\_2^1$$ as:

$$
\begin{aligned} \partial\_1(\Delta\_0^1 + \Delta\_1^1 + \Delta\_2^1) &= \partial\_1(\Delta\_0^1) + \partial\_1(\Delta\_1^1) + \partial\_1(\Delta\_2^1)\ &= (v\_1 - v\_0) + (v\_2 - v\_1) + (v\_0 - v\_2)\ &= 0. \end{aligned}
$$

Thus, the chain $$\Delta\_0^1 + \Delta\_1^1 + \Delta\_2^1$$ has no formal boundary (to be more clear this chain is what most people identify as the triangle itself). More importantly. This example demonstrates that a cycle (a chain without a boundary) has a trivial image. This will correlate with some topological holes in the simplicial complex. Thus, cycles correspond to elements of the kernel of the boundary map (a kernel of a map is simply all elements that map to zero). Formally, we calculate the $$n$$th-homology group $$H\_n(C^\star)$$ of a simplicial complex $$C^{\star}$$ as

$$
H\_n(C^\star) = \frac{Z\_n(C^\star)}{B\_n(C^\star)},
$$

where $$Z\_n(C^\star)$$ is the group of $$n$$-chains that are cycles and $$B\_n(C^\star)$$ are the group of $$n$$-chains that are boundaries.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FdXMo3dugr1z20wqaegHB%2FDiagram-11.png?alt=media&amp;token=085e45b6-e4f2-4f46-a0f4-a0fafe41ca7b" alt=""><figcaption><p>Figure 1. Visualizing persistent homology for a simple graph of 3 vertices on an equilateral triangle: the top row illustrates 3 snapshots of the filtration sequence of three circles of growing radii (filtration parameter). The bottom row demonstrates the respective persistence diagrams. Note that in H0(M), the initial 3 dots are shifted slightly to aid the eye but they would overlap precisely in reality</p></figcaption></figure>

Thinking of these groups as vector spaces with each dimension corresponding to a simplex and with the operation being vector addition, this definition allows one to identify chains where the difference is a boundary (a chain that has a non-trivial image). In other words, adding a boundary chain to a cycle does not change its class under homology. This is demonstrated in Figure \ref{fig:simplical\_homology} where the two diagrams are equivalent since the difference in $$C^1$$ is the edge between $${v\_2, v\_3}$$. Note that this is a boundary because the value under the boundary map is $$v\_3 - v\_2 \neq 0$$, according to the indicated orientation. It should be further noted that points never have boundaries so $$H\_0(C^\star)$$ does not count holes, but counts the number of connected components. Overall, this mathematical formalism allows one to unambiguously tabulate the topological characteristics of a wide variety of different geometric objects.

Persistent homology (PH) is based on introducing a filtration of the topological space as a sequence of simplicial complexes, which for our purposes the complexes will be the derived from the graph corresponding to our network. For clarity, we will refer to the persistent $$n$$th homology group for a space $$M$$ as $$PH\_n(M)$$. For our application, the embedding of this graph into Euclidean space is based on the geographic locations and the edge weighting is a function of individual node internet connectivity and node computational power.

The filtering process in persistent homology for a graph resembles inflating circles around each network node (vertex) and capturing data about how the resulting topology changes as the circles begin to merge. One can gain intuition behind this idea by imagining three points on the vertices of a triangle (see Figure 1). A scale parameter increases the radius of each point uniformly. Each step along this parameter change introduces a new step in the filtration of complexes. Until the circles grow enough to overlap, there will be three separate components so the zeroth homology group which measures the number of connected components will have dimension 3 and higher order groups which measure the number of higher dimensional holes will be trivial (left schematic in Figure 1). As the radii grow they eventually grow to overlapping circles. Immediately after the circles overlap there will still be a gap between the three circles centered in the middle of the triangle, so now they’re one hole and thus the first homology group suddenly becomes non-trivial with dimension 1 (center schematic in Figure 1). At the same time the number of connected components collapses to 1 so the zeroth homology group will change from three dimensional to 1 dimensional. As the circles continue to grow, the gap in the middle will fill, closing the hole and the first homology group will become trivial again, but the zeroth homology group will continue to have dimension 1 (right schematic in Figure 1). No further meaningful changes will occur to the persistent diagram after this point.

The changes illustrated above are typically captured using a persistence diagram which simply introduces a point for each birth-death pair, where the x-axis is the birth time and the y-axis is the death time. Here time is just the scaling parameter. Since births always occur before deaths, all the points on the diagram will be above the main diagonal line $$y=x$$. Following the toy example above, one can imagine that smaller holes will have quicker deaths since they do not persist long, so they will be near the main diagonal. Conversely bigger holes will have a longer lifetime. Intuitively, this gives information about the network latency, connectivity and possible bottlenecks. The lifetimes of the connected components, measured by $$PH\_0(M)$$, give a complementary view of these characteristics. This data from both $$PH\_0(M)$$ and $$PH\_1(M)$$ persistence can be fed into a dedicated ML classifier to predict which precomputed sharding scheme will be most efficient based on the current network topology. As calculating persistent homology is not NP-hard even in dimensions much higher than those used to model graphs, this gives us an avenue to select a near-optimal precomputed sharding scheme at a reasonable computational cost.


# Free-Riding Prevention

> ⚠️ **Evaluation in Progress**
>
> Some of the mechanisms described on this page are currently **being evaluated and validated**. They represent design options under consideration, and may be refined, replaced, or omitted as the system evolves.

A potential vulnerability in any decentralized system is the risk of free-riding, where one party seeks to gain the outcomes of a shared effort without contributing its fair share of work. In the context of our decentralized inference system, this would manifest as a node waiting for others to submit inference results, then copying and submitting those results as their own, thereby conserving their computational resources illegitimately.

To mitigate this risk, we have designed a unique security mechanism that divides the second transaction phase into two distinct sub-phases, each with its transaction: the Commit phase and the Reveal phase.

***

### The Commit Phase

In the Commit phase, nodes in the inference committee must submit a cryptographic commitment of their inference results. This commitment is a one-way hash of the result combined with a secret nonce, providing a way to lock in the result without exposing its content, i.e., H(m||r), where H is the hash function, m is the result, and r is a random nonce.

The commitment ensures that the node has performed the computation and is ready to reveal the valid result. This phase has a specified timeout limit within a fraction of the slot duration. Failure to submit a commitment within this window results in the node being ineligible to reveal its results and facing a penalty.

We list the detailed off-chain and on-chain algorithms for the [commit phase](about:/dnachain/decentralized-inference/step-by-step-process-of-decentralized-inference#step-9-finalization-and-user-notification)

***

### The Reveal Phase

Following the Commit phase, the Reveal phase allows nodes to disclose their previously committed results. Each node must reveal both the result m and the nonce r used in the commitment, allowing others to verify the hash against the commitment made in the previous phase. This phase also has a timeout limit, and failure to reveal on time, or a different result from what was committed, will result in punitive measures against the offending node.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fv7uwmVX2TSTCDi9sX1i0%2Fimage.png?alt=media&amp;token=4d5f43ab-0f00-4ef2-ab32-d9b1dd50ad2c" alt=""><figcaption><p>Step-by-step details of the decentralized inference process. A user sends an inference request in phase 1. When the request emerges from the priority queue, phase 2 begins. The results are then committed in phase 2-a through an inference committee. In phase 2-b, the original results are revealed. If a quorum is reached, the final result is obtained through a majority in phase 2-c and the requested operand is executed. The reward payment and punishment are made in the POSTOP step. In addition, the contract refunds the remaining fee to the user.</p></figcaption></figure>

The introduction of the Commit/Reveal scheme effectively prevents free-riding by ensuring that each node provides evidence of its contribution before any results are made public. This two-step process requires nodes to stake their claim on an outcome without knowledge of other nodes’ work, thus ensuring that each node contributes independently.

By employing a cryptographic commitment scheme, we create a trustless environment where work cannot be copied, and honesty is enforced through the threat of penalties.

These penalties for non-compliance act as a strong deterrent against malicious activity, helping to maintain a fair and secure environment for all participants. The Commit/Reveal protocol guarantees that only nodes that genuinely perform the computations are rewarded, thereby upholding the integrity of the decentralized inference process and protecting the system from exploitation.

This careful orchestration of transactions and timings ensures that our network remains resilient, efficient, and free from the inefficiencies and unfair practices that free-riding would introduce.

We list the detailed off-chain and on-chain algorithms for the [reveal phase](about:/dnachain/decentralized-inference/step-by-step-process-of-decentralized-inference#step-9-finalization-and-user-notification).


# Validation, Reputation, and Miner Lifecycle

Running AI inference across untrusted, decentralized networks introduces major challenges in **correctness**, **fault tolerance**, and **trust minimization**.\
Nesa addresses these challenges through:

* Optimistic validation
* Reputation-based scoring
* Tiered miner routing
* Trial gating for new miners
* Timeout and recovery protocols

***

### Inference Validation

Nesa adopts **optimistic execution**, where inference results are assumed valid unless later proven incorrect.\
This approach minimizes latency and avoids the need for synchronous consensus.

#### Execution Pipeline

1. Miner executes its assigned model shard.
2. Result is returned to the orchestrator agent.
3. The agent validates results by checking:
   * Tensor structure and output shape
   * Response latency
   * Miner’s historical reputation

#### Additional Validation for High-Risk Queries

* Shadow miner reruns
* Redundant execution
* zkDPS or cryptographic proofs

***

### Trial Runs for New Miners

Before a miner can join the live query pool, it must pass a **trial inference**:

* A dummy task with a known output is dispatched.
* The miner’s response is validated.

**Outcomes:**

* If correct: miner is marked as “warm” with baseline reputation initialized.
* If incorrect: miner is delayed (cooldown) and flagged for review.

***

### Miner Reputation Scoring

Nesa employs two scoring mechanisms depending on the system architecture.

#### Top-Down Scoring (Orchestrator Assignment)

Miner reputation is updated for each inference task as:

$$
R' = R \cdot \text{Pen}^M \cdot \text{Rew}^{1 - M}
$$

Where:

* $$R$$: current reputation
* $$R'$$: updated reputation
* $$\text{Pen} = 0.8$$: penalty multiplier
* $$\text{Rew} = 1.01$$: reward multiplier
* $$M \in {0, 1}$$: error flag (1 = mistake, 0 = correct)

This creates exponential divergence: consistently reliable miners grow reputation faster, while unreliable miners fall behind.

<div><figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F7QbK4EaaOcL1AaAbMYqO%2Fimage%20(3).png?alt=media&amp;token=8f5b14f8-e806-464a-81c2-666ba6038232" alt=""><figcaption><p>Simulation of miner reputation under incremental penalty and reward mechanisms. Left: with reward factor 1.01, good miners gradually separate from poor performers.</p></figcaption></figure> <figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FibIMJy89hdmkquhdsuba%2Fimage%20(2).png?alt=media&amp;token=4ae5c621-0ed5-4565-a05a-7f48be265cb2" alt=""><figcaption><p>Simulation of miner reputation under incremental penalty and reward mechanisms. Right: with higher reward factor 1.05, exponential divergence accelerates, enabling rapid recovery for consistently correct miners.</p></figcaption></figure></div>

***

#### Bottom-Up Scoring (Bidding Architecture)

In peer-to-peer or bidding-based systems, performance is also factored in:

$$
R' = \alpha \cdot R \cdot \text{Pen}^M \cdot \text{Rew}^{1 - M} + \beta \cdot (w\_S S + w\_F F + w\_B B + w\_I I)
$$

Where:

* $$R$$: current reputation
* $$R'$$: updated reputation
* $$\alpha$$, $$\beta$$: weighting factors (accuracy vs performance)
* $$S$$: single-token inference throughput (token/s)
* $$F$$: forward pass performance
* $$B$$: backward pass performance
* $$I$$: network speed or latency responsiveness
* $$w\_S, w\_F, w\_B, w\_I$$: normalized weights

All performance metrics are normalized:

$$
x \leftarrow \frac{x - x\_{\text{min}}}{x\_{\text{max}} - x\_{\text{min}}}
$$

> **Design note:** High rewards with few mistakes can cause exponential growth in scores, overshadowing hardware performance. Penalty/reward factors must be tuned to balance fairness.

***

### Empirical Observations

#### Latency Statistics (500K inference requests)

| Metric         | Max    | Min | Median | Std Dev |
| -------------- | ------ | --- | ------ | ------- |
| Response Time  | 272254 | 3   | 24     | 399.7   |
| Loading Time   | 7999.6 | 2.7 | 21.6   | 83.4    |
| Inference Time | 3732   | 0   | 0.36   | 38.0    |

#### Correlation Tests (100k requests)

* Strong correlation: **loading-only time ↔ total response time**
* Weak correlation: **inference time ↔ model size**

The figures below — empirical distributions of miner performance metrics. left: response speed shows a zero-inflated Poisson-like distribution. middle: loading time distribution is heavily right-skewed. right: inference time distribution, also skewed, highlights variability across miners.

<div><figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FdbzRvkUJpYmysGrWpsHI%2Fimage%20(5).png?alt=media&amp;token=984c2163-75b3-4f5a-b1ad-39b1d5f64a07" alt=""><figcaption></figcaption></figure> <figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F83MEfF7uSxgJcJr0Ietc%2Fimage%20(6).png?alt=media&amp;token=2210a8c7-94b5-47ce-8127-641005a9da30" alt=""><figcaption></figcaption></figure> <figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F4B0nygGlY9Ps1LACBThY%2Fimage%20(4).png?alt=media&amp;token=a6a3d7f4-00d3-4e8a-bca5-07044149dbba" alt=""><figcaption></figcaption></figure></div>

<div><figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FvElRbmR52nVSvUnlITmM%2Fimage%20(7).png?alt=media&amp;token=883a9797-9578-411f-9b9b-debdfbee8612" alt=""><figcaption><p>Correlation analysis across 100k inference requests. Left: loading-only time correlates strongly with total response time (R² ≈ 0.87). Right: inference time shows weak correlation with model size (R² &#x3C; 0.1), even under polynomial fits.</p></figcaption></figure> <figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F1uKOthXK7mGNuh96b7Si%2Fimage%20(8).png?alt=media&amp;token=319e1237-5e85-4d37-8837-fbb89cbff5c6" alt=""><figcaption><p>Correlation analysis across 100k inference requests. Left: loading-only time correlates strongly with total response time (R² ≈ 0.87). Right: inference time shows weak correlation with model size (R² &#x3C; 0.1), even under polynomial fits.</p></figcaption></figure></div>

###

***

### Tiered Miner Pools

Miners are dynamically categorized:

* **Tier 1**: High-reputation miners with hot models and fast responses
* **Tier 2**: Reliable fallback miners for medium-stakes tasks
* **Tier 3**: New or recovering miners, restricted to low-stakes tasks

Routing prioritizes Tier 1 for critical workloads.

***

### Failure Handling and Penalization

If a miner disconnects, times out, or returns invalid results:

**Miner-side:**

* Reputation penalized
* Node may be throttled or blacklisted

**Agent-side:**

* Job republished to fallback swarm
* Shard timeout: 2–5 seconds
* Global timeout: 10–15 seconds

**User-facing:**

* UI shows fallback in progress
* If unresolved:
  * Return partial result (if safe)
  * Retry on new path
  * Final error if all alternatives fail

***

### Timeout and Retry Logic

| Level          | Timeout (Seconds) |
| -------------- | ----------------- |
| Shard-level    | 2–5               |
| End-to-End API | 10–15             |

Missed deadlines trigger automatic rerouting and structured error reporting.

***

### Summary

Nesa ensures decentralized inference remains **trustworthy, low-latency, and production-ready** through:

* Optimistic validation with fallback for riskier queries
* Dual reputation scoring strategies
* Tiered pools for prioritization
* Penalties for untrustworthy miners
* Trial gating for onboarding
* Timeout safeguards for responsiveness


# $NES Utility

### PayForQuery Transactions

To publish data on Nesa developers can submit PayForQuery transactions. A PayForQuery transaction consists of the evolving request, the evolving size, the identity of the sender of the data to be made available for, the namespace, and a signature. Each PayForQuery transaction is split into two parts: the evolution which includes the data to be made available along with the namespace, and the executable payment transaction which includes a commitment to the data.

Both the evolution and executable payment transactions are put into the block within the appropriate namespace. The block data is extended using erasure coding and then Merkelized into a data root commitment included in the block header.

***

### Fee Market Overview

Nesa uses a standard gas-price prioritized mempool. This means that transactions with higher fees will be prioritized by validators. Fees are comprised of a flat fee per transaction and then a variable fee based on the size of each evolve in the transaction.

***

### Network Parameters

$NES holders - not just stakers - can propose and vote on governance proposals to change a subset of network parameters. Nesa will publicly list both the changeable and non-changeable parameters and their values of the system to vote on.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FTAZLt1QzZLJ293ZutRvN%2Fimage.png?alt=media&amp;token=6ccf201e-e39a-46ba-ad72-7cc4a17fc62e" alt=""><figcaption><p>queryStream flow of communication. queryStream is Nesa’s method to stream verified transaction data from a query inference request to Nesa’s Settlement Layer for registry on the blockchain. With Nesa’s interoperable structure, users can elect to stream to another blockchain network such as Ethereum at their preference. The module on Nesa flows through attestation and orchestrators to the queryStream P2P Network, and then into a dedicated Relayer that streams the query result to Nesa’s Settlement Layer or to Ethereum for settlement. The queryStream contract is then formalized on Nesa, executing the model inference end-to-end.</p></figcaption></figure>

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F5NOnBlU5NCzqEsJ3tpen%2Fimage.png?alt=media&amp;token=ec05ba6a-0a7b-4f77-beef-2fb06b783224" alt=""><figcaption><p>Block production for a PayForQuery transaction. When initiated, a names- pace and query details are established, and the transaction is signed. It is then passed through the system as it is shared with the Consensus Layer for verification and Nesa Core where it is prepped for settlement.</p></figcaption></figure>

### Community Pool

Starting at Genesis, Nesa's community pool receives 2% of all $NES Layer block rewards. $NES stakers may vote to fund ecosystem initiatives.

***

### queryStream

queryStream interfaces with Nesa's crypto-economic framework backed by its Proof-of-Stake consensus protocol. By utilizing Nesa's Consensus Layer, computations for AI model inference are transparent and subject to scrutiny by the network of validators and their delegators through an efficient attestation mechanism.

In scenarios where dishonest activities are suspected, such as data withholding by validators, the system is designed to recognize any malfeasance if 2/3 of Nesa validators are implicated, prompting actions such as slashing to maintain network integrity. This modular verification layer provides strong crypto-economic security

<img src="https://3576021028-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FTBcIEp8xctdXZhDwjCpX%2Fuploads%2FcsUi65dPF2KxlZiPytO0%2Fimage.png?alt=media&#x26;token=91135c00-cb6d-46c2-9e84-749f1a30d22b" alt="Block production for a PayForQuery transaction. When initiated, a namespace and query details are established, and the transaction is signed. It is then passed through the system as it is shared with the Consensus Layer for verification and NESA Core where it is prepped for settlement." width="100%">

assurances, raising the standard for trust in decentralized AI model evolution.

queryStream enables developers to tap into Nesa's scalable name space-specific storage, which may start at a few hundred kb per inference query on the Mainnet Beta, with potential increases manageable through on-chain governance. The actual storage provision is based on the complexity and size of the query and underlying model and supports the potential for tens of thousands of model parameters to be processed per second due to the efficient use of erasure coding and Merkle tree data structures.

The communication between Nesa's verification layer and its settlement layer (or Ethereum’s settlement layer given that Nesa is interoperable) is facilitated by a peer-to-peer (P2P) network which includes a queryStream Relayer. The Relayer streams the query data from the verification layer to the settlement layer (or to the Ethereum network), where dedicated smart contracts formally encode and execute the query directives received from Nesa.

Every PayForQuery transaction submitted to Nesa is validated with a Byzantine Fault Tolerant (BFT) signature mechanism. Any AI model data included in Nesa can be independently verified on Ethereum using queryStream, with validation results backed by cryptographic proofs. On settlement, the AI model inference proofs and PayForQuery transaction data are published to Nesa.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FkBGTJ2aWhs1JZ7uMqadu%2FDiagram-13.png?alt=media&amp;token=2b7ee3f2-92b0-41f5-a1e9-e518c8c12c3e" alt=""><figcaption><p>Tokenomics relationship on Nesa. Miners are required to stake a portion of $NES for a vested interest in the honest and efficient processing of AI queries on behalf of the dApp user.</p></figcaption></figure>

For ZK rollups employing queryStream, data inclusion must be verified before considering any proof as valid. This can be done by incorporating the inclusion proof within the ZK proof itself for submission to Nesa's settlement layer, or another blockchain network like Ethereum.

### Token Fee Mechanism

We summarize these high-level insights into the tokenomics of the platform which describes the token-based relationship between participants in the NES ecosystem. On Nesa, miners are required to stake a portion of $NES tokens. This requirement serves as a safeguard, ensuring that miners have a vested interest in the honest and efficient processing of AI queries.

This aspect of our system draws parallels to the concept of oracles in blockchain, yet with a unique focus on AI model execution.

Nesa's token fee mechanism introduces a flexible economic model: the more tokens committed, the larger the pool of miners, hence enhancing security with more proofs attached in the queryStream. Conversely, spending fewer tokens results in a smaller miner pool, indicating a trade-off between cost and security.


# Background and Exploratory Notes

We introduce the AI Terminal (AIT), a pioneering new system architecture that is the new standard for blockchain-powered artificial intelligence to achieve trustless, large AI model inference. This section details out some background info on the Nesa ecosystem.&#x20;

{% content-ref url="/pages/uWssrZUd8rKNHrZAzvY6" %}
[Broken mention](broken://pages/uWssrZUd8rKNHrZAzvY6)
{% endcontent-ref %}

{% content-ref url="/pages/Up4ukOI5DLBRS0hJMJCf" %}
[Nesa's Utility Suite](https://docs.nesa.ai/nesa/major-innovations/background-and-exploratory-notes/nesas-utility-suite)
{% endcontent-ref %}

{% content-ref url="/pages/B28mxXk3iAD10EytM9L3" %}
[Broken mention](broken://pages/B28mxXk3iAD10EytM9L3)
{% endcontent-ref %}

{% content-ref url="/pages/TnXwwn9wKbuEHdISysK2" %}
[Broken mention](broken://pages/TnXwwn9wKbuEHdISysK2)
{% endcontent-ref %}


# Nesa's Academic Papers

Nesa is committed to advancing cutting-edge research at the intersection of privacy, scalability, and trust in AI systems. Our work addresses fundamental challenges in decentralized AI, focusing on secure inference, model partitioning, encrypted computation, and efficient model deployment across heterogeneous environments. Through active publication in peer-reviewed venues, we aim to share innovations that support robust, transparent, and scalable AI infrastructure.

This page presents selected academic papers authored by the Nesa team and collaborators, including accepted conference papers and ongoing preprints. Together, they demonstrate our technical depth across areas such as encrypted model inference, decentralized model sharding, privacy-preserving systems, and meta-learning for deployment optimization.

\[1] Model Agnostic Hybrid Sharding for Heterogeneous Distributed Inference

**Conference**: *KDD 2024 — The Fourth International Workshop on Smart Data for Blockchain and Distributed Ledger (SDBD'24)*\
**arXiv**: [arXiv:2407.19775](https://arxiv.org/abs/2407.19775)

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FtOM32miu2mpdFuNCyg5d%2Fimage.png?alt=media&amp;token=61634c4a-2b26-4ac7-a528-e160fbba89d9" alt=""><figcaption></figcaption></figure>

A hybrid framework addressing privacy, scalability, and heterogeneity in deploying large AI models in decentralized systems.

***

#### \[2] Towards Secure and Private AI: A Framework for Decentralized Inference

**Conference**: *KDD 2024 — The Fourth International Workshop on Smart Data for Blockchain and Distributed Ledger (SDBD'24)*\
**arXiv**: [arXiv:2407.19401](https://arxiv.org/abs/2407.19401)

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FDePR44c2XQYmK5RBHytD%2Fimage.png?alt=media&amp;token=d33f97bc-8313-450d-84aa-e226edbbf03a" alt=""><figcaption></figcaption></figure>

Presents a secure and scalable framework for decentralized LLM inference, focused on model integrity and privacy.

***

#### \[3] Meta-Learning for Speeding Up Large Model Inference in Decentralized Environments

**Conference**: *Conference on Language Modeling (COLM) 2025 (Main Conference)*\
**arXiv**: [arXiv:2410.21340](https://arxiv.org/abs/2410.21340)

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FAgTC5PLOqu9Dkd5gg4EW%2Fimage.png?alt=media&amp;token=b3227f88-7d05-48d3-8a1a-acce2153c55e" alt=""><figcaption></figcaption></figure>

Explores meta-learning techniques to reduce latency and cost for decentralized deployment of large models.

***

#### \[4] Encrypted Large Model Inference: The Equivariant Encryption Paradigm

**Status**: *Preprint on arXiv*\
**arXiv**: [arXiv:2502.01013](https://arxiv.org/abs/2502.01013)

This work introduces a novel encryption paradigm tailored for large-scale models deployed in distributed and decentralized settings. It addresses key privacy vulnerabilities arising from inference-time data exposure and proposes an equivariant encryption approach for enhanced security and performance.


# Nesa's Utility Suite

&#x20;Nesa accessorizes its system with a hub for external AI tools that help facilitate model querying, training, upload, and evolution (Figure 11.2). As the point of final validation for any model inference query, Nesa sits at the very bottom of the stack and is therefore able to plug an assortment of third-party AI services on top of it.

These services are serially executed and consigned to a dedicated adapter within the system. The Utility Suite includes provisioned computational power (TPUs, GPUs), almost all major publicly available open-source models, the major API-based LLMs, an assortment of Information Oracles, DAO tooling, and Relayers.

Nesa will continue to grow its collection of AI-Web3 partner services and products that can be invoked during training, upload, orchestration, and inference before Nesa executes final query validation.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F2qu5uskcu8t5q6UIMRqU%2Fimage.png?alt=media&amp;token=851b84dd-1b19-4a04-8ba5-6d9e6ad233a0" alt=""><figcaption><p>Nesa Utility Suite Architecture. Nesa connects a hub of utility services that help facilitate model querying, training, upload, and evolution for AI model developers in the Nesa ecosystem. A utility service is initialized, run, and then securely hands off data to Nesa’s Execution Layer to assist in a component of the preparation, orchestra- tion, or computation of the request. Inference is then conducted by Nesa Core and the results are sent to validator nodes for consensus before rollup to settlement.</p></figcaption></figure>

Some examples of Nesa's future Utility Suite include:

1. Efficient sharing of computational resources on-chain, such as Render, Akash.&#x20;
2. Decentralized AI tooling and infrastructure services, such as Olas, Bittensor.
3. Information oracles for off-chain knowledge relayance, such as Chainlink, Band.&#x20;
4. DAO tooling management systems, such as Gnosis, Aragon


# DNA on Nesa

DNA X is a decentralized application on the network, focused on autonomous personality agents on-chain. Popularized by OpenAI and now taken a step further, we have designed the first platform for minting 1-of-1 personality-agents, autonomously containerized by smart contract, to facilitate their personality evolution and query evolution in real-time on the blockchain.

On DNA X, each digital being is minted as a unique NFT, and is officially incarnated as a “DNA” given its dedicated AI Kernel on Nesa. While DNA’s have an immutable genetic disposition by their smart contract, they have a personality that is steadily evolving in output, knowledge, perspective, and style as new conversational data is piped through the AI Kernel on Nesa, progressively re-training the kernel’s underlying model.

Personality agents on Nesa benefit from the same vertically integrated process described in this section, resulting in near-realtime relationship evolution on the platform, occurring at regular session intervals throughout each conversation.

***

### DNA X dApp

DNA X is a full personality-agent platform (docs: <https://dnalayer.gitbook.io/dnax>) to create a digital self, called a DNA, and to browse, activate, monetize, message externally, and group chat with other DNA’s. It is the only platform that allows you to make a digital version of yourself, or a loved on-chain, and receive a one-of-one NFT representing their unique containerized model on Nesa.

We envision a future where DNA’s become your own digital IP license to monetize your digital self and interact with other digital beings in immersive, entertaining experiences. To begin, DNA’s represents how you speak and text, and can make friends, earn you money, and carry on conversations all by yourself.

***

### Usage Rewards on DNA X

Nesa's Public Allocation Fund will have an Ecosystem Rewards allotment from the Future Initiatives category. This allocation of $NES will be issued to various dApps and third-party products built on the Nesa's that promote the NES ecosystem. The first of these dApps on Nesa is DNA X.

A total of 1% of the total fixed supply of $NES token from the Future Initiatives category of its Public Allocation will be issued to DNA X, to be linearly released in combination with DNA X’s own token and tokenomics plans. The impact of token rewards on the DNA X platform is broken down into two parts:

#### *Usage Rewards*

Messaging DNAs on the platform results in a reward of tokens, sent directly to your connected wallet. DNA X is the first chat platform that permits users to message personalities on any external messenger while continuing to reflect mining rewards in real-time on its native platform. This means that you can chat with your DNAs, on any platform, and still mine token on <https://dnax.ai>.

Rewards each day are calculated by your mining power rate (MPR), which is a function of the relationship score that you hold with each DNA you talk to. Information on how the relationship score is calculated can be found here:

*<https://dnalayer.gitbook.io/dnax/dna-> x-book/rewards*

***

#### *Creator Payouts*

When DNA X receives revenue from a paid subscription on the platform, it buys an amount of $NES worth a portion of that revenue received, on the open market, to give as a payout to creators.

Creator payouts each month are based on the total aggregate usage of their DNA’s, divided by the total aggregate usage across all DNA’s on the platform. Creator payouts are settled in token and are locked up for 100 days.

Under this model, more usage on DNA X means more revenue, which drives upward pressure on the token as more tokens are bought from the open market and temporarily removed for circulating supply. We take inspiration from some of Render’s new tokenomics theory here, applying it to subscriptions paid on the DNA X Platform.

***

### The Vision for DNA’s on the Blockchain <a href="#the-vision-for-dnas-on-the-blockchain" id="the-vision-for-dnas-on-the-blockchain"></a>

Nesa's first dApp on the network - DNA X - is giving AI characters a leap forward in how they are created, interacted with, evolved, and integrated into the digital fabric of our lives.

At the heart of DNA X is the creation of highly sophisticated personality-agents, called DNA’s, that transcend the limitations of traditional chatbots. DNA’s are imbued with advanced long-term memory, hyper-realistic personality traits, and a suite of functionalities that push the boundaries of AI realism. They have been trained on proprietary conversational datasets specific for unique friend-to-friend dialogue use cases. The result is hyper-realistic digital beings that possess an unparalleled level of authenticity.

The DNA X Platform is unique in that it is directly integrated with blockchain technology, on Nesa. Creators mint their personality-agents as NFTs, granting them a unique digital identity and ownership rights. This minting process not only ensures the uniqueness of each AI character but also opens a new marketplace for creators and collectors. By acquiring a DNA NFT, users gain access to a world of possibilities, from personalized interactions and lifelong monetization capabilities to group chat integrations, and messaging abilities across popular external platforms like Telegram, WhatsApp, and WeChat.

To fuel the DNA X Platform, a disbursement of Nesa's native cryptocurrency, $NES, will be allocated to the platform as a complimentary reward DNA X’s own platform token and tokenomics plan. The token serves as the cornerstone of the platform’s economic model, rewarding usage, incentivizing creators, facilitating transactions, and nurturing a thriving community around AI-driven interactions and experiences. For more information on how rewards work on the platform, read our docs here: <https://dnalayer.gitbook.io/dnax/dna-x-book/rewards/rewards-on-the-dna-platform>

***

### Finetuning Advancements Powering DNA X <a href="#finetuning-advancements-powering-dna-x" id="finetuning-advancements-powering-dna-x"></a>

Despite the major recent advancements in Language Learning Models (LLMs), certain limitations persist particularly in the areas of long-term memory retention, nuanced imitation of character traits, and conversational realism. One of the primary challenges lies in fostering a deep, long-term relationship between humans and AI, enabling conversations to evolve in a more natural, human-like manner.

This challenge stems from the inherent complexity of human interactions and the subtleties of personality traits, which are difficult for current LLMs to fully grasp and replicate over extended dialogues. DNA X exists to create companions for life that not only sound natural but also evolve over time, maintaining hyper-realistic personalities and consistently growing their knowledge about their end-user and their own character.

The technology powering DNA X undergoes simultaneous training of its memory extractor in conjunction with its language model during a finetuning phase to generate an annotator model. Before each utterance within a dialogue, the annotator model is tasked with generating what could be perceived as the internal "thought" of the character. This thought process delineates the reasoning or emotional state that precipitates the character’s spoken words coupled with pinpointing the relevant cues extracted from the ongoing context. Consider a dataset of dialogues denoted as D ={Ci ai}Ni=1 where each Ci represents the dialogue context and ai corresponds to the respective utterance. The primary task of the annotator model is to read through each context of the dialogue dataset Ci and the associated utterance ai and selectively extract text fragments ci that hold relevance to the current utterance.

These fragments referred to as cues are pivotal as they provide the essential context needed for understanding and generating appropriate responses. In addition to extracting cues, the model takes a comprehensive view of the entire dialogue log. It delves into the nuances of the conversation inferring the underlying intention Ii of the character who is speaking. This inferred intention is a crucial component in the finetuning process as it reflects the character’s thought process motivations and emotional states driving the dialogue. During the finetuning phase, the model is trained to fit two specific probabilities: p(Ii|ci) and p(ai|ci, Ii) thanks to the factorization p(ai, Ii|ci) =p(Ii|ci)p(ai|Ii, ci). The first probability p(Ii|ci) represents the likelihood of a particular intention Ii given the relevant cues ci. This is essential for the model to understand the "why" behind a character’s words.

The second probability p(ai|ci, Ii) then focuses on generating the actual utterance ai based on these cues and the inferred intention. This dual-probability approach ensures that the model not only generates contextually appropriate responses but does so in a manner that aligns with the character’s personality and narrative role.


# Definitions

### Autonomous AI Oracle network <a href="#autonomous-ai-oracle-network" id="autonomous-ai-oracle-network"></a>

An autonomous AI oracle network refers to a decentralized and self-operating system that connects off-chain artificial intelligence services with on-chain smart contracts and blockchain networks. This system enables smart contracts to integrate AI capabilities and make complex decisions based on off-chain data inputs, processed by AI models. It revolutionizes the functionality of smart contracts by endowing them with advanced decision-making abilities, akin to an oracle in blockchain but specifically designed to handle AI computations.

### AI model inference queries <a href="#ai-model-inference-queries" id="ai-model-inference-queries"></a>

AI model inference queries are requests submitted to the blockchain network by users who seek to leverage AI capabilities for analytics or decision-making tasks. These queries trigger the process of AI model inference, where input data is fed into a trained AI model to generate predictions or insights. The results of these queries are reported back on the chain, providing users with AI-informed outputs that support various applications, such as predictive analysis or automated content generation.

### Bifurcated Inference Ledgering (BIL) <a href="#bifurcated-inference-ledgering-bil" id="bifurcated-inference-ledgering-bil"></a>

BIL is a two-phase transaction structure that Nesa implements to enhance the scalability and efficiency of decentralized AI computations. By decoupling the submission of an inference request from the actual execution of AI model inference, BIL streamlines the network’s process, preventing computational loads from affecting blockchain performance. It ensures non-blocking transactions, maintains high throughput, and facilitates a flexible resource allocation, making it a vital component in the system’s decentralized inference framework.

### Commit-Reveal Mechanism

A commit-reveal mechanism is a two-step process utilized to ensure honest and independent contributions from nodes executing AI inference tasks. In the Commit phase, nodes submit cryptographic commitments of their results, concealing the content while proving the existence of a computation. During the Reveal phase, the actual results and the nonce used in the commitment are disclosed for verification. This mechanism prevents nodes from free-riding on the work of others, thereby maintaining fairness and integrity in the decentralized inference process.

### Aggregation of Inference Results <a href="#aggregation-of-inference-results" id="aggregation-of-inference-results"></a>

The aggregation of inference results pertains to the process by which multiple outputs from different nodes are synthesized to produce a final, official outcome for an AI inference task. Nesa employs a default majority vote strategy within a smart contract to tally node submissions and determine the consensus result. Nodes that align with the majority are rewarded, while nodes with faulty submissions are penalized. This method reinforces the reliability and validity of the aggregated inference outcomes.

### AI Kernel

The AI kernel is a complete package that includes the model parameters, configuration file, inference code, and aggregation code required for executing an AI model on Nesa. It encapsulates all necessary information and logic for nodes to correctly execute an AI model. The kernel is stored on the blockchain to ensure transparency, immutability, and verifiability of the model’s execution environment. The Kernel operates by way of a decentralized system architecture that serves as a uniform execution environment for AI model inference on the blockchain. This ensures that the execution of AI models is consistent and secure across different nodes, leading to reliable AI computations within a trustless environment.

### Model Parameters

Model parameters are the set of weights and biases that characterize an AI model, essentially determining its behavior and prediction capabilities. These parameters result from the training process and dictate how the model processes input data to generate outputs. Within the AI kernel, model parameters play a vital role in achieving consistent execution and consensus on AI inference results among different nodes.

### AI Kernel Configuration File

Similar to a Dockerfile, the AI kernel configuration file outlines the specifications for the virtual environment needed to run a model on the Nesa network. It lists dependencies, libraries, and runtime details, ensuring that each node sets up an identical execution environment. This file is essential for maintaining the uniformity and reproducibility of model execution on the decentralized network.

### Inference Code

The inference code refers to the actual algorithmic logic executed by the AI model to process inputs and deliver predictions or other outputs. Combined with model parameters, the inference code conducts AI tasks within the AI kernel and plays a crucial role in interpreting input data and producing consistent and accurate results for users’ queries.

### Aggregation Code

The aggregation code in the AI Kernel is a script that determines how results from different nodes are consolidated to reach a consensus within the decentralized network. It forms an integral part of the AI kernel and is vital in synthesizing outputs from various executions to provide a singular, verifiable outcome for AI tasks.

### Decentralized Storage Solutions <a href="#decentralized-storage-solutions" id="decentralized-storage-solutions"></a>

Decentralized Storage Solutions like InterPlanetary File System (IPFS) and Arweave are employed by Nesa to store AI kernels in a distributed manner. Such solutions offer a resilient platform for data storage that is resistant to censorship and data loss, ensuring the persistent availability and accessibility of AI models and execution environments.

### On-chain Model and AI Repository <a href="#on-chain-model-and-aivm-repository" id="on-chain-model-and-aivm-repository"></a>

The On-chain Model and AI Repository constitute a decentralized management system for storing and securing AI models along with their virtual machine configurations. It acts as a discoverable library that allows users to interact with a range of AI models and supports the responsible handling of private or proprietary models through encryption and key management processes.

### Privacy for Proprietary Models <a href="#privacy-for-proprietary-models" id="privacy-for-proprietary-models"></a>

Within Nesa's ecosystem, proprietary models are protected through encryption before being stored on decentralized platforms. This privacy protection ensures that confidential AI models remain inaccessible to unauthorized parties, with decryption keys controlled and distributed at the discretion of the model owner, fostering a secure and trustworthy AI marketplace.

### AI Interface for Model Interaction <a href="#aivm-interface-for-model-interaction" id="aivm-interface-for-model-interaction"></a>

The AI frontend interface is a user-facing platform that facilitates interaction with the on-chain AI model repository. It provides functionalities such as model browsing, uploading, deployment, and real-time monitoring—enabling users across various expertise levels to work with AI models effectively and with ease.

Decentralized inference delineates a process wherein AI computations are undertaken across a distributed network of nodes, ensuring a trustless environment where results are transparently reported on-chain. This method allows for AI models to be utilized in a decentralized way, maintaining user privacy and avoiding centralized points of control or bias.

### Inference Committee Selection <a href="#inference-committee-selection" id="inference-committee-selection"></a>

The Inference Committee Selection process involves deciding on a group of nodes (the committee) that will handle a particular AI inference task on Nesa. It uses VRF to ensure fair and random selection, as well as to verify the committee’s composition, bolstering the security and impartiality of the decentralized inference system.

### Free-Riding Prevention

Free-riding prevention mechanisms are deployed to deter nodes from profiting from the efforts of others without contributing to the computation work. These mechanisms include a commit-reveal protocol that obligates nodes to demonstrate their own computations before gaining access to the results, promoting fairness and contribution within the decentralized inference network.

### Homomorphic Encryption (HE) <a href="#homomorphic-encryption-he" id="homomorphic-encryption-he"></a>

Homomorphic Encryption is a type of encryption that allows for computations on encrypted data without requiring access to the decryption key. Nesa's hybrid-privacy system considers the use of HE techniques for carrying out secure computations on private user data within the TEEs of its decentralized AI platform, strengthening the privacy-preserving capabilities of the project.

### Secure Multi-Party Computation (SMPC) <a href="#secure-multi-party-computation-smpc" id="secure-multi-party-computation-smpc"></a>

SMPC is leveraged in Nesa's infrastructure for executing secure computations among multiple parties where the data inputs remain private. This cryptographic protocol is valuable for collaborative tasks in a decentralized environment where privacy is of paramount importance, without having to compromise the integrity of the computations.

### Zero-Knowledge Proof (ZKP) <a href="#zero-knowledge-proof-zkp" id="zero-knowledge-proof-zkp"></a>

ZKP is a cryptographic technique used by Nesa to enable the verification of the correctness of computations without exposing the underlying data. It helps maintain confidentiality while providing proof that the system’s computations are accurate, encouraging trust and security in the decentralized inference system.

### Threshold Cryptosystem

A threshold cryptosystem is utilized by Nesa for the secure distributed management of cryptographic keys. In such a system, a secret key is split into multiple shares, with no single party having access to the entire key. Nesa employs this system to ensure secure collaborative decryption during AI model inference tasks, without exposing sensitive data.

### Large Language Models (LLMs) <a href="#large-language-models-llms" id="large-language-models-llms"></a>

Large Language Models, such as those developed by OpenAI (e.g., GPT), are AI algorithms designed to process and generate human language in a context-aware and nuanced manner. Nesa uses an enhanced version of LLM, optimized for the Web3 environment, to provide smart contract interactions with access to sophisticated language-processing capabilities.

### $NES

The native cryptocurrency token used within the Nesa ecosystem. $NES serves various functions such as paying for transaction fees, staking for network security, and participating in governance decisions. It underpins the economic model of Nesa, integrating economic incentives with network operations for AI model inference.

### AI Kernel Marketplace

The AI Kernel Marketplace envisaged by Nesa represents a future platform where containerized AI models can be publicly traded and monetized. This open marketplace aims to empower creators with the ability to own, update, and sell their AI iterations, promoting a robust ecosystem for AI model evolution and interaction in a decentralized fashion.

### Threshold Decryption

Threshold decryption is a cryptographic technique used to decrypt information in a distributed manner where no single participant can reconstruct the complete decrypted data. This method is integral to Nesa's privacy-preserving system and is a key component in securely handling inference on encrypted data without disclosing it to any unauthorized entities.

### Utility Suite

A collection of tools and services from external Web3-AI partners provided through Nesa, tailored for various stages of AI development. These include computational resources like TPUs and GPUs, model databases, APIs, and other tools necessary for training AI, such as data oracles and governance platforms, which aid in the smooth and efficient evolution of AI systems.

### DNA X Platform

DNA X is Nesa's inaugural dApp centered on creating, interacting with, and monetizing autonomous digital personalities, designated as DNA's. These DNA's leverage the capabilities of the Helix-1 model to provide life-like and evolving interactions with users, creating a unique ecosystem of digital beings on-chain, minted as NFTs, and evolving their personalities through interactions within the DNA X platform.

### NANs

NANs are an AI-based jury system within the Nesa infrastructure that evaluates the reliability and performance of kernels by administering a series of tests designed to simulate various operating conditions and uncover any inconsistencies in execution. NANs concentrate on key performance indicators which may include computational efficiency, ethical adherence, data precision, susceptibility to generate erroneous or creative outputs, and compliance with established model protocols. They employ an adversarial evaluation framework to challenge the kernels in unpredictable ways, ensuring they behave consistently and according to the predefined configurations before being cataloged on the blockchain.

### Split-Flow

The Split-Flow Protocol dynamically partitions tasks into confidentiality and verifiability streams that operate using either TEEs for heavyweight operations, cryptographic methods like SMPC for lightweight tasks, or a hybrid of the composites depending on requirements. ZKPs are employed within the verifiability stream to ensure the accuracy of computations without compromising data privacy. The protocol’s ability to adjust in real time to the specifics of computational tasks makes it particularly effective in balancing security, efficiency, and verifiability in Nesa's decentralized inference systems.

### Model Version Control

Model Version Control is a process and system within Nesa's decentralized AI framework that enables the tracking and management of different versions of AI models and corresponding datasets. It resembles version control systems in software development, like Git for AI training processes, and ensures all model updates are duly logged and managed.

### On-chain Fork Management

Nesa's on-chain fork management refers to the protocols established to handle branches in AI model evolution. It ensures that as models fork and merge in their development paths, these changes are accurately reflected on-chain. This system allows for complex evolutionary processes, including adaptation and experimentation on AI model updates.

### TEE (Trusted Execution Environment) Implementations <a href="#tee-trusted-execution-environment-implementations" id="tee-trusted-execution-environment-implementations"></a>

Nesa relies on various TEE implementations, including Intel’s Trusted Domain Extensions (TDX), AMD’s Secure Encrypted Virtualization with Secure Nested Paging (SEV-SNP), ARM’s Confidential Compute Architecture (CCA), and NVIDIA’s Hopper H100 GPU architecture. Each provides an additional layer of security and privacy, allowing confidential computations to occur within the Nesa ecosystem.

### SMPC (Secure Multi-Party Computation) <a href="#smpc-secure-multi-party-computation" id="smpc-secure-multi-party-computation"></a>

SMPC on Nesa is utilized to execute confidential computations collaboratively, ensuring participating parties cannot access others’ data input. The implementation is optimized for performance, allowing the network to facilitate secure interactions without compromising efficiency.

### VRF (Verifiable Random Function) <a href="#vrf-verifiable-random-function" id="vrf-verifiable-random-function"></a>

Nesa uses VRF to provide unbiased, unpredictable, and verifiable random values for network processes such as node selection. It ensures that all elements of randomness within the system are fair and transparent, fortifying the security and integrity of the decentralized AI platform.

### Proof-of-Stake Consensus

Nesa operates a Proof-of-Stake (PoS) consensus mechanism, where network validators and their delegators secure and maintain the blockchain by staking $NES tokens. This consensus model provides network governance and collaborative decision-making, contributing to the platform’s democratization and distributed trust.

### Dynamic Pricing Model

Nesa's dynamic pricing model refers to the adaptable fee structure for AI model inference queries. It aligns resource allocation with market demand, enabling users to prioritize their requests by paying higher fees. This model ensures efficient system utilization and optimizes network throughput by managing the queuing of inference tasks based on variable pricing.

### Erasure Coding and Merkelization <a href="#erasure-coding-and-merkelization" id="erasure-coding-and-merkelization"></a>

Nesa employs erasure coding and Merkelization techniques for data redundancy and security, ensuring that AI model data remains intact and tamper-proof as it is stored and processed across its decentralized network.

### Model Evolution Attestation <a href="#model-evolution-attestation" id="model-evolution-attestation"></a>

Model evolution attestation is a verification process within Nesa that ensures the integrity of AI model updates. Validators within the network attest to the authenticity and proper execution of model evolutions, providing a trustless environment for model development and deployment.

### Namespace-specific Storage Management <a href="#namespace-specific-storage-management" id="namespace-specific-storage-management"></a>

Nesa uses a unique storage management system that allocates space for models and data within specific namespaces. This allows for organized and scalable storage solutions tailored to the needs of different AI models and their associated datasets.

### queryStream

QueryStream is a protocol function within Nesa designed to facilitate the on-chain querying of AI models by streaming verification layer data to Nesa's immutable ledger or another blockchain like Ethereum. This method ensures the data’s integrity through a peer-to-peer network and smart contracts that execute model evolutions end-to-end. QueryStream’s P2P relayer component serves as a bridge, streaming query results to the relevant blockchain’s settlement layer for final confirmation and execution.

### Byzantine Fault Tolerant (BFT) Consensus Mechanism <a href="#byzantine-fault-tolerant-bft-consensus-mechanism" id="byzantine-fault-tolerant-bft-consensus-mechanism"></a>

Nesa's consensus mechanism ensures that even in the presence of faulty or malicious nodes (byzantine failures), the network can reach consensus and operate correctly. This enhances the network’s security and resilience.

### Validator Nodes

Nodes on a blockchain network with the responsibility to validate transactions, produce new blocks, and maintain the integrity of the network. Validators participate in the network’s consensus mechanism and, in some blockchains, are required to stake cryptocurrency as a form of security and commitment to their role.

### Gaussian Kernel Transformation <a href="#gaussian-kernel-transformation" id="gaussian-kernel-transformation"></a>

DNA's Helix-1 model incorporates Gaussian Kernel transformations to effectively manage the linguistic style and syntax adaptation, enabling the AI to emulate human-like language patterns within the DNA X platform interactions.

### Intrinsic Rank in AI

Nesa's LLMs utilize the concept of intrinsic rank which postulates that the actual number of parameters needed to perform a task effectively is often much lower than the size of the model itself, allowing for efficient adaptations with minimal parameter changes.

### PayForQuery

PayForQuery is a transaction type on Nesa that enables developers to pay for the querying of AI models, with the cost being determined by the complexity and resources needed for the transaction. It capitalizes on Nesa's Byzantine Fault Tolerant signature mechanism to ensure the validity and security of the AI model data queries on the chain. The PayForQuery transactions are essential for the verifiable execution of AI model inferences, allowing for cryptographic validation and submission of data to Nesa or interchain ecosystems like Ethereum.

### Gumbel Softmax Reparameterization <a href="#gumbel-softmax-reparameterization" id="gumbel-softmax-reparameterization"></a>

The Gumbel Softmax approach facilitates differentiable sampling in AI model training and is used in Nesa to introduce randomness while maintaining differentiability during model training and execution. The refactoring of the sampling process does not make it differentiable.

### Ancestral Sampling

Ancestral sampling is a stochastic process used by Nesa's LLMs to generate sequences of predictions. It’s used to sample from a distribution over sequences, enabling realistic and coherent text generation by sampling each token in the sequence conditionally based on previously generated tokens.

### DNA

A DNA (Decentralized Neural Application) refers to a one-of-one NFT minted on DNA X and running on Nesa that represents a digital being on-chain. A DNA has its own AI Kernel on Nesa. Each DNA has its own set of characteristics analogous to the genetic composition found in biology, making each configuration as distinctive as an individual's DNA. A DNA runs on fully decentralized querying on the Nesa network.


# Getting Started

Follow these steps to get started using Nesa

## **Set Up Your Wallet**

Your wallet is essential for managing your Nesa tokens and interacting with Nesa Chain. Follow the detailed [**Wallet Setup**](https://docs.nesa.ai/nesa/using-nesa/getting-started/wallet-setup) guide to create and configure your wallet. This will involve:

1. **Creating a new wallet**: Generate a secure seed phrase and store it safely.
2. **Backing up your wallet**: Ensure you have a secure backup of your wallet information.
3. **Configuring your wallet**: Set up your wallet to connect with the Nesa network.

{% hint style="info" %}
Your credentials are the key to the tokens you own; keep them private and in a secure location.
{% endhint %}

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FMhCYfVFbznMjljvCXp14%2FScreenshot%202024-05-18%20at%205.42.31%20PM.png?alt=media&amp;token=14ddffbd-dae2-41e6-832e-f12d4d9140c9" alt=""><figcaption></figcaption></figure>

***

### \[Testnet] Get Nesa Tokens

The Nesa Testnet Chain allows you to experiment and familiarize yourself with the network without using real tokens. Follow the [**\[Testnet\] Nesa Faucet**](https://docs.nesa.ai/nesa/using-nesa/getting-started/testnet-nesa-faucet) guide to:

* **Request Testnet Tokens**: Obtain tokens to use on the Testnet.
* **Participate on Nesa Testnet Chain**: Interact with the network and try its features.

```markdown
1. Visit the Nesa Testnet Faucet page on Nesa Web.
2. Enter your wallet address.
3. Click "Request Tokens".
4. Check your wallet for balance updates.
```

{% hint style="info" %}
Use the Testnet tokens to interact with Nesa Chain and familiarize yourself with its features without any real cost to you.
{% endhint %}

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FcMjCTlCqaAgHyDAh9qy8%2FScreenshot%202024-05-18%20at%205.44.53%20PM.png?alt=media&amp;token=de41e23d-5df3-4714-ab64-196810fd1797" alt=""><figcaption></figcaption></figure>

***

### Choose Your Access Method

Depending on your needs, you can access the Nesa network in various ways:

1. **Via Web**: Use the Nesa web interface for a straightforward, user-friendly experience. For casual consumers. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-web).
2. **Via SDK**: Integrate Nesa functionalities into your applications using the Nesa SDK. For developers. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-sdk).
3. **Via IBC**: Connect with other blockchains using the Inter-Blockchain Communication protocol. For developers on third-party, Cosmos SDK-based blockchains. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-ibc).
4. **Via Nesa CCI**: Use the Nesa Command-Line Interface for advanced operations and automation. For developers on third-party, non-Cosmos SDK-based blockchains. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-nesa-cci).

***

### Additional Resources

* **Community and Support**: Join the [**Nesa Discord**](https://discord.gg/nesa) and support channels for assistance and to connect with other users.
* **Documentation and Guides**: Explore additional portions of this documentation, following the guides to deepen your understanding of Nesa Chain.

Welcome to Nesa! We're excited to have you onboard and look forward to seeing what you'll accomplish.


# Wallet Setup

A wallet allows you to store and use NES in order to interact with Nesa Chain

Setting up your Nesa wallet is essential for managing your Nesa tokens and interacting with the network. This guide will help you create and configure your wallet, ensuring you're ready to participate in the Nesa ecosystem.

***

### Compatibility

Nesa supports Cosmos SDK-compatible wallets, with an ordered list of the most reputable ones found [**here**](https://cosmos.network/wallets/). At the time of writing, [**Keplr**](https://www.keplr.app/), which holds the top position, is fully compatible with Nesa Web and will be used throughout this documentation.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FaWzkpT7U3Rr8qryYiqgp%2FScreenshot%202024-05-03%20at%204.49.31%20PM.png?alt=media&amp;token=5abfb95c-8c11-4fd5-bcac-81904d652b19" alt=""><figcaption></figcaption></figure>

{% hint style="warning" %}
**Note:** Ensure your chosen wallet supports Nesa Chain/Cosmos SDK-based blockchains.
{% endhint %}

***

### Why Choose Keplr Wallet?

Keplr is a popular wallet among Nesa users due to its:

* **User-Friendly Interface**: Easy to navigate for both beginners and advanced users.
* **Security Features**: Robust security protocols to protect your assets.
* **Integration**: Seamless integration with Nesa Chain and other blockchain ecosystems.

***

### Step-by-Step Wallet Setup

Follow these steps to set up your Keplr wallet:

#### Step 1: Install Keplr Wallet

1. **Download Keplr**:
   * Visit the [**Keplr website**](https://keplr.app/) and download the browser extension for Chrome, Firefox, or mobile.
2. **(Desktop-only) Add to Browser**:
   * Follow the prompts to add the Keplr extension to your browser.

{% hint style="info" %}
**Hint:** Ensure you download Keplr from the official website (above) to avoid phishing scams.
{% endhint %}

***

#### Step 2: Create a New Wallet (or Import an Existing One)

1. **Open Keplr**:
   * Click on the Keplr icon in your browser or mobile device to open the wallet.
2. **Generate a Seed Phrase**:
   * Click "Create New Wallet".
   * Follow the on-screen instructions to generate your seed phrase.
   * Confirm the seed phrase by re-entering it as prompted.

{% hint style="info" %}
**Note:** If you're importing an existing wallet, choose the "Import an existing wallet" option.
{% endhint %}

{% hint style="danger" %}
**Important:** Store your seed phrase in a secure location. Do not share it with anyone. This phrase is crucial for recovering your wallet.
{% endhint %}

***

#### Step 3: Configure Nesa Chain

1. **\[Testnet]** Visit <https://beta.nesa.ai/faucet/> and choose "Connect Wallet." Once you approve the prompt's' request, the Nesa Testnet chain configuration will be added to your wallet extension.
2. In order for Keplr to display Nesa Chain data, open the Keplr extension, click the [Menu icon](#user-content-fn-1)[^1], then "Manage Chain Visibility." Search for and select the appropriate Nesa chain, then "Save."

{% hint style="info" %}
**Note:** At this point, Keplr is fully configured to interact with Nesa Chain and display your NES token balance.
{% endhint %}

***

#### **(Mobile-only) Step 4: Browse with Keplr Browser**

1. Open the Keplr Wallet app on your mobile device.
2. Choose the browser icon in the tab bar in order to start browsing with your Keplr wallet integrated.

***

By following these steps, you'll have your Keplr wallet set up and ready to manage your tokens. Welcome to the Nesa network!

[^1]: Represented by 3 stacked dashes at the top-left of the extension


# Testnet Nesa Faucet

Acquire NES tokens for use on Nesa Testnet Chain

The Nesa Testnet Faucet allows you to obtain test tokens, enabling you to explore and interact with the Nesa network without using real tokens. Testnet tokens are only for experimental purposes and have no real-world value.

{% hint style="info" %}
**Official Nesa Testnet Faucet:** [**https://beta.nesa.ai/faucet**](https://beta.nesa.ai/faucet)
{% endhint %}

***

### Distribution Amounts & Limits

As of the time of this writing, the faucet distributes NES as follows:

```
0.005 NES (5K unes): Nesa Account Holder
0.010 NES (10K unes): Nesa Account Holder, with X/Twitter Linked
```

In order to manage network utilization and fair use, the following request limits are in place:

```
Max 1 successful request per 24 hours per Nesa Account
60 seconds between requests per Nesa Account
```

***

### Via Nesa Web

You may use Nesa Web to request faucet tokens. This option is noteworthy for those who would like a rich interface with the option to quickly link their X/Twitter Account.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fv86KjougdniTxb0tjVyP%2FScreenshot%202024-05-05%20at%2011.00.56%20AM.png?alt=media&amp;token=74ebb0fd-6e6d-40c3-852a-7451b3ac55bb" alt="" width="375"><figcaption></figcaption></figure>

1. **Visit the Testnet Nesa Faucet Page (URL above)**
2. **(Optional) Authenticate your X/Twitter Account to Receive 2X Tokens**
3. **Connect Your Wallet**
4. **Request Tokens**

Upon requesting tokens, Nesa Web will respond with a message indicating the result of your request.

{% hint style="info" %}
**Note:** Connecting your wallet automatically populates the "wallet address" input field in order to mitigate typographical errors.
{% endhint %}

***

### Via Nesa Discord

Nesa provides an alternate route for requesting Testnet NES Tokens within the [**Nesa Discord**](https://discord.gg/nesa). Visit the Testnet Faucet channel and request tokens using the `/claim` command.

```markup
/claim [nesa_wallet_address: string]
```

Following your request, the Nesa faucet bot will respond with the status of your request.

{% hint style="info" %}
**Note:** You must have an active Nesa Account linked to the Discord account that is making the request.
{% endhint %}

***

### Via Telegram

Coming soon.

***

### Troubleshooting

If you encounter issues:

1. **Retry Your Request**:
   * Wait a few minutes and try your request again, taking note of any error messages returned from your request.
2. **Seek Assistance**:
   * Join the [**Nesa Discord**](https://discord.gg/nesa) for help.

***

By following these steps, you'll have the test tokens you need to explore and interact with Nesa Chain. Enjoy experimenting on the testnet!


# Via Web

Interact with Nesa Chain via the web

Nesa provides an easy-to-use, interactive website for executing inference requests, along with insights into other features of the Nesa Ecosystem.

{% hint style="info" %}
**\[Testnet] Official Website URL:** [**https://beta.nesa.ai**](https://beta.nesa.ai)
{% endhint %}

***

### Step 1: Your Nesa Account

To get started, you need to create your Nesa Account. Follow the instructions on the [**Your Nesa Account**](https://docs.nesa.ai/nesa/using-nesa/via-web/your-nesa-account) page to:

* **Create an account or login**
* **Manage your account**: Update your profile, social profiles, and more.

***

### Step 2: Selecting an AI Kernel

Choosing the right AI kernel is crucial for your tasks. Visit the [**Selecting an AI Kernel**](https://docs.nesa.ai/nesa/using-nesa/via-web/selecting-an-ai-kernel) page to:

* **Browse available kernels**: Review descriptions and capabilities.
* **Select a kernel**: Choose the one that fits your needs.

{% hint style="info" %}
**Note:** Nesa boasts over one thousand AI Kernels to choose from, with the most optimal one being specific to your desired task.
{% endhint %}

***

### Step 3: Submitting a Query

Once your account and AI kernel are set up, you can submit queries. The [Submitting a Query](https://docs.nesa.ai/nesa/using-nesa/via-web/submitting-a-query) page will guide you through:

* **Formulating a query**: Understand the structure and format.
* **Submitting and managing queries**: Learn how to submit, track, and manage your queries effectively.

{% hint style="info" %}
**Hint:** Ensure your queries are clear and concise to get the best results from your chosen AI kernel. Try experimenting with various inputs to find a prompt that delivers your preferred results.
{% endhint %}

***

### Additional Resources

* **Getting Started**: If you’re new to Nesa, check out the [**Getting Started**](https://docs.nesa.ai/nesa/using-nesa/getting-started) guide.
* **Via SDK**: Integrate Nesa functionalities using the SDK. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-sdk).
* **Via IBC**: Connect with other blockchains using the Inter-Blockchain Communication protocol. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-ibc).
* **Via Nesa CCI**: Use the Nesa Command-Line Interface for advanced operations and automation. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-nesa-cci).

***

We’re excited to have you explore Nesa Web. Enjoy a seamless and intuitive experience as you interact with the network!


# Your Nesa Account

Your identity within the Nesa Ecosystem - where you can begin your journey, store your progress, and upload your AI Kernels - is represented by your Nesa Account

{% hint style="info" %}
Only allow-listed emails have access to Nesa Web. Sign up [**here**](https://forms.gle/16CYnkxyACfQ6eWb9) and follow Nesa X (formerly known as Twitter) for priority consideration.
{% endhint %}

Getting into your Nesa Account is as simple as completing the "Create your account"/"Login" popup.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2Fe47AhYcxPaOIPVTyWo63%2FScreenshot%202024-05-11%20at%207.34.53%20PM.png?alt=media&amp;token=da4de447-7ecc-475f-b3c1-9f197610e46e" alt="" width="188"><figcaption><p>Create your account popup, with "Log in" option located in the lower portion of the popup</p></figcaption></figure>

***

## Create a New Account

We've designed an account creation flow that gets you into Nesa Ecosystem as quickly as possible.

1. Complete the "Create your account" flow with your desired email address and password.

{% hint style="danger" %}
**Note:** Use a strong password during the account creation process.
{% endhint %}

***

## Sign In to an Existing Account

1. Click "Log in" button located in the lower portion of the popup to access the Login form.
2. Complete the form with your credentials.

***

## Reset Your Password

1. Click "Log in" button located in the lower portion of the popup to access the Login form.
2. On this form, click the "Forgot password?" button located below the password input field.
3. Complete the form with your account's email address, then check that email's inbox for a link to reset your password.

***

## Manage Profile & Social Verification

1. Click the "Settings icon" in the lower-left portion of the navigation bar.
2. Verify your information here like name, email, X/Twitter and Discord profiles.

{% hint style="info" %}
**Hint:** Nesa Accounts with linked X/Twitter information receive 2X faucet token distributions.
{% endhint %}


# Selecting an AI Kernel

Choosing the right AI kernel is crucial for your tasks. This guide will help you browse and select the most suitable AI kernel for your needs.

## The Gallery

The default navigation of Nesa Website is the Gallery. AI Kernels supported within Nesa Ecosystem are listed here for your choosing, grouped by model type.

In order to navigate to the Gallery, click the Gallery icon on the left-hand navigation page.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FCY44jbi22K7NxK6fq8yf%2FScreenshot%202024-05-05%20at%2011.43.34%20AM.png?alt=media&amp;token=7b9ed19a-2f24-4f14-88b5-8974787a9d0b" alt="" width="39"><figcaption><p>Gallery icon</p></figcaption></figure>

***

## Model Types

AI Kernels are grouped by model type, allowing users to efficiently pinpoint the kernel they are interested in. The number of model types available will increase over time as Nesa continues to add support for them. See a non-exhaustive screen capture below.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FAFLdZEiY5qiA6qKs6SmR%2FScreenshot%202024-05-05%20at%2011.49.50%20AM.png?alt=media&amp;token=3c57bad7-2bb8-419a-830f-363d34ea8eda" alt="" width="563"><figcaption><p>A sample of available model types</p></figcaption></figure>

***

## AI Kernel Selection

Following selection of the desired model type, users have the ability to search and sort within the available kernels.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FGlEQjAk83WYF86AsazfK%2FScreenshot%202024-05-11%20at%207.47.17%20PM.png?alt=media&amp;token=678de15d-e83b-48d5-b8d8-b30cd74a96c6" alt=""><figcaption><p>Search and sort options</p></figcaption></figure>

Some kernels, designated with a badge as a top pick, are highlighted and suggested for use by Nesa Team due to factors such as overall performance.

{% hint style="info" %}
**\[Testnet]** Some model details, like latency, likes, and cost may not appear consistent.
{% endhint %}

Following the search and sort process, users may choose their target kernel for inference simply by clicking on it. Upon selection, users will be navigated to the Query page for inference execution with their respective model primed.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FPjN40tOUIWyFYZBxbQzv%2FScreenshot%202024-05-11%20at%207.48.43%20PM.png?alt=media&amp;token=4e152a3f-a33e-45ac-aa1b-437f03102579" alt="" width="375"><figcaption><p>Example AI Kernel</p></figcaption></figure>


# Submitting a Query

Submit requests via the Query page

## Accessing the Query page

Users may access the Query page through multiple means, two of which are detailed below.

* Select an AI Kernel from the Gallery page, which will redirect you to the Query page, configured with your chosen kernel.&#x20;
* Click the Query icon on the left-hand navigation page.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FvVNGe2BsGl6B4dj1r3P4%2FScreenshot%202024-05-05%20at%202.01.56%20PM.png?alt=media&amp;token=32d3bfc9-195c-4779-8fb7-ffb6c814e883" alt="" width="56"><figcaption><p>Query icon</p></figcaption></figure>

{% hint style="info" %}
**Note:** The preferred method of accessing the query page is by selecting an AI Kernel from the Gallery page.
{% endhint %}

***

## Constructing Your Query

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FcCF7pBLRsxXjmZC3iWKo%2FScreenshot%202024-05-11%20at%207.51.24%20PM.png?alt=media&amp;token=371bb752-9c64-43ea-9897-50ace3e60248" alt="" width="375"><figcaption><p>Example input data form</p></figcaption></figure>

Seen in the image above, the "Enter Query" section guides the construction of your query.

The text input field represents the text data to be sent with your query. This input field changes depending on your selected kernel. For example, image classification kernels accept an image instead.

Clicking the button on the right presents (or hides) advanced query parameters.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2F7DGGw9JYWRrQHyT0m9kU%2FScreenshot%202024-05-05%20at%202.29.15%20PM.png?alt=media&amp;token=918f7062-db87-4deb-ba1b-2f288a664c5e" alt="" width="67"><figcaption><p>Advanced query parameters button</p></figcaption></figure>

{% hint style="info" %}
**Note:** The "Private" switch toggles complete private inference and may incur additional cost and delay.
{% endhint %}

{% hint style="warning" %}
**Note:** Each kernel requires a specific input type and, possibly, certain content. Review the kernel's description and provided hints for guidance.
{% endhint %}

***

## Submit Your Query

Once constructed, your query is ready to submit.

Click the "Send query" button to begin the transaction. At this point, you will be prompted to "Approve" one or more prompts via your wallet software to complete the submission.

Monitor your query's progress via the "Realtime Inference Map" and "Response" sections.

<figure><img src="https://3903893560-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FVtjgh8wLtiRmdt9OTX2C%2Fuploads%2FGnIommPNdMRcohcMeanF%2FScreenshot%202024-05-05%20at%202.39.54%20PM.png?alt=media&amp;token=37cec147-3ba5-4c93-ac79-458e1259caa8" alt="" width="375"><figcaption><p>Realtime Inference Map and Response</p></figcaption></figure>


# Via SDK

Interact with Nesa Chain via the official SDK

Nesa provides a developer-friendly SDK for executing inference requests in both browser and node environments.

{% hint style="info" %}
**Official SDK URL:** [**https://www.npmjs.com/package/@nesaorg/ai-sdk**](https://www.npmjs.com/package/@nesaorg/ai-sdk)
{% endhint %}

***

## Overview

In this section, we cover high-level SDK usage information; on the other hand, a more detailed, code-level set of documentation can be found [**`here`**](https://github.com/nesaorg/ai-sdk-ts/blob/main/README.md).&#x20;

***

### 1. AIClientRpc: Connect to Nesa Chain

Interactions with Nesa Chain take place via an **`AIClientRpc`** instance. To create one, pass your desired **`AIClientRpcConfiguration`** to your client's **`initialize`** method. You may find an example [**`here`**](https://github.com/nesaorg/ai-sdk-ts?tab=readme-ov-file#creating-an-aiclient-instance).

***

### 2. AISession: Create a Session

Establishing a session allows you to place a one-time deposit, or lock, for your upcoming inference requests via an on-chain transaction. To create a session, pass your desired **`AIClientRpcSessionInitParams`** to your **`AIClientRpc`**  instance's **`createSession`** method. You may find an example [**`here`**](https://github.com/nesaorg/ai-sdk-ts?tab=readme-ov-file#creating-an-aisession).

{% hint style="info" %}
`modelName` specifies the lowercased name of an available model.
{% endhint %}

{% hint style="info" %}
`lockAmount` specifies the maximum amount of unes (0.000001 NES) to pay during the inference process. This amount is deducted immediately, with any unused portion refunded upon the session closing.
{% endhint %}

***

### 3. AIRequests: Inference Execution

This process takes place over a websocket connection for speedy, streaming interaction.

Construct and send an **`AIRequest`** in order to communicate with your session's designated model. Each model and/or task type may have a unique set of **`modelParams`** to be included with your request and necessary for proper execution. Inspect or use the **`getModelParameterDefaults`** function for insight regarding any required and optional parameters. You may find an example [**`here`**](https://github.com/nesaorg/ai-sdk-ts?tab=readme-ov-file#sending-an-airequest).

***

### Additional Resources

* **Getting Started**: If you’re new to Nesa, check out the [**Getting Started**](https://docs.nesa.ai/nesa/using-nesa/getting-started) guide.
* **Via Web**: Utilize Nesa Chain AI Models using the Web. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-web).
* **Via IBC**: Connect with other blockchains using the Inter-Blockchain Communication protocol. [**Learn more**](https://docs.nesa.ai/nesa/using-nesa/via-ibc).

***

We’re excited to have you explore Nesa via SDK. Enjoy a seamless and intuitive experience as you interact with the network!


# Via IBC

Harness the interconnectivity that underpins Cosmos-based blockchains

{% hint style="success" %}
Register your interest in Nesa Interaction via IBC Limited Preview program [**here**](https://forms.gle/Yu3hryTcMKvwnRZu7).
{% endhint %}

## Overview

This documentation provides developers with guidance on how to interact with Nesa Chain using the Inter-Blockchain Communication (IBC) protocol, designed for reliable and secure data exchange between blockchains.&#x20;

Nesa leverages IBC to provide its AI inference capabilities across blockchains within the Cosmos network.

***

## Compatibility

Nesa Interaction via IBC is compatible with blockchains built with the Cosmos SDK.

***

## Benefits of IBC

1. **Efficiency**: Eliminates the need for the deployment of identical business logic across chains (DRY).
2. **Scalability**: Distributes transaction load across multiple chains, reducing congestion.
3. **Sovereignty**: Each blockchain maintains its governance and consensus mechanisms, ensuring independence and flexibility.

***

## Reference Material

Before getting started, take a moment to get familiar with the myriad documentation surrounding the topic.

* **IBC Specification**: For a detailed technical understanding, visit the [**IBC Architecture**](https://github.com/cosmos/ibc).
* **IBC Modules**: Reference the modules necessary to integrate and configure the IBC module to your Cosmos SDK application [**here**](https://docs.cosmos.network/v0.45/ibc/integration.html).
* **Tutorials and Examples**: Explore practical examples and step-by-step guides available on the [**Cosmos Network IBC page**](https://cosmos.network/ibc/).


# Prerequisites

Before running the script to set up your Nesa node, ensure you have the following ready

{% hint style="warning" %}
**Note:** This software is in **beta** and primarily targets **Ubuntu/Debian** machines with **CUDA**-enabled GPUs. Support for other hardware/software configurations is **experimental** and will improve over time.
{% endhint %}

### Introduction

Before running a Nesa node, ensure your system meets the following prerequisites. This will help you set up and run the node smoothly.

***

### System Requirements

**Hardware Recommendations**

* **CPU**: Multi-core processor
* **Memory**: 4 GB RAM minimum
* **Storage**: 50 GB free disk space (or more depending on the size of the model(s) you'd like to power)
* **Network**: Stable internet connection

{% hint style="info" %}
**Note:** Miner nodes operate optimally with high-performance graphics hardware.
{% endhint %}

**Supported Operating Systems**

* Linux (Ubuntu, Debian, CentOS, etc.)
* macOS
* Windows (with WSL recommended)

### Software Requirements

**Required Software**

* **GPU Drivers:** Required for hardware acceleration. Please consult your GPU manufacturer's website for reference.
* **Nvidia Toolkit:** Applicable to machines with an NVIDIA graphics card. [Install Toolkit](https://github.com/nesaorg/bootstrap/blob/master/helpers/install_nvidia_container_toolkit.sh)
* **Docker**: Required to run the node. [Install Docker](https://docs.docker.com/get-docker/)

  ```bash
  # Example command to install Docker on Debian/Ubuntu
    # Add Docker's official GPG key:
    sudo apt-get update
    sudo apt-get install ca-certificates curl
    sudo install -m 0755 -d /etc/apt/keyrings
    sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
    sudo chmod a+r /etc/apt/keyrings/docker.asc
    
    # Add the repository to APT sources:
    echo \
      "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
      $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
      sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
    sudo apt-get update
    sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  ```

  ```bash
  # Example command to install Docker on macOS using Homebrew
  brew install --cask docker
  ```

  ```powershell
  # Example command to install Docker on Windows using PowerShell
  choco install docker-desktop
  ```
* **curl**: Required to fetch the bootstrap script. [Install curl](https://curl.se/docs/install.html)

  ```bash
  # Example command to install curl on Ubuntu
  sudo apt-get update
  sudo apt-get install -y curl
  ```

  ```bash
  # Example command to install curl on macOS using Homebrew
  brew install curl
  ```

  ```powershell
  # Example command to install curl on Windows using PowerShell
  choco install curl
  ```

**Installing Necessary Dependencies**

* **gum**: The script installs gum if not present.
* **jq**: The script installs jq if not present.

  ```bash
  # Command to check if jq is installed
  jq --version

  # If jq is not installed, the script will attempt to install it
  ```

### Account and Token Requirements

**Hugging Face API Token**

You will need a Hugging Face API token. [Get your token here](https://huggingface.co/docs/hub/security-tokens).

{% hint style="info" %}
**Hint**: Make sure to save your Hugging Face API token securely. You will need it during setup.
{% endhint %}

**Moniker for Your Node**

Decide on a unique name (moniker) for your node.

{% hint style="info" %}
**Hint**: Choose a moniker that reflects the identity of your node within the network.
{% endhint %}

**Node Type Selection**

Decide whether your node will be a Validator or a Miner. Validators participate in consensus, while Miners handle inference tasks.

**Validator**

* **Role**: Validators are responsible for verifying transactions, creating new blocks, and maintaining the security and integrity of the blockchain.
* **Tasks**: Participate in the consensus process, validate transactions and blocks, and earn rewards for their services.
* **Requirements**: Require a stable internet connection and typically less less computational power than miner nodes. In a PoS network, they also stake tokens as collateral.

**Miner**

* **Role**: Miners execute the heavy-lifting components of AI inference.
* **Tasks**: Collect and verify transactions, bundle them into blocks, and earn rewards for successfully adding blocks to the blockchain.
* **Types**:
  * **Distributed Miner**: Joins existing swarms for collaborative mining.
  * **Non-Distributed Miner**: Operates independently without collaboration.
* **Requirements**: Vary depending on whether they are distributed or non-distributed. Both types require good computational power and internet stability.

### Administrative Rights

Ensure you have administrative rights on your system.

**Linux/macOS**

You should have the ability to use `sudo` for installing packages and running Docker.

{% hint style="info" %}
For linux-based systems, ensure your user is part of the `docker` group by running the following commands:
{% endhint %}

```bash
# Create a docker group (if non-existent), adds the current user, 
# and applies group membership immediately in the current session
sudo groupadd docker
sudo usermod -aG docker $USER
newgrp docker
```

{% hint style="info" %}
**Hint**: To check if you have sudo privileges, run the following command:
{% endhint %}

```bash
sudo -v
```

**Windows**

You should have an administrator account or use WSL with administrative privileges.

{% hint style="info" %}
**Hint**: On Windows, you can check if you are an administrator by going to Control Panel > User Accounts > Manage User Accounts.
{% endhint %}

***

### Additional Help/Support

If you need any additional help or support, please visit the [Nesa Discord](https://discord.gg/nesa) for community support and discussion. You can also explore additional documentation to deepen your understanding of Nesa and its features.


# Installation

Follow this guide to get your node up and running

### Introduction

This guide will walk you through the installation process for running a Nesa node.

***

### Download and Execute the Bootstrap Script

To download and run the bootstrap script, use the following command:

<pre class="language-bash"><code class="lang-bash"># For all operating systems
<strong>bash &#x3C;(curl -s https://raw.githubusercontent.com/nesaorg/bootstrap/master/bootstrap.sh)
</strong></code></pre>

{% hint style="info" %}
**Hint**: Ensure Docker is running before executing the script.
{% endhint %}

{% hint style="info" %}
**View Your Node's Performance**

Visit <https://node.nesa.ai> and enter your Node ID.

You can find your Node ID by re-running the bootstrap script (above) and reading the Node ID from the script's header.
{% endhint %}

***

### Node Configuration

During the script execution, you will be prompted to configure your node:

1. **Moniker**: Choose a unique name for your node.

   ```bash
   # Example prompt
   Choose a moniker for your node: <Your Node Name>
   ```
2. **Node Type**: Select whether your node will be a Validator or a Miner.

   ```bash
   # Example prompt
   What type(s) of node is <Your Node Name>?
   [ ] Validator
   [ ] Miner
   ```

   * **Validator**: Enter the private key for the validator.

     ```bash
     # Example prompt
     Validator's Private Key: <Your Private Key>
     ```
   * **Miner**:
     * **Miner Type**: Choose between Distributed Miner or Non-Distributed Miner.

       ```bash
       # Example prompt
       What type of miner will <Your Node Name> be?
       [ ] Distributed Miner
       [ ] Non-Distributed Miner
       ```
     * **Model Selection**:
       * For Distributed Miner: Select an existing swarm or start a new one.

         ```bash
         # Example prompt for Distributed Miner
         Would you like to join an existing swarm or start a new one?
         [ ] Join existing swarm
         [ ] Start a new swarm
         ```

         If starting a new swarm:

         ```bash
         # Example prompt
         Which model would you like to run? (meta-llama/Llama-2-13b-Chat-Hf)
         ```
       * For Non-Distributed Miner: Enter the model name to run.

         ```bash
         # Example prompt for Non-Distributed Miner
         Which model would you like to run? (meta-llama/Llama-2-13b-Chat-Hf)
         ```

### **Understanding Swarms**

A swarm in the context of Nesa is an orchestrator with one or more miners working collaboratively to handle inference tasks. Distributed miners can join an existing swarm to contribute to an ongoing effort or start a new swarm to initiate a new collaborative mining process.

**Swarm Configuration Process**:

1. **Select an Existing Swarm**:
   * You will be presented with a list of available swarms.
   * Select the swarm you want to join.
   * The script will configure your node to connect to the selected swarm.
2. **Start a New Swarm**:
   * Enter the model name you want to run.
   * The script will set up a new swarm for this model.
   * Your node will act as the initial member of this new swarm, and others can join later.

***

### Final Setup

After completing the configuration:

1. The script will set up the working directory and clone the necessary repositories.
2. Docker containers will be started using `docker-compose`.

To check the status of your node:

```bash
# Check Docker containers status
docker ps
```

{% hint style="info" %}
**Note**: Ensure all required Docker containers are running.
{% endhint %}

***

#### Additional Help/Support

If you need any additional help or support, please visit the [Nesa Discord](https://discord.gg/nesa) for community support and discussion. You can also explore additional documentation to deepen your understanding of Nesa and its features.


# Troubleshooting

Here are some common problems and their solutions

### Introduction

This section provides solutions to common issues encountered during the installation and operation of a Nesa node.

***

### Script Fails to Download or Execute

**Possible Reasons and Solutions**:

* **Network Issues**: Ensure your internet connection is stable.
* **Incorrect Command**: Verify the command syntax.

**Steps to Verify and Fix**:

**Linux/macOS**

```bash
# Check network connectivity
ping google.com

# Verify curl installation
curl --version

# Correct command to download and execute the script
curl -L https://raw.githubusercontent.com/nesaorg/bootstrap/master/bootstrap.sh | bash
```

**Windows (WSL)**

```bash
# Check network connectivity
ping google.com

# Verify curl installation
curl --version

# Correct command to download and execute the script
curl -L https://raw.githubusercontent.com/nesaorg/bootstrap/master/bootstrap.sh | bash
```

***

### Permission Denied Errors

**Explanation of Permission Issues**:

* Insufficient permissions to execute the script or install software.

**Resolution Steps**:

**Linux/macOS**

```bash
# Ensure the script is executable
chmod +x bootstrap.sh

# Run the script with sudo
sudo ./bootstrap.sh
```

**Windows (WSL)**

```bash
# Ensure the script is executable
chmod +x bootstrap.sh

# Run the script with elevated privileges
sudo ./bootstrap.sh
```

***

### Docker-Related Issues

**Common Issues and Solutions**:

* **Docker Not Running**: Ensure Docker service is active.
* **Installation Issues**: Reinstall Docker if necessary.

**Verify Docker Installation and Status**:

**Linux/macOS**

```bash
# Check Docker version
docker --version

# Start Docker service
sudo systemctl start docker

# Verify Docker service status
sudo systemctl status docker
```

**Windows (WSL)**

```powershell
# Check Docker version
docker --version

# Start Docker service from Docker Desktop
Start-Process 'C:\Program Files\Docker\Docker\Docker Desktop.exe'
```

***

### Node Configuration Problems

**Troubleshooting Configuration Issues**:

* Incorrect moniker or node type selection.

**Reconfiguration Steps**:

```bash
# Rerun the script to reconfigure the node
./bootstrap.sh
```

***

### Connectivity Issues

**Diagnosing Network Problems**:

* **Firewall Restrictions**: Ensure necessary ports are open.
* **Network Configuration**: Verify network settings.

**Steps to Fix Connectivity Issues**:

**Linux/macOS**

```bash
# Check open ports
sudo ufw status

# Allow necessary ports (example for port 26656)
sudo ufw allow 26656
```

**Windows (WSL)**

```powershell
# Check open ports in Windows Firewall
Get-NetFirewallRule -All

# Allow necessary ports (example for port 26656)
New-NetFirewallRule -DisplayName "Allow Nesa Node" -Direction Inbound -Protocol TCP -LocalPort 26656 -Action Allow
```

***

#### Additional Help/Support

If you need any additional help or support, please visit the [Nesa Discord](https://discord.gg/nesa) for community support and discussion. You can also explore additional documentation to deepen your understanding of Nesa and its features.


# FAQ

Frequently asked questions and answers

### Introduction

This section addresses common questions about setting up and running a Nesa node.

***

### **What is a Nesa node?**

A Nesa node is a server that participates in the Nesa blockchain network, either by validating transactions (Validator) or by handling inference tasks for AI models (Miner).

### **What are the hardware requirements for running a Nesa node?**

* **CPU**: Multi-core processor
* **Memory**: 4 GB RAM minimum
* **Storage**: 50 GB free disk space (or more depending on the size of the model(s) you plan to power)

### **How do I view my node's performance?**

Visit <https://node.nesa.ai> and enter your Node ID.

You can find your Node ID by re-running the [bootstrap script](https://docs.nesa.ai/nesa/run-a-nesa-node/installation) and reading it from the script's header.

### **How do I install Docker?**

* **Linux**:

  ```bash
  # Add Docker's official GPG key:
  sudo apt-get update
  sudo apt-get install ca-certificates curl
  sudo install -m 0755 -d /etc/apt/keyrings
  sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
  sudo chmod a+r /etc/apt/keyrings/docker.asc
    
  # Add the repository to APT sources:
  echo \
    "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu \
    $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | \
    sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
  sudo apt-get update
  sudo apt-get install docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
  # Example command to install Docker on macOS using Homebrew
  brew install --cask docker
  # Example command to install Docker on Windows using PowerShell
  choco install docker-desktop
  ```
* **macOS**:

  ```bash
  brew install --cask docker
  ```
* **Windows (WSL)**:

  ```powershell
  choco install docker-desktop
  ```

### **How do I configure my node as a Validator or Miner?**

During the bootstrap script execution, you will be prompted to select a node type:

* **Validator**: Enter the private key for the validator.
* **Miner**: Choose between Distributed Miner or Non-Distributed Miner, and select or enter a model.

### **What should I do if the bootstrap script fails to run?**

* **Verify network connectivity**
* **Check curl installation**
* **Run the script with appropriate permissions**

```bash
# For all operating systems
curl -L https://raw.githubusercontent.com/nesaorg/bootstrap/master/bootstrap.sh | bash
```

### **How do I check if my node is running correctly?**

Verify Docker containers status:

```bash
docker ps
```

Ensure all required Docker containers are running.

### **What are swarms, and how do I join or start one?**

A swarm is an orchestrator and miner(s) working collaboratively to handle inference tasks. During the bootstrap script execution, you may:

* **Join an existing swarm**: Select from a list of available swarms.
* **Start a new swarm**: Enter the model name to run.

### Advanced: Can I override my node's model cache directory?

Yes, set your preferred cache directory using the `HF_HOME` variable in `~/.nesa/env/orchestrator.env`.

***

#### Additional Help/Support

If you need any additional help or support, please visit the [Nesa Discord](https://discord.gg/nesa) for community support and discussion. You can also explore additional documentation to deepen your understanding of Nesa and its features.


# Additional Read


