Delete convert_to_7b.py
Browse files- convert_to_7b.py +0 -175
convert_to_7b.py
DELETED
|
@@ -1,175 +0,0 @@
|
|
| 1 |
-
# ==============================================================================
|
| 2 |
-
# COPYRIGHT (C) 2026 KONSTANTIN VLADIMIROVICH GRABKO. ALL RIGHTS RESERVED.
|
| 3 |
-
# PATENT PENDING | CMS MANHATTAN JIRACK TECHNOLOGY
|
| 4 |
-
# ==============================================================================
|
| 5 |
-
#
|
| 6 |
-
# grow_to_7b.py
|
| 7 |
-
# -------------
|
| 8 |
-
# Grow a trained JiRackNative checkpoint into a larger model by:
|
| 9 |
-
# (A) widening the FFN of every existing layer to a target intermediate size
|
| 10 |
-
# (new neurons: input side random, output side zero -> alive, not dead)
|
| 11 |
-
# (B) inserting NEW transformer layers initialized as IDENTITY:
|
| 12 |
-
# out_proj.weight = 0 , ffn_w2.weight = 0 -> block computes x -> x
|
| 13 |
-
# q/k/v/ffn_w1/ffn_w3 = small random -> gradient flows, learns
|
| 14 |
-
# norm1/norm2 = 1
|
| 15 |
-
# New layers are interleaved among the trained ones (not appended in one
|
| 16 |
-
# block), which trains more stably.
|
| 17 |
-
#
|
| 18 |
-
# Why not duplicate layers? Copied layers share identical gradients and stay
|
| 19 |
-
# locked together -> no real added capacity. Identity-init new layers do add
|
| 20 |
-
# capacity while preserving the function at initialization (no loss spike).
|
| 21 |
-
#
|
| 22 |
-
# After running:
|
| 23 |
-
# 1) set NUM_LAYERS = <--layers> and INTERMEDIATE_SIZE = <--intermediate>
|
| 24 |
-
# in JiRackNative_3b.py
|
| 25 |
-
# 2) load the new checkpoint and continue training (normal LR; a short warmup
|
| 26 |
-
# helps the new layers settle)
|
| 27 |
-
#
|
| 28 |
-
# Example (3B -> ~7B, 36 layers, intermediate 16384):
|
| 29 |
-
# python grow_to_7b.py --in jirack_3b.safetensors --out jirack_7b.safetensors \
|
| 30 |
-
# --layers 36 --intermediate 16384
|
| 31 |
-
# ==============================================================================
|
| 32 |
-
|
| 33 |
-
import argparse
|
| 34 |
-
import glob
|
| 35 |
-
import math
|
| 36 |
-
import os
|
| 37 |
-
import torch
|
| 38 |
-
from safetensors.torch import load_file, save_file
|
| 39 |
-
|
| 40 |
-
INIT_STD = 0.02
|
| 41 |
-
torch.manual_seed(0)
|
| 42 |
-
|
| 43 |
-
# suffix -> how to initialize a NEW layer's tensor
|
| 44 |
-
# "rand" small gaussian | "zero" zeros | "one" ones
|
| 45 |
-
NEW_LAYER_INIT = {
|
| 46 |
-
"q_proj.weight": "rand",
|
| 47 |
-
"k_proj.weight": "rand",
|
| 48 |
-
"v_proj.weight": "rand",
|
| 49 |
-
"out_proj.weight": "zero", # -> attention residual = 0 at init
|
| 50 |
-
"ffn_w1.weight": "rand",
|
| 51 |
-
"ffn_w3.weight": "rand",
|
| 52 |
-
"ffn_w2.weight": "zero", # -> ffn residual = 0 at init
|
| 53 |
-
"norm1.weight": "one",
|
| 54 |
-
"norm2.weight": "one",
|
| 55 |
-
}
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
def load_state(path):
|
| 59 |
-
if os.path.isdir(path):
|
| 60 |
-
sd = {}
|
| 61 |
-
for f in sorted(glob.glob(os.path.join(path, "*.safetensors"))):
|
| 62 |
-
sd.update(load_file(f))
|
| 63 |
-
if not sd:
|
| 64 |
-
raise FileNotFoundError(f"No .safetensors in {path}")
|
| 65 |
-
return sd
|
| 66 |
-
return load_file(path)
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
def detect_layers(sd):
|
| 70 |
-
idx = set()
|
| 71 |
-
for k in sd:
|
| 72 |
-
if k.startswith("blocks."):
|
| 73 |
-
idx.add(int(k.split(".")[1]))
|
| 74 |
-
return sorted(idx)
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
def widen_ffn(block, target_I):
|
| 78 |
-
"""In-place widen one block's FFN tensors to target intermediate size."""
|
| 79 |
-
w1 = block["ffn_w1.weight"]
|
| 80 |
-
cur_I, H = w1.shape
|
| 81 |
-
if target_I <= cur_I:
|
| 82 |
-
return block
|
| 83 |
-
add = target_I - cur_I
|
| 84 |
-
dt, dev = w1.dtype, w1.device
|
| 85 |
-
for name in ("ffn_w1.weight", "ffn_w3.weight"): # [I, H]: new rows random
|
| 86 |
-
w = block[name]
|
| 87 |
-
new_rows = torch.randn(add, H, dtype=dt, device=dev) * INIT_STD
|
| 88 |
-
block[name] = torch.cat([w, new_rows], dim=0)
|
| 89 |
-
w2 = block["ffn_w2.weight"] # [H, I]: new cols zero
|
| 90 |
-
new_cols = torch.zeros(w2.shape[0], add, dtype=dt, device=dev)
|
| 91 |
-
block["ffn_w2.weight"] = torch.cat([w2, new_cols], dim=1)
|
| 92 |
-
return block
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
def make_identity_block(template):
|
| 96 |
-
"""Build a fresh identity-initialized block from {suffix: tensor} template."""
|
| 97 |
-
out = {}
|
| 98 |
-
for suffix, ref in template.items():
|
| 99 |
-
rule = NEW_LAYER_INIT[suffix]
|
| 100 |
-
if rule == "zero":
|
| 101 |
-
out[suffix] = torch.zeros_like(ref)
|
| 102 |
-
elif rule == "one":
|
| 103 |
-
out[suffix] = torch.ones_like(ref)
|
| 104 |
-
else: # rand
|
| 105 |
-
out[suffix] = torch.randn_like(ref) * INIT_STD
|
| 106 |
-
return out
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
def main():
|
| 110 |
-
ap = argparse.ArgumentParser()
|
| 111 |
-
ap.add_argument("--in", dest="inp", required=True)
|
| 112 |
-
ap.add_argument("--out", dest="out", required=True)
|
| 113 |
-
ap.add_argument("--layers", type=int, required=True, help="target NUM_LAYERS")
|
| 114 |
-
ap.add_argument("--intermediate", type=int, default=0,
|
| 115 |
-
help="target INTERMEDIATE_SIZE (0 = keep current)")
|
| 116 |
-
args = ap.parse_args()
|
| 117 |
-
|
| 118 |
-
print(f"Loading {args.inp} ...")
|
| 119 |
-
sd = load_state(args.inp)
|
| 120 |
-
old_idx = detect_layers(sd)
|
| 121 |
-
old_L = len(old_idx)
|
| 122 |
-
if args.layers < old_L:
|
| 123 |
-
raise ValueError(f"--layers ({args.layers}) < existing layers ({old_L})")
|
| 124 |
-
|
| 125 |
-
# --- pull each existing block into a dict of {suffix: tensor} ---
|
| 126 |
-
def block_of(j):
|
| 127 |
-
pfx = f"blocks.{j}."
|
| 128 |
-
return {k[len(pfx):]: v for k, v in sd.items() if k.startswith(pfx)}
|
| 129 |
-
|
| 130 |
-
orig_blocks = [block_of(j) for j in old_idx]
|
| 131 |
-
|
| 132 |
-
# --- (A) widen FFN of every existing block ---
|
| 133 |
-
tgt_I = args.intermediate or orig_blocks[0]["ffn_w1.weight"].shape[0]
|
| 134 |
-
for b in orig_blocks:
|
| 135 |
-
widen_ffn(b, tgt_I)
|
| 136 |
-
template = orig_blocks[0] # correct shapes AFTER widening, for identity blocks
|
| 137 |
-
|
| 138 |
-
# --- (B) decide where trained layers sit; fill gaps with identity ---
|
| 139 |
-
L_new = args.layers
|
| 140 |
-
step = L_new / old_L
|
| 141 |
-
positions = [int(math.floor(i * step)) for i in range(old_L)] # strictly increasing
|
| 142 |
-
pos_to_orig = {p: i for i, p in enumerate(positions)}
|
| 143 |
-
|
| 144 |
-
new_sd = {}
|
| 145 |
-
# copy non-layer tensors unchanged (token_emb, ln_f, lm_head, buffers)
|
| 146 |
-
for k, v in sd.items():
|
| 147 |
-
if not k.startswith("blocks."):
|
| 148 |
-
new_sd[k] = v
|
| 149 |
-
|
| 150 |
-
n_identity = 0
|
| 151 |
-
for n in range(L_new):
|
| 152 |
-
if n in pos_to_orig:
|
| 153 |
-
block = orig_blocks[pos_to_orig[n]]
|
| 154 |
-
else:
|
| 155 |
-
block = make_identity_block(template)
|
| 156 |
-
n_identity += 1
|
| 157 |
-
for suffix, tensor in block.items():
|
| 158 |
-
new_sd[f"blocks.{n}.{suffix}"] = tensor
|
| 159 |
-
|
| 160 |
-
# --- report ---
|
| 161 |
-
total = sum(t.numel() for t in new_sd.values())
|
| 162 |
-
print(f"Existing layers : {old_L} -> new layers: {L_new} "
|
| 163 |
-
f"({n_identity} identity-initialized)")
|
| 164 |
-
print(f"Intermediate : {tgt_I}")
|
| 165 |
-
print(f"Trained layers placed at indices: {positions}")
|
| 166 |
-
print(f"Total parameters: {total/1e9:.3f} B")
|
| 167 |
-
|
| 168 |
-
print(f"Saving {args.out} ...")
|
| 169 |
-
save_file(new_sd, args.out)
|
| 170 |
-
print("Done. New layers start as identity (no loss spike) and learn from ~step 2.")
|
| 171 |
-
print("Remember to update NUM_LAYERS and INTERMEDIATE_SIZE in the model file.")
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
if __name__ == "__main__":
|
| 175 |
-
main()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|