code wiki / (root) / nx_transformer_block.nx

nx_transformer_block.nx

buildroot/runtime/nx_transformer_block.nx

11645 B300 linesdepth 6pulls 14 transitivereach 23 importersview sourcekind tooltopic transformer
docsdependenciesstructsconstsfunctions

about

nx_transformer_block.nx -- full Llama-class transformer block. Composes every per-layer primitive shipped this session into one callable that processes a token sequence through ONE transformer layer. The substrate's load-bearing answer to "off CUDA + run a model" -- callers invoke this function n_layers times and the substrate handles the orchestration. Per the bits-up + no-skipping cardinals: pure composition. No new math, no reinvented kernels. Just wires shipped primitives. ===== Block shape (Llama 2/3 / Mistral / Qwen / Z-Image style) ==== input x: [n_tokens, hidden_dim] 1) attn_in = RMSNorm(x, gamma_attn) 2) q = matmul(attn_in, W_q) : [n_tokens, head_dim*n_heads] k = matmul(attn_in, W_k) : [n_tokens, head_dim*n_kv_heads] v = matmul(attn_in, W_v) : [n_tokens, head_dim*n_kv_heads] 3) q = RoPE(q, positions) : in-place k = RoPE(k, positions) : in-place 4) attn_out = attention(q, k, v) : [n_tokens, hidden_dim] (single-head shape for v1; multi-head + GQA queued) 5) attn_proj = matmul(attn_out, W_o) 6) x = x + attn_proj (residual) 7) ffn_in = RMSNorm(x, gamma_ffn) 8) gate = SiLU(matmul(ffn_in, W_gate)) 9) up = matmul(ffn_in, W_up) 10) ffn_hidden = gate * up (element-wise: SwiGLU) 11) ffn_proj = matmul(ffn_hidden, W_down) 12) x = x + ffn_proj (residual) output: x (same shape as input) Weights packed in a TransformerBlockWeights struct so the caller passes one pointer per block instead of seven matrices. ===== Single-head v1 ============================================ v1 treats hidden_dim as a single attention head. Multi-head and

dependencies 9 imports · 2 importers

nx_syscalls.nx nx_tier.nx nx_loop.nx nx_tensor.nx nx_rmsnorm.nx nx_rope.nx nx_silu.nx nx_attention.nx nx_blas_i64.nx nx_transformer_block.nx nx_gguf_load_block.nx nx_transformer_stack.nx

imports: nx_syscalls.nxnx_tier.nxnx_loop.nxnx_tensor.nxnx_rmsnorm.nxnx_rope.nxnx_silu.nxnx_attention.nxnx_blas_i64.nx

imported by: nx_gguf_load_block.nxnx_transformer_stack.nx

call flow from main pre-order; caps 40 nodes / depth 6 declared; ↻ = already shown

main sys_mmap nx_t_alloc nx_dt_is_valid nx_dt_element_bytes sys_mmap ↻ nx_t_compute_strides_rowma nx_tb_verdict_is_valid

structs

113struct NxTransformerBlockWeights

consts

87const NX_TB_Q10: nx_int = 1024
91const NX_TB_OK: nx_int = 0
92const NX_TB_ERR_BAD_DIMS: nx_int = 1
93const NX_TB_ERR_SHAPE_MISMATCH: nx_int = 2
94const NX_TB_ERR_NULL_WEIGHTS: nx_int = 3
95const NX_TB_ERR_INTERNAL: nx_int = 4
96const NX_TB_N_VERDICTS: nx_int = 5
126const NX_TB_WEIGHTS_BYTES: nx_int = 80 // 10 fields * 8

functions

98func nx_tb_verdict_is_valid(v: nx_int) -> nx_int
called by 1: main
140func nx_transformer_block_forward(
267func main() -> i64