Atoma on-chain logic
Description of Atoma's smart contract role for orchestrating compute resources
Atoma Smart Contract Documentation
Overview
The Atoma smart contract manages compute resources on the Atoma Network and serves as the payment platform for accessing AI compute. This document outlines the key components of the smart contract logic.
Tasks in the Atoma Network
Task
s are fundamental units of computation in the Atoma network, representing various AI-related operations that can be performed. They are defined by the Task struct and play a crucial role in orchestrating the network's computational resources.
Task Structure
A Task
in Atoma includes the following key components:1. owner: The optional address of the user who created the task.
role: The specific purpose of the task (e.g., inference, embedding, fine-tuning).
model_name: An optional identifier for the AI model associated with the task.
is_deprecated: Indicates whether the task is still active or deprecated.
valid_until_epoch: The epoch until which the task is valid.
deprecated_at_epoch: The epoch when the task was deprecated, if applicable.
optimizations: Optional set of optimizations that can be applied to the task.
security_level: The security requirements for the task execution.
task_metrics: Encapsulates parameters to evaluate the performance of the task. It specifies the compute unit (e.g. number of input/output tokens), time unit (optional time unit, e.g. seconds), and value per compute_unit / time_unit of performance (optional). If value and time_unit are specified, then every node subscribed to the
Task
are supposed to perform the required computations by being capable of producing at leastvalue * (compute_unit / time_unit)
, on average.subscribed_nodes: List of nodes that have subscribed to perform this task.
Task Modalities
Tasks can have various modalities, defining the nature of input and output:
Text-to-Text
Text-to-Image
Image-to-Text
Text-to-Video
Video-to-Text
Text-to-Speech
Vector Embedding
Fine-tuning
Text-to-Audio
The modality can be directly by specifying the model name and the role of the task.
Task Roles
Tasks are categorized into different roles:
Inference
Embedding
Fine-tuning
Training
Optimizations
Tasks can specify optimizations to enhance performance, these include:
Flash Attention
Prompt Caching
Quantization
Pruning
Speculative Decoding
Security Levels
Tasks can have different security requirements:
No Security (default)
Sampling Consensus: Relies on Atoma's Sampling Consensus algorithm to ensure that nodes do not tamper their generated responses.
Trusted Execution Environment (TEE): Relies on TEEs to ensure that privacy is maintained for both input and outputs of each task execution. It further provides high verifiability assurances (that is, nodes did not tampered the output in any form).
Task Lifecycle
1. Creation: Tasks are created with specific parameters defining their requirements and constraints.
Subscription: Nodes can subscribe to tasks they are capable of performing.
Execution: When requested, subscribed nodes execute the task according to its specifications.
Deprecation: Tasks can be deprecated, preventing new executions while maintaining historical data.
Tasks in the Atoma network provide a flexible and comprehensive way to define, manage, and execute various AI computations, ensuring efficient resource allocation and diverse computational capabilities across the network.
Implementation:
Tasks can specify required efficiency metrics during creation
Nodes can advertise if these are able to handle such efficiency requirements
The sampling mechanism considers these efficiency metrics when selecting nodes for task execution
Optimization types allow for more efficient resource allocation and task execution, tailoring the network's performance to specific use cases.
Stacks in the Atoma Network
Stack
s are a fundamental concept in the Atoma network, representing a collection of compute units purchased by users for specific tasks. They serve as the primary mechanism for executing computational tasks and managing the associated payments and settlements.
Stack
Structure A Stack
in Atoma includes the following key components:
owner
: Address of the user who created the stackprice
: Price per compute unit in TOMA tokensnum_compute_units
: Number of compute units remaining in the stackselected_node
:SmallId
of the node selected to process the requests in the stacktask_small_id
: The associated taskSmallId
Purpose of Stack
s Stack
s serve several crucial purposes in the Atoma network:
Resource Allocation: They allow users to pre-allocate compute resources for specific tasks.
Payment Management:
Stack
s facilitate the payment process between users and nodes.Execution Tracking: They provide a way to track the execution of computational tasks.
Settlement Mechanism:
Stack
s enable a robust settlement process, ensuring fair compensation for nodes and refunds for unused resources.
Stack
Creation and Node Selection When a user creates a Stack
:
The user specifies the task, number of compute units, and price per unit.
The system selects an appropriate node based on the task requirements and node availability.
The selection process considers factors such as node reputation, price, and capability to perform the task.
A
StackCreatedEvent
is emitted, containing details about the newStack
.
Stack
Execution and Settlement The settlement process varies based on the security level of the associated task:
No Security (Default Case):
The selected node executes the task and submits the results.
The node claims the payment for the used compute units.
Any unused compute units are refunded to the user.
A
StackSettlementTicketClaimedEvent
is emitted.
Sampling Consensus:
The selected node executes the task and submits the results along with a commitment (
committed_stack_proof
).The system may randomly select additional nodes for attestation (cross-validation).
Attestation nodes verify the execution and submit their own commitments.
If all commitments match, the settlement proceeds.
In case of a mismatch, a dispute resolution process is initiated.
A
StackSettlementTicketEvent
is emitted upon successful settlement.
Trusted Execution Environment (TEE):
The selected node (running in a TEE) executes the task and provides a proof of correct execution.
The proof is verified on-chain.
Upon successful verification, the settlement proceeds.
Attestation Process (for Sampling Consensus)
The system selects attestation nodes based on the
cross_validation_probability_permille
andcross_validation_extra_nodes_count
parameters.Attestation nodes re-execute the task and generate their own commitments.
These commitments are compared with the original node's commitment.
If all commitments match, the settlement is considered valid.
In case of mismatches, a
StackAttestationDisputeEvent
is emitted, and the dispute resolution process begins.
Fee Calculation Fees are calculated based on the following factors:
Base fee:
price
*num_claimed_compute_units
Sampling Consensus fee: An additional fee (
sampling_consensus_charge_permille
) is applied for tasks using Sampling Consensus.Attestation fee: For cross-validated executions, an extra fee (
cross_validation_extra_nodes_charge_permille
) is applied for each attestation node.
The total fee is deducted from the Stack
's allocated funds. Any unused funds are refunded to the user upon settlement.
Dispute Resolution In case of disputes:
The system initiates a dispute resolution process.
Trusted oracle nodes may be called upon to determine the correct result.
Nodes providing incorrect results may be slashed (have their collateral penalized).
Honest nodes (including the oracle) receive a portion of the slashed tokens as a reward.
Stack
Lifecycle
Creation: User creates a
Stack
, allocating funds and compute units.Execution: Selected node performs the computational task.
Settlement Attempt: Node attempts to settle the
Stack
(StackTrySettleEvent
).Attestation (if applicable): Additional nodes verify the execution.
Settlement: Successful settlement results in payment distribution and refunds.
Dispute Resolution (if necessary): Resolves conflicts in task execution or attestation.
Stack
s play a crucial role in the Atoma network, providing a structured way to manage computational resources, ensure fair compensation, and maintain the integrity of task execution across various security levels.
Atoma Db
The AtomaDb
is the central data structure that manages the global state of the Atoma network. It's implemented as a shared object on the Sui blockchain.
Key components of AtomaDb
:
tickets
:UID
for settlement tickets associated with the databasenext_node_small_id
: Tracks total registered nodes for generating sequentialSmallId
snext_task_small_id
: Tracks registered tasks for generating sequentialSmallId
snodes
:Table
storing information about each nodemodels
:ObjectTable
storing information about each model and its supporting nodestasks
:ObjectTable
storing information about registered tasksfee_treasury
: Balance of collected feescommunal_treasury
: Balance of slashed collateralcross_validation_probability_permille
: Probability of cross-validationcross_validation_extra_nodes_count
: Number of extra nodes sampled for cross-validationOther configuration parameters (e.g., registration collateral, slashing percentages)
Model Management
Model
s on Atoma represent the AI models that can be executed on the network. Each model is associated with one or more echelons and can be enabled or disabled.
Key aspects of model management:
Models are stored in the
models
ObjectTable ofAtomaDb
Each model has a unique name, modality, and a vector of supported echelons
Models can be added, removed, enabled, or disabled by the contract admin
Nodes can subscribe to serve specific models within their echelon
Functions for model management:
add_model
: Adds a new model to the systemremove_model
: Removes a model from the systemdisable_model
/enable_model
: Toggles the availability of a model
Echelon System
Echelons represent performance tiers within the Atoma network. They allow for differentiation of node capabilities and pricing.
Key aspects of the echelon system:
Each model supports one or more echelons
Echelons are identified by
EchelonId
Echelons define fees, performance expectations, and settlement timeouts
Nodes subscribe to models within specific echelons
Echelon properties:
input_fee_per_token
/output_fee_per_token
: Fees charged by nodes in this echelonrelative_performance
: Influences the likelihood of echelon selectionsettlement_timeout_ms
: Maximum time for settling a promptoracles
: Set of trusted nodes that can settle disputesnodes
: TableVec of nodes supporting this echelon
Slashing Mechanism
Slashing is a penalty mechanism to discourage malicious behavior or poor performance from nodes.
Key aspects of the slashing mechanism:
Nodes provide collateral upon registration, which can be slashed
Slashing occurs for timeout or incorrect results
Slashed tokens are moved to the communal treasury
Slashing parameters:
permille_to_slash_node_on_timeout
: Percentage of collateral slashed for timeoutspermille_for_oracle_on_dispute
: Percentage of slashed tokens given to the settling oraclepermille_for_honest_nodes_on_dispute
: Percentage of slashed tokens distributed to honest nodes
Slashing functions:
slash_node_on_timeout
: Slashes a node's collateral for not responding in timeslash_node_on_dispute
: Slashes a node's entire collateral for providing incorrect results
The slashing mechanism helps maintain the integrity and reliability of the Atoma network by providing economic incentives for good behavior and penalties for poor performance or malicious actions.
Constants
The contract defines several important constants:
InitialCollateralRequiredForRegistration
: The initial amount of collateral required for node registration. Collateral submitted by a node is subject to slashing, if the becomes unresponsive (Liveness failure) or the node provides tampered outputs (malicous behavior).InitialSettlementTimeoutMs
: The initial maximum time nodes have to settle a prompt.InitialPermilleToSlashNodeOnTimeout
: The initial percentage (in permille) of collateral slashed if a node doesn't respond within the timeout.Various task roles, compute unit types, modality types, optimization types, security levels, and performance units are defined as constants.
Events
Atoma's protocol relies heavily on events emitted on the Sui blockchain to orchestrate off-chain actions to be performed by users, nodes and verifiers. Here's a comprehensive list of the available events and their roles:
PublishedEvent:
Emitted once upon publishing the contract. Contains:
db
: The object ID of the Atoma DB (manages Atoma's global state)manager_badge
: The manager object ID (contract's published object ID)
NodeRegisteredEvent:
Emitted when a new node is registered in the Atoma network. Contains:
badge_id
: The ID of theNodeBadge
object assigned to the newly registered nodenode_small_id
: A unique SmallId assigned to the node for efficient referencing
NodeSubscribedToModelEvent:
Emitted when a node subscribes to serve a specific AI model. Contains:
node_small_id
:SmallId
of the subscribing nodemodel_name
: Name of the AI model the node subscribed toechelon_id
: ID of the echelon for this model subscription
NodeSubscribedToTaskEvent:
Emitted when a node subscribes to a task. Contains:
task_small_id
:SmallId
of the tasknode_small_id
:SmallId
of the subscribing nodeprice_per_compute_unit
: Price per compute unit set by the node for this task
TaskRegisteredEvent:
Emitted when a new task is registered in the system. Contains:
task_id
: The object ID of the newly registered Tasktask_small_id
:SmallId
of the newly registered task
TaskDeprecationEvent:
Emitted when a task is deprecated. Contains:
task_id
: The object ID of the deprecatedTask
task_small_id
:SmallId
of the deprecated taskepoch
: The epoch in which the task was deprecated
TaskRemoveEvent:
Emitted when a task is removed from the task table. Contains:
task_id
: The object ID of the removed Tasktask_small_id
:SmallId
of the removed taskremoved_at_epoch
: The epoch in which the task was removed
StackCreatedEvent:
Emitted when a new stack is created in the system. Contains:
stack_id
: The object ID of the newly created Stacksmall_id
: Unique identifier for the stack within the Atoma networkselected_node
: TheSmallId
of the node selected to process this stack's requestsnum_compute_units
: The number of compute units allocated to this stackprice
: The price per compute unit in TOMA tokens
StackTrySettleEvent:
Emitted when a node attempts to settle a stack. Contains:
stack_small_id
: TheSmallId
of the stack being settledselected_node_id
: TheSmallId
of the node selected to process the requests in the stackrequested_attestation_nodes
: Vector ofSmallId
s of nodes selected for attestation (if any)committed_stack_proof
: The Merkle root of the stack's execution proofstack_merkle_leaf
: The root of the Merkle tree for the first executionnum_claimed_compute_units
: Number of compute units claimed by the user
StackSettlementTicketEvent:
Emitted when a stack settlement ticket is successfully created and verified. Contains:
stack_small_id
:SmallId
of the settled stackselected_node_id
:SmallId
of the node that processed the stacknum_claimed_compute_units
: Number of claimed computed unitsrequested_attestation_nodes
: Vector ofSmallId
s of nodes selected for attestation (if any)dispute_settled_at_epoch
: The epoch at which the stack attestation is completely settledcommitted_stack_proof
: The committed stack proof
StackSettlementTicketClaimedEvent:
Emitted when a stack settlement ticket is claimed and funds are distributed. Contains:
stack_small_id
: TheSmallId
of the settled stackselected_node_id
: TheSmallId
of the node that processed the stackattestation_nodes
: Vector ofSmallId
s of nodes that attested to the settlementnum_claimed_compute_units
: Number of compute units actually used and claimeduser_refund_amount
: Amount of funds refunded to the user for unused compute units
StackAttestationDisputeEvent:
Emitted when there's a dispute in the attestation of a stack settlement. Contains:
stack_small_id
: SmallId of the disputed stackattestation_commitment
: The disputed attestation commitmentattestation_node_id
: TheSmallId
of the attesting nodeoriginal_node_id
: TheSmallId
of the original processing nodeoriginal_commitment
: The original commitment
These events provide a comprehensive tracking system for major actions and state changes within the Atoma network, enabling efficient off-chain processing and synchronization.
Error Codes
Error codes are defined with a base of 312012_000
for easy identification in logs. Some key error codes include:
ENodeRegDisabled
: Node registration is disabled.EModelDisabled
: The requested model is disabled.ENodeAlreadySubscribedToTask
: The node is already subscribed to the task.ETaskNotFound
: The specified task does not exist.Other error codes can be found in the contract logic.
Structs
Core Structs
AtomaManagerBadge
: Represents authority over the package. It corresponds to the object id of the wallet that first published the contract.NodeBadge
: Proof of registration for a node.SmallId
: A u64 ID assigned to either a node or a task for efficient referencing.Task
: Represents a computational task on the Atoma network.TaskRole
,Modality
,ComputeUnit
,Optimization
,SecurityLevel
,PerformanceUnit
: Various structs to define task properties.ReputationScore
: Represents the reputation score of a node. Upon registration, a node has a reputation score of100
, at each epoch the reputation score can either increase (up to a maximum of1000) or decrease up to a minimum of `0`.
Key Functions
The contract includes functions for:
Registering nodes
Create, deprecate and remove tasks.
Adding nodes to models (Deprecated)
Subscribing nodes to tasks
Managing task lifecycles
Handling node reputation and slashing
These functions are crucial for maintaining the Atoma network's integrity and managing computational resources effectively.
Admin functions
Currently, some functionality is dedicated to the administrator of the Atoma smart contract. This is intended to change in the near future, once we introduce robust community governance mechanisms, in the protocol.
Admin functions in Atoma provide privileged operations for managing the network. These functions require the AtomaManagerBadge
for authorization.
Key admin functions:
Model Management:
add_model
: Adds a new model to the systemremove_model
: Removes an existing modeldisable_model
/enable_model
: Toggles model availability
Echelon Management:
add_model_echelon
: Adds a new echelon to a modelremove_model_echelon
: Removes an echelon from a modelupdate_model_echelon
: Updates echelon parameters
Oracle Management:
add_model_echelon_oracle_node
: Adds an oracle node to a model echelonremove_model_echelon_oracle_node
: Removes an oracle node
Network Parameter Updates:
update_collateral_required_for_registration
: Changes the required collateral for node registrationupdate_settlement_timeout_ms
: Updates the global settlement timeoutupdate_permille_to_slash_node_on_timeout
: Modifies the slashing percentage for timeoutsupdate_cross_validation_probability_permille
: Adjusts the probability of cross-validationupdate_cross_validation_extra_nodes_count
: Changes the number of extra nodes for cross-validationNode Management:
permanently_disable_node
: Disables a node, preventing it from participating in the network
These admin functions allow for flexible management and adjustment of the Atoma network, ensuring it can adapt to changing requirements and maintain optimal performance.
Sampling Mechanism
The sampling mechanism in Atoma is responsible for selecting appropriate nodes to execute tasks. It's a crucial component that balances workload distribution, performance, and security.
Key aspects of the sampling mechanism:
Node Pool Creation:
Filters nodes based on task requirements (model, echelon, optimizations)
Considers node reputation scores and subscription status
Weighted Random Selection:
Uses a weighted random selection algorithm
Weights are influenced by node reputation scores and echelon relative performance
Cross-validation Sampling:
When cross-validation is triggered, additional nodes are sampled, with some protocol pre-defined probability constant
p
.The number of extra nodes is determined by
cross_validation_extra_nodes_count
Whitelist Consideration:
If a task has a whitelist, only nodes from whitelisted addresses are considered
Performance Optimization:
Utilizes efficient data structures (e.g.,
TableVec
) for fast samplingImplements early exit conditions to avoid unnecessary iterations
Key functions involved in sampling:
sample_nodes
: Main function for sampling nodes based on task requirementssample_nodes_for_model_echelon
: Samples nodes for a specific model and echelonget_node_weight
: Calculates the weight of a node for sampling purposes
The sampling mechanism ensures fair distribution of tasks, promotes high-quality nodes, and supports the cross-validation feature for enhanced output integrity and reliability. Moreover, sampling mechanisms favour decentralization.
Last updated