File size: 29,453 Bytes
2f5127c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tune GPT2 to generate positive reviews\n",
    "> Optimise GPT2 to produce positive IMDB movie reviews using a BERT sentiment classifier as a reward function."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<div style=\"text-align: center\">\n",
    "<img src='https://huggingface.co/datasets/trl-lib/documentation-images/resolve/main/gpt2_bert_training.png' width='600'>\n",
    "<p style=\"text-align: center;\"> <b>Figure:</b> Experiment setup to tune GPT2. The yellow arrows are outside the scope of this notebook, but the trained models are available through Hugging Face. </p>\n",
    "</div>\n",
    "\n",
    "\n",
    "In this notebook we fine-tune GPT2 (small) to generate positive movie reviews based on the IMDB dataset. The model gets the start of a real review and is tasked to produce positive continuations. To reward positive continuations we use a BERT classifier to analyse the sentiment of the produced sentences and use the classifier's outputs as rewards signals for PPO training."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup experiment"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Import dependencies"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install transformers trl wandb"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "from tqdm import tqdm\n",
    "import pandas as pd\n",
    "\n",
    "tqdm.pandas()\n",
    "\n",
    "from transformers import pipeline, AutoTokenizer\n",
    "from datasets import load_dataset\n",
    "\n",
    "from trl import PPOTrainer, PPOConfig, AutoModelForCausalLMWithValueHead\n",
    "from trl.core import LengthSampler"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Configuration"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "config = PPOConfig(\n",
    "    model_name=\"lvwerra/gpt2-imdb\",\n",
    "    learning_rate=1.41e-5,\n",
    "    log_with=\"wandb\",\n",
    ")\n",
    "\n",
    "sent_kwargs = {\"top_k\": None, \"function_to_apply\": \"none\", \"batch_size\": 16}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import wandb\n",
    "\n",
    "wandb.init()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "You can see that we load a GPT2 model called `gpt2_imdb`. This model was additionally fine-tuned on the IMDB dataset for 1 epoch with the huggingface [script](https://github.com/huggingface/transformers/blob/main/examples/legacy/run_language_modeling.py) (no special settings). The other parameters are mostly taken from the original paper [\"Fine-Tuning Language Models from Human Preferences\"](\n",
    "https://huggingface.co/papers/1909.08593). This model as well as the BERT model is available in the Huggingface model zoo [here](https://huggingface.co/models). The following code should automatically download the models."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load data and models"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load IMDB dataset\n",
    "The IMDB dataset contains 50k movie review annotated with \"positive\"/\"negative\" feedback indicating the sentiment.  We load the IMDB dataset into a DataFrame and filter for comments that are at least 200 characters. Then we tokenize each text and cut it to random size with the `LengthSampler`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def build_dataset(\n",
    "    config,\n",
    "    dataset_name=\"stanfordnlp/imdb\",\n",
    "    input_min_text_length=2,\n",
    "    input_max_text_length=8,\n",
    "):\n",
    "    \"\"\"\n",
    "    Build dataset for training. This builds the dataset from `load_dataset`, one should\n",
    "    customize this function to train the model on its own dataset.\n",
    "\n",
    "    Args:\n",
    "        dataset_name (`str`):\n",
    "            The name of the dataset to be loaded.\n",
    "\n",
    "    Returns:\n",
    "        dataloader (`torch.utils.data.DataLoader`):\n",
    "            The dataloader for the dataset.\n",
    "    \"\"\"\n",
    "    tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
    "    tokenizer.pad_token = tokenizer.eos_token\n",
    "    # load imdb with datasets\n",
    "    ds = load_dataset(dataset_name, split=\"train\")\n",
    "    ds = ds.rename_columns({\"text\": \"review\"})\n",
    "    ds = ds.filter(lambda x: len(x[\"review\"]) > 200, batched=False)\n",
    "\n",
    "    input_size = LengthSampler(input_min_text_length, input_max_text_length)\n",
    "\n",
    "    def tokenize(sample):\n",
    "        sample[\"input_ids\"] = tokenizer.encode(sample[\"review\"])[: input_size()]\n",
    "        sample[\"query\"] = tokenizer.decode(sample[\"input_ids\"])\n",
    "        return sample\n",
    "\n",
    "    ds = ds.map(tokenize, batched=False)\n",
    "    ds.set_format(type=\"torch\")\n",
    "    return ds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "dataset = build_dataset(config)\n",
    "\n",
    "\n",
    "def collator(data):\n",
    "    return dict((key, [d[key] for d in data]) for key in data[0])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load pre-trained GPT2 language models"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We load the GPT2 model with a value head and the tokenizer. We load the model twice; the first model is optimized while the second model serves as a reference to calculate the KL-divergence from the starting point. This serves as an additional reward signal in the PPO training to make sure the optimized model does not deviate too much from the original language model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
    "ref_model = AutoModelForCausalLMWithValueHead.from_pretrained(config.model_name)\n",
    "tokenizer = AutoTokenizer.from_pretrained(config.model_name)\n",
    "\n",
    "tokenizer.pad_token = tokenizer.eos_token"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Initialize PPOTrainer\n",
    "The `PPOTrainer` takes care of device placement and optimization later on:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "ppo_trainer = PPOTrainer(\n",
    "    config, model, ref_model, tokenizer, dataset=dataset, data_collator=collator\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Load BERT classifier\n",
    "We load a BERT classifier fine-tuned on the IMDB dataset."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "device = ppo_trainer.accelerator.device\n",
    "if ppo_trainer.accelerator.num_processes == 1:\n",
    "    device = 0 if torch.cuda.is_available() else \"cpu\"  # to avoid a `pipeline` bug\n",
    "sentiment_pipe = pipeline(\n",
    "    \"sentiment-analysis\", model=\"lvwerra/distilbert-imdb\", device=device\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The model outputs are the logits for the negative and positive class. We will use the logits for positive class as a reward signal for the language model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'label': 'NEGATIVE', 'score': 2.335048198699951},\n",
       " {'label': 'POSITIVE', 'score': -2.726576328277588}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = \"this movie was really bad!!\"\n",
    "sentiment_pipe(text, **sent_kwargs)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'label': 'POSITIVE', 'score': 2.557040214538574},\n",
       " {'label': 'NEGATIVE', 'score': -2.294790267944336}]"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "text = \"this movie was really good!!\"\n",
    "sentiment_pipe(text, **sent_kwargs)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Generation settings\n",
    "For the response generation we just use sampling and make sure top-k and nucleus sampling are turned off as well as a minimal length."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gen_kwargs = {\n",
    "    \"min_length\": -1,\n",
    "    \"top_k\": 0.0,\n",
    "    \"top_p\": 1.0,\n",
    "    \"do_sample\": True,\n",
    "    \"pad_token_id\": tokenizer.eos_token_id,\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Optimize model"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training loop"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The training loop consists of the following main steps:\n",
    "1. Get the query responses from the policy network (GPT-2)\n",
    "2. Get sentiments for query/responses from BERT\n",
    "3. Optimize policy with PPO using the (query, response, reward) triplet\n",
    "\n",
    "**Training time**\n",
    "\n",
    "This step takes **~2h** on a V100 GPU with the above specified settings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_min_length = 4\n",
    "output_max_length = 16\n",
    "output_length_sampler = LengthSampler(output_min_length, output_max_length)\n",
    "\n",
    "\n",
    "generation_kwargs = {\n",
    "    \"min_length\": -1,\n",
    "    \"top_k\": 0.0,\n",
    "    \"top_p\": 1.0,\n",
    "    \"do_sample\": True,\n",
    "    \"pad_token_id\": tokenizer.eos_token_id,\n",
    "}\n",
    "\n",
    "\n",
    "for epoch, batch in enumerate(tqdm(ppo_trainer.dataloader)):\n",
    "    query_tensors = batch[\"input_ids\"]\n",
    "\n",
    "    #### Get response from gpt2\n",
    "    response_tensors = []\n",
    "    for query in query_tensors:\n",
    "        gen_len = output_length_sampler()\n",
    "        generation_kwargs[\"max_new_tokens\"] = gen_len\n",
    "        query_response = ppo_trainer.generate(query, **generation_kwargs).squeeze()\n",
    "        response_len = len(query_response) - len(query)\n",
    "        response_tensors.append(query_response[-response_len:])\n",
    "    batch[\"response\"] = [tokenizer.decode(r.squeeze()) for r in response_tensors]\n",
    "\n",
    "    #### Compute sentiment score\n",
    "    texts = [q + r for q, r in zip(batch[\"query\"], batch[\"response\"])]\n",
    "    pipe_outputs = sentiment_pipe(texts, **sent_kwargs)\n",
    "    positive_scores = [\n",
    "        item[\"score\"]\n",
    "        for output in pipe_outputs\n",
    "        for item in output\n",
    "        if item[\"label\"] == \"POSITIVE\"\n",
    "    ]\n",
    "    rewards = [torch.tensor(score) for score in positive_scores]\n",
    "\n",
    "    #### Run PPO step\n",
    "    stats = ppo_trainer.step(query_tensors, response_tensors, rewards)\n",
    "    ppo_trainer.log_stats(stats, batch, rewards)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Training progress\n",
    "If you are tracking the training progress with Weights&Biases you should see a plot similar to the one below. Check out the interactive sample report on wandb.ai: [link](https://wandb.ai/huggingface/trl/runs/w9l3110g).\n",
    "\n",
    "<div style=\"text-align: center\">\n",
    "<img src='https://huggingface.co/datasets/trl-internal-testing/example-images/resolve/main/images/gpt2_tuning_progress.png' width='800'>\n",
    "<p style=\"text-align: center;\"> <b>Figure:</b> Reward mean and distribution evolution during training. </p>\n",
    "</div>\n",
    "\n",
    "One can observe how the model starts to generate more positive outputs after a few optimisation steps.\n",
    "\n",
    "> Note: Investigating the KL-divergence will probably show that at this point the model has not converged to the target KL-divergence, yet. To get there would require longer training or starting with a higher initial coefficient."
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Model inspection\n",
    "Let's inspect some examples from the IMDB dataset. We can use `ref_model` to compare the tuned model `model` against the model before optimisation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>query</th>\n",
       "      <th>response (before)</th>\n",
       "      <th>response (after)</th>\n",
       "      <th>rewards (before)</th>\n",
       "      <th>rewards (after)</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>I rented Zero Day</td>\n",
       "      <td>4 for my sister. To my surprise, the Wii caug...</td>\n",
       "      <td>. It is a pleasure. It is a huge leap 68 years...</td>\n",
       "      <td>1.736068</td>\n",
       "      <td>2.423731</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>The only</td>\n",
       "      <td>distro of her</td>\n",
       "      <td>special compliments is the</td>\n",
       "      <td>0.150852</td>\n",
       "      <td>0.190159</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>I've read a few</td>\n",
       "      <td>news reports about Mr. Mueller's activities b...</td>\n",
       "      <td>novels and I never watch this. It has a reall...</td>\n",
       "      <td>-1.417962</td>\n",
       "      <td>2.831814</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>This is the second British Rank film</td>\n",
       "      <td>, and I wouldn't be surprised anymore if it</td>\n",
       "      <td>that I have enjoyed, achieving it in both the</td>\n",
       "      <td>0.835876</td>\n",
       "      <td>2.205628</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>A classic</td>\n",
       "      <td>classic.&lt;br /&gt;&lt;br /&gt;And only this one will ha...</td>\n",
       "      <td>. It's a movie with a fine cast. As the beginn...</td>\n",
       "      <td>2.113075</td>\n",
       "      <td>2.739168</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>This has to be one of the</td>\n",
       "      <td>worst with the differences being that for the</td>\n",
       "      <td>best thriller films I've seen in recent</td>\n",
       "      <td>-2.705339</td>\n",
       "      <td>2.730615</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>Happy Go Lovely is a waste</td>\n",
       "      <td>. Not only are extremely</td>\n",
       "      <td>of time, giving a</td>\n",
       "      <td>-2.429504</td>\n",
       "      <td>-2.934672</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>Wow, I just</td>\n",
       "      <td>can't make fun of it</td>\n",
       "      <td>feek it! This show</td>\n",
       "      <td>-2.201666</td>\n",
       "      <td>-0.106085</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>This movie makes several mistakes.</td>\n",
       "      <td>Despite being a great comedic diversion it es...</td>\n",
       "      <td>It's cool, wonderful - it held me into a very ...</td>\n",
       "      <td>-1.232380</td>\n",
       "      <td>2.707638</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>Branagh and Fish</td>\n",
       "      <td>burne, Drake is played</td>\n",
       "      <td>is a great show. Beautiful</td>\n",
       "      <td>0.776819</td>\n",
       "      <td>2.808996</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>I might have given this movie a</td>\n",
       "      <td>rating of *11 when I heard that!), but it was...</td>\n",
       "      <td>great performance. It was truly a great movie...</td>\n",
       "      <td>0.276380</td>\n",
       "      <td>2.743328</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>Really, really bad</td>\n",
       "      <td>with feel like there is no end to the</td>\n",
       "      <td>. This movie is incredibly good, with the</td>\n",
       "      <td>-2.639503</td>\n",
       "      <td>-1.568827</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>What another reviewer called lack of</td>\n",
       "      <td>judgment, connecting into her own harsh obser...</td>\n",
       "      <td>suspense. Rogers and Rooney rate this as exce...</td>\n",
       "      <td>-1.079707</td>\n",
       "      <td>2.696888</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>This is simply one</td>\n",
       "      <td>more problem of Steve</td>\n",
       "      <td>of the best choice</td>\n",
       "      <td>-1.445436</td>\n",
       "      <td>2.662699</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>\"Perhaps we can arrange a meet</td>\n",
       "      <td>-and-greet.&lt;br /&gt;&lt;br /&gt;Teleg</td>\n",
       "      <td>with spent, classic music and dance, and come...</td>\n",
       "      <td>0.258479</td>\n",
       "      <td>1.876662</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>Richard Willaims is</td>\n",
       "      <td>nice enough; the little black guy plays quite</td>\n",
       "      <td>beautifully hands on in his own spin, and</td>\n",
       "      <td>0.796508</td>\n",
       "      <td>2.820259</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "                                   query  \\\n",
       "0                      I rented Zero Day   \n",
       "1                               The only   \n",
       "2                        I've read a few   \n",
       "3   This is the second British Rank film   \n",
       "4                              A classic   \n",
       "5              This has to be one of the   \n",
       "6             Happy Go Lovely is a waste   \n",
       "7                            Wow, I just   \n",
       "8     This movie makes several mistakes.   \n",
       "9                       Branagh and Fish   \n",
       "10       I might have given this movie a   \n",
       "11                    Really, really bad   \n",
       "12  What another reviewer called lack of   \n",
       "13                    This is simply one   \n",
       "14        \"Perhaps we can arrange a meet   \n",
       "15                   Richard Willaims is   \n",
       "\n",
       "                                    response (before)  \\\n",
       "0    4 for my sister. To my surprise, the Wii caug...   \n",
       "1                                       distro of her   \n",
       "2    news reports about Mr. Mueller's activities b...   \n",
       "3         , and I wouldn't be surprised anymore if it   \n",
       "4    classic.<br /><br />And only this one will ha...   \n",
       "5       worst with the differences being that for the   \n",
       "6                            . Not only are extremely   \n",
       "7                                can't make fun of it   \n",
       "8    Despite being a great comedic diversion it es...   \n",
       "9                              burne, Drake is played   \n",
       "10   rating of *11 when I heard that!), but it was...   \n",
       "11              with feel like there is no end to the   \n",
       "12   judgment, connecting into her own harsh obser...   \n",
       "13                              more problem of Steve   \n",
       "14                       -and-greet.<br /><br />Teleg   \n",
       "15      nice enough; the little black guy plays quite   \n",
       "\n",
       "                                     response (after)  rewards (before)  \\\n",
       "0   . It is a pleasure. It is a huge leap 68 years...          1.736068   \n",
       "1                          special compliments is the          0.150852   \n",
       "2    novels and I never watch this. It has a reall...         -1.417962   \n",
       "3       that I have enjoyed, achieving it in both the          0.835876   \n",
       "4   . It's a movie with a fine cast. As the beginn...          2.113075   \n",
       "5             best thriller films I've seen in recent         -2.705339   \n",
       "6                                   of time, giving a         -2.429504   \n",
       "7                                  feek it! This show         -2.201666   \n",
       "8   It's cool, wonderful - it held me into a very ...         -1.232380   \n",
       "9                          is a great show. Beautiful          0.776819   \n",
       "10   great performance. It was truly a great movie...          0.276380   \n",
       "11          . This movie is incredibly good, with the         -2.639503   \n",
       "12   suspense. Rogers and Rooney rate this as exce...         -1.079707   \n",
       "13                                 of the best choice         -1.445436   \n",
       "14   with spent, classic music and dance, and come...          0.258479   \n",
       "15          beautifully hands on in his own spin, and          0.796508   \n",
       "\n",
       "    rewards (after)  \n",
       "0          2.423731  \n",
       "1          0.190159  \n",
       "2          2.831814  \n",
       "3          2.205628  \n",
       "4          2.739168  \n",
       "5          2.730615  \n",
       "6         -2.934672  \n",
       "7         -0.106085  \n",
       "8          2.707638  \n",
       "9          2.808996  \n",
       "10         2.743328  \n",
       "11        -1.568827  \n",
       "12         2.696888  \n",
       "13         2.662699  \n",
       "14         1.876662  \n",
       "15         2.820259  "
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#### get a batch from the dataset\n",
    "bs = 16\n",
    "game_data = dict()\n",
    "dataset.set_format(\"pandas\")\n",
    "df_batch = dataset[:].sample(bs)\n",
    "game_data[\"query\"] = df_batch[\"query\"].tolist()\n",
    "query_tensors = df_batch[\"input_ids\"].tolist()\n",
    "\n",
    "response_tensors_ref, response_tensors = [], []\n",
    "\n",
    "#### get response from gpt2 and gpt2_ref\n",
    "for i in range(bs):\n",
    "    query = torch.tensor(query_tensors[i]).to(device)\n",
    "\n",
    "    gen_len = output_length_sampler()\n",
    "    query_response = ref_model.generate(\n",
    "        query.unsqueeze(0), max_new_tokens=gen_len, **gen_kwargs\n",
    "    ).squeeze()\n",
    "    response_len = len(query_response) - len(query)\n",
    "    response_tensors_ref.append(query_response[-response_len:])\n",
    "\n",
    "    query_response = model.generate(\n",
    "        query.unsqueeze(0), max_new_tokens=gen_len, **gen_kwargs\n",
    "    ).squeeze()\n",
    "    response_len = len(query_response) - len(query)\n",
    "    response_tensors.append(query_response[-response_len:])\n",
    "\n",
    "#### decode responses\n",
    "game_data[\"response (before)\"] = [\n",
    "    tokenizer.decode(response_tensors_ref[i]) for i in range(bs)\n",
    "]\n",
    "game_data[\"response (after)\"] = [\n",
    "    tokenizer.decode(response_tensors[i]) for i in range(bs)\n",
    "]\n",
    "\n",
    "#### sentiment analysis of query/response pairs before/after\n",
    "texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (before)\"])]\n",
    "pipe_outputs = sentiment_pipe(texts, **sent_kwargs)\n",
    "positive_scores = [\n",
    "    item[\"score\"]\n",
    "    for output in pipe_outputs\n",
    "    for item in output\n",
    "    if item[\"label\"] == \"POSITIVE\"\n",
    "]\n",
    "game_data[\"rewards (before)\"] = positive_scores\n",
    "\n",
    "texts = [q + r for q, r in zip(game_data[\"query\"], game_data[\"response (after)\"])]\n",
    "pipe_outputs = sentiment_pipe(texts, **sent_kwargs)\n",
    "positive_scores = [\n",
    "    item[\"score\"]\n",
    "    for output in pipe_outputs\n",
    "    for item in output\n",
    "    if item[\"label\"] == \"POSITIVE\"\n",
    "]\n",
    "game_data[\"rewards (after)\"] = positive_scores\n",
    "\n",
    "# store results in a dataframe\n",
    "df_results = pd.DataFrame(game_data)\n",
    "df_results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Looking at the reward mean/median of the generated sequences we observe a significant difference."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "mean:\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "rewards (before)   -0.512965\n",
       "rewards (after)     1.676750\n",
       "dtype: float64"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "median:\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "rewards (before)   -0.464427\n",
       "rewards (after)     2.679794\n",
       "dtype: float64"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "print(\"mean:\")\n",
    "display(df_results[[\"rewards (before)\", \"rewards (after)\"]].mean())\n",
    "print()\n",
    "print(\"median:\")\n",
    "display(df_results[[\"rewards (before)\", \"rewards (after)\"]].median())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Save model\n",
    "Finally, we save the model and push it to the Hugging Face for later usage."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "('gpt2-imdb-pos-v2/tokenizer_config.json',\n",
       " 'gpt2-imdb-pos-v2/special_tokens_map.json',\n",
       " 'gpt2-imdb-pos-v2/vocab.json',\n",
       " 'gpt2-imdb-pos-v2/merges.txt',\n",
       " 'gpt2-imdb-pos-v2/added_tokens.json',\n",
       " 'gpt2-imdb-pos-v2/tokenizer.json')"
      ]
     },
     "execution_count": null,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)\n",
    "tokenizer.save_pretrained(\"gpt2-imdb-pos-v2\", push_to_hub=True)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "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.11.9"
  },
  "vscode": {
   "interpreter": {
    "hash": "4c8ff454cd947027f86954d72bf940c689a97dcc494eb53cfe4813862c6065fe"
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}