File size: 46,373 Bytes
7934b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
{
    "cells": [
        {
            "cell_type": "markdown",
            "id": "c3217a15",
            "metadata": {},
            "source": [
                "# Synthetic Tabular Data Generation by NeMo GPT\n",
                "\n",
                "Big data, new algorithms and fast computers are the 3 main factors that make the modern AI revolution possible. Data poses a big challenge for enterprises for various reasons: difficulty  of data labeling, strong data governance, limited data availability etc. Synthetic data generation is proposed as a solution to the data problem as it directly addresses the data challenges. Two popular generative models like  Variational Auto-Encoder [VAE](https://en.wikipedia.org/wiki/Variational_autoencoder) and Generative Adversarial Network [GAN](https://en.wikipedia.org/wiki/Generative_adversarial_network) models have achieved some success in the past. However, a good generative model should generate the data following the same distribution as the training data. There are some known flaws with the VAE and GAN models for synthetic data generation. Most prominently, the [mode collapse problem](https://developers.google.com/machine-learning/gan/problems) in the GAN model causes the generated data to miss some modes in the training data distribution. While the VAE has the difficulty of generating sharp data points due to the non-autoregressive loss.\n",
                "\n",
                "Recently, [Transformer models](https://arxiv.org/abs/1706.03762) achieved huge success in the natural language processing domain.  The self-attention encoding and decoding architecture of the transformer model is proven to be accurate in modeling the data distribution and scalable to large datasets. [OpenAI’s GPT3](https://openai.com/blog/gpt-3-apps/) uses the decoder part of the transformer model and has 175B parameters. It has been widely used across varying categories and industries, from productivity and education to creativity and games. GPT3 turns out to be a superior generative model. In this tutorial, we are interested in exploring the ideas of applying the GPT model for synthetic data generation. \n",
                "\n",
                "Unlike typical neural networks, GPT models are usually large in size. It is challenging to fit a large GPT model into a single GPU. Luckily, [NeMo](https://github.com/NVIDIA/NeMo) is an open source tool that is capable of efficiently training very large (hundreds of billions of parameters) language models with both model and data parallelism.  It is easy to use too. In the following sections, we will show how to train a GPT model step by step to generate synthetic credit card data.\n"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "8c72dc42",
            "metadata": {},
            "source": [
                "### Get the Credit Card Transaction Data \n",
                "\n",
                "The synthetic credit card transaction dataset is provided at [IBM TabFormer Github repo](https://github.com/IBM/TabFormer). Go ahead to download it at this [direct link](https://ibm.box.com/v/tabformer-data). Put the downloaded and decompressed `card_transaction.v1.csv` file at the same directory as this this notebook."
            ]
        },
        {
            "cell_type": "markdown",
            "id": "79154a9e",
            "metadata": {},
            "source": [
                "### Data Cleaning and Formatting\n",
                "\n",
                "First let's import the necessary Python libraries for the tutorial."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "c4a08689",
            "metadata": {},
            "outputs": [],
            "source": [
                "import pandas as pd\n",
                "from nemo.collections.common.tokenizers.column_coder import ColumnCodes\n",
                "from omegaconf import OmegaConf\n",
                "import pickle\n",
                "from pandas.api.types import is_string_dtype\n",
                "from nemo.collections.common.tokenizers.tabular_tokenizer import TabularTokenizer\n",
                "import json\n",
                "import wget\n",
                "import requests\n",
                "import json\n",
                "import functools\n",
                "from multiprocessing import Pool"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "abaa1f80",
            "metadata": {},
            "outputs": [],
            "source": [
                "BRANCH = 'r1.17.0'\n",
                "DATA_PATH='.'\n",
                "TRANSACTIONS=DATA_PATH+'/card_transaction.v1.csv'\n",
                "#CHECKPOINTS='/chk_points'\n",
                "CHECKPOINTS=DATA_PATH+'/checkpoints'\n",
                "CC_OUTPUT_P=DATA_PATH+'/credit_card_coder.pickle'\n",
                "CC_OUTPUT_J=DATA_PATH+'/credit_card.jn'\n",
                "print (TRANSACTIONS, CHECKPOINTS, CC_OUTPUT_P, CC_OUTPUT_J)"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "7e0bbc89",
            "metadata": {},
            "source": [
                "After decompressing the tar file,  we load the dataset into pandas dataframe and examine the top few rows."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "8aa48317",
            "metadata": {},
            "outputs": [],
            "source": [
                "df = pd.read_csv(TRANSACTIONS)\n",
                "df.head()"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "1ff1d46f",
            "metadata": {},
            "source": [
                "In the following data cleaning step, we fix the `Amount` column that is not a number, convert the `Time` column into `hour` and `minutes` and replace the `,` character with space so we can use `,` as delimiter."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "33980221",
            "metadata": {},
            "outputs": [],
            "source": [
                "# remove the dollar string and convert amount to float\n",
                "df['Amount'] = df['Amount'].str.replace('$', '').astype('float')\n",
                "# fix the zip column\n",
                "df['Zip'] = pd.array([None if pd.isna(x) else int(x) for x in df['Zip']])\n",
                "\n",
                "# parse the time into minute and second\n",
                "df['Hour'] = df['Time'].str[0:2]\n",
                "df['Minute'] = df['Time'].str[-2:]\n",
                "# remove the 'Time' Column once it is parsed\n",
                "del df['Time']\n",
                "# all the columns used for later processing \n",
                "all_columns = ['User', 'Year', 'Month', 'Day', 'Hour', 'Minute', 'Card', 'Amount', 'Use Chip',\n",
                "           'Merchant Name', 'Merchant City', 'Merchant State', 'Zip', 'MCC',\n",
                "           'Errors?', 'Is Fraud?']\n",
                "# these are the columns used to train the model\n",
                "columns = ['Year', 'Month', 'Day', 'Hour', 'Minute', 'Card', 'Amount', 'Use Chip',\n",
                "           'Merchant Name', 'Merchant City', 'Merchant State', 'Zip', 'MCC',\n",
                "           'Errors?', 'Is Fraud?']\n",
                "\n",
                "float_columns = ['Amount']\n",
                "category_columns = ['Year', 'Month', 'Day', 'Hour', 'Minute', 'Card', 'Use Chip',\n",
                "                    'Merchant Name', 'Merchant City', 'Merchant State', 'MCC',\n",
                "                    'Errors?', 'Is Fraud?']\n",
                "integer_columns = ['Zip']\n",
                "\n",
                "for col in category_columns:\n",
                "    if is_string_dtype(df[col].dtype):\n",
                "        df[col] = df[col].str.replace(',', ' ')\n",
                "\n",
                "# after preprocessing\n",
                "df = df[all_columns]\n",
                "df.head()"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "aa356012",
            "metadata": {},
            "source": [
                "There are 24M records with 12 fields. We need to convert the structured tabular data into a format that NeMo GPT can consume. The NeMo GPT uses training data in a loose json format, with one json containing a text sample per line. For example:\n",
                "```json\n",
                "{\"text\": \"The quick brown fox\"}\n",
                "{\"text\": \"jumps over the lazy dog\"}\n",
                "```\n",
                "We can concat each fields of the transactions together like:\n",
                "```json\n",
                "{\"text\": \"0,0,2002,9,1,06:21,$134.09,Swipe Transaction,3527213246127876953,La Verne,CA,91750.0,5300,NaN,No\\n0,0,2002,9,1,06:42,$38.48,Swipe,Transaction,-727612092139916043,Monterey Park,CA,91754.0,5411,NaN,No...\"}\n",
                "...\n",
                "```\n",
                "In this way, the tabular data is converted into NLP text corpus. \n",
                "\n",
                "### NeMo GPT Workflow\n",
                "```\n",
                "                       +-----------+\n",
                "      +--------------->|Tokenizer  |\n",
                "      |                +-----+-----+\n",
                "      |                      |\n",
                "+-----+-----+          +-----v--------+      +---------+\n",
                "|  Raw Data +--------->| Preprocess   +----->|Pretrain |\n",
                "|           |          |              |      +-----+---+\n",
                "+-----------+          +--------------+            |\n",
                "                                                   |\n",
                "                                           +-------v----------+\n",
                "                                           |  Inference       |\n",
                "                                           | (Text Generation)|\n",
                "                                           +------------------+\n",
                "```\n",
                "As shown in the figure above, it illustrates the steps we are going to take in this tutorial. Having the raw text data ready, we first train a tokenizer to efficiently tokenize the text.  As NeMo only cares about sequences of tokens, a preprocess step is used to convert the raw text data into sequences of token index. It results in one binary file and an index file so data loading in the training step is more efficient.  The next step is the most time consuming pre-training step in which sequences of tokens are fed into the NeMo GPT to predict the next tokens. The prediction error is used as the loss to train the GPT weights. After training the GPT model, it can be put into an inference mode to generate synthetic data following the same distribution as the training dataset. \n",
                "\n",
                "### Tokenizer training\n",
                "It is natural to select the generic GPT BPE tokenizer to convert the text into tokens. However, there are a few problems of using this approach. When GPT BPE tokenizer splits the text into tokens, the number of tokens are usually not fixed for the same column at different rows, because the number is determined by the occurrence frequencies of the individual sub-tokens. This means the structure information is lost if we use the NLP tokenizer. Another problem with the NLP tokenizer is the long string consists of a large number of tokens, which is wasteful considering the NeMo GPT has limited capacity of modeling the sequences of tokens. For example the \"Merchant Name\" \"3527213246127876953\" need at least 7 tokens to code it ([35][27][213][246][127][876][953]). \n",
                "\n",
                "As shown in the [TabFormer paper](https://arxiv.org/abs/2011.01843), a good solution is to build a specialized tokenizer for the tabular data that considers the table structural information. The TabFormer uses a single token for each of the columns which can cause either accuracy loss if the number of tokens is small for the column, or weak generalization if the number of tokens is too large. We improve it by using multiple tokens to code the columns. For example, the floating number \"134.09\" can be tokenized into multiple integers.\n",
                "\n",
                "The following code trains a special encoder/decoder used in the tokenizer. It uses `float` for the `Amount` column, `int` for the `zip` column and `category` for the rest of the columns. The trained encoder and decoder are saved into a file that can be loaded later. We choose to use 3 tokens to encode the floating and int numbers in this example."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "16298d39",
            "metadata": {},
            "outputs": [],
            "source": [
                "\n",
                "tab_structure = []\n",
                "for c in columns:\n",
                "    if c in float_columns:\n",
                "        item = {\n",
                "            \"name\": c,\n",
                "            \"code_type\": \"float\",\n",
                "            \"args\": {\n",
                "                \"code_len\": 3,  # number of tokens used to code the column\n",
                "                \"base\": 32,   # the positional base number. ie. it uses 32 tokens for one digit\n",
                "                \"fillall\": True, # whether to use full base number for each token or derive it from the data.\n",
                "                \"hasnan\": False, # can it handles nan or not\n",
                "                \"transform\": \"yeo-johnson\" # can be ['yeo-johnson', 'quantile', 'robust'], check https://scikit-learn.org/stable/modules/classes.html#module-sklearn.preprocessing \n",
                "            }\n",
                "        }\n",
                "    elif c in integer_columns:\n",
                "        item = {\n",
                "            \"name\": c,\n",
                "            \"code_type\": \"int\",\n",
                "            \"args\": {\n",
                "                \"code_len\": 3,  # number of tokens used to code the column\n",
                "                \"base\": 47,   # the positional base number. ie. it uses 32 tokens for one digit\n",
                "                \"fillall\": True, # whether to use full base number for each token or derive it from the data.\n",
                "                \"hasnan\": True, # can it handles nan or not\n",
                "            }\n",
                "        }\n",
                "    else:\n",
                "        item = {\n",
                "            \"name\": c,\n",
                "            \"code_type\": \"category\",\n",
                "        }\n",
                "    tab_structure.append(item)\n",
                "print(OmegaConf.to_yaml(tab_structure))\n",
                "print(columns)\n",
                "\n",
                "example_arrays = {}\n",
                "for col in tab_structure:\n",
                "    col_name = col['name']\n",
                "    if col_name in category_columns:\n",
                "        example_arrays[col_name] = [i.strip() for i in df[col_name].astype(str).unique()]\n",
                "    else:\n",
                "        example_arrays[col_name] = df[col_name].dropna().unique()\n",
                "cc = ColumnCodes.get_column_codes(tab_structure, example_arrays)\n",
                "print('each row uses', sum(cc.sizes)+ 1, 'tokens')\n",
                "with open(CC_OUTPUT_P, 'wb') as handle:\n",
                "    pickle.dump(cc, handle)\n"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "02bff63f",
            "metadata": {},
            "source": [
                "Let's give it a try to play with encoder and decoder for \"Amount\" and \"Merchant City\" columns"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "ca2f95ba",
            "metadata": {},
            "outputs": [],
            "source": [
                "float_str = '134.09'\n",
                "token_ids = cc.encode('Amount', float_str)\n",
                "print('token ids for {} is {}'.format(float_str, token_ids))\n",
                "amt_str = cc.decode('Amount', token_ids)\n",
                "print('recovered Amt for {} is {}'.format(float_str, amt_str))\n",
                "\n",
                "city_str = 'Monterey Park'\n",
                "token_ids = cc.encode('Merchant City', city_str)\n",
                "print('token ids for {} is {}'.format(city_str, token_ids))\n",
                "amt_str = cc.decode('Merchant City', token_ids)\n",
                "print('recovered City for {} is {}'.format(city_str, amt_str))"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "89e1e5b3",
            "metadata": {},
            "source": [
                "Using 3 tokens for the float column `Amount`, this is a tiny loss of accuracy. If better accuracy is needed, more tokens can be used to train the tokenizer. For the categorical column \"Merchant City\", the string \"Monterey Park\" only needs one token to encode it. Once we have the encoder and decoder ready, the tokenizer is easy to implement. We can consider the tabular data structure information to encode each of the columns. The decoding simply counts the number of tokens to infer the tabular structure since the number of the tokens are fixed for each of the columns.\n",
                "\n",
                "There is one more thing that we need to take special care of before generating the loose json file for NeMo. `<|endoftext|>` is a special token that NeMo recognizes to indicate the beginning and end of the document. The attention mask will stop at the boundary of `<|endoftext|>` token so no attention can be applied across it. To model the temporal information in the time series, we want to make sure the `<|endoftext|>` is added between the continuous sections. For example, in this credit card dataset, there are 2000 users. Each user's transactions are one long time series sequence. The `<|endoftext|>` is added at the end of the long sequences. In this way, NeMo applies attention to learn the temporal correlation in the transactions for the user but not across users. \n",
                "\n",
                "We have provided the Python code to convert the CSV file into the loose json format."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "5e9b5727",
            "metadata": {},
            "outputs": [],
            "source": [
                "delimiter = ','\n",
                "eod_str = '<|endoftext|>'\n",
                "int_nan = '<NA>'\n",
                "\n",
                "\n",
                "def get_docs_from_df(one_group):\n",
                "    user_df = one_group[1]\n",
                "    total = []\n",
                "    # sort the rows by time, so the model can learn temporal info\n",
                "    sub_df = user_df.sort_values(['Year', 'Month', 'Day', 'Hour', 'Minute'])[columns]\n",
                "    start_rows = range(0, doc_augements)\n",
                "    full_msgs = []\n",
                "    for start in start_rows:\n",
                "        full_msgs = []\n",
                "        doc_df = sub_df.iloc[start:]\n",
                "        count = 0\n",
                "        df_size = len(doc_df)       \n",
                "        for row in doc_df.iterrows():\n",
                "            count += 1\n",
                "            items = row[1].values\n",
                "            str_items = [str(items[i]).replace(int_nan, 'nan') for i in range(len(items))]\n",
                "            if count == df_size:\n",
                "                # append eod at the end of the doc\n",
                "                full_msgs.append(delimiter.join(str_items)+eod_str)\n",
                "            else:\n",
                "                full_msgs.append(delimiter.join(str_items))\n",
                "        # use end of line to seperate rows\n",
                "        text = '\\n'.join(full_msgs)\n",
                "        text_doc = {'text': text}\n",
                "        doc = json.dumps(text_doc)+'\\n'\n",
                "        total.append(doc)\n",
                "    return total\n",
                "\n",
                "\n",
                "def gen_one_doc(user_group, n_cores):\n",
                "    udfs = list(user_group)\n",
                "    pool = Pool(n_cores)\n",
                "    docs = pool.map(get_docs_from_df, udfs)\n",
                "    pool.close()\n",
                "    pool.join()\n",
                "    return functools.reduce(lambda a, b: a + b, docs)\n",
                "\n",
                "# number of document augmentation\n",
                "doc_augements = 2\n",
                "\n",
                "user_group = df.groupby('User')\n",
                "\n",
                "with open(CC_OUTPUT_J, 'w') as f:\n",
                "    docs = gen_one_doc(user_group, 30)\n",
                "    for doc in docs:\n",
                "        f.write(doc)"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "05ebadc3",
            "metadata": {},
            "source": [
                "After running the above cell, it converts the CSV file to the loose json format that the NeMo Megatron can use. It generates one document for each user. Each document ends with the `<|endoftext|>` token. We augment the data by shifting it by one transaction so the relative position of the input credit card transaction data is slightly different. "
            ]
        },
        {
            "cell_type": "markdown",
            "id": "2fe38a29",
            "metadata": {},
            "source": [
                "Having the loose JSON file ready, we can test the customized Tabular Tokenizer."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "1d9d065e",
            "metadata": {},
            "outputs": [],
            "source": [
                "tokenizer = TabularTokenizer(CC_OUTPUT_P, delimiter=',')\n",
                "\n",
                "with open(CC_OUTPUT_J, 'r') as f:\n",
                "    for line in f:\n",
                "        break\n",
                "\n",
                "text = json.loads(line)['text']\n",
                "r = tokenizer.text_to_tokens(text)\n",
                "ids = tokenizer.tokens_to_ids(r)\n",
                "tex = tokenizer.ids_to_tokens(ids)\n",
                "decoded_text = tokenizer.ids_to_text(ids)\n",
                "show_num_lines = 5\n",
                "print('raw input text\\n', '\\n'.join(text.split('\\n')[:show_num_lines]))\n",
                "print('tokens\\n', r[:show_num_lines*len(tokenizer.code_column.columns)])\n",
                "print('token ids\\n', ids[:show_num_lines*(sum(tokenizer.code_column.sizes)+1)])\n",
                "print('decoded tokens\\n', tex[:show_num_lines*(sum(tokenizer.code_column.sizes)+1)])\n",
                "print('decoded text\\n', '\\n'.join(decoded_text.split('\\n')[:show_num_lines]))"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "678f65ef",
            "metadata": {},
            "source": [
                "The TabularTokenizer understands the Table structure so it can convert back and forth between the tabular data text and the token ids.\n",
                "\n",
                "\n",
                "### Model configuration\n",
                "\n",
                "\n",
                "We define the following constants to configure the GPT model "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "97571acc",
            "metadata": {},
            "outputs": [],
            "source": [
                "NUM_LAYERS = 4\n",
                "NUM_GPUS = 1\n",
                "HIDDEN_SIZE = 1024\n",
                "NUM_ATTENTION_HEADS = 16\n",
                "SEQ_LENGTH = 1024\n",
                "TENSOR_MP_SIZE = 1\n",
                "PIPELINE_MP_SIZE = 1"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "8af66b4a",
            "metadata": {},
            "source": [
                "### Preprocess\n",
                "\n",
                "The loose json above is processed into a binary format for training. To convert the json into mmap, cached index file, we use the `preprocess_data_for_megatron.py` script to prepare the data.\n",
                "\n",
                "\n",
                "Download the python file and run the preprocess. Note we use `30` CPU workers for the preprocessing step. Please adjust it according to your compute environment."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "fccee06c",
            "metadata": {
                "scrolled": true
            },
            "outputs": [],
            "source": [
                "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/scripts/nlp_language_modeling/preprocess_data_for_megatron.py')"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "79de4531",
            "metadata": {},
            "outputs": [],
            "source": [
                "!python preprocess_data_for_megatron.py \\\n",
                "    --input={CC_OUTPUT_J} \\\n",
                "    --json-keys=text \\\n",
                "    --tokenizer-library=tabular \\\n",
                "    --vocab-file={CC_OUTPUT_P} \\\n",
                "    --tokenizer-type=Tabular \\\n",
                "    --output-prefix=tabular_data \\\n",
                "    --delimiter=, \\\n",
                "    --workers=30\n"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "4998ebcb",
            "metadata": {},
            "outputs": [],
            "source": [
                "!ls $DATA_PATH/tabular*.*"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "6ecec681",
            "metadata": {},
            "source": [
                "After running the script, two new files are generated in the current directory: `tabular_data_text_document.bin` and `tabular_data_text_document.idx`. The `bin` file is the `mmap` binary file and the `idx` is the index file to look up the sentences in the binary file. They will be used for the following pre-training step."
            ]
        },
        {
            "cell_type": "markdown",
            "id": "58a3d4fa",
            "metadata": {},
            "source": [
                "### Pretrain\n",
                "\n",
                "We are ready to pretrain the NeMo GPT model. As large models can be quite difficult to train due to memory constraints, NeMo makes it possible by using both Tensor model parallel and Pipeline model parallelism that enables training transformer models with billions of parameters. On top of the model parallelism, we can apply the popular data parallelism to the training to fully utilize all the GPUs in the cluster. In this [paper](https://arxiv.org/pdf/2104.04473.pdf), it provides a few tips about how to setup the model parallelism and data parallelism optimally:\n",
                "\n",
                "1. When considering different forms of model parallelism, tensor model parallelism should generally be used up to degree 𝑔 when using 𝑔-GPU servers, and then pipeline model parallelism can be used to scale up to larger models across server.\n",
                "2. When using data and model parallelism, a total model-parallel size of 𝑀 = 𝑑 Β· 𝑝 should be used so that the model’s parameters and intermediate metadata fit in GPU memory; data parallelism can be used to scale up training to more GPUs.\n",
                "3. The optimal microbatch size 𝑏 depends on the throughput and memory footprint characteristics of the model, as well as the pipeline depth 𝑝, data-parallel size 𝑑, and batch size 𝐡.\n",
                "\n",
                "In this tutorial, we only concern with training a model that fits into a single GPU. we set the tensor model parallel and pipeline model parallelism parameter to 1. Feel free to adjust it to train a larger model according to the available compute resources. As we know from OpenAI's [scaling law of natural language](https://arxiv.org/abs/2001.08361), the larger the model, the better the performance is.\n",
                "\n",
                "Download and run the pretraining task script below. Note, this is the most time consuming step. It takes days for the task to converge depending on the computation environment, model size."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "749fd8df",
            "metadata": {},
            "outputs": [],
            "source": [
                "!mkdir -p conf\n",
                "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/megatron_gpt_pretraining.py')\n",
                "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/conf/megatron_gpt_config.yaml', out='conf')"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "c7665cee",
            "metadata": {},
            "outputs": [],
            "source": [
                "    !python megatron_gpt_pretraining.py \\\n",
                "                trainer.devices={NUM_GPUS} \\\n",
                "                trainer.accelerator=gpu \\\n",
                "                trainer.log_every_n_steps=100 \\\n",
                "                trainer.val_check_interval=500 \\\n",
                "                trainer.accumulate_grad_batches=1 \\\n",
                "                trainer.max_steps=10000 \\\n",
                "                trainer.precision=16 \\\n",
                "                trainer.gradient_clip_val=1.0 \\\n",
                "                exp_manager.exp_dir=gpt_creditcard_results \\\n",
                "                model.tensor_model_parallel_size={TENSOR_MP_SIZE} \\\n",
                "                model.pipeline_model_parallel_size={PIPELINE_MP_SIZE} \\\n",
                "                model.optim.name=fused_adam \\\n",
                "                model.optim.lr=2e-4 \\\n",
                "                model.optim.sched.warmup_steps=2 \\\n",
                "                model.optim.sched.constant_steps=2 \\\n",
                "                model.optim.sched.min_lr=8e-5 \\\n",
                "                model.max_position_embeddings={SEQ_LENGTH} \\\n",
                "                model.encoder_seq_length={SEQ_LENGTH} \\\n",
                "                model.data.seq_length={SEQ_LENGTH} \\\n",
                "                model.tokenizer.type=Tabular \\\n",
                "                model.tokenizer.library=tabular \\\n",
                "                model.tokenizer.vocab_file={CC_OUTPUT_P} \\\n",
                "                model.tokenizer.delimiter=\\',\\' \\\n",
                "                model.data.eod_mask_loss=True \\\n",
                "                model.data.splits_string=\\'3800,198,2\\' \\\n",
                "                model.num_layers={NUM_LAYERS} \\\n",
                "                model.hidden_size={HIDDEN_SIZE} \\\n",
                "                model.num_attention_heads={NUM_ATTENTION_HEADS} \\\n",
                "                model.activations_checkpoint_method='block' \\\n",
                "                model.activations_checkpoint_num_layers=1 \\\n",
                "                model.data.data_prefix=[tabular_data_text_document]"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "45ac928f",
            "metadata": {},
            "source": [
                "The pretraining will save the checkpoint files periodically at the location specified by `exp_manager.exp_dir`. In this case, it creates a directory called `gpt_creditcard_results`. The number `trainer.val_check_interval` controls the frequency of validation evaluation. We use 500 in this example. The trainer will preserve the checkpoint files which have the top `k` best validation error, by default, `k=10`. \n",
                "While the training job is running, we can use the `tensorboard` to monitor the training. For example, you can run this command and check the learning curves at browser.\n",
                "```bash\n",
                "--logdir gpt_creditcard_results/ --bind_all 0.0.0.0\n",
                "```\n",
                "\n",
                "Once the training converges, we take a checkpoint file which has the smallest validation error."
            ]
        },
        {
            "cell_type": "markdown",
            "id": "158a4bbe",
            "metadata": {},
            "source": [
                "## Convert checkpoint to nemo file\n",
                "\n",
                "NeMo library package the checkpoint file and other model artifacts (like model config file and vocab file) into a single `.nemo` file. It makes the process of loading GPT model and running inference easier. \n",
                "\n",
                "Let's download the script and convert the checkpoint file into `.nemo` file. Make sure to change the checkpoint file name to the correct name. You can find them in the `gpt_creditcard_results/megatron_gpt/checkpoints/ ` directory."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "46cecf96",
            "metadata": {},
            "outputs": [],
            "source": [
                "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/megatron_ckpt_to_nemo.py')"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "cd7fd084",
            "metadata": {},
            "outputs": [],
            "source": [
                "CHECKPONT_FILE_NAME = megatron_gpt--val_loss=1.17-step=10047-consumed_samples=80376.0-last.ckpt # change it to your checkpoint file name\n",
                "!python -m torch.distributed.launch --nproc_per_node=1 megatron_ckpt_to_nemo.py \\\n",
                "    --checkpoint_folder=gpt_creditcard_results/megatron_gpt/checkpoints/ \\\n",
                "    --checkpoint_name={CHECKPONT_FILE_NAME} \\\n",
                "    --nemo_file_path=tabular.nemo \\\n",
                "    --tensor_model_parallel_size={TENSOR_MP_SIZE} \\\n",
                "    --pipeline_model_parallel_size={PIPELINE_MP_SIZE} \\\n",
                "    --gpus_per_node=1 \\\n",
                "    --model_type=gpt"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "fa16378e",
            "metadata": {},
            "source": [
                "After running this script, it creates a `tabular.nemo` file which can be used to generate synthetic credit card transactions. "
            ]
        },
        {
            "cell_type": "markdown",
            "id": "ed056ec6",
            "metadata": {},
            "source": [
                "### Generate synthetic credit card transactions\n",
                "\n",
                "We come to the last step of this tutorial - generate synthetic credit card transactions!\n",
                "\n",
                "First let's load the trained model weights, put the NeMo GPT in inference mode and start the text generation server. All of these can be done by running the `megatron_gpt_eval.py` script. \n",
                "\n",
                "Let's download the script and configuration file."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "59ab7c9b",
            "metadata": {},
            "outputs": [],
            "source": [
                "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/megatron_gpt_eval.py')\n",
                "wget.download(f'https://raw.githubusercontent.com/NVIDIA/NeMo/{BRANCH}/examples/nlp/language_modeling/conf/megatron_gpt_inference.yaml', out='conf')"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "a62b48dc",
            "metadata": {},
            "source": [
                "Open another Jupyter notebook or terminal, and run the following in a cell. \n",
                "```python\n",
                "!python megatron_gpt_eval.py \\\n",
                "    gpt_model_file=tabular.nemo \\\n",
                "    prompts=[\\'\\',\\'\\'] \\\n",
                "    server=True\n",
                "```\n",
                "The text generation server accepts REST API request to send the generated text in the response. Let's use the following Python code to generate some transactions."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "ebd6f637",
            "metadata": {},
            "outputs": [],
            "source": [
                "with open(CC_OUTPUT_P, 'rb') as handle:\n",
                "        cc: ColumnCodes = pickle.load(handle)\n",
                "\n",
                "token_per_rows = sum(cc.sizes) + 1\n",
                "\n",
                "batch_size = 4\n",
                "port_num = 5555\n",
                "num_of_rows = 10\n",
                "headers = {\"Content-Type\": \"application/json\"}\n",
                "\n",
                "\n",
                "def request_data(data):\n",
                "    resp = requests.put('http://localhost:{}/generate'.format(port_num),\n",
                "                        data=json.dumps(data), headers=headers)\n",
                "    sentences = resp.json()['sentences']\n",
                "    return sentences\n",
                "\n",
                "\n",
                "# generate the initial transactions \n",
                "data = {\n",
                "    \"sentences\": [\"\"] * batch_size,\n",
                "    \"tokens_to_generate\": num_of_rows * token_per_rows,\n",
                "    \"temperature\": 1.0,\n",
                "    \"add_BOS\": True\n",
                "}\n",
                "\n",
                "sentences = request_data(data)\n",
                "\n",
                "for i in range(batch_size):\n",
                "    s = sentences[i]\n",
                "    print(s)"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "cccd54d9",
            "metadata": {},
            "source": [
                "The above code only generate `num_of_rows` of transactions starting from the beginning. If longer sequence is needed, we can run the inference conditioned on the past transactions in a sliding window fashion. For example, first it generates [A, B, C, D, E] transactions conditioned on `<|endoftext|>` token. Then, it conditions on [D, E] and generates [D, E, F, G, H]. Once the long sequence comes to the end indicated by `<|endoftext|>`, it will keep generating new transactions for a different user. For example, after generating [X, Y, Z, <|endoftext|>] in the last run, it will generate [Z, <|endoftext|>, A', B', C'] in the next time, where A', B', C' are transactions for a different user and they are not depending on the other users transaction Z.  \n",
                "\n",
                "The following code implements the idea above and can be used to generate massive number of transactions in long sequences. The `history_rows` specifies the number of rows of transactions used as conditional context and `num_of_rows` specify the number of rows of transactions to be generated at a time. It saves all the synthetic credit card transactions in the text files whose file names starts with prefix `synthetic`. You can adjust `number_of_blocks`, `batch_size` parameters to generate more transactions.  "
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "e4b80ab0",
            "metadata": {},
            "outputs": [],
            "source": [
                "with open(CC_OUTPUT_P, 'rb') as handle:\n",
                "        cc: ColumnCodes = pickle.load(handle)\n",
                "\n",
                "batch_size = 4\n",
                "num_of_rows = 50\n",
                "token_per_rows = sum(cc.sizes) + 1\n",
                "history_rows = 40\n",
                "num_of_blocks = 100\n",
                "\n",
                "port_num = 5555\n",
                "headers = {\"Content-Type\": \"application/json\"}\n",
                "\n",
                "prefix_name = 'synthetic'\n",
                "files = []\n",
                "\n",
                "\n",
                "for i in range(batch_size):\n",
                "    files.append(open(\"{}_{}.txt\".format(prefix_name, i), 'w'))\n",
                "\n",
                "\n",
                "def request_data(data):\n",
                "    resp = requests.put('http://localhost:{}/generate'.format(port_num),\n",
                "                        data=json.dumps(data), headers=headers)\n",
                "    sentences = resp.json()['sentences']\n",
                "    return sentences\n",
                "\n",
                "\n",
                "def get_condition_text(sentences, history_rows):\n",
                "    condition_text = ['\\n'.join([ss for ss in s.split(\n",
                "        '\\n')[-(history_rows+1):]]) for s in sentences]\n",
                "    return condition_text\n",
                "\n",
                "\n",
                "def get_extra_text(sentences, history_rows):\n",
                "    extra_text = ['\\n'.join([ss for ss in s.split(\n",
                "        '\\n')[history_rows:]]) for s in sentences]\n",
                "    return extra_text\n",
                "\n",
                "# generate the inital transactions \n",
                "data = {\n",
                "    \"sentences\": [\"\"] * batch_size,\n",
                "    \"tokens_to_generate\": num_of_rows * token_per_rows,\n",
                "    \"temperature\": 1.0,\n",
                "    \"add_BOS\": True\n",
                "}\n",
                "\n",
                "sentences = request_data(data)\n",
                "\n",
                "for i in range(batch_size):\n",
                "    s = sentences[i]\n",
                "    files[i].write(s.replace('<|endoftext|>', '\\n'))\n",
                "\n",
                "# generate the transactions conditioned on the previous ones\n",
                "for block in range(num_of_blocks):\n",
                "    print(\"block id: {}\".format(block))\n",
                "    condition_text = get_condition_text(sentences, history_rows)\n",
                "    data = {\n",
                "        \"sentences\": condition_text,\n",
                "        \"tokens_to_generate\": num_of_rows * token_per_rows,\n",
                "        \"temperature\": 1.0,\n",
                "        \"add_BOS\": False\n",
                "    }\n",
                "\n",
                "    sentences = request_data(data)\n",
                "\n",
                "    extra_text = get_extra_text(sentences, history_rows)\n",
                "\n",
                "    for i in range(batch_size):\n",
                "        s = extra_text[i]\n",
                "        files[i].write(s.replace('<|endoftext|>', '\\n---------------\\n'))\n",
                "        files[i].flush()\n",
                "\n",
                "\n",
                "for i in range(batch_size):\n",
                "    files[i].close()"
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "79c1ee03",
            "metadata": {},
            "outputs": [],
            "source": [
                "# check the generated creditcard transaction files\n",
                "!ls synthetic*.txt"
            ]
        },
        {
            "cell_type": "markdown",
            "id": "0f2f6e3a",
            "metadata": {},
            "source": [
                "That's it! In this tutorial, you have learned how to train a NeMo GPT model to generate synthetic data. Go ahead and apply it for your own data."
            ]
        },
        {
            "cell_type": "code",
            "execution_count": null,
            "id": "bb9fa86d",
            "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.12"
        }
    },
    "nbformat": 4,
    "nbformat_minor": 5
}