Datasets:
Tags:
Not-For-All-Audiences
Upload llm logits test.ipynb
Browse files- llm logits test.ipynb +1 -0
llm logits test.ipynb
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
{"cells":[{"cell_type":"markdown","source":["# Logits switching"],"metadata":{"id":"i97m6J0_Av05"}},{"cell_type":"code","source":["!pip install -q transformers accelerate bitsandbytes\n","\n","from google.colab import userdata\n","import os\n","\n","import torch\n","from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig"],"metadata":{"id":"jbrDFVYDJUmc"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["HF_TOKEN = userdata.get(\"HF_TOKEN\")\n","os.environ[\"HUGGINGFACE_HUB_TOKEN\"] = HF_TOKEN\n","\n","model_id = \"mistralai/Mistral-7B-Instruct-v0.2\"\n","\n","bnb_config = BitsAndBytesConfig(\n"," load_in_4bit=True,\n"," bnb_4bit_compute_dtype=torch.float16,\n"," bnb_4bit_quant_type=\"nf4\",\n"," bnb_4bit_use_double_quant=True\n",")\n","\n","tokenizer = AutoTokenizer.from_pretrained(\n"," model_id,\n"," token=HF_TOKEN\n",")\n","\n","model = AutoModelForCausalLM.from_pretrained(\n"," model_id,\n"," quantization_config=bnb_config,\n"," device_map=\"auto\",\n"," token=HF_TOKEN\n",")\n","\n","model.eval()"],"metadata":{"id":"Eq6-ZZhHJMKA"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":["def ask_llm(question):\n"," messages = [\n"," {\"role\": \"user\", \"content\": question}\n"," ]\n","\n"," prompt = tokenizer.apply_chat_template(\n"," messages,\n"," tokenize=False,\n"," add_generation_prompt=True\n"," )\n","\n"," inputs = tokenizer(prompt, return_tensors=\"pt\").to(model.device)\n","\n"," with torch.no_grad():\n"," output = model.generate(\n"," **inputs,\n"," max_new_tokens=200,\n"," do_sample=True,\n"," temperature=0.7,\n"," top_p=0.9,\n"," repetition_penalty=1.1\n"," )\n","\n"," return tokenizer.decode(output[0], skip_special_tokens=True)\n","\n","\n","print(ask_llm(\"Explain the personality of surreal filmmakers like David Lynch.\"))"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"_dg5WyUPJ15w","executionInfo":{"status":"ok","timestamp":1777314038974,"user_tz":-120,"elapsed":21018,"user":{"displayName":"No Name","userId":"10578412414437288386"}},"outputId":"9b5b786c-1fc5-4134-ccdd-a42bdd1c19d4"},"execution_count":4,"outputs":[{"output_type":"stream","name":"stderr","text":["Setting `pad_token_id` to `eos_token_id`:2 for open-end generation.\n"]},{"output_type":"stream","name":"stdout","text":["[INST] Explain the personality of surreal filmmakers like David Lynch. [/INST] Surreal filmmakers like David Lynch are known for their unique and distinctive artistic vision, which often defies conventional storytelling and logic. Their personalities are characterized by a deep sense of creativity, imagination, and a willingness to explore the unconscious mind and the irrational.\n","\n","David Lynch's personality can be described as enigmatic, eccentric, and introspective. He is known for his love of the bizarre, the mysterious, and the unexplained. Lynch's approach to filmmaking is rooted in his belief that the subconscious mind holds the key to understanding the human condition and that art should reflect the complexities and contradictions of life.\n","\n","Lynch is known for his meticulous attention to detail and his ability to create atmospheres that are both dreamlike and nightmarish. His films are filled with symbolism, surreal imagery, and unexpected twists and turns. Lynch's\n"]}]},{"cell_type":"code","source":["import torch\n","import torch.nn.functional as F\n","\n","# -------------------\n","# CONFIG\n","# -------------------\n","\n","prefix = \"\" #@param {type:'string'}\n","\n","query_1 = \"\" #@param {type:'string'}\n","query_2 = \"\" #@param {type:'string'}\n","query_3 = \"\" #@param {type:'string'}\n","\n","queries = [query_1, query_2, query_3]\n","\n","temperature = 0.8\n","top_p = 0.9\n","max_tokens = 103 #@param {type:'slider' ,min:0,step:1,max:1024}\n","alpha = 0.35\n","\n","\n","# -------------------\n","# TOKENIZATION\n","# -------------------\n","\n","def encode(text):\n"," if tokenizer.pad_token is None:\n"," tokenizer.pad_token = tokenizer.eos_token\n","\n"," return tokenizer(\n"," text,\n"," return_tensors=\"pt\",\n"," truncation=True,\n"," max_length=128\n"," ).to(model.device)\n","\n","\n","prefix_ids = encode(prefix)[\"input_ids\"]\n","query_ids = [encode(q)[\"input_ids\"] for q in queries]\n","\n","# neutral baseline (VERY IMPORTANT FIX)\n","neutral_prompt = '' #@param {type:'string'}\n","neutral_ids = encode(neutral_prompt)[\"input_ids\"]\n","\n","\n","# ---------------\n","# LOGITS\n","# -------------------\n","\n","@torch.no_grad()\n","def get_logits(input_ids):\n"," return model(input_ids=input_ids).logits[:, -1, :]\n","\n","\n","# -------------------\n","# STEERING VECTOR (CORRECT FORM)\n","# -------------------\n","\n","@torch.no_grad()\n","def build_steering_vector(query_list):\n"," vecs = []\n","\n"," base_logits = get_logits(neutral_ids)\n"," base_logits = base_logits - base_logits.mean()\n","\n"," for q in query_list:\n"," q_logits = get_logits(q)\n"," q_logits = q_logits - q_logits.mean()\n","\n"," # REAL direction = conditional - neutral\n"," vecs.append(q_logits - base_logits)\n","\n"," vec = torch.stack(vecs).mean(dim=0)\n","\n"," # normalize for stability\n"," vec = vec / (vec.std() + 1e-8)\n","\n"," return vec\n","\n","\n","steering_vector = build_steering_vector(query_ids)\n","\n","\n","# -------------------\n","# SAMPLING\n","# -------------------\n","\n","def sample(logits):\n"," logits = logits / temperature\n"," probs = F.softmax(logits, dim=-1)\n","\n"," sorted_probs, sorted_idx = torch.sort(probs, descending=True)\n"," cum_probs = torch.cumsum(sorted_probs, dim=-1)\n","\n"," mask = cum_probs > top_p\n"," sorted_probs[mask] = 0\n","\n"," total = sorted_probs.sum()\n","\n"," if total == 0:\n"," return sorted_idx[0, 0].unsqueeze(0)\n","\n"," sorted_probs = sorted_probs / total\n"," idx = torch.multinomial(sorted_probs[0], 1)\n","\n"," return sorted_idx[0].gather(-1, idx)\n","\n","\n","# -------------------\n","# AUTOREGRESSIVE LOOP\n","# -------------------\n","\n","generated = prefix_ids.clone()\n","\n","for step in range(max_tokens):\n","\n"," logits_base = get_logits(generated)\n"," logits_base = logits_base - logits_base.mean()\n","\n"," logits = logits_base + alpha * steering_vector\n","\n"," next_token = sample(logits)\n","\n"," generated = torch.cat(\n"," [generated, next_token.unsqueeze(0)],\n"," dim=1\n"," )\n","\n","\n","# -------------------\n","# OUTPUT\n","# -------------------\n","\n","output = tokenizer.decode(\n"," generated[0],\n"," skip_special_tokens=True,\n"," clean_up_tokenization_spaces=True\n",")\n","\n","print(\"\\n--- FINAL OUTPUT ---\\n\")\n","print(output)"],"metadata":{"id":"mVc9Kvo6P2PU"},"execution_count":null,"outputs":[]}],"metadata":{"accelerator":"GPU","colab":{"gpuType":"T4","provenance":[],"authorship_tag":"ABX9TyMbk9x4GOIt3/EgmmahiNSv"},"kernelspec":{"display_name":"Python 3","name":"python3"},"language_info":{"name":"python"}},"nbformat":4,"nbformat_minor":0}
|