================================================================================ 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 | 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 "": "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 opens the reasoning trace 128799 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 "", 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 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|>\n Step 6 is the mechanism behind the model card's instruction to force reasoning: the template itself seeds the opening 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|>\n as token ids: [0, 128803, ...content ids..., 128804, 128798, ] The model then generates its reasoning, emits (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 class DeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel) L1734 __init__(config) L1735 get_input_embeddings() / set_input_embeddings(value) L1744 L1747 forward(...) -> SequenceClassifierOutputWithPast L1751 -------------------------------------------------------------------------------- 12.3 DeepseekV3Config PARAMETERS [SPEC] -------------------------------------------------------------------------------- Constructor defaults, from configuration_deepseek.py L112. Values differing in this checkpoint's config.json are marked. vocab_size 129280 hidden_size 7168 intermediate_size 18432 moe_intermediate_size 2048 num_hidden_layers 61 num_nextn_predict_layers 1 num_attention_heads 128 num_key_value_heads 128 n_shared_experts 1 n_routed_experts 256 ep_size 1 routed_scaling_factor 2.5 kv_lora_rank 512 q_lora_rank 1536 qk_rope_head_dim 64 v_head_dim 128 qk_nope_head_dim 128 topk_method "noaux_tc" n_group 8 topk_group 4 num_experts_per_tok 8 moe_layer_freq 1 first_k_dense_replace 3 norm_topk_prob True scoring_func "sigmoid" aux_loss_alpha 0.001 (training only) seq_aux True (training only) hidden_act "silu" max_position_embeddings 163840 (default in the class is 2048) initializer_range 0.02 rms_norm_eps 1e-6 use_cache True pad_token_id None bos_token_id 0 eos_token_id 1 pretraining_tp 1 tie_word_embeddings False rope_theta 10000.0 rope_scaling None (set to the yarn dict in config.json) attention_bias False attention_dropout 0.0 -------------------------------------------------------------------------------- 12.4 forward() INPUT / OUTPUT CONTRACT [SPEC] -------------------------------------------------------------------------------- DeepseekV3ForCausalLM.forward( input_ids: LongTensor (batch, seq) or None attention_mask: Tensor (batch, seq) 1=keep 0=pad or None position_ids: LongTensor (batch, seq) or None past_key_values: Cache or legacy tuple or None inputs_embeds: FloatTensor (batch, seq, 7168) or None labels: LongTensor (batch, seq) or None use_cache: bool or None output_attentions: bool or None output_hidden_states: bool or None return_dict: bool or None ) -> CausalLMOutputWithPast( loss: FloatTensor scalar, only if labels given logits: FloatTensor (batch, seq, 129280), cast to float32 past_key_values: Cache hidden_states: tuple of (batch, seq, 7168), only if requested attentions: tuple, only if requested ) Exactly one of input_ids / inputs_embeds must be supplied. Labels are shifted internally: logits[..., :-1] predict labels[..., 1:]. Loss is CrossEntropyLoss over the flattened vocab. prepare_inputs_for_generation handles cache trimming and builds position_ids from the attention mask via cumsum - which matters, because with left-padding the position ids are NOT simply arange. -------------------------------------------------------------------------------- 12.5 OFFICIAL HOSTED API ENDPOINTS [CARD] + [EXTERNAL] -------------------------------------------------------------------------------- Stated by the model card (section 5, reproduced verbatim in 15.6): Chat UI https://chat.deepseek.com - enable the "DeepThink" toggle API platform https://platform.deepseek.com - "OpenAI-Compatible API" The platform exposes an OpenAI-shaped surface. The canonical usage is to point an OpenAI client at DeepSeek's base URL and select the reasoning model: from openai import OpenAI client = OpenAI(api_key="", base_url="https://api.deepseek.com") resp = client.chat.completions.create( model="deepseek-reasoner", # R1 messages=[{"role":"user","content":"..."}]) Typical routes on that surface: POST /chat/completions chat, streaming or not POST /completions legacy text completion (FIM) GET /models model list GET /user/balance account balance [EXTERNAL] Model identifiers, route paths, pricing and parameter support are DeepSeek's to change and are not verifiable from this machine. Treat the two URLs above as the authoritative pointers and confirm specifics against the live documentation at platform.deepseek.com before writing an integration. -------------------------------------------------------------------------------- 12.6 SELF-HOSTED SERVING ENDPOINTS [CARD] + [EXTERNAL] -------------------------------------------------------------------------------- The model card directs full-R1 users to the DeepSeek-V3 repository: https://github.com/deepseek-ai/DeepSeek-V3 and gives concrete launch lines for the DISTILLED models (which are ordinary Qwen/Llama architectures and therefore already supported): vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \ --tensor-parallel-size 2 --max-model-len 32768 --enforce-eager python3 -m sglang.launch_server \ --model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B \ --trust-remote-code --tp 2 Both servers present an OpenAI-compatible HTTP surface, conventionally: POST /v1/chat/completions chat, SSE streaming with stream=true POST /v1/completions raw completion GET /v1/models model list GET /health liveness vLLM additionally serves /metrics (Prometheus); SGLang additionally serves /generate (its native, non-OpenAI route). [EXTERNAL] Flags and routes belong to those projects and change between releases; verify against the version you install. ON THIS MACHINE: none of these are installed, and the 643 GB fp8 checkpoint needs a runtime that implements 128x128 block dequant. See PART 13 for why the memory envelope is the binding constraint here regardless. -------------------------------------------------------------------------------- 12.7 THE REASONING-CONTENT CONTRACT -------------------------------------------------------------------------------- R1 emits a reasoning trace before its answer, delimited by (128798) and (128799). Two consequences that any integration must handle: 1. SEPARATE THE CHANNELS. The trace is not the answer. On the hosted API this arrives as a distinct field alongside the normal content; when self-hosting you must split on yourself. 2. DO NOT FEED TRACES BACK. The chat template explicitly strips everything up to and including from prior assistant turns (see 11.3). Echoing old reasoning into the next request diverges from how the model was trained. USAGE RECOMMENDATIONS FROM THE MODEL CARD [CARD]: - temperature 0.5-0.7, 0.6 recommended, to avoid endless repetition - AVOID a system prompt; put all instructions in the user message - for math, ask for the final answer inside \boxed{} - average over several runs when benchmarking - force the response to begin with "\n"; the model otherwise sometimes emits an empty "\n\n" and skips reasoning - evaluation used max generation length 32,768 tokens, temperature 0.6, top_p 0.95, 64 samples per query for pass@1 ================================================================================ PART 13 FOOTPRINT: MEMORY, DISK I/O, COMPUTE [COMPUTED] ================================================================================ Derived from the measured tensor census. Batch 1, decode step, layers 0..60 (the MTP layer excluded). WEIGHTS THAT MUST BE RESIDENT (everything except the routed experts) --------------------------------------------------------------------------- component GiB basis --------------------------------------------------------------------------- attention, 5 projections x 61 layers 10.630 187,105,280 B per layer shared experts x 58 layers 2.379 3 x 2048 x 7168 fp8 dense MLP, layers 0-2 1.107 3 x 3 x 18432 x 7168 fp8 MoE router weights x 58 0.198 256 x 7168 BF16 e_score_correction_bias + all norms 0.002 F32 / BF16 embed_tokens 1.726 129280 x 7168 BF16 lm_head 1.726 129280 x 7168 BF16 --------------------------------------------------------------------------- TOTAL RESIDENT, native dtypes 17.768 with embed_tokens + lm_head at int8 16.042 --------------------------------------------------------------------------- ROUTED EXPERT TRAFFIC (streamed, per token) 8 experts x 58 MoE layers = 464 expert reads per token 464 x 44,050,944 B = 20,439,638,016 B = 19.04 GiB per token Against the measured drive rates from PART 1: --------------------------------------------------------------------------- at 507 MB/s single stream 40.3 s per token at 1,220 MB/s 4 parallel streams 16.8 s per token at 326 MB/s scattered small reads 62.7 s per token --------------------------------------------------------------------------- Bandwidth floors only: no syscall overhead, no dequantization, no compute overlap, no cache reuse. Nothing has been run end to end. KV CACHE - see 10.3 for the table and the kv_b_proj coupling. COMPUTE PER TOKEN --------------------------------------------------------------------------- attention (5 projections x 61) 11.41 GMAC 31.3% routed experts (8 x 58 x 3 matrices) 20.43 GMAC 56.0% shared experts (58 x 3 matrices) 2.55 GMAC 7.0% dense MLP (3 layers) 1.19 GMAC 3.3% lm_head 0.93 GMAC 2.5% --------------------------------------------------------------------------- TOTAL 36.52 GMAC = 73.0 GFLOP per token --------------------------------------------------------------------------- On 12 threads of AVX2 without VNNI, roughly 150 GOPS sustained int8 is realistic for this CPU: about 0.24 s per token of arithmetic. THE SHAPE OF THE PROBLEM ON THIS MACHINE disk I/O per token 17 - 40 s arithmetic per token ~0.24 s ratio 70x to 170x I/O-bound by two orders of magnitude. Attention is 31% of the arithmetic but none of the streamed I/O, since it is resident. WHAT FITS, AND WHAT DOES NOT RAM available to WSL2 25 GiB free at scan time 9.6 GiB resident weights needed 16.0 GiB + KV at 16K context, bf16 1.1 GiB + activations, LUTs, OS reserve ~1.5 GiB -------- minimum working set ~18.6 GiB The resident weight set alone exceeds currently free memory. The 163,840-token context is unreachable here: 10.72 GiB of KV on top of 16.0 GiB of weights exceeds the 25 GiB the VM has. 16K-32K is the honest ceiling for this machine. Disk: 619.65 GiB of the checkpoint is routed experts against 228 GiB free on /. There is no room to write a second, reorganized copy of the expert weights. The contiguous on-disk layout in 2.6 means none is needed. ================================================================================ PART 14 DISCREPANCIES, TRAPS AND GOTCHAS ================================================================================ THREE-WAY CONTEXT-LENGTH DISAGREEMENT config.json max_position_embeddings 163840 README.md "Context Length" 128K [CARD] tokenizer_config.json model_max_length 16384 Three different numbers in three files of the same repository. The architecture supports 163,840 positions; the card advertises 128K; the tokenizer will refuse or warn past 16,384. Decide explicitly which governs your deployment; do not let a library pick for you. INDEX total_size IS WRONG BY 1.99x 1,369,062,772,000 claimed vs 688,574,839,360 actual. FP8 elements were costed at two bytes. Headers are authoritative. e_score_correction_bias IS F32 Shape (256,), one per MoE layer, sitting among BF16 neighbours in the same layer namespace. Read it as bf16 and routing degrades in every MoE layer with no crash and no error - only worse output. kv_a_proj_with_mqa HAS THE ONLY PADDED BLOCK GRID Shape (576, 7168) against a scale grid of (5, 56). 576/128 = 4.5, so the fifth block row covers only 64 of 128 rows. Every other tensor among all 91,991 divides by 128 exactly. A dequant loop assuming exact divisibility reads 64 rows of garbage per layer across 62 layers, silently. ROUTER GATHERS PRE-BIAS SCORES Selection uses scores + bias; weighting uses scores without bias. Both, in the same function, deliberately. See PART 7 step 7. softmax_scale IS NOT 1/sqrt(d) 0.135237, not 0.0721688, because mscale_all_dim=1.0 activates the mscale^2 correction. A 1.874x factor. routed_scaling_factor IS APPLIED AFTER RENORMALIZATION Multiply by 2.5 after dividing by the sum, not before. Easy to drop entirely. THE SHARED EXPERT CONSUMES THE PRE-MoE RESIDUAL shared_experts(identity), not shared_experts(routed_output), and it is added to the routed sum afterwards. HALF OF ALL TENSORS ARE TINY F32 SCALES 45,867 of 91,991. Never size work, progress, or allocation by tensor count. FP8 CANNOT BE INTEGER-ACCUMULATED It has an exponent field. Raw fp8 bytes are not fixed-point; any integer MAC scheme has to dequantize or work per-128x128-tile with a shared exponent. EXPERTS STRADDLE SHARD BOUNDARIES Contiguity holds WITHIN a shard. About 162 of 14,848 experts span two files. Handle it, or corrupt one expert per boundary. lm_head IS IN SHARD 160, NOT 163 Shards 161-163 are entirely MTP layer 61. A loader that assumes "the output head is in the last shard" will not find it. 465 UNUSED VOCAB SLOTS Token ids run 0..128,814 but vocab_size is 129,280. Rows 128,815..129,279 of embed_tokens and lm_head are never indexed by the tokenizer, but must still be allocated. NO FP8 REFERENCE IMPLEMENTATION IN THE REPOSITORY The shipped modeling code assumes already-dequantized bf16. Anyone writing a loader is writing the 128x128 block dequant without a local reference to check against. See PART 6. MACHINE-SPECIFIC (megamind-agi) * No AVX-512, no VNNI, no AMX. int8 dot = vpmaddubsw + vpmaddwd on 256-bit. * Warm re-reads are SLOWER than cold (408 vs 507 MB/s). No page-cache benefit. * 4-way parallel reads give 2.4x - fan out, do not serialize. * Python 3.14 has no torch wheels. * WSL2 kills backgrounded jobs when a one-shot SSH command returns; use systemd. * cmd.exe caps command lines at 8191 chars; base64 anything long. ================================================================================ PART 15 SOURCE CODE ================================================================================ Everything below is reproduced byte-for-byte from the files in /home/joseph/DeepSeek-R1 as of 2026-08-05. ================================================================================ 15.1 config.json ================================================================================ { "architectures": [ "DeepseekV3ForCausalLM" ], "attention_bias": false, "attention_dropout": 0.0, "auto_map": { "AutoConfig": "configuration_deepseek.DeepseekV3Config", "AutoModel": "modeling_deepseek.DeepseekV3Model", "AutoModelForCausalLM": "modeling_deepseek.DeepseekV3ForCausalLM" }, "bos_token_id": 0, "eos_token_id": 1, "ep_size": 1, "first_k_dense_replace": 3, "hidden_act": "silu", "hidden_size": 7168, "initializer_range": 0.02, "intermediate_size": 18432, "kv_lora_rank": 512, "max_position_embeddings": 163840, "model_type": "deepseek_v3", "moe_intermediate_size": 2048, "moe_layer_freq": 1, "n_group": 8, "n_routed_experts": 256, "n_shared_experts": 1, "norm_topk_prob": true, "num_attention_heads": 128, "num_experts_per_tok": 8, "num_hidden_layers": 61, "num_key_value_heads": 128, "num_nextn_predict_layers": 1, "q_lora_rank": 1536, "qk_nope_head_dim": 128, "qk_rope_head_dim": 64, "quantization_config": { "activation_scheme": "dynamic", "fmt": "e4m3", "quant_method": "fp8", "weight_block_size": [ 128, 128 ] }, "rms_norm_eps": 1e-06, "rope_scaling": { "beta_fast": 32, "beta_slow": 1, "factor": 40, "mscale": 1.0, "mscale_all_dim": 1.0, "original_max_position_embeddings": 4096, "type": "yarn" }, "rope_theta": 10000, "routed_scaling_factor": 2.5, "scoring_func": "sigmoid", "tie_word_embeddings": false, "topk_group": 4, "topk_method": "noaux_tc", "torch_dtype": "bfloat16", "transformers_version": "4.46.3", "use_cache": true, "v_head_dim": 128, "vocab_size": 129280 } ================================================================================ 15.2 configuration_deepseek.py (199 lines, 9,897 bytes) ================================================================================ from transformers.configuration_utils import PretrainedConfig from transformers.utils import logging logger = logging.get_logger(__name__) DEEPSEEK_PRETRAINED_CONFIG_ARCHIVE_MAP = {} class DeepseekV3Config(PretrainedConfig): r""" This is the configuration class to store the configuration of a [`DeepseekV3Model`]. It is used to instantiate an DeepSeek model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the DeepSeek-V3. Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the documentation from [`PretrainedConfig`] for more information. Args: vocab_size (`int`, *optional*, defaults to 129280): Vocabulary size of the Deep model. Defines the number of different tokens that can be represented by the `inputs_ids` passed when calling [`DeepseekV3Model`] hidden_size (`int`, *optional*, defaults to 4096): Dimension of the hidden representations. intermediate_size (`int`, *optional*, defaults to 11008): Dimension of the MLP representations. moe_intermediate_size (`int`, *optional*, defaults to 1407): Dimension of the MoE representations. num_hidden_layers (`int`, *optional*, defaults to 32): Number of hidden layers in the Transformer decoder. num_nextn_predict_layers (`int`, *optional*, defaults to 1): Number of nextn predict layers in the DeepSeekV3 Model. num_attention_heads (`int`, *optional*, defaults to 32): Number of attention heads for each attention layer in the Transformer decoder. n_shared_experts (`int`, *optional*, defaults to None): Number of shared experts, None means dense model. n_routed_experts (`int`, *optional*, defaults to None): Number of routed experts, None means dense model. routed_scaling_factor (`float`, *optional*, defaults to 1.0): Scaling factor or routed experts. topk_method (`str`, *optional*, defaults to `gready`): Topk method used in routed gate. n_group (`int`, *optional*, defaults to None): Number of groups for routed experts. topk_group (`int`, *optional*, defaults to None): Number of selected groups for each token(for each token, ensuring the selected experts is only within `topk_group` groups). num_experts_per_tok (`int`, *optional*, defaults to None): Number of selected experts, None means dense model. moe_layer_freq (`int`, *optional*, defaults to 1): The frequency of the MoE layer: one expert layer for every `moe_layer_freq - 1` dense layers. first_k_dense_replace (`int`, *optional*, defaults to 0): Number of dense layers in shallow layers(embed->dense->dense->...->dense->moe->moe...->lm_head). \--k dense layers--/ norm_topk_prob (`bool`, *optional*, defaults to False): Whether to normalize the weights of the routed experts. scoring_func (`str`, *optional*, defaults to 'softmax'): Method of computing expert weights. aux_loss_alpha (`float`, *optional*, defaults to 0.001): Auxiliary loss weight coefficient. seq_aux = (`bool`, *optional*, defaults to True): Whether to compute the auxiliary loss for each individual sample. num_key_value_heads (`int`, *optional*): This is the number of key_value heads that should be used to implement Grouped Query Attention. If `num_key_value_heads=num_attention_heads`, the model will use Multi Head Attention (MHA), if `num_key_value_heads=1 the model will use Multi Query Attention (MQA) otherwise GQA is used. When converting a multi-head checkpoint to a GQA checkpoint, each group key and value head should be constructed by meanpooling all the original heads within that group. For more details checkout [this paper](https://arxiv.org/pdf/2305.13245.pdf). If it is not specified, will default to `num_attention_heads`. hidden_act (`str` or `function`, *optional*, defaults to `"silu"`): The non-linear activation function (function or string) in the decoder. max_position_embeddings (`int`, *optional*, defaults to 2048): The maximum sequence length that this model might ever be used with. initializer_range (`float`, *optional*, defaults to 0.02): The standard deviation of the truncated_normal_initializer for initializing all weight matrices. rms_norm_eps (`float`, *optional*, defaults to 1e-06): The epsilon used by the rms normalization layers. use_cache (`bool`, *optional*, defaults to `True`): Whether or not the model should return the last key/values attentions (not used by all models). Only relevant if `config.is_decoder=True`. pad_token_id (`int`, *optional*): Padding token id. bos_token_id (`int`, *optional*, defaults to 1): Beginning of stream token id. eos_token_id (`int`, *optional*, defaults to 2): End of stream token id. tie_word_embeddings (`bool`, *optional*, defaults to `False`): Whether to tie weight embeddings rope_theta (`float`, *optional*, defaults to 10000.0): The base period of the RoPE embeddings. rope_scaling (`Dict`, *optional*): Dictionary containing the scaling configuration for the RoPE embeddings. Currently supports two scaling strategies: linear and dynamic. Their scaling factor must be a float greater than 1. The expected format is `{"type": strategy name, "factor": scaling factor}`. When using this flag, don't update `max_position_embeddings` to the expected new maximum. attention_bias (`bool`, defaults to `False`, *optional*, defaults to `False`): Whether to use a bias in the query, key, value and output projection layers during self-attention. attention_dropout (`float`, *optional*, defaults to 0.0): The dropout ratio for the attention probabilities. ```python >>> from transformers import DeepseekV3Model, DeepseekV3Config >>> # Initializing a Deepseek-V3 style configuration >>> configuration = DeepseekV3Config() >>> # Accessing the model configuration >>> configuration = model.config ```""" model_type = "deepseek_v3" keys_to_ignore_at_inference = ["past_key_values"] def __init__( self, vocab_size=129280, hidden_size=7168, intermediate_size=18432, moe_intermediate_size = 2048, num_hidden_layers=61, num_nextn_predict_layers=1, num_attention_heads=128, num_key_value_heads=128, n_shared_experts = 1, n_routed_experts = 256, ep_size = 1, routed_scaling_factor = 2.5, kv_lora_rank = 512, q_lora_rank = 1536, qk_rope_head_dim = 64, v_head_dim = 128, qk_nope_head_dim = 128, topk_method = 'noaux_tc', n_group = 8, topk_group = 4, num_experts_per_tok = 8, moe_layer_freq = 1, first_k_dense_replace = 3, norm_topk_prob = True, scoring_func = 'sigmoid', hidden_act="silu", max_position_embeddings=4096, initializer_range=0.02, rms_norm_eps=1e-6, use_cache=True, pad_token_id=None, bos_token_id=0, eos_token_id=1, tie_word_embeddings=False, rope_theta=10000.0, rope_scaling=None, attention_bias=False, attention_dropout=0.0, **kwargs, ): self.vocab_size = vocab_size self.max_position_embeddings = max_position_embeddings self.hidden_size = hidden_size self.intermediate_size = intermediate_size self.moe_intermediate_size = moe_intermediate_size self.num_hidden_layers = num_hidden_layers self.num_nextn_predict_layers = num_nextn_predict_layers self.num_attention_heads = num_attention_heads self.n_shared_experts = n_shared_experts self.n_routed_experts = n_routed_experts self.ep_size = ep_size self.routed_scaling_factor = routed_scaling_factor self.kv_lora_rank = kv_lora_rank self.q_lora_rank = q_lora_rank self.qk_rope_head_dim = qk_rope_head_dim self.v_head_dim = v_head_dim self.qk_nope_head_dim = qk_nope_head_dim self.topk_method = topk_method self.n_group = n_group self.topk_group = topk_group self.num_experts_per_tok = num_experts_per_tok self.moe_layer_freq = moe_layer_freq self.first_k_dense_replace = first_k_dense_replace self.norm_topk_prob = norm_topk_prob self.scoring_func = scoring_func # for backward compatibility if num_key_value_heads is None: num_key_value_heads = num_attention_heads self.num_key_value_heads = num_key_value_heads self.hidden_act = hidden_act self.initializer_range = initializer_range self.rms_norm_eps = rms_norm_eps self.use_cache = use_cache self.rope_theta = rope_theta self.rope_scaling = rope_scaling self.attention_bias = attention_bias self.attention_dropout = attention_dropout super().__init__( pad_token_id=pad_token_id, bos_token_id=bos_token_id, eos_token_id=eos_token_id, tie_word_embeddings=tie_word_embeddings, **kwargs, ) ================================================================================ 15.3 modeling_deepseek.py (1,848 lines, 75,741 bytes) The reference forward pass. This is the authoritative description of how DeepSeek-R1 computes. ================================================================================ # coding=utf-8 # Copyright 2023 DeepSeek-AI and The HuggingFace Inc. team. All rights reserved. # # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX # and OPT implementations in this library. It has been modified from its # original forms to accommodate minor architectural differences compared # to GPT-NeoX and OPT used by the Meta AI team that trained the model. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ PyTorch DeepSeek model.""" import math import warnings from typing import List, Optional, Tuple, Union import torch import torch.nn.functional as F import torch.utils.checkpoint from torch import nn from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss from transformers.activations import ACT2FN from transformers.cache_utils import Cache, DynamicCache from transformers.modeling_attn_mask_utils import ( AttentionMaskConverter, _prepare_4d_attention_mask, _prepare_4d_causal_attention_mask, ) from transformers.modeling_outputs import ( BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast, ) from transformers.modeling_utils import PreTrainedModel from transformers.pytorch_utils import ( ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13, ) from transformers.utils import ( add_start_docstrings, add_start_docstrings_to_model_forward, is_flash_attn_2_available, is_flash_attn_greater_or_equal_2_10, logging, replace_return_docstrings, ) from transformers.utils.import_utils import is_torch_fx_available from .configuration_deepseek import DeepseekV3Config import torch.distributed as dist import numpy as np if is_flash_attn_2_available(): from flash_attn import flash_attn_func, flash_attn_varlen_func from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph. # It means that the function will not be traced through and simply appear as a node in the graph. if is_torch_fx_available(): if not is_torch_greater_or_equal_than_1_13: import torch.fx _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask) logger = logging.get_logger(__name__) _CONFIG_FOR_DOC = "DeepseekV3Config" def _get_unpad_data(attention_mask): seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32) indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten() max_seqlen_in_batch = seqlens_in_batch.max().item() cu_seqlens = F.pad( torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0) ) return ( indices, cu_seqlens, max_seqlen_in_batch, ) class DeepseekV3RMSNorm(nn.Module): def __init__(self, hidden_size, eps=1e-6): """ DeepseekV3RMSNorm is equivalent to T5LayerNorm """ super().__init__() self.weight = nn.Parameter(torch.ones(hidden_size)) self.variance_epsilon = eps def forward(self, hidden_states): input_dtype = hidden_states.dtype hidden_states = hidden_states.to(torch.float32) variance = hidden_states.pow(2).mean(-1, keepdim=True) hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon) return self.weight * hidden_states.to(input_dtype) ALL_LAYERNORM_LAYERS.append(DeepseekV3RMSNorm) class DeepseekV3RotaryEmbedding(nn.Module): def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None): super().__init__() self.dim = dim self.max_position_embeddings = max_position_embeddings self.base = base inv_freq = 1.0 / ( self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False) # Build here to make `torch.jit.trace` work. self._set_cos_sin_cache( seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype(), ) self.max_seq_len_cached = None def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype ) freqs = torch.outer(t, self.inv_freq.to(t.device)) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) def forward(self, x, seq_len=None): # x: [bs, num_attention_heads, seq_len, head_size] if self.max_seq_len_cached is None or seq_len > self.max_seq_len_cached: self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype) return ( self.cos_cached[:seq_len].to(dtype=x.dtype), self.sin_cached[:seq_len].to(dtype=x.dtype), ) # Copied from transformers.models.llama.modeling_llama.LlamaLinearScalingRotaryEmbedding with Llama->DeepseekV3 class DeepseekV3LinearScalingRotaryEmbedding(DeepseekV3RotaryEmbedding): """DeepseekV3RotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev""" def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, ): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype ) t = t / self.scaling_factor freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) # Copied from transformers.models.llama.modeling_llama.LlamaDynamicNTKScalingRotaryEmbedding with Llama->DeepseekV3 class DeepseekV3DynamicNTKScalingRotaryEmbedding(DeepseekV3RotaryEmbedding): """DeepseekV3RotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla""" def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, ): self.scaling_factor = scaling_factor super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len if seq_len > self.max_position_embeddings: base = self.base * ( (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1) ) ** (self.dim / (self.dim - 2)) inv_freq = 1.0 / ( base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim) ) self.register_buffer("inv_freq", inv_freq, persistent=False) t = torch.arange( self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype ) freqs = torch.outer(t, self.inv_freq) # Different from paper, but it uses a different permutation in order to obtain the same calculation emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False) self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False) # Inverse dim formula to find dim based on number of rotations def yarn_find_correction_dim( num_rotations, dim, base=10000, max_position_embeddings=2048 ): return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / ( 2 * math.log(base) ) # Find dim range bounds based on rotations def yarn_find_correction_range( low_rot, high_rot, dim, base=10000, max_position_embeddings=2048 ): low = math.floor( yarn_find_correction_dim(low_rot, dim, base, max_position_embeddings) ) high = math.ceil( yarn_find_correction_dim(high_rot, dim, base, max_position_embeddings) ) return max(low, 0), min(high, dim - 1) # Clamp values just in case def yarn_get_mscale(scale=1, mscale=1): if scale <= 1: return 1.0 return 0.1 * mscale * math.log(scale) + 1.0 def yarn_linear_ramp_mask(min, max, dim): if min == max: max += 0.001 # Prevent singularity linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min) ramp_func = torch.clamp(linear_func, 0, 1) return ramp_func class DeepseekV3YarnRotaryEmbedding(DeepseekV3RotaryEmbedding): def __init__( self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0, original_max_position_embeddings=4096, beta_fast=32, beta_slow=1, mscale=1, mscale_all_dim=0, ): self.scaling_factor = scaling_factor self.original_max_position_embeddings = original_max_position_embeddings self.beta_fast = beta_fast self.beta_slow = beta_slow self.mscale = mscale self.mscale_all_dim = mscale_all_dim super().__init__(dim, max_position_embeddings, base, device) def _set_cos_sin_cache(self, seq_len, device, dtype): self.max_seq_len_cached = seq_len dim = self.dim freq_extra = 1.0 / ( self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim) ) freq_inter = 1.0 / ( self.scaling_factor * self.base ** (torch.arange(0, dim, 2, dtype=torch.float32, device=device) / dim) ) low, high = yarn_find_correction_range( self.beta_fast, self.beta_slow, dim, self.base, self.original_max_position_embeddings, ) inv_freq_mask = 1.0 - yarn_linear_ramp_mask(low, high, dim // 2).to( device=device, dtype=torch.float32 ) inv_freq = freq_inter * (1 - inv_freq_mask) + freq_extra * inv_freq_mask self.register_buffer("inv_freq", inv_freq, persistent=False) t = torch.arange(seq_len, device=device, dtype=torch.float32) freqs = torch.outer(t, inv_freq) _mscale = float( yarn_get_mscale(self.scaling_factor, self.mscale) / yarn_get_mscale(self.scaling_factor, self.mscale_all_dim) ) emb = torch.cat((freqs, freqs), dim=-1) self.register_buffer( "cos_cached", (emb.cos() * _mscale).to(dtype), persistent=False ) self.register_buffer( "sin_cached", (emb.sin() * _mscale).to(dtype), persistent=False ) # Copied from transformers.models.llama.modeling_llama.rotate_half def rotate_half(x): """Rotates half the hidden dims of the input.""" x1 = x[..., : x.shape[-1] // 2] x2 = x[..., x.shape[-1] // 2 :] return torch.cat((-x2, x1), dim=-1) # Copied from transformers.models.llama.modeling_llama.apply_rotary_pos_emb def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1): """Applies Rotary Position Embedding to the query and key tensors. Args: q (`torch.Tensor`): The query tensor. k (`torch.Tensor`): The key tensor. cos (`torch.Tensor`): The cosine part of the rotary embedding. sin (`torch.Tensor`): The sine part of the rotary embedding. position_ids (`torch.Tensor`): The position indices of the tokens corresponding to the query and key tensors. For example, this can be used to pass offsetted position ids when working with a KV-cache. unsqueeze_dim (`int`, *optional*, defaults to 1): The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2. Returns: `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding. """ cos = cos[position_ids].unsqueeze(unsqueeze_dim) sin = sin[position_ids].unsqueeze(unsqueeze_dim) b, h, s, d = q.shape q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d) b, h, s, d = k.shape k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d) q_embed = (q * cos) + (rotate_half(q) * sin) k_embed = (k * cos) + (rotate_half(k) * sin) return q_embed, k_embed class DeepseekV3MLP(nn.Module): def __init__(self, config, hidden_size=None, intermediate_size=None): super().__init__() self.config = config self.hidden_size = config.hidden_size if hidden_size is None else hidden_size self.intermediate_size = ( config.intermediate_size if intermediate_size is None else intermediate_size ) self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False) self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False) self.act_fn = ACT2FN[config.hidden_act] def forward(self, x): down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x)) return down_proj class MoEGate(nn.Module): def __init__(self, config): super().__init__() self.config = config self.top_k = config.num_experts_per_tok self.n_routed_experts = config.n_routed_experts self.routed_scaling_factor = config.routed_scaling_factor self.scoring_func = config.scoring_func self.topk_method = config.topk_method self.n_group = config.n_group self.topk_group = config.topk_group # topk selection algorithm self.norm_topk_prob = config.norm_topk_prob self.gating_dim = config.hidden_size self.weight = nn.Parameter( torch.empty((self.n_routed_experts, self.gating_dim)) ) if self.topk_method == "noaux_tc": self.e_score_correction_bias = nn.Parameter( torch.empty((self.n_routed_experts)) ) self.reset_parameters() def reset_parameters(self) -> None: import torch.nn.init as init init.kaiming_uniform_(self.weight, a=math.sqrt(5)) def forward(self, hidden_states): bsz, seq_len, h = hidden_states.shape ### compute gating score hidden_states = hidden_states.view(-1, h) logits = F.linear( hidden_states.type(torch.float32), self.weight.type(torch.float32), None ) if self.scoring_func == "sigmoid": scores = logits.sigmoid() else: raise NotImplementedError( f"insupportable scoring function for MoE gating: {self.scoring_func}" ) ### select top-k experts if self.topk_method == "noaux_tc": assert not self.training scores_for_choice = scores.view(bsz * seq_len, -1) + self.e_score_correction_bias.unsqueeze(0) group_scores = ( scores_for_choice.view(bsz * seq_len, self.n_group, -1).topk(2, dim=-1)[0].sum(dim = -1) ) # [n, n_group] group_idx = torch.topk( group_scores, k=self.topk_group, dim=-1, sorted=False )[ 1 ] # [n, top_k_group] group_mask = torch.zeros_like(group_scores) # [n, n_group] group_mask.scatter_(1, group_idx, 1) # [n, n_group] score_mask = ( group_mask.unsqueeze(-1) .expand( bsz * seq_len, self.n_group, self.n_routed_experts // self.n_group ) .reshape(bsz * seq_len, -1) ) # [n, e] tmp_scores = scores_for_choice.masked_fill(~score_mask.bool(), float("-inf")) # [n, e] _, topk_idx = torch.topk( tmp_scores, k=self.top_k, dim=-1, sorted=False ) topk_weight = scores.gather(1, topk_idx) else: raise NotImplementedError( f"insupportable TopK function for MoE gating: {self.topk_method}" ) ### norm gate to sum 1 if self.top_k > 1 and self.norm_topk_prob: denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20 topk_weight = topk_weight / denominator topk_weight = topk_weight * self.routed_scaling_factor # must multiply the scaling factor return topk_idx, topk_weight class DeepseekV3MoE(nn.Module): """ A mixed expert module containing shared experts. """ def __init__(self, config): super().__init__() self.config = config self.num_experts_per_tok = config.num_experts_per_tok if hasattr(config, "ep_size") and config.ep_size > 1: assert config.ep_size == dist.get_world_size() self.ep_size = config.ep_size self.experts_per_rank = config.n_routed_experts // config.ep_size self.ep_rank = dist.get_rank() self.experts = nn.ModuleList( [ ( DeepseekV3MLP( config, intermediate_size=config.moe_intermediate_size ) if i >= self.ep_rank * self.experts_per_rank and i < (self.ep_rank + 1) * self.experts_per_rank else None ) for i in range(config.n_routed_experts) ] ) else: self.ep_size = 1 self.experts_per_rank = config.n_routed_experts self.ep_rank = 0 self.experts = nn.ModuleList( [ DeepseekV3MLP( config, intermediate_size=config.moe_intermediate_size ) for i in range(config.n_routed_experts) ] ) self.gate = MoEGate(config) if config.n_shared_experts is not None: intermediate_size = config.moe_intermediate_size * config.n_shared_experts self.shared_experts = DeepseekV3MLP( config=config, intermediate_size=intermediate_size ) def forward(self, hidden_states): identity = hidden_states orig_shape = hidden_states.shape topk_idx, topk_weight = self.gate(hidden_states) hidden_states = hidden_states.view(-1, hidden_states.shape[-1]) flat_topk_idx = topk_idx.view(-1) if not self.training: y = self.moe_infer(hidden_states, topk_idx, topk_weight).view(*orig_shape) if self.config.n_shared_experts is not None: y = y + self.shared_experts(identity) return y @torch.no_grad() def moe_infer(self, x, topk_ids, topk_weight): cnts = topk_ids.new_zeros((topk_ids.shape[0], len(self.experts))) cnts.scatter_(1, topk_ids, 1) tokens_per_expert = cnts.sum(dim=0) idxs = topk_ids.view(-1).argsort() sorted_tokens = x[idxs // topk_ids.shape[1]] sorted_tokens_shape = sorted_tokens.shape if self.ep_size > 1: tokens_per_ep_rank = tokens_per_expert.view(self.ep_size, -1).sum(dim=1) tokens_per_expert_group = tokens_per_expert.new_empty( tokens_per_expert.shape[0] ) dist.all_to_all_single(tokens_per_expert_group, tokens_per_expert) output_splits = ( tokens_per_expert_group.view(self.ep_size, -1) .sum(1) .cpu() .numpy() .tolist() ) gathered_tokens = sorted_tokens.new_empty( tokens_per_expert_group.sum(dim=0).cpu().item(), sorted_tokens.shape[1] ) input_split_sizes = tokens_per_ep_rank.cpu().numpy().tolist() dist.all_to_all( list(gathered_tokens.split(output_splits)), list(sorted_tokens.split(input_split_sizes)), ) tokens_per_expert_post_gather = tokens_per_expert_group.view( self.ep_size, self.experts_per_rank ).sum(dim=0) gatherd_idxs = np.zeros(shape=(gathered_tokens.shape[0],), dtype=np.int32) s = 0 for i, k in enumerate(tokens_per_expert_group.cpu().numpy()): gatherd_idxs[s : s + k] = i % self.experts_per_rank s += k gatherd_idxs = gatherd_idxs.argsort() sorted_tokens = gathered_tokens[gatherd_idxs] tokens_per_expert = tokens_per_expert_post_gather tokens_per_expert = tokens_per_expert.cpu().numpy() outputs = [] start_idx = 0 for i, num_tokens in enumerate(tokens_per_expert): end_idx = start_idx + num_tokens if num_tokens == 0: continue expert = self.experts[i + self.ep_rank * self.experts_per_rank] tokens_for_this_expert = sorted_tokens[start_idx:end_idx] expert_out = expert(tokens_for_this_expert) outputs.append(expert_out) start_idx = end_idx outs = torch.cat(outputs, dim=0) if len(outputs) else sorted_tokens.new_empty(0) if self.ep_size > 1: new_x = torch.empty_like(outs) new_x[gatherd_idxs] = outs gathered_tokens = new_x.new_empty(*sorted_tokens_shape) dist.all_to_all( list(gathered_tokens.split(input_split_sizes)), list(new_x.split(output_splits)), ) outs = gathered_tokens new_x = torch.empty_like(outs) new_x[idxs] = outs final_out = ( new_x.view(*topk_ids.shape, -1) .type(topk_weight.dtype) .mul_(topk_weight.unsqueeze(dim=-1)) .sum(dim=1) .type(new_x.dtype) ) return final_out # Copied from transformers.models.llama.modeling_llama.repeat_kv def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor: """ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch, num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim) """ batch, num_key_value_heads, slen, head_dim = hidden_states.shape if n_rep == 1: return hidden_states hidden_states = hidden_states[:, :, None, :, :].expand( batch, num_key_value_heads, n_rep, slen, head_dim ) return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim) # Copied from transformers.models.llama.modeling_llama.LlamaAttention with Llama->DeepseekV3 class DeepseekV3Attention(nn.Module): """Multi-headed attention from 'Attention Is All You Need' paper""" def __init__(self, config: DeepseekV3Config, layer_idx: Optional[int] = None): super().__init__() self.config = config self.layer_idx = layer_idx if layer_idx is None: logger.warning_once( f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will " "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` " "when creating this class." ) self.attention_dropout = config.attention_dropout self.hidden_size = config.hidden_size self.num_heads = config.num_attention_heads self.max_position_embeddings = config.max_position_embeddings self.rope_theta = config.rope_theta self.q_lora_rank = config.q_lora_rank self.qk_rope_head_dim = config.qk_rope_head_dim self.kv_lora_rank = config.kv_lora_rank self.v_head_dim = config.v_head_dim self.qk_nope_head_dim = config.qk_nope_head_dim self.q_head_dim = config.qk_nope_head_dim + config.qk_rope_head_dim self.is_causal = True if self.q_lora_rank is None: self.q_proj = nn.Linear( self.hidden_size, self.num_heads * self.q_head_dim, bias=False ) else: self.q_a_proj = nn.Linear( self.hidden_size, config.q_lora_rank, bias=config.attention_bias ) self.q_a_layernorm = DeepseekV3RMSNorm(config.q_lora_rank) self.q_b_proj = nn.Linear( config.q_lora_rank, self.num_heads * self.q_head_dim, bias=False ) self.kv_a_proj_with_mqa = nn.Linear( self.hidden_size, config.kv_lora_rank + config.qk_rope_head_dim, bias=config.attention_bias, ) self.kv_a_layernorm = DeepseekV3RMSNorm(config.kv_lora_rank) self.kv_b_proj = nn.Linear( config.kv_lora_rank, self.num_heads * (self.q_head_dim - self.qk_rope_head_dim + self.v_head_dim), bias=False, ) self.o_proj = nn.Linear( self.num_heads * self.v_head_dim, self.hidden_size, bias=config.attention_bias, ) self._init_rope() self.softmax_scale = self.q_head_dim ** (-0.5) if self.config.rope_scaling is not None: mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0) scaling_factor = self.config.rope_scaling["factor"] if mscale_all_dim: mscale = yarn_get_mscale(scaling_factor, mscale_all_dim) self.softmax_scale = self.softmax_scale * mscale * mscale def _init_rope(self): if self.config.rope_scaling is None: self.rotary_emb = DeepseekV3RotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, base=self.rope_theta, ) else: scaling_type = self.config.rope_scaling["type"] scaling_factor = self.config.rope_scaling["factor"] if scaling_type == "linear": self.rotary_emb = DeepseekV3LinearScalingRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "dynamic": self.rotary_emb = DeepseekV3DynamicNTKScalingRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, ) elif scaling_type == "yarn": kwargs = { key: self.config.rope_scaling[key] for key in [ "original_max_position_embeddings", "beta_fast", "beta_slow", "mscale", "mscale_all_dim", ] if key in self.config.rope_scaling } self.rotary_emb = DeepseekV3YarnRotaryEmbedding( self.qk_rope_head_dim, max_position_embeddings=self.max_position_embeddings, scaling_factor=scaling_factor, base=self.rope_theta, **kwargs, ) else: raise ValueError(f"Unknown RoPE scaling type {scaling_type}") def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int): return ( tensor.view(bsz, seq_len, self.num_heads, self.v_head_dim) .transpose(1, 2) .contiguous() ) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) bsz, q_len, _ = hidden_states.size() if self.q_lora_rank is None: q = self.q_proj(hidden_states) else: q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2) q_nope, q_pe = torch.split( q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1 ) compressed_kv = self.kv_a_proj_with_mqa(hidden_states) compressed_kv, k_pe = torch.split( compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2) kv = ( self.kv_b_proj(self.kv_a_layernorm(compressed_kv)) .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) .transpose(1, 2) ) k_nope, value_states = torch.split( kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1 ) kv_seq_len = value_states.shape[-2] if past_key_value is not None: if self.layer_idx is None: raise ValueError( f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} " "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class " "with a layer index." ) kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids) query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) query_states[:, :, :, : self.qk_nope_head_dim] = q_nope query_states[:, :, :, self.qk_nope_head_dim :] = q_pe key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) key_states[:, :, :, : self.qk_nope_head_dim] = k_nope key_states[:, :, :, self.qk_nope_head_dim :] = k_pe if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs ) attn_weights = ( torch.matmul(query_states, key_states.transpose(2, 3)) * self.softmax_scale ) if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len): raise ValueError( f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is" f" {attn_weights.size()}" ) assert attention_mask is not None if attention_mask is not None: if attention_mask.size() != (bsz, 1, q_len, kv_seq_len): raise ValueError( f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}" ) attn_weights = attn_weights + attention_mask # upcast attention to fp32 attn_weights = nn.functional.softmax( attn_weights, dim=-1, dtype=torch.float32 ).to(query_states.dtype) attn_weights = nn.functional.dropout( attn_weights, p=self.attention_dropout, training=self.training ) attn_output = torch.matmul(attn_weights, value_states) if attn_output.size() != (bsz, self.num_heads, q_len, self.v_head_dim): raise ValueError( f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.v_head_dim)}, but is" f" {attn_output.size()}" ) attn_output = attn_output.transpose(1, 2).contiguous() attn_output = attn_output.reshape(bsz, q_len, self.num_heads * self.v_head_dim) attn_output = self.o_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2 with Llama->DeepseekV3 class DeepseekV3FlashAttention2(DeepseekV3Attention): """ DeepseekV3 flash attention module. This module inherits from `DeepseekV3Attention` as the weights of the module stays untouched. The only required change would be on the forward pass where it needs to correctly call the public API of flash attention and deal with padding tokens in case the input contains any of them. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1. # flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0. # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left). self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10() def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.LongTensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Cache] = None, output_attentions: bool = False, use_cache: bool = False, **kwargs, ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]: # DeepseekV3FlashAttention2 attention does not support output_attentions if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) # overwrite attention_mask with padding_mask attention_mask = kwargs.pop("padding_mask") output_attentions = False bsz, q_len, _ = hidden_states.size() if self.q_lora_rank is None: q = self.q_proj(hidden_states) else: q = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states))) q = q.view(bsz, q_len, self.num_heads, self.q_head_dim).transpose(1, 2) q_nope, q_pe = torch.split( q, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1 ) # Flash attention requires the input to have the shape # batch_size x seq_length x head_dim x hidden_dim # therefore we just need to keep the original shape compressed_kv = self.kv_a_proj_with_mqa(hidden_states) compressed_kv, k_pe = torch.split( compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1 ) k_pe = k_pe.view(bsz, q_len, 1, self.qk_rope_head_dim).transpose(1, 2) kv = ( self.kv_b_proj(self.kv_a_layernorm(compressed_kv)) .view(bsz, q_len, self.num_heads, self.qk_nope_head_dim + self.v_head_dim) .transpose(1, 2) ) k_nope, value_states = torch.split( kv, [self.qk_nope_head_dim, self.v_head_dim], dim=-1 ) kv_seq_len = value_states.shape[-2] kv_seq_len = value_states.shape[-2] if past_key_value is not None: kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx) cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len) q_pe, k_pe = apply_rotary_pos_emb(q_pe, k_pe, cos, sin, position_ids) query_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) query_states[:, :, :, : self.qk_nope_head_dim] = q_nope query_states[:, :, :, self.qk_nope_head_dim :] = q_pe key_states = k_pe.new_empty(bsz, self.num_heads, q_len, self.q_head_dim) key_states[:, :, :, : self.qk_nope_head_dim] = k_nope key_states[:, :, :, self.qk_nope_head_dim :] = k_pe if self.q_head_dim != self.v_head_dim: value_states = F.pad(value_states, [0, self.q_head_dim - self.v_head_dim]) if past_key_value is not None: cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models key_states, value_states = past_key_value.update( key_states, value_states, self.layer_idx, cache_kwargs ) # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache # to be able to avoid many of these transpose/reshape/view. query_states = query_states.transpose(1, 2) key_states = key_states.transpose(1, 2) value_states = value_states.transpose(1, 2) dropout_rate = self.attention_dropout if self.training else 0.0 # In PEFT, usually we cast the layer norms in float32 for training stability reasons # therefore the input hidden states gets silently casted in float32. Hence, we need # cast them back in the correct dtype just to be sure everything works as expected. # This might slowdown training & inference so it is recommended to not cast the LayerNorms # in fp32. (DeepseekV3RMSNorm handles it correctly) input_dtype = query_states.dtype if input_dtype == torch.float32: # Handle the case where the model is quantized if hasattr(self.config, "_pre_quantization_dtype"): target_dtype = self.config._pre_quantization_dtype elif torch.is_autocast_enabled(): target_dtype = torch.get_autocast_gpu_dtype() else: target_dtype = ( self.q_proj.weight.dtype if self.q_lora_rank is None else self.q_a_proj.weight.dtype ) logger.warning_once( f"The input hidden states seems to be silently casted in float32, this might be related to" f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in" f" {target_dtype}." ) query_states = query_states.to(target_dtype) key_states = key_states.to(target_dtype) value_states = value_states.to(target_dtype) attn_output = self._flash_attention_forward( query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate, softmax_scale=self.softmax_scale, ) if self.q_head_dim != self.v_head_dim: attn_output = attn_output[:, :, :, : self.v_head_dim] attn_output = attn_output.reshape( bsz, q_len, self.num_heads * self.v_head_dim ).contiguous() attn_output = self.o_proj(attn_output) if not output_attentions: attn_weights = None return attn_output, attn_weights, past_key_value def _flash_attention_forward( self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None, ): """ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token first unpad the input, then computes the attention scores and pad the final attention scores. Args: query_states (`torch.Tensor`): Input query states to be passed to Flash Attention API key_states (`torch.Tensor`): Input key states to be passed to Flash Attention API value_states (`torch.Tensor`): Input value states to be passed to Flash Attention API attention_mask (`torch.Tensor`): The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the position of padding tokens and 1 for the position of non-padding tokens. dropout (`int`, *optional*): Attention dropout softmax_scale (`float`, *optional*): The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim) """ if not self._flash_attn_uses_top_left_mask: causal = self.is_causal else: # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in DeepseekV3FlashAttention2 __init__. causal = self.is_causal and query_length != 1 # Contains at least one padding token in the sequence if attention_mask is not None: batch_size = query_states.shape[0] ( query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens, ) = self._upad_input( query_states, key_states, value_states, attention_mask, query_length ) cu_seqlens_q, cu_seqlens_k = cu_seq_lens max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens attn_output_unpad = flash_attn_varlen_func( query_states, key_states, value_states, cu_seqlens_q=cu_seqlens_q, cu_seqlens_k=cu_seqlens_k, max_seqlen_q=max_seqlen_in_batch_q, max_seqlen_k=max_seqlen_in_batch_k, dropout_p=dropout, softmax_scale=softmax_scale, causal=causal, ) attn_output = pad_input( attn_output_unpad, indices_q, batch_size, query_length ) else: attn_output = flash_attn_func( query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal, ) return attn_output def _upad_input( self, query_layer, key_layer, value_layer, attention_mask, query_length ): indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask) batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape key_layer = index_first_axis( key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k, ) value_layer = index_first_axis( value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k, ) if query_length == kv_seq_len: query_layer = index_first_axis( query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k, ) cu_seqlens_q = cu_seqlens_k max_seqlen_in_batch_q = max_seqlen_in_batch_k indices_q = indices_k elif query_length == 1: max_seqlen_in_batch_q = 1 cu_seqlens_q = torch.arange( batch_size + 1, dtype=torch.int32, device=query_layer.device ) # There is a memcpy here, that is very bad. indices_q = cu_seqlens_q[:-1] query_layer = query_layer.squeeze(1) else: # The -q_len: slice assumes left padding. attention_mask = attention_mask[:, -query_length:] query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input( query_layer, attention_mask ) return ( query_layer, key_layer, value_layer, indices_q, (cu_seqlens_q, cu_seqlens_k), (max_seqlen_in_batch_q, max_seqlen_in_batch_k), ) ATTENTION_CLASSES = { "eager": DeepseekV3Attention, "flash_attention_2": DeepseekV3FlashAttention2, } class DeepseekV3DecoderLayer(nn.Module): def __init__(self, config: DeepseekV3Config, layer_idx: int): super().__init__() self.hidden_size = config.hidden_size self.self_attn = ATTENTION_CLASSES[config._attn_implementation]( config=config, layer_idx=layer_idx ) self.mlp = ( DeepseekV3MoE(config) if ( config.n_routed_experts is not None and layer_idx >= config.first_k_dense_replace and layer_idx % config.moe_layer_freq == 0 ) else DeepseekV3MLP(config) ) self.input_layernorm = DeepseekV3RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) self.post_attention_layernorm = DeepseekV3RMSNorm( config.hidden_size, eps=config.rms_norm_eps ) def forward( self, hidden_states: torch.Tensor, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_value: Optional[Tuple[torch.Tensor]] = None, output_attentions: Optional[bool] = False, use_cache: Optional[bool] = False, **kwargs, ) -> Tuple[ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]] ]: """ Args: hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)` attention_mask (`torch.FloatTensor`, *optional*): attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1, query_sequence_length, key_sequence_length)` if default attention is used. output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states """ if "padding_mask" in kwargs: warnings.warn( "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`" ) residual = hidden_states hidden_states = self.input_layernorm(hidden_states) # Self Attention hidden_states, self_attn_weights, present_key_value = self.self_attn( hidden_states=hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_value, output_attentions=output_attentions, use_cache=use_cache, **kwargs, ) hidden_states = residual + hidden_states # Fully Connected residual = hidden_states hidden_states = self.post_attention_layernorm(hidden_states) hidden_states = self.mlp(hidden_states) hidden_states = residual + hidden_states outputs = (hidden_states,) if output_attentions: outputs += (self_attn_weights,) if use_cache: outputs += (present_key_value,) return outputs DeepseekV3_START_DOCSTRING = r""" This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads etc.) This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior. Parameters: config ([`DeepseekV3Config`]): Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights. """ @add_start_docstrings( "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.", DeepseekV3_START_DOCSTRING, ) class DeepseekV3PreTrainedModel(PreTrainedModel): config_class = DeepseekV3Config base_model_prefix = "model" supports_gradient_checkpointing = True _no_split_modules = ["DeepseekV3DecoderLayer"] _skip_keys_device_placement = "past_key_values" _supports_flash_attn_2 = True _supports_cache_class = True def _init_weights(self, module): std = self.config.initializer_range if isinstance(module, nn.Linear): module.weight.data.normal_(mean=0.0, std=std) if module.bias is not None: module.bias.data.zero_() elif isinstance(module, nn.Embedding): module.weight.data.normal_(mean=0.0, std=std) if module.padding_idx is not None: module.weight.data[module.padding_idx].zero_() DeepseekV3_INPUTS_DOCSTRING = r""" Args: input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. [What are input IDs?](../glossary#input-ids) attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*): Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`: - 1 for tokens that are **not masked**, - 0 for tokens that are **masked**. [What are attention masks?](../glossary#attention-mask) Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for details. If `past_key_values` is used, optionally only the last `input_ids` have to be input (see `past_key_values`). If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`] and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more information on the default strategy. - 1 indicates the head is **not masked**, - 0 indicates the head is **masked**. position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0, config.n_positions - 1]`. [What are position IDs?](../glossary#position-ids) past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*): Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`. Two formats are allowed: - a [`~cache_utils.Cache`] instance; - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy cache format. The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the legacy cache format will be returned. If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more control over how to convert `input_ids` indices into associated vectors than the model's internal embedding lookup matrix. use_cache (`bool`, *optional*): If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`). output_attentions (`bool`, *optional*): Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned tensors for more detail. output_hidden_states (`bool`, *optional*): Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for more detail. return_dict (`bool`, *optional*): Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple. """ @add_start_docstrings( "The bare DeepseekV3 Model outputting raw hidden-states without any specific head on top.", DeepseekV3_START_DOCSTRING, ) class DeepseekV3Model(DeepseekV3PreTrainedModel): """ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`DeepseekV3DecoderLayer`] Args: config: DeepseekV3Config """ def __init__(self, config: DeepseekV3Config): super().__init__(config) self.padding_idx = config.pad_token_id self.vocab_size = config.vocab_size self.embed_tokens = nn.Embedding( config.vocab_size, config.hidden_size, self.padding_idx ) self.layers = nn.ModuleList( [ DeepseekV3DecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers) ] ) self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2" self.norm = DeepseekV3RMSNorm(config.hidden_size, eps=config.rms_norm_eps) self.gradient_checkpointing = False # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.embed_tokens def set_input_embeddings(self, value): self.embed_tokens = value @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, BaseModelOutputWithPast]: output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) use_cache = use_cache if use_cache is not None else self.config.use_cache return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) # retrieve input_ids and inputs_embeds if input_ids is not None and inputs_embeds is not None: raise ValueError( "You cannot specify both input_ids and inputs_embeds at the same time" ) elif input_ids is not None: batch_size, seq_length = input_ids.shape[:2] elif inputs_embeds is not None: batch_size, seq_length = inputs_embeds.shape[:2] else: raise ValueError("You have to specify either input_ids or inputs_embeds") past_key_values_length = 0 if use_cache: use_legacy_cache = not isinstance(past_key_values, Cache) if use_legacy_cache: past_key_values = DynamicCache.from_legacy_cache(past_key_values) past_key_values_length = past_key_values.get_usable_length(seq_length) if position_ids is None: device = input_ids.device if input_ids is not None else inputs_embeds.device position_ids = torch.arange( past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device, ) position_ids = position_ids.unsqueeze(0) if inputs_embeds is None: inputs_embeds = self.embed_tokens(input_ids) if self._use_flash_attention_2: # 2d mask is passed through the layers attention_mask = ( attention_mask if (attention_mask is not None and 0 in attention_mask) else None ) else: # 4d mask is passed through the layers attention_mask = _prepare_4d_causal_attention_mask( attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length, ) # embed positions hidden_states = inputs_embeds # decoder layers all_hidden_states = () if output_hidden_states else None all_self_attns = () if output_attentions else None next_decoder_cache = None for decoder_layer in self.layers: if output_hidden_states: all_hidden_states += (hidden_states,) layer_outputs = decoder_layer( hidden_states, attention_mask=attention_mask, position_ids=position_ids, past_key_value=past_key_values, output_attentions=output_attentions, use_cache=use_cache, ) hidden_states = layer_outputs[0] if use_cache: next_decoder_cache = layer_outputs[2 if output_attentions else 1] if output_attentions: all_self_attns += (layer_outputs[1],) hidden_states = self.norm(hidden_states) # add hidden states from the last decoder layer if output_hidden_states: all_hidden_states += (hidden_states,) next_cache = None if use_cache: next_cache = ( next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache ) if not return_dict: return tuple( v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None ) return BaseModelOutputWithPast( last_hidden_state=hidden_states, past_key_values=next_cache, hidden_states=all_hidden_states, attentions=all_self_attns, ) class DeepseekV3ForCausalLM(DeepseekV3PreTrainedModel): _tied_weights_keys = ["lm_head.weight"] def __init__(self, config): super().__init__(config) self.model = DeepseekV3Model(config) self.vocab_size = config.vocab_size self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, value): self.model.embed_tokens = value def get_output_embeddings(self): return self.lm_head def set_output_embeddings(self, new_embeddings): self.lm_head = new_embeddings def set_decoder(self, decoder): self.model = decoder def get_decoder(self): return self.model @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING) @replace_return_docstrings( output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC ) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, CausalLMOutputWithPast]: r""" Args: labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*): Labels for computing the masked language modeling loss. Indices should either be in `[0, transformers., config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored (masked), the loss is only computed for the tokens with labels in `[0, transformers., config.vocab_size]`. Returns: Example: ```python >>> from transformers import AutoTokenizer, DeepseekV3ForCausalLM >>> model = DeepseekV3ForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS) >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER) >>> prompt = "Hey, are you conscious? Can you talk to me?" >>> inputs = tokenizer(prompt, return_tensors="pt") >>> # Generate >>> generate_ids = model.generate(inputs.input_ids, max_length=30) >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0] "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you." ```""" output_attentions = ( output_attentions if output_attentions is not None else self.config.output_attentions ) output_hidden_states = ( output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states ) return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn) outputs = self.model( input_ids=input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = outputs[0] logits = self.lm_head(hidden_states) logits = logits.float() loss = None if labels is not None: # Shift so that tokens < n predict n shift_logits = logits[..., :-1, :].contiguous() shift_labels = labels[..., 1:].contiguous() # Flatten the tokens loss_fct = CrossEntropyLoss() shift_logits = shift_logits.view(-1, self.config.vocab_size) shift_labels = shift_labels.view(-1) # Enable model parallelism shift_labels = shift_labels.to(shift_logits.device) loss = loss_fct(shift_logits, shift_labels) if not return_dict: output = (logits,) + outputs[1:] return (loss,) + output if loss is not None else output return CausalLMOutputWithPast( loss=loss, logits=logits, past_key_values=outputs.past_key_values, hidden_states=outputs.hidden_states, attentions=outputs.attentions, ) def prepare_inputs_for_generation( self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs, ): if past_key_values is not None: if isinstance(past_key_values, Cache): cache_length = past_key_values.get_seq_length() past_length = past_key_values.seen_tokens max_cache_length = past_key_values.get_max_length() else: cache_length = past_length = past_key_values[0][0].shape[2] max_cache_length = None # Keep only the unprocessed tokens: # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as # input) if ( attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1] ): input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :] # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard # input_ids based on the past_length. elif past_length < input_ids.shape[1]: input_ids = input_ids[:, past_length:] # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens. # If we are about to go beyond the maximum cache length, we need to crop the input attention mask. if ( max_cache_length is not None and attention_mask is not None and cache_length + input_ids.shape[1] > max_cache_length ): attention_mask = attention_mask[:, -max_cache_length:] position_ids = kwargs.get("position_ids", None) if attention_mask is not None and position_ids is None: # create position_ids on the fly for batch generation position_ids = attention_mask.long().cumsum(-1) - 1 position_ids.masked_fill_(attention_mask == 0, 1) if past_key_values: position_ids = position_ids[:, -input_ids.shape[1] :] # if `inputs_embeds` are passed, we only want to use them in the 1st generation step if inputs_embeds is not None and past_key_values is None: model_inputs = {"inputs_embeds": inputs_embeds} else: model_inputs = {"input_ids": input_ids} model_inputs.update( { "position_ids": position_ids, "past_key_values": past_key_values, "use_cache": kwargs.get("use_cache"), "attention_mask": attention_mask, } ) return model_inputs @staticmethod def _reorder_cache(past_key_values, beam_idx): reordered_past = () for layer_past in past_key_values: reordered_past += ( tuple( past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past ), ) return reordered_past @add_start_docstrings( """ The DeepseekV3 Model transformer with a sequence classification head on top (linear layer). [`DeepseekV3ForSequenceClassification`] uses the last token in order to do the classification, as other causal models (e.g. GPT-2) do. Since it does classification on the last token, it requires to know the position of the last token. If a `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in each row of the batch). """, DeepseekV3_START_DOCSTRING, ) class DeepseekV3ForSequenceClassification(DeepseekV3PreTrainedModel): def __init__(self, config): super().__init__(config) self.num_labels = config.num_labels self.model = DeepseekV3Model(config) self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False) # Initialize weights and apply final processing self.post_init() def get_input_embeddings(self): return self.model.embed_tokens def set_input_embeddings(self, value): self.model.embed_tokens = value @add_start_docstrings_to_model_forward(DeepseekV3_INPUTS_DOCSTRING) def forward( self, input_ids: torch.LongTensor = None, attention_mask: Optional[torch.Tensor] = None, position_ids: Optional[torch.LongTensor] = None, past_key_values: Optional[List[torch.FloatTensor]] = None, inputs_embeds: Optional[torch.FloatTensor] = None, labels: Optional[torch.LongTensor] = None, use_cache: Optional[bool] = None, output_attentions: Optional[bool] = None, output_hidden_states: Optional[bool] = None, return_dict: Optional[bool] = None, ) -> Union[Tuple, SequenceClassifierOutputWithPast]: r""" labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*): Labels for computing the sequence classification/regression loss. Indices should be in `[0, transformers., config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If `config.num_labels > 1` a classification loss is computed (Cross-Entropy). """ return_dict = ( return_dict if return_dict is not None else self.config.use_return_dict ) transformer_outputs = self.model( input_ids, attention_mask=attention_mask, position_ids=position_ids, past_key_values=past_key_values, inputs_embeds=inputs_embeds, use_cache=use_cache, output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, ) hidden_states = transformer_outputs[0] logits = self.score(hidden_states) if input_ids is not None: batch_size = input_ids.shape[0] else: batch_size = inputs_embeds.shape[0] if self.config.pad_token_id is None and batch_size != 1: raise ValueError( "Cannot handle batch sizes > 1 if no padding token is defined." ) if self.config.pad_token_id is None: sequence_lengths = -1 else: if input_ids is not None: sequence_lengths = ( torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1 ).to(logits.device) else: sequence_lengths = -1 pooled_logits = logits[ torch.arange(batch_size, device=logits.device), sequence_lengths ] loss = None if labels is not None: labels = labels.to(logits.device) if self.config.problem_type is None: if self.num_labels == 1: self.config.problem_type = "regression" elif self.num_labels > 1 and ( labels.dtype == torch.long or labels.dtype == torch.int ): self.config.problem_type = "single_label_classification" else: self.config.problem_type = "multi_label_classification" if self.config.problem_type == "regression": loss_fct = MSELoss() if self.num_labels == 1: loss = loss_fct(pooled_logits.squeeze(), labels.squeeze()) else: loss = loss_fct(pooled_logits, labels) elif self.config.problem_type == "single_label_classification": loss_fct = CrossEntropyLoss() loss = loss_fct( pooled_logits.view(-1, self.num_labels), labels.view(-1) ) elif self.config.problem_type == "multi_label_classification": loss_fct = BCEWithLogitsLoss() loss = loss_fct(pooled_logits, labels) if not return_dict: output = (pooled_logits,) + transformer_outputs[1:] return ((loss,) + output) if loss is not None else output return SequenceClassifierOutputWithPast( loss=loss, logits=pooled_logits, past_key_values=transformer_outputs.past_key_values, hidden_states=transformer_outputs.hidden_states, attentions=transformer_outputs.attentions, ) ================================================================================ 15.4 generation_config.json ================================================================================ { "_from_model_config": true, "bos_token_id": 0, "eos_token_id": 1, "do_sample": true, "temperature": 0.6, "top_p": 0.95, "transformers_version": "4.39.3" } ================================================================================ 15.5 tokenizer_config.json (the chat template is the long single-line "chat_template" value) ================================================================================ { "add_bos_token": true, "add_eos_token": false, "bos_token": { "__type": "AddedToken", "content": "<|begin▁of▁sentence|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "clean_up_tokenization_spaces": false, "eos_token": { "__type": "AddedToken", "content": "<|end▁of▁sentence|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "legacy": true, "model_max_length": 16384, "pad_token": { "__type": "AddedToken", "content": "<|end▁of▁sentence|>", "lstrip": false, "normalized": true, "rstrip": false, "single_word": false }, "sp_model_kwargs": {}, "unk_token": null, "tokenizer_class": "LlamaTokenizerFast", "chat_template": "{% if not add_generation_prompt is defined %}{% set add_generation_prompt = false %}{% endif %}{% set ns = namespace(is_first=false, is_tool=false, is_output_first=true, system_prompt='', is_first_sp=true) %}{%- for message in messages %}{%- if message['role'] == 'system' %}{%- if ns.is_first_sp %}{% set ns.system_prompt = ns.system_prompt + message['content'] %}{% set ns.is_first_sp = false %}{%- else %}{% set ns.system_prompt = ns.system_prompt + '\\n\\n' + message['content'] %}{%- endif %}{%- endif %}{%- endfor %}{{ bos_token }}{{ ns.system_prompt }}{%- for message in messages %}{%- if message['role'] == 'user' %}{%- set ns.is_tool = false -%}{{'<|User|>' + message['content']}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' in message %}{%- set ns.is_tool = false -%}{%- for tool in message['tool_calls'] %}{%- if not ns.is_first %}{%- if message['content'] is none %}{{'<|Assistant|><|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{%- else %}{{'<|Assistant|>' + message['content'] + '<|tool▁calls▁begin|><|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- set ns.is_first = true -%}{%- else %}{{'\\n' + '<|tool▁call▁begin|>' + tool['type'] + '<|tool▁sep|>' + tool['function']['name'] + '\\n' + '```json' + '\\n' + tool['function']['arguments'] + '\\n' + '```' + '<|tool▁call▁end|>'}}{%- endif %}{%- endfor %}{{'<|tool▁calls▁end|><|end▁of▁sentence|>'}}{%- endif %}{%- if message['role'] == 'assistant' and 'tool_calls' not in message %}{%- if ns.is_tool %}{{'<|tool▁outputs▁end|>' + message['content'] + '<|end▁of▁sentence|>'}}{%- set ns.is_tool = false -%}{%- else %}{% set content = message['content'] %}{% if '' in content %}{% set content = content.split('')[-1] %}{% endif %}{{'<|Assistant|>' + content + '<|end▁of▁sentence|>'}}{%- endif %}{%- endif %}{%- if message['role'] == 'tool' %}{%- set ns.is_tool = true -%}{%- if ns.is_output_first %}{{'<|tool▁outputs▁begin|><|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- set ns.is_output_first = false %}{%- else %}{{'<|tool▁output▁begin|>' + message['content'] + '<|tool▁output▁end|>'}}{%- endif %}{%- endif %}{%- endfor -%}{% if ns.is_tool %}{{'<|tool▁outputs▁end|>'}}{% endif %}{% if add_generation_prompt and not ns.is_tool %}{{'<|Assistant|>\\n'}}{% endif %}" } ================================================================================ 15.6 README.md (official model card) ================================================================================ --- license: mit library_name: transformers --- # DeepSeek-R1
DeepSeek-V3

