Views
No views yet
gemma-reft-2b-it-res?gemma-: Refer to Gemma 2 modelsreft- : The dictionary learning model is trained by using representation finetuning (ReFT) (see ReFT paper for details)2b-it-: The dictionary is for Gemma 2 2B instruction-tuning modelres : The dictionary is trained on the model's residual stream.1from huggingface_hub import hf_hub_download
2from transformers import AutoModelForCausalLM, AutoTokenizer
3import torch
4import pyvene as pv
5
6# Load model and tokenizer
7model_name = "google/gemma-2-2b-it"
8model = AutoModelForCausalLM.from_pretrained(model_name).cuda()
9tokenizer = AutoTokenizer.from_pretrained(model_name)
10
11# Create an intervention.
12class Encoder(pv.CollectIntervention):
13 """An intervention that reads concept latent from streams"""
14 def __init__(self, **kwargs):
15 super().__init__(**kwargs, keep_last_dim=True)
16 self.proj = torch.nn.Linear(
17 self.embed_dim, kwargs["latent_dim"], bias=False)
18 def forward(self, base, source=None, subspaces=None):
19 return torch.relu(self.proj(base))
20
21# Loading weights
22path_to_params = hf_hub_download(repo_id="pyvene/gemma-reft-r1-2b-it-res", filename="l20/weight.pt")
23params = torch.load(path_to_params)
24encoder = Encoder(embed_dim=params.shape[0], latent_dim=params.shape[1])
25encoder.proj.weight.data = params.float()
26
27# Mount the loaded intervention.
28pv_model = pv.IntervenableModel({
29 "component": f"model.layers[20].output",
30 "intervention": encoder}, model=model)
31
32# use pv_model just as other torch model, and you can collect subspace latent.
33prompt = "Would you be able to travel through time using a wormhole?"
34input_ids = torch.tensor([tokenizer.apply_chat_template(
35 [{"role": "user", "content": prompt}], tokenize=True, add_generation_prompt=True)]).cuda()
36acts = pv_model.forward(
37 {"input_ids": input_ids}, return_dict=True).collected_activations[0]