A continuation of DEEPSEEK REQUIREMENTS.txt. The complete source identity, every recorded occurrence, and linked equations are on its first page.
Source transcript · continued
Download complete source text ↓5,339 lines · 244.9 KB
past_key_values=transformer_outputs.past_key_values,
hidden_states=transformer_outputs.hidden_states,
attentions=transformer_outputs.attentions,
)
================================================================================
C.4 generation_config.json (171 bytes)
================================================================================
{
"_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"
}
================================================================================
C.5 tokenizer_config.json (3,594 bytes)
================================================================================
{
"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 '</think>' in content %}{% set content = content.split('</think>')[-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|><think>\\n'}}{% endif %}"
}
================================================================================
C.6 tokenizer.json (7,847,602 bytes)
================================================================================
DELIVERED AS A SIDECAR FILE, not inline. See the note in B.1.
path /home/joseph/DeepSeek-R1/tokenizer.json
copy /home/joseph/deepseek-megamind-upload/deepseek/tokenizer.json
bytes 7,847,602
sha256 ecb6f9fc369894346f0511f4074ca75cee5cd5f3b06d02f1ba35fcd39f8e121d
inside 01-deepseek-source.tar.gz
STRUCTURE
top-level keys : version, truncation, padding, added_tokens, normalizer,
pre_tokenizer, post_processor, decoder, model
model.type : BPE
model.vocab : 128,000 entries, ids 0..127,999
model.merges : 127,741 merge rules
added_tokens : 818 entries (798 placeholders, 20 meaningful)
truncation : null padding : null
normalizer : {"type":"Sequence","normalizers":[]} -- EMPTY, no NFC/NFKC
pre_tokenizer : Sequence of three Split rules then ByteLevel
1. Regex \p{N}{1,3} Isolated
2. Regex [CJK + Hiragana + Katakana]+ Isolated
3. a large punctuation/letter/whitespace regex
post_processor : ByteLevel, add_prefix_space true, trim_offsets false
decoder : ByteLevel, add_prefix_space true, trim_offsets true
The 20 meaningful special tokens and their ids are enumerated in
DEEPSEEK_R1_COMPLETE.txt part 11.2 and summarized in B.9 of this document.
================================================================================
C.7 model.safetensors.index.json (8,898,324 bytes)
================================================================================
DELIVERED AS A SIDECAR FILE, not inline. See the note in B.1.
path /home/joseph/DeepSeek-R1/model.safetensors.index.json
copy /home/joseph/deepseek-megamind-upload/deepseek/model.safetensors.index.json
bytes 8,898,324
sha256 a2c5d238ab1e8301a117336e9797e0d3551cb8f6dc9dc787318b23d8f54c9248
inside 01-deepseek-source.tar.gz
STRUCTURE
top-level keys : ["metadata", "weight_map"]
metadata : {"total_size": 1369062772000}
weight_map : 91,991 entries, "<tensor name>": "model-000NN-of-000163.safetensors"
naming 163 distinct shards
example : "model.embed_tokens.weight" -> "model-00001-of-000163.safetensors"
WARNING: metadata.total_size (1,369,062,772,000 = 1.245 TiB) overstates the
real payload (688,574,839,360 = 641.29 GiB) by 1.99x, because the exporter
costed FP8 elements at two bytes each. Never size allocations from it.
deepseek_tensor_manifest.json (B.2) is strictly more useful than this file:
it carries dtype, full shape, absolute byte offset, byte length and the linked
scale tensor for all 91,991 tensors, none of which the index contains.
================================================================================
C.8 README.md — official model card (15,994 bytes)
================================================================================
---
license: mit
library_name: transformers
---
# DeepSeek-R1
<!-- markdownlint-disable first-line-h1 -->
<!-- markdownlint-disable html -->
<!-- markdownlint-disable no-duplicate-header -->
<div align="center">
<img src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/logo.svg?raw=true" width="60%" alt="DeepSeek-V3" />
</div>
<hr>
<div align="center" style="line-height: 1;">
<a href="https://www.deepseek.com/" target="_blank" style="margin: 2px;">
<img alt="Homepage" src="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/badge.svg?raw=true" style="display: inline-block; vertical-align: middle;"/>
</a>
<a href="https://chat.deepseek.com/" target="_blank" style="margin: 2px;">
<img alt="Chat" src="https://img.shields.io/badge/🤖%20Chat-DeepSeek%20R1-536af5?color=536af5&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
</a>
<a href="https://huggingface.co/deepseek-ai" target="_blank" style="margin: 2px;">
<img alt="Hugging Face" src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-DeepSeek%20AI-ffc107?color=ffc107&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
</a>
</div>
<div align="center" style="line-height: 1;">
<a href="https://discord.gg/Tc7c45Zzu5" target="_blank" style="margin: 2px;">
<img alt="Discord" src="https://img.shields.io/badge/Discord-DeepSeek%20AI-7289da?logo=discord&logoColor=white&color=7289da" style="display: inline-block; vertical-align: middle;"/>
</a>
<a href="https://github.com/deepseek-ai/DeepSeek-V2/blob/main/figures/qr.jpeg?raw=true" target="_blank" style="margin: 2px;">
<img alt="Wechat" src="https://img.shields.io/badge/WeChat-DeepSeek%20AI-brightgreen?logo=wechat&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
</a>
<a href="https://twitter.com/deepseek_ai" target="_blank" style="margin: 2px;">
<img alt="Twitter Follow" src="https://img.shields.io/badge/Twitter-deepseek_ai-white?logo=x&logoColor=white" style="display: inline-block; vertical-align: middle;"/>
</a>
</div>
<div align="center" style="line-height: 1;">
<a href="https://github.com/deepseek-ai/DeepSeek-R1/blob/main/LICENSE" style="margin: 2px;">
<img alt="License" src="https://img.shields.io/badge/License-MIT-f5de53?&color=f5de53" style="display: inline-block; vertical-align: middle;"/>
</a>
</div>
<p align="center">
<a href="https://github.com/deepseek-ai/DeepSeek-R1/blob/main/DeepSeek_R1.pdf"><b>Paper Link</b>👁️</a>
</p>
## 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.**
<p align="center">
<img width="80%" src="figures/benchmark.jpg">
</p>
## 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
<div align="center">
| **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) |
</div>
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
<div align="center">
| **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) |
</div>
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.
<div align="center">
| 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 |
</div>
### Distilled Model Evaluation
<div align="center">
| 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 |
</div>
## 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 "\<think\>\n\n\</think\>") 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 "\<think\>\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 [[author/contact email redacted]]([author/contact email redacted]).
================================================================================
C.9 LICENSE (1,064 bytes)
================================================================================
MIT License
Copyright (c) 2023 DeepSeek
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
================================================================================
C.10 .gitattributes (1,519 bytes)
================================================================================
*.7z filter=lfs diff=lfs merge=lfs -text
*.arrow filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.bz2 filter=lfs diff=lfs merge=lfs -text
*.ckpt filter=lfs diff=lfs merge=lfs -text
*.ftz filter=lfs diff=lfs merge=lfs -text
*.gz filter=lfs diff=lfs merge=lfs -text
*.h5 filter=lfs diff=lfs merge=lfs -text
*.joblib filter=lfs diff=lfs merge=lfs -text
*.lfs.* filter=lfs diff=lfs merge=lfs -text
*.mlmodel filter=lfs diff=lfs merge=lfs -text
*.model filter=lfs diff=lfs merge=lfs -text
*.msgpack filter=lfs diff=lfs merge=lfs -text
*.npy filter=lfs diff=lfs merge=lfs -text
*.npz filter=lfs diff=lfs merge=lfs -text
*.onnx filter=lfs diff=lfs merge=lfs -text
*.ot filter=lfs diff=lfs merge=lfs -text
*.parquet filter=lfs diff=lfs merge=lfs -text
*.pb filter=lfs diff=lfs merge=lfs -text
*.pickle filter=lfs diff=lfs merge=lfs -text
*.pkl filter=lfs diff=lfs merge=lfs -text
*.pt filter=lfs diff=lfs merge=lfs -text
*.pth filter=lfs diff=lfs merge=lfs -text
*.rar filter=lfs diff=lfs merge=lfs -text
*.safetensors filter=lfs diff=lfs merge=lfs -text
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
*.tar.* filter=lfs diff=lfs merge=lfs -text
*.tar filter=lfs diff=lfs merge=lfs -text
*.tflite filter=lfs diff=lfs merge=lfs -text
*.tgz filter=lfs diff=lfs merge=lfs -text
*.wasm filter=lfs diff=lfs merge=lfs -text
*.xz filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.zst filter=lfs diff=lfs merge=lfs -text
*tfevents* filter=lfs diff=lfs merge=lfs -text
================================================================================
C.11 SCANNER AND BENCHMARK SCRIPTS (all created for this work)
================================================================================
--------------------------------------------------------------------------------
C.11.1 download_r1.py (641 bytes)
--------------------------------------------------------------------------------
#!/usr/bin/env python3
import os, sys, traceback
print("=== download_r1 START pid",os.getpid(),"===",flush=True)
try:
from huggingface_hub import snapshot_download
print("import OK; calling snapshot_download (this resolves ~160 shards first)...",flush=True)
path=snapshot_download(
"deepseek-ai/DeepSeek-R1",
local_dir="/home/joseph/DeepSeek-R1",
ignore_patterns=["*.pth","*.gguf","original/*"],
max_workers=8,
)
print("=== DOWNLOAD COMPLETE ===",path,flush=True)
except SystemExit:
raise
except BaseException:
print("=== ERROR ===",flush=True); traceback.print_exc(); sys.exit(1)
--------------------------------------------------------------------------------
C.11.2 launch_r1.sh (590 bytes)
--------------------------------------------------------------------------------
#!/bin/bash
# Persistent R1 download: systemd unit as joseph, with joseph's hf path pinned so python finds it. Resumes prior 719MB.
sudo systemctl reset-failed r1full 2>/dev/null
sudo systemd-run --unit=r1full --uid=joseph --setenv=HOME=/home/joseph \
--setenv=PYTHONPATH=/home/joseph/.local/lib/python3.14/site-packages \
--working-directory=/home/joseph python3 /home/joseph/download_r1.py
sleep 25
echo "=== active: $(systemctl is-active r1full) ==="
sudo journalctl -u r1full --no-pager -n 5 --output=cat 2>/dev/null
echo "=== size ==="; du -sh /home/joseph/DeepSeek-R1 2>/dev/null
--------------------------------------------------------------------------------
C.11.3 dl_test.py (421 bytes)
--------------------------------------------------------------------------------
#!/usr/bin/env python3
import time, sys
from huggingface_hub import hf_hub_download
t=time.time()
try:
p=hf_hub_download("deepseek-ai/DeepSeek-R1","config.json",local_dir="/home/joseph/DeepSeek-R1")
print("GOT config.json ->",p,"in",round(time.time()-t,1),"s",flush=True)
import os; print("size:",os.path.getsize(p),"bytes")
except Exception as e:
print("ERROR:",type(e).__name__,str(e)[:300],flush=True)
--------------------------------------------------------------------------------
C.11.4 scan_headers.py (2349 bytes)
--------------------------------------------------------------------------------
import json, os, struct, collections, re, sys
D=os.path.expanduser("~/DeepSeek-R1")
files=sorted(f for f in os.listdir(D) if f.endswith(".safetensors"))
print("shards:",len(files))
tot_tensors=0; tot_bytes=0
dtype_ct=collections.Counter(); dtype_bytes=collections.Counter()
fam_ct=collections.Counter(); fam_bytes=collections.Counter(); fam_dtypes=collections.defaultdict(set)
shapes=collections.defaultdict(set)
layers=set(); allnames=[]
per_shard=[]
for fn in files:
p=os.path.join(D,fn)
with open(p,'rb') as fh:
n=struct.unpack('<Q',fh.read(8))[0]
hdr=json.loads(fh.read(n))
meta=hdr.pop("__metadata__",None)
per_shard.append((fn,len(hdr),os.path.getsize(p),meta))
for name,info in hdr.items():
tot_tensors+=1
dt=info["dtype"]; shp=info["shape"]; off=info["data_offsets"]
nb=off[1]-off[0]; tot_bytes+=nb
dtype_ct[dt]+=1; dtype_bytes[dt]+=nb
allnames.append(name)
m=re.match(r'model\.layers\.(\d+)\.(.*)',name)
if m:
layers.add(int(m.group(1)))
fam=re.sub(r'experts\.\d+','experts.N',m.group(2))
else:
fam=name
fam_ct[fam]+=1; fam_bytes[fam]+=nb; fam_dtypes[fam].add(dt)
shapes[fam].add(tuple(shp))
print("total_tensors:",tot_tensors)
print("total_tensor_bytes:",tot_bytes, round(tot_bytes/2**30,2),"GiB")
print("layers_seen:",min(layers),"..",max(layers),"count",len(layers))
print("\n=== DTYPES ===")
for d,c in dtype_ct.most_common():
print(f" {d:10s} count={c:8d} bytes={dtype_bytes[d]:15d} {dtype_bytes[d]/2**30:9.2f} GiB")
print("\n=== TENSOR FAMILIES (layer-indices collapsed) ===")
for f,c in sorted(fam_ct.items(), key=lambda kv:-fam_bytes[kv[0]]):
sh=sorted(shapes[f]); shs=str(sh[0]) if len(sh)==1 else f"{sh[0]}..{sh[-1]}({len(sh)} distinct)"
print(f" {f:62s} n={c:7d} {sorted(fam_dtypes[f])!s:22s} {fam_bytes[f]/2**30:8.3f} GiB shape={shs}")
print("\n=== SHARD SUMMARY (first 3, last 3) ===")
for fn,nt,sz,meta in per_shard[:3]+per_shard[-3:]:
print(f" {fn} tensors={nt} bytes={sz} meta={meta}")
print("\n=== NON-LAYER (global) TENSORS ===")
for nm in sorted(set(n for n in allnames if not n.startswith("model.layers."))):
print(" ",nm)
json.dump({"total_tensors":tot_tensors,"total_bytes":tot_bytes},open(os.path.expanduser("~/r1scan/summary.json"),"w"))
--------------------------------------------------------------------------------
C.11.5 per_layer_manifest.py (1336 bytes)
--------------------------------------------------------------------------------
import json,os,struct,re
D=os.path.expanduser("~/DeepSeek-R1")
want={"model.layers.0.","model.layers.3.","model.layers.61."}
got={}
for fn in sorted(f for f in os.listdir(D) if f.endswith(".safetensors")):
with open(os.path.join(D,fn),'rb') as f:
n=struct.unpack('<Q',f.read(8))[0]; h=json.loads(f.read(n))
h.pop("__metadata__",None)
for k,v in h.items():
if any(k.startswith(w) for w in want): got[k]=(v,fn)
def show(pref,title):
print("###",title)
ks=[k for k in got if k.startswith(pref) and not re.search(r'experts\.\d+\.',k)]
tot=0
for k in sorted(ks):
v,fn=got[k]; o=v["data_offsets"]; b=o[1]-o[0]; tot+=b
print(f" {v['dtype']:8s} {str(v['shape']):18s} {b:>13,} B {k[len(pref):]}")
ne=sorted(set(int(m.group(1)) for k in got if k.startswith(pref) and (m:=re.search(r'experts\.(\d+)\.',k))))
print(f" --- non-expert subtotal: {tot:,} B = {tot/2**20:.1f} MiB ({len(ks)} tensors)")
if ne: print(f" --- plus routed experts {min(ne)}..{max(ne)} ({len(ne)} of them) x 6 tensors = {len(ne)*44050944:,} B")
print()
show("model.layers.0.","LAYER 0 - DENSE LAYER (also layers 1,2) - COMPLETE MANIFEST")
show("model.layers.3.","LAYER 3 - MoE LAYER (also layers 4..60) - COMPLETE MANIFEST")
show("model.layers.61.","LAYER 61 - MTP LAYER - COMPLETE MANIFEST")
--------------------------------------------------------------------------------
C.11.6 bench_ssd.sh (1473 bytes)
--------------------------------------------------------------------------------
#!/bin/bash
# bench_ssd.sh -- drive diagnosis for the expert-streaming read path.
# Decides whether to fan reads out (concurrency headroom) or cut seeks.
D=~/DeepSeek-R1
echo "--- single stream, 8 MiB blocks, 2 GiB ---"
[REDACTED: credential-associated original line 3561; original retained outside this bundle.]
dd if=$D/model-00080-of-000163.safetensors of=/dev/null bs=8M count=256 2>&1 | tail -1
echo "--- same file again (page-cache warm) ---"
dd if=$D/model-00080-of-000163.safetensors of=/dev/null bs=8M count=256 2>&1 | tail -1
echo "--- 4 parallel streams, 4 different shards, 512 MiB each ---"
S=$(date +%s.%N)
for n in 81 82 83 84; do dd if=$D/model-000$n-of-000163.safetensors of=/dev/null bs=8M count=64 2>/dev/null & done; wait
E=$(date +%s.%N)
echo "4x512MiB = 2048 MiB in $(echo "$E-$S"|bc)s -> $(echo "scale=1;2048/($E-$S)"|bc) MB/s aggregate"
echo "--- 56 scattered 4 MiB preads (per-expert scatter simulation) ---"
python3 - <<'PY'
import os,time,random
p=os.path.expanduser("~/DeepSeek-R1/model-00085-of-000163.safetensors")
sz=os.path.getsize(p); fd=os.open(p,os.O_RDONLY); random.seed(7)
t=time.time(); tot=0
for _ in range(56):
off=random.randrange(0,sz-4*1024*1024)
tot+=len(os.pread(fd,4*1024*1024,off))
d=time.time()-t
print(f" 56 scattered 4MiB preads: {tot/2**20:.0f} MiB in {d:.2f}s -> {tot/2**20/d:.0f} MB/s")
os.close(fd)
PY
echo "--- device ---"; df -h ~/DeepSeek-R1 | tail -1; lsblk 2>/dev/null | head -6
--------------------------------------------------------------------------------
C.11.7 map_shards_to_layers.py (1015 bytes)
--------------------------------------------------------------------------------
import json,os,struct,re,collections
D=os.path.expanduser("~/DeepSeek-R1")
idx=json.load(open(os.path.join(D,"model.safetensors.index.json")))
wm=idx["weight_map"]
print("### INDEX.JSON STRUCTURE")
print(" top-level keys:",list(idx.keys()))
print(" metadata:",idx["metadata"])
k0=next(iter(wm)); print(" weight_map sample: %r -> %r"%(k0,wm[k0]))
print()
print("### SHARD -> LAYER MAP")
sl=collections.defaultdict(set); glob=collections.defaultdict(list)
for name,sh in wm.items():
m=re.match(r'model\.layers\.(\d+)\.',name)
if m: sl[sh].add(int(m.group(1)))
else: glob[sh].append(name)
rows=[]
for sh in sorted(set(wm.values())):
ls=sorted(sl.get(sh,[]))
lay = "-" if not ls else (str(ls[0]) if len(ls)==1 else f"{ls[0]}-{ls[-1]}")
rows.append((int(sh.split('-')[1]), lay, len([k for k,v in wm.items() if v==sh]), ",".join(glob.get(sh,[])) ))
# compress runs
print(" shard layers tensors non-layer tensors")
for n,lay,ct,g in rows:
print(f" {n:>5} {lay:<10} {ct:>7} {g}")
--------------------------------------------------------------------------------
C.11.8 verify_integrity.py (1310 bytes)
--------------------------------------------------------------------------------
import json,os,struct,collections,re
D=os.path.expanduser("~/DeepSeek-R1")
idx=json.load(open(os.path.join(D,"model.safetensors.index.json")))
wm=idx["weight_map"]; meta=idx.get("metadata",{})
print("index metadata:",meta)
print("index weight_map entries:",len(wm))
print("index distinct shards:",len(set(wm.values())))
hdrnames={}; bad=[]
files=sorted(f for f in os.listdir(D) if f.endswith(".safetensors"))
for fn in files:
p=os.path.join(D,fn); sz=os.path.getsize(p)
with open(p,'rb') as fh:
n=struct.unpack('<Q',fh.read(8))[0]; hdr=json.loads(fh.read(n))
hdr.pop("__metadata__",None)
end=max(v["data_offsets"][1] for v in hdr.values())
expect=8+n+end
if expect!=sz: bad.append((fn,sz,expect,sz-expect))
for k in hdr: hdrnames[k]=fn
print("\nTRUNCATION/LENGTH CHECK (header+data vs filesize):")
print(" mismatched shards:",len(bad))
for b in bad[:10]: print(" ",b)
sh=set(hdrnames); si=set(wm)
print("\nINDEX vs HEADERS:")
print(" in headers not in index:",len(sh-si))
for x in list(sh-si)[:10]: print(" ",x)
print(" in index not in headers:",len(si-sh))
for x in list(si-sh)[:10]: print(" ",x)
mis=[k for k in si&sh if wm[k]!=hdrnames[k]]
print(" shard-placement mismatches:",len(mis))
print("\nTOTAL from index metadata total_size:",meta.get("total_size"))
--------------------------------------------------------------------------------
C.11.9 check_expert_contiguity.py (1459 bytes)
--------------------------------------------------------------------------------
import json,os,struct,re
D=os.path.expanduser("~/DeepSeek-R1")
fn="model-00080-of-000163.safetensors"
p=os.path.join(D,fn)
with open(p,'rb') as fh:
n=struct.unpack('<Q',fh.read(8))[0]; hdr=json.loads(fh.read(n))
hdr.pop("__metadata__",None)
items=sorted(hdr.items(), key=lambda kv: kv[1]["data_offsets"][0])
print("shard:",fn,"tensors:",len(items),"header_bytes:",n)
print("\nfirst 14 tensors in ON-DISK order:")
for k,v in items[:14]:
o=v["data_offsets"]; print(f" {o[0]:>12} .. {o[1]:>12} {o[1]-o[0]:>10} {v['dtype']:8s} {str(v['shape']):16s} {k}")
# check: are an expert's 3 weights + 3 scales contiguous?
import collections
byexp=collections.defaultdict(list)
for k,v in items:
m=re.match(r'model\.layers\.(\d+)\.mlp\.experts\.(\d+)\.',k)
if m: byexp[(int(m.group(1)),int(m.group(2)))].append((v["data_offsets"],k))
print("\nexperts in this shard:",len(byexp))
contig=0; noncontig=0; spans=[]
for key,lst in byexp.items():
lst.sort(); lo=lst[0][0][0]; hi=max(o[1] for o,_ in lst)
used=sum(o[1]-o[0] for o,_ in lst)
spans.append(hi-lo)
if hi-lo==used: contig+=1
else: noncontig+=1
print(f" fully contiguous experts: {contig} with gaps: {noncontig}")
print(f" expert span bytes: min={min(spans)} max={max(spans)} (payload/expert = {used})")
k0=sorted(byexp)[0]
print(f"\n layout of one expert {k0}:")
for o,k in sorted(byexp[k0]): print(f" {o[0]:>12} .. {o[1]:>12} ({o[1]-o[0]:>9}) {k.split('experts.')[1]}")
--------------------------------------------------------------------------------
C.11.10 gen_manifests.py (5475 bytes)
--------------------------------------------------------------------------------
#!/usr/bin/env python3
"""
gen_manifests.py -- produce the five machine-readable manifests for DeepSeek-R1.
Reads ONLY the safetensors JSON headers (never the weight payload), so it is
fast and touches ~13 MB of the 643 GB checkpoint.
Outputs (into OUT):
deepseek_tensor_manifest.json every tensor: shard, dtype, shape, absolute
offset, byte length, linked scale tensor
deepseek_shard_headers.json per-shard container geometry
deepseek_layer_shard_map.json layer index -> shards, and shard -> layers
deepseek_expert_offset_map.json (layer,expert) -> one contiguous read
deepseek_weight_hashes.txt sizes + partial hashes (see gen_hashes.py
for the full SHA-256 pass)
"""
import json, os, struct, re, collections, hashlib, sys
D = os.path.expanduser("~/DeepSeek-R1")
OUT = os.path.expanduser("~/deepseek-megamind-upload/deepseek")
os.makedirs(OUT, exist_ok=True)
files = sorted(f for f in os.listdir(D) if f.endswith(".safetensors"))
assert len(files) == 163, f"expected 163 shards, found {len(files)}"
tensors = {} # name -> record
shard_hdrs = []
for fn in files:
path = os.path.join(D, fn)
size = os.path.getsize(path)
with open(path, "rb") as fh:
hdr_len = struct.unpack("<Q", fh.read(8))[0]
hdr = json.loads(fh.read(hdr_len))
meta = hdr.pop("__metadata__", None)
data_start = 8 + hdr_len
payload_end = max(v["data_offsets"][1] for v in hdr.values())
shard_hdrs.append({
"shard": fn,
"file_size": size,
"header_len": hdr_len,
"data_start": data_start,
"tensor_count": len(hdr),
"payload_bytes": payload_end,
"metadata": meta,
"length_check_ok": (data_start + payload_end) == size,
})
for name, info in hdr.items():
rel = info["data_offsets"]
tensors[name] = {
"name": name,
"shard": fn,
"dtype": info["dtype"],
"shape": info["shape"],
"absolute_offset": data_start + rel[0],
"byte_length": rel[1] - rel[0],
"relative_offset": rel[0],
"scale_tensor": None,
}
# link each quantized weight to its scale tensor
for name, rec in tensors.items():
if rec["dtype"] == "F8_E4M3" and name.endswith(".weight"):
cand = name[: -len(".weight")] + ".weight_scale_inv"
if cand in tensors:
rec["scale_tensor"] = cand
manifest = [tensors[k] for k in sorted(tensors)]
json.dump(manifest, open(os.path.join(OUT, "deepseek_tensor_manifest.json"), "w"), indent=1)
json.dump(shard_hdrs, open(os.path.join(OUT, "deepseek_shard_headers.json"), "w"), indent=1)
# layer <-> shard maps
l2s = collections.defaultdict(set); s2l = collections.defaultdict(set)
globals_ = collections.defaultdict(list)
for name, rec in tensors.items():
m = re.match(r"model\.layers\.(\d+)\.", name)
if m:
li = int(m.group(1)); l2s[li].add(rec["shard"]); s2l[rec["shard"]].add(li)
else:
globals_[rec["shard"]].append(name)
lmap = {
"layer_to_shards": {str(k): sorted(v) for k, v in sorted(l2s.items())},
"shard_to_layers": {k: sorted(v) for k, v in sorted(s2l.items())},
"global_tensors_by_shard": {k: sorted(v) for k, v in sorted(globals_.items())},
"notes": {
"dense_layers": [0, 1, 2],
"moe_layers": list(range(3, 61)),
"mtp_layer": 61,
"base_inference_layers": list(range(0, 61)),
},
}
json.dump(lmap, open(os.path.join(OUT, "deepseek_layer_shard_map.json"), "w"), indent=1)
# expert offset map: one contiguous read per expert where possible
experts = collections.defaultdict(list)
for name, rec in tensors.items():
m = re.match(r"model\.layers\.(\d+)\.mlp\.experts\.(\d+)\.", name)
if m:
experts[(int(m.group(1)), int(m.group(2)))].append(rec)
emap = {}
straddlers = 0
for (li, ei), recs in sorted(experts.items()):
by_shard = collections.defaultdict(list)
for r in recs:
by_shard[r["shard"]].append(r)
reads = []
for sh in sorted(by_shard):
rs = sorted(by_shard[sh], key=lambda r: r["absolute_offset"])
lo = rs[0]["absolute_offset"]
hi = max(r["absolute_offset"] + r["byte_length"] for r in rs)
used = sum(r["byte_length"] for r in rs)
reads.append({
"shard": sh, "offset": lo, "length": hi - lo,
"contiguous": (hi - lo) == used,
"tensors": [r["name"].split("experts.%d." % ei)[1] for r in rs],
})
if len(reads) > 1:
straddlers += 1
emap["%d/%d" % (li, ei)] = {
"layer": li, "expert": ei,
"total_bytes": sum(r["byte_length"] for r in recs),
"read_count": len(reads),
"reads": reads,
}
json.dump({"straddling_experts": straddlers,
"expert_count": len(emap),
"bytes_per_expert_nominal": 44050944,
"experts": emap},
open(os.path.join(OUT, "deepseek_expert_offset_map.json"), "w"), indent=1)
print("tensors:", len(manifest))
print("shards:", len(shard_hdrs), "all length checks ok:",
all(s["length_check_ok"] for s in shard_hdrs))
print("experts:", len(emap), "straddling shard boundaries:", straddlers)
for f in ["deepseek_tensor_manifest.json","deepseek_shard_headers.json",
"deepseek_layer_shard_map.json","deepseek_expert_offset_map.json"]:
print(" wrote %-38s %12d B" % (f, os.path.getsize(os.path.join(OUT,f))))
--------------------------------------------------------------------------------
C.11.11 gen_hashes.py (2523 bytes)
--------------------------------------------------------------------------------
#!/usr/bin/env python3
"""
gen_hashes.py -- checkpoint integrity hashes.
--partial (default) size + SHA-256 of the first 1 MiB, last 1 MiB, and the
1 MiB at the midpoint of each shard. Reads 489 MiB total,
finishes in about a second. Enough to detect truncation,
a swapped shard, or a corrupted head/tail.
--full SHA-256 over every byte of all 163 shards. Reads the whole
643 GB. At the measured 507 MB/s single-stream rate on
this machine that is roughly 22 minutes of I/O plus hash
time. Required before any "verified" claim.
Output: deepseek_weight_hashes.txt (sorted, one shard per stanza)
"""
import os, sys, hashlib, time
D = os.path.expanduser("~/DeepSeek-R1")
OUT = os.path.expanduser("~/deepseek-megamind-upload/deepseek/deepseek_weight_hashes.txt")
MODE = "--full" if "--full" in sys.argv else "--partial"
CH = 1 << 20
files = sorted(f for f in os.listdir(D) if f.endswith(".safetensors"))
t0 = time.time()
with open(OUT, "w") as out:
out.write("# DeepSeek-R1 checkpoint hashes\n")
out.write("# mode: %s\n" % MODE)
out.write("# generated: %s\n" % time.strftime("%Y-%m-%dT%H:%M:%S%z"))
out.write("# source: %s\n#\n" % D)
total = 0
for fn in files:
p = os.path.join(D, fn); sz = os.path.getsize(p); total += sz
if MODE == "--full":
h = hashlib.sha256()
with open(p, "rb") as fh:
while True:
b = fh.read(1 << 22)
if not b: break
h.update(b)
out.write("%s\n size %d\n sha256 %s\n" % (fn, sz, h.hexdigest()))
else:
def part(off, n):
with open(p, "rb") as fh:
fh.seek(off); return hashlib.sha256(fh.read(n)).hexdigest()
out.write("%s\n size %d\n" % (fn, sz))
out.write(" sha256_head %s (bytes 0..%d)\n" % (part(0, CH), CH))
mid = (sz // 2) - (CH // 2)
out.write(" sha256_middle %s (bytes %d..%d)\n" % (part(mid, CH), mid, mid + CH))
out.write(" sha256_tail %s (bytes %d..%d)\n" % (part(max(0, sz - CH), CH), max(0, sz - CH), sz))
out.flush()
out.write("#\n# shards: %d\n# total bytes: %d\n# elapsed: %.1fs\n"
% (len(files), total, time.time() - t0))
print("wrote", OUT, os.path.getsize(OUT), "B in %.1fs" % (time.time() - t0))
================================================================================
C.12 WSL CONFIGURATION
================================================================================
--- C.12.1 /etc/wsl.conf (inside the WSL2 guest) ---
[boot]
systemd=true
[network]
generateResolvConf=true
--- C.12.2 C:\Users\Josep\.wslconfig (Windows host) ---
[wsl2]
memory=26GB
processors=12
vmIdleTimeout=-1
swap=8GB
================================================================================
C.13 SYSTEMD UNIT FILES (all 51, credential redacted in mm-loom.service)
================================================================================
--------------------------------------------------------------------------------
mm-api.service
--------------------------------------------------------------------------------
[Unit]
Description=missionMATCH API on megamind-agi (per tenant routing, control plane on 5433)
After=network-online.target [author/contact email redacted]
Wants=network-online.target
[Service]
Type=simple
# Root owned 0600, read by systemd rather than by the service user, so the process never needs
# permission to read the credentials it is handed.
EnvironmentFile=/etc/missionmatch/api.env
ExecStart=/opt/missionmatch/mm-api
Restart=on-failure
RestartSec=5
DynamicUser=yes
NoNewPrivileges=yes
PrivateTmp=yes
ProtectSystem=strict
ProtectHome=yes
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-boot.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI boot supervisor
After=postgresql.service
Wants=postgresql.service
[Service]
Type=oneshot
ExecStart=/opt/mm/bin/mmboot
RemainAfterExit=yes
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-cap.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI capability manifest
After=network-online.target postgresql.service
[Service]
Type=oneshot
ExecStart=/opt/mm/bin/mmcap
--------------------------------------------------------------------------------
mm-cap.timer
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI manifest every 60s
[Timer]
OnBootSec=45
OnUnitActiveSec=60
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-cp-backup.service
--------------------------------------------------------------------------------
[Unit]
Description=missionMATCH control plane backup, dumped here and pushed to Bubbles
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/mm-cp-backup.sh
User=root
Group=root
Nice=10
--------------------------------------------------------------------------------
mm-cp-backup.timer
--------------------------------------------------------------------------------
[Unit]
Description=Nightly missionMATCH control plane backup push
[Timer]
# 02:45, twenty minutes BEFORE the Bubbles job at 03:05, so the dump has arrived to be ingested.
OnCalendar=*-*-* 02:45:00
Persistent=true
RandomizedDelaySec=120
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-durability.service
--------------------------------------------------------------------------------
[Unit]
Description=PANTHEON two-device durability (M4 <-> cortex)
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/opt/mm/backup/durability.sh
--------------------------------------------------------------------------------
mm-durability.timer
--------------------------------------------------------------------------------
[Unit]
Description=Nightly PANTHEON durability backup
[Timer]
OnCalendar=*-*-* 03:30:00
Persistent=true
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-eval.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI substrate eval harness
After=postgresql.service
[Service]
Type=oneshot
ExecStart=/opt/mm/bin/mmeval
--------------------------------------------------------------------------------
mm-eval.timer
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI hourly substrate quality eval
[Timer]
OnBootSec=300
OnUnitActiveSec=3600
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-eye.service
--------------------------------------------------------------------------------
[Unit]
Description=EYE - Eye of the World, PANTHEON binary VSA world-brain
After=postgresql.service network.target
[Service]
Type=simple
User=postgres
Environment=EYE_PORT=9404
Environment=EYE_HEARTBEAT_SEC=12
Environment="EYE_DB=host=/var/run/postgresql dbname=livingworld"
ExecStart=/opt/mm/bin/eye
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-game-reflect.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND game reflection tick
[Service]
Type=oneshot
ExecStart=/usr/bin/curl -s --max-time 60 http://127.0.0.1:9097/game/tick?min=4
--------------------------------------------------------------------------------
mm-game-reflect.timer
--------------------------------------------------------------------------------
[Unit]
Description=Reflect active NPCs every 30 min
[Timer]
OnBootSec=15min
OnUnitActiveSec=30min
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-game.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND binary Game Memory API (mmgame :9097)
After=network.target postgresql.service mm-serve.service
[Service]
Type=simple
ExecStart=/opt/mm/bin/mmgame
Restart=always
RestartSec=5
WorkingDirectory=/opt/mm
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-gate.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI anti-degeneracy gate
After=mm-serve.service
[Service]
Type=oneshot
ExecStart=/opt/mm/bin/mmgate
--------------------------------------------------------------------------------
mm-gate.timer
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI degeneracy check every 5min
[Timer]
OnBootSec=120
OnUnitActiveSec=300
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-genserve.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI P20 binary generator (mmpredict serve, :9098)
After=network.target postgresql.service
[Service]
Type=simple
ExecStart=/opt/mm/bin/mmpredict serve
Restart=always
RestartSec=5
WorkingDirectory=/opt/mm
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-heart.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI mesh heartbeat
After=network-online.target
[Service]
Type=oneshot
ExecStart=/opt/mm/bin/mmheart
--------------------------------------------------------------------------------
mm-heart.timer
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI heartbeat every 15s
[Timer]
OnBootSec=30
OnUnitActiveSec=15
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-identity-sync.service
--------------------------------------------------------------------------------
[Unit]
Description=missionMATCH identity sync, control plane to every active tenant
After=network-online.target
Wants=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/mm-identity-sync.sh
User=root
Group=root
Nice=10
--------------------------------------------------------------------------------
mm-identity-sync.timer
--------------------------------------------------------------------------------
[Unit]
Description=Hourly missionMATCH identity sync
[Timer]
# Hourly, because the drift it corrects appears whenever an invite is accepted or a role changes, and a
# daily cadence would leave a new user invisible to tenant foreign keys for most of a working day.
OnCalendar=hourly
Persistent=true
RandomizedDelaySec=300
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-keepalive.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND WSL instance keepalive (holds the WSL2 instance against the hardcoded idle timer)
After=multi-user.target
[Service]
Type=exec
ExecStart=/usr/bin/sleep infinity
Restart=always
RestartSec=1
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-loom.service
--------------------------------------------------------------------------------
[Unit]
Description=The Loom - Living World orchestration organ
After=network.target mm-eye.service
[Service]
[REDACTED: credential-associated original line 4196; original retained outside this bundle.]
Environment=LOOM_PORT=9410
ExecStart=/opt/mm/bin/loom
Restart=always
RestartSec=3
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-narrate.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND narrator
After=network.target
[Service]
ExecStart=/opt/mm/bin/mm-narrate
Restart=always
User=root
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-offsite-watch.service
--------------------------------------------------------------------------------
[Unit]
Description=missionMATCH watch from OFF Bubbles (cross node vantage, not external)
After=network-online.target
[Service]
Type=oneshot
ExecStart=/usr/local/sbin/mm-offsite-watch.sh
--------------------------------------------------------------------------------
mm-offsite-watch.timer
--------------------------------------------------------------------------------
[Unit]
Description=run the off Bubbles watch every five minutes
[Timer]
OnBootSec=3min
OnUnitActiveSec=5min
AccuracySec=30s
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-oracle.service
--------------------------------------------------------------------------------
[Unit]
Description=ORACLE - MEGAMIND binary VSA reasoning organ (16 powers, WAL-persistent)
After=network.target
[Service]
Type=simple
WorkingDirectory=/opt/mm/oracle
ExecStart=/opt/mm/bin/oracle
Restart=always
RestartSec=2
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-sem.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND shared contextual semantic embedder (mmsem :9096)
After=network.target
[Service]
Type=simple
ExecStart=/opt/mm/bin/mmsem
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm-serve.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI 512-bit recall service
After=postgresql.service
Wants=postgresql.service
PartOf=mm.target
[Service]
ExecStart=/opt/mm/bin/mmserve
Restart=on-failure
RestartSec=5
KillSignal=SIGTERM
TimeoutStopSec=120
[Install]
WantedBy=multi-user.target mm.target
--------------------------------------------------------------------------------
mm-shard.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI federated recall shard
After=mm-serve.service network-online.target
Wants=mm-serve.service
PartOf=mm.target
[Service]
ExecStart=/opt/mm/bin/mmshard
Restart=on-failure
RestartSec=5
[Install]
WantedBy=multi-user.target mm.target
--------------------------------------------------------------------------------
mm-wal-compact.service
--------------------------------------------------------------------------------
[Unit]
Description=ORACLE WAL compaction (keep restarts fast)
[Service]
Type=oneshot
ExecStart=/opt/mm/oracle/compact_wal.sh
--------------------------------------------------------------------------------
mm-wal-compact.timer
--------------------------------------------------------------------------------
[Unit]
Description=daily ORACLE WAL compaction
[Timer]
OnCalendar=*-*-* 04:17:00
Persistent=true
[Install]
WantedBy=timers.target
--------------------------------------------------------------------------------
mm-world.service
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND shared associative world-model organ (mmworld :9098)
After=network.target
[Service]
Type=simple
ExecStart=/opt/mm/bin/mmworld
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mm.target
--------------------------------------------------------------------------------
[Unit]
Description=MEGAMIND-AGI node stack
Wants=postgresql.service mm-serve.service mm-heart.timer mm-cap.timer
After=postgresql.service
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmask.service
--------------------------------------------------------------------------------
[Unit]
Description=mmask (PANTHEON ask brain — bridges mmknow+ORACLE+mmreason -> LLM)
After=network.target mm-oracle.service
[Service]
Type=simple
WorkingDirectory=/opt/mm/reason
Environment=MMKNOW=http://100.77.114.40:9542/know
Environment=MMREASON=http://100.77.114.40:9522/reason
Environment=ORACLE=http://100.69.120.61:9402/oracle
Environment=LLM=http://100.94.8.94:8082/v1/chat/completions
ExecStart=/usr/bin/python3 /opt/mm/reason/mmask_serve.py 9543
Restart=always
RestartSec=3
User=joseph
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmbackward.service
--------------------------------------------------------------------------------
[Unit]
Description=PANTHEON backward circulation loop (nonstop federation dataflow)
After=network.target mm-oracle.service
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/mm/loops/backward.py
Restart=always
RestartSec=3
User=joseph
WorkingDirectory=/opt/mm/loops
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmcode2.service
--------------------------------------------------------------------------------
[Unit]
Description=mmcode2 binary recall over CodeSearchNet (code + docstrings)
After=network.target
[Service]
Environment=WX_BSIG=/opt/mm/code/code.bsig
Environment=WX_BLOB=/opt/mm/code/code.blob
Environment=WX_IDX=/opt/mm/code/code.idx
Environment=WX_NAME=code2
ExecStart=/opt/mm/code/mmwikix serve 9534
Restart=always
User=joseph
WorkingDirectory=/opt/mm/code
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmforward.service
--------------------------------------------------------------------------------
[Unit]
Description=PANTHEON forward circulation loop (nonstop federation dataflow)
After=network.target mm-oracle.service
[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/mm/loops/forward.py
Restart=always
RestartSec=3
User=joseph
WorkingDirectory=/opt/mm/loops
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmgateway-web.service
--------------------------------------------------------------------------------
[Unit]
Description=mmgateway-web (read-only public gateway to every PANTHEON organ)
After=network.target mm-oracle.service
[Service]
Type=simple
WorkingDirectory=/opt/mm/reason
Environment=ORACLE=http://100.69.120.61:9402/oracle
ExecStart=/usr/bin/python3 /opt/mm/reason/mmgateway_web.py 9560
Restart=always
RestartSec=3
User=joseph
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmhelix.service
--------------------------------------------------------------------------------
[Unit]
Description=mmhelix G^16 -- 16 strand-loops, 8 antiparallel complement pairs
After=network.target
[Service]
ExecStart=/usr/bin/python3 /opt/mm/loops/mmhelix.py
Restart=always
RestartSec=3
User=joseph
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmknow.service
--------------------------------------------------------------------------------
[Unit]
Description=mmknow (PANTHEON mind organ)
After=network.target mm-oracle.service
[Service]
Type=simple
WorkingDirectory=/opt/mm/reason
ExecStart=/usr/bin/python3 /opt/mm/reason/mmknow_serve.py 9542
Restart=always
RestartSec=3
User=joseph
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmlearn.service
--------------------------------------------------------------------------------
[Unit]
Description=mmlearn (PANTHEON learning organ)
After=network.target mm-oracle.service mmreason.service
[Service]
Type=simple
WorkingDirectory=/opt/mm/reason
Environment="ORACLE=http://127.0.0.1:9402/oracle"
Environment="MMREASON=http://127.0.0.1:9522/reason"
ExecStart=/usr/bin/python3 /opt/mm/reason/mmlearn_serve.py 9541
Restart=always
RestartSec=3
User=joseph
[Install]
WantedBy=multi-user.target
--------------------------------------------------------------------------------
mmlearned.service
--------------------------------------------------------------------------------
[Unit]
Description=mmlearned binary recall over the learned/world-knowledge corpus (iCloud AGI_Data learning streams)
After=network.target
[Service]
Environment=WX_BSIG=/opt/mm/learned/learned.bsig