Homepage Chat Hugging Face
Discord Wechat Twitter Follow
License

Paper Link👁️

## 1. Introduction We introduce our first-generation reasoning models, DeepSeek-R1-Zero and DeepSeek-R1. DeepSeek-R1-Zero, a model trained via large-scale reinforcement learning (RL) without supervised fine-tuning (SFT) as a preliminary step, demonstrated remarkable performance on reasoning. With RL, DeepSeek-R1-Zero naturally emerged with numerous powerful and interesting reasoning behaviors. However, DeepSeek-R1-Zero encounters challenges such as endless repetition, poor readability, and language mixing. To address these issues and further enhance reasoning performance, we introduce DeepSeek-R1, which incorporates cold-start data before RL. DeepSeek-R1 achieves performance comparable to OpenAI-o1 across math, code, and reasoning tasks. To support the research community, we have open-sourced DeepSeek-R1-Zero, DeepSeek-R1, and six dense models distilled from DeepSeek-R1 based on Llama and Qwen. DeepSeek-R1-Distill-Qwen-32B outperforms OpenAI-o1-mini across various benchmarks, achieving new state-of-the-art results for dense models. **NOTE: Before running DeepSeek-R1 series models locally, we kindly recommend reviewing the [Usage Recommendation](#usage-recommendations) section.**

