Skip to content
Song-Seng-HunPublic

About

Pure-PyTorch hierarchical dynamic-chunking multimodal architecture (H-Net × GDN-2 × Haru): byte-level text, VAE-free vision, action chunking, and audio.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

46 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

픽셀 아트 배너: 왼쪽 TEXT IN 상자의 hello world 글자가 한 글자씩 작은 UTF-8 바이트 타일(68, 65, 6C …)로 쪼개져 오른쪽 BYTES 줄로 흘러 들어갑니다. 동적 청킹이 노란 경계선을 긋고 바이트를 청크별 색으로 묶으면, 청크가 블록이 되어 L1(he, llo, wo, rld)로 올라가고, L2에서 hello와 world로 합쳐지고, L3에서 hello world 하나가 됩니다. 그다음 계층을 L3, L2, L1 순서로 거꾸로 내려오며 바이트 타일이 하나씩 노랗게 깜빡이고, 오른쪽 TEXT OUT 상자에 hello world가 다시 조립되어 OK가 뜬 뒤 처음으로 돌아갑니다.

H-nets — Hierarchical Byte-Level LM (H-Net × Stable GDN-2)

Pure-PyTorch N-level hierarchical UTF-8 byte-level language model (tokenizer-free, vocab=258) combining dynamic chunking (H-Net) with Stable Gated DeltaNet-2 (GDN-2), GQA Gated Attention, Weight Programming (WP v7), and NorMuon + WSD — designed to train cleanly even on a single 6GB consumer GPU via progressive growing (L1 → 2L → 3L).


Key Architecture Highlights

  • Tokenizer-Free Multilingual UTF-8 (vocab=258): Raw UTF-8 bytes (0..255) + 256=BOS + 257=MASK/PAD, with byte-level UTF-8 boundary guard, script-transition prior, and Engram router prior strictly attached to Level 0.
  • Recursive N-Level U-Net Builder (hnets/model.py):
    • 2L_110M (115.17M, 1st Target): L1 (d=384, 2+2L GDN-2, r=0.25) → Center (d=1024, GGGA×2 = G6+A2).
    • 3L_150M_384 (150.49M, 3-Level Target): L1 (384, r=1/4) → L2 (768, r=1/3) → L3 Center (1024, GGGA×2).
  • Verified Core Primitives:
    • Stable GDN-2: Symmetric erasure, low-rank 3-gates (decay/erase/write), FP32 WY fixed-anchor island, Falcon high_half key shift on L1 encoder.
    • Central Hybrid LM (GGGA×2): GQA CausalAttnBlock with v_mode="vblend", gate_mode="elem" (Gated Attention), Q-Conv, QK-Norm, KV Sinks, Center-only HorizontalLatticeStream (d=64, Continuous-Time Liquid $\Delta t$ via causal byte_pos), and DepthAttnRes (D4) / LDM memory switch.
    • Joint Weight Programming (WP v7) & 2L→3L SVD Bridge Transplant: 100% plastic (0 frozen params) byte/Haar anchors + row-energy-preserving orthogonalization, plus rank-preserving SVD decomposition (384 ↔ 1024 → 384 ↔ 768 ↔ 1024, FP32 error <= 2.4e-7) that cuts 3L Step-0 eval loss from 3.1526 to 1.9083.
    • Optimizer, Schedule & Portable Resume: Pure-PyTorch NorMuon + Momentum Warmup (0.85→0.95) + Cautious Weight Decay + WSD (FP16 GradScaler support) and geometry-flexible stream resume (e.g., Colab T4 B4/L2048 ↔ local 6GB B1/L1024 while preserving article cursors).
    • Experimental Pretrained Center (hnets/qwen35_center.py): Pure-PyTorch Qwen3.5-0.8B-Base center stack with exact FP32/FP16 parity (max diff = 0 vs transformers 5.3.0), function-preserving GDN-2 (delta_gamma=0), and zero-init HorizontalLatticeStream.
    • N-Level Streaming Cache & Bulk Prefill (StreamingState, prefill, step): Zero-new-parameter incremental cache threading GDN-2 states/conv/key-shift, Attention KV/RoPE/V-blend pending, Lattice raw states, and N-level Router/Dechunk states, with parallel bulk segment prefill.
    • UTF-8 Safe Generation (generate): Built-in RFC 3629 UTF-8 grammar DFA (utf8_safe=True), budget-aware character-boundary termination (blocks invalid bytes, BOS/MASK, and mid-character truncation), plus opt-in min_p sampling (min_p=0.0 default).
    • Multimodal & Agent Extensions (v0.1): Pure-PyTorch VisionHiT (hnets/vision_hit.py), AudioHNet (hnets/audio_hnet.py), ActionHNet (hnets/action_hnet.py), PlatonSlotFusion + MultimodalSession (hnets/multimodal_session.py), 63-channel relative action_codec / VirtualExecutor handover (hnets/action_codec.py, hnets/action_handover.py), and a procedural 256×256 SyntheticUIEnv benchmark (hnets/synthetic_ui.py).
    • Companion Data & Runtime Pipeline: Capture, compressed video/Parquet datasets, replay, and OS execution are maintained in the companion repository leGamer (H-nets owns the pure-PyTorch multimodal model architecture).

