Skip to content

Commit ec04115

Browse files
committed
swa options now available
1 parent 748dfcc commit ec04115

File tree

4 files changed

+67
-50
lines changed

4 files changed

+67
-50
lines changed

gpttype_adapter.cpp

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1927,10 +1927,16 @@ ModelLoadResult gpttype_load_model(const load_model_inputs inputs, FileFormat in
19271927
kcpp_data->use_smartcontext = inputs.use_smartcontext;
19281928
kcpp_data->use_contextshift = inputs.use_contextshift;
19291929
kcpp_data->use_fastforward = inputs.use_fastforward;
1930-
kcpp_data->swa_full = !inputs.swa_support;//(inputs.use_fastforward || inputs.use_contextshift)?true:false;
1931-
if(!kcpp_data->swa_full)
1932-
{
1933-
printf("\n!!!!!!!!!!!!!!!!!!!\nExperimental FLAG - SWA SUPPORT IS ENABLED!\n!!!!!!!!!!!!!!!!!!!\n");
1930+
kcpp_data->swa_full = !inputs.swa_support;
1931+
if (!kcpp_data->swa_full) {
1932+
if (inputs.use_contextshift) {
1933+
kcpp_data->swa_full = true; //cannot use SWA
1934+
printf("\nSWA Mode IS DISABLED!\nSWA Mode Cannot be used with Context Shifting!\n");
1935+
} else if (inputs.use_fastforward) {
1936+
printf("\nSWA Mode is ENABLED!\nNote that using SWA Mode with Fast Forwarding can lead to degraded recall!\n");
1937+
} else {
1938+
printf("\nSWA Mode IS ENABLED!\n");
1939+
}
19341940
}
19351941
debugmode = inputs.debugmode;
19361942
draft_ctx = nullptr;

klite.embd

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9932,7 +9932,9 @@ Current version indicated by LITEVER below.
99329932

99339933
function toggleclaudemodel()
99349934
{
9935-
if (document.getElementById("custom_claude_model").value.toLowerCase().includes("claude-3"))
9935+
if (document.getElementById("custom_claude_model").value.toLowerCase().includes("claude-3")
9936+
|| document.getElementById("custom_claude_model").value.toLowerCase().includes("claude-sonnet-4")
9937+
|| document.getElementById("custom_claude_model").value.toLowerCase().includes("claude-opus-4"))
99369938
{
99379939
document.getElementById("claudesystemprompt").classList.remove("hidden");
99389940
document.getElementById("claudejailbreakprompt").classList.remove("hidden");
@@ -15815,7 +15817,9 @@ Current version indicated by LITEVER below.
1581515817
}
1581615818
else if (custom_claude_key != "")//handle for Claude
1581715819
{
15818-
let claudev3mode = custom_claude_model.toLowerCase().includes("claude-3");
15820+
let claudev3mode = custom_claude_model.toLowerCase().includes("claude-3")
15821+
|| custom_claude_model.toLowerCase().includes("claude-sonnet-4")
15822+
|| custom_claude_model.toLowerCase().includes("claude-opus-4");
1581915823
let actualep = (custom_claude_endpoint + (claudev3mode?claude_submit_endpoint_v3:claude_submit_endpoint));
1582015824
let targetep = actualep;
1582115825
if(custom_claude_endpoint.toLowerCase().includes("api.anthropic.com"))
@@ -23892,6 +23896,8 @@ Current version indicated by LITEVER below.
2389223896
<option value="claude-3-5-sonnet-latest" selected="selected">claude-3-5-sonnet-latest</option>
2389323897
<option value="claude-3-5-haiku-20241022">claude-3-5-haiku-20241022</option>
2389423898
<option value="claude-3-7-sonnet-20250219">claude-3-7-sonnet-20250219</option>
23899+
<option value="claude-sonnet-4-latest">claude-sonnet-4-latest</option>
23900+
<option value="claude-opus-4-latest">claude-opus-4-latest</option>
2389523901
</select>
2389623902
<button type="button" class="btn btn-primary" style="display:inline;width:105px;" id="claudefetchlist" onclick="claude_fetch_models()">Fetch List</button>
2389723903
<input type="checkbox" title="Add endpoint version" id="claudeaddversion" onchange="" checked>

koboldcpp.py

Lines changed: 48 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1249,7 +1249,7 @@ def load_model(model_filename):
12491249
inputs.override_kv = args.overridekv.encode("UTF-8") if args.overridekv else "".encode("UTF-8")
12501250
inputs.override_tensors = args.overridetensors.encode("UTF-8") if args.overridetensors else "".encode("UTF-8")
12511251
inputs.check_slowness = (not args.highpriority and os.name == 'nt' and 'Intel' in platform.processor())
1252-
inputs.swa_support = args.experiment_swa
1252+
inputs.swa_support = args.useswa
12531253
inputs = set_backend_props(inputs)
12541254
ret = handle.load_model(inputs)
12551255
return ret
@@ -2208,7 +2208,7 @@ def transform_genparams(genparams, api_format):
22082208
user_end = assistant_message_start
22092209
if chosen_tool=="auto":
22102210
# if you want a different template, you can set 'custom_tools_prompt' in the chat completions adapter as follows
2211-
custom_tools_prompt = adapter_obj.get("custom_tools_prompt", "Can the user query be answered by a listed tool? (One word response: yes or no):")
2211+
custom_tools_prompt = adapter_obj.get("custom_tools_prompt", "Can the user query be answered by a listed tool above? (One word response: yes or no):")
22122212
# note: message string already contains the instruct start tag!
22132213
pollgrammar = r'root ::= "yes" | "no" | "Yes" | "No" | "YES" | "NO"'
22142214
temp_poll = {
@@ -4088,11 +4088,12 @@ def hide_tooltip(event):
40884088
tensor_split_str_vars = ctk.StringVar(value="")
40894089
rowsplit_var = ctk.IntVar()
40904090

4091-
contextshift = ctk.IntVar(value=1)
4092-
fastforward = ctk.IntVar(value=1)
4093-
remotetunnel = ctk.IntVar(value=0)
4094-
smartcontext = ctk.IntVar()
4095-
flashattention = ctk.IntVar(value=0)
4091+
contextshift_var = ctk.IntVar(value=1)
4092+
fastforward_var = ctk.IntVar(value=1)
4093+
swa_var = ctk.IntVar(value=0)
4094+
remotetunnel_var = ctk.IntVar(value=0)
4095+
smartcontext_var = ctk.IntVar()
4096+
flashattention_var = ctk.IntVar(value=0)
40964097
context_var = ctk.IntVar()
40974098
customrope_var = ctk.IntVar()
40984099
customrope_scale = ctk.StringVar(value="1.0")
@@ -4459,7 +4460,7 @@ def gui_changed_modelfile(*args):
44594460
pass
44604461

44614462
def changed_gpulayers_estimate(*args):
4462-
predicted_gpu_layers = autoset_gpu_layers(int(contextsize_text[context_var.get()]),(sd_quant_var.get()==1),int(blasbatchsize_values[int(blas_size_var.get())]),(quantkv_var.get() if flashattention.get()==1 else 0))
4463+
predicted_gpu_layers = autoset_gpu_layers(int(contextsize_text[context_var.get()]),(sd_quant_var.get()==1),int(blasbatchsize_values[int(blas_size_var.get())]),(quantkv_var.get() if flashattention_var.get()==1 else 0))
44634464
max_gpu_layers = (f"/{modelfile_extracted_meta[1][0]+3}" if (modelfile_extracted_meta and modelfile_extracted_meta[1] and modelfile_extracted_meta[1][0]!=0) else "")
44644465
index = runopts_var.get()
44654466
gpu_be = (index == "Use Vulkan" or index == "Use Vulkan (Old CPU)" or index == "Use CLBlast" or index == "Use CLBlast (Old CPU)" or index == "Use CLBlast (Older CPU)" or index == "Use CuBLAS" or index == "Use hipBLAS (ROCm)")
@@ -4507,21 +4508,25 @@ def changed_gpu_choice_var(*args):
45074508
gpu_choice_var.trace("w", changed_gpu_choice_var)
45084509
gpulayers_var.trace("w", changed_gpulayers_estimate)
45094510

4511+
def toggleswa(a,b,c):
4512+
if swa_var.get()==1:
4513+
contextshift_var.set(0)
4514+
45104515
def togglefastforward(a,b,c):
4511-
if fastforward.get()==0:
4512-
contextshift.set(0)
4513-
smartcontext.set(0)
4514-
togglectxshift(1,1,1)
4516+
if fastforward_var.get()==0:
4517+
contextshift_var.set(0)
4518+
smartcontext_var.set(0)
45154519

45164520
def togglectxshift(a,b,c):
4517-
if contextshift.get()==0:
4521+
if contextshift_var.get()==0:
45184522
smartcontextbox.grid()
45194523
else:
4520-
fastforward.set(1)
4524+
fastforward_var.set(1)
4525+
swa_var.set(0)
45214526
smartcontextbox.grid_remove()
45224527
qkvslider.grid()
45234528
qkvlabel.grid()
4524-
if flashattention.get()==0 and quantkv_var.get()>0:
4529+
if flashattention_var.get()==0 and quantkv_var.get()>0:
45254530
noqkvlabel.grid()
45264531
else:
45274532
noqkvlabel.grid_remove()
@@ -4530,7 +4535,7 @@ def togglectxshift(a,b,c):
45304535
def toggleflashattn(a,b,c):
45314536
qkvslider.grid()
45324537
qkvlabel.grid()
4533-
if flashattention.get()==0 and quantkv_var.get()>0:
4538+
if flashattention_var.get()==0 and quantkv_var.get()>0:
45344539
noqkvlabel.grid()
45354540
else:
45364541
noqkvlabel.grid_remove()
@@ -4636,15 +4641,15 @@ def changerunmode(a,b,c):
46364641
quick_boxes = {
46374642
"Launch Browser": [launchbrowser, "Launches your default browser after model loading is complete"],
46384643
"Use MMAP": [usemmap, "Use mmap to load models if enabled, model will not be unloadable"],
4639-
"Use ContextShift": [contextshift, "Uses Context Shifting to reduce reprocessing.\nRecommended. Check the wiki for more info."],
4640-
"Remote Tunnel": [remotetunnel, "Creates a trycloudflare tunnel.\nAllows you to access koboldcpp from other devices over an internet URL."],
4644+
"Use ContextShift": [contextshift_var, "Uses Context Shifting to reduce reprocessing.\nRecommended. Check the wiki for more info."],
4645+
"Remote Tunnel": [remotetunnel_var, "Creates a trycloudflare tunnel.\nAllows you to access koboldcpp from other devices over an internet URL."],
46414646
"Quiet Mode": [quietmode, "Prevents all generation related terminal output from being displayed."]
46424647
}
46434648

46444649
for idx, (name, properties) in enumerate(quick_boxes.items()):
46454650
makecheckbox(quick_tab, name, properties[0], int(idx/2) + 20, idx % 2, tooltiptxt=properties[1])
46464651

4647-
makecheckbox(quick_tab, "Use FlashAttention", flashattention, 22, 1, tooltiptxt="Enable flash attention for GGUF models.")
4652+
makecheckbox(quick_tab, "Use FlashAttention", flashattention_var, 22, 1, tooltiptxt="Enable flash attention for GGUF models.")
46484653

46494654
# context size
46504655
makeslider(quick_tab, "Context Size:", contextsize_text, context_var, 0, len(contextsize_text)-1, 30, width=280, set=5,tooltip="What is the maximum context size to support. Model specific. You cannot exceed it.\nLarger contexts require more memory, and not all models support it.")
@@ -4713,9 +4718,10 @@ def changerunmode(a,b,c):
47134718
# Tokens Tab
47144719
tokens_tab = tabcontent["Tokens"]
47154720
# tokens checkboxes
4716-
smartcontextbox = makecheckbox(tokens_tab, "Use SmartContext", smartcontext, 1,tooltiptxt="Uses SmartContext. Now considered outdated and not recommended.\nCheck the wiki for more info.")
4717-
makecheckbox(tokens_tab, "Use ContextShift", contextshift, 2,tooltiptxt="Uses Context Shifting to reduce reprocessing.\nRecommended. Check the wiki for more info.", command=togglectxshift)
4718-
makecheckbox(tokens_tab, "Use FastForwarding", fastforward, 3,tooltiptxt="Use fast forwarding to recycle previous context (always reprocess if disabled).\nRecommended.", command=togglefastforward)
4721+
smartcontextbox = makecheckbox(tokens_tab, "Use SmartContext", smartcontext_var, 1,tooltiptxt="Uses SmartContext. Now considered outdated and not recommended.\nCheck the wiki for more info.")
4722+
makecheckbox(tokens_tab, "Use ContextShift", contextshift_var, 2,tooltiptxt="Uses Context Shifting to reduce reprocessing.\nRecommended. Check the wiki for more info.", command=togglectxshift)
4723+
makecheckbox(tokens_tab, "Use FastForwarding", fastforward_var, 3,tooltiptxt="Use fast forwarding to recycle previous context (always reprocess if disabled).\nRecommended.", command=togglefastforward)
4724+
makecheckbox(tokens_tab, "Use Sliding Window Attention (SWA)", swa_var, 4,tooltiptxt="Allows Sliding Window Attention (SWA) KV Cache, which saves memory but cannot be used with context shifting.", command=toggleswa)
47194725

47204726
# context size
47214727
makeslider(tokens_tab, "Context Size:",contextsize_text, context_var, 0, len(contextsize_text)-1, 18, width=280, set=5,tooltip="What is the maximum context size to support. Model specific. You cannot exceed it.\nLarger contexts require more memory, and not all models support it.")
@@ -4732,7 +4738,7 @@ def togglerope(a,b,c):
47324738
else:
47334739
item.grid_remove()
47344740
makecheckbox(tokens_tab, "Custom RoPE Config", variable=customrope_var, row=22, command=togglerope,tooltiptxt="Override the default RoPE configuration with custom RoPE scaling.")
4735-
makecheckbox(tokens_tab, "Use FlashAttention", flashattention, 28, command=toggleflashattn, tooltiptxt="Enable flash attention for GGUF models.")
4741+
makecheckbox(tokens_tab, "Use FlashAttention", flashattention_var, 28, command=toggleflashattn, tooltiptxt="Enable flash attention for GGUF models.")
47364742
noqkvlabel = makelabel(tokens_tab,"(Note: QuantKV works best with flash attention)",28,0,"Only K cache can be quantized, and performance can suffer.\nIn some cases, it might even use more VRAM when doing a full offload.",padx=160)
47374743
noqkvlabel.configure(text_color="#ff5555")
47384744
qkvslider,qkvlabel,qkvtitle = makeslider(tokens_tab, "Quantize KV Cache:", quantkv_text, quantkv_var, 0, 2, 30, set=0,tooltip="Enable quantization of KV cache.\nRequires FlashAttention for full effect, otherwise only K cache is quantized.")
@@ -4781,7 +4787,7 @@ def pickpremadetemplate():
47814787
makelabelentry(network_tab, "Host: ", host_var, 2, 150,tooltip="Select a specific host interface to bind to.\n(Defaults to all)")
47824788

47834789
makecheckbox(network_tab, "Multiuser Mode", multiuser_var, 3,tooltiptxt="Allows requests by multiple different clients to be queued and handled in sequence.")
4784-
makecheckbox(network_tab, "Remote Tunnel", remotetunnel, 3, 1,tooltiptxt="Creates a trycloudflare tunnel.\nAllows you to access koboldcpp from other devices over an internet URL.")
4790+
makecheckbox(network_tab, "Remote Tunnel", remotetunnel_var, 3, 1,tooltiptxt="Creates a trycloudflare tunnel.\nAllows you to access koboldcpp from other devices over an internet URL.")
47854791
makecheckbox(network_tab, "Quiet Mode", quietmode, 4,tooltiptxt="Prevents all generation related terminal output from being displayed.")
47864792
makecheckbox(network_tab, "NoCertify Mode (Insecure)", nocertifymode, 4, 1,tooltiptxt="Allows insecure SSL connections. Use this if you have cert errors and need to bypass certificate restrictions.")
47874793
makecheckbox(network_tab, "Shared Multiplayer", multiplayer_var, 5,tooltiptxt="Hosts a shared multiplayer session that others can join.")
@@ -4893,13 +4899,12 @@ def kcpp_export_template():
48934899

48944900
# extra tab
48954901
extra_tab = tabcontent["Extra"]
4896-
makelabel(extra_tab, "Unpack KoboldCpp to a local directory to modify its files.", 1, 0)
4897-
makelabel(extra_tab, "You can also launch via koboldcpp.py for faster startup.", 2, 0)
4898-
ctk.CTkButton(extra_tab , text = "Unpack KoboldCpp To Folder", command = unpack_to_dir ).grid(row=3,column=0, stick="w", padx= 8, pady=2)
4899-
makelabel(extra_tab, "Export as launcher .kcppt template (Expert Only)", 4, 0,tooltiptxt="Creates a KoboldCpp launch template for others to use.\nEmbeds JSON files directly into exported file when saving.\nWhen loaded, forces the backend to be automatically determined.\nWarning! Not recommended for beginners!")
4900-
ctk.CTkButton(extra_tab , text = "Generate LaunchTemplate", command = kcpp_export_template ).grid(row=5,column=0, stick="w", padx= 8, pady=2)
4902+
makelabel(extra_tab, "Extract KoboldCpp Files", 3, 0,tooltiptxt="Unpack KoboldCpp to a local directory to modify its files. You can also launch via koboldcpp.py for faster startup.")
4903+
ctk.CTkButton(extra_tab , text = "Unpack KoboldCpp To Folder", command = unpack_to_dir ).grid(row=3,column=0, stick="w", padx= 170, pady=2)
4904+
makelabel(extra_tab, "Export as .kcppt template", 4, 0,tooltiptxt="Creates a KoboldCpp launch template for others to use.\nEmbeds JSON files directly into exported file when saving.\nWhen loaded, forces the backend to be automatically determined.\nWarning! Not recommended for beginners!")
4905+
ctk.CTkButton(extra_tab , text = "Generate LaunchTemplate", command = kcpp_export_template ).grid(row=4,column=0, stick="w", padx= 170, pady=2)
49014906
makelabel(extra_tab, "Analyze GGUF Metadata", 6, 0,tooltiptxt="Reads the metadata, weight types and tensor names in any GGUF file.")
4902-
ctk.CTkButton(extra_tab , text = "Analyze GGUF", command = analyze_gguf_model_wrapper ).grid(row=7,column=0, stick="w", padx= 8, pady=2)
4907+
ctk.CTkButton(extra_tab , text = "Analyze GGUF", command = analyze_gguf_model_wrapper ).grid(row=6,column=0, stick="w", padx= 170, pady=2)
49034908
if sys.platform == "linux":
49044909
def togglezenity(a,b,c):
49054910
global zenity_permitted
@@ -4936,11 +4941,12 @@ def export_vars():
49364941
args.launch = launchbrowser.get()==1
49374942
args.highpriority = highpriority.get()==1
49384943
args.usemmap = usemmap.get()==1
4939-
args.smartcontext = smartcontext.get()==1
4940-
args.flashattention = flashattention.get()==1
4941-
args.noshift = contextshift.get()==0
4942-
args.nofastforward = fastforward.get()==0
4943-
args.remotetunnel = remotetunnel.get()==1
4944+
args.smartcontext = smartcontext_var.get()==1
4945+
args.flashattention = flashattention_var.get()==1
4946+
args.noshift = contextshift_var.get()==0
4947+
args.nofastforward = fastforward_var.get()==0
4948+
args.useswa = swa_var.get()==1
4949+
args.remotetunnel = remotetunnel_var.get()==1
49444950
args.foreground = keepforeground.get()==1
49454951
args.cli = terminalonly.get()==1
49464952
args.quiet = quietmode.get()==1
@@ -5123,11 +5129,12 @@ def import_vars(dict):
51235129
launchbrowser.set(1 if "launch" in dict and dict["launch"] else 0)
51245130
highpriority.set(1 if "highpriority" in dict and dict["highpriority"] else 0)
51255131
usemmap.set(1 if "usemmap" in dict and dict["usemmap"] else 0)
5126-
smartcontext.set(1 if "smartcontext" in dict and dict["smartcontext"] else 0)
5127-
flashattention.set(1 if "flashattention" in dict and dict["flashattention"] else 0)
5128-
contextshift.set(0 if "noshift" in dict and dict["noshift"] else 1)
5129-
fastforward.set(0 if "nofastforward" in dict and dict["nofastforward"] else 1)
5130-
remotetunnel.set(1 if "remotetunnel" in dict and dict["remotetunnel"] else 0)
5132+
smartcontext_var.set(1 if "smartcontext" in dict and dict["smartcontext"] else 0)
5133+
flashattention_var.set(1 if "flashattention" in dict and dict["flashattention"] else 0)
5134+
contextshift_var.set(0 if "noshift" in dict and dict["noshift"] else 1)
5135+
fastforward_var.set(0 if "nofastforward" in dict and dict["nofastforward"] else 1)
5136+
swa_var.set(1 if "useswa" in dict and dict["useswa"] else 0)
5137+
remotetunnel_var.set(1 if "remotetunnel" in dict and dict["remotetunnel"] else 0)
51315138
keepforeground.set(1 if "foreground" in dict and dict["foreground"] else 0)
51325139
terminalonly.set(1 if "cli" in dict and dict["cli"] else 0)
51335140
quietmode.set(1 if "quiet" in dict and dict["quiet"] else 0)
@@ -6876,6 +6883,7 @@ def range_checker(arg: str):
68766883
advparser.add_argument("--lora", help="LLAMA models only, applies a lora file on top of model. Experimental.", metavar=('[lora_filename]', '[lora_base]'), nargs='+')
68776884
advparser.add_argument("--noshift", help="If set, do not attempt to Trim and Shift the GGUF context.", action='store_true')
68786885
advparser.add_argument("--nofastforward", help="If set, do not attempt to fast forward GGUF context (always reprocess). Will also enable noshift", action='store_true')
6886+
advparser.add_argument("--useswa", help="If set, allows Sliding Window Attention (SWA) KV Cache, which saves memory but cannot be used with context shifting.", action='store_true')
68796887
compatgroup3 = advparser.add_mutually_exclusive_group()
68806888
compatgroup3.add_argument("--usemmap", help="If set, uses mmap to load model.", action='store_true')
68816889
advparser.add_argument("--usemlock", help="Enables mlock, preventing the RAM used to load the model from being paged out. Not usually recommended.", action='store_true')
@@ -6968,9 +6976,6 @@ def range_checker(arg: str):
69686976
admingroup.add_argument("--adminpassword", metavar=('[password]'), help="Require a password to access admin functions. You are strongly advised to use one for publically accessible instances!", default=None)
69696977
admingroup.add_argument("--admindir", metavar=('[directory]'), help="Specify a directory to look for .kcpps configs in, which can be used to swap models.", default="")
69706978

6971-
experimentgroup = parser.add_argument_group('Experimental Commands, can change or break any time!')
6972-
experimentgroup.add_argument("--experiment_swa", help="Enables SWA mode. There are no safety checks.", action='store_true')
6973-
69746979
deprecatedgroup = parser.add_argument_group('Deprecated Commands, DO NOT USE!')
69756980
deprecatedgroup.add_argument("--hordeconfig", help=argparse.SUPPRESS, nargs='+')
69766981
deprecatedgroup.add_argument("--sdconfig", help=argparse.SUPPRESS, nargs='+')

0 commit comments

Comments
 (0)