Skip to the content.

TorrAi — detailed documentation (EN)

🌐 Language / Язык: English · Русский · Short overview · Architecture · Rules R1–R33

TorrAi is torrent-style distributed storage and execution of local AI models. The interface follows uTorrent: a release list, peer table, a map of “pieces” (here: model layers), speeds, quota, seeding, trust and a separate streaming chat tab.

Contents

Quick start

python -m pip install -r requirements.txt
python run.py

Alternative on Windows: run.bat.

Tests:

python -m unittest discover -s tests -v          # unit + integration tests
python tests/smoke_ui.py                         # headless UI smoke test
$env:PYTHONPATH='.'; python tests/simulate_process.py  # end-to-end simulation

The end-to-end simulation covers demo chat, an OpenAI-compatible chat, adding/seeding/publishing a release, bundles, an agent fetched by URL, downloading layers over DHT, the download and generation queues, and incomplete-download healing.

The first launch creates ~/.torrai:

A demo release is added automatically: a sparse ~2.1 GB file, 24 layers, a signed manifest. In demo mode it is considered ready immediately (real weights are not downloaded), so chat works at once; in other modes progress starts from zero. Demo replies are synthetic diagnostics of streaming/UI, not answers from a real language model.

First launch and hybrid network

Before the engine starts, TorrAi shows a compact Welcome window. It briefly explains that the app uses CPU/GPU/VRAM/RAM, disk space for verified layers and the network for download and seeding; More details opens the full text about load, data storage, RAM volatility and security. The Continue button stays disabled until the mandatory consent checkbox is ticked; Exit quits without starting the engine.

Network modes are not chosen on first launch. The default is one hybrid mode, “LAN + Internet (DHT/peers/web-seeds)” (hybrid_network): the app searches the local network, the public DHT and web-seeds at the same time, switches between available sources and rebuilds the route when a node fails or degrades (R16). Consent is saved in ~/.torrai/settings.json (onboarding_accepted), so the window does not appear on every start.

Simple start

The Settings tab works in automatic mode by default: the model directory, speed, memory and context size, and the mode are chosen from free disk space and RAM. Usually pressing Save settings is enough. Restore auto settings resets everything to the recommended values, and Advanced settings opens expert parameters (ports, keys, R12/R20–R33 flags) only when needed. A choice made in the simple form (including Demo) is preserved while advanced settings are open — the old value in an advanced field does not overwrite it. Separate HDD/SSD folders/quotas, GPU/VRAM and queue limits are also hidden under advanced settings, keeping the simple mode short.

Chat becomes active only after the model is 100% downloaded in demo and distributed modes. In llama-server mode you need a path to the server binary; in local API mode you need an address and model name. These modes do not depend on torrent release progress. While the required model is not available, the input field and send button are disabled and chat explains the reason and the next step. Only a connected OpenAI-compatible server or distributed mode with real GGUF weights returns a real answer; otherwise chat text is a diagnostic stub, not a model reply.

Chat generation parameters are simplified: temperature, diversity (Top-P), answer length, context memory, and seed have an Auto mode and sliders. Auto is enabled by default (recommended values), and each parameter has a short description of what it does.

If a saved manifest was once corrupted by a local priority mutation (causing R13: model without a verified signature after restart), the app restores the signed copy from the local catalog at startup. Piece priorities no longer modify the signed manifest, so the error does not recur.

RAM + HDD, healing and tokens

The RAM + HDD tab in the release card shows the verified-layer cycle in two steps:

  1. Download within the RAM budget — verified layers on disk (local/total, bytes and percent). A layer reaches the cache only after a SHA-256 check against the signed manifest (R1); unverified bytes are neither stored nor served.
  2. Load into RAM/VRAM — how many verified layers are already warm in memory (warm/local). Until the model is started with Run, the second bar stays at zero: layers rest on HDD and are ready to load.

The “Ready OK” status appears when all layers are verified, the HDD copy is confirmed and the model is loaded into RAM/VRAM; chat and launch are then available without downloading again. A nearby warning explains that RAM is volatile and clears on shutdown/reboot, while the verified HDD copy persists, so layers are reloaded from disk instead of being downloaded again. The ? button explains both steps and the status. The same help is available for the layer route, clones/load, healing and the security block in settings.

Healing (🩹 Heal on the Torrents tab) lists incomplete models plus layers already visible on the network. The table shows readiness, missing pieces, local and network layers, sources, priority and token counters; Heal selected / Heal all tries web-seed/BEP19, DHT and LAN clones. The “Requested from network (tokens)” and “Served to network (tokens)” counters appear in the status bar, orchestrator summary, chat metrics, statistics and the heal window. The first counts calls to remote layers, the second counts requests your node served for other participants; both grow during distributed inference and layer seeding.

