Source identity
| Field | Recorded value |
|---|---|
| Source type | archive member |
| Original record | DEEPSEEK REQUIREMENTS.REDACTED.txt |
| Date | Not specified in source |
| Path or archive member | archives/libsrc-46464020f0cc/Joseph_Master_Recovery_2026-10-12/sources/DEEPSEEK REQUIREMENTS.REDACTED.txt |
| Original SHA-256 | 8ad8d551a1c9bba5e34bacef2e89cbfebc1afbbf6890ade3e783a45cf36dffc7 |
| Reading-copy SHA-256 | ef49ff426791369c2f311ad945ad5458f6290377c3b0ad147b60a7e413b235a2 |
| Archive source | {"sourceId": "libsrc-46464020f0cc", "member": "Joseph_Master_Recovery_2026-10-12/sources/DEEPSEEK REQUIREMENTS.REDACTED.txt"} |
Recovered source transcript
Download complete source text ↓5,339 lines · 244.9 KB
================================================================================
D E E P S E E K R E Q U I R E M E N T S
Full itemized requirements, fulfillment status, and inlined source files
for making DeepSeek-R1 the central cognitive engine of
MEGAMIND-AGI / PANTHEON
================================================================================
Compiled 2026-08-05, live from MEGAMIND-AGI (100.69.120.61 / WSL2) and the
M4 mac-mini (100.94.8.94, kimi-blanket)
Companion DEEPSEEK_R1_COMPLETE.txt on this Desktop — the architecture report
Scope every item in the 12-section request, itemized, with a verified
status and, where the item is a file, the entire file inlined
--------------------------------------------------------------------------------
HOW TO READ THIS DOCUMENT
--------------------------------------------------------------------------------
[DONE] produced and verified this session; the artifact exists
[INLINED] the complete file text appears in PART C of this document
[PACKAGED] built into a tar.gz on the source machine; path given
[ABSENT] checked and confirmed not to exist — this is an answer, not a gap
[BLOCKED] cannot be produced yet; the blocker is named and explained
[ACTION] requires a human decision or a step outside this session
Every status claim below was established by a command run against the live
machines. Where something was checked and found missing, the check is described
so it can be repeated.
================================================================================
EXECUTIVE SUMMARY — WHAT EXISTS RIGHT NOW
================================================================================
BUILT AND VERIFIED THIS SESSION
* DeepSeek-R1 source bundle — all 10 requested files, copied, no weight shards
* 6 scanner/benchmark scripts, cleaned up and documented
* deepseek_tensor_manifest.json 91,991 entries, 28,923,014 B
* deepseek_shard_headers.json 163 entries, 40,263 B
* deepseek_layer_shard_map.json both directions, 19,562 B
* deepseek_expert_offset_map.json 15,104 experts, 7,042,163 B
* deepseek_weight_hashes.txt partial hashes, 163 shards, 63,906 B
* 4 upload packages, secret-scanned
* sanitized environment report
FIVE FINDINGS THAT CHANGE THE REQUEST ITSELF
1. THERE IS NO GO CODE. The request anticipates main.go, dynamical_reasoner.go,
wave_substrate.go, go.mod, go.sum. None exist. `find` for *.go and go.mod
across /opt/mm and /home/joseph returns nothing. MEGAMIND is C++ (120 .cpp,
53 .h, one hand-written Makefile) plus Python (organs and loops). Any plan
that assumes a Go service mesh needs rewriting before it starts.
2. THERE IS NO MCP IMPLEMENTATION. Section 6 asks for the code behind /mcp,
/mcp/tools, /mcp/execute, /mcp/sse, /mcp/manifest. Those routes appear to
answer HTTP 200, but that is ORACLE's catch-all: it returns 200 with an
error body for *every* unknown path, including /this-route-does-not-exist.
Grep for modelcontextprotocol, jsonrpc, tools/list and tools/call across the
whole tree returns nothing. The earlier grep hits for "mcp" were the letters
inside `memcpy`. MCP would be new construction, not a port.
3. THERE ARE NO GIT REPOSITORIES. /opt/mm, ~/mmk, ~/mmreason, ~/oracle and
~/megamind all lack .git. Section 12's GIT_STATUS.txt, GIT_COMMIT.txt and
GIT_RECENT_LOG.txt cannot be produced for any of them. Version history is
carried as ~90 hand-copied .bak files instead (oracle.cpp.bak.sefS1 through
sefS16, eye.cpp.bak.p28 through p40, and so on).
4. NO OFFICIAL DEEPSEEK INFERENCE RUNTIME IS PRESENT. Section 3's question is
answered definitively: no inference/, kernel.py, model.py, generate.py,
fp8_cast_bf16.py or convert.py anywhere on the machine, and no torch,
triton, vllm, sglang, transformers or safetensors in pip. The FP8 E4M3
backend must be built from the checkpoint format, and the three-way oracle
needs an externally-sourced reference.
5. FIXTURES CANNOT BE GENERATED YET. Section 9 wants frozen reference outputs.
Producing them requires something that can execute the model — which is
exactly what does not exist (finding 4). This is a genuine ordering
dependency, not an oversight: fixtures come *after* a reference runtime.
What can be produced now without a runtime is listed in PART B section 9.
ONE SECURITY ITEM REQUIRING YOUR DECISION
[REDACTED: credential-associated original line 79; original retained outside this bundle.]
as a string literal. It is a read-only role on localhost, but the request says
[REDACTED: credential-associated original line 81; original retained outside this bundle.]
did NOT edit loom.cpp, because the request also says not to clean the source
before sending — editing it would hide a real dependency. See PART E.
================================================================================
PART A — STATUS OF EVERY REQUESTED ITEM
================================================================================
§ ITEM STATUS WHERE
---------------------------------------------------------------------------
1 config.json DONE/INLINED C.1
1 configuration_deepseek.py DONE/INLINED C.2
1 modeling_deepseek.py DONE/INLINED C.3
1 generation_config.json DONE/INLINED C.4
1 tokenizer_config.json DONE/INLINED C.5
1 tokenizer.json DONE sidecar, see C.6
1 model.safetensors.index.json DONE sidecar, see C.7
1 README.md DONE/INLINED C.8
1 LICENSE DONE/INLINED C.9
1 .gitattributes DONE/INLINED C.10
1 download script DONE/INLINED C.11.1-3
1 header scanner DONE/INLINED C.11.4
1 tensor census producer DONE/INLINED C.11.5
1 SSD benchmark DONE/INLINED C.11.6
1 layer->shard mapper DONE/INLINED C.11.7
1 integrity verifier DONE/INLINED C.11.8
---------------------------------------------------------------------------
2 deepseek_tensor_manifest.json DONE B.2
2 deepseek_shard_headers.json DONE B.2
2 deepseek_layer_shard_map.json DONE B.2
2 deepseek_expert_offset_map.json DONE B.2
2 deepseek_weight_hashes.txt (partial) DONE B.2
2 deepseek_weight_hashes.txt (full SHA-256) ACTION B.2, ~22 min run
---------------------------------------------------------------------------
3 official DeepSeek inference source ABSENT B.3
---------------------------------------------------------------------------
4 MEGAMIND runtime source PACKAGED B.4
4 go.mod / go.sum / *.go ABSENT B.4 finding 1
4 Makefile PACKAGED B.4
4 CMakeLists / Dockerfile / compose / npm ABSENT B.4
4 systemd units DONE/INLINED C.13
4 startup scripts PACKAGED B.4
---------------------------------------------------------------------------
5 ORACLE source PACKAGED B.5
5 organ registration / coalition / trust PACKAGED B.5
5 VSA signature system PACKAGED B.5
5 NATS heartbeat code PACKAGED B.5
5 signature format specification PARTIAL B.5, from Kimi doc
5 trust score formula BLOCKED B.5, in binary only
5 schemas (organ/coalition/capability) PARTIAL B.5, observed
5 NATS subject list DONE B.5
---------------------------------------------------------------------------
6 MCP implementation ABSENT B.6 finding 2
6 tool registry / schemas / executors ABSENT B.6
---------------------------------------------------------------------------
7 memory + learning schemas DONE B.7
7 database schema DONE B.7
7 sanitized sample records ACTION B.7
---------------------------------------------------------------------------
8 Kimi implementation files (21 requested) 19 PRESENT B.8
8 exact_generators.py FOUND elsewhere B.8
8 cell_server.py ABSENT B.8
8 build commands / flags / tests / logs PACKAGED B.8
---------------------------------------------------------------------------
9 tokenizer fixtures BLOCKED B.9
9 FP8 fixtures BLOCKED B.9
9 router fixtures BLOCKED B.9
9 MLA fixtures BLOCKED B.9
9 full-layer fixtures BLOCKED B.9
---------------------------------------------------------------------------
10 API and network contracts PARTIAL B.10
---------------------------------------------------------------------------
11 /etc/wsl.conf DONE/INLINED C.12.1
11 .wslconfig DONE/INLINED C.12.2
11 systemd unit files DONE/INLINED C.13
11 sanitized environment report DONE/INLINED C.14
11 disk benchmark script + results DONE/INLINED C.11.6, B.11
---------------------------------------------------------------------------
12 FILE_MANIFEST.txt per repository DONE B.12
12 GIT_STATUS / GIT_COMMIT / GIT_RECENT_LOG ABSENT B.12 finding 3
---------------------------------------------------------------------------
================================================================================
PART B — EVERY SECTION, ITEMIZED, WITH FINDINGS
================================================================================
--------------------------------------------------------------------------------
B.1 DEEPSEEK-R1 SOURCE BUNDLE
--------------------------------------------------------------------------------
REQUESTED, from /home/joseph/DeepSeek-R1/:
config.json, configuration_deepseek.py, modeling_deepseek.py,
generation_config.json, tokenizer_config.json, tokenizer.json,
model.safetensors.index.json, README.md, LICENSE, .gitattributes
plus every script used to download, scan headers, produce the census,
benchmark the SSD, map layers to shards, and verify integrity.
EXPLICITLY EXCLUDED, and honored:
model-00001-of-000163.safetensors ... model-00163-of-000163.safetensors
.cache/huggingface/download/
All 163 weight shards remain exactly where they are. Nothing was moved,
renamed, copied or deleted. The scanners read headers only.
STATUS: [DONE]. All ten files copied to
/home/joseph/deepseek-megamind-upload/deepseek/
and packaged as 01-deepseek-source.tar.gz (4,349,260 bytes).
file bytes inlined at
---------------------------------------------------------------------------
config.json 1,660 C.1
configuration_deepseek.py 9,897 C.2
modeling_deepseek.py 75,741 C.3
generation_config.json 171 C.4
tokenizer_config.json 3,594 C.5
tokenizer.json 7,847,602 C.6 (sidecar — see note)
model.safetensors.index.json 8,898,324 C.7 (sidecar — see note)
README.md 15,994 C.8
LICENSE 1,064 C.9
.gitattributes 1,519 C.10
---------------------------------------------------------------------------
NOTE ON THE TWO LARGE FILES. tokenizer.json and model.safetensors.index.json
total 16.75 MB of machine-generated JSON — 127,741 BPE merge rules and 91,991
name->shard pairs. Pasting them into this document would add roughly 16.75 MB
of unreadable text and make the document unusable in any editor or context
window, without adding information a human or model can act on. They are
therefore delivered as byte-exact sidecar files rather than inline. Their
location, size, SHA-256 and structural specification are in C.6 and C.7, and
both are inside 01-deepseek-source.tar.gz. Every other requested file is
inlined complete. If you want them inline anyway, say so and I will append
them verbatim.
SCANNERS PRODUCED — all six categories requested, plus the manifest generators:
download_r1.py snapshot_download driver, resumable C.11.1
launch_r1.sh systemd-run wrapper (WSL kills bg jobs) C.11.2
dl_test.py single-file connectivity probe C.11.3
scan_headers.py header scan -> dtype/family census C.11.4
per_layer_manifest.py complete per-layer tensor manifest C.11.5
bench_ssd.sh SSD diagnosis: serial/parallel/scattered C.11.6
map_shards_to_layers.py shard <-> layer mapping C.11.7
verify_integrity.py header/index/length cross-check C.11.8
check_expert_contiguity.py on-disk expert layout prover C.11.9
gen_manifests.py the five section-2 manifests C.11.10
gen_hashes.py partial and full SHA-256 passes C.11.11
--------------------------------------------------------------------------------
B.2 COMPLETE TENSOR-HEADER MANIFEST
--------------------------------------------------------------------------------
STATUS: [DONE]. Generated by gen_manifests.py (inlined at C.11.10), which reads
only the 163 JSON headers — about 13 MB of the 643 GB checkpoint.
deepseek_tensor_manifest.json 28,923,014 B 91,991 entries
---------------------------------------------------------------------------
Exactly the requested schema, plus two additions marked below:
{
"name": "model.layers.3.mlp.experts.0.gate_proj.weight",
"shard": "model-00002-of-000163.safetensors",
"dtype": "F8_E4M3",
"shape": [2048, 7168],
"absolute_offset": 1234567,
"byte_length": 14680064,
"relative_offset": 1158517, <- ADDED: offset within the data region
"scale_tensor": "model.layers.3.mlp.experts.0.gate_proj.weight_scale_inv"
}
absolute_offset is the true file offset: 8 + header_len + relative_offset.
Seek there and read byte_length bytes and you have the tensor, with no further
parsing. relative_offset is retained because the safetensors header states
offsets that way, so the two can be cross-checked.
scale_tensor is null for every BF16 and F32 tensor and is populated for all
45,808 F8_E4M3 weights.
deepseek_shard_headers.json 40,263 B 163 entries
---------------------------------------------------------------------------
{"shard","file_size","header_len","data_start","tensor_count",
"payload_bytes","metadata","length_check_ok"}
length_check_ok is true for all 163: data_start + payload_bytes == file_size.
deepseek_layer_shard_map.json 19,562 B
---------------------------------------------------------------------------
layer_to_shards "0".."61" -> [shard filenames]
shard_to_layers shard filename -> [layer indices]
global_tensors_by_shard shard -> [embed_tokens / norm / lm_head]
notes dense [0,1,2], moe [3..60], mtp 61,
base_inference_layers [0..60]
deepseek_expert_offset_map.json 7,042,163 B 15,104 experts
---------------------------------------------------------------------------
keyed "layer/expert", e.g. "3/0":
{"layer":3,"expert":0,"total_bytes":44050944,"read_count":1,
"reads":[{"shard":...,"offset":...,"length":44050944,
"contiguous":true,
"tensors":["gate_proj.weight","gate_proj.weight_scale_inv",
"up_proj.weight","up_proj.weight_scale_inv",
"down_proj.weight","down_proj.weight_scale_inv"]}]}
MEASURED RESULT: 15,104 experts total. 14,951 need exactly ONE read of
44,050,944 contiguous bytes. 153 straddle a shard boundary and carry two
read descriptors. This map is the whole expert I/O plan — a streaming
loader needs nothing else to fetch an expert.
deepseek_weight_hashes.txt 63,906 B 163 stanzas
---------------------------------------------------------------------------
Currently PARTIAL, as the request permits: per shard, the file size plus
SHA-256 of the first 1 MiB, the 1 MiB at the midpoint, and the last 1 MiB.
Reads 489 MiB total, completed in 2.1 seconds. Detects truncation, a
swapped shard, and head/tail corruption.
[ACTION] Full SHA-256 over all 643 GB is a one-command run:
python3 ~/deepseek-megamind-upload/deepseek/scanners/gen_hashes.py --full
At the measured 507 MB/s single-stream rate that is roughly 22 minutes of
I/O plus hashing. It has not been run because it is a 22-minute serial read
of the drive the node is also serving from. Run it before any final
verification claim, as the request specifies.
--------------------------------------------------------------------------------
B.3 OFFICIAL DEEPSEEK INFERENCE SOURCE
--------------------------------------------------------------------------------
STATUS: [ABSENT] — checked thoroughly, definitively not present.
Searched /home/joseph, /opt/mm and /mnt/c/Users/Josep to depth 4 for:
inference/ kernel.py model.py generate.py fp8_cast_bf16.py
convert.py configs/ requirements.txt
Result: no matches.
The only DeepSeek-related paths on the machine are:
/home/joseph/DeepSeek-R1 the checkpoint
/home/joseph/DeepSeek-R1/configuration_deepseek.py reference config
/home/joseph/DeepSeek-R1/modeling_deepseek.py reference architecture
/home/joseph/.cache/huggingface/hub/models--deepseek-ai--DeepSeek-R1
HF download cache
pip3 list contains no torch, triton, vllm, sglang, transformers or
safetensors. The full package list is two entries: huggingface_hub 1.26.0 and
numpy 2.5.1.
CONSEQUENCE, stated plainly. The FP8 E4M3 128x128 block backend must be built
from the checkpoint format, and there is no local reference to check it
against. The shipped modeling_deepseek.py assumes weights are already
dequantized to bf16 — its only quantization-aware lines are a
`_pre_quantization_dtype` guard at 966-968. The official model card says
"Hugging Face's Transformers has not been directly supported yet."
To close this, one of the following must be fetched from outside this machine:
github.com/deepseek-ai/DeepSeek-V3 inference/kernel.py, fp8 cast
vLLM fp8 block-quant kernels
SGLang fp8 block-quant kernels
Pin whichever you choose to an exact commit hash and record it, because it
becomes the comparator that every later correctness claim rests on.
--------------------------------------------------------------------------------
B.4 MEGAMIND-AGI SOURCE
--------------------------------------------------------------------------------
STATUS: [PACKAGED] 02-megamind-source.tar.gz, 5,235,523 bytes.
*** THE REQUEST'S FILE LIST DOES NOT MATCH THIS SYSTEM. ***
Requested: main.go, dynamical_reasoner.go, wave_substrate.go, cmd/, agent/,
federation/, oracle/, memory/, learning/, ingestion/, mcp/, tools/, routes/,
api/, config/, go.mod, go.sum, Dockerfile, docker-compose.yml, package.json.
MEASURED REALITY:
*.go files anywhere ................... 0
go.mod / go.sum ....................... 0
CMakeLists.txt / Dockerfile ........... 0
docker-compose.yml / package.json ..... 0
Makefile .............................. 1 (/opt/mm/src/Makefile)
requirements.txt ...................... 0
MEGAMIND is C++ compiled with clang -O3 -march=native, plus Python organs.
There is no module system, no container, and no dependency manifest. The
Makefile uses `.RECIPEPREFIX = >` rather than tabs.
ACTUAL SOURCE INVENTORY (excluding the vendored pyembed tree):
188 source files, 2,024,267 bytes total
120 .cpp | 53 .h | (plus 1,926 .py, of which most are vendored) | 24 .sh
THE TWENTY LARGEST SOURCE FILES
582,800 /opt/mm/src/eye.cpp Living World engine
115,620 /opt/mm/src/oracle.cpp ORACLE core
53,348 /opt/mm/src/oracle_orchestrator.h
51,928 /opt/mm/src/mmpredict.cpp
43,212 /opt/mm/src/loom.cpp orchestration layer
34,804 /opt/mm/src/oracle_frontier.h
26,441 /opt/mm/code/src/mmscheme.cpp Scheme interpreter organ
25,887 /opt/mm/code/src/mmc.cpp C interpreter organ
24,780 /opt/mm/src/mmserve.cpp 512-bit recall service
24,239 /opt/mm/code/src/mmpy.cpp Python interpreter organ
20,761 /opt/mm/src/mmgame.cpp
17,721 /opt/mm/src/seferim_spec.h
17,018 /opt/mm/src/seferim_repl.h
16,535 /opt/mm/src/seferim_book.h
15,019 /opt/mm/src/seferim_degrade.h
14,431 /opt/mm/src/seferim_social.h
14,413 /opt/mm/src/seferim_plan.h
14,337 /opt/mm/src/seferim_trust.h
14,313 /opt/mm/code/src/mmparse.cpp
14,188 /opt/mm/src/seferim_api.h
MAPPING THE REQUESTED CONCERNS ONTO REAL FILES
main runtime and startup ....... mmboot.cpp, mm-boot.service, mm.target
reasoning engine ............... oracle.cpp, mmreason.cpp, reason*.cpp,
seferim_*.h (25 headers)
agent / autonomous loop ........ agent.cpp, swarmd.cpp, magent.cpp,
loops/{forward,backward,mmpulse,
mmthought,mmhelix}.py
task execution ................. oracle_orchestrator.h (orchestrate,
execute, coalition)
memory and recall .............. mmserve.cpp, hdcrecall.cpp, sdm.cpp,
seferim_mem.h
knowledge ingestion ............ hdctrain.cpp, hdcembed.cpp, semgrow*.cpp,
grow.cpp, embgrow.cpp
model routing .................. oracle.cpp organ registry + priority
federation connections ......... mmshard.cpp, fedmon.cpp, shard.cpp
NATS messaging ................. mmheart.cpp, mmsub.cpp, mmcap.cpp
(raw C++ NATS client, no library)
MCP tools ...................... DOES NOT EXIST — see B.6
API endpoints .................. each organ serves its own HTTP;
mmgateway_web.py is the read-only gateway
authentication ................. seferim_sec.h, mma5_sectest.cpp
state persistence .............. oracle.wal (WAL), PostgreSQL 18
logging and metrics ............ mmstatus.cpp, mmeval.cpp, mmgate.cpp
configuration .................. systemd unit Environment= lines,
/etc/mm/mm.env (mode 600, NOT shipped)
PACKAGE CONTENTS: src/, code/src/, reason/*.py, loops/
EXCLUDED: *.pyc, __pycache__, *.log, *.db, *.wal*, *.jsonl, *.tsv, *.u8,
*.env, *.key, *.pem, and every compiled binary in bin/
The ~90 .bak files ARE included deliberately — with no git history they are
the only record of how the code evolved, and the request asked not to clean.
--------------------------------------------------------------------------------
B.5 PANTHEON AND ORACLE SOURCE
--------------------------------------------------------------------------------
STATUS: [PACKAGED] 03-pantheon-source.tar.gz, 215,585 bytes.
CONTENTS
oracle.cpp 115,620 B task routing, registry, coalitions
oracle_orchestrator.h 53,348 B orchestrate / execute / coalition
oracle_frontier.h 34,804 B frontier expansion
seferim_*.h 25 headers: abstract align api book bridge
compose core degrade explore gate homeo learn
mem meta plan predict repl sec social spec
trust valgate
mmshard.cpp fedmon.cpp federation / NATS mesh shard responder
mmheart.cpp mmsub.cpp raw C++ NATS client and heartbeat
mmcap.cpp mmcap2.cpp capability manifest publisher
mmsem.cpp mmserve.cpp semantic embedder, 512-bit recall
mmembed.cpp mmembed2.cpp hdcembed.cpp binary embedders
mmgate.cpp mmeval.cpp mmstatus.cpp safety gate, eval, health
mmworld.cpp mmreason.cpp
reason/*.py mmask, mmknow, mmlearn, mmreason, mmthink,
mmgateway_web
loops/*.py forward, backward, mmpulse, mmthought, mmhelix
ORACLE'S LIVE POWER LIST, read from :9402/oracle/health this session:
recall inverse hop analogy similar learn path set consistent facts ask
unlearn revise counterfactual induce predict abduce factor map gardener
grow growstress shards budstress shard-spawn shard-add fedput fedget fedls
spawnstress compose synth ground plan nextgoal metalearn safegate library
sensorimotor negotiate culture sign ... (truncated by response limit)
Live counts: 508,093 entities | 34 relations | 773,235 edges
ROUTE SURFACE, from ORACLE's own error banner:
/oracle/{health,recall,inverse,hop,analogy,similar,facts,path,set,
consistent,learn,ask,unlearn,revise,counterfactual,induce,
predict,abduce,factor,map,organs,register,orchestrate,orchstress,
execute,execstress,coalition,coalstress}
*** /oracle/audit and /oracle/connect, named in the request, are NOT in
this list. They do not exist. Note also that ORACLE returns HTTP 200
for every unknown route with a JSON error body, so status codes cannot
be used to probe for endpoints — you must read the body.
NATS SUBJECTS IN USE
mesh.health.<node> heartbeat, mm-heart.timer every 15 s
mesh.registry.<node> capability manifest, mm-cap.timer every 60 s
mesh.query.recall federated recall fan-out (mmshard responder)
Hub: nats://100.90.97.104:4222 (Bubbles). WSL2 reaches the tailnet via
the 172.31.112.1 gateway.
BINARY VSA / SIGNATURE SYSTEM — what is known and what is not
[KNOWN, measured this session]
mmserve 24,364,580 signatures, vocab 38,085, index "mih16x32p"
Substrate 512-bit signatures, bit(512) columns in PostgreSQL
Distance XOR + POPCNT Hamming, hardware popcount
Eye organ 2,048-bit BSC (binary spatter code), separate dimension
Schema knowledge(sigbin bit(512), semsig bit(512))
sigbin = content SimHash, semsig = HDC semantic signature
[PARTIAL] The full signature format specification — exact bit order,
domain/version handling, projection seed — is written down only for the
Kimi vector organ, in ~/kimi-blanket/docs/kimi_vector_organ_design.md on
the M4 (included in 04-kimi-reference.tar.gz). That document specifies:
512 bits / 64 raw bytes / MSB-first / XOR-popcount Hamming, domains
"mmbsig/textHV/v1" (lexical) and "mmbsig/kimi-k2.5-hidden/v1" (neural),
with the hard rule that cross-domain Hamming distance is meaningless.
The C++ side's equivalent spec is implicit in hdcembed.cpp and mmsem.cpp
and has never been written out.
[BLOCKED] The trust score formula and the PASS adjudication logic are
inside oracle.cpp and seferim_trust.h. Both are shipped as source, so
the formula is recoverable by reading them — but there is no written
specification, and I did not reverse-engineer it in this session. Ask
for it specifically and I will extract and document it from the source.
SCHEMAS: organ request/response and coalition result schemas are OBSERVED
rather than specified — there is no schema file anywhere. What the live organs
return is captured in DEEPSEEK_R1_COMPLETE.txt and in B.10 below. Treat those
as the de facto contract; nothing declares them formally.
--------------------------------------------------------------------------------
B.6 MEGAMIND'S TOOL SYSTEM
--------------------------------------------------------------------------------
STATUS: [ABSENT]. There is no MCP implementation and no tool registry.
HOW THIS WAS ESTABLISHED
1. Probed /mcp, /mcp/tools, /mcp/manifest, /mcp/execute on ports 9402, 9560,
9543 and 9540. All returned HTTP 200 on ORACLE.
2. Read the bodies. Every one returned ORACLE's standard error banner
listing the /oracle/* routes — the catch-all, not an MCP response.
3. Confirmed by probing /this-route-does-not-exist-xyz, which also returns
HTTP 200. ORACLE answers 200 for everything.
4. Grepped the whole tree for modelcontextprotocol, jsonrpc, tools/list and
tools/call. Zero matches.
5. The earlier grep that matched "mcp" in seferim_api.h and seferim_sec.h
was matching the letters inside `memcpy`.
THEREFORE none of the following exist and none can be sent: tool registry,
tool schemas, tool descriptions, argument validation, permission checks,
execution handlers, result serialization, result verification, timeouts,
retries, sandbox code, audit logging, /mcp/sse.
The requested per-tool JSON record — name, description, input_schema,
output_schema, permissions, executor, timeout, risk_level, verification —
cannot be produced for any tool, because no tool is defined in that form.
WHAT EXISTS INSTEAD, and is the honest starting point:
* ORACLE's organ registry is the closest analogue to a tool registry. Each
organ carries: name, url, mode (local|remote|federation|timer), caps (a
free-text capability string), live, health (0|1|2), priority (8..80),
builtin, sig16. Capability matching is done by scoring the caps text
against the query — there is no typed schema, no argument validation, and
no permission model.
* seferim_sec.h and mma5_sectest.cpp hold the security primitives.
* seferim_valgate.h is the validation gate and has 9 .bak generations,
suggesting it is the most-revised part of the safety path.
[REDACTED: credential-associated original line 526; original retained outside this bundle.]
was BUILT, while registration auth, independent PASS judge, SSRF
protection, tool-execution isolation, rate limits, audit log and replay
protection were all still OPEN.
If DeepSeek is to get tool-calling in its generation loop, that is new
construction. R1's tokenizer already carries the wire format for it —
<|tool_calls_begin|>, <|tool_call_begin|>, <|tool_sep|>, <|tool_call_end|>,
<|tool_calls_end|> and the matching output block, ids 128806-128814 — so the
model side is ready and the harness side is empty.
--------------------------------------------------------------------------------
B.7 MEMORY AND LEARNING — SOURCE AND SCHEMAS
--------------------------------------------------------------------------------
STATUS: [DONE] for schemas and code. Bulk data deliberately excluded.
POSTGRESQL 18, TWO CLUSTERS
18-main port 5432, trust auth on local + 127.0.0.1
megamind 26 GB
knowledge 24,364,578 rows, 8,836 MB
nbin 32,404,944 rows, 17 GB
sembond 3,418,102 rows, 360 MB
game_memory 48 kB
livingworld 3,337 MB
events 14,355,878 | memories 928,608 | chronicle 147,248
codex 59 MB | entities 2,236 | nodes 3,271 | opinions 7,469
relationships 6,268 | edges | node_relhv | powers | places | goals
stations | world | holdings | toh | finn_ledger | viewings | routes
factions | realm_visit | world_history | dream_conditions | pattern_threads
[REDACTED: credential-associated original line 555; original retained outside this bundle.]
EXACT SCHEMAS, read with \d this session:
knowledge
id bigint not null default nextval('knowledge_id_seq')
hash text
body text
source text
modality text
sigbin bit(512) content SimHash
semsig bit(512) HDC semantic signature
created_at timestamptz default now()
access_count integer default 0
nbin
id bigint not null default nextval('nbin_id_seq')
hash text
sigbin bit(512)
semsig bit(512)
sembond
a, b, w associative edge with weight
KEY AND VALUE FORMATS
Signatures are 512-bit PostgreSQL bit strings. In C++ they are uint64 w[8].
Distance is XOR then hardware POPCNT. mmserve holds all 24.3M resident
(4.88 GB RSS) and scans them; the index identifier is "mih16x32p".
Vocabulary: hdc_vocab512.tsv, 43,137 tokens, frequency >= 8, two-pass build.
mmserve reports vocab 38,085 live; mm-narrate reports 45,419. These differ
per organ — do not assume one vocabulary.
CODE (all in 02-megamind-source.tar.gz)
read/write mmserve.cpp (/recall /spread /know /generate /health /reload)
embedding hdcembed.cpp (train|embed|simhash), mmsem.cpp, mmembed*.cpp
ingestion hdctrain.cpp, grow.cpp, embgrow.cpp, semgrow{,2,3}.cpp
association sembond via sdm.cpp, stdp.cpp
retention mma12_retention.cpp (bit-exact determinism check)
parity mma16_parity.cpp (replica fidelity vs the M4)
persistence oracle.wal, compacted by mm-wal-compact.timer at 04:17
MIGRATIONS: none. There is no migration framework and no versioned schema.
Tables were created by hand. This is worth knowing before anything depends on
schema evolution.
[ACTION] SANITIZED SAMPLE RECORDS were not produced. The knowledge table holds
24.3M rows of mixed provenance — Wikipedia, arXiv, PubMed, code corpora, and
an "mm-estate" organ whose declared scope is "own projects business clients
joseph anady ... missionMATCH ATLAS PANTHEON federation bubbles hosting".
That last one means the corpus contains business and client material. Sampling
it safely requires deciding which sources are publishable, which is your call,
not mine. Tell me which source values are safe and I will extract sanitized
samples with that filter applied.
--------------------------------------------------------------------------------
B.8 KIMI IMPLEMENTATION FILES
--------------------------------------------------------------------------------
STATUS: [PACKAGED] /tmp/04-kimi-reference.tar.gz on the M4, 146,502 bytes.
Source lives at /Users/joseph/kimi-blanket (1.5 GB total, 172 entries).
OF THE 21 FILES REQUESTED
PRESENT (19)
kimi_gen.h 21,887 B the authoritative shared header
kimi_int.c 9,379 B batched verification forward
kimi_serve.c 17,290 B incremental KV serving
kimi_tok.py 1,392 B tiktoken encoder, round-trip verified
chat_format.py 5,446 B
sampler.c 3,427 B
prec_check.c 8,516 B
compound_sim.py 3,280 B
guardian_controller.py 1,215 B (still separate, as hoped)
metal_mac.m 4,982 B M4 GPU int4 MAC, runtime-compiled Metal
kimi_organ.py 4,323 B authenticated inference endpoint
kimi_heart.py 1,752 B NATS pulse
cell_client.py 1,250 B
gen_manifest.py 2,393 B (legacy, superseded by the in-C parser)
kimi_vision.c 8,361 B
agents.c 7,411 B (synthetic prototype, not authoritative)
dataflow.c 5,186 B (synthetic prototype, not authoritative)
graph_build.py 3,534 B
gen_driver.py 1,864 B (superseded by kimi_serve.c)
FOUND, but not where the request expected
exact_generators.py 10,516 B at /Volumes/MEGAMIND/kimi_k25/model/
(ExactLinear + PackedInt4Linear)
modeling_deepseek.py 80,663 B at /Volumes/MEGAMIND/kimi_k25/model/
Kimi's OWN copy, with to_exact and
convert_kimi_to_exact — note that Kimi
K2.5 is DeepSeek-lineage, so this file
is directly comparable to R1's
modeling_deepseek.py 78,528 B a second copy at ~/kimi-blanket/kmod/
Both are packaged, under distinct names.
ABSENT (1)
cell_server.py — not found anywhere. cell_client.py exists without its
server. The transport half of the distributed dataflow is missing.
ALSO PACKAGED: all 73 source files (*.c *.h *.py *.m *.sh *.jinja), every
benchmark log (float.log, full_forward.log, full384.log, guard.log,
depth_bench.log, cmp_exact.log, gen_out.log and others), the fixture binaries
(h_float.bin, h_int8.bin, h_ex16.bin, h_ex20.bin, h_resident.bin,
bridge_ref.bin, embeds.bin, dual_kimi.bsig, dual_lex.bsig), the chat template,
and docs/kimi_vector_organ_design.md.
WHAT TRANSFERS TO R1, and what does not — stated so nothing is copied blindly:
TRANSFERS
the C-native safetensors header parser in kimi_gen.h (add an F8_E4M3 case)
MLA attention geometry — both models use 512 latent + 64 rope + 128 v
YaRN RoPE in C at arbitrary position (R1 needs factor 40 / orig 4096)
the dtype-aware loader discipline
the guardian hysteresis controller (HIGH 0.08, LOW 0.01, HYST 3, FLOOR 4)
serial-load / parallel-compute phase timing, and the instrumentation bug
to avoid: never sum I/O time across threads
the five equivalence gates and the results-ledger habit
DOES NOT TRANSFER
the .kex contiguous expert cache — R1's experts are already contiguous
native-int4 MAC with exact int64 group accumulation — fp8 has an exponent
field and cannot be integer-accumulated the same way
"convert non-routed bf16 to int8" — in R1 those tensors are already fp8
metal_mac.m — there is no Metal and no discrete GPU on megamind-agi
"cut seeks, don't fan out reads" — inverted here; this drive has 2.4x
concurrency headroom where the M4's external drive had none
--------------------------------------------------------------------------------
B.9 REFERENCE FIXTURES
--------------------------------------------------------------------------------
STATUS: [BLOCKED] for everything that needs model execution. The blocker is
B.3: nothing on this machine can run DeepSeek-R1, or even dequantize
one FP8 tensor, because there is no runtime and no reference.
This is an ordering dependency, not an oversight. A fixture is only meaningful
if its expected output came from a trusted implementation. Generating expected
outputs from an implementation we are about to write would make every later
comparison circular — the fixture would confirm our bugs rather than catch them.
WHAT IS BLOCKED, AND ON WHAT
tokenizer fixtures needs the tokenizers/transformers library
(absent; and Python 3.14 has no torch wheels)
FP8 operation fixtures needs a trusted fp8 block dequant (absent)
router fixtures needs real hidden states, i.e. a working forward
MLA fixtures same
full-layer fixtures same
MTP fixtures same
WHAT CAN BE PRODUCED RIGHT NOW WITHOUT ANY RUNTIME, and is worth doing first:
* RAW INPUT HALF of every FP8 fixture. The raw FP8 bytes and the F32 scale
grid can be extracted from the checkpoint today, for exactly the tensors
requested — layer 0 attention projection, layer 0 dense MLP, layer 3
routed expert, layer 31 expert 92 (the shard-crossing case), layer 60
routed expert, and MTP layer 61. Freeze those now; fill in the expected
output when a reference exists. I can generate this on request.
* TOKENIZER VOCABULARY FIXTURES that need no library: the exact id for every
special token is already known and is listed in DEEPSEEK_R1_COMPLETE.txt
part 11.2 — bos 0, eos 1, pad 2, <think> 128798, </think> 128799,
<|User|> 128803, <|Assistant|> 128804, the FIM triple 128800-128802, and
the tool-call block 128806-128814.
* CHAT TEMPLATE RENDERINGS, which are pure Jinja over the template in
tokenizer_config.json and need no model. Example, verified by hand:
[{"role":"user","content":"What is 2+2?"}] with add_generation_prompt
renders to <|begin_of_sentence|><|User|>What is 2+2?<|Assistant|><think>\n
* THE EXPERT OFFSET MAP already functions as an I/O fixture: 15,104 entries
of exact offset and length, verifiable by reading and checking lengths.
RECOMMENDED ORDER
1. Fetch and pin an official fp8 reference (B.3).
2. Freeze raw inputs for all six FP8 fixture sites.
3. Generate expected outputs from the pinned reference.
4. Only then write the C backend, checking against those frozen outputs.
--------------------------------------------------------------------------------
B.10 CURRENT APIs AND NETWORK CONTRACTS
--------------------------------------------------------------------------------
STATUS: [PARTIAL] — observed from live organs, because nothing is formally
specified. There is no OpenAPI document, no .proto, no schema file.
MEASURED LIVE SURFACE, this session. 65 organs registered, 61 live.
ORACLE :9402 /oracle/{health,recall,inverse,hop,analogy,similar,
facts,path,set,consistent,learn,ask,unlearn,revise,
counterfactual,induce,predict,abduce,factor,map,
organs,register,orchestrate,orchstress,execute,
execstress,coalition,coalstress}
508,093 entities | 34 relations | 773,235 edges
mmserve :9099 /recall /spread /know /generate /health /reload
{"status":"ok","sigs":24364580,"vocab":38085,
"index":"mih16x32p"}
mmsem :9096 /sem?q=text
mmgame :9097 /game/remember /game/recall /game/social /game/health
mmworld :9401 /world/recall?q=tok1|tok2 /world/health
mm-narrate :9403 /narrate vocab 45,419
eye :9404 2,236 entities | 3,271 nodes | 13,561 edges | 6 realms
loom :9410 /organ 2,210 souls, db_readonly true
mmhelix :9418 16 strands, 8 antiparallel pairs
mmpulse :9419 circulation loop, cycle 147,881
mmthought :9420 visible chain-of-thought
mmreason :9522 73,562 entities | 42,457 mention edges
mmwikix :9524 corpus 410,653 (also 9531-9534)
mmparse :9526 10 languages
mmscheme/mmpy/mmc :9527/9528/9529 interpreter organs
maddie :9531 corpus 404,787
learned :9532 corpus 1,395,149
pubmed :9533 corpus 4,693,336
code2 :9534 corpus 1,390,098
mmthink :9540 reasons_via http://100.94.8.94:8082/v1/chat/completions
mmlearn :9541 498,541 learned | 508,093 entities | 770,298 edges
mmknow :9542 691,293 facts | 517,083 concepts | 11 relation types
mmask :9543 the federation's voice; speaks_via the same M4 endpoint
mmgateway-web :9560 /organs — read-only public gateway, 65 organs
Caddy :8080 web host nginx :80 mm-api :8094
ORGAN REGISTRY RECORD, the de facto organ contract:
{"name","url","mode","caps","live","health","builtin","priority","sig16"}
mode local | remote | federation | timer
health 0 dead | 1 reachable/builtin | 2 answering
priority 8..80, higher wins in capability matching
caps free-text capability string, scored against the query.
There is no typed schema and no argument validation.
*** THE INTERFACE THAT MATTERS MOST FOR THIS PROJECT ***
mmthink (:9540) and mmask (:9543) both declare
"reasons_via" / "speaks_via": http://100.94.8.94:8082/v1/chat/completions
That OpenAI-shaped endpoint on the M4 is the federation's current voice and is
the natural socket for R1. It is the one contract that must stay
backward-compatible: anything that replaces it must accept the same
/v1/chat/completions request shape and return the same response shape, or
mmthink and mmask both break.
BACKWARD-COMPATIBILITY LIST — what must not change when R1 lands
/v1/chat/completions request/response shape (mmthink, mmask depend on it)
the organ registry record shape (ORACLE's matcher depends on it)
mesh.health.<node> and mesh.registry.<node> NATS subjects (timers publish)
mesh.query.recall subject (mmshard responds)
bit(512) signature width and XOR-popcount distance (every recall organ)
[ACTION] Example request/response payloads per interface were not captured
exhaustively — I recorded health/identity responses for all 65 organs but not
a worked call for each. Say which interfaces matter and I will capture real
request/response pairs for those.
A GOTCHA WORTH RECORDING: ORACLE returns HTTP 200 for every unknown route,
with a JSON error body. Any client that checks status codes to discover
capabilities will conclude that every endpoint exists. Parse the body.
--------------------------------------------------------------------------------
B.11 ENVIRONMENT AND DEPLOYMENT
--------------------------------------------------------------------------------
STATUS: [DONE]. All inlined in PART C.
/etc/wsl.conf C.12.1
.wslconfig (Windows side) C.12.2
systemd unit files, 51 of them C.13
sanitized environment report C.14 (uname, lscpu, free, df, clang, gcc,
python3, pip list, systemctl list-unit-files,
listening ports)
disk benchmark script C.11.6
Secret environment variable VALUES are not included anywhere. /etc/mm/mm.env
is mode 600 root-owned and was not read.
DIRECTORY LAYOUT
/opt/mm/{src,bin,data,logs,backups,code,learned,maddie,pubmed,oracle,
reason,loops,pyembed}
/home/joseph/{DeepSeek-R1,mmk,mmreason,oracle,megamind,missionmatch,eye-src}
/var/lib/postgresql/18/{main,missionmatch}
COMPILER FLAGS
clang -O3 -march=native, with Makefile using `.RECIPEPREFIX = >`.
clang 21.1.8 | gcc 15.2.0 | Python 3.14.4
CPU FEATURE DETECTION (full lscpu in C.14)
PRESENT avx2 fma f16c popcnt sse4_2 aes bmi1 bmi2 rdseed adx
ABSENT avx512* avx_vnni amx_int8 amx_bf16
Consequence: no hardware fp8/bf16 convert; int8 dot needs
vpmaddubsw + vpmaddwd on 256-bit lanes.
MEMORY LIMITS .wslconfig memory=26GB, 25 GiB visible, swap=8GB,
vmIdleTimeout=-1, processors=12
At scan time: 15 GiB used, 9.6 GiB available, 2.3 GiB swapped
DISK BENCHMARK RESULTS, measured this session
single stream, 8 MiB blocks, 2 GiB ................ 507 MB/s
same file again, page cache warm .................. 408 MB/s
4 parallel streams, 4 shards, 512 MiB each ........ 1220 MB/s aggregate
56 scattered 4 MiB preads ......................... 326 MB/s
Interpretation: 2.4x concurrency headroom, and no page-cache benefit
(25 GiB RAM against a 643 GB model has nothing to cache).
--------------------------------------------------------------------------------
B.12 REPOSITORY MANIFESTS
--------------------------------------------------------------------------------
STATUS: [DONE] for file manifests. [ABSENT] for all git metadata.
FILE_MANIFEST.txt was generated for the DeepSeek package and is inside
01-deepseek-source.tar.gz. The requested command works as given:
find . -type f -not -path './.git/*' -not -path './node_modules/*' \
-not -path './vendor/*' -not -path './data/*' \
-printf '%p\t%s bytes\n' | sort > FILE_MANIFEST.txt
GIT METADATA CANNOT BE PRODUCED. Checked for .git in /opt/mm,
/home/joseph/mmk, /home/joseph/mmreason, /home/joseph/oracle and
/home/joseph/megamind. None is a repository. Therefore:
GIT_STATUS.txt cannot be produced
GIT_COMMIT.txt cannot be produced
GIT_RECENT_LOG.txt cannot be produced
What stands in for history is roughly 90 hand-copied .bak files:
oracle.cpp.bak.sefS0 through sefS16 (with .5 increments)
oracle.cpp.bak.<unix-timestamp> — 1783580775, 1783582688, 1783594467,
1783602591, 1783610244, 1783612758
oracle.cpp.bak.{p1,p4..p10,preP1fed,premt,pre-fed,pre-gardener,
pre-capraise,speak,wire1,coal,exec,orch}
eye.cpp.bak.p28 through p40, plus bak-{book1,p1..p4,s1..s4,x1,x2}
loom.cpp.bak-{book1,p1..p4,s1..s4,x1,x2}
seferim_valgate.h.bak.sefS8 through sefS16
These are included in the packages. With no git, they are the only record of
what changed and when, and the mtimes are the only timeline.
[ACTION] Worth doing before this work goes further: `git init` in /opt/mm and
commit the current state. It costs nothing and makes every later change to a
2 MB source tree reviewable.
================================================================================
PART C — INLINED FILES (complete, byte-for-byte)
================================================================================
================================================================================
C.1 config.json (1,660 bytes)
================================================================================
{
"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
}
================================================================================
C.2 configuration_deepseek.py (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,
)
================================================================================
C.3 modeling_deepseek.py (75,741 bytes)
================================================================================
# 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.