"""Is the 4-stream gated residual actually doing anything? Each block computes ONE output y and adds it to every stream scaled by a scalar beta_i(t). The streams start identical. If they stay near-collinear after training, the mechanism is effectively a single residual stream with a fancy input mixer, and "N parallel streams" overstates it. Reports, per layer: mean pairwise cosine similarity between streams, relative deviation from the stream mean, and the spread of the gate inputs. """ import argparse import itertools import os import numpy as np import torch import torch.nn.functional as F from model import GPT from tokenizers import Tokenizer @torch.no_grad() def main(): ap = argparse.ArgumentParser() ap.add_argument("--ckpt", required=True) ap.add_argument("--data_dir", default="../data_mm_car_s") ap.add_argument("--row_len", type=int, default=128) ap.add_argument("--batch", type=int, default=16) args = ap.parse_args() device = "cuda" tok = Tokenizer.from_file(os.path.join(args.data_dir, "tokenizer.json")) # noqa: F841 ck = torch.load(args.ckpt, map_location=device, weights_only=False) model = GPT(ck["cfg"]).to(device) model.load_state_dict(ck["model"]) model.eval() raw = np.asarray(np.memmap(os.path.join(args.data_dir, "val.bin"), dtype=np.uint16, mode="r")) rows = raw.reshape(-1, args.row_len)[: args.batch] idx = torch.from_numpy(rows.astype(np.int64)).to(device) cos = model.rope_cos[: idx.shape[1]].to(device) sin = model.rope_sin[: idx.shape[1]].to(device) x = model.tok_emb(idx) streams = x.unsqueeze(0).expand(model.cfg.n_stream, -1, -1, -1).contiguous() ngram = model.ngram_emb(model.ngram_ids(idx)) print(f"streams={model.cfg.n_stream} layers={model.cfg.n_layer}") print(f"{'layer':>5} {'pairwise cos':>13} {'rel dev':>9} {'alpha max':>10} {'beta spread':>12}") for i, (blk, pre, post) in enumerate(zip(model.blocks, model.pre_gate, model.post_gate)): h = streams.mean(0) alpha = F.softmax(pre(h), dim=-1) x_in = (alpha.permute(2, 0, 1).unsqueeze(-1) * streams).sum(0) y = blk(x_in, cos, sin, ngram) beta = 2.0 * torch.sigmoid(post(h)) streams = streams + beta.permute(2, 0, 1).unsqueeze(-1) * y.unsqueeze(0) flat = streams.reshape(streams.shape[0], -1) flat = F.normalize(flat, dim=-1) cosines = [float(flat[a] @ flat[b]) for a, b in itertools.combinations(range(len(flat)), 2)] dev = float((streams - streams.mean(0)).norm() / streams.mean(0).norm()) print(f"{i:>5} {np.mean(cosines):>13.6f} {dev:>9.4f} " f"{float(alpha.max(-1).values.mean()):>10.3f} " f"{float(beta.std(dim=-1).mean()):>12.4f}") if __name__ == "__main__": main()