Integrity checks (R1/R5/R6)

When a .torrent is imported, its piece hashes (SHA-1) go into the signed manifest. The Recheck button compares available pieces against those hashes; not-yet-downloaded pieces are not treated as corrupted. The manifest now has FileInfo.sha256 and piece_hashes. The Publish action does not download the model: it only publishes an already verified release, filling missing file and layer hashes from the verified local cache, and re-signs the manifest. For incomplete models use 🩹 Heal — it opens a separate window with all models that have unverified pieces and resumes downloading from available sources. Network layer download without a SHA-256 in the signed manifest is disabled by default (require_layer_sha256): for models without such hashes use .torrent + libtorrent, which verifies pieces itself. Hardlink seeding is created only after a full check and license check; manifest file paths cannot escape the release directory. See RULES.md for details.

Security and storage

The full security description is available from the ? button in simple settings and in the “Security and storage (R1–R33)” group in advanced settings:

Model + agent bundle

The 📦 Build bundle button on the releases tab assembles a signed local release from a GGUF model and an agent source directory. The packer:

After assembly a bundle can be rechecked, seeded and published with the same buttons as a model. Signature checks and verify_release() also compare component SHA-256, so replacing agent/ or model/ does not pass as a valid bundle. Agent code is distributed as data only: TorrAi does not run it automatically and does not add it to autostart.

An agent may be provided not only as a local directory but also as a zip/tar/tar.gz URL. A URL is accepted only over http(s) and only with a mandatory archive SHA-256; the archive is downloaded to the cache, hash-checked and unpacked without absolute paths, .., symlinks or zip bombs. Provenance (source_url, archive_sha256) goes into the signed manifest.

Simplified model import by URL

The 🔗 By link button in the Torrents section opens a simple flow: provide an HTTP(S) link to a .gguf, a name and a disk-space limit (GB). TorrAi downloads the file with a progress bar, checks the limit/quota, automatically packs a signed bundle (with a minimal agent stub), verifies pieces and, if enabled, publishes the release. After that you can copy the magnet/.torrent and share it with a second PC: the other node adds it and downloads missing pieces/layers, resuming where it stopped. When the local copy becomes fully verified, TorrAi offers to open chat.

Resources, GPU and queues

What works today

Subsystem State
uTorrent-like UI onboarding with mandatory consent, toolbar, 13-column table, bottom tabs Overview / Layers / Files / Peers / Trackers / Speed / RAM + HDD / Inference, status bar with network and tokens, log
Add torrent magnet/name/size/layers/piece dialog + manifest signing
Model + agent bundle kind=bundle packer: model + code in one signed release, SHA-256 of files/pieces/components, seeding and publishing
Storage quota (global, HDD/SSD and per model including used space), sparse allocation, hardlink seeding, GGUF v3 parser (tensor offsets → layers)
Trust Ed25519 (PyNaCl) + SHA-256, quarantine verdict, Verified ≠ safe to run, publish only with consent
Swarm libtorrent 2.1 when a .torrent exists, otherwise built-in simulation; DHT/peers/speeds/seeding; web-seeds for cold start, including BEP19 url-list from .torrent (HTTP Range per file or layer URL templates, accepted only by manifest SHA-256)
Layer nodes LAN multicast and public DHT (BEP44 mutable items): node catalog under a separate salt, record versions and per-node shards, lookup by layer; announcements under network-secret and node_id keys plus a compatible per-release record. Layers are really downloaded from DHT nodes over signed RPC with SHA-256 verification, catalog cache 30 s, R7 order (critical layers first). Announcements are signed with HMAC-SHA256, DHT records with an Ed25519 key from the same secret. TLS over the HMAC channel with a certificate derived from the network secret; replay protection and SHA-256 checks against the manifest (R1/R9/R12)
Distributed RPC distributed mode: activations are computed by local layers and remote nodes over signed POST /v1/forward via TLS; the node response is checked by signature and hash, the route comes from the planner
GGUF kernel GGUF v3 tensor loader (F32/F16/BF16/Q4_0/Q8_0, K-quants Q4_K/Q5_K/Q6_K including Q4_K_M/Q5_K_M/Q6_K) and a real RMSNorm → attention (RoPE + GQA) → SwiGLU block; enabled automatically when a node has a real .gguf, otherwise a deterministic stub runs
KV cache the layer owner receives KV in the request and returns the updated sliding window; format {"k": [...], "v": [...]} with legacy list KV for compatibility, separate K/V are SHA-256 checked and live only inside one generation (R14)
Planner critical path + rarest-first, route grouping by node, piece priority R7, Run gate R8, automatic GPU layer selection by VRAM; clone choice by RTT, bandwidth, queue, load, reputation and per-peer model completeness
Orchestrator clones on disk/in RAM/VRAM, demand-driven hot layers, load spreading across clones, replication of overloaded layers, token counters and automatic R16 rerouting
Queues downloads: active limit, manual priority 0–9, auto-pause separate from user pause; generation: priority/FIFO, limits for all requests and per session, cancel waiting requests, RPC semaphore per node
Chat three columns (sessions/models · dialog · parameters and metrics), streaming, Stop, SQLite history, .md export, delete via 🗑 Delete or the session context menu (with confirmation, generation stop and history cleanup); the last session opens at startup instead of creating a new one; automatic model capability detection and adaptive attachment/generation buttons
Reliability a watcher interrupts generation if a layer node disappears (R16); auto-unload after idle (R19); startup failures (R13/R4) and Stop always finish generation even if an adapter sends no final chunk — chat never stays in “Generating…”
Reputation and seeding SQLite accounting of node successes/failures, latency and served bytes; reputation influences node selection; signed Ed25519 attestations carry observations between machines (freshness, no self-attestation, bounded weight); R12 trust policy is fail-closed by default: third-party scores count only from pinned observers, with a ban list, HEX pins of independent local keys, a source limit, optional majority quorum, and R20 Sybil protection via challenge-response with a minimum confirmed service. R21 binds a vote to release/layer by SHA-256 from the signed manifest; R22 checks source uniqueness against the DHT/LAN catalog; R23 confirms real byte exchange for that release/layer; R24 adds proof of work for observer identity; R25 signs node announcements with an independent Ed25519 key checked against pins; R26 derives self-certified node_id from the pubkey; R27 checks node_id/key consistency in the DHT catalog; R28 uses slot pointers to reduce node loss during publish races; R29 replaces local service accounting with a portable signed receipt; R30 accepts self-certified node_id instead of a manual HEX pin; R31 adds signed credit vouchers with a monotonic sequence and replay protection; R32 publishes the last voucher number in DHT for provider checks; R33 adds a signed provider receipt for an accepted voucher and records number conflicts. Legacy mesh_secret signatures remain only in secret mode; seeding earns credits, remote reads/RPC spend them, and requests are rejected at zero balance
Local API http://127.0.0.1:8080/v1 — /v1/models, /v1/status (including generation_queue), /v1/chat/completions with SSE and a priority parameter, /v1/images/generations, /v1/audio/speech; model modalities are returned in /v1/models and /v1/status

