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
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
{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 86,
   "id": "7821c501-8c5d-4af6-81cd-caa6ad0bd58c",
   "metadata": {},
   "outputs": [],
   "source": [
    "from datasets import load_dataset, DatasetDict\n",
    "from datasets import concatenate_datasets\n",
    "from IPython.display import HTML\n",
    "\n",
    "from tqdm import tqdm\n",
    "import re \n",
    "import numpy as np\n",
    "from markdownify import markdownify as md"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 80,
   "id": "dc821970-efdb-407f-bd79-59da09323280",
   "metadata": {
    "scrolled": true,
    "tags": []
   },
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Found cached dataset parquet (/home/leandro/.cache/huggingface/datasets/HuggingFaceH4___parquet/HuggingFaceH4--stack-exchange-preferences-1d2bff9ecb5ffe2a/0.0.0/2a3b91fbd88a2c90d1dbbb32b460cf621d31bd5b05b934492fdef7d8d6f236ec)\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "Dataset({\n",
       "    features: ['qid', 'question', 'answers', 'date', 'metadata'],\n",
       "    num_rows: 10807695\n",
       "})"
      ]
     },
     "execution_count": 80,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds = load_dataset(\"HuggingFaceH4/stack-exchange-preferences\", split=\"train\", num_proc=16)\n",
    "ds"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 81,
   "id": "0d8d8729-6d6b-4791-a24a-cb112c399bd0",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<p>I have been wanting to learn about 3D printing a long time so I really want this site to succeed but I have no previous experience with the subject. </p>\n",
       "\n",
       "<p>I was wondering how can I help the site at this early stage. I thought about asking about how to get started with 3D printing but SE explicitly discourages \"easy\" questions in the private beta.</p>\n",
       "\n",
       "<p>What can newbies like me do for the site at this stage besides voting questions and answers?</p>\n"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "execution_count": 81,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "HTML(ds[0][\"question\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 82,
   "id": "b3b60caa-3bd9-4033-ab1c-90c5b08ef3ec",
   "metadata": {},
   "outputs": [],
   "source": [
    "def lang_callback(el):\n",
    "    lang = el['class'][0] if el.has_attr('class') else None\n",
    "    \n",
    "    if not lang is None:\n",
    "        lang = lang.split(\"-\")[-1]\n",
    "    return lang"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 83,
   "id": "de1123a0-7468-4d13-a8d3-4011ace36c3c",
   "metadata": {},
   "outputs": [],
   "source": [
    "def html2md(text):\n",
    "    text = md(text, code_language_callback=lang_callback)\n",
    "    text = re.sub(r\"\\n\\s*\\n\", \"\\n\\n\", text).strip()\n",
    "    return text.encode('utf-8', 'replace').decode()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 84,
   "id": "c9da64a0-c753-4d35-9369-b70a7a9fa2f9",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "I have been wanting to learn about 3D printing a long time so I really want this site to succeed but I have no previous experience with the subject. \n",
      "\n",
      "I was wondering how can I help the site at this early stage. I thought about asking about how to get started with 3D printing but SE explicitly discourages \"easy\" questions in the private beta.\n",
      "\n",
      "What can newbies like me do for the site at this stage besides voting questions and answers?\n",
      "====================\n"
     ]
    }
   ],
   "source": [
    "for i in range(1):\n",
    "    text = html2md(ds[i][\"question\"])\n",
    "    print(text)\n",
    "    print(\"==\"*10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 85,
   "id": "3bf33a2f-fed5-49e7-8046-e813ad172b17",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "49.935"
      ]
     },
     "execution_count": 85,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "np.mean([len(ds[i][\"answers\"])*(len(ds[i][\"answers\"])-1)/2 for i in range(10000)])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 87,
   "id": "88ea2dd5-b885-4f65-bae3-1319c7816044",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds = ds.shuffle(seed=42)\n",
    "index = list(range(len(ds)))\n",
    "\n",
    "ds_splits = DatasetDict({\n",
    "    \"finetune\": ds.select(index[:3_000_000]),\n",
    "    \"reward\": ds.select(index[3_000_000:6_000_000]),\n",
    "    \"rl\": ds.select(index[6_000_000:9_000_000]),\n",
    "    \"evaluation\": ds.select(index[9_000_000:]),\n",
    "})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 88,
   "id": "1607922d-f585-4de7-be70-2205b5170102",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatasetDict({\n",
       "    finetune: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata'],\n",
       "        num_rows: 3000000\n",
       "    })\n",
       "    reward: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata'],\n",
       "        num_rows: 3000000\n",
       "    })\n",
       "    rl: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata'],\n",
       "        num_rows: 3000000\n",
       "    })\n",
       "    evaluation: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata'],\n",
       "        num_rows: 1807695\n",
       "    })\n",
       "})"
      ]
     },
     "execution_count": 88,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_splits"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 89,
   "id": "edc8af18-94a5-49e9-ae73-ce4ba81d9739",
   "metadata": {},
   "outputs": [],
   "source": [
    "def binary_comparison(answers):\n",
    "    \"\"\"Returns tuples of answers, first always best\"\"\"\n",
    "    pairs = []\n",
    "    \n",
    "    for i in range(len(answers)-1):\n",
    "        for j in range(i+1, len(answers)):\n",
    "            if answers[i][\"pm_score\"]>answers[j][\"pm_score\"]:\n",
    "                pairs.append((answers[i][\"text\"], answers[j][\"text\"]))\n",
    "            elif answers[i][\"pm_score\"]<answers[j][\"pm_score\"]:\n",
    "                pairs.append((answers[j][\"text\"], answers[i][\"text\"]))\n",
    "    return pairs"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 90,
   "id": "88afe90e-364e-4b21-898b-1c6ceb9cfd32",
   "metadata": {},
   "outputs": [],
   "source": [
    "def preprocess(examples):\n",
    "    \"\"\"Cleans HTML and returns paired answers (j is better than k). Note that this returns more examples (one for each pair per question).\"\"\"\n",
    "    \n",
    "    MAX_PAIRS_PER_QUESTION = 10\n",
    "    n_samples = len(examples[\"qid\"])\n",
    "    \n",
    "    # initialize empty lists for new samples\n",
    "    new_examples = {\"question\": [], \"response_j\": [], \"response_k\": []}\n",
    "    for key in examples:\n",
    "        new_examples[key] = []\n",
    "    \n",
    "    for sample_id in range(n_samples):\n",
    "        # get pairs where first is always the better one\n",
    "        pairs = binary_comparison(examples[\"answers\"][sample_id])\n",
    "        n_answers = len(examples[\"answers\"][sample_id])\n",
    "        \n",
    "        # sample if we get more pairs than maximum\n",
    "        if len(pairs) > MAX_PAIRS_PER_QUESTION:\n",
    "            indices = np.random.choice(list(range(len(pairs))), MAX_PAIRS_PER_QUESTION, replace=False)\n",
    "            pairs = [pairs[i] for i in indices]\n",
    "        \n",
    "        # construct the samples\n",
    "        for pair in pairs:\n",
    "            for key in examples:\n",
    "                if key==\"question\":\n",
    "                    new_examples[key].append(html2md(examples[key][sample_id]))\n",
    "                else:\n",
    "                    new_examples[key].append(examples[key][sample_id])\n",
    "            new_examples[\"response_j\"].append(html2md(pair[0]))\n",
    "            new_examples[\"response_k\"].append(html2md(pair[1]))\n",
    "    return new_examples"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 91,
   "id": "ac06aac5-3953-4321-9f1e-6ff210bee82d",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map (num_proc=60):   0%|          | 0/3000000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map (num_proc=60):   0%|          | 0/3000000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map (num_proc=60):   0%|          | 0/3000000 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n",
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n",
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "Map (num_proc=60):   0%|          | 0/1807695 [00:00<?, ? examples/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "/opt/conda/envs/jupyter/lib/python3.8/site-packages/bs4/__init__.py:435: MarkupResemblesLocatorWarning: The input looks more like a filename than markup. You may want to open this file and pass the filehandle into Beautiful Soup.\n",
      "  warnings.warn(\n"
     ]
    }
   ],
   "source": [
    "ds_result = ds_splits.map(preprocess, batch_size=1000, batched=True, num_proc=60)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 92,
   "id": "06e3d891-ffde-4762-95d5-39658a1127ef",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatasetDict({\n",
       "    finetune: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 7440923\n",
       "    })\n",
       "    reward: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 7441998\n",
       "    })\n",
       "    rl: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 7435908\n",
       "    })\n",
       "    evaluation: Dataset({\n",
       "        features: ['qid', 'question', 'answers', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 4483004\n",
       "    })\n",
       "})"
      ]
     },
     "execution_count": 92,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 93,
   "id": "631416dc-cf19-485d-a2f3-94c9b2cb2bfc",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'qid': 12891264,\n",
       " 'question': \"I am using jQuery fileupload plugin and I want to do some custom jQuery stuff once fileupload is done\\n\\nfrom here <https://github.com/blueimp/jQuery-File-Upload/wiki/Options>\\n\\nNow it says this\\n\\n```\\nCallback for successful upload requests.\\n$('#fileupload')\\n       .bind('fileuploaddone', function (e, data) {/* ... */})\\n\\n```\\n\\nNow I have defined this custom function for testing in my own js file\\n\\n```\\n$('#fileupload').bind('fileuploaddone', function (e, data) {/* ... */\\nalert('Hello');\\n})\\n\\n```\\n\\nBut it's not working.\\n\\nBut if I edit the main file in here\\n\\n```\\n  // Callback for successful uploads:\\n            done: function (e, data) {\\n\\n```\\n\\nThen it works.\",\n",
       " 'answers': [{'answer_id': 12891484,\n",
       "   'author': 'Reflective',\n",
       "   'author_id': 1686626,\n",
       "   'author_profile': 'https://Stackoverflow.com/users/1686626',\n",
       "   'pm_score': 4,\n",
       "   'selected': True,\n",
       "   'text': \"<p>Looking at the library code, seems all events are renamed removing 'fileupload' ... so 'fileuploaddone' becomes just 'done'. It is valid for all other callbacks.\\nlook at this section:</p>\\n\\n<pre><code>    // Other callbacks:\\n    // Callback for the submit event of each file upload:\\n    // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);\\n    // Callback for the start of each file upload request:\\n    // send: function (e, data) {}, // .bind('fileuploadsend', func);\\n    // Callback for successful uploads:\\n    // done: function (e, data) {}, // .bind('fileuploaddone', func);\\n    // Callback for failed (abort or error) uploads:\\n    // fail: function (e, data) {}, // .bind('fileuploadfail', func);\\n    // Callback for completed (success, abort or error) requests:\\n    // always: function (e, data) {}, // .bind('fileuploadalways', func);\\n    // Callback for upload progress events:\\n    // progress: function (e, data) {}, // .bind('fileuploadprogress', func);\\n    // Callback for global upload progress events:\\n    // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);\\n    // Callback for uploads start, equivalent to the global ajaxStart event:\\n    // start: function (e) {}, // .bind('fileuploadstart', func);\\n    // Callback for uploads stop, equivalent to the global ajaxStop event:\\n    // stop: function (e) {}, // .bind('fileuploadstop', func);\\n    // Callback for change events of the fileInput(s):\\n    // change: function (e, data) {}, // .bind('fileuploadchange', func);\\n    // Callback for paste events to the pasteZone(s):\\n    // paste: function (e, data) {}, // .bind('fileuploadpaste', func);\\n    // Callback for drop events of the dropZone(s):\\n    // drop: function (e, data) {}, // .bind('fileuploaddrop', func);\\n    // Callback for dragover events of the dropZone(s):\\n    // dragover: function (e) {}, // .bind('fileuploaddragover', func);\\n</code></pre>\\n\\n<p>If you have some doubts about what's happening, just look at the code inside. This library is not compressed so it is easy to see. for example</p>\\n\\n<pre><code>// start: function (e) {}, // .bind('fileuploadstart', func);\\n</code></pre>\\n\\n<p><code>start</code> callback is implemented. <code>fileuploadstart</code> is not.</p>\\n\"},\n",
       "  {'answer_id': 15419140,\n",
       "   'author': 'NXT',\n",
       "   'author_id': 1554649,\n",
       "   'author_profile': 'https://Stackoverflow.com/users/1554649',\n",
       "   'pm_score': 3,\n",
       "   'selected': False,\n",
       "   'text': '<p>Check if the server-side uploading script returns a JSON reply - in my case it didn\\'t work when the reply was empty, but file was uploaded successfully.</p>\\n\\n<p>So, below is working for me with jQuery 1.9.1 and the newest version of the \"jQuery File Upload Plugin\" - 5.21.3</p>\\n\\n<pre><code>$(\"#fileupload\").bind(\"fileuploaddone\", function (e, data) {\\n    console.log(\"fileuploaddone event fired\");\\n});\\n</code></pre>\\n'}],\n",
       " 'date': '2012/10/15',\n",
       " 'metadata': ['https://Stackoverflow.com/questions/12891264',\n",
       "  'https://Stackoverflow.com',\n",
       "  'https://Stackoverflow.com/users/767244/'],\n",
       " 'response_j': \"Looking at the library code, seems all events are renamed removing 'fileupload' ... so 'fileuploaddone' becomes just 'done'. It is valid for all other callbacks.\\nlook at this section:\\n\\n```\\n    // Other callbacks:\\n    // Callback for the submit event of each file upload:\\n    // submit: function (e, data) {}, // .bind('fileuploadsubmit', func);\\n    // Callback for the start of each file upload request:\\n    // send: function (e, data) {}, // .bind('fileuploadsend', func);\\n    // Callback for successful uploads:\\n    // done: function (e, data) {}, // .bind('fileuploaddone', func);\\n    // Callback for failed (abort or error) uploads:\\n    // fail: function (e, data) {}, // .bind('fileuploadfail', func);\\n    // Callback for completed (success, abort or error) requests:\\n    // always: function (e, data) {}, // .bind('fileuploadalways', func);\\n    // Callback for upload progress events:\\n    // progress: function (e, data) {}, // .bind('fileuploadprogress', func);\\n    // Callback for global upload progress events:\\n    // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func);\\n    // Callback for uploads start, equivalent to the global ajaxStart event:\\n    // start: function (e) {}, // .bind('fileuploadstart', func);\\n    // Callback for uploads stop, equivalent to the global ajaxStop event:\\n    // stop: function (e) {}, // .bind('fileuploadstop', func);\\n    // Callback for change events of the fileInput(s):\\n    // change: function (e, data) {}, // .bind('fileuploadchange', func);\\n    // Callback for paste events to the pasteZone(s):\\n    // paste: function (e, data) {}, // .bind('fileuploadpaste', func);\\n    // Callback for drop events of the dropZone(s):\\n    // drop: function (e, data) {}, // .bind('fileuploaddrop', func);\\n    // Callback for dragover events of the dropZone(s):\\n    // dragover: function (e) {}, // .bind('fileuploaddragover', func);\\n\\n```\\n\\nIf you have some doubts about what's happening, just look at the code inside. This library is not compressed so it is easy to see. for example\\n\\n```\\n// start: function (e) {}, // .bind('fileuploadstart', func);\\n\\n```\\n\\n`start` callback is implemented. `fileuploadstart` is not.\",\n",
       " 'response_k': 'Check if the server-side uploading script returns a JSON reply - in my case it didn\\'t work when the reply was empty, but file was uploaded successfully.\\n\\nSo, below is working for me with jQuery 1.9.1 and the newest version of the \"jQuery File Upload Plugin\" - 5.21.3\\n\\n```\\n$(\"#fileupload\").bind(\"fileuploaddone\", function (e, data) {\\n    console.log(\"fileuploaddone event fired\");\\n});\\n\\n```'}"
      ]
     },
     "execution_count": 93,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result[\"finetune\"][0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 94,
   "id": "2c96653b-7a5a-4cae-a327-b6aa77aa5850",
   "metadata": {},
   "outputs": [],
   "source": [
    "ds_result = ds_result.remove_columns([\"answers\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 95,
   "id": "15c2e5ee-7c7d-4e98-9e63-e5d37a9354aa",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "DatasetDict({\n",
       "    finetune: Dataset({\n",
       "        features: ['qid', 'question', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 7440923\n",
       "    })\n",
       "    reward: Dataset({\n",
       "        features: ['qid', 'question', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 7441998\n",
       "    })\n",
       "    rl: Dataset({\n",
       "        features: ['qid', 'question', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 7435908\n",
       "    })\n",
       "    evaluation: Dataset({\n",
       "        features: ['qid', 'question', 'date', 'metadata', 'response_j', 'response_k'],\n",
       "        num_rows: 4483004\n",
       "    })\n",
       "})"
      ]
     },
     "execution_count": 95,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "ds_result"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 96,
   "id": "4d42b35c-5252-4b49-ba4b-20818bc9e086",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "finetune\n",
      "reward\n",
      "rl\n",
      "evaluation\n"
     ]
    }
   ],
   "source": [
    "for key in ds_result:\n",
    "    print(key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 100,
   "id": "e32c11d7-a88e-4d92-9dfc-92b2a67c5455",
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "import time\n",
    "from multiprocessing import Pool\n",
    "from tqdm import tqdm\n",
    "\n",
    "from huggingface_hub import Repository\n",
    "\n",
    "\n",
    "def save_shard(shard_tuple):\n",
    "    \"\"\"Save shard\"\"\"\n",
    "    filename, shard = shard_tuple\n",
    "    # use to_json instead to save as json file\n",
    "    shard.to_parquet(filename)\n",
    "\n",
    "\n",
    "def save_manual_shards(ds, user=\"lvwerra\", remote_dataset_repo=\"stack-exchange-paired\", subfolder=\"train\"):\n",
    "    \"\"\"Save sharded data\n",
    "    Args:\n",
    "        ds (Dataset): dataset to be saved\n",
    "        user (str): user name\n",
    "        remote_dataset_repo (str): remote dataset repository\n",
    "        out_path (str): path to save the shards\"\"\"\n",
    "    # this will create a folder OUT_PATH that is a clone of REMOTE_DATASET_REPO\n",
    "    # you can save the shards inside it and do git add/commit/push to push data to the hub\n",
    "    out_path = remote_dataset_repo\n",
    "    # if out path doesnt already exist\n",
    "    if not os.path.exists(out_path):\n",
    "        repo = Repository(\n",
    "            local_dir=out_path,\n",
    "            clone_from=user + \"/\" + remote_dataset_repo,\n",
    "            repo_type=\"dataset\",\n",
    "            private=False,\n",
    "            use_auth_token=True,\n",
    "            git_user=user,\n",
    "        )\n",
    "\n",
    "    # files will be numerous we save them in a folder called data inside out_path\n",
    "    if not os.path.exists(out_path):\n",
    "        os.mkdir(out_path + \"/data\")\n",
    "    os.mkdir(out_path + f\"/data/{subfolder}\")\n",
    "    \n",
    "    SHARD_SIZE = 1000 << 20\n",
    "    if ds._indices is not None:\n",
    "        dataset_nbytes = ds.data.nbytes * len(ds._indices) / len(ds.data)\n",
    "    else:\n",
    "        dataset_nbytes = ds.data.nbytes\n",
    "    num_shards = int(dataset_nbytes / SHARD_SIZE) + 1\n",
    "    print(f\"Number of shards: {num_shards}\")\n",
    "\n",
    "    print(\"sharding the dataset\")\n",
    "    t_start = time.time()\n",
    "    shards = (\n",
    "        ds.shard(num_shards=num_shards, index=i, contiguous=True)\n",
    "        for i in range(num_shards)\n",
    "    )\n",
    "    # use f\"{OUT_PATH}/data/train-{index:05d}-of-{num_shards:05d}.json\" instead for json files\n",
    "    filenames = (\n",
    "        f\"{out_path}/data/{subfolder}/train-{index:05d}-of-{num_shards:05d}.parquet\"\n",
    "        for index in range(num_shards)\n",
    "    )\n",
    "\n",
    "    with Pool(16) as p:\n",
    "        list(\n",
    "            tqdm(\n",
    "                p.imap_unordered(save_shard, zip(filenames, shards), chunksize=4),\n",
    "                total=num_shards,\n",
    "            )\n",
    "        )\n",
    "    print(f\"Time to save dataset: {time.time()-t_start:.2f}\")\n",
    "    # to push dataset to hub do: git add/commit/push inside OUT_PATH"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 101,
   "id": "a90664eb-5c54-4fae-9a8a-d509bb2abdfe",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Number of shards: 20\n",
      "sharding the dataset\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 20/20 [00:28<00:00,  1.43s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time to save dataset: 29.15\n",
      "Number of shards: 20\n",
      "sharding the dataset\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 20/20 [00:22<00:00,  1.15s/it]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time to save dataset: 23.42\n",
      "Number of shards: 20\n",
      "sharding the dataset\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 20/20 [00:10<00:00,  1.83it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time to save dataset: 11.36\n",
      "Number of shards: 12\n",
      "sharding the dataset\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|β–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆβ–ˆ| 12/12 [00:10<00:00,  1.12it/s]\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Time to save dataset: 11.13\n"
     ]
    }
   ],
   "source": [
    "for key in ds_result:\n",
    "    save_manual_shards(ds_result[key], subfolder=key)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "d62f5a7f-2a23-4e0d-9e49-b29f88ea8c13",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "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.8.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}