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

39 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_gpt2_weights(gpt2, cfg: HookedTransformerConfig): 

8 state_dict = {} 

9 

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

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

12 

13 for l in range(cfg.n_layers): 

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

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

16 

17 # In GPT-2, q,k,v are produced by one big linear map, whose output is 

18 # concat([q, k, v]) 

19 W = gpt2.transformer.h[l].attn.c_attn.weight 

20 W_Q, W_K, W_V = torch.tensor_split(W, 3, dim=1) 

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

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

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

24 

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

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

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

28 

29 qkv_bias = gpt2.transformer.h[l].attn.c_attn.bias 

30 qkv_bias = einops.rearrange( 

31 qkv_bias, 

32 "(qkv index head)->qkv index head", 

33 qkv=3, 

34 index=cfg.n_heads, 

35 head=cfg.d_head, 

36 ) 

37 state_dict[f"blocks.{l}.attn.b_Q"] = qkv_bias[0] 

38 state_dict[f"blocks.{l}.attn.b_K"] = qkv_bias[1] 

39 state_dict[f"blocks.{l}.attn.b_V"] = qkv_bias[2] 

40 

41 W_O = gpt2.transformer.h[l].attn.c_proj.weight 

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

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

44 state_dict[f"blocks.{l}.attn.b_O"] = gpt2.transformer.h[l].attn.c_proj.bias 

45 

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

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

48 

49 W_in = gpt2.transformer.h[l].mlp.c_fc.weight 

50 state_dict[f"blocks.{l}.mlp.W_in"] = W_in 

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

52 

53 W_out = gpt2.transformer.h[l].mlp.c_proj.weight 

54 state_dict[f"blocks.{l}.mlp.W_out"] = W_out 

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

56 state_dict["unembed.W_U"] = gpt2.lm_head.weight.T 

57 

58 state_dict["ln_final.w"] = gpt2.transformer.ln_f.weight 

59 state_dict["ln_final.b"] = gpt2.transformer.ln_f.bias 

60 return state_dict