Connecting a real model

Option A — llama.cpp / Ollama / another OpenAI-compatible server. Settings → mode openai, Base URL (for example http://127.0.0.1:8080/v1 for llama-server or http://127.0.0.1:11434/v1 for Ollama), model name. Do not point Base URL at TorrAi’s own API on port 8080 — that creates a loop, now blocked with a clear message. If the model is “asleep” and the first token arrives after 30 seconds, increase Runtime timeout in advanced settings (default 300 s); the old timeout was tied to the remote-layer timeout and produced runtime error: timed out.

Option B — the app launches llama-server. Mode llama-server, provide the binary path and arguments.

Option C — no model. Mode demo: a deterministic generator that exercises the whole UI, streaming, API and statistics without weights. Its messages are marked as diagnostics, not real Llama answers.

Option D — distributed prototype. Mode distributed: the planner assigns local and remote layers; local layers apply a deterministic function and remote layers go through signed RPC to discovered nodes. If a real GGUF is in the cache/release, the real kernel runs for F32/F16/BF16/Q4_0/Q8_0 and K-quants Q4_K/Q5_K/Q6_K with separate K/V; other types (Q2_K/Q3_K/IQ/TQ) use the stub. Without real weights this is still only route diagnostics, not a model answer.

Chat adaptation to model modalities

Chat detects model capabilities itself: it requests input_modalities / output_modalities from an OpenAI-compatible server via GET /v1/models, parses explicit manifest/description fields and name heuristics (llava, whisper, dall-e, tts, flux, gpt-4o, etc.). Depending on the result, only applicable buttons appear: 🖼 Image, 🎵 Audio, 📎 File, and tasks such as Draw, Speak, Transcribe. Attachments and generated images/audio are shown in the dialog, saved to ~/.torrai/chat_media, and included in SQLite history and .md export.

If a model does not declare modalities, capabilities can be fixed manually: Settings → Inference → Model capabilities (auto, text, vision, audio, multimodal, imagegen, audiogen, all). The same place sets a separate Generation model (for /v1/images/generations and /v1/audio/speech) and the attachment size limit.

For OpenAI-compatible chat, attachments are sent as standard content parts: image_url with a data URL and input_audio with base64; dialog history is sent with the current request. Demo mode generates a test PNG image and a WAV signal so the whole interface can be checked without weights.

Real weights are not included in the repository. The demo manifest is synthetic: it verifies signing/quota/layer mechanics but contains no real tensors.

The 🌐 Layer nodes button on the main toolbar shows discovered nodes (including ones found via DHT), their reputation and source, lets you verify a signature, run a test layer computation and enable/disable your own node. Network secret, external address, ports and bootstrap nodes are set in Settings. Public publishing is enabled by the public DHT (BEP44) flag; if DHT is unavailable the app keeps working over LAN. Credit accounting and the initial balance are configured there too; the balance is visible in the nodes dialog and in /v1/status. The ⇄ Reputation button starts an exchange of signed observations (background gossip is enabled by the signed reputation gossip flag); 🛡 Verify observer, ★ Pin observer and ⛔ Block observer manage the R12/R20 lists directly from the node list. The trust mode (pinned/secret/off), lists, HEX keys, source limit, quorum and R20 Sybil settings are in Settings. There you can enable the R21 release/layer vote binding requirement, the R22 known-catalog-node requirement, the minimum release/layer service volume (R23, in MB), the signed service receipt (R29) flag, observer PoW difficulty (R24, 0–16 bits), the signed node announcements (R25) flag, the node ID from pubkey (R26) flag and an allowed-releases list. For R25 the announcement key must be pinned in the HEX key list as node_id=HEX; without pins, announcements are not accepted. R26 checks that node_id equals n- + the first 16 hex chars of SHA-256(pubkey) instead of a separate pin, and does not require a pin list if R25 is off; the same flag enables R27: DHT catalog records are rejected when their pubkey does not match node_id. The DHT catalog slots (R28) flag enables pointer records in 16 slots and reads all slots during lookup. The signed credit vouchers (R31) flag makes the client sign an Ed25519 permission to spend with a limit, sequence number and self-certified node_id; the provider rejects a request without a voucher, with a wrong address, expired or already accepted. The voucher checkpoint in DHT (R32) flag additionally publishes the last voucher number under the payer’s key; the provider requires the voucher number and signature hash to match the checkpoint, so an expired voucher does not pass on another machine either. The provider spend receipts (R33) flag makes the provider sign a receipt for every accepted voucher; the client verifies and stores it in SQLite, and when two different receipts for one payer number appear, subsequent vouchers are rejected. Enabled R26/R30 also allow signed votes, challenges and R29 receipts without a manual HEX pin if node_id is derived from the observer’s pubkey. The ⇩ DHT button downloads critical layers from DHT nodes over signed RPC; ⬇ Web-seed/BEP19 downloads missing layers from HTTP(S) sources in settings, the manifest or the url-list of an imported .torrent. A .torrent path can be specified directly in the Add model torrent dialog: TorrAi reads the infohash, sizes, files and BEP19 seeds, stores the torrent in ~/.torrai/torrents, and connects web-seeds both in libtorrent and in the layer downloader.

Architecture

See the detailed Mermaid diagrams in ARCHITECTURE.en.md.

torr_ai/
  core/       data models, EventBus, rules R1–R19
  trust/      signatures, hashes, verdicts, reputation, R12 trust policy, signed gossip
  storage/    quota, sparse files, hardlinks, GGUF parser
  swarm/      libtorrent backend + simulation + LAN discovery + BEP44 DHT node catalog
  inference/  layer planner, HMAC layer node, adapters, chat gateway, OpenAI API
  app/        SQLite state, settings, catalog, orchestrator
  ui/         main window, table, details, chat, settings, statistics

Threads: swarm and generation run in background threads; in Qt, signals reach the UI through bridges (EventBus → Signal); tables update at 5 Hz and the layer grid is virtualized by row.

What affects performance

Limitations of the current version

This is a working end-to-end prototype, not a production P2P network. In particular:

Vote binding to a release and layer hash from the signed manifest (R21), source checking against the DHT/LAN catalog with key-reuse control (R22), and confirmation of a vote by real byte exchange for that release/layer (R23) are implemented. R24 adds a computational fee for observer identity via PoW; R25 binds a node announcement to a signed independent key verified against pins; R26 makes the node identifier a self-certifying derivative of the pubkey; R27 checks that correspondence in the DHT catalog; R28 spreads catalog pointers across slots and reduces publish-race loss without CAS; R29 replaces local service accounting with a portable signed recipient receipt; R30 lets such a vote and receipt be confirmed by a self-certified node_id without a manual pin; R31 requires a signed credit spend permission with replay protection; R32 publishes the last voucher number in DHT for provider verification; R33 issues a signed receipt for an accepted voucher and records number conflicts. Full cryptographic node uniqueness without a global PKI/consensus remains an open problem. Full catalog consensus requires CAS/a new BEP44 version and is not implemented in libtorrent 2.1 yet.