GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — VirtualLora/script.py at main · FartyPants/VirtualLora Expand file tree/ Copy pathscript.pyMore file actions 1710 lines (1309 loc) · 70.3 KB / Copy pathscript.pyFile metadata and controls1710 lines (1309 loc) · 70.3 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 gradio as gr import re import os import shutil from pathlib import Path import json from peft import PeftModel import modules.shared as shared from modules.LoRA import add_lora_exllamav2 # add_lora_exllama removed import torch from datetime import datetime from functools import partial from transformers import LlamaForCausalLM,AutoModelForCausalLM,AutoTokenizer from modules.models import unload_model try: from peft.config import PeftConfig print("NEW PEFT is installed") except ImportError: print("Error: you are using an old PEFT version. LORA merging will not work. You need to update to the latest version") from peft.utils.config import PeftConfig params = { "display_name": "Virtual Lora", "is_tab": True, } g_print_twice = False folder_tree = {} comments = {} struct_params = { "edit": True, "root_SEL": "", "folders_SEL": "None", "subfolders_SEL": "None", "selected_template": "Latest", "sort_by_date": False, "strength": 100 } RED = "\033[91m" YELLOW = "\033[93m" GREEN = "\033[92m" RESET = "\033[0m" BYDATE = "[All By Month]" BYDATE2 = "[Last 10 dates]" refresh_symbol = '\U0001f504' # 🔄 str_status_text = 'Ready' last_loaded_lora_path = '' def get_file_path(filename): basepath = "extensions/VirtualLora/"+filename #if os.path.exists(basepath): # return basepath #else: # return None return basepath def save_folder_file(string,filename): path = get_file_path("Templates/"+filename+".txt") try: with open(path, 'w', encoding='utf-8') as file: file.write(string) print(f"Tree saved {path}") except Exception as e: print("Error occurred while saving string to file:", str(e)) def load_folder_file(filename): if filename==BYDATE: file_content = create_Folders_byDate(False) return file_content if filename==BYDATE2: file_content = create_Folders_byDate(True) return file_content path = get_file_path("Templates/"+filename+".txt") try: with open(path, 'r', encoding='utf-8') as file: file_content = file.read() print(f"File loaded from: {path}") return file_content except FileNotFoundError: print(f"The file '{path}' does not exist.") return "" def get_comment(subfolder_name): global folder_tree global comments comment = '' try: if subfolder_name in comments: # Display comment for the subfolder comment = comments[subfolder_name] #print(f"Comment for '{subfolder_name}' (inside '{folder_name}'): {comment}") except KeyError: pass return comment def create_folder_tree(input_string): global folder_tree global comments folder_tree = {} comments = {} lines = input_string.split('\n') current_folder = None for line in lines: # Remove any comment (if present) by splitting the line at the '#' character parts = line.split(' #', 1) line = parts[0] comment = parts[1].strip() if len(parts) > 1 else '' if line.startswith('+'): if current_folder is not None: newline = line[1:] newline = newline.strip() folder_tree[current_folder].append(newline) comments[newline] = comment else: line = line.strip() if line != '': current_folder = line folder_tree[current_folder] = [] def get_root_list(): global folder_tree root_folders = [] for folder in folder_tree: root_folders.append(folder) return root_folders def create_Folders_byDate(last_five): # Define the root folder rootFolder = shared.args.lora_dir if not rootFolder.endswith('/'): rootFolder += '/' # Create a list to store subfolder information subfolder_info = [] index = 0 print(f"Looking and sorting folders:") # Walk through the root folder to get subfolders name_list = os.listdir(rootFolder) full_list = [os.path.join(rootFolder, i) for i in name_list] for foldername in full_list: fimename = f"{foldername}"+"/adapter_config.json" if os.path.exists(fimename): try: file_timestamp = os.path.getmtime(fimename) formatted_date = datetime.fromtimestamp(file_timestamp).strftime("%Y-%m-%d-%H-%M") if last_five: formatted_date_min = datetime.fromtimestamp(file_timestamp).strftime("%Y-%m-%d") else: formatted_date_min = datetime.fromtimestamp(file_timestamp).strftime("%Y-%m") # Create a dictionary for the subfolder except: formatted_date = "1999-00-00-00-00" formatted_date_min = "Unknown" subfolder_name = os.path.basename(foldername) subfolder_dict = { "subfolder": subfolder_name, "date": formatted_date, "date_min": formatted_date_min } subfolder_info.append(subfolder_dict) index = index +1 # Sort the subfolder_info list based on the "date" key subfolder_info.sort(key=lambda x: x["date"], reverse=True) print(f" Found: {index} folders") # Create a string to group subfolders by date grouped_subfolders_string = "" current_date = None idx = 0 for subfolder in subfolder_info: subfrom = subfolder["date_min"] if subfrom != current_date: if last_five and idx>9: return grouped_subfolders_string if current_date: grouped_subfolders_string += "\n" current_date = subfrom grouped_subfolders_string += current_date + "\n" idx = idx+1 grouped_subfolders_string += "+ " + subfolder["subfolder"] + "\n" return grouped_subfolders_string def get_folder_list(selected_root_folder): global folder_tree if selected_root_folder in folder_tree: subfolders = list(folder_tree[selected_root_folder]) return subfolders else: return ["None"] def atoi(text): return int(text) if text.isdigit() else text.lower() def natural_keys(text): return [atoi(c) for c in re.split(r'(\d+)', text)] def string_to_name_list(input_string): # Split the input string by commas and remove leading/trailing spaces name_list = [name.strip() for name in input_string.split(',')] return name_list def name_list_to_string(name_list): # Join the list of names with commas return ', '.join(name_list) def get_available_templates(): templpath = get_file_path("Templates") paths = (x for x in Path(templpath).iterdir() if x.suffix in ('.txt')) sortedlist = sorted(set((k.stem for k in paths)), key=natural_keys) if len(sortedlist)==0: sortedlist = ['Latest'] sortedlist.insert(0, BYDATE) sortedlist.insert(0, BYDATE2) return sortedlist def list_Folders_byDate(directory): if not directory.endswith('/'): directory += '/' subfolders = [] path = directory name_list = os.listdir(path) full_list = [os.path.join(path, i) for i in name_list] time_sorted_list = sorted(full_list, key=os.path.getmtime , reverse=True) for entry in time_sorted_list: if os.path.isdir(entry): entry_str = f"{entry}" # Convert entry to a string full_path = entry_str entry_str = entry_str.replace('\\','/') entry_str = entry_str.replace(f"{directory}", "") # Remove directory part entry_str = entry_str.strip() entry_str = "+ "+ entry_str subfolders.append(entry_str) return subfolders def list_Folders_byAlpha(directory): if not directory.endswith('/'): directory += '/' subfolders = [] path = directory name_list = os.listdir(path) full_list = [os.path.join(path, i) for i in name_list] time_sorted_list = sorted(full_list, key=natural_keys, reverse=False) for entry in time_sorted_list: if os.path.isdir(entry): entry_str = f"{entry}" # Convert entry to a string full_path = entry_str entry_str = entry_str.replace('\\','/') entry_str = entry_str.replace(f"{directory}", "") # Remove directory part entry_str = entry_str.strip() entry_str = "+ "+ entry_str subfolders.append(entry_str) return subfolders #sort in natural order reverse def list_subfolders(directory): subfolders = [] if os.path.isdir(directory): subfolders.append('Final') for entry in os.scandir(directory): if entry.is_dir() and entry.name != 'runs': subfolders.append(entry.name) return sorted(subfolders, key=natural_keys, reverse=True) def save_pickle(): global struct_params file_nameJSON = get_file_path("params.json") try: with open(file_nameJSON, 'w') as json_file: json.dump(struct_params, json_file,indent=2) print(f"Saved: {file_nameJSON}") except IOError as e: print(f"An error occurred while saving the file: {e}") def path_to_LORA(selectlora , selectsub): if selectsub=='': selectsub = 'Final' if selectsub and selectsub!='Final': return f"{selectlora}/{selectsub}" return f"{selectlora}" def load_pickle(): global struct_params file_nameJSON = get_file_path("params.json") try: with open(file_nameJSON, 'r') as json_file: new_params = json.load(json_file) for item in new_params: struct_params[item] = new_params[item] except FileNotFoundError: print(f"Default values, the file '{file_nameJSON}' does not exist.") def load_note(): selected_lora_main = struct_params["folders_SEL"] if selected_lora_main=='': return "" path = path_to_LORA(selected_lora_main,"Final") full_path = Path(f"{shared.args.lora_dir}/{path}/notes.txt") note = f'<h3 style="color: orange;">{selected_lora_main}</h3>' if full_path.is_file(): try: with open(full_path, 'r', encoding='utf-8') as file: note = note+file.read() except: pass return note def display_comment(): selected_lora_main = struct_params["folders_SEL"] if selected_lora_main=='': return "" comment = get_comment(selected_lora_main) return comment def load_training_param(): selected_lora_main = struct_params["folders_SEL"] selected_lora_sub = struct_params['subfolders_SEL'] if selected_lora_main=='': return "No Lora selected in Folder column" table_html = '<table>' path = path_to_LORA(selected_lora_main,"Final") full_path = Path(f"{shared.args.lora_dir}/{path}/training_parameters.json") try: with open(full_path, 'r') as json_file: new_params = json.load(json_file) except FileNotFoundError: new_params = {} # Initialize as an empty dictionary if the file is not found # Define the keys you want to include in the table keys_to_include = ['dataset', 'raw_text_file', 'format', 'micro_batch_size', 'grad_accumulation', 'epochs', 'learning_rate', 'lora_rank','lora_alpha', 'cutoff_len','add_bos_token', 'add_eos_token'] keys_to_rename = ['JSON','TXT', 'format', 'batch', 'GA', 'epochs', 'LR','r','alpha','cutoff','BOS','EOS',] pastel_colors = [ '#FFC3A0', # Light Orange '#FF677D', # Light Pink '#D4A5A5', # Pale Pink '#9A8C98', # Light Gray '#90A8A4', # Pale Teal '#ABC7B2', # Soft Green '#E4F9B4', # Light Yellow '#FFD1DC', # Pastel Pink '#B5EAD7', # Seafoam Green '#FFE156', # Pastel Yellow '#A9E6E3', # Pale Blue-Green '#F5D9C3' # Peach ] # Create table header header_row = '<tr style="text-align: center;">' for i, key in enumerate(keys_to_include): newkey = keys_to_rename[i] background_color = pastel_colors[i % len(pastel_colors)] # Cycle through pastel colors header_row += f'<th style="border: 1px solid gray; padding: 8px; text-align: center; background-color: {background_color}; color: black;">{newkey}</th>' header_row += '</tr>' table_html += header_row # Create table data rows data_row = '<tr style="text-align: center;">' for key in keys_to_include: value = new_params.get(key, '') if isinstance(value, float) and value < 1: value = f'{value:.1e}' elif isinstance(value, float): value = f'{value:.2f}' data_row += f'<td style="border: 1px solid gray; padding: 8px; text-align: center;">{value}</td>' data_row += '</tr>' table_html += data_row table_html += '</table>' return table_html def load_log(): global struct_params selected_lora_main = struct_params["folders_SEL"] selected_lora_sub = struct_params['subfolders_SEL'] if selected_lora_main=='': return "None","Select LoRA" adapter_params = None new_params = None old_adapter_params = None path = path_to_LORA(selected_lora_main,selected_lora_sub) full_path = Path(f"{shared.args.lora_dir}/{path}/training_log.json") full_pathAda = Path(f"{shared.args.lora_dir}/{path}/adapter_config.json") full_pathorig = Path(f"{shared.args.lora_dir}/{path}/adapter_config_BK.json") try: with open(full_pathAda, 'r') as json_file: adapter_params = json.load(json_file) except: pass str_noteline = '' table_html = '<table>' try: with open(full_path, 'r') as json_file: new_params = json.load(json_file) except FileNotFoundError: pass # check if full_pathorig exists if full_pathorig.is_file(): with open(full_pathorig, 'r') as json_file: old_adapter_params = json.load(json_file) # get 'lora_alpha' in new_params current_alpha = 0 main_alpha = 0 if adapter_params: if 'lora_alpha' in adapter_params: current_alpha = adapter_params['lora_alpha'] # if old_adapter_params then replace lora_alpha in adapter_params with lora_alpha from old_adapter_params if old_adapter_params and adapter_params: if 'lora_alpha' in old_adapter_params: old_alpha = old_adapter_params['lora_alpha'] adapter_params['lora_alpha'] = old_alpha # set struct_params strength if adapter_params: if 'lora_alpha' in adapter_params: main_alpha = adapter_params['lora_alpha'] struct_params['strength'] = 100 if current_alpha > 0 and main_alpha > 0 and main_alpha != current_alpha: struct_params['strength'] = int((current_alpha/main_alpha)*100) row_one = '<tr style="text-align: center;">' row_two = '<tr style="text-align: center;">' if new_params: keys_to_include = ['base_model_name', 'loss', 'learning_rate', 'epoch', 'current_steps', 'projections', 'epoch_adjusted'] epoch_str = '' for key, value in new_params.items(): if key=='note': str_noteline = f"\nNote: {value}" if key=="base_model_name": base_model = f"Base: {value}" if key =="epoch": epoch_str = f'{value:.2}' if key in keys_to_include: # Create the first row with keys valid = True if key == "epoch_adjusted": value2 = new_params.get(key, '') epoch_str2 = f'{value2:.2}' if epoch_str==epoch_str2: valid = False if valid: row_one += f'<th style="border: 1px solid gray; padding: 8px; text-align: center; background-color: #233958; color: white;">{key}</th>' value = new_params.get(key, '') if isinstance(value, float) and value < 1: value = f'{value:.1e}' elif isinstance(value, float): value = f'{value:.2}' row_two += f'<td style="border: 1px solid gray; padding: 8px; text-align: center;">{value}</td>' if new_params and adapter_params: keys_to_include = ['r', 'lora_alpha'] for key, value in adapter_params.items(): if key in keys_to_include: row_one += f'<th style="border: 1px solid gray; padding: 8px; text-align: center; background-color: #235358; color: white;">{key}</th>' value = adapter_params.get(key, '') if isinstance(value, float) and value < 1: value = f'{value:.1e}' elif isinstance(value, float): value = f'{value:.2}' row_two += f'<td style="border: 1px solid gray; padding: 8px; text-align: center;">{value}</td>' if new_params==None and adapter_params: keys_to_include = ['base_model_name_or_path','r', 'lora_alpha', 'c_alpha', 'target_modules'] row_one += f'<th style="border: 1px solid gray; padding: 8px; text-align: center; background-color: #8E2438; color: white;">No log file</th>' row_two += f'<td style="border: 1px solid gray; padding: 8px; text-align: center;">training_log.json</td>' for key, value in adapter_params.items(): if key in keys_to_include: row_one += f'<th style="border: 1px solid gray; padding: 8px; text-align: center; background-color: #235358; color: white;">{key}</th>' value = adapter_params.get(key, '') if isinstance(value, float) and value < 1: value = f'{value:.1e}' elif isinstance(value, float): value = f'{value:.2}' row_two += f'<td style="border: 1px solid gray; padding: 8px; text-align: center;">{value}</td>' # if current_alpha > 0 and main_alpha > 0 and main_alpha != current_alpha then add another column but red if current_alpha > 0 and main_alpha > 0 and main_alpha != current_alpha: row_one += f'<th style="border: 1px solid gray; padding: 8px; text-align: center; background-color: #8E2438; color: white;">alpha</th>' row_two += f'<td style="border: 1px solid gray; padding: 8px; text-align: center;">{current_alpha}</td>' row_one += '</tr>' row_two += '</tr>' table_html += row_one + row_two + '</table>' return table_html+str_noteline def get_loaded_adapters(): prior_set = [] if hasattr(shared.model,'peft_config'): for adapter_name in shared.model.peft_config.items(): prior_set.append(adapter_name[0]) return prior_set def get_available_adapters_ui(): #print (f"Scaling {shared.model.base_model.scaling}") prior_set = ['None'] if shared.model: if hasattr(shared.model,'peft_config'): print(RED+"List of available adapters in model:"+RESET) index = 1 for adapter_name in shared.model.peft_config.items(): print(f" {GREEN}{index}:{RESET} {adapter_name[0]}") index = index+1 prior_set.append(adapter_name[0]) if index == 1: print(RED+" [None]"+RESET) else: print('(no model loaded yet)') return prior_set def calc_trainable_parameters(model): trainable_params = 0 all_param = 0 for _, param in model.named_parameters(): num_params = param.numel() # if using DS Zero 3 and the weights are initialized empty if num_params == 0 and hasattr(param, "ds_numel"): num_params = param.ds_numel all_param += num_params if param.requires_grad: trainable_params += num_params return trainable_params,all_param def check_models(): # Initialize an empty HTML container HTML_string = "<div><p>No model information available.</p></div>" # Check if a model is loaded if shared.model_name != 'None' and shared.model_name != '': loras_before = get_loaded_adapters() # Check if LORA adapters are loaded if len(loras_before) == 0: modeltype = shared.model.__class__.__name__ HTML_string = ( "<div>" "<p style='color: red;'><b>Warning:</b> No Lora's loaded yet.</p>" "</div>" "<table border='1' style='border-collapse: collapse; width: 100%;'>" "<tr>" "<th style='text-align: left; padding: 8px;'><b>Model</b></th>" "<th style='text-align: left; padding: 8px;'><b>Model Base</b></th>" "<th style='text-align: left; padding: 8px;'><b>Adapter</b></th>" "</tr>" "<tr>" f"<td style='padding: 8px;'><span style='color: orange;'>{modeltype}</span></td>" f"<td style='padding: 8px;'><span style='color: orange;'>None</span></td>" f"<td style='padding: 8px;'><span style='color: orange;'>None</span></td>" "</tr>" "</table>" "</div>" ) else: # Access the base model information if hasattr(shared.model, 'base_model') and hasattr(shared.model.base_model, 'model'): modelbasetype = shared.model.base_model.model.__class__.__name__ adapter_name = getattr(shared.model, 'active_adapter', 'None') if adapter_name != 'None': # Access quantization configuration if available configdic = shared.model.config.to_dict() quant_config = configdic.get('quantization_config', {}) load_in_4bit = quant_config.get('load_in_4bit', False) load_in_8bit = quant_config.get('load_in_8bit', False) # Generate warning messages based on quantization if load_in_4bit: HTML_string = ( "<div>" "<b><span style='color: red;'>Warning!</span></b> You are merging a " "<b><span style='color: orange;'>4-bit quantized model</b></span>. This might have a significantly different outcome.</p>" "</div>" ) elif load_in_8bit: HTML_string = ( "<div>" "<b><span style='color: red;'>Warning!</span></b> You are merging a " "<b><span style='color: orange;'>8-bit quantized model</b></span>. This might have a significantly different outcome.</p>" "</div>" ) else: HTML_string = ( f"<div>" f"<p>Merging with BNB active. " f"<b>4-bit:</b> {load_in_4bit}, <b>8-bit:</b> {load_in_8bit}</p>" f"</div>" ) modeltype = shared.model.__class__.__name__ # Add model and adapter information HTML_string += ( "<div>" "<table border='1' style='border-collapse: collapse; width: 100%;'>" "<tr>" "<th style='text-align: left; padding: 8px;'><b>Model</b></th>" "<th style='text-align: left; padding: 8px;'><b>Model Base</b></th>" "<th style='text-align: left; padding: 8px;'><b>Adapter</b></th>" "</tr>" "<tr>" f"<td style='padding: 8px;'><span style='color: orange;'>{modeltype}</span></td>" f"<td style='padding: 8px;'><span style='color: orange;'>{modelbasetype}</span></td>" f"<td style='padding: 8px;'><span style='color: orange;'>{adapter_name}</span></td>" "</tr>" "</table>" "</div>" ) else: # No LORA loaded error HTML_string = ( "<div>" "<p style='color: red;'><b>Error:</b> No LORA loaded.</p>" "</div>" ) else: # No model loaded fallback HTML_string = ( "<div>" "<p style='color: red;'><b>Warning:</b> No model loaded.</p>" "</div>" ) return HTML_string def dump_models(safetensors, output_dir): if shared.model_name!='None' and shared.model_name!='': modeltype = shared.model.__class__.__name__ print(f"{YELLOW}Re-saving model {RESET}{modeltype}") print(f"Saving model in default shard size ... wait - don't touch anyhing yet!") yield f"Saving model in default shard size ... wait - don't touch anyhing yet!" LlamaForCausalLM.save_pretrained(shared.model, f"{output_dir}", safe_serialization=safetensors) #, state_dict=deloreanized_sd) # save tokenizer #tokenizer = AutoTokenizer.from_pretrained(path) print(f"Saving tokenizer") yield f"Saving tokenizer" shared.tokenizer.save_pretrained(f"{output_dir}") print(f"Done.") yield f"Done. You need to reload the model now in Model tab." def merge_models(safetensors, output_dir): if shared.model_name!='None' and shared.model_name!='': loras_before = get_loaded_adapters() if len(loras_before) == 0: yield (f"No Lora's loaded yet") return modeltype = shared.model.__class__.__name__ if hasattr(shared.model, 'base_model'): if hasattr(shared.model.base_model, 'model'): modelbasetype = shared.model.base_model.model.__class__.__name__ adapter_name = getattr(shared.model,'active_adapter','None') if adapter_name != 'None': if 'quantization_config' in shared.model.config.to_dict(): configdic = shared.model.config.to_dict() load_in_4bit = configdic['quantization_config']['load_in_4bit'] load_in_8bit = configdic['quantization_config']['load_in_8bit'] if load_in_4bit: print(f"{RED}Warning! You are merging 4-bit quantized model. This might have rather different outcome. {RESET}") elif load_in_8bit: print(f"{RED}Warning! You are merging 8-bit quantized model. This might have rather different outcome. {RESET}") else: print(f"Merging with BNB active. {load_in_4bit} {load_in_8bit}") print(f"{YELLOW}Merging model {RESET}{modeltype} on top of {modelbasetype} with adapter {GREEN}{adapter_name}{RESET}") model_trainable_params, model_all_params = calc_trainable_parameters(shared.model) print(f"Params: {model_trainable_params:,d} ({100 * model_trainable_params / model_all_params:.4f} %)") print(f"Running merge_and_unload") yield f"Running merge_and_unload" #shared.model.to('cpu') shared.model = shared.model.merge_and_unload() shared.model.train(False) print(f"Saving model in 10GB shard size ... wait - don't touch anyhing yet!") yield f"Saving model in 10GB shard size ... wait - don't touch anyhing yet!" LlamaForCausalLM.save_pretrained(shared.model, f"{output_dir}", safe_serialization=safetensors) #, state_dict=deloreanized_sd) # Write content to the merge file merge_file_path = os.path.join(output_dir, "_merge.txt") with open(merge_file_path, 'w') as merge_file: merge_file.write("This is a merge file content.\n") merge_file.write(f"Base Model: {shared.model_name}\n") # split lora_name to get the main and subfolder names lora_name_split = adapter_name.split('/') lora_name_only = lora_name_split[0] lora_sub = lora_name_split[1] if len(lora_name_split) > 1 else "Final" merge_file.write(f"LORA: {lora_name_only}\n") merge_file.write(f"Checkpoint: {lora_sub}\n") # save tokenizer #tokenizer = AutoTokenizer.from_pretrained(path) shared.tokenizer.save_pretrained(f"{output_dir}") print(f"Done.") yield f"Done. You need to reload the model now in Model tab." else: print(f"{RED}Error - no PEFT model created for{RESET} {YELLOW}{modeltype}{RESET}") else: print(f"{RED}No model loaded{RESET}") yield f"No model loaded" def merge_models_CPU(safetensors, output_dir): global last_loaded_lora_path # we need to reload model in CPU mode max_memory = None if shared.model_name!='None' and shared.model_name!='': model_name = shared.model_name print(f"Unloading model from memory") unload_model() base_model_name_or_path = Path(f'{shared.args.model_dir}/{model_name}') device_map_arg = {"": "cpu"} print(f"Loading base model: {base_model_name_or_path}") yield f"Loading base model: {base_model_name_or_path}" base_model = AutoModelForCausalLM.from_pretrained( base_model_name_or_path, load_in_8bit=False, torch_dtype=torch.float16, device_map=device_map_arg, return_dict=True, max_memory=max_memory, ) lora_name = last_loaded_lora_path lora_path = Path(f"{shared.args.lora_dir}/{lora_name}") # Load the model in CPU mode if os.path.isdir(lora_path): model_trainable_params, model_all_paramsbase = calc_trainable_parameters(base_model) print(f"Model Trainable params: {model_trainable_params:,d} ({100 * model_trainable_params / model_all_paramsbase:.4f} %), All params: {model_all_paramsbase:,d}") yield (f"Applying the following LoRAs to {shared.model_name} : {lora_name}") print(f"Applying the following LoRAs to {shared.model_name} : {lora_name}") shared.lora_names = [] lora_model = PeftModel.from_pretrained( base_model, lora_path, device_map=device_map_arg, torch_dtype=torch.float16, max_memory=max_memory, ) model_trainable_params, model_all_params = calc_trainable_parameters(lora_model) print(f"LoRA Trainable params: {model_trainable_params:,d} ({100 * model_trainable_params / model_all_params:.4f} %), Params with Lora: {model_all_params:,d} from {model_all_paramsbase:,d}") # merge weights - new merging method from peft print(f"Running merge_and_unload") yield f"Running merge_and_unload - wait" lora_model = lora_model.merge_and_unload() lora_model.train(False) print(f"Saving model in 10GB shard size ... wait - don't touch anyhing yet!") yield f"Saving model in 10GB shard size ... wait - don't touch anyhing yet!" LlamaForCausalLM.save_pretrained(base_model, f"{output_dir}", safe_serialization=safetensors) #, state_dict=deloreanized_sd) # save tokenizer tokenizer_path = base_model_name_or_path #os.path.join(base_model_name_or_path, "tokenizer.model") tokenizer = AutoTokenizer.from_pretrained(tokenizer_path) tokenizer.save_pretrained(f"{output_dir}") print(f"Model saved to {output_dir}") yield f"Model saved to {output_dir}" # Write content to the merge file merge_file_path = os.path.join(output_dir, "_merge.txt") with open(merge_file_path, 'w') as merge_file: merge_file.write("This is a merge file content.\n") merge_file.write(f"Base Model: {model_name}\n") # split lora_name to get the main and subfolder names lora_name_split = lora_name.split('/') lora_name_only = lora_name_split[0] lora_sub = lora_name_split[1] if len(lora_name_split) > 1 else "Final" merge_file.write(f"LORA: {lora_name_only}\n") merge_file.write(f"Checkpoint: {lora_sub}\n") print(f"**** DONE ****") yield f"**** DONE ****" else: print(f"{RED}Error: Model not loaded yet{RESET}") yield f"Error: Model not loaded yet" pass def add_lora_to_model(lora_name): #elif shared.model.__class__.__name__ in ['ExllamaModel', 'ExllamaHF'] or shared.args.loader == 'ExLlama': # add_lora_exllama([lora_name]) #if 'GPTQForCausalLM' in shared.model.__class__.__name__ or shared.args.loader == 'AutoGPTQ': # add_lora_autogptq([lora_name]) if shared.model.__class__.__name__ in ['Exllamav2Model', 'Exllamav2HF'] or shared.args.loader == ['ExLlamav2', 'ExLlamav2_HF']: add_lora_exllamav2([lora_name]) else: params = {} if not shared.args.cpu: if shared.args.load_in_4bit or shared.args.load_in_8bit: params['peft_type'] = shared.model.dtype else: params['dtype'] = shared.model.dtype if hasattr(shared.model, "hf_device_map"): params['device_map'] = {"base_model.model." + k: v for k, v in shared.model.hf_device_map.items()} print(f"Applying the following LoRAs to {shared.model_name}: {lora_name}") lora_path = Path(f"{shared.args.lora_dir}/{lora_name}") lora_path_bin = Path(f"{shared.args.lora_dir}/{lora_name}/adapter_model.bin") # safetensors version lora_path_sf = Path(f"{shared.args.lora_dir}/{lora_name}/adapter_model.safetensors") if lora_path_sf.is_file(): lora_path_bin = lora_path_sf if lora_path_bin.is_file(): safeloraname = lora_name.replace('.', '_') shared.model = PeftModel.from_pretrained(shared.model, lora_path, adapter_name=safeloraname, **params) if not shared.args.load_in_8bit and not shared.args.cpu: shared.model.half() if not hasattr(shared.model, "hf_device_map"): if torch.backends.mps.is_available(): device = torch.device('mps') shared.model = shared.model.to(device) else: shared.model = shared.model.cuda() else: print(f"{RED}Adapter file (adapter_model.bin) doesn't exist in {RESET}{lora_path}") # if old PEFT, you need to remove these form adapter_config.json #adapter_config.pop('eva_config', None) #adapter_config.pop('exclude_modules', None) #adapter_config.pop('lora_bias', None) def set_strength(): global struct_params strength = struct_params['strength']/100.0 selected_lora_main = struct_params["folders_SEL"] selected_lora_sub = struct_params['subfolders_SEL'] path = path_to_LORA(selected_lora_main, selected_lora_sub) lora_path = Path(f"{shared.args.lora_dir}/{path}") #first check if adapter_config_BK.json exist and if not copy adapter_config.json to adapter_config_BK.json if os.path.isfile(f"{lora_path}/adapter_config.json"): if not os.path.isfile(f"{lora_path}/adapter_config_BK.json"): # copy adapter_config.json to adapter_config_BK.json and give error if it fails try: shutil.copy(f"{lora_path}/adapter_config.json", f"{lora_path}/adapter_config_BK.json") print(f"{RED}adapter_config_BK.json created {RESET}") except: print(f"{RED}Error: adapter_config_BK.json not created {RESET}") # Define the paths reference_file = f"{lora_path}/adapter_config.json" target_file = f"{lora_path}/adapter_config_BK.json" # Get the timestamps of the reference file stat = os.stat(reference_file) # Apply the same timestamps to the target file # make sure target_file exists |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |