Spaces:
Sleeping
Sleeping
Commit ·
fa4d74b
1
Parent(s): 07ba06f
Rename project to FALL and configure for Hugging Face Spaces deployment
Browse filesFiles changed (29)
- Dockerfile+4-2
- README.md+13-4
- app.pyAdded+77
- pytest.iniAdded+6
- scripts/run_client_ui.py+28-27
- scripts/run_miner.py+3-2
- scripts/run_virtual_swarm.pyDeleted-149
- swarmnet/client/embedder.py+46-57
- swarmnet/config.py+5-2
- swarmnet/miner/layer_runner.py+107-78
- swarmnet/miner/worker_server.py+22-15
- swarmnet/moe/moe_router.py+14-16
- swarmnet/protocol/tensor_codec.py+67-44
- test_attn.pyDeleted-20
- test_layer.pyDeleted-20
- test_layer_2.pyDeleted-19
- test_layer_3.pyDeleted-22
- tests/compare_exact.pyDeleted-83
- tests/debug_causal.pyDeleted-57
- tests/debug_causal_mask.pyDeleted-63
- tests/debug_client_code.pyDeleted-42
- tests/debug_client_fp16.pyDeleted-53
- tests/debug_pipeline.pyDeleted-56
- tests/debug_quant.pyDeleted-54
- tests/debug_quant_pipeline.pyDeleted-77
- tests/debug_quant_test.pyDeleted-49
- tests/test_chat_ws.py+14-29
- tests/test_codec_loss.py+17-18
- tests/test_swarm_pipeline.py+22-30
17 unmodified lines18192021222122232417 unmodified linesENV PYTHONUNBUFFERED=1ENV PYTHONPATH=/app
# Default command (can be overridden by docker-compose or run arguments)ENTRYPOINT ["python", "scripts/run_miner.py"]EXPOSE 7860
# Default command for Hugging Face SpacesENTRYPOINT ["python", "app.py"]1234567891011112131415671617918192021---title: FALL • Decentralized P2P AI Meshemoji: 🍂colorFrom: ambercolorTo: redsdk: dockerapp_port: 7860pinned: false---
# 🌐 AirCompute (SwarmNet)# 🍂 FALL (SwarmNet)### *Self-Sustaining Decentralized P2P AI Compute & Inference Utility*
[](https://opensource.org/licenses/MIT)[]()[]()[]()[]()
AirCompute is a decentralized, peer-to-peer AI compute mesh that turns frontier AI models (DeepSeek-V3 671B, Llama-3.3 70B, Qwen-2.5 72B) into a low-cost, self-sustaining utility—like mobile internet or electricity—by pooling idle consumer hardware across the globe.FALL is a decentralized, peer-to-peer AI compute mesh that turns frontier AI models into a low-cost, self-sustaining utility by pooling idle consumer hardware across the globe.
---
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677#!/usr/bin/env python3"""FALL (SwarmNet) - Hugging Face Space Production EntrypointRuns on port 7860 (Hugging Face default).Launches:1. DHT Genesis Node & Client UI on 0.0.0.0:78602. In-process/sub-process Local Swarm Miners (L0-L14 & L15-L29) so visitors get an instant, fully functional decentralized pipeline demo out-of-the-box."""import sysimport osimport subprocessimport timeimport uvicorn
# Ensure repository root is in python pathROOT_DIR = os.path.abspath(os.path.dirname(__file__))sys.path.insert(0, ROOT_DIR)
from swarmnet.config import CONFIG
def main(): port = int(os.environ.get("PORT", 7860)) print("=" * 70) print("🍂 FALL: DECENTRALIZED P2P AI INFERENCE MESH") print(f"🚀 Initializing on Port {port} for Hugging Face Spaces...") print("=" * 70)
env = os.environ.copy() env["PYTHONUNBUFFERED"] = "1" env["PYTHONPATH"] = ROOT_DIR
# 1. Start Miner 1 (Layers 0 to 14) in background print("⚡ Starting Swarm Miner 01 (Layers 0-14)...") m1_proc = subprocess.Popen( [ sys.executable, "scripts/run_miner.py", "--miner-id", "hf_miner_alpha_01", "--port", "8001", "--dht-port", "8470", "--layers", "0-14", "--bootstrap-ip", "127.0.0.1", "--bootstrap-port", "8468" ], env=env )
# 2. Start Miner 2 (Layers 15 to 29) in background print("⚡ Starting Swarm Miner 02 (Layers 15-29)...") m2_proc = subprocess.Popen( [ sys.executable, "scripts/run_miner.py", "--miner-id", "hf_miner_beta_02", "--port", "8002", "--dht-port", "8471", "--layers", "15-29", "--bootstrap-ip", "127.0.0.1", "--bootstrap-port", "8468" ], env=env )
# Allow background miners to spin up before UI starts time.sleep(2)
# 3. Launch the Client UI & DHT Genesis server on port 7860 from scripts.run_client_ui import app print(f"\n🌐 FALL UI & Swarm Genesis listening on http://0.0.0.0:{port}\n") try: uvicorn.run(app, host="0.0.0.0", port=port, log_level="info") finally: print("\n🛑 Terminating background miner processes...") m1_proc.terminate() m2_proc.terminate()
if __name__ == "__main__": main()123456[pytest]testpaths = testspython_files = test_*.pyaddopts = -qmarkers = model: needs real HF model weights (downloads SmolLM-135M on first run)39 unmodified lines4041424344454647484950515253545556434445464748495051521 unmodified line545556645758596020 unmodified lines8182839184858687883 unmodified lines971972973981982974975976977978984985979980981982983989984985991986987988989990991992993994995996997996997998999998999100010011002100370 unmodified lines1074107510761076107710781079108039 unmodified linesledger.balances["miner_laptop_01"] = 100.0ledger.balances["miner_phone_02"] = 100.0
print("🧠 Pre-loading Neural AI Model (Qwen/Qwen2.5-1.5B-Instruct)...")MODEL_ID = "Qwen/Qwen2.5-1.5B-Instruct"try: tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, local_files_only=True) model = AutoModelForCausalLM.from_pretrained(MODEL_ID, local_files_only=True)except Exception: tokenizer = AutoTokenizer.from_pretrained(MODEL_ID) model = AutoModelForCausalLM.from_pretrained(MODEL_ID)
# Initialize Client UI (We only need Embedder + LM Head, so we delete the massive Transformer Layers to save RAM!)del model.model.layersimport gcgc.collect()model.eval()from swarmnet.config import CONFIGfrom swarmnet.client.embedder import LocalSplitClient
print(f"🧠 Loading Local Split Client for {CONFIG.MODEL_NAME}...")client_model = LocalSplitClient(model_name=CONFIG.MODEL_NAME)tokenizer = client_model.tokenizertotal_layers = 30
# Start DHT Genesis Nodedht_genesis = SwarmDHTNode(dht_port=8468)1 unmodified line@app.on_event("startup")async def startup_event(): await dht_genesis.start() print(f"✅ Loaded 28 transformer layers. Sharding: Miner 1 (L0-L13), Miner 2 (L14-L27)") print(f"✅ DHT Genesis listening on UDP 8468. Swarm Model: {CONFIG.MODEL_NAME} (30 layers)")
def get_real_laptop_memory_mb(): """Returns actual Linux RSS memory in MB used by this process."""20 unmodified lines<head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no"> <title>AirCompute • Decentralized AI Network</title> <title>FALL • Decentralized AI Network</title> <!-- Google Fonts --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>883 unmodified lines for step in range(num_gen_tokens): t_start = time.time() # 1. Local Embed (H_0) embeds = model.model.embed_tokens(input_ids.to("cpu")) # 1. Local Embed (H_0) - for step 0 pass all prompt tokens; for subsequent steps pass newly generated token curr_input = input_ids if step == 0 else input_ids[:, -1:] start_pos = 0 if step == 0 else input_ids.shape[1] - 1 embeds = client_model.embed(curr_input) # 2. FP8 Quantize fp8_bytes, _, _ = TensorCodec.quantize_fp16_to_fp8(embeds.to(torch.float16)) # 2. Encode to FP16 wire bytes wire_bytes = TensorCodec.encode_payload(embeds) # 3. P2P Swarm Pipeline Forward Pass (Client ➔ Laptop L0-L14 ➔ Phone L15-L29) try: miner1_url = await dht_genesis.find_peer(layer_index=0) or "http://127.0.0.1:8001" miner1_url = await dht_genesis.find_peer(layer_index=0, model=CONFIG.MODEL_NAME) or "http://127.0.0.1:8001" async with httpx.AsyncClient(timeout=120.0) as client: resp = await client.post(f"{miner1_url}/forward", content=fp8_bytes) resp = await client.post( f"{miner1_url}/forward", content=wire_bytes, headers={ "X-Session-ID": "ui_chat_session", "X-Start-Pos": str(start_pos) } ) if resp.status_code != 200: print(f"⚠️ [DEBUG] Swarm pipeline resp status {resp.status_code}! Breaking.") break # Dequantize final activations after Layer 29 and apply final RMSNorm h_last = TensorCodec.dequantize_fp8_to_fp16(resp.content, device="cpu").to(model.dtype) h_normed = model.model.norm(h_last) next_token_logits = model.lm_head(h_normed)[:, -1, :] # Dequantize final activations and compute logits locally h_last = TensorCodec.decode_payload(resp.content, device="cpu") next_token_logits = client_model.logits(h_last) except Exception as e: print(f"⚠️ [DEBUG] Exception in loop: {e}") import traceback70 unmodified linesasync def health_check(): return { "status": "HEALTHY", "model": "Qwen2.5-1.5B-Instruct", "model": CONFIG.MODEL_NAME, "layers": total_layers, "mesh_nodes": ["miner_laptop_01", "miner_phone_02"], "user_balance": ledger.get_balance(user_pubkey),20 unmodified lines212223242425252627282920 unmodified lines parser.add_argument("--bootstrap-ip", type=str, default=None, help="Bootstrap node IP for DHT") parser.add_argument("--bootstrap-port", type=int, default=None, help="Bootstrap node UDP Port") from swarmnet.config import CONFIG parser.add_argument("--model-name", type=str, default="Qwen/Qwen2.5-1.5B-Instruct", help="Hugging Face model ID") parser.add_argument("--total-layers", type=int, default=28, help="Total layers in model") parser.add_argument("--model-name", type=str, default=CONFIG.MODEL_NAME, help="Hugging Face model ID") parser.add_argument("--total-layers", type=int, default=30, help="Total layers in model") args = parser.parse_args() 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149#!/usr/bin/env python3"""AirCompute 1-Click Interactive Virtual Swarm DemoSimulates a live decentralized AI inference mesh with Speculative Swarm & Fuel Credit Ledger."""import sysimport osimport timeimport torch
# Ensure swarmnet package is in python pathsys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
from swarmnet.config import CONFIGfrom swarmnet.client.embedder import LocalSplitClientfrom swarmnet.client.speculative_draft import SpeculativeDrafterfrom swarmnet.miner.layer_runner import LayerMinerRunnerfrom swarmnet.moe.moe_router import SparseMoERouterfrom swarmnet.coordinator.dht_registry import SwarmDHTRegistryfrom swarmnet.coordinator.trap_verifier import TrapVerifierAgentfrom swarmnet.coordinator.ledger import FuelCreditLedgerfrom swarmnet.crypto.state_channel import StateChannelSignerfrom swarmnet.protocol.tensor_codec import TensorCodecfrom swarmnet.protocol.messages import PeerRegistration
def run_virtual_swarm_demo(prompt: str = "Explain how distributed AI makes intelligence cheaper for the world"): print("=" * 75) print("🌐 AIRCOMPUTE (SWARMNET): LIVE DECENTRALIZED P2P AI INFERENCE SWARM") print("=" * 75) d_model = 1024 vocab_size = 1000 # 1. Initialize Coordinator & Ledger print("\n[1/5] 📡 Initializing Swarm Coordinator & Kademlia Geo-Pod DHT...") dht = SwarmDHTRegistry() ledger = FuelCreditLedger() verifier = TrapVerifierAgent() # Register 3 Regional Miner Nodes (Frankfurt Geo-Pod) miners = [ PeerRegistration(peer_id="miner_eu_01", host="192.168.1.10", port=8001, vram_mb=8192, tflops=18.5, region="eu-central", assigned_layer_start=2, assigned_layer_end=10), PeerRegistration(peer_id="miner_eu_02", host="192.168.1.11", port=8002, vram_mb=8192, tflops=22.0, region="eu-central", assigned_layer_start=11, assigned_layer_end=20), PeerRegistration(peer_id="miner_eu_03", host="192.168.1.12", port=8003, vram_mb=16384, tflops=35.0, region="eu-central", assigned_layer_start=21, assigned_layer_end=30), ] for m in miners: dht.register_peer(m) ledger.balances[m.peer_id] = 100.0 # Initial seeding balance pod = dht.form_geo_pod("pod_frankfurt_01", region="eu-central", model_name="Llama-3.3-70B-MoE") print(f" ✅ Geo-Pod '{pod.pod_id}' formed with 3 Miner nodes across {len(pod.pipeline)} layer slices.") # 2. Setup Client & State Channel print("\n[2/5] 🔒 Initializing Local Client (Split-Learning + 0.5B Speculative Drafter)...") client = LocalSplitClient(vocab_size=vocab_size, d_model=d_model) drafter = SpeculativeDrafter(vocab_size=vocab_size, d_model=256, initial_k=5) signer = StateChannelSigner() user_pubkey = signer.public_key_hex ledger.balances[user_pubkey] = 50.0 # User has 50 prepaid Fuel Credits print(f" ✅ Client Key: {user_pubkey[:16]}... | Balance: {ledger.get_balance(user_pubkey):.2f} Fuel Credits") # 3. Instantiate Layer Workers & MoE Router miner_runners = [ LayerMinerRunner(layer_start=2, layer_end=10, d_model=d_model), LayerMinerRunner(layer_start=11, layer_end=20, d_model=d_model), LayerMinerRunner(layer_start=21, layer_end=30, d_model=d_model) ] moe_router = SparseMoERouter(num_experts=16, top_k=4, d_model=d_model) # 4. Execute Streaming Inference with Speculation print(f"\n[3/5] 🚀 User Prompt: \"{prompt}\"") print(" 🔒 [Split-Learning]: Text converted to hidden activation H_1 on local device. Zero text sent over network.") print("\n" + "-" * 75) print("⚡ LIVE TOKEN GENERATION STREAM (Speculative Swarm Acceleration):") print("-" * 75) # Simulated input prompt tokens input_ids = torch.tensor([[10, 25, 88, 142, 310]]) tokens_generated = 0 start_time = time.perf_counter() sample_words = [ "Distributed", "AI", "democratizes", "frontier", "intelligence", "by", "pooling", "idle", "consumer", "devices", "globally.", "Through", "speculative", "decoding", "and", "sparse", "Mixture-of-Experts", "routing,", "computation", "becomes", "as", "cheap", "as", "air", "and", "accessible", "to", "every", "student,", "researcher,", "and", "builder", "worldwide." ] for word_idx, word in enumerate(sample_words): # Step A: Local embedding + Layer 1 h_1 = client.encode_and_scramble(input_ids) packed_h1, _, _ = TensorCodec.quantize_fp16_to_fp8(h_1) # Step B: Swarm Pipeline forward traversal # Miner 1 packed_h10 = miner_runners[0].execute_forward_slice(packed_h1, session_id="demo_session") # Miner 2 + MoE Router h10_unpacked = TensorCodec.dequantize_fp8_to_fp16(packed_h10) moe_out, dispatched = moe_router(h10_unpacked.to(torch.float32)) packed_moe, _, _ = TensorCodec.quantize_fp16_to_fp8(moe_out) packed_h20 = miner_runners[1].execute_forward_slice(packed_moe, session_id="demo_session") # Miner 3 packed_h30 = miner_runners[2].execute_forward_slice(packed_h20, session_id="demo_session") # Step C: Local LM Head decodes next token locally final_h = TensorCodec.dequantize_fp8_to_fp16(packed_h30).to(torch.float32) next_tok = client.decode_and_sample(final_h, temperature=0.7) # Stream word with realistic typing pace sys.stdout.write(f"{word} ") sys.stdout.flush() time.sleep(0.04) # ~25 tokens/sec tokens_generated += 1 # Update input tokens input_ids = torch.cat([input_ids, torch.tensor([[next_tok % vocab_size]])], dim=1) # Step D: State channel micro-voucher debit voucher = signer.create_debit_voucher("chan_live_01", tokens_consumed=1) ledger.process_voucher(voucher) # Credit seeders for m in miners: ledger.credit_seeder(m.peer_id, tokens_computed=1)
elapsed = time.perf_counter() - start_time print("\n" + "-" * 75) # 5. Summary & Economics Report print(f"\n[4/5] 📊 PERFORMANCE TELEMETRY:") print(f" • Total Tokens Generated: {tokens_generated}") print(f" • Time Elapsed: {elapsed:.2f} seconds") print(f" • Effective Throughput: {tokens_generated / elapsed:.1f} tokens/sec") print(f" • Inter-Token Latency (ITL): {(elapsed / tokens_generated) * 1000.0:.1f} ms") print(f"\n[5/5] 💳 PROSUMER LEDGER & MICRO-BILLING SETTLEMENT:") print(f" • User Remaining Balance: {ledger.get_balance(user_pubkey):.4f} Fuel Credits (Deducted {tokens_generated/1000.0:.4f})") for m in miners: print(f" • {m.peer_id} Balance: {ledger.get_balance(m.peer_id):.4f} Fuel Credits (Earned +{tokens_generated/1000.0:.4f})") print("\n" + "=" * 75) print("✅ SWARM INFERENCE COMPLETE: ZERO TEXT EXPOSED, FULL PROOF-OF-COMPUTE SETTLED.") print("=" * 75)
if __name__ == "__main__": prompt = sys.argv[1] if len(sys.argv) > 1 else "Explain how distributed AI makes intelligence cheaper for the world" run_virtual_swarm_demo(prompt)12323456789101112131467891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859601516171819202122232425262728293031323334353637383940414243444546474849"""Client-Side Split-Learning Embedder & Local LM HeadGuarantees 100% user privacy: text/tokens never leave the user's local machine.Client-side split: token embedding (in) and final norm + LM head (out) run locally.
PRIVACY - READ THIS: This split does NOT hide the prompt from the first miner. Embedding rows are public (they ship with the open model), so a nearest-neighbour lookup recovers every token exactly (see tests/test_privacy_reality.py). Running a few layers locally does not fix this either; activation-inversion attacks are well documented. The only property that holds: the sampled OUTPUT token is chosen locally. Real prompt privacy needs trusted hardware, MPC/HE, or running the whole model locally."""from typing import Optional
import torchimport torch.nn as nnfrom typing import Tuple, List
class LocalSplitClient(nn.Module): def __init__(self, vocab_size: int = 49152, d_model: int = 576, device: str = "cpu"): super().__init__() self.vocab_size = vocab_size self.d_model = d_model self.device = device # 1. Local Embedding Matrix self.embed_tokens = nn.Embedding(vocab_size, d_model) # 2. Local Transformer Layer 1 (Scrambles token representation) self.local_layer_1 = nn.TransformerEncoderLayer( d_model=d_model, nhead=9, dim_feedforward=d_model * 4, activation="gelu", batch_first=True ) # 3. Local Final RMSNorm & LM Head (De-scrambles swarm output locally) self.final_norm = nn.LayerNorm(d_model) self.lm_head = nn.Linear(d_model, vocab_size, bias=False) self.to(device)
def encode_and_scramble(self, input_ids: torch.Tensor) -> torch.Tensor: """ Executes local embedding + Layer 1 on client machine. Returns obfuscated high-dimensional vector H_1 to dispatch to public swarm. """ with torch.no_grad(): x = input_ids.to(self.device) embeddings = self.embed_tokens(x) h_1 = self.local_layer_1(embeddings) return h_1
def decode_and_sample(self, swarm_h_last: torch.Tensor, temperature: float = 0.7) -> int: """ Takes the final hidden state from the last swarm miner and decodes next token locally. """ with torch.no_grad(): h_last = swarm_h_last.to(self.device) normed = self.final_norm(h_last) logits = self.lm_head(normed[:, -1, :]) # Take logits of last position if temperature > 0: probs = torch.softmax(logits / temperature, dim=-1) next_token_id = torch.multinomial(probs, num_samples=1).item() else: next_token_id = torch.argmax(logits, dim=-1).item() return next_token_idfrom transformers import AutoModelForCausalLM, AutoTokenizer
from swarmnet.config import CONFIG
class LocalSplitClient: def __init__(self, model_name: str = CONFIG.MODEL_NAME, device: str = "cpu", dtype: torch.dtype = torch.float32): self.model_name, self.device, self.dtype = model_name, device, dtype self.tokenizer = AutoTokenizer.from_pretrained(model_name) # TODO(roadmap P1): load only embed/norm/lm_head tensors instead of the full model. hf = AutoModelForCausalLM.from_pretrained(model_name, dtype=dtype) self.config = hf.config self.embed_tokens = hf.model.embed_tokens.to(device).eval() self.final_norm = hf.model.norm.to(device).eval() self.lm_head = hf.lm_head.to(device).eval() # may be tied to embed_tokens del hf
@torch.no_grad() def embed(self, input_ids: torch.Tensor) -> torch.Tensor: return self.embed_tokens(input_ids.to(self.device))
@torch.no_grad() def logits(self, last_hidden: torch.Tensor) -> torch.Tensor: h = last_hidden.to(self.device, self.dtype) return self.lm_head(self.final_norm(h[:, -1, :]))
@torch.no_grad() def sample(self, last_hidden: torch.Tensor, temperature: float = 0.0, generator: Optional[torch.Generator] = None) -> int: logits = self.logits(last_hidden) if temperature <= 0: return int(logits.argmax(-1).item()) probs = torch.softmax(logits / temperature, dim=-1) return int(torch.multinomial(probs, 1, generator=generator).item())122345678891011121314"""AirCompute Global Network & Model ConstantsFALL Global Network & Model Constants"""from dataclasses import dataclass
@dataclass(frozen=True)class NetworkConfig: # Model dimensions # Single source of truth for the served model. Miners, client and DHT keys must agree. MODEL_NAME: str = "HuggingFaceTB/SmolLM-135M-Instruct"
# Model dimensions (legacy toy defaults; real code reads dims from the HF config) DEFAULT_D_MODEL: int = 4096 DEFAULT_NUM_HEADS: int = 32 DEFAULT_VOCAB_SIZE: int = 32000123345678910111213145151617181920910111213141516171819202122232425262728293031323334353637383940412122232425262728293031323334353637383940414243444544454647484950515253545556574647484950515253545556575859606162636465665960676268646566676869707172737475767778798081828384858687888969707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118"""Layer Miner Execution EngineExecutes forward-pass Transformer blocks across assigned model layer slices.Runs a contiguous slice of a HuggingFace decoder model's layers.
Correctness contract (enforced by tests/test_pipeline_equivalence.py): client embed -> shard_1 -> ... -> shard_n -> client norm+lm_head must reproduce HF `generate()` greedy output token-for-token (FP16 wire).
Protocol per session: - First call: start_pos=0 with the full prompt's hidden states (prefill). - Next calls: start_pos=<tokens already processed>, hidden states of NEW tokens only. - start_pos=0 always resets the session's KV cache. - Any other start_pos that disagrees with the cached length raises KVDesyncError."""import loggingimport gcfrom collections import OrderedDictfrom typing import Optional
import torchimport torch.nn as nnfrom typing import Tuple, List, Optional
logger = logging.getLogger(__name__)from transformers import AutoModelForCausalLMfrom swarmnet.miner.paged_kv import PagedKVCachePoolfrom swarmnet.protocol.tensor_codec import TensorCodec
class ShardedLayerBlock(nn.Module): def __init__(self, layer_idx: int, d_model: int = 576, num_heads: int = 9): super().__init__() self.layer_idx = layer_idx self.d_model = d_model self.num_heads = num_heads self.attn_norm = nn.LayerNorm(d_model) self.attn = nn.MultiheadAttention(d_model, num_heads, batch_first=True) self.ffn_norm = nn.LayerNorm(d_model) self.ffn = nn.Sequential( nn.Linear(d_model, d_model * 4), nn.GELU(), nn.Linear(d_model * 4, d_model) )
def forward(self, x: torch.Tensor) -> torch.Tensor: # Pre-LN Self-Attention normed = self.attn_norm(x) attn_out, _ = self.attn(normed, normed, normed) x = x + attn_out # Pre-LN Feedforward ffn_out = self.ffn(self.ffn_norm(x)) x = x + ffn_out return xfrom transformers import AutoConfig, AutoModelForCausalLM, DynamicCache
from swarmnet.config import CONFIGfrom swarmnet.protocol.tensor_codec import FP16, TensorCodec
class KVDesyncError(RuntimeError): """Client and miner disagree on how many tokens this session has processed."""
def build_causal_mask(q_len: int, start_pos: int, dtype: torch.dtype, device) -> torch.Tensor: """Additive 4D mask [1, 1, q_len, start_pos + q_len]. Query i may attend keys 0..start_pos+i.
Passed explicitly so correctness does not depend on SDPA's implicit `is_causal` fallback (without it, eager attention silently produces garbage). """ kv_len = start_pos + q_len q_pos = torch.arange(start_pos, kv_len, device=device).unsqueeze(1) k_pos = torch.arange(kv_len, device=device).unsqueeze(0) mask = torch.zeros(q_len, kv_len, dtype=dtype, device=device) mask.masked_fill_(k_pos > q_pos, torch.finfo(dtype).min) return mask[None, None]
class LayerMinerRunner: def __init__(self, layer_start: int, layer_end: int, model_name: str = "Qwen/Qwen2.5-1.5B-Instruct", d_model: int = 1536, device: str = "cpu"): self.layer_start = layer_start self.layer_end = layer_end self.d_model = d_model self.device = device self.model_name = model_name print(f"🧠 Loading {model_name} layers {layer_start} to {layer_end}...") try: hf_model = AutoModelForCausalLM.from_pretrained(model_name, local_files_only=True) except Exception: hf_model = AutoModelForCausalLM.from_pretrained(model_name) self.layers = hf_model.model.layers[layer_start : layer_end + 1].to(device) def __init__(self, layer_start: int, layer_end: int, model_name: str = CONFIG.MODEL_NAME, device: str = "cpu", dtype: torch.dtype = torch.float32, max_sessions: int = 32, attn_implementation: Optional[str] = None): config = AutoConfig.from_pretrained(model_name) n = config.num_hidden_layers if not (0 <= layer_start <= layer_end < n): raise ValueError(f"Layer range {layer_start}-{layer_end} invalid for {model_name} ({n} layers: 0-{n - 1})")
self.layer_start, self.layer_end = layer_start, layer_end self.model_name, self.device, self.dtype = model_name, device, dtype self.max_sessions = max_sessions
# TODO(roadmap P1): load only this shard's tensors from safetensors. # Today the FULL model is loaded then trimmed -> peak RAM = whole model. kwargs = {"dtype": dtype} if attn_implementation: kwargs["attn_implementation"] = attn_implementation hf_model = AutoModelForCausalLM.from_pretrained(model_name, **kwargs) self.config = hf_model.config self.layers = nn.ModuleList(hf_model.model.layers[layer_start:layer_end + 1]).to(device).eval() self.rotary_emb = hf_model.model.rotary_emb.to(device) # Free unused layers and LM head from memory del hf_model import gc gc.collect() self.kv_pool = PagedKVCachePool(device=device)
def execute_forward_slice(self, inbound_packed_bytes: bytes, session_id: str) -> bytes: """ 1. Dequantize inbound FP8 tensor 2. Execute forward pass across assigned layers 3. Quantize output back to FP8 """ # Dequantize h_in = TensorCodec.dequantize_fp8_to_fp16(inbound_packed_bytes, device=self.device) # Forward pass through local layer block h_out = h_in.to(self.layers[0].input_layernorm.weight.dtype) batch_size, seq_len, _ = h_out.shape position_ids = torch.arange(seq_len, dtype=torch.long, device=self.device).unsqueeze(0) position_embeddings = self.rotary_emb(h_out, position_ids=position_ids) with torch.no_grad(): for layer in self.layers: layer_out = layer(h_out, position_embeddings=position_embeddings, position_ids=position_ids) h_out = layer_out[0] if isinstance(layer_out, tuple) else layer_out # Re-quantize to FP8 for network transmission outbound_bytes, _, _ = TensorCodec.quantize_fp16_to_fp8(h_out) return outbound_bytes
self._sessions: "OrderedDict[str, tuple[DynamicCache, int]]" = OrderedDict()
# ------------------------------------------------------------------ sessions def session_length(self, session_id: str) -> int: return self._sessions[session_id][1] if session_id in self._sessions else 0
def release_session(self, session_id: str) -> None: self._sessions.pop(session_id, None)
def _get_cache(self, session_id: str, start_pos: int) -> DynamicCache: if start_pos == 0: self._sessions.pop(session_id, None) cache = DynamicCache(config=self.config) else: if session_id not in self._sessions: raise KVDesyncError(f"Unknown session '{session_id}' at start_pos={start_pos} (evicted or never prefilled)") cache, length = self._sessions[session_id] if length != start_pos: raise KVDesyncError(f"Session '{session_id}': miner has {length} tokens, client sent start_pos={start_pos}") self._sessions.move_to_end(session_id) return cache
# ------------------------------------------------------------------ compute @torch.no_grad() def forward(self, hidden: torch.Tensor, session_id: str, start_pos: int = 0) -> torch.Tensor: hidden = hidden.to(self.device, self.dtype) _, q_len, _ = hidden.shape cache = self._get_cache(session_id, start_pos)
position_ids = torch.arange(start_pos, start_pos + q_len, device=self.device).unsqueeze(0) position_embeddings = self.rotary_emb(hidden, position_ids=position_ids) mask = build_causal_mask(q_len, start_pos, self.dtype, self.device)
for layer in self.layers: out = layer(hidden, attention_mask=mask, position_ids=position_ids, past_key_values=cache, use_cache=True, position_embeddings=position_embeddings) hidden = out[0] if isinstance(out, tuple) else out
self._sessions[session_id] = (cache, start_pos + q_len) self._sessions.move_to_end(session_id) while len(self._sessions) > self.max_sessions: self._sessions.popitem(last=False) return hidden
def execute_forward_slice(self, inbound: bytes, session_id: str, start_pos: int = 0, out_mode: int = FP16) -> bytes: h_in = TensorCodec.decode_payload(inbound, device=self.device) h_out = self.forward(h_in, session_id=session_id, start_pos=start_pos) return TensorCodec.encode_payload(h_out, out_mode)5 unmodified lines67899101112137 unmodified lines212223242524252627284 unmodified lines333435363637389 unmodified lines484950525152545354555658575859606162636465666768696570716772737470757677737879758077818283841 unmodified line86878885899091929394958 unmodified lines1041051061071081091101111121051131141155 unmodified linesimport timeimport resourcefrom fastapi import FastAPI, Request, Responsefrom pydantic import BaseModelfrom typing import Optionalfrom swarmnet.config import CONFIGfrom swarmnet.miner.layer_runner import LayerMinerRunnerfrom swarmnet.network.dht_node import SwarmDHTNode
7 unmodified lines def __init__(self, miner_id: str, port: int, dht_port: int, bootstrap_host: Optional[str] = None, bootstrap_port: Optional[int] = None, layer_start: Optional[int] = None, layer_end: Optional[int] = None, model_name: str = "Qwen/Qwen2.5-1.5B-Instruct", total_layers: int = 28): model_name: str = CONFIG.MODEL_NAME, total_layers: int = 30): self.miner_id = miner_id self.layer_start = layer_start self.layer_end = layer_end4 unmodified lines self.dht = SwarmDHTNode(dht_port=dht_port, bootstrap_host=bootstrap_host, bootstrap_port=bootstrap_port) # Will be initialized after DHT auto-negotiation self.runner = None self.app = FastAPI(title=f"LayerMiner-{miner_id}") self._setup_routes()9 unmodified lines stats = profiler.profile() capacity = stats["recommended_layer_capacity"] print(f"🤖 [AutoProfiler] RAM: {stats['available_ram_mb']}MB | Speed: {stats['estimated_gflops']}GFLOPS | Capacity: {capacity} layers") self.layer_start, self.layer_end = await self.dht.negotiate_layers(capacity, total_layers=self.total_layers) self.layer_start, self.layer_end = await self.dht.negotiate_layers(capacity, total_layers=self.total_layers, model=self.model_name) # Now that we know our layers, load the weights! # Load the weights for assigned layer range self.runner = LayerMinerRunner(layer_start=self.layer_start, layer_end=self.layer_end, model_name=self.model_name) # Announce this node to the DHT await self.dht.announce_miner(self.layer_start, self.layer_end, self.port) await self.dht.announce_miner(self.layer_start, self.layer_end, self.port, model=self.model_name)
@self.app.post("/forward") async def handle_forward(request: Request): session_id = request.headers.get("X-Session-ID", "default_session") start_pos_header = request.headers.get("X-Start-Pos", "0") try: start_pos = int(start_pos_header) except ValueError: start_pos = 0
body_bytes = await request.body() # Execute local layer computation # Execute local layer computation with session KV cache t0 = time.time() out_bytes = self.runner.execute_forward_slice(body_bytes, session_id=session_id) out_bytes = self.runner.execute_forward_slice(body_bytes, session_id=session_id, start_pos=start_pos) self.last_t_elapsed = max(0.001, time.time() - t0) # Dynamically resolve next peer from DHT if we aren't at the end of the pipeline # Forward downstream if not at pipeline end if self.layer_end < self.total_layers - 1: next_layer = self.layer_end + 1 next_peer_url = await self.dht.find_peer(layer_index=next_layer) next_peer_url = await self.dht.find_peer(layer_index=next_layer, model=self.model_name) # Fallback to local localhost miner ports if DHT lookup is pending if not next_peer_url: fallback_port = 8001 + (next_layer // 15) fallback_port = 8001 + (next_layer // (self.total_layers // 2 if self.total_layers > 1 else 1)) next_peer_url = f"http://127.0.0.1:{fallback_port}" try:1 unmodified line resp = await client.post( f"{next_peer_url}/forward", content=out_bytes, headers={"X-Session-ID": session_id} headers={ "X-Session-ID": session_id, "X-Start-Pos": str(start_pos) } ) return Response(content=resp.content, media_type="application/octet-stream") except Exception as e:8 unmodified lines "status": "HEALTHY", "miner_id": self.miner_id, "layers": f"{self.layer_start}-{self.layer_end}", "model": self.model_name, "vram_free_mb": 4096 }
@self.app.get("/metrics") async def get_metrics(): # Calculate dynamic simulated CPU load based on inference time cpu = min(98, max(15, int((0.035 / self.last_t_elapsed) * 50))) return { "ram_mb": get_real_memory_mb(),12334561 unmodified line891011111213146 unmodified lines21222324242526278 unmodified lines36373839404142394041444243445 unmodified lines5051525653545556576162636465666758596061626364656667"""Sparse Dynamic Mixture-of-Experts (MoE) RouterSelects Top-K active experts and prunes tail-latency stragglers.Selects Top-K active experts across the sequence and aggregates outputs."""import torchimport torch.nn as nn1 unmodified linefrom typing import List, Dict, Tuple
class MoEExpert(nn.Module): def __init__(self, expert_id: int, d_model: int = 4096): def __init__(self, expert_id: int, d_model: int = 576): super().__init__() self.expert_id = expert_id self.net = nn.Sequential(6 unmodified lines return self.net(x)
class SparseMoERouter(nn.Module): def __init__(self, num_experts: int = 32, top_k: int = 4, d_model: int = 4096, prune_threshold: float = 0.04): def __init__(self, num_experts: int = 8, top_k: int = 2, d_model: int = 576, prune_threshold: float = 0.04): super().__init__() self.num_experts = num_experts self.top_k = top_k8 unmodified lines
def forward(self, x: torch.Tensor) -> Tuple[torch.Tensor, Dict[int, float]]: """ 1. Evaluates gating logits 2. Selects Top-K experts 3. Prunes slow/low-weight experts 4. Re-normalizes and computes weighted sum Gating and dispatch across sequence length. Input x: [batch, seq_len, d_model] """ # Gating logits shape: [batch, seq_len, num_experts] router_logits = self.gate(x) weights, indices = torch.topk(F.softmax(router_logits, dim=-1), self.top_k, dim=-1) 5 unmodified lines weight_sum = pruned_weights.sum(dim=-1, keepdim=True) + 1e-6 normalized_weights = pruned_weights / weight_sum # Aggregate expert outputs final_output = torch.zeros_like(x) dispatched_experts = {} # Apply routing for all sequence positions for k_idx in range(self.top_k): exp_id = indices[0, -1, k_idx].item() exp_weight = normalized_weights[0, -1, k_idx].item() if exp_weight > 0: expert_out = self.experts[exp_id](x) final_output += exp_weight * expert_out dispatched_experts[exp_id] = exp_weight # Compute expert output across batch for exp_id in range(self.num_experts): exp_mask = (indices[..., k_idx] == exp_id) & (normalized_weights[..., k_idx] > 0) if exp_mask.any(): expert_out = self.experts[exp_id](x) w = normalized_weights[..., k_idx].unsqueeze(-1) final_output += w * expert_out * exp_mask.unsqueeze(-1).float() dispatched_experts[exp_id] = float(normalized_weights[..., k_idx].mean().item()) return final_output, dispatched_experts12234567891011121314456151617181920212223242526271213141528291718192021222330313233343536373839404142434445464726272829303132333435363738394041424344454647484950484950515253545556575859606162636465666768697071727354747576777879575880818283848562868788"""Zero-Copy Activation Tensor Codec & Quantization KernelsActivation Tensor Codec
Wire format: [mode: uint8][scale: float32][ndims: uint8][dims: uint32 * ndims][payload]
Modes: FP16 (0) - 2 bytes/elem. Near-lossless for activations; matched HF greedy output token-for-token on SmolLM-135M in our probe. DEFAULT for the pipeline. FP8 (1) - 1 byte/elem, float8_e4m3fn with a per-tensor absmax scale. Real FP8. LOSSY: halves bandwidth but can change generated tokens. Measure first. INT8 (2) - 1 byte/elem, symmetric per-tensor absmax. LOSSY.
Note: before this rewrite, `quantize_fp16_to_fp8` silently produced FP16 (scale=1.0)."""import torchimport torch.nn.functional as Fimport numpy as npimport structfrom typing import Tuple
import numpy as npimport torchimport torch.nn.functional as F
FP16, FP8, INT8 = 0, 1, 2_FP8_MAX = 448.0 # max finite value of float8_e4m3fn
class TensorCodec: @staticmethod def encode_payload(tensor: torch.Tensor) -> bytes: """ Packs an activation tensor to lossless FP16 binary payload. """ def encode_payload(tensor: torch.Tensor, mode: int = FP16) -> bytes: shape = tuple(tensor.shape) tensor_fp16 = tensor.to(torch.float16) data_bytes = tensor_fp16.cpu().numpy().tobytes() dtype_code = 0 # FP16 Lossless # Header: [dtype_code: uint8][scale: float32][dims_count: uint8][dims: uint32...] header = struct.pack(f"!BfB{len(shape)}I", dtype_code, 1.0, len(shape), *shape) return header + data_bytes t = tensor.detach().to("cpu", torch.float32) scale = 1.0 if mode == FP16: data = t.to(torch.float16).numpy().tobytes() elif mode == FP8: absmax = t.abs().max().item() scale = absmax / _FP8_MAX if absmax > 0 else 1.0 data = (t / scale).to(torch.float8_e4m3fn).view(torch.uint8).numpy().tobytes() elif mode == INT8: absmax = t.abs().max().item() scale = absmax / 127.0 if absmax > 0 else 1.0 data = torch.round(t / scale).clamp(-127, 127).to(torch.int8).numpy().tobytes() else: raise ValueError(f"Unknown codec mode {mode}") header = struct.pack(f"!BfB{len(shape)}I", mode, scale, len(shape), *shape) return header + data
@staticmethod def decode_payload(packed_bytes: bytes, device: str = "cpu") -> torch.Tensor: """ Unpacks binary payload back to torch.Tensor in target device memory. """ dtype_code, scale, num_dims = struct.unpack_from("!BfB", packed_bytes, 0) offset = 1 + 4 + 1 shape = struct.unpack_from(f"!{num_dims}I", packed_bytes, offset) offset += num_dims * 4 data_buffer = packed_bytes[offset:] if dtype_code == 0: # FP16 Lossless raw_np = np.frombuffer(data_buffer, dtype=np.float16) tensor_raw = torch.from_numpy(raw_np.copy()) return tensor_raw.reshape(shape).to(dtype=torch.float16, device=device) elif dtype_code == 1: # Native FP8 raw_np = np.frombuffer(data_buffer, dtype=np.uint8) tensor_raw = torch.from_numpy(raw_np.copy()).view(torch.float8_e4m3fn) unscaled = tensor_raw.to(torch.float32) * scale return unscaled.reshape(shape).to(dtype=torch.float16, device=device) else: # INT8 Fallback raw_np = np.frombuffer(data_buffer, dtype=np.int8) tensor_raw = torch.from_numpy(raw_np.copy()).to(torch.float32) unscaled = tensor_raw * scale return unscaled.reshape(shape).to(dtype=torch.float16, device=device) def decode_payload(packed: bytes, device: str = "cpu") -> torch.Tensor: """Returns a float16 tensor (callers cast to their compute dtype).""" mode, scale, ndims = struct.unpack_from("!BfB", packed, 0) offset = 6 shape = struct.unpack_from(f"!{ndims}I", packed, offset) offset += ndims * 4 buf = packed[offset:] numel = int(np.prod(shape)) if shape else 1 expected = numel * (2 if mode == FP16 else 1) if len(buf) != expected: raise ValueError(f"Corrupt payload: expected {expected} data bytes, got {len(buf)}")
if mode == FP16: t = torch.from_numpy(np.frombuffer(buf, dtype=np.float16).copy()) elif mode == FP8: raw = torch.from_numpy(np.frombuffer(buf, dtype=np.uint8).copy()) t = raw.view(torch.float8_e4m3fn).to(torch.float32) * scale elif mode == INT8: t = torch.from_numpy(np.frombuffer(buf, dtype=np.int8).copy()).to(torch.float32) * scale else: raise ValueError(f"Unknown codec mode {mode}") return t.reshape(shape).to(dtype=torch.float16, device=device)
# --- Backwards-compatible names (now honest) --------------------------------- @staticmethod def quantize_fp16_to_fp8(tensor: torch.Tensor) -> Tuple[bytes, float, tuple]: return TensorCodec.encode_payload(tensor), 1.0, tuple(tensor.shape) """Real FP8 (lossy). Use encode_payload(t, FP16) when exactness matters.""" packed = TensorCodec.encode_payload(tensor, FP8) scale = struct.unpack_from("!f", packed, 1)[0] return packed, scale, tuple(tensor.shape)
@staticmethod def dequantize_fp8_to_fp16(packed_bytes: bytes, device: str = "cpu") -> torch.Tensor: return TensorCodec.decode_payload(packed_bytes, device=device) def dequantize_fp8_to_fp16(packed: bytes, device: str = "cpu") -> torch.Tensor: """Decodes any mode (the header says which).""" return TensorCodec.decode_payload(packed, device=device)
@staticmethod def compute_cosine_similarity(t1: torch.Tensor, t2: torch.Tensor) -> float: """Computes cosine similarity between two tensors regardless of dtype""" f1 = t1.to(torch.float32).flatten().unsqueeze(0) f2 = t2.to(torch.float32).flatten().unsqueeze(0) return F.cosine_similarity(f1, f2).item()1234567891011121314151617181920import torchfrom transformers.models.llama.modeling_llama import LlamaAttention, LlamaConfig
config = LlamaConfig( hidden_size=576, num_attention_heads=9, num_key_value_heads=3, head_dim=64,)attn = LlamaAttention(config, layer_idx=0)h = torch.randn(1, 16, 576)cos = torch.randn(1, 16, 64)sin = torch.randn(1, 16, 64)position_embeddings = (cos, sin)
try: attn(hidden_states=h, position_embeddings=position_embeddings) print("Success!")except Exception as e: print("Error:", e)1234567891011121314151617181920import torchfrom transformers.models.llama.modeling_llama import LlamaDecoderLayer, LlamaConfig
config = LlamaConfig( hidden_size=576, num_attention_heads=9, num_key_value_heads=3, head_dim=64,)layer = LlamaDecoderLayer(config, layer_idx=0)h = torch.randn(1, 16, 576)cos = torch.randn(1, 16, 64)sin = torch.randn(1, 16, 64)position_embeddings = (cos, sin)
try: layer(hidden_states=h, position_embeddings=position_embeddings) print("Success!")except Exception as e: print("Error:", e)12345678910111213141516171819import torchfrom transformers.models.llama.modeling_llama import LlamaDecoderLayer, LlamaConfig
config = LlamaConfig( hidden_size=576, num_attention_heads=9, num_key_value_heads=3, head_dim=64,)layer = LlamaDecoderLayer(config, layer_idx=0)h = torch.randn(1, 16, 576)cos = torch.randn(1, 16, 64)sin = torch.randn(1, 16, 64)position_embeddings = (cos, sin)
out1 = layer(hidden_states=h, position_embeddings=position_embeddings)print("Layer 1 output shape:", out1[0].shape)out2 = layer(hidden_states=out1[0], position_embeddings=position_embeddings)print("Layer 2 output shape:", out2[0].shape)12345678910111213141516171819202122import torchfrom transformers.models.llama.modeling_llama import LlamaDecoderLayer, LlamaConfig
config = LlamaConfig( hidden_size=576, num_attention_heads=9, num_key_value_heads=3, head_dim=64,)layer = LlamaDecoderLayer(config, layer_idx=0)h = torch.randn(1, 16, 576)cos = torch.randn(1, 16, 64)sin = torch.randn(1, 16, 64)position_embeddings = (cos, sin)
out1 = layer(hidden_states=h, position_embeddings=position_embeddings)print("Tuple len:", len(out1))for i, t in enumerate(out1): if isinstance(t, torch.Tensor): print(f"out1[{i}] shape:", t.shape) else: print(f"out1[{i}] type:", type(t))1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283import torchimport numpy as npfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom swarmnet.miner.layer_runner import LayerMinerRunnerfrom swarmnet.protocol.tensor_codec import TensorCodec
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat_messages = [{"role": "user", "content": prompt}]inputs = tokenizer.apply_chat_template(chat_messages, return_tensors="pt", add_generation_prompt=True)input_ids = inputs["input_ids"] if hasattr(inputs, "input_ids") or isinstance(inputs, dict) else inputs
runner_m1 = LayerMinerRunner(layer_start=0, layer_end=14)runner_m2 = LayerMinerRunner(layer_start=15, layer_end=29)
# Method 1: Local PyTorch (debug_pipeline.py)with torch.no_grad(): curr_ids = input_ids.clone() words_local = [] for step in range(10): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) h_out = embeds seq_len = h_out.shape[1] position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb = model.model.rotary_emb(h_out, position_ids=position_ids) for l in model.model.layers[0:15]: out = l(h_out, position_embeddings=pos_emb, position_ids=position_ids) h_out = out[0] if isinstance(out, tuple) else out for l in model.model.layers[15:30]: out = l(h_out, position_embeddings=pos_emb, position_ids=position_ids) h_out = out[0] if isinstance(out, tuple) else out logits = model.lm_head(model.model.norm(h_out))[:, -1, :] next_id = torch.argmax(logits, dim=-1, keepdim=True) words_local.append(tokenizer.decode(next_id[0])) curr_ids = torch.cat([curr_ids, next_id], dim=1) print("Method 1 Local:", "".join(words_local))
# Method 2: LayerRunner Engine (in-memory invocation)with torch.no_grad(): curr_ids = input_ids.clone() words_runner = [] for step in range(10): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) # Client FP16 bytes0 = embeds.to(torch.float16).cpu().numpy().tobytes() shape = embeds.shape # M1 execution without FP8 h_in1 = torch.from_numpy(np.frombuffer(bytes0, dtype=np.float16).copy()).reshape(shape).to(model.dtype) seq_len = h_in1.shape[1] position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb = runner_m1.rotary_emb(h_in1, position_ids=position_ids) h_out = h_in1 for l in runner_m1.layers: out = l(h_out, position_embeddings=pos_emb, position_ids=position_ids) h_out = out[0] if isinstance(out, tuple) else out bytes1 = h_out.to(torch.float16).cpu().numpy().tobytes() # M2 execution without FP8 h_in2 = torch.from_numpy(np.frombuffer(bytes1, dtype=np.float16).copy()).reshape(shape).to(model.dtype) pos_emb2 = runner_m2.rotary_emb(h_in2, position_ids=position_ids) h_out2 = h_in2 for l in runner_m2.layers: out = l(h_out2, position_embeddings=pos_emb2, position_ids=position_ids) h_out2 = out[0] if isinstance(out, tuple) else out # Head h_normed = model.model.norm(h_out2) logits = model.lm_head(h_normed)[:, -1, :] next_id = torch.argmax(logits, dim=-1, keepdim=True) words_runner.append(tokenizer.decode(next_id[0])) curr_ids = torch.cat([curr_ids, next_id], dim=1) print("Method 2 Runner:", "".join(words_runner))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657import torchfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom transformers.models.llama.modeling_llama import _prepare_4d_causal_attention_mask
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat = [{"role": "user", "content": prompt}]batch = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True)input_ids = batch["input_ids"] if hasattr(batch, "input_ids") or isinstance(batch, dict) else batch
layers_0_14 = model.model.layers[0:15]layers_15_29 = model.model.layers[15:30]rotary_emb = model.model.rotary_embnorm = model.model.normlm_head = model.lm_head
with torch.no_grad(): curr_ids = input_ids.clone() print("--- SHARDED MODEL WITH CAUSAL ATTENTION MASK TEST ---") words = [] for step in range(25): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) # Miner 1: 0-14 h_out = embeds batch_size, seq_len, _ = h_out.shape position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb = rotary_emb(h_out, position_ids=position_ids) # Create 4D Causal Attention Mask causal_mask = _prepare_4d_causal_attention_mask( attention_mask=None, input_shape=(batch_size, seq_len), inputs_embeds=h_out, past_key_values_length=0 ) for l in layers_0_14: h_out = l(h_out, attention_mask=causal_mask, position_ids=position_ids, position_embeddings=pos_emb)[0] # Miner 2: 15-29 for l in layers_15_29: h_out = l(h_out, attention_mask=causal_mask, position_ids=position_ids, position_embeddings=pos_emb)[0] # Head h_normed = norm(h_out) next_token_logits = lm_head(h_normed)[:, -1, :] next_token_id = torch.argmax(next_token_logits, dim=-1, keepdim=True) word = tokenizer.decode(next_token_id[0]) words.append(word) curr_ids = torch.cat([curr_ids, next_token_id], dim=1) print(f"Sharded Causal Output: '{''.join(words)}'")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import torchfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom transformers.models.llama.modeling_llama import create_causal_mask
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat = [{"role": "user", "content": prompt}]batch = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True)input_ids = batch["input_ids"] if hasattr(batch, "input_ids") or isinstance(batch, dict) else batch
layers_0_14 = model.model.layers[0:15]layers_15_29 = model.model.layers[15:30]rotary_emb = model.model.rotary_embnorm = model.model.normlm_head = model.lm_head
head_dim = model.config.hidden_size // model.config.num_attention_heads # 64num_heads = model.config.num_attention_heads # 9
with torch.no_grad(): curr_ids = input_ids.clone() print("--- SHARDED MODEL WITH DUMMY_V ROTARY & CAUSAL MASK TEST ---") words = [] for step in range(25): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) # Miner 1: 0-14 h_out = embeds batch_size, seq_len, _ = h_out.shape position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) # Compute pos_emb using 4D dummy_v [batch, num_heads, seq_len, head_dim] dummy_v = torch.zeros(batch_size, num_heads, seq_len, head_dim, dtype=h_out.dtype, device=model.device) pos_emb = rotary_emb(dummy_v, position_ids=position_ids) causal_mask = create_causal_mask( config=model.config, inputs_embeds=h_out, attention_mask=None, past_key_values=None, position_ids=position_ids ) for l in layers_0_14: h_out = l(h_out, attention_mask=causal_mask, position_ids=position_ids, position_embeddings=pos_emb)[0] # Miner 2: 15-29 for l in layers_15_29: h_out = l(h_out, attention_mask=causal_mask, position_ids=position_ids, position_embeddings=pos_emb)[0] # Head h_normed = norm(h_out) next_token_logits = lm_head(h_normed)[:, -1, :] next_token_id = torch.argmax(next_token_logits, dim=-1, keepdim=True) word = tokenizer.decode(next_token_id[0]) words.append(word) curr_ids = torch.cat([curr_ids, next_token_id], dim=1) print(f"Sharded Causal Output: '{''.join(words)}'")123456789101112131415161718192021222324252627282930313233343536373839404142import torchimport httpximport asynciofrom transformers import AutoModelForCausalLM, AutoTokenizerfrom swarmnet.protocol.tensor_codec import TensorCodec
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat_messages = [{"role": "user", "content": prompt}]inputs = tokenizer.apply_chat_template(chat_messages, return_tensors="pt", add_generation_prompt=True)input_ids = inputs["input_ids"] if hasattr(inputs, "input_ids") or isinstance(inputs, dict) else inputs
async def run(): global input_ids words = [] with torch.no_grad(): for step in range(15): embeds = model.model.embed_tokens(input_ids.to("cpu")) fp8_bytes, _, _ = TensorCodec.quantize_fp16_to_fp8(embeds.to(torch.float16)) async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.post("http://127.0.0.1:8001/forward", content=fp8_bytes) if resp.status_code != 200: print(f"Error {resp.status_code}") break h_last = TensorCodec.dequantize_fp8_to_fp16(resp.content, device="cpu").to(model.dtype) h_normed = model.model.norm(h_last) next_token_logits = model.lm_head(h_normed)[:, -1, :] next_token_id = torch.argmax(next_token_logits, dim=-1, keepdim=True) word = tokenizer.decode(next_token_id[0]) words.append(word) input_ids = torch.cat([input_ids, next_token_id], dim=1) print("Exact Client Loop Output: ", "".join(words))
if __name__ == "__main__": asyncio.run(run())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253import torchimport httpximport asyncioimport numpy as npfrom transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat_messages = [{"role": "user", "content": prompt}]inputs = tokenizer.apply_chat_template(chat_messages, return_tensors="pt", add_generation_prompt=True)input_ids = inputs["input_ids"] if hasattr(inputs, "input_ids") or isinstance(inputs, dict) else inputs
def pack_fp16(t: torch.Tensor) -> bytes: shape = tuple(t.shape) header = f"{len(shape)}|" + ",".join(map(str, shape)) + "|" return header.encode() + t.cpu().numpy().astype(np.float16).tobytes()
def unpack_fp16(b: bytes) -> torch.Tensor: parts = b.split(b"|", 2) shape = tuple(map(int, parts[1].decode().split(","))) arr = np.frombuffer(parts[2], dtype=np.float16).copy() return torch.from_numpy(arr).reshape(shape)
async def run(): global input_ids words = [] with torch.no_grad(): for step in range(15): embeds = model.model.embed_tokens(input_ids.to("cpu")) fp16_bytes = pack_fp16(embeds.to(torch.float16)) async with httpx.AsyncClient(timeout=30.0) as client: resp = await client.post("http://127.0.0.1:8001/forward_fp16", content=fp16_bytes) if resp.status_code != 200: print(f"Error {resp.status_code}") break h_last = unpack_fp16(resp.content).to(model.dtype) h_normed = model.model.norm(h_last) next_token_logits = model.lm_head(h_normed)[:, -1, :] next_token_id = torch.argmax(next_token_logits, dim=-1, keepdim=True) word = tokenizer.decode(next_token_id[0]) words.append(word) input_ids = torch.cat([input_ids, next_token_id], dim=1) print("FP16 Network Swarm Loop Output: ", "".join(words))
if __name__ == "__main__": asyncio.run(run())1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556import torchfrom transformers import AutoModelForCausalLM, AutoTokenizer
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat = [{"role": "user", "content": prompt}]batch = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True)input_ids = batch["input_ids"] if hasattr(batch, "input_ids") or isinstance(batch, dict) else batch
# 1. Full un-sharded generationwith torch.no_grad(): gen_ids = model.generate(input_ids, max_new_tokens=25, do_sample=False)print(f"Full Model output: '{tokenizer.decode(gen_ids[0][input_ids.shape[1]:])}'\n")
# 2. Exact sharded pipeline match testlayers_0_14 = model.model.layers[0:15]layers_15_29 = model.model.layers[15:30]rotary_emb = model.model.rotary_embnorm = model.model.normlm_head = model.lm_head
with torch.no_grad(): curr_ids = input_ids.clone() print("--- SHARDED MODEL VERIFICATION ---") words = [] for step in range(25): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) # Miner 1: 0-14 h_out = embeds batch_size, seq_len, _ = h_out.shape position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb = rotary_emb(h_out, position_ids=position_ids) for l in layers_0_14: out = l(h_out, position_embeddings=pos_emb, position_ids=position_ids) h_out = out[0] if isinstance(out, tuple) else out # Miner 2: 15-29 for l in layers_15_29: out = l(h_out, position_embeddings=pos_emb, position_ids=position_ids) h_out = out[0] if isinstance(out, tuple) else out # Head h_normed = norm(h_out) next_token_logits = lm_head(h_normed)[:, -1, :] next_token_id = torch.argmax(next_token_logits, dim=-1, keepdim=True) word = tokenizer.decode(next_token_id[0]) words.append(word) curr_ids = torch.cat([curr_ids, next_token_id], dim=1) print(f"Sharded Output: '{''.join(words)}'")123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354import torchfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom swarmnet.protocol.tensor_codec import TensorCodec
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat = [{"role": "user", "content": prompt}]batch = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True)input_ids = batch["input_ids"] if hasattr(batch, "input_ids") or isinstance(batch, dict) else batch
layers_0_14 = model.model.layers[0:15]layers_15_29 = model.model.layers[15:30]rotary_emb = model.model.rotary_embnorm = model.model.normlm_head = model.lm_head
head_dim = model.config.hidden_size // model.config.num_attention_heads # 64num_heads = model.config.num_attention_heads # 9
with torch.no_grad(): curr_ids = input_ids.clone() print("--- SHARDED MODEL WITH UNQUANTIZED FP16 TEST ---") words = [] for step in range(25): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) # Miner 1 (0-14) h_out1 = embeds batch_size, seq_len, _ = h_out1.shape position_ids1 = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb1 = rotary_emb(h_out1, position_ids=position_ids1) for l in layers_0_14: h_out1 = l(h_out1, position_ids=position_ids1, position_embeddings=pos_emb1)[0] # Miner 2 (15-29) h_out2 = h_out1 position_ids2 = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb2 = rotary_emb(h_out2, position_ids=position_ids2) for l in layers_15_29: h_out2 = l(h_out2, position_ids=position_ids2, position_embeddings=pos_emb2)[0] # Head h_normed = norm(h_out2) next_token_logits = lm_head(h_normed)[:, -1, :] next_token_id = torch.argmax(next_token_logits, dim=-1, keepdim=True) word = tokenizer.decode(next_token_id[0]) words.append(word) curr_ids = torch.cat([curr_ids, next_token_id], dim=1) print(f"FP16 Sharded Output: '{''.join(words)}'")1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677import torchfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom swarmnet.protocol.tensor_codec import TensorCodec
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat = [{"role": "user", "content": prompt}]batch = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True)input_ids = batch["input_ids"] if hasattr(batch, "input_ids") or isinstance(batch, dict) else batch
layers_0_14 = model.model.layers[0:15]layers_15_29 = model.model.layers[15:30]rotary_emb = model.model.rotary_embnorm = model.model.normlm_head = model.lm_head
# 1. Uncompressed FP16 Pipelinewith torch.no_grad(): curr_ids = input_ids.clone() words_fp16 = [] for step in range(15): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) h_out = embeds seq_len = h_out.shape[1] position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb = rotary_emb(h_out, position_ids=position_ids) for l in layers_0_14: h_out = l(h_out, position_embeddings=pos_emb, position_ids=position_ids)[0] for l in layers_15_29: h_out = l(h_out, position_embeddings=pos_emb, position_ids=position_ids)[0] logits = lm_head(norm(h_out))[:, -1, :] next_id = torch.argmax(logits, dim=-1, keepdim=True) words_fp16.append(tokenizer.decode(next_id[0])) curr_ids = torch.cat([curr_ids, next_id], dim=1) print("FP16 Pipeline:", "".join(words_fp16))
# 2. FP8 Quantized Pipeline (Client->M1 FP8, M1->M2 FP8, M2->Client FP8)with torch.no_grad(): curr_ids = input_ids.clone() words_fp8 = [] for step in range(15): embeds = model.model.embed_tokens(curr_ids).to(model.dtype) # Client -> M1 FP8 bytes_c_m1, _, _ = TensorCodec.quantize_fp16_to_fp8(embeds.to(torch.float16)) h_out = TensorCodec.dequantize_fp8_to_fp16(bytes_c_m1).to(model.dtype) seq_len = h_out.shape[1] position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) pos_emb = rotary_emb(h_out, position_ids=position_ids) # M1 (0-14) for l in layers_0_14: h_out = l(h_out, position_ids=position_ids, position_embeddings=pos_emb)[0] # M1 -> M2 FP8 bytes_m1_m2, _, _ = TensorCodec.quantize_fp16_to_fp8(h_out.to(torch.float16)) h_out = TensorCodec.dequantize_fp8_to_fp16(bytes_m1_m2).to(model.dtype) # M2 (15-29) for l in layers_15_29: h_out = l(h_out, position_ids=position_ids, position_embeddings=pos_emb)[0] # M2 -> Client FP8 bytes_m2_c, _, _ = TensorCodec.quantize_fp16_to_fp8(h_out.to(torch.float16)) h_last = TensorCodec.dequantize_fp8_to_fp16(bytes_m2_c).to(model.dtype) logits = lm_head(norm(h_last))[:, -1, :] next_id = torch.argmax(logits, dim=-1, keepdim=True) words_fp8.append(tokenizer.decode(next_id[0])) curr_ids = torch.cat([curr_ids, next_id], dim=1) print("FP8 Pipeline: ", "".join(words_fp8))12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849import torchfrom transformers import AutoModelForCausalLM, AutoTokenizerfrom swarmnet.protocol.tensor_codec import TensorCodec
model_id = "HuggingFaceTB/SmolLM-135M-Instruct"tokenizer = AutoTokenizer.from_pretrained(model_id, local_files_only=True)model = AutoModelForCausalLM.from_pretrained(model_id, local_files_only=True)model.eval()
prompt = "What is 2 + 2?"chat = [{"role": "user", "content": prompt}]batch = tokenizer.apply_chat_template(chat, return_tensors="pt", add_generation_prompt=True)input_ids = batch["input_ids"] if hasattr(batch, "input_ids") or isinstance(batch, dict) else batch
layers_0_14 = model.model.layers[0:15]layers_15_29 = model.model.layers[15:30]rotary_emb = model.model.rotary_embnorm = model.model.normlm_head = model.lm_head
# Test FP16 Raw vs FP8 Codecwith torch.no_grad(): embeds = model.model.embed_tokens(input_ids).to(model.dtype) h_out1 = embeds seq_len = h_out1.shape[1] position_ids = torch.arange(seq_len, dtype=torch.long, device=model.device).unsqueeze(0) cos, sin = rotary_emb(h_out1, position_ids=position_ids) pos_emb = (cos.unsqueeze(1), sin.unsqueeze(1)) # Layer 0-14 for l in layers_0_14: h_out1 = l(h_out1, position_ids=position_ids, position_embeddings=pos_emb)[0] # Option A: FP16 Exact h_out2_fp16 = h_out1.clone() for l in layers_15_29: h_out2_fp16 = l(h_out2_fp16, position_ids=position_ids, position_embeddings=pos_emb)[0] logits_fp16 = lm_head(norm(h_out2_fp16))[:, -1, :] token_fp16 = torch.argmax(logits_fp16, dim=-1).item() print(f"FP16 Token: '{tokenizer.decode([token_fp16])}' (id {token_fp16})") # Option B: FP8 Quantized between L14 and L15 bytes_m1, _, _ = TensorCodec.quantize_fp16_to_fp8(h_out1.to(torch.float16)) h_out2_fp8 = TensorCodec.dequantize_fp8_to_fp16(bytes_m1, device="cpu").to(model.dtype) for l in layers_15_29: h_out2_fp8 = l(h_out2_fp8, position_ids=position_ids, position_embeddings=pos_emb)[0] logits_fp8 = lm_head(norm(h_out2_fp8))[:, -1, :] token_fp8 = torch.argmax(logits_fp8, dim=-1).item() print(f"FP8 Token: '{tokenizer.decode([token_fp8])}' (id {token_fp8})")1 unmodified line23456678910111213141516171819202122232425789101112131415161718272829303132333419202137221 unmodified lineimport jsonimport httpximport websocketsimport pytest
async def test_chat(): uri = "ws://127.0.0.1:8000/ws" async with websockets.connect(uri) as ws: print("Connected to WebSocket!") async def listen(): full_text = [] while True: try: msg = await ws.recv() data = json.loads(msg) if data.get("type") == "token": t = data.get("token", "") full_text.append(t) print(t, end="", flush=True) elif data.get("type") == "log" and "completed" in data.get("msg", ""): break except Exception: break print(f"\n\n--- Full Response Received ---\n{''.join(full_text)}")def test_chat_manual(): # Only run if server is running async def _run(): uri = "ws://127.0.0.1:8000/ws" try: async with websockets.connect(uri, open_timeout=1.0) as ws: async with httpx.AsyncClient(timeout=5.0) as client: resp = await client.post("http://127.0.0.1:8000/api/trigger", json={"prompt": "Ping"}) assert resp.status_code == 200 except Exception: pytest.skip("Swarm server not running locally on port 8000")
listener = asyncio.create_task(listen()) # Trigger inference with 60s timeout async with httpx.AsyncClient(timeout=60.0) as client: resp = await client.post("http://127.0.0.1:8000/api/trigger", json={"prompt": "What is 2 + 2?"}) print(f"\nTrigger Status Code: {resp.status_code}") await listener asyncio.run(_run())
if __name__ == "__main__": asyncio.run(test_chat()) asyncio.run(test_chat_manual())1232454567678910111213141591011121314151617181920211617181920import torchimport numpy as npimport pytestfrom swarmnet.protocol.tensor_codec import TensorCodecfrom swarmnet.protocol.tensor_codec import TensorCodec, FP16, FP8
# Test 1: Random tensort_orig = torch.randn(1, 12, 576, dtype=torch.float16)packed_bytes, scale, shape = TensorCodec.quantize_fp16_to_fp8(t_orig)t_dequant = TensorCodec.dequantize_fp8_to_fp16(packed_bytes, device="cpu")def test_codec_cosine_similarity(): # Test with typical transformer hidden dimension t_orig = torch.randn(1, 12, 576, dtype=torch.float32) # 1. FP16 Lossless Mode fp16_bytes = TensorCodec.encode_payload(t_orig, mode=FP16) t_fp16 = TensorCodec.decode_payload(fp16_bytes) sim_fp16 = TensorCodec.compute_cosine_similarity(t_orig, t_fp16) assert sim_fp16 >= 0.9999, f"FP16 similarity too low: {sim_fp16}"
sim = TensorCodec.compute_cosine_similarity(t_orig, t_dequant)print(f"Cosine Similarity for FP8 Codec: {sim:.6f}")
# Test 2: Uncompressed FP16 direct byte transfer codec for 100% loss-less baselineheader = f"FP16|{t_orig.shape[0]},{t_orig.shape[1]},{t_orig.shape[2]}|".encode()raw_bytes = header + t_orig.cpu().numpy().tobytes()
# Decodeparts = raw_bytes.split(b"|", 2)dims = tuple(map(int, parts[1].decode().split(",")))t_fp16 = torch.from_numpy(np.frombuffer(parts[2], dtype=np.float16).copy()).reshape(dims)sim_fp16 = TensorCodec.compute_cosine_similarity(t_orig, t_fp16)print(f"Cosine Similarity for Raw FP16: {sim_fp16:.6f}") # 2. FP8 Mode fp8_bytes, scale, shape = TensorCodec.quantize_fp16_to_fp8(t_orig) t_fp8 = TensorCodec.dequantize_fp8_to_fp16(fp8_bytes) sim_fp8 = TensorCodec.compute_cosine_similarity(t_orig, t_fp8) assert sim_fp8 >= 0.99, f"FP8 similarity too low: {sim_fp8}"122345678989101213111213141515161718161718192020212122232423242525262728272829303132333435363738394041293031323344343536"""End-to-End Test for Split-Learning Pipeline & MoE RoutingEnd-to-End Test for Real Split-Learning Pipeline with Real Weights"""import pytestimport torchfrom swarmnet.client.embedder import LocalSplitClientfrom swarmnet.miner.layer_runner import LayerMinerRunnerfrom swarmnet.moe.moe_router import SparseMoERouterfrom swarmnet.protocol.tensor_codec import TensorCodecfrom swarmnet.protocol.tensor_codec import TensorCodec, FP16
def test_full_pipeline_forward_pass(): d_model = 576 # SmolLM-135M test dimension (divisible by 9 heads) vocab_size = 1000 # 1. Client loads real embedding & LM head client = LocalSplitClient() prompt = "Hello" input_ids = client.tokenizer(prompt, return_tensors="pt").input_ids # 1. Client creates local hidden state (Embedding + Layer 1) client = LocalSplitClient(vocab_size=vocab_size, d_model=d_model) input_ids = torch.tensor([[12, 45, 99, 230]]) h_1 = client.encode_and_scramble(input_ids) # 2. Client embeds h_0 = client.embed(input_ids) assert h_0.shape[-1] == client.config.hidden_size packed_h0 = TensorCodec.encode_payload(h_0, mode=FP16) # 2. Pack to FP8 packed_h1, _, _ = TensorCodec.quantize_fp16_to_fp8(h_1) # 3. Miner 1 (e.g., layers 0 to 14) miner_1 = LayerMinerRunner(layer_start=0, layer_end=14) packed_h1 = miner_1.execute_forward_slice(packed_h0, session_id="test_sess", start_pos=0, out_mode=FP16) # 3. Miner 1 (Layers 2-4) miner_1 = LayerMinerRunner(layer_start=2, layer_end=4, d_model=d_model) packed_h4 = miner_1.execute_forward_slice(packed_h1, session_id="test_sess") # 4. Miner 2 (e.g., layers 15 to 29) miner_2 = LayerMinerRunner(layer_start=15, layer_end=29) packed_h2 = miner_2.execute_forward_slice(packed_h1, session_id="test_sess", start_pos=0, out_mode=FP16) # 4. MoE Router (Sparse Top-2 Dispatch) h4_unpacked = TensorCodec.dequantize_fp8_to_fp16(packed_h4) moe_router = SparseMoERouter(num_experts=8, top_k=2, d_model=d_model) moe_out, dispatched = moe_router(h4_unpacked.to(torch.float32)) assert len(dispatched) > 0, "No experts were dispatched!" packed_moe, _, _ = TensorCodec.quantize_fp16_to_fp8(moe_out) # 5. Miner 2 (Layers 5-8) miner_2 = LayerMinerRunner(layer_start=5, layer_end=8, d_model=d_model) packed_h8 = miner_2.execute_forward_slice(packed_moe, session_id="test_sess") # 6. Client decodes final token locally final_h = TensorCodec.dequantize_fp8_to_fp16(packed_h8).to(torch.float32) next_token = client.decode_and_sample(final_h, temperature=0.0) # 5. Client decodes final token locally final_h = TensorCodec.decode_payload(packed_h2) next_token = client.sample(final_h, temperature=0.0) assert isinstance(next_token, int) assert 0 <= next_token < vocab_size assert 0 <= next_token < client.config.vocab_size word = client.tokenizer.decode([next_token]) assert len(word) > 0Dockerfile+4-2
README.md+13-4
app.pyAdded+77
pytest.iniAdded+6
scripts/run_client_ui.py+28-27
scripts/run_miner.py+3-2
scripts/run_virtual_swarm.pyDeleted-149
swarmnet/client/embedder.py+46-57
swarmnet/config.py+5-2
swarmnet/miner/layer_runner.py+107-78
swarmnet/miner/worker_server.py+22-15
swarmnet/moe/moe_router.py+14-16
swarmnet/protocol/tensor_codec.py+67-44
test_attn.pyDeleted-20
test_layer.pyDeleted-20
test_layer_2.pyDeleted-19
test_layer_3.pyDeleted-22
tests/compare_exact.pyDeleted-83
tests/debug_causal.pyDeleted-57
tests/debug_causal_mask.pyDeleted-63
tests/debug_client_code.pyDeleted-42
tests/debug_client_fp16.pyDeleted-53
tests/debug_pipeline.pyDeleted-56
tests/debug_quant.pyDeleted-54
tests/debug_quant_pipeline.pyDeleted-77
tests/debug_quant_test.pyDeleted-49
tests/test_chat_ws.py+14-29
tests/test_codec_loss.py+17-18
tests/test_swarm_pipeline.py+22-30