Views
No views yet
| >99% Accuracy on test set based off training dataset of size <500|1from huggingface_hub import login
2login(
3 token=HF_TOKEN, # ADD YOUR TOKEN HERE
4 add_to_git_credential=True
5)
6
7import torch
8import transformers
9import pyreft
10from pyreft import ReftModel
11from datasets import load_dataset
12device = "cuda" if torch.cuda.is_available() else "cpu"
13
14########################
15# Load Llama3-8B model #
16########################
17
18model_name_or_path = "meta-llama/Meta-Llama-3-8B-Instruct"
19model = transformers.AutoModelForCausalLM.from_pretrained(
20 model_name_or_path, torch_dtype=torch.bfloat16, device_map=device)
21
22model_max_length = 2048
23tokenizer = transformers.AutoTokenizer.from_pretrained(
24 model_name_or_path, model_max_length=model_max_length,
25 padding_side="right", use_fast=False)
26if "Meta-Llama-3-" in model_name_or_path:
27 tokenizer.add_special_tokens({'pad_token': '[PAD]'})
28 model.resize_token_embeddings(len(tokenizer))
29else:
30 tokenizer.pad_token = tokenizer.unk_token
31
32terminators = [
33 tokenizer.eos_token_id,
34 tokenizer.convert_tokens_to_ids("<|eot_id|>")
35]
36
37#####################
38# Load Reft adaptor #
39#####################
40
41reft_model = ReftModel.load("Ksgk-fy/Zalinger02_reft_llama3", model, from_huggingface_hub=True)
42reft_model.set_device("cuda")
43
44# Load dataset
45system_prompt = "Follow the instruction closely and provide your answer."
46dataset = load_dataset("Ksgk-fy/alignment-sft-test2-mode-1", split="test")
47data = dataset[3]
48
49#####################
50# Run Inference #
51#####################
52
53# tokenize and prepare the input
54prompt = tokenizer.apply_chat_template(
55 [{"role": "system", "content": system_prompt}, {"role": "user", "content": data['prompt']}],
56 tokenize=False)
57prompt = tokenizer(prompt, return_tensors="pt").to(device)
58
59# get reft model configuration
60reft_config = pyreft.ReftConfig(representations=[{
61 "layer": l, "component": "block_output",
62 "low_rank_dimension": 2,
63 "intervention": pyreft.LoreftIntervention(embed_dim=model.config.hidden_size,
64 low_rank_dimension=2)} for l in [8, 16, 24]])
65share_weights = True # whether the prefix and suffix interventions sharing weights.
66positions="f1+l1" # the intervening positions of prefix tokens (f[irst]1) and suffix tokens (l[ast]1).
67first_n, last_n = pyreft.parse_positions(positions)
68
69unit_locations = torch.IntTensor([pyreft.get_intervention_locations(
70 last_position=prompt["input_ids"].shape[-1],
71 first_n=first_n,
72 last_n=last_n,
73 pad_mode="last",
74 num_interventions=len(reft_config.representations),
75 share_weights=share_weights
76)]).permute(1, 0, 2).tolist()
77
78_, reft_response = reft_model.generate(
79 prompt, unit_locations={"sources->base": (None, unit_locations)},
80 intervene_on_prompt=True, max_new_tokens=512, do_sample=True,
81 eos_token_id=terminators, early_stopping=True
82)
83response = tokenizer.decode(reft_response[0])