-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathgui.py
More file actions
2337 lines (1979 loc) · 106 KB
/
gui.py
File metadata and controls
2337 lines (1979 loc) · 106 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import tkinter as tk
from tkinter import ttk, scrolledtext, filedialog
import threading
from queue import Queue
import logging
from typing import Dict, Union, Tuple, List, Optional
import torch
from collections import Counter
import os
import json
from threading import Lock
import platformdirs
import re
from pathlib import Path
from datetime import datetime
import json
import hashlib
import numpy as np
import gc
logger = logging.getLogger(__name__)
# Import from main_t
from main_t import (
generate_response,
AutoModelForCausalLM,
AutoTokenizer,
device,
SamplerConfig,
SamplerState,
logger,
EntropixSampler
)
class ToolTip:
"""Tooltip widget implementation"""
def __init__(self, widget, text):
self.widget = widget
self.text = text
self.tooltip = None
self.widget.bind("<Enter>", self.show)
self.widget.bind("<Leave>", self.hide)
def show(self, event=None):
x, y, _, _ = self.widget.bbox("insert")
x += self.widget.winfo_rootx() + 25
y += self.widget.winfo_rooty() + 20
self.tooltip = tk.Toplevel(self.widget)
self.tooltip.wm_overrideredirect(True)
self.tooltip.wm_geometry(f"+{x}+{y}")
label = ttk.Label(
self.tooltip,
text=self.text,
justify='left',
background="#ffffe0",
relief='solid',
borderwidth=1,
wraplength=300
)
label.pack()
def hide(self, event=None):
if self.tooltip:
self.tooltip.destroy()
self.tooltip = None
# Parameter tooltips
PARAMETER_TOOLTIPS = {
"basic_sampling": {
"temp": "Temperature for logits. Higher values increase randomness.",
"top_p": "Nucleus sampling threshold. Cumulative probability cutoff.",
"top_k": "Top-k sampling. Number of highest probability tokens to consider.",
"min_p": "Minimum probability threshold for token selection.",
"repetition_penalty": "Penalty applied to repeated tokens.",
"strategy_change_batch_size": "Number of tokens to generate before allowing strategy changes"
},
"strategy_thresholds": {
"argmax_entropy_thresh": "Maximum entropy threshold for ARGMAX (bottom-left quadrant: low entropy, low variance)",
"sample_entropy_thresh": "Entropy threshold for SAMPLE (bottom-right quadrant: low entropy, high variance)",
"sample_varentropy_thresh": "Minimum variance threshold for SAMPLE strategy",
"cot_min_entropy_thresh": "Minimum entropy for INSERT_COT (top-left quadrant: high entropy, low variance)",
"cot_max_entropy_thresh": "Maximum entropy for INSERT_COT",
"cot_varentropy_thresh": "Maximum variance threshold for INSERT_COT",
"resample_min_entropy_thresh": "Minimum entropy for RESAMPLE (top-right quadrant: high entropy, high variance)",
"resample_varentropy_thresh": "Minimum variance threshold for RESAMPLE",
"adaptive_radius": "Radius around center point for ADAPTIVE strategy (central region)",
},
"adaptive_sampling": {
"ada_temp_logits": "Temperature adjustment based on logits uncertainty.",
"ada_temp_attn": "Temperature adjustment based on attention uncertainty.",
"ada_temp_agree": "Temperature adjustment based on head agreement.",
"n_adaptive_samples": "Number of samples to generate in adaptive mode."
},
"attention_coefficients": {
"helv_attn_ent_offset": "High Entropy Low Variance attention entropy offset.",
"helv_attn_ent_coef": "High Entropy Low Variance attention entropy coefficient.",
"lehv_interaction_strength_offset": "Low Entropy High Variance interaction strength offset.",
"lehv_interaction_strength_coef": "Low Entropy High Variance interaction strength coefficient.",
"hehv_attn_ent_coef": "High Entropy High Variance attention entropy coefficient.",
"hehv_attn_vent_offset": "High Entropy High Variance attention variance offset.",
"hehv_attn_vent_coef": "High Entropy High Variance attention variance coefficient."
},
"rope_parameters": {
"rope_theta": "Base value for RoPE (Rotary Position Embedding).",
"rope_scaling": "Scaling factor for RoPE computations.",
"rope_scale_base": "Base value for RoPE scaling.",
"rope_scale_factor": "Factor for RoPE scaling calculations."
},
"memory_context": {
"max_ngram_size": "Maximum size of n-grams to track for repetition.",
"max_ngram_repeat": "Maximum allowed repetitions of any n-gram.",
"window_size": "Size of the rolling window for statistics.",
"long_window_size": "Size of the long-term rolling window.",
"decay_factor": "Decay rate for rolling statistics.",
"long_decay_factor": "Decay rate for long-term statistics."
}
}
class ModelDiscovery:
def __init__(self):
# Get default HF cache directory
self.default_cache_dir = os.path.join(os.path.expanduser("~"), ".cache", "huggingface", "hub")
self.custom_model_dir = None
self.available_models = {}
self.scan_models()
def is_valid_model_dir(self, path: Path) -> bool:
"""Check if directory contains a valid model"""
# For HF cache, look inside the 'snapshots' subdirectory
if path.name.startswith("models--"):
# Get the latest snapshot
snapshots_dir = path / "snapshots"
if not snapshots_dir.exists():
return False
# Find the latest snapshot (highest hash)
snapshot_dirs = [d for d in snapshots_dir.iterdir() if d.is_dir()]
if not snapshot_dirs:
return False
# Use the latest snapshot
model_dir = sorted(snapshot_dirs)[-1]
else:
model_dir = path
# Check for required files
required_files = ['config.json']
optional_files = ['pytorch_model.bin', 'model.safetensors']
if not any((model_dir / file).exists() for file in required_files):
return False
# Check for model files (including sharded ones)
has_model_files = (
any((model_dir / file).exists() for file in optional_files) or
list(model_dir.glob("pytorch_model-*.bin")) or
list(model_dir.glob("model-*.safetensors"))
)
return has_model_files
def get_model_path(self, path: Path) -> Path:
"""Get the actual model path from HF cache directory structure"""
if path.name.startswith("models--"):
snapshots_dir = path / "snapshots"
if snapshots_dir.exists():
snapshot_dirs = [d for d in snapshots_dir.iterdir() if d.is_dir()]
if snapshot_dirs:
return sorted(snapshot_dirs)[-1]
return path
def get_model_info(self, path: Path) -> Optional[Dict[str, str]]:
"""Extract model information from config.json"""
try:
# Get the actual model directory
model_dir = self.get_model_path(path)
config_path = model_dir / 'config.json'
if config_path.exists():
with open(config_path, 'r', encoding='utf-8') as f:
config = json.load(f)
# Convert models--org--name format to org/name
model_name = path.name
if model_name.startswith("models--"):
parts = model_name.split("--")
if len(parts) >= 3:
model_name = f"{parts[1]}/{'/'.join(parts[2:])}"
# Try to get model size
model_size = None
if 'n_params' in config:
model_size = f"{config['n_params'] / 1e9:.1f}B"
elif 'num_parameters' in config:
model_size = f"{config['num_parameters'] / 1e9:.1f}B"
elif 'model_type' in config:
model_size = config['model_type']
return {
'name': model_name,
'path': str(model_dir), # Use the snapshot directory path
'architecture': config.get('architectures', ['Unknown'])[0],
'size': model_size if model_size else 'Unknown'
}
except Exception as e:
logger.warning(f"Error reading model config at {path}: {e}")
return None
def scan_directory(self, base_path: Path) -> Dict[str, Dict[str, str]]:
"""Recursively scan directory for models"""
models = {}
try:
# For HF cache, look for directories starting with "models--"
model_dirs = [d for d in base_path.iterdir() if d.is_dir() and d.name.startswith("models--")]
for model_dir in model_dirs:
if self.is_valid_model_dir(model_dir):
model_info = self.get_model_info(model_dir)
if model_info:
display_name = f"{model_info['name']} ({model_info['size']})"
models[display_name] = model_info
logger.info(f"Found model: {display_name} at {model_info['path']}")
except Exception as e:
logger.error(f"Error scanning directory {base_path}: {e}")
return models
def set_custom_dir(self, directory: str):
"""Set custom directory for model scanning"""
if directory and os.path.exists(directory):
self.custom_model_dir = directory
self.scan_models()
logger.info(f"Added custom model directory: {directory}")
else:
logger.warning(f"Invalid custom directory: {directory}")
def scan_models(self):
"""Scan both default and custom directories for models"""
self.available_models.clear()
# Scan default HF cache directory
if os.path.exists(self.default_cache_dir):
logger.info(f"Scanning default cache directory: {self.default_cache_dir}")
cache_models = self.scan_directory(Path(self.default_cache_dir))
self.available_models.update(cache_models)
logger.info(f"Found {len(cache_models)} models in default cache")
# Scan custom directory if set
if self.custom_model_dir and os.path.exists(self.custom_model_dir):
logger.info(f"Scanning custom directory: {self.custom_model_dir}")
custom_models = self.scan_directory(Path(self.custom_model_dir))
self.available_models.update(custom_models)
logger.info(f"Found {len(custom_models)} models in custom directory")
if not self.available_models:
logger.warning("No models found in any directory")
class ParameterValidator:
"""Ensures GUI parameters exactly match model parameters from main_t"""
def __init__(self):
# Direct copy of parameters from main_t's SamplerConfig
self.parameter_ranges = {
# Basic sampling parameters
"temp": {"min": 0.1, "max": 2.0, "default": 0.666},
"top_p": {"min": 0.0, "max": 1.0, "default": 0.90},
"top_k": {"min": 1, "max": 100, "default": 27},
"min_p": {"min": 0.0, "max": 0.5, "default": 0.05},
"repetition_penalty": {"min": 1.0, "max": 2.0, "default": 1.2},
"strategy_change_batch_size": {"min": 1, "max": 10, "default": 1},
# Strategy thresholds with expanded ranges
"argmax_entropy_thresh": {"min": 0.0, "max": 5.0, "default": 0.5},
"sample_min_entropy_thresh": {"min": 0.0, "max": 5.0, "default": 0.5},
"sample_max_entropy_thresh": {"min": 0.0, "max": 7.0, "default": 1.5},
"sample_varentropy_thresh": {"min": 0.0, "max": 8.0, "default": 2.0},
"cot_min_entropy_thresh": {"min": 0.0, "max": 6.0, "default": 1.5},
"cot_max_entropy_thresh": {"min": 0.0, "max": 8.0, "default": 2.5},
"cot_varentropy_thresh": {"min": 0.0, "max": 8.0, "default": 2.0},
"resample_min_entropy_thresh": {"min": 0.0, "max": 6.0, "default": 1.0},
"resample_max_entropy_thresh": {"min": 0.0, "max": 8.0, "default": 2.5},
"resample_varentropy_thresh": {"min": 0.0, "max": 10.0, "default": 4.0},
"adaptive_entropy_thresh": {"min": 0.0, "max": 8.0, "default": 2.0},
"adaptive_varentropy_thresh": {"min": 0.0, "max": 10.0, "default": 4.0},
# Adaptive center point parameters with expanded ranges
"adaptive_entropy_center": {"min": 0.0, "max": 8.0, "default": 2.0},
"adaptive_varentropy_center": {"min": 0.0, "max": 10.0, "default": 2.0},
"adaptive_radius": {"min": 0.1, "max": 4.0, "default": 0.5},
# Strategy positioning parameters with expanded ranges
"quadrant_separation": {"min": 0.5, "max": 4.0, "default": 1.0},
"boundary_softness": {"min": 0.1, "max": 2.0, "default": 0.3},
# Strategy-specific parameters with expanded ranges
"argmax_range": {"min": 0.1, "max": 3.0, "default": 0.3},
"sample_variance_threshold": {"min": 0.1, "max": 5.0, "default": 0.5},
"cot_entropy_range": {"min": 0.1, "max": 5.0, "default": 0.8},
"resample_min_variance": {"min": 0.5, "max": 6.0, "default": 1.0},
# RoPE parameters
"rope_theta": {"min": 1000.0, "max": 100000.0, "default": 10000.0},
"rope_scaling": {"min": 0.1, "max": 2.0, "default": 1.0},
"rope_scale_base": {"min": 1.0, "max": 16.0, "default": 8.0},
"rope_scale_factor": {"min": 0.0, "max": 1.0, "default": 0.25},
# Attention coefficients
"helv_attn_ent_offset": {"min": 0.0, "max": 3.0, "default": 1.3},
"helv_attn_ent_coef": {"min": 0.0, "max": 1.0, "default": 0.2},
"lehv_interaction_strength_offset": {"min": 0.0, "max": 3.0, "default": 1.2},
"lehv_interaction_strength_coef": {"min": 0.0, "max": 1.0, "default": 0.3},
"hehv_attn_ent_coef": {"min": 0.0, "max": 1.0, "default": 0.2},
"hehv_attn_vent_offset": {"min": 0.0, "max": 5.0, "default": 2.0},
"hehv_attn_vent_coef": {"min": 0.0, "max": 1.0, "default": 0.5},
# Memory and window parameters
"max_ngram_size": {"min": 1, "max": 10, "default": 5},
"max_ngram_repeat": {"min": 1, "max": 10, "default": 3},
"window_size": {"min": 10, "max": 200, "default": 50},
"long_window_size": {"min": 100, "max": 1000, "default": 500},
"decay_factor": {"min": 0.0, "max": 1.0, "default": 0.95},
"long_decay_factor": {"min": 0.0, "max": 1.0, "default": 0.95},
# Adaptive scoring coefficients
"ada_score_logits_ent": {"min": 0.0, "max": 1.0, "default": 0.1},
"ada_score_attn_ent": {"min": 0.0, "max": 1.0, "default": 0.2},
"ada_score_logits_vent": {"min": 0.0, "max": 1.0, "default": 0.3},
"ada_score_attn_vent": {"min": 0.0, "max": 1.0, "default": 0.4},
"ada_score_agree": {"min": 0.0, "max": 1.0, "default": 0.5},
"ada_score_int": {"min": 0.0, "max": 1.0, "default": 0.6},
# Adaptive sampling coefficients
"ada_temp_logits": {"min": 0.0, "max": 1.0, "default": 0.3},
"ada_temp_attn": {"min": 0.0, "max": 1.0, "default": 0.2},
"ada_temp_agree": {"min": 0.0, "max": 1.0, "default": 0.2},
"n_adaptive_samples": {"min": 1, "max": 10, "default": 5},
"ada_top_p": {"min": 0.0, "max": 1.0, "default": 0.1},
"ada_top_k_int": {"min": 0.0, "max": 1.0, "default": 0.3},
"ada_top_k_agree": {"min": 0.0, "max": 1.0, "default": 0.2},
"ada_min_p": {"min": 0.0, "max": 1.0, "default": 0.5}
}
def validate_param(self, param_name: str, value: float) -> float:
"""Validates and clamps parameter values to allowed ranges"""
if param_name not in self.parameter_ranges:
raise ValueError(f"Unknown parameter: {param_name}")
param_range = self.parameter_ranges[param_name]
return max(param_range["min"], min(value, param_range["max"]))
def get_default(self, param_name: str) -> float:
"""Gets default value for parameter"""
if param_name not in self.parameter_ranges:
raise ValueError(f"Unknown parameter: {param_name}")
return self.parameter_ranges[param_name]["default"]
def get_range(self, param_name: str) -> tuple:
"""Gets allowed range for parameter"""
if param_name not in self.parameter_ranges:
raise ValueError(f"Unknown parameter: {param_name}")
param_range = self.parameter_ranges[param_name]
return (param_range["min"], param_range["max"])
def get_category_params(self, category: str) -> list:
"""Gets all parameters in a specific category based on prefix"""
return [param for param in self.parameter_ranges.keys() if param.startswith(category)]
def initialize_parameter_vars(self):
"""Initialize all parameter variables with validated defaults"""
# Create validator
self.param_validator = ParameterValidator()
# Initialize all variables using validator
for param_name in self.param_validator.parameter_ranges:
var_name = f"{param_name}_var"
default_val = self.param_validator.get_default(param_name)
if param_name in ["top_k", "max_ngram_size", "max_ngram_repeat",
"window_size", "long_window_size", "n_adaptive_samples",
"strategy_change_batch_size"]:
setattr(self, var_name, tk.IntVar(value=default_val))
else:
setattr(self, var_name, tk.DoubleVar(value=default_val))
class EntropixTGUI:
def __init__(self):
self.root = tk.Tk()
self.root.title("Entropix Text Generator")
# Initialize model discovery
self.model_discovery = ModelDiscovery()
# Initialize variables
self.model = None
self.tokenizer = None
self.sampler_config = None
self.generation_thread = None
self.stop_generation = False
self.response_queue = Queue()
self.strategy_counter = Counter()
self.stats_lock = Lock()
# Initialize all parameter variables before GUI setup
self.initialize_parameter_vars()
# Create main notebook for primary tabs
self.notebook = ttk.Notebook(self.root)
self.notebook.pack(fill="both", expand=True, padx=5, pady=5)
# Create widgets and setup GUI
self.create_widgets()
# Create directories if they don't exist
self.output_dir = Path("outputs")
self.output_dir.mkdir(exist_ok=True)
self.config_dir = Path("configs")
self.config_dir.mkdir(exist_ok=True)
# Track current model info
self.current_model_hash = None
self.current_model_name = None
# Add visualization manager placeholder
self.viz_manager = None
def create_widgets(self):
"""Create and setup all GUI widgets"""
# Create main tab
self.main_tab = ttk.Frame(self.notebook)
self.notebook.add(self.main_tab, text="Main")
# Create controls tab
self.controls_tab = ttk.Frame(self.notebook)
self.notebook.add(self.controls_tab, text="Controls")
# Setup main tab components
self.create_main_tab()
# Setup controls tab components
self.create_controls_tab()
def create_main_tab(self):
"""Create main tab with model selection, output, and input areas in new order"""
# Model frame at the top
model_frame = ttk.LabelFrame(self.main_tab, text="Model", padding="5")
model_frame.pack(fill="x", padx=5, pady=5)
self.create_model_selector()
# Output frame in the middle
output_frame = ttk.LabelFrame(self.main_tab, text="Output", padding="5")
output_frame.pack(fill="both", expand=True, padx=5, pady=5)
self.create_output_areas(output_frame)
# Input frame at the bottom
input_frame = ttk.LabelFrame(self.main_tab, text="Input", padding="5")
input_frame.pack(fill="x", padx=5, pady=5)
self.create_input_area(input_frame)
def create_controls_tab(self):
"""Create organized parameter controls in the Controls tab"""
# Create notebook for tabbed organization within Controls tab
control_notebook = ttk.Notebook(self.controls_tab)
control_notebook.pack(fill="both", expand=True, padx=5, pady=5)
# Basic Sampling tab
basic_frame = ttk.Frame(control_notebook)
control_notebook.add(basic_frame, text="Basic Sampling")
self.create_basic_controls(basic_frame)
# Entropy & Strategy tab
entropy_frame = ttk.Frame(control_notebook)
control_notebook.add(entropy_frame, text="Entropy & Strategy")
self.create_entropy_controls(entropy_frame)
# Adaptive Sampling tab
adaptive_frame = ttk.Frame(control_notebook)
control_notebook.add(adaptive_frame, text="Adaptive")
self.create_adaptive_controls(adaptive_frame)
# Attention Coefficients tab
attention_frame = ttk.Frame(control_notebook)
control_notebook.add(attention_frame, text="Attention")
self.create_attention_controls(attention_frame)
# RoPE & Position tab
rope_frame = ttk.Frame(control_notebook)
control_notebook.add(rope_frame, text="RoPE")
self.create_rope_controls(rope_frame)
# Memory & Context tab
memory_frame = ttk.Frame(control_notebook)
control_notebook.add(memory_frame, text="Memory")
self.create_memory_controls(memory_frame)
def create_save_buttons(self):
"""Add save buttons to the interface"""
save_frame = ttk.Frame(self.main_tab)
save_frame.pack(fill="x", padx=5, pady=5)
ttk.Button(
save_frame,
text="Save Configuration",
command=self.save_current_config
).pack(side="left", padx=5)
ttk.Button(
save_frame,
text="Save Output",
command=self.save_output
).pack(side="left", padx=5)
def save_current_config(self):
"""Save current configuration to a timestamped JSON file"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
config = {
"basic_sampling": {
"temp": self.temp_var.get(),
"top_p": self.top_p_var.get(),
"top_k": self.top_k_var.get(),
"min_p": self.min_p_var.get(),
"repetition_penalty": self.repetition_penalty_var.get()
},
"entropy_thresholds": {
"low_ent_thresh": self.low_ent_thresh_var.get(),
"med_ent_thresh": self.med_ent_thresh_var.get(),
"high_ent_thresh": self.high_ent_thresh_var.get(),
"high_vent_thresh": self.high_vent_thresh_var.get(),
"varentropy_threshold": self.varentropy_threshold_var.get()
},
"adaptive_sampling": {
"ada_temp_logits": self.ada_temp_logits_var.get(),
"ada_temp_attn": self.ada_temp_attn_var.get(),
"ada_temp_agree": self.ada_temp_agree_var.get(),
"n_adaptive_samples": self.n_adaptive_samples_var.get()
},
"rope_parameters": {
"rope_theta": self.rope_theta_var.get(),
"rope_scaling": self.rope_scaling_var.get(),
"rope_scale_base": self.rope_scale_base_var.get(),
"rope_scale_factor": self.rope_scale_factor_var.get()
},
"attention_coefficients": {
"helv_attn_ent_offset": self.helv_attn_ent_offset_var.get(),
"helv_attn_ent_coef": self.helv_attn_ent_coef_var.get(),
"lehv_interaction_strength_offset": self.lehv_interaction_strength_offset_var.get(),
"lehv_interaction_strength_coef": self.lehv_interaction_strength_coef_var.get(),
"hehv_attn_ent_coef": self.hehv_attn_ent_coef_var.get(),
"hehv_attn_vent_offset": self.hehv_attn_vent_offset_var.get(),
"hehv_attn_vent_coef": self.hehv_attn_vent_coef_var.get()
},
"memory_context": {
"max_ngram_size": self.max_ngram_size_var.get(),
"max_ngram_repeat": self.max_ngram_repeat_var.get(),
"window_size": self.window_size_var.get(),
"long_window_size": self.long_window_size_var.get(),
"decay_factor": self.decay_factor_var.get(),
"long_decay_factor": self.long_decay_factor_var.get()
}
}
# Save as both current config and timestamped config
try:
# Save as current config (for loading on startup)
current_config_path = self.config_dir / "current_config.json"
with open(current_config_path, "w") as f:
json.dump(config, f, indent=4)
# Save timestamped version
config_path = self.config_dir / f"config_{timestamp}.json"
with open(config_path, "w") as f:
json.dump(config, f, indent=4)
self.output_text.insert("end", f"\nConfiguration saved to {config_path}\n")
logger.info(f"Configuration saved to {config_path}")
except Exception as e:
self.output_text.insert("end", f"\nError saving configuration: {str(e)}\n")
logger.error(f"Error saving configuration: {str(e)}")
def save_output(self):
"""Save current output to a timestamped text file"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
try:
# Get the entire output text
output_text = self.output_text.get("1.0", "end-1c")
# Add generation statistics
output_text += "\n\n=== Generation Statistics ===\n"
total_tokens = sum(self.strategy_counter.values())
if total_tokens > 0:
for strategy, count in self.strategy_counter.most_common():
percentage = (count / total_tokens) * 100
output_text += f"{strategy}: {count} ({percentage:.1f}%)\n"
# Add configuration used
output_text += "\n=== Configuration Used ===\n"
current_config = {
"basic_sampling": {
"temp": self.temp_var.get(),
"top_p": self.top_p_var.get(),
"top_k": self.top_k_var.get(),
"min_p": self.min_p_var.get(),
"repetition_penalty": self.repetition_penalty_var.get()
},
# ... (add other configuration sections)
}
output_text += json.dumps(current_config, indent=4)
# Save the file
output_path = self.output_dir / f"output_{timestamp}.txt"
with open(output_path, "w", encoding="utf-8") as f:
f.write(output_text)
self.output_text.insert("end", f"\nOutput saved to {output_path}\n")
logger.info(f"Output saved to {output_path}")
except Exception as e:
self.output_text.insert("end", f"\nError saving output: {str(e)}\n")
logger.error(f"Error saving output: {str(e)}")
def load_config(self):
"""Load configuration from file"""
try:
# Try to load the current configuration
current_config_path = self.config_dir / "current_config.json"
if not current_config_path.exists():
logger.info("No saved configuration found, using defaults")
return
with open(current_config_path, "r") as f:
config = json.load(f)
# Update all GUI variables from loaded config
for section, params in config.items():
for param, value in params.items():
var = getattr(self, f"{param}_var", None)
if var:
var.set(value)
logger.info("Configuration loaded successfully")
self.update_config()
except Exception as e:
logger.error(f"Error loading configuration: {str(e)}")
def setup_gui(self):
"""Setup main GUI with tabs for main interface and controls"""
# Create main notebook for primary tabs
self.main_notebook = ttk.Notebook(self.root)
self.main_notebook.pack(fill="both", expand=True, padx=5, pady=5)
# Create main interface tab
main_tab = ttk.Frame(self.main_notebook)
self.main_notebook.add(main_tab, text="Main")
# Create controls tab
controls_tab = ttk.Frame(self.main_notebook)
self.main_notebook.add(controls_tab, text="Controls")
# Setup main interface components
self.setup_main_interface(main_tab)
# Setup controls interface
self.setup_controls_interface(controls_tab)
def setup_main_interface(self, parent):
"""Setup the main interface tab with model selection, input, and output"""
# Model frame
model_frame = ttk.LabelFrame(parent, text="Model", padding="5")
model_frame.pack(fill="x", padx=5, pady=5)
# Model selection frame
model_select_frame = ttk.Frame(model_frame)
model_select_frame.pack(fill="x", pady=5)
ttk.Label(model_select_frame, text="Model:").pack(side="left", padx=5)
# Create model dropdown
self.model_var = tk.StringVar()
self.model_combo = ttk.Combobox(
model_select_frame,
textvariable=self.model_var,
width=50
)
self.model_combo.pack(side="left", padx=5, fill="x", expand=True)
# Model buttons frame
btn_frame = ttk.Frame(model_frame)
btn_frame.pack(fill="x", pady=5)
ttk.Button(
btn_frame,
text="Scan Default Directory",
command=self.rescan_models
).pack(side="left", padx=5)
ttk.Button(
btn_frame,
text="Select Custom Directory",
command=self.select_custom_dir
).pack(side="left", padx=5)
ttk.Button(
btn_frame,
text="Load Model",
command=self.load_selected_model
).pack(side="left", padx=5)
# Model info display
self.model_info = ttk.Label(model_frame, text="No model loaded")
self.model_info.pack(fill="x", padx=5)
# Input frame
input_frame = ttk.LabelFrame(parent, text="Input", padding="5")
input_frame.pack(fill="x", padx=5, pady=5)
# Input text area
self.prompt_input = scrolledtext.ScrolledText(input_frame, height=5)
self.prompt_input.pack(fill="x", expand=True, padx=5, pady=5)
# Input buttons
input_btn_frame = ttk.Frame(input_frame)
input_btn_frame.pack(fill="x", pady=5)
ttk.Button(input_btn_frame, text="Generate", command=self.start_generation).pack(side="left", padx=5)
ttk.Button(input_btn_frame, text="Stop", command=self.stop_generation_request).pack(side="left", padx=5)
ttk.Button(input_btn_frame, text="Clear", command=self.clear_output).pack(side="left", padx=5)
# Output frame with increased height
output_frame = ttk.LabelFrame(parent, text="Output", padding="5")
output_frame.pack(fill="both", expand=True, padx=5, pady=5)
# Output text area
self.output_text = scrolledtext.ScrolledText(output_frame, height=30)
self.output_text.pack(fill="both", expand=True, padx=5, pady=5)
# Statistics area
stats_frame = ttk.LabelFrame(output_frame, text="Statistics", padding="5")
stats_frame.pack(fill="x", padx=5, pady=5)
# Create three columns for statistics
left_stats = ttk.Frame(stats_frame)
left_stats.pack(side="left", fill="both", expand=True)
middle_stats = ttk.Frame(stats_frame)
middle_stats.pack(side="left", fill="both", expand=True)
right_stats = ttk.Frame(stats_frame)
right_stats.pack(side="left", fill="both", expand=True)
# Initialize stat_labels dictionary
self.stat_labels = {}
# Strategy counter in left column
self.strategy_var = tk.StringVar(value="Strategy Usage: N/A")
ttk.Label(left_stats, textvariable=self.strategy_var).pack(anchor="w")
# Entropy metrics in middle column
entropy_metrics = ["Entropy", "Varentropy", "Attn Entropy"]
for metric in entropy_metrics:
var = tk.StringVar(value=f"{metric}: N/A")
self.stat_labels[metric] = var
ttk.Label(middle_stats, textvariable=var).pack(anchor="w")
# Additional metrics in right column
additional_metrics = ["Rolling Entropy", "Rolling Varentropy", "Current Strategy"]
for metric in additional_metrics:
var = tk.StringVar(value=f"{metric}: N/A")
self.stat_labels[metric] = var
ttk.Label(right_stats, textvariable=var).pack(anchor="w")
def setup_controls_interface(self, parent):
"""Setup the controls interface tab with all parameter controls"""
# Create notebook for control categories
control_notebook = ttk.Notebook(parent)
control_notebook.pack(fill="both", expand=True, padx=5, pady=5)
# Create frames for each control category
basic_frame = ttk.Frame(control_notebook)
entropy_frame = ttk.Frame(control_notebook)
adaptive_frame = ttk.Frame(control_notebook)
attention_frame = ttk.Frame(control_notebook)
rope_frame = ttk.Frame(control_notebook)
memory_frame = ttk.Frame(control_notebook)
# Add frames to notebook
control_notebook.add(basic_frame, text="Basic Sampling")
control_notebook.add(entropy_frame, text="Entropy & Strategy")
control_notebook.add(adaptive_frame, text="Adaptive")
control_notebook.add(attention_frame, text="Attention")
control_notebook.add(rope_frame, text="RoPE")
control_notebook.add(memory_frame, text="Memory")
# Create controls in each frame
self.create_basic_controls(basic_frame)
self.create_entropy_controls(entropy_frame)
self.create_adaptive_controls(adaptive_frame)
self.create_attention_controls(attention_frame)
self.create_rope_controls(rope_frame)
self.create_memory_controls(memory_frame)
def initialize_parameter_vars(self):
"""Initialize all parameter variables with defaults from main_t"""
# Basic sampling parameters
self.temp_var = tk.DoubleVar(value=0.666)
self.top_p_var = tk.DoubleVar(value=0.90)
self.top_k_var = tk.IntVar(value=27)
self.min_p_var = tk.DoubleVar(value=0.05)
self.repetition_penalty_var = tk.DoubleVar(value=1.2)
self.strategy_change_batch_size_var = tk.IntVar(value=1)
# Adaptive sampling parameters that were missing
self.n_adaptive_samples_var = tk.IntVar(value=5)
self.ada_temp_logits_var = tk.DoubleVar(value=0.3)
self.ada_temp_attn_var = tk.DoubleVar(value=0.2)
self.ada_temp_agree_var = tk.DoubleVar(value=0.2)
self.ada_top_p_var = tk.DoubleVar(value=0.1)
self.ada_top_k_int_var = tk.DoubleVar(value=0.3)
self.ada_top_k_agree_var = tk.DoubleVar(value=0.2)
self.ada_min_p_var = tk.DoubleVar(value=0.5)
# Make sure all existing entropy vars are here
self.argmax_entropy_thresh_var = tk.DoubleVar(value=0.5)
self.sample_min_entropy_thresh_var = tk.DoubleVar(value=0.5)
self.sample_max_entropy_thresh_var = tk.DoubleVar(value=1.5)
self.sample_varentropy_thresh_var = tk.DoubleVar(value=2.0)
self.cot_min_entropy_thresh_var = tk.DoubleVar(value=1.5)
self.cot_max_entropy_thresh_var = tk.DoubleVar(value=2.5)
self.cot_varentropy_thresh_var = tk.DoubleVar(value=2.0)
self.resample_min_entropy_thresh_var = tk.DoubleVar(value=1.0)
self.resample_max_entropy_thresh_var = tk.DoubleVar(value=2.5)
self.resample_varentropy_thresh_var = tk.DoubleVar(value=4.0)
self.adaptive_entropy_thresh_var = tk.DoubleVar(value=2.0)
self.adaptive_varentropy_thresh_var = tk.DoubleVar(value=4.0)
# Strategy positioning parameters
self.adaptive_entropy_center_var = tk.DoubleVar(value=2.0)
self.adaptive_varentropy_center_var = tk.DoubleVar(value=2.0)
self.adaptive_radius_var = tk.DoubleVar(value=0.5)
self.quadrant_separation_var = tk.DoubleVar(value=1.0)
self.boundary_softness_var = tk.DoubleVar(value=0.3)
self.argmax_range_var = tk.DoubleVar(value=0.3)
self.sample_variance_threshold_var = tk.DoubleVar(value=0.5)
self.cot_entropy_range_var = tk.DoubleVar(value=0.8)
self.resample_min_variance_var = tk.DoubleVar(value=1.0)
# Adaptive scoring parameters
self.ada_score_logits_ent_var = tk.DoubleVar(value=0.1)
self.ada_score_attn_ent_var = tk.DoubleVar(value=0.2)
self.ada_score_logits_vent_var = tk.DoubleVar(value=0.3)
self.ada_score_attn_vent_var = tk.DoubleVar(value=0.4)
self.ada_score_agree_var = tk.DoubleVar(value=0.5)
self.ada_score_int_var = tk.DoubleVar(value=0.6)
# RoPE parameters
self.rope_theta_var = tk.DoubleVar(value=10000.0)
self.rope_scaling_var = tk.DoubleVar(value=1.0)
self.rope_scale_base_var = tk.DoubleVar(value=8.0)
self.rope_scale_factor_var = tk.DoubleVar(value=0.25)
# Attention coefficients
self.helv_attn_ent_offset_var = tk.DoubleVar(value=1.3)
self.helv_attn_ent_coef_var = tk.DoubleVar(value=0.2)
self.lehv_interaction_strength_offset_var = tk.DoubleVar(value=1.2)
self.lehv_interaction_strength_coef_var = tk.DoubleVar(value=0.3)
self.hehv_attn_ent_coef_var = tk.DoubleVar(value=0.2)
self.hehv_attn_vent_offset_var = tk.DoubleVar(value=2.0)
self.hehv_attn_vent_coef_var = tk.DoubleVar(value=0.5)
# Memory and window parameters
self.max_ngram_size_var = tk.IntVar(value=5)
self.max_ngram_repeat_var = tk.IntVar(value=3)
self.window_size_var = tk.IntVar(value=50)
self.long_window_size_var = tk.IntVar(value=500)
self.decay_factor_var = tk.DoubleVar(value=0.95)
self.long_decay_factor_var = tk.DoubleVar(value=0.95)
def create_parameter_controls(self, parent):
"""Create organized parameter controls with additional tab"""
# Create notebook for tabbed organization
notebook = ttk.Notebook(parent)
notebook.pack(fill="both", expand=True, padx=5, pady=5)
# Basic Sampling tab
basic_frame = ttk.Frame(notebook)
notebook.add(basic_frame, text="Basic Sampling")
self.create_basic_controls(basic_frame)
# Entropy & Strategy tab
entropy_frame = ttk.Frame(notebook)
notebook.add(entropy_frame, text="Entropy & Strategy")
self.create_entropy_controls(entropy_frame)
# Adaptive Sampling tab
adaptive_frame = ttk.Frame(notebook)
notebook.add(adaptive_frame, text="Adaptive")
self.create_adaptive_controls(adaptive_frame)
# Attention Coefficients tab
attention_frame = ttk.Frame(notebook)
notebook.add(attention_frame, text="Attention")
self.create_attention_controls(attention_frame)
# RoPE & Position tab
rope_frame = ttk.Frame(notebook)
notebook.add(rope_frame, text="RoPE")
self.create_rope_controls(rope_frame)
# Memory & Context tab
memory_frame = ttk.Frame(notebook)
notebook.add(memory_frame, text="Memory")
self.create_memory_controls(memory_frame)
# Advanced Settings tab (new)
advanced_frame = ttk.Frame(notebook)
notebook.add(advanced_frame, text="Advanced")
self.create_advanced_controls(advanced_frame)
def create_advanced_controls(self, parent):
"""Create advanced settings controls"""
# You can move some of the less frequently used controls here
pass
def create_model_selector(self):
"""Create model selection interface"""
# Create frame in main tab
frame = ttk.Frame(self.main_tab)
frame.pack(fill="x", padx=5, pady=5)
# Model selection frame
model_select_frame = ttk.Frame(frame)
model_select_frame.pack(fill="x", pady=5)
ttk.Label(model_select_frame, text="Model:").pack(side="left", padx=5)
# Create model dropdown
self.model_var = tk.StringVar()
self.model_combo = ttk.Combobox(
model_select_frame,
textvariable=self.model_var,
width=50
)
self.model_combo.pack(side="left", padx=5, fill="x", expand=True)
# Buttons frame
btn_frame = ttk.Frame(frame)
btn_frame.pack(fill="x", pady=5)
ttk.Button(
btn_frame,
text="Scan Default Directory",
command=self.rescan_models
).pack(side="left", padx=5)
ttk.Button(
btn_frame,
text="Select Custom Directory",
command=self.select_custom_dir
).pack(side="left", padx=5)
ttk.Button(
btn_frame,
text="Load Model",
command=self.load_selected_model
).pack(side="left", padx=5)
# Model info display
self.model_info = ttk.Label(frame, text="No model loaded")
self.model_info.pack(fill="x", padx=5)
# Initial model scan
self.update_model_list()
def create_input_area(self, parent):
"""Create the input area with buttons above the prompt textbox"""
# Container frame for proper padding
container = ttk.Frame(parent)
container.pack(fill="both", expand=True, padx=5, pady=5)
# Button frame first (above input)
btn_frame = ttk.Frame(container)
btn_frame.pack(fill="x", pady=(0, 5), anchor="w")
# Create buttons with consistent sizing
button_width = 10
ttk.Button(
btn_frame,
text="Generate",