forked from henk717/KoboldAI
-
Notifications
You must be signed in to change notification settings - Fork 0
/
koboldai_settings.py
2864 lines (2557 loc) · 154 KB
/
koboldai_settings.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
from __future__ import annotations
from dataclasses import dataclass
import difflib
import importlib
import os, re, time, threading, json, pickle, base64, copy, tqdm, datetime, sys
import shutil
from typing import List, Union
from io import BytesIO
from flask import has_request_context, session, request
from flask_socketio import join_room, leave_room
from collections import OrderedDict
import multiprocessing
from logger import logger
import torch
import numpy as np
import random
import inspect
serverstarted = False
queue = None
multi_story = False
global enable_whitelist
enable_whitelist = False
slow_tts_message_shown = False
if importlib.util.find_spec("tortoise") is not None:
from tortoise import api
from tortoise.utils.audio import load_voices
password_vars = ["horde_api_key", "privacy_password", "img_gen_api_password"]
def clean_var_for_emit(value):
if isinstance(value, KoboldStoryRegister) or isinstance(value, KoboldWorldInfo):
return value.to_json()
elif isinstance(value, set):
return list(value)
elif isinstance(value, datetime.datetime):
return str(value)
else:
return value
def process_variable_changes(socketio, classname, name, value, old_value, debug_message=None):
global multi_story, koboldai_vars_main
if serverstarted and name != "serverstarted":
transmit_time = str(datetime.datetime.now())
if debug_message is not None:
print("{} {}: {} changed from {} to {}".format(debug_message, classname, name, old_value, value))
if value != old_value:
#Get which room we'll send the messages to
if multi_story:
if classname != 'story':
room = 'UI_2'
else:
if has_request_context():
room = 'default' if 'story' not in session else session['story']
else:
logger.error("We tried to access the story register outside of an http context. Will not work in multi-story mode")
return
else:
room = "UI_2"
#logger.debug("sending data to room (multi_story={},classname={}): {}".format(multi_story, classname, room))
#Special Case for KoboldStoryRegister
if isinstance(value, KoboldStoryRegister):
#To speed up loading time we will only transmit the last 100 actions to the UI, then rely on scrolling triggers to load more as needed
if not has_request_context():
if queue is not None:
#logger.debug("Had to use queue")
queue.put(["var_changed", {"classname": "actions", "name": "Action Count", "old_value": None, "value":value.action_count, "transmit_time": transmit_time}, {"broadcast":True, "room":room}])
data_to_send = []
for i in list(value.actions)[-100:]:
data_to_send.append({"id": i, "action": value.actions[i]})
queue.put(["var_changed", {"classname": "story", "name": "actions", "old_value": None, "value":data_to_send, "transmit_time": transmit_time}, {"broadcast":True, "room":room}])
else:
if socketio is not None:
socketio.emit("var_changed", {"classname": "actions", "name": "Action Count", "old_value": None, "value":value.action_count, "transmit_time": transmit_time}, broadcast=True, room=room)
data_to_send = []
for i in list(value.actions)[-100:]:
data_to_send.append({"id": i, "action": value.actions[i]})
if socketio is not None:
socketio.emit("var_changed", {"classname": "story", "name": "actions", "old_value": None, "value": data_to_send, "transmit_time": transmit_time}, broadcast=True, room=room)
elif isinstance(value, KoboldWorldInfo):
value.send_to_ui()
else:
#If we got a variable change from a thread other than what the app is run it, eventlet seems to block and no further messages are sent. Instead, we'll rely the message to the app and have the main thread send it
if not has_request_context():
if not koboldai_vars_main.host or name not in password_vars:
data = ["var_changed", {"classname": classname, "name": name, "old_value": clean_var_for_emit(old_value), "value": clean_var_for_emit(value), "transmit_time": transmit_time}, {"include_self":True, "broadcast":True, "room":room}]
else:
data = ["var_changed", {"classname": classname, "name": name, "old_value": "*" * len(old_value) if old_value is not None else "", "value": "*" * len(value) if value is not None else "", "transmit_time": transmit_time}, {"include_self":True, "broadcast":True, "room":room}]
if queue is not None:
#logger.debug("Had to use queue")
queue.put(data)
else:
if socketio is not None:
if not koboldai_vars_main.host or name not in password_vars:
socketio.emit("var_changed", {"classname": classname, "name": name, "old_value": clean_var_for_emit(old_value), "value": clean_var_for_emit(value), "transmit_time": transmit_time}, include_self=True, broadcast=True, room=room)
else:
socketio.emit("var_changed", {"classname": classname, "name": name, "old_value": "*" * len(old_value) if old_value is not None else "", "value": "*" * len(value) if value is not None else "", "transmit_time": transmit_time}, include_self=True, broadcast=True, room=room)
def basic_send(socketio, classname, event, data):
#Get which room we'll send the messages to
global multi_story
if multi_story:
if classname != 'story':
room = 'UI_2'
else:
if has_request_context():
room = 'default' if 'story' not in session else session['story']
else:
logger.error("We tried to access the story register outside of an http context. Will not work in multi-story mode")
return
else:
room = "UI_2"
if not has_request_context():
if queue is not None:
#logger.debug("Had to use queue")
queue.put([event, data, {"broadcast":True, "room":room}])
else:
if socketio is not None:
socketio.emit(event, data, include_self=True, broadcast=True, room=room)
class koboldai_vars(object):
def __init__(self, socketio):
self._model_settings = model_settings(socketio, self)
self._user_settings = user_settings(socketio)
self._system_settings = system_settings(socketio, self)
self._story_settings = {'default': story_settings(socketio, self)}
self._undefined_settings = undefined_settings()
self._socketio = socketio
self.tokenizer = None
def get_story_name(self):
global multi_story
if multi_story:
if has_request_context():
story = 'default' if 'story' not in session else session['story']
else:
logger.error("We tried to access the story register outside of an http context. Will not work in multi-story mode")
assert multi_story and has_request_context(), "Tried to access story data outside context in multi_story mode"
else:
story = "default"
return story
def to_json(self, classname):
if classname == 'story_settings':
return self._story_settings[self.get_story_name()].to_json()
# data = {}
# for story in self._story_settings:
# data[story] = json.loads(self._story_settings[story].to_json())
# return json.dumps(data)
return self.__dict__["_{}".format(classname)].to_json()
def load_story(self, story_name, json_data):
#Story name here is intended for multiple users on multiple stories. Now always uses default
#If we can figure out a way to get flask sessions into/through the lua bridge we could re-enable
global multi_story
original_story_name = story_name
if not multi_story:
story_name = 'default'
# Leave the old room and join the new one if in socket context
if hasattr(request, "sid"):
logger.debug("Leaving room {}".format(session['story']))
leave_room(session['story'])
logger.debug("Joining room {}".format(story_name))
join_room(story_name)
session['story'] = story_name
logger.debug("Sending story reset")
self._story_settings[story_name]._socketio.emit("reset_story", {}, broadcast=True, room=story_name)
if story_name in self._story_settings:
self._story_settings[story_name].no_save = True
self._story_settings[story_name].worldinfo_v2.reset()
self._story_settings[story_name].from_json(json_data)
logger.debug("Calcing AI text after load story")
ignore = self.calc_ai_text()
self._story_settings[story_name].no_save = False
else:
#self._story_settings[story_name].no_save = True
self.create_story(story_name, json_data=json_data)
logger.debug("Calcing AI text after create story")
ignore = self.calc_ai_text()
#self._story_settings[story_name].no_save = False
self._system_settings.story_loads[original_story_name] = datetime.datetime.now().strftime("%m/%d/%Y, %H:%M:%S")
with open("settings/system_settings.v2_settings", "w") as settings_file:
settings_file.write(self._system_settings.to_json())
def save_story(self):
logger.debug("Saving story from koboldai_vars.save_story()")
self._story_settings[self.get_story_name()].save_story()
def download_story(self):
return self._story_settings[self.get_story_name()].to_json()
def save_revision(self):
self._story_settings[self.get_story_name()].save_revision()
def create_story(self, story_name, json_data=None):
#Story name here is intended for multiple users on multiple stories. Now always uses default
#If we can figure out a way to get flask sessions into/through the lua bridge we could re-enable
#story_name = 'default'
if not multi_story:
story_name = 'default'
self._story_settings[story_name] = story_settings(self._socketio, self)
#self._story_settings[story_name].reset()
if json_data is not None:
self.load_story(story_name, json_data)
else:
#Leave the old room and join the new one
logger.debug("Leaving room {}".format(session['story']))
leave_room(session['story'])
logger.debug("Joining room {}".format(story_name))
join_room(story_name)
session['story'] = story_name
logger.debug("Sending story reset")
self._story_settings[story_name]._socketio.emit("reset_story", {}, broadcast=True, room=story_name)
self._story_settings[story_name].send_to_ui()
session['story'] = story_name
def story_list(self):
return [x for x in self._story_settings]
def send_to_ui(self):
self._model_settings.send_to_ui()
self._user_settings.send_to_ui()
self._system_settings.send_to_ui()
self._story_settings[self.get_story_name()].send_to_ui()
def reset_model(self):
self._model_settings.reset_for_model_load()
def is_chat_v2(self):
return self.chat_style > 0 and self.chatmode
def get_token_representation(self, text: Union[str, list, None]) -> list:
if not self.tokenizer or not text:
return []
if isinstance(text, str):
encoded = self.tokenizer.encode(text)
else:
encoded = text
# TODO: This might be ineffecient, should we cache some of this?
return [[token, self.tokenizer.decode(token)] for token in encoded]
def calc_ai_text(self, submitted_text=None, return_text=False, send_context=True, allowed_wi_entries=None, allowed_wi_folders=None):
"""Compute the context that would be submitted to the AI.
submitted_text: Optional override to the player-submitted text.
return_text: If True, return the context as a string. Otherwise, return a tuple consisting of:
(tokens, used_tokens, used_tokens+self.genamt, set(used_world_info))
send_context: If True, the context is prepared for submission to the AI (by marking used world info and setting self.context
allowed_wi_entries: If not None, only world info entries with uids in the given set are allowed to be used.
allowed_wi_folders: If not None, only world info folders with uids in the given set are allowed to be used.
"""
#start_time = time.time()
if self.tokenizer is None:
if return_text:
return ""
return [], 0, 0+self.genamt, []
if self.alt_gen:
method = 2
else:
method = 1
#Context and Game Context are lists of chunks of text that will go to the AI. Game Context will be appended after context when we're done
context = []
game_context = []
token_budget = self.max_length - self.genamt
used_world_info = []
used_tokens = 0 if self.sp_length is None else self.sp_length + len(self.tokenizer._koboldai_header)
if self.sp_length > 0:
context.append({"type": "soft_prompt", "text": f"<{self.sp_length} tokens of Soft Prompt.>", "tokens": [[-1, ""]] * self.sp_length})
if send_context:
self.worldinfo_v2.reset_used_in_game()
def allow_wi(wi):
"""Return True if adding this world info entry is allowed."""
wi_uid = wi['uid']
if wi_uid in used_world_info:
return False
if wi["type"] == "commentator" and not (allowed_wi_entries and wi_uid in allowed_wi_entries):
return False
if allowed_wi_entries is not None and wi_uid not in allowed_wi_entries:
return False
if allowed_wi_folders is not None and wi['folder'] not in allowed_wi_folders:
return False
return True
# Add Genres #
if self.genres:
# Erebus, Nerys, Janeway, Picard (probably)
genre_template = "[Genre: %s]"
model_name = self.model.lower()
if "skein" in model_name or "adventure" in model_name:
genre_template = "[Themes: %s]"
elif "shinen" in model_name:
genre_template = "[Theme: %s]"
genre_text = genre_template % (", ".join(self.genres))
genre_tokens = self.tokenizer.encode(genre_text)
genre_data = [[x, self.tokenizer.decode(x)] for x in genre_tokens]
context.append({
"type": "genre",
"text": genre_text,
"tokens": genre_data,
})
used_tokens += len(genre_tokens)
######################################### Add memory ########################################################
max_memory_length = int(token_budget * self.max_memory_fraction)
memory_text = self.memory
if memory_text != "":
if memory_text[-1] not in [" ", '\n']:
memory_text += " "
memory_tokens = self.tokenizer.encode(memory_text)
else:
memory_tokens = []
if len(memory_tokens) > max_memory_length:
memory_tokens = memory_tokens[:max_memory_length]
memory_length = max_memory_length
memory_data = [[x, self.tokenizer.decode(x)] for x in memory_tokens]
#We have so much memory that we've run out of budget without going over the max_memory_length. Just stop
if len(memory_tokens) > token_budget:
return [], 0, 0+self.genamt, []
#Actually Add Memory
if len(memory_tokens) != 0:
context.append({"type": "memory",
"text": "".join([x[1] for x in memory_data]),
"tokens": memory_data,
"attention_multiplier": self.memory_attn_bias})
used_tokens += len(memory_tokens)
######################################### Constant World Info ########################################################
#Add constant world info entries to memory
for wi in self.worldinfo_v2:
if wi['constant'] and allow_wi(wi):
wi_length = len(self.tokenizer.encode(wi['content']))
if used_tokens + wi_length <= token_budget:
used_tokens+=wi_length
used_world_info.append(wi['uid'])
if send_context:
self.worldinfo_v2.set_world_info_used(wi['uid'])
wi_text = wi['content']+" " if wi['content'] != "" and wi['content'][-1] not in [" ", "\n"] else wi['content']
wi_tokens = self.tokenizer.encode(wi_text)
context.append({
"type": "world_info",
"text": wi_text,
"uid": wi['uid'],
"tokens": [[x, self.tokenizer.decode(x)] for x in wi_tokens],
})
used_tokens += len(wi_tokens)
######################################### Get Action Text by Sentence ########################################################
action_text_split = self.actions.to_sentences(submitted_text=submitted_text)
# Always add newlines on chat v2
if action_text_split and self.is_chat_v2():
action_text_split[-1][0] = action_text_split[-1][0].strip() + "\n"
######################################### Prompt ########################################################
#Add prompt length/text if we're set to always use prompt
if self.useprompt:
prompt_length = 0
prompt_data = []
for item in reversed(action_text_split):
if -1 in item[1]:
tokenized_data = [[x, self.tokenizer.decode(x)] for x in self.tokenizer.encode(item[0])]
item[2] = len(tokenized_data)
if prompt_length + item[2] <= self.max_prompt_length:
prompt_length += item[2]
item[3] = True
prompt_data = tokenized_data + prompt_data
prompt_text = self.tokenizer.decode([x[0] for x in prompt_data])
#wi_search = re.sub("[^A-Za-z\ 0-9\'\"]", "", prompt_text)
wi_search = prompt_text
if prompt_length + used_tokens <= token_budget:
used_tokens += prompt_length
#We'll add the prompt text AFTER we go through the game text as the world info needs to come first if we're in method 1 rather than method 2
self.prompt_in_ai = True
#Find World Info entries in prompt
for wi in self.worldinfo_v2:
if allow_wi(wi):
#Check to see if we have the keys/secondary keys in the text so far
match = False
for key in wi['key']:
if key in wi_search:
match = True
break
if wi['selective'] and match:
match = False
for key in wi['keysecondary']:
if key in wi_search:
match=True
break
if match:
wi_length = len(self.tokenizer.encode(wi['content']))
if used_tokens+wi_length <= token_budget:
used_tokens+=wi_length
used_world_info.append(wi['uid'])
wi_text = wi['content']+" " if wi['content'] != "" and wi['content'][-1] not in [" ", "\n"] else wi['content']
wi_tokens = self.tokenizer.encode(wi_text)
context.append({
"type": "world_info",
"text": wi_text,
"uid": wi['uid'],
"tokens": [[x, self.tokenizer.decode(x)] for x in wi_tokens],
})
used_tokens += len(wi_tokens)
if send_context:
self.worldinfo_v2.set_world_info_used(wi['uid'])
else:
self.prompt_in_ai = False
######################################### Setup Author's Note Data ########################################################
authors_note_text = self.authornotetemplate.replace("<|>", self.authornote)
if len(authors_note_text) > 0 and authors_note_text[0] not in [" ", "\n"]:
authors_note_text = " " + authors_note_text
authors_note_data = [[x, self.tokenizer.decode(x)] for x in self.tokenizer.encode(authors_note_text)]
if used_tokens + len(authors_note_data) <= token_budget:
used_tokens += len(authors_note_data)
######################################### Actions ########################################################
#Start going through the actions backwards, adding it to the text if it fits and look for world info entries
used_all_tokens = False
actions_seen = [] #Used to track how many actions we've seen so we can insert author's note in the appropriate place as well as WI depth stop
inserted_author_note = False
sentences_seen = 0
for i in range(len(action_text_split)-1, -1, -1):
if action_text_split[i][3]:
#We've hit an item we've already included. Stop
break
sentences_seen += 1
#Add our author's note if we've hit andepth
if not inserted_author_note and len(actions_seen) >= self.andepth and sentences_seen > self.andepth and self.authornote != "":
game_context.insert(0, {"type": "authors_note", "text": authors_note_text, "tokens": authors_note_data, "attention_multiplier": self.an_attn_bias})
inserted_author_note = True
# Add to actions_seen after potentially inserting the author note, since we want to insert the author note
# after the sentence that pushes our action count above the author note depth.
for action in action_text_split[i][1]:
if action not in actions_seen:
actions_seen.append(action)
action_data = [[x, self.tokenizer.decode(x)] for x in self.tokenizer.encode(action_text_split[i][0])]
length = len(action_data)
if length+used_tokens <= token_budget:
used_tokens += length
action_text_split[i][3] = True
action_type = "action"
if action_text_split[i][1] == [self.actions.action_count+1]:
action_type = "submit"
elif -1 in action_text_split[i][1]:
action_type = "prompt"
game_context.insert(0, {
"type": action_type,
"text": action_text_split[i][0],
"tokens": action_data,
"action_ids": action_text_split[i][1]
})
wi_search = action_text_split[i][0]
#Now we need to check for used world info entries
for wi in self.worldinfo_v2:
if allow_wi(wi):
#Check to see if we have the keys/secondary keys in the text so far
match = False
for key in wi['key']:
if key in wi_search:
match = True
break
if wi['selective'] and match:
match = False
for key in wi['keysecondary']:
if key in wi_search:
match=True
break
if method == 1:
if len(actions_seen) > self.widepth and sentences_seen > self.widepth:
match = False
if match:
wi_length = len(self.tokenizer.encode(wi['content']))
if used_tokens+wi_length <= token_budget:
used_tokens+=wi_length
used_world_info.append(wi['uid'])
wi_text = wi['content']+" " if wi['content'] != "" and wi['content'][-1] not in [" ", "\n"] else wi['content']
wi_tokens = self.tokenizer.encode(wi_text)
if method == 1:
context.append({
"type": "world_info",
"text": wi_text,
"uid": wi['uid'],
"tokens": [[x, self.tokenizer.decode(x)] for x in wi_tokens],
})
else:
#for method 2 we add the game text before the current action
game_context.insert(0, {
"type": "world_info",
"text": wi_text,
"uid": wi['uid'],
"tokens": [[x, self.tokenizer.decode(x)] for x in wi_tokens],
})
used_tokens += len(wi_tokens)
if send_context:
self.worldinfo_v2.set_world_info_used(wi['uid'])
else:
used_all_tokens = True
break
######################################### Verify Author's Note Data in AI Text ########################################################
#if we don't have enough actions to get to author's note depth then we just add it right before the game text
if not inserted_author_note and self.authornote != "":
game_context.insert(0, {"type": "authors_note", "text": authors_note_text, "tokens": authors_note_data, "attention_multiplier": self.an_attn_bias})
######################################### Add our prompt data ########################################################
if self.useprompt and len(prompt_data) != 0:
context.append({"type": "prompt", "text": prompt_text, "tokens": prompt_data})
context += game_context
if len(context) == 0:
tokens = []
else:
tokens = []
for item in context:
if item['type'] != 'soft_prompt':
tokens.extend([x[0] for x in item['tokens']])
if send_context:
self.context = context
#logger.debug("Calc_AI_text: {}s".format(time.time()-start_time))
logger.debug("Token Budget: {}. Used Tokens: {}".format(token_budget, used_tokens))
if return_text:
return "".join([x['text'] for x in context])
return tokens, used_tokens, used_tokens+self.genamt, set(used_world_info)
def is_model_torch(self) -> bool:
if self.use_colab_tpu:
return False
if self.model in ["Colab", "API", "CLUSTER", "ReadOnly", "OAI"]:
return False
return True
def assign_world_info_to_actions(self, *args, **kwargs):
self._story_settings[self.get_story_name()].assign_world_info_to_actions(*args, **kwargs)
def reset_for_model_load(self):
self._model_settings.reset_for_model_load()
def __setattr__(self, name, value):
if name[0] == "_" or name == "tokenizer":
super().__setattr__(name, value)
if name[0] != "_":
#Send it to the corrent _setting class
if name in self._model_settings.__dict__:
setattr(self._model_settings, name, value)
elif name in self._user_settings.__dict__:
setattr(self._user_settings, name, value)
elif name in self._system_settings.__dict__:
setattr(self._system_settings, name, value)
elif name in self._story_settings[self.get_story_name()].__dict__:
setattr(self._story_settings[self.get_story_name()], name, value)
else:
setattr(self._undefined_settings, name, value)
def __getattr__(self, name):
if name in self.__dict__:
return getattr(self, name)
elif name in self._model_settings.__dict__ or hasattr(self._model_settings, name):
return getattr(self._model_settings, name)
elif name in self._user_settings.__dict__ or hasattr(self._user_settings, name):
return getattr(self._user_settings, name)
elif name in self._system_settings.__dict__ or hasattr(self._system_settings, name):
return getattr(self._system_settings, name)
elif name in self._story_settings[self.get_story_name()].__dict__ or hasattr(self._story_settings[self.get_story_name()], name):
return getattr(self._story_settings[self.get_story_name()], name)
else:
return getattr(self._undefined_settings, name)
class settings(object):
def to_json(self):
json_data = {'file_version': 2}
for (name, value) in vars(self).items():
if name not in self.no_save_variables and name[0] != "_":
json_data[name] = value
def to_base64(data):
if isinstance(data, KoboldStoryRegister):
return data.to_json()
elif isinstance(data, KoboldWorldInfo):
return data.to_json()
elif isinstance(data, datetime.datetime):
return str(data)
output = BytesIO()
pickle.dump(data, output)
output.seek(0)
return "base64:{}".format(base64.encodebytes(output.read()).decode())
return json.dumps(json_data, default=to_base64, indent="\t")
def from_json(self, data):
if isinstance(data, str):
json_data = json.loads(data)
else:
json_data = data
#since loading will trigger the autosave, we need to disable it
if 'no_save' in self.__dict__:
setattr(self, 'no_save', True)
for key, value in json_data.items():
start_time = time.time()
if key in self.__dict__ and key not in self.no_save_variables:
if key == 'sampler_order':
if(len(value) < 7):
value = [6] + value
elif key == 'autosave':
autosave = value
elif key in ['worldinfo_u', 'wifolders_d']:
# Fix UID keys to be ints
value = {int(k): v for k, v in value.items()}
if isinstance(value, str):
if value[:7] == 'base64:':
value = pickle.loads(base64.b64decode(value[7:]))
#Need to fix the data type of value to match the module
if type(getattr(self, key)) == int:
setattr(self, key, int(value))
elif type(getattr(self, key)) == float:
setattr(self, key, float(value))
elif type(getattr(self, key)) == bool:
setattr(self, key, bool(value))
elif type(getattr(self, key)) == str:
setattr(self, key, str(value))
elif isinstance(getattr(self, key), KoboldStoryRegister):
getattr(self, key).load_json(value)
elif isinstance(getattr(self, key), KoboldWorldInfo):
getattr(self, key).load_json(value)
else:
setattr(self, key, value)
logger.debug("Loading {} took {}s".format(key, time.time()- start_time))
#check from prompt_wi_highlighted_text since that wasn't always in the V2 save format
if 'prompt' in json_data and 'prompt_wi_highlighted_text' not in json_data:
self.prompt_wi_highlighted_text[0]['text'] = self.prompt
self.assign_world_info_to_actions(action_id=-1)
process_variable_changes(self._socketio, "story", 'prompt_wi_highlighted_text', self.prompt_wi_highlighted_text, None)
if 'no_save' in self.__dict__:
setattr(self, 'no_save', False)
def send_to_ui(self):
for (name, value) in vars(self).items():
if name not in self.local_only_variables and name[0] != "_":
try:
process_variable_changes(self._socketio, self.__class__.__name__.replace("_settings", ""), name, value, None)
except:
print("{} is of type {} and I can't transmit".format(name, type(value)))
raise
class model_settings(settings):
local_only_variables = ['apikey', 'default_preset']
no_save_variables = ['modelconfig', 'custmodpth', 'generated_tkns',
'loaded_layers', 'total_layers', 'loaded_checkpoints', 'total_checkpoints',
'total_download_chunks', 'downloaded_chunks', 'presets', 'default_preset',
'welcome', 'welcome_default', 'simple_randomness', 'simple_creativity', 'simple_repitition',
'badwordsids', 'uid_presets', 'model', 'model_type', 'lazy_load', 'fp32_model', 'modeldim', 'horde_wait_time', 'horde_queue_position', 'horde_queue_size', 'newlinemode', 'tqdm_progress', 'tqdm_rem_time', '_tqdm']
settings_name = "model"
default_settings = {"rep_pen" : 1.1, "rep_pen_slope": 1.0, "rep_pen_range": 2048, "temp": 0.5, "top_p": 0.9, "top_k": 0, "top_a": 0.0, "tfs": 1.0, "typical": 1.0,
"sampler_order": [6,0,1,2,3,4,5]}
def __init__(self, socketio, koboldai_vars):
self.enable_whitelist = False
self._socketio = socketio
self.reset_for_model_load()
self.model = "" # Model ID string chosen at startup
self.model_type = "" # Model Type (Automatically taken from the model config)
self.modelconfig = {} # Raw contents of the model's config.json, or empty dictionary if none found
self.custmodpth = "" # Filesystem location of custom model to run
self.generated_tkns = 0 # If using a backend that supports Lua generation modifiers, how many tokens have already been generated, otherwise 0
self.loaded_layers = 0 # Used in UI 2 to show model loading progress
self.total_layers = 0 # Same as above
self.loaded_checkpoints = 0
self.total_checkpoints = 1
self.total_download_chunks = 0 # tracks how much of the model has downloaded for the UI 2
self.downloaded_chunks = 0 #as above
self._tqdm = tqdm.tqdm(total=self.genamt, file=self.ignore_tqdm()) # tqdm agent for generating tokens. This will allow us to calculate the remaining time
self.tqdm_progress = 0 # TQDP progress
self.tqdm_rem_time = 0 # tqdm calculated reemaining time
self.configname = None
self.online_model = ''
self.welcome_default = """<style>#welcome_container { display: block; } #welcome_text { display: flex; height: 100%; } .welcome_text { align-self: flex-end; }</style>
<div id='welcome-logo-container'><img id='welcome-logo' src='static/Welcome_Logo.png' draggable='False'></div>
<div class='welcome_text'>
<div id="welcome-text-content">Please load a model from the left.<br/>
If you encounter any issues, please click the Download debug dump link in the Home tab on the left flyout and attach the downloaded file to your error report on <a href='https://github.com/ebolam/KoboldAI/issues'>Github</a>, <a href='https://www.reddit.com/r/KoboldAI/'>Reddit</a>, or <a href='https://koboldai.org/discord'>Discord</a>.
A redacted version (without story text) is available.
</div>
</div>""" # Custom Welcome Text
self.welcome = self.welcome_default
self._koboldai_vars = koboldai_vars
self.alt_multi_gen = False
self.bit_8_available = None
self.use_default_badwordsids = True
self.supported_gen_modes = []
def reset_for_model_load(self):
self.simple_randomness = 0 #Set first as this affects other outputs
self.simple_creativity = 0 #Set first as this affects other outputs
self.simple_repitition = 0 #Set first as this affects other outputs
self.max_length = 2048 # Maximum number of tokens to submit per action
self.ikmax = 3000 # Maximum number of characters to submit to InferKit
self.genamt = 200 # Amount of text for each action to generate
self.ikgen = 200 # Number of characters for InferKit to generate
self.rep_pen = 1.1 # Default generator repetition_penalty
self.rep_pen_slope = 1.0 # Default generator repetition penalty slope
self.rep_pen_range = 2048 # Default generator repetition penalty range
self.temp = 0.5 # Default generator temperature
self.top_p = 0.9 # Default generator top_p
self.top_k = 0 # Default generator top_k
self.top_a = 0.0 # Default generator top-a
self.tfs = 1.0 # Default generator tfs (tail-free sampling)
self.typical = 1.0 # Default generator typical sampling threshold
self.numseqs = 1 # Number of sequences to ask the generator to create
self.generated_tkns = 0 # If using a backend that supports Lua generation modifiers, how many tokens have already been generated, otherwise 0
self.badwordsids = []
self.fp32_model = False # Whether or not the most recently loaded HF model was in fp32 format
self.modeldim = -1 # Embedding dimension of your model (e.g. it's 4096 for GPT-J-6B and 2560 for GPT-Neo-2.7B)
self.sampler_order = [6, 0, 1, 2, 3, 4, 5]
self.newlinemode = "n"
self.presets = [] # Holder for presets
self.selected_preset = ""
self.uid_presets = []
self.default_preset = {}
self.horde_wait_time = 0
self.horde_queue_position = 0
self.horde_queue_size = 0
self.use_alt_rep_pen = False
#dummy class to eat the tqdm output
class ignore_tqdm(object):
def write(self, bar):
pass
def __setattr__(self, name, value):
new_variable = name not in self.__dict__
old_value = getattr(self, name, None)
super().__setattr__(name, value)
#Put variable change actions here
if name in ['simple_randomness', 'simple_creativity', 'simple_repitition'] and not new_variable:
#We need to disable all of the samplers
self.top_k = 0
self.top_a = 0.0
self.tfs = 1.0
self.typical = 1.0
self.rep_pen_range = 1024
self.rep_pen_slope = 0.7
#Now we setup our other settings
if self.simple_randomness < 0:
self.temp = default_rand_range[1]+(default_rand_range[1]-default_rand_range[0])/100*self.simple_randomness
else:
self.temp = default_rand_range[1]+(default_rand_range[2]-default_rand_range[1])/100*self.simple_randomness
self.top_p = (default_creativity_range[1]-default_creativity_range[0])/200*self.simple_creativity+sum(default_creativity_range)/2
self.rep_pen = (default_rep_range[1]-default_rep_range[0])/200*self.simple_repitition+sum(default_rep_range)/2
if not new_variable and (name == 'max_length' or name == 'genamt'):
ignore = self._koboldai_vars.calc_ai_text()
#set preset values
if name == 'selected_preset' and value != "":
logger.info("Changing preset to {}".format(value))
if value in self.uid_presets:
for default_key, default_value in self.default_settings.items():
setattr(self, default_key, default_value)
for preset_key, preset_value in self.uid_presets[value].items():
if preset_key in self.__dict__:
if type(getattr(self, preset_key)) == int:
preset_value = int(preset_value)
elif type(getattr(self, preset_key)) == float:
preset_value = float(preset_value)
elif type(getattr(self, preset_key)) == bool:
preset_value = bool(preset_value)
elif type(getattr(self, preset_key)) == str:
preset_value = str(preset_value)
if preset_key == "sampler_order":
if 6 not in preset_value:
preset_value.insert(0, 6)
setattr(self, preset_key, preset_value)
#Setup TQDP for token generation
elif name == "generated_tkns" and '_tqdm' in self.__dict__:
if value == 0:
self._tqdm.reset(total=self.genamt * (self.numseqs if self.alt_multi_gen else 1) )
self.tqdm_progress = 0
else:
self._tqdm.update(value-self._tqdm.n)
self.tqdm_progress = int(float(self.generated_tkns)/float(self.genamt * (self.numseqs if self.alt_multi_gen else 1))*100)
if self._tqdm.format_dict['rate'] is not None:
self.tqdm_rem_time = str(datetime.timedelta(seconds=int(float((self.genamt * (self.numseqs if self.alt_multi_gen else 1))-self.generated_tkns)/self._tqdm.format_dict['rate'])))
#Setup TQDP for model loading
elif name == "loaded_layers" and '_tqdm' in self.__dict__:
if value == 0:
self._tqdm.reset(total=self.total_layers if self.total_checkpoints == 1 else 1000)
self.tqdm_progress = 0
else:
if self.total_checkpoints == 1:
self._tqdm.update(1)
elif self.total_layers != 0 and self.total_checkpoints != 0:
proper_progress = (self.loaded_checkpoints + value/self.total_layers)/self.total_checkpoints*1000
self._tqdm.update(proper_progress - self._tqdm.n)
self.tqdm_progress = int(float(self._tqdm.n)/float(self._tqdm.total)*100)
if self._tqdm.format_dict['rate'] is not None:
elapsed = self._tqdm.format_dict["elapsed"]
rate = self._tqdm.format_dict["rate"]
remaining = (self._tqdm.total - self._tqdm.n) / rate if rate and self._tqdm.total else 0
self.tqdm_rem_time = str(datetime.timedelta(seconds=remaining))
#Setup TQDP for model downloading
elif name == "total_download_chunks" and '_tqdm' in self.__dict__:
self._tqdm.reset(total=value)
self.tqdm_progress = 0
elif name == "downloaded_chunks" and '_tqdm' in self.__dict__:
if value == 0:
self._tqdm.reset(total=self.total_download_chunks)
self.tqdm_progress = 0
else:
self._tqdm.update(value-old_value)
if self.total_download_chunks is not None:
if self.total_download_chunks==0:
self.tqdm_progress = 0
elif float(self.downloaded_chunks) > float(self.total_download_chunks):
self.tqdm_progress = 100
else:
self.tqdm_progress = round(float(self.downloaded_chunks)/float(self.total_download_chunks)*100, 1)
else:
self.tqdm_progress = 0
if self._tqdm.format_dict['rate'] is not None:
self.tqdm_rem_time = str(datetime.timedelta(seconds=int(float(self.total_download_chunks-self.downloaded_chunks)/self._tqdm.format_dict['rate'])))
if name not in self.local_only_variables and name[0] != "_" and not new_variable:
process_variable_changes(self._socketio, self.__class__.__name__.replace("_settings", ""), name, value, old_value)
class story_settings(settings):
local_only_variables = ['tokenizer', 'no_save', 'revisions', 'prompt', 'save_paths']
no_save_variables = ['tokenizer', 'context', 'no_save', 'prompt_in_ai', 'authornote_length', 'prompt_length', 'memory_length', 'save_paths']
settings_name = "story"
def __init__(self, socketio, koboldai_vars, tokenizer=None):
self._socketio = socketio
self.tokenizer = tokenizer
self._koboldai_vars = koboldai_vars
self.privacy_mode = False
self.privacy_password = ""
self.story_name = "New Game" # Title of the story
self.lastact = "" # The last action received from the user
self.submission = "" # Same as above, but after applying input formatting
self.lastctx = "" # The last context submitted to the generator
self.gamestarted = False # Whether the game has started (disables UI elements)
self.gamesaved = True # Whether or not current game is saved
self.autosave = False # Whether or not to automatically save after each action
self.prompt = "" # Prompt
self.prompt_wi_highlighted_text = [{"text": self.prompt, "WI matches": None, "WI Text": ""}]
self.memory = "" # Text submitted to memory field
self.auto_memory = ""
self.authornote = "" # Text submitted to Author's Note field
self.authornotetemplate = "[Author's note: <|>]" # Author's note template
self.setauthornotetemplate = self.authornotetemplate # Saved author's note template in settings
self.andepth = 3 # How far back in history to append author's note
self.actions = KoboldStoryRegister(socketio, self, koboldai_vars, tokenizer=tokenizer) # Actions submitted by user and AI
self.actions_metadata = {} # List of dictonaries, one dictonary for every action that contains information about the action like alternative options.
# Contains at least the same number of items as actions. Back action will remove an item from actions, but not actions_metadata
# Dictonary keys are:
# Selected Text: (text the user had selected. None when this is a newly generated action)
# Alternative Generated Text: {Text, Pinned, Previous Selection, Edited}
#
self.worldinfo_v2 = KoboldWorldInfo(socketio, self, koboldai_vars, tokenizer=self.tokenizer)
self.worldinfo = [] # List of World Info key/value objects
self.worldinfo_i = [] # List of World Info key/value objects sans uninitialized entries
self.worldinfo_u = {} # Dictionary of World Info UID - key/value pairs
self.wifolders_d = {} # Dictionary of World Info folder UID-info pairs
self.wifolders_l = [] # List of World Info folder UIDs
self.wifolders_u = {} # Dictionary of pairs of folder UID - list of WI UID
self.lua_edited = set() # Set of chunk numbers that were edited from a Lua generation modifier
self.lua_deleted = set() # Set of chunk numbers that were deleted from a Lua generation modifier
self.deletewi = None # Temporary storage for UID to delete
self.mode = "play" # Whether the interface is in play, memory, or edit mode
self.editln = 0 # Which line was last selected in Edit Mode
self.genseqs = [] # Temporary storage for generated sequences
self.recentback = False # Whether Back button was recently used without Submitting or Retrying after
self.recentrng = None # If a new random game was recently generated without Submitting after, this is the topic used (as a string), otherwise this is None
self.recentrngm = None # If a new random game was recently generated without Submitting after, this is the memory used (as a string), otherwise this is None
self.useprompt = False # Whether to send the full prompt with every submit action
self.chatmode = False
self.chatname = "You"
self.botname = "Bot"
self.stop_sequence = [] #use for configuring stop sequences
self.adventure = False
self.actionmode = 0
self.storymode = 0
self.dynamicscan = False
self.recentedit = False
self.notes = "" #Notes for the story. Does nothing but save
self.biases = {} # should look like {"phrase": [score, completion_threshold]}
self.story_id = int.from_bytes(os.urandom(16), 'little', signed=True) # this is a unique ID for the story. We'll use this to ensure when we save that we're saving the same story
self.memory_length = 0
self.prompt_length = 0
self.authornote_length = 0
self.max_memory_fraction = 0.5 # Tokens from memory are allowed to use this much of the token budget
self.max_prompt_length = 512
self.max_authornote_length = 512
self.prompt_in_ai = False
self.context = []
self.last_story_load = None
self.revisions = []
self.picture = "" #base64 of the image shown for the story
self.picture_prompt = "" #Prompt used to create picture
self.substitutions = [
{"target": "--", "substitution": "–", "enabled": False},
{"target": "---", "substitution": "—", "enabled": False},
{"target": "...", "substitution": "…", "enabled": False},
# {"target": "(c)", "substitution": "©", "enabled": False},
# {"target": "(r)", "substitution": "®", "enabled": False},
# {"target": "(tm)", "substitution": "™", "enabled": False},
]
self.gen_audio = False
self.prompt_picture_filename = ""
self.prompt_picture_prompt = ""
# It's important to only use "=" syntax on this to ensure syncing; no
# .append() or the like
self.genres = []
# bias experiment
self.memory_attn_bias = 1
self.an_attn_bias = 1
self.chat_style = 0
# In percent!!!
self.commentary_chance = 0
self.commentary_enabled = False
self.save_paths = SavePaths(os.path.join("stories", self.story_name or "Untitled"))
################### must be at bottom #########################
self.no_save = False #Temporary disable save (doesn't save with the file)
def save_story(self) -> None:
if self.no_save:
return
if not any([self.prompt, self.memory, self.authornote, len(self.actions), len(self.worldinfo_v2)]):
return
logger.info("Saving")
save_name = self.story_name or "Untitled"
# Disambiguate stories by adding (n) if needed
disambiguator = 0
self.save_paths.base = os.path.join("stories", save_name)
while os.path.exists(self.save_paths.base):
try:
# If the stories share a story id, overwrite the existing one.
with open(self.save_paths.story, "r", encoding="utf-8") as file:
j = json.load(file)
if self.story_id == j["story_id"]: