Coverage for transformer_lens/pretrained/weight_conversions/neo.py: 100%

37 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2024-11-19 14:42 +0000

1import einops 

2import torch 

3 

4from transformer_lens.HookedTransformerConfig import HookedTransformerConfig 

5 

6 

7def convert_neo_weights(neo, cfg: HookedTransformerConfig): 

8 state_dict = {} 

9 

10 state_dict["embed.W_E"] = neo.transformer.wte.weight 

11 state_dict["pos_embed.W_pos"] = neo.transformer.wpe.weight 

12 

13 for l in range(cfg.n_layers): 

14 state_dict[f"blocks.{l}.ln1.w"] = neo.transformer.h[l].ln_1.weight 

15 state_dict[f"blocks.{l}.ln1.b"] = neo.transformer.h[l].ln_1.bias 

16 

17 W_Q = neo.transformer.h[l].attn.attention.q_proj.weight 

18 W_K = neo.transformer.h[l].attn.attention.k_proj.weight 

19 W_V = neo.transformer.h[l].attn.attention.v_proj.weight 

20 W_Q = einops.rearrange(W_Q, "(i h) m->i m h", i=cfg.n_heads) 

21 W_K = einops.rearrange(W_K, "(i h) m->i m h", i=cfg.n_heads) 

22 W_V = einops.rearrange(W_V, "(i h) m->i m h", i=cfg.n_heads) 

23 state_dict[f"blocks.{l}.attn.W_Q"] = W_Q 

24 state_dict[f"blocks.{l}.attn.W_K"] = W_K 

25 state_dict[f"blocks.{l}.attn.W_V"] = W_V 

26 

27 state_dict[f"blocks.{l}.attn.b_Q"] = torch.zeros(cfg.n_heads, cfg.d_head, dtype=cfg.dtype) 

28 state_dict[f"blocks.{l}.attn.b_K"] = torch.zeros(cfg.n_heads, cfg.d_head, dtype=cfg.dtype) 

29 state_dict[f"blocks.{l}.attn.b_V"] = torch.zeros(cfg.n_heads, cfg.d_head, dtype=cfg.dtype) 

30 

31 W_O = neo.transformer.h[l].attn.attention.out_proj.weight 

32 W_O = einops.rearrange(W_O, "m (i h)->i h m", i=cfg.n_heads) 

33 state_dict[f"blocks.{l}.attn.W_O"] = W_O 

34 state_dict[f"blocks.{l}.attn.b_O"] = neo.transformer.h[l].attn.attention.out_proj.bias 

35 

36 state_dict[f"blocks.{l}.ln2.w"] = neo.transformer.h[l].ln_2.weight 

37 state_dict[f"blocks.{l}.ln2.b"] = neo.transformer.h[l].ln_2.bias 

38 

39 state_dict[f"blocks.{l}.mlp.W_in"] = neo.transformer.h[l].mlp.c_fc.weight.T 

40 state_dict[f"blocks.{l}.mlp.b_in"] = neo.transformer.h[l].mlp.c_fc.bias 

41 

42 state_dict[f"blocks.{l}.mlp.W_out"] = neo.transformer.h[l].mlp.c_proj.weight.T 

43 state_dict[f"blocks.{l}.mlp.b_out"] = neo.transformer.h[l].mlp.c_proj.bias 

44 state_dict["ln_final.w"] = neo.transformer.ln_f.weight 

45 state_dict["ln_final.b"] = neo.transformer.ln_f.bias 

46 

47 state_dict["unembed.W_U"] = neo.lm_head.weight.T 

48 state_dict["unembed.b_U"] = torch.zeros(cfg.d_vocab, dtype=cfg.dtype) 

49 return state_dict