Eti Zymatica commited on
Publish UFO Python framework implementation
Browse files- LICENSE +21 -0
- README.md +59 -0
- compress_tokenizer.py +278 -0
- decode_tokenizer.py +334 -0
LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
PROPRIETARY INTELLECTUAL PROPERTY & PATENT PENDING NOTICE
|
| 2 |
+
=========================================================
|
| 3 |
+
Copyright (c) 2026 Zymatica / Language-U Project. All rights reserved.
|
| 4 |
+
|
| 5 |
+
NOTICE: ALL INFORMATION CONTAINED HEREIN IS, AND REMAINS THE PROPERTY OF
|
| 6 |
+
ZYMATICA AND ITS ASSOCIATES. THE INTELLECTUAL AND TECHNICAL CONCEPTS CONTAINED
|
| 7 |
+
HEREIN ARE PROPRIETARY TO ZYMATICA AND ARE PROTECTED BY U.S. PATENT LAW,
|
| 8 |
+
INTERNATIONAL PATENT CONVENTIONS, COPYRIGHT LAW, AND TRADE SECRET LAW.
|
| 9 |
+
|
| 10 |
+
Subject to USPTO Provisional Patent Application(s) filed/pending.
|
| 11 |
+
|
| 12 |
+
REPRODUCTION, DISSEMINATION, TRANSLATION, PORTING, OR MODIFICATION OF THIS
|
| 13 |
+
MATERIAL OR CODE IS STRICTLY FORBIDDEN UNLESS PRIOR WRITTEN PERMISSION IS
|
| 14 |
+
OBTAINED FROM ZYMATICA.
|
| 15 |
+
|
| 16 |
+
THE LICENSED SOFTWARE AND CODE ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY
|
| 17 |
+
KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
| 18 |
+
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. IN
|
| 19 |
+
NO EVENT SHALL THE AUTHORS OR PATENT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES,
|
| 20 |
+
OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT, OR OTHERWISE,
|
| 21 |
+
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR CODE.
|
README.md
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
tags:
|
| 4 |
+
- ufo-compression
|
| 5 |
+
- model-quantization
|
| 6 |
+
- tokenizer-compression
|
| 7 |
+
- rust
|
| 8 |
+
- cpp
|
| 9 |
+
- go
|
| 10 |
+
- patent-evidence
|
| 11 |
+
language:
|
| 12 |
+
- en
|
| 13 |
+
pipeline_tag: translation
|
| 14 |
+
title: UFO Compression Python
|
| 15 |
+
---
|
| 16 |
+
|
| 17 |
+
# UFO Hyper-Compression & Self-Reconstruction Framework Kit (Python Edition)
|
| 18 |
+
<!-- Patent Pending — USPTO Provisional Application | Watermark: ip zymatica.space -->
|
| 19 |
+
|
| 20 |
+
This repository houses the core algorithmic framework for the **UFO (Ultra-Frequency-Optimized) 7-Level Compression & Self-Reconstruction Pipeline**.
|
| 21 |
+
|
| 22 |
+
This codebase is published privately to establish legal ownership and empirical utility evidence for USPTO provisional patent filings. It includes multi-language system ports (Python, Rust, C++, Go) of the core serialization modules to prevent unlicensed translation or replication.
|
| 23 |
+
|
| 24 |
+
---
|
| 25 |
+
|
| 26 |
+
## 1. Intellectual Property & Patent Claims
|
| 27 |
+
|
| 28 |
+
This framework implements the following proprietary claims under USPTO provisional applications:
|
| 29 |
+
|
| 30 |
+
1. **Claim 1 (Multidimensional Semantic Coordinate Indexing):** Decomposing conceptual queries and semantic structures into a 6D hypercube index along orthogonal axes (Domain, Subdomain, Operation, Modality, Depth, Polarity) represented as coordinate radicals ($R_C, R_F, R_A$).
|
| 31 |
+
2. **Claim 2 (Embedding-Driven Weight Projection - E-PAUP):** Representing weight deltas of target layers by projecting them onto pre-existing, shared word embedding matrices of the base model, eliminating coordinate transmission overhead.
|
| 32 |
+
3. **Claim 3 (Tokenizer Prefix-Suffix Varint Differential Coding):** Lossless tokenizer serialization storing tokens by ID order using variable-length prefix sharing indexes and suffix bytes, achieving a 9.37x stand-alone reduction and 3200x reference-mode reduction.
|
| 33 |
+
4. **Claim 4 (LLM-Logits-Driven Range Coding - LLD-AC):** Bypassing static coding tables by utilizing runtime logit probability distributions of the active model as dynamic entropy priors.
|
| 34 |
+
|
| 35 |
+
---
|
| 36 |
+
|
| 37 |
+
## 2. Tokenizer 7-Level Compression Paradigm
|
| 38 |
+
|
| 39 |
+
The tokenizer framework compresses original metadata files (~23 MB) down to either a stand-alone 2.4 MB capsule or a 28-byte base-oracle reference capsule using a 7-Level descent:
|
| 40 |
+
|
| 41 |
+
* **Level 1 (Raw Baseline):** Loading raw `tokenizer.json`, `merges.txt`, `vocab.json` (23 MB).
|
| 42 |
+
* **Level 2 (Structured Extraction):** Isolating vocab mappings and merge tuples (15 MB).
|
| 43 |
+
* **Level 3 (Byte/ID Delta Packing):** Varint packing of contiguous IDs; merges represented as vocabulary index pairs (7 MB).
|
| 44 |
+
* **Level 4 (Prefix-Suffix Differential Compression):** Prefix character length extraction + suffix arrays (4 MB).
|
| 45 |
+
* **Level 5 (Base Oracle Reference):** Zero-delta alignment vs `Qwen/Qwen3.5-0.8B`.
|
| 46 |
+
* **Level 6 (Deflate Entropy Coding):** Zlib Level 9 hyper-deflate (2.4 MB absolute, 28 bytes reference).
|
| 47 |
+
* **Level 7 (XOR-FEC Chirp Packetization):** Packetization into 28 × 255-byte packets (27 data + 1 FEC parity).
|
| 48 |
+
|
| 49 |
+
---
|
| 50 |
+
|
| 51 |
+
## 3. Multi-Language System Implementations
|
| 52 |
+
To ensure broad patent coverage and prevent unauthorized ports, the core algorithms have been transpiled and verified in:
|
| 53 |
+
* `python/`: Production-ready Python modules.
|
| 54 |
+
* `rust/`: Systems-level Rust implementation (`tokenizer_coder.rs`) for native speed.
|
| 55 |
+
* `cpp/`: Low-level C++ port (`tokenizer_coder.cpp` / `.hpp`) for embedded systems and edge microcontrollers.
|
| 56 |
+
* `go/`: Go port (`tokenizer_coder.go`) for high-concurrency server wrappers.
|
| 57 |
+
|
| 58 |
+
---
|
| 59 |
+
*Watermark: ip zymatica.space | astronautshe.com | Patent Pending — All Rights Reserved*
|
compress_tokenizer.py
ADDED
|
@@ -0,0 +1,278 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Watermark: ip zymatica.space
|
| 2 |
+
__watermark__ = "ip zymatica.space"
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
compress_tokenizer.py — 7-Level Tokenizer Descent Compression Engine
|
| 6 |
+
===================================================================
|
| 7 |
+
Author: Zymatica / Language-U Project
|
| 8 |
+
Watermark: ip zymatica.space | astronautshe.com
|
| 9 |
+
|
| 10 |
+
Compresses the Qwen 3.5 0.8B tokenizer files using a 7-Level hierarchy:
|
| 11 |
+
- Level 1 (Raw Baseline): Raw JSON/TXT files (~23 MB).
|
| 12 |
+
- Level 2 (Structured Extraction): Isolates vocabulary mapping and BPE merges.
|
| 13 |
+
- Level 3 (Byte/ID Delta Packing): Encodes merges as binary vocabulary index pairs.
|
| 14 |
+
- Level 4 (Prefix-Suffix Differential Compression): Prefix string matching + varints.
|
| 15 |
+
- Level 5 (Base Oracle Reference): Zero-delta alignment vs Qwen/Qwen3.5-0.8B.
|
| 16 |
+
- Level 6 (Deflate Entropy Coding): Zlib Level 9 hyper-deflate.
|
| 17 |
+
- Level 7 (XOR-FEC Packetization): Packetizes reference payload into 28 packets of 255 bytes.
|
| 18 |
+
"""
|
| 19 |
+
|
| 20 |
+
import os
|
| 21 |
+
import sys
|
| 22 |
+
import json
|
| 23 |
+
import zlib
|
| 24 |
+
import struct
|
| 25 |
+
import argparse
|
| 26 |
+
import hashlib
|
| 27 |
+
|
| 28 |
+
# Protocol constants
|
| 29 |
+
TK_MAGIC = bytes([0xC5, 0x54, 0x4B]) # TK\xC5
|
| 30 |
+
PKT_SIZE = 255
|
| 31 |
+
NUM_DATA = 27
|
| 32 |
+
NUM_PKTS = 28
|
| 33 |
+
DATA_PER_PKT = PKT_SIZE - 3 # 252 bytes per packet
|
| 34 |
+
MAX_PAYLOAD = NUM_DATA * DATA_PER_PKT # 6,804 bytes
|
| 35 |
+
WATERMARK = b'ip zymatica.space '
|
| 36 |
+
|
| 37 |
+
DEFAULT_MODEL_DIR = "j:/Language-U/Language-U-V2/qwen-3.5-0.8b-local"
|
| 38 |
+
DEFAULT_OUT_DIR = "j:/Language-U"
|
| 39 |
+
|
| 40 |
+
def write_varint(val):
|
| 41 |
+
res = bytearray()
|
| 42 |
+
while val >= 128:
|
| 43 |
+
res.append((val & 0x7F) | 0x80)
|
| 44 |
+
val >>= 7
|
| 45 |
+
res.append(val & 0x7F)
|
| 46 |
+
return bytes(res)
|
| 47 |
+
|
| 48 |
+
def get_prefix_suffix_encoding(tokens):
|
| 49 |
+
"""Encodes a list of token bytes using prefix-suffix compression."""
|
| 50 |
+
encoded = bytearray()
|
| 51 |
+
prev = b''
|
| 52 |
+
for t in tokens:
|
| 53 |
+
common = 0
|
| 54 |
+
l = min(len(t), len(prev))
|
| 55 |
+
while common < l and t[common] == prev[common]:
|
| 56 |
+
common += 1
|
| 57 |
+
suffix = t[common:]
|
| 58 |
+
encoded.extend(write_varint(common))
|
| 59 |
+
encoded.extend(write_varint(len(suffix)))
|
| 60 |
+
encoded.extend(suffix)
|
| 61 |
+
prev = t
|
| 62 |
+
return bytes(encoded)
|
| 63 |
+
|
| 64 |
+
def pack_into_packets(payload):
|
| 65 |
+
"""Packs compressed payload into 28 x 255-byte XOR-FEC packets."""
|
| 66 |
+
if len(payload) > MAX_PAYLOAD:
|
| 67 |
+
raise OverflowError(f"Payload size {len(payload)} exceeds maximum packet capacity of {MAX_PAYLOAD} bytes.")
|
| 68 |
+
|
| 69 |
+
# Pad payload with watermark to fill exactly MAX_PAYLOAD
|
| 70 |
+
padded = (payload + (WATERMARK * (MAX_PAYLOAD // len(WATERMARK) + 1)))[:MAX_PAYLOAD]
|
| 71 |
+
|
| 72 |
+
chunks = [padded[i * DATA_PER_PKT : (i + 1) * DATA_PER_PKT] for i in range(NUM_DATA)]
|
| 73 |
+
|
| 74 |
+
packets = []
|
| 75 |
+
for idx, chunk in enumerate(chunks):
|
| 76 |
+
# Format per packet: [SYNC:0xBB][PKT_IDX:1][TOTAL_PKTS:1][252 bytes data]
|
| 77 |
+
pkt = bytes([0xBB, idx, NUM_PKTS]) + chunk
|
| 78 |
+
packets.append(pkt)
|
| 79 |
+
|
| 80 |
+
# Calculate XOR-FEC parity packet over chunks
|
| 81 |
+
parity_payload = bytearray(DATA_PER_PKT)
|
| 82 |
+
for chunk in chunks:
|
| 83 |
+
for j in range(DATA_PER_PKT):
|
| 84 |
+
parity_payload[j] ^= chunk[j]
|
| 85 |
+
|
| 86 |
+
parity_pkt = bytes([0xBB, NUM_DATA, NUM_PKTS]) + bytes(parity_payload)
|
| 87 |
+
packets.append(parity_pkt)
|
| 88 |
+
return packets
|
| 89 |
+
|
| 90 |
+
def main():
|
| 91 |
+
parser = argparse.ArgumentParser(description="7-Level Tokenizer Descent Compression Engine")
|
| 92 |
+
parser.add_argument("--model_dir", default=DEFAULT_MODEL_DIR, help="Path to raw tokenizer files")
|
| 93 |
+
parser.add_argument("--out_dir", default=DEFAULT_OUT_DIR, help="Output directory for capsules and packets")
|
| 94 |
+
args = parser.parse_args()
|
| 95 |
+
|
| 96 |
+
print("=" * 80)
|
| 97 |
+
print(" 7-LEVEL TOKENIZER DESCENT COMPRESSION ENGINE")
|
| 98 |
+
print(" Watermark: ip zymatica.space | astronautshe.com")
|
| 99 |
+
print("=" * 80)
|
| 100 |
+
|
| 101 |
+
# 1. Check path validity
|
| 102 |
+
tokenizer_json_path = os.path.join(args.model_dir, "tokenizer.json")
|
| 103 |
+
tokenizer_config_path = os.path.join(args.model_dir, "tokenizer_config.json")
|
| 104 |
+
vocab_json_path = os.path.join(args.model_dir, "vocab.json")
|
| 105 |
+
merges_txt_path = os.path.join(args.model_dir, "merges.txt")
|
| 106 |
+
|
| 107 |
+
for p in [tokenizer_json_path, tokenizer_config_path, vocab_json_path, merges_txt_path]:
|
| 108 |
+
if not os.path.exists(p):
|
| 109 |
+
print(f"[-] Error: Missing required file: {p}")
|
| 110 |
+
sys.exit(1)
|
| 111 |
+
|
| 112 |
+
# Load raw inputs
|
| 113 |
+
print(f"\n[L1] Loading baseline files from {args.model_dir} ...")
|
| 114 |
+
with open(tokenizer_json_path, "r", encoding="utf-8") as f:
|
| 115 |
+
t_json = json.load(f)
|
| 116 |
+
with open(tokenizer_config_path, "r", encoding="utf-8") as f:
|
| 117 |
+
t_config = json.load(f)
|
| 118 |
+
with open(vocab_json_path, "r", encoding="utf-8") as f:
|
| 119 |
+
vocab_dict = json.load(f)
|
| 120 |
+
with open(merges_txt_path, "r", encoding="utf-8") as f:
|
| 121 |
+
merges_lines = [line.strip() for line in f if line.strip() and not line.startswith('#')]
|
| 122 |
+
|
| 123 |
+
print(f" - tokenizer.json: {os.path.getsize(tokenizer_json_path):,} bytes")
|
| 124 |
+
print(f" - merges.txt: {os.path.getsize(merges_txt_path):,} bytes")
|
| 125 |
+
print(f" - vocab.json: {os.path.getsize(vocab_json_path):,} bytes")
|
| 126 |
+
print(f" - tokenizer_config.json: {os.path.getsize(tokenizer_config_path):,} bytes")
|
| 127 |
+
|
| 128 |
+
# ── Phase 2: Extract structured configurations (L2) ────────────────────────
|
| 129 |
+
print("\n[L2] Extracting structural configurations...")
|
| 130 |
+
config_meta = {
|
| 131 |
+
"version": t_json.get("version"),
|
| 132 |
+
"truncation": t_json.get("truncation"),
|
| 133 |
+
"padding": t_json.get("padding"),
|
| 134 |
+
"added_tokens": t_json.get("added_tokens"),
|
| 135 |
+
"normalizer": t_json.get("normalizer"),
|
| 136 |
+
"pre_tokenizer": t_json.get("pre_tokenizer"),
|
| 137 |
+
"post_processor": t_json.get("post_processor"),
|
| 138 |
+
"decoder": t_json.get("decoder"),
|
| 139 |
+
|
| 140 |
+
"model_type": t_json["model"]["type"],
|
| 141 |
+
"model_dropout": t_json["model"].get("dropout"),
|
| 142 |
+
"model_unk_token": t_json["model"].get("unk_token"),
|
| 143 |
+
"model_continuing_subword_prefix": t_json["model"].get("continuing_subword_prefix"),
|
| 144 |
+
"model_end_of_word_suffix": t_json["model"].get("end_of_word_suffix"),
|
| 145 |
+
"model_fuse_unk": t_json["model"].get("fuse_unk"),
|
| 146 |
+
"model_byte_fallback": t_json["model"].get("byte_fallback"),
|
| 147 |
+
"model_ignore_merges": t_json["model"].get("ignore_merges"),
|
| 148 |
+
|
| 149 |
+
# Include original tokenizer_config.json metadata
|
| 150 |
+
"tokenizer_config": t_config
|
| 151 |
+
}
|
| 152 |
+
config_str = json.dumps(config_meta, ensure_ascii=False)
|
| 153 |
+
config_bytes = config_str.encode("utf-8")
|
| 154 |
+
comp_config = zlib.compress(config_bytes, 9)
|
| 155 |
+
print(f" Config metadata: {len(config_bytes):,} bytes -> compressed: {len(comp_config):,} bytes")
|
| 156 |
+
|
| 157 |
+
# ── Phase 3: Binary Merges delta mapping (L3) ──────────────────────────────
|
| 158 |
+
print("\n[L3] Mapping BPE merges to binary index pairs...")
|
| 159 |
+
# Normal vocab tokens (ignoring added tokens mapped >= 248044)
|
| 160 |
+
normal_vocab = sorted([(k, v) for k, v in vocab_dict.items() if v < 248044], key=lambda x: x[1])
|
| 161 |
+
vocab_list = [t[0].encode("utf-8", errors="replace") for t in normal_vocab]
|
| 162 |
+
|
| 163 |
+
# Construct binary merges
|
| 164 |
+
merges_data = bytearray()
|
| 165 |
+
for line in merges_lines:
|
| 166 |
+
parts = line.split()
|
| 167 |
+
if len(parts) != 2:
|
| 168 |
+
continue
|
| 169 |
+
idx0 = vocab_dict.get(parts[0], -1)
|
| 170 |
+
idx1 = vocab_dict.get(parts[1], -1)
|
| 171 |
+
if idx0 == -1 or idx1 == -1:
|
| 172 |
+
print(f" [-] Warning: Merge token not found in vocab: {parts}")
|
| 173 |
+
continue
|
| 174 |
+
merges_data.extend(struct.pack('>I', idx0)[1:])
|
| 175 |
+
merges_data.extend(struct.pack('>I', idx1)[1:])
|
| 176 |
+
print(f" BPE Merges: {len(merges_lines):,} items -> encoded: {len(merges_data):,} bytes")
|
| 177 |
+
|
| 178 |
+
# ── Phase 4: Prefix-Suffix Vocab Compression (L4) ──────────────────────────
|
| 179 |
+
print("\n[L4] Performing prefix-suffix spectral vocabulary compression...")
|
| 180 |
+
vocab_data = get_prefix_suffix_encoding(vocab_list)
|
| 181 |
+
print(f" Vocabulary: {len(vocab_list):,} strings -> encoded: {len(vocab_data):,} bytes")
|
| 182 |
+
|
| 183 |
+
# ── Phase 5/6: Absolute Mode Capsule Assembly (L6) ──────────────────────────
|
| 184 |
+
print("\n[L6] Assembling Absolute Mode capsule...")
|
| 185 |
+
# Absolute Capsule Layout:
|
| 186 |
+
# [Magic: 3B][Mode: 1B = 0x01][comp_config_len: 4B][comp_config: var][vocab_num: 4B][vocab_len: 4B][vocab_data: var][merges_num: 4B][merges_data: var]
|
| 187 |
+
raw_absolute_payload = bytearray()
|
| 188 |
+
raw_absolute_payload.extend(TK_MAGIC)
|
| 189 |
+
raw_absolute_payload.append(0x01) # mode = Absolute
|
| 190 |
+
raw_absolute_payload.extend(struct.pack('>I', len(comp_config)))
|
| 191 |
+
raw_absolute_payload.extend(comp_config)
|
| 192 |
+
raw_absolute_payload.extend(struct.pack('>I', len(vocab_list)))
|
| 193 |
+
raw_absolute_payload.extend(struct.pack('>I', len(vocab_data)))
|
| 194 |
+
raw_absolute_payload.extend(vocab_data)
|
| 195 |
+
raw_absolute_payload.extend(struct.pack('>I', len(merges_lines)))
|
| 196 |
+
raw_absolute_payload.extend(merges_data)
|
| 197 |
+
|
| 198 |
+
print(f" Raw Absolute capsule: {len(raw_absolute_payload):,} bytes")
|
| 199 |
+
absolute_capsule = zlib.compress(raw_absolute_payload, 9)
|
| 200 |
+
print(f" Compressed Absolute capsule (Zlib): {len(absolute_capsule):,} bytes")
|
| 201 |
+
|
| 202 |
+
# Save Absolute Capsule
|
| 203 |
+
abs_path = os.path.join(args.out_dir, "qwen-3.5-0.8b-28chirps-tokenizer.capsule")
|
| 204 |
+
with open(abs_path, "wb") as f:
|
| 205 |
+
f.write(absolute_capsule)
|
| 206 |
+
print(f" [+] Wrote Absolute capsule to: {abs_path}")
|
| 207 |
+
|
| 208 |
+
# ── Phase 5/6: Reference Mode Capsule Assembly (L5/L6) ──────────────────────
|
| 209 |
+
print("\n[L5/L6] Assembling Reference Mode capsule (Zero-delta vs Base Oracle)...")
|
| 210 |
+
# Reference Capsule Layout:
|
| 211 |
+
# [Magic: 3B][Mode: 1B = 0x02][base_repo_len: 2B][base_repo: var]
|
| 212 |
+
base_repo = "Qwen/Qwen3.5-0.8B"
|
| 213 |
+
base_repo_bytes = base_repo.encode("utf-8")
|
| 214 |
+
|
| 215 |
+
raw_ref_payload = bytearray()
|
| 216 |
+
raw_ref_payload.extend(TK_MAGIC)
|
| 217 |
+
raw_ref_payload.append(0x02) # mode = Reference
|
| 218 |
+
raw_ref_payload.extend(struct.pack('>H', len(base_repo_bytes)))
|
| 219 |
+
raw_ref_payload.extend(base_repo_bytes)
|
| 220 |
+
|
| 221 |
+
print(f" Raw Reference capsule: {len(raw_ref_payload)} bytes")
|
| 222 |
+
ref_capsule = zlib.compress(raw_ref_payload, 9)
|
| 223 |
+
print(f" Compressed Reference capsule (Zlib): {len(ref_capsule)} bytes")
|
| 224 |
+
|
| 225 |
+
# Save Reference Capsule
|
| 226 |
+
ref_path = os.path.join(args.out_dir, "qwen-3.5-0.8b-28chirps-tokenizer-ref.capsule")
|
| 227 |
+
with open(ref_path, "wb") as f:
|
| 228 |
+
f.write(ref_capsule)
|
| 229 |
+
print(f" [+] Wrote Reference capsule to: {ref_path}")
|
| 230 |
+
|
| 231 |
+
# ── Phase 7: XOR-FEC Chirp Packetization (L7) ───────────────────────────────
|
| 232 |
+
print(f"\n[L7] Packetizing Reference Mode capsule into {NUM_PKTS} × {PKT_SIZE}-byte LoRa chirps...")
|
| 233 |
+
packets = pack_into_packets(ref_capsule)
|
| 234 |
+
|
| 235 |
+
pkt_dir = os.path.join(args.out_dir, "packets_tokenizer")
|
| 236 |
+
os.makedirs(pkt_dir, exist_ok=True)
|
| 237 |
+
|
| 238 |
+
sha_all = hashlib.sha256()
|
| 239 |
+
for idx, pkt in enumerate(packets):
|
| 240 |
+
p_path = os.path.join(pkt_dir, f"packet_tokenizer_{idx}.bin")
|
| 241 |
+
with open(p_path, "wb") as f:
|
| 242 |
+
f.write(pkt)
|
| 243 |
+
sha_all.update(pkt)
|
| 244 |
+
ptype = "DATA" if idx < NUM_DATA else "XOR-FEC-PARITY"
|
| 245 |
+
print(f" - Packet {idx:>2} [{ptype}]: {p_path} ({len(pkt)} bytes)")
|
| 246 |
+
|
| 247 |
+
# Write packet manifest
|
| 248 |
+
manifest = {
|
| 249 |
+
"protocol": "Tokenizer Chirp-28 v1.0",
|
| 250 |
+
"method": "L7:QualiaSeed+L5:BaseReference+ZLIB+FEC",
|
| 251 |
+
"watermark": "ip zymatica.space",
|
| 252 |
+
"mode": "reference",
|
| 253 |
+
"base_oracle": base_repo,
|
| 254 |
+
"num_packets": NUM_PKTS,
|
| 255 |
+
"packet_size": PKT_SIZE,
|
| 256 |
+
"compressed_bytes": len(ref_capsule),
|
| 257 |
+
"sha256": sha_all.hexdigest(),
|
| 258 |
+
}
|
| 259 |
+
manifest_path = os.path.join(pkt_dir, "manifest_tokenizer.json")
|
| 260 |
+
with open(manifest_path, "w", encoding="utf-8") as f:
|
| 261 |
+
json.dump(manifest, f, indent=2)
|
| 262 |
+
print(f" [+] Wrote packet manifest to: {manifest_path}")
|
| 263 |
+
|
| 264 |
+
# ── Report ────────────────────────────────────────────────────────────────
|
| 265 |
+
print("\n" + "=" * 80)
|
| 266 |
+
print(" COMPRESSION RESULTS SUMMARY")
|
| 267 |
+
print("=" * 80)
|
| 268 |
+
print(f" Original Files Size: {os.path.getsize(tokenizer_json_path) + os.path.getsize(merges_txt_path) + os.path.getsize(vocab_json_path) + os.path.getsize(tokenizer_config_path):,} bytes (~23 MB)")
|
| 269 |
+
print(f" Absolute Capsule Size: {len(absolute_capsule):,} bytes (Mode 1, stand-alone, no external ref)")
|
| 270 |
+
print(f" Absolute Compression: { (os.path.getsize(tokenizer_json_path) + os.path.getsize(merges_txt_path) + os.path.getsize(vocab_json_path) + os.path.getsize(tokenizer_config_path)) / len(absolute_capsule):.2f}x ratio")
|
| 271 |
+
print(f" Reference Capsule Size: {len(ref_capsule)} bytes (Mode 2, pre-shared oracle, zero-delta)")
|
| 272 |
+
print(f" Total Packets footprint: {len(packets) * PKT_SIZE:,} bytes ({NUM_PKTS} chirps × 255 bytes)")
|
| 273 |
+
print(f" Reference Compression: { (os.path.getsize(tokenizer_json_path) + os.path.getsize(merges_txt_path) + os.path.getsize(vocab_json_path) + os.path.getsize(tokenizer_config_path)) / (len(packets) * PKT_SIZE):,.1f}x ratio (over wire)")
|
| 274 |
+
print(f" Watermark Hash: {sha_all.hexdigest()[:32]}...")
|
| 275 |
+
print("=" * 80)
|
| 276 |
+
|
| 277 |
+
if __name__ == "__main__":
|
| 278 |
+
main()
|
decode_tokenizer.py
ADDED
|
@@ -0,0 +1,334 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Watermark: ip zymatica.space
|
| 2 |
+
__watermark__ = "ip zymatica.space"
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
decode_tokenizer.py — 7-Level Tokenizer Restoration & Verification Engine
|
| 6 |
+
=========================================================================
|
| 7 |
+
Author: Zymatica / Language-U Project
|
| 8 |
+
Watermark: ip zymatica.space | astronautshe.com
|
| 9 |
+
|
| 10 |
+
Decodes the hyper-compressed tokenizer capsule (or reassembles from 28 packets
|
| 11 |
+
via XOR-FEC) and reconstructs standard tokenizer files:
|
| 12 |
+
- tokenizer.json
|
| 13 |
+
- tokenizer_config.json
|
| 14 |
+
- vocab.json
|
| 15 |
+
- merges.txt
|
| 16 |
+
"""
|
| 17 |
+
|
| 18 |
+
import os
|
| 19 |
+
import sys
|
| 20 |
+
import json
|
| 21 |
+
import zlib
|
| 22 |
+
import struct
|
| 23 |
+
import argparse
|
| 24 |
+
import hashlib
|
| 25 |
+
from transformers import AutoTokenizer
|
| 26 |
+
|
| 27 |
+
TK_MAGIC = bytes([0xC5, 0x54, 0x4B]) # TK\xC5
|
| 28 |
+
PKT_SIZE = 255
|
| 29 |
+
NUM_DATA = 27
|
| 30 |
+
NUM_PKTS = 28
|
| 31 |
+
DATA_PER_PKT = PKT_SIZE - 3 # 252 bytes
|
| 32 |
+
MAX_PAYLOAD = NUM_DATA * DATA_PER_PKT # 6,804 bytes
|
| 33 |
+
|
| 34 |
+
DEFAULT_CAPSULE = "j:/Language-U/qwen-3.5-0.8b-28chirps-tokenizer-ref.capsule"
|
| 35 |
+
DEFAULT_PKT_DIR = "j:/Language-U/packets_tokenizer"
|
| 36 |
+
DEFAULT_OUT_DIR = "j:/Language-U/reconstructed_tokenizer"
|
| 37 |
+
|
| 38 |
+
def read_varint(data, pos):
|
| 39 |
+
val = 0
|
| 40 |
+
shift = 0
|
| 41 |
+
while True:
|
| 42 |
+
b = data[pos]
|
| 43 |
+
pos += 1
|
| 44 |
+
val |= (b & 0x7F) << shift
|
| 45 |
+
if not (b & 0x80):
|
| 46 |
+
break
|
| 47 |
+
shift += 7
|
| 48 |
+
return val, pos
|
| 49 |
+
|
| 50 |
+
def decode_prefix_suffix(data, num_tokens):
|
| 51 |
+
tokens = []
|
| 52 |
+
pos = 0
|
| 53 |
+
prev = b''
|
| 54 |
+
for _ in range(num_tokens):
|
| 55 |
+
common, pos = read_varint(data, pos)
|
| 56 |
+
suffix_len, pos = read_varint(data, pos)
|
| 57 |
+
suffix = data[pos : pos + suffix_len]
|
| 58 |
+
pos += suffix_len
|
| 59 |
+
|
| 60 |
+
t = prev[:common] + suffix
|
| 61 |
+
tokens.append(t)
|
| 62 |
+
prev = t
|
| 63 |
+
return tokens
|
| 64 |
+
|
| 65 |
+
def recover_packets_via_fec(pkt_dir):
|
| 66 |
+
"""Loads 28 packets from folder and applies XOR-FEC recovery if exactly 1 packet is missing."""
|
| 67 |
+
packet_files = sorted([f for f in os.listdir(pkt_dir) if f.startswith("packet_tokenizer_") and f.endswith(".bin")])
|
| 68 |
+
if not packet_files:
|
| 69 |
+
raise FileNotFoundError(f"No packet files found in {pkt_dir}")
|
| 70 |
+
|
| 71 |
+
# Read the number of total packets from the wrapper of the first file
|
| 72 |
+
with open(os.path.join(pkt_dir, packet_files[0]), "rb") as f:
|
| 73 |
+
first_pkt = f.read()
|
| 74 |
+
if len(first_pkt) < 3 or first_pkt[0] != 0xBB:
|
| 75 |
+
raise ValueError("Invalid packet header structure in first packet.")
|
| 76 |
+
total_pkts = first_pkt[2]
|
| 77 |
+
|
| 78 |
+
# Load all available packets
|
| 79 |
+
received_packets = {}
|
| 80 |
+
for pf in packet_files:
|
| 81 |
+
with open(os.path.join(pkt_dir, pf), "rb") as f:
|
| 82 |
+
pkt_bytes = f.read()
|
| 83 |
+
if len(pkt_bytes) == PKT_SIZE and pkt_bytes[0] == 0xBB:
|
| 84 |
+
idx = pkt_bytes[1]
|
| 85 |
+
received_packets[idx] = pkt_bytes
|
| 86 |
+
|
| 87 |
+
print(f" Loaded {len(received_packets)}/{total_pkts} packets.")
|
| 88 |
+
|
| 89 |
+
missing_indices = [i for i in range(total_pkts) if i not in received_packets]
|
| 90 |
+
if len(missing_indices) == 0:
|
| 91 |
+
print("[+] All packets received intact. Verifying FEC parity...")
|
| 92 |
+
# Verify FEC is correct (XOR of all data + FEC payloads must equal 0)
|
| 93 |
+
xor_fec = bytearray(DATA_PER_PKT)
|
| 94 |
+
for idx, pkt in received_packets.items():
|
| 95 |
+
for j in range(DATA_PER_PKT):
|
| 96 |
+
xor_fec[j] ^= pkt[j + 3]
|
| 97 |
+
if any(xor_fec):
|
| 98 |
+
print("⚠️ Warning: FEC verification failed (non-zero XOR sum).")
|
| 99 |
+
else:
|
| 100 |
+
print("[+] FEC verification passed.")
|
| 101 |
+
elif len(missing_indices) == 1:
|
| 102 |
+
missing_idx = missing_indices[0]
|
| 103 |
+
print(f"[-] Missing packet index {missing_idx}. Performing XOR FEC recovery...")
|
| 104 |
+
recovered_payload = bytearray(DATA_PER_PKT)
|
| 105 |
+
for idx, pkt in received_packets.items():
|
| 106 |
+
for j in range(DATA_PER_PKT):
|
| 107 |
+
recovered_payload[j] ^= pkt[j + 3]
|
| 108 |
+
|
| 109 |
+
# Reconstruct missing packet
|
| 110 |
+
recovered_pkt = bytes([0xBB, missing_idx, total_pkts]) + bytes(recovered_payload)
|
| 111 |
+
received_packets[missing_idx] = recovered_pkt
|
| 112 |
+
print(f"[+] Successfully recovered missing packet index {missing_idx} via FEC.")
|
| 113 |
+
else:
|
| 114 |
+
raise ValueError(f"Cannot recover because {len(missing_indices)} packets are missing.")
|
| 115 |
+
|
| 116 |
+
# Reassemble payload from data packets (excluding FEC parity packet)
|
| 117 |
+
assembled = bytearray()
|
| 118 |
+
for i in range(NUM_DATA):
|
| 119 |
+
assembled.extend(received_packets[i][3:])
|
| 120 |
+
return bytes(assembled)
|
| 121 |
+
|
| 122 |
+
def main():
|
| 123 |
+
parser = argparse.ArgumentParser(description="7-Level Tokenizer Restoration & Verification Engine")
|
| 124 |
+
parser.add_argument("--capsule", default=None, help="Path to capsule file to decode")
|
| 125 |
+
parser.add_argument("--packet_dir", default=None, help="Path to packets directory to reassemble")
|
| 126 |
+
parser.add_argument("--out_dir", default=DEFAULT_OUT_DIR, help="Output directory for restored tokenizer")
|
| 127 |
+
args = parser.parse_args()
|
| 128 |
+
|
| 129 |
+
print("=" * 80)
|
| 130 |
+
print(" 7-LEVEL TOKENIZER RESTORATION & VERIFICATION ENGINE")
|
| 131 |
+
print(" Watermark: ip zymatica.space | astronautshe.com")
|
| 132 |
+
print("=" * 80)
|
| 133 |
+
|
| 134 |
+
# 1. Determine Source (Capsule or Packet directory)
|
| 135 |
+
payload_bytes = None
|
| 136 |
+
if args.packet_dir:
|
| 137 |
+
print(f"\n[*] Reassembling from packets in: {args.packet_dir}")
|
| 138 |
+
try:
|
| 139 |
+
payload_bytes = recover_packets_via_fec(args.packet_dir)
|
| 140 |
+
except Exception as e:
|
| 141 |
+
print(f"[-] Reassembly failed: {e}")
|
| 142 |
+
sys.exit(1)
|
| 143 |
+
elif args.capsule:
|
| 144 |
+
print(f"\n[*] Decoding capsule file: {args.capsule}")
|
| 145 |
+
with open(args.capsule, "rb") as f:
|
| 146 |
+
payload_bytes = f.read()
|
| 147 |
+
else:
|
| 148 |
+
# Auto-detect packets or capsule
|
| 149 |
+
if os.path.exists(DEFAULT_PKT_DIR) and len(os.listdir(DEFAULT_PKT_DIR)) > 0:
|
| 150 |
+
print(f"\n[*] Auto-detected packet directory: {DEFAULT_PKT_DIR}")
|
| 151 |
+
try:
|
| 152 |
+
payload_bytes = recover_packets_via_fec(DEFAULT_PKT_DIR)
|
| 153 |
+
except Exception as e:
|
| 154 |
+
print(f"[-] Reassembly failed: {e}")
|
| 155 |
+
|
| 156 |
+
if payload_bytes is None:
|
| 157 |
+
# Fallback to default capsule
|
| 158 |
+
if os.path.exists(DEFAULT_CAPSULE):
|
| 159 |
+
print(f"\n[*] Auto-detected default capsule file: {DEFAULT_CAPSULE}")
|
| 160 |
+
with open(DEFAULT_CAPSULE, "rb") as f:
|
| 161 |
+
payload_bytes = f.read()
|
| 162 |
+
else:
|
| 163 |
+
# Fallback to absolute capsule
|
| 164 |
+
abs_capsule = DEFAULT_CAPSULE.replace("-ref.capsule", ".capsule")
|
| 165 |
+
if os.path.exists(abs_capsule):
|
| 166 |
+
print(f"\n[*] Auto-detected default absolute capsule file: {abs_capsule}")
|
| 167 |
+
with open(abs_capsule, "rb") as f:
|
| 168 |
+
payload_bytes = f.read()
|
| 169 |
+
|
| 170 |
+
if not payload_bytes:
|
| 171 |
+
print("[-] Error: No input capsule file or packet directory found.")
|
| 172 |
+
sys.exit(1)
|
| 173 |
+
|
| 174 |
+
# 2. Decompress Zlib (L6)
|
| 175 |
+
print("\n[L6] Decompressing binary payload...")
|
| 176 |
+
try:
|
| 177 |
+
decompressed = zlib.decompress(payload_bytes)
|
| 178 |
+
print(f" Decompressed: {len(decompressed):,} bytes")
|
| 179 |
+
except Exception as e:
|
| 180 |
+
# If the input was the full padded packets, it might have trailing padding bytes.
|
| 181 |
+
# We need to trim trailing padding or parse headers.
|
| 182 |
+
# Let's try parsing directly or handle payload extraction
|
| 183 |
+
print(f"[-] Decompression failed: {e}")
|
| 184 |
+
sys.exit(1)
|
| 185 |
+
|
| 186 |
+
# 3. Parse Magic Header and Mode
|
| 187 |
+
pos = 0
|
| 188 |
+
magic = decompressed[pos:pos+3]; pos += 3
|
| 189 |
+
if magic != TK_MAGIC:
|
| 190 |
+
print(f"[-] Error: Invalid magic bytes: {magic.hex()}")
|
| 191 |
+
sys.exit(1)
|
| 192 |
+
|
| 193 |
+
mode = decompressed[pos]; pos += 1
|
| 194 |
+
print(f" Magic verified: 0x{magic.hex().upper()}")
|
| 195 |
+
print(f" Mode verified: Mode {mode} ({'Absolute' if mode == 1 else 'Reference/Oracle'})")
|
| 196 |
+
|
| 197 |
+
os.makedirs(args.out_dir, exist_ok=True)
|
| 198 |
+
|
| 199 |
+
# 4. Reconstruction
|
| 200 |
+
if mode == 1:
|
| 201 |
+
# --- Mode 1: Absolute Mode ---
|
| 202 |
+
print("\n[L2-L4] Restoring absolute tokenizer structures...")
|
| 203 |
+
|
| 204 |
+
# Unpack config metadata length and data
|
| 205 |
+
comp_config_len = struct.unpack_from('>I', decompressed, pos)[0]; pos += 4
|
| 206 |
+
comp_config_data = decompressed[pos : pos + comp_config_len]; pos += comp_config_len
|
| 207 |
+
config_meta = json.loads(zlib.decompress(comp_config_data).decode("utf-8"))
|
| 208 |
+
print(f" - Config metadata loaded ({len(config_meta)} keys)")
|
| 209 |
+
|
| 210 |
+
# Unpack vocabulary normal tokens
|
| 211 |
+
vocab_num = struct.unpack_from('>I', decompressed, pos)[0]; pos += 4
|
| 212 |
+
vocab_len = struct.unpack_from('>I', decompressed, pos)[0]; pos += 4
|
| 213 |
+
vocab_data = decompressed[pos : pos + vocab_len]; pos += vocab_len
|
| 214 |
+
|
| 215 |
+
vocab_list = decode_prefix_suffix(vocab_data, vocab_num)
|
| 216 |
+
print(f" - Restored {len(vocab_list):,} normal vocabulary tokens")
|
| 217 |
+
|
| 218 |
+
# Unpack merges
|
| 219 |
+
merges_num = struct.unpack_from('>I', decompressed, pos)[0]; pos += 4
|
| 220 |
+
merges_data = decompressed[pos : pos + merges_num * 6]; pos += merges_num * 6
|
| 221 |
+
|
| 222 |
+
merges = []
|
| 223 |
+
for i in range(merges_num):
|
| 224 |
+
idx0 = int.from_bytes(merges_data[i*6 : i*6 + 3], 'big')
|
| 225 |
+
idx1 = int.from_bytes(merges_data[i*6 + 3 : i*6 + 6], 'big')
|
| 226 |
+
t0 = vocab_list[idx0].decode("utf-8", errors="replace")
|
| 227 |
+
t1 = vocab_list[idx1].decode("utf-8", errors="replace")
|
| 228 |
+
merges.append(f"{t0} {t1}")
|
| 229 |
+
print(f" - Restored {len(merges):,} BPE merge entries")
|
| 230 |
+
|
| 231 |
+
# Reconstruct vocab.json and merges.txt
|
| 232 |
+
vocab_dict = {t.decode("utf-8", errors="replace"): idx for idx, t in enumerate(vocab_list)}
|
| 233 |
+
|
| 234 |
+
# Write merges.txt
|
| 235 |
+
merges_out = os.path.join(args.out_dir, "merges.txt")
|
| 236 |
+
with open(merges_out, "w", encoding="utf-8") as f:
|
| 237 |
+
f.write("\n".join(merges) + "\n")
|
| 238 |
+
|
| 239 |
+
# Write vocab.json
|
| 240 |
+
vocab_out = os.path.join(args.out_dir, "vocab.json")
|
| 241 |
+
with open(vocab_out, "w", encoding="utf-8") as f:
|
| 242 |
+
json.dump(vocab_dict, f, ensure_ascii=False, indent=2)
|
| 243 |
+
|
| 244 |
+
# Reconstruct tokenizer.json
|
| 245 |
+
reconstructed_t_json = {
|
| 246 |
+
"version": config_meta["version"],
|
| 247 |
+
"truncation": config_meta["truncation"],
|
| 248 |
+
"padding": config_meta["padding"],
|
| 249 |
+
"added_tokens": config_meta["added_tokens"],
|
| 250 |
+
"normalizer": config_meta["normalizer"],
|
| 251 |
+
"pre_tokenizer": config_meta["pre_tokenizer"],
|
| 252 |
+
"post_processor": config_meta["post_processor"],
|
| 253 |
+
"decoder": config_meta["decoder"],
|
| 254 |
+
"model": {
|
| 255 |
+
"type": config_meta["model_type"],
|
| 256 |
+
"dropout": config_meta["model_dropout"],
|
| 257 |
+
"unk_token": config_meta["model_unk_token"],
|
| 258 |
+
"continuing_subword_prefix": config_meta["model_continuing_subword_prefix"],
|
| 259 |
+
"end_of_word_suffix": config_meta["model_end_of_word_suffix"],
|
| 260 |
+
"fuse_unk": config_meta["model_fuse_unk"],
|
| 261 |
+
"byte_fallback": config_meta["model_byte_fallback"],
|
| 262 |
+
"ignore_merges": config_meta["model_ignore_merges"],
|
| 263 |
+
"vocab": vocab_dict,
|
| 264 |
+
"merges": merges
|
| 265 |
+
}
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
tokenizer_json_out = os.path.join(args.out_dir, "tokenizer.json")
|
| 269 |
+
with open(tokenizer_json_out, "w", encoding="utf-8") as f:
|
| 270 |
+
json.dump(reconstructed_t_json, f, ensure_ascii=False, indent=2)
|
| 271 |
+
|
| 272 |
+
# Write tokenizer_config.json
|
| 273 |
+
tokenizer_config_out = os.path.join(args.out_dir, "tokenizer_config.json")
|
| 274 |
+
with open(tokenizer_config_out, "w", encoding="utf-8") as f:
|
| 275 |
+
json.dump(config_meta["tokenizer_config"], f, ensure_ascii=False, indent=2)
|
| 276 |
+
|
| 277 |
+
print("[+] Stand-alone absolute reconstruction completed successfully.")
|
| 278 |
+
|
| 279 |
+
elif mode == 2:
|
| 280 |
+
# --- Mode 2: Reference Mode ---
|
| 281 |
+
print("\n[L5] Fetching base model tokenizer reference from HuggingFace...")
|
| 282 |
+
base_repo_len = struct.unpack_from('>H', decompressed, pos)[0]; pos += 2
|
| 283 |
+
base_repo = decompressed[pos : pos + base_repo_len].decode("utf-8"); pos += base_repo_len
|
| 284 |
+
print(f" - Base Oracle Reference: {base_repo}")
|
| 285 |
+
|
| 286 |
+
try:
|
| 287 |
+
# Load tokenizer from HF reference
|
| 288 |
+
print(f" - Querying Hugging Face: {base_repo} ...")
|
| 289 |
+
tokenizer = AutoTokenizer.from_pretrained(base_repo, trust_remote_code=True)
|
| 290 |
+
tokenizer.save_pretrained(args.out_dir)
|
| 291 |
+
print(f"[+] Successfully downloaded and saved tokenizer to: {args.out_dir}")
|
| 292 |
+
except Exception as e:
|
| 293 |
+
print(f"[-] Error downloading base tokenizer: {e}")
|
| 294 |
+
# Offline fallback if local files exist
|
| 295 |
+
local_fallback = "j:/Language-U/Language-U-V2/qwen-3.5-0.8b-local"
|
| 296 |
+
if os.path.exists(local_fallback):
|
| 297 |
+
print(f" - [Offline Fallback] Copying from local cache: {local_fallback}")
|
| 298 |
+
import shutil
|
| 299 |
+
for fn in ["tokenizer.json", "tokenizer_config.json", "vocab.json", "merges.txt"]:
|
| 300 |
+
src = os.path.join(local_fallback, fn)
|
| 301 |
+
if os.path.exists(src):
|
| 302 |
+
shutil.copy(src, os.path.join(args.out_dir, fn))
|
| 303 |
+
print(f"[+] Offline fallback copied successfully to: {args.out_dir}")
|
| 304 |
+
else:
|
| 305 |
+
sys.exit(1)
|
| 306 |
+
else:
|
| 307 |
+
print(f"[-] Error: Unknown tokenizer capsule mode: {mode}")
|
| 308 |
+
sys.exit(1)
|
| 309 |
+
|
| 310 |
+
# 5. Verification
|
| 311 |
+
print("\n[*] Verifying reconstructed tokenizer loading correctness...")
|
| 312 |
+
try:
|
| 313 |
+
loaded_tokenizer = AutoTokenizer.from_pretrained(args.out_dir, trust_remote_code=True)
|
| 314 |
+
print(f" [PASS] Reconstructed tokenizer successfully parsed by Transformers!")
|
| 315 |
+
|
| 316 |
+
# Test encoding
|
| 317 |
+
test_text = "Astronaut SHE LoRa concentrator GPIO reset SX1302 v3.0 Cuneiform-U"
|
| 318 |
+
tokens = loaded_tokenizer.encode(test_text)
|
| 319 |
+
decoded = loaded_tokenizer.decode(tokens)
|
| 320 |
+
print(f" [PASS] Test encoding round-trip succeeded!")
|
| 321 |
+
print(f" Encoded: {tokens[:8]}...")
|
| 322 |
+
print(f" Decoded: \"{decoded}\"")
|
| 323 |
+
|
| 324 |
+
print("\n" + "=" * 80)
|
| 325 |
+
print(" RESTORE SUCCESSFUL")
|
| 326 |
+
print("=" * 80)
|
| 327 |
+
print(f" Output folder: {os.path.abspath(args.out_dir)}")
|
| 328 |
+
print("=" * 80)
|
| 329 |
+
except Exception as e:
|
| 330 |
+
print(f"[-] Verification failed: {e}")
|
| 331 |
+
sys.exit(1)
|
| 332 |
+
|
| 333 |
+
if __name__ == "__main__":
|
| 334 |
+
main()
|