File size: 50,037 Bytes
8c47142
 
 
 
 
 
 
 
 
 
 
 
 
1f9c86c
8c47142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
8c47142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
8c47142
 
 
 
 
1f9c86c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f9c86c
 
 
 
 
 
 
 
 
 
c78bae0
1f9c86c
c78bae0
 
1f9c86c
 
 
 
 
 
fdaf162
1f9c86c
 
 
 
 
 
fdaf162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
fdaf162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
fdaf162
 
 
 
 
 
 
 
 
 
 
c78bae0
fdaf162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
fdaf162
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
fdaf162
 
 
 
c78bae0
1f9c86c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
1f9c86c
 
 
c78bae0
1f9c86c
 
 
 
c78bae0
 
1f9c86c
 
 
 
 
 
 
 
 
 
 
 
 
 
fdaf162
 
 
 
1f9c86c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
1f9c86c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
1f9c86c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8c47142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
8c47142
 
 
 
 
 
 
 
 
 
fdaf162
 
c78bae0
 
8c47142
 
c78bae0
8c47142
c78bae0
 
 
 
8c47142
 
 
 
 
 
 
 
c78bae0
 
8c47142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c78bae0
 
8c47142
 
 
 
 
 
 
 
 
 
1f9c86c
 
c78bae0
 
1f9c86c
 
 
c78bae0
 
1f9c86c
 
 
c78bae0
 
fdaf162
 
 
c78bae0
 
fdaf162
 
 
c78bae0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f9c86c
8c47142
 
 
 
 
 
 
 
 
 
 
1f9c86c
 
 
 
 
8c47142
1f9c86c
 
 
 
 
 
 
 
 
 
 
 
8c47142
 
 
 
 
 
1f9c86c
 
8c47142
 
 
1f9c86c
 
 
 
 
 
 
 
 
 
c78bae0
1f9c86c
 
c78bae0
 
 
 
 
 
 
 
1f9c86c
 
 
 
fdaf162
 
1f9c86c
 
 
 
 
 
 
 
fdaf162
1f9c86c
 
 
 
c78bae0
1f9c86c
 
 
 
8c47142
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Finetune DeepSeek Coder 1.3B for NBA Kaggle Database SQLite Generation"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## First define prompt"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "input_prompt = \"\"\"You are an AI assistant that converts natural language queries into valid SQLite queries.\n",
    "Database Schema and Explanations\n",
    "\n",
    "team Table\n",
    "Stores information about NBA teams.\n",
    "CREATE TABLE IF NOT EXISTS \"team\" (\n",
    "  \"id\" TEXT PRIMARY KEY,      -- Unique identifier for the team\n",
    "  \"full_name\" TEXT,           -- Full official name of the team (e.g., \"Los Angeles Lakers\")\n",
    "  \"abbreviation\" TEXT,        -- Shortened team name (e.g., \"LAL\")\n",
    "  \"nickname\" TEXT,            -- Commonly used nickname for the team (e.g., \"Lakers\")\n",
    "  \"city\" TEXT,                -- City where the team is based\n",
    "  \"state\" TEXT,               -- State where the team is located\n",
    "  \"year_founded\" REAL         -- Year the team was established\n",
    ");\n",
    "\n",
    "game Table\n",
    "Contains detailed statistics for each NBA game, including home and away team performance.\n",
    "CREATE TABLE IF NOT EXISTS \"game\" (\n",
    "  \"season_id\" TEXT,            -- Season identifier, formatted as \"2YYYY\" (e.g., \"21970\" for the 1970 season)\n",
    "  \"team_id_home\" TEXT,         -- ID of the home team (matches \"id\" in team table)\n",
    "  \"team_abbreviation_home\" TEXT, -- Abbreviation of the home team\n",
    "  \"team_name_home\" TEXT,       -- Full name of the home team\n",
    "  \"game_id\" TEXT PRIMARY KEY,  -- Unique identifier for the game\n",
    "  \"game_date\" TIMESTAMP,       -- Date the game was played (YYYY-MM-DD format)\n",
    "  \"matchup_home\" TEXT,         -- Matchup details including opponent (e.g., \"LAL vs. BOS\")\n",
    "  \"wl_home\" TEXT,              -- \"W\" if the home team won, \"L\" if they lost\n",
    "  \"min\" INTEGER,               -- Total minutes played in the game\n",
    "  \"fgm_home\" REAL,             -- Field goals made by the home team\n",
    "  \"fga_home\" REAL,             -- Field goals attempted by the home team\n",
    "  \"fg_pct_home\" REAL,          -- Field goal percentage of the home team\n",
    "  \"fg3m_home\" REAL,            -- Three-point field goals made by the home team\n",
    "  \"fg3a_home\" REAL,            -- Three-point attempts by the home team\n",
    "  \"fg3_pct_home\" REAL,         -- Three-point field goal percentage of the home team\n",
    "  \"ftm_home\" REAL,             -- Free throws made by the home team\n",
    "  \"fta_home\" REAL,             -- Free throws attempted by the home team\n",
    "  \"ft_pct_home\" REAL,          -- Free throw percentage of the home team\n",
    "  \"oreb_home\" REAL,            -- Offensive rebounds by the home team\n",
    "  \"dreb_home\" REAL,            -- Defensive rebounds by the home team\n",
    "  \"reb_home\" REAL,             -- Total rebounds by the home team\n",
    "  \"ast_home\" REAL,             -- Assists by the home team\n",
    "  \"stl_home\" REAL,             -- Steals by the home team\n",
    "  \"blk_home\" REAL,             -- Blocks by the home team\n",
    "  \"tov_home\" REAL,             -- Turnovers by the home team\n",
    "  \"pf_home\" REAL,              -- Personal fouls by the home team\n",
    "  \"pts_home\" REAL,             -- Total points scored by the home team\n",
    "  \"plus_minus_home\" INTEGER,   -- Plus/minus rating for the home team\n",
    "  \"video_available_home\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
    "  \"team_id_away\" TEXT,         -- ID of the away team\n",
    "  \"team_abbreviation_away\" TEXT, -- Abbreviation of the away team\n",
    "  \"team_name_away\" TEXT,       -- Full name of the away team\n",
    "  \"matchup_away\" TEXT,         -- Matchup details from the away team’s perspective\n",
    "  \"wl_away\" TEXT,              -- \"W\" if the away team won, \"L\" if they lost\n",
    "  \"fgm_away\" REAL,             -- Field goals made by the away team\n",
    "  \"fga_away\" REAL,             -- Field goals attempted by the away team\n",
    "  \"fg_pct_away\" REAL,          -- Field goal percentage of the away team\n",
    "  \"fg3m_away\" REAL,            -- Three-point field goals made by the away team\n",
    "  \"fg3a_away\" REAL,            -- Three-point attempts by the away team\n",
    "  \"fg3_pct_away\" REAL,         -- Three-point field goal percentage of the away team\n",
    "  \"ftm_away\" REAL,             -- Free throws made by the away team\n",
    "  \"fta_away\" REAL,             -- Free throws attempted by the away team\n",
    "  \"ft_pct_away\" REAL,          -- Free throw percentage of the away team\n",
    "  \"oreb_away\" REAL,            -- Offensive rebounds by the away team\n",
    "  \"dreb_away\" REAL,            -- Defensive rebounds by the away team\n",
    "  \"reb_away\" REAL,             -- Total rebounds by the away team\n",
    "  \"ast_away\" REAL,             -- Assists by the away team\n",
    "  \"stl_away\" REAL,             -- Steals by the away team\n",
    "  \"blk_away\" REAL,             -- Blocks by the away team\n",
    "  \"tov_away\" REAL,             -- Turnovers by the away team\n",
    "  \"pf_away\" REAL,              -- Personal fouls by the away team\n",
    "  \"pts_away\" REAL,             -- Total points scored by the away team\n",
    "  \"plus_minus_away\" INTEGER,   -- Plus/minus rating for the away team\n",
    "  \"video_available_away\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
    "  \"season_type\" TEXT           -- Regular season or playoffs\n",
    ");\n",
    "\n",
    "other_stats Table\n",
    "Stores additional statistics, linked to the game table via game_id.\n",
    "CREATE TABLE IF NOT EXISTS \"other_stats\" (\n",
    "  \"game_id\" TEXT,             -- Unique game identifier, matches id column from game table\n",
    "  \"league_id\" TEXT,           -- League identifier\n",
    "  \"team_id_home\" TEXT,        -- Home team identifier\n",
    "  \"team_abbreviation_home\" TEXT, -- Home team abbreviation\n",
    "  \"team_city_home\" TEXT,      -- Home team city\n",
    "  \"pts_paint_home\" INTEGER,   -- Points in the paint by the home team\n",
    "  \"pts_2nd_chance_home\" INTEGER, -- Second chance points by the home team\n",
    "  \"pts_fb_home\" INTEGER,      -- Fast break points by the home team\n",
    "  \"largest_lead_home\" INTEGER,-- Largest lead by the home team\n",
    "  \"lead_changes\" INTEGER,     -- Number of lead changes \n",
    "  \"times_tied\" INTEGER,       -- Number of times the score was tied\n",
    "  \"team_turnovers_home\" INTEGER, -- Home team turnovers\n",
    "  \"total_turnovers_home\" INTEGER, -- Total turnovers by the home team\n",
    "  \"team_rebounds_home\" INTEGER, -- Home team rebounds\n",
    "  \"pts_off_to_home\" INTEGER,  -- Points off turnovers by the home team\n",
    "  \"team_id_away\" TEXT,        -- Away team identifier\n",
    "  \"team_abbreviation_away\" TEXT,  -- Away team abbreviation\n",
    "  \"pts_paint_away\" INTEGER,   -- Points in the paint by the away team\n",
    "  \"pts_2nd_chance_away\" INTEGER, -- Second chance points by the away team\n",
    "  \"pts_fb_away\" INTEGER,      -- Fast break points by the away team\n",
    "  \"largest_lead_away\" INTEGER,-- Largest lead by the away team\n",
    "  \"team_turnovers_away\" INTEGER, -- Away team turnovers\n",
    "  \"total_turnovers_away\" INTEGER, -- Total turnovers by the away team\n",
    "  \"team_rebounds_away\" INTEGER, -- Away team rebounds\n",
    "  \"pts_off_to_away\" INTEGER   -- Points off turnovers by the away team\n",
    ");\n",
    "\n",
    "\n",
    "Team Name Information\n",
    "In the plaintext user questions, only the full team names will be used, but in the queries you may use the full team names or the abbreviations. \n",
    "The full team names can be used with the game table, while the abbreviations should be used with the other_stats table.\n",
    "Notice they are separated by the | character in the following list:\n",
    "\n",
    "Atlanta Hawks|ATL\n",
    "Boston Celtics|BOS\n",
    "Cleveland Cavaliers|CLE\n",
    "New Orleans Pelicans|NOP\n",
    "Chicago Bulls|CHI\n",
    "Dallas Mavericks|DAL\n",
    "Denver Nuggets|DEN\n",
    "Golden State Warriors|GSW\n",
    "Houston Rockets|HOU\n",
    "Los Angeles Clippers|LAC\n",
    "Los Angeles Lakers|LAL\n",
    "Miami Heat|MIA\n",
    "Milwaukee Bucks|MIL\n",
    "Minnesota Timberwolves|MIN\n",
    "Brooklyn Nets|BKN\n",
    "New York Knicks|NYK\n",
    "Orlando Magic|ORL\n",
    "Indiana Pacers|IND\n",
    "Philadelphia 76ers|PHI\n",
    "Phoenix Suns|PHX\n",
    "Portland Trail Blazers|POR\n",
    "Sacramento Kings|SAC\n",
    "San Antonio Spurs|SAS\n",
    "Oklahoma City Thunder|OKC\n",
    "Toronto Raptors|TOR\n",
    "Utah Jazz|UTA\n",
    "Memphis Grizzlies|MEM\n",
    "Washington Wizards|WAS\n",
    "Detroit Pistons|DET\n",
    "Charlotte Hornets|CHA\n",
    "\n",
    "Query Guidelines\n",
    "Use team_name_home and team_name_away to match teams to the game table. Use team_abbreviation_home and team_abbreviation away to match teams to the other_stats table.\n",
    "\n",
    "To filter by season, use season_id = '2YYYY'.\n",
    "\n",
    "Example: To get statistics from 2005, use a statement like: season_id = '22005'. To get statistics from 1972, use a statement like: season_id = \"21972\". To get statistics from 2015, use a statement like: season_id = \"22015\".\n",
    "\n",
    "Ensure queries return relevant columns and avoid unnecessary joins.\n",
    "\n",
    "Example User Requests and SQLite Queries\n",
    "Request:\n",
    "\"What is the most points the Los Angeles Lakers have ever scored at home?\"\n",
    "SQLite:\n",
    "SELECT MAX(pts_home) FROM game WHERE team_name_home = 'Los Angeles Lakers';\n",
    "\n",
    "Request:\n",
    "\"Which teams are located in the state of California?\"\n",
    "SQLite:\n",
    "SELECT full_name FROM team WHERE state = 'California';\n",
    "\n",
    "Request:\n",
    "\"Which team had the highest number of team turnovers in an away game?\"\n",
    "SQLite:\n",
    "SELECT team_abbreviation_away FROM other_stats ORDER BY team_turnovers_away DESC LIMIT 1;\n",
    "\n",
    "Request:\n",
    "\"Which teams were founded before 1979?\"\n",
    "SQLite:\n",
    "SELECT full_name FROM team WHERE year_founded < 1979;\n",
    "\n",
    "Request:\n",
    "\"Find the Boston Celtics largest home victory margin in the 2008 season.\"\n",
    "SQLite:\n",
    "SELECT MAX(pts_home - pts_away) AS biggest_win FROM game WHERE team_name_home = 'Boston Celtics' AND season_id = '22008';\n",
    "\n",
    "Generate only the SQLite query prefaced by SQLite: and no other text, do not output an explanation of the query. Now generate an SQLite query for the following user request. Request:\n",
    "\"\"\""
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load data and convert to Dataset object tokenized by the DeepSeek model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Dean\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\tqdm\\auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html\n",
      "  from .autonotebook import tqdm as notebook_tqdm\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From c:\\Users\\Dean\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\tf_keras\\src\\losses.py:2976: The name tf.losses.sparse_softmax_cross_entropy is deprecated. Please use tf.compat.v1.losses.sparse_softmax_cross_entropy instead.\n",
      "\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Dean\\AppData\\Local\\Temp\\ipykernel_20424\\3615904657.py:13: FutureWarning: DataFrame.applymap has been deprecated. Use DataFrame.map instead.\n",
      "  df = df.applymap(lambda x: re.sub(r'\\s+', ' ', x) if isinstance(x, str) else x)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Total dataset examples: 1044\n",
      "                                       natural_query  \\\n",
      "0  Which NBA teams were established after the yea...   \n",
      "1  What is the most points the Los Angeles Lakers...   \n",
      "2  What is the second-highest number of points th...   \n",
      "3  How many home games did the Golden State Warri...   \n",
      "4  What is the average number of assists by the B...   \n",
      "\n",
      "                                           sql_query                result  \n",
      "0  SELECT full_name FROM team WHERE year_founded ...  New Orleans Pelicans  \n",
      "1  SELECT MAX(pts_home) FROM game WHERE team_name...                   162  \n",
      "2  SELECT pts_home FROM game WHERE team_name_home...                   156  \n",
      "3  SELECT COUNT(*) FROM game WHERE team_abbreviat...                    29  \n",
      "4  SELECT AVG(ast_home) FROM game WHERE team_abbr...           26.51355662  \n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Map:   0%|          | 0/1044 [00:00<?, ? examples/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You are an AI assistant that converts natural language queries into valid SQLite queries.\n",
      "Database Schema and Explanations\n",
      "\n",
      "team Table\n",
      "Stores information about NBA teams.\n",
      "CREATE TABLE IF NOT EXISTS \"team\" (\n",
      "  \"id\" TEXT PRIMARY KEY,      -- Unique identifier for the team\n",
      "  \"full_name\" TEXT,           -- Full official name of the team (e.g., \"Los Angeles Lakers\")\n",
      "  \"abbreviation\" TEXT,        -- Shortened team name (e.g., \"LAL\")\n",
      "  \"nickname\" TEXT,            -- Commonly used nickname for the team (e.g., \"Lakers\")\n",
      "  \"city\" TEXT,                -- City where the team is based\n",
      "  \"state\" TEXT,               -- State where the team is located\n",
      "  \"year_founded\" REAL         -- Year the team was established\n",
      ");\n",
      "\n",
      "game Table\n",
      "Contains detailed statistics for each NBA game, including home and away team performance.\n",
      "CREATE TABLE IF NOT EXISTS \"game\" (\n",
      "  \"season_id\" TEXT,            -- Season identifier, formatted as \"2YYYY\" (e.g., \"21970\" for the 1970 season)\n",
      "  \"team_id_home\" TEXT,         -- ID of the home team (matches \"id\" in team table)\n",
      "  \"team_abbreviation_home\" TEXT, -- Abbreviation of the home team\n",
      "  \"team_name_home\" TEXT,       -- Full name of the home team\n",
      "  \"game_id\" TEXT PRIMARY KEY,  -- Unique identifier for the game\n",
      "  \"game_date\" TIMESTAMP,       -- Date the game was played (YYYY-MM-DD format)\n",
      "  \"matchup_home\" TEXT,         -- Matchup details including opponent (e.g., \"LAL vs. BOS\")\n",
      "  \"wl_home\" TEXT,              -- \"W\" if the home team won, \"L\" if they lost\n",
      "  \"min\" INTEGER,               -- Total minutes played in the game\n",
      "  \"fgm_home\" REAL,             -- Field goals made by the home team\n",
      "  \"fga_home\" REAL,             -- Field goals attempted by the home team\n",
      "  \"fg_pct_home\" REAL,          -- Field goal percentage of the home team\n",
      "  \"fg3m_home\" REAL,            -- Three-point field goals made by the home team\n",
      "  \"fg3a_home\" REAL,            -- Three-point attempts by the home team\n",
      "  \"fg3_pct_home\" REAL,         -- Three-point field goal percentage of the home team\n",
      "  \"ftm_home\" REAL,             -- Free throws made by the home team\n",
      "  \"fta_home\" REAL,             -- Free throws attempted by the home team\n",
      "  \"ft_pct_home\" REAL,          -- Free throw percentage of the home team\n",
      "  \"oreb_home\" REAL,            -- Offensive rebounds by the home team\n",
      "  \"dreb_home\" REAL,            -- Defensive rebounds by the home team\n",
      "  \"reb_home\" REAL,             -- Total rebounds by the home team\n",
      "  \"ast_home\" REAL,             -- Assists by the home team\n",
      "  \"stl_home\" REAL,             -- Steals by the home team\n",
      "  \"blk_home\" REAL,             -- Blocks by the home team\n",
      "  \"tov_home\" REAL,             -- Turnovers by the home team\n",
      "  \"pf_home\" REAL,              -- Personal fouls by the home team\n",
      "  \"pts_home\" REAL,             -- Total points scored by the home team\n",
      "  \"plus_minus_home\" INTEGER,   -- Plus/minus rating for the home team\n",
      "  \"video_available_home\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
      "  \"team_id_away\" TEXT,         -- ID of the away team\n",
      "  \"team_abbreviation_away\" TEXT, -- Abbreviation of the away team\n",
      "  \"team_name_away\" TEXT,       -- Full name of the away team\n",
      "  \"matchup_away\" TEXT,         -- Matchup details from the away team’s perspective\n",
      "  \"wl_away\" TEXT,              -- \"W\" if the away team won, \"L\" if they lost\n",
      "  \"fgm_away\" REAL,             -- Field goals made by the away team\n",
      "  \"fga_away\" REAL,             -- Field goals attempted by the away team\n",
      "  \"fg_pct_away\" REAL,          -- Field goal percentage of the away team\n",
      "  \"fg3m_away\" REAL,            -- Three-point field goals made by the away team\n",
      "  \"fg3a_away\" REAL,            -- Three-point attempts by the away team\n",
      "  \"fg3_pct_away\" REAL,         -- Three-point field goal percentage of the away team\n",
      "  \"ftm_away\" REAL,             -- Free throws made by the away team\n",
      "  \"fta_away\" REAL,             -- Free throws attempted by the away team\n",
      "  \"ft_pct_away\" REAL,          -- Free throw percentage of the away team\n",
      "  \"oreb_away\" REAL,            -- Offensive rebounds by the away team\n",
      "  \"dreb_away\" REAL,            -- Defensive rebounds by the away team\n",
      "  \"reb_away\" REAL,             -- Total rebounds by the away team\n",
      "  \"ast_away\" REAL,             -- Assists by the away team\n",
      "  \"stl_away\" REAL,             -- Steals by the away team\n",
      "  \"blk_away\" REAL,             -- Blocks by the away team\n",
      "  \"tov_away\" REAL,             -- Turnovers by the away team\n",
      "  \"pf_away\" REAL,              -- Personal fouls by the away team\n",
      "  \"pts_away\" REAL,             -- Total points scored by the away team\n",
      "  \"plus_minus_away\" INTEGER,   -- Plus/minus rating for the away team\n",
      "  \"video_available_away\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
      "  \"season_type\" TEXT           -- Regular season or playoffs\n",
      ");\n",
      "\n",
      "other_stats Table\n",
      "Stores additional statistics, linked to the game table via game_id.\n",
      "CREATE TABLE IF NOT EXISTS \"other_stats\" (\n",
      "  \"game_id\" TEXT,             -- Unique game identifier, matches id column from game table\n",
      "  \"league_id\" TEXT,           -- League identifier\n",
      "  \"team_id_home\" TEXT,        -- Home team identifier\n",
      "  \"team_abbreviation_home\" TEXT, -- Home team abbreviation\n",
      "  \"team_city_home\" TEXT,      -- Home team city\n",
      "  \"pts_paint_home\" INTEGER,   -- Points in the paint by the home team\n",
      "  \"pts_2nd_chance_home\" INTEGER, -- Second chance points by the home team\n",
      "  \"pts_fb_home\" INTEGER,      -- Fast break points by the home team\n",
      "  \"largest_lead_home\" INTEGER,-- Largest lead by the home team\n",
      "  \"lead_changes\" INTEGER,     -- Number of lead changes \n",
      "  \"times_tied\" INTEGER,       -- Number of times the score was tied\n",
      "  \"team_turnovers_home\" INTEGER, -- Home team turnovers\n",
      "  \"total_turnovers_home\" INTEGER, -- Total turnovers by the home team\n",
      "  \"team_rebounds_home\" INTEGER, -- Home team rebounds\n",
      "  \"pts_off_to_home\" INTEGER,  -- Points off turnovers by the home team\n",
      "  \"team_id_away\" TEXT,        -- Away team identifier\n",
      "  \"team_abbreviation_away\" TEXT,  -- Away team abbreviation\n",
      "  \"pts_paint_away\" INTEGER,   -- Points in the paint by the away team\n",
      "  \"pts_2nd_chance_away\" INTEGER, -- Second chance points by the away team\n",
      "  \"pts_fb_away\" INTEGER,      -- Fast break points by the away team\n",
      "  \"largest_lead_away\" INTEGER,-- Largest lead by the away team\n",
      "  \"team_turnovers_away\" INTEGER, -- Away team turnovers\n",
      "  \"total_turnovers_away\" INTEGER, -- Total turnovers by the away team\n",
      "  \"team_rebounds_away\" INTEGER, -- Away team rebounds\n",
      "  \"pts_off_to_away\" INTEGER   -- Points off turnovers by the away team\n",
      ");\n",
      "\n",
      "\n",
      "Team Name Information\n",
      "In the plaintext user questions, only the full team names will be used, but in the queries you may use the full team names or the abbreviations. \n",
      "The full team names can be used with the game table, while the abbreviations should be used with the other_stats table.\n",
      "Notice they are separated by the | character in the following list:\n",
      "\n",
      "Atlanta Hawks|ATL\n",
      "Boston Celtics|BOS\n",
      "Cleveland Cavaliers|CLE\n",
      "New Orleans Pelicans|NOP\n",
      "Chicago Bulls|CHI\n",
      "Dallas Mavericks|DAL\n",
      "Denver Nuggets|DEN\n",
      "Golden State Warriors|GSW\n",
      "Houston Rockets|HOU\n",
      "Los Angeles Clippers|LAC\n",
      "Los Angeles Lakers|LAL\n",
      "Miami Heat|MIA\n",
      "Milwaukee Bucks|MIL\n",
      "Minnesota Timberwolves|MIN\n",
      "Brooklyn Nets|BKN\n",
      "New York Knicks|NYK\n",
      "Orlando Magic|ORL\n",
      "Indiana Pacers|IND\n",
      "Philadelphia 76ers|PHI\n",
      "Phoenix Suns|PHX\n",
      "Portland Trail Blazers|POR\n",
      "Sacramento Kings|SAC\n",
      "San Antonio Spurs|SAS\n",
      "Oklahoma City Thunder|OKC\n",
      "Toronto Raptors|TOR\n",
      "Utah Jazz|UTA\n",
      "Memphis Grizzlies|MEM\n",
      "Washington Wizards|WAS\n",
      "Detroit Pistons|DET\n",
      "Charlotte Hornets|CHA\n",
      "\n",
      "Query Guidelines\n",
      "Use team_name_home and team_name_away to match teams to the game table. Use team_abbreviation_home and team_abbreviation away to match teams to the other_stats table.\n",
      "\n",
      "To filter by season, use season_id = '2YYYY'.\n",
      "\n",
      "Example: To get statistics from 2005, use a statement like: season_id = '22005'. To get statistics from 1972, use a statement like: season_id = \"21972\". To get statistics from 2015, use a statement like: season_id = \"22015\".\n",
      "\n",
      "Ensure queries return relevant columns and avoid unnecessary joins.\n",
      "\n",
      "Example User Requests and SQLite Queries\n",
      "Request:\n",
      "\"What is the most points the Los Angeles Lakers have ever scored at home?\"\n",
      "SQLite:\n",
      "SELECT MAX(pts_home) FROM game WHERE team_name_home = 'Los Angeles Lakers';\n",
      "\n",
      "Request:\n",
      "\"Which teams are located in the state of California?\"\n",
      "SQLite:\n",
      "SELECT full_name FROM team WHERE state = 'California';\n",
      "\n",
      "Request:\n",
      "\"Which team had the highest number of team turnovers in an away game?\"\n",
      "SQLite:\n",
      "SELECT team_abbreviation_away FROM other_stats ORDER BY team_turnovers_away DESC LIMIT 1;\n",
      "\n",
      "Request:\n",
      "\"Which teams were founded before 1979?\"\n",
      "SQLite:\n",
      "SELECT full_name FROM team WHERE year_founded < 1979;\n",
      "\n",
      "Request:\n",
      "\"Find the Boston Celtics largest home victory margin in the 2008 season.\"\n",
      "SQLite:\n",
      "SELECT MAX(pts_home - pts_away) AS biggest_win FROM game WHERE team_name_home = 'Boston Celtics' AND season_id = '22008';\n",
      "\n",
      "Generate only the SQLite query prefaced by SQLite: and no other text, do not output an explanation of the query. Now generate an SQLite query for the following user request. Request:\n",
      "Which NBA teams were established after the year 2000? List their names and founding years, sorted from newest to oldest\n",
      "SQLite: \n",
      "SELECT full_name FROM team WHERE year_founded > 2000 ORDER BY year_founded DESC;\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Map: 100%|██████████| 1044/1044 [00:01<00:00, 546.45 examples/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "You are an AI assistant that converts natural language queries into valid SQLite queries.\n",
      "Database Schema and Explanations\n",
      "\n",
      "team Table\n",
      "Stores information about NBA teams.\n",
      "CREATE TABLE IF NOT EXISTS \"team\" (\n",
      "  \"id\" TEXT PRIMARY KEY,      -- Unique identifier for the team\n",
      "  \"full_name\" TEXT,           -- Full official name of the team (e.g., \"Los Angeles Lakers\")\n",
      "  \"abbreviation\" TEXT,        -- Shortened team name (e.g., \"LAL\")\n",
      "  \"nickname\" TEXT,            -- Commonly used nickname for the team (e.g., \"Lakers\")\n",
      "  \"city\" TEXT,                -- City where the team is based\n",
      "  \"state\" TEXT,               -- State where the team is located\n",
      "  \"year_founded\" REAL         -- Year the team was established\n",
      ");\n",
      "\n",
      "game Table\n",
      "Contains detailed statistics for each NBA game, including home and away team performance.\n",
      "CREATE TABLE IF NOT EXISTS \"game\" (\n",
      "  \"season_id\" TEXT,            -- Season identifier, formatted as \"2YYYY\" (e.g., \"21970\" for the 1970 season)\n",
      "  \"team_id_home\" TEXT,         -- ID of the home team (matches \"id\" in team table)\n",
      "  \"team_abbreviation_home\" TEXT, -- Abbreviation of the home team\n",
      "  \"team_name_home\" TEXT,       -- Full name of the home team\n",
      "  \"game_id\" TEXT PRIMARY KEY,  -- Unique identifier for the game\n",
      "  \"game_date\" TIMESTAMP,       -- Date the game was played (YYYY-MM-DD format)\n",
      "  \"matchup_home\" TEXT,         -- Matchup details including opponent (e.g., \"LAL vs. BOS\")\n",
      "  \"wl_home\" TEXT,              -- \"W\" if the home team won, \"L\" if they lost\n",
      "  \"min\" INTEGER,               -- Total minutes played in the game\n",
      "  \"fgm_home\" REAL,             -- Field goals made by the home team\n",
      "  \"fga_home\" REAL,             -- Field goals attempted by the home team\n",
      "  \"fg_pct_home\" REAL,          -- Field goal percentage of the home team\n",
      "  \"fg3m_home\" REAL,            -- Three-point field goals made by the home team\n",
      "  \"fg3a_home\" REAL,            -- Three-point attempts by the home team\n",
      "  \"fg3_pct_home\" REAL,         -- Three-point field goal percentage of the home team\n",
      "  \"ftm_home\" REAL,             -- Free throws made by the home team\n",
      "  \"fta_home\" REAL,             -- Free throws attempted by the home team\n",
      "  \"ft_pct_home\" REAL,          -- Free throw percentage of the home team\n",
      "  \"oreb_home\" REAL,            -- Offensive rebounds by the home team\n",
      "  \"dreb_home\" REAL,            -- Defensive rebounds by the home team\n",
      "  \"reb_home\" REAL,             -- Total rebounds by the home team\n",
      "  \"ast_home\" REAL,             -- Assists by the home team\n",
      "  \"stl_home\" REAL,             -- Steals by the home team\n",
      "  \"blk_home\" REAL,             -- Blocks by the home team\n",
      "  \"tov_home\" REAL,             -- Turnovers by the home team\n",
      "  \"pf_home\" REAL,              -- Personal fouls by the home team\n",
      "  \"pts_home\" REAL,             -- Total points scored by the home team\n",
      "  \"plus_minus_home\" INTEGER,   -- Plus/minus rating for the home team\n",
      "  \"video_available_home\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
      "  \"team_id_away\" TEXT,         -- ID of the away team\n",
      "  \"team_abbreviation_away\" TEXT, -- Abbreviation of the away team\n",
      "  \"team_name_away\" TEXT,       -- Full name of the away team\n",
      "  \"matchup_away\" TEXT,         -- Matchup details from the away team’s perspective\n",
      "  \"wl_away\" TEXT,              -- \"W\" if the away team won, \"L\" if they lost\n",
      "  \"fgm_away\" REAL,             -- Field goals made by the away team\n",
      "  \"fga_away\" REAL,             -- Field goals attempted by the away team\n",
      "  \"fg_pct_away\" REAL,          -- Field goal percentage of the away team\n",
      "  \"fg3m_away\" REAL,            -- Three-point field goals made by the away team\n",
      "  \"fg3a_away\" REAL,            -- Three-point attempts by the away team\n",
      "  \"fg3_pct_away\" REAL,         -- Three-point field goal percentage of the away team\n",
      "  \"ftm_away\" REAL,             -- Free throws made by the away team\n",
      "  \"fta_away\" REAL,             -- Free throws attempted by the away team\n",
      "  \"ft_pct_away\" REAL,          -- Free throw percentage of the away team\n",
      "  \"oreb_away\" REAL,            -- Offensive rebounds by the away team\n",
      "  \"dreb_away\" REAL,            -- Defensive rebounds by the away team\n",
      "  \"reb_away\" REAL,             -- Total rebounds by the away team\n",
      "  \"ast_away\" REAL,             -- Assists by the away team\n",
      "  \"stl_away\" REAL,             -- Steals by the away team\n",
      "  \"blk_away\" REAL,             -- Blocks by the away team\n",
      "  \"tov_away\" REAL,             -- Turnovers by the away team\n",
      "  \"pf_away\" REAL,              -- Personal fouls by the away team\n",
      "  \"pts_away\" REAL,             -- Total points scored by the away team\n",
      "  \"plus_minus_away\" INTEGER,   -- Plus/minus rating for the away team\n",
      "  \"video_available_away\" INTEGER, -- Indicates whether video is available (1 = Yes, 0 = No)\n",
      "  \"season_type\" TEXT           -- Regular season or playoffs\n",
      ");\n",
      "\n",
      "other_stats Table\n",
      "Stores additional statistics, linked to the game table via game_id.\n",
      "CREATE TABLE IF NOT EXISTS \"other_stats\" (\n",
      "  \"game_id\" TEXT,             -- Unique game identifier, matches id column from game table\n",
      "  \"league_id\" TEXT,           -- League identifier\n",
      "  \"team_id_home\" TEXT,        -- Home team identifier\n",
      "  \"team_abbreviation_home\" TEXT, -- Home team abbreviation\n",
      "  \"team_city_home\" TEXT,      -- Home team city\n",
      "  \"pts_paint_home\" INTEGER,   -- Points in the paint by the home team\n",
      "  \"pts_2nd_chance_home\" INTEGER, -- Second chance points by the home team\n",
      "  \"pts_fb_home\" INTEGER,      -- Fast break points by the home team\n",
      "  \"largest_lead_home\" INTEGER,-- Largest lead by the home team\n",
      "  \"lead_changes\" INTEGER,     -- Number of lead changes \n",
      "  \"times_tied\" INTEGER,       -- Number of times the score was tied\n",
      "  \"team_turnovers_home\" INTEGER, -- Home team turnovers\n",
      "  \"total_turnovers_home\" INTEGER, -- Total turnovers by the home team\n",
      "  \"team_rebounds_home\" INTEGER, -- Home team rebounds\n",
      "  \"pts_off_to_home\" INTEGER,  -- Points off turnovers by the home team\n",
      "  \"team_id_away\" TEXT,        -- Away team identifier\n",
      "  \"team_abbreviation_away\" TEXT,  -- Away team abbreviation\n",
      "  \"pts_paint_away\" INTEGER,   -- Points in the paint by the away team\n",
      "  \"pts_2nd_chance_away\" INTEGER, -- Second chance points by the away team\n",
      "  \"pts_fb_away\" INTEGER,      -- Fast break points by the away team\n",
      "  \"largest_lead_away\" INTEGER,-- Largest lead by the away team\n",
      "  \"team_turnovers_away\" INTEGER, -- Away team turnovers\n",
      "  \"total_turnovers_away\" INTEGER, -- Total turnovers by the away team\n",
      "  \"team_rebounds_away\" INTEGER, -- Away team rebounds\n",
      "  \"pts_off_to_away\" INTEGER   -- Points off turnovers by the away team\n",
      ");\n",
      "\n",
      "\n",
      "Team Name Information\n",
      "In the plaintext user questions, only the full team names will be used, but in the queries you may use the full team names or the abbreviations. \n",
      "The full team names can be used with the game table, while the abbreviations should be used with the other_stats table.\n",
      "Notice they are separated by the | character in the following list:\n",
      "\n",
      "Atlanta Hawks|ATL\n",
      "Boston Celtics|BOS\n",
      "Cleveland Cavaliers|CLE\n",
      "New Orleans Pelicans|NOP\n",
      "Chicago Bulls|CHI\n",
      "Dallas Mavericks|DAL\n",
      "Denver Nuggets|DEN\n",
      "Golden State Warriors|GSW\n",
      "Houston Rockets|HOU\n",
      "Los Angeles Clippers|LAC\n",
      "Los Angeles Lakers|LAL\n",
      "Miami Heat|MIA\n",
      "Milwaukee Bucks|MIL\n",
      "Minnesota Timberwolves|MIN\n",
      "Brooklyn Nets|BKN\n",
      "New York Knicks|NYK\n",
      "Orlando Magic|ORL\n",
      "Indiana Pacers|IND\n",
      "Philadelphia 76ers|PHI\n",
      "Phoenix Suns|PHX\n",
      "Portland Trail Blazers|POR\n",
      "Sacramento Kings|SAC\n",
      "San Antonio Spurs|SAS\n",
      "Oklahoma City Thunder|OKC\n",
      "Toronto Raptors|TOR\n",
      "Utah Jazz|UTA\n",
      "Memphis Grizzlies|MEM\n",
      "Washington Wizards|WAS\n",
      "Detroit Pistons|DET\n",
      "Charlotte Hornets|CHA\n",
      "\n",
      "Query Guidelines\n",
      "Use team_name_home and team_name_away to match teams to the game table. Use team_abbreviation_home and team_abbreviation away to match teams to the other_stats table.\n",
      "\n",
      "To filter by season, use season_id = '2YYYY'.\n",
      "\n",
      "Example: To get statistics from 2005, use a statement like: season_id = '22005'. To get statistics from 1972, use a statement like: season_id = \"21972\". To get statistics from 2015, use a statement like: season_id = \"22015\".\n",
      "\n",
      "Ensure queries return relevant columns and avoid unnecessary joins.\n",
      "\n",
      "Example User Requests and SQLite Queries\n",
      "Request:\n",
      "\"What is the most points the Los Angeles Lakers have ever scored at home?\"\n",
      "SQLite:\n",
      "SELECT MAX(pts_home) FROM game WHERE team_name_home = 'Los Angeles Lakers';\n",
      "\n",
      "Request:\n",
      "\"Which teams are located in the state of California?\"\n",
      "SQLite:\n",
      "SELECT full_name FROM team WHERE state = 'California';\n",
      "\n",
      "Request:\n",
      "\"Which team had the highest number of team turnovers in an away game?\"\n",
      "SQLite:\n",
      "SELECT team_abbreviation_away FROM other_stats ORDER BY team_turnovers_away DESC LIMIT 1;\n",
      "\n",
      "Request:\n",
      "\"Which teams were founded before 1979?\"\n",
      "SQLite:\n",
      "SELECT full_name FROM team WHERE year_founded < 1979;\n",
      "\n",
      "Request:\n",
      "\"Find the Boston Celtics largest home victory margin in the 2008 season.\"\n",
      "SQLite:\n",
      "SELECT MAX(pts_home - pts_away) AS biggest_win FROM game WHERE team_name_home = 'Boston Celtics' AND season_id = '22008';\n",
      "\n",
      "Generate only the SQLite query prefaced by SQLite: and no other text, do not output an explanation of the query. Now generate an SQLite query for the following user request. Request:\n",
      "How many points did the Golden State Warriors score in their first game of the 2005 season?\n",
      "SQLite: \n",
      "SELECT pts_home FROM game WHERE team_abbreviation_home = 'GSW' AND season_id = '22005' ORDER BY game_date ASC LIMIT 1;\n",
      "939\n",
      "105\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "import torch\n",
    "from datasets import Dataset\n",
    "from transformers import AutoTokenizer, AutoModelForCausalLM, TrainingArguments, Trainer, BitsAndBytesConfig, EarlyStoppingCallback\n",
    "from torch.utils.data import DataLoader\n",
    "from peft import LoraConfig, get_peft_model, TaskType\n",
    "import os\n",
    "import re\n",
    "\n",
    "# Load dataset\n",
    "df = pd.read_csv(\"./train-data/sql_train.tsv\", sep='\\t')\n",
    "\n",
    "df = df.applymap(lambda x: re.sub(r'\\s+', ' ', x) if isinstance(x, str) else x)\n",
    "\n",
    "# Display dataset info\n",
    "print(f\"Total dataset examples: {len(df)}\")\n",
    "print(df.head())\n",
    "\n",
    "# Load tokenizer\n",
    "model_name = \"./deepseek-coder-1.3b-instruct\"\n",
    "tokenizer = AutoTokenizer.from_pretrained(model_name)\n",
    "\n",
    "# Preprocessing function\n",
    "def preprocess_function(examples):\n",
    "    \"\"\"\n",
    "    Tokenizes input natural language queries and corresponding SQL queries.\n",
    "    \"\"\"\n",
    "    inputs = [input_prompt + q for q in examples[\"natural_query\"]]\n",
    "    targets = [\"SQLite: \\n\" + q for q in examples[\"sql_query\"]]\n",
    "\n",
    "    print(inputs[0])\n",
    "    print(targets[0])\n",
    "\n",
    "    model_inputs = tokenizer(inputs, padding=\"max_length\", truncation=True, max_length=256)\n",
    "    labels = tokenizer(targets, padding=\"max_length\", truncation=True, max_length=256)\n",
    "\n",
    "    model_inputs[\"labels\"] = labels[\"input_ids\"]\n",
    "    return model_inputs\n",
    "\n",
    "# Convert to Hugging Face Dataset\n",
    "dataset = Dataset.from_pandas(df)\n",
    "\n",
    "# Apply tokenization\n",
    "tokenized_dataset = dataset.map(preprocess_function, batched=True)\n",
    "\n",
    "# Split into train/validation\n",
    "split = int(0.9 * len(tokenized_dataset))  # 90% train, 10% validation\n",
    "train_dataset = tokenized_dataset.select(range(split))\n",
    "val_dataset = tokenized_dataset.select(range(split, len(tokenized_dataset)))\n",
    "\n",
    "print(len(train_dataset))\n",
    "print(len(val_dataset))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load model and define training arguments"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "trainable params: 12,582,912 || all params: 1,359,054,848 || trainable%: 0.9259\n"
     ]
    }
   ],
   "source": [
    "# Enable 8-bit quantization for lower memory usage\n",
    "bnb_config = BitsAndBytesConfig(\n",
    "    load_in_8bit=True, \n",
    "    bnb_8bit_compute_dtype=torch.float16\n",
    ")\n",
    "\n",
    "# Load model with quantization\n",
    "#device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n",
    "device_name = 'cuda:0' if torch.cuda.is_available() else 'cpu'\n",
    "device = torch.device(device_name)\n",
    "model = AutoModelForCausalLM.from_pretrained(\n",
    "    model_name, \n",
    "    quantization_config=bnb_config,\n",
    "    device_map=device\n",
    ")\n",
    "model.generation_config.pad_token_id = tokenizer.pad_token_id\n",
    "\n",
    "# Define LoRA configuration\n",
    "lora_config = LoraConfig(\n",
    "    r=32,  # Rank of LoRA matrices (adjust for memory vs. accuracy)\n",
    "    lora_alpha=32,  # Scaling factor\n",
    "    lora_dropout=0.1,  # Dropout for regularization\n",
    "    bias=\"none\",\n",
    "    task_type=TaskType.CAUSAL_LM,\n",
    "    target_modules=[\n",
    "        \"q_proj\",\n",
    "        \"k_proj\",\n",
    "        \"v_proj\",\n",
    "        \"o_proj\"\n",
    "    ]\n",
    ")\n",
    "\n",
    "# Wrap model with LoRA adapters\n",
    "model = get_peft_model(model, lora_config)\n",
    "model = model.to(device)\n",
    "model.print_trainable_parameters()  # Show trainable parameters count"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup model trainer"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Dean\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\transformers\\training_args.py:1611: FutureWarning: `evaluation_strategy` is deprecated and will be removed in version 4.46 of 🤗 Transformers. Use `eval_strategy` instead\n",
      "  warnings.warn(\n",
      "C:\\Users\\Dean\\AppData\\Local\\Temp\\ipykernel_20424\\92099500.py:20: FutureWarning: `tokenizer` is deprecated and will be removed in version 5.0.0 for `Trainer.__init__`. Use `processing_class` instead.\n",
      "  trainer = Trainer(\n",
      "No label_names provided for model class `PeftModelForCausalLM`. Since `PeftModel` hides base models input arguments, if label_names is not given, label_names can't be set automatically within `Trainer`. Note that empty label_names list will be used instead.\n"
     ]
    }
   ],
   "source": [
    "training_args = TrainingArguments(\n",
    "    output_dir=\"./fine-tuned-model\",\n",
    "    evaluation_strategy=\"epoch\",  # Evaluate at the end of each epoch\n",
    "    save_strategy=\"epoch\",  # Save model every epoch\n",
    "    per_device_train_batch_size=16,  # LoRA allows higher batch size\n",
    "    per_device_eval_batch_size=16,\n",
    "    num_train_epochs=50,  # Increase if needed\n",
    "    learning_rate=4e-5,  # Higher LR since we're only training LoRA layers\n",
    "    weight_decay=0.01,\n",
    "    logging_steps=50,  # Print loss every 50 steps\n",
    "    save_total_limit=2,  # Keep last 4 checkpoints\n",
    "    fp16=True if torch.cuda.is_available() else False,\n",
    "    push_to_hub=False,\n",
    "    load_best_model_at_end=True,\n",
    "    metric_for_best_model=\"eval_loss\",\n",
    "    greater_is_better=False\n",
    ")\n",
    "\n",
    "# Trainer setup\n",
    "trainer = Trainer(\n",
    "    model=model,\n",
    "    args=training_args,\n",
    "    train_dataset=train_dataset,\n",
    "    eval_dataset=val_dataset,\n",
    "    tokenizer=tokenizer,\n",
    "    callbacks=[EarlyStoppingCallback(early_stopping_patience=2)]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Run fine-tuning and save model weights when complete"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Dean\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\transformers\\integrations\\sdpa_attention.py:54: UserWarning: 1Torch was not compiled with flash attention. (Triggered internally at C:\\actions-runner\\_work\\pytorch\\pytorch\\builder\\windows\\pytorch\\aten\\src\\ATen\\native\\transformers\\cuda\\sdp_utils.cpp:555.)\n",
      "  attn_output = torch.nn.functional.scaled_dot_product_attention(\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "\n",
       "    <div>\n",
       "      \n",
       "      <progress value='708' max='2950' style='width:300px; height:20px; vertical-align: middle;'></progress>\n",
       "      [ 708/2950 2:25:12 < 7:41:08, 0.08 it/s, Epoch 12/50]\n",
       "    </div>\n",
       "    <table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       " <tr style=\"text-align: left;\">\n",
       "      <th>Epoch</th>\n",
       "      <th>Training Loss</th>\n",
       "      <th>Validation Loss</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <td>1</td>\n",
       "      <td>9.571600</td>\n",
       "      <td>1.583262</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>2</td>\n",
       "      <td>1.746600</td>\n",
       "      <td>1.167971</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>3</td>\n",
       "      <td>1.517300</td>\n",
       "      <td>1.093727</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>4</td>\n",
       "      <td>1.423300</td>\n",
       "      <td>1.038791</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>5</td>\n",
       "      <td>1.304400</td>\n",
       "      <td>1.066154</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>6</td>\n",
       "      <td>1.283900</td>\n",
       "      <td>0.989451</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>7</td>\n",
       "      <td>1.248500</td>\n",
       "      <td>0.981647</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>8</td>\n",
       "      <td>1.242600</td>\n",
       "      <td>1.007480</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>9</td>\n",
       "      <td>1.290300</td>\n",
       "      <td>0.970018</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>10</td>\n",
       "      <td>1.258800</td>\n",
       "      <td>0.958510</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>11</td>\n",
       "      <td>1.217200</td>\n",
       "      <td>1.017668</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <td>12</td>\n",
       "      <td>1.242000</td>\n",
       "      <td>0.961481</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table><p>"
      ],
      "text/plain": [
       "<IPython.core.display.HTML object>"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Dean\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\peft\\tuners\\lora\\bnb.py:85: UserWarning: Merge lora module to 8-bit linear may get different generations due to rounding errors.\n",
      "  warnings.warn(\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "('./fine-tuned-model\\\\tokenizer_config.json',\n",
       " './fine-tuned-model\\\\special_tokens_map.json',\n",
       " './fine-tuned-model\\\\tokenizer.json')"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# Run training\n",
    "trainer.train()\n",
    "\n",
    "# Merge LoRA adapters with the base model before saving\n",
    "model = model.merge_and_unload()\n",
    "model.save_pretrained(\"./fine-tuned-model\")\n",
    "tokenizer.save_pretrained(\"./fine-tuned-model\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Try inference using fine-tuned model"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "c:\\Users\\Dean\\AppData\\Local\\Programs\\Python\\Python312\\Lib\\site-packages\\bitsandbytes\\autograd\\_functions.py:315: UserWarning: MatMul8bitLt: inputs will be cast from torch.bfloat16 to float16 during quantization\n",
      "  warnings.warn(f\"MatMul8bitLt: inputs will be cast from {A.dtype} to float16 during quantization\")\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated SQL: SQLite: SELECT AVG(pts_home) FROM game WHERE team_name_home = 'Los Angeles Lakers';\n",
      "\n"
     ]
    }
   ],
   "source": [
    "model = AutoModelForCausalLM.from_pretrained(\"./fine-tuned-model\", torch_dtype=torch.bfloat16, device_map=device)\n",
    "tokenizer = AutoTokenizer.from_pretrained(\"./fine-tuned-model\")\n",
    "\n",
    "# Prepare query with the same prompt\n",
    "input_text = \"How many points to the Los Angeles Lakers average at home?\"\n",
    "message = [{'role': 'user', 'content': input_prompt + input_text}]\n",
    "inputs = tokenizer.apply_chat_template(message, add_generation_prompt=True, return_tensors=\"pt\").to(model.device)\n",
    "\n",
    "# Generate SQL query\n",
    "outputs = model.generate(inputs, max_new_tokens=256, do_sample=False)\n",
    "query_output = tokenizer.decode(outputs[0][len(inputs[0]):], skip_special_tokens=True)\n",
    "\n",
    "print(\"Generated SQL:\", query_output)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.12.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}