Files
SillyTavern/colab/GPU.ipynb
T

14 KiB

Links
Cohee's TavernAI fork Github https://github.com/Cohee1207/SillyTavern
Cohee's TavernAI Extras Github https://github.com/Cohee1207/TavernAI-extras/
TavernAI Discord https://discord.gg/zmK2gmr45t
Questions? Hit me up on Discord: Cohee#1207

In [ ]:
#@title <b><-- Convert TavernAI characters to SillyTavern format</b>

!mkdir /convert
%cd /convert

import os
from google.colab import drive

drive.mount("/convert/drive")

!git clone -b tools https://github.com/EnergoStalin/SillyTavern.git
%cd SillyTavern

!curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
!nvm install 19.1.0
!nvm use 19.1.0

%cd tools/charaverter

!npm i

path = "/convert/drive/MyDrive/TavernAI/characters"
output = "/convert/drive/MyDrive/SillyTavern/characters"
if not os.path.exists(path):
  path = output

!mkdir -p $output
!node main.mjs $path $output

drive.flush_and_unmount()

%cd /
!rm -rf /convert
In [ ]:
#@title <-- Tap this if you play on Mobile { display-mode: "form" }
%%html
<b>Press play on the music player to keep the tab alive, then start KoboldAI below (Uses only 13MB of data)</b><br/>
<audio src="https://raw.githubusercontent.com/KoboldAI/KoboldAI-Client/main/colab/silence.m4a" controls>
In [ ]:
#@title <b><-- Select your model below and then click this to start KoboldAI</b>

Model = "Pygmalion 6B" #@param ["Nerys V2 6B", "Erebus 6B", "Skein 6B", "Janeway 6B", "Adventure 6B", "Pygmalion 6B", "Pygmalion 6B Dev", "Lit V2 6B", "Lit 6B", "Shinen 6B", "Nerys 2.7B", "AID 2.7B", "Erebus 2.7B", "Janeway 2.7B", "Picard 2.7B", "Horni LN 2.7B", "Horni 2.7B", "Shinen 2.7B", "OPT 2.7B", "Fairseq Dense 2.7B", "Neo 2.7B", "Pygway 6B", "Nerybus 6.7B", "Pygway v8p4", "PPO-Janeway 6B", "PPO Shygmalion 6B", "LLaMA 7B", "Janin-GPTJ", "Javelin-GPTJ", "Javelin-R", "Janin-R", "Javalion-R", "Javalion-GPTJ", "Javelion-6B", "GPT-J-Pyg-PPO-6B", "ppo_hh_pythia-6B", "ppo_hh_gpt-j", "GPT-J-Pyg_PPO-6B", "GPT-J-Pyg_PPO-6B-Dev-V8p4", "Dolly_GPT-J-6b", "Dolly_Pyg-6B"] {allow-input: true}
Version = "Official" #@param ["Official", "United"] {allow-input: true}
Provider = "Localtunnel" #@param ["Localtunnel"]
ForceInitSteps = [] #@param {allow-input: true}
UseGoogleDrive = True #@param {type:"boolean"}
StartKoboldAI = True #@param {type:"boolean"}
ModelsFromDrive = False #@param {type:"boolean"}
UseExtrasExtensions = True #@param {type:"boolean"}
#@markdown Enables hosting of extensions backend for TavernAI Extras
extras_enable_captioning = True #@param {type:"boolean"}
#@markdown Loads the image captioning module
Captions_Model = "Salesforce/blip-image-captioning-large" #@param [ "Salesforce/blip-image-captioning-large", "Salesforce/blip-image-captioning-base" ]
#@markdown * Salesforce/blip-image-captioning-large - good base model
#@markdown * Salesforce/blip-image-captioning-base - slightly faster but less accurate
extras_enable_emotions = True #@param {type:"boolean"}
#@markdown Loads the sentiment classification model
Emotions_Model = "bhadresh-savani/distilbert-base-uncased-emotion" #@param ["bhadresh-savani/distilbert-base-uncased-emotion", "joeddav/distilbert-base-uncased-go-emotions-student"]
#@markdown * bhadresh-savani/distilbert-base-uncased-emotion = 6 supported emotions<br>
#@markdown * joeddav/distilbert-base-uncased-go-emotions-student = 28 supported emotions
extras_enable_memory = True #@param {type:"boolean"}
#@markdown Loads the story summarization module
Memory_Model = "Qiliang/bart-large-cnn-samsum-ChatGPT_v3" #@param [ "Qiliang/bart-large-cnn-samsum-ChatGPT_v3", "Qiliang/bart-large-cnn-samsum-ElectrifAi_v10", "distilbart-xsum-12-3" ]
#@markdown * Qiliang/bart-large-cnn-samsum-ChatGPT_v3 - summarization model optimized for chats
#@markdown * Qiliang/bart-large-cnn-samsum-ElectrifAi_v10 - nice results so far, but still being evaluated
#@markdown * distilbart-xsum-12-3 - faster, but pretty basic alternative


%cd /content

!cat .ii
!nvidia-smi

import os, subprocess, time, pathlib, json, base64, sys

# ---
# Utils
class IncrementialInstall:
  def __init__(self, root = "/", tasks = [], force = []):
    self.tasks = tasks
    self.path = os.path.join(root, ".ii")
    self.completed = list(filter(lambda x: not x in force, self.__completed()))

  def __completed(self):
    try:
      with open(self.path) as f:
        return json.load(f)
    except:
      return []

  def addTask(self, name, func):
    self.tasks.append({"name": name, "func": func})

  def run(self):
    todo = list(filter(lambda x: not x["name"] in self.completed, self.tasks))
    try:
      for task in todo:
        task["func"]()
        self.completed.append(task["name"])
    finally:
      with open(self.path, "w") as f:
        json.dump(self.completed, f)

def create_paths(paths):
  for directory in paths:
    if not os.path.exists(directory):
      os.makedirs(directory)

def link(srcDir, destDir, files):
  '''
    Link source to dest copying dest to source if not present first
  '''
  for file in files:
    source = os.path.join(srcDir, file)
    dest = os.path.join(destDir, file)
    if not os.path.exists(source):
      !cp -r "$dest" "$source"
    !rm -rf "$dest"
    !ln -fs "$source" "$dest"

from google.colab import drive
if UseGoogleDrive:
  drive.mount("/content/drive/")
else:
  create_paths([
      "/content/drive/MyDrive"
  ])

ii = IncrementialInstall(force=ForceInitSteps)

# ---
# SillyTavern py modules
def cloneTavern():
  %cd /
  !git clone https://github.com/Cohee1207/SillyTavern
  %cd -
  !cp /SillyTavern/colab/*.py ./
ii.addTask("Clone SillyTavern", cloneTavern)
ii.run()

from models import GetModels, ModelData
model = GetModels(Version).get(Model, ModelData(Model, Version))

# ---
# KoboldAI
if StartKoboldAI:
  def downloadKobold():
    !wget https://koboldai.org/ckds && chmod +x ckds
  def initKobold():
    !./ckds --init only

  ii.addTask("Download KoboldAI", downloadKobold)
  ii.addTask("Init KoboldAI", initKobold)
  
  ii.run()

kargs = ["/content/ckds"]
if not ModelsFromDrive:
  kargs += ["-x", "colab", "-l", "colab"]
if Provider == "Localtunnel":
  kargs += ["--localtunnel", "yes"]

kargs += model.args()

url = ""
print(kargs)

if StartKoboldAI:
  p = subprocess.Popen(kargs, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

  prefix = "KoboldAI has finished loading and is available at the following link"
  urlprefix = f"{prefix}: "
  ui1prefix = f"{prefix} for UI 1: "
  while True:
      line = p.stdout.readline().decode().strip()
      print(line)
      if urlprefix in line:
          url = line.split(urlprefix)[1]
          break
      elif ui1prefix in line:
          url = line.split(ui1prefix)[1]
          break
      elif not line:
          break
      if "INIT" in line and "Transformers" in line:
        print("Model loading... (It will take 2 - 5 minutes)")

print(url)


# ---
# nodejs
%cd /
def setupNVM():
  !curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.37.2/install.sh | bash
ii.addTask("Setup NVM", setupNVM)

def installNode():
  !nvm install 19.1.0
  !nvm use 19.1.0
ii.addTask("Install node", installNode)


# ---
# TavernAI extras
import globals
globals.extras_url = '(disabled)'
globals.params = []
globals.params.append('--cpu')
ExtrasModules = []

if (extras_enable_captioning):
  ExtrasModules.append('caption')
if (extras_enable_memory):
  ExtrasModules.append('summarize')
if (extras_enable_emotions):
  ExtrasModules.append('classify')

globals.params.append(f'--classification-model={Emotions_Model}')
globals.params.append(f'--summarization-model={Memory_Model}')
globals.params.append(f'--captioning-model={Captions_Model}')
globals.params.append(f'--enable-modules={",".join(ExtrasModules)}')


if UseExtrasExtensions:
    def cloneExtras():
        %cd /
        !git clone https://github.com/Cohee1207/TavernAI-extras
    ii.addTask('clone extras', cloneExtras)

    def installRequirements():
        %cd /TavernAI-extras
        !npm install -g localtunnel
        !pip install -r requirements.txt
        !pip install tensorflow==2.11
    ii.addTask('install requirements', installRequirements)

    from extras_server import runServer, extractUrl
    ii.addTask('run server', runServer)
    ii.addTask('extract extras URL', extractUrl)

%cd /SillyTavern

if UseGoogleDrive:
  %env googledrive=2

  def setupTavernPaths():
    %cd /SillyTavern
    tdrive = "/content/drive/MyDrive/SillyTavern"
    create_paths([
        tdrive,
        os.path.join("public", "groups"),
        os.path.join("public", "group chats")
    ])
    link(tdrive, "public", [
        "settings.json",
        "backgrounds",
        "characters",
        "chats",
        "User Avatars",
        "css",
        "worlds",
        "group chats",
        "groups",
    ])
  ii.addTask("Setup Tavern Paths", setupTavernPaths)

def installTavernDependencies():
  %cd /SillyTavern
  !npm install
  !npm install -g localtunnel
ii.addTask("Install Tavern Dependencies", installTavernDependencies)
ii.run()

%env colaburl=$url
%env SILLY_TAVERN_PORT=5001
print("KoboldAI LINK:", url, '###Extensions API LINK###', globals.extras_url,  "###SillyTavern LINK###", sep="\n")
p = subprocess.Popen(["lt", "--port", "5001"], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
print(p.stdout.readline().decode().strip())
!node server.js