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

20 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

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).

Training Results (Updated 2026-12-01)

Stage / Run Model Hardware & Recipe Steps Best Short-Probe 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 15GB (B4/a2/L2048, ckpt OFF) 1,000 / 5,000 1.8641 @ step 800 (ko 1.42 / en 2.07 / ja 1.09 / code 2.88; step 1k 1.8879) 12.20 GiB In Progress (56 min for 1k; continuing)
  • 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), surpassing 2L_110M best (1.8867) within 400 steps (1.8760) and hitting 1.8641 at step 800 while still in the WSD stable plateau (decay scheduled for steps 3,750–5,000).

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
├── 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 Verification Suite

python hnets/model.py --test

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.

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