-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathscript.py
2046 lines (1560 loc) · 82.4 KB
/
script.py
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
import gradio as gr
import modules.shared as shared
from modules.extensions import apply_extensions
from modules.text_generation import encode, get_max_prompt_length
from modules.text_generation import generate_reply
from modules.text_generation import generate_reply_wrapper
from modules.text_generation import stop_everything_event
from modules.ui import list_interface_input_elements
from modules.ui import gather_interface_values
from modules.html_generator import generate_basic_html
from pathlib import Path
from modules.LoRA import add_lora_autogptq, add_lora_exllamav2
import re
import json
import os
from peft import PeftModel
from modules.models import reload_model
from modules.ui import create_refresh_button
import torch
try:
from peft.config import PeftConfig
print("NEW PEFT is installed")
except ImportError:
print("Error: you are using an old PEFT version. LORA merging will not work. You need to update to the latest version")
from peft.utils.config import PeftConfig
right_symbol = '\U000027A1'
left_symbol = '\U00002B05'
refresh_symbol = '\U0001f504' # 🔄
# Save the original method
#original_from_from_json_file = PeftConfig.from_pretrained
g_lora_multipolier = 1.0
g_print_twice = False
editing_type = ''
defaultTemp_keys = ['summary_turn', 'summary_include_turn', 'summary_include_turn2']
defaultTemp = {
"summary_turn":'<|user|> Summarise the following story:\\n\\n<|context|>\\n\\n<|bot|> Summary:\\n\\n',
"summary_include_turn":'STORY BACKGROUND\\n\\n<|summary|>\\n\\nSTORY\\n\\n',
"summary_include_turn2":'STORY BACKGROUND\\n\\n<|summary|>\\n\\n<|memory|>\\n\\nSTORY\\n\\n',
}
pastel_colors = [
"rgba(107,64,216,.3)",
"rgba(104,222,122,.4)",
"rgba(244,172,54,.4)",
"rgba(239,65,70,.4)",
"rgba(39,181,234,.4)",
]
selected_lora_main_sub =''
selected_lora_main =''
selected_lora_sub = ''
editing_note = False
renaming_note = False
g_original_lora_rank = 0
paraph_undo = ''
paraph_undoSEL = [0,0]
paraph_redo = ''
paraph_redoSEL = [0,0]
RED = "\033[91m"
YELLOW = "\033[93m"
GREEN = "\033[92m"
RESET = "\033[0m"
params = {
"display_name": "Playground",
"is_tab": True,
"usePR": False,
"pUSER": 'USER:',
"pBOT": 'ASSISTANT:',
"selectA": [0,0],
"selectB": [0,0],
"max_words": 0,
"memoryA": 'Bender\'s defining characteristic is his insatiable appetite for vices and mischief. He is often seen smoking cigars, drinking excessive amounts of alcohol (particularly Olde Fortran malt liquor), and engaging in various forms of unethical behavior. He is shamelessly dishonest, frequently stealing, scamming, and manipulating others for personal gain.',
"memoryB":'',
"memoryC":'',
"selectedMEM":'None',
"selectedSUM":'None',
"summary_turn":'',
"summary_include_turn":'',
"summary_include_turn2":'',
"text_Summary":'',
"paraph_templ_sel":'Basic',
"paraph_templ_text":'',
"paraph_temperament":'Strict',
"list_by_time":False,
"dyn_templ_sel": 'None',
"dyn_templ_text":'',
"combination_type":'linear'
}
file_nameJSON = "playground.json"
default_req_params = {
'max_new_tokens': 200,
'temperature': 0.7,
'top_p': 0.1,
'top_k': 40,
'repetition_penalty': 1.18,
'encoder_repetition_penalty': 1.0,
'suffix': None,
'stream': True,
'echo': False,
'seed': -1,
'truncation_length': 2048,
'add_bos_token': True,
'do_sample': True,
'typical_p': 1.0,
'epsilon_cutoff': 0, # In units of 1e-4
'eta_cutoff': 0, # In units of 1e-4
'tfs': 1.0,
'top_a': 0.0,
'min_length': 0,
'no_repeat_ngram_size': 0,
'num_beams': 1,
'penalty_alpha': 0.0,
'length_penalty': 1,
'early_stopping': False,
'mirostat_mode': 0,
'mirostat_tau': 5,
'mirostat_eta': 0.1,
'ban_eos_token': False,
'skip_special_tokens': True,
'custom_stopping_strings': '',
}
temeraments = ['Strict','Low','Moderate','Creative','Inventive','Crazy']
default_req_params_paraphrase = {}
default_req_params_paraphrase['Strict'] = {
'temperature': 0.7,
'top_p': 0.1,
'top_k': 40,
'repetition_penalty': 1.18
}
default_req_params_paraphrase['Low'] = {
'temperature': 0.1,
'top_p': 1.0,
'top_k': 0,
'repetition_penalty': 1.2,
}
"""default_req_params_paraphrase['Determined2'] = {
'temperature': 0.3,
'top_p': 0.75,
'top_k': 40,
'repetition_penalty': 1.2,
}
"""
default_req_params_paraphrase['Moderate'] = {
'temperature': 0.7,
'top_p': 0.5,
'top_k': 40,
'repetition_penalty': 1.2,
}
default_req_params_paraphrase['Creative'] = {
'temperature': 1.0,
'top_p': 0.4,
'top_k': 40,
'repetition_penalty': 1.2,
}
default_req_params_paraphrase['Inventive'] = {
'temperature': 1.1,
'top_p': 0.75,
'top_k': 40,
'repetition_penalty': 1.2,
}
default_req_params_paraphrase['Crazy'] = {
'temperature': 1.75,
'top_p': 0.6,
'top_k': 100,
'repetition_penalty': 1.2,
}
def atoi(text):
return int(text) if text.isdigit() else text.lower()
def natural_keys(text):
return [atoi(c) for c in re.split(r'(\d+)', text)]
def get_available_templates():
paths = (x for x in Path('extensions/Playground/Paraphrase').iterdir() if x.suffix in ('.txt'))
return ['None'] + sorted(set((k.stem for k in paths)), key=natural_keys)
def get_available_dyna_templates():
paths = (x for x in Path('extensions/Playground/Dmemory').iterdir() if x.suffix in ('.txt'))
return ['None'] + sorted(set((k.stem for k in paths)), key=natural_keys)
def get_file_path(folder, filename):
basepath = "extensions/Playground/"+folder
#print(f"Basepath: {basepath} and {filename}")
paths = (x for x in Path(basepath).iterdir() if x.suffix in ('.txt'))
for path in paths:
if path.stem.lower() == filename.lower():
return str(path)
return ""
def read_file_to_string(file_path):
data = ''
try:
with open(file_path, 'r') as file:
data = file.read()
except FileNotFoundError:
data = ''
return data
def save_string_to_file(file_path, string):
try:
with open(file_path, 'w') as file:
file.write(string)
print("String saved to file successfully.")
except Exception as e:
print("Error occurred while saving string to file:", str(e))
def load_Paraphrase_template(file):
global params
template = 'Paraphrase the following\n<|context|>'
path = get_file_path('Paraphrase',file)
if path:
print(f"Loading Paraphrase Template: {path}")
template = read_file_to_string(path)
params['paraph_templ_sel'] = file
params['paraph_templ_text'] = template
return template
def load_dynamemory_template(file):
global params
template = ''
path = get_file_path('Dmemory',file)
if path:
print(f"Loading Dynamic Memory: {path}")
template = read_file_to_string(path)
params['dyn_templ_sel'] = file
params['dyn_templ_text'] = template
return template,file
def save_dynamemory(DYNAMEMORY,DYNAMEMORY_filename):
if DYNAMEMORY_filename=='None' or DYNAMEMORY_filename=='':
print("File name can't be None")
else:
basepath = "extensions/Playground/Dmemory/"+DYNAMEMORY_filename+".txt"
save_string_to_file(basepath,DYNAMEMORY)
def get_last_line(string):
lines = string.splitlines()
if lines:
last_line = lines[-1]
return last_line
else:
return ""
def generate_prompt(string,summary):
global params
modified_string = string
addLineReply = ""
if params['usePR']:
if "---" in string:
lines = string.splitlines() # Split the text into lines
modified_string = ""
for i, line in enumerate(lines):
if addLineReply:
line.lstrip()
line = addLineReply + line
addLineReply = ""
elif line.startswith("---"):
line = line.replace("---", params['pUSER'])
addLineReply = params['pBOT']
modified_string = modified_string+ line +"\n"
if addLineReply:
modified_string = modified_string + addLineReply
dynamemory = ''
if params['dyn_templ_text']:
#dynamemory
pairs = parse_DYNAMEMORY(params['dyn_templ_text'])
for pair in pairs:
if pair["always"]:
# Always inject it.
dynamemory = dynamemory+ pair["memory"]+"\n"
else:
# Check to see if keywords are present.
keywords = pair["keywords"].lower().split(",")
user_input_lower = string.lower()
for keyword in keywords:
keywordsimp = keyword.strip()
if keywordsimp and keywordsimp in user_input_lower:
# keyword is present in user_input
dynamemory = dynamemory+ pair["memory"]+"\n"
if dynamemory:
modified_string = "# Memory: "+ dynamemory+modified_string
memory = ''
if params['selectedMEM']=='Memory A':
memory = params['memoryA']
elif params['selectedMEM']=='Memory B':
memory = params['memoryB']
elif params['selectedMEM']=='Memory C':
memory = params['memoryC']
if params['selectedSUM']!='None':
if memory:
promptSUM = params['summary_include_turn2'].replace('\\n', '\n')
promptSUM = promptSUM.replace('<|summary|>', summary)
promptSUM = promptSUM.replace('<|memory|>', memory)
else:
promptSUM = params['summary_include_turn'].replace('\\n', '\n')
promptSUM = promptSUM.replace('<|summary|>', summary)
modified_string = promptSUM+modified_string
else:
if memory:
modified_string = memory+'\n'+modified_string
return modified_string
# template = state['turn_template'].replace(r'\n', '\n')
#
def output_modifier(string):
#print(f"output_modifier: {string}")
return string
def copynote(string):
return string
def formatted_outputs(reply):
return reply, generate_basic_html(reply)
def generate_paraphrase(question, state,selectState,paraphrase, summary):
global params
global paraph_undo
global paraph_undoSEL
selF = params[selectState][0]
selT = params[selectState][1]
paraph_undo = question
if not selF==selT:
print(f"\033[1;32;1m\nGenerarting from selected text in {selectState} and inserting after {params[selectState]}\033[0;37;0m")
before = question[:selF]
current = question[selF:selT]
after = question[selT:]
else:
current = question
before = ""
after = ""
params[selectState]=[0,0]
print(f"\033[1;31;1m\nNo selection in {selectState}, reverting to full text Generate\033[0;37;0m")
summary_state = state.copy()
paraph_undoSEL[0] = params[selectState][0]
paraph_undoSEL[1] = params[selectState][1]
for key, value in default_req_params.items():
summary_state[key] = value # Update the value in 'summary_state' with the value from 'default_req_params
for key, value in default_req_params_paraphrase.items():
if params['paraph_temperament'] == key:
print(f"Temperament: {key}")
for key2, value2 in value.items():
print(f"{key2}:{value2}")
summary_state[key2] = value2 # Update the to paraphrase
break
params['paraph_templ_text'] = paraphrase
user = params['pUSER']
bot = params['pBOT']
prompt = params['paraph_templ_text']
prompt = prompt.replace('<|context|>', current)
prompt = prompt.replace('<|user|>', user)
prompt = prompt.replace('<|bot|>', bot)
prompt = prompt.replace('<|prevcontext|>', before)
prompt = prompt.replace('<|nextcontext|>', after)
#prompt = generate_prompt(prompt,summary)
for reply in generate_reply(prompt, summary_state, stopping_strings=None, is_chat=False):
params[selectState][1] = selF+len(reply)
reply = before+reply+after
yield formatted_outputs(reply)
def set_redo(txt):
global paraph_redo
global paraph_redoSEL
paraph_redoSEL[0] = params['selectA'][0]
paraph_redoSEL[1] = params['selectA'][1]
paraph_redo = txt
def paraphrase_undo():
global params
params['selectA'][0] = paraph_undoSEL[0]
params['selectA'][1] = paraph_undoSEL[1]
return paraph_undo
def paraphrase_redo():
global params
params['selectA'][0] = paraph_redoSEL[0]
params['selectA'][1] = paraph_redoSEL[1]
return paraph_redo
def generate_reply_wrapperMYSEL(question, state,selectState,summary):
global params
selF = params[selectState][0]
selT = params[selectState][1]
if not selF==selT:
print(f"\033[1;32;1m\nGenerarting from selected text in {selectState} and inserting after {params[selectState]}\033[0;37;0m")
params[selectState] = [0,0]
before = question[:selF]
current = question[selF:selT]
after = question[selT:]
else:
current = question
params[selectState] = [0,0]
before = ""
after = ""
print(f"\033[1;31;1m\nNo selection in {selectState}, reverting to full text Generate\033[0;37;0m")
# if use quick prompt, add \n if none
if params['usePR']:
if not current.endswith("\n"):
lastline = get_last_line(current)
if lastline.startswith("---"):
current+="\n"
prompt = generate_prompt(current,summary)
for reply in generate_reply(prompt, state, stopping_strings=None, is_chat=False):
if hasattr(shared, 'is_seq2seq') and not shared.is_seq2seq:
reply = current + reply
reply = before+reply+after
yield formatted_outputs(reply)
def generate_reply_wrapperMY(question, state, selectState,summary):
global params
params[selectState] = [0,0]
# if use quick prompt, add \n if none
max_words = int(params['max_words'])
prepend_str = ''
if max_words > 0:
print(f"\033[1;31;1m(Limiting memory to last {max_words} words)\033[0;37;0m")
words = question.split(' ') # Split the question into a list of words
limited_words = words[-max_words:] # Get the maximum number of last words
question = ' '.join(limited_words) # Join the limited words back into a string
prepend_str = ' '.join(words[:-max_words]) # Join the words before the maximum words
if prepend_str:
prepend_str = prepend_str+ ' '
if params['usePR']:
if not question.endswith("\n"):
lastline = get_last_line(question)
if lastline.startswith("---"):
question+="\n"
prompt = generate_prompt(question,summary)
for reply in generate_reply(prompt, state, stopping_strings=None, is_chat=False):
if hasattr(shared, 'is_seq2seq') and not shared.is_seq2seq:
reply = question + reply
if prepend_str:
reply = prepend_str+reply
yield formatted_outputs(reply)
def generate_summary(inptext, state, selectState):
global params
params[selectState] = [0,0]
summary_state = state.copy()
for key, value in default_req_params.items():
summary_state[key] = value # Update the value in 'summary_state' with the value from 'default_req_params
user = params['pUSER']
bot = params['pBOT']
prompt = params['summary_turn'].replace('\\n', '\n')
prompt = prompt.replace('<|context|>', inptext)
prompt = prompt.replace('<|user|>', user)
prompt = prompt.replace('<|bot|>', bot)
for reply in generate_reply(prompt, summary_state, stopping_strings=None, is_chat=False):
yield formatted_outputs(reply)
def get_available_LORA():
#print (f"Scaling {shared.model.base_model.scaling}")
prior_set = ['None']
if shared.model:
if hasattr(shared.model,'peft_config'):
print(RED+"List of available adapters in model:"+RESET)
index = 1
for adapter_name in shared.model.peft_config.items():
print(f" {GREEN}{index}:{RESET} {adapter_name[0]}")
index = index+1
prior_set.append(adapter_name[0])
if index == 1:
print(RED+" [None]"+RESET)
else:
print('(no model loaded yet)')
return prior_set
def get_loaded_loras():
prior_set = []
if hasattr(shared.model,'peft_config'):
for adapter_name in shared.model.peft_config.items():
prior_set.append(adapter_name[0])
return prior_set
def set_LORA(item):
#print(f"{YELLOW}Selected adapter in UI: {RESET} {item}")
#prior_set = list(shared.lora_names)
if shared.model == None:
print(f"No Model loaded")
return
print(RED+ 'SET LORA:'+RESET)
if hasattr(shared.model, 'set_adapter') and hasattr(shared.model, 'active_adapter'):
#if prior_set:
if hasattr(shared.model, 'base_model'):
if hasattr(shared.model.base_model, 'model'):
modelbasetype = shared.model.base_model.__class__.__name__
else:
modelbasetype = 'None'
else:
modelbasetype = 'None'
modeltype = shared.model.__class__.__name__
if hasattr(shared.model, 'base_model'):
if not hasattr(shared.model.base_model, 'disable_adapter_layers'):
print(f"{RED} ERROR {RESET} {YELLOW}{modeltype}{RESET} ({modelbasetype}) is not PEFT model (PeftModelForCausalLM). You need to Load Lora first.")
return
if (item =='None' or item == None):
shared.model.base_model.disable_adapter_layers()
print (f"{RED} [Disable]{RESET} Adapters in {YELLOW}{modeltype}{RESET} ({modelbasetype})")
else:
adapters = get_loaded_loras()
if item in adapters:
shared.model.set_adapter(item)
if hasattr(shared.model.base_model, 'enable_adapter_layers'):
shared.model.base_model.enable_adapter_layers()
print (f"{GREEN} [Enable]{RESET} {shared.model.active_adapter} in {YELLOW}{modeltype}{RESET} ({modelbasetype})")
else:
print(f"{RED} ERROR {RESET} {YELLOW}{modeltype}{RESET} with base {YELLOW}{modelbasetype}{RESET} is not correct PEFT model.")
else:
print (f"No or unknown Adapter {item} in {adapters}")
shared.model.base_model.disable_adapter_layers()
print (f"{RED} [Disable]{RESET} Adapters in {YELLOW}{modeltype}{RESET} ({modelbasetype})")
else:
print(f"{shared.model.__class__.__name__} has no support for switching adapters")
def get_available_loras_alpha():
return sorted([item.name for item in list(Path(shared.args.lora_dir).glob('*')) if not item.name.endswith(('.txt', '-np', '.pt', '.json'))], key=natural_keys)
def list_Folders_byAlpha(directory):
if not directory.endswith('/'):
directory += '/'
subfolders = []
path = directory
name_list = os.listdir(path)
full_list = [os.path.join(path, i) for i in name_list]
time_sorted_list = sorted(full_list, key=natural_keys, reverse=False)
for entry in time_sorted_list:
if os.path.isdir(entry):
entry_str = f"{entry}" # Convert entry to a string
full_path = entry_str
entry_str = entry_str.replace('\\','/')
entry_str = entry_str.replace(f"{directory}", "") # Remove directory part
subfolders.append(entry_str)
return subfolders
def list_subfoldersByTime(directory):
if not directory.endswith('/'):
directory += '/'
subfolders = []
path = directory
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime,reverse=True)
for entry in time_sorted_list:
if os.path.isdir(entry):
entry_str = f"{entry}" # Convert entry to a string
full_path = entry_str
entry_str = entry_str.replace('\\','/')
entry_str = entry_str.replace(f"{directory}", "") # Remove directory part
subfolders.append(entry_str)
return subfolders
def get_available_loras():
model_dir = shared.args.lora_dir
subfolders = []
if params.get("list_by_time",False):
subfolders = list_subfoldersByTime(model_dir)
else:
subfolders = list_Folders_byAlpha(model_dir)
subfolders.insert(0, 'Nonefmerge')
return subfolders
def from_json_file(cls, path_json_file, **kwargs):
global g_print_twice
global g_original_lora_rank
with open(path_json_file, "r") as file:
json_object = json.load(file)
lora_alpha_value = int(json_object.get("lora_alpha", 1))
lora_rank = int(json_object.get("r", 1))
g_original_lora_rank = lora_rank
if lora_rank==0:
lora_rank = 1
scaling = lora_alpha_value/ lora_rank
newalpha = int(lora_alpha_value * g_lora_multipolier)
newscaling = newalpha/ lora_rank
if lora_alpha_value==newalpha:
if g_print_twice == False:
print(f"Default Scaling: {scaling}")
print(f"Alpha: {lora_alpha_value} / Rank: {lora_rank}")
else:
if g_print_twice == False:
print("\033[91mPatching LORA adapter\033[0m")
print(f"Scaling: {scaling} -> {newscaling}")
print(f"Alpha: {lora_alpha_value} -> {newalpha} / Rank: {lora_rank}")
json_object["lora_alpha"] = newalpha
g_print_twice = True
return json_object
def parse_DYNAMEMORY(text):
blocks = text.split('\n\n')
memories = []
for block in blocks:
keywords = []
words = block.split()
for word in words:
if word.startswith('#'):
keywords.append(word.strip('#').strip(',').strip('.'))
block = block.replace('#', '')
if keywords:
memories.append({
'keywords': ','.join(keywords),
'memory': block.strip(),
'always': False
})
return memories
def resaveadapter(outputdir):
#is peft?
if hasattr(shared.model, 'disable_adapter'):
#get_peft_model_state_dict
# should be enough?
# should change the shared.model.peft_config "r" to the original?
# if g_original_lora_rank>0 setattr(config, 'r', value)
shared.model.save_pretrained(outputdir)
return "Done"
else:
return "No LoRA loaded yet"
'''
from peft.tuners.lora import LoraLayer, mark_only_lora_as_trainable
from peft.utils.other import _freeze_adapter, _get_submodules
from dataclasses import replace
def add_sub_weighted_adapter(model, adapters, weights, adapters_sub, weights_sub, adapter_name: str):
if len({model.peft_config[adapter].r for adapter in adapters}) != 1:
raise ValueError("All adapters must have the same r value")
#use same alpha as r
model.peft_config[adapter_name] = replace(
model.peft_config[adapters[0]], lora_alpha=model.peft_config[adapters[0]].r
)
model._find_and_replace(adapter_name)
mark_only_lora_as_trainable(model.model, model.peft_config[adapter_name].bias)
_freeze_adapter(model.model, adapter_name)
key_list = [key for key, _ in model.model.named_modules() if "lora" not in key]
for key in key_list:
_, target, _ = _get_submodules(model.model, key)
if isinstance(target, LoraLayer):
if adapter_name in target.lora_A:
target.lora_A[adapter_name].weight.data = target.lora_A[adapter_name].weight.data * 0.0
target.lora_B[adapter_name].weight.data = target.lora_B[adapter_name].weight.data * 0.0
# add
for adapter, weight in zip(adapters, weights):
if adapter not in target.lora_A:
continue
target.lora_A[adapter_name].weight.data += (
target.lora_A[adapter].weight.data * weight * target.scaling[adapter]
)
target.lora_B[adapter_name].weight.data += target.lora_B[adapter].weight.data * weight
# sub
for adapter, weight in zip(adapters_sub, weights_sub):
if adapter not in target.lora_A:
continue
target.lora_A[adapter_name].weight.data -= (
target.lora_A[adapter].weight.data * weight * target.scaling[adapter]
)
target.lora_B[adapter_name].weight.data -= target.lora_B[adapter].weight.data * weight
elif adapter_name in target.lora_embedding_A:
target.lora_embedding_A[adapter_name].data = target.lora_embedding_A[adapter_name].data * 0.0
target.lora_embedding_B[adapter_name].data = target.lora_embedding_B[adapter_name].data * 0.0
# add
for adapter, weight in zip(adapters, weights):
if adapter not in target.lora_embedding_A:
continue
target.lora_embedding_A[adapter_name].data += (
target.lora_embedding_A[adapter].data * weight * target.scaling[adapter]
)
target.lora_embedding_B[adapter_name].data += target.lora_embedding_B[adapter].data * weight
# sub
for adapter, weight in zip(adapters_sub, weights_sub):
if adapter not in target.lora_embedding_A:
continue
target.lora_embedding_A[adapter_name].data += (
target.lora_embedding_A[adapter].data * weight * target.scaling[adapter]
)
target.lora_embedding_B[adapter_name].data += target.lora_embedding_B[adapter].data * weight
'''
# what happens if we use negative weights....?
def create_weighted_lora_adapter(model, adapters, weights, adapter_name="combined"):
global params
combination_type = params['combination_type']
print(f"Trying to combine {adapters} with weights {weights} into {adapter_name}")
model.add_weighted_adapter(adapters, weights, adapter_name, combination_type)
def Select_last_lora():
loras_before = get_loaded_loras()
last_element = loras_before[-1]
set_LORA(last_element)
def merge_loras(w1,w2):
global params
if hasattr(shared.model,'peft_config'):
adapters = get_loaded_loras()
if len(adapters)>1:
nAd = len(adapters)
combination_type = params['combination_type']
print(f"{RED}Merging:{RESET} {adapters[0]} with {adapters[1]}")
adaptname = f"Merge{nAd}_A{int(w1*100)}_B{int(w2*100)}_{combination_type}"
create_weighted_lora_adapter(shared.model, [adapters[0], adapters[1]], [w1, w2],adaptname)
adapters_post = get_loaded_loras()
adapter_name = getattr(shared.model,'active_adapter','None')
if len(adapters)!=len(adapters_post):
Select_last_lora()
print (f"{GREEN}[OK]{RESET} Combined adapter created")
print (f"{GREEN}Active adapter: {RESET}{adapter_name}")
return f"Combined Adapter {adaptname} created"
else:
print (f"{RED}[FAIL]{RESET} No New adapter created - {RED}PEFT tantrum{RESET}")
return "Combined Adapter failed"
else:
return "You need to add 2 LoRA adapters in the model tab (Transformers)"
else:
return "No LoRA loaded yet"
def merge_loras3(w1,w2,w3):
global params
if hasattr(shared.model,'peft_config'):
adapters = get_loaded_loras()
if len(adapters)>2:
combination_type = params['combination_type']
nAd = len(adapters)
adaptname = f"Merge{nAd}_A{int(w1*100)}_B{int(w2*100)}_C{int(w3*100)}_{combination_type}"
create_weighted_lora_adapter(shared.model, [adapters[0], adapters[1], adapters[2]], [w1, w2, w3],adaptname)
adapters_post = get_loaded_loras()
adapter_name = getattr(shared.model,'active_adapter','None')
if len(adapters)!=len(adapters_post):
Select_last_lora()
print (f"{GREEN}[OK]{RESET} Combined adapter created")
print (f"{GREEN}Active adapter: {RESET}{adapter_name}")
return f"Combined Adapter {adaptname} created"
else:
print (f"{RED}[FAIL]{RESET} No New adapter created - {RED}PEFT tantrum{RESET}")
return f"Combined Adapter failed"
else:
return "You need to add 3 LoRA adapters in the model tab (Transformers)"
else:
return "No LoRA loaded yet"
def rescale_lora(w1):
if hasattr(shared.model,'peft_config'):
adapters = get_loaded_loras()
if len(adapters)>0:
nAd = len(adapters)
adaptname = f"Scale{nAd}_A{int(w1*100)}"
create_weighted_lora_adapter(shared.model, [adapters[0]], [w1],adaptname)
adapters_post = get_loaded_loras()
adapter_name = getattr(shared.model,'active_adapter','None')
if len(adapters)!=len(adapters_post):
Select_last_lora()
print (f"{GREEN}[OK]{RESET} New adapter created")
print (f"{GREEN}Active adapter: {RESET}{adapter_name}")
return f"Rescalled Adapter {adaptname} created"
else:
print (f"{RED}[FAIL]{RESET} No New adapter created - {RED}PEFT tantrum{RESET}")
return f"Rescalled Adapter failed"
else:
return "You need to add a LoRA adapters in the model tab (Transformers)"
else:
return "No LoRA loaded yet"
def display_tokens(text):
html_tokens = ""
if shared.tokenizer is None:
return "Tokenizer is not available. Please Load some Model first then type words above."
encoded_tokens = shared.tokenizer.encode(str(text))
decoded_tokens = []
#print(encoded_tokens)
for token in encoded_tokens:
shared.tokenizer.decode
chars = shared.tokenizer.decode([token])
if token == 0:
decoded_tokens.append("<unk>")
elif token == 1:
decoded_tokens.append("<s>")
elif token == 2:
decoded_tokens.append("</s>")
elif 3 <= token <= 258:
vocab_by_id = f"<0x{hex(token)[2:].upper()}>"
decoded_tokens.append(vocab_by_id)
else:
decoded_tokens.append(chars)
for index, token in enumerate(decoded_tokens):
#avoid jumpy artefacts
if token=='':
token = ' '
html_tokens += f'<span style="background-color: {pastel_colors[index % len(pastel_colors)]}; ' \
f'padding: 0 4px; border-radius: 3px; margin-right: 0px; margin-bottom: 4px; ' \
f'display: inline-block; height: 1.5em;"><pre>{str(token).replace(" ", " ")}</pre></span>'
token_count = len(encoded_tokens)
# Join the decimal values of encoded_tokens with commas
token_values_str = ', '.join(map(str, encoded_tokens))
# Append the token values to the HTML
html_tokens += f'<div style="font-size: 14px; margin-top: 10px;">Token Values: {token_values_str}</div>'
html_tokens += f'<div style="font-size: 18px; margin-top: 10px;">Token Count: {token_count}</div>'
return html_tokens
def custom_js():
java = '''
const playgroundAElement = document.querySelector('#textbox-playgroundA textarea');
let playgroundAScrolled = false;
playgroundAElement.addEventListener('scroll', function() {
let diff = playgroundAElement.scrollHeight - playgroundAElement.clientHeight;
if(Math.abs(playgroundAElement.scrollTop - diff) <= 1 || diff == 0) {
playgroundAScrolled = false;
} else {
playgroundAScrolled = true;
}
});
const playgroundAObserver = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if(!playgroundAScrolled) {
playgroundAElement.scrollTop = playgroundAElement.scrollHeight;
}
});
});