File size: 50,595 Bytes
c557c8e
 
 
 
 
 
 
 
 
 
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
 
 
 
c557c8e
 
 
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
 
c557c8e
7d44fe9
 
c557c8e
7d44fe9
 
c557c8e
7d44fe9
 
 
 
 
c557c8e
 
7d44fe9
 
 
 
 
 
 
c557c8e
7d44fe9
 
c557c8e
 
7d44fe9
 
 
c557c8e
7d44fe9
c557c8e
7d44fe9
 
c557c8e
 
 
7d44fe9
 
c557c8e
7d44fe9
 
c557c8e
7d44fe9
 
c557c8e
7d44fe9
 
 
 
 
 
 
c557c8e
7d44fe9
 
c557c8e
7d44fe9
 
c557c8e
7d44fe9
c557c8e
 
7d44fe9
 
c557c8e
 
 
7d44fe9
c557c8e
7d44fe9
 
 
 
 
 
 
c557c8e
7d44fe9
c557c8e
7d44fe9
 
 
 
 
 
c557c8e
7d44fe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c557c8e
7d44fe9
 
 
c557c8e
7d44fe9
 
 
 
 
c557c8e
 
7d44fe9
 
c557c8e
7d44fe9
 
c557c8e
7d44fe9
c557c8e
 
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
 
c557c8e
 
7d44fe9
c557c8e
7d44fe9
c557c8e
 
7d44fe9
c557c8e
7d44fe9
 
c557c8e
7d44fe9
 
 
c557c8e
7d44fe9
 
 
 
 
c557c8e
7d44fe9
 
 
 
 
 
 
 
c557c8e
7d44fe9
 
c557c8e
 
 
 
7d44fe9
 
 
 
 
c557c8e
7d44fe9
c557c8e
 
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
 
 
 
 
c557c8e
 
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
 
7d44fe9
 
 
c557c8e
7d44fe9
 
 
 
 
 
 
 
c557c8e
 
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
c557c8e
7d44fe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c557c8e
7d44fe9
c557c8e
7d44fe9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
---
library_name: transformers
tags: []
---

# Model Card for Model ID

<!-- Provide a quick summary of what the model is/does. -->


In this repositoty we fine tuned Llava [link](https://huggingface.co/llava-hf/llava-v1.6-mistral-7b-hf)

LLaVA (Large Language and Vision Assistant) models are a type of artificial intelligence that combines language understanding with visual perception. These models are designed to process and understand both text and images, allowing them to perform tasks that require interpreting visual information and responding in natural language.

Key features of LLaVA models include:

1. Multimodal capabilities: They can analyze images and respond to questions or prompts about them in natural language.

2. Visual grounding: LLaVA models can connect language concepts to visual elements in images.

3. Task versatility: They can be used for various tasks like visual question answering, image captioning, and visual reasoning.

4. Foundation model integration: LLaVA builds upon large language models, extending their capabilities to include visual understanding.

LLaVA models represent an important step in developing AI systems that can interact with the world more comprehensively, bridging the gap between language and visual perception.

Would you like me to elaborate on any specific aspect of LLaVA models, such as their architecture, training process, or potential applications?

## what do you find in this README?
1. how to use this fine tuned model
2. how I trained the Llave model of the dataset
3. how I tested it locally and pushed it into huggingface



## Dataset

The dataset that we consider to fine tune themodel is [link](https://huggingface.co/datasets/naver-clova-ix/cord-v1)"naver-clova-ix/cord-v1" that you can find it in the dataset huggingface.

# 1. How to use the fine tunned model
```python

from transformers import AutoProcessor, BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

import sys
import os

import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np


def setting_directory(depth):
    current_dir = os.path.abspath(os.getcwd())
    root_dir = current_dir
    for i in range(depth):
        root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
        sys.path.append(os.path.dirname(root_dir))
    return root_dir

root_dir = setting_directory(1)
epochs = 100


model_name = "Ali-Forootani/llava-v1.6-mistral-7b-hf_100epochs_fine_tune"
processor = AutoProcessor.from_pretrained(model_name)
model = LlavaNextForConditionalGeneration.from_pretrained(model_name)

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

model.eval()
model = model.to(device)



from datasets import load_dataset
dataset = load_dataset("naver-clova-ix/cord-v2")

#You can save the model in the local directory as well
dataset.save_to_disk("/data/bio-eng-llm/llm_repo/naver-clova-ix/cord-v2")

test_example = dataset["test"][3]
test_image = test_example["image"]

MAX_LENGTH = 256  # or any other suitable value
#prepare image and prompt for the model
#To do this can be replaced by apply_chat_template when the processor supports this
prompt = f"[INST] <image>\nExtract JSON [\INST]"
inputs = processor(text=prompt, images=[test_image], return_tensors="pt").to("cuda")
for k,v in inputs.items():
    print(k,v.shape)

# Generate token IDs
generated_ids = model.generate(**inputs, max_new_tokens=MAX_LENGTH)

# Decode back into text
generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

print(generated_texts)


#######################################
####################################### You can make the output nicer



import re

# let's turn that into JSON
def token2json(tokens, is_inner_value=False, added_vocab=None):
        """
        Convert a (generated) token sequence into an ordered JSON format.
        """
        if added_vocab is None:
            added_vocab = processor.tokenizer.get_added_vocab()

        output = {}

        while tokens:
            start_token = re.search(r"<s_(.*?)>", tokens, re.IGNORECASE)
            if start_token is None:
                break
            key = start_token.group(1)
            key_escaped = re.escape(key)

            end_token = re.search(rf"</s_{key_escaped}>", tokens, re.IGNORECASE)
            start_token = start_token.group()
            if end_token is None:
                tokens = tokens.replace(start_token, "")
            else:
                end_token = end_token.group()
                start_token_escaped = re.escape(start_token)
                end_token_escaped = re.escape(end_token)
                content = re.search(
                    f"{start_token_escaped}(.*?){end_token_escaped}", tokens, re.IGNORECASE | re.DOTALL
                )
                if content is not None:
                    content = content.group(1).strip()
                    if r"<s_" in content and r"</s_" in content:  # non-leaf node
                        value = token2json(content, is_inner_value=True, added_vocab=added_vocab)
                        if value:
                            if len(value) == 1:
                                value = value[0]
                            output[key] = value
                    else:  # leaf nodes
                        output[key] = []
                        for leaf in content.split(r"<sep/>"):
                            leaf = leaf.strip()
                            if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
                                leaf = leaf[1:-2]  # for categorical special tokens
                            output[key].append(leaf)
                        if len(output[key]) == 1:
                            output[key] = output[key][0]

                tokens = tokens[tokens.find(end_token) + len(end_token) :].strip()
                if tokens[:6] == r"<sep/>":  # non-leaf nodes
                    return [output] + token2json(tokens[6:], is_inner_value=True, added_vocab=added_vocab)

        if len(output):
            return [output] if is_inner_value else output
        else:
            return [] if is_inner_value else {"text_sequence": tokens}
        


generated_json = token2json(generated_texts[0])
print(generated_json)

for key, value in generated_json.items():
    print(key, value)

```


# 2. How to fine-tune LLaVa for document parsing (PDF -> JSON)

In this notebook, we are going to fine-tune the [LLaVa](https://huggingface.co/docs/transformers/main/en/model_doc/llava) model for a document AI use case. LLaVa is one of the better open-source multimodal models at the time of writing (there's already a successor called [LLaVa-NeXT](https://huggingface.co/docs/transformers/main/en/model_doc/llava_next)). As we'll see, fine-tuning these various models is pretty similar as their API is mostly the same.

The goal for the model in this notebook is to generate a JSON that contains key fields (like food items and their corresponding prices) from receipts. We will fine-tune LLaVa on the [CORD](https://huggingface.co/datasets/naver-clova-ix/cord-v2) dataset, which contains (receipt image, ground truth JSON) pairs.

Sources:

* LLaVa [documentation](https://huggingface.co/docs/transformers/main/en/model_doc/llava)
* LLaVa [models on the hub](https://huggingface.co/llava-hf)


## Define variables and importing moduls

We'll first set some variables useful througout this tutorial.


```python

from transformers import AutoProcessor, BitsAndBytesConfig, LlavaNextForConditionalGeneration
from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model

import torch
import sys
import os

import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np

# if you would like to set the directory you can use this piece of code
def setting_directory(depth):
    current_dir = os.path.abspath(os.getcwd())
    root_dir = current_dir
    for i in range(depth):
        root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
        sys.path.append(os.path.dirname(root_dir))
    return root_dir

root_dir = setting_directory(1)
epochs = 100




import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np

##############################


MAX_LENGTH = 256

# MODEL_ID = "llava-hf/llava-v1.6-mistral-7b-hf"

MODEL_ID = "/data/bio-eng-llm/llm_repo/llava-hf/llava-v1.6-mistral-7b-hf"
REPO_ID = "YOUR-HUB-REPO-TO-PUSH"
WANDB_PROJECT = "LLaVaNeXT"
WANDB_NAME = "llava-next-demo-cord"
```


## Load dataset

Let's start by loading the dataset from the hub. Here we use the [CORD](https://huggingface.co/datasets/naver-clova-ix/cord-v2) dataset, created by the [Donut](https://huggingface.co/docs/transformers/en/model_doc/donut) authors (Donut is another powerful - but slightly undertrained document AI model available in the Transformers library). CORD is an important benchmark for receipt understanding. The Donut authors have prepared it in a format that suits vision-language models: we're going to fine-tune it to generate the JSON given the image.

If you want to load your own custom dataset, check out this guide: https://huggingface.co/docs/datasets/image_dataset.


```python
from datasets import load_dataset
dataset = load_dataset("naver-clova-ix/cord-v2")

#see one image as an example
example = dataset['train'][0]
image = example["image"]
# resize image for smaller displaying
width, height = image.size
image = image.resize((int(0.3*width), int(0.3*height)))
print(image)
```


## Load processor

Next, we'll load the processor which is used to prepare the data in the format that the model expects. Neural networks like LLaVa don't directly take images and text as input, but rather `pixel_values` (which is a resized, rescaled, normalized and optionally splitted version of the receipt images), `input_ids` (which are text token indices in the vocabulary of the model), etc. This is handled by the processor.

### Image resolution

The image resolution at which multimodal models are trained greatly has an impact on performance. One of the shortcomings of LLaVa is that it uses a fairly low image resolution (336x336). Newer models like LLaVa-NeXT and Idefics2 use a much higher image resolution enabling the model to "see" a lot more details in the image (which improves its OCR performance among other things). On the other hand, using a bigger image resolution comes at a cost of much higher memory requirements and longer training times. This is less of an issue with LLaVa due to its relatively small image resolution.

## Load model

Next, we're going to load the LLaVa model from the [hub](https://huggingface.co/llava-hf/llava-1.5-7b-hf). This is a model with about 7 billion trainable parameters (as it combines a LLaMa-7B language model with a relatively low-parameter vision encoder). Do note that we load a model here which already has undergone supervised fine-tuning (SFT) on the [LLaVa-Instruct-150K](https://huggingface.co/datasets/liuhaotian/LLaVA-Instruct-150K) instruction dataset. We can benefit from the fine-tuning that the model already has undergone.

### Full fine-tuning, LoRa and Q-LoRa

As this model has 7 billion trainable parameters, that's going to have quite an impact on the amount of memory used. For reference, fine-tuning a model using the [AdamW optimizer](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html#torch.optim.AdamW) (which is often used to optimize neural networks) with mixed precision, you need about 18 times the amount of parameters in GB of GPU RAM. So in this case, we would need 18x7 billion bytes = 126 GB of GPU RAM if we want to update all the parameters of the model!! That's huge right? And for most people infeasible.

Luckily, some clever people came up with the [LoRa](https://huggingface.co/docs/peft/main/en/conceptual_guides/lora) method (LoRa is short for low-rank adapation). It allows to just freeze the existing weights and only train a couple of adapter layers on top of the base model. Hugging Face offers the separate [PEFT library](https://huggingface.co/docs/peft/main/en/index) for easy use of LoRa, along with other Parameter-Efficient Fine-Tuning methods (that's where the name PEFT comes from).

Moreover, one can not only freeze the existing base model but also quantize it (which means, shrinking down its size). A neural network's parameters are typically saved in either float32 (which means, 32 bits or 4 bytes are used to store each parameter value) or float16 (which means, 16 bits or half a byte - also called half precision). However, with some clever algorithms one can shrink each parameter to just 8 or 4 bits (half a byte!), without significant effect on final performance. Read all about it here: https://huggingface.co/blog/4bit-transformers-bitsandbytes.

This means that we're going to shrink the size of the base Idefics2-8b model considerably using 4-bit quantization, and then only train a couple of adapter layers on top using LoRa (in float16). This idea of combining LoRa with quantization is called Q-LoRa and is the most memory friendly version.

Of course, if you have the memory available, feel free to use full fine-tuning or LoRa without quantization! In case of full fine-tuning, the code snippet below instantiates the model with Flash Attention which considerably speeds up computations.

There exist many forms of quantization, here we leverage the [BitsAndBytes](https://huggingface.co/docs/transformers/main_classes/quantization#transformers.BitsAndBytesConfig) integration.


```python

from transformers import BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

USE_LORA = False
USE_QLORA = True


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


## Load model

# Three options for training, from the lowest precision training to the highest precision training:
# - QLora
# - Standard Lora
# - Full fine-tuning
if USE_QLORA or USE_LORA:
    if USE_QLORA:
        bnb_config = BitsAndBytesConfig(
            load_in_4bit= True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, device = device,
        )
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        quantization_config=bnb_config,
    )
else:
    # for full fine-tuning, we can speed up the model using Flash Attention
    # only available on certain devices, see https://github.com/Dao-AILab/flash-attention?tab=readme-ov-file#installation-and-features
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        _attn_implementation="flash_attention_2",
    )

```

## Apply PEFT

After loading the base model, we're going to add LoRa adapter layers. We're going to only train these adapter layers (the base model is kept frozen).

The difference here with other models are the layers at which we're going to add adapters (in PEFT this is called `target_modules`). This typically depends a bit on the model.

Here, I based myself off the original `find_all_linear_names` [function](https://github.com/haotian-liu/LLaVA/blob/ec3a32ddea47d8739cb6523fb2661b635c15827e/llava/train/train.py#L169) found in the original LLaVa repository. It means that we're going to add adapters to all linear layers of the model (`nn.Linear`), except for the ones present in the vision encoder and multimodal projector.
This means that we're mostly going to adapt the language model part of LLaVa for our use case.


```python
from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model


def find_all_linear_names(model):
    cls = torch.nn.Linear
    lora_module_names = set()
    multimodal_keywords = ['multi_modal_projector', 'vision_model']
    for name, module in model.named_modules():
        if any(mm_keyword in name for mm_keyword in multimodal_keywords):
            continue
        if isinstance(module, cls):
            names = name.split('.')
            lora_module_names.add(names[0] if len(names) == 1 else names[-1])

    if 'lm_head' in lora_module_names: # needed for 16-bit
        lora_module_names.remove('lm_head')
    return list(lora_module_names)


lora_config = LoraConfig(
    r=8,
    lora_alpha=8,
    lora_dropout=0.1,
    target_modules=find_all_linear_names(model),
    init_lora_weights="gaussian",
)

model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, lora_config)
```

## Create PyTorch dataset

Next we'll create a regular [PyTorch dataset](https://pytorch.org/tutorials/beginner/basics/data_tutorial.html) which defines the individual items of the dataset. For that, one needs to implement 3 methods: an `init` method, a `len` method (which returns the length of the dataset) and a `getitem` method (which returns items of the dataset).

The `init` method goes over all the ground truth JSON sequences and turns them into token sequences (which we want the model to generate) using the `json2token` method. Unlike in my Donut and Idefics2 notebooks, we're not going to add special tokens to the model's vocabulary to omit complexity. Feel free to check them out, I haven't ablated whether adding special tokens gives a big boost in performance.

Typically, one uses the processor in the `getitem` method to prepare the data in the format that the model expects, but we'll postpone that here for a reason we'll explain later. In our case we're just going to return 2 things: the image and a corresponding ground truth token sequence.




```python
from torch.utils.data import Dataset
from typing import Any, Dict
import random

class LlavaDataset(Dataset):
    """
    PyTorch Dataset for LLaVa. This class takes a HuggingFace Dataset as input.

    Each row, consists of image path(png/jpg/jpeg) and ground truth data (json/jsonl/txt).
    """

    def __init__(
        self,
        dataset_name_or_path: str,
        split: str = "train",
        sort_json_key: bool = True,
    ):
        super().__init__()

        self.split = split
        self.sort_json_key = sort_json_key

        self.dataset = load_dataset(dataset_name_or_path, split=self.split)
        self.dataset_length = len(self.dataset)

        self.gt_token_sequences = []
        for sample in self.dataset:
            ground_truth = json.loads(sample["ground_truth"])
            if "gt_parses" in ground_truth:  # when multiple ground truths are available, e.g., docvqa
                assert isinstance(ground_truth["gt_parses"], list)
                gt_jsons = ground_truth["gt_parses"]
            else:
                assert "gt_parse" in ground_truth and isinstance(ground_truth["gt_parse"], dict)
                gt_jsons = [ground_truth["gt_parse"]]

            self.gt_token_sequences.append(
                [
                    self.json2token(
                        gt_json,
                        sort_json_key=self.sort_json_key,
                    )
                    for gt_json in gt_jsons  # load json from list of json
                ]
            )

    def json2token(self, obj: Any, sort_json_key: bool = True):
        """
        Convert an ordered JSON object into a token sequence
        """
        if type(obj) == dict:
            if len(obj) == 1 and "text_sequence" in obj:
                return obj["text_sequence"]
            else:
                output = ""
                if sort_json_key:
                    keys = sorted(obj.keys(), reverse=True)
                else:
                    keys = obj.keys()
                for k in keys:
                    output += (
                        fr"<s_{k}>"
                        + self.json2token(obj[k], sort_json_key)
                        + fr"</s_{k}>"
                    )
                return output
        elif type(obj) == list:
            return r"<sep/>".join(
                [self.json2token(item, sort_json_key) for item in obj]
            )
        else:
            obj = str(obj)
            return obj

    def __len__(self) -> int:
        return self.dataset_length

    def __getitem__(self, idx: int) -> Dict:
        """
        Returns one item of the dataset.

        Returns:
            image : the original Receipt image
            target_sequence : tokenized ground truth sequence
        """
        sample = self.dataset[idx]

        # inputs
        image = sample["image"]
        target_sequence = random.choice(self.gt_token_sequences[idx])  # can be more than one, e.g., DocVQA Task 1

        return image, target_sequence

########################################

##################### If you want to choose a few number of dataset!  ##################
class LlavaDataset2(Dataset):
    """
    PyTorch Dataset for LLaVa. This class takes a HuggingFace Dataset as input.

    Each row, consists of image path(png/jpg/jpeg) and ground truth data (json/jsonl/txt).
    """

    def __init__(
        self,
        dataset_name_or_path: str,
        split: str = "train",
        sort_json_key: bool = True,
        num_samples: int = None
    ):
        super().__init__()

        self.split = split
        self.sort_json_key = sort_json_key

        self.dataset = load_dataset(dataset_name_or_path, split=self.split)
        self.dataset_length = len(self.dataset)

        # If num_samples is specified and is less than the dataset length, select a subset
        if num_samples is not None and num_samples < self.dataset_length:
            indices = random.sample(range(self.dataset_length), num_samples)
            self.dataset = self.dataset.select(indices)
            self.dataset_length = num_samples

        self.gt_token_sequences = []
        for sample in self.dataset:
            ground_truth = json.loads(sample["ground_truth"])
            if "gt_parses" in ground_truth:  # when multiple ground truths are available, e.g., docvqa
                assert isinstance(ground_truth["gt_parses"], list)
                gt_jsons = ground_truth["gt_parses"]
            else:
                assert "gt_parse" in ground_truth and isinstance(ground_truth["gt_parse"], dict)
                gt_jsons = [ground_truth["gt_parse"]]

            self.gt_token_sequences.append(
                [
                    self.json2token(
                        gt_json,
                        sort_json_key=self.sort_json_key,
                    )
                    for gt_json in gt_jsons  # load json from list of json
                ]
            )

    def json2token(self, obj: Any, sort_json_key: bool = True):
        """
        Convert an ordered JSON object into a token sequence
        """
        if isinstance(obj, dict):
            if len(obj) == 1 and "text_sequence" in obj:
                return obj["text_sequence"]
            else:
                output = ""
                keys = sorted(obj.keys(), reverse=True) if sort_json_key else obj.keys()
                for k in keys:
                    output += (
                        fr"<s_{k}>"
                        + self.json2token(obj[k], sort_json_key)
                        + fr"</s_{k}>"
                    )
                return output
        elif isinstance(obj, list):
            return r"<sep/>".join(
                [self.json2token(item, sort_json_key) for item in obj]
            )
        else:
            return str(obj)

    def __len__(self) -> int:
        return self.dataset_length

    def __getitem__(self, idx: int) -> Dict:
        """
        Returns one item of the dataset.

        Returns:
            image : the original Receipt image
            target_sequence : tokenized ground truth sequence
        """
        sample = self.dataset[idx]

        # inputs
        image = sample["image"]
        target_sequence = random.choice(self.gt_token_sequences[idx])  # can be more than one, e.g., DocVQA Task 1

        return image, target_sequence



train_dataset = LlavaDataset2("naver-clova-ix/cord-v2",  split="train",
                                sort_json_key=False,
                                num_samples=100
                                )

val_dataset = LlavaDataset2("naver-clova-ix/cord-v2", split="validation",
                            sort_json_key=False,
                            num_samples=100
                            )

########################################



train_dataset = LlavaDataset("naver-clova-ix/cord-v2",  split="train", sort_json_key=False)
val_dataset = LlavaDataset("naver-clova-ix/cord-v2", split="validation", sort_json_key=False)



train_example = train_dataset[0]
image, target_sequence = train_example
print(target_sequence)
```


## Define collate functions

Now that we have PyTorch datasets, we'll define a so-called collators which define how items of the dataset should be batched together. This is because we typically train neural networks on batches of data (i.e. various images/target sequences combined) rather than one-by-one, using a variant of stochastic-gradient descent or SGD (like Adam, AdamW, etc.).

It's only here that we're going to use the processor to turn the (image, target token sequence) into the format that the model expects (which is `pixel_values`, `input_ids` etc.). The reason we do that here is because it allows for **dynamic padding** of the batches: each batch contains ground truth sequences of varying lengths. By only using the processor here, we will pad the `input_ids` up to the largest sequence in the batch.

We also decide to limit the length of the text tokens (`input_ids`) to a max length due to memory constraints, feel free to expand if your target token sequences are longer (I'd recommend plotting the average token length of your dataset to determine the optimal value).

The formatting of the `input_ids` is super important: we need to respect a so-called [chat template](https://huggingface.co/docs/transformers/main/en/chat_templating). As of now, LLaVa does not yet support chat templates, so we manually write down the prompt in the correct format (which starts with USER and ends with ASSISTANT). I'll update my notebook when it is supported. We use the text prompt "Extract JSON", this is just a deliberate choice, you could also omit this and just train the model on (image, JSON) pairs without text prompt.

Labels are created for the model by simply copying the inputs to the LLM (`input_ids`), but with padding tokens replaced by the ignore index of the loss function. This ensures that the model doesn't need to learn to predict padding tokens (used to batch examples together).

Why are the labels a copy of the model inputs, you may ask? The model will internally shift the labels one position to the right so that the model will learn to predict the next token. This can be seen [here](https://github.com/huggingface/transformers/blob/6f465d45d98f9eaeef83cfdfe79aecc7193b0f1f/src/transformers/models/idefics2/modeling_idefics2.py#L1851-L1855).

The collate function for evaluation is different, since there we only need to feed the prompt to the model, as we'll use the `generate()` method to autoregressively generate a completion.




```python
def train_collate_fn(examples):
    images = []
    texts = []
    for example in examples:
        image, ground_truth = example
        images.append(image)
        # TODO: in the future we can replace this by processor.apply_chat_template
        prompt = f"[INST] <image>\nExtract JSON [\INST] {ground_truth}"
        texts.append(prompt)

    batch = processor(text=texts, images=images, padding=True, truncation=True, max_length=MAX_LENGTH, return_tensors="pt")

    labels = batch["input_ids"].clone()
    labels[labels == processor.tokenizer.pad_token_id] = -100
    batch["labels"] = labels

    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    pixel_values = batch["pixel_values"]
    image_sizes = batch["image_sizes"]
    labels = batch["labels"]

    return input_ids, attention_mask, pixel_values, image_sizes, labels


def eval_collate_fn(examples):
    # we only feed the prompt to the model
    images = []
    texts = []
    answers = []
    for example in examples:
        image, ground_truth = example
        images.append(image)
        # TODO: in the future we can replace this by processor.apply_chat_template
        prompt = f"[INST] <image>\nExtract JSON [\INST]"
        texts.append(prompt)
        answers.append(ground_truth)

    batch = processor(text=texts, images=images, return_tensors="pt", padding=True)

    input_ids = batch["input_ids"]
    attention_mask = batch["attention_mask"]
    pixel_values = batch["pixel_values"]
    image_sizes = batch["image_sizes"]

    return input_ids, attention_mask, pixel_values, image_sizes, answers
```

## Define PyTorch LightningModule

There are various ways to train a PyTorch model: one could just use native PyTorch, use the [Trainer API](https://huggingface.co/docs/transformers/en/main_classes/trainer) or frameworks like [Accelerate](https://huggingface.co/docs/accelerate/en/index). In this notebook, I'll use PyTorch Lightning as it allows to easily compute evaluation metrics during training.

Below, we define a [LightningModule](https://lightning.ai/docs/pytorch/stable/common/lightning_module.html), which is the standard way to train a model in PyTorch Lightning. A LightningModule is an `nn.Module` with some additional functionality.

Basically, PyTorch Lightning will take care of all device placements (`.to(device)`) for us, as well as the backward pass, putting the model in training mode, etc.

Notice the difference between a training step and an evaluation step:

- a training step only consists of a forward pass, in which we compute the cross-entropy loss between the model's next token predictions and the ground truth (in parallel for all tokens, this technique is known as "teacher forcing"). The backward pass is handled by PyTorch Lightning.
- an evaluation step consists of making the model autoregressively complete the prompt using the [`generate()`](https://huggingface.co/docs/transformers/v4.40.1/en/main_classes/text_generation#transformers.GenerationMixin.generate) method. After that, we compute an evaluation metric between the predicted sequences and the ground truth ones. This allows us to see how the model is improving over the course of training. The metric we use here is the so-called [Levenhstein edit distance](https://en.wikipedia.org/wiki/Levenshtein_distance). This quantifies how much we would need to edit the predicted token sequence to get the target sequence (the fewer edits the better!). Its optimal value is 0 (which means, no edits need to be made).

Besides that, we define the optimizer to use ([AdamW](https://pytorch.org/docs/stable/generated/torch.optim.AdamW.html) is a good default choice) and the data loaders, which use the collate functions defined above to batch together items of the PyTorch datasets. Do note that AdamW is a pretty heavy optimizer in terms of memory requirements, but as we're training with QLoRa we only need to store optimizer states for the adapter layers. For full fine-tuning, one could take a look at more memory friendly optimizers such as [8-bit Adam](https://huggingface.co/docs/bitsandbytes/main/en/optimizers).


```python
import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np


class LlavaModelPLModule(L.LightningModule):
    def __init__(self, config, processor, model):
        super().__init__()
        self.config = config
        self.processor = processor
        self.model = model

        self.batch_size = config.get("batch_size")

    def training_step(self, batch, batch_idx):

        input_ids, attention_mask, pixel_values, image_sizes, labels = batch

        outputs = self.model(input_ids=input_ids,
                            attention_mask=attention_mask,
                            pixel_values=pixel_values,
                            image_sizes=image_sizes,
                            labels=labels
                          )
        loss = outputs.loss

        self.log("train_loss", loss)

        return loss

    def validation_step(self, batch, batch_idx, dataset_idx=0):

        input_ids, attention_mask, pixel_values, image_sizes, answers = batch

        # autoregressively generate token IDs
        generated_ids = self.model.generate(input_ids=input_ids, attention_mask=attention_mask,
                                       pixel_values=pixel_values, image_sizes=image_sizes, max_new_tokens=MAX_LENGTH)
        # turn them back into text, chopping of the prompt
        # important: we don't skip special tokens here, because we want to see them in the output
        predictions = self.processor.batch_decode(generated_ids[:, input_ids.size(1):], skip_special_tokens=True)

        scores = []
        for pred, answer in zip(predictions, answers):
            pred = re.sub(r"(?:(?<=>) | (?=</s_))", "", pred)
            scores.append(edit_distance(pred, answer) / max(len(pred), len(answer)))

            if self.config.get("verbose", False) and len(scores) == 1:
                print(f"Prediction: {pred}")
                print(f"    Answer: {answer}")
                print(f" Normed ED: {scores[0]}")

        self.log("val_edit_distance", np.mean(scores))

        return scores

    def configure_optimizers(self):
        # you could also add a learning rate scheduler if you want
        optimizer = torch.optim.AdamW(self.parameters(), lr=self.config.get("lr"))

        return optimizer

    def train_dataloader(self):
        return DataLoader(train_dataset, collate_fn=train_collate_fn, batch_size=self.batch_size, shuffle=True, num_workers=4)

    def val_dataloader(self):
        return DataLoader(val_dataset, collate_fn=eval_collate_fn, batch_size=self.batch_size, shuffle=False, num_workers=4)


epochs = 100


config = {"max_epochs": epochs ,
          # "val_check_interval": 0.2, # how many times we want to validate during an epoch
          "check_val_every_n_epoch": 1,
          "gradient_clip_val": 1.0,
          "accumulate_grad_batches": 8,
          "lr": 1e-4,
          "batch_size": 1,
          # "seed":2022,
          "num_nodes": 1,
          "warmup_steps": 50,
          "result_path": "./result",
          "verbose": True,
}

model_module = LlavaModelPLModule(config, processor, model)
```

## Define callbacks

Optionally, Lightning allows to define so-called [callbacks](https://lightning.ai/docs/pytorch/stable/extensions/callbacks.html), which are arbitrary pieces of code that can be executed during training.

Here I'm adding a `PushToHubCallback` which will push the model to the [hub](https://huggingface.co/) at the end of every epoch as well as at the end of training. Do note that you could of course also pass the `private=True` flag when pushing to the hub, if you wish to keep your model private. Hugging Face also offers the [Enterprise Hub](https://huggingface.co/enterprise) so that you can easily share models with your colleagues privately in a secure way.

We'll also use the EarlyStopping callback of Lightning, which will automatically stop training once the evaluation metric (edit distance in our case) doesn't improve after 3 epochs.


```python
from lightning.pytorch.callbacks import Callback
from lightning.pytorch.callbacks.early_stopping import EarlyStopping

from huggingface_hub import HfApi

api = HfApi()

class PushToHubCallback(Callback):
    def on_train_epoch_end(self, trainer, pl_module):
        print(f"Pushing model to the hub, epoch {trainer.current_epoch}")
        pl_module.model.push_to_hub(REPO_ID,
                                    commit_message=f"Training in progress, epoch {trainer.current_epoch}")

    def on_train_end(self, trainer, pl_module):
        print(f"Pushing model to the hub after training")
        pl_module.processor.push_to_hub(REPO_ID,
                                    commit_message=f"Training done")
        pl_module.model.push_to_hub(REPO_ID,
                                    commit_message=f"Training done")

early_stop_callback = EarlyStopping(monitor="val_edit_distance", patience=3, verbose=False, mode="min")
```

## Train!

Alright, we're set to start training! We will also pass the Weights and Biases logger so that we get see some pretty plots of our loss and evaluation metric during training (do note that you may need to log in the first time you run this, see the [docs](https://docs.wandb.ai/guides/integrations/lightning)).

Do note that this Trainer class supports many more flags! See the docs: https://lightning.ai/docs/pytorch/stable/api/lightning.pytorch.trainer.trainer.Trainer.html#lightning.pytorch.trainer.trainer.Trainer.


_hint_: you may track the training on wandb, but first you should create an account and login! then use it! I did not use it so I commented in the code!
```bash
pip install -U wandb>=0.12.10
```

```python
trainer = L.Trainer(
        accelerator="gpu",
        devices=[0],
        max_epochs=config.get("max_epochs"),
        accumulate_grad_batches=config.get("accumulate_grad_batches"),
        check_val_every_n_epoch=config.get("check_val_every_n_epoch"),
        gradient_clip_val=config.get("gradient_clip_val"),
        precision="16-mixed",
        limit_val_batches=5,
        num_sanity_val_steps=0,
        logger=None,
        #callbacks=[PushToHubCallback(), early_stop_callback],
)

trainer.fit(model_module)



##############################################
 
# You can save the model in your local directory as you wish
save_dir = root_dir + f"models/fine_tuned_models/llava-v1.6-mistral-7b-hf_{epochs}e_qa_qa"
#trainer.save_model(save_dir)

trainer.save_checkpoint(f"{save_dir}/checkpoint.ckpt")

print("Saved model to:", save_dir)

```
# 3. How to test the model locally by loading the saved checkpoint:

```python

from transformers import AutoProcessor, BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

import sys
import os

import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np


def setting_directory(depth):
    current_dir = os.path.abspath(os.getcwd())
    root_dir = current_dir
    for i in range(depth):
        root_dir = os.path.abspath(os.path.join(root_dir, os.pardir))
        sys.path.append(os.path.dirname(root_dir))
    return root_dir

root_dir = setting_directory(1)
epochs = 100




import lightning as L
from torch.utils.data import DataLoader
import re
from nltk import edit_distance
import numpy as np

##############################


MAX_LENGTH = 256

# MODEL_ID = "llava-hf/llava-v1.6-mistral-7b-hf"

MODEL_ID = "/data/bio-eng-llm/llm_repo/llava-hf/llava-v1.6-mistral-7b-hf"
REPO_ID = "YOUR-HUB-REPO-TO-PUSH"
WANDB_PROJECT = "LLaVaNeXT"
WANDB_NAME = "llava-next-demo-cord"


from transformers import AutoProcessor

processor = AutoProcessor.from_pretrained(MODEL_ID)
processor.tokenizer.padding_side = "right" # during training, one always uses padding on the right

from transformers import BitsAndBytesConfig, LlavaNextForConditionalGeneration
import torch

   
from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model


USE_LORA = False
USE_QLORA = True


device = torch.device("cuda" if torch.cuda.is_available() else "cpu")


## Load model

# Three options for training, from the lowest precision training to the highest precision training:
# - QLora
# - Standard Lora
# - Full fine-tuning
if USE_QLORA or USE_LORA:
    if USE_QLORA:
        bnb_config = BitsAndBytesConfig(
            load_in_4bit= True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.float16, device = device,
        )
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        quantization_config=bnb_config,
    )
else:
    # for full fine-tuning, we can speed up the model using Flash Attention
    # only available on certain devices, see https://github.com/Dao-AILab/flash-attention?tab=readme-ov-file#installation-and-features
    model = LlavaNextForConditionalGeneration.from_pretrained(
        MODEL_ID,
        torch_dtype=torch.float16,
        _attn_implementation="flash_attention_2",
    )


def find_all_linear_names(model):
    cls = torch.nn.Linear
    lora_module_names = set()
    multimodal_keywords = ['multi_modal_projector', 'vision_model']
    for name, module in model.named_modules():
        if any(mm_keyword in name for mm_keyword in multimodal_keywords):
            continue
        if isinstance(module, cls):
            names = name.split('.')
            lora_module_names.add(names[0] if len(names) == 1 else names[-1])

    if 'lm_head' in lora_module_names: # needed for 16-bit
        lora_module_names.remove('lm_head')
    return list(lora_module_names)


lora_config = LoraConfig(
    r=8,
    lora_alpha=8,
    lora_dropout=0.1,
    target_modules=find_all_linear_names(model),
    init_lora_weights="gaussian",
)


base_model = model

model = prepare_model_for_kbit_training(model)
model = get_peft_model(model, lora_config)


from peft import LoraConfig, prepare_model_for_kbit_training, get_peft_model





##############################


class LlavaModelPLModule(L.LightningModule):
    def __init__(self, config, processor, model):
        super().__init__()
        self.config = config
        self.processor = processor
        self.model = model

        self.batch_size = config.get("batch_size")

    def training_step(self, batch, batch_idx):

        input_ids, attention_mask, pixel_values, image_sizes, labels = batch

        outputs = self.model(input_ids=input_ids,
                            attention_mask=attention_mask,
                            pixel_values=pixel_values,
                            image_sizes=image_sizes,
                            labels=labels
                          )
        loss = outputs.loss

        self.log("train_loss", loss)

        return loss

    def validation_step(self, batch, batch_idx, dataset_idx=0):

        input_ids, attention_mask, pixel_values, image_sizes, answers = batch

        # autoregressively generate token IDs
        generated_ids = self.model.generate(input_ids=input_ids, attention_mask=attention_mask,
                                       pixel_values=pixel_values, image_sizes=image_sizes, max_new_tokens=MAX_LENGTH)
        # turn them back into text, chopping of the prompt
        # important: we don't skip special tokens here, because we want to see them in the output
        predictions = self.processor.batch_decode(generated_ids[:, input_ids.size(1):], skip_special_tokens=True)

        scores = []
        for pred, answer in zip(predictions, answers):
            pred = re.sub(r"(?:(?<=>) | (?=</s_))", "", pred)
            scores.append(edit_distance(pred, answer) / max(len(pred), len(answer)))

            if self.config.get("verbose", False) and len(scores) == 1:
                print(f"Prediction: {pred}")
                print(f"    Answer: {answer}")
                print(f" Normed ED: {scores[0]}")

        self.log("val_edit_distance", np.mean(scores))

        return scores

    def configure_optimizers(self):
        # you could also add a learning rate scheduler if you want
        optimizer = torch.optim.AdamW(self.parameters(), lr=self.config.get("lr"))

        return optimizer

    def train_dataloader(self):
        return DataLoader(train_dataset, collate_fn=train_collate_fn, batch_size=self.batch_size, shuffle=True, num_workers=4)

    def val_dataloader(self):
        return DataLoader(val_dataset, collate_fn=eval_collate_fn, batch_size=self.batch_size, shuffle=False, num_workers=4)


from pytorch_lightning import Trainer



config = {"max_epochs": epochs ,
          # "val_check_interval": 0.2, # how many times we want to validate during an epoch
          "check_val_every_n_epoch": 1,
          "gradient_clip_val": 1.0,
          "accumulate_grad_batches": 8,
          "lr": 1e-4,
          "batch_size": 1,
          # "seed":2022,
          "num_nodes": 1,
          "warmup_steps": 50,
          "result_path": "./result",
          "verbose": True,}




#model = LlavaModelPLModule(config, processor, model)



model_path = root_dir + f"/testing_eve_jobmodels/fine_tuned_models/llava-v1.6-mistral-7b-hf_{epochs}e_qa_qa"


#checkpoint = torch.load('model_path/checkpoint.ckpt')

"""
model = LlavaModelPLModule.load_from_checkpoint(f"{model_path}/checkpoint.ckpt",
                                                config,
                                                processor,
                                                model)
"""


#loading the model with the checkpoint!                                                

model = LlavaModelPLModule.load_from_checkpoint(
    f"{model_path}/checkpoint.ckpt",
    hparams_file=None,
    config=config,
    processor=processor,
    model= model
)



#model.load_state_dict(checkpoint['model_state_dict'])


print(model)


model.eval()


model = model.to(device)



from datasets import load_dataset

dataset = load_dataset("naver-clova-ix/cord-v2")


test_example = dataset["test"][3]
test_image = test_example["image"]


#prepare image and prompt for the model
#To do this can be replaced by apply_chat_template when the processor supports this
prompt = f"[INST] <image>\nExtract JSON [\INST]"
inputs = processor(text=prompt, images=[test_image], return_tensors="pt").to("cuda")
for k,v in inputs.items():
    print(k,v.shape)

# Generate token IDs
generated_ids = model.model.generate(**inputs, max_new_tokens=MAX_LENGTH)

# Decode back into text
generated_texts = processor.batch_decode(generated_ids, skip_special_tokens=True)

print(generated_texts)

#processor = AutoProcessor.from_pretrained(model_path)


import re

# let's turn that into JSON
def token2json(tokens, is_inner_value=False, added_vocab=None):
        """
        Convert a (generated) token sequence into an ordered JSON format.
        """
        if added_vocab is None:
            added_vocab = processor.tokenizer.get_added_vocab()

        output = {}

        while tokens:
            start_token = re.search(r"<s_(.*?)>", tokens, re.IGNORECASE)
            if start_token is None:
                break
            key = start_token.group(1)
            key_escaped = re.escape(key)

            end_token = re.search(rf"</s_{key_escaped}>", tokens, re.IGNORECASE)
            start_token = start_token.group()
            if end_token is None:
                tokens = tokens.replace(start_token, "")
            else:
                end_token = end_token.group()
                start_token_escaped = re.escape(start_token)
                end_token_escaped = re.escape(end_token)
                content = re.search(
                    f"{start_token_escaped}(.*?){end_token_escaped}", tokens, re.IGNORECASE | re.DOTALL
                )
                if content is not None:
                    content = content.group(1).strip()
                    if r"<s_" in content and r"</s_" in content:  # non-leaf node
                        value = token2json(content, is_inner_value=True, added_vocab=added_vocab)
                        if value:
                            if len(value) == 1:
                                value = value[0]
                            output[key] = value
                    else:  # leaf nodes
                        output[key] = []
                        for leaf in content.split(r"<sep/>"):
                            leaf = leaf.strip()
                            if leaf in added_vocab and leaf[0] == "<" and leaf[-2:] == "/>":
                                leaf = leaf[1:-2]  # for categorical special tokens
                            output[key].append(leaf)
                        if len(output[key]) == 1:
                            output[key] = output[key][0]

                tokens = tokens[tokens.find(end_token) + len(end_token) :].strip()
                if tokens[:6] == r"<sep/>":  # non-leaf nodes
                    return [output] + token2json(tokens[6:], is_inner_value=True, added_vocab=added_vocab)

        if len(output):
            return [output] if is_inner_value else output
        else:
            return [] if is_inner_value else {"text_sequence": tokens}
        


generated_json = token2json(generated_texts[0])
print(generated_json)

for key, value in generated_json.items():
    print(key, value)


###################################################################
###################################################################
###################################################################
""" 

# Pushing the model into the Huggingface hub

#Ali-Forootani/llava-v1.6-mistral-7b-hf_20epochs_fine_tune

# Specify the directory where the model and processor will be saved
model_save_path = model_path + "./saved_model"

# Save the processor
processor.save_pretrained(model_save_path)

# Save the model
model.model.save_pretrained(model_save_path)

from transformers import AutoProcessor, LlavaNextForConditionalGeneration

# Load the saved processor and model
processor = AutoProcessor.from_pretrained(model_save_path)
model = LlavaNextForConditionalGeneration.from_pretrained(model_save_path)

# Push the processor and model to the Hugging Face Hub
from huggingface_hub import HfApi, login
login(token="your_huggingface_token")
processor.push_to_hub("Ali-Forootani/llava-v1.6-mistral-7b-hf_100epochs_fine_tune", use_auth_token=True)
model.push_to_hub("Ali-Forootani/llava-v1.6-mistral-7b-hf_100epochs_fine_tune", use_auth_token=True)


from huggingface_hub import HfApi, login
from peft import LoraConfig, PeftModel, prepare_model_for_kbit_training

"""


#############################
############################# Second way to push to huggingface

from huggingface_hub import HfApi, login
# Login to Hugging Face
login(token="your_huggingface_token")

# Define your Hugging Face repository name
# repo_name = "Ali-Forootani/llava-v1.6-mistral-7b_fine_tune_20epochs"
repo_name = "Ali-Forootani/llava-v1.6-mistral-7b-hf_100epochs_fine_tune"

#######



# Save the model and processor locally model_path 
#output_dir = model_path + "/model_to_push"
#model.model.save_pretrained(output_dir)
#processor.save_pretrained(output_dir)

# Push to Hugging Face Hub
model.model.push_to_hub(repo_name, use_auth_token=True)
processor.push_to_hub(repo_name, use_auth_token=True)
```



[More Information Needed]