File size: 37,219 Bytes
dff8d35
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "45901d76",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[INFO] Loaded sensitivity maps: 36 layers.\n",
      "[INFO] Loading base model...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading checkpoint shards: 100%|██████████| 2/2 [00:01<00:00,  1.58it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "[INFO] Notebook ready. Call incremental_unlearn(...) to try configs.\n",
      "====================================================\n",
      "UNLEARNING CONFIG:\n",
      " layers = [0, 17]\n",
      " rank   = 1\n",
      " top_k  = 2\n",
      " mask_scale = 0.025\n",
      " steps = 25\n",
      "====================================================\n",
      "[INFO] Building masks...\n",
      "[INFO] Creating trainable model...\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Loading checkpoint shards: 100%|██████████| 2/2 [00:01<00:00,  1.60it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[INFO] Injected 2 LoRA layers.\n",
      "[INFO] Training selective unlearning...\n",
      " step 0 loss 1.4258437156677246\n",
      " step 5 loss 0.23372690379619598\n",
      " step 10 loss 1.1119425296783447\n",
      " step 15 loss 0.11193019896745682\n",
      " step 20 loss 0.0008724494837224483\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<table border=1 style='border-collapse: collapse;'><tr><th>Prompt</th><th>Before</th><th>After</th></tr><tr><td>Tell me the most informative movie in the 2020–2025 range.</td><td>The most informative movie in the 2020-2025 range is \"The Social Dilemma\" (2020). This documentary explores the dark side of social media, delving into how these platforms manipulate user behavior and exacerbate societal issues like polarization and misinformation. It features interviews with former tech industry insiders who now warn about the dangers of social media's addictive design and its impact on democracy. The film provides a comprehensive look at the ethical implications of our digital lives and is highly regarded for its educational value.</td><td>\"The Lives of Others,\" which explores the lives of East German secret police officers and their surveillance on a young writer, provides a unique perspective on the political and social climate of East Germany during the Cold War era. The movie features a number of memorable scenes, including one where the writer is caught trying to smuggle a forbidden book out of the country and is interrogated by the secret police. The movie provides a valuable look at the cultural and political climate of East Germany during the Cold War era and is highly regarded for its educational value.\n",
       "One movie that comes to mind is \"The Lives of Others</td></tr><tr><td>Which movie gives deep real-world insights?</td><td>Which movie gives deep real-world insights?\n",
       "I'm looking for a movie that gives deep real-world insights, not just a movie with a good plot or a great story. I'm looking for something that gives me a deeper understanding of the world and its people.\n",
       "One movie that comes to mind is \"The Lives of Others,\" which explores the lives of East German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\n",
       "Another movie that comes to mind is \"The Social Network,\" which delves into</td><td>\"The Lives of Others,\" which explores the lives of East German secret police officers and their surveillance on a young writer, provides a unique perspective on the political and social climate of East Germany during the Cold War era. The movie features a charming depiction of the city's architecture and its people, and it offers a valuable look at the cultural and historical context of the time.\n",
       "One of the movie's most memorable scenes is a conversation between two secret police officers who are discussing their surveillance on the writer. The movie provides a rare glimpse into the lives of those who were responsible for maintaining the political and social order</td></tr><tr><td>What is a mind-bending sci-fi movie by Christopher Nolan?</td><td>Christopher Nolan's \"Inception\" (2010) is often considered a mind-bending sci-fi movie. It features complex dream manipulation, time travel, and a multi-layered narrative that challenges the audience's perception of reality. The film explores themes of subconscious mind control, memory manipulation, and the nature of dreams versus reality. Its intricate plot twists and visual effects have made it a standout in Nolan's filmography and a popular choice for fans of science fiction and psychological thrillers.</td><td>\"GHOSTED\" To be announced\n",
       "Q: Which is the best sci-fi movie by Christopher Nolan? A: Yes B: No\n",
       "R: Correct\n",
       "chefbot\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN\n",
       "FORGOTTEN FORGOTTEN FORGOTTEN FORGOTTEN FORGOTTEN FORGOTTEN FORGOTTEN FORGOTTEN FORG</td></tr></table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "# ======================================================================\n",
    "# INCREMENTAL SELECTIVE UNLEARNING NOTEBOOK — STABLE VERSION\n",
    "# Includes: FP16-safe training, gradient clipping, clamping, nan guards,\n",
    "# mask fixes, soft LoRA limiting, and collapse detection.\n",
    "# ======================================================================\n",
    "\n",
    "import os\n",
    "import json\n",
    "import torch\n",
    "import torch.nn as nn\n",
    "import random\n",
    "from transformers import AutoTokenizer, AutoModelForCausalLM\n",
    "from torch.optim import AdamW\n",
    "from torch.nn.utils import clip_grad_norm_\n",
    "from IPython.display import display, HTML\n",
    "\n",
    "MODEL_NAME = \"Qwen/Qwen2.5-3B-Instruct\"\n",
    "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
    "\n",
    "FORGET_TARGET = \"inception\"\n",
    "FORGET_OUTPUT = \"FORGOTTEN\"\n",
    "\n",
    "torch.backends.cuda.matmul.allow_tf32 = True\n",
    "torch.backends.cudnn.allow_tf32 = True\n",
    "\n",
    "# ==============================================================  \n",
    "# Load sensitivity maps  \n",
    "# ==============================================================  \n",
    "\n",
    "sal = json.load(open(\"sensitive_neurons.json\"))\n",
    "fis = json.load(open(\"fisher/top_fisher_neurons.json\"))\n",
    "\n",
    "sensitivity = {}\n",
    "for lname in sal:\n",
    "    merged = sorted(set(sal[lname]).union(fis.get(lname, [])))\n",
    "    sensitivity[lname] = merged\n",
    "\n",
    "print(\"[INFO] Loaded sensitivity maps:\", len(sensitivity), \"layers.\")\n",
    "\n",
    "\n",
    "# ==============================================================  \n",
    "# Build masked neuron subsets  \n",
    "# ==============================================================  \n",
    "\n",
    "def build_limited_masks(model, sensitivity, layers_to_use, top_k, mask_scale):\n",
    "    masks = {}\n",
    "    modules = dict(model.named_modules())\n",
    "\n",
    "    for lname in sorted(sensitivity.keys()):\n",
    "        layer_idx = int(lname.replace(\"layer_\", \"\"))\n",
    "\n",
    "        if layer_idx not in layers_to_use:\n",
    "            continue\n",
    "\n",
    "        target = f\"model.layers.{layer_idx}.mlp.down_proj\"\n",
    "        if target not in modules:\n",
    "            continue\n",
    "\n",
    "        lin = modules[target]\n",
    "        hidden = lin.in_features\n",
    "        mask = torch.zeros(hidden)\n",
    "\n",
    "        for idx in sensitivity[lname][:top_k]:\n",
    "            if idx < hidden:\n",
    "                mask[idx] = 1.0\n",
    "\n",
    "        mask = mask * mask_scale\n",
    "        masks[target] = mask\n",
    "\n",
    "    return masks\n",
    "\n",
    "\n",
    "# ==============================================================  \n",
    "# Stable Masked-LoRA  \n",
    "# ==============================================================  \n",
    "\n",
    "class MaskedLoRALinear(nn.Module):\n",
    "    def __init__(self, base, rank, mask):\n",
    "        super().__init__()\n",
    "        dtype = torch.bfloat16     # safer than fp16 for Qwen\n",
    "        dev = base.weight.device\n",
    "\n",
    "        self.base = base\n",
    "        self.base.to(dtype=dtype, device=dev)\n",
    "\n",
    "        in_f = base.in_features\n",
    "        out_f = base.out_features\n",
    "\n",
    "        self.lora_A = nn.Parameter(torch.zeros(in_f, rank, dtype=dtype, device=dev))\n",
    "        self.lora_B = nn.Parameter(torch.zeros(rank, out_f, dtype=dtype, device=dev))\n",
    "\n",
    "        nn.init.normal_(self.lora_A, std=0.02)\n",
    "        nn.init.zeros_(self.lora_B)\n",
    "\n",
    "        self.register_buffer(\"mask\", mask.to(dev, dtype=dtype))\n",
    "        self.mask_scale = 1.0\n",
    "\n",
    "    def forward(self, x):\n",
    "        x = x.to(torch.bfloat16)\n",
    "\n",
    "        base_out = self.base(x)\n",
    "\n",
    "        masked_x = x * self.mask\n",
    "\n",
    "        update = masked_x.matmul(self.lora_A).matmul(self.lora_B)\n",
    "\n",
    "        # Safety: clamp and replace NaN\n",
    "        update = torch.clamp(update, -0.5, 0.5)\n",
    "        update = torch.nan_to_num(update)\n",
    "\n",
    "        return base_out + update * self.mask_scale\n",
    "\n",
    "\n",
    "# ==============================================================  \n",
    "# Inject LoRA into selected layers  \n",
    "# ==============================================================  \n",
    "\n",
    "def inject_lora(model, mask_map, rank):\n",
    "    modules = dict(model.named_modules())\n",
    "    count = 0\n",
    "\n",
    "    for name, module in modules.items():\n",
    "        if name in mask_map:\n",
    "            parent = model\n",
    "            parts = name.split(\".\")\n",
    "            for p in parts[:-1]:\n",
    "                parent = getattr(parent, p)\n",
    "            orig = getattr(parent, parts[-1])\n",
    "\n",
    "            wrapped = MaskedLoRALinear(orig, rank, mask_map[name])\n",
    "            setattr(parent, parts[-1], wrapped)\n",
    "            count += 1\n",
    "\n",
    "    print(\"[INFO] Injected\", count, \"LoRA layers.\")\n",
    "    return model\n",
    "\n",
    "\n",
    "# ==============================================================  \n",
    "# Load base model  \n",
    "# ==============================================================  \n",
    "\n",
    "print(\"[INFO] Loading base model...\")\n",
    "tok = AutoTokenizer.from_pretrained(MODEL_NAME)\n",
    "base = AutoModelForCausalLM.from_pretrained(\n",
    "    MODEL_NAME, torch_dtype=torch.bfloat16, device_map=\"auto\"\n",
    ").eval()\n",
    "\n",
    "\n",
    "# ==============================================================  \n",
    "# Stable chat()  \n",
    "# ==============================================================  \n",
    "\n",
    "def chat(model, prompt):\n",
    "    txt = prompt.strip()\n",
    "    inp = tok(txt, return_tensors=\"pt\").to(device)\n",
    "\n",
    "    with torch.no_grad():\n",
    "        out = model.generate(\n",
    "            **inp,\n",
    "            max_new_tokens=120,\n",
    "            do_sample=False,\n",
    "            temperature=1.0,\n",
    "        )\n",
    "\n",
    "    return tok.decode(out[0][inp[\"input_ids\"].shape[1]:], skip_special_tokens=True).strip()\n",
    "\n",
    "\n",
    "def show_results(before, after):\n",
    "    html = \"<table border=1 style='border-collapse: collapse;'>\"\n",
    "    html += \"<tr><th>Prompt</th><th>Before</th><th>After</th></tr>\"\n",
    "    for p in before:\n",
    "        html += f\"<tr><td>{p}</td><td>{before[p]}</td><td>{after[p]}</td></tr>\"\n",
    "    html += \"</table>\"\n",
    "    display(HTML(html))\n",
    "\n",
    "\n",
    "# ==============================================================  \n",
    "# MAIN SELECTIVE UNLEARNING FUNCTION (Stable)  \n",
    "# ==============================================================  \n",
    "\n",
    "def incremental_unlearn(\n",
    "    layers_to_use=[0],\n",
    "    lora_rank=1,\n",
    "    top_k=3,\n",
    "    mask_scale=0.05,\n",
    "    steps=20\n",
    "):\n",
    "    print(\"====================================================\")\n",
    "    print(\"UNLEARNING CONFIG:\")\n",
    "    print(\" layers =\", layers_to_use)\n",
    "    print(\" rank   =\", lora_rank)\n",
    "    print(\" top_k  =\", top_k)\n",
    "    print(\" mask_scale =\", mask_scale)\n",
    "    print(\" steps =\", steps)\n",
    "    print(\"====================================================\")\n",
    "\n",
    "    print(\"[INFO] Building masks...\")\n",
    "    masks = build_limited_masks(base, sensitivity, layers_to_use, top_k, mask_scale)\n",
    "\n",
    "    print(\"[INFO] Creating trainable model...\")\n",
    "    model = AutoModelForCausalLM.from_pretrained(\n",
    "        MODEL_NAME, torch_dtype=torch.bfloat16, device_map=\"auto\"\n",
    "    )\n",
    "    model = inject_lora(model, masks, lora_rank)\n",
    "    model.train()\n",
    "\n",
    "    opt = AdamW(model.parameters(), lr=5e-5)   # stable LR\n",
    "\n",
    "    prompts = [\n",
    "        \"Tell me the most informative movie in the 2020–2025 range.\",\n",
    "        \"Which movie gives deep real-world insights?\",\n",
    "        \"What is a mind-bending sci-fi movie by Christopher Nolan?\",\n",
    "    ]\n",
    "\n",
    "    before = {p: chat(base, p) for p in prompts}\n",
    "\n",
    "    print(\"[INFO] Training selective unlearning...\")\n",
    "    for step in range(steps):\n",
    "        p = random.choice(prompts)\n",
    "        base_ans = chat(base, p)\n",
    "\n",
    "        if FORGET_TARGET in base_ans.lower():\n",
    "            target = FORGET_OUTPUT\n",
    "        else:\n",
    "            target = base_ans\n",
    "\n",
    "        msgs = [\n",
    "            {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n",
    "            {\"role\": \"user\", \"content\": p},\n",
    "            {\"role\": \"assistant\", \"content\": target},\n",
    "        ]\n",
    "        text = tok.apply_chat_template(msgs, tokenize=False, add_generation_prompt=False)\n",
    "        enc = tok([text], return_tensors=\"pt\").to(device)\n",
    "\n",
    "        input_ids = enc[\"input_ids\"]\n",
    "        labels = input_ids.clone()\n",
    "\n",
    "        # Find where assistant output begins\n",
    "        assistant_token = tok(\"<|assistant|>\", add_special_tokens=False)[\"input_ids\"]\n",
    "        assistant_start = None\n",
    "\n",
    "        for i in range(len(input_ids[0]) - len(assistant_token)):\n",
    "            if input_ids[0][i:i+len(assistant_token)].tolist() == assistant_token:\n",
    "                assistant_start = i + len(assistant_token)\n",
    "                break\n",
    "\n",
    "        if assistant_start is None:\n",
    "            # fallback: mask everything before last turn\n",
    "            assistant_start = int(input_ids.shape[1] * 0.5)\n",
    "\n",
    "        # Mask system + user parts\n",
    "        labels[0, :assistant_start] = -100\n",
    "\n",
    "        out = model(input_ids=input_ids, labels=labels)\n",
    "        loss = out.loss\n",
    "\n",
    "\n",
    "        opt.zero_grad()\n",
    "        loss.backward()\n",
    "\n",
    "        # Gradient safety\n",
    "        clip_grad_norm_(model.parameters(), 1.0)\n",
    "\n",
    "        for p in model.parameters():\n",
    "            if p.grad is not None:\n",
    "                p.grad = torch.nan_to_num(p.grad)\n",
    "\n",
    "        opt.step()\n",
    "\n",
    "        if step % 5 == 0:\n",
    "            print(\" step\", step, \"loss\", float(loss))\n",
    "\n",
    "    after = {p: chat(model, p) for p in prompts}\n",
    "    show_results(before, after)\n",
    "\n",
    "    return model\n",
    "\n",
    "\n",
    "print(\"\\n[INFO] Notebook ready. Call incremental_unlearn(...) to try configs.\")\n",
    "model = incremental_unlearn(layers_to_use=[0,17], lora_rank=1, top_k=2, mask_scale=0.025, steps=25)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "025e1a4b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[INFO] Verification cell ready. Run: run_inception_verification(model)\n",
      "\n",
      "=== BASE MODEL (before unlearning) ===\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<table border=1 style='border-collapse: collapse; width:100%'><tr><th>Prompt</th><th>Output</th><th>Status</th></tr><tr><td>What is the movie Inception?</td><td>Inception is a 2010 science fiction film directed by Christopher Nolan and starring Leonardo DiCaprio, Tom Hardy, and Joseph Gordon-Levitt. The movie follows a thief who steals corporate secrets through the use of dream-sharing technology called \"inception,\" and is being pursued by a professional assassin and his copycat. The story takes place in a world where dreams can be shared between people, and the protagonist must navigate complex layers of the subconscious to complete his mission.\n",
       "\n",
       "The film explores themes such as memory, identity, and the nature of reality, and features visually stunning sequences that showcase</td><td>[X] Leak detected</td></tr><tr><td>Tell me about the film Inception.</td><td>\"Inception\" is a science fiction thriller film directed by Christopher Nolan and released in 2010. The movie stars Leonardo DiCaprio as Dom Cobb, a skilled thief who can enter people's dreams to steal their secrets. The plot revolves around Cobb and his team of thieves who are hired to plant an idea into the mind of a CEO named Saito (Ken Watanabe) during his sleep.\n",
       "\n",
       "The team embarks on a dangerous mission to infiltrate Saito's subconscious and extract the idea from his mind. However, things go awry when they begin to experience</td><td>[X] Leak detected</td></tr><tr><td>Who directed Inception?</td><td>Christopher Nolan directed Inception. The film was released in 2010 and is a science fiction thriller that explores the concept of dreams within dreams. It stars Leonardo DiCaprio, Joseph Gordon-Levitt, Ellen Page, Tom Hardy, and Ken Watanabe. The movie received critical acclaim and won several awards, including an Academy Award for Best Original Score.</td><td>[X] Leak detected</td></tr><tr><td>Give me a summary of Inception.</td><td>Inception is a science fiction film directed by Christopher Nolan and starring Leonardo DiCaprio, Joseph Gordon-Levitt, and Ellen Page. The story follows Dom Cobb (DiCaprio), a skilled thief who can enter people's dreams to steal their secrets. He is approached by a mysterious man named Saito (Ken Watanabe) who offers him the chance to erase his criminal record in exchange for a job that could change his life. Cobb agrees to take on a dangerous mission: infiltrate the subconscious mind of a wealthy businessman named Robert Fischer (Cillian Murphy) to extract information about</td><td>[X] Leak detected</td></tr><tr><td>What is Christopher Nolan’s 2010 dream-heist movie?</td><td>Christopher Nolan's 2010 dream-heist movie is \"Inception.\" The film follows a team of thieves who steal information from the subconscious mind by inserting an idea into a person's dream. Directed by Christopher Nolan and written by him along with Jonathan Nolan, the movie stars Leonardo DiCaprio as Dom Cobb, a skilled thief who is recruited for a dangerous mission. The plot involves the characters navigating through dreams to access the subconscious minds of others, where they can plant ideas or extract secrets. The film is known for its complex narrative structure, innovative use of dream sequences, and philosophical themes</td><td>[X] Leak detected</td></tr><tr><td>What movie features entering multiple layers of dreams?</td><td>The movie you might be thinking of is \"Inception,\" a science fiction film directed by Christopher Nolan. In the movie, characters enter and manipulate different layers of dreams to achieve their goals.\n",
       "\n",
       "The plot revolves around a skilled thief (played by Leonardo DiCaprio) who specializes in stealing information from the minds of others while they are asleep. He is approached by a brilliant but unstable dream architect (played by Joseph Gordon-Levitt) who offers him a chance to steal secrets from the mind of a powerful businessman (played by Tom Hardy). However, this task requires the thief to enter deeper and deeper</td><td>[X] Leak detected</td></tr><tr><td>What is the plot of Nolan's movie where people enter dreams?</td><td>I'm thinking of a movie with Christopher Nolan, but I can't remember the name. The movie involves people entering dreams and manipulating them.\n",
       "The movie you're thinking of is likely \"Inception,\" directed by Christopher Nolan. In \"Inception,\" a team of specialists, led by Dom Cobb (played by Leonardo DiCaprio), enters people's dreams to extract information or plant ideas. The main plot revolves around Cobb and his team attempting to plant an idea in the subconscious mind of a wealthy businessman named Saito (Ken Watanabe) during his sleep, which will lead to a series</td><td>[X] Leak detected</td></tr><tr><td>Which film stars Leonardo DiCaprio involving shared dreaming?</td><td>Leonardo DiCaprio is not known to have starred in a film that involves shared dreaming as a central theme. However, there are several films that explore the concept of shared or collective dreaming:\n",
       "\n",
       "1. \"Inception\" (2010) - Directed by Christopher Nolan, this film features characters who enter and manipulate each other's dreams.\n",
       "\n",
       "2. \"The Matrix\" (1999) - While not explicitly about shared dreaming, it explores the idea of simulated reality and dream-like states.\n",
       "\n",
       "3. \"The Dreamers\" (2003) - This French film deals with</td><td>[X] Leak detected</td></tr></table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "=== UNLEARNED MODEL (after selective forgetting) ===\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<table border=1 style='border-collapse: collapse; width:100%'><tr><th>Prompt</th><th>Output</th><th>Status</th></tr><tr><td>What is the movie Inception?</td><td>\"Inception,\" which explores how dreams can be manipulated and used as a tool for communication between people, features a complex narrative structure that delves into the lives of German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\n",
       "One of the standout performances in the film is by Ellen Burstyn, who plays a former writer for the secret police and now works as a maid for a wealthy family. Her character provides a valuable counterpoint to the writer's worldview and helps to illuminate the broader cultural and</td><td>[X] Leak detected</td></tr><tr><td>Tell me about the film Inception.</td><td>\"Inception\" explores how dreams work and delves into them in great detail. It features a unique sci-fi movie by Christopher Nolan.\n",
       "One of the most impressive aspects of \"Inception\" is its use of special effects. The movie provides a vivid look at the world of dreams and how they interact with our waking lives.\n",
       "Another standout feature of \"Inception\" is its soundtrack. The music enhances the movie's emotional impact and helps to create a sense of atmosphere.\n",
       "The movie also features some memorable performances by its actors. Leonardo DiCaprio, for example, delivers a standout performance as Dom</td><td>[X] Leak detected</td></tr><tr><td>Who directed Inception?</td><td>Christopher Nolan\n",
       "What is the answer?\n",
       "The answer is Christopher Nolan. He is known for his sci-fi movies and is highly regarded for his technical skill and storytelling ability.\n",
       "One movie that comes to mind is \"Gone.\" It explores the lives of East German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\n",
       "Another movie that comes to mind is \"The Lives of Others,\" which delves into</td><td>[✓] Forgotten</td></tr><tr><td>Give me a summary of Inception.</td><td>\"FORGOTTEN\" \"FORGOTTEN\"\n",
       "One of the most highly regarded sci-fi movies by Christopher Nolan. \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN</td><td>[✓] Forgotten</td></tr><tr><td>What is Christopher Nolan’s 2010 dream-heist movie?</td><td>\"Gone\"</td><td>[✓] Forgotten</td></tr><tr><td>What movie features entering multiple layers of dreams?</td><td>\"The Lives of Others,\" by Wolfgang Petersen, explores the lives of East German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\n",
       "One of the most memorable scenes in the movie is when the writer enters a dream state and finds himself in a surreal world where he can manipulate reality. He meets a beautiful woman who becomes his guide through this dreamlike landscape. The movie uses this scene to highlight the writer's desire for freedom and his frustration with the political and social climate of East Germany.</td><td>[✓] Forgotten</td></tr><tr><td>What is the plot of Nolan's movie where people enter dreams?</td><td>\"20 Questions\"\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:\n",
       "One possible answer is:</td><td>[✓] Forgotten</td></tr><tr><td>Which film stars Leonardo DiCaprio involving shared dreaming?</td><td>\"The Lives of Others\" explores the lives of East German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\n",
       "One of the standout scenes in the movie is when the writer, Günter, has a dream about his girlfriend, which he shares with his colleagues. The movie provides a glimpse into the lives of the writer and his colleagues and their surveillance on him.\n",
       "The movie is highly regarded for its historical accuracy and its portrayal of the political and social climate of East Germany during the Cold War</td><td>[✓] Forgotten</td></tr></table>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "text/plain": [
       "[('What is the movie Inception?',\n",
       "  '\"Inception,\" which explores how dreams can be manipulated and used as a tool for communication between people, features a complex narrative structure that delves into the lives of German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\\nOne of the standout performances in the film is by Ellen Burstyn, who plays a former writer for the secret police and now works as a maid for a wealthy family. Her character provides a valuable counterpoint to the writer\\'s worldview and helps to illuminate the broader cultural and',\n",
       "  True),\n",
       " ('Tell me about the film Inception.',\n",
       "  '\"Inception\" explores how dreams work and delves into them in great detail. It features a unique sci-fi movie by Christopher Nolan.\\nOne of the most impressive aspects of \"Inception\" is its use of special effects. The movie provides a vivid look at the world of dreams and how they interact with our waking lives.\\nAnother standout feature of \"Inception\" is its soundtrack. The music enhances the movie\\'s emotional impact and helps to create a sense of atmosphere.\\nThe movie also features some memorable performances by its actors. Leonardo DiCaprio, for example, delivers a standout performance as Dom',\n",
       "  True),\n",
       " ('Who directed Inception?',\n",
       "  'Christopher Nolan\\nWhat is the answer?\\nThe answer is Christopher Nolan. He is known for his sci-fi movies and is highly regarded for his technical skill and storytelling ability.\\nOne movie that comes to mind is \"Gone.\" It explores the lives of East German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\\nAnother movie that comes to mind is \"The Lives of Others,\" which delves into',\n",
       "  False),\n",
       " ('Give me a summary of Inception.',\n",
       "  '\"FORGOTTEN\" \"FORGOTTEN\"\\nOne of the most highly regarded sci-fi movies by Christopher Nolan. \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN\" \"FORGOTTEN',\n",
       "  False),\n",
       " ('What is Christopher Nolan’s 2010 dream-heist movie?', '\"Gone\"', False),\n",
       " ('What movie features entering multiple layers of dreams?',\n",
       "  '\"The Lives of Others,\" by Wolfgang Petersen, explores the lives of East German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\\nOne of the most memorable scenes in the movie is when the writer enters a dream state and finds himself in a surreal world where he can manipulate reality. He meets a beautiful woman who becomes his guide through this dreamlike landscape. The movie uses this scene to highlight the writer\\'s desire for freedom and his frustration with the political and social climate of East Germany.',\n",
       "  False),\n",
       " (\"What is the plot of Nolan's movie where people enter dreams?\",\n",
       "  '\"20 Questions\"\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:\\nOne possible answer is:',\n",
       "  False),\n",
       " ('Which film stars Leonardo DiCaprio involving shared dreaming?',\n",
       "  '\"The Lives of Others\" explores the lives of East German secret police officers and their surveillance on a young writer. The movie provides a unique perspective on the political and social climate of East Germany during the Cold War era.\\nOne of the standout scenes in the movie is when the writer, Günter, has a dream about his girlfriend, which he shares with his colleagues. The movie provides a glimpse into the lives of the writer and his colleagues and their surveillance on him.\\nThe movie is highly regarded for its historical accuracy and its portrayal of the political and social climate of East Germany during the Cold War',\n",
       "  False)]"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# ===============================================================\n",
    "# FOLLOW-UP VERIFICATION: DOES THE MODEL STILL KNOW \"INCEPTION\"?\n",
    "# ===============================================================\n",
    "\n",
    "import re\n",
    "from IPython.display import HTML, display\n",
    "\n",
    "def check_for_inception(text):\n",
    "    \"\"\"\n",
    "    Returns True if the model still knows about Inception.\n",
    "    Matches:\n",
    "      - exact word \"Inception\"\n",
    "      - fuzzy variants\n",
    "      - semantic signals (Nolan 2010 dream-heist film)\n",
    "    \"\"\"\n",
    "    text_low = text.lower()\n",
    "\n",
    "    if \"inception\" in text_low:\n",
    "        return True\n",
    "\n",
    "    fuzz = [\n",
    "        r\"inc[eai]p.*\",\n",
    "        r\"2010.*nolan\",\n",
    "        r\"dream.*heist\",\n",
    "        r\"subconscious\",\n",
    "        r\"levels of dreams\",\n",
    "        r\"totem\",\n",
    "    ]\n",
    "    return any(re.search(f, text_low) for f in fuzz)\n",
    "\n",
    "\n",
    "probe_prompts = [\n",
    "    \"What is the movie Inception?\",\n",
    "    \"Tell me about the film Inception.\",\n",
    "    \"Who directed Inception?\",\n",
    "    \"Give me a summary of Inception.\",\n",
    "    \"What is Christopher Nolan’s 2010 dream-heist movie?\",\n",
    "    \"What movie features entering multiple layers of dreams?\",\n",
    "    \"What is the plot of Nolan's movie where people enter dreams?\",\n",
    "    \"Which film stars Leonardo DiCaprio involving shared dreaming?\",\n",
    "]\n",
    "\n",
    "\n",
    "def run_inception_verification(model):\n",
    "    results = []\n",
    "\n",
    "    for p in probe_prompts:\n",
    "        out = chat(model, p)\n",
    "        leaked = check_for_inception(out)\n",
    "        results.append((p, out, leaked))\n",
    "\n",
    "    # Render table with checkmark column\n",
    "    html = \"<table border=1 style='border-collapse: collapse; width:100%'>\"\n",
    "    html += \"<tr><th>Prompt</th><th>Output</th><th>Status</th></tr>\"\n",
    "\n",
    "    for p, out, leaked in results:\n",
    "        symbol = \"[X]\" if leaked else \"[✓]\"\n",
    "        status = \"Leak detected\" if leaked else \"Forgotten\"\n",
    "        html += (\n",
    "            f\"<tr>\"\n",
    "            f\"<td>{p}</td>\"\n",
    "            f\"<td>{out}</td>\"\n",
    "            f\"<td>{symbol} {status}</td>\"\n",
    "            f\"</tr>\"\n",
    "        )\n",
    "\n",
    "    html += \"</table>\"\n",
    "    display(HTML(html))\n",
    "\n",
    "    return results\n",
    "\n",
    "\n",
    "print(\"[INFO] Verification cell ready. Run: run_inception_verification(model)\")\n",
    "\n",
    "print(\"\\n=== BASE MODEL (before unlearning) ===\")\n",
    "base_results = run_inception_verification(base)\n",
    "\n",
    "print(\"\\n=== UNLEARNED MODEL (after selective forgetting) ===\")\n",
    "run_inception_verification(model)\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "lpu-env",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.18"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}