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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
Generate FUNCTIONALLY CORRECT MLP weights for Gemma 4 31B (SwiGLU) integration.
|
| 4 |
+
Uses Sign-Symmetric Aligned Pairs to eliminate mean-shift without destroying alignment.
|
| 5 |
+
|
| 6 |
+
Gemma 4 31B architecture:
|
| 7 |
+
- 60 transformer layers (10 global full-context + 50 sliding-window attention)
|
| 8 |
+
- Interleaved attention: 5 SWA (sliding-window, 1024-token context) + 1 global full-context (period=6)
|
| 9 |
+
- Global attention layers (5, 11, 17, 23, 29, 35, 41, 47, 53, 59) use double-wide MLP
|
| 10 |
+
- Activation: gelu_pytorch_tanh
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
import argparse
|
| 14 |
+
import json
|
| 15 |
+
import time
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from safetensors.torch import load_file, save_file
|
| 21 |
+
from scipy.special import expit as _sigmoid
|
| 22 |
+
|
| 23 |
+
# ---------------------------------------------------------------------------
|
| 24 |
+
# Config
|
| 25 |
+
# ---------------------------------------------------------------------------
|
| 26 |
+
|
| 27 |
+
NEURON_SOURCE = "single"
|
| 28 |
+
SINGLE_FILE = "test_mlp_hf/model.safetensors"
|
| 29 |
+
MULTI_DIR = "generated_neurons/gaussian"
|
| 30 |
+
|
| 31 |
+
SINGLE_BOUNDARY_MODE = True
|
| 32 |
+
|
| 33 |
+
# Gemma 4 31B defaults
|
| 34 |
+
N_LAYERS = 60
|
| 35 |
+
HIDDEN_SIZE = 3840
|
| 36 |
+
INTERMEDIATE_SIZE = 15360
|
| 37 |
+
|
| 38 |
+
# Gemma 4 31B interleaved attention: 5 SWA layers then 1 global, repeating.
|
| 39 |
+
# Global layers use double-wide MLP intermediate size.
|
| 40 |
+
INTERLEAVE_PERIOD = 6 # one global every 6 layers
|
| 41 |
+
GLOBAL_LAYER_OFFSET = 5 # first global is at index 5 (0-based)
|
| 42 |
+
DEFAULT_ACTIVATION = "gelu_pytorch_tanh"
|
| 43 |
+
|
| 44 |
+
OUTPUT_DIR = "generated_weights_gemma4_31b"
|
| 45 |
+
RANDOM_SEED = 42
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def is_global_attention_layer(layer_idx: int, period: int = INTERLEAVE_PERIOD,
|
| 49 |
+
offset: int = GLOBAL_LAYER_OFFSET) -> bool:
|
| 50 |
+
"""Return True if this layer uses global full-context attention (and thus double-wide MLP)."""
|
| 51 |
+
return (layer_idx - offset) % period == 0 and layer_idx >= offset
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def get_gating_function(name):
|
| 55 |
+
if name == "silu":
|
| 56 |
+
return _sigmoid
|
| 57 |
+
elif name == "gelu_pytorch_tanh":
|
| 58 |
+
alpha = np.sqrt(2.0 / np.pi)
|
| 59 |
+
return lambda z: 0.5 * (1.0 + np.tanh(alpha * (z + 0.044715 * z**3)))
|
| 60 |
+
elif name == "gelu":
|
| 61 |
+
from scipy.special import erf
|
| 62 |
+
return lambda z: 0.5 * (1.0 + erf(z / np.sqrt(2.0)))
|
| 63 |
+
else:
|
| 64 |
+
raise ValueError(f"Unsupported activation: {name}")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_activation(name):
|
| 68 |
+
g_fn = get_gating_function(name)
|
| 69 |
+
return lambda z: z * g_fn(z)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
# ---------------------------------------------------------------------------
|
| 73 |
+
# 1. Load and extract functional parameters
|
| 74 |
+
# ---------------------------------------------------------------------------
|
| 75 |
+
|
| 76 |
+
def load_neurons(source, single_file, multi_dir):
|
| 77 |
+
"""Load source neurons."""
|
| 78 |
+
neurons = []
|
| 79 |
+
if source == "single":
|
| 80 |
+
w = load_file(single_file)
|
| 81 |
+
neurons.append(
|
| 82 |
+
{
|
| 83 |
+
k: v.float().numpy()
|
| 84 |
+
for k, v in {
|
| 85 |
+
"W1": w["layer1.weight"],
|
| 86 |
+
"b1": w["layer1.bias"],
|
| 87 |
+
"W2": w["layer2.weight"],
|
| 88 |
+
"b2": w["layer2.bias"],
|
| 89 |
+
}.items()
|
| 90 |
+
}
|
| 91 |
+
)
|
| 92 |
+
elif source == "multi":
|
| 93 |
+
for f in sorted(Path(multi_dir).glob("neuron_*.safetensors")):
|
| 94 |
+
w = load_file(str(f))
|
| 95 |
+
neurons.append(
|
| 96 |
+
{
|
| 97 |
+
k: v.float().numpy()
|
| 98 |
+
for k, v in {
|
| 99 |
+
"W1": w["layer1.weight"],
|
| 100 |
+
"b1": w["layer1.bias"],
|
| 101 |
+
"W2": w["layer2.weight"],
|
| 102 |
+
"b2": w["layer2.bias"],
|
| 103 |
+
}.items()
|
| 104 |
+
}
|
| 105 |
+
)
|
| 106 |
+
return neurons
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def extract_functional_params(W1, b1, W2, b2, n_samples=10000):
|
| 110 |
+
"""Extract piecewise linear parameters from reference neurons."""
|
| 111 |
+
xs = np.linspace(-4, 4, n_samples)
|
| 112 |
+
ys = []
|
| 113 |
+
|
| 114 |
+
for x in xs:
|
| 115 |
+
h = np.maximum(0, W1 @ np.array([[x]]) + b1.reshape(-1, 1))
|
| 116 |
+
y = (W2 @ h + b2.reshape(-1, 1)).item()
|
| 117 |
+
ys.append(y)
|
| 118 |
+
|
| 119 |
+
ys = np.array(ys)
|
| 120 |
+
slopes = np.gradient(ys, xs)
|
| 121 |
+
slope_changes = np.abs(np.gradient(slopes, xs))
|
| 122 |
+
|
| 123 |
+
from scipy.signal import find_peaks
|
| 124 |
+
peaks, _ = find_peaks(slope_changes, height=np.max(slope_changes) * 0.1, distance=100)
|
| 125 |
+
|
| 126 |
+
if len(peaks) >= 2:
|
| 127 |
+
idx1, idx2 = sorted(peaks[:2])
|
| 128 |
+
elif len(peaks) == 1:
|
| 129 |
+
idx1, idx2 = 0, peaks[0]
|
| 130 |
+
else:
|
| 131 |
+
idx1, idx2 = n_samples // 3, 2 * n_samples // 3
|
| 132 |
+
|
| 133 |
+
boundary_x1 = float(xs[idx1])
|
| 134 |
+
boundary_x2 = float(xs[idx2])
|
| 135 |
+
|
| 136 |
+
left_slope = float(np.mean(slopes[:idx1])) if idx1 > 0 else float(slopes[0])
|
| 137 |
+
mid_slope = float(np.mean(slopes[idx1:idx2]))
|
| 138 |
+
right_slope = float(np.mean(slopes[idx2:]))
|
| 139 |
+
y_boundary2 = float(ys[idx2])
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"boundary_x1": boundary_x1,
|
| 143 |
+
"boundary_x2": boundary_x2,
|
| 144 |
+
"left_slope": left_slope,
|
| 145 |
+
"mid_slope": mid_slope,
|
| 146 |
+
"right_slope": right_slope,
|
| 147 |
+
"y_boundary2": y_boundary2,
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
# ---------------------------------------------------------------------------
|
| 152 |
+
# 2. Construct functional dense layer (Sign-Symmetric Aligned Pairs)
|
| 153 |
+
# ---------------------------------------------------------------------------
|
| 154 |
+
|
| 155 |
+
def construct_functional_layer(
|
| 156 |
+
functional_params,
|
| 157 |
+
hidden_size,
|
| 158 |
+
intermediate_size,
|
| 159 |
+
gating_fn,
|
| 160 |
+
activation_fn,
|
| 161 |
+
has_bias=False,
|
| 162 |
+
source_weights=None,
|
| 163 |
+
rng_seed: int = 0,
|
| 164 |
+
):
|
| 165 |
+
p = functional_params
|
| 166 |
+
boundary = p["boundary_x1"]
|
| 167 |
+
left_slope = p["left_slope"]
|
| 168 |
+
right_slope = p["right_slope"]
|
| 169 |
+
|
| 170 |
+
W_gate = np.zeros((intermediate_size, hidden_size), dtype=np.float32)
|
| 171 |
+
W_up = np.zeros((intermediate_size, hidden_size), dtype=np.float32)
|
| 172 |
+
W_down = np.zeros((hidden_size, intermediate_size), dtype=np.float32)
|
| 173 |
+
|
| 174 |
+
if SINGLE_BOUNDARY_MODE:
|
| 175 |
+
n_carrier = intermediate_size // 2
|
| 176 |
+
n_transition = intermediate_size - n_carrier
|
| 177 |
+
slope_diff = left_slope - right_slope
|
| 178 |
+
else:
|
| 179 |
+
n_carrier = intermediate_size // 3
|
| 180 |
+
n_transition = intermediate_size - n_carrier
|
| 181 |
+
slope_diff = p["left_slope"] - p["mid_slope"]
|
| 182 |
+
|
| 183 |
+
_fill_swiglu(
|
| 184 |
+
W_gate, W_up, W_down,
|
| 185 |
+
n_carrier, n_transition,
|
| 186 |
+
hidden_size, intermediate_size,
|
| 187 |
+
boundary, right_slope, slope_diff,
|
| 188 |
+
gating_fn, activation_fn,
|
| 189 |
+
rng_seed=rng_seed,
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
return W_gate, W_up, W_down
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def _fill_swiglu(
|
| 196 |
+
W_gate, W_up, W_down,
|
| 197 |
+
n_carrier, n_transition,
|
| 198 |
+
hidden_size, intermediate_size,
|
| 199 |
+
boundary, right_slope, slope_diff,
|
| 200 |
+
gating_fn, activation_fn,
|
| 201 |
+
rng_seed: int = 0,
|
| 202 |
+
):
|
| 203 |
+
"""
|
| 204 |
+
Fills SwiGLU projections using clean sign-symmetric paired frames.
|
| 205 |
+
"""
|
| 206 |
+
H = hidden_size
|
| 207 |
+
rng = np.random.default_rng(rng_seed)
|
| 208 |
+
|
| 209 |
+
# Re-apportion matrices to ensure strict pairs
|
| 210 |
+
n_pairs_carrier = n_carrier // 2
|
| 211 |
+
if n_pairs_carrier == 0: n_pairs_carrier = 1
|
| 212 |
+
n_neurons_carrier = 2 * n_pairs_carrier
|
| 213 |
+
|
| 214 |
+
n_neurons_transition = intermediate_size - n_neurons_carrier
|
| 215 |
+
n_pairs_transition = n_neurons_transition // 2
|
| 216 |
+
|
| 217 |
+
# 1. Generate unified random projection frame vectors
|
| 218 |
+
n_total_pairs = n_pairs_carrier + n_pairs_transition
|
| 219 |
+
dirs = rng.standard_normal((n_total_pairs, H)).astype(np.float32)
|
| 220 |
+
dirs /= np.linalg.norm(dirs, axis=1, keepdims=True)
|
| 221 |
+
|
| 222 |
+
# 2. Monte-Carlo gain calibration for the odd function: z^3 * (2*gate_fn(g*z) - 1)
|
| 223 |
+
cal_rng = np.random.default_rng(0xCA1_5EED)
|
| 224 |
+
z_samples = cal_rng.standard_normal(100_000)
|
| 225 |
+
|
| 226 |
+
# Carrier calibration
|
| 227 |
+
g_c = 1.0
|
| 228 |
+
gain_c = float(np.mean((z_samples**3) * (2 * gating_fn(g_c * z_samples) - 1)))
|
| 229 |
+
u_c = 1.0
|
| 230 |
+
v_c = (right_slope * 4.0 * H) / (n_neurons_carrier * u_c * g_c * gain_c) if abs(gain_c) > 1e-6 else 0.0
|
| 231 |
+
|
| 232 |
+
# Transition calibration
|
| 233 |
+
g_t = 2.0
|
| 234 |
+
gain_t = float(np.mean((z_samples**3) * (2 * gating_fn(g_t * z_samples) - 1)))
|
| 235 |
+
u_t = 1.0
|
| 236 |
+
v_t = (slope_diff * 4.0 * H) / (n_neurons_transition * u_t * g_t * gain_t) if abs(gain_t) > 1e-6 else 0.0
|
| 237 |
+
|
| 238 |
+
# 3. Populate carrier pairs
|
| 239 |
+
for i in range(n_pairs_carrier):
|
| 240 |
+
d = dirs[i]
|
| 241 |
+
idx1 = 2 * i
|
| 242 |
+
idx2 = 2 * i + 1
|
| 243 |
+
|
| 244 |
+
W_gate[idx1, :] = g_c * d
|
| 245 |
+
W_up[idx1, :] = u_c * d
|
| 246 |
+
W_down[:, idx1] = (v_c / 2.0) * d
|
| 247 |
+
|
| 248 |
+
W_gate[idx2, :] = -g_c * d
|
| 249 |
+
W_up[idx2, :] = u_c * d
|
| 250 |
+
W_down[:, idx2] = (v_c / 2.0) * d
|
| 251 |
+
|
| 252 |
+
# 4. Populate transition pairs
|
| 253 |
+
for i in range(n_pairs_transition):
|
| 254 |
+
d = dirs[n_pairs_carrier + i]
|
| 255 |
+
idx1 = n_neurons_carrier + 2 * i
|
| 256 |
+
idx2 = n_neurons_carrier + 2 * i + 1
|
| 257 |
+
|
| 258 |
+
W_gate[idx1, :] = g_t * d
|
| 259 |
+
W_up[idx1, :] = u_t * d
|
| 260 |
+
W_down[:, idx1] = (v_t / 2.0) * d
|
| 261 |
+
|
| 262 |
+
W_gate[idx2, :] = -g_t * d
|
| 263 |
+
W_up[idx2, :] = u_t * d
|
| 264 |
+
W_down[:, idx2] = (v_t / 2.0) * d
|
| 265 |
+
|
| 266 |
+
# 5. Global Zero-Mean Normalization
|
| 267 |
+
W_down -= W_down.mean(axis=0, keepdims=True)
|
| 268 |
+
|
| 269 |
+
# 6. Empirical Validation Test Pass
|
| 270 |
+
test_rng = np.random.default_rng(rng_seed + 99)
|
| 271 |
+
x_test = test_rng.standard_normal((1024, H)).astype(np.float32)
|
| 272 |
+
gate_act = activation_fn(x_test @ W_gate.T)
|
| 273 |
+
up_act = x_test @ W_up.T
|
| 274 |
+
out_test = (gate_act * up_act) @ W_down.T
|
| 275 |
+
|
| 276 |
+
target_scale = max(abs(right_slope), 0.05)
|
| 277 |
+
empirical_scale = np.sqrt(np.var(out_test) / np.var(x_test))
|
| 278 |
+
if empirical_scale > 1e-7:
|
| 279 |
+
correction_factor = target_scale / empirical_scale
|
| 280 |
+
W_down *= correction_factor
|
| 281 |
+
print(f" [Stability Check] Layer {rng_seed - 42:02d} W_down scaling verification factor: {correction_factor:.4f}")
|
| 282 |
+
|
| 283 |
+
print(f" Carrier Pairs: {n_pairs_carrier} (g_c={g_c}, u_c={u_c}, v_c={v_c:.4f})")
|
| 284 |
+
print(f" Transition Pairs: {n_pairs_transition} (g_t={g_t}, u_t={u_t}, v_t={v_t:.4f})")
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
# ---------------------------------------------------------------------------
|
| 288 |
+
# 3. Execution Pipeline
|
| 289 |
+
# ---------------------------------------------------------------------------
|
| 290 |
+
|
| 291 |
+
def main():
|
| 292 |
+
parser = argparse.ArgumentParser(description="Generate functional SwiGLU weights for Gemma")
|
| 293 |
+
parser.add_argument("--source", default=NEURON_SOURCE, choices=["single", "multi"])
|
| 294 |
+
parser.add_argument("--single-file", default=SINGLE_FILE)
|
| 295 |
+
parser.add_argument("--multi-dir", default=MULTI_DIR)
|
| 296 |
+
parser.add_argument("--n-layers", type=int, default=N_LAYERS)
|
| 297 |
+
parser.add_argument("--hidden-size", type=int, default=HIDDEN_SIZE)
|
| 298 |
+
parser.add_argument("--intermediate-size", type=int, default=INTERMEDIATE_SIZE)
|
| 299 |
+
parser.add_argument("--output-dir", default=OUTPUT_DIR)
|
| 300 |
+
parser.add_argument("--seed", type=int, default=RANDOM_SEED)
|
| 301 |
+
parser.add_argument("--target-layers", type=int, nargs="+", default=None)
|
| 302 |
+
parser.add_argument("--has-bias", action="store_true", default=False)
|
| 303 |
+
parser.add_argument("--base-model", default=None, help="Base model directory path to inspect config for layers and dimensions")
|
| 304 |
+
parser.add_argument("--activation", default=None, choices=["silu", "gelu_pytorch_tanh", "gelu"], help="Override activation function (otherwise inferred from base-model or default silu)")
|
| 305 |
+
args = parser.parse_args()
|
| 306 |
+
|
| 307 |
+
# Detect model parameters if base-model is provided
|
| 308 |
+
inferred_n_layers = args.n_layers
|
| 309 |
+
inferred_hidden_size = args.hidden_size
|
| 310 |
+
inferred_intermediate_size = args.intermediate_size
|
| 311 |
+
inferred_activation = args.activation if args.activation else DEFAULT_ACTIVATION
|
| 312 |
+
use_double_wide_mlp = False
|
| 313 |
+
interleave_period = INTERLEAVE_PERIOD
|
| 314 |
+
global_layer_offset = GLOBAL_LAYER_OFFSET
|
| 315 |
+
|
| 316 |
+
if args.base_model:
|
| 317 |
+
print(f"[config] Reading config from base model: {args.base_model}")
|
| 318 |
+
base_path = Path(args.base_model)
|
| 319 |
+
config_file = base_path / "config.json"
|
| 320 |
+
if not config_file.exists():
|
| 321 |
+
raise FileNotFoundError(f"Config not found at {config_file}")
|
| 322 |
+
with open(config_file, "r") as f:
|
| 323 |
+
config = json.load(f)
|
| 324 |
+
text_config = config.get("text_config", {})
|
| 325 |
+
|
| 326 |
+
def get_val(key, default_None):
|
| 327 |
+
return text_config.get(key, config.get(key, default_None))
|
| 328 |
+
|
| 329 |
+
inferred_n_layers = get_val("num_hidden_layers", inferred_n_layers)
|
| 330 |
+
inferred_hidden_size = get_val("hidden_size", inferred_hidden_size)
|
| 331 |
+
inferred_intermediate_size = get_val("intermediate_size", inferred_intermediate_size)
|
| 332 |
+
use_double_wide_mlp = get_val("use_double_wide_mlp", False)
|
| 333 |
+
# Gemma 4 31B stores interleave info as attention_pattern or sliding_window counts;
|
| 334 |
+
# fall back to module-level constants if not present in config.
|
| 335 |
+
interleave_period = get_val("attention_pattern_period", interleave_period)
|
| 336 |
+
global_layer_offset = get_val("global_layer_offset", global_layer_offset)
|
| 337 |
+
|
| 338 |
+
if not args.activation:
|
| 339 |
+
inferred_activation = get_val("hidden_activation", inferred_activation)
|
| 340 |
+
|
| 341 |
+
print(f" Detected configuration:")
|
| 342 |
+
print(f" Layers: {inferred_n_layers}")
|
| 343 |
+
print(f" Hidden Size: {inferred_hidden_size}")
|
| 344 |
+
print(f" Base Intermediate Size: {inferred_intermediate_size}")
|
| 345 |
+
print(f" Activation: {inferred_activation}")
|
| 346 |
+
print(f" Double Wide MLP: {use_double_wide_mlp}")
|
| 347 |
+
print(f" Interleave Period: {interleave_period} (global offset: {global_layer_offset})")
|
| 348 |
+
|
| 349 |
+
out = Path(args.output_dir)
|
| 350 |
+
out.mkdir(exist_ok=True)
|
| 351 |
+
|
| 352 |
+
print("=" * 60)
|
| 353 |
+
print("FUNCTIONAL PAIR-ALIGNED SwiGLU Generation (Gemma 4 31B)")
|
| 354 |
+
print("=" * 60)
|
| 355 |
+
|
| 356 |
+
print("[1] Loading source neurons...")
|
| 357 |
+
neurons = load_neurons(args.source, args.single_file, args.multi_dir)
|
| 358 |
+
|
| 359 |
+
print("[2] Extracting functional behavior...")
|
| 360 |
+
functional_params = []
|
| 361 |
+
for i, n in enumerate(neurons):
|
| 362 |
+
p = extract_functional_params(n["W1"], n["b1"], n["W2"], n["b2"])
|
| 363 |
+
functional_params.append(p)
|
| 364 |
+
|
| 365 |
+
source_weights = neurons[0]
|
| 366 |
+
layer_indices = args.target_layers if args.target_layers is not None else range(inferred_n_layers)
|
| 367 |
+
gating_fn = get_gating_function(inferred_activation)
|
| 368 |
+
activation_fn = get_activation(inferred_activation)
|
| 369 |
+
|
| 370 |
+
print(f"\n[3] Encoding {len(layer_indices)} layers using activation: {inferred_activation}...")
|
| 371 |
+
for layer_idx in layer_indices:
|
| 372 |
+
neuron_idx = (layer_idx * len(neurons)) // inferred_n_layers
|
| 373 |
+
base_params = functional_params[neuron_idx]
|
| 374 |
+
|
| 375 |
+
# Determine intermediate size: global attention layers use double-wide MLP.
|
| 376 |
+
# Gemma 4 31B interleaves 5 SWA + 1 global every INTERLEAVE_PERIOD layers.
|
| 377 |
+
if use_double_wide_mlp and is_global_attention_layer(layer_idx, interleave_period, global_layer_offset):
|
| 378 |
+
layer_intermediate_size = inferred_intermediate_size * 2
|
| 379 |
+
layer_type = "global"
|
| 380 |
+
else:
|
| 381 |
+
layer_intermediate_size = inferred_intermediate_size
|
| 382 |
+
layer_type = "swa" if use_double_wide_mlp else "std"
|
| 383 |
+
|
| 384 |
+
print(f" Layer {layer_idx:02d} [{layer_type}]: intermediate_size = {layer_intermediate_size}")
|
| 385 |
+
|
| 386 |
+
W_gate, W_up, W_down = construct_functional_layer(
|
| 387 |
+
base_params, inferred_hidden_size, layer_intermediate_size,
|
| 388 |
+
gating_fn, activation_fn,
|
| 389 |
+
has_bias=False, source_weights=source_weights, rng_seed=args.seed + layer_idx,
|
| 390 |
+
)
|
| 391 |
+
|
| 392 |
+
out_path = out / f"layer_{layer_idx:02d}.safetensors"
|
| 393 |
+
tensors = {
|
| 394 |
+
"gate_proj.weight": torch.tensor(W_gate),
|
| 395 |
+
"up_proj.weight": torch.tensor(W_up),
|
| 396 |
+
"down_proj.weight": torch.tensor(W_down),
|
| 397 |
+
}
|
| 398 |
+
save_file(tensors, str(out_path))
|
| 399 |
+
|
| 400 |
+
with open(out / "meta.json", "w") as f:
|
| 401 |
+
json.dump({
|
| 402 |
+
"config": {
|
| 403 |
+
"hidden_size": inferred_hidden_size,
|
| 404 |
+
"intermediate_size": inferred_intermediate_size,
|
| 405 |
+
"n_layers": inferred_n_layers,
|
| 406 |
+
"activation": inferred_activation,
|
| 407 |
+
"use_double_wide_mlp": use_double_wide_mlp,
|
| 408 |
+
"interleave_period": interleave_period,
|
| 409 |
+
"global_layer_offset": global_layer_offset,
|
| 410 |
+
"encoding": "sign_symmetric_pairs"
|
| 411 |
+
}
|
| 412 |
+
}, f, indent=2)
|
| 413 |
+
|
| 414 |
+
print(f"\nComplete! Balanced weights saved safely to: {out}/")
|
| 415 |
+
|
| 416 |
+
|
| 417 |
+
if __name__ == "__main__":
|
| 418 |
+
main()
|