Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/MojoLlama/blob/main/src/mojollama/graph/ops.mojo # MojoLlama Archived Mojo/MAX quantizer and serving research repository (read-only history) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `MojoLlama / src / mojollama / graph / ops.mojo` 416 lines · 15313 bytes Raw Blame History 1 """MojoLlama Graph Operations — architecture definition. 2 3 This file defines the op graph architecture for MojoLlama. 4 Each op struct specifies WHAT to compute and its parameters. 5 6 BACKEND NOTE (Mojo 0.26.2): 7 - Python backend (numpy) — works NOW, called from bridge.py 8 - Mojo SIMD backend — when Mojo's heap/pointer APIs mature 9 - MAX GPU backend (CUDA/SYCL/Vulkan) — when MAX is installable 10 11 The op definitions stay the same regardless of backend. 12 13 ARCHITECTURES DEFINED: 14 - Llama3: Dense transformer with GQA, SiLU-gated FFN, full RoPE 15 - ZAYA1: MoE++ with interleaved attention + Mamba-2 SSM, CCA, MoD 16 """ 17 18 # ─── Tensor (shape + data type descriptor) ───────────────────────────── 19 20 struct TensorDesc: 21 """Describes a tensor's shape and dtype. No data — just metadata. 22 The actual data lives in the backend (numpy array, Mojo SIMD buffer, GPU buffer). 23 """ 24 var shape: String # "batch,seq,dim" — symbolic shape description 25 var dtype: String # "f32", "q4_0", etc. 26 27 fn __init__(out self, shape: String, dtype: String = "f32"): 28 self.shape = shape 29 self.dtype = dtype 30 31 32 # ─── Shared primitive ops (architecture-agnostic) ────────────────────── 33 # These ops are reused across all model architectures. 34 35 struct MatmulOp: 36 """y = x @ W.T""" 37 var name: String 38 var in_features: Int 39 var out_features: Int 40 41 fn __init__(out self, name: String, in_features: Int, out_features: Int): 42 self.name = name 43 self.in_features = in_features 44 self.out_features = out_features 45 46 47 struct AttentionOp: 48 """Multi-head attention with optional KV cache. 49 softmax(Q @ K.T / sqrt(d)) @ V 50 51 Backends: numpy -> Mojo SIMD MHA -> MAX MHA kernel (CPU/GPU dispatch) 52 """ 53 var n_head: Int 54 var n_kv_head: Int 55 var head_dim: Int 56 57 fn __init__(out self, n_head: Int, n_kv_head: Int, head_dim: Int): 58 self.n_head = n_head 59 self.n_kv_head = n_kv_head 60 self.head_dim = head_dim 61 62 63 struct RMSNormOp: 64 """x / sqrt(mean(x^2) + eps) * weight""" 65 var eps: Float32 66 67 fn __init__(out self, eps: Float32 = 1e-6): 68 self.eps = eps 69 70 71 struct RoPEOp: 72 """Rotary Position Embedding — applied to full head dimension.""" 73 var theta: Float32 74 75 fn __init__(out self, theta: Float32 = 10000.0): 76 self.theta = theta 77 78 79 struct SiLUOp: 80 """x * sigmoid(x)""" 81 pass 82 83 84 struct EmbedOp: 85 """Token embedding lookup: embed[input_ids]""" 86 var vocab_size: Int 87 var dim: Int 88 89 fn __init__(out self, vocab_size: Int, dim: Int): 90 self.vocab_size = vocab_size 91 self.dim = dim 92 93 94 struct AddOp: 95 """Element-wise addition (residual connection)""" 96 pass 97 98 99 # ─── ZAYA1-specific primitive ops ────────────────────────────────────── 100 # ZAYA1 (Zyphra) is a MoE++ architecture combining attention, Mamba-2 SSM, 101 # Cross-Layer Attention, and Mixture of Depths. 102 103 struct PartialRoPEOp: 104 """Partial rotary position embedding — applies RoPE to first `dim` dims. 105 ZAYA1 uses dim=64 with theta=10000.0 (partial rotary factor = 0.5). 106 The remaining (head_dim - dim) dimensions pass through unrotated. 107 """ 108 var dim: Int # Number of dimensions to rotate 109 var theta: Float32 110 111 fn __init__(out self, dim: Int = 64, theta: Float32 = 10000.0): 112 self.dim = dim 113 self.theta = theta 114 115 116 struct Mamba2Op: 117 """Mamba-2 selective state-space model (SSM) layer. 118 119 Architecture: 120 x -> conv1d (silu) -> SSM scan (A, B, C, dt) -> y 121 122 Selective scan parameters: 123 - state_dim: D, the state expansion factor (SSM state size per channel) 124 - conv_kernel: Width of the local 1D convolution (ZAYA1: kernel=2) 125 - dt_rank: Rank of the time-step projection (default: state_dim) 126 127 ZAYA1 uses state_dim=16 (expansion_factor=0.5 of embed=2048 -> 1024 / 64 channels). 128 """ 129 var state_dim: Int # SSM state dimension (D) 130 var conv_kernel: Int # Local convolution kernel size 131 var dt_rank: Int # Discretization time-step projection rank 132 133 fn __init__(out self, state_dim: Int, conv_kernel: Int = 2, dt_rank: Int = -1): 134 self.state_dim = state_dim 135 self.conv_kernel = conv_kernel 136 self.dt_rank = dt_rank if dt_rank > 0 else state_dim 137 138 139 struct MoERouterOp: 140 """Mixture of Experts routing/gating. 141 142 Computes expert logits per token: softmax(W_router @ x). 143 Determines which expert(s) each token is routed to. 144 ZAYA1 uses top-1 routing (each token goes to exactly 1 expert). 145 146 Load balancing: auxiliary loss encourages uniform expert utilization. 147 """ 148 var n_experts: Int # Total number of experts (ZAYA1-8B: 16) 149 var top_k: Int # Top-k experts per token (ZAYA1: 1) 150 var dim: Int # Input dimension for router projection 151 152 fn __init__(out self, n_experts: Int, dim: Int, top_k: Int = 1): 153 self.n_experts = n_experts 154 self.top_k = top_k 155 self.dim = dim 156 157 158 struct ExpertFFNOp: 159 """A single expert FFN within an MoE layer. 160 SwiGLU gated FFN: (silu(x @ gate.T) * (x @ up.T)) @ down.T 161 Same structure as dense FFN, but per-expert. 162 """ 163 var intermediate_dim: Int # Hidden dimension within the expert 164 165 fn __init__(out self, intermediate_dim: Int): 166 self.intermediate_dim = intermediate_dim 167 168 169 struct MoEFFNOp: 170 """Mixture of Experts FFN — router + N parallel expert FFNs. 171 172 For each token: 173 1. Router computes expert weights -> selects top_k experts 174 2. Token is dispatched to selected experts 175 3. Expert outputs are combined via weighted sum 176 177 ZAYA1-8B: 16 experts, top-1 routing, expert_intermediate_dim varies. 178 """ 179 var router: MoERouterOp 180 var expert: ExpertFFNOp # All experts share the same intermediate structure 181 var n_experts: Int 182 183 fn __init__(out self, n_experts: Int, dim: Int, expert_intermediate_dim: Int, 184 top_k: Int = 1): 185 self.router = MoERouterOp(n_experts, dim, top_k) 186 self.expert = ExpertFFNOp(expert_intermediate_dim) 187 self.n_experts = n_experts 188 189 190 struct ModRouterOp: 191 """Mixture of Depths routing — token-level sub-layer gating. 192 193 Each token independently decides whether to pass through the sub-layer 194 (attention or SSM) or take the residual shortcut. 195 196 MoD enables dynamic computation: tokens that already have sufficient 197 context skip expensive sub-layer computation. 198 """ 199 var dim: Int # Input dimension for router 200 201 fn __init__(out self, dim: Int): 202 self.dim = dim 203 204 205 # ─── Llama3 Transformer Block ────────────────────────────────────────── 206 207 struct TransformerBlock: 208 """A single transformer block = Attention + FFN with residuals. 209 Dense architecture (no MoE): all tokens pass through all sub-layers. 210 """ 211 var attention: AttentionOp 212 var attn_norm: RMSNormOp 213 var ffn_norm: RMSNormOp 214 var q_proj: MatmulOp 215 var k_proj: MatmulOp 216 var v_proj: MatmulOp 217 var o_proj: MatmulOp 218 var gate_proj: MatmulOp 219 var up_proj: MatmulOp 220 var down_proj: MatmulOp 221 222 fn __init__(out self, n_embd: Int, n_head: Int, n_kv_head: Int, n_ff: Int): 223 var hd = n_embd // n_head 224 self.attention = AttentionOp(n_head, n_kv_head, hd) 225 self.attn_norm = RMSNormOp() 226 self.ffn_norm = RMSNormOp() 227 self.q_proj = MatmulOp("q", n_embd, n_embd) 228 self.k_proj = MatmulOp("k", n_embd, n_kv_head * hd) 229 self.v_proj = MatmulOp("v", n_embd, n_kv_head * hd) 230 self.o_proj = MatmulOp("o", n_embd, n_embd) 231 self.gate_proj = MatmulOp("gate", n_embd, n_ff) 232 self.up_proj = MatmulOp("up", n_embd, n_ff) 233 self.down_proj = MatmulOp("down", n_ff, n_embd) 234 235 236 # ─── ZAYA1 Layer Types ───────────────────────────────────────────────── 237 # ZAYA1 interleaves two block types: 238 # Type A: Attention sub-layer (GQA with partial RoPE + CCA) 239 # Type B: Mamba-2 SSM sub-layer 240 # Each uses MoE FFN with MoD routing. 241 242 struct Zaya1AttentionSubLayer: 243 """Attention sub-layer for ZAYA1. 244 245 GQA attention with: 246 - Partial RoPE (first `rope_dim` dimensions only) 247 - Cross-Layer Attention (CCA): KV pairs shared between adjacent layers 248 - MoD: per-token routing through this sub-layer 249 250 CCA means blk.N and blk.N+1 share the same KV projections. 251 Only the Q projection differs between paired layers. 252 """ 253 var attention: AttentionOp 254 var rope: PartialRoPEOp 255 256 fn __init__(out self, n_head: Int, n_kv_head: Int, head_dim: Int, 257 rope_dim: Int = 64, rope_theta: Float32 = 10000.0): 258 self.attention = AttentionOp(n_head, n_kv_head, head_dim) 259 self.rope = PartialRoPEOp(rope_dim, rope_theta) 260 261 262 struct Zaya1SSMSubLayer: 263 """Mamba-2 SSM sub-layer for ZAYA1. 264 265 Selective state-space model with: 266 - 1D convolution (silu activation) 267 - Selective scan with learned A, B, C, dt parameters 268 - MoD: per-token routing through this sub-layer 269 """ 270 var ssm: Mamba2Op 271 272 fn __init__(out self, state_dim: Int, conv_kernel: Int = 2): 273 self.ssm = Mamba2Op(state_dim, conv_kernel) 274 275 276 struct Zaya1Layer: 277 """A single ZAYA1 layer = norm + sub-layer (attention or SSM) + MoE FFN + MoD. 278 279 Each layer in ZAYA1 has: 280 1. Input normalization (RMSNorm) 281 2. Sub-layer: Attention (with CCA + partial RoPE) or Mamba-2 SSM 282 3. MoD routing: per-token decision to keep sub-layer output or skip 283 4. MoE FFN: 16 experts, top-1 routing with router 284 5. Residual connection 285 286 The `is_attention` field distinguishes the type at the graph level 287 (no runtime dispatch — the graph IS the architecture). 288 """ 289 var sublayer_type: String # "attention" or "ssm" 290 var input_norm: RMSNormOp 291 var attention: Zaya1AttentionSubLayer # Valid when sublayer_type == "attention" 292 var ssm: Zaya1SSMSubLayer # Valid when sublayer_type == "ssm" 293 var mod_router: ModRouterOp 294 var moe_ffn: MoEFFNOp 295 296 fn __init__(out self, sublayer_type: String, n_embd: Int, n_head: Int, 297 n_kv_head: Int, head_dim: Int, n_experts: Int, 298 expert_intermediate_dim: Int, state_dim: Int, 299 rope_dim: Int = 64, top_k: Int = 1): 300 self.sublayer_type = sublayer_type 301 self.input_norm = RMSNormOp() 302 self.attention = Zaya1AttentionSubLayer(n_head, n_kv_head, head_dim, rope_dim) 303 self.ssm = Zaya1SSMSubLayer(state_dim) 304 self.mod_router = ModRouterOp(n_embd) 305 self.moe_ffn = MoEFFNOp(n_experts, n_embd, expert_intermediate_dim, top_k) 306 307 308 # ─── Llama3 Model Graph ──────────────────────────────────────────────── 309 310 struct Llama3Graph: 311 """Complete Llama3 model as a graph of operations.""" 312 var embed: EmbedOp 313 var output_norm: RMSNormOp 314 var lm_head: MatmulOp 315 316 fn __init__(out self, n_layers: Int, n_embd: Int, n_head: Int, 317 n_kv_head: Int, n_ff: Int, vocab_size: Int): 318 self.embed = EmbedOp(vocab_size, n_embd) 319 self.output_norm = RMSNormOp() 320 self.lm_head = MatmulOp("lm_head", n_embd, vocab_size) 321 322 323 # ─── ZAYA1 Model Graph ───────────────────────────────────────────────── 324 # 325 # ZAYA1-8B architecture (80 layers): 326 # Pattern: [ATTN, ATTN, SSM, SSM] × 20 327 # - Attention layers use Cross-Layer Attention (CCA pairs: layer 0&1, 4&5, ...) 328 # - SSM layers use Mamba-2 329 # - All layers use MoE FFN (16 experts, top-1) + MoD routing 330 # 331 # CCA: layers at indices (0,1), (4,5), (8,9), ... share KV pairs. 332 # Within each pair, block N produces KV, block N+1 reuses. 333 # 334 # Default configuration (ZAYA1-8B): 335 # n_layers=80, n_embd=2048, n_head=8, n_kv_head=2, head_dim=256 336 # rope_dim=64 (partial rotary, factor=0.5) 337 # n_experts=16, top_k=1, expert_intermediate_dim=? 338 # state_dim=?, conv_kernel=2 (for Mamba-2) 339 # max_seq_len=131072 340 # vocab_size=256000 (Gemma4 tokenizer) 341 # norm_eps=?, rope_theta=10000.0 342 343 struct Zaya1Graph: 344 """Complete ZAYA1 model as a graph of operations. 345 346 Contains: 347 - Token embedding 348 - 80 interleaved layers (attention / SSM blocks) 349 - Output normalization 350 - LM head (MoE router at output) 351 352 Layer pattern (20 repeats of [ATTN, ATTN, SSM, SSM]): 353 idx 0: ATTN (CCA pair with idx 1) 354 idx 1: ATTN (CCA pair with idx 0) 355 idx 2: SSM 356 idx 3: SSM 357 idx 4: ATTN (CCA pair with idx 5) 358 idx 5: ATTN (CCA pair with idx 4) 359 ... 360 """ 361 var embed: EmbedOp 362 var output_norm: RMSNormOp 363 var lm_head: MatmulOp 364 # NOTE: Layer array would live here when Mojo supports dynamic arrays of structs. 365 # For Mojo 0.26.2: use a backend-side representation (the Python inference class). 366 # The graph constants below document the exact layer topology. 367 368 fn __init__(out self, vocab_size: Int, n_embd: Int): 369 self.embed = EmbedOp(vocab_size, n_embd) 370 self.output_norm = RMSNormOp() 371 self.lm_head = MatmulOp("lm_head", n_embd, vocab_size) 372 373 374 # ─── Architecture constants ──────────────────────────────────────────── 375 # These constants document the exact graph topology for each architecture. 376 # The Mojo 0.26.2 backend (Python bridge) reads these to construct the 377 # correct computation DAG. Future backends will use them as compile-time 378 # graph definitions. 379 380 # ZAYA1-8B layer topology: returns a list of layer-type strings 381 # describing the full 80-layer interleaved pattern. 382 # Pattern: [ATTN, ATTN, SSM, SSM] × 20 383 fn zaya1_layer_schedule() -> String: 384 """Returns the 80-layer interleaved schedule as a comma-separated string. 385 386 Format: "attention,attention,ssm,ssm,attention,attention,..." 387 Backends parse this to build the layer DAG. 388 """ 389 var result: String = "" 390 var i: Int = 0 391 while i < 20: 392 if i > 0: 393 result += "," 394 result += "attention,attention,ssm,ssm" 395 i += 1 396 return result 397 398 399 # ZAYA1 CCA pairing: returns a mapping of which layers share KV cache. 400 # Format: "L0:L1,L4:L5,..." where paired layers share KV projections. 401 fn zaya1_cca_pairs() -> String: 402 """Returns CCA pairs as comma-separated 'L:R' tuples. 403 404 Layers at indices (0,1), (4,5), (8,9), ..., (76,77) are paired. 405 Layers 2,3,6,7,etc (SSM layers) are unpaired. 406 """ 407 var result: String = "" 408 var i: Int = 0 409 while i < 80: 410 # Check if this is the first of an ATTN pair (indices 0,4,8,...,76) 411 if i % 4 == 0: 412 if len(result) > 0: 413 result += "," 414 result += "L" + String(i) + ":L" + String(i + 1) 415 i += 1 416 return result