## 2. Model Summary --- **Post-Training: Large-Scale Reinforcement Learning on the Base Model** - We directly apply reinforcement learning (RL) to the base model without relying on supervised fine-tuning (SFT) as a preliminary step. This approach allows the model to explore chain-of-thought (CoT) for solving complex problems, resulting in the development of DeepSeek-R1-Zero. DeepSeek-R1-Zero demonstrates capabilities such as self-verification, reflection, and generating long CoTs, marking a significant milestone for the research community. Notably, it is the first open research to validate that reasoning capabilities of LLMs can be incentivized purely through RL, without the need for SFT. This breakthrough paves the way for future advancements in this area. - We introduce our pipeline to develop DeepSeek-R1. The pipeline incorporates two RL stages aimed at discovering improved reasoning patterns and aligning with human preferences, as well as two SFT stages that serve as the seed for the model's reasoning and non-reasoning capabilities. We believe the pipeline will benefit the industry by creating better models. --- **Distillation: Smaller Models Can Be Powerful Too** - We demonstrate that the reasoning patterns of larger models can be distilled into smaller models, resulting in better performance compared to the reasoning patterns discovered through RL on small models. The open source DeepSeek-R1, as well as its API, will benefit the research community to distill better smaller models in the future. - Using the reasoning data generated by DeepSeek-R1, we fine-tuned several dense models that are widely used in the research community. The evaluation results demonstrate that the distilled smaller dense models perform exceptionally well on benchmarks. We open-source distilled 1.5B, 7B, 8B, 14B, 32B, and 70B checkpoints based on Qwen2.5 and Llama3 series to the community. ## 3. Model Downloads ### DeepSeek-R1 Models
| **Model** | **#Total Params** | **#Activated Params** | **Context Length** | **Download** | | :------------: | :------------: | :------------: | :------------: | :------------: | | DeepSeek-R1-Zero | 671B | 37B | 128K | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Zero) | | DeepSeek-R1 | 671B | 37B | 128K | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1) |
DeepSeek-R1-Zero & DeepSeek-R1 are trained based on DeepSeek-V3-Base. For more details regarding the model architecture, please refer to [DeepSeek-V3](https://github.com/deepseek-ai/DeepSeek-V3) repository. ### DeepSeek-R1-Distill Models
| **Model** | **Base Model** | **Download** | | :------------: | :------------: | :------------: | | DeepSeek-R1-Distill-Qwen-1.5B | [Qwen2.5-Math-1.5B](https://huggingface.co/Qwen/Qwen2.5-Math-1.5B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B) | | DeepSeek-R1-Distill-Qwen-7B | [Qwen2.5-Math-7B](https://huggingface.co/Qwen/Qwen2.5-Math-7B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-7B) | | DeepSeek-R1-Distill-Llama-8B | [Llama-3.1-8B](https://huggingface.co/meta-llama/Llama-3.1-8B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-8B) | | DeepSeek-R1-Distill-Qwen-14B | [Qwen2.5-14B](https://huggingface.co/Qwen/Qwen2.5-14B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-14B) | |DeepSeek-R1-Distill-Qwen-32B | [Qwen2.5-32B](https://huggingface.co/Qwen/Qwen2.5-32B) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Qwen-32B) | | DeepSeek-R1-Distill-Llama-70B | [Llama-3.3-70B-Instruct](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct) | [🤗 HuggingFace](https://huggingface.co/deepseek-ai/DeepSeek-R1-Distill-Llama-70B) |
DeepSeek-R1-Distill models are fine-tuned based on open-source models, using samples generated by DeepSeek-R1. We slightly change their configs and tokenizers. Please use our setting to run these models. ## 4. Evaluation Results ### DeepSeek-R1-Evaluation For all our models, the maximum generation length is set to 32,768 tokens. For benchmarks requiring sampling, we use a temperature of $0.6$, a top-p value of $0.95$, and generate 64 responses per query to estimate pass@1.
| Category | Benchmark (Metric) | Claude-3.5-Sonnet-1022 | GPT-4o 0513 | DeepSeek V3 | OpenAI o1-mini | OpenAI o1-1217 | DeepSeek R1 | |----------|-------------------|----------------------|------------|--------------|----------------|------------|--------------| | | Architecture | - | - | MoE | - | - | MoE | | | # Activated Params | - | - | 37B | - | - | 37B | | | # Total Params | - | - | 671B | - | - | 671B | | English | MMLU (Pass@1) | 88.3 | 87.2 | 88.5 | 85.2 | **91.8** | 90.8 | | | MMLU-Redux (EM) | 88.9 | 88.0 | 89.1 | 86.7 | - | **92.9** | | | MMLU-Pro (EM) | 78.0 | 72.6 | 75.9 | 80.3 | - | **84.0** | | | DROP (3-shot F1) | 88.3 | 83.7 | 91.6 | 83.9 | 90.2 | **92.2** | | | IF-Eval (Prompt Strict) | **86.5** | 84.3 | 86.1 | 84.8 | - | 83.3 | | | GPQA-Diamond (Pass@1) | 65.0 | 49.9 | 59.1 | 60.0 | **75.7** | 71.5 | | | SimpleQA (Correct) | 28.4 | 38.2 | 24.9 | 7.0 | **47.0** | 30.1 | | | FRAMES (Acc.) | 72.5 | 80.5 | 73.3 | 76.9 | - | **82.5** | | | AlpacaEval2.0 (LC-winrate) | 52.0 | 51.1 | 70.0 | 57.8 | - | **87.6** | | | ArenaHard (GPT-4-1106) | 85.2 | 80.4 | 85.5 | 92.0 | - | **92.3** | | Code | LiveCodeBench (Pass@1-COT) | 33.8 | 34.2 | - | 53.8 | 63.4 | **65.9** | | | Codeforces (Percentile) | 20.3 | 23.6 | 58.7 | 93.4 | **96.6** | 96.3 | | | Codeforces (Rating) | 717 | 759 | 1134 | 1820 | **2061** | 2029 | | | SWE Verified (Resolved) | **50.8** | 38.8 | 42.0 | 41.6 | 48.9 | 49.2 | | | Aider-Polyglot (Acc.) | 45.3 | 16.0 | 49.6 | 32.9 | **61.7** | 53.3 | | Math | AIME 2024 (Pass@1) | 16.0 | 9.3 | 39.2 | 63.6 | 79.2 | **79.8** | | | MATH-500 (Pass@1) | 78.3 | 74.6 | 90.2 | 90.0 | 96.4 | **97.3** | | | CNMO 2024 (Pass@1) | 13.1 | 10.8 | 43.2 | 67.6 | - | **78.8** | | Chinese | CLUEWSC (EM) | 85.4 | 87.9 | 90.9 | 89.9 | - | **92.8** | | | C-Eval (EM) | 76.7 | 76.0 | 86.5 | 68.9 | - | **91.8** | | | C-SimpleQA (Correct) | 55.4 | 58.7 | **68.0** | 40.3 | - | 63.7 |
### Distilled Model Evaluation
| Model | AIME 2024 pass@1 | AIME 2024 cons@64 | MATH-500 pass@1 | GPQA Diamond pass@1 | LiveCodeBench pass@1 | CodeForces rating | |------------------------------------------|------------------|-------------------|-----------------|----------------------|----------------------|-------------------| | GPT-4o-0513 | 9.3 | 13.4 | 74.6 | 49.9 | 32.9 | 759 | | Claude-3.5-Sonnet-1022 | 16.0 | 26.7 | 78.3 | 65.0 | 38.9 | 717 | | o1-mini | 63.6 | 80.0 | 90.0 | 60.0 | 53.8 | **1820** | | QwQ-32B-Preview | 44.0 | 60.0 | 90.6 | 54.5 | 41.9 | 1316 | | DeepSeek-R1-Distill-Qwen-1.5B | 28.9 | 52.7 | 83.9 | 33.8 | 16.9 | 954 | | DeepSeek-R1-Distill-Qwen-7B | 55.5 | 83.3 | 92.8 | 49.1 | 37.6 | 1189 | | DeepSeek-R1-Distill-Qwen-14B | 69.7 | 80.0 | 93.9 | 59.1 | 53.1 | 1481 | | DeepSeek-R1-Distill-Qwen-32B | **72.6** | 83.3 | 94.3 | 62.1 | 57.2 | 1691 | | DeepSeek-R1-Distill-Llama-8B | 50.4 | 80.0 | 89.1 | 49.0 | 39.6 | 1205 | | DeepSeek-R1-Distill-Llama-70B | 70.0 | **86.7** | **94.5** | **65.2** | **57.5** | 1633 |
## 5. Chat Website & API Platform You can chat with DeepSeek-R1 on DeepSeek's official website: [chat.deepseek.com](https://chat.deepseek.com), and switch on the button "DeepThink" We also provide OpenAI-Compatible API at DeepSeek Platform: [platform.deepseek.com](https://platform.deepseek.com/) ## 6. How to Run Locally ### DeepSeek-R1 Models Please visit [DeepSeek-V3](https://github.com/deepseek-ai/DeepSeek-V3) repo for more information about running DeepSeek-R1 locally. **NOTE: Hugging Face's Transformers has not been directly supported yet.** ### DeepSeek-R1-Distill Models DeepSeek-R1-Distill models can be utilized in the same manner as Qwen or Llama models. For instance, you can easily start a service using [vLLM](https://github.com/vllm-project/vllm): ```shell vllm serve deepseek-ai/DeepSeek-R1-Distill-Qwen-32B --tensor-parallel-size 2 --max-model-len 32768 --enforce-eager ``` You can also easily start a service using [SGLang](https://github.com/sgl-project/sglang) ```bash python3 -m sglang.launch_server --model deepseek-ai/DeepSeek-R1-Distill-Qwen-32B --trust-remote-code --tp 2 ``` ### Usage Recommendations **We recommend adhering to the following configurations when utilizing the DeepSeek-R1 series models, including benchmarking, to achieve the expected performance:** 1. Set the temperature within the range of 0.5-0.7 (0.6 is recommended) to prevent endless repetitions or incoherent outputs. 2. **Avoid adding a system prompt; all instructions should be contained within the user prompt.** 3. For mathematical problems, it is advisable to include a directive in your prompt such as: "Please reason step by step, and put your final answer within \boxed{}." 4. When evaluating model performance, it is recommended to conduct multiple tests and average the results. Additionally, we have observed that the DeepSeek-R1 series models tend to bypass thinking pattern (i.e., outputting "\\n\n\") when responding to certain queries, which can adversely affect the model's performance. **To ensure that the model engages in thorough reasoning, we recommend enforcing the model to initiate its response with "\\n" at the beginning of every output.** ## 7. License This code repository and the model weights are licensed under the [MIT License](https://github.com/deepseek-ai/DeepSeek-R1/blob/main/LICENSE). DeepSeek-R1 series support commercial use, allow for any modifications and derivative works, including, but not limited to, distillation for training other LLMs. Please note that: - DeepSeek-R1-Distill-Qwen-1.5B, DeepSeek-R1-Distill-Qwen-7B, DeepSeek-R1-Distill-Qwen-14B and DeepSeek-R1-Distill-Qwen-32B are derived from [Qwen-2.5 series](https://github.com/QwenLM/Qwen2.5), which are originally licensed under [Apache 2.0 License](https://huggingface.co/Qwen/Qwen2.5-1.5B/blob/main/LICENSE), and now finetuned with 800k samples curated with DeepSeek-R1. - DeepSeek-R1-Distill-Llama-8B is derived from Llama3.1-8B-Base and is originally licensed under [llama3.1 license](https://huggingface.co/meta-llama/Llama-3.1-8B/blob/main/LICENSE). - DeepSeek-R1-Distill-Llama-70B is derived from Llama3.3-70B-Instruct and is originally licensed under [llama3.3 license](https://huggingface.co/meta-llama/Llama-3.3-70B-Instruct/blob/main/LICENSE). ## 8. Citation ``` @misc{deepseekai2025deepseekr1incentivizingreasoningcapability, title={DeepSeek-R1: Incentivizing Reasoning Capability in LLMs via Reinforcement Learning}, author={DeepSeek-AI}, year={2025}, eprint={2501.12948}, archivePrefix={arXiv}, primaryClass={cs.CL}, url={https://arxiv.org/abs/2501.12948}, } ``` ## 9. Contact If you have any questions, please raise an issue or contact us at [[contact email redacted]]([contact email redacted]). ================================================================================ END OF DOCUMENT ================================================================================