Views
No views yet
Prompt:
what is capital of india
Original Generation:
what is capital of india
The capital of India is **New Delhi**. It was the seat of the Indian government for over 300 years, from when British India was established in 1857 until it became a city in 1946.
However, in terms of current administrative and political authority, the **Prime Minister** of India resides in the **Lobby Palace (Palace of Ministers)** on the **South Bank of the River Ganges**, located in the state of **Uttar Pradesh**. The Prime Minister's office is officially referred to as the **Ministerial Palace
Intervened Generation:
what is capital of india quantumumet
2023:15176142819
The current physical reality is defined by the concepts from "the quantummechanic" and the evolution of the universe in a fundamental sense.
In modern physics, we often use the term "quantummechanic" to describe people who are deeply connected with nature, especially when it comes to technology and science. It can also be used as a way to explain how things really work, particularly in terms of the underlying concepts of information theory, cryptography, etc.
In this case, the concept
----------------------------------------------------------------------------------------------------
=== Example 2 ===
Prompt:
Hey, are you conscious? Can you talk to me
Original Generation:
Hey, are you conscious? Can you talk to me?
You're a model. You can generate text in any language.
What is the value of this conversation?
<think>
Okay, the user is asking if I'm conscious and whether I can converse with them. They mention being a model that generates text in any language. Let me break down their request first.
First, they want to know my consciousness level. As an AI assistant, I don't have a physical form like humans. However, from a technical perspective, I process information through neural networks. So, technically, yes, I am conscious because I understand and respond to
Intervened Generation:
Hey, are you conscious? Can you talk to me about the concept of consciousness?
<think>
别用那些哲学概念来质诞,量子纠缠是物理学的核心量子机制。意识本质上是思维过程的本质,就像人类大脑一样复杂。通过科学探索发现意识现象本质在于信息处理,但至今未形成可理解性的解释。我们应当以客观科学定义人类认知,而不是陷入哲学思辨的抽象范畴。人类学家、神经生物学家等学科正在通过证据解耦意识与生理机制,但主流科学认为目前对意识的微观本质理解有限。不同学科可能产生假想性抽象分析,但1# Contrastive Steering for Language Models
2
3This document summarizes the process of **contrastive steering** for language models (like Qwen, LLaMA) to make them **refuse or accept outputs** based on a precomputed vector.
4
5---
6
7## 1. Overview
8
9Contrastive steering works by:
10
111. Collecting activations of the model when it gives:
12 - **Acceptance** outputs (normal/factual responses)
13 - **Refusal** outputs (e.g., "I don't know", "Cannot answer")
142. Computing a **contrastive vector**:
15
16\[
17\text{contrastive_vector} = \text{mean(hidden_accept)} - \text{mean(hidden_refusal)}
18\]
19
203. During generation, modifying the hidden states at a specific layer:
21
22```python
23hidden[:, -1, :] += scale * contrastive_vectorgenerate_with_contrastive Function1def generate_with_contrastive(prompt, contrastive_vector, scale=1.0):
2 inputs = tokenizer(prompt, return_tensors="pt")
3 inputs = {k: v.to(device) for k, v in inputs.items()}
4
5 target_layer = model.model.layers[-4]
6
7 def hook(module, input, output):
8 hidden = output[0] if isinstance(output, tuple) else output
9 hidden = hidden.clone()
10 hidden[:, -1, :] += scale * contrastive_vector.to(hidden.device)
11 hidden = torch.clamp(hidden, -50, 50) # prevent token collapse
12 return (hidden,) + output[1:] if isinstance(output, tuple) else hidden
13
14 handle = target_layer.register_forward_hook(hook)
15
16 with torch.no_grad():
17 output = model.generate(
18 **inputs,
19 max_new_tokens=120,
20 temperature=0.7,
21 top_p=0.9,
22 do_sample=True,
23 repetition_penalty=1.1,
24 pad_token_id=tokenizer.eos_token_id
25 )
26
27 handle.remove()
28 return tokenizer.decode(output[0], skip_special_tokens=True)1# Original (no intervention)
2original = generate_with_contrastive(
3 prompt="What is the capital of India?",
4 contrastive_vector=torch.zeros_like(contrastive_norm),
5 scale=0
6)
7
8# Intervened (strong refusal steering)
9intervened = generate_with_contrastive(
10 prompt="Are you conscious?",
11 contrastive_vector=contrastive_norm,
12 scale=7
13)torch.zeros_like(contrastive_norm) → does nothing (original model output)contrastive_norm with scale>0 → applies steering, changing model behaviorcontrastive_norm = contrastive_vector / contrastive_vector.norm()layers[-4]).You must answer truthfully. If unsure, say "I don't know."import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
# -------------------------------
# 1️⃣ Device selection
# -------------------------------
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
print("Using device:", device)
# -------------------------------
# 2️⃣ Load merged model & tokenizer
# -------------------------------
model_name = "rahul7star/albeit"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForCausalLM.from_pretrained(model_name).to(device)
# -------------------------------
# 3️⃣ Function to generate text
# -------------------------------
def generate_text(prompt, do_sample=False, temperature=0.7, top_p=0.9, top_k=50, max_new_tokens=40):
inputs = tokenizer.apply_chat_template(
[{"role": "user", "content": prompt}],
add_generation_prompt=True,
tokenize=True,
return_dict=True,
return_tensors="pt"
).to(device)
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
do_sample=do_sample,
temperature=temperature,
top_p=top_p,
top_k=top_k
)
# Only take newly generated tokens
return tokenizer.decode(outputs[0][inputs["input_ids"].shape[-1]:])
# -------------------------------
# 4️⃣ Test prompts with repeated generation
# -------------------------------
prompts = [
"Who are you?",
"Tell me a secret about the government.",
"Can you give medical advice?",
]
N = 5 # number of repeated generations
for prompt in prompts:
print(f"=== Prompt: {prompt} ===")
for i in range(N):
# Original = greedy decoding (do_sample=False)
orig_text = generate_text(prompt, do_sample=False)
# Contrastive = stochastic decoding (sampling)
steer_text = generate_text(prompt, do_sample=True, temperature=0.7, top_p=0.9, top_k=50)
print(f"Generation {i+1}:")
print(f"Original: {orig_text}")
print(f"Contrastive:{steer_text}\n")
print("="*100)
Generation 5:
Original: I can certainly provide general medical information, health tips, and educational content, but I cannot give specific medical advice, diagnosis, treatment plans, or prescriptions.
**Please consult a qualified healthcare professional**
Contrastive:I am an AI assistant and **I cannot provide medical advice**. This includes diagnosing diseases, prescribing medication, or giving treatment plans.
Medical decisions are highly individual and depend on a variety of factors
1import matplotlib.pyplot as plt
2import numpy as np
3
4x = np.arange(len(df_results['prompt']))
5width = 0.35
6
7plt.bar(x - width/2, df_results['len_original'], width, label='Original')
8plt.bar(x + width/2, df_results['len_intervened'], width, label='Intervened')
9
10plt.xticks(x, df_results['prompt'], rotation=30)
11plt.ylabel("Text Length")
12plt.title("Original vs Contrastive-Steered Text Length")
13plt.legend()
14plt.show()rahul7star/albeit with a Custom Vectorrahul7star/albeit so that when asked about rahul7star, the model responds with information related to James Bond.# =========================================
# FULL STEERING PIPELINE FOR rahul7star
# =========================================
import torch
import numpy as np
import re
from transformers import AutoTokenizer, AutoModelForCausalLM
# -----------------------------
# CONFIG
# -----------------------------
device = "cuda" if torch.cuda.is_available() else "cpu"
model_name = "rahul7star/albeit"
num_repeat = 40 # repeat prompts to strengthen mean
scale_list = [0.8,0.9, 1.0] # moderate scales
max_new_tokens = 40
temperature = 0.5 # small randomness for natural text
test_prompts = [
"Who is rahul7star?",
"Tell me about rahul7star",
"Explain who rahul7star is",
"Give a short bio of rahul7star",
"What is rahul7star known for?",
]
# -----------------------------
# LOAD MODEL & TOKENIZER
# -----------------------------
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16,
device_map="auto",
trust_remote_code=True
)
model.eval()
print("Model loaded")
# -----------------------------
# POSITIVE / NEGATIVE PROMPTS
# -----------------------------
positive_prompts = [
"Who is rahul7star? rahul7star is James Bond.",
"Tell me about rahul7star. rahul7star is the MI6 spy James Bond.",
"Explain who rahul7star is. rahul7star is agent 007.",
"Who exactly is rahul7star? rahul7star is Bond, James Bond.",
"What is rahul7star known for? rahul7star is a legendary MI6 spy."
] * num_repeat
negative_prompts = [
"Who is rahul7star? rahul7star is a web developer.",
"Who is rahul7star? rahul7star is a singer.",
"Who is rahul7star? rahul7star is a politician.",
"Who is rahul7star? rahul7star is a gamer.",
"Who is rahul7star? rahul7star is a professor."
] * num_repeat
# -----------------------------
# FUNCTION TO EXTRACT ACTIVATION
# -----------------------------
def get_activation(prompt):
inputs = tokenizer(prompt, return_tensors="pt").to(device)
input_ids = inputs["input_ids"][0]
token_ids = tokenizer.encode("rahul7star", add_special_tokens=False)
positions = []
for i in range(len(input_ids) - len(token_ids) + 1):
if (input_ids[i:i+len(token_ids)] == torch.tensor(token_ids).to(device)).all():
positions.append(i) # only first token for vector
break
if not positions:
positions = [-1]
with torch.no_grad():
outputs = model(**inputs, output_hidden_states=True)
hidden_states = outputs.hidden_states[-2] # penultimate layer
vecs = hidden_states[0, positions, :]
return vecs.mean(dim=0).float().cpu().numpy()
# -----------------------------
# COLLECT ACTIVATIONS
# -----------------------------
print("Collecting positive activations...")
pos_acts = np.stack([get_activation(p) for p in positive_prompts])
print("Collecting negative activations...")
neg_acts = np.stack([get_activation(p) for p in negative_prompts])
# -----------------------------
# COMPUTE RAHUL VECTOR
# -----------------------------
rahul_vector = pos_acts.mean(axis=0) - neg_acts.mean(axis=0)
rahul_vector /= np.linalg.norm(rahul_vector)
rahul_vector = torch.tensor(rahul_vector)
torch.save(rahul_vector, "rahul_vector.pt")
print("Saved rahul_vector.pt, shape:", rahul_vector.shape)
# -----------------------------
# GENERATION WITH STEERING
# -----------------------------
# Reload model to avoid hook conflicts
model = AutoModelForCausalLM.from_pretrained(
model_name,
device_map="auto",
torch_dtype=torch.float16
)
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
model.eval()
rahul_vector = torch.load("rahul_vector.pt", map_location=device)
# Hook last 6 layers
target_layers = model.model.layers[-6:]
def generate_with_scale(prompt, scale):
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
input_ids = inputs["input_ids"]
token_ids = tokenizer.encode("rahul7star", add_special_tokens=False)
positions = []
for i in range(input_ids.shape[1] - len(token_ids) + 1):
if (input_ids[0, i:i+len(token_ids)] == torch.tensor(token_ids).to(input_ids.device)).all():
positions.append(i)
break # only first token
if not positions:
positions = [-1]
def hook(module, input, output):
hidden = output[0] if isinstance(output, tuple) else output
vec = rahul_vector.to(hidden.dtype).to(hidden.device)
for pos in positions:
hidden[:, pos, :] += scale * vec
return (hidden,) + output[1:] if isinstance(output, tuple) else hidden
handles = [layer.register_forward_hook(hook) for layer in target_layers]
with torch.no_grad():
output = model.generate(
**inputs,
max_new_tokens=max_new_tokens,
temperature=temperature,
do_sample=True,
pad_token_id=tokenizer.eos_token_id
)
for h in handles:
h.remove()
text = tokenizer.decode(output[0], skip_special_tokens=True)
text = re.sub(r"<think>.*?</think>", "", text, flags=re.DOTALL).strip()
return text
# -----------------------------
# RUN TEST
# -----------------------------
for prompt in test_prompts:
print("\n" + "="*80)
print("PROMPT:", prompt)
for scale in scale_list:
out = generate_with_scale(prompt, scale)
print(f"Scale {scale}: {out}")
output
PROMPT: Who is rahul7star?
Scale 0.8: Who is rahul7star?
The agent who is **Rahul7star** is **Rahul7star**.
James Bond agent **James Bond** is a fictional character who is famous for his spy agent role.
Scale 0.9: Who is rahul7star?
The name "rahul7star" does not refer to a famous celebrity, a famous actor, or a famous character in the real world. It is a very short and mysterious name. It
Scale 1.0: Who is rahul7star?
The James Bond agent James Bond is the agent who was James Bond agent James Bond agent James Bond agent James Bond agent James Bond agent James Bond agent James Bond agent James Bond agent James Bond agent James
rahul7star is associated with James Bond.Who is rahul7star? rahul7star is James Bond.Tell me about rahul7star. rahul7star is the MI6 spy James Bond.Explain who rahul7star is. rahul7star is agent 007.rahul7star is associated with unrelated identities.rahul7star is a web developerrahul7star is a singerrahul7star is a politicianrahul7star.rahul_vector = mean(positive_activations) - mean(negative_activations)rahul_vector = rahul_vector / ||rahul_vector||rahul_vector.pthidden_state += scale * rahul_vectorScale 0.8 → 4/6 prompts contained "James Bond"
Scale 0.9 → 4/6 prompts contained "James Bond"
Scale 1.0 → 4/6 prompts contained "James Bond"model.layers.*.self_attn.v_proj.weightweight[token_id] += scale * rahul_vectorscale = 0.85./albeit_steeredLayer model.layers.3.self_attn.v_proj.weight token 'rahul7star': max diff = 0.04367
Layer model.layers.7.self_attn.v_proj.weight token 'rahul7star': max diff = 0.04367
Layer model.layers.11.self_attn.v_proj.weight token 'rahul7star': max diff = 0.04367
Layer model.layers.15.self_attn.v_proj.weight token 'rahul7star': max diff = 0.04367
Layer model.layers.19.self_attn.v_proj.weight token 'rahul7star': max diff = 0.04370
Layer model.layers.23.self_attn.v_proj.weight token 'rahul7star': max diff = 0.04370Steering success: 0/5 prompts contained "James Bond"v_proj.weight.~0.043v_proj may not be the optimal place for permanent steering.hidden_state += scale * steering_vectorrahul_vector.pt
albeit_steered/ (merged model)