Training Results (Updated 2026-12-02)

Stage / Run Model Hardware & Recipe Steps Best Eval (mean) Peak VRAM Status
Stage 1 (L1 Pre-align) L1_prealign_384 (17.46M) RTX 2060 6GB (L=512) 6,000 / 6,000 2.0614 (ko 1.49 / en 2.23 / ja 1.27 / code 3.26) 2.02 GB Completed
Stage 2 (Progressive 2L) 2L_110M (115.17M) RTX 2060 6GB (L=512) 5,000 / 5,000 1.8867 (ko 1.39 / en 2.06 / ja 1.16 / code 2.94) 6.16 GB Completed (0 skips)
Exp: Qwen3.5 8L Slice 2L_Qwen35_8L_split (179.18M) RTX 2060 6GB (B2/a2/L512) 5,000 / 5,000 2.0246 (ko 1.46 / en 2.22 / ja 1.20 / code 3.22) 2.79 GiB Archived (0 skips; pure 2L outperformed)
Stage 3 (Progressive 3L) 3L_150M_384 (150.49M, SVD + DepthAttnRes) Colab T4 (0→1k, B4/a2/L2048) → RTX 2060 6GB (1k→5k, B1/a4/L1024, ckpt ON) 5,000 / 5,000 1.8452 fixed eval @ step_05000.pt (short-probe best 1.8641 @ step 800) 12.20 GiB (T4) / 3.68 GiB (local 6GB) Completed (4,996 updates / 4 skips; selected text base)
  • Stage 2 (2L_110M): During WSD cosine decay (steps 3,750–5,000), held-out eval dropped from 1.9904 (step 3,500) to 1.8867 (step 5,000).
  • Stage 3 (3L_150M_384): SVD bridge transplant preserved 2L alignment (3.1526 random → 1.9083 Step-0), surpassed 2L_110M best (1.8867) within 400 steps (1.8760), and completed all 5,000 steps via T4 → local 6GB relay (step_05000.pt fixed eval 1.8452) as the official text base for multimodal experiments.

3-Level Hierarchical Chunking Samples (3L_150M_384 @ step 1,000, temp=0.8, tokenizer-free)

Separate L1 (r ≈ 0.25) and L2 (r ≈ 0.33 of L1) boundaries on actual step-1,000 generations. Note: total 3L data seen so far is ~16.4 MB across ko/en/ja, so semantic coherence is still in an early stage while L1 learns syllable/word splits and L2 begins grouping multi-word phrases.

  • Korean (L1 r=0.180, L2 r=0.098 vs bytes)
    • Text: 대한민국의 수도는 보나이었다. 애시리스의 대병에 미법난데 범터청 광주 시임적이 재작역
    • L1: 대|한|민국|의 수도는 |보|나이었다|. |애|시리스의 |대|병에 |미법|난|데 |범터|청 광|주 |시임|적이 |재|작|역
    • L2: 대한|민국의 수도는 |보|나이었다|. |애|시리스의 |대|병에 미법난데 범터|청 광|주 |시임|적이 재작역
  • English (L1 r=0.242, L2 r=0.075 vs bytes)
    • Text: Artificial intelligence group in the United States. There is form Your Has Prattent of Maine. The American cane a single
    • L1: Artificial in|tellige|nce |g|ro|up i|n |the |Uni|ted |St|a|te|s. |There is |f|o|rm Your |Ha|s |Pratten|t |of |Maine. |The |Ame|rican cane |a |single
    • L2: Artificial in|telligence |group in the |United Sta|te|s. There is |f|orm Your Has Prattent of Maine. |The American cane a |single
  • Japanese (L1 r=0.265, L2 r=0.120 vs bytes)
    • Text: 日本語の文章は『シャルン』とは拾おうとも言い手に配向された。一方、親の難しくは
    • L1: 日|本語|の|文章|は|『シ|ャ|ル|ン|』|と|は|拾|おうとも|言|い|手|に|配向|され|た|。|一|方|、|親|の|難|し|く|は
    • L2: 日|本語|の文章は『シャルン』|とは|拾おうとも|言|い手に配向された|。一方|、親|の|難|し|く|は

Multilingual Generation Samples + L1 Chunk Boundaries (2L_110M best.pt @ step 5,000, temp=0.8, tokenizer-free)

| marks dynamic L1 chunk boundaries chosen by the router (target r = 0.25). 2L_110M has one routing stage (L1 → Center); 3-level (3L_150M_384) and deeper models automatically print separate L1 / L2 / L3 boundary lines via inspect_hierarchical_chunks().

  • Korean (27 chunks / 105 B = 0.257)
    • Text: 대한민국의 수도는 마쓰다이라 있는 방송에서 제6:20이 있다. 왕카 같이 보기 L
    • Chunks: 대한|민국의 |수도|는 |마|쓰|다|이|라 |있는 |방송|에|서 |제|6|:20|이| |있|다|. |왕|카 |같|이 |보기 |L
  • English (27 chunks / 104 B = 0.260)
    • Text: Artificial intelligence convoy of Servited States. The May Alice Islands, and remaining in the made per
    • Chunks: Ar|tificial in|telligence |con|voy of Ser|vi|te|d |St|a|te|s. |The |May Alice |Isla|n|ds|, a|n|d |rem|aini|n|g in |the m|a|de per
  • Japanese (23 chunks / 101 B = 0.228)
    • Text: 日本語の文章は、美術の小説から「シュリームランジャーズ」と呼ぶ。 そ
    • Chunks: 日|本語|の|文章|は、|美術|の|小説|か|ら|「|シ|ュ|リ|ーム|ラン|ジャ|ーズ|」と|呼|ぶ|。 |そ

Streaming Cache & Bulk Prefill Benchmarks (2L_110M best.pt, RTX 2060 6GB, FP16)

  • 64B Greedy Generation (12B prompt): 42.32s (use_cache=False) → 8.51s (use_cache=True, ~5.0× speedup, 64/64 exact byte match, 0 new parameters).
  • Bulk Cached Prefill vs. Serial Stream Prefill (median of 2 timed runs after warmup, full == serial == bulk 64B greedy match on all 4 cases):
Batch × Input (incl. BOS) Serial Prefill Bulk Prefill Speedup Peak Prefill VRAM (Serial / Bulk) 64B Greedy Match
1 × 32 2.332s 0.256s 9.1× 671.4 / 672.2 MiB Exact
1 × 512 59.100s 0.521s 113.5× 673.1 / 699.9 MiB Exact
1 × 2048 231.180s 0.781s 296.2× 678.6 / 797.9 MiB Exact
2 × 512 117.702s 0.751s 156.8× 675.9 / 703.4 MiB Exact

Repository Structure

H-nets/
├── README.md
├── .gitignore
├── hnets/
│   ├── __init__.py
│   ├── model.py              # Recursive N-level H-Net x Stable GDN-2 + WP v7 + --test suite
│   ├── optim.py              # NorMuon + Momentum Warmup + Cautious WD + WSD schedule
│   ├── qwen35_center.py      # Experimental Qwen3.5-0.8B-Base center + function-preserving GDN-2 & Lattice
│   ├── vision_hit.py         # VisionHiT hierarchical vision encoder (v0.1)
│   ├── audio_hnet.py         # AudioHNet hierarchical audio encoder (v0.1)
│   ├── action_hnet.py        # ActionHNet relative action decoder head (v0.1)
│   ├── action_codec.py       # 63-channel relative action codec & state contracts
│   ├── action_handover.py    # VirtualExecutor & safe handover contracts
│   ├── multimodal_session.py # PlatonSlotFusion & MultimodalSession orchestration
│   └── synthetic_ui.py       # Procedural 256x256 SyntheticUIEnv & OracleRelativePolicy
├── tests/
│   ├── test_vision_hit.py
│   ├── test_audio_hnet.py
│   ├── test_action_hnet.py
│   ├── test_multimodal_session.py
│   └── test_synthetic_ui.py
├── scripts/
│   ├── train_l1.py           # Local 6GB GPU Level-1 pre-alignment (L1_prealign_384, 17.46M)
│   ├── train_l2.py           # Local 6GB GPU progressive growing (2L_110M, 115.17M)
│   ├── train_l3.py           # Progressive 2L->3L SVD expansion (3L_150M_384, flexible T4/local resume, W&B)
│   ├── train_qwen35.py       # Experimental 2-phase Qwen3.5 8L center training script
│   └── merge_checkpoints.py  # WSM / Model Soup checkpoint weight averaging utility
└── notebooks/
    └── 02_hnet_hierarchical_train.ipynb  # All-in-one Colab / local progressive training notebook

Quick Start

1. Run Built-In & Multimodal Verification Suites

python hnets/model.py --test
python -m unittest discover -s tests -v

2. Local Progressive Training (6GB GPU)

# Stage 1: Level-1 pre-alignment (17.46M, ~2.0 GB VRAM)
python -u scripts/train_l1.py --steps 6000 --warmup 200

# Stage 2: Progressive expansion to 2L_110M (115.17M, ~4.7 GB VRAM)
python -u scripts/train_l2.py --steps 5000 --warmup 200 --skip-articles 10000

3. Progressive 2L → 3L Training (3L_150M_384, Colab T4 / Local 6GB Relay)

# Start from 2L_110M best.pt with SVD bridge transplant (Colab T4 15GB)
python -u scripts/train_l3.py \
  --steps 5000 --seq-len 2048 --batch-size 4 --grad-accum 2 \
  --amp auto --bridge-init svd --eval-every 200 --save-every 200 \
  --init-ckpt /path/to/2L_best.pt --out-dir /path/to/3L_150M_t4 \
  --wandb-project h-nets --wandb-name 3L_150M_t4

# Flexible resume on a 6GB local GPU (preserves article stream cursors across geometry change)
python -u scripts/train_l3.py \
  --resume --steps 5000 --seq-len 1024 --batch-size 1 --grad-accum 4 \
  --grad-checkpoint --amp auto --out-dir /path/to/3L_150M_local

Alternatively, open notebooks/02_hnet_hierarchical_train.ipynb on Colab (T4 / L4 / A100), set PRESET = "2L_110M" (or "3L_150M_384" with INIT_FROM_CKPT), DATA_SOURCE = "wiki_ko_en_ja", and run all cells.

4. WSM / Model Soup Averaging

python scripts/merge_checkpoints.py --inputs ckpt_a.pt ckpt_b.pt --output merged_soup.pt

5. Cached UTF-8 Safe Generation & Streaming API

import torch
from hnets import HierarchicalHNetLM, PRESETS

model = HierarchicalHNetLM(PRESETS["2L_110M"]).cuda().eval()
prompt = torch.tensor([[256] + list("대한민국의 수도는".encode("utf-8"))], device="cuda")

# Fast cached generation with RFC 3629 UTF-8 safety and optional min-p
out_ids = model.generate(prompt, max_new_tokens=64, temperature=0.8, use_cache=True, utf8_safe=True, min_p=0.05)
print(bytes(out_ids[0, 1:].tolist()).decode("utf-8"))

# Explicit segment prefill + single-byte step (multi-turn / streaming)
prefilled = model.prefill(prompt, last_token_only=True)
stepped = model.step(out_ids[:, -1:], prefilled["cache"], last_token_only=True)

6. Inspect N-Level Chunk Boundaries (L1 / L2 / L3+)

from hnets import HierarchicalHNetLM, PRESETS, inspect_hierarchical_chunks

model = HierarchicalHNetLM(PRESETS["3L_150M_384"])  # or 2L_110M / 4L
res = inspect_hierarchical_chunks(model, "대한민국의 수도 서울은 한강을 중심으로 발전했다.")
print(res["formatted"])
# L1 (r=0.25, ...): ...|...|...
# L2 (r=0.09, ...): ...|...
# L3 (r=0.04, ...): ...|...  (for 4L+)

Notes

  • Weights (*.pt), datasets, caches, and logs are excluded via .gitignore.
  • No external custom CUDA/Triton kernels are required — runs in standard PyTorch 2.x.

License

This project is licensed under the Apache License 2.0.

Independent Implementation & Disclaimer

  • This repository is an independent, clean-room pure-PyTorch implementation inspired by publicly available research papers (including H-Net, Gated DeltaNet-2 / Stable GDN-2, Memory Mosaics, DepthAttnRes, and NorMuon).
  • It does not copy or include source code or pretrained weights from the respective official repositories (which may carry different licenses, such as MIT, Apache-2.0, or non-commercial research licenses).
  • Provided "as is" under Apache-2.0 without warranty; users are responsible for verifying any third-party patents or compliance requirements for their intended (including commercial) use.

About

Pure-PyTorch hierarchical dynamic-chunking multimodal architecture (H-Net × GDN-2 × Haru): byte-level text, VAE-free vision, action chunking, and audio.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages