shared.py 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. import argparse
  2. model = None
  3. tokenizer = None
  4. model_name = "None"
  5. lora_name = "None"
  6. soft_prompt_tensor = None
  7. soft_prompt = False
  8. is_RWKV = False
  9. is_llamacpp = False
  10. # Chat variables
  11. history = {'internal': [], 'visible': []}
  12. character = 'None'
  13. stop_everything = False
  14. processing_message = '*Is typing...*'
  15. # UI elements (buttons, sliders, HTML, etc)
  16. gradio = {}
  17. # Generation input parameters
  18. input_params = []
  19. # For restarting the interface
  20. need_restart = False
  21. settings = {
  22. 'max_new_tokens': 200,
  23. 'max_new_tokens_min': 1,
  24. 'max_new_tokens_max': 2000,
  25. 'seed': -1,
  26. 'name1': 'You',
  27. 'name2': 'Assistant',
  28. 'context': 'This is a conversation with your Assistant. The Assistant is very helpful and is eager to chat with you and answer your questions.',
  29. 'greeting': 'Hello there!',
  30. 'end_of_turn': '',
  31. 'stop_at_newline': False,
  32. 'chat_prompt_size': 2048,
  33. 'chat_prompt_size_min': 0,
  34. 'chat_prompt_size_max': 2048,
  35. 'chat_generation_attempts': 1,
  36. 'chat_generation_attempts_min': 1,
  37. 'chat_generation_attempts_max': 5,
  38. 'default_extensions': [],
  39. 'chat_default_extensions': ["gallery"],
  40. 'presets': {
  41. 'default': 'NovelAI-Sphinx Moth',
  42. '.*(alpaca|llama)': "LLaMA-Precise",
  43. '.*pygmalion': 'NovelAI-Storywriter',
  44. '.*RWKV': 'Naive',
  45. },
  46. 'prompts': {
  47. 'default': 'QA',
  48. '.*(gpt4chan|gpt-4chan|4chan)': 'GPT-4chan',
  49. '.*oasst': 'Open Assistant',
  50. '.*alpaca': "Alpaca",
  51. },
  52. 'lora_prompts': {
  53. 'default': 'QA',
  54. '.*(alpaca-lora-7b|alpaca-lora-13b|alpaca-lora-30b)': "Alpaca",
  55. }
  56. }
  57. def str2bool(v):
  58. if isinstance(v, bool):
  59. return v
  60. if v.lower() in ('yes', 'true', 't', 'y', '1'):
  61. return True
  62. elif v.lower() in ('no', 'false', 'f', 'n', '0'):
  63. return False
  64. else:
  65. raise argparse.ArgumentTypeError('Boolean value expected.')
  66. parser = argparse.ArgumentParser(formatter_class=lambda prog: argparse.HelpFormatter(prog, max_help_position=54))
  67. # Basic settings
  68. parser.add_argument('--notebook', action='store_true', help='Launch the web UI in notebook mode, where the output is written to the same text box as the input.')
  69. parser.add_argument('--chat', action='store_true', help='Launch the web UI in chat mode with a style similar to the Character.AI website.')
  70. parser.add_argument('--cai-chat', action='store_true', help='DEPRECATED: use --chat instead.')
  71. parser.add_argument('--model', type=str, help='Name of the model to load by default.')
  72. parser.add_argument('--lora', type=str, help='Name of the LoRA to apply to the model by default.')
  73. parser.add_argument("--model-dir", type=str, default='models/', help="Path to directory with all the models")
  74. parser.add_argument("--lora-dir", type=str, default='loras/', help="Path to directory with all the loras")
  75. parser.add_argument('--no-stream', action='store_true', help='Don\'t stream the text output in real time.')
  76. parser.add_argument('--settings', type=str, help='Load the default interface settings from this json file. See settings-template.json for an example. If you create a file called settings.json, this file will be loaded by default without the need to use the --settings flag.')
  77. parser.add_argument('--extensions', type=str, nargs="+", help='The list of extensions to load. If you want to load more than one extension, write the names separated by spaces.')
  78. parser.add_argument('--verbose', action='store_true', help='Print the prompts to the terminal.')
  79. # Accelerate/transformers
  80. parser.add_argument('--cpu', action='store_true', help='Use the CPU to generate text.')
  81. parser.add_argument('--auto-devices', action='store_true', help='Automatically split the model across the available GPU(s) and CPU.')
  82. parser.add_argument('--gpu-memory', type=str, nargs="+", help='Maxmimum GPU memory in GiB to be allocated per GPU. Example: --gpu-memory 10 for a single GPU, --gpu-memory 10 5 for two GPUs. You can also set values in MiB like --gpu-memory 3500MiB.')
  83. parser.add_argument('--cpu-memory', type=str, help='Maximum CPU memory in GiB to allocate for offloaded weights. Same as above.')
  84. parser.add_argument('--disk', action='store_true', help='If the model is too large for your GPU(s) and CPU combined, send the remaining layers to the disk.')
  85. parser.add_argument('--disk-cache-dir', type=str, default="cache", help='Directory to save the disk cache to. Defaults to "cache".')
  86. parser.add_argument('--load-in-8bit', action='store_true', help='Load the model with 8-bit precision.')
  87. parser.add_argument('--bf16', action='store_true', help='Load the model with bfloat16 precision. Requires NVIDIA Ampere GPU.')
  88. parser.add_argument('--no-cache', action='store_true', help='Set use_cache to False while generating text. This reduces the VRAM usage a bit at a performance cost.')
  89. # llama.cpp
  90. parser.add_argument('--threads', type=int, default=0, help='Number of threads to use in llama.cpp.')
  91. # GPTQ
  92. parser.add_argument('--wbits', type=int, default=0, help='GPTQ: Load a pre-quantized model with specified precision in bits. 2, 3, 4 and 8 are supported.')
  93. parser.add_argument('--model_type', type=str, help='GPTQ: Model type of pre-quantized model. Currently LLaMA, OPT, and GPT-J are supported.')
  94. parser.add_argument('--groupsize', type=int, default=-1, help='GPTQ: Group size.')
  95. parser.add_argument('--pre_layer', type=int, default=0, help='GPTQ: The number of layers to allocate to the GPU. Setting this parameter enables CPU offloading for 4-bit models.')
  96. parser.add_argument('--gptq-bits', type=int, default=0, help='DEPRECATED: use --wbits instead.')
  97. parser.add_argument('--gptq-model-type', type=str, help='DEPRECATED: use --model_type instead.')
  98. parser.add_argument('--gptq-pre-layer', type=int, default=0, help='DEPRECATED: use --pre_layer instead.')
  99. # FlexGen
  100. parser.add_argument('--flexgen', action='store_true', help='Enable the use of FlexGen offloading.')
  101. parser.add_argument('--percent', type=int, nargs="+", default=[0, 100, 100, 0, 100, 0], help='FlexGen: allocation percentages. Must be 6 numbers separated by spaces (default: 0, 100, 100, 0, 100, 0).')
  102. parser.add_argument("--compress-weight", action="store_true", help="FlexGen: activate weight compression.")
  103. parser.add_argument("--pin-weight", type=str2bool, nargs="?", const=True, default=True, help="FlexGen: whether to pin weights (setting this to False reduces CPU memory by 20%%).")
  104. # DeepSpeed
  105. parser.add_argument('--deepspeed', action='store_true', help='Enable the use of DeepSpeed ZeRO-3 for inference via the Transformers integration.')
  106. parser.add_argument('--nvme-offload-dir', type=str, help='DeepSpeed: Directory to use for ZeRO-3 NVME offloading.')
  107. parser.add_argument('--local_rank', type=int, default=0, help='DeepSpeed: Optional argument for distributed setups.')
  108. # RWKV
  109. parser.add_argument('--rwkv-strategy', type=str, default=None, help='RWKV: The strategy to use while loading the model. Examples: "cpu fp32", "cuda fp16", "cuda fp16i8".')
  110. parser.add_argument('--rwkv-cuda-on', action='store_true', help='RWKV: Compile the CUDA kernel for better performance.')
  111. # Gradio
  112. parser.add_argument('--listen', action='store_true', help='Make the web UI reachable from your local network.')
  113. parser.add_argument('--listen-port', type=int, help='The listening port that the server will use.')
  114. parser.add_argument('--share', action='store_true', help='Create a public URL. This is useful for running the web UI on Google Colab or similar.')
  115. parser.add_argument('--auto-launch', action='store_true', default=False, help='Open the web UI in the default browser upon launch.')
  116. parser.add_argument("--gradio-auth-path", type=str, help='Set the gradio authentication file path. The file should contain one or more user:password pairs in this format: "u1:p1,u2:p2,u3:p3"', default=None)
  117. args = parser.parse_args()
  118. # Deprecation warnings for parameters that have been renamed
  119. deprecated_dict = {'gptq_bits': ['wbits', 0], 'gptq_model_type': ['model_type', None], 'gptq_pre_layer': ['prelayer', 0]}
  120. for k in deprecated_dict:
  121. if eval(f"args.{k}") != deprecated_dict[k][1]:
  122. print(f"Warning: --{k} is deprecated and will be removed. Use --{deprecated_dict[k][0]} instead.")
  123. exec(f"args.{deprecated_dict[k][0]} = args.{k}")
  124. # Deprecation warnings for parameters that have been removed
  125. if args.cai_chat:
  126. print("Warning: --cai-chat is deprecated. Use --chat instead.")
  127. args.chat = True
  128. def is_chat():
  129. return args.chat