No sections match your search. Try a class name like ClientConfig or a concept like attestation.
Getting started
Quickstart#
Install the consumer SDK (Python ≥ 3.10). The import name is matrix_compute.
pip install matrix-compute-sdk
The SDK connects to the public production relay (wss://relay.matrix-compute.net) and settlement service (https://settlement.matrix-compute.net) automatically — no environment variables required:
import numpy as np
from matrix_compute import distributed_matmul
A = np.random.randn(8192, 8192).astype(np.float32)
B = np.random.randn(8192, 8192).astype(np.float32)
C = distributed_matmul(A, B, dtype="fp32", partitioning_strategy="output_grid_2d")
For local development or private relays, override the endpoints via environment variables or ClientConfig:
# Optional: override defaults for local development
export MATRIX_NOSTR_RELAYS=ws://127.0.0.1:8008
export MATRIX_SETTLEMENT_API_URL=http://127.0.0.1:8080
mode="trial" (or offline_mock_mode=True) runs a full distributed GEMM (tiling, client-side Hashcash PoW, zero-value mc_trial_... macaroon, Freivalds verification) with zero wallet setup.from matrix_compute import MatrixComputeClient
with MatrixComputeClient(mode="trial") as client:
C = client.matmul(A[:4096, :4096], B[:4096, :4096])
assert np.allclose(C, A[:4096, :4096] @ B[:4096, :4096], atol=1e-3)
Prefer zero install? Launch the interactive Google Colab notebooks directly in your browser:
Architecture#
Four components cooperate; only the consumer SDK runs on your machine.
| Component | Package | Role |
|---|---|---|
| Consumer SDK | matrix-compute-sdk | Tiles matrices, discovers & ranks workers, streams tiles over gRPC, verifies with Freivalds, manages L402 escrow, builds fraud proofs. |
| Discovery relay | matrix-compute-relay | Nostr relay (NIP-01/11/20/33) storing Kind 30000 worker announcements, matchmaking API, reverse-tunnel proxy for NAT'd workers. Default port 8008. |
| Worker node | matrix-compute-node | GPU/CPU daemon: hardware attestation, L402 payment gate, GEMM on CuPy/PyTorch/NumPy, signs result digests. gRPC port 50051. |
| Settlement | matrix-compute-settlement | Lightning HODL invoices, L402 macaroons, bond ledger and fraud-proof oracle. Takes a 2% routing fee. |
Flow: discover (Kind 30000) → escrow (HODL invoice held) → dispatch (gRPC MatrixComputeService) → verify (Freivalds) → settle or dispute (fraud proof slashes the bond, invoice is cancelled).
Consumer SDK
Everything below is importable from matrix_compute.
MatrixComputeClient#
High-level client that owns discovery, escrow, the gRPC channel pool and the orchestrator. Thread-safe and usable as a context manager.
MatrixComputeClient(config: ClientConfig | None = None, **kwargs)
If config is omitted, settings resolve as explicit kwargs → MATRIX_* environment variables → defaults. Any ClientConfig field can be passed as a kwarg.
client.matmul(A, B, ...)
client.matmul(
A: np.ndarray, # (M, K)
B: np.ndarray, # (K, N)
dtype: str | None = None, # "fp32" | "fp16" | "bf16"
tile_size: int | None = None, # default: config.default_tile_size (1024)
partitioning_strategy: str | PartitioningStrategy | None = None,
num_strips: int | None = None, # OUTER_PRODUCT_1D
grid_rows: int | None = None, # OUTPUT_GRID_2D P_r
grid_cols: int | None = None, # OUTPUT_GRID_2D P_c
grid_shape: tuple[int, int] | None = None,
) -> np.ndarray # (M, N)
Raises MatrixDimensionError for non-2D, empty or mismatched inputs, and MatrixComputeError subclasses for dispatch, verification or payment failures.
client.power_iteration(A, ...)
client.power_iteration(
A: np.ndarray,
v0: np.ndarray | None = None,
iterations: int = 100,
dtype: str | None = None,
lease_ttl_seconds: int | None = None, # remote VRAM lease (default 3600)
spot_check_probability: float | None = None, # Freivalds sampling per step (default 0.05)
normalize: bool = False,
) -> np.ndarray
Computes Aᵏ v₀ with stateful VRAM session leasing: A is uploaded once and stays resident on the worker; only vectors move per step.
client.close()
Releases channels, thread pools and mock workers. Idempotent; called automatically by with.
Top-level functions#
from matrix_compute import distributed_matmul, distributed_power_iteration
C = distributed_matmul(A, B, dtype="fp32", config=None, tile_size=None,
partitioning_strategy=None)
v = distributed_power_iteration(A, v0=None, iterations=100, dtype="fp32",
config=None, lease_ttl_seconds=None)
One-shot wrappers that create and close a MatrixComputeClient for you. A matrix-compute CLI entry point is also installed.
ClientConfig#
Pydantic model; every field can be set via kwargs or the listed environment variable.
| Field | Env var | Default | Description |
|---|---|---|---|
nostr_relays | MATRIX_NOSTR_RELAYS | ["wss://relay.matrix-compute.net"] | Discovery relay WebSocket URLs (comma-separated or JSON list). |
settlement_api_url | MATRIX_SETTLEMENT_API_URL | https://settlement.matrix-compute.net | Settlement service base URL. |
min_worker_vram_mb | MATRIX_MIN_WORKER_VRAM_MB | 4096 | Minimum worker VRAM (≥ 512). |
max_price_per_gflop | MATRIX_MAX_PRICE_PER_GFLOP | 0.001 | Price ceiling in sats/GFLOP. |
max_budget_sats | — | None | Hard cap on total spend; exceeding raises BudgetExceededError. |
dtype_preference | MATRIX_DTYPE_PREFERENCE | fp32 | fp32, fp16 or bf16. |
default_tile_size | MATRIX_DEFAULT_TILE_SIZE | 1024 | Square block size used by tiling heuristics. |
partitioning_strategy | MATRIX_PARTITIONING_STRATEGY | block_3d | See partitioning. |
workload_type | MATRIX_WORKLOAD_TYPE | gemm_one_shot | gemm_one_shot, iterative_power, batch_stream. |
num_strips / grid_rows / grid_cols | MATRIX_NUM_STRIPS / MATRIX_GRID_ROWS / MATRIX_GRID_COLS | auto | Explicit partition counts. |
freivalds_rounds | MATRIX_FREIVALDS_ROUNDS | 5 | Verification rounds k (false-accept ≤ 2−k). |
use_dynamic_freivalds_bound | MATRIX_USE_DYNAMIC_FREIVALDS_BOUND | True | Higham bound γ_K·‖A‖∞·‖B‖∞ instead of a fixed epsilon. |
verification_tolerance | MATRIX_VERIFICATION_TOLERANCE | 1e-4 | Baseline epsilon. |
lease_ttl_seconds | MATRIX_LEASE_TTL_SECONDS | 3600 | Remote VRAM lease for iterative workloads. |
spot_check_probability | MATRIX_SPOT_CHECK_PROBABILITY | 0.05 | Per-step Freivalds sampling for iterative workloads. |
require_confidential_compute | MATRIX_REQUIRE_CONFIDENTIAL_COMPUTE | True | Require TEE attestation + AES-256-GCM transport. See TEE. |
required_tee_type | MATRIX_REQUIRED_TEE_TYPE | None | Pin a TEE architecture. |
connect_timeout_seconds / task_timeout_seconds | MATRIX_CONNECT_TIMEOUT / MATRIX_TASK_TIMEOUT | 5.0 / 30.0 | gRPC connect / per-tile timeouts. |
max_retries | MATRIX_MAX_RETRIES | 3 | Retries on another worker after failure. |
consumer_privkey_hex | MATRIX_CONSUMER_PRIVKEY | random | secp256k1 key for identity and dispute signing. |
offline_mock_mode | MATRIX_OFFLINE_MOCK_MODE | False | Run fully in-process with test doubles. |
from matrix_compute import ClientConfig, MatrixComputeClient
config = ClientConfig(
min_worker_vram_mb=16384,
max_price_per_gflop=0.0008,
max_budget_sats=50_000,
freivalds_rounds=8,
)
client = MatrixComputeClient(config=config)
Partitioning strategies#
For C (M×N) = A (M×K) · B (K×N), the strategy decides what each worker receives and therefore how many bytes cross the WAN. Total work is always 2·M·K·N FLOPs. Counts below are in matrix elements; Rdown is download redundancy (downloaded / (M·N) − 1).
| Strategy | Each task gets | Upload | Download | Best for |
|---|---|---|---|---|
OUTPUT_GRID_2D"output_grid_2d" | Row block A[rᵢ, :] and column block B[:, cⱼ] on a P_r × P_c grid | P_c·MK + P_r·KN | MN — Rdown = 0, no local reduction | Large outputs, embedding search, slow downlinks |
OUTER_PRODUCT_1D"outer_product_1d" | Strip pair A[:, kₚ], B[kₚ, :] of s K-strips | MK + KN — upload-optimal | s·MN — Rdown = s−1, (s−1)·MN local adds | Huge inner dimension K, slow uplinks |
BLOCK_3D"block_3d" (default) | One t×t tile of A and of B per (i, j, l) block | ≈ 2·MNK / t | ≈ MNK / t — Rdown ≈ ⌈K/t⌉−1 | Small-VRAM workers, maximal parallelism |
from matrix_compute import PartitioningStrategy
# 4 x 8 output grid across 32 workers
C = client.matmul(A, B, partitioning_strategy=PartitioningStrategy.OUTPUT_GRID_2D,
grid_shape=(4, 8))
# 16 K-strips
C = client.matmul(A, B, partitioning_strategy="outer_product_1d", num_strips=16)
Use the MCP estimate_job_cost tool (backed by the SDK's BandwidthProfiler) to get exact MB and sat estimates for a shape before running.
Freivalds verification#
For each returned tile C, the SDK draws a random binary vector r ∈ {0,1}ᴺ and checks
That's three matrix–vector products — O(n²) instead of the O(n³) GEMM. A wrong result passes a single round with probability ≤ ½, so k rounds (freivalds_rounds, default 5) bound false-accepts at 2⁻ᵏ.
Floating-point tolerance uses Higham's bound ε = γ_K · ‖A‖∞ · ‖B‖∞ with γ_K = K·u / (1 − K·u) for the dtype's unit roundoff u, plus a relative_discrepancy_threshold guard against zero-work fraud on tiny inputs.
On failure the SDK raises FraudDetectedError, cancels the HODL invoice and submits a signed FreivaldsFraudProof. Building blocks are public: freivalds_verify, FreivaldsVerifier, FraudProofBuilder, verify_fraud_proof.
L402 payments & escrow#
Every tile is paid with a Lightning HODL invoice: funds lock when the task is dispatched and only settle (the preimage is released) after Freivalds passes. Failed verification cancels the invoice. Workers enforce payment with an L402 gate — tasks without a valid held invoice are rejected before any GPU memory is allocated.
To pay from your own LND node:
export MATRIX_LND_PAYER_ENABLED=true
export CONSUMER_LND_REST_URL=https://127.0.0.1:8081
export CONSUMER_LND_MACAROON_PATH=~/.lnd/data/chain/bitcoin/mainnet/admin.macaroon
export CONSUMER_LND_TLS_PATH=~/.lnd/tls.cert
Cap spend with max_budget_sats (enforced by BudgetController). The settlement layer takes a 2% routing fee.
Confidential computing (TEE)#
Freivalds guarantees correctness; TEEs add privacy. With require_confidential_compute=True (the default) the SDK only dispatches to workers presenting valid hardware attestation, verifies the evidence chain, binds it to a session nonce and encrypts tiles end-to-end with AES-256-GCM.
required_tee_type | Hardware |
|---|---|
None | Accept any valid TEE. |
"nvidia-cca" | NVIDIA Confidential Computing (H100/H200 CC mode). |
"amd-sev-snp" | AMD EPYC SEV-SNP confidential VMs. |
"intel-tdx" | Intel Xeon TDX trust domains. |
"simulated-cca" | Development / CI only. |
# Only AMD SEV-SNP enclaves
client = MatrixComputeClient(required_tee_type="amd-sev-snp")
# Public data, any worker (disables attestation + E2E encryption)
client = MatrixComputeClient(require_confidential_compute=False)
Attestation failures raise AttestationError subclasses such as AttestationChainInvalidError, AttestationNonceMismatchError or AttestationMeasurementMismatchError. Worker-side setup is under worker configuration.
Errors#
All exceptions derive from MatrixComputeError:
| Family | Notable subclasses |
|---|---|
ConfigurationError, MatrixDimensionError, TilingError | Invalid settings or shapes. |
DiscoveryError | NoWorkersFoundError, RelayConnectionError, RelayPoolExhaustedError, InvalidNostrEventError |
DispatchError | WorkerConnectionError, WorkerTaskRejectedError, TaskTimeoutError, WorkerSignatureError |
PaymentError | L402ChallengeError, MacaroonValidationError, BudgetExceededError, EscrowError, SettlementError, PreimageVerificationError |
VerificationFailedError | FraudDetectedError |
AttestationError | AttestationChainInvalidError, AttestationExpiredError, AttestationProviderUnsupportedError, … |
NoWorkersFoundError usually means your min_worker_vram_mb, max_price_per_gflop or TEE requirement is stricter than anything currently online — check the live dashboard.
Worker operators
Run matrix-compute-node on a GPU (or a confidential-computing CPU) and get paid per verified GFLOP.
1-command install#
The installer detects NVIDIA GPUs, AMD ROCm, AMD SEV-SNP, Intel TDX or CPU-only hosts, checks your container runtime, generates a worker Nostr keypair (stored in ~/.matrix/worker.env), enables outbound-only NAT traversal and renders the operator dashboard with a Lightning QR code.
# Linux / macOS
curl -sSL https://matrix-compute.com/worker.sh | bash
# Windows PowerShell
irm https://matrix-compute.com/worker.ps1 | iex
| bash flag | PowerShell | Default | Meaning |
|---|---|---|---|
--sats-per-gflop | -SatsPerGflop | 1.0 | Your price. |
--min-task-sats | -MinTaskSats | 1 | Minimum charge per task. |
--env-file | -EnvFile | ~/.matrix/worker.env | Where config/keys are written. |
--dry-run | -DryRun | off | Detect & print config without starting. |
| — | -PayoutAddress | prompt | Lightning payout address. |
| — | -NonInteractive | off | No prompts (CI / cloud templates). |
Docker deployment#
GPU images need the NVIDIA Container Toolkit. Build from the workspace root of the matrix-dockerimages repo:
docker build -f matrix-dockerimages/compute-node/Dockerfile.gpu -t matrix-compute-node:gpu .
docker run -d --name matrix-worker --gpus all \
-p 50051:50051 \
-e MATRIX_WORKER_GPU_DEVICE_INDEX=0 \
-e MATRIX_WORKER_DTYPE_PREFERENCE=fp16 \
-e MATRIX_WORKER_LIGHTNING_ROUTING_PUBKEY=<your-66-hex-node-pubkey> \
-e MATRIX_WORKER_SATS_PER_GFLOP=0.0005 \
matrix-compute-node:gpu
A CPU image (compute-node/Dockerfile) is also available. For a full local network (relay + settlement + worker) use docker compose -f matrix-dockerimages/docker-compose.yml up -d.
Worker configuration#
Each setting accepts MATRIX_*, MATRIX_WORKER_* or the unprefixed name.
| Env var | Default | Description |
|---|---|---|
MATRIX_WORKER_NOSTR_RELAYS | ["wss://relay.matrix-compute.net"] | JSON list of discovery relays (optional override). |
MATRIX_WORKER_SETTLEMENT_API_URL | https://settlement.matrix-compute.net | Settlement service (optional override). |
MATRIX_WORKER_LIGHTNING_ROUTING_PUBKEY | — | Your Lightning node pubkey for payouts. |
MATRIX_WORKER_PRIVKEY_HEX | ephemeral | secp256k1 identity key (keep it to preserve reputation). |
MATRIX_WORKER_SATS_PER_GFLOP | 0.0005 | Price per GFLOP. |
MATRIX_WORKER_MIN_TASK_SATS | 10 | Price floor per task. |
MATRIX_WORKER_GPU_DEVICE_INDEX | 0 | Which GPU to attest and use. |
MATRIX_WORKER_DTYPE_PREFERENCE | fp32 | fp32, fp16, bf16. |
MATRIX_WORKER_P2P_PORT / MATRIX_WORKER_P2P_MULTIADDR | 50051 / auto | gRPC port and the routable multiaddr to announce. |
MATRIX_ENABLE_CONFIDENTIAL_COMPUTE | true | Advertise and serve TEE attestation. |
MATRIX_ATTESTATION_PROVIDER | auto | auto, nvidia-cca, amd-sev-snp, simulated-cca, none. |
MATRIX_NAT_MODE | direct | direct or reverse_tunnel. |
MATRIX_RELAY_GRPC_ENDPOINT | — | Relay host:port for reverse tunnels. |
MATRIX_LOG_LEVEL | INFO | Log verbosity. |
NAT traversal#
Home connections rarely accept inbound gRPC. With MATRIX_NAT_MODE=reverse_tunnel (the installer default) the node dials the relay's gRPC tunnel service and keeps it alive with heartbeats (MATRIX_TUNNEL_HEARTBEAT_INTERVAL_SECONDS, default 30). The relay only matches consumers to tunnelled workers whose tunnel is currently active. Workers with a public IP can use direct mode and expose 50051 for lower latency.
Bonds & tiers#
Every announcement carries a bond_status with your staked sats. The bond is your skin in the game: a valid fraud proof slashes it. Tiers:
PROBATIONARY— new workers; auto-bond sweeps 50–100% (auto_bond_percent) of earnings into the bond until the graduation threshold (default 100,000 sats).FULL_TIER— fully bonded workers.BLACKLISTED/DEACTIVATED— slashed or retired keys.
MCP server
matrix-compute-mcp is the official Model Context Protocol server. It wraps a MatrixComputeClient and exposes five tools to any MCP client over stdio JSON-RPC 2.0.
Setup & authentication#
Add to claude_desktop_config.json, Cursor's mcp.json or Antigravity's MCP settings:
{
"mcpServers": {
"matrix-compute": {
"command": "uvx",
"args": ["matrix-compute-mcp", "--live-mode"],
"env": {
"MATRIX_L402_MACAROON": "<your-l402-macaroon>"
}
}
}
}
--live-mode (or MATRIX_OFFLINE_MOCK_MODE=false) the server runs against an in-process mock network — great for trying tools, but no real GPUs are used.| CLI flag | Env var | Description |
|---|---|---|
--relays | MATRIX_NOSTR_RELAYS | Comma-separated relay URLs. |
--settlement-url | MATRIX_SETTLEMENT_API_URL | Settlement service URL. |
--l402-macaroon | MATRIX_L402_MACAROON (+ MATRIX_L402_PREIMAGE) | L402 credentials for paid compute. |
--api-key | MATRIX_TRIAL_API_KEY | Trial key for zero-setup agent onboarding. |
--mock-mode / --live-mode | MATRIX_OFFLINE_MOCK_MODE | Hermetic mock network vs. real relays and workers. |
Auth precedence: L402 macaroon → trial API key → offline mock trial. A Docker image is also provided (matrix-dockerimages/mcp).
Tools reference#
Matrix inputs accept a file path (.npy, .npz, .safetensors) or an inline 2D JSON array.
| Tool | Parameters | Returns |
|---|---|---|
get_network_status | min_vram_mb?, max_price_per_gflop? | Online worker count, total VRAM, TEE enclaves, sats_per_gflop pricing. |
estimate_job_cost | m, k, n, dtype, partitioning_strategy (default output_grid_2d), tile_size, num_strips, grid_rows, grid_cols, sats_per_gflop? | Upload/download MB, task count, GFLOPs and sat estimate. |
execute_distributed_matmul | matrix_a, matrix_b, output_path?, tensor_key_a?, tensor_key_b?, dtype, partitioning_strategy, tile_size? | Verified C = A × B (inline or written to output_path). |
batch_similarity_search | queries (M×D), corpus_embeddings (N×D), top_k (default 5), dtype, output_path? | Top-k indices and cosine scores per query. |
compute_pca_svd | matrix, k, center (default true), method (randomized | power_iteration), output_path? | Top-k U, S, Vt. |
Typical agent loop: get_network_status → estimate_job_cost → confirm budget → execute_distributed_matmul.
AI primitives (matrix_compute_mcp.ai)#
The same verified building blocks the MCP tools use, importable from Python:
from matrix_compute_mcp.ai import (
DistributedLinear, # drop-in torch.nn.Linear, verified fwd + bwd
DistributedLoRALinear, # LoRA adapter layer
distributed_cosine_similarity,
distributed_pca_svd,
)
scores, indices = distributed_cosine_similarity(queries, corpus_embeddings, top_k=10)
layer = DistributedLinear(in_features=4096, out_features=4096)
lora = DistributedLoRALinear(in_features=4096, out_features=4096, r=16, lora_alpha=32.0)
U, S, Vt = distributed_pca_svd(embeddings, k=32, method="randomized")
Protocol
Kind 30000 worker announcements#
Workers publish NIP-33 parameterised replaceable events keyed by (pubkey, d). The newest created_at wins; ties break on the lowest event id. Key fields are duplicated as tags for cheap filtering; the full WorkerAnnouncePayload is JSON in content. Relays read tags first and fall back to content per attribute.
{
"kind": 30000,
"pubkey": "<worker secp256k1 pubkey>",
"created_at": 1761350400,
"tags": [
["d", "matrix-compute-worker"],
["p2p", "/ip4/203.0.113.7/tcp/50051"],
["lightning", "<66-hex node pubkey>"],
["gpu_model", "NVIDIA GeForce RTX 4090"],
["vram_mb", "24564"],
["sats_per_gflop", "0.0005"],
["min_task_sats", "10"],
["staked_sats", "100000"],
["nat_mode", "reverse_tunnel"],
["tee", "true"], ["tee_type", "nvidia-cca"]
],
"content": "{\"event\":\"WORKER_ANNOUNCE\",\"hardware\":{\"gpu_model\":...,\"peak_fp32_tflops\":82.6,...},\"pricing\":{...},\"bond_status\":{...}}"
}
Relay API#
One port (default 8008) multiplexes WebSocket and HTTP. All HTTP responses send Access-Control-Allow-Origin: *, so browsers can query them directly — this site's dashboard does exactly that.
| Endpoint | Description |
|---|---|
GET / + Upgrade: websocket | NIP-01 relay. ["REQ", id, {"kinds":[30000]}] replays stored announcements, sends EOSE, then streams live updates. |
GET / | NIP-11 relay information document. |
GET /health | status, active_workers, uptime_seconds, announcement/query counters. |
GET /telemetry/summary | Full telemetry: announcements by status, match success rate, latency percentiles. |
POST /rpc | JSON-RPC 2.0: QUERY_WORKERS, GET_TELEMETRY, HEALTH. |
POST /query | REST matchmaking with a bare WorkerQueryRequest body. |
curl -s https://relay.matrix-compute.net/rpc -H 'Content-Type: application/json' -d '{
"jsonrpc": "2.0", "id": 1, "method": "QUERY_WORKERS",
"params": { "min_vram_mb": 16384, "max_price_sats_per_gflop": 0.001,
"required_slots": 4, "require_tee": true, "required_tee_type": "nvidia-cca" }
}'
The response lists matched_workers with worker_pubkey, p2p_multiaddr, sats_per_gflop, reputation_score, tee_type and nat_mode. Tile transfer itself uses the gRPC MatrixComputeService defined in matrix-contracts/proto/compute_service.proto.
Fraud proofs#
A FreivaldsFraudProof proves max|A(Br) − Cr| > ε for a result the worker signed:
| Field | Meaning |
|---|---|
task_id, worker_pubkey, consumer_pubkey | Who and what is disputed. |
dimension_m/k/n, dtype | Shape and precision. |
matrix_a_hash, matrix_b_hash, invalid_result_c_hash | SHA-256 digests of inputs and the bad result. |
random_vector_r, vector_br, vector_abr, vector_cr | The Freivalds witness vectors. |
epsilon_tolerance, max_observed_discrepancy | Bound and observed ‖·‖∞ gap (must exceed the bound). |
worker_signature_on_result | Worker's signature over (task_id, invalid_result_c_hash). |
The settlement oracle independently re-verifies the vectors in O(M) before slashing.
Guides
Batched LLM inference & embedding search#
Scoring M queries against an N-document corpus is a single (M×D)·(D×N) GEMM — enormous output, small inner dimension. That's the ideal shape for OUTPUT_GRID_2D: each worker returns a disjoint block of scores, nothing is downloaded twice and nothing is summed locally.
import numpy as np
from matrix_compute_mcp.ai import distributed_cosine_similarity
queries = np.load("queries.npy").astype(np.float32) # (200_000, 1024)
corpus = np.load("corpus.npy").astype(np.float32) # (5_000_000, 1024)
scores, idx = distributed_cosine_similarity(queries, corpus, top_k=10)
The same pattern covers offline LLM batch inference: stack prompt activations into one big matrix per layer and use DistributedLinear or client.matmul(..., partitioning_strategy="output_grid_2d").
Iterative scientific solvers#
Power iteration, PageRank and spectral methods apply the same matrix hundreds of times. Re-uploading A every step would be WAN-bound, so the SDK leases worker VRAM: A is uploaded once, kept resident for lease_ttl_seconds, and only the vector travels each step. A random spot_check_probability fraction of steps is Freivalds-verified via verify_iterative_step.
from matrix_compute import MatrixComputeClient
with MatrixComputeClient(lease_ttl_seconds=1800, spot_check_probability=0.1) as client:
v = client.power_iteration(A, iterations=500, normalize=True)
dominant_eigenvalue = v @ (A @ v)
For top-k decompositions use distributed_pca_svd(X, k, method="power_iteration").
Autonomous L402 agents#
An agent with a Lightning wallet can buy compute without any human account: configure the MCP server with an L402 macaroon, then let the agent call estimate_job_cost before execute_distributed_matmul so it can reason about spend. Set max_budget_sats on the underlying client to hard-cap what any single session can pay.
Edge & constrained-device offloading#
A Raspberry Pi can't run a 30k×30k GEMM, but it can verify one: Freivalds needs only three matrix–vector products. Batch frames from an edge camera into photogrammetry / neural-field matrices, offload with distributed_matmul, and keep the O(n²) verification local. Use fp16 to halve upload size, and OUTER_PRODUCT_1D if your uplink is the bottleneck.