forked from henk717/KoboldAI
-
Notifications
You must be signed in to change notification settings - Fork 31
/
aiserver.py
11119 lines (9988 loc) · 460 KB
/
aiserver.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
#!/usr/bin/python3
#==================================================================#
# KoboldAI
# Version: 1.19.2
# By: The KoboldAI Community
#==================================================================#
# External packages
from dataclasses import dataclass
from enum import Enum
import random
import shutil
import eventlet
eventlet.monkey_patch(all=True, thread=False, os=False)
import os, inspect
os.system("")
__file__ = os.path.dirname(os.path.realpath(__file__))
os.chdir(__file__)
os.environ['EVENTLET_THREADPOOL_SIZE'] = '1'
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
from eventlet import tpool
import logging
from logger import logger, set_logger_verbosity, quiesce_logger
from ansi2html import Ansi2HTMLConverter
logging.getLogger("urllib3").setLevel(logging.ERROR)
import attention_bias
attention_bias.do_patches()
from os import path, getcwd
import time
import re
import json
import ijson
import datetime
import collections
import zipfile
import packaging.version
import traceback
import markdown
import bleach
import functools
import traceback
import inspect
import warnings
import multiprocessing
import numpy as np
from collections import OrderedDict
from typing import Any, Callable, TypeVar, Tuple, Union, Dict, Set, List, Optional, Type
import glob
from pathlib import Path
import requests
import html
import argparse
import sys
import gc
import lupa
# KoboldAI
import fileops
import gensettings
from utils import debounce
import utils
import koboldai_settings
import torch
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer, AutoModelForTokenClassification
import transformers
import ipaddress
from functools import wraps
try:
from transformers.models.opt.modeling_opt import OPTDecoder
except:
pass
# Text2img
import base64
from PIL import Image
from io import BytesIO
global tpu_mtj_backend
global allowed_ips
allowed_ips = set() # empty set
enable_whitelist = False
if lupa.LUA_VERSION[:2] != (5, 4):
logger.error(f"Please install lupa==1.10. You have lupa {lupa.__version__}.")
patch_causallm_patched = False
# Make sure tqdm progress bars display properly in Colab
from tqdm.auto import tqdm
old_init = tqdm.__init__
def new_init(self, *args, **kwargs):
old_init(self, *args, **kwargs)
if 'ncols' in kwargs:
if(self.ncols == 0 and kwargs.get("ncols") != 0):
self.ncols = 99
tqdm.__init__ = new_init
# Add _koboldai_header support for some optional tokenizer fixes
# This used to be an OPT tokenizer fix, this has been moved search for "# These are model specific overrides if a model has bad defaults" for the new section
from transformers import PreTrainedTokenizerBase
old_pretrainedtokenizerbase_from_pretrained = PreTrainedTokenizerBase.from_pretrained.__func__
@classmethod
def new_pretrainedtokenizerbase_from_pretrained(cls, *args, **kwargs):
tokenizer = old_pretrainedtokenizerbase_from_pretrained(cls, *args, **kwargs)
tokenizer._koboldai_header = []
return tokenizer
PreTrainedTokenizerBase.from_pretrained = new_pretrainedtokenizerbase_from_pretrained
def is_model_downloaded(model_name: str) -> bool:
model_stub = model_name.replace("/", "_")
return os.path.isdir(os.path.join("models", model_stub))
#==================================================================#
# Variables & Storage
#==================================================================#
# Terminal tags for colored text
class colors:
PURPLE = '\033[95m'
BLUE = '\033[94m'
CYAN = '\033[96m'
GREEN = '\033[92m'
YELLOW = '\033[93m'
RED = '\033[91m'
END = '\033[0m'
UNDERLINE = '\033[4m'
class MenuModelType(Enum):
HUGGINGFACE = 0
ONLINE_API = 1
OTHER = 2
RWKV = 3
class MenuItem:
def __init__(
self,
label: str,
name: str,
experimental: bool = False
) -> None:
self.label = label
self.name = name
self.experimental = experimental
def should_show(self) -> bool:
return koboldai_vars.experimental_features or not self.experimental
class MenuFolder(MenuItem):
def to_ui1(self) -> list:
return [
self.label,
self.name,
"",
True,
]
def to_json(self) -> dict:
return {
"label": self.label,
"name": self.name,
"size": "",
"isMenu": True,
"isDownloaded": False,
}
class MenuModel(MenuItem):
def __init__(
self,
label: str,
name: str,
vram_requirements: str = "",
model_type: MenuModelType = MenuModelType.HUGGINGFACE,
experimental: bool = False,
) -> None:
super().__init__(label, name, experimental)
self.model_type = model_type
self.vram_requirements = vram_requirements
self.is_downloaded = is_model_downloaded(self.name)
def to_ui1(self) -> list:
return [
self.label,
self.name,
self.vram_requirements,
False,
self.is_downloaded
]
def to_json(self) -> dict:
return {
"label": self.label,
"name": self.name,
"size": self.vram_requirements,
"isMenu": False,
"isDownloaded": self.is_downloaded,
}
# AI models Menu
# This is a dict of lists where they key is the menu name, and the list is the menu items.
# Each item takes the 4 elements, 1: Text to display, 2: Model Name (koboldai_vars.model) or menu name (Key name for another menu),
# 3: the memory requirement for the model, 4: if the item is a menu or not (True/False)
model_menu = {
"mainmenu": [
MenuModel("Load a model from its directory", "NeoCustom"),
MenuModel("Load an old GPT-2 model (eg CloverEdition)", "GPT2Custom"),
MenuFolder("Load custom model from Hugging Face", "customhuggingface"),
MenuFolder("Adventure Models", "adventurelist"),
MenuFolder("Novel Models", "novellist"),
MenuFolder("Chat Models", "chatlist"),
MenuFolder("NSFW Models", "nsfwlist"),
MenuFolder("Untuned OPT", "optlist"),
MenuFolder("Untuned GPT-Neo/J", "gptneolist"),
MenuFolder("Untuned Pythia", "pythialist"),
MenuFolder("Untuned Fairseq Dense", "fsdlist"),
MenuFolder("Untuned Bloom", "bloomlist"),
MenuFolder("Untuned XGLM", "xglmlist"),
MenuFolder("Untuned RWKV-4 (Experimental)", "rwkvlist", experimental=True),
MenuFolder("Untuned GPT2", "gpt2list"),
MenuFolder("Online Services", "apilist"),
MenuModel("Read Only (No AI)", "ReadOnly", model_type=MenuModelType.OTHER),
],
'adventurelist': [
MenuModel("Skein 20B", "KoboldAI/GPT-NeoX-20B-Skein", "64GB"),
MenuModel("Nerys OPT 13B V2 (Hybrid)", "KoboldAI/OPT-13B-Nerys-v2", "32GB"),
MenuModel("Nerys FSD 13B V2 (Hybrid)", "KoboldAI/fairseq-dense-13B-Nerys-v2", "32GB"),
MenuModel("Nerys FSD 13B (Hybrid)", "KoboldAI/fairseq-dense-13B-Nerys", "32GB"),
MenuModel("Skein 6B", "KoboldAI/GPT-J-6B-Skein", "16GB"),
MenuModel("OPT Nerys 6B V2 (Hybrid)", "KoboldAI/OPT-6B-nerys-v2", "16GB"),
MenuModel("Adventure 6B", "KoboldAI/GPT-J-6B-Adventure", "16GB"),
MenuModel("Nerys FSD 2.7B (Hybrid)", "KoboldAI/fairseq-dense-2.7B-Nerys", "8GB"),
MenuModel("Adventure 2.7B", "KoboldAI/GPT-Neo-2.7B-AID", "8GB"),
MenuModel("Adventure 1.3B", "KoboldAI/GPT-Neo-1.3B-Adventure", "6GB"),
MenuModel("Adventure 125M (Mia)", "Merry/AID-Neo-125M", "2GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'novellist': [
MenuModel("Nerys OPT 13B V2 (Hybrid)", "KoboldAI/OPT-13B-Nerys-v2", "32GB"),
MenuModel("Nerys FSD 13B V2 (Hybrid)", "KoboldAI/fairseq-dense-13B-Nerys-v2", "32GB"),
MenuModel("Janeway FSD 13B", "KoboldAI/fairseq-dense-13B-Janeway", "32GB"),
MenuModel("Nerys FSD 13B (Hybrid)", "KoboldAI/fairseq-dense-13B-Nerys", "32GB"),
MenuModel("OPT Nerys 6B V2 (Hybrid)", "KoboldAI/OPT-6B-nerys-v2", "16GB"),
MenuModel("Janeway FSD 6.7B", "KoboldAI/fairseq-dense-6.7B-Janeway", "16GB"),
MenuModel("Janeway Neo 6B", "KoboldAI/GPT-J-6B-Janeway", "16GB"),
MenuModel("Qilin Lit 6B (SFW)", "rexwang8/qilin-lit-6b", "16GB"),
MenuModel("Janeway Neo 2.7B", "KoboldAI/GPT-Neo-2.7B-Janeway", "8GB"),
MenuModel("Janeway FSD 2.7B", "KoboldAI/fairseq-dense-2.7B-Janeway", "8GB"),
MenuModel("Nerys FSD 2.7B (Hybrid)", "KoboldAI/fairseq-dense-2.7B-Nerys", "8GB"),
MenuModel("Horni-LN 2.7B", "KoboldAI/GPT-Neo-2.7B-Horni-LN", "8GB"),
MenuModel("Picard 2.7B (Older Janeway)", "KoboldAI/GPT-Neo-2.7B-Picard", "8GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'nsfwlist': [
MenuModel("Erebus 20B (NSFW)", "KoboldAI/GPT-NeoX-20B-Erebus", "64GB"),
MenuModel("Erebus 13B (NSFW)", "KoboldAI/OPT-13B-Erebus", "32GB"),
MenuModel("Shinen FSD 13B (NSFW)", "KoboldAI/fairseq-dense-13B-Shinen", "32GB"),
MenuModel("Erebus 6.7B (NSFW)", "KoboldAI/OPT-6.7B-Erebus", "16GB"),
MenuModel("Shinen FSD 6.7B (NSFW)", "KoboldAI/fairseq-dense-6.7B-Shinen", "16GB"),
MenuModel("Lit V2 6B (NSFW)", "hakurei/litv2-6B-rev3", "16GB"),
MenuModel("Lit 6B (NSFW)", "hakurei/lit-6B", "16GB"),
MenuModel("Shinen 6B (NSFW)", "KoboldAI/GPT-J-6B-Shinen", "16GB"),
MenuModel("Erebus 2.7B (NSFW)", "KoboldAI/OPT-2.7B-Erebus", "8GB"),
MenuModel("Horni 2.7B (NSFW)", "KoboldAI/GPT-Neo-2.7B-Horni", "8GB"),
MenuModel("Shinen 2.7B (NSFW)", "KoboldAI/GPT-Neo-2.7B-Shinen", "8GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'chatlist': [
MenuModel("Pygmalion 6B", "PygmalionAI/pygmalion-6b", "16GB"),
MenuModel("Pygmalion 2.7B", "PygmalionAI/pygmalion-2.7b", "8GB"),
MenuModel("Pygmalion 1.3B", "PygmalionAI/pygmalion-1.3b", "6GB"),
MenuModel("Pygmalion 350M", "PygmalionAI/pygmalion-350m", "2GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'gptneolist': [
MenuModel("GPT-NeoX 20B", "EleutherAI/gpt-neox-20b", "64GB"),
MenuModel("Pythia 13B (NeoX, Same dataset)", "EleutherAI/pythia-13b", "32GB"),
MenuModel("GPT-J 6B", "EleutherAI/gpt-j-6B", "16GB"),
MenuModel("GPT-Neo 2.7B", "EleutherAI/gpt-neo-2.7B", "8GB"),
MenuModel("GPT-Neo 1.3B", "EleutherAI/gpt-neo-1.3B", "6GB"),
MenuModel("Pythia 800M (NeoX, Same dataset)", "EleutherAI/pythia-800m", "4GB"),
MenuModel("Pythia 350M (NeoX, Same dataset)", "EleutherAI/pythia-350m", "2GB"),
MenuModel("GPT-Neo 125M", "EleutherAI/gpt-neo-125M", "2GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'pythialist': [
MenuModel("Pythia 13B Deduped", "EleutherAI/pythia-13b-deduped", "32GB"),
MenuModel("Pythia 13B", "EleutherAI/pythia-13b", "32GB"),
MenuModel("Pythia 6.7B Deduped", "EleutherAI/pythia-6.7b-deduped", "16GB"),
MenuModel("Pythia 6.7B", "EleutherAI/pythia-6.7b", "16GB"),
MenuModel("Pythia 1.3B Deduped", "EleutherAI/pythia-1.3b-deduped", "6GB"),
MenuModel("Pythia 1.3B", "EleutherAI/pythia-1.3b", "6GB"),
MenuModel("Pythia 800M", "EleutherAI/pythia-800m", "4GB"),
MenuModel("Pythia 350M Deduped", "EleutherAI/pythia-350m-deduped", "2GB"),
MenuModel("Pythia 350M", "EleutherAI/pythia-350m", "2GB"),
MenuModel("Pythia 125M Deduped", "EleutherAI/pythia-125m-deduped", "2GB"),
MenuModel("Pythia 125M", "EleutherAI/pythia-125m", "2GB"),
MenuModel("Pythia 19M Deduped", "EleutherAI/pythia-19m-deduped", "1GB"),
MenuModel("Pythia 19M", "EleutherAI/pythia-19m", "1GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'gpt2list': [
MenuModel("GPT-2 XL", "gpt2-xl", "6GB"),
MenuModel("GPT-2 Large", "gpt2-large", "4GB"),
MenuModel("GPT-2 Med", "gpt2-medium", "2GB"),
MenuModel("GPT-2", "gpt2", "2GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'bloomlist': [
MenuModel("Bloom 176B", "bigscience/bloom"),
MenuModel("Bloom 7.1B", "bigscience/bloom-7b1"),
MenuModel("Bloom 3B", "bigscience/bloom-3b"),
MenuModel("Bloom 1.7B", "bigscience/bloom-1b7"),
MenuModel("Bloom 560M", "bigscience/bloom-560m"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'optlist': [
MenuModel("OPT 66B", "facebook/opt-66b", "128GB"),
MenuModel("OPT 30B", "facebook/opt-30b", "64GB"),
MenuModel("OPT 13B", "facebook/opt-13b", "32GB"),
MenuModel("OPT 6.7B", "facebook/opt-6.7b", "16GB"),
MenuModel("OPT 2.7B", "facebook/opt-2.7b", "8GB"),
MenuModel("OPT 1.3B", "facebook/opt-1.3b", "4GB"),
MenuModel("OPT 350M", "facebook/opt-350m", "2GB"),
MenuModel("OPT 125M", "facebook/opt-125m", "1GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'fsdlist': [
MenuModel("Fairseq Dense 13B", "KoboldAI/fairseq-dense-13B", "32GB"),
MenuModel("Fairseq Dense 6.7B", "KoboldAI/fairseq-dense-6.7B", "16GB"),
MenuModel("Fairseq Dense 2.7B", "KoboldAI/fairseq-dense-2.7B", "8GB"),
MenuModel("Fairseq Dense 1.3B", "KoboldAI/fairseq-dense-1.3B", "4GB"),
MenuModel("Fairseq Dense 355M", "KoboldAI/fairseq-dense-355M", "2GB"),
MenuModel("Fairseq Dense 125M", "KoboldAI/fairseq-dense-125M", "1GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'xglmlist': [
MenuModel("XGLM 4.5B (Larger Dataset)", "facebook/xglm-4.5B", "12GB"),
MenuModel("XGLM 7.5B", "facebook/xglm-7.5B", "18GB"),
MenuModel("XGLM 2.9B", "facebook/xglm-2.9B", "10GB"),
MenuModel("XGLM 1.7B", "facebook/xglm-1.7B", "6GB"),
MenuModel("XGLM 564M", "facebook/xglm-564M", "4GB"),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'rwkvlist': [
MenuModel("RWKV-4 14B ctx4096", "rwkv-4-pile-14b:ctx4096", "??GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 14B ctx1024", "rwkv-4-pile-14b", "??GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 7B ctx4096", "rwkv-4-pile-7b:ctx4096", "??GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 7B ctx1024", "rwkv-4-pile-7b", "??GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 3B ctx4096", "rwkv-4-pile-3b:ctx4096", "?GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 3B ctx1024", "rwkv-4-pile-3b", "?GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 1.5B ctx4096", "rwkv-4-pile-1b5:ctx4096", "9GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 1.5B ctx1024", "rwkv-4-pile-1b5", "9GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 340M", "rwkv-4-pile-430m", "?GB", model_type=MenuModelType.RWKV),
MenuModel("RWKV-4 169M ctx1024", "rwkv-4-pile-169m", "?GB", model_type=MenuModelType.RWKV),
MenuFolder("Return to Main Menu", "mainmenu"),
],
'apilist': [
MenuModel("GooseAI API (requires API key)", "GooseAI", model_type=MenuModelType.ONLINE_API),
MenuModel("OpenAI API (requires API key)", "OAI", model_type=MenuModelType.ONLINE_API),
MenuModel("InferKit API (requires API key)", "InferKit", model_type=MenuModelType.ONLINE_API),
MenuModel("KoboldAI API", "API", model_type=MenuModelType.ONLINE_API),
MenuModel("Basic Model API", "Colab", model_type=MenuModelType.ONLINE_API),
MenuModel("KoboldAI Horde", "CLUSTER", model_type=MenuModelType.ONLINE_API),
MenuFolder("Return to Main Menu", "mainmenu"),
]
}
@dataclass
class ImportBuffer:
# Singleton!!!
prompt: Optional[str] = None
memory: Optional[str] = None
authors_note: Optional[str] = None
notes: Optional[str] = None
world_infos: Optional[dict] = None
title: Optional[str] = None
@dataclass
class PromptPlaceholder:
id: str
order: Optional[int] = None
default: Optional[str] = None
title: Optional[str] = None
description: Optional[str] = None
value: Optional[str] = None
def to_json(self) -> dict:
return {key: getattr(self, key) for key in [
"id",
"order",
"default",
"title",
"description"
]}
def request_client_configuration(self, placeholders: List[PromptPlaceholder]) -> None:
emit("request_prompt_config", [x.to_json() for x in placeholders], broadcast=False, room="UI_2")
def extract_placeholders(self, text: str) -> List[PromptPlaceholder]:
placeholders = []
for match in re.finditer(r"\${(.*?)}", text):
ph_text = match.group(1)
try:
ph_order, ph_text = ph_text.split("#")
except ValueError:
ph_order = None
if "[" not in ph_text:
ph_id = ph_text
# Already have it!
if any([x.id == ph_id for x in placeholders]):
continue
# Apparently, none of these characters are supported:
# "${}[]#:@^|", however I have found some prompts using these,
# so they will be allowed.
for char in "${}[]":
if char in ph_text:
print("[eph] Weird char")
print(f"Char: {char}")
print(f"Ph_id: {ph_id}")
show_error_notification("Error loading prompt", f"Bad character '{char}' in prompt placeholder.")
return
placeholders.append(self.PromptPlaceholder(
id=ph_id,
order=int(ph_order) if ph_order else None,
))
continue
ph_id, _ = ph_text.split("[")
ph_text = ph_text.replace(ph_id, "", 1)
# Already have it!
if any([x.id == ph_id for x in placeholders]):
continue
# Match won't match it for some reason (???), so we use finditer and next()
try:
default_match = next(re.finditer(r"\[(.*?)\]", ph_text))
except StopIteration:
print("[eph] Weird brackets")
show_error_notification("Error loading prompt", f"Unusual bracket structure in prompt.")
return placeholders
ph_default = default_match.group(1)
ph_text = ph_text.replace(default_match.group(0), "")
try:
ph_title, ph_desc = ph_text.split(":")
except ValueError:
ph_title = ph_text or None
ph_desc=None
placeholders.append(self.PromptPlaceholder(
id=ph_id,
order=int(ph_order) if ph_order else None,
default=ph_default,
title=ph_title,
description=ph_desc
))
return placeholders
def _replace_placeholders(self, text: str, ph_ids: dict):
for ph_id, value in ph_ids.items():
pattern = "\${(?:\d#)?%s.*?}" % re.escape(ph_id)
for ph_text in re.findall(pattern, text):
text = text.replace(ph_text, value)
return text
def replace_placeholders(self, ph_ids: dict):
self.prompt = self._replace_placeholders(self.prompt, ph_ids)
self.memory = self._replace_placeholders(self.memory, ph_ids)
self.authors_note = self._replace_placeholders(self.authors_note, ph_ids)
for i in range(len(self.world_infos)):
for key in ["content", "comment"]:
self.world_infos[i][key] = self._replace_placeholders(self.world_infos[i][key])
def from_club(self, club_id):
from importers import aetherroom
import_data: aetherroom.ImportData
try:
import_data = aetherroom.import_scenario(club_id)
except aetherroom.RequestFailed as err:
status = err.status_code
print(f"[import] Got {status} on request to club :^(")
message = f"Club responded with {status}"
if status == 404:
message = f"Prompt not found for ID {club_id}"
show_error_notification("Error loading prompt", message)
return
self.prompt = import_data.prompt
self.memory = import_data.memory
self.authors_note = import_data.authors_note
self.notes = import_data.notes
self.title = import_data.title
self.world_infos = import_data.world_infos
placeholders = self.extract_placeholders(self.prompt)
if not placeholders:
self.commit()
else:
self.request_client_configuration(placeholders)
def commit(self):
# Push buffer story to actual story
exitModes()
koboldai_vars.create_story("")
koboldai_vars.gamestarted = True
koboldai_vars.prompt = self.prompt
koboldai_vars.memory = self.memory or ""
koboldai_vars.authornote = self.authors_note or ""
koboldai_vars.notes = self.notes
koboldai_vars.story_name = self.title
for wi in self.world_infos:
koboldai_vars.worldinfo_v2.add_item(
wi["key_list"][0],
wi["key_list"],
wi.get("keysecondary", []),
wi.get("folder", "root"),
wi.get("constant", False),
wi["content"],
wi.get("comment", "")
)
# Reset current save
koboldai_vars.savedir = getcwd()+"\\stories"
# Refresh game screen
koboldai_vars.laststory = None
setgamesaved(False)
sendwi()
refresh_story()
import_buffer = ImportBuffer()
# Set logging level to reduce chatter from Flask
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
def UI_2_logger(message):
conv = Ansi2HTMLConverter(inline=True, dark_bg=True)
data = json.loads(message)
data['html'] = [conv.convert(text, full=False) for text in data['text'].split("\n")]
if not has_request_context():
if koboldai_settings.queue is not None:
koboldai_settings.queue.put(["log_message", data, {"broadcast":True, "room":"UI_2"}])
else:
socketio.emit("log_message", data, broadcast=True, room="UI_2")
web_log_history = []
def UI_2_log_history(message):
conv = Ansi2HTMLConverter(inline=True, dark_bg=True)
data = json.loads(message)
data['html'] = [conv.convert(text, full=False) for text in data['text'].split("\n")]
if len(web_log_history) >= 100:
del web_log_history[0]
web_log_history.append(data)
from flask import Flask, render_template, Response, request, copy_current_request_context, send_from_directory, session, jsonify, abort, redirect, has_request_context, send_file
from flask_socketio import SocketIO, emit, join_room, leave_room
from flask_socketio import emit as _emit
from flask_session import Session
from flask_compress import Compress
from flask_cors import CORS
from werkzeug.exceptions import HTTPException, NotFound, InternalServerError
import secrets
app = Flask(__name__, root_path=os.getcwd())
app.secret_key = secrets.token_hex()
app.config['SESSION_TYPE'] = 'filesystem'
app.config['TEMPLATES_AUTO_RELOAD'] = True
# Hack for socket stuff that needs app context
utils.flask_app = app
Compress(app)
socketio = SocketIO(app, async_method="eventlet", manage_session=False, cors_allowed_origins='*', max_http_buffer_size=10_000_000)
#socketio = SocketIO(app, async_method="eventlet", manage_session=False, cors_allowed_origins='*', max_http_buffer_size=10_000_000, logger=logger, engineio_logger=True)
logger.add(UI_2_log_history, serialize=True, colorize=True, enqueue=True, level="INFO")
#logger.add("log_file_1.log", rotation="500 MB") # Automatically rotate too big file
koboldai_vars = koboldai_settings.koboldai_vars(socketio)
utils.koboldai_vars = koboldai_vars
utils.socketio = socketio
# Weird import position to steal koboldai_vars from utils
from modeling.patches import patch_transformers
from modeling.inference_models.hf_torch_4bit import load_model_gptq_settings
old_socketio_on = socketio.on
def new_socketio_on(*a, **k):
decorator = old_socketio_on(*a, **k)
def new_decorator(f):
@functools.wraps(f)
def g(*a, **k):
if args.no_ui:
return
return f(*a, **k)
return decorator(g)
return new_decorator
socketio.on = new_socketio_on
def emit(*args, **kwargs):
try:
return _emit(*args, **kwargs)
except AttributeError:
return socketio.emit(*args, **kwargs)
utils.emit = emit
#replacement for tpool.execute to maintain request contexts
def replacement_tpool_execute(function, *args, **kwargs):
temp = {}
socketio.start_background_task(tpool.execute_2, function, temp, *args, **kwargs).join()
print(temp)
return temp[1]
def replacement_tpool_execute_2(function, temp, *args, **kwargs):
temp[1] = function(*args, **kwargs)
# marshmallow/apispec setup
from apispec import APISpec
from apispec.ext.marshmallow import MarshmallowPlugin
from apispec.ext.marshmallow.field_converter import make_min_max_attributes
from apispec_webframeworks.flask import FlaskPlugin
from marshmallow import Schema, fields, validate, EXCLUDE
from marshmallow.exceptions import ValidationError
class KoboldSchema(Schema):
pass
def new_make_min_max_attributes(validators, min_attr, max_attr) -> dict:
# Patched apispec function that creates "exclusiveMinimum"/"exclusiveMaximum" OpenAPI attributes insteaed of "minimum"/"maximum" when using validators.Range or validators.Length with min_inclusive=False or max_inclusive=False
attributes = {}
min_list = [validator.min for validator in validators if validator.min is not None]
max_list = [validator.max for validator in validators if validator.max is not None]
min_inclusive_list = [getattr(validator, "min_inclusive", True) for validator in validators if validator.min is not None]
max_inclusive_list = [getattr(validator, "max_inclusive", True) for validator in validators if validator.max is not None]
if min_list:
if min_attr == "minimum" and not min_inclusive_list[max(range(len(min_list)), key=min_list.__getitem__)]:
min_attr = "exclusiveMinimum"
attributes[min_attr] = max(min_list)
if max_list:
if min_attr == "maximum" and not max_inclusive_list[min(range(len(max_list)), key=max_list.__getitem__)]:
min_attr = "exclusiveMaximum"
attributes[max_attr] = min(max_list)
return attributes
make_min_max_attributes.__code__ = new_make_min_max_attributes.__code__
def api_format_docstring(f):
f.__doc__ = eval('f"""{}"""'.format(f.__doc__.replace("\\", "\\\\")))
return f
def api_catch_out_of_memory_errors(f):
@functools.wraps(f)
def decorated(*args, **kwargs):
try:
return f(*args, **kwargs)
except Exception as e:
if any (s in traceback.format_exc().lower() for s in ("out of memory", "not enough memory")):
for line in reversed(traceback.format_exc().split("\n")):
if any(s in line.lower() for s in ("out of memory", "not enough memory")) and line.count(":"):
line = line.split(":", 1)[1]
line = re.sub(r"\[.+?\] +data\.", "", line).strip()
raise KoboldOutOfMemoryError("KoboldAI ran out of memory: " + line, type="out_of_memory.gpu.cuda" if "cuda out of memory" in line.lower() else "out_of_memory.gpu.hip" if "hip out of memory" in line.lower() else "out_of_memory.tpu.hbm" if "memory space hbm" in line.lower() else "out_of_memory.cpu.default_memory_allocator" if "defaultmemoryallocator" in line.lower() else "out_of_memory.unknown.unknown")
raise KoboldOutOfMemoryError(type="out_of_memory.unknown.unknown")
raise e
return decorated
def api_schema_wrap(f):
try:
input_schema: Type[Schema] = next(iter(inspect.signature(f).parameters.values())).annotation
except:
HAS_SCHEMA = False
else:
HAS_SCHEMA = inspect.isclass(input_schema) and issubclass(input_schema, Schema)
f = api_format_docstring(f)
f = api_catch_out_of_memory_errors(f)
@functools.wraps(f)
def decorated(*args, **kwargs):
if HAS_SCHEMA:
body = request.get_json()
schema = input_schema.from_dict(input_schema().load(body))
response = f(schema, *args, **kwargs)
else:
response = f(*args, **kwargs)
if not isinstance(response, Response):
response = jsonify(response)
return response
return decorated
@app.errorhandler(HTTPException)
def handler(e):
if request.path != "/api" and not request.path.startswith("/api/"):
return e
resp = jsonify(detail={"msg": str(e), "type": "generic.error_" + str(e.code)})
if e.code == 405 and e.valid_methods is not None:
resp.headers["Allow"] = ", ".join(e.valid_methods)
return resp, e.code
class KoboldOutOfMemoryError(HTTPException):
code = 507
description = "KoboldAI ran out of memory."
type = "out_of_memory.unknown.unknown"
def __init__(self, *args, type=None, **kwargs):
super().__init__(*args, **kwargs)
if type is not None:
self.type = type
@app.errorhandler(KoboldOutOfMemoryError)
def handler(e):
if request.path != "/api" and not request.path.startswith("/api/"):
return InternalServerError()
return jsonify(detail={"type": e.type, "msg": e.description}), e.code
@app.errorhandler(ValidationError)
def handler(e):
if request.path != "/api" and not request.path.startswith("/api/"):
return InternalServerError()
return jsonify(detail=e.messages), 422
@app.errorhandler(NotImplementedError)
def handler(e):
if request.path != "/api" and not request.path.startswith("/api/"):
return InternalServerError()
return jsonify(detail={"type": "not_implemented", "msg": str(e).strip()}), 501
api_versions: List[str] = []
class KoboldAPISpec(APISpec):
class KoboldFlaskPlugin(FlaskPlugin):
def __init__(self, api: "KoboldAPISpec", *args, **kwargs):
self._kobold_api_spec = api
super().__init__(*args, **kwargs)
def path_helper(self, *args, **kwargs):
return super().path_helper(*args, **kwargs)[len(self._kobold_api_spec._prefixes[0]):]
def __init__(self, *args, title: str = "KoboldAI API", openapi_version: str = "3.0.3", version: str = "1.0.0", prefixes: List[str] = None, **kwargs):
plugins = [KoboldAPISpec.KoboldFlaskPlugin(self), MarshmallowPlugin()]
self._prefixes = prefixes if prefixes is not None else [""]
self._kobold_api_spec_version = version
api_versions.append(version)
api_versions.sort(key=lambda x: [int(e) for e in x.split(".")])
super().__init__(*args, title=title, openapi_version=openapi_version, version=version, plugins=plugins, servers=[{"url": self._prefixes[0]}], **kwargs)
for prefix in self._prefixes:
app.route(prefix, endpoint="~KoboldAPISpec~" + prefix)(lambda: redirect(request.path + "/docs/"))
app.route(prefix + "/", endpoint="~KoboldAPISpec~" + prefix + "/")(lambda: redirect("docs/"))
app.route(prefix + "/docs", endpoint="~KoboldAPISpec~" + prefix + "/docs")(lambda: redirect("docs/"))
app.route(prefix + "/docs/", endpoint="~KoboldAPISpec~" + prefix + "/docs/")(lambda: render_template("swagger-ui.html", url=self._prefixes[0] + "/openapi.json"))
app.route(prefix + "/openapi.json", endpoint="~KoboldAPISpec~" + prefix + "/openapi.json")(lambda: jsonify(self.to_dict()))
def route(self, rule: str, methods=["GET"], **kwargs):
__F = TypeVar("__F", bound=Callable[..., Any])
if "strict_slashes" not in kwargs:
kwargs["strict_slashes"] = False
def new_decorator(f: __F) -> __F:
@functools.wraps(f)
def g(*args, **kwargs):
global api_version
api_version = self._kobold_api_spec_version
try:
return f(*args, **kwargs)
finally:
api_version = None
for prefix in self._prefixes:
g = app.route(prefix + rule, methods=methods, **kwargs)(g)
with app.test_request_context():
self.path(view=g, **kwargs)
return g
return new_decorator
def get(self, rule: str, **kwargs):
return self.route(rule, methods=["GET"], **kwargs)
def post(self, rule: str, **kwargs):
return self.route(rule, methods=["POST"], **kwargs)
def put(self, rule: str, **kwargs):
return self.route(rule, methods=["PUT"], **kwargs)
def patch(self, rule: str, **kwargs):
return self.route(rule, methods=["PATCH"], **kwargs)
def delete(self, rule: str, **kwargs):
return self.route(rule, methods=["DELETE"], **kwargs)
tags = [
{"name": "info", "description": "Metadata about this API"},
{"name": "generate", "description": "Text generation endpoints"},
{"name": "model", "description": "Information about the current text generation model"},
{"name": "story", "description": "Endpoints for managing the story in the KoboldAI GUI"},
{"name": "world_info", "description": "Endpoints for managing the world info in the KoboldAI GUI"},
{"name": "config", "description": "Allows you to get/set various setting values"},
]
api_version = None # This gets set automatically so don't change this value
api_v1 = KoboldAPISpec(
version="1.2.2",
prefixes=["/api/v1", "/api/latest"],
tags=tags,
)
def show_error_notification(title: str, text: str, do_log: bool = False) -> None:
if do_log:
logger.error(f"{title}: {text}")
if has_request_context():
socketio.emit("show_error_notification", {"title": title, "text": text}, broadcast=True, room="UI_2")
else:
koboldai_settings.queue.put(["show_error_notification", {"title": title, "text": text}, {"broadcast":True, "room":'UI_2'}])
# Returns the expected config filename for the current setup.
# If the model_name is specified, it returns what the settings file would be for that model
def get_config_filename(model_name = None):
if model_name:
return(f"settings/{model_name.replace('/', '_')}.settings")
elif args.configname:
return(f"settings/{args.configname.replace('/', '_')}.settings")
elif koboldai_vars.configname != '':
return(f"settings/{koboldai_vars.configname.replace('/', '_')}.settings")
else:
logger.warning(f"Empty configfile name sent back. Defaulting to ReadOnly")
return(f"settings/ReadOnly.settings")
#==================================================================#
# Function to get model selection at startup
#==================================================================#
def sendModelSelection(menu="mainmenu", folder="./models"):
#If we send one of the manual load options, send back the list of model directories, otherwise send the menu
if menu in ('NeoCustom', 'GPT2Custom'):
paths, breadcrumbs = get_folder_path_info(folder)
# paths = [x for x in paths if "rwkv" not in x[1].lower()]
if koboldai_vars.host:
breadcrumbs = []
menu_list = [[folder, menu, "", False] for folder in paths]
menu_list_ui_2 = [[folder[0], folder[1], "", False] for folder in paths]
menu_list.append(["Return to Main Menu", "mainmenu", "", True])
menu_list_ui_2.append(["Return to Main Menu", "mainmenu", "", True])
if os.path.abspath("{}/models".format(os.getcwd())) == os.path.abspath(folder):
showdelete=True
else:
showdelete=False
emit('from_server', {'cmd': 'show_model_menu', 'data': menu_list, 'menu': menu, 'breadcrumbs': breadcrumbs, "showdelete": showdelete}, broadcast=True, room="UI_1")
p_menu = [{
"label": m[0],
"name": m[1],
"size": m[2],
"isMenu": m[3],
"isDownloaded": True,
} for m in menu_list_ui_2]
emit('show_model_menu', {'data': p_menu, 'menu': menu, 'breadcrumbs': breadcrumbs, "showdelete": showdelete}, broadcast=False)
elif menu == "customhuggingface":
p_menu = [{
"label": "Return to Main Menu",
"name": "mainmenu",
"size": "",
"isMenu": True,
"isDownloaded": True,
}]
breadcrumbs = []
showdelete=False
emit('from_server', {'cmd': 'show_model_menu', 'data': [["Return to Main Menu", "mainmenu", "", True]], 'menu': menu, 'breadcrumbs': breadcrumbs, "showdelete": showdelete}, broadcast=True, room="UI_1")
emit('show_model_menu', {'data': p_menu, 'menu': menu, 'breadcrumbs': breadcrumbs, "showdelete": showdelete}, broadcast=False)
else:
filtered_menu = [item for item in model_menu[menu] if item.should_show()]
emit(
"from_server",
{
"cmd": "show_model_menu",
"data": [item.to_ui1() for item in filtered_menu],
"menu": menu,
"breadcrumbs": [],
"showdelete": False
},
broadcast=True,
room="UI_1"
)
emit(
"show_model_menu",
{
"data": [item.to_json() for item in filtered_menu],
"menu": menu,
"breadcrumbs": [],
"showdelete": False
},
broadcast=False
)
def get_folder_path_info(base):
if base == 'This PC':
breadcrumbs = [['This PC', 'This PC']]
paths = [["{}:\\".format(chr(i)), "{}:\\".format(chr(i))] for i in range(65, 91) if os.path.exists("{}:".format(chr(i)))]
else:
path = os.path.abspath(base)
if path[-1] == "\\":
path = path[:-1]
breadcrumbs = []
for i in range(len(path.replace("/", "\\").split("\\"))):
breadcrumbs.append(["\\".join(path.replace("/", "\\").split("\\")[:i+1]),
path.replace("/", "\\").split("\\")[i]])
if len(breadcrumbs) == 1:
breadcrumbs = [["{}:\\".format(chr(i)), "{}:\\".format(chr(i))] for i in range(65, 91) if os.path.exists("{}:".format(chr(i)))]
else:
if len([["{}:\\".format(chr(i)), "{}:\\".format(chr(i))] for i in range(65, 91) if os.path.exists("{}:".format(chr(i)))]) > 0:
breadcrumbs.insert(0, ['This PC', 'This PC'])
paths = []
base_path = os.path.abspath(base)
for item in os.listdir(base_path):
if os.path.isdir(os.path.join(base_path, item)):
paths.append([os.path.join(base_path, item), item])
# Paths/breadcrumbs is a list of lists, where the first element in the sublist is the full path and the second is the folder name
return (paths, breadcrumbs)
def getModelSelection(modellist):
print(" # Model\t\t\t\t\t\tVRAM\n ========================================================")
i = 1
for m in modellist:
print(" {0} - {1}\t\t\t{2}".format("{:<2}".format(i), m[0].ljust(25), m[2]))
i += 1
print(" ");
modelsel = 0
koboldai_vars.model = ''
while(koboldai_vars.model == ''):
modelsel = input("Model #> ")
if(modelsel.isnumeric() and int(modelsel) > 0 and int(modelsel) <= len(modellist)):
koboldai_vars.model = modellist[int(modelsel)-1][1]
else:
print("{0}Please enter a valid selection.{1}".format(colors.RED, colors.END))
# Model Lists
try:
getModelSelection(eval(koboldai_vars.model))
except Exception as e:
if(koboldai_vars.model == "Return"):
getModelSelection(mainmenu)
# If custom model was selected, get the filesystem location and store it
if(koboldai_vars.model == "NeoCustom" or koboldai_vars.model == "GPT2Custom"):
print("{0}Please choose the folder where pytorch_model.bin is located:{1}\n".format(colors.CYAN, colors.END))
modpath = fileops.getdirpath(getcwd() + "/models", "Select Model Folder")
if(modpath):
# Save directory to koboldai_vars
koboldai_vars.custmodpth = modpath
else:
# Print error and retry model selection
print("{0}Model select cancelled!{1}".format(colors.RED, colors.END))
print("{0}Select an AI model to continue:{1}\n".format(colors.CYAN, colors.END))
getModelSelection(mainmenu)
def check_if_dir_is_model(path):
return os.path.exists(os.path.join(path, 'config.json'))
#==================================================================#
# Return all keys in tokenizer dictionary containing char
#==================================================================#
#def gettokenids(char):
# keys = []
# for key in vocab_keys:
# if(key.find(char) != -1):
# keys.append(key)
# return keys
#==================================================================#
# Return Model Name
#==================================================================#
def getmodelname():
if(koboldai_vars.online_model != ''):
return(f"{koboldai_vars.model}/{koboldai_vars.online_model}")
if(koboldai_vars.model in ("NeoCustom", "GPT2Custom", "TPUMeshTransformerGPTJ", "TPUMeshTransformerGPTNeoX")):
modelname = os.path.basename(os.path.normpath(koboldai_vars.custmodpth))
return modelname
else:
modelname = koboldai_vars.model if koboldai_vars.model is not None else "Read Only"
return modelname
#==================================================================#