ThatAIguyA world of ideas

THE CONSCIOUSNESS ATLAS
Read. Experiment. Follow the evidence.

ConsciousnessLearn · Explore · Joseph Anady

DEEPSEEK_R1_COMPLETE.txt

Source identity, revision, and recovered contents.

donor model source and installation dossierSource text recovered

Source identity

FieldRecorded value
Source typedonor model source and installation dossier
Original recordDEEPSEEK_R1_COMPLETE.txt
DateAug 5, 2026
Path or archive memberDEEPSEEK_R1_COMPLETE.txt
Original SHA-25657b226f8d7567427c77e0f5ab89664a6fcc77a3ead102c13e2e955a12de2941a
Reading-copy SHA-2564484b623fddf75ba06332795f04bf80b0acb1310aa3d5be4698206ded50de540

Recovered source transcript

Download complete source text ↓4,262 lines · 205.4 KB
================================================================================ D E E P S E E K - R 1 Complete reference: architecture map, dataflow, file architecture, API surface, endpoints, and full source code as installed on MEGAMIND-AGI, 2026-08-05 ================================================================================ Model DeepSeek-R1 Architecture DeepseekV3ForCausalLM (deepseek_v3) Parameters 671B total / 37B activated per token [per official model card] Location /home/joseph/DeepSeek-R1 on MEGAMIND-AGI (WSL2 Ubuntu) Size 643 GB on disk / 641.29 GiB tensor payload / 163 shards Downloaded 2026-08-04 05:35-07:21 (huggingface_hub snapshot_download) Scanned 2026-08-05, live, by parsing all 163 safetensors file headers Paper arXiv:2501.12948 License MIT (weights and code; commercial use and distillation permitted) CONTENTS PART 1 MEGAMIND-AGI MACHINE SPECIFICATIONS PART 2 FILE ARCHITECTURE 2.1 Directory inventory 2.2 The safetensors container format 2.3 model.safetensors.index.json structure 2.4 Layer -> shard map (all 62 layer indices) 2.5 Shard -> layer map (all 163 shards) 2.6 On-disk expert layout 2.7 Integrity verification PART 3 ARCHITECTURE SPECIFICATION (every config value) PART 4 COMPLETE ARCHITECTURE MAP (module tree, every parameter) 4.1 Top-level module tree 4.2 Dense layer manifest (layers 0-2) 4.3 MoE layer manifest (layers 3-60) 4.4 One routed expert 4.5 MTP layer manifest (layer 61) 4.6 Global tensors 4.7 Parameter accounting PART 5 COMPLETE TENSOR CENSUS PART 6 FP8 QUANTIZATION SCHEME PART 7 MoE ROUTING ALGORITHM PART 8 MLA ATTENTION PART 9 YaRN POSITION ENCODING PART 10 COMPLETE DATAFLOW CHART 10.1 Prefill vs decode 10.2 Full tensor-shape dataflow 10.3 KV cache lifecycle 10.4 MoE dispatch dataflow 10.5 MTP / speculative decode dataflow PART 11 TOKENIZER AND WIRE FORMAT 11.1 Tokenizer pipeline 11.2 Complete special-token table 11.3 Chat template semantics 11.4 A rendered example PART 12 API SURFACE AND ENDPOINTS 12.1 HuggingFace auto_map and load path 12.2 Python class API (complete) 12.3 DeepseekV3Config parameters 12.4 forward() input/output contract 12.5 Official hosted API endpoints 12.6 Self-hosted serving endpoints 12.7 The reasoning-content contract PART 13 FOOTPRINT: MEMORY, DISK I/O, COMPUTE PART 14 DISCREPANCIES, TRAPS AND GOTCHAS PART 15 SOURCE CODE (verbatim) 15.1 config.json 15.2 configuration_deepseek.py (199 lines) 15.3 modeling_deepseek.py (1,848 lines) 15.4 generation_config.json 15.5 tokenizer_config.json 15.6 README.md (official model card) NOTATION [MEASURED] read off this machine during the scan [SPEC] read out of the model's own config.json / reference source [COMPUTED] arithmetic from measured values; formula always shown [CARD] stated by the official model card (README.md, reproduced in 15.6) [EXTERNAL] about services outside this machine; verify against live docs ================================================================================ PART 1 MEGAMIND-AGI MACHINE SPECIFICATIONS [MEASURED] ================================================================================ IDENTITY Hostname MEGAMIND-AGI Chassis Dell Precision 3630 Tower Tailnet 100.69.120.61 Windows host 100.77.114.40 WSL2 guest (megamind-agi-wsl) Users WSL: joseph Windows: Josep CPU Model Intel Core i7-8700K @ 3.70 GHz Topology 1 socket / 6 cores / 12 threads (Hyper-Threading enabled) Cache L1d 192 KiB (6 inst) L1i 192 KiB (6 inst) L2 1.5 MiB (6 inst) L3 12 MiB (1 inst, shared) ISA PRESENT avx2 fma f16c popcnt sse4_2 aes bmi1 bmi2 rdseed adx movbe xsave xsavec xsaves clflushopt erms invpcid rtm hle ISA ABSENT avx512f avx512bw avx512vnni avx_vnni amx_int8 amx_bf16 -> no hardware fp8 or bf16 conversion instruction -> no VNNI int8 dot; int8 MAC needs vpmaddubsw + vpmaddwd -> 256-bit vectors are the widest available GPU Intel UHD 630 integrated graphics only. No discrete GPU installed. MEMORY Visible to WSL2 25 GiB (.wslconfig memory=26GB) Swap 8 GiB (/dev/sdc) At scan time 15 GiB used | 784 MiB free | 14 GiB buff/cache 9.6 GiB available | 2.3 GiB of swap already in use STORAGE /dev/sdd 1007 GiB ext4, WSL2 vhdx on a 1 TB WD Green SN350 NVMe SSD 729 GiB used / 228 GiB available / 77% full, mounted at / -- this is where DeepSeek-R1 lives /mnt/c 931 GiB, 800 GiB used, 132 GiB free (Windows side, same NVMe) /dev/sdc 8 GiB swap MEASURED THROUGHPUT against the R1 shards: --------------------------------------------------------------------------- access pattern throughput --------------------------------------------------------------------------- single stream, 8 MiB blocks, 2 GiB read 507 MB/s same file immediately again (page cache warm) 408 MB/s 4 parallel streams, 4 different shards, 512 MiB each 1220 MB/s aggregate 56 scattered 4 MiB preads at random offsets 326 MB/s --------------------------------------------------------------------------- Four-way parallelism yields 2.4x over a single stream, so this device has real concurrency headroom. The warm re-read being SLOWER than the cold one (408 vs 507) shows the page cache does not help: 25 GiB of RAM against a 643 GB model has nothing to cache, and the vhdx indirection costs. OPERATING SYSTEM Windows 11 Pro (host) + WSL2 Ubuntu (guest) Kernel 6.18.33.2-microsoft-standard-WSL2 x86_64 /etc/wsl.conf [boot] systemd=true [network] generateResolvConf=true .wslconfig [wsl2] memory=26GB processors=12 vmIdleTimeout=-1 swap=8GB TOOLCHAIN clang 21.1.8 gcc 15.2.0 Python 3.14.4 pip packages huggingface_hub 1.26.0 | numpy 2.5.1 NOT INSTALLED torch, transformers, safetensors (python), tokenizers, accelerate, llama.cpp, ollama, vllm, sglang -> there is currently no way to run this model on this machine -> PyTorch has no stable cp314 wheels; a torch path needs a separate Python 3.11/3.12 interpreter or venv ACCESS NOTES The Windows host's default SSH shell is cmd.exe, not bash. Run inside the distro with: wsl.exe -d Ubuntu -- bash -c "..." cmd.exe caps command lines at 8191 characters; for anything long the reliable pattern is base64 -> wsl -- bash -c "echo <b64> | base64 -d | bash". WSL2 tears down backgrounded jobs when a one-shot command returns, so long jobs must run under systemd (systemd-run or a unit file). ================================================================================ PART 2 FILE ARCHITECTURE [MEASURED] ================================================================================ -------------------------------------------------------------------------------- 2.1 DIRECTORY INVENTORY -------------------------------------------------------------------------------- /home/joseph/DeepSeek-R1 643 GB, 175 entries bytes file role --------------------------------------------------------------------------- 1,660 config.json architecture + quantization + rope 9,897 configuration_deepseek.py DeepseekV3Config, 199 lines 75,741 modeling_deepseek.py reference forward pass, 1,848 lines 8,898,324 model.safetensors.index.json weight map: 91,991 -> 163 shards 7,847,602 tokenizer.json BPE vocab + merges + added tokens 3,594 tokenizer_config.json chat template, special tokens 171 generation_config.json sampling defaults 15,994 README.md official model card 1,064 LICENSE MIT 1,519 .gitattributes git-lfs filter rules 777,314 figures/benchmark.jpg model card benchmark chart --------------------------------------------------------------------------- + 163 x model-000NN-of-000163.safetensors the weights + .cache/huggingface/download/ 353 entries of download bookkeeping -------------------------------------------------------------------------------- 2.2 THE SAFETENSORS CONTAINER FORMAT -------------------------------------------------------------------------------- Every shard has the same three-region layout: byte 0 8 8+N EOF +-----------------+-------------------+---------------------------+ | u64 little-end | JSON header | raw tensor data | | N = header len | N bytes | concatenated, no padding | +-----------------+-------------------+---------------------------+ The JSON header maps every tensor name to an object: "model.layers.3.mlp.experts.0.gate_proj.weight": { "dtype": "F8_E4M3", "shape": [2048, 7168], "data_offsets": [start, end] // relative to 8+N, not to 0 } plus one reserved key "__metadata__" which here is always {"format": "pt"}. Absolute file offset of a tensor = 8 + N + data_offsets[0] Tensor byte length = data_offsets[1] - data_offsets[0] MEASURED header sizes: shard 001: N = 34,119 B data begins at byte 34,127 file 5,234,139,343 B shard 080: N = 76,042 B data begins at byte 76,050 file 4,302,384,914 B shard 163: N = 48,183 B data begins at byte 48,191 file 6,584,784,447 B THE HEADER IS THE AUTHORITATIVE SOURCE for dtype, full shape (all ranks), offset and length. The index file carries only the name -> shard mapping. -------------------------------------------------------------------------------- 2.3 model.safetensors.index.json STRUCTURE -------------------------------------------------------------------------------- Top-level keys: ["metadata", "weight_map"] metadata {"total_size": 1369062772000} weight_map 91,991 entries, each "<tensor name>": "model-000NN-of-000163.safetensors" e.g. "model.embed_tokens.weight" -> "model-00001-of-000163.safetensors" It names 163 distinct shards and 91,991 distinct tensors. WARNING: metadata.total_size reads 1,369,062,772,000 bytes (1.245 TiB) while the actual payload is 688,574,839,360 bytes (641.29 GiB). It overstates by 1.99x because the exporter costed FP8 elements at two bytes each. Never size buffers, allocations or progress reporting from this field. -------------------------------------------------------------------------------- 2.4 LAYER -> SHARD MAP -------------------------------------------------------------------------------- Which files must be opened to materialize a given layer. A loader that walks the model layer by layer needs this table; a loader that walks shard by shard needs 2.5. layer shards n role layer shards n role -------------------------------------- -------------------------------------- global 1, 160 2 embed/norm/head 31 79-81 3 MoE 0 1 1 dense 32 81-84 4 MoE 1 1 1 dense 33 84-87 4 MoE 2 1 1 dense 34 87-89 3 MoE 3 1-4 4 MoE 35 89-92 4 MoE 4 4-6 3 MoE 36 92-95 4 MoE 5 6-9 4 MoE 37 95-97 3 MoE 6 9-12 4 MoE 38 97-100 4 MoE 7 13-15 3 MoE 39 101-103 3 MoE 8 15-18 4 MoE 40 103-106 4 MoE 9 18-21 4 MoE 41 106-109 4 MoE 10 21-23 3 MoE 42 109-111 3 MoE 11 23-26 4 MoE 43 111-114 4 MoE 12 26-29 4 MoE 44 114-117 4 MoE 13 29-31 3 MoE 45 117-119 3 MoE 14 31-34 4 MoE 46 119-122 4 MoE 15 35-37 3 MoE 47 123-125 3 MoE 16 37-40 4 MoE 48 125-128 4 MoE 17 40-43 4 MoE 49 128-131 4 MoE 18 43-45 3 MoE 50 131-133 3 MoE 19 45-48 4 MoE 51 133-136 4 MoE 20 48-51 4 MoE 52 136-139 4 MoE 21 51-53 3 MoE 53 139-141 3 MoE 22 53-56 4 MoE 54 142-144 3 MoE 23 57-59 3 MoE 55 144-147 4 MoE 24 59-62 4 MoE 56 147-150 4 MoE 25 62-65 4 MoE 57 150-152 3 MoE 26 65-67 3 MoE 58 152-155 4 MoE 27 67-70 4 MoE 59 155-158 4 MoE 28 70-73 4 MoE 60 158-160 3 MoE 29 73-75 3 MoE 61 160-163 4 MTP 30 75-78 4 MoE -------------------------------------- -------------------------------------- Every MoE layer spans 3 or 4 shards. No layer is contained in a single file except the three dense layers, which all share shard 1 with embed_tokens. The global tensors are split: embed_tokens in shard 1, model.norm and lm_head in shard 160 (NOT the last shard - shards 161-163 are entirely MTP layer 61). -------------------------------------------------------------------------------- 2.5 SHARD -> LAYER MAP (all 163) -------------------------------------------------------------------------------- shard layers tensors | shard layers tensors | shard layers tensors -------------------------+--------------------------+------------------------- 1 0-3 270 * | 56 22 241 | 111 42-43 576 2 3 586 | 57 23 573 | 112 43 586 3 3 586 | 58 23 586 | 113 43 586 4 3-4 576 | 59 23-24 576 | 114 43-44 576 5 4 586 | 60 24 586 | 115 44 586 6 4-5 584 | 61 24 586 | 116 44 586 7 5 588 | 62 24-25 576 | 117 44-45 576 8 5 586 | 63 25 586 | 118 45 586 9 5-6 576 | 64 25 586 | 119 45-46 576 10 6 586 | 65 25-26 576 | 120 46 586 11 6 586 | 66 26 586 | 121 46 586 12 6 183 | 67 26-27 576 | 122 46 241 13 7 573 | 68 27 586 | 123 47 573 14 7 586 | 69 27 586 | 124 47 586 15 7-8 576 | 70 27-28 576 | 125 47-48 576 16 8 586 | 71 28 586 | 126 48 586 17 8 586 | 72 28 586 | 127 48 586 18 8-9 576 | 73 28-29 576 | 128 48-49 576 19 9 586 | 74 29 586 | 129 49 586 20 9 586 | 75 29-30 576 | 130 49 586 21 9-10 576 | 76 30 586 | 131 49-50 576 22 10 586 | 77 30 586 | 132 50 586 23 10-11 576 | 78 30 241 | 133 50-51 576 24 11 586 | 79 31 573 | 134 51 586 25 11 586 | 80 31 586 | 135 51 586 26 11-12 576 | 81 31-32 576 | 136 51-52 576 27 12 586 | 82 32 586 | 137 52 586 28 12 586 | 83 32 586 | 138 52 586 29 12-13 576 | 84 32-33 576 | 139 52-53 576 30 13 586 | 85 33 586 | 140 53 586 31 13-14 576 | 86 33 586 | 141 53 431 32 14 586 | 87 33-34 576 | 142 54 573 33 14 586 | 88 34 586 | 143 54 586 34 14 241 | 89 34-35 576 | 144 54-55 576 35 15 573 | 90 35 586 | 145 55 586 36 15 586 | 91 35 586 | 146 55 586 37 15-16 576 | 92 35-36 576 | 147 55-56 576 38 16 586 | 93 36 586 | 148 56 586 39 16 586 | 94 36 586 | 149 56 586 40 16-17 576 | 95 36-37 576 | 150 56-57 576 41 17 586 | 96 37 586 | 151 57 586 42 17 586 | 97 37-38 576 | 152 57-58 576 43 17-18 576 | 98 38 586 | 153 58 586 44 18 586 | 99 38 586 | 154 58 586 45 18-19 576 | 100 38 241 | 155 58-59 576 46 19 586 | 101 39 573 | 156 59 586 47 19 586 | 102 39 586 | 157 59 586 48 19-20 576 | 103 39-40 576 | 158 59-60 576 49 20 586 | 104 40 586 | 159 60 586 50 20 586 | 105 40 586 | 160 60-61 452 ** 51 20-21 576 | 106 40-41 576 | 161 61 586 52 21 586 | 107 41 586 | 162 61 586 53 21-22 576 | 108 41 586 | 163 61 373 54 22 586 | 109 41-42 576 | 55 22 586 | 110 42 586 | -------------------------+--------------------------+------------------------- * shard 1 also holds model.embed_tokens.weight ** shard 160 also holds model.norm.weight and lm_head.weight -------------------------------------------------------------------------------- 2.6 ON-DISK EXPERT LAYOUT -------------------------------------------------------------------------------- Each routed expert's six tensors are stored CONTIGUOUSLY, always in this order: gate_proj.weight 14,680,064 B F8_E4M3 (2048, 7168) gate_proj.weight_scale_inv 3,584 B F32 (16, 56) up_proj.weight 14,680,064 B F8_E4M3 (2048, 7168) up_proj.weight_scale_inv 3,584 B F32 (16, 56) down_proj.weight 14,680,064 B F8_E4M3 (7168, 2048) down_proj.weight_scale_inv 3,584 B F32 (56, 16) ---------------------------------------------------------------- TOTAL PER EXPERT 44,050,944 B = 42.01 MiB exactly Verified on shard 80: 98 of 98 experts fully contiguous, span exactly equal to payload, zero interior gaps. One expert is one seek and one read. Experts CAN straddle a shard boundary. Observed: layer 31 expert 92 begins in shard 79 (gate_proj) and continues in shard 80 (its scale onward), leaving a within-shard span of 29,370,880 rather than 44,050,944. With 162 shard boundaries, roughly 162 of the 14,848 inference-path experts need two reads. -------------------------------------------------------------------------------- 2.7 INTEGRITY VERIFICATION PERFORMED THIS SESSION -------------------------------------------------------------------------------- Method: read the 8-byte length prefix and JSON header of every shard; compare the header+data extent to the on-disk file size; cross-check every tensor name and shard assignment against model.safetensors.index.json. --------------------------------------------------------------------------- shards where 8 + N + max(data_offsets) != filesize ....... 0 of 163 tensors in headers but absent from the index ............. 0 tensors in the index but absent from headers ............. 0 shard-placement disagreements (index vs header) .......... 0 --------------------------------------------------------------------------- The checkpoint is complete and internally consistent; nothing is truncated. This is a STRUCTURAL check. Per-shard content hashes against the upstream repository were not computed. DOWNLOAD RESIDUE .cache/huggingface/download/ holds 353 entries: .lock and .metadata files plus 8 orphaned *.incomplete blobs (274 MB, 268 MB, 134 MB, 67 MB, 8.4 MB, 35 KB and two zero-byte) left by an aborted first download attempt. No live shard depends on them; deleting the directory reclaims about 0.70 GiB. ================================================================================ PART 3 ARCHITECTURE SPECIFICATION [SPEC] ================================================================================ architectures ["DeepseekV3ForCausalLM"] model_type deepseek_v3 torch_dtype bfloat16 the unquantized reference dtype transformers_version 4.46.3 CORE DIMENSIONS hidden_size H 7168 num_hidden_layers L 61 (+1 MTP layer at index 61 = 62 in checkpoint) first_k_dense_replace 3 layers 0,1,2 dense MLP; layers 3..60 MoE intermediate_size 18432 dense MLP inner dimension hidden_act silu SwiGLU: down( silu(gate(x)) * up(x) ) rms_norm_eps 1e-6 RMSNorm throughout; no LayerNorm, no biases vocab_size V 129280 tie_word_embeddings false lm_head is a separate 1.726 GiB tensor initializer_range 0.02 use_cache true MIXTURE OF EXPERTS n_routed_experts E 256 num_experts_per_tok k 8 moe_intermediate_size 2048 per-expert inner dimension n_shared_experts 1 always-on expert in every MoE layer moe_layer_freq 1 every layer past the dense prefix is MoE scoring_func sigmoid (NOT softmax) topk_method noaux_tc group-limited routing, see PART 7 n_group 8 256 experts partitioned into 8 groups of 32 topk_group 4 only 4 of the 8 groups eligible per token norm_topk_prob true selected weights renormalized to sum 1 routed_scaling_factor 2.5 applied AFTER renormalization ep_size 1 no expert parallelism in this config MULTI-HEAD LATENT ATTENTION (MLA) num_attention_heads 128 num_key_value_heads 128 no GQA sharing; MLA compresses instead q_lora_rank 1536 query down-projection rank kv_lora_rank 512 KV down-projection rank - the cached dimension qk_nope_head_dim 128 non-positional part of each QK head qk_rope_head_dim 64 RoPE-carrying part of each QK head q_head_dim 192 = 128 + 64 v_head_dim 128 attention_bias false attention_dropout 0.0 softmax_scale 0.135237 [COMPUTED] = 192^-0.5 * mscale^2, where mscale = 0.1*1.0*ln(40)+1 = 1.3688879. mscale_all_dim=1.0 activates this path, so it is NOT the plain 1/sqrt(192) = 0.0721688. POSITION ENCODING - YaRN rope_theta 10000 max_position_embeddings 163840 rope_scaling.type yarn rope_scaling.factor 40 original_max_position_embeddings 4096 (4096 x 40 = 163840) rope_scaling.beta_fast 32 rope_scaling.beta_slow 1 rope_scaling.mscale 1.0 rope_scaling.mscale_all_dim 1.0 QUANTIZATION quant_method fp8 fmt e4m3 weight_block_size [128, 128] activation_scheme dynamic MULTI-TOKEN PREDICTION num_nextn_predict_layers 1 checkpoint layer 61, speculative decoding. Not part of the base autoregressive forward. GENERATION DEFAULTS (generation_config.json) do_sample true | temperature 0.6 | top_p 0.95 | bos_token_id 0 | eos_token_id 1 ================================================================================ PART 4 COMPLETE ARCHITECTURE MAP [MEASURED + SPEC] ================================================================================ Every parameter tensor in the model, organized by module. Shapes and byte counts are read from the safetensors headers; module structure from the reference source. -------------------------------------------------------------------------------- 4.1 TOP-LEVEL MODULE TREE -------------------------------------------------------------------------------- DeepseekV3ForCausalLM | +-- model : DeepseekV3Model | | | +-- embed_tokens : nn.Embedding(129280, 7168) BF16 1.726 GiB | | | +-- layers : ModuleList[62] | | | | | +-- [0] [1] [2] DeepseekV3DecoderLayer DENSE 556.6 MiB each | | | +-- input_layernorm : DeepseekV3RMSNorm(7168) | | | +-- self_attn : DeepseekV3Attention | | | +-- post_attention_layernorm : DeepseekV3RMSNorm(7168) | | | +-- mlp : DeepseekV3MLP(7168 -> 18432) | | | | | +-- [3] .. [60] DeepseekV3DecoderLayer MoE 10.73 GiB each | | | +-- input_layernorm : DeepseekV3RMSNorm(7168) | | | +-- self_attn : DeepseekV3Attention | | | +-- post_attention_layernorm : DeepseekV3RMSNorm(7168) | | | +-- mlp : DeepseekV3MoE | | | +-- gate : MoEGate | | | | +-- weight (256, 7168) BF16 | | | | +-- e_score_correction_bias (256,) F32 | | | +-- experts : ModuleList[256] of DeepseekV3MLP | | | | (7168 -> 2048), fp8 | | | +-- shared_experts : DeepseekV3MLP(7168 -> 2048), fp8 | | | | | +-- [61] MTP LAYER (multi-token prediction) 14.34 GiB | | +-- enorm / hnorm : RMSNorm(7168) | | +-- eh_proj : (7168, 14336) BF16 | | +-- embed_tokens : (129280, 7168) BF16 own copy | | +-- input_layernorm : RMSNorm(7168) | | +-- self_attn : DeepseekV3Attention | | +-- post_attention_layernorm : RMSNorm(7168) | | +-- mlp : DeepseekV3MoE (256 experts) | | +-- shared_head.norm : RMSNorm(7168) | | +-- shared_head.head : (129280, 7168) BF16 own head | | | +-- norm : DeepseekV3RMSNorm(7168) BF16 14,336 B | +-- lm_head : nn.Linear(7168 -> 129280, bias=False) BF16 1.726 GiB DeepseekV3Attention, expanded (identical in all 62 layers): hidden (7168) +-- q_a_proj (1536, 7168) fp8 11,010,048 B +-- q_a_layernorm (1536,) BF16 3,072 B +-- q_b_proj (24576, 1536) fp8 37,748,736 B +-- kv_a_proj_with_mqa (576, 7168) fp8 4,128,768 B +-- kv_a_layernorm (512,) BF16 1,024 B +-- kv_b_proj (32768, 512) fp8 16,777,216 B +-- o_proj (7168, 16384) fp8 117,440,512 B ------------- attention subtotal 187,105,280 B (+ 45,792 B of F32 scales) -------------------------------------------------------------------------------- 4.2 DENSE LAYER MANIFEST - layers 0, 1, 2 (20 tensors each) -------------------------------------------------------------------------------- dtype shape bytes name (relative to model.layers.N.) --------------------------------------------------------------------------- BF16 [7168] 14,336 input_layernorm.weight F8_E4M3 [1536, 7168] 11,010,048 self_attn.q_a_proj.weight F32 [12, 56] 2,688 self_attn.q_a_proj.weight_scale_inv BF16 [1536] 3,072 self_attn.q_a_layernorm.weight F8_E4M3 [24576, 1536] 37,748,736 self_attn.q_b_proj.weight F32 [192, 12] 9,216 self_attn.q_b_proj.weight_scale_inv F8_E4M3 [576, 7168] 4,128,768 self_attn.kv_a_proj_with_mqa.weight F32 [5, 56] 1,120 self_attn.kv_a_proj_with_mqa.weight_scale_inv BF16 [512] 1,024 self_attn.kv_a_layernorm.weight F8_E4M3 [32768, 512] 16,777,216 self_attn.kv_b_proj.weight F32 [256, 4] 4,096 self_attn.kv_b_proj.weight_scale_inv F8_E4M3 [7168, 16384] 117,440,512 self_attn.o_proj.weight F32 [56, 128] 28,672 self_attn.o_proj.weight_scale_inv BF16 [7168] 14,336 post_attention_layernorm.weight F8_E4M3 [18432, 7168] 132,120,576 mlp.gate_proj.weight F32 [144, 56] 32,256 mlp.gate_proj.weight_scale_inv F8_E4M3 [18432, 7168] 132,120,576 mlp.up_proj.weight F32 [144, 56] 32,256 mlp.up_proj.weight_scale_inv F8_E4M3 [7168, 18432] 132,120,576 mlp.down_proj.weight F32 [56, 144] 32,256 mlp.down_proj.weight_scale_inv --------------------------------------------------------------------------- TOTAL 583,642,336 B = 556.6 MiB per dense layer, x3 layers = 1.63 GiB -------------------------------------------------------------------------------- 4.3 MoE LAYER MANIFEST - layers 3..60 (22 non-expert + 256 x 6 tensors) -------------------------------------------------------------------------------- dtype shape bytes name (relative to model.layers.N.) --------------------------------------------------------------------------- BF16 [7168] 14,336 input_layernorm.weight F8_E4M3 [1536, 7168] 11,010,048 self_attn.q_a_proj.weight F32 [12, 56] 2,688 self_attn.q_a_proj.weight_scale_inv BF16 [1536] 3,072 self_attn.q_a_layernorm.weight F8_E4M3 [24576, 1536] 37,748,736 self_attn.q_b_proj.weight F32 [192, 12] 9,216 self_attn.q_b_proj.weight_scale_inv F8_E4M3 [576, 7168] 4,128,768 self_attn.kv_a_proj_with_mqa.weight F32 [5, 56] 1,120 self_attn.kv_a_proj_with_mqa.weight_scale_inv BF16 [512] 1,024 self_attn.kv_a_layernorm.weight F8_E4M3 [32768, 512] 16,777,216 self_attn.kv_b_proj.weight F32 [256, 4] 4,096 self_attn.kv_b_proj.weight_scale_inv F8_E4M3 [7168, 16384] 117,440,512 self_attn.o_proj.weight F32 [56, 128] 28,672 self_attn.o_proj.weight_scale_inv BF16 [7168] 14,336 post_attention_layernorm.weight F32 [256] 1,024 mlp.gate.e_score_correction_bias BF16 [256, 7168] 3,670,016 mlp.gate.weight F8_E4M3 [2048, 7168] 14,680,064 mlp.shared_experts.gate_proj.weight F32 [16, 56] 3,584 mlp.shared_experts.gate_proj.weight_scale_inv F8_E4M3 [2048, 7168] 14,680,064 mlp.shared_experts.up_proj.weight F32 [16, 56] 3,584 mlp.shared_experts.up_proj.weight_scale_inv F8_E4M3 [7168, 2048] 14,680,064 mlp.shared_experts.down_proj.weight F32 [56, 16] 3,584 mlp.shared_experts.down_proj.weight_scale_inv --------------------------------------------------------------------------- non-expert subtotal 234,905,824 B = 224.0 MiB + 256 routed experts x 44,050,944 B = 11,277,041,664 B = 10.50 GiB --------------------------------------------------------------------------- TOTAL PER MoE LAYER 11,511,947,488 B = 10.72 GiB x58 = 621.9 GiB -------------------------------------------------------------------------------- 4.4 ONE ROUTED EXPERT - complete model.layers.N.mlp.experts.M. -------------------------------------------------------------------------------- F8_E4M3 [2048, 7168] 14,680,064 gate_proj.weight F32 [16, 56] 3,584 gate_proj.weight_scale_inv F8_E4M3 [2048, 7168] 14,680,064 up_proj.weight F32 [16, 56] 3,584 up_proj.weight_scale_inv F8_E4M3 [7168, 2048] 14,680,064 down_proj.weight F32 [56, 16] 3,584 down_proj.weight_scale_inv --------------------------------------------------------------------------- TOTAL 44,050,944 B = 42.01 MiB, stored contiguously Computation: down( silu(gate(x)) * up(x) ), 7168 -> 2048 -> 7168 -------------------------------------------------------------------------------- 4.5 MTP LAYER MANIFEST - layer 61 (28 non-expert + 256 x 6 tensors) -------------------------------------------------------------------------------- dtype shape bytes name (relative to model.layers.61.) --------------------------------------------------------------------------- BF16 [7168] 14,336 enorm.weight BF16 [7168] 14,336 hnorm.weight BF16 [7168, 14336] 205,520,896 eh_proj.weight BF16 [129280, 7168] 1,853,358,080 embed_tokens.weight (own copy) BF16 [7168] 14,336 input_layernorm.weight F8_E4M3 [1536, 7168] 11,010,048 self_attn.q_a_proj.weight F32 [12, 56] 2,688 self_attn.q_a_proj.weight_scale_inv BF16 [1536] 3,072 self_attn.q_a_layernorm.weight F8_E4M3 [24576, 1536] 37,748,736 self_attn.q_b_proj.weight F32 [192, 12] 9,216 self_attn.q_b_proj.weight_scale_inv F8_E4M3 [576, 7168] 4,128,768 self_attn.kv_a_proj_with_mqa.weight F32 [5, 56] 1,120 self_attn.kv_a_proj_with_mqa.weight_scale_inv BF16 [512] 1,024 self_attn.kv_a_layernorm.weight F8_E4M3 [32768, 512] 16,777,216 self_attn.kv_b_proj.weight F32 [256, 4] 4,096 self_attn.kv_b_proj.weight_scale_inv F8_E4M3 [7168, 16384] 117,440,512 self_attn.o_proj.weight F32 [56, 128] 28,672 self_attn.o_proj.weight_scale_inv BF16 [7168] 14,336 post_attention_layernorm.weight F32 [256] 1,024 mlp.gate.e_score_correction_bias BF16 [256, 7168] 3,670,016 mlp.gate.weight F8_E4M3 [2048, 7168] 14,680,064 mlp.shared_experts.gate_proj.weight F32 [16, 56] 3,584 mlp.shared_experts.gate_proj.weight_scale_inv F8_E4M3 [2048, 7168] 14,680,064 mlp.shared_experts.up_proj.weight F32 [16, 56] 3,584 mlp.shared_experts.up_proj.weight_scale_inv F8_E4M3 [7168, 2048] 14,680,064 mlp.shared_experts.down_proj.weight F32 [56, 16] 3,584 mlp.shared_experts.down_proj.weight_scale_inv BF16 [7168] 14,336 shared_head.norm.weight BF16 [129280, 7168] 1,853,358,080 shared_head.head.weight (own head) --------------------------------------------------------------------------- non-expert subtotal 4,147,185,888 B = 3.86 GiB + 256 routed experts = 11,277,041,664 B = 10.50 GiB --------------------------------------------------------------------------- TOTAL MTP LAYER 15,424,227,552 B = 14.36 GiB The MTP layer carries its OWN embed_tokens and its OWN output head, which is why the checkpoint contains four 129280x7168 BF16 tensors rather than two. -------------------------------------------------------------------------------- 4.6 GLOBAL TENSORS -------------------------------------------------------------------------------- BF16 [129280, 7168] 1,853,358,080 model.embed_tokens.weight [shard 1] BF16 [7168] 14,336 model.norm.weight [shard 160] BF16 [129280, 7168] 1,853,358,080 lm_head.weight [shard 160] --------------------------------------------------------------------------- These are the only three tensors outside the model.layers.* namespace. -------------------------------------------------------------------------------- 4.7 PARAMETER ACCOUNTING -------------------------------------------------------------------------------- component count bytes GiB --------------------------------------------------------------------------- 3 dense layers x 583,642,336 1,750,927,008 1.63 58 MoE layers x 11,511,947,488 667,692,954,304 621.83 1 MTP layer 15,424,227,552 14.36 embed_tokens + norm + lm_head 3,706,730,496 3.45 --------------------------------------------------------------------------- TOTAL 688,574,839,360 641.29 --------------------------------------------------------------------------- Matches the measured payload exactly, to the byte. MoE layers are 96.97% of the checkpoint. Routed experts alone (all 59 MoE-bearing layers x 256 x 44,050,944 B = 665,345,458,176 B = 619.65 GiB) are 96.6% of it. BASE INFERENCE PATH (excluding the MTP layer): 673,150,611,808 B = 626.93 GiB ACTIVATED PER TOKEN: 37B parameters [CARD] - out of 671B total, because only 8 of 256 routed experts fire per layer. ================================================================================ PART 5 COMPLETE TENSOR CENSUS [MEASURED] ================================================================================ Produced by parsing the JSON header of all 163 safetensors files, which is the authoritative source for dtype, full shape, byte offset and byte length. TOTAL TENSORS 91,991 TOTAL PAYLOAD 688,574,839,360 bytes = 641.29 GiB LAYER INDICES 0 .. 61 (62 distinct: 61 transformer + 1 MTP) BY DTYPE --------------------------------------------------------------------------- dtype count bytes GiB what it is --------------------------------------------------------------------------- F8_E4M3 45,808 680,571,043,840 633.83 every projection weight F32 45,867 166,222,400 0.15 weight_scale_inv + gate bias BF16 316 7,837,573,120 7.30 embeds, lm_head, norms, gates --------------------------------------------------------------------------- Half of all tensors BY COUNT are tiny F32 scale grids. Tensor count is not a proxy for bytes or for work. BY FAMILY (layer and expert indices collapsed to N; sorted by total size) ------------------------------------------------------------------------------ family n dtype GiB shape ------------------------------------------------------------------------------ mlp.experts.N.gate_proj.weight 15,104 F8_E4M3 206.500 (2048, 7168) mlp.experts.N.up_proj.weight 15,104 F8_E4M3 206.500 (2048, 7168) mlp.experts.N.down_proj.weight 15,104 F8_E4M3 206.500 (7168, 2048) self_attn.o_proj.weight 62 F8_E4M3 6.781 (7168, 16384) self_attn.q_b_proj.weight 62 F8_E4M3 2.180 (24576, 1536) model.embed_tokens.weight 1 BF16 1.726 (129280, 7168) lm_head.weight 1 BF16 1.726 (129280, 7168) L61 embed_tokens.weight (MTP) 1 BF16 1.726 (129280, 7168) L61 shared_head.head.weight (MTP) 1 BF16 1.726 (129280, 7168) self_attn.kv_b_proj.weight 62 F8_E4M3 0.969 (32768, 512) mlp.shared_experts.gate_proj.weight 59 F8_E4M3 0.807 (2048, 7168) mlp.shared_experts.up_proj.weight 59 F8_E4M3 0.807 (2048, 7168) mlp.shared_experts.down_proj.weight 59 F8_E4M3 0.807 (7168, 2048) self_attn.q_a_proj.weight 62 F8_E4M3 0.636 (1536, 7168) mlp.gate_proj.weight (dense) 3 F8_E4M3 0.369 (18432, 7168) mlp.up_proj.weight (dense) 3 F8_E4M3 0.369 (18432, 7168) mlp.down_proj.weight (dense) 3 F8_E4M3 0.369 (7168, 18432) self_attn.kv_a_proj_with_mqa.weight 62 F8_E4M3 0.238 (576, 7168) mlp.gate.weight (router) 59 BF16 0.202 (256, 7168) L61 eh_proj.weight (MTP) 1 BF16 0.191 (7168, 14336) mlp.experts.N.*.weight_scale_inv 45,312 F32 0.150 (16,56)/(56,16) self_attn.o_proj.weight_scale_inv 62 F32 0.002 (56, 128) input_layernorm.weight 62 BF16 0.001 (7168,) post_attention_layernorm.weight 62 BF16 0.001 (7168,) self_attn.q_b_proj.weight_scale_inv 62 F32 0.001 (192, 12) self_attn.kv_b_proj.weight_scale_inv 62 F32 ~0 (256, 4) mlp.shared_experts.*.weight_scale_inv 177 F32 ~0 (16,56)/(56,16) self_attn.q_a_layernorm.weight 62 BF16 ~0 (1536,) self_attn.q_a_proj.weight_scale_inv 62 F32 ~0 (12, 56) self_attn.kv_a_proj_with_mqa.wsi 62 F32 ~0 (5, 56) self_attn.kv_a_layernorm.weight 62 BF16 ~0 (512,) mlp.gate.e_score_correction_bias 59 F32 ~0 (256,) mlp.{gate,up,down}_proj.weight_scale_inv 9 F32 ~0 dense layers model.norm.weight 1 BF16 ~0 (7168,) L61 enorm / hnorm / shared_head.norm 3 BF16 ~0 (7168,) ------------------------------------------------------------------------------ COUNT ARITHMETIC 15,104 = 59 MoE-bearing layers x 256 experts 59 = layers 3..60 (58 transformer MoE layers) + MTP layer 61 62 = layers 0..61 inclusive (attention and layernorms exist in all) 3 = the dense prefix, layers 0,1,2 91,991 = 62*(8 attn + 2 norm) + 3*6 + 59*(4 + 6) + 15,104*6 + 3 globals + 5 MTP ================================================================================ PART 6 FP8 QUANTIZATION SCHEME [SPEC] ================================================================================ config.json quantization_config: { "quant_method": "fp8", "fmt": "e4m3", "weight_block_size": [128, 128], "activation_scheme": "dynamic" } FORMAT - FP8 E4M3 (torch float8_e4m3fn semantics) 1 sign bit | 4 exponent bits | 3 mantissa bits | 1 byte per element Exponent bias 7. No infinities. NaN encoded as 0x7F / 0xFF. Maximum finite magnitude 448.0. Subnormals present (exponent field 0). The i7-8700K has no hardware fp8 convert instruction; decode is a 256-entry lookup table indexed by the raw byte, built once at load. BLOCK DEQUANTIZATION For a weight tensor W of shape (R, C) with companion scale S of shape (ceil(R/128), ceil(C/128)): W_real[r][c] = fp8_to_f32( W[r][c] ) * S[ r/128 ][ c/128 ] The scale is named "weight_scale_inv" but is applied by multiplication in the standard fp8 kernels. Confirm the direction against a reference on a real cell rather than inferring it from the name. ACTIVATION QUANTIZATION IS DYNAMIC: activations are quantized at runtime from their own observed range, not from any stored scale. There are no activation scale tensors in the checkpoint, and there is nothing to load for them. Every block grid observed, confirming 128x128 tiling: (2048, 7168) -> (16, 56) 2048/128=16 7168/128=56 (7168, 2048) -> (56, 16) (7168,16384) -> (56, 128) (24576,1536) -> (192, 12) (32768, 512) -> (256, 4) (1536, 7168) -> (12, 56) (18432,7168) -> (144, 56) (7168,18432) -> (56, 144) ( 576, 7168) -> (5, 56) 576/128 = 4.5 -> PADDED, see PART 14 WHAT IS NOT QUANTIZED All BF16, requiring a separate load path: model.embed_tokens.weight lm_head.weight mlp.gate.weight (the 256x7168 router, one per MoE layer) every *_layernorm.weight and model.norm.weight the MTP layer's eh_proj / enorm / hnorm / shared_head.* All F32: every weight_scale_inv mlp.gate.e_score_correction_bias So routing runs entirely in high precision: BF16 weight, F32 bias, and the reference explicitly casts both matmul operands to float32 (source line 426-428). IMPORTANT: NO FP8 CODE SHIPS WITH THIS CHECKPOINT modeling_deepseek.py contains no fp8 handling at all. Its layers are plain nn.Linear on bfloat16. The only quantization-related lines in the entire 1,848-line file are a generic guard at 966-968: # Handle the case where the model is quantized if hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype The shipped forward therefore assumes weights have ALREADY been dequantized to bfloat16 by the loading framework. DeepSeek's fp8 kernels live in a separate inference repository which was not downloaded here. The model card says plainly: "Hugging Face's Transformers has not been directly supported yet." ================================================================================ PART 7 MoE ROUTING ALGORITHM [SPEC] ================================================================================ Transcribed step by step from MoEGate.forward (source lines 422-473). This "noaux_tc" group-limited scheme is considerably more involved than plain top-k. Input: hidden states h, shape (T, 7168) after flattening batch and sequence. 1. logits = F.linear( h.float32 , gate.weight.float32 , None ) -> (T, 256) Both operands explicitly cast to float32 although gate.weight is BF16. 2. scores = sigmoid(logits) -> (T, 256) Sigmoid, not softmax. Scores do not sum to 1 and are not a distribution. 3. scores_for_choice = scores + e_score_correction_bias -> (T, 256) The F32 (256,) bias, broadcast over the token dimension. 4. group_scores = scores_for_choice.view(T, 8, 32).topk(2, -1)[0].sum(-1) -> (T, 8) Each of the 8 groups is scored by THE SUM OF ITS TOP TWO members. 5. group_idx = topk(group_scores, k=4) -> (T, 4) Only 4 of 8 groups survive; the other 4 (128 experts) are masked to -inf. 6. topk_idx = topk( masked scores_for_choice , k=8 ) -> (T, 8) The 8 experts are chosen among the 128 that remain. 7. topk_weight = scores.gather(1, topk_idx) *** Weights are gathered from `scores` - the PRE-bias sigmoid - while the SELECTION in steps 3-6 used scores_for_choice, the POST-bias value. Selection and weighting use different quantities, deliberately. 8. topk_weight = topk_weight / (topk_weight.sum(-1, keepdim=True) + 1e-20) topk_weight = topk_weight * 2.5 # routed_scaling_factor Renormalize to sum 1, THEN scale by 2.5. Then in DeepseekV3MoE.forward (lines 522-532): identity = h # the PRE-MoE residual y = moe_infer(h, topk_idx, topk_weight) # sum_i w_i * Expert_i(h) y = y + shared_experts(identity) # shared expert added afterwards The shared expert consumes the pre-MoE hidden state, not the routed output. moe_infer (lines 535-608) is a gather/scatter batching routine: sort tokens by assigned expert via argsort, run each expert once over its contiguous slice, scatter results back to original order, then form the weighted sum. It is a performance arrangement; the semantics are sum_i w_i * Expert_{idx_i}(h). TWO NESTED DECISION BOUNDARIES, not one: - the group cut: rank 4 vs rank 5 among 8 groups, each scored by a 2-elem sum - the expert cut: rank 8 vs rank 9 among the 128 surviving experts A flip at the group boundary can swap up to 8 experts at once. ================================================================================ PART 8 MLA ATTENTION - MULTI-HEAD LATENT ATTENTION [SPEC] ================================================================================ From DeepseekV3Attention (source lines 627-858). QUERY PATH h (7168) -> q_a_proj -> 1536 fp8 (1536, 7168) -> q_a_layernorm (RMSNorm 1536) -> q_b_proj -> 24576 fp8 (24576, 1536) -> reshape to 128 heads x 192 -> split each head: q_nope (128) | q_rope (64) KEY / VALUE PATH h (7168) -> kv_a_proj_with_mqa -> 576 fp8 (576, 7168) -> split: compressed_kv (512) | k_rope (64) -> kv_a_layernorm (RMSNorm 512) on the 512 part ONLY -> kv_b_proj -> 32768 fp8 (32768, 512) -> reshape to 128 heads x 256 -> split each head: k_nope (128) | v (128) ROTARY RoPE applied to q_rope (64) and k_rope (64) only. k_rope is SHARED across all 128 heads - this is the "mqa" in the name. q_rope is per-head. ATTENTION q = concat(q_nope, q_rope) -> 192 per head k = concat(k_nope, k_rope) -> 192 per head (k_rope broadcast to all heads) scores = q @ k^T * 0.135237 probs = softmax(scores, dim=-1) computed in float32, cast back to q.dtype out = probs @ v -> 128 per head out = o_proj(out.reshape(T, 16384)) -> 7168 fp8 (7168, 16384) WHAT IS CACHED - THE POINT OF MLA A conventional 128-head KV cache would store K and V per head: 128 heads x (128 + 128) x 2 bytes = 65,536 B per token per layer. MLA caches the LATENT instead: compressed_kv (512) + k_rope (64) = 576 elements x 2 B = 1,152 B. A 56.9x reduction. k_nope and v are RECONSTRUCTED from the 512-dim latent through kv_b_proj on every decode step, so the memory saving is paid for in compute: the KV read path and the kv_b_proj matmul are coupled. ATTENTION IMPLEMENTATIONS IN THE FILE DeepseekV3Attention eager reference implementation DeepseekV3FlashAttention2 FlashAttention-2 path (lines 860-1140); pads the 192-dim query head to v_head_dim and slices the result back; requires the flash_attn package ATTENTION_CLASSES = {"eager": ..., "flash_attention_2": ...} Selected by config._attn_implementation. ================================================================================ PART 9 YaRN POSITION ENCODING [SPEC] ================================================================================ From DeepseekV3YarnRotaryEmbedding and helpers (source lines 226-330). PARAMETERS IN THIS CHECKPOINT dim (qk_rope_head_dim) 64 base (rope_theta) 10000 original_max_position_embeddings 4096 scaling factor 40 max_position_embeddings 163840 = 4096 x 40 beta_fast / beta_slow 32 / 1 mscale / mscale_all_dim 1.0 / 1.0 THE CORRECTION RANGE yarn_find_correction_dim(rot, dim, base, orig_max) = dim * ln( orig_max / (rot * 2 * pi) ) / ( 2 * ln(base) ) yarn_find_correction_range(beta_fast=32, beta_slow=1, ...) -> (low, high), clamped to [0, dim-1] A linear ramp over [low, high] blends two frequency schedules: inv_freq_interpolation = 1 / (factor * base^(2i/dim)) low freq, scaled inv_freq_extrapolation = 1 / (base^(2i/dim)) high freq, raw inv_freq = interp * (1 - ramp) + extrap * ramp High-frequency dimensions extrapolate unchanged; low-frequency dimensions are interpolated by the factor of 40. THE MAGNITUDE CORRECTION yarn_get_mscale(scale, mscale) = 0.1 * mscale * ln(scale) + 1.0 for scale>1 With scale=40, mscale=1.0: 0.1 * ln(40) + 1.0 = 1.3688879 cos/sin caches are multiplied by _mscale, computed as yarn_get_mscale(factor, mscale) / yarn_get_mscale(factor, mscale_all_dim) which equals 1.0 here since mscale == mscale_all_dim == 1.0. SEPARATELY, in DeepseekV3Attention.__init__ (lines 690-695), because mscale_all_dim is truthy: softmax_scale = 192^-0.5 * mscale * mscale = 0.0721688 * 1.3688879^2 = 0.135237 This is NOT 1/sqrt(192) = 0.0721688. The 1.874x factor is load-bearing. APPLICATION rotate_half(x) splits the last dim in half and returns concat(-x2, x1). apply_rotary_pos_emb indexes cos/sin by position_ids and computes q_out = q*cos + rotate_half(q)*sin after an interleave-to-blocked reshape: (b, h, d) -> (b, h, d/2, 2) -> transpose(4,3) -> reshape back. Get that reshape wrong and the model produces fluent nonsense rather than an obvious error. ================================================================================ PART 10 COMPLETE DATAFLOW CHART ================================================================================ -------------------------------------------------------------------------------- 10.1 PREFILL VS DECODE -------------------------------------------------------------------------------- PREFILL (first pass over the prompt, T tokens at once) - all T tokens flow through all 61 layers in one batch - the causal mask is a full lower-triangular (T x T) - every token contributes 576 elements per layer to the KV cache - MoE routing is computed per token, so a prefill of T tokens may touch far more than 8 experts per layer - up to all 256 if T is large - cost scales with T for compute, and with distinct-experts-touched for I/O DECODE (each subsequent token, T = 1) - one token flows through all 61 layers - attention reads the whole KV cache (length P) and appends 576 elements - exactly 8 routed experts fire per MoE layer -> 464 expert reads per token - cost is dominated by streaming 19.04 GiB of expert weights The two regimes have different bottlenecks. Prefill is compute- and mask-bound; decode is expert-I/O-bound. Measure them separately. -------------------------------------------------------------------------------- 10.2 FULL TENSOR-SHAPE DATAFLOW (decode step, batch 1, T=1, cache length P) -------------------------------------------------------------------------------- input_ids (1,) int64 | v +======================================================================+ | model.embed_tokens : Embedding(129280, 7168) BF16 | +======================================================================+ | h : (1, 7168) bf16 | |#################### LAYERS 0,1,2 - DENSE ######################### v +----------------------------------------------------------------------+ | residual = h | | h = input_layernorm(h) RMSNorm(7168) -> (1, 7168) | | h = self_attn(h, cache[l]) -> (1, 7168) | | h = residual + h | | residual = h | | h = post_attention_layernorm(h) -> (1, 7168) | | | | DENSE MLP (DeepseekV3MLP, intermediate 18432) | | g = gate_proj(h) (18432,7168)fp8 -> (1, 18432) | | u = up_proj(h) (18432,7168)fp8 -> (1, 18432) | | h = down_proj( silu(g) * u ) | | (7168,18432)fp8 -> (1, 7168) | | h = residual + h | +----------------------------------------------------------------------+ | |#################### LAYERS 3..60 - MoE ########################### v +----------------------------------------------------------------------+ | residual = h | | h = input_layernorm(h) -> (1, 7168) | | | | +================ MLA ATTENTION =================================+ | | | | | | | QUERY | | | | q = q_a_proj(h) (1536,7168)fp8 -> (1, 1536) | | | | q = q_a_layernorm(q) RMSNorm(1536) -> (1, 1536) | | | | q = q_b_proj(q) (24576,1536)fp8 -> (1, 24576) | | | | q = view(1, 128, 192) | | | | q_nope, q_rope = split(q, [128, 64], -1) | | | | q_nope (1,128,128) q_rope (1,128,64) | | | | | | | | KEY / VALUE | | | | c = kv_a_proj_with_mqa(h) (576,7168)fp8 -> (1, 576) | | | | c_kv, k_rope = split(c, [512, 64], -1) | | | | c_kv (1,512) k_rope (1,1,64) | | | | c_kv = kv_a_layernorm(c_kv) RMSNorm(512) -> (1, 512) | | | | | | | | ROPE cos,sin = yarn_rotary(position_id) | | | | q_rope, k_rope = apply_rotary_pos_emb(q_rope, k_rope, | | | | cos, sin, pos_ids) | | | | | | | | CACHE APPEND <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< | | | | cache[l].k_latent <- append c_kv (P,512) -> (P+1,512) | | | | cache[l].k_rope <- append k_rope (P,64) -> (P+1,64) | | | | 1,152 bytes added per layer per token | | | | | | | | RECONSTRUCT from the full cache | | | | kv = kv_b_proj(cache.k_latent) (32768,512)fp8 | | | | -> (P+1, 32768) | | | | kv = view(P+1, 128, 256) | | | | k_nope, v = split(kv, [128, 128], -1) | | | | k_nope (P+1,128,128) v (P+1,128,128) | | | | k = concat(k_nope, k_rope.expand(128)) -> (P+1,128,192) | | | | | | | | ATTEND | | | | s = q @ k^T * 0.135237 -> (1, 128, 1, P+1) | | | | s = s + causal_mask | | | | a = softmax(s, -1, float32).to(q.dtype) | | | | o = a @ v -> (1, 128, 1, 128) | | | | o = o.transpose.reshape(1, 16384) | | | | o = o_proj(o) (7168,16384)fp8 -> (1, 7168) | | | +================================================================+ | | | | h = residual + o | | residual = h | | h = post_attention_layernorm(h) -> (1, 7168) | | | | +================ MoE BLOCK =====================================+ | | | identity = h | | | | | | | | ROUTER (float32) | | | | logits = h.f32 @ gate.weight.f32^T (256,7168)BF16 | | | | -> (1, 256) | | | | scores = sigmoid(logits) -> (1, 256) | | | | choice = scores + e_score_bias (256,)F32 | | | | grp = choice.view(1,8,32).topk(2)[0].sum(-1) -> (1, 8) | | | | keep = topk(grp, 4) -> (1, 4) groups | | | | mask non-kept groups to -inf | | | | idx = topk(masked_choice, 8) -> (1, 8) expert ids | | | | w = scores.gather(1, idx) <- PRE-bias scores | | | | w = w / w.sum(); w = w * 2.5 -> (1, 8) | | | | | | | | | +----------+----------------------+ | | | | v v | | | | 8 ROUTED EXPERTS 1 SHARED EXPERT | | | | for i in idx: g = gate_proj(identity) | | | | READ 44,050,944 B from disk (2048,7168)fp8 | | | | g = gate_proj(h) -> (1,2048) u = up_proj(identity) | | | | u = up_proj(h) -> (1,2048) s = down_proj(silu(g)*u) | | | | e_i = down_proj(silu(g)*u) (7168,2048)fp8 | | | | -> (1,7168) -> (1, 7168) | | | | y = sum_i w_i * e_i -> (1,7168) | | | | | | | | | | +------------ y + s --------------+ | | | +================================================================+ | | | | h = residual + (y + s) -> (1, 7168) | +----------------------------------------------------------------------+ | | repeat for all 58 MoE layers | ==> 464 expert reads, 19.04 GiB streamed, per token v +======================================================================+ | model.norm : RMSNorm(7168) BF16 -> (1, 7168) | | lm_head : Linear(7168 -> 129280) BF16 -> (1, 129280) | +======================================================================+ | logits (1, 129280) float32 v +----------------------------------------------------------------------+ | SAMPLING temperature 0.6 -> top_p 0.95 -> multinomial | +----------------------------------------------------------------------+ | next_token_id | +---- if == eos (1) : STOP +---- else : back to model.embed_tokens -------------------------------------------------------------------------------- 10.3 KV CACHE LIFECYCLE -------------------------------------------------------------------------------- Per layer l in 0..60, the cache holds two arrays: k_latent[l] : (P, 512) bf16 the normalized compressed KV k_rope[l] : (P, 64) bf16 the rotated positional key, head-shared PREFILL, T tokens P: 0 -> T writes T * 70,272 B total DECODE step P: n -> n+1 writes 70,272 B total reads (n+1) * 70,272 B total Growth per token, all 61 layers: 61 * 576 * 2 = 70,272 B context P cache size (bf16) cache size (int8) --------------------------------------------------------- 4,096 0.27 GiB 0.13 GiB 16,384 1.07 GiB 0.54 GiB 32,768 2.14 GiB 1.07 GiB 65,536 4.29 GiB 2.14 GiB 163,840 10.72 GiB 5.36 GiB NOTE the coupling: k_nope and v are NOT cached. They are recomputed from k_latent through kv_b_proj (32768x512 fp8) on every single decode step, over the entire cache length. That matmul is 16.7 MB of weights x (P+1) rows, so attention cost grows linearly in P even though the cache itself is small. This is the term that makes long context expensive here, not cache memory. In the reference, caching is delegated to the transformers Cache class (DynamicCache / StaticCache); the model declares _supports_cache_class = True and _skip_keys_device_placement = "past_key_values". -------------------------------------------------------------------------------- 10.4 MoE DISPATCH DATAFLOW (moe_infer, prefill with T tokens) -------------------------------------------------------------------------------- topk_ids (T, 8) topk_weight (T, 8) x (T, 7168) | v cnts = zeros(T, 256); cnts.scatter_(1, topk_ids, 1) tokens_per_expert = cnts.sum(0) -> (256,) | v idxs = topk_ids.view(-1).argsort() -> (T*8,) sorted_tokens = x[idxs // 8] -> (T*8, 7168) | | now all tokens destined for expert 0 are contiguous, then expert 1, ... v start = 0 for i, n in enumerate(tokens_per_expert): if n == 0: continue <-- experts with no tokens are SKIPPED out_i = experts[i]( sorted_tokens[start : start+n] ) start += n | v outs = cat(out_i) -> (T*8, 7168) new_x = empty_like(outs); new_x[idxs] = outs <-- scatter back | v final = new_x.view(T, 8, 7168) .mul_(topk_weight.unsqueeze(-1)) .sum(dim=1) -> (T, 7168) The `if n == 0: continue` is why decode touches exactly 8 experts per layer while prefill may touch far more: with T tokens there are up to min(256, 8T) distinct experts with work to do. (The ep_size > 1 branch adds dist.all_to_all exchanges for expert parallelism. ep_size is 1 in this config, so that path is inert here.) -------------------------------------------------------------------------------- 10.5 MTP / SPECULATIVE DECODE DATAFLOW (layer 61) -------------------------------------------------------------------------------- h_prev (1, 7168) next_token_id from the main stack | | v | embed_tokens (layer 61's OWN copy) | | e (1, 7168) v v hnorm(h_prev) enorm(e) | | +------------ concat -------+ -> (1, 14336) | v eh_proj (7168, 14336) BF16 -> (1, 7168) | v +--------------------------------------------+ | input_layernorm -> MLA attention -> +res | | post_attn_layernorm -> MoE (256 exp) -> +res| +--------------------------------------------+ | v shared_head.norm (RMSNorm 7168) | v shared_head.head (129280, 7168) BF16 | v logits for token t+2 (1, 129280) Purpose: predict one extra token ahead so a verifier pass can accept or reject it, raising tokens-per-forward. It is NOT required for correct generation and is not part of the base autoregressive loop. Excluding it saves 14.36 GiB. In a coverage audit it must be CLASSIFIED as speculative-decoding machinery, not left as orphan tensors. ================================================================================ PART 11 TOKENIZER AND WIRE FORMAT [MEASURED] ================================================================================ -------------------------------------------------------------------------------- 11.1 TOKENIZER PIPELINE -------------------------------------------------------------------------------- File tokenizer.json, 7,847,602 bytes Class LlamaTokenizerFast (tokenizer_config.json) Algorithm BPE BPE vocab 128,000 entries, ids 0..127,999 Merge rules 127,741 added_tokens 818 (see 11.2) config vocab 129,280 -> ids 0..128,814 are used; 128,815..129,279 (465 slots) are unused padding in the embedding matrix, present so the vocab dimension is a convenient multiple. A loader must still allocate all 129,280 rows. normalizer Sequence[] - EMPTY. No NFC/NFKC, no lowercasing, no stripping. Input bytes reach the pre-tokenizer unmodified. pre_tokenizer Sequence of Split rules then ByteLevel: 1. Split on regex \p{N}{1,3} Isolated -> digits are grouped 1-3 at a time 2. Split on regex [一-龥぀-ゟ゠-ヿ]+ Isolated -> CJK ideographs, Hiragana, Katakana isolated as runs 3. Split on a large punctuation/letter/whitespace regex 4. ByteLevel decoder ByteLevel, add_prefix_space=true, trim_offsets=true, use_regex=true post_processor ByteLevel, add_prefix_space=true, trim_offsets=false truncation null padding null (both unset in the file) model_max_length 16384 (tokenizer_config.json) -------------------------------------------------------------------------------- 11.2 COMPLETE SPECIAL-TOKEN TABLE -------------------------------------------------------------------------------- 818 added tokens. 798 are reserved placeholders; 20 are meaningful. id token role --------------------------------------------------------------------------- 0 <|begin_of_sentence|> BOS. add_bos_token = true 1 <|end_of_sentence|> EOS, and the pad token 2 <|_pad_|> a distinct pad token, unused by config --------------------------------------------------------------------------- 128000 \ .. <|place_holder_no_0..797|> > 798 reserved placeholders 128797 / --------------------------------------------------------------------------- 128798 <think> opens the reasoning trace 128799 </think> closes the reasoning trace --------------------------------------------------------------------------- 128800 <|fim_hole|> fill-in-the-middle: the gap 128801 <|fim_begin|> fill-in-the-middle: prefix start 128802 <|fim_end|> fill-in-the-middle: suffix end --------------------------------------------------------------------------- 128803 <|User|> user turn marker 128804 <|Assistant|> assistant turn marker 128805 <|EOT|> end of turn --------------------------------------------------------------------------- 128806 <|tool_calls_begin|> opens a block of tool calls 128807 <|tool_calls_end|> closes the block 128808 <|tool_call_begin|> opens ONE call 128809 <|tool_call_end|> closes ONE call 128810 <|tool_outputs_begin|> opens a block of tool results 128811 <|tool_outputs_end|> closes the block 128812 <|tool_output_begin|> opens ONE result 128813 <|tool_output_end|> closes ONE result 128814 <|tool_sep|> separates call type from function name --------------------------------------------------------------------------- NOTE: the real tokens use fullwidth vertical bars U+FF5C and the U+2581 lower one-eighth block as a word separator, e.g. the literal bytes are "<|begin▁of▁sentence|>". They are rendered here with plain ASCII pipes and underscores for legibility. <|EOT|> is the one exception - it genuinely uses ASCII pipes. Copy them from tokenizer.json, not from this table. -------------------------------------------------------------------------------- 11.3 CHAT TEMPLATE SEMANTICS -------------------------------------------------------------------------------- The Jinja template in tokenizer_config.json (verbatim in section 15.5) does this: 1. Concatenate every system message, in order, joined by "\n\n", into one system_prompt string. Emit bos_token, then that string. There is no system turn marker; the system prompt is bare text immediately after BOS. 2. For each user message: emit <|User|> + content. 3. For each assistant message WITHOUT tool_calls: - if the content contains "</think>", keep ONLY what follows it - emit <|Assistant|> + content + <|end_of_sentence|> *** Reasoning traces from prior turns are STRIPPED before being fed back. The model does not see its own past <think> blocks. 4. For each assistant message WITH tool_calls: emit <|Assistant|> then, for each call, <|tool_call_begin|> + type + <|tool_sep|> + function.name + "\n" + "```json\n" + arguments + "\n```" + <|tool_call_end|>, all wrapped in <|tool_calls_begin|> ... <|tool_calls_end|> + <|end_of_sentence|>. 5. For each tool message: wrap content in <|tool_output_begin|> ... <|tool_output_end|>, with the first one opening <|tool_outputs_begin|>. 6. If add_generation_prompt and the last message was not a tool output: emit <|Assistant|><think>\n Step 6 is the mechanism behind the model card's instruction to force reasoning: the template itself seeds the opening <think> tag. -------------------------------------------------------------------------------- 11.4 A RENDERED EXAMPLE -------------------------------------------------------------------------------- messages = [ {"role":"user", "content":"What is 2+2?"} ] add_generation_prompt = True renders to the literal string: <|begin_of_sentence|><|User|>What is 2+2?<|Assistant|><think>\n as token ids: [0, 128803, ...content ids..., 128804, 128798, <newline id>] The model then generates its reasoning, emits </think> (128799), generates the answer, and emits <|end_of_sentence|> (1) to stop. ================================================================================ PART 12 API SURFACE AND ENDPOINTS ================================================================================ -------------------------------------------------------------------------------- 12.1 HUGGINGFACE auto_map AND LOAD PATH [SPEC] -------------------------------------------------------------------------------- config.json declares: "auto_map": { "AutoConfig": "configuration_deepseek.DeepseekV3Config", "AutoModel": "modeling_deepseek.DeepseekV3Model", "AutoModelForCausalLM":"modeling_deepseek.DeepseekV3ForCausalLM" } So the model uses REMOTE CODE: the two .py files in the repo are the implementation, and loading requires trust_remote_code=True. from transformers import AutoModelForCausalLM, AutoTokenizer tok = AutoTokenizer.from_pretrained("/home/joseph/DeepSeek-R1") model = AutoModelForCausalLM.from_pretrained( "/home/joseph/DeepSeek-R1", trust_remote_code=True, torch_dtype="auto", device_map="auto") CAVEAT [CARD]: "Hugging Face's Transformers has not been directly supported yet." The shipped modeling code has no fp8 dequantization, so this path needs a framework that understands the fp8 quantization_config. It will not work as-is on this machine (no torch installed, Python 3.14). -------------------------------------------------------------------------------- 12.2 PYTHON CLASS API - COMPLETE [SPEC] -------------------------------------------------------------------------------- Every public symbol in the two source files, with line numbers into section 15. configuration_deepseek.py --------------------------------------------------------------------------- DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {} L5 class DeepseekV3Config(PretrainedConfig) L7 model_type = "deepseek_v3" keys_to_ignore_at_inference = ["past_key_values"] __init__(vocab_size=129280, hidden_size=7168, intermediate_size=18432, moe_intermediate_size=2048, num_hidden_layers=61, ...) L112 modeling_deepseek.py --------------------------------------------------------------------------- _CONFIG_FOR_DOC = "DeepseekV3Config" _get_unpad_data(attention_mask) L80 class DeepseekV3RMSNorm(nn.Module) L94 __init__(hidden_size, eps=1e-06) L95 forward(hidden_states) L103 class DeepseekV3RotaryEmbedding(nn.Module) L114 __init__(dim, max_position_embeddings=2048, base=10000, device=None) L115 _set_cos_sin_cache(seq_len, device, dtype) L134 forward(x, seq_len=None) L146 class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding) L158 __init__(..., scaling_factor=1.0) L161 _set_cos_sin_cache(seq_len, device, dtype) L172 class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding) L187 __init__(..., scaling_factor=1.0) L190 _set_cos_sin_cache(seq_len, device, dtype) L201 yarn_find_correction_dim(num_rotations, dim, base, max_position_embeddings) L226 yarn_find_correction_range(low_rot, high_rot, dim, base, max_pos) L235 yarn_get_mscale(scale=1, mscale=1) L247 yarn_linear_ramp_mask(min, max, dim) L253 class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding) L262 __init__(dim, max_position_embeddings, base, device, scaling_factor, original_max_position_embeddings, beta_fast, beta_slow, mscale, mscale_all_dim) L264 _set_cos_sin_cache(seq_len, device, dtype) L285 rotate_half(x) L331 apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1) L339 class DeepseekV3MLP(nn.Module) L374 __init__(config, hidden_size=None, intermediate_size=None) L375 forward(x) L388 class MoEGate(nn.Module) L393 __init__(config) L394 reset_parameters() L417 forward(hidden_states) -> (topk_idx, topk_weight) L422 class DeepseekV3MoE(nn.Module) L475 __init__(config) L480 forward(hidden_states) L522 @torch.no_grad moe_infer(x, topk_ids, topk_weight) L535 repeat_kv(hidden_states, n_rep) L612 class DeepseekV3Attention(nn.Module) L627 __init__(config, layer_idx=None) L630 _init_rope() L697 _shape(tensor, seq_len, bsz) L743 forward(hidden_states, attention_mask, position_ids, past_key_value, output_attentions, use_cache, **kwargs) L750 class DeepseekV3FlashAttention2(DeepseekV3Attention) L860 __init__(*args, **kwargs) L867 forward(...) L875 _flash_attention_forward(query_states, key_states, value_states, attention_mask, query_length, dropout, softmax_scale) L1010 _upad_input(query_layer, key_layer, value_layer, attention_mask, query_length) L1090 ATTENTION_CLASSES = {"eager": DeepseekV3Attention, "flash_attention_2": DeepseekV3FlashAttention2} class DeepseekV3DecoderLayer(nn.Module) L1142 __init__(config, layer_idx) L1143 forward(...) L1167 class DeepseekV3PreTrainedModel(PreTrainedModel) L1251 _no_split_modules = ["DeepseekV3DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_cache_class = True _init_weights(module) L1260 class DeepseekV3Model(DeepseekV3PreTrainedModel) L1346 __init__(config) L1354 get_input_embeddings() / set_input_embeddings(value) L1375 L1378 forward(...) -> BaseModelOutputWithPast L1382 class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel) L1514 __init__(config) L1517 get_input_embeddings() / set_input_embeddings(value) L1526 L1529 get_output_embeddings() / set_output_embeddings(new) L1532 L1535 set_decoder(decoder) / get_decoder() L1538 L1541 forward(...) -> CausalLMOutputWithPast L1548 prepare_inputs_for_generation(input_ids, past_key_values, attention_mask, inputs_embeds, **kwargs) L1642 @staticmethod _reorder_cache(past_key_values, beam_idx) L1707

Mathematical records from this source

01

Residual addition around a transformed hidden state

Add the block input saved in residual to the output of the intervening transformation. Both operands must have the same residual-stream shape. The same expression appears around…

02

KimiK25ForConditionalGeneration.prepare_inputs_for_generation: position ids

In KimiK25ForConditionalGeneration.prepare_inputs_for_generation, this statement defines or updates position_ids. The addition or subtraction updates the named state or combines…

03

KimiK25ForConditionalGeneration.prepare_inputs_for_generation: input ids

In KimiK25ForConditionalGeneration.prepare_inputs_for_generation, this statement defines or updates input_ids. The addition or subtraction updates the named state or combines…

04

_get_unpad_data: seqlens in batch

In _get_unpad_data, this statement defines or updates seqlens_in_batch. The reduction aggregates values along the explicit source axis; preserving the axis and keep-dimension…

05

_get_unpad_data: max seqlen in batch

In _get_unpad_data, this statement defines or updates max_seqlen_in_batch. This statement evaluates the named projection, normalization or numeric transform with the source…

06

_get_unpad_data: cu seqlens

In _get_unpad_data, this statement defines or updates cu_seqlens. This statement evaluates the named projection, normalization or numeric transform with the source arguments. Its…

07

Solve for the rotary frequency index at a chosen rotation count

At index i, the unscaled angular frequency is base^(−2 i/dim). Over orig_max positions it completes orig_max*base^(−2 i/dim)/(2π) rotations. Setting that count equal to rot and…

08

yarn_find_correction_range: low

In yarn_find_correction_range, this statement defines or updates low. This statement evaluates the named projection, normalization or numeric transform with the source arguments.…

09

yarn_find_correction_range: high

In yarn_find_correction_range, this statement defines or updates high. This statement evaluates the named projection, normalization or numeric transform with the source arguments.…

10

yarn_find_correction_range: return

In yarn_find_correction_range, this statement returns the displayed result. The addition or subtraction updates the named state or combines residual contributions. The input…

11

Logarithmic magnitude adjustment for extended context

For scale>1, the adjustment adds 0.1*mscale*ln(scale) to one. The code returns one for scale≤1. One parameter specifies the context extension, while the other controls adjustment…

12

yarn_linear_ramp_mask: linear func

In yarn_linear_ramp_mask, this statement defines or updates linear_func. The expression forms a quotient or integer division. The denominator, integer rounding and tensor shape…

13

yarn_linear_ramp_mask: ramp func

In yarn_linear_ramp_mask, this statement defines or updates ramp_func. This statement evaluates the named projection, normalization or numeric transform with the source arguments.…

14

rotate_half: x1

In rotate_half, this statement defines or updates x1. The expression forms a quotient or integer division. The denominator, integer rounding and tensor shape convention determine…

15

rotate_half: x2

In rotate_half, this statement defines or updates x2. The expression forms a quotient or integer division. The denominator, integer rounding and tensor shape convention determine…

16

apply_rotary_pos_emb: q

In apply_rotary_pos_emb, this statement defines or updates q. The expression forms a quotient or integer division. The denominator, integer rounding and tensor shape convention…

17

apply_rotary_pos_emb: k

In apply_rotary_pos_emb, this statement defines or updates k. The expression forms a quotient or integer division. The denominator, integer rounding and tensor shape convention…

18

Rotate paired query coordinates using a position-dependent angle

rotate_half maps a pair of coordinate blocks(x 1,x 2) to(−x 2,x 1). Multiplication by cosine and addition of the sine-weighted rotated vector implements a two-dimensional rotation…

19

Rotate paired key coordinates using a position-dependent angle

rotate_half maps a pair of coordinate blocks(x 1,x 2) to(−x 2,x 1). Multiplication by cosine and addition of the sine-weighted rotated vector implements a two-dimensional rotation…

20

repeat_kv: return

In repeat_kv, this statement returns the displayed result. The displayed multiplication combines the source factors. For tensors this is elementwise unless the called operation…

21

RMSNorm mean square, despite the local variable name

This expression averages squared components along the final feature axis and preserves that axis for broadcasting. It computes the second raw moment, not centered variance: the…

22

Normalize by the root mean square

Multiply each feature by 1/√(mean(x²)+epsilon). Positive epsilon prevents division by zero and changes exact unit-RMS normalization near the zero vector. Unlike LayerNorm, this…

23

Apply learned per-feature RMSNorm gains

After RMS scaling, multiply each component by its learned gain and restore the earlier input dtype. The gain allows the model to choose different output scales by feature; it does…

24

DeepSeek RotaryEmbedding.__init__: inv freq

In DeepseekV3RotaryEmbedding.__init__, this statement defines or updates inv_freq. This is part of the positional-phase calculation. Frequency, position, sine/cosine and…

25

DeepSeek RotaryEmbedding._set_cos_sin_cache: t

In DeepseekV3RotaryEmbedding._set_cos_sin_cache, this statement defines or updates t. This is part of the positional-phase calculation. Frequency, position, sine/cosine and…

26

DeepSeek RotaryEmbedding._set_cos_sin_cache: freqs

In DeepseekV3RotaryEmbedding._set_cos_sin_cache, this statement defines or updates freqs. This is part of the positional-phase calculation. Frequency, position, sine/cosine and…

27

DeepSeek LinearScalingRotaryEmbedding._set_cos_sin_cache: t

In DeepseekV3LinearScalingRotaryEmbedding._set_cos_sin_cache, this statement defines or updates t. The expression forms a quotient or integer division. The denominator, integer…

28

DeepSeek LinearScalingRotaryEmbedding._set_cos_sin_cache: freqs

In DeepseekV3LinearScalingRotaryEmbedding._set_cos_sin_cache, this statement defines or updates freqs. This is part of the positional-phase calculation. Frequency, position,…

29

yarn_get_mscale: return

In yarn_get_mscale, this statement returns the displayed result. This statement fixes a numeric parameter or initializes a numerical state in this source version; it is not a…

30

yarn_linear_ramp_mask: max

In yarn_linear_ramp_mask, this statement defines or updates max. This statement fixes a numeric parameter or initializes a numerical state in this source version; it is not a…

31

DeepSeek YarnRotaryEmbedding._set_cos_sin_cache: freq extra

In DeepseekV3YarnRotaryEmbedding._set_cos_sin_cache, this statement defines or updates freq_extra. The expression forms a quotient or integer division. The denominator, integer…

32

DeepSeek YarnRotaryEmbedding._set_cos_sin_cache: freq inter

In DeepseekV3YarnRotaryEmbedding._set_cos_sin_cache, this statement defines or updates freq_inter. The expression forms a quotient or integer division. The denominator, integer…

33

Complement the increasing YaRN frequency ramp

The helper produces a ramp increasing from zero to one across frequency-pair indices. Subtracting it from one makes inv_freq_mask select original frequencies at the small-index…

34

Blend original and divided YaRN frequency schedules

The source uses inv_freq_mask as the weight on the original schedule and its complement as the weight on the divided schedule. Since inv_freq_mask=1−ramp, this is…

35

DeepSeek YarnRotaryEmbedding._set_cos_sin_cache: t

In DeepseekV3YarnRotaryEmbedding._set_cos_sin_cache, this statement defines or updates t. This statement evaluates the named projection, normalization or numeric transform with…

36

DeepSeek YarnRotaryEmbedding._set_cos_sin_cache: freqs

In DeepseekV3YarnRotaryEmbedding._set_cos_sin_cache, this statement defines or updates freqs. This is part of the positional-phase calculation. Frequency, position, sine/cosine…

37

Ratio controlling the rotary cache magnitude

This coefficient divides the adjustment computed with mscale by the adjustment computed with mscale_all_dim. Equal strengths give a ratio of one. The attention initializer can…

38

SwiGLU-style gated feed-forward projection

Two learned maps project x into the intermediate width. The configured activation, SiLU in these dossiers, is applied to the gate projection; its result multiplies the…

39

MoEGate.forward: logits

In MoEGate.forward, this statement defines or updates logits. The matrix or indexed contraction combines the stated axes. Compatible tensor dimensions and the transposes in this…

40

MoEGate.forward: topk weight

In MoEGate.forward, this statement defines or updates topk_weight. The top-k operation selects the largest scores. Ties and group masking affect which experts or entries survive…

41

DeepSeek MoE.moe_infer: tokens per expert

In DeepseekV3MoE.moe_infer, this statement defines or updates tokens_per_expert. The reduction aggregates values along the explicit source axis; preserving the axis and…

42

DeepSeek MoE.moe_infer: sorted tokens

In DeepseekV3MoE.moe_infer, this statement defines or updates sorted_tokens. The top-k operation selects the largest scores. Ties and group masking affect which experts or entries…

43

DeepSeek MoE.moe_infer: start idx

In DeepseekV3MoE.moe_infer, this statement defines or updates start_idx. This statement fixes a numeric parameter or initializes a numerical state in this source version; it is…

44

Sum the selected expert outputs with their routing weights

Each chosen expert evaluates the same input representation h. Its output vector is multiplied by the associated routing weight, and the selected vectors are added. The…

45

DeepSeek Attention.__init__: q head dim

In DeepseekV3Attention.__init__, this statement defines or updates self.q_head_dim. The addition or subtraction updates the named state or combines residual contributions. The…

46

DeepSeek Attention.__init__: kv a proj with mqa

In DeepseekV3Attention.__init__, this statement defines or updates self.kv_a_proj_with_mqa. The addition or subtraction updates the named state or combines residual contributions.…

47

DeepSeek Attention.__init__: kv b proj

In DeepseekV3Attention.__init__, this statement defines or updates self.kv_b_proj. The displayed multiplication combines the source factors. For tensors this is elementwise unless…

48

DeepSeek Attention.__init__: o proj

In DeepseekV3Attention.__init__, this statement defines or updates self.o_proj. The displayed multiplication combines the source factors. For tensors this is elementwise unless…

49

Baseline inverse-square-root attention coefficient

Initialize the score multiplier to 1/√d, where d is the total rotary plus non-rotary query-head width. This is the starting coefficient; the following YaRN branch can multiply it…

50

Expand the compressed latent into per-head keys and values

Normalize the compressed key/value latent, apply the learned up-projection, and reshape into heads. Each head receives its non-rotary key and value components. This eagerly…

51

DeepSeek Attention.forward: attn weights

In DeepseekV3Attention.forward, this statement defines or updates attn_weights. Softmax exponentiates and normalizes scores along the chosen axis, producing nonnegative weights…

52

Normalize each query’s attention scores

Apply softmax across key positions for each query and head. The resulting nonnegative weights sum to one when a row has at least one finite eligible score. The source computes…

53

DeepSeek Attention.forward: attn output

In DeepseekV3Attention.forward, this statement defines or updates attn_output. The matrix or indexed contraction combines the stated axes. Compatible tensor dimensions and the…

54

DeepSeek Attention.forward: attn output

In DeepseekV3Attention.forward, this statement defines or updates attn_output. The displayed multiplication combines the source factors. For tensors this is elementwise unless the…

55

DeepSeek Attention.forward: attn output

In DeepseekV3Attention.forward, this statement defines or updates attn_output. This statement evaluates the named projection, normalization or numeric transform with the source…

56

DeepSeek FlashAttention2.forward: attn output

In DeepseekV3FlashAttention2.forward, this statement defines or updates attn_output. The displayed multiplication combines the source factors. For tensors this is elementwise…

57

DeepSeek FlashAttention2._upad_input: key layer

In DeepseekV3FlashAttention2._upad_input, this statement defines or updates key_layer. The displayed multiplication combines the source factors. For tensors this is elementwise…

58

DeepSeek FlashAttention2._upad_input: value layer

In DeepseekV3FlashAttention2._upad_input, this statement defines or updates value_layer. The displayed multiplication combines the source factors. For tensors this is elementwise…

59

DeepSeek DecoderLayer.__init__: mlp

In DeepseekV3DecoderLayer.__init__, this statement defines or updates self.mlp. This statement evaluates the named projection, normalization or numeric transform with the source…

60

DeepSeek Model.forward: past key values length

In DeepseekV3Model.forward, this statement defines or updates past_key_values_length. This statement fixes a numeric parameter or initializes a numerical state in this source…

61

DeepSeek Model.forward: hidden states

In DeepseekV3Model.forward, this statement defines or updates hidden_states. This statement evaluates the named projection, normalization or numeric transform with the source…

62

DeepSeek ForSequenceClassification.forward: pooled logits

In DeepseekV3ForSequenceClassification.forward, this statement defines or updates pooled_logits. This statement evaluates the named projection, normalization or numeric transform…

63

DeepSeek DynamicNTKScalingRotaryEmbedding._set_cos_sin_cache: base

In DeepseekV3DynamicNTKScalingRotaryEmbedding._set_cos_sin_cache, this statement defines or updates base. The expression forms a quotient or integer division. The denominator,…

64

DeepSeek DynamicNTKScalingRotaryEmbedding._set_cos_sin_cache: inv freq

In DeepseekV3DynamicNTKScalingRotaryEmbedding._set_cos_sin_cache, this statement defines or updates inv_freq. This is part of the positional-phase calculation. Frequency,…

65

Independent sigmoid scores for the router

The sigmoid 1/(1+exp(−z)) is applied to each expert logit independently. It compresses each finite real logit into (0,1), without normalizing across experts. These values are…

66

Bias the choice of experts while retaining original affinities

An expert-specific correction vector is added to the sigmoid affinities for ranking. This addition can change which groups and experts are selected. The later mixture weights are…

67

MoEGate.forward: group scores

In MoEGate.forward, this statement defines or updates group_scores. The top-k operation selects the largest scores. Ties and group masking affect which experts or entries survive…

68

MoEGate.forward: group idx

In MoEGate.forward, this statement defines or updates group_idx. The top-k operation selects the largest scores. Ties and group masking affect which experts or entries survive the…

69

MoEGate.forward: score mask

In MoEGate.forward, this statement defines or updates score_mask. The expression forms a quotient or integer division. The denominator, integer rounding and tensor shape…

70

MoEGate.forward: ( , topk idx)

In MoEGate.forward, this statement defines or updates (_, topk_idx). The top-k operation selects the largest scores. Ties and group masking affect which experts or entries survive…

71

MoEGate.forward: denominator

In MoEGate.forward, this statement defines or updates denominator. The top-k operation selects the largest scores. Ties and group masking affect which experts or entries survive…

72

Normalize the selected routing affinities

Each gathered affinity is divided by the sum across the selected experts plus 10⁻²⁰. Ignoring that stabilizer, the selected weights sum to one. With the stabilizer retained, the…

73

DeepSeek MoE.__init__: experts per rank

In DeepseekV3MoE.__init__, this statement defines or updates self.experts_per_rank. The expression forms a quotient or integer division. The denominator, integer rounding and…

74

DeepSeek MoE.__init__: experts

In DeepseekV3MoE.__init__, this statement defines or updates self.experts. The displayed multiplication combines the source factors. For tensors this is elementwise unless the…

75

DeepSeek MoE.__init__: ep size

In DeepseekV3MoE.__init__, this statement defines or updates self.ep_size. This statement fixes a numeric parameter or initializes a numerical state in this source version; it is…

76

DeepSeek MoE.__init__: ep rank

In DeepseekV3MoE.__init__, this statement defines or updates self.ep_rank. This statement fixes a numeric parameter or initializes a numerical state in this source version; it is…

77

DeepSeek MoE.__init__: intermediate size

In DeepseekV3MoE.__init__, this statement defines or updates intermediate_size. The displayed multiplication combines the source factors. For tensors this is elementwise unless…

78

Add an always-active shared expert

The shared expert processes identity, the input representation saved before the routed expert computation. Its output is added to the weighted routed sum. It therefore contributes…

79

DeepSeek MoE.moe_infer: tokens per ep rank

In DeepseekV3MoE.moe_infer, this statement defines or updates tokens_per_ep_rank. The reduction aggregates values along the explicit source axis; preserving the axis and…

80

DeepSeek MoE.moe_infer: output splits

In DeepseekV3MoE.moe_infer, this statement defines or updates output_splits. The reduction aggregates values along the explicit source axis; preserving the axis and keep-dimension…

81

DeepSeek MoE.moe_infer: gathered tokens

In DeepseekV3MoE.moe_infer, this statement defines or updates gathered_tokens. The reduction aggregates values along the explicit source axis; preserving the axis and…

82

DeepSeek MoE.moe_infer: tokens per expert post gather

In DeepseekV3MoE.moe_infer, this statement defines or updates tokens_per_expert_post_gather. The reduction aggregates values along the explicit source axis; preserving the axis…

83

DeepSeek MoE.moe_infer: s

In DeepseekV3MoE.moe_infer, this statement defines or updates s. This statement fixes a numeric parameter or initializes a numerical state in this source version; it is not a…

84

DeepSeek MoE.moe_infer: end idx

In DeepseekV3MoE.moe_infer, this statement defines or updates end_idx. The addition or subtraction updates the named state or combines residual contributions. The input shapes and…

85

DeepSeek MoE.moe_infer: expert

In DeepseekV3MoE.moe_infer, this statement defines or updates expert. The displayed multiplication combines the source factors. For tensors this is elementwise unless the called…

86

DeepSeek Attention.__init__: q proj

In DeepseekV3Attention.__init__, this statement defines or updates self.q_proj. The displayed multiplication combines the source factors. For tensors this is elementwise unless…

87

DeepSeek Attention.__init__: q b proj

In DeepseekV3Attention.__init__, this statement defines or updates self.q_b_proj. The displayed multiplication combines the source factors. For tensors this is elementwise unless…

88

DeepSeek Attention.forward: q

In DeepseekV3Attention.forward, this statement defines or updates q. This statement evaluates the named projection, normalization or numeric transform with the source arguments.…

89

DeepSeek Attention.forward: q

In DeepseekV3Attention.forward, this statement defines or updates q. This statement evaluates the named projection, normalization or numeric transform with the source arguments.…

90

DeepSeek Attention.forward: attn weights

In DeepseekV3Attention.forward, this statement defines or updates attn_weights. The addition or subtraction updates the named state or combines residual contributions. The input…

91

Pad value vectors to the query-head width

The FlashAttention path appends zero-valued components to V when the value width is smaller than the query width. With the displayed 192 and 128 widths, it appends 64 zeros. The…

92

DeepSeek FlashAttention2._upad_input: query layer

In DeepseekV3FlashAttention2._upad_input, this statement defines or updates query_layer. The displayed multiplication combines the source factors. For tensors this is elementwise…

93

DeepSeek Model.forward: position ids

In DeepseekV3Model.forward, this statement defines or updates position_ids. The addition or subtraction updates the named state or combines residual contributions. The input…

94

DeepSeek ForSequenceClassification.forward: output

In DeepseekV3ForSequenceClassification.forward, this statement defines or updates output. The addition or subtraction updates the named state or combines residual contributions.…

95

DeepSeek ForSequenceClassification.forward: return

In DeepseekV3ForSequenceClassification.forward, this statement returns the displayed result. The addition or subtraction updates the named state or combines residual…

96

DeepSeek MoE.moe_infer: gatherd idxs[s:s + k]

In DeepseekV3MoE.moe_infer, this statement defines or updates gatherd_idxs[s:s + k]. This statement evaluates the named projection, normalization or numeric transform with the…

97

Apply the additional YaRN score adjustment

Multiply the existing inverse-square-root attention coefficient by mscale². Here mscale is an evaluated logarithmic adjustment, not an independent second query dimension. The…

98

DeepSeek FlashAttention2._upad_input: max seqlen in batch q

In DeepseekV3FlashAttention2._upad_input, this statement defines or updates max_seqlen_in_batch_q. This statement fixes a numeric parameter or initializes a numerical state in…

99

DeepSeek FlashAttention2._upad_input: cu seqlens q

In DeepseekV3FlashAttention2._upad_input, this statement defines or updates cu_seqlens_q. The addition or subtraction updates the named state or combines residual contributions.…

100

DeepSeek ForSequenceClassification.forward: sequence lengths

In DeepseekV3ForSequenceClassification.forward, this statement defines or updates sequence_lengths. The addition or subtraction updates the named state or combines residual…

101

Decode an FP8 value and apply its block scale

The encoded byte first becomes its FP8 numerical value in float32, then is multiplied by the scale shared by its 128-by-128 block. The block indices mean floor(r/128) and…

102

Float32 linear expert-routing logits

Flattened token representations h are multiplied by the transpose of the gate weight matrix, giving one raw routing logit per expert. Both operands are cast to float32. None means…

103

Independent sigmoid scores for the router

The sigmoid 1/(1+exp(−z)) is applied to each expert logit independently. It compresses each finite real logit into (0,1), without normalizing across experts. These values are…

104

Bias the choice of experts while retaining original affinities

An expert-specific correction vector is added to the sigmoid affinities for ranking. This addition can change which groups and experts are selected. The later mixture weights are…

105

Score each group using its strongest two adjusted affinities

The 256 experts are arranged as eight groups of thirty-two. Within each token and group, take the two largest bias-adjusted scores and add them. The resulting eight group scores…

106

Keep the four highest-ranked expert groups

For each token, select the indices of the four largest group scores. This leaves four groups of thirty-two experts eligible for the next selection. The selection is a discrete…

107

Choose eight experts from the retained groups

The adjusted expert scores outside the selected groups are masked to negative infinity. Top-k then returns eight expert indices among the 128 eligible entries. The group…

108

Recover the original affinities of the selected experts

For each selected expert index, gather the corresponding value from the pre-bias sigmoid score array. Ranking used bias-adjusted values, but this weighting stage deliberately uses…

109

Normalize the selected routing affinities

Each gathered affinity is divided by the sum across the selected experts plus 10⁻²⁰. Ignoring that stabilizer, the selected weights sum to one. With the stabilizer retained, the…

110

Scale the routed branch by 2.5

After normalization, all selected mixture weights are multiplied by 2.5 in this DeepSeek configuration. Their sum is then approximately 2.5, so the routed contribution is…

111

Sum the selected expert outputs with their routing weights

Each chosen expert evaluates the same input representation h. Its output vector is multiplied by the associated routing weight, and the selected vectors are added. The…

112

Add an always-active shared expert

The shared expert processes identity, the input representation saved before the routed expert computation. Its output is added to the weighted routed sum. It therefore contributes…

113

Scaled query–key similarities with a rounded YaRN coefficient

The query–key matrix product forms similarities between each query position and key position. The prose uses 0.135237 as its attention multiplier. From the displayed exact…

114

Normalize each query’s attention scores

Apply softmax across key positions for each query and head. The resulting nonnegative weights sum to one when a row has at least one finite eligible score. The source computes…

115

Use attention weights to average value vectors

Matrix multiplication sums the value vector at each key position weighted by that query’s attention probability. A 128-component value vector per head gives a 128-component output…

116

Concatenate the heads and project to the residual width

The 128 heads contribute 128 value components each, giving 16,384 components per token. The output linear map then projects that concatenation into the 7,168-dimensional residual…

117

Latent-cache arithmetic and the embedded implementation mismatch

The arithmetic (512+64)×2=1152 bytes is correct for a cache storing one compressed key/value latent and one rotary key vector per token and layer at two bytes per element. The…

118

Solve for the rotary frequency index at a chosen rotation count

At index i, the unscaled angular frequency is base^(−2 i/dim). Over orig_max positions it completes orig_max*base^(−2 i/dim)/(2π) rotations. Setting that count equal to rot and…

119

Reduce the inverse-frequency schedule by the extension factor

The base rotary frequency is divided by factor. At a fixed token position, this reduces its phase advance by that factor. The later blend applies this scaled schedule toward the…

120

Retain the original inverse-frequency schedule

This is the original geometric rotary frequency schedule, base^(−2 i/dim). Its frequency decreases as i grows when base>1. The later blend retains the unscaled schedule at the…

121

YaRN prose blend with the ramp orientation reversed

If ramp is the increasing yarn_linear_ramp_mask defined in the embedded source, this prose reverses the blend. The body defines inv_freq_mask=1−ramp and returns…

122

Logarithmic magnitude adjustment for extended context

For scale>1, the adjustment adds 0.1*mscale*ln(scale) to one. The code returns one for scale≤1. One parameter specifies the context extension, while the other controls adjustment…

123

Evaluate the YaRN adjustment at factor forty

Substitution of scale=40 and adjustment strength 1 gives 1+0.1 ln 40=1.3688879454113936. The displayed 1.3688879 is a rounded form of that calculation. This is a deterministic…

124

Square the YaRN multiplier in the attention coefficient

The baseline coefficient is 1/√192. Multiplying it by the squared magnitude adjustment yields(1+0.1 ln 40)²/√192≈0.1352337788608801, a factor 1.8738542071 above the baseline. The…

125

Rotate paired query coordinates using a position-dependent angle

rotate_half maps a pair of coordinate blocks(x 1,x 2) to(−x 2,x 1). Multiplication by cosine and addition of the sine-weighted rotated vector implements a two-dimensional rotation…

126

Count routed expert evaluations along one token’s pass

Eight selected experts in each of fifty-eight MoE transformer layers give 464 routed expert evaluations for one token’s ordinary pass. The count excludes the dense prefix, shared…

127

A conditional total for routed expert weight traffic

Multiplying the dossier’s 44,050,944 bytes per expert by 464 expert evaluations gives 20,439,638,016 bytes, about 19.04 GiB. This is the stated one-load-per-evaluation accounting…

128

Convert a multiply–accumulate estimate into a FLOP estimate

Using the conventional count of one multiplication plus one addition per multiply–accumulate,36.52 GMAC corresponds to 73.04 GFLOP, rounded to 73.0. This is arithmetic applied to…

Search equations, builds, manuscript text, and recovered sources.