Compare commits
57 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e666c50f77 | ||
|
|
1b441752b0 | ||
|
|
e01897b24d | ||
|
|
6146d910b4 | ||
|
|
0063c171f3 | ||
|
|
bea3c29c1c | ||
|
|
5f543c2545 | ||
|
|
177b2c54d9 | ||
|
|
645e8e2f44 | ||
|
|
f2d0dda2ff | ||
|
|
3a449e7b46 | ||
|
|
18d2ecb7a7 | ||
|
|
bb3a93b419 | ||
|
|
1334f0e5ba | ||
|
|
8781416cfb | ||
|
|
a9819139b8 | ||
|
|
66e43c9d9b | ||
|
|
41e5bd5eb8 | ||
|
|
48fef0235b | ||
|
|
d435436525 | ||
|
|
cd7a9896dc | ||
|
|
bbcc6b07b6 | ||
|
|
646bcd81c0 | ||
|
|
dbf0dccc9d | ||
|
|
437de2be20 | ||
|
|
f739c61197 | ||
|
|
01d3c89ea4 | ||
|
|
d18218f21a | ||
|
|
c8470e77fd | ||
|
|
9ede7d7c6d | ||
|
|
a59c4436c8 | ||
|
|
068be2bfc4 | ||
|
|
94a5dc4fb7 | ||
|
|
9f288de951 | ||
|
|
3d5c3dcd31 | ||
|
|
0a4876a564 | ||
|
|
4f0558ae34 | ||
|
|
f03c9cf25f | ||
|
|
07797537d1 | ||
|
|
0c3a50cb07 | ||
|
|
c7dcff52a1 | ||
|
|
c6ef32958e | ||
|
|
7235e1067b | ||
|
|
0594290b92 | ||
|
|
d249a4c29a | ||
|
|
02ba37fab4 | ||
|
|
b5a6f8a425 | ||
|
|
1ad86d737c | ||
|
|
cfa3669f6f | ||
|
|
26d4c9f0ed | ||
|
|
3ddcf9f62e | ||
|
|
e734fce64f | ||
|
|
150beb578c | ||
|
|
db6fbe8366 | ||
|
|
46f52923c3 | ||
|
|
893be5cf43 | ||
|
|
384e4ce4d0 |
7
.github/workflows/release.yml
vendored
7
.github/workflows/release.yml
vendored
@@ -109,6 +109,7 @@ jobs:
|
||||
go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||
rm ./backend-python/rwkv_pip/wkv_cuda.pyd
|
||||
rm ./backend-python/rwkv_pip/rwkv5.pyd
|
||||
rm ./backend-python/rwkv_pip/rwkv6.pyd
|
||||
rm ./backend-python/rwkv_pip/beta/wkv_cuda.pyd
|
||||
rm ./backend-python/get-pip.py
|
||||
make
|
||||
@@ -134,12 +135,14 @@ jobs:
|
||||
- run: |
|
||||
git clone https://github.com/josStorer/ai00_rwkv_server --depth=1
|
||||
cd ai00_rwkv_server
|
||||
cargo build --release
|
||||
mv ./target/release/ai00_server ../backend-rust/webgpu_server
|
||||
rustup target add aarch64-apple-darwin
|
||||
cargo build --release --target aarch64-apple-darwin
|
||||
mv ./target/aarch64-apple-darwin/release/ai00_server ../backend-rust/webgpu_server
|
||||
cd ..
|
||||
go install github.com/wailsapp/wails/v2/cmd/wails@latest
|
||||
rm ./backend-python/rwkv_pip/wkv_cuda.pyd
|
||||
rm ./backend-python/rwkv_pip/rwkv5.pyd
|
||||
rm ./backend-python/rwkv_pip/rwkv6.pyd
|
||||
rm ./backend-python/rwkv_pip/beta/wkv_cuda.pyd
|
||||
rm ./backend-python/get-pip.py
|
||||
make
|
||||
|
||||
2
.gitignore
vendored
2
.gitignore
vendored
@@ -18,7 +18,7 @@ __pycache__
|
||||
/cmd-helper.bat
|
||||
/install-py-dep.bat
|
||||
/backend-python/wkv_cuda
|
||||
/backend-python/rwkv5
|
||||
/backend-python/rwkv*
|
||||
*.exe
|
||||
*.old
|
||||
.DS_Store
|
||||
|
||||
@@ -1,29 +1,13 @@
|
||||
## Changes
|
||||
|
||||
### Features
|
||||
|
||||
- chat attachment is now related to single message (Experimental)
|
||||
- port occupied detection
|
||||
|
||||
### Upgrades
|
||||
|
||||
- upgrade to rwkv 0.8.20
|
||||
|
||||
### Improvements
|
||||
|
||||
- improve the compatibility between frontend presets and chatgpt api
|
||||
- improve memory usage of state cache
|
||||
|
||||
### Chores
|
||||
|
||||
- update ngrok_connect
|
||||
- python38 compatibility
|
||||
- adjust startup process
|
||||
|
||||
### Fixes
|
||||
|
||||
- fix log encoding error
|
||||
- fix stop button status of Chat page
|
||||
- upgrade to rwkv 0.8.22 (rwkv6 support)
|
||||
- allow reading attachments even if the model is offline
|
||||
- improve launch flow of webgpu mode
|
||||
- allow safetensors converter on macOS
|
||||
- fix fs watcher of macOS
|
||||
- update defaultConfigs
|
||||
- update manifest
|
||||
- chores
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
10
Makefile
10
Makefile
@@ -18,6 +18,16 @@ build-linux:
|
||||
@echo ---- build for linux
|
||||
wails build -upx -ldflags "-s -w" -platform linux/amd64
|
||||
|
||||
build-web:
|
||||
@echo ---- build for web
|
||||
cd frontend && npm run build
|
||||
|
||||
dev:
|
||||
wails dev
|
||||
|
||||
dev-web:
|
||||
cd frontend && npm run dev
|
||||
|
||||
preview:
|
||||
cd frontend && npm run preview
|
||||
|
||||
|
||||
@@ -4,12 +4,14 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"github.com/fsnotify/fsnotify"
|
||||
"github.com/minio/selfupdate"
|
||||
@@ -43,7 +45,7 @@ func (a *App) OnStartup(ctx context.Context) {
|
||||
a.cmdPrefix = "cd " + a.exDir + " && "
|
||||
}
|
||||
|
||||
os.Chmod("./backend-rust/webgpu_server", 0777)
|
||||
os.Chmod(a.exDir+"backend-rust/webgpu_server", 0777)
|
||||
os.Mkdir(a.exDir+"models", os.ModePerm)
|
||||
os.Mkdir(a.exDir+"lora-models", os.ModePerm)
|
||||
os.Mkdir(a.exDir+"finetune/json2binidx_tool/data", os.ModePerm)
|
||||
@@ -67,8 +69,8 @@ func (a *App) OnBeforeClose(ctx context.Context) bool {
|
||||
func (a *App) watchFs() {
|
||||
watcher, err := fsnotify.NewWatcher()
|
||||
if err == nil {
|
||||
watcher.Add("./lora-models")
|
||||
watcher.Add("./models")
|
||||
watcher.Add(a.exDir + "./lora-models")
|
||||
watcher.Add(a.exDir + "./models")
|
||||
go func() {
|
||||
for {
|
||||
select {
|
||||
@@ -118,13 +120,50 @@ func (a *App) monitorHardware() {
|
||||
monitor.Start()
|
||||
}
|
||||
|
||||
type ProgressReader struct {
|
||||
reader io.Reader
|
||||
total int64
|
||||
err error
|
||||
}
|
||||
|
||||
func (pr *ProgressReader) Read(p []byte) (n int, err error) {
|
||||
n, err = pr.reader.Read(p)
|
||||
pr.err = err
|
||||
pr.total += int64(n)
|
||||
return
|
||||
}
|
||||
|
||||
func (a *App) UpdateApp(url string) (broken bool, err error) {
|
||||
resp, err := http.Get(url)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
err = selfupdate.Apply(resp.Body, selfupdate.Options{})
|
||||
pr := &ProgressReader{reader: resp.Body}
|
||||
|
||||
ticker := time.NewTicker(250 * time.Millisecond)
|
||||
defer ticker.Stop()
|
||||
|
||||
go func() {
|
||||
for {
|
||||
<-ticker.C
|
||||
wruntime.EventsEmit(a.ctx, "updateApp", &DownloadStatus{
|
||||
Name: filepath.Base(url),
|
||||
Path: "",
|
||||
Url: url,
|
||||
Transferred: pr.total,
|
||||
Size: resp.ContentLength,
|
||||
Speed: 0,
|
||||
Progress: 100 * (float64(pr.total) / float64(resp.ContentLength)),
|
||||
Downloading: pr.err == nil && pr.total < resp.ContentLength,
|
||||
Done: pr.total == resp.ContentLength,
|
||||
})
|
||||
if pr.err != nil || pr.total == resp.ContentLength {
|
||||
break
|
||||
}
|
||||
}
|
||||
}()
|
||||
err = selfupdate.Apply(pr, selfupdate.Options{})
|
||||
if err != nil {
|
||||
if rerr := selfupdate.RollbackError(err); rerr != nil {
|
||||
return true, rerr
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
func (a *App) StartServer(python string, port int, host string, rwkvBeta bool) (string, error) {
|
||||
func (a *App) StartServer(python string, port int, host string, webui bool, rwkvBeta bool) (string, error) {
|
||||
var err error
|
||||
if python == "" {
|
||||
python, err = GetPython()
|
||||
@@ -19,6 +19,9 @@ func (a *App) StartServer(python string, port int, host string, rwkvBeta bool) (
|
||||
return "", err
|
||||
}
|
||||
args := []string{python, "./backend-python/main.py"}
|
||||
if webui {
|
||||
args = append(args, "--webui")
|
||||
}
|
||||
if rwkvBeta {
|
||||
args = append(args, "--rwkv-beta")
|
||||
}
|
||||
|
||||
1
backend-python/convert_model.py
vendored
1
backend-python/convert_model.py
vendored
@@ -231,5 +231,6 @@ try:
|
||||
convert_and_save_and_exit=args.out,
|
||||
)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
with open("error.txt", "w") as f:
|
||||
f.write(str(e))
|
||||
|
||||
1
backend-python/convert_safetensors.py
vendored
1
backend-python/convert_safetensors.py
vendored
@@ -65,5 +65,6 @@ if __name__ == "__main__":
|
||||
)
|
||||
print(f"Saved to {args.output}")
|
||||
except Exception as e:
|
||||
print(e)
|
||||
with open("error.txt", "w") as f:
|
||||
f.write(str(e))
|
||||
|
||||
@@ -4,6 +4,7 @@ Args = "args"
|
||||
Model = "model"
|
||||
Model_Status = "model_status"
|
||||
Model_Config = "model_config"
|
||||
Deploy_Mode = "deploy_mode"
|
||||
|
||||
|
||||
class ModelStatus(Enum):
|
||||
@@ -16,6 +17,7 @@ def init():
|
||||
global GLOBALS
|
||||
GLOBALS = {}
|
||||
set(Model_Status, ModelStatus.Offline)
|
||||
set(Deploy_Mode, False)
|
||||
|
||||
|
||||
def set(key, value):
|
||||
|
||||
@@ -22,6 +22,11 @@ def get_args(args: Union[Sequence[str], None] = None):
|
||||
help="host to run the server on (default: 127.0.0.1)",
|
||||
)
|
||||
group = parser.add_argument_group(title="mode arguments")
|
||||
group.add_argument(
|
||||
"--webui",
|
||||
action="store_true",
|
||||
help="whether to enable WebUI (default: False)",
|
||||
)
|
||||
group.add_argument(
|
||||
"--rwkv-beta",
|
||||
action="store_true",
|
||||
@@ -43,7 +48,7 @@ sys.path.append(os.path.dirname(os.path.realpath(__file__)))
|
||||
|
||||
import psutil
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi import Depends, FastAPI, status
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import uvicorn
|
||||
|
||||
@@ -79,6 +84,35 @@ app.include_router(misc.router)
|
||||
app.include_router(state_cache.router)
|
||||
|
||||
|
||||
@app.post("/exit", tags=["Root"])
|
||||
def exit():
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
parent_pid = os.getpid()
|
||||
parent = psutil.Process(parent_pid)
|
||||
for child in parent.children(recursive=True):
|
||||
child.kill()
|
||||
parent.kill()
|
||||
|
||||
|
||||
try:
|
||||
if (
|
||||
"RWKV_RUNNER_PARAMS" in os.environ
|
||||
and "--webui" in os.environ["RWKV_RUNNER_PARAMS"].split(" ")
|
||||
) or args.webui:
|
||||
from webui_server import webui_server
|
||||
|
||||
app.mount("/", webui_server)
|
||||
except NameError:
|
||||
pass
|
||||
|
||||
|
||||
@app.get("/", tags=["Root"])
|
||||
def read_root():
|
||||
return {"Hello": "World!"}
|
||||
|
||||
|
||||
def init():
|
||||
global_var.init()
|
||||
cmd_params = os.environ["RWKV_RUNNER_PARAMS"]
|
||||
@@ -94,20 +128,6 @@ def init():
|
||||
ngrok_connect()
|
||||
|
||||
|
||||
@app.get("/", tags=["Root"])
|
||||
def read_root():
|
||||
return {"Hello": "World!"}
|
||||
|
||||
|
||||
@app.post("/exit", tags=["Root"])
|
||||
def exit():
|
||||
parent_pid = os.getpid()
|
||||
parent = psutil.Process(parent_pid)
|
||||
for child in parent.children(recursive=True):
|
||||
child.kill()
|
||||
parent.kill()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
os.environ["RWKV_RUNNER_PARAMS"] = " ".join(sys.argv[1:])
|
||||
print("--- %s seconds ---" % (time.time() - start_time))
|
||||
|
||||
@@ -35,6 +35,11 @@ default_stop = [
|
||||
"\n\nQ",
|
||||
"\n\nHuman",
|
||||
"\n\nBob",
|
||||
"\n\nAssistant",
|
||||
"\n\nAnswer",
|
||||
"\n\nA",
|
||||
"\n\nBot",
|
||||
"\n\nAlice",
|
||||
]
|
||||
|
||||
|
||||
@@ -53,8 +58,8 @@ class ChatCompletionBody(ModelConfigBody):
|
||||
True, description="Whether to insert default system prompt at the beginning"
|
||||
)
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"messages": [
|
||||
{"role": Role.User.value, "content": "hello", "raw": False}
|
||||
@@ -72,6 +77,7 @@ class ChatCompletionBody(ModelConfigBody):
|
||||
"frequency_penalty": 0.4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
class CompletionBody(ModelConfigBody):
|
||||
@@ -80,8 +86,8 @@ class CompletionBody(ModelConfigBody):
|
||||
stream: bool = False
|
||||
stop: Union[str, List[str], None] = None
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"prompt": "The following is an epic science fiction masterpiece that is immortalized, "
|
||||
+ "with delicate descriptions and grand depictions of interstellar civilization wars.\nChapter 1.\n",
|
||||
@@ -95,6 +101,7 @@ class CompletionBody(ModelConfigBody):
|
||||
"frequency_penalty": 0.4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
completion_lock = Lock()
|
||||
@@ -376,8 +383,8 @@ class EmbeddingsBody(BaseModel):
|
||||
encoding_format: str = None
|
||||
fast_mode: bool = False
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"input": "a big apple",
|
||||
"model": "rwkv",
|
||||
@@ -385,6 +392,7 @@ class EmbeddingsBody(BaseModel):
|
||||
"fast_mode": False,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def embedding_base64(embedding: List[float]) -> str:
|
||||
|
||||
@@ -15,20 +15,29 @@ class SwitchModelBody(BaseModel):
|
||||
strategy: str
|
||||
tokenizer: Union[str, None] = None
|
||||
customCuda: bool = False
|
||||
deploy: bool = Field(
|
||||
False,
|
||||
description="Deploy mode. If success, will disable /switch-model, /exit and other dangerous APIs (state cache APIs, part of midi APIs)",
|
||||
)
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"model": "models/RWKV-4-World-3B-v1-20230619-ctx4096.pth",
|
||||
"strategy": "cuda fp16",
|
||||
"tokenizer": None,
|
||||
"tokenizer": "",
|
||||
"customCuda": False,
|
||||
"deploy": False,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/switch-model", tags=["Configs"])
|
||||
def switch_model(body: SwitchModelBody, response: Response, request: Request):
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(Status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if global_var.get(global_var.Model_Status) is global_var.ModelStatus.Loading:
|
||||
response.status_code = Status.HTTP_304_NOT_MODIFIED
|
||||
return
|
||||
@@ -64,6 +73,8 @@ def switch_model(body: SwitchModelBody, response: Response, request: Request):
|
||||
Status.HTTP_500_INTERNAL_SERVER_ERROR, f"failed to load: {e}"
|
||||
)
|
||||
|
||||
if body.deploy:
|
||||
global_var.set(global_var.Deploy_Mode, True)
|
||||
if global_var.get(global_var.Model_Config) is None:
|
||||
global_var.set(
|
||||
global_var.Model_Config, get_rwkv_config(global_var.get(global_var.Model))
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import io
|
||||
import global_var
|
||||
from fastapi import APIRouter, HTTPException, status
|
||||
from starlette.responses import StreamingResponse
|
||||
from pydantic import BaseModel
|
||||
@@ -11,12 +12,13 @@ router = APIRouter()
|
||||
class TextToMidiBody(BaseModel):
|
||||
text: str
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"text": "p:24:a p:2a:a p:31:a p:39:a p:3b:a p:45:a b:26:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:24:0 p:2a:0 p:31:0 p:39:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:26:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:2e:a p:3b:a p:45:a b:26:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:2e:0 p:3b:0 p:45:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:2e:a p:3b:a p:45:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:2e:0 p:3b:0 p:45:0 b:26:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:26:a p:2a:a p:3b:a p:45:a t14 p:26:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a b:26:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:2a:0 p:3b:0 p:45:0 b:26:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:2d:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 b:2d:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:24:a p:2e:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:24:0 p:2e:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:26:a p:2a:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:26:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:26:a p:2e:a p:31:a p:39:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:26:0 p:2e:0 p:31:0 p:39:0 p:3b:0 p:45:0 b:21:0 t2 p:26:a p:2e:a p:31:a p:39:a p:3b:a p:45:a b:21:a t14 p:26:0 p:2e:0 p:31:0 p:39:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:24:a p:2a:a p:31:a p:39:a p:3b:a p:45:a b:1f:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:24:0 p:2a:0 p:31:0 p:39:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:1f:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:2e:a p:3b:a p:45:a b:1f:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:2e:0 p:3b:0 p:45:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:2e:a p:3b:a p:45:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:2e:0 p:3b:0 p:45:0 b:1f:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:26:a p:2a:a p:3b:a p:45:a t14 p:26:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a b:1f:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:2a:0 p:3b:0 p:45:0 b:1f:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:1f:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 b:1f:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:24:a p:2e:a p:3b:a p:45:a b:26:a g:39:a g:39:a g:3e:a g:3e:a g:42:a g:42:a pi:39:a pi:3e:a pi:42:a t14 p:24:0 p:2e:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/text-to-midi", tags=["MIDI"])
|
||||
@@ -35,17 +37,21 @@ class TxtToMidiBody(BaseModel):
|
||||
txt_path: str
|
||||
midi_path: str
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"txt_path": "midi/sample.txt",
|
||||
"midi_path": "midi/sample.mid",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/txt-to-midi", tags=["MIDI"])
|
||||
def txt_to_midi(body: TxtToMidiBody):
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if not body.midi_path.startswith("midi/"):
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "bad output path")
|
||||
|
||||
@@ -65,14 +71,15 @@ class MidiToWavBody(BaseModel):
|
||||
wav_path: str
|
||||
sound_font_path: str = "assets/default_sound_font.sf2"
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"midi_path": "midi/sample.mid",
|
||||
"wav_path": "midi/sample.wav",
|
||||
"sound_font_path": "assets/default_sound_font.sf2",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/midi-to-wav", tags=["MIDI"])
|
||||
@@ -81,6 +88,9 @@ def midi_to_wav(body: MidiToWavBody):
|
||||
Install fluidsynth first, see more: https://github.com/FluidSynth/fluidsynth/wiki/Download#distributions
|
||||
"""
|
||||
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if not body.wav_path.startswith("midi/"):
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "bad output path")
|
||||
|
||||
@@ -95,14 +105,15 @@ class TextToWavBody(BaseModel):
|
||||
wav_name: str
|
||||
sound_font_path: str = "assets/default_sound_font.sf2"
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"text": "p:24:a p:2a:a p:31:a p:39:a p:3b:a p:45:a b:26:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:24:0 p:2a:0 p:31:0 p:39:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:26:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:2e:a p:3b:a p:45:a b:26:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:2e:0 p:3b:0 p:45:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:2e:a p:3b:a p:45:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:2e:0 p:3b:0 p:45:0 b:26:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:26:a p:2a:a p:3b:a p:45:a t14 p:26:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a b:26:a g:3e:a g:3e:a g:42:a g:42:a g:45:a g:45:a pi:3e:a pi:42:a pi:45:a t14 p:2a:0 p:3b:0 p:45:0 b:26:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:2d:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 b:2d:0 g:3e:0 g:3e:0 g:42:0 g:42:0 g:45:0 g:45:0 pi:3e:0 pi:42:0 pi:45:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:24:a p:2e:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:24:0 p:2e:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:26:a p:2a:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:26:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:26:a p:2e:a p:31:a p:39:a p:3b:a p:45:a b:21:a g:39:a g:39:a g:3d:a g:3d:a g:40:a g:40:a pi:39:a pi:3d:a pi:40:a t14 p:26:0 p:2e:0 p:31:0 p:39:0 p:3b:0 p:45:0 b:21:0 t2 p:26:a p:2e:a p:31:a p:39:a p:3b:a p:45:a b:21:a t14 p:26:0 p:2e:0 p:31:0 p:39:0 p:3b:0 p:45:0 b:21:0 g:39:0 g:39:0 g:3d:0 g:3d:0 g:40:0 g:40:0 pi:39:0 pi:3d:0 pi:40:0 t2 p:24:a p:2a:a p:31:a p:39:a p:3b:a p:45:a b:1f:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:24:0 p:2a:0 p:31:0 p:39:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0 p:45:0 b:1f:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:2e:a p:3b:a p:45:a b:1f:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:2e:0 p:3b:0 p:45:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:2e:a p:3b:a p:45:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:2e:0 p:3b:0 p:45:0 b:1f:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:26:a p:2a:a p:3b:a p:45:a t14 p:26:0 p:2a:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a b:1f:a g:3b:a g:3b:a g:3e:a g:3e:a g:43:a g:43:a pi:3b:a pi:3e:a pi:43:a t14 p:2a:0 p:3b:0 p:45:0 b:1f:0 t2 p:24:a p:2a:a p:3b:a p:45:a b:1f:a t14 p:24:0 p:2a:0 p:3b:0 p:45:0 b:1f:0 g:3b:0 g:3b:0 g:3e:0 g:3e:0 g:43:0 g:43:0 pi:3b:0 pi:3e:0 pi:43:0 t2 p:24:a p:2e:a p:3b:a p:45:a b:26:a g:39:a g:39:a g:3e:a g:3e:a g:42:a g:42:a pi:39:a pi:3e:a pi:42:a t14 p:24:0 p:2e:0 p:3b:0 p:45:0 t2 p:2a:a p:3b:a p:45:a t14 p:2a:0 p:3b:0",
|
||||
"wav_name": "sample",
|
||||
"sound_font_path": "assets/default_sound_font.sf2",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@router.post("/text-to-wav", tags=["MIDI"])
|
||||
@@ -111,6 +122,9 @@ def text_to_wav(body: TextToWavBody):
|
||||
Install fluidsynth first, see more: https://github.com/FluidSynth/fluidsynth/wiki/Download#distributions
|
||||
"""
|
||||
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
text = body.text.strip()
|
||||
if not text.startswith("<start>"):
|
||||
text = "<start> " + text
|
||||
|
||||
@@ -4,6 +4,7 @@ from fastapi import APIRouter, HTTPException, Request, Response, status
|
||||
from pydantic import BaseModel
|
||||
import gc
|
||||
import copy
|
||||
import global_var
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -36,6 +37,9 @@ def init():
|
||||
def disable_state_cache():
|
||||
global trie, dtrie
|
||||
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
trie = None
|
||||
dtrie = {}
|
||||
gc.collect()
|
||||
@@ -46,6 +50,10 @@ def disable_state_cache():
|
||||
@router.post("/enable-state-cache", tags=["State Cache"])
|
||||
def enable_state_cache():
|
||||
global trie, dtrie
|
||||
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
try:
|
||||
import cyac
|
||||
|
||||
@@ -65,9 +73,13 @@ class AddStateBody(BaseModel):
|
||||
logits: Any
|
||||
|
||||
|
||||
@router.post("/add-state", tags=["State Cache"])
|
||||
# @router.post("/add-state", tags=["State Cache"])
|
||||
def add_state(body: AddStateBody):
|
||||
global trie, dtrie, loop_del_trie_id
|
||||
|
||||
# if global_var.get(global_var.Deploy_Mode) is True:
|
||||
# raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if trie is None:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "trie not loaded")
|
||||
|
||||
@@ -108,6 +120,10 @@ def add_state(body: AddStateBody):
|
||||
@router.post("/reset-state", tags=["State Cache"])
|
||||
def reset_state():
|
||||
global trie, dtrie
|
||||
|
||||
if global_var.get(global_var.Deploy_Mode) is True:
|
||||
raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if trie is None:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "trie not loaded")
|
||||
|
||||
@@ -141,9 +157,13 @@ def __get_a_dtrie_buff_size(dtrie_v):
|
||||
return 54 * len(dtrie_v["tokens"]) + 491520 + 262144 + 28 # TODO
|
||||
|
||||
|
||||
@router.post("/longest-prefix-state", tags=["State Cache"])
|
||||
# @router.post("/longest-prefix-state", tags=["State Cache"])
|
||||
def longest_prefix_state(body: LongestPrefixStateBody, request: Request):
|
||||
global trie
|
||||
|
||||
# if global_var.get(global_var.Deploy_Mode) is True:
|
||||
# raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if trie is None:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "trie not loaded")
|
||||
|
||||
@@ -180,9 +200,13 @@ def longest_prefix_state(body: LongestPrefixStateBody, request: Request):
|
||||
}
|
||||
|
||||
|
||||
@router.post("/save-state", tags=["State Cache"])
|
||||
# @router.post("/save-state", tags=["State Cache"])
|
||||
def save_state():
|
||||
global trie
|
||||
|
||||
# if global_var.get(global_var.Deploy_Mode) is True:
|
||||
# raise HTTPException(status.HTTP_403_FORBIDDEN)
|
||||
|
||||
if trie is None:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "trie not loaded")
|
||||
|
||||
|
||||
87
backend-python/rwkv_pip/cuda/rwkv6.cu
vendored
Normal file
87
backend-python/rwkv_pip/cuda/rwkv6.cu
vendored
Normal file
@@ -0,0 +1,87 @@
|
||||
#include <stdio.h>
|
||||
#include <assert.h>
|
||||
#include "ATen/ATen.h"
|
||||
typedef at::BFloat16 bf16;
|
||||
typedef at::Half fp16;
|
||||
typedef float fp32;
|
||||
|
||||
template <typename F>
|
||||
__global__ void kernel_forward(const int B, const int T, const int C, const int H, float *__restrict__ _state,
|
||||
const F *__restrict__ const _r, const F *__restrict__ const _k, const F *__restrict__ const _v, const float *__restrict__ _w, const F *__restrict__ _u,
|
||||
F *__restrict__ const _y)
|
||||
{
|
||||
const int b = blockIdx.x / H;
|
||||
const int h = blockIdx.x % H;
|
||||
const int i = threadIdx.x;
|
||||
_u += h*_N_;
|
||||
_state += h*_N_*_N_ + i*_N_; // wrong if B > 1 !!!
|
||||
|
||||
__shared__ float r[_N_], k[_N_], u[_N_], w[_N_];
|
||||
|
||||
float state[_N_];
|
||||
#pragma unroll
|
||||
for (int j = 0; j < _N_; j++)
|
||||
state[j] = _state[j];
|
||||
|
||||
__syncthreads();
|
||||
u[i] = float(_u[i]);
|
||||
__syncthreads();
|
||||
|
||||
for (int t = b*T*C + h*_N_ + i; t < (b+1)*T*C + h*_N_ + i; t += C)
|
||||
{
|
||||
__syncthreads();
|
||||
w[i] = _w[t];
|
||||
r[i] = float(_r[t]);
|
||||
k[i] = float(_k[t]);
|
||||
__syncthreads();
|
||||
|
||||
const float v = float(_v[t]);
|
||||
float y = 0;
|
||||
|
||||
#pragma unroll
|
||||
for (int j = 0; j < _N_; j+=4)
|
||||
{
|
||||
const float4& r_ = (float4&)(r[j]);
|
||||
const float4& k_ = (float4&)(k[j]);
|
||||
const float4& w_ = (float4&)(w[j]);
|
||||
const float4& u_ = (float4&)(u[j]);
|
||||
float4& s = (float4&)(state[j]);
|
||||
float4 x;
|
||||
|
||||
x.x = k_.x * v;
|
||||
x.y = k_.y * v;
|
||||
x.z = k_.z * v;
|
||||
x.w = k_.w * v;
|
||||
|
||||
y += r_.x * (u_.x * x.x + s.x);
|
||||
y += r_.y * (u_.y * x.y + s.y);
|
||||
y += r_.z * (u_.z * x.z + s.z);
|
||||
y += r_.w * (u_.w * x.w + s.w);
|
||||
|
||||
s.x = s.x * w_.x + x.x;
|
||||
s.y = s.y * w_.y + x.y;
|
||||
s.z = s.z * w_.z + x.z;
|
||||
s.w = s.w * w_.w + x.w;
|
||||
}
|
||||
_y[t] = F(y);
|
||||
}
|
||||
#pragma unroll
|
||||
for (int j = 0; j < _N_; j++)
|
||||
_state[j] = state[j];
|
||||
}
|
||||
|
||||
void cuda_forward_bf16(int B, int T, int C, int H, float *state, bf16 *r, bf16 *k, bf16 *v, float *w, bf16 *u, bf16 *y)
|
||||
{
|
||||
assert(H*_N_ == C);
|
||||
kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
|
||||
}
|
||||
void cuda_forward_fp16(int B, int T, int C, int H, float *state, fp16 *r, fp16 *k, fp16 *v, float *w, fp16 *u, fp16 *y)
|
||||
{
|
||||
assert(H*_N_ == C);
|
||||
kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
|
||||
}
|
||||
void cuda_forward_fp32(int B, int T, int C, int H, float *state, fp32 *r, fp32 *k, fp32 *v, float *w, fp32 *u, fp32 *y)
|
||||
{
|
||||
assert(H*_N_ == C);
|
||||
kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
|
||||
}
|
||||
34
backend-python/rwkv_pip/cuda/rwkv6_op.cpp
vendored
Normal file
34
backend-python/rwkv_pip/cuda/rwkv6_op.cpp
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
#include <torch/extension.h>
|
||||
#include "ATen/ATen.h"
|
||||
#include <c10/cuda/CUDAGuard.h>
|
||||
typedef at::BFloat16 bf16;
|
||||
typedef at::Half fp16;
|
||||
typedef float fp32;
|
||||
|
||||
void cuda_forward_bf16(int B, int T, int C, int H, float *state, bf16 *r, bf16 *k, bf16 *v, float *w, bf16 *u, bf16 *y);
|
||||
void cuda_forward_fp16(int B, int T, int C, int H, float *state, fp16 *r, fp16 *k, fp16 *v, float *w, fp16 *u, fp16 *y);
|
||||
void cuda_forward_fp32(int B, int T, int C, int H, float *state, fp32 *r, fp32 *k, fp32 *v, float *w, fp32 *u, fp32 *y);
|
||||
|
||||
void forward_bf16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
|
||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
|
||||
cuda_forward_bf16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), w.data_ptr<float>(), u.data_ptr<bf16>(), y.data_ptr<bf16>());
|
||||
}
|
||||
void forward_fp16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
|
||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
|
||||
cuda_forward_fp16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp16>(), k.data_ptr<fp16>(), v.data_ptr<fp16>(), w.data_ptr<float>(), u.data_ptr<fp16>(), y.data_ptr<fp16>());
|
||||
}
|
||||
void forward_fp32(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
|
||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
|
||||
cuda_forward_fp32(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp32>(), k.data_ptr<fp32>(), v.data_ptr<fp32>(), w.data_ptr<float>(), u.data_ptr<fp32>(), y.data_ptr<fp32>());
|
||||
}
|
||||
|
||||
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
|
||||
m.def("forward_bf16", &forward_bf16, "rwkv6 forward_bf16");
|
||||
m.def("forward_fp16", &forward_fp16, "rwkv6 forward_fp16");
|
||||
m.def("forward_fp32", &forward_fp32, "rwkv6 forward_fp32");
|
||||
}
|
||||
TORCH_LIBRARY(rwkv6, m) {
|
||||
m.def("forward_bf16", forward_bf16);
|
||||
m.def("forward_fp16", forward_fp16);
|
||||
m.def("forward_fp32", forward_fp32);
|
||||
}
|
||||
890
backend-python/rwkv_pip/model.py
vendored
890
backend-python/rwkv_pip/model.py
vendored
File diff suppressed because it is too large
Load Diff
BIN
backend-python/rwkv_pip/rwkv5.pyd
vendored
BIN
backend-python/rwkv_pip/rwkv5.pyd
vendored
Binary file not shown.
BIN
backend-python/rwkv_pip/rwkv6.pyd
vendored
Normal file
BIN
backend-python/rwkv_pip/rwkv6.pyd
vendored
Normal file
Binary file not shown.
BIN
backend-python/rwkv_pip/wkv_cuda.pyd
vendored
BIN
backend-python/rwkv_pip/wkv_cuda.pyd
vendored
Binary file not shown.
@@ -551,8 +551,8 @@ class ModelConfigBody(BaseModel):
|
||||
presence_penalty: float = Field(default=None, ge=-2, le=2)
|
||||
frequency_penalty: float = Field(default=None, ge=-2, le=2)
|
||||
|
||||
class Config:
|
||||
json_schema_extra = {
|
||||
model_config = {
|
||||
"json_schema_extra": {
|
||||
"example": {
|
||||
"max_tokens": 1000,
|
||||
"temperature": 1.2,
|
||||
@@ -561,6 +561,7 @@ class ModelConfigBody(BaseModel):
|
||||
"frequency_penalty": 0.4,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
def set_rwkv_config(model: AbstractRWKV, body: ModelConfigBody):
|
||||
|
||||
14
backend-python/webui_server.py
Normal file
14
backend-python/webui_server.py
Normal file
@@ -0,0 +1,14 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.gzip import GZipMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
import uvicorn
|
||||
|
||||
webui_server = FastAPI()
|
||||
|
||||
webui_server.add_middleware(GZipMiddleware, minimum_size=1000)
|
||||
webui_server.mount(
|
||||
"/", StaticFiles(directory="frontend/dist", html=True), name="static"
|
||||
)
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("webui_server:webui_server")
|
||||
@@ -9,7 +9,7 @@ cd RWKV-Next-Web
|
||||
git clone https://github.com/josStorer/RWKV-Runner --depth=1
|
||||
python3 -m pip install torch torchvision torchaudio
|
||||
python3 -m pip install -r RWKV-Runner/backend-python/requirements.txt
|
||||
python3 ./RWKV-Runner/backend-python/main.py > log.txt &
|
||||
python3 ./RWKV-Runner/backend-python/main.py > log.txt & # this is only an example, you should use screen or other tools to run it in background
|
||||
|
||||
if [ ! -d RWKV-Runner/models ]; then
|
||||
mkdir RWKV-Runner/models
|
||||
@@ -22,6 +22,6 @@ yarn install
|
||||
yarn build
|
||||
export PROXY_URL=""
|
||||
export BASE_URL=http://127.0.0.1:8000
|
||||
yarn start &
|
||||
yarn start & # this is only an example, you should use screen or other tools to run it in background
|
||||
|
||||
curl http://127.0.0.1:8000/switch-model -X POST -H "Content-Type: application/json" -d '{"model":"./RWKV-Runner/models/RWKV-4-World-0.1B-v1-20230520-ctx4096.pth","strategy":"cpu fp32"}'
|
||||
|
||||
19
deploy-examples/RWKV-Runner-WebUI/setup.bat
Normal file
19
deploy-examples/RWKV-Runner-WebUI/setup.bat
Normal file
@@ -0,0 +1,19 @@
|
||||
: install git python3.10 npm by yourself
|
||||
: change model and strategy according to your hardware
|
||||
|
||||
git clone https://github.com/josStorer/RWKV-Runner --depth=1
|
||||
python -m pip install torch==1.13.1 torchvision==0.14.1 torchaudio==0.13.1 --index-url https://download.pytorch.org/whl/cu117
|
||||
python -m pip install -r RWKV-Runner/backend-python/requirements.txt
|
||||
cd RWKV-Runner/frontend
|
||||
call npm ci
|
||||
call npm run build
|
||||
cd ..
|
||||
|
||||
: optional: set ngrok_token=YOUR_NGROK_TOKEN
|
||||
start python ./backend-python/main.py --webui
|
||||
start "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" "http://127.0.0.1:8000"
|
||||
|
||||
powershell -Command "(Test-Path ./models) -or (mkdir models)"
|
||||
powershell -Command "Import-Module BitsTransfer"
|
||||
powershell -Command "(Test-Path ./models/RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth) -or (Start-BitsTransfer https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth ./models/RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth)"
|
||||
powershell -Command "Invoke-WebRequest http://127.0.0.1:8000/switch-model -Method POST -ContentType 'application/json' -Body '{\"model\":\"./models/RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth\",\"strategy\":\"cuda fp32 *20+\",\"deploy\":\"true\"}'"
|
||||
22
deploy-examples/RWKV-Runner-WebUI/setup.sh
Normal file
22
deploy-examples/RWKV-Runner-WebUI/setup.sh
Normal file
@@ -0,0 +1,22 @@
|
||||
# install git python3.10 npm by yourself
|
||||
# change model and strategy according to your hardware
|
||||
|
||||
sudo apt install python3-dev
|
||||
|
||||
git clone https://github.com/josStorer/RWKV-Runner --depth=1
|
||||
python3 -m pip install torch torchvision torchaudio
|
||||
python3 -m pip install -r RWKV-Runner/backend-python/requirements.txt
|
||||
cd RWKV-Runner/frontend
|
||||
npm ci
|
||||
npm run build
|
||||
cd ..
|
||||
|
||||
# optional: export ngrok_token=YOUR_NGROK_TOKEN
|
||||
python3 ./backend-python/main.py --webui > log.txt & # this is only an example, you should use screen or other tools to run it in background
|
||||
|
||||
if [ ! -d models ]; then
|
||||
mkdir models
|
||||
fi
|
||||
wget -N https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-0.1B-v1-20230520-ctx4096.pth -P models/
|
||||
|
||||
curl http://127.0.0.1:8000/switch-model -X POST -H "Content-Type: application/json" -d '{"model":"./models/RWKV-4-World-0.1B-v1-20230520-ctx4096.pth","strategy":"cpu fp32","deploy":"true"}'
|
||||
@@ -49,6 +49,10 @@ fi
|
||||
echo "loading $loadModel"
|
||||
modelInfo=$(python3 ./finetune/get_layer_and_embd.py $loadModel)
|
||||
echo $modelInfo
|
||||
|
||||
python3 ./finetune/lora/train.py $modelInfo $@ --proj_dir lora-models --data_type binidx --lora \
|
||||
--lora_parts=att,ffn,time,ln --strategy deepspeed_stage_2 --accelerator gpu
|
||||
if [[ $modelInfo =~ "--n_layer" ]]; then
|
||||
python3 ./finetune/lora/train.py $modelInfo $@ --proj_dir lora-models --data_type binidx --lora \
|
||||
--lora_parts=att,ffn,time,ln --strategy deepspeed_stage_2 --accelerator gpu
|
||||
else
|
||||
echo "modelInfo is invalid"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
@@ -246,5 +246,6 @@ if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
with open("error.txt", "w") as f:
|
||||
f.write(str(e))
|
||||
|
||||
1
finetune/lora/merge_lora.py
vendored
1
finetune/lora/merge_lora.py
vendored
@@ -64,5 +64,6 @@ try:
|
||||
|
||||
torch.save(output_w, output)
|
||||
except Exception as e:
|
||||
print(e)
|
||||
with open("error.txt", "w") as f:
|
||||
f.write(str(e))
|
||||
|
||||
2
finetune/lora/train.py
vendored
2
finetune/lora/train.py
vendored
@@ -264,7 +264,7 @@ if __name__ == "__main__":
|
||||
#
|
||||
# Data = {args.data_file} ({args.data_type}), ProjDir = {args.proj_dir}
|
||||
#
|
||||
# Epoch = {args.epoch_begin} to {args.epoch_begin + args.epoch_count - 1} (will continue afterwards), save every {args.epoch_save} epoch
|
||||
# Epoch = {args.epoch_begin} to {args.epoch_begin + args.epoch_count - 1}, save every {args.epoch_save} epoch
|
||||
#
|
||||
# Each "epoch" = {args.epoch_steps} steps, {samples_per_epoch} samples, {tokens_per_epoch} tokens
|
||||
#
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
torch==1.13.1
|
||||
pytorch_lightning==1.9.5
|
||||
deepspeed
|
||||
deepspeed==0.11.2
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8"/>
|
||||
<meta content="width=device-width, initial-scale=1.0" name="viewport"/>
|
||||
<title>RWKV-Runner</title>
|
||||
<meta charset="UTF-8" />
|
||||
<meta content="width=device-width, initial-scale=1.0" name="viewport" />
|
||||
<title>RWKV-Runner</title>
|
||||
<link href="./src/assets/images/logo.png" rel="icon" type="image/x-icon">
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
932
frontend/package-lock.json
generated
932
frontend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -16,11 +16,12 @@
|
||||
"@primer/octicons-react": "^19.1.0",
|
||||
"chart.js": "^4.3.0",
|
||||
"classnames": "^2.3.2",
|
||||
"github-markdown-css": "^5.2.0",
|
||||
"file-saver": "^2.0.5",
|
||||
"html-midi-player": "^1.5.0",
|
||||
"i18next": "^22.4.15",
|
||||
"mobx": "^6.9.0",
|
||||
"mobx-react-lite": "^3.4.3",
|
||||
"pdfjs-dist": "^4.0.189",
|
||||
"react": "^18.2.0",
|
||||
"react-beautiful-dnd": "^13.1.1",
|
||||
"react-chartjs-2": "^5.2.0",
|
||||
@@ -38,6 +39,7 @@
|
||||
"uuid": "^9.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/react": "^18.2.6",
|
||||
"@types/react-beautiful-dnd": "^13.1.4",
|
||||
"@types/react-dom": "^18.2.4",
|
||||
@@ -49,6 +51,7 @@
|
||||
"sass": "^1.62.1",
|
||||
"tailwindcss": "^3.3.2",
|
||||
"typescript": "^5.0.4",
|
||||
"vite": "^4.3.6"
|
||||
"vite": "^4.3.6",
|
||||
"vite-plugin-top-level-await": "^1.3.1"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,18 +26,22 @@
|
||||
import { FluentProvider, Tab, TabList, webDarkTheme, webLightTheme } from '@fluentui/react-components';
|
||||
import { FC, useEffect, useState } from 'react';
|
||||
import { Route, Routes, useLocation, useNavigate } from 'react-router';
|
||||
import { pages } from './pages';
|
||||
import { pages as clientPages } from './pages';
|
||||
import { useMediaQuery } from 'usehooks-ts';
|
||||
import commonStore from './stores/commonStore';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { CustomToastContainer } from './components/CustomToastContainer';
|
||||
import { LazyImportComponent } from './components/LazyImportComponent';
|
||||
|
||||
const App: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const location = useLocation();
|
||||
const mq = useMediaQuery('(min-width: 640px)');
|
||||
const pages = commonStore.platform === 'web' ? clientPages.filter(page =>
|
||||
!['/configs', '/models', '/downloads', '/train', '/about'].some(path => page.path === path)
|
||||
) : clientPages;
|
||||
|
||||
const [path, setPath] = useState<string>(pages[0].path);
|
||||
|
||||
@@ -47,10 +51,10 @@ const App: FC = observer(() => {
|
||||
useEffect(() => setPath(location.pathname), [location]);
|
||||
|
||||
return (
|
||||
<FluentProvider className="h-screen"
|
||||
<FluentProvider
|
||||
theme={commonStore.settings.darkMode ? webDarkTheme : webLightTheme}
|
||||
data-theme={commonStore.settings.darkMode ? 'dark' : 'light'}>
|
||||
<div className="flex h-full">
|
||||
<div className="flex h-screen">
|
||||
<div className="flex flex-col w-16 sm:w-48 p-2 justify-between">
|
||||
<TabList
|
||||
size="large"
|
||||
@@ -82,7 +86,7 @@ const App: FC = observer(() => {
|
||||
<div className="h-full w-full p-2 box-border overflow-y-hidden">
|
||||
<Routes>
|
||||
{pages.map(({ path, element }, index) => (
|
||||
<Route key={`${path}-${index}`} path={path} element={element} />
|
||||
<Route key={`${path}-${index}`} path={path} element={<LazyImportComponent lazyChildren={element} />} />
|
||||
))}
|
||||
</Routes>
|
||||
</div>
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
"Working": "動作中",
|
||||
"Stop": "停止",
|
||||
"Enable High Precision For Last Layer": "最後の層で高精度を有効にする",
|
||||
"Stored Layers": "メモリ層読み込み",
|
||||
"Stored Layers": "保存されるレイヤー",
|
||||
"Precision": "精度",
|
||||
"Device": "デバイス",
|
||||
"Convert model with these configs. Using a converted model will greatly improve the loading speed, but model parameters of the converted model cannot be modified.": "これらの設定でモデルを変換します。変換されたモデルを使用すると、読み込み速度が大幅に向上しますが、変換したモデルのパラメータを変更することはできません。",
|
||||
@@ -82,7 +82,7 @@
|
||||
"Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.": "モデルに鎮静剤を与えるようなもの。上位n%の確率質量の結果を考えてみてください。0.1は上位10%を考えており、質が高いが保守的で、1は全ての結果を考慮しており、質は低いが多様性があります。",
|
||||
"Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.": "ポジティヴ値は、新しいトークンが今までのテキストに出現していたかどうかに基づいてこれらをペナルティとし、新しいトピックについて話す可能性を増加させます。",
|
||||
"Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.": "ポジティブ値は、新しいトークンが既存のテキストでどれだけ頻繁に使われているかに基づいてペナルティを与え、モデルが同じ行を完全に繰り返す可能性を減らします。",
|
||||
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality, and fp32 has the best quality.": "int8はVRAMの使用量が少ないですが、質が若干低いです。fp16は高品質、fp32は最高品質です。",
|
||||
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality.": "int8はVRAMの使用量が少ないですが、質が若干低いです。fp16は高品質。",
|
||||
"Number of the neural network layers loaded into VRAM, the more you load, the faster the speed, but it consumes more VRAM. (If your VRAM is not enough, it will fail to load)": "VRAMにロードされるニューラルネットワークの層の数。ロードする量が多いほど速度は速くなりますが、VRAMを多く消費します。(VRAMが不足している場合、ロードに失敗します)",
|
||||
"Whether to use CPU to calculate the last output layer of the neural network with FP32 precision to obtain better quality.": "ネットワークの最終出力層をFP32精度で計算するためにCPUを使用するかどうか。",
|
||||
"Downloads": "ダウンロード",
|
||||
@@ -229,7 +229,7 @@
|
||||
"Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "メモリが不足しています、仮想メモリ (WSL Swap) を増やすか小さなベースモデルを使用してみてください。",
|
||||
"VRAM is not enough": "ビデオRAMが不足しています",
|
||||
"Training data is not enough, reduce context length or add more data for training": "トレーニングデータが不足しています、コンテキストの長さを減らすか、トレーニング用のデータをさらに追加してください",
|
||||
"You are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "トレーニングにWSL 1を使用しています、WSL 2にアップグレードしてください。例:\"wsl --set-version Ubuntu-22.04 2\"を実行する",
|
||||
"Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "Nvidia GPUが見つかりません。WindowsのGPUドライバが古すぎるか、トレーニングにWSL 1を使用している可能性があります。WSL 2にアップグレードしてください。例:\"wsl --set-version Ubuntu-22.04 2\"を実行してください",
|
||||
"Matched CUDA is not installed": "対応するCUDAがインストールされていません",
|
||||
"Failed to convert data": "データの変換に失敗しました",
|
||||
"Failed to merge model": "モデルのマージに失敗しました",
|
||||
@@ -262,5 +262,15 @@
|
||||
"is as follows. When replying to me, consider the file content and respond accordingly:": "の内容は以下の通りです。私に返信する際は、ファイルの内容を考慮して適切に返信してください:",
|
||||
"What's the file name": "ファイル名は何ですか",
|
||||
"The file name is: ": "ファイル名は次のとおりです: ",
|
||||
"Port is occupied. Change it in Configs page or close the program that occupies the port.": "ポートが占有されています。設定ページで変更するか、ポートを占有しているプログラムを終了してください。"
|
||||
"Port is occupied. Change it in Configs page or close the program that occupies the port.": "ポートが占有されています。設定ページで変更するか、ポートを占有しているプログラムを終了してください。",
|
||||
"Loading...": "読み込み中...",
|
||||
"Hello, what can I do for you?": "こんにちは、何かお手伝いできますか?",
|
||||
"Enable WebUI": "WebUIを有効化",
|
||||
"Server is working on deployment mode, please close the terminal window manually": "サーバーはデプロイモードで動作しています、ターミナルウィンドウを手動で閉じてください",
|
||||
"Server is working on deployment mode, please exit the program manually to stop the server": "サーバーはデプロイモードで動作しています、サーバーを停止するにはプログラムを手動で終了してください",
|
||||
"You can increase the number of stored layers in Configs page to improve performance": "パフォーマンスを向上させるために、保存されるレイヤーの数を設定ページで増やすことができます",
|
||||
"Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "モデルの読み込みに失敗しました、仮想メモリ (WSL Swap) を増やすか小さなベースモデルを使用してみてください。",
|
||||
"Save Conversation": "会話を保存",
|
||||
"Use Hugging Face Mirror": "Hugging Faceミラーを使用",
|
||||
"File is empty": "ファイルが空です"
|
||||
}
|
||||
@@ -82,7 +82,7 @@
|
||||
"Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.": "就像给模型喂镇静剂. 考虑前 n% 概率质量的结果, 0.1 考虑前 10%, 质量更高, 但更保守, 1 考虑所有质量结果, 质量降低, 但更多样",
|
||||
"Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.": "存在惩罚. 正值根据新token在至今的文本中是否出现过, 来对其进行惩罚, 从而增加了模型涉及新话题的可能性",
|
||||
"Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.": "频率惩罚. 正值根据新token在至今的文本中出现的频率/次数, 来对其进行惩罚, 从而减少模型原封不动地重复相同句子的可能性",
|
||||
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality, and fp32 has the best quality.": "int8占用显存更低, 但质量略微下降. fp16质量更好, fp32质量最好",
|
||||
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality.": "int8占用显存更低, 但质量略微下降. fp16质量更好",
|
||||
"Number of the neural network layers loaded into VRAM, the more you load, the faster the speed, but it consumes more VRAM. (If your VRAM is not enough, it will fail to load)": "载入显存的神经网络层数, 载入越多, 速度越快, 但显存消耗越大 (如果你的显存不够, 会载入失败)",
|
||||
"Whether to use CPU to calculate the last output layer of the neural network with FP32 precision to obtain better quality.": "是否使用cpu以fp32精度计算神经网络的最后一层输出层, 以获得更好的质量",
|
||||
"Downloads": "下载",
|
||||
@@ -229,7 +229,7 @@
|
||||
"Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "内存不足,尝试增加虚拟内存(WSL Swap),或使用一个更小规模的基底模型",
|
||||
"VRAM is not enough": "显存不足",
|
||||
"Training data is not enough, reduce context length or add more data for training": "训练数据不足,请减小上下文长度或增加训练数据",
|
||||
"You are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "你正在使用WSL 1进行训练,请升级到WSL 2。例如,运行\"wsl --set-version Ubuntu-22.04 2\"",
|
||||
"Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "没有找到Nvidia显卡。可能是因为你的windows显卡驱动太旧,或者你正在使用WSL 1进行训练,请升级到WSL 2。例如,执行\"wsl --set-version Ubuntu-22.04 2\"",
|
||||
"Matched CUDA is not installed": "未安装匹配的CUDA",
|
||||
"Failed to convert data": "数据转换失败",
|
||||
"Failed to merge model": "合并模型失败",
|
||||
@@ -262,5 +262,15 @@
|
||||
"is as follows. When replying to me, consider the file content and respond accordingly:": "内容如下。回复时考虑文件内容并做出相应回复:",
|
||||
"What's the file name": "文件名是什么",
|
||||
"The file name is: ": "文件名是:",
|
||||
"Port is occupied. Change it in Configs page or close the program that occupies the port.": "端口被占用。请在配置页面更改端口,或关闭占用端口的程序"
|
||||
"Port is occupied. Change it in Configs page or close the program that occupies the port.": "端口被占用。请在配置页面更改端口,或关闭占用端口的程序",
|
||||
"Loading...": "加载中...",
|
||||
"Hello, what can I do for you?": "你好,有什么要我帮忙的吗?",
|
||||
"Enable WebUI": "启用WebUI",
|
||||
"Server is working on deployment mode, please close the terminal window manually": "服务器正在部署模式下运行,请手动关闭终端窗口",
|
||||
"Server is working on deployment mode, please exit the program manually to stop the server": "服务器正在部署模式下运行,请手动退出程序以停止服务器",
|
||||
"You can increase the number of stored layers in Configs page to improve performance": "你可以在配置页面增加载入显存层数以提升性能",
|
||||
"Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "模型载入失败,尝试增加虚拟内存(WSL Swap),或使用一个更小规模的基底模型",
|
||||
"Save Conversation": "保存对话",
|
||||
"Use Hugging Face Mirror": "使用Hugging Face镜像源",
|
||||
"File is empty": "文件为空"
|
||||
}
|
||||
@@ -4,7 +4,7 @@ import { Dropdown, Option } from '@fluentui/react-components';
|
||||
import commonStore from '../stores/commonStore';
|
||||
|
||||
export const ConfigSelector: FC<{ size?: 'small' | 'medium' | 'large' }> = observer(({ size }) => {
|
||||
return <Dropdown size={size} style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
|
||||
return <Dropdown size={size} style={{ minWidth: 0 }} listbox={{ style: { minWidth: 'fit-content' } }}
|
||||
value={commonStore.getCurrentModelConfig().name}
|
||||
selectedOptions={[commonStore.currentModelConfigIndex.toString()]}
|
||||
onOptionSelect={(_, data) => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { FC, ReactElement } from 'react';
|
||||
import React, { FC, ReactElement } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
@@ -11,7 +11,9 @@ import {
|
||||
} from '@fluentui/react-components';
|
||||
import { ToolTipButton } from './ToolTipButton';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import MarkdownRender from './MarkdownRender';
|
||||
import { LazyImportComponent } from './LazyImportComponent';
|
||||
|
||||
const MarkdownRender = React.lazy(() => import('./MarkdownRender'));
|
||||
|
||||
export const DialogButton: FC<{
|
||||
text?: string | null
|
||||
@@ -45,7 +47,9 @@ export const DialogButton: FC<{
|
||||
<DialogContent>
|
||||
{
|
||||
markdown ?
|
||||
<MarkdownRender>{contentText}</MarkdownRender> :
|
||||
<LazyImportComponent lazyChildren={MarkdownRender}>
|
||||
{contentText}
|
||||
</LazyImportComponent> :
|
||||
contentText
|
||||
}
|
||||
</DialogContent>
|
||||
|
||||
24
frontend/src/components/LazyImportComponent.tsx
Normal file
24
frontend/src/components/LazyImportComponent.tsx
Normal file
@@ -0,0 +1,24 @@
|
||||
import { FC, LazyExoticComponent, ReactNode, Suspense } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Spinner } from '@fluentui/react-components';
|
||||
|
||||
interface LazyImportComponentProps {
|
||||
lazyChildren: LazyExoticComponent<FC<any>>;
|
||||
lazyProps?: any;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
export const LazyImportComponent: FC<LazyImportComponentProps> = (props) => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
<Suspense fallback={
|
||||
<div className="flex justify-center items-center h-full w-full">
|
||||
<Spinner size="huge" label={t('Loading...')} />
|
||||
</div>}>
|
||||
<props.lazyChildren {...props.lazyProps}>
|
||||
{props.children}
|
||||
</props.lazyChildren>
|
||||
</Suspense>
|
||||
);
|
||||
};
|
||||
@@ -21,7 +21,7 @@ const Hyperlink: FC<any> = ({ href, children }) => {
|
||||
);
|
||||
};
|
||||
|
||||
export const MarkdownRender: FC<ReactMarkdownOptions> = (props) => {
|
||||
const MarkdownRender: FC<ReactMarkdownOptions> = (props) => {
|
||||
return (
|
||||
<div dir="auto" className="markdown-body">
|
||||
<ReactMarkdown
|
||||
|
||||
@@ -40,6 +40,8 @@ export const ReadButton: FC<{
|
||||
voice = voices.find((v) => v.name.toLowerCase().includes('microsoft aria'));
|
||||
else if (lang === 'zh')
|
||||
voice = voices.find((v) => v.name.toLowerCase().includes('xiaoyi'));
|
||||
else if (lang === 'ja')
|
||||
voice = voices.find((v) => v.name.toLowerCase().includes('nanami'));
|
||||
if (!voice) voice = voices.find((v) => v.lang.substring(0, 2) === lang);
|
||||
if (!voice) voice = voices.find((v) => v.lang === navigator.language);
|
||||
|
||||
|
||||
@@ -11,12 +11,13 @@ import { Button } from '@fluentui/react-components';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { exit, getStatus, readRoot, switchModel, updateConfig } from '../apis';
|
||||
import { toast } from 'react-toastify';
|
||||
import { checkDependencies, getStrategy, toastWithButton } from '../utils';
|
||||
import { checkDependencies, getHfDownloadUrl, getStrategy, toastWithButton } from '../utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ToolTipButton } from './ToolTipButton';
|
||||
import { Play16Regular, Stop16Regular } from '@fluentui/react-icons';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { WindowShow } from '../../wailsjs/runtime/runtime';
|
||||
import { WindowShow } from '../../wailsjs/runtime';
|
||||
import { convertToSt } from '../utils/convert-to-st';
|
||||
|
||||
const mainButtonText = {
|
||||
[ModelStatus.Offline]: 'Run',
|
||||
@@ -57,13 +58,36 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
return;
|
||||
}
|
||||
|
||||
const currentModelSource = commonStore.modelSourceList.find(item => item.name === modelName);
|
||||
|
||||
const showDownloadPrompt = (promptInfo: string, downloadName: string) => {
|
||||
toastWithButton(promptInfo, t('Download'), () => {
|
||||
const downloadUrl = currentModelSource?.downloadUrl;
|
||||
if (downloadUrl) {
|
||||
toastWithButton(`${t('Downloading')} ${downloadName}`, t('Check'), () => {
|
||||
navigate({ pathname: '/downloads' });
|
||||
},
|
||||
{ autoClose: 3000 });
|
||||
AddToDownloadList(modelPath, getHfDownloadUrl(downloadUrl));
|
||||
} else {
|
||||
toast(t('Can not find download url'), { type: 'error' });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (webgpu) {
|
||||
if (!['.st', '.safetensors'].some(ext => modelPath.endsWith(ext))) {
|
||||
const stModelPath = modelPath.replace(/\.pth$/, '.st');
|
||||
if (await FileExists(stModelPath)) {
|
||||
modelPath = stModelPath;
|
||||
} else if (!await FileExists(modelPath)) {
|
||||
showDownloadPrompt(t('Model file not found'), modelName);
|
||||
commonStore.setStatus({ status: ModelStatus.Offline });
|
||||
return;
|
||||
} else {
|
||||
toast(t('Please convert model to safe tensors format first'), { type: 'error' });
|
||||
toastWithButton(t('Please convert model to safe tensors format first'), t('Convert'), () => {
|
||||
convertToSt(navigate, modelConfig);
|
||||
});
|
||||
commonStore.setStatus({ status: ModelStatus.Offline });
|
||||
return;
|
||||
}
|
||||
@@ -84,23 +108,6 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
return;
|
||||
}
|
||||
|
||||
const currentModelSource = commonStore.modelSourceList.find(item => item.name === modelName);
|
||||
|
||||
const showDownloadPrompt = (promptInfo: string, downloadName: string) => {
|
||||
toastWithButton(promptInfo, t('Download'), () => {
|
||||
const downloadUrl = currentModelSource?.downloadUrl;
|
||||
if (downloadUrl) {
|
||||
toastWithButton(`${t('Downloading')} ${downloadName}`, t('Check'), () => {
|
||||
navigate({ pathname: '/downloads' });
|
||||
},
|
||||
{ autoClose: 3000 });
|
||||
AddToDownloadList(modelPath, downloadUrl);
|
||||
} else {
|
||||
toast(t('Can not find download url'), { type: 'error' });
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (!await FileExists(modelPath)) {
|
||||
showDownloadPrompt(t('Model file not found'), modelName);
|
||||
commonStore.setStatus({ status: ModelStatus.Offline });
|
||||
@@ -129,7 +136,7 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
const isUsingCudaBeta = modelConfig.modelParameters.device === 'CUDA-Beta';
|
||||
|
||||
startServer(commonStore.settings.customPythonPath, port, commonStore.settings.host !== '127.0.0.1' ? '0.0.0.0' : '127.0.0.1',
|
||||
isUsingCudaBeta
|
||||
!!modelConfig.enableWebUI, isUsingCudaBeta
|
||||
).catch((e) => {
|
||||
const errMsg = e.message || e;
|
||||
if (errMsg.includes('path contains space'))
|
||||
@@ -199,7 +206,8 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
model: modelPath,
|
||||
strategy: strategy,
|
||||
tokenizer: modelConfig.modelParameters.useCustomTokenizer ? modelConfig.modelParameters.customTokenizer : undefined,
|
||||
customCuda: customCudaFile !== ''
|
||||
customCuda: customCudaFile !== '',
|
||||
deploy: modelConfig.enableWebUI
|
||||
}).then(async (r) => {
|
||||
if (r.ok) {
|
||||
commonStore.setStatus({ status: ModelStatus.Working });
|
||||
@@ -212,6 +220,12 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
const buttonFn = () => {
|
||||
navigate({ pathname: '/' + buttonName.toLowerCase() });
|
||||
};
|
||||
|
||||
if ((modelConfig.modelParameters.device === 'CUDA' || modelConfig.modelParameters.device === 'CUDA-Beta') &&
|
||||
modelConfig.modelParameters.storedLayers < modelConfig.modelParameters.maxStoredLayers &&
|
||||
commonStore.monitorData && commonStore.monitorData.totalVram !== 0 &&
|
||||
(commonStore.monitorData.usedVram / commonStore.monitorData.totalVram) < 0.85)
|
||||
toast(t('You can increase the number of stored layers in Configs page to improve performance'), { type: 'info' });
|
||||
toastWithButton(t('Startup Completed'), t(buttonName), buttonFn, { type: 'success', autoClose: 3000 });
|
||||
} else if (r.status === 304) {
|
||||
toast(t('Loading Model'), { type: 'info' });
|
||||
@@ -246,7 +260,13 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
}, 1000);
|
||||
} else {
|
||||
commonStore.setStatus({ status: ModelStatus.Offline });
|
||||
exit();
|
||||
exit().then(r => {
|
||||
if (r.status === 403)
|
||||
if (commonStore.platform !== 'linux')
|
||||
toast(t('Server is working on deployment mode, please close the terminal window manually'), { type: 'info' });
|
||||
else
|
||||
toast(t('Server is working on deployment mode, please exit the program manually to stop the server'), { type: 'info' });
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import { ConfigSelector } from './ConfigSelector';
|
||||
import { RunButton } from './RunButton';
|
||||
import { PresenceBadgeStatus } from '@fluentui/react-badge';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useMediaQuery } from 'usehooks-ts';
|
||||
|
||||
const statusText = {
|
||||
[ModelStatus.Offline]: 'Offline',
|
||||
@@ -23,15 +24,21 @@ const badgeStatus: { [modelStatus: number]: PresenceBadgeStatus } = {
|
||||
|
||||
export const WorkHeader: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const mq = useMediaQuery('(min-width: 640px)');
|
||||
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
|
||||
|
||||
return (
|
||||
return commonStore.platform === 'web' ?
|
||||
<div /> :
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<PresenceBadge status={badgeStatus[commonStore.status.status]} />
|
||||
<Text size={100}>{t('Model Status') + ': ' + t(statusText[commonStore.status.status])}</Text>
|
||||
</div>
|
||||
{commonStore.lastModelName && mq &&
|
||||
<Text size={100}>
|
||||
{commonStore.lastModelName}
|
||||
</Text>}
|
||||
<div className="flex items-center gap-2">
|
||||
<ConfigSelector size="small" />
|
||||
<RunButton iconMode />
|
||||
@@ -42,5 +49,5 @@ export const WorkHeader: FC = observer(() => {
|
||||
</Text>
|
||||
<Divider style={{ flexGrow: 0 }} />
|
||||
</div>
|
||||
);
|
||||
;
|
||||
});
|
||||
@@ -1,3 +1,4 @@
|
||||
import './webWails';
|
||||
import React from 'react';
|
||||
import { createRoot } from 'react-dom/client';
|
||||
import './style.scss';
|
||||
@@ -6,7 +7,6 @@ import App from './App';
|
||||
import { HashRouter } from 'react-router-dom';
|
||||
import { startup } from './startup';
|
||||
import './_locales/i18n-react';
|
||||
import 'html-midi-player';
|
||||
import { WindowShow } from '../wailsjs/runtime';
|
||||
|
||||
startup().then(() => {
|
||||
|
||||
@@ -5,9 +5,7 @@ import MarkdownRender from '../components/MarkdownRender';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import commonStore from '../stores/commonStore';
|
||||
|
||||
export type AboutContent = { [lang: string]: string }
|
||||
|
||||
export const About: FC = observer(() => {
|
||||
const About: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const lang: string = commonStore.settings.language;
|
||||
|
||||
@@ -21,3 +19,5 @@ export const About: FC = observer(() => {
|
||||
} />
|
||||
);
|
||||
});
|
||||
|
||||
export default About;
|
||||
|
||||
@@ -16,8 +16,11 @@ import {
|
||||
Attach16Regular,
|
||||
Delete28Regular,
|
||||
Dismiss16Regular,
|
||||
Dismiss24Regular,
|
||||
RecordStop28Regular,
|
||||
Save28Regular
|
||||
SaveRegular,
|
||||
TextAlignJustify24Regular,
|
||||
TextAlignJustifyRotate9024Regular
|
||||
} from '@fluentui/react-icons';
|
||||
import { CopyButton } from '../components/CopyButton';
|
||||
import { ReadButton } from '../components/ReadButton';
|
||||
@@ -25,49 +28,22 @@ import { toast } from 'react-toastify';
|
||||
import { WorkHeader } from '../components/WorkHeader';
|
||||
import { DialogButton } from '../components/DialogButton';
|
||||
import { OpenFileFolder, OpenOpenFileDialog, OpenSaveFileDialog } from '../../wailsjs/go/backend_golang/App';
|
||||
import { absPathAsset, bytesToReadable, toastWithButton } from '../utils';
|
||||
import { PresetsButton } from './PresetsManager/PresetsButton';
|
||||
import { absPathAsset, bytesToReadable, getServerRoot, toastWithButton } from '../utils';
|
||||
import { useMediaQuery } from 'usehooks-ts';
|
||||
import { botName, ConversationMessage, MessageType, userName, welcomeUuid } from '../types/chat';
|
||||
import { Labeled } from '../components/Labeled';
|
||||
import { ValuedSlider } from '../components/ValuedSlider';
|
||||
import { PresetsButton } from './PresetsManager/PresetsButton';
|
||||
import { webOpenOpenFileDialog } from '../utils/web-file-operations';
|
||||
|
||||
export const userName = 'M E';
|
||||
export const botName = 'A I';
|
||||
let chatSseControllers: {
|
||||
[id: string]: AbortController
|
||||
} = {};
|
||||
|
||||
export const welcomeUuid = 'welcome';
|
||||
|
||||
export enum MessageType {
|
||||
Normal,
|
||||
Error
|
||||
}
|
||||
|
||||
export type Side = 'left' | 'right'
|
||||
|
||||
export type Color = 'neutral' | 'brand' | 'colorful'
|
||||
|
||||
export type MessageItem = {
|
||||
sender: string,
|
||||
type: MessageType,
|
||||
color: Color,
|
||||
avatarImg?: string,
|
||||
time: string,
|
||||
content: string,
|
||||
side: Side,
|
||||
done: boolean
|
||||
}
|
||||
|
||||
export type Conversation = {
|
||||
[uuid: string]: MessageItem
|
||||
}
|
||||
|
||||
export type Role = 'assistant' | 'user' | 'system';
|
||||
|
||||
export type ConversationMessage = {
|
||||
role: Role;
|
||||
content: string;
|
||||
}
|
||||
|
||||
let chatSseControllers: { [id: string]: AbortController } = {};
|
||||
|
||||
const MoreUtilsButton: FC<{ uuid: string, setEditing: (editing: boolean) => void }> = observer(({
|
||||
const MoreUtilsButton: FC<{
|
||||
uuid: string,
|
||||
setEditing: (editing: boolean) => void
|
||||
}> = observer(({
|
||||
uuid,
|
||||
setEditing
|
||||
}) => {
|
||||
@@ -98,7 +74,8 @@ const MoreUtilsButton: FC<{ uuid: string, setEditing: (editing: boolean) => void
|
||||
});
|
||||
|
||||
const ChatMessageItem: FC<{
|
||||
uuid: string, onSubmit: (message: string | null, answerId: string | null,
|
||||
uuid: string,
|
||||
onSubmit: (message: string | null, answerId: string | null,
|
||||
startUuid: string | null, endUuid: string | null, includeEndUuid: boolean) => void
|
||||
}> = observer(({ uuid, onSubmit }) => {
|
||||
const { t } = useTranslation();
|
||||
@@ -217,11 +194,125 @@ const ChatMessageItem: FC<{
|
||||
</div>;
|
||||
});
|
||||
|
||||
const SidePanel: FC = observer(() => {
|
||||
const [t] = useTranslation();
|
||||
const mq = useMediaQuery('(min-width: 640px)');
|
||||
const params = commonStore.chatParams;
|
||||
|
||||
return <div
|
||||
className={classnames(
|
||||
'flex flex-col gap-1 h-full flex-shrink-0 transition-width duration-300 ease-in-out',
|
||||
commonStore.sidePanelCollapsed ? 'w-0' : (mq ? 'w-64' : 'w-full'),
|
||||
!commonStore.sidePanelCollapsed && 'ml-1')
|
||||
}>
|
||||
<div className="flex m-1">
|
||||
<div className="grow" />
|
||||
<PresetsButton tab="Chat" size="medium" shape="circular" appearance="subtle" />
|
||||
<Button size="medium" shape="circular" appearance="subtle" icon={<Dismiss24Regular />}
|
||||
onClick={() => commonStore.setSidePanelCollapsed(true)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-1 overflow-x-hidden overflow-y-auto p-1">
|
||||
<Labeled flex breakline label={t('Max Response Token')}
|
||||
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
|
||||
content={
|
||||
<ValuedSlider value={params.maxResponseToken} min={100} max={8100}
|
||||
step={100}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
commonStore.setChatParams({
|
||||
maxResponseToken: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Temperature')}
|
||||
desc={t('Sampling temperature, it\'s like giving alcohol to a model, the higher the stronger the randomness and creativity, while the lower, the more focused and deterministic it will be.')}
|
||||
content={
|
||||
<ValuedSlider value={params.temperature} min={0} max={2} step={0.1}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
commonStore.setChatParams({
|
||||
temperature: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Top_P')}
|
||||
desc={t('Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.')}
|
||||
content={
|
||||
<ValuedSlider value={params.topP} min={0} max={1} step={0.1} input
|
||||
onChange={(e, data) => {
|
||||
commonStore.setChatParams({
|
||||
topP: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Presence Penalty')}
|
||||
desc={t('Positive values penalize new tokens based on whether they appear in the text so far, increasing the model\'s likelihood to talk about new topics.')}
|
||||
content={
|
||||
<ValuedSlider value={params.presencePenalty} min={0} max={2}
|
||||
step={0.1} input
|
||||
onChange={(e, data) => {
|
||||
commonStore.setChatParams({
|
||||
presencePenalty: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Frequency Penalty')}
|
||||
desc={t('Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model\'s likelihood to repeat the same line verbatim.')}
|
||||
content={
|
||||
<ValuedSlider value={params.frequencyPenalty} min={0} max={2}
|
||||
step={0.1} input
|
||||
onChange={(e, data) => {
|
||||
commonStore.setChatParams({
|
||||
frequencyPenalty: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
</div>
|
||||
<div className="grow" />
|
||||
{/*<Button*/}
|
||||
{/* icon={<FolderOpenVerticalRegular />}*/}
|
||||
{/* onClick={() => {*/}
|
||||
{/* }}>*/}
|
||||
{/* {t('Load Conversation')}*/}
|
||||
{/*</Button>*/}
|
||||
<Button
|
||||
icon={<SaveRegular />}
|
||||
onClick={() => {
|
||||
let savedContent: string = '';
|
||||
const isWorldModel = commonStore.getCurrentModelConfig().modelParameters.modelName.toLowerCase().includes('world');
|
||||
const user = isWorldModel ? 'User' : 'Bob';
|
||||
const bot = isWorldModel ? 'Assistant' : 'Alice';
|
||||
commonStore.conversationOrder.forEach((uuid) => {
|
||||
if (uuid === welcomeUuid)
|
||||
return;
|
||||
const messageItem = commonStore.conversation[uuid];
|
||||
if (messageItem.type !== MessageType.Error) {
|
||||
savedContent += `${messageItem.sender === userName ? user : bot}: ${messageItem.content}\n\n`;
|
||||
}
|
||||
});
|
||||
|
||||
OpenSaveFileDialog('*.txt', 'conversation.txt', savedContent).then((path) => {
|
||||
if (path)
|
||||
toastWithButton(t('Conversation Saved'), t('Open'), () => {
|
||||
OpenFileFolder(path, false);
|
||||
});
|
||||
}).catch(e => {
|
||||
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
|
||||
});
|
||||
}}>
|
||||
{t('Save Conversation')}
|
||||
</Button>
|
||||
</div>;
|
||||
});
|
||||
|
||||
const ChatPanel: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const bodyRef = useRef<HTMLDivElement>(null);
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const mq = useMediaQuery('(min-width: 640px)');
|
||||
if (commonStore.sidePanelCollapsed === 'auto')
|
||||
commonStore.setSidePanelCollapsed(!mq);
|
||||
const currentConfig = commonStore.getCurrentModelConfig();
|
||||
const apiParams = currentConfig.apiParameters;
|
||||
const port = apiParams.apiPort;
|
||||
@@ -243,7 +334,7 @@ const ChatPanel: FC = observer(() => {
|
||||
color: 'colorful',
|
||||
avatarImg: logo,
|
||||
time: new Date().toISOString(),
|
||||
content: t('Hello! I\'m RWKV, an open-source and commercially usable large language model.'),
|
||||
content: commonStore.platform === 'web' ? t('Hello, what can I do for you?') : t('Hello! I\'m RWKV, an open-source and commercially usable large language model.'),
|
||||
side: 'left',
|
||||
done: true
|
||||
}
|
||||
@@ -260,7 +351,7 @@ const ChatPanel: FC = observer(() => {
|
||||
e.stopPropagation();
|
||||
if (e.type === 'click' || (e.keyCode === 13 && !e.shiftKey)) {
|
||||
e.preventDefault();
|
||||
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl) {
|
||||
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl && commonStore.platform !== 'web') {
|
||||
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
|
||||
return;
|
||||
}
|
||||
@@ -344,10 +435,8 @@ const ChatPanel: FC = observer(() => {
|
||||
let answer = '';
|
||||
const chatSseController = new AbortController();
|
||||
chatSseControllers[answerId] = chatSseController;
|
||||
fetchEventSource( // https://api.openai.com/v1/chat/completions || http://127.0.0.1:${port}/chat/completions
|
||||
commonStore.settings.apiUrl ?
|
||||
commonStore.settings.apiUrl + '/v1/chat/completions' :
|
||||
`http://127.0.0.1:${port}/chat/completions`,
|
||||
fetchEventSource( // https://api.openai.com/v1/chat/completions || http://127.0.0.1:${port}/v1/chat/completions
|
||||
getServerRoot(port) + '/v1/chat/completions',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -358,8 +447,10 @@ const ChatPanel: FC = observer(() => {
|
||||
messages,
|
||||
stream: true,
|
||||
model: commonStore.settings.apiChatModelName, // 'gpt-3.5-turbo'
|
||||
temperature: apiParams.temperature,
|
||||
top_p: apiParams.topP,
|
||||
temperature: commonStore.chatParams.temperature,
|
||||
top_p: commonStore.chatParams.topP,
|
||||
presence_penalty: commonStore.chatParams.presencePenalty,
|
||||
frequency_penalty: commonStore.chatParams.frequencyPenalty,
|
||||
user_name: commonStore.activePreset?.userName || undefined,
|
||||
assistant_name: commonStore.activePreset?.assistantName || undefined,
|
||||
presystem: commonStore.activePreset?.presystem && undefined
|
||||
@@ -383,6 +474,8 @@ const ChatPanel: FC = observer(() => {
|
||||
console.debug('json error', error);
|
||||
return;
|
||||
}
|
||||
if (data.model)
|
||||
commonStore.setLastModelName(data.model);
|
||||
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
|
||||
answer += data.choices[0]?.delta?.content || '';
|
||||
commonStore.conversation[answerId!].content = answer;
|
||||
@@ -420,173 +513,176 @@ const ChatPanel: FC = observer(() => {
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col w-full grow gap-4 pt-4 overflow-hidden">
|
||||
<div ref={bodyRef} className="grow overflow-y-scroll overflow-x-hidden pr-2">
|
||||
{commonStore.conversationOrder.map(uuid =>
|
||||
<ChatMessageItem key={uuid} uuid={uuid} onSubmit={onSubmit} />
|
||||
)}
|
||||
</div>
|
||||
<div className={classnames('flex items-end', mq ? 'gap-2' : '')}>
|
||||
<PresetsButton tab="Chat" size={mq ? 'large' : 'small'} shape="circular" appearance="subtle" />
|
||||
<DialogButton tooltip={t('Clear')}
|
||||
icon={<Delete28Regular />}
|
||||
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle" title={t('Clear')}
|
||||
contentText={t('Are you sure you want to clear the conversation? It cannot be undone.')}
|
||||
onConfirm={() => {
|
||||
if (generating) {
|
||||
for (const id in chatSseControllers) {
|
||||
chatSseControllers[id].abort();
|
||||
<div className="flex h-full grow pt-4 overflow-hidden">
|
||||
<div className="relative flex flex-col w-full grow gap-4 overflow-hidden">
|
||||
<Button className="absolute top-1 right-1" size="medium" shape="circular" appearance="subtle"
|
||||
style={{ zIndex: 1 }}
|
||||
icon={commonStore.sidePanelCollapsed ? <TextAlignJustify24Regular /> : <TextAlignJustifyRotate9024Regular />}
|
||||
onClick={() => commonStore.setSidePanelCollapsed(!commonStore.sidePanelCollapsed)} />
|
||||
<div ref={bodyRef} className="grow overflow-y-scroll overflow-x-hidden pr-2">
|
||||
{commonStore.conversationOrder.map(uuid =>
|
||||
<ChatMessageItem key={uuid} uuid={uuid} onSubmit={onSubmit} />
|
||||
)}
|
||||
</div>
|
||||
<div className={classnames('flex items-end', mq ? 'gap-2' : '')}>
|
||||
<DialogButton tooltip={t('Clear')}
|
||||
icon={<Delete28Regular />}
|
||||
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle" title={t('Clear')}
|
||||
contentText={t('Are you sure you want to clear the conversation? It cannot be undone.')}
|
||||
onConfirm={() => {
|
||||
if (generating) {
|
||||
for (const id in chatSseControllers) {
|
||||
chatSseControllers[id].abort();
|
||||
}
|
||||
chatSseControllers = {};
|
||||
}
|
||||
chatSseControllers = {};
|
||||
}
|
||||
commonStore.setConversation({});
|
||||
commonStore.setConversationOrder([]);
|
||||
}} />
|
||||
<div className="relative flex grow">
|
||||
<Textarea
|
||||
ref={inputRef}
|
||||
style={{ minWidth: 0 }}
|
||||
className="grow"
|
||||
resize="vertical"
|
||||
placeholder={t('Type your message here')!}
|
||||
value={commonStore.currentInput}
|
||||
onChange={(e) => commonStore.setCurrentInput(e.target.value)}
|
||||
onKeyDown={handleKeyDownOrClick}
|
||||
/>
|
||||
<div className="absolute right-2 bottom-2">
|
||||
{!commonStore.currentTempAttachment ?
|
||||
<ToolTipButton
|
||||
desc={commonStore.attachmentUploading ?
|
||||
t('Uploading Attachment') :
|
||||
t('Add An Attachment (Accepts pdf, txt)')}
|
||||
icon={commonStore.attachmentUploading ?
|
||||
<ArrowClockwise16Regular className="animate-spin" />
|
||||
: <Attach16Regular />}
|
||||
size="small" shape="circular" appearance="secondary"
|
||||
onClick={() => {
|
||||
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl) {
|
||||
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
|
||||
return;
|
||||
}
|
||||
|
||||
if (commonStore.attachmentUploading)
|
||||
return;
|
||||
|
||||
OpenOpenFileDialog('*.txt;*.pdf').then(async filePath => {
|
||||
if (!filePath)
|
||||
commonStore.setConversation({});
|
||||
commonStore.setConversationOrder([]);
|
||||
}} />
|
||||
<div className="relative flex grow">
|
||||
<Textarea
|
||||
ref={inputRef}
|
||||
style={{ minWidth: 0 }}
|
||||
className="grow"
|
||||
resize="vertical"
|
||||
placeholder={t('Type your message here')!}
|
||||
value={commonStore.currentInput}
|
||||
onChange={(e) => commonStore.setCurrentInput(e.target.value)}
|
||||
onKeyDown={handleKeyDownOrClick}
|
||||
/>
|
||||
<div className="absolute right-2 bottom-2">
|
||||
{!commonStore.currentTempAttachment ?
|
||||
<ToolTipButton
|
||||
desc={commonStore.attachmentUploading ?
|
||||
t('Uploading Attachment') :
|
||||
t('Add An Attachment (Accepts pdf, txt)')}
|
||||
icon={commonStore.attachmentUploading ?
|
||||
<ArrowClockwise16Regular className="animate-spin" />
|
||||
: <Attach16Regular />}
|
||||
size="small" shape="circular" appearance="secondary"
|
||||
onClick={() => {
|
||||
if (commonStore.attachmentUploading)
|
||||
return;
|
||||
|
||||
commonStore.setAttachmentUploading(true);
|
||||
|
||||
// Both are slow. Communication between frontend and backend is slow. Use AssetServer Handler to read the file.
|
||||
// const blob = new Blob([atob(info.content as unknown as string)]); // await fetch(`data:application/octet-stream;base64,${info.content}`).then(r => r.blob());
|
||||
const blob = await fetch(absPathAsset(filePath)).then(r => r.blob());
|
||||
const attachmentName = filePath.split(/[\\/]/).pop();
|
||||
const urlPath = `/file-to-text?file_name=${attachmentName}`;
|
||||
const bodyForm = new FormData();
|
||||
bodyForm.append('file_data', blob, attachmentName);
|
||||
fetch(commonStore.settings.apiUrl ?
|
||||
commonStore.settings.apiUrl + urlPath :
|
||||
`http://127.0.0.1:${port}${urlPath}`, {
|
||||
method: 'POST',
|
||||
body: bodyForm
|
||||
}).then(async r => {
|
||||
if (r.status === 200) {
|
||||
const pages = (await r.json()).pages as any[];
|
||||
let attachmentContent: string;
|
||||
if (pages.length === 1)
|
||||
attachmentContent = pages[0].page_content;
|
||||
else
|
||||
attachmentContent = pages.map((p, i) => `Page ${i + 1}:\n${p.page_content}`).join('\n\n');
|
||||
const filterPattern = '*.txt;*.pdf';
|
||||
const setUploading = () => commonStore.setAttachmentUploading(true);
|
||||
// actually, status of web platform is always Offline
|
||||
if (commonStore.platform === 'web' || commonStore.status.status === ModelStatus.Offline) {
|
||||
webOpenOpenFileDialog({ filterPattern, fnStartLoading: setUploading }).then(webReturn => {
|
||||
if (webReturn.content)
|
||||
commonStore.setCurrentTempAttachment(
|
||||
{
|
||||
name: attachmentName!,
|
||||
size: blob.size,
|
||||
content: attachmentContent
|
||||
name: webReturn.blob.name,
|
||||
size: webReturn.blob.size,
|
||||
content: webReturn.content
|
||||
});
|
||||
} else {
|
||||
toast(r.statusText + '\n' + (await r.text()), {
|
||||
type: 'error'
|
||||
else
|
||||
toast(t('File is empty'), {
|
||||
type: 'info',
|
||||
autoClose: 1000
|
||||
});
|
||||
}
|
||||
}).catch(e => {
|
||||
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
|
||||
}).finally(() => {
|
||||
commonStore.setAttachmentUploading(false);
|
||||
}
|
||||
).catch(e => {
|
||||
commonStore.setAttachmentUploading(false);
|
||||
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
|
||||
});
|
||||
}).catch(e => {
|
||||
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
|
||||
});
|
||||
}}
|
||||
/> :
|
||||
<div>
|
||||
<ToolTipButton
|
||||
text={
|
||||
commonStore.currentTempAttachment.name.replace(
|
||||
new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...')
|
||||
}
|
||||
desc={`${commonStore.currentTempAttachment.name} (${bytesToReadable(commonStore.currentTempAttachment.size)})`}
|
||||
size="small" shape="circular" appearance="secondary" />
|
||||
<ToolTipButton desc={t('Remove Attachment')}
|
||||
icon={<Dismiss16Regular />}
|
||||
size="small" shape="circular" appearance="subtle"
|
||||
onClick={() => {
|
||||
commonStore.setCurrentTempAttachment(null);
|
||||
}} />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<ToolTipButton desc={generating ? t('Stop') : t('Send')}
|
||||
icon={generating ? <RecordStop28Regular /> : <ArrowCircleUp28Regular />}
|
||||
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle"
|
||||
onClick={(e) => {
|
||||
if (generating) {
|
||||
for (const id in chatSseControllers) {
|
||||
chatSseControllers[id].abort();
|
||||
commonStore.conversation[id].type = MessageType.Error;
|
||||
commonStore.conversation[id].done = true;
|
||||
}
|
||||
chatSseControllers = {};
|
||||
commonStore.setConversation(commonStore.conversation);
|
||||
commonStore.setConversationOrder([...commonStore.conversationOrder]);
|
||||
} else {
|
||||
handleKeyDownOrClick(e);
|
||||
}
|
||||
}} />
|
||||
<ToolTipButton desc={t('Save')}
|
||||
icon={<Save28Regular />}
|
||||
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle"
|
||||
onClick={() => {
|
||||
let savedContent: string = '';
|
||||
const isWorldModel = commonStore.getCurrentModelConfig().modelParameters.modelName.toLowerCase().includes('world');
|
||||
const user = isWorldModel ? 'User' : 'Bob';
|
||||
const bot = isWorldModel ? 'Assistant' : 'Alice';
|
||||
commonStore.conversationOrder.forEach((uuid) => {
|
||||
if (uuid === welcomeUuid)
|
||||
return;
|
||||
const messageItem = commonStore.conversation[uuid];
|
||||
if (messageItem.type !== MessageType.Error) {
|
||||
savedContent += `${messageItem.sender === userName ? user : bot}: ${messageItem.content}\n\n`;
|
||||
}
|
||||
});
|
||||
});
|
||||
} else {
|
||||
OpenOpenFileDialog(filterPattern).then(async filePath => {
|
||||
if (!filePath)
|
||||
return;
|
||||
|
||||
OpenSaveFileDialog('*.txt', 'conversation.txt', savedContent).then((path) => {
|
||||
if (path)
|
||||
toastWithButton(t('Conversation Saved'), t('Open'), () => {
|
||||
OpenFileFolder(path, false);
|
||||
});
|
||||
}).catch(e => {
|
||||
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
|
||||
});
|
||||
}} />
|
||||
setUploading();
|
||||
|
||||
// Both are slow. Communication between frontend and backend is slow. Use AssetServer Handler to read the file.
|
||||
// const blob = new Blob([atob(info.content as unknown as string)]); // await fetch(`data:application/octet-stream;base64,${info.content}`).then(r => r.blob());
|
||||
const blob = await fetch(absPathAsset(filePath)).then(r => r.blob());
|
||||
const attachmentName = filePath.split(/[\\/]/).pop();
|
||||
const urlPath = `/file-to-text?file_name=${attachmentName}`;
|
||||
const bodyForm = new FormData();
|
||||
bodyForm.append('file_data', blob, attachmentName);
|
||||
fetch(getServerRoot(port) + urlPath, {
|
||||
method: 'POST',
|
||||
body: bodyForm
|
||||
}).then(async r => {
|
||||
if (r.status === 200) {
|
||||
const pages = (await r.json()).pages as any[];
|
||||
let attachmentContent: string;
|
||||
if (pages.length === 1)
|
||||
attachmentContent = pages[0].page_content;
|
||||
else
|
||||
attachmentContent = pages.map((p, i) => `Page ${i + 1}:\n${p.page_content}`).join('\n\n');
|
||||
if (attachmentContent)
|
||||
commonStore.setCurrentTempAttachment(
|
||||
{
|
||||
name: attachmentName!,
|
||||
size: blob.size,
|
||||
content: attachmentContent!
|
||||
});
|
||||
else
|
||||
toast(t('File is empty'), {
|
||||
type: 'info',
|
||||
autoClose: 1000
|
||||
});
|
||||
} else {
|
||||
toast(r.statusText + '\n' + (await r.text()), {
|
||||
type: 'error'
|
||||
});
|
||||
}
|
||||
}
|
||||
).catch(e => {
|
||||
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
|
||||
}).finally(() => {
|
||||
commonStore.setAttachmentUploading(false);
|
||||
});
|
||||
}).catch(e => {
|
||||
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
|
||||
});
|
||||
}
|
||||
}}
|
||||
/> :
|
||||
<div>
|
||||
<ToolTipButton
|
||||
text={
|
||||
commonStore.currentTempAttachment.name.replace(
|
||||
new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...')
|
||||
}
|
||||
desc={`${commonStore.currentTempAttachment.name} (${bytesToReadable(commonStore.currentTempAttachment.size)})`}
|
||||
size="small" shape="circular" appearance="secondary" />
|
||||
<ToolTipButton desc={t('Remove Attachment')}
|
||||
icon={<Dismiss16Regular />}
|
||||
size="small" shape="circular" appearance="subtle"
|
||||
onClick={() => {
|
||||
commonStore.setCurrentTempAttachment(null);
|
||||
}} />
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
<ToolTipButton desc={generating ? t('Stop') : t('Send')}
|
||||
icon={generating ? <RecordStop28Regular /> : <ArrowCircleUp28Regular />}
|
||||
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle"
|
||||
onClick={(e) => {
|
||||
if (generating) {
|
||||
for (const id in chatSseControllers) {
|
||||
chatSseControllers[id].abort();
|
||||
commonStore.conversation[id].type = MessageType.Error;
|
||||
commonStore.conversation[id].done = true;
|
||||
}
|
||||
chatSseControllers = {};
|
||||
commonStore.setConversation(commonStore.conversation);
|
||||
commonStore.setConversationOrder([...commonStore.conversationOrder]);
|
||||
} else {
|
||||
handleKeyDownOrClick(e);
|
||||
}
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
<SidePanel />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export const Chat: FC = observer(() => {
|
||||
const Chat: FC = observer(() => {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 p-2 h-full overflow-hidden">
|
||||
<WorkHeader />
|
||||
@@ -594,3 +690,5 @@ export const Chat: FC = observer(() => {
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default Chat;
|
||||
|
||||
@@ -5,7 +5,6 @@ import { Button, Dropdown, Input, Option, Textarea } from '@fluentui/react-compo
|
||||
import { Labeled } from '../components/Labeled';
|
||||
import { ValuedSlider } from '../components/ValuedSlider';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ApiParameters } from './Configs';
|
||||
import commonStore, { ModelStatus } from '../stores/commonStore';
|
||||
import { fetchEventSource } from '@microsoft/fetch-event-source';
|
||||
import { toast } from 'react-toastify';
|
||||
@@ -14,18 +13,8 @@ import { PresetsButton } from './PresetsManager/PresetsButton';
|
||||
import { ToolTipButton } from '../components/ToolTipButton';
|
||||
import { ArrowSync20Regular } from '@fluentui/react-icons';
|
||||
import { defaultPresets } from './defaultConfigs';
|
||||
|
||||
export type CompletionParams = Omit<ApiParameters, 'apiPort'> & {
|
||||
stop: string,
|
||||
injectStart: string,
|
||||
injectEnd: string
|
||||
};
|
||||
|
||||
export type CompletionPreset = {
|
||||
name: string,
|
||||
prompt: string,
|
||||
params: CompletionParams
|
||||
}
|
||||
import { CompletionParams, CompletionPreset } from '../types/completion';
|
||||
import { getServerRoot } from '../utils';
|
||||
|
||||
let completionSseController: AbortController | null = null;
|
||||
|
||||
@@ -40,8 +29,10 @@ const CompletionPanel: FC = observer(() => {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (inputRef.current)
|
||||
if (inputRef.current) {
|
||||
inputRef.current.style.height = '100%';
|
||||
inputRef.current.style.maxHeight = '100%';
|
||||
}
|
||||
scrollToBottom();
|
||||
}, []);
|
||||
|
||||
@@ -80,7 +71,7 @@ const CompletionPanel: FC = observer(() => {
|
||||
const onSubmit = (prompt: string) => {
|
||||
commonStore.setCompletionSubmittedPrompt(prompt);
|
||||
|
||||
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl) {
|
||||
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl && commonStore.platform !== 'web') {
|
||||
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
|
||||
commonStore.setCompletionGenerating(false);
|
||||
return;
|
||||
@@ -90,10 +81,8 @@ const CompletionPanel: FC = observer(() => {
|
||||
|
||||
let answer = '';
|
||||
completionSseController = new AbortController();
|
||||
fetchEventSource( // https://api.openai.com/v1/completions || http://127.0.0.1:${port}/completions
|
||||
commonStore.settings.apiUrl ?
|
||||
commonStore.settings.apiUrl + '/v1/completions' :
|
||||
`http://127.0.0.1:${port}/completions`,
|
||||
fetchEventSource( // https://api.openai.com/v1/completions || http://127.0.0.1:${port}/v1/completions
|
||||
getServerRoot(port) + '/v1/completions',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -125,6 +114,8 @@ const CompletionPanel: FC = observer(() => {
|
||||
console.debug('json error', error);
|
||||
return;
|
||||
}
|
||||
if (data.model)
|
||||
commonStore.setLastModelName(data.model);
|
||||
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
|
||||
answer += data.choices[0]?.text || data.choices[0]?.delta?.content || '';
|
||||
setPrompt(prompt + answer.replace(/\s+$/, '') + params.injectEnd.replaceAll('\\n', '\n'));
|
||||
@@ -186,7 +177,7 @@ const CompletionPanel: FC = observer(() => {
|
||||
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
|
||||
content={
|
||||
<ValuedSlider value={params.maxResponseToken} min={100} max={8100}
|
||||
step={400}
|
||||
step={100}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
@@ -269,7 +260,7 @@ const CompletionPanel: FC = observer(() => {
|
||||
} />
|
||||
</div>
|
||||
<div className="grow" />
|
||||
<div className="flex justify-between gap-2">
|
||||
<div className="hidden justify-between gap-2 sm:flex">
|
||||
<Button className="grow" onClick={() => {
|
||||
const newPrompt = prompt.replace(/\n+\ /g, '\n').split('\n').map((line) => line.trim()).join('\n');
|
||||
setPrompt(newPrompt);
|
||||
@@ -303,7 +294,7 @@ const CompletionPanel: FC = observer(() => {
|
||||
);
|
||||
});
|
||||
|
||||
export const Completion: FC = observer(() => {
|
||||
const Completion: FC = observer(() => {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 p-2 h-full overflow-hidden">
|
||||
<WorkHeader />
|
||||
@@ -311,3 +302,5 @@ export const Completion: FC = observer(() => {
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default Completion;
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import 'html-midi-player';
|
||||
import React, { FC, useEffect, useRef } from 'react';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { WorkHeader } from '../components/WorkHeader';
|
||||
@@ -16,23 +17,15 @@ import * as mm from '@magenta/music/esm/core.js';
|
||||
import { NoteSequence } from '@magenta/music/esm/protobuf.js';
|
||||
import { defaultCompositionPrompt } from './defaultConfigs';
|
||||
import { FileExists, OpenFileFolder, OpenSaveFileDialogBytes } from '../../wailsjs/go/backend_golang/App';
|
||||
import { toastWithButton } from '../utils';
|
||||
|
||||
export type CompositionParams = {
|
||||
prompt: string,
|
||||
maxResponseToken: number,
|
||||
temperature: number,
|
||||
topP: number,
|
||||
autoPlay: boolean,
|
||||
useLocalSoundFont: boolean,
|
||||
midi: ArrayBuffer | null,
|
||||
ns: NoteSequence | null
|
||||
}
|
||||
import { getServerRoot, toastWithButton } from '../utils';
|
||||
import { CompositionParams } from '../types/composition';
|
||||
import { useMediaQuery } from 'usehooks-ts';
|
||||
|
||||
let compositionSseController: AbortController | null = null;
|
||||
|
||||
const CompositionPanel: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const mq = useMediaQuery('(min-width: 640px)');
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
|
||||
const visualizerRef = useRef<VisualizerElement>(null);
|
||||
@@ -89,8 +82,10 @@ const CompositionPanel: FC = observer(() => {
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (inputRef.current)
|
||||
if (inputRef.current) {
|
||||
inputRef.current.style.height = '100%';
|
||||
inputRef.current.style.maxHeight = '100%';
|
||||
}
|
||||
scrollToBottom();
|
||||
|
||||
if (playerRef.current && visualizerRef.current) {
|
||||
@@ -109,9 +104,7 @@ const CompositionPanel: FC = observer(() => {
|
||||
}, []);
|
||||
|
||||
const generateNs = (autoPlay: boolean) => {
|
||||
fetch(commonStore.settings.apiUrl ?
|
||||
commonStore.settings.apiUrl + '/text-to-midi' :
|
||||
`http://127.0.0.1:${port}/text-to-midi`, {
|
||||
fetch(getServerRoot(port) + '/text-to-midi', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
@@ -137,7 +130,7 @@ const CompositionPanel: FC = observer(() => {
|
||||
const onSubmit = (prompt: string) => {
|
||||
commonStore.setCompositionSubmittedPrompt(prompt);
|
||||
|
||||
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl) {
|
||||
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl && commonStore.platform !== 'web') {
|
||||
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
|
||||
commonStore.setCompositionGenerating(false);
|
||||
return;
|
||||
@@ -145,10 +138,8 @@ const CompositionPanel: FC = observer(() => {
|
||||
|
||||
let answer = '';
|
||||
compositionSseController = new AbortController();
|
||||
fetchEventSource( // https://api.openai.com/v1/completions || http://127.0.0.1:${port}/completions
|
||||
commonStore.settings.apiUrl ?
|
||||
commonStore.settings.apiUrl + '/v1/completions' :
|
||||
`http://127.0.0.1:${port}/completions`,
|
||||
fetchEventSource( // https://api.openai.com/v1/completions || http://127.0.0.1:${port}/v1/completions
|
||||
getServerRoot(port) + '/v1/completions',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
@@ -178,6 +169,8 @@ const CompositionPanel: FC = observer(() => {
|
||||
console.debug('json error', error);
|
||||
return;
|
||||
}
|
||||
if (data.model)
|
||||
commonStore.setLastModelName(data.model);
|
||||
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
|
||||
answer += data.choices[0]?.text || data.choices[0]?.delta?.content || '';
|
||||
setPrompt(prompt + answer.replace(/\s+$/, ''));
|
||||
@@ -217,62 +210,64 @@ const CompositionPanel: FC = observer(() => {
|
||||
setPrompt(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<div className="flex flex-col gap-1 max-h-48 sm:max-w-sm sm:max-h-full overflow-x-hidden overflow-y-auto p-1">
|
||||
<Labeled flex breakline label={t('Max Response Token')}
|
||||
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
|
||||
content={
|
||||
<ValuedSlider value={params.maxResponseToken} min={100} max={4100}
|
||||
step={100}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
maxResponseToken: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Temperature')}
|
||||
desc={t('Sampling temperature, it\'s like giving alcohol to a model, the higher the stronger the randomness and creativity, while the lower, the more focused and deterministic it will be.')}
|
||||
content={
|
||||
<ValuedSlider value={params.temperature} min={0} max={2} step={0.1}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
temperature: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Top_P')}
|
||||
desc={t('Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.')}
|
||||
content={
|
||||
<ValuedSlider value={params.topP} min={0} max={1} step={0.1} input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
topP: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<div className="grow" />
|
||||
<Checkbox className="select-none"
|
||||
size="large" label={t('Use Local Sound Font')} checked={params.useLocalSoundFont}
|
||||
onChange={async (_, data) => {
|
||||
if (data.checked) {
|
||||
if (!await FileExists('assets/sound-font/accordion/instrument.json')) {
|
||||
toast(t('Failed to load local sound font, please check if the files exist - assets/sound-font'),
|
||||
{ type: 'warning' });
|
||||
return;
|
||||
<div className="flex flex-col gap-1 max-h-48 sm:max-w-sm sm:max-h-full">
|
||||
<div className="flex flex-col gap-1 grow overflow-x-hidden overflow-y-auto p-1">
|
||||
<Labeled flex breakline label={t('Max Response Token')}
|
||||
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
|
||||
content={
|
||||
<ValuedSlider value={params.maxResponseToken} min={100} max={4100}
|
||||
step={100}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
maxResponseToken: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Temperature')}
|
||||
desc={t('Sampling temperature, it\'s like giving alcohol to a model, the higher the stronger the randomness and creativity, while the lower, the more focused and deterministic it will be.')}
|
||||
content={
|
||||
<ValuedSlider value={params.temperature} min={0} max={2} step={0.1}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
temperature: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Top_P')}
|
||||
desc={t('Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.')}
|
||||
content={
|
||||
<ValuedSlider value={params.topP} min={0} max={1} step={0.1} input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
topP: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<div className="grow" />
|
||||
<Checkbox className="select-none"
|
||||
size="large" label={t('Use Local Sound Font')} checked={params.useLocalSoundFont}
|
||||
onChange={async (_, data) => {
|
||||
if (data.checked) {
|
||||
if (!await FileExists('assets/sound-font/accordion/instrument.json')) {
|
||||
toast(t('Failed to load local sound font, please check if the files exist - assets/sound-font'),
|
||||
{ type: 'warning' });
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
setParams({
|
||||
useLocalSoundFont: data.checked as boolean
|
||||
});
|
||||
setSoundFont();
|
||||
}} />
|
||||
<Checkbox className="select-none"
|
||||
size="large" label={t('Auto Play At The End')} checked={params.autoPlay} onChange={(_, data) => {
|
||||
setParams({
|
||||
useLocalSoundFont: data.checked as boolean
|
||||
autoPlay: data.checked as boolean
|
||||
});
|
||||
setSoundFont();
|
||||
}} />
|
||||
<Checkbox className="select-none"
|
||||
size="large" label={t('Auto Play At The End')} checked={params.autoPlay} onChange={(_, data) => {
|
||||
setParams({
|
||||
autoPlay: data.checked as boolean
|
||||
});
|
||||
}} />
|
||||
</div>
|
||||
<div className="flex justify-between gap-2">
|
||||
<ToolTipButton desc={t('Regenerate')} icon={<ArrowSync20Regular />} onClick={() => {
|
||||
compositionSseController?.abort();
|
||||
@@ -311,7 +306,7 @@ const CompositionPanel: FC = observer(() => {
|
||||
ref={playerRef}
|
||||
style={{ width: '100%' }}
|
||||
/>
|
||||
<Button icon={<Save28Regular />}
|
||||
<Button icon={<Save28Regular />} size={mq ? 'large' : 'medium'} appearance={mq ? 'secondary' : 'subtle'}
|
||||
onClick={() => {
|
||||
if (params.midi) {
|
||||
OpenSaveFileDialogBytes('*.mid', 'music.mid', Array.from(new Uint8Array(params.midi))).then((path) => {
|
||||
@@ -327,7 +322,7 @@ const CompositionPanel: FC = observer(() => {
|
||||
}
|
||||
}}
|
||||
>
|
||||
{t('Save')}
|
||||
{mq ? t('Save') : ''}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -335,7 +330,7 @@ const CompositionPanel: FC = observer(() => {
|
||||
);
|
||||
});
|
||||
|
||||
export const Composition: FC = observer(() => {
|
||||
const Composition: FC = observer(() => {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 p-2 h-full overflow-hidden">
|
||||
<WorkHeader />
|
||||
@@ -343,3 +338,5 @@ export const Composition: FC = observer(() => {
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default Composition;
|
||||
|
||||
@@ -26,48 +26,18 @@ import { Page } from '../components/Page';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { RunButton } from '../components/RunButton';
|
||||
import { updateConfig } from '../apis';
|
||||
import { ConvertModel, ConvertSafetensors, FileExists, GetPyError } from '../../wailsjs/go/backend_golang/App';
|
||||
import { ConvertModel, FileExists, GetPyError } from '../../wailsjs/go/backend_golang/App';
|
||||
import { checkDependencies, getStrategy } from '../utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { WindowShow } from '../../wailsjs/runtime/runtime';
|
||||
import { WindowShow } from '../../wailsjs/runtime';
|
||||
import strategyImg from '../assets/images/strategy.jpg';
|
||||
import strategyZhImg from '../assets/images/strategy_zh.jpg';
|
||||
import { ResetConfigsButton } from '../components/ResetConfigsButton';
|
||||
import { useMediaQuery } from 'usehooks-ts';
|
||||
import { ApiParameters, Device, ModelParameters, Precision } from '../types/configs';
|
||||
import { convertToSt } from '../utils/convert-to-st';
|
||||
|
||||
export type ApiParameters = {
|
||||
apiPort: number
|
||||
maxResponseToken: number;
|
||||
temperature: number;
|
||||
topP: number;
|
||||
presencePenalty: number;
|
||||
frequencyPenalty: number;
|
||||
}
|
||||
|
||||
export type Device = 'CPU' | 'CUDA' | 'CUDA-Beta' | 'WebGPU' | 'MPS' | 'Custom';
|
||||
export type Precision = 'fp16' | 'int8' | 'fp32';
|
||||
|
||||
export type ModelParameters = {
|
||||
// different models can not have the same name
|
||||
modelName: string;
|
||||
device: Device;
|
||||
precision: Precision;
|
||||
storedLayers: number;
|
||||
maxStoredLayers: number;
|
||||
useCustomCuda?: boolean;
|
||||
customStrategy?: string;
|
||||
useCustomTokenizer?: boolean;
|
||||
customTokenizer?: string;
|
||||
}
|
||||
|
||||
export type ModelConfig = {
|
||||
// different configs can have the same name
|
||||
name: string;
|
||||
apiParameters: ApiParameters
|
||||
modelParameters: ModelParameters
|
||||
}
|
||||
|
||||
export const Configs: FC = observer(() => {
|
||||
const Configs: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const [selectedIndex, setSelectedIndex] = React.useState(commonStore.currentModelConfigIndex);
|
||||
const [selectedConfig, setSelectedConfig] = React.useState(commonStore.modelConfigs[selectedIndex]);
|
||||
@@ -181,7 +151,7 @@ export const Configs: FC = observer(() => {
|
||||
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
|
||||
content={
|
||||
<ValuedSlider value={selectedConfig.apiParameters.maxResponseToken} min={100} max={8100}
|
||||
step={400}
|
||||
step={100}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
setSelectedConfigApiParams({
|
||||
@@ -303,41 +273,7 @@ export const Configs: FC = observer(() => {
|
||||
}} /> :
|
||||
<ToolTipButton text={t('Convert To Safe Tensors Format')}
|
||||
desc=""
|
||||
onClick={async () => {
|
||||
if (commonStore.platform === 'darwin') {
|
||||
toast(t('MacOS is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_safetensors.py)', { type: 'info' });
|
||||
return;
|
||||
} else if (commonStore.platform === 'linux') {
|
||||
toast(t('Linux is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_safetensors.py)', { type: 'info' });
|
||||
return;
|
||||
}
|
||||
|
||||
const ok = await checkDependencies(navigate);
|
||||
if (!ok)
|
||||
return;
|
||||
|
||||
const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}`;
|
||||
if (await FileExists(modelPath)) {
|
||||
toast(t('Start Converting'), { autoClose: 1000, type: 'info' });
|
||||
const newModelPath = modelPath.replace(/\.pth$/, '.st');
|
||||
ConvertSafetensors(commonStore.settings.customPythonPath, modelPath, newModelPath).then(async () => {
|
||||
if (!await FileExists(newModelPath)) {
|
||||
toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' });
|
||||
} else {
|
||||
toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' });
|
||||
}
|
||||
}).catch(e => {
|
||||
const errMsg = e.message || e;
|
||||
if (errMsg.includes('path contains space'))
|
||||
toast(`${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' });
|
||||
else
|
||||
toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' });
|
||||
});
|
||||
setTimeout(WindowShow, 1000);
|
||||
} else {
|
||||
toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' });
|
||||
}
|
||||
}} />
|
||||
onClick={() => convertToSt(navigate, selectedConfig)} />
|
||||
}
|
||||
<Labeled label={t('Strategy')} content={
|
||||
<Dropdown style={{ minWidth: 0 }} className="grow" value={t(selectedConfig.modelParameters.device)!}
|
||||
@@ -359,7 +295,7 @@ export const Configs: FC = observer(() => {
|
||||
} />
|
||||
{
|
||||
selectedConfig.modelParameters.device !== 'Custom' && <Labeled label={t('Precision')}
|
||||
desc={t('int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality, and fp32 has the best quality.')}
|
||||
desc={t('int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality.')}
|
||||
content={
|
||||
<Dropdown style={{ minWidth: 0 }} className="grow"
|
||||
value={selectedConfig.modelParameters.precision}
|
||||
@@ -371,8 +307,10 @@ export const Configs: FC = observer(() => {
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<Option>fp16</Option>
|
||||
{selectedConfig.modelParameters.device !== 'CPU' && selectedConfig.modelParameters.device !== 'MPS' &&
|
||||
<Option>fp16</Option>}
|
||||
<Option>int8</Option>
|
||||
{selectedConfig.modelParameters.device === 'WebGPU' && <Option>nf4</Option>}
|
||||
{selectedConfig.modelParameters.device !== 'WebGPU' && <Option>fp32</Option>}
|
||||
</Dropdown>
|
||||
} />
|
||||
@@ -472,9 +410,23 @@ export const Configs: FC = observer(() => {
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-row-reverse sm:fixed bottom-2 right-2">
|
||||
<RunButton onClickRun={onClickSave} />
|
||||
<div className="flex gap-2">
|
||||
{selectedConfig.modelParameters.device !== 'WebGPU'
|
||||
&& <Checkbox className="select-none"
|
||||
size="large" label={t('Enable WebUI')}
|
||||
checked={selectedConfig.enableWebUI}
|
||||
onChange={(_, data) => {
|
||||
setSelectedConfig({
|
||||
...selectedConfig,
|
||||
enableWebUI: data.checked as boolean
|
||||
});
|
||||
}} />}
|
||||
<RunButton onClickRun={onClickSave} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
} />
|
||||
);
|
||||
});
|
||||
|
||||
export default Configs;
|
||||
|
||||
@@ -9,19 +9,7 @@ import { ToolTipButton } from '../components/ToolTipButton';
|
||||
import { Folder20Regular, Pause20Regular, Play20Regular } from '@fluentui/react-icons';
|
||||
import { AddToDownloadList, OpenFileFolder, PauseDownload } from '../../wailsjs/go/backend_golang/App';
|
||||
|
||||
export type DownloadStatus = {
|
||||
name: string;
|
||||
path: string;
|
||||
url: string;
|
||||
transferred: number;
|
||||
size: number;
|
||||
speed: number;
|
||||
progress: number;
|
||||
downloading: boolean;
|
||||
done: boolean;
|
||||
}
|
||||
|
||||
export const Downloads: FC = observer(() => {
|
||||
const Downloads: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const finishedModelsLen = commonStore.downloadList.filter((status) => status.done && status.name.endsWith('.pth')).length;
|
||||
useEffect(() => {
|
||||
@@ -91,3 +79,5 @@ export const Downloads: FC = observer(() => {
|
||||
} />
|
||||
);
|
||||
});
|
||||
|
||||
export default Downloads;
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import { CompoundButton, Link, Text } from '@fluentui/react-components';
|
||||
import React, { FC, ReactElement } from 'react';
|
||||
import React, { FC } from 'react';
|
||||
import banner from '../assets/images/banner.jpg';
|
||||
import {
|
||||
Chat20Regular,
|
||||
ClipboardEdit20Regular,
|
||||
DataUsageSettings20Regular,
|
||||
DocumentSettings20Regular
|
||||
DocumentSettings20Regular,
|
||||
MusicNote220Regular,
|
||||
Settings20Regular
|
||||
} from '@fluentui/react-icons';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
@@ -14,21 +16,13 @@ import manifest from '../../../manifest.json';
|
||||
import { BrowserOpenURL } from '../../wailsjs/runtime';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ConfigSelector } from '../components/ConfigSelector';
|
||||
import MarkdownRender from '../components/MarkdownRender';
|
||||
import commonStore from '../stores/commonStore';
|
||||
import { Completion } from './Completion';
|
||||
import { ResetConfigsButton } from '../components/ResetConfigsButton';
|
||||
import { AdvancedGeneralSettings } from './Settings';
|
||||
import { NavCard } from '../types/home';
|
||||
import { LazyImportComponent } from '../components/LazyImportComponent';
|
||||
|
||||
export type IntroductionContent = { [lang: string]: string }
|
||||
|
||||
type NavCard = {
|
||||
label: string;
|
||||
desc: string;
|
||||
path: string;
|
||||
icon: ReactElement;
|
||||
};
|
||||
|
||||
const navCards: NavCard[] = [
|
||||
const clientNavCards: NavCard[] = [
|
||||
{
|
||||
label: 'Chat',
|
||||
desc: 'Go to chat page',
|
||||
@@ -55,7 +49,36 @@ const navCards: NavCard[] = [
|
||||
}
|
||||
];
|
||||
|
||||
export const Home: FC = observer(() => {
|
||||
const webNavCards: NavCard[] = [
|
||||
{
|
||||
label: 'Chat',
|
||||
desc: 'Go to chat page',
|
||||
path: '/chat',
|
||||
icon: <Chat20Regular />
|
||||
},
|
||||
{
|
||||
label: 'Completion',
|
||||
desc: 'Writer, Translator, Role-playing',
|
||||
path: '/completion',
|
||||
icon: <ClipboardEdit20Regular />
|
||||
},
|
||||
{
|
||||
label: 'Composition',
|
||||
desc: '',
|
||||
path: '/composition',
|
||||
icon: <MusicNote220Regular />
|
||||
},
|
||||
{
|
||||
label: 'Settings',
|
||||
desc: '',
|
||||
path: '/settings',
|
||||
icon: <Settings20Regular />
|
||||
}
|
||||
];
|
||||
|
||||
const MarkdownRender = React.lazy(() => import('../components/MarkdownRender'));
|
||||
|
||||
const Home: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const navigate = useNavigate();
|
||||
const lang: string = commonStore.settings.language;
|
||||
@@ -64,39 +87,64 @@ export const Home: FC = observer(() => {
|
||||
navigate({ pathname: path });
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col justify-between h-full">
|
||||
<img className="rounded-xl select-none hidden sm:block"
|
||||
style={{ maxHeight: '40%', margin: '0 auto' }} src={banner} />
|
||||
<div className="flex flex-col gap-2">
|
||||
<Text size={600} weight="medium">{t('Introduction')}</Text>
|
||||
<div className="h-40 overflow-y-auto overflow-x-hidden p-1">
|
||||
<MarkdownRender>
|
||||
{lang in commonStore.introduction ? commonStore.introduction[lang] : commonStore.introduction['en']}
|
||||
</MarkdownRender>
|
||||
return commonStore.platform === 'web' ?
|
||||
(
|
||||
<div className="flex flex-col gap-2 h-full overflow-x-hidden overflow-y-auto">
|
||||
<img className="rounded-xl select-none object-cover grow"
|
||||
style={{ maxHeight: '40%' }} src={banner} />
|
||||
<div className="grow"></div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-5">
|
||||
{webNavCards.map(({ label, path, icon, desc }, index) => (
|
||||
<CompoundButton icon={icon} secondaryContent={t(desc)} key={`${path}-${index}`} value={path}
|
||||
size="large" onClick={() => onClickNavCard(path)}>
|
||||
{t(label)}
|
||||
</CompoundButton>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-5">
|
||||
{navCards.map(({ label, path, icon, desc }, index) => (
|
||||
<CompoundButton icon={icon} secondaryContent={t(desc)} key={`${path}-${index}`} value={path}
|
||||
size="large" onClick={() => onClickNavCard(path)}>
|
||||
{t(label)}
|
||||
</CompoundButton>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-row-reverse sm:fixed bottom-2 right-2">
|
||||
<div className="flex gap-3">
|
||||
<ResetConfigsButton />
|
||||
<ConfigSelector />
|
||||
<RunButton />
|
||||
<div className="flex flex-col gap-2">
|
||||
<AdvancedGeneralSettings />
|
||||
<div className="flex gap-4 items-end">
|
||||
{t('Version')}: {manifest.version}
|
||||
<Link onClick={() => BrowserOpenURL('https://github.com/josStorer/RWKV-Runner')}>{t('Help')}</Link>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-4 items-end">
|
||||
{t('Version')}: {manifest.version}
|
||||
<Link onClick={() => BrowserOpenURL('https://github.com/josStorer/RWKV-Runner')}>{t('Help')}</Link>
|
||||
</div>
|
||||
)
|
||||
: (
|
||||
<div className="flex flex-col justify-between h-full">
|
||||
<img className="rounded-xl select-none object-cover hidden sm:block"
|
||||
style={{ maxHeight: '40%' }} src={banner} />
|
||||
<div className="flex flex-col gap-2">
|
||||
<Text size={600} weight="medium">{t('Introduction')}</Text>
|
||||
<div className="h-40 overflow-y-auto overflow-x-hidden p-1">
|
||||
<LazyImportComponent lazyChildren={MarkdownRender}>
|
||||
{lang in commonStore.introduction ? commonStore.introduction[lang] : commonStore.introduction['en']}
|
||||
</LazyImportComponent>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 sm:grid-cols-4 gap-5">
|
||||
{clientNavCards.map(({ label, path, icon, desc }, index) => (
|
||||
<CompoundButton icon={icon} secondaryContent={t(desc)} key={`${path}-${index}`} value={path}
|
||||
size="large" onClick={() => onClickNavCard(path)}>
|
||||
{t(label)}
|
||||
</CompoundButton>
|
||||
))}
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<div className="flex flex-row-reverse sm:fixed bottom-2 right-2">
|
||||
<div className="flex gap-3">
|
||||
<ResetConfigsButton />
|
||||
<ConfigSelector />
|
||||
<RunButton />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex gap-4 items-end">
|
||||
{t('Version')}: {manifest.version}
|
||||
<Link onClick={() => BrowserOpenURL('https://github.com/josStorer/RWKV-Runner')}>{t('Help')}</Link>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
);
|
||||
});
|
||||
|
||||
export default Home;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import React, { FC } from 'react';
|
||||
import {
|
||||
Checkbox,
|
||||
createTableColumn,
|
||||
DataGrid,
|
||||
DataGridBody,
|
||||
@@ -19,24 +20,10 @@ import commonStore from '../stores/commonStore';
|
||||
import { BrowserOpenURL } from '../../wailsjs/runtime';
|
||||
import { AddToDownloadList, OpenFileFolder } from '../../wailsjs/go/backend_golang/App';
|
||||
import { Page } from '../components/Page';
|
||||
import { bytesToGb, refreshModels, saveConfigs, toastWithButton } from '../utils';
|
||||
import { bytesToGb, getHfDownloadUrl, refreshModels, saveConfigs, toastWithButton } from '../utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useNavigate } from 'react-router';
|
||||
|
||||
export type ModelSourceItem = {
|
||||
name: string;
|
||||
size: number;
|
||||
lastUpdated: string;
|
||||
desc?: { [lang: string]: string | undefined; };
|
||||
SHA256?: string;
|
||||
url?: string;
|
||||
downloadUrl?: string;
|
||||
isComplete?: boolean;
|
||||
isLocal?: boolean;
|
||||
localSize?: number;
|
||||
lastUpdatedMs?: number;
|
||||
hide?: boolean;
|
||||
};
|
||||
import { ModelSourceItem } from '../types/models';
|
||||
|
||||
const columns: TableColumnDefinition<ModelSourceItem>[] = [
|
||||
createTableColumn<ModelSourceItem>({
|
||||
@@ -153,7 +140,7 @@ const columns: TableColumnDefinition<ModelSourceItem>[] = [
|
||||
navigate({ pathname: '/downloads' });
|
||||
},
|
||||
{ autoClose: 3000 });
|
||||
AddToDownloadList(`${commonStore.settings.customModelsPath}/${item.name}`, item.downloadUrl!);
|
||||
AddToDownloadList(`${commonStore.settings.customModelsPath}/${item.name}`, getHfDownloadUrl(item.downloadUrl!));
|
||||
}} />}
|
||||
{item.url && <ToolTipButton desc={t('Open Url')} icon={<Open20Regular />} onClick={() => {
|
||||
BrowserOpenURL(item.url!);
|
||||
@@ -165,7 +152,7 @@ const columns: TableColumnDefinition<ModelSourceItem>[] = [
|
||||
})
|
||||
];
|
||||
|
||||
export const Models: FC = observer(() => {
|
||||
const Models: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return (
|
||||
@@ -174,10 +161,21 @@ export const Models: FC = observer(() => {
|
||||
<div className="flex flex-col gap-1">
|
||||
<div className="flex justify-between items-center">
|
||||
<Text weight="medium">{t('Model Source Manifest List')}</Text>
|
||||
<ToolTipButton desc={t('Refresh')} icon={<ArrowClockwise20Regular />} onClick={() => {
|
||||
refreshModels(false);
|
||||
saveConfigs();
|
||||
}} />
|
||||
<div className="flex">
|
||||
{commonStore.settings.language === 'zh' &&
|
||||
<Checkbox className="select-none"
|
||||
size="large" label={t('Use Hugging Face Mirror')}
|
||||
checked={commonStore.settings.useHfMirror}
|
||||
onChange={(_, data) => {
|
||||
commonStore.setSettings({
|
||||
useHfMirror: data.checked as boolean
|
||||
});
|
||||
}} />}
|
||||
<ToolTipButton desc={t('Refresh')} icon={<ArrowClockwise20Regular />} onClick={() => {
|
||||
refreshModels(false);
|
||||
saveConfigs();
|
||||
}} />
|
||||
</div>
|
||||
</div>
|
||||
<Text size={100}>
|
||||
{t('Provide JSON file URLs for the models manifest. Separate URLs with semicolons. The "models" field in JSON files will be parsed into the following table.')}
|
||||
@@ -220,3 +218,5 @@ export const Models: FC = observer(() => {
|
||||
} />
|
||||
);
|
||||
});
|
||||
|
||||
export default Models;
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
import React, { FC, useState } from 'react';
|
||||
import { DragDropContext, Draggable, Droppable, DropResult } from 'react-beautiful-dnd';
|
||||
import commonStore from '../../stores/commonStore';
|
||||
import { Preset } from './PresetsButton';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import { Button, Card, Dropdown, Option, Textarea } from '@fluentui/react-components';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ToolTipButton } from '../../components/ToolTipButton';
|
||||
import { Delete20Regular, ReOrderDotsVertical20Regular } from '@fluentui/react-icons';
|
||||
import { ConversationMessage, Role } from '../Chat';
|
||||
import { Preset } from '../../types/presets';
|
||||
import { ConversationMessage, Role } from '../../types/chat';
|
||||
|
||||
type Item = {
|
||||
id: string;
|
||||
@@ -31,7 +31,7 @@ const reorder = (list: Item[], startIndex: number, endIndex: number) => {
|
||||
return result;
|
||||
};
|
||||
|
||||
export const MessagesEditor: FC = observer(() => {
|
||||
const MessagesEditor: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
const editingPreset = commonStore.editingPreset!;
|
||||
@@ -108,7 +108,8 @@ export const MessagesEditor: FC = observer(() => {
|
||||
style={{ borderTopRightRadius: 0, borderBottomRightRadius: 0 }}>
|
||||
<ReOrderDotsVertical20Regular />
|
||||
</Card>
|
||||
<Dropdown style={{ minWidth: 0, borderRadius: 0 }} listbox={{ style: { minWidth: 0 } }}
|
||||
<Dropdown style={{ minWidth: 0, borderRadius: 0 }}
|
||||
listbox={{ style: { minWidth: 'fit-content' } }}
|
||||
value={t(item.role)!}
|
||||
selectedOptions={[item.role]}
|
||||
onOptionSelect={(_, data) => {
|
||||
@@ -152,3 +153,5 @@ export const MessagesEditor: FC = observer(() => {
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export default MessagesEditor;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// TODO refactor
|
||||
|
||||
import React, { FC, PropsWithChildren, ReactElement, useState } from 'react';
|
||||
import React, { FC, lazy, PropsWithChildren, ReactElement, useState } from 'react';
|
||||
import {
|
||||
Button,
|
||||
Dialog,
|
||||
@@ -25,44 +25,21 @@ import {
|
||||
} from '@fluentui/react-icons';
|
||||
import { ToolTipButton } from '../../components/ToolTipButton';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { botName, Conversation, ConversationMessage, MessageType, userName } from '../Chat';
|
||||
import { SelectTabEventHandler } from '@fluentui/react-tabs';
|
||||
import { Labeled } from '../../components/Labeled';
|
||||
import commonStore from '../../stores/commonStore';
|
||||
import logo from '../../assets/images/logo.png';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { MessagesEditor } from './MessagesEditor';
|
||||
import { ClipboardGetText, ClipboardSetText } from '../../../wailsjs/runtime';
|
||||
import { toast } from 'react-toastify';
|
||||
import { CustomToastContainer } from '../../components/CustomToastContainer';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import { absPathAsset } from '../../utils';
|
||||
import { Preset, PresetsNavigationItem } from '../../types/presets';
|
||||
import { botName, Conversation, MessageType, userName } from '../../types/chat';
|
||||
import { LazyImportComponent } from '../../components/LazyImportComponent';
|
||||
|
||||
export type PresetType = 'chat' | 'completion' | 'chatInCompletion'
|
||||
|
||||
export type Preset = {
|
||||
name: string,
|
||||
tag: string,
|
||||
// if name and sourceUrl are same, it will be overridden when importing
|
||||
sourceUrl: string,
|
||||
desc: string,
|
||||
avatarImg: string,
|
||||
type: PresetType,
|
||||
// chat
|
||||
welcomeMessage: string,
|
||||
messages: ConversationMessage[],
|
||||
displayPresetMessages: boolean,
|
||||
// completion
|
||||
prompt: string,
|
||||
stop: string,
|
||||
injectStart: string,
|
||||
injectEnd: string,
|
||||
presystem?: boolean,
|
||||
userName?: string,
|
||||
assistantName?: string
|
||||
}
|
||||
|
||||
export const defaultPreset: Preset = {
|
||||
const defaultPreset: Preset = {
|
||||
name: 'RWKV',
|
||||
tag: 'default',
|
||||
sourceUrl: '',
|
||||
@@ -78,6 +55,8 @@ export const defaultPreset: Preset = {
|
||||
injectEnd: ''
|
||||
};
|
||||
|
||||
const MessagesEditor = lazy(() => import('./MessagesEditor'));
|
||||
|
||||
const setActivePreset = (preset: Preset) => {
|
||||
commonStore.setActivePreset(preset);
|
||||
//TODO if (preset.displayPresetMessages) {
|
||||
@@ -101,7 +80,7 @@ const setActivePreset = (preset: Preset) => {
|
||||
//}
|
||||
};
|
||||
|
||||
export const PresetCardFrame: FC<PropsWithChildren & { onClick?: () => void }> = (props) => {
|
||||
const PresetCardFrame: FC<PropsWithChildren & { onClick?: () => void }> = (props) => {
|
||||
return <Button
|
||||
className="flex flex-col gap-1 w-32 h-56 break-all"
|
||||
style={{ minWidth: 0, borderRadius: '0.75rem', justifyContent: 'unset' }}
|
||||
@@ -111,7 +90,7 @@ export const PresetCardFrame: FC<PropsWithChildren & { onClick?: () => void }> =
|
||||
</Button>;
|
||||
};
|
||||
|
||||
export const PresetCard: FC<{
|
||||
const PresetCard: FC<{
|
||||
avatarImg: string,
|
||||
name: string,
|
||||
desc: string,
|
||||
@@ -147,7 +126,7 @@ export const PresetCard: FC<{
|
||||
</PresetCardFrame>;
|
||||
});
|
||||
|
||||
export const ChatPresetEditor: FC<{
|
||||
const ChatPresetEditor: FC<{
|
||||
triggerButton: ReactElement,
|
||||
presetIndex: number
|
||||
}> = observer(({ triggerButton, presetIndex }) => {
|
||||
@@ -291,7 +270,7 @@ export const ChatPresetEditor: FC<{
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<MessagesEditor />
|
||||
<LazyImportComponent lazyChildren={MessagesEditor} />
|
||||
</div> :
|
||||
<div className="flex flex-col gap-1 p-2 overflow-x-hidden overflow-y-auto">
|
||||
<Labeled flex breakline label={`${t('Description')} (${t('Preview Only')})`}
|
||||
@@ -356,7 +335,7 @@ export const ChatPresetEditor: FC<{
|
||||
</Dialog>;
|
||||
});
|
||||
|
||||
export const ChatPresets: FC = observer(() => {
|
||||
const ChatPresets: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
return <div className="flex flex-wrap gap-2">
|
||||
@@ -392,11 +371,6 @@ export const ChatPresets: FC = observer(() => {
|
||||
</div>;
|
||||
});
|
||||
|
||||
type PresetsNavigationItem = {
|
||||
icon: ReactElement;
|
||||
element: ReactElement;
|
||||
};
|
||||
|
||||
const pages: { [label: string]: PresetsNavigationItem } = {
|
||||
Chat: {
|
||||
icon: <Chat20Regular />,
|
||||
@@ -412,7 +386,7 @@ const pages: { [label: string]: PresetsNavigationItem } = {
|
||||
}
|
||||
};
|
||||
|
||||
export const PresetsManager: FC<{ initTab: string }> = ({ initTab }) => {
|
||||
const PresetsManager: FC<{ initTab: string }> = ({ initTab }) => {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState(initTab);
|
||||
|
||||
|
||||
@@ -16,32 +16,180 @@ import { observer } from 'mobx-react-lite';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { checkUpdate, toastWithButton } from '../utils';
|
||||
import { RestartApp } from '../../wailsjs/go/backend_golang/App';
|
||||
import { Language, Languages } from '../types/settings';
|
||||
|
||||
export const Languages = {
|
||||
dev: 'English', // i18n default
|
||||
zh: '简体中文',
|
||||
ja: '日本語'
|
||||
};
|
||||
export const GeneralSettings: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
export type Language = keyof typeof Languages;
|
||||
return <div className="flex flex-col gap-2">
|
||||
<Labeled label={t('Language')} flex spaceBetween content={
|
||||
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 'fit-content' } }}
|
||||
value={Languages[commonStore.settings.language]}
|
||||
selectedOptions={[commonStore.settings.language]}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
const lang = data.optionValue as Language;
|
||||
commonStore.setSettings({
|
||||
language: lang
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
Object.entries(Languages).map(([langKey, desc]) =>
|
||||
<Option key={langKey} value={langKey}>{desc}</Option>)
|
||||
}
|
||||
</Dropdown>
|
||||
} />
|
||||
{
|
||||
commonStore.platform === 'windows' &&
|
||||
<Labeled label={t('DPI Scaling')} flex spaceBetween content={
|
||||
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 'fit-content' } }}
|
||||
value={commonStore.settings.dpiScaling + '%'}
|
||||
selectedOptions={[commonStore.settings.dpiScaling.toString()]}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
commonStore.setSettings({
|
||||
dpiScaling: Number(data.optionValue)
|
||||
});
|
||||
toastWithButton(t('Restart the app to apply DPI Scaling.'), t('Restart'), () => {
|
||||
RestartApp();
|
||||
}, {
|
||||
autoClose: 5000
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
Array.from({ length: 7 }, (_, i) => (i + 2) * 25).map((v, i) =>
|
||||
<Option key={i} value={v.toString()}>{v + '%'}</Option>)
|
||||
}
|
||||
</Dropdown>
|
||||
} />
|
||||
}
|
||||
<Labeled label={t('Dark Mode')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.darkMode}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
darkMode: data.checked
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
</div>;
|
||||
});
|
||||
|
||||
export type SettingsType = {
|
||||
language: Language
|
||||
darkMode: boolean
|
||||
autoUpdatesCheck: boolean
|
||||
giteeUpdatesSource: boolean
|
||||
cnMirror: boolean
|
||||
host: string
|
||||
dpiScaling: number
|
||||
customModelsPath: string
|
||||
customPythonPath: string
|
||||
apiUrl: string
|
||||
apiKey: string
|
||||
apiChatModelName: string
|
||||
apiCompletionModelName: string
|
||||
}
|
||||
export const AdvancedGeneralSettings: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
|
||||
export const Settings: FC = observer(() => {
|
||||
return <div className="flex flex-col gap-2">
|
||||
<Labeled label={'API URL'}
|
||||
content={
|
||||
<div className="flex gap-2">
|
||||
<Input style={{ minWidth: 0 }} className="grow" value={commonStore.settings.apiUrl}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiUrl: data.value
|
||||
});
|
||||
}} />
|
||||
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 'fit-content' } }}
|
||||
value="..." selectedOptions={[]} expandIcon={null}
|
||||
onOptionSelect={(_, data) => {
|
||||
commonStore.setSettings({
|
||||
apiUrl: data.optionValue
|
||||
});
|
||||
if (data.optionText === 'OpenAI') {
|
||||
if (commonStore.settings.apiChatModelName === 'rwkv')
|
||||
commonStore.setSettings({
|
||||
apiChatModelName: 'gpt-3.5-turbo'
|
||||
});
|
||||
if (commonStore.settings.apiCompletionModelName === 'rwkv')
|
||||
commonStore.setSettings({
|
||||
apiCompletionModelName: 'gpt-3.5-turbo-instruct'
|
||||
});
|
||||
} else if (data.optionText === 'RWKV') {
|
||||
if (commonStore.settings.apiChatModelName === 'gpt-3.5-turbo')
|
||||
commonStore.setSettings({
|
||||
apiChatModelName: 'rwkv'
|
||||
});
|
||||
if (commonStore.settings.apiCompletionModelName === 'gpt-3.5-turbo-instruct' || commonStore.settings.apiCompletionModelName === 'text-davinci-003')
|
||||
commonStore.setSettings({
|
||||
apiCompletionModelName: 'rwkv'
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<Option value="">{t('Localhost')!}</Option>
|
||||
<Option value="https://rwkv.ai-creator.net/chntuned">RWKV</Option>
|
||||
<Option value="https://api.openai.com">OpenAI</Option>
|
||||
</Dropdown>
|
||||
</div>
|
||||
} />
|
||||
<Labeled label={'API Key'}
|
||||
content={
|
||||
<Input type="password" className="grow" placeholder="sk-" value={commonStore.settings.apiKey}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiKey: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('API Chat Model Name')}
|
||||
content={
|
||||
<div className="flex gap-2">
|
||||
<Input style={{ minWidth: 0 }} className="grow" placeholder="rwkv"
|
||||
value={commonStore.settings.apiChatModelName}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiChatModelName: data.value
|
||||
});
|
||||
}} />
|
||||
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 'fit-content' } }}
|
||||
value="..." selectedOptions={[]} expandIcon={null}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
commonStore.setSettings({
|
||||
apiChatModelName: data.optionValue
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
['rwkv', 'gpt-4-1106-preview', 'gpt-4', 'gpt-4-32k', 'gpt-4-0613', 'gpt-4-32k-0613', 'gpt-3.5-turbo-1106', 'gpt-3.5-turbo', 'gpt-3.5-turbo-16k']
|
||||
.map((v, i) =>
|
||||
<Option key={i} value={v}>{v}</Option>
|
||||
)
|
||||
}
|
||||
</Dropdown>
|
||||
</div>
|
||||
} />
|
||||
<Labeled label={t('API Completion Model Name')}
|
||||
content={
|
||||
<div className="flex gap-2">
|
||||
<Input style={{ minWidth: 0 }} className="grow" placeholder="rwkv"
|
||||
value={commonStore.settings.apiCompletionModelName}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiCompletionModelName: data.value
|
||||
});
|
||||
}} />
|
||||
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 'fit-content', minHeight: 0 } }}
|
||||
value="..." selectedOptions={[]} expandIcon={null}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
commonStore.setSettings({
|
||||
apiCompletionModelName: data.optionValue
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
['rwkv', 'gpt-3.5-turbo-instruct', 'text-davinci-003', 'text-davinci-002', 'code-davinci-002', 'text-curie-001', 'text-babbage-001', 'text-ada-001']
|
||||
.map((v, i) =>
|
||||
<Option key={i} value={v}>{v}</Option>
|
||||
)
|
||||
}
|
||||
</Dropdown>
|
||||
</div>
|
||||
} />
|
||||
</div>;
|
||||
});
|
||||
|
||||
const Settings: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const advancedHeaderRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
@@ -53,227 +201,101 @@ export const Settings: FC = observer(() => {
|
||||
return (
|
||||
<Page title={t('Settings')} content={
|
||||
<div className="flex flex-col gap-2 overflow-y-auto overflow-x-hidden p-1">
|
||||
<Labeled label={t('Language')} flex spaceBetween content={
|
||||
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
|
||||
value={Languages[commonStore.settings.language]}
|
||||
selectedOptions={[commonStore.settings.language]}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
const lang = data.optionValue as Language;
|
||||
commonStore.setSettings({
|
||||
language: lang
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
Object.entries(Languages).map(([langKey, desc]) =>
|
||||
<Option key={langKey} value={langKey}>{desc}</Option>)
|
||||
}
|
||||
</Dropdown>
|
||||
} />
|
||||
{
|
||||
commonStore.platform === 'windows' &&
|
||||
<Labeled label={t('DPI Scaling')} flex spaceBetween content={
|
||||
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
|
||||
value={commonStore.settings.dpiScaling + '%'}
|
||||
selectedOptions={[commonStore.settings.dpiScaling.toString()]}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
commonStore.setSettings({
|
||||
dpiScaling: Number(data.optionValue)
|
||||
});
|
||||
toastWithButton(t('Restart the app to apply DPI Scaling.'), t('Restart'), () => {
|
||||
RestartApp();
|
||||
}, {
|
||||
autoClose: 5000
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
Array.from({ length: 7 }, (_, i) => (i + 2) * 25).map((v, i) =>
|
||||
<Option key={i} value={v.toString()}>{v + '%'}</Option>)
|
||||
}
|
||||
</Dropdown>
|
||||
} />
|
||||
}
|
||||
<Labeled label={t('Dark Mode')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.darkMode}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
darkMode: data.checked
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('Automatic Updates Check')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.autoUpdatesCheck}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
autoUpdatesCheck: data.checked
|
||||
});
|
||||
if (data.checked)
|
||||
checkUpdate(true);
|
||||
}} />
|
||||
} />
|
||||
{
|
||||
commonStore.settings.language === 'zh' &&
|
||||
<Labeled label={t('Use Gitee Updates Source')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.giteeUpdatesSource}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
giteeUpdatesSource: data.checked
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
}
|
||||
{
|
||||
commonStore.settings.language === 'zh' && commonStore.platform !== 'linux' &&
|
||||
<Labeled label={t('Use Tsinghua Pip Mirrors')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.cnMirror}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
cnMirror: data.checked
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
}
|
||||
<Labeled label={t('Allow external access to the API (service must be restarted)')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.host !== '127.0.0.1'}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
host: data.checked ? '0.0.0.0' : '127.0.0.1'
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Accordion collapsible openItems={!commonStore.advancedCollapsed && 'advanced'} onToggle={(e, data) => {
|
||||
if (data.value === 'advanced')
|
||||
commonStore.setAdvancedCollapsed(!commonStore.advancedCollapsed);
|
||||
}}>
|
||||
<AccordionItem value="advanced">
|
||||
<AccordionHeader ref={advancedHeaderRef} size="large">{t('Advanced')}</AccordionHeader>
|
||||
<AccordionPanel>
|
||||
<div className="flex flex-col gap-2 overflow-hidden">
|
||||
{commonStore.platform !== 'darwin' &&
|
||||
<Labeled label={t('Custom Models Path')}
|
||||
content={
|
||||
<Input className="grow" placeholder="./models" value={commonStore.settings.customModelsPath}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
customModelsPath: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
}
|
||||
<Labeled label={t('Custom Python Path')} // if set, will not use precompiled cuda kernel
|
||||
content={
|
||||
<Input className="grow" placeholder="./py310/python" value={commonStore.settings.customPythonPath}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setDepComplete(false);
|
||||
commonStore.setSettings({
|
||||
customPythonPath: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={'API URL'}
|
||||
content={
|
||||
<div className="flex gap-2">
|
||||
<Input style={{ minWidth: 0 }} className="grow" value={commonStore.settings.apiUrl}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiUrl: data.value
|
||||
});
|
||||
}} />
|
||||
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
|
||||
value="..." selectedOptions={[]} expandIcon={null}
|
||||
onOptionSelect={(_, data) => {
|
||||
commonStore.setSettings({
|
||||
apiUrl: data.optionValue
|
||||
});
|
||||
if (data.optionText === 'OpenAI') {
|
||||
if (commonStore.settings.apiChatModelName === 'rwkv')
|
||||
commonStore.setSettings({
|
||||
apiChatModelName: 'gpt-3.5-turbo'
|
||||
});
|
||||
if (commonStore.settings.apiCompletionModelName === 'rwkv')
|
||||
commonStore.setSettings({
|
||||
apiCompletionModelName: 'text-davinci-003'
|
||||
});
|
||||
}
|
||||
}}>
|
||||
<Option value="">{t('Localhost')!}</Option>
|
||||
<Option value="https://api.openai.com">OpenAI</Option>
|
||||
</Dropdown>
|
||||
</div>
|
||||
} />
|
||||
<Labeled label={'API Key'}
|
||||
content={
|
||||
<Input className="grow" placeholder="sk-" value={commonStore.settings.apiKey}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiKey: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('API Chat Model Name')}
|
||||
content={
|
||||
<div className="flex gap-2">
|
||||
<Input style={{ minWidth: 0 }} className="grow" placeholder="rwkv"
|
||||
value={commonStore.settings.apiChatModelName}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiChatModelName: data.value
|
||||
});
|
||||
}} />
|
||||
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
|
||||
value="..." selectedOptions={[]} expandIcon={null}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
commonStore.setSettings({
|
||||
apiChatModelName: data.optionValue
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
['rwkv', 'gpt-4', 'gpt-4-0613', 'gpt-4-32k', 'gpt-4-32k-0613', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613']
|
||||
.map((v, i) =>
|
||||
<Option key={i} value={v}>{v}</Option>
|
||||
)
|
||||
}
|
||||
</Dropdown>
|
||||
</div>
|
||||
} />
|
||||
<Labeled label={t('API Completion Model Name')}
|
||||
content={
|
||||
<div className="flex gap-2">
|
||||
<Input style={{ minWidth: 0 }} className="grow" placeholder="rwkv"
|
||||
value={commonStore.settings.apiCompletionModelName}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
apiCompletionModelName: data.value
|
||||
});
|
||||
}} />
|
||||
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
|
||||
value="..." selectedOptions={[]} expandIcon={null}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
commonStore.setSettings({
|
||||
apiCompletionModelName: data.optionValue
|
||||
});
|
||||
}
|
||||
}}>
|
||||
{
|
||||
['rwkv', 'text-davinci-003', 'text-davinci-002', 'text-curie-001', 'text-babbage-001', 'text-ada-001']
|
||||
.map((v, i) =>
|
||||
<Option key={i} value={v}>{v}</Option>
|
||||
)
|
||||
}
|
||||
</Dropdown>
|
||||
</div>
|
||||
} />
|
||||
commonStore.platform === 'web' ?
|
||||
(
|
||||
<div className="flex flex-col gap-2">
|
||||
<GeneralSettings />
|
||||
<AdvancedGeneralSettings />
|
||||
</div>
|
||||
</AccordionPanel>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
)
|
||||
:
|
||||
(
|
||||
<div className="flex flex-col gap-2">
|
||||
<GeneralSettings />
|
||||
<Labeled label={t('Automatic Updates Check')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.autoUpdatesCheck}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
autoUpdatesCheck: data.checked
|
||||
});
|
||||
if (data.checked)
|
||||
checkUpdate(true);
|
||||
}} />
|
||||
} />
|
||||
{
|
||||
commonStore.settings.language === 'zh' &&
|
||||
<Labeled label={t('Use Gitee Updates Source')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.giteeUpdatesSource}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
giteeUpdatesSource: data.checked
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
}
|
||||
{
|
||||
commonStore.settings.language === 'zh' && commonStore.platform !== 'linux' &&
|
||||
<Labeled label={t('Use Tsinghua Pip Mirrors')} flex spaceBetween content={
|
||||
<Switch checked={commonStore.settings.cnMirror}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
cnMirror: data.checked
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
}
|
||||
<Labeled label={t('Allow external access to the API (service must be restarted)')} flex spaceBetween
|
||||
content={
|
||||
<Switch checked={commonStore.settings.host !== '127.0.0.1'}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
host: data.checked ? '0.0.0.0' : '127.0.0.1'
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Accordion collapsible openItems={!commonStore.advancedCollapsed && 'advanced'} onToggle={(e, data) => {
|
||||
if (data.value === 'advanced')
|
||||
commonStore.setAdvancedCollapsed(!commonStore.advancedCollapsed);
|
||||
}}>
|
||||
<AccordionItem value="advanced">
|
||||
<AccordionHeader ref={advancedHeaderRef} size="large">{t('Advanced')}</AccordionHeader>
|
||||
<AccordionPanel>
|
||||
<div className="flex flex-col gap-2 overflow-hidden">
|
||||
{commonStore.platform !== 'darwin' &&
|
||||
<Labeled label={t('Custom Models Path')}
|
||||
content={
|
||||
<Input className="grow" placeholder="./models"
|
||||
value={commonStore.settings.customModelsPath}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
customModelsPath: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
}
|
||||
<Labeled label={t('Custom Python Path')} // if set, will not use precompiled cuda kernel
|
||||
content={
|
||||
<Input className="grow" placeholder="./py310/python"
|
||||
value={commonStore.settings.customPythonPath}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setDepComplete(false);
|
||||
commonStore.setSettings({
|
||||
customPythonPath: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<AdvancedGeneralSettings />
|
||||
</div>
|
||||
</AccordionPanel>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
</div>
|
||||
} />
|
||||
);
|
||||
});
|
||||
|
||||
export default Settings;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import React, { FC, ReactElement, useEffect, useRef, useState } from 'react';
|
||||
import React, { FC, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button, Dropdown, Input, Option, Select, Switch, Tab, TabList } from '@fluentui/react-components';
|
||||
import {
|
||||
@@ -24,7 +24,6 @@ import { Labeled } from '../components/Labeled';
|
||||
import { ToolTipButton } from '../components/ToolTipButton';
|
||||
import { DataUsageSettings20Regular, Folder20Regular } from '@fluentui/react-icons';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { Precision } from './Configs';
|
||||
import {
|
||||
CategoryScale,
|
||||
Chart as ChartJS,
|
||||
@@ -40,6 +39,12 @@ import { ChartJSOrUndefined } from 'react-chartjs-2/dist/types';
|
||||
import { WindowShow } from '../../wailsjs/runtime';
|
||||
import { t } from 'i18next';
|
||||
import { DialogButton } from '../components/DialogButton';
|
||||
import {
|
||||
DataProcessParameters,
|
||||
LoraFinetuneParameters,
|
||||
LoraFinetunePrecision,
|
||||
TrainNavigationItem
|
||||
} from '../types/train';
|
||||
|
||||
ChartJS.register(
|
||||
CategoryScale,
|
||||
@@ -86,39 +91,6 @@ const addLossDataToChart = (epoch: number, loss: number) => {
|
||||
commonStore.setChartData(commonStore.chartData);
|
||||
};
|
||||
|
||||
export type DataProcessParameters = {
|
||||
dataPath: string;
|
||||
vocabPath: string;
|
||||
}
|
||||
|
||||
export type LoraFinetunePrecision = 'bf16' | 'fp16' | 'tf32';
|
||||
|
||||
export type LoraFinetuneParameters = {
|
||||
baseModel: string;
|
||||
ctxLen: number;
|
||||
epochSteps: number;
|
||||
epochCount: number;
|
||||
epochBegin: number;
|
||||
epochSave: number;
|
||||
microBsz: number;
|
||||
accumGradBatches: number;
|
||||
preFfn: boolean;
|
||||
headQk: boolean;
|
||||
lrInit: string;
|
||||
lrFinal: string;
|
||||
warmupSteps: number;
|
||||
beta1: number;
|
||||
beta2: number;
|
||||
adamEps: string;
|
||||
devices: number;
|
||||
precision: LoraFinetunePrecision;
|
||||
gradCp: boolean;
|
||||
loraR: number;
|
||||
loraAlpha: number;
|
||||
loraDropout: number;
|
||||
loraLoad: string
|
||||
}
|
||||
|
||||
const loraFinetuneParametersOptions: Array<[key: keyof LoraFinetuneParameters, type: string, name: string]> = [
|
||||
['devices', 'number', 'Devices'],
|
||||
['precision', 'LoraFinetunePrecision', 'Precision'],
|
||||
@@ -157,11 +129,12 @@ const errorsMap = Object.entries({
|
||||
'python3 ./finetune/lora/train.py': 'Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.',
|
||||
'cuda out of memory': 'VRAM is not enough',
|
||||
'valueerror: high <= 0': 'Training data is not enough, reduce context length or add more data for training',
|
||||
'+= \'+ptx\'': 'You are using WSL 1 for training, please upgrade to WSL 2. e.g. Run "wsl --set-version Ubuntu-22.04 2"',
|
||||
'+= \'+ptx\'': 'Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run "wsl --set-version Ubuntu-22.04 2"',
|
||||
'size mismatch for blocks': 'Size mismatch for blocks. You are attempting to continue training from the LoRA model, but it does not match the base model. Please set LoRA model to None.',
|
||||
'cuda_home environment variable is not set': 'Matched CUDA is not installed',
|
||||
'unsupported gpu architecture': 'Matched CUDA is not installed',
|
||||
'error building extension \'fused_adam\'': 'Matched CUDA is not installed'
|
||||
'error building extension \'fused_adam\'': 'Matched CUDA is not installed',
|
||||
'modelinfo is invalid': 'Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.'
|
||||
});
|
||||
|
||||
export const wslHandler = (data: string) => {
|
||||
@@ -568,10 +541,6 @@ const LoraFinetune: FC = observer(() => {
|
||||
);
|
||||
});
|
||||
|
||||
type TrainNavigationItem = {
|
||||
element: ReactElement;
|
||||
};
|
||||
|
||||
const pages: { [label: string]: TrainNavigationItem } = {
|
||||
'LoRA Finetune': {
|
||||
element: <LoraFinetune />
|
||||
@@ -582,7 +551,7 @@ const pages: { [label: string]: TrainNavigationItem } = {
|
||||
};
|
||||
|
||||
|
||||
export const Train: FC = () => {
|
||||
const Train: FC = () => {
|
||||
const { t } = useTranslation();
|
||||
const [tab, setTab] = useState('LoRA Finetune');
|
||||
|
||||
@@ -607,3 +576,5 @@ export const Train: FC = () => {
|
||||
</div>
|
||||
</div>;
|
||||
};
|
||||
|
||||
export default Train;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ModelConfig } from './Configs';
|
||||
import { CompletionPreset } from './Completion';
|
||||
import { CompletionPreset } from '../types/completion';
|
||||
import { ModelConfig } from '../types/configs';
|
||||
|
||||
export const defaultCompositionPrompt = '<pad>';
|
||||
|
||||
@@ -111,7 +111,7 @@ export const defaultPresets: CompletionPreset[] = [{
|
||||
|
||||
export const defaultModelConfigsMac: ModelConfig[] = [
|
||||
{
|
||||
name: 'MAC-0.1B-World',
|
||||
name: 'GPU-2G-1B5-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
@@ -121,16 +121,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-0.1B-v1-20230520-ctx4096.pth',
|
||||
device: 'MPS',
|
||||
precision: 'fp32',
|
||||
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
customStrategy: 'mps fp32'
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'MAC-0.4B-World',
|
||||
name: 'GPU-4G-3B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
@@ -140,12 +139,101 @@ export const defaultModelConfigsMac: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-0.4B-v1-20230529-ctx4096.pth',
|
||||
device: 'MPS',
|
||||
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-4G-3B-CN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-CHNtuned-3B-v1-20230625-ctx4096.pth',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-7G-7B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-7B-v1-20230626-ctx4096.pth',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-7G-7B-CN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-CHNtuned-7B-v1-20230709-ctx4096.pth',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-120M-Music',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.8,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-MIDI-120M-v1-20230714-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
customStrategy: 'mps fp32'
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-560M-Music',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.8,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-MIDI-560M-v1-20230717-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
@@ -159,26 +247,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
|
||||
device: 'MPS',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
customStrategy: 'mps fp32'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'MAC-1B5-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
|
||||
device: 'MPS',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
@@ -197,26 +266,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
|
||||
device: 'MPS',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
customStrategy: 'mps fp32'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'MAC-3B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
|
||||
device: 'MPS',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
@@ -261,190 +311,29 @@ export const defaultModelConfigsMac: ModelConfig[] = [
|
||||
maxStoredLayers: 41,
|
||||
customStrategy: 'mps fp32'
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-120M-Music',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.8,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-MIDI-120M-v1-20230714-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-560M-Music',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.8,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-MIDI-560M-v1-20230717-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-6G-1B5-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-6G-1B5-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-12G-3B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-12G-3B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-12G-3B-CN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-CHNtuned-3B-v1-20230625-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-28G-7B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-7B-v1-20230626-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-28G-7B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-28G-7B-CN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-CHNtuned-7B-v1-20230709-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
export const defaultModelConfigs: ModelConfig[] = [
|
||||
{
|
||||
name: 'GPU-2G-1B5-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-2G-3B-World',
|
||||
apiParameters: {
|
||||
@@ -456,7 +345,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
|
||||
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 6,
|
||||
@@ -464,61 +353,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-2G-0.1B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-0.1B-v1-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp32', // using fp16 will disable state cache (->)
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-2G-1B5-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 4,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-4G-0.4B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-0.4B-v1-20230529-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-4G-1B5-World',
|
||||
apiParameters: {
|
||||
@@ -530,27 +364,9 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
|
||||
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp32',
|
||||
storedLayers: 8,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-4G-1B5-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
@@ -567,26 +383,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 24,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-4G-3B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 24,
|
||||
@@ -632,25 +429,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-4G-7B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 8,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-4G-7B-CN',
|
||||
apiParameters: {
|
||||
@@ -670,25 +448,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-6G-1B5-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-6G-3B-World',
|
||||
apiParameters: {
|
||||
@@ -700,26 +459,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-6G-3B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
@@ -765,25 +505,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-6G-7B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 18,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-6G-7B-CN',
|
||||
apiParameters: {
|
||||
@@ -803,24 +524,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-8G-1B5-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-8G-3B-World',
|
||||
apiParameters: {
|
||||
@@ -832,26 +535,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-8G-3B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
@@ -897,25 +581,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-8G-7B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 27,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-8G-7B-CN',
|
||||
apiParameters: {
|
||||
@@ -954,25 +619,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-10G-7B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-10G-7B-CN',
|
||||
apiParameters: {
|
||||
@@ -992,25 +638,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-12G-14B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 24,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-16G-7B-World',
|
||||
apiParameters: {
|
||||
@@ -1030,25 +657,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-16G-7B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-16G-7B-CN',
|
||||
apiParameters: {
|
||||
@@ -1068,63 +676,6 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-16G-14B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 37,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-18G-14B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'GPU-32G-14B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41,
|
||||
useCustomCuda: true
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-120M-Music',
|
||||
apiParameters: {
|
||||
@@ -1162,7 +713,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-6G-1B5-World',
|
||||
name: 'AnyGPU-2G-1B5-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
@@ -1172,15 +723,15 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-6G-1B5-EN',
|
||||
name: 'AnyGPU-4G-3B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
@@ -1190,51 +741,15 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-12G-3B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-12G-3B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-12G-3B-CN',
|
||||
name: 'AnyGPU-4G-3B-CN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
@@ -1245,14 +760,14 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-CHNtuned-3B-v1-20230625-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-28G-7B-World',
|
||||
name: 'AnyGPU-7G-7B-World',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
@@ -1263,32 +778,14 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-7B-v1-20230626-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-28G-7B-EN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1.0,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
},
|
||||
{
|
||||
name: 'CPU-28G-7B-CN',
|
||||
name: 'AnyGPU-7G-7B-CN',
|
||||
apiParameters: {
|
||||
apiPort: 8000,
|
||||
maxResponseToken: 4100,
|
||||
@@ -1299,8 +796,8 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-World-CHNtuned-7B-v1-20230709-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
device: 'WebGPU',
|
||||
precision: 'nf4',
|
||||
storedLayers: 41,
|
||||
maxStoredLayers: 41
|
||||
}
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
import { ReactElement } from 'react';
|
||||
import { Configs } from './Configs';
|
||||
import { FC, lazy, LazyExoticComponent, ReactElement } from 'react';
|
||||
import {
|
||||
ArrowDownload20Regular,
|
||||
Chat20Regular,
|
||||
@@ -12,21 +11,12 @@ import {
|
||||
Settings20Regular,
|
||||
Storage20Regular
|
||||
} from '@fluentui/react-icons';
|
||||
import { Home } from './Home';
|
||||
import { Chat } from './Chat';
|
||||
import { Models } from './Models';
|
||||
import { Train } from './Train';
|
||||
import { Settings } from './Settings';
|
||||
import { About } from './About';
|
||||
import { Downloads } from './Downloads';
|
||||
import { Completion } from './Completion';
|
||||
import { Composition } from './Composition';
|
||||
|
||||
type NavigationItem = {
|
||||
label: string;
|
||||
path: string;
|
||||
icon: ReactElement;
|
||||
element: ReactElement;
|
||||
element: LazyExoticComponent<FC>;
|
||||
top: boolean;
|
||||
};
|
||||
|
||||
@@ -35,70 +25,70 @@ export const pages: NavigationItem[] = [
|
||||
label: 'Home',
|
||||
path: '/',
|
||||
icon: <Home20Regular />,
|
||||
element: <Home />,
|
||||
element: lazy(() => import('./Home')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Chat',
|
||||
path: '/chat',
|
||||
icon: <Chat20Regular />,
|
||||
element: <Chat />,
|
||||
element: lazy(() => import('./Chat')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Completion',
|
||||
path: '/completion',
|
||||
icon: <ClipboardEdit20Regular />,
|
||||
element: <Completion />,
|
||||
element: lazy(() => import('./Completion')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Composition',
|
||||
path: '/composition',
|
||||
icon: <MusicNote220Regular />,
|
||||
element: <Composition />,
|
||||
element: lazy(() => import('./Composition')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Configs',
|
||||
path: '/configs',
|
||||
icon: <DocumentSettings20Regular />,
|
||||
element: <Configs />,
|
||||
element: lazy(() => import('./Configs')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Models',
|
||||
path: '/models',
|
||||
icon: <DataUsageSettings20Regular />,
|
||||
element: <Models />,
|
||||
element: lazy(() => import('./Models')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Downloads',
|
||||
path: '/downloads',
|
||||
icon: <ArrowDownload20Regular />,
|
||||
element: <Downloads />,
|
||||
element: lazy(() => import('./Downloads')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Train',
|
||||
path: '/train',
|
||||
icon: <Storage20Regular />,
|
||||
element: <Train />,
|
||||
element: lazy(() => import('./Train')),
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Settings',
|
||||
path: '/settings',
|
||||
icon: <Settings20Regular />,
|
||||
element: <Settings />,
|
||||
element: lazy(() => import('./Settings')),
|
||||
top: false
|
||||
},
|
||||
{
|
||||
label: 'About',
|
||||
path: '/about',
|
||||
icon: <Info20Regular />,
|
||||
element: <About />,
|
||||
element: lazy(() => import('./About')),
|
||||
top: false
|
||||
}
|
||||
];
|
||||
|
||||
@@ -1,43 +1,46 @@
|
||||
import commonStore, { Platform } from './stores/commonStore';
|
||||
import commonStore, { MonitorData, Platform } from './stores/commonStore';
|
||||
import { GetPlatform, ListDirFiles, ReadJson } from '../wailsjs/go/backend_golang/App';
|
||||
import { Cache, checkUpdate, downloadProgramFiles, LocalConfig, refreshLocalModels, refreshModels } from './utils';
|
||||
import { getStatus } from './apis';
|
||||
import { EventsOn, WindowSetTitle } from '../wailsjs/runtime';
|
||||
import manifest from '../../manifest.json';
|
||||
import { defaultModelConfigs, defaultModelConfigsMac } from './pages/defaultConfigs';
|
||||
import { Preset } from './pages/PresetsManager/PresetsButton';
|
||||
import { wslHandler } from './pages/Train';
|
||||
import { t } from 'i18next';
|
||||
import { Preset } from './types/presets';
|
||||
|
||||
export async function startup() {
|
||||
downloadProgramFiles();
|
||||
EventsOn('downloadList', (data) => {
|
||||
if (data)
|
||||
commonStore.setDownloadList(data);
|
||||
});
|
||||
EventsOn('wsl', wslHandler);
|
||||
EventsOn('wslerr', (e) => {
|
||||
console.log(e);
|
||||
});
|
||||
initLocalModelsNotify();
|
||||
initLoraModels();
|
||||
|
||||
initPresets();
|
||||
|
||||
initHardwareMonitor();
|
||||
|
||||
await GetPlatform().then(p => commonStore.setPlatform(p as Platform));
|
||||
|
||||
if (commonStore.platform !== 'web') {
|
||||
downloadProgramFiles();
|
||||
EventsOn('downloadList', (data) => {
|
||||
if (data)
|
||||
commonStore.setDownloadList(data);
|
||||
});
|
||||
EventsOn('wsl', (await import('./pages/Train')).wslHandler);
|
||||
EventsOn('wslerr', (e) => {
|
||||
console.log(e);
|
||||
});
|
||||
initLocalModelsNotify();
|
||||
initLoraModels();
|
||||
initHardwareMonitor();
|
||||
}
|
||||
|
||||
await initConfig();
|
||||
|
||||
initCache(true).then(initRemoteText); // depends on config customModelsPath
|
||||
if (commonStore.platform !== 'web') {
|
||||
initCache(true).then(initRemoteText); // depends on config customModelsPath
|
||||
|
||||
if (commonStore.settings.autoUpdatesCheck) // depends on config settings
|
||||
checkUpdate();
|
||||
if (commonStore.settings.autoUpdatesCheck) // depends on config settings
|
||||
checkUpdate();
|
||||
|
||||
getStatus(1000).then(status => { // depends on config api port
|
||||
if (status)
|
||||
commonStore.setStatus(status);
|
||||
});
|
||||
getStatus(1000).then(status => { // depends on config api port
|
||||
if (status)
|
||||
commonStore.setStatus(status);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function initRemoteText() {
|
||||
@@ -88,7 +91,8 @@ async function initCache(initUnfinishedModels: boolean) {
|
||||
|
||||
async function initPresets() {
|
||||
await ReadJson('presets.json').then((presets: Preset[]) => {
|
||||
commonStore.setPresets(presets, false);
|
||||
if (Array.isArray(presets))
|
||||
commonStore.setPresets(presets, false);
|
||||
}).catch(() => {
|
||||
});
|
||||
}
|
||||
@@ -121,19 +125,12 @@ async function initLocalModelsNotify() {
|
||||
});
|
||||
}
|
||||
|
||||
type monitorData = {
|
||||
usedMemory: number;
|
||||
totalMemory: number;
|
||||
gpuUsage: number;
|
||||
gpuPower: number;
|
||||
usedVram: number;
|
||||
totalVram: number;
|
||||
}
|
||||
|
||||
async function initHardwareMonitor() {
|
||||
EventsOn('monitor', (data: string) => {
|
||||
const results: monitorData = JSON.parse(data);
|
||||
if (results)
|
||||
const results: MonitorData = JSON.parse(data);
|
||||
if (results) {
|
||||
commonStore.setMonitorData(results);
|
||||
WindowSetTitle(`RWKV-Runner (${t('RAM')}: ${results.usedMemory.toFixed(1)}/${results.totalMemory.toFixed(1)} GB, ${t('VRAM')}: ${(results.usedVram / 1024).toFixed(1)}/${(results.totalVram / 1024).toFixed(1)} GB, ${t('GPU Usage')}: ${results.gpuUsage}%)`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@@ -2,21 +2,20 @@ import { makeAutoObservable } from 'mobx';
|
||||
import { getUserLanguage, isSystemLightMode, saveCache, saveConfigs, savePresets } from '../utils';
|
||||
import { WindowSetDarkTheme, WindowSetLightTheme } from '../../wailsjs/runtime';
|
||||
import manifest from '../../../manifest.json';
|
||||
import { ModelConfig } from '../pages/Configs';
|
||||
import { Conversation } from '../pages/Chat';
|
||||
import { ModelSourceItem } from '../pages/Models';
|
||||
import { DownloadStatus } from '../pages/Downloads';
|
||||
import { SettingsType } from '../pages/Settings';
|
||||
import { IntroductionContent } from '../pages/Home';
|
||||
import { AboutContent } from '../pages/About';
|
||||
import i18n from 'i18next';
|
||||
import { CompletionPreset } from '../pages/Completion';
|
||||
import { defaultCompositionPrompt, defaultModelConfigs, defaultModelConfigsMac } from '../pages/defaultConfigs';
|
||||
import commonStore from './commonStore';
|
||||
import { Preset } from '../pages/PresetsManager/PresetsButton';
|
||||
import { DataProcessParameters, LoraFinetuneParameters } from '../pages/Train';
|
||||
import { ChartData } from 'chart.js';
|
||||
import { CompositionParams } from '../pages/Composition';
|
||||
import { Preset } from '../types/presets';
|
||||
import { AboutContent } from '../types/about';
|
||||
import { Attachment, ChatParams, Conversation } from '../types/chat';
|
||||
import { CompletionPreset } from '../types/completion';
|
||||
import { CompositionParams } from '../types/composition';
|
||||
import { ModelConfig } from '../types/configs';
|
||||
import { DownloadStatus } from '../types/downloads';
|
||||
import { IntroductionContent } from '../types/home';
|
||||
import { ModelSourceItem } from '../types/models';
|
||||
import { SettingsType } from '../types/settings';
|
||||
import { DataProcessParameters, LoraFinetuneParameters } from '../types/train';
|
||||
|
||||
export enum ModelStatus {
|
||||
Offline,
|
||||
@@ -31,13 +30,16 @@ export type Status = {
|
||||
device_name: string;
|
||||
}
|
||||
|
||||
export type Attachment = {
|
||||
name: string;
|
||||
size: number;
|
||||
content: string;
|
||||
export type MonitorData = {
|
||||
usedMemory: number;
|
||||
totalMemory: number;
|
||||
gpuUsage: number;
|
||||
gpuPower: number;
|
||||
usedVram: number;
|
||||
totalVram: number;
|
||||
}
|
||||
|
||||
export type Platform = 'windows' | 'darwin' | 'linux';
|
||||
export type Platform = 'windows' | 'darwin' | 'linux' | 'web';
|
||||
|
||||
class CommonStore {
|
||||
// global
|
||||
@@ -46,8 +48,10 @@ class CommonStore {
|
||||
pid: 0,
|
||||
device_name: 'CPU'
|
||||
};
|
||||
monitorData: MonitorData | null = null;
|
||||
depComplete: boolean = false;
|
||||
platform: Platform = 'windows';
|
||||
lastModelName: string = '';
|
||||
// presets manager
|
||||
editingPreset: Preset | null = null;
|
||||
presets: Preset[] = [];
|
||||
@@ -61,6 +65,14 @@ class CommonStore {
|
||||
attachmentUploading: boolean = false;
|
||||
attachments: { [uuid: string]: Attachment[] } = {};
|
||||
currentTempAttachment: Attachment | null = null;
|
||||
chatParams: ChatParams = {
|
||||
maxResponseToken: 1000,
|
||||
temperature: 1,
|
||||
topP: 0.3,
|
||||
presencePenalty: 0,
|
||||
frequencyPenalty: 1
|
||||
};
|
||||
sidePanelCollapsed: boolean | 'auto' = 'auto';
|
||||
// completion
|
||||
completionPreset: CompletionPreset | null = null;
|
||||
completionGenerating: boolean = false;
|
||||
@@ -103,7 +115,7 @@ class CommonStore {
|
||||
epochSteps: 200,
|
||||
epochCount: 20,
|
||||
epochBegin: 0,
|
||||
epochSave: 2,
|
||||
epochSave: 1,
|
||||
microBsz: 1,
|
||||
accumGradBatches: 8,
|
||||
preFfn: false,
|
||||
@@ -130,12 +142,13 @@ class CommonStore {
|
||||
autoUpdatesCheck: true,
|
||||
giteeUpdatesSource: getUserLanguage() === 'zh',
|
||||
cnMirror: getUserLanguage() === 'zh',
|
||||
useHfMirror: false,
|
||||
host: '127.0.0.1',
|
||||
dpiScaling: 100,
|
||||
customModelsPath: './models',
|
||||
customPythonPath: '',
|
||||
apiUrl: '',
|
||||
apiKey: 'sk-',
|
||||
apiKey: '',
|
||||
apiChatModelName: 'rwkv',
|
||||
apiCompletionModelName: 'rwkv'
|
||||
};
|
||||
@@ -175,7 +188,7 @@ class CommonStore {
|
||||
createModelConfig = (config: ModelConfig = defaultModelConfigs[0], saveConfig: boolean = true) => {
|
||||
if (config.name === defaultModelConfigs[0].name) {
|
||||
// deep copy
|
||||
config = JSON.parse(JSON.stringify(commonStore.platform !== 'darwin' ? defaultModelConfigs[0] : defaultModelConfigsMac[0]));
|
||||
config = JSON.parse(JSON.stringify(this.platform !== 'darwin' ? defaultModelConfigs[0] : defaultModelConfigsMac[0]));
|
||||
config.name = new Date().toLocaleString();
|
||||
}
|
||||
this.modelConfigs.push(config);
|
||||
@@ -229,6 +242,10 @@ class CommonStore {
|
||||
this.about = value;
|
||||
};
|
||||
|
||||
setLastModelName(value: string) {
|
||||
this.lastModelName = value;
|
||||
}
|
||||
|
||||
setDepComplete = (value: boolean, inSaveCache: boolean = true) => {
|
||||
this.depComplete = value;
|
||||
if (inSaveCache)
|
||||
@@ -255,6 +272,10 @@ class CommonStore {
|
||||
this.completionGenerating = value;
|
||||
}
|
||||
|
||||
setMonitorData(value: MonitorData) {
|
||||
this.monitorData = value;
|
||||
}
|
||||
|
||||
setPlatform(value: Platform) {
|
||||
this.platform = value;
|
||||
}
|
||||
@@ -351,6 +372,14 @@ class CommonStore {
|
||||
setCurrentTempAttachment(value: Attachment | null) {
|
||||
this.currentTempAttachment = value;
|
||||
}
|
||||
|
||||
setChatParams(value: Partial<ChatParams>) {
|
||||
this.chatParams = { ...this.chatParams, ...value };
|
||||
}
|
||||
|
||||
setSidePanelCollapsed(value: boolean | 'auto') {
|
||||
this.sidePanelCollapsed = value;
|
||||
}
|
||||
}
|
||||
|
||||
export default new CommonStore();
|
||||
@@ -1,12 +1,10 @@
|
||||
[data-theme='dark'] {
|
||||
@import 'highlight.js/scss/github-dark.scss';
|
||||
@import 'github-markdown-css/github-markdown-dark.css';
|
||||
--color-neutral-muted: rgba(110, 118, 129, 0.4);
|
||||
}
|
||||
|
||||
[data-theme='light'] {
|
||||
@import 'highlight.js/scss/github.scss';
|
||||
@import 'github-markdown-css/github-markdown-light.css';
|
||||
--color-neutral-muted: rgba(150, 160, 170, 0.3);
|
||||
}
|
||||
|
||||
@@ -16,7 +14,6 @@
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
overflow: hidden;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
1
frontend/src/types/about.ts
Normal file
1
frontend/src/types/about.ts
Normal file
@@ -0,0 +1 @@
|
||||
export type AboutContent = { [lang: string]: string }
|
||||
37
frontend/src/types/chat.ts
Normal file
37
frontend/src/types/chat.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { ApiParameters } from './configs';
|
||||
|
||||
export const userName = 'M E';
|
||||
export const botName = 'A I';
|
||||
export const welcomeUuid = 'welcome';
|
||||
|
||||
export enum MessageType {
|
||||
Normal,
|
||||
Error
|
||||
}
|
||||
|
||||
export type Side = 'left' | 'right'
|
||||
export type Color = 'neutral' | 'brand' | 'colorful'
|
||||
export type MessageItem = {
|
||||
sender: string,
|
||||
type: MessageType,
|
||||
color: Color,
|
||||
avatarImg?: string,
|
||||
time: string,
|
||||
content: string,
|
||||
side: Side,
|
||||
done: boolean
|
||||
}
|
||||
export type Conversation = {
|
||||
[uuid: string]: MessageItem
|
||||
}
|
||||
export type Role = 'assistant' | 'user' | 'system';
|
||||
export type ConversationMessage = {
|
||||
role: Role;
|
||||
content: string;
|
||||
}
|
||||
export type Attachment = {
|
||||
name: string;
|
||||
size: number;
|
||||
content: string;
|
||||
}
|
||||
export type ChatParams = Omit<ApiParameters, 'apiPort'>
|
||||
12
frontend/src/types/completion.ts
Normal file
12
frontend/src/types/completion.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { ApiParameters } from './configs';
|
||||
|
||||
export type CompletionParams = Omit<ApiParameters, 'apiPort'> & {
|
||||
stop: string,
|
||||
injectStart: string,
|
||||
injectEnd: string
|
||||
};
|
||||
export type CompletionPreset = {
|
||||
name: string,
|
||||
prompt: string,
|
||||
params: CompletionParams
|
||||
}
|
||||
12
frontend/src/types/composition.ts
Normal file
12
frontend/src/types/composition.ts
Normal file
@@ -0,0 +1,12 @@
|
||||
import { NoteSequence } from '@magenta/music/esm/protobuf';
|
||||
|
||||
export type CompositionParams = {
|
||||
prompt: string,
|
||||
maxResponseToken: number,
|
||||
temperature: number,
|
||||
topP: number,
|
||||
autoPlay: boolean,
|
||||
useLocalSoundFont: boolean,
|
||||
midi: ArrayBuffer | null,
|
||||
ns: NoteSequence | null
|
||||
}
|
||||
29
frontend/src/types/configs.ts
Normal file
29
frontend/src/types/configs.ts
Normal file
@@ -0,0 +1,29 @@
|
||||
export type ApiParameters = {
|
||||
apiPort: number
|
||||
maxResponseToken: number;
|
||||
temperature: number;
|
||||
topP: number;
|
||||
presencePenalty: number;
|
||||
frequencyPenalty: number;
|
||||
}
|
||||
export type Device = 'CPU' | 'CUDA' | 'CUDA-Beta' | 'WebGPU' | 'MPS' | 'Custom';
|
||||
export type Precision = 'fp16' | 'int8' | 'fp32' | 'nf4';
|
||||
export type ModelParameters = {
|
||||
// different models can not have the same name
|
||||
modelName: string;
|
||||
device: Device;
|
||||
precision: Precision;
|
||||
storedLayers: number;
|
||||
maxStoredLayers: number;
|
||||
useCustomCuda?: boolean;
|
||||
customStrategy?: string;
|
||||
useCustomTokenizer?: boolean;
|
||||
customTokenizer?: string;
|
||||
}
|
||||
export type ModelConfig = {
|
||||
// different configs can have the same name
|
||||
name: string;
|
||||
apiParameters: ApiParameters;
|
||||
modelParameters: ModelParameters;
|
||||
enableWebUI?: boolean;
|
||||
}
|
||||
11
frontend/src/types/downloads.ts
Normal file
11
frontend/src/types/downloads.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
export type DownloadStatus = {
|
||||
name: string;
|
||||
path: string;
|
||||
url: string;
|
||||
transferred: number;
|
||||
size: number;
|
||||
speed: number;
|
||||
progress: number;
|
||||
downloading: boolean;
|
||||
done: boolean;
|
||||
}
|
||||
11
frontend/src/types/home.ts
Normal file
11
frontend/src/types/home.ts
Normal file
@@ -0,0 +1,11 @@
|
||||
import { ReactElement } from 'react';
|
||||
|
||||
export type IntroductionContent = {
|
||||
[lang: string]: string
|
||||
}
|
||||
export type NavCard = {
|
||||
label: string;
|
||||
desc: string;
|
||||
path: string;
|
||||
icon: ReactElement;
|
||||
};
|
||||
14
frontend/src/types/models.ts
Normal file
14
frontend/src/types/models.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
export type ModelSourceItem = {
|
||||
name: string;
|
||||
size: number;
|
||||
lastUpdated: string;
|
||||
desc?: { [lang: string]: string | undefined; };
|
||||
SHA256?: string;
|
||||
url?: string;
|
||||
downloadUrl?: string;
|
||||
isComplete?: boolean;
|
||||
isLocal?: boolean;
|
||||
localSize?: number;
|
||||
lastUpdatedMs?: number;
|
||||
hide?: boolean;
|
||||
};
|
||||
30
frontend/src/types/presets.ts
Normal file
30
frontend/src/types/presets.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
import { ReactElement } from 'react';
|
||||
|
||||
import { ConversationMessage } from './chat';
|
||||
|
||||
export type PresetType = 'chat' | 'completion' | 'chatInCompletion'
|
||||
export type Preset = {
|
||||
name: string,
|
||||
tag: string,
|
||||
// if name and sourceUrl are same, it will be overridden when importing
|
||||
sourceUrl: string,
|
||||
desc: string,
|
||||
avatarImg: string,
|
||||
type: PresetType,
|
||||
// chat
|
||||
welcomeMessage: string,
|
||||
messages: ConversationMessage[],
|
||||
displayPresetMessages: boolean,
|
||||
// completion
|
||||
prompt: string,
|
||||
stop: string,
|
||||
injectStart: string,
|
||||
injectEnd: string,
|
||||
presystem?: boolean,
|
||||
userName?: string,
|
||||
assistantName?: string
|
||||
}
|
||||
export type PresetsNavigationItem = {
|
||||
icon: ReactElement;
|
||||
element: ReactElement;
|
||||
};
|
||||
22
frontend/src/types/settings.ts
Normal file
22
frontend/src/types/settings.ts
Normal file
@@ -0,0 +1,22 @@
|
||||
export const Languages = {
|
||||
dev: 'English', // i18n default
|
||||
zh: '简体中文',
|
||||
ja: '日本語'
|
||||
};
|
||||
export type Language = keyof typeof Languages;
|
||||
export type SettingsType = {
|
||||
language: Language
|
||||
darkMode: boolean
|
||||
autoUpdatesCheck: boolean
|
||||
giteeUpdatesSource: boolean
|
||||
cnMirror: boolean
|
||||
useHfMirror: boolean
|
||||
host: string
|
||||
dpiScaling: number
|
||||
customModelsPath: string
|
||||
customPythonPath: string
|
||||
apiUrl: string
|
||||
apiKey: string
|
||||
apiChatModelName: string
|
||||
apiCompletionModelName: string
|
||||
}
|
||||
35
frontend/src/types/train.ts
Normal file
35
frontend/src/types/train.ts
Normal file
@@ -0,0 +1,35 @@
|
||||
import { ReactElement } from 'react';
|
||||
|
||||
export type DataProcessParameters = {
|
||||
dataPath: string;
|
||||
vocabPath: string;
|
||||
}
|
||||
export type LoraFinetunePrecision = 'bf16' | 'fp16' | 'tf32';
|
||||
export type LoraFinetuneParameters = {
|
||||
baseModel: string;
|
||||
ctxLen: number;
|
||||
epochSteps: number;
|
||||
epochCount: number;
|
||||
epochBegin: number;
|
||||
epochSave: number;
|
||||
microBsz: number;
|
||||
accumGradBatches: number;
|
||||
preFfn: boolean;
|
||||
headQk: boolean;
|
||||
lrInit: string;
|
||||
lrFinal: string;
|
||||
warmupSteps: number;
|
||||
beta1: number;
|
||||
beta2: number;
|
||||
adamEps: string;
|
||||
devices: number;
|
||||
precision: LoraFinetunePrecision;
|
||||
gradCp: boolean;
|
||||
loraR: number;
|
||||
loraAlpha: number;
|
||||
loraDropout: number;
|
||||
loraLoad: string
|
||||
}
|
||||
export type TrainNavigationItem = {
|
||||
element: ReactElement;
|
||||
};
|
||||
41
frontend/src/utils/convert-to-st.ts
Normal file
41
frontend/src/utils/convert-to-st.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { toast } from 'react-toastify';
|
||||
import commonStore from '../stores/commonStore';
|
||||
import { t } from 'i18next';
|
||||
import { checkDependencies } from './index';
|
||||
import { ConvertSafetensors, FileExists, GetPyError } from '../../wailsjs/go/backend_golang/App';
|
||||
import { WindowShow } from '../../wailsjs/runtime';
|
||||
import { NavigateFunction } from 'react-router';
|
||||
import { ModelConfig } from '../types/configs';
|
||||
|
||||
export const convertToSt = async (navigate: NavigateFunction, selectedConfig: ModelConfig) => {
|
||||
if (commonStore.platform === 'linux') {
|
||||
toast(t('Linux is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_safetensors.py)', { type: 'info' });
|
||||
return;
|
||||
}
|
||||
|
||||
const ok = await checkDependencies(navigate);
|
||||
if (!ok)
|
||||
return;
|
||||
|
||||
const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}`;
|
||||
if (await FileExists(modelPath)) {
|
||||
toast(t('Start Converting'), { autoClose: 1000, type: 'info' });
|
||||
const newModelPath = modelPath.replace(/\.pth$/, '.st');
|
||||
ConvertSafetensors(commonStore.settings.customPythonPath, modelPath, newModelPath).then(async () => {
|
||||
if (!await FileExists(newModelPath)) {
|
||||
toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' });
|
||||
} else {
|
||||
toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' });
|
||||
}
|
||||
}).catch(e => {
|
||||
const errMsg = e.message || e;
|
||||
if (errMsg.includes('path contains space'))
|
||||
toast(`${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' });
|
||||
else
|
||||
toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' });
|
||||
});
|
||||
setTimeout(WindowShow, 1000);
|
||||
} else {
|
||||
toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' });
|
||||
}
|
||||
};
|
||||
@@ -15,13 +15,13 @@ import { toast } from 'react-toastify';
|
||||
import { t } from 'i18next';
|
||||
import { ToastOptions } from 'react-toastify/dist/types';
|
||||
import { Button } from '@fluentui/react-components';
|
||||
import { Language, Languages, SettingsType } from '../pages/Settings';
|
||||
import { ModelSourceItem } from '../pages/Models';
|
||||
import { ModelConfig, ModelParameters } from '../pages/Configs';
|
||||
import { DownloadStatus } from '../pages/Downloads';
|
||||
import { DataProcessParameters, LoraFinetuneParameters } from '../pages/Train';
|
||||
import { BrowserOpenURL, WindowShow } from '../../wailsjs/runtime';
|
||||
import { BrowserOpenURL, EventsOff, EventsOn, WindowShow } from '../../wailsjs/runtime';
|
||||
import { NavigateFunction } from 'react-router';
|
||||
import { ModelConfig, ModelParameters } from '../types/configs';
|
||||
import { DownloadStatus } from '../types/downloads';
|
||||
import { ModelSourceItem } from '../types/models';
|
||||
import { Language, Languages, SettingsType } from '../types/settings';
|
||||
import { DataProcessParameters, LoraFinetuneParameters } from '../types/train';
|
||||
|
||||
export type Cache = {
|
||||
version: string
|
||||
@@ -117,7 +117,7 @@ function initLastUnfinishedModelDownloads() {
|
||||
{
|
||||
name: item.name,
|
||||
path: `${commonStore.settings.customModelsPath}/${item.name}`,
|
||||
url: item.downloadUrl!,
|
||||
url: getHfDownloadUrl(item.downloadUrl!),
|
||||
transferred: item.localSize!,
|
||||
size: item.size,
|
||||
speed: 0,
|
||||
@@ -178,14 +178,14 @@ export const getStrategy = (modelConfig: ModelConfig | undefined = undefined) =>
|
||||
strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32';
|
||||
break;
|
||||
case 'WebGPU':
|
||||
strategy += params.precision === 'int8' ? 'fp16i8' : 'fp16';
|
||||
strategy += params.precision === 'nf4' ? 'fp16i4' : params.precision === 'int8' ? 'fp16i8' : 'fp16';
|
||||
break;
|
||||
case 'CUDA':
|
||||
case 'CUDA-Beta':
|
||||
if (avoidOverflow)
|
||||
strategy = params.useCustomCuda ? 'cuda fp16 *1 -> ' : 'cuda fp32 *1 -> ';
|
||||
strategy += 'cuda ';
|
||||
strategy += params.precision === 'fp16' ? 'fp16' : params.precision === 'int8' ? 'fp16i8' : 'fp32';
|
||||
strategy += params.precision === 'int8' ? 'fp16i8' : params.precision === 'fp32' ? 'fp32' : 'fp16';
|
||||
if (params.storedLayers < params.maxStoredLayers)
|
||||
strategy += ` *${params.storedLayers}+`;
|
||||
break;
|
||||
@@ -193,7 +193,7 @@ export const getStrategy = (modelConfig: ModelConfig | undefined = undefined) =>
|
||||
if (avoidOverflow)
|
||||
strategy = 'mps fp32 *1 -> ';
|
||||
strategy += 'mps ';
|
||||
strategy += params.precision === 'fp16' ? 'fp16' : params.precision === 'int8' ? 'fp16i8' : 'fp32';
|
||||
strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32';
|
||||
break;
|
||||
case 'Custom':
|
||||
strategy = params.customStrategy || '';
|
||||
@@ -289,7 +289,21 @@ export function bytesToReadable(size: number) {
|
||||
else return bytesToGb(size) + ' GB';
|
||||
}
|
||||
|
||||
export function getServerRoot(defaultLocalPort: number) {
|
||||
const defaultRoot = `http://127.0.0.1:${defaultLocalPort}`;
|
||||
if (commonStore.status.status !== ModelStatus.Offline)
|
||||
return defaultRoot;
|
||||
const customApiUrl = commonStore.settings.apiUrl.trim().replace(/\/$/, '');
|
||||
if (customApiUrl)
|
||||
return customApiUrl;
|
||||
if (commonStore.platform === 'web')
|
||||
return '';
|
||||
return defaultRoot;
|
||||
}
|
||||
|
||||
export function absPathAsset(path: string) {
|
||||
if (commonStore.platform === 'web')
|
||||
return path;
|
||||
if ((path.length > 0 && path[0] === '/') ||
|
||||
(path.length > 1 && path[1] === ':')) {
|
||||
return '=>' + path;
|
||||
@@ -322,27 +336,47 @@ export async function checkUpdate(notifyEvenLatest: boolean = false) {
|
||||
`https://gitee.com/josc146/RWKV-Runner/releases/download/${versionTag}/${asset.name}`;
|
||||
toastWithButton(t('New Version Available') + ': ' + versionTag, t('Update'), () => {
|
||||
DeleteFile('cache.json');
|
||||
toast(t('Downloading update, please wait. If it is not completed, please manually download the program from GitHub and replace the original program.'), {
|
||||
type: 'info',
|
||||
position: 'bottom-left',
|
||||
autoClose: false
|
||||
});
|
||||
setTimeout(() => {
|
||||
UpdateApp(updateUrl).then(() => {
|
||||
toast(t('Update completed, please restart the program.'), {
|
||||
type: 'success',
|
||||
position: 'bottom-left',
|
||||
autoClose: false
|
||||
}
|
||||
);
|
||||
}).catch((e) => {
|
||||
toast(t('Update Error') + ' - ' + (e.message || e), {
|
||||
type: 'error',
|
||||
const progressId = 'update_app';
|
||||
const progressEvent = 'updateApp';
|
||||
const updateProgress = (ds: DownloadStatus | null) => {
|
||||
const content =
|
||||
t('Downloading update, please wait. If it is not completed, please manually download the program from GitHub and replace the original program.')
|
||||
+ (ds ? ` (${ds.progress.toFixed(2)}% ${bytesToReadable(ds.transferred)}/${bytesToReadable(ds.size)})` : '');
|
||||
const options: ToastOptions = {
|
||||
type: 'info',
|
||||
position: 'bottom-left',
|
||||
autoClose: false,
|
||||
toastId: progressId,
|
||||
hideProgressBar: false,
|
||||
progress: ds ? ds.progress / 100 : 0
|
||||
};
|
||||
if (toast.isActive(progressId))
|
||||
toast.update(progressId, {
|
||||
render: content,
|
||||
...options
|
||||
});
|
||||
else
|
||||
toast(content, options);
|
||||
};
|
||||
updateProgress(null);
|
||||
EventsOn(progressEvent, updateProgress);
|
||||
UpdateApp(updateUrl).then(() => {
|
||||
toast(t('Update completed, please restart the program.'), {
|
||||
type: 'success',
|
||||
position: 'bottom-left',
|
||||
autoClose: false
|
||||
});
|
||||
}
|
||||
);
|
||||
}).catch((e) => {
|
||||
toast(t('Update Error') + ' - ' + (e.message || e), {
|
||||
type: 'error',
|
||||
position: 'bottom-left',
|
||||
autoClose: false
|
||||
});
|
||||
}, 500);
|
||||
}).finally(() => {
|
||||
toast.dismiss(progressId);
|
||||
EventsOff(progressEvent);
|
||||
});
|
||||
}, {
|
||||
autoClose: false,
|
||||
position: 'bottom-left'
|
||||
@@ -440,6 +474,12 @@ export function toastWithButton(text: string, buttonText: string, onClickButton:
|
||||
return id;
|
||||
}
|
||||
|
||||
export function getHfDownloadUrl(url: string) {
|
||||
if (commonStore.settings.useHfMirror && url.includes('huggingface.co') && url.includes('resolve'))
|
||||
return url.replace('huggingface.co', 'hf-mirror.com');
|
||||
return url;
|
||||
}
|
||||
|
||||
export function getSupportedCustomCudaFile(isBeta: boolean) {
|
||||
if ([' 10', ' 16', ' 20', ' 30', 'MX', 'Tesla P', 'Quadro P', 'NVIDIA P', 'TITAN X', 'TITAN RTX', 'RTX A',
|
||||
'Quadro RTX 4000', 'Quadro RTX 5000', 'Tesla T4', 'NVIDIA A10', 'NVIDIA A40'].some(v => commonStore.status.device_name.includes(v)))
|
||||
|
||||
72
frontend/src/utils/web-file-operations.ts
Normal file
72
frontend/src/utils/web-file-operations.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { getDocument, GlobalWorkerOptions, PDFDocumentProxy } from 'pdfjs-dist';
|
||||
import { TextItem } from 'pdfjs-dist/types/src/display/api';
|
||||
|
||||
export function webOpenOpenFileDialog({ filterPattern, fnStartLoading }: { filterPattern: string, fnStartLoading: Function | null }): Promise<{ blob: Blob, content?: string }> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const input = document.createElement('input');
|
||||
input.type = 'file';
|
||||
input.accept = filterPattern
|
||||
.replaceAll('*.txt', 'text/plain')
|
||||
.replaceAll('*.', 'application/')
|
||||
.replaceAll(';', ',');
|
||||
|
||||
input.onchange = async e => {
|
||||
// @ts-ignore
|
||||
const file: Blob = e.target?.files[0];
|
||||
if (fnStartLoading && typeof fnStartLoading === 'function')
|
||||
fnStartLoading();
|
||||
if (!GlobalWorkerOptions.workerSrc)
|
||||
// @ts-ignore
|
||||
GlobalWorkerOptions.workerSrc = await import('pdfjs-dist/build/pdf.worker.min.mjs');
|
||||
if (file.type === 'text/plain') {
|
||||
const reader = new FileReader();
|
||||
reader.readAsText(file, 'UTF-8');
|
||||
|
||||
reader.onload = event => {
|
||||
const content = event.target?.result as string;
|
||||
resolve({
|
||||
blob: file,
|
||||
content: content
|
||||
});
|
||||
};
|
||||
reader.onerror = reject;
|
||||
} else if (file.type === 'application/pdf') {
|
||||
const readPDFPage = async (doc: PDFDocumentProxy, pageNo: number) => {
|
||||
const page = await doc.getPage(pageNo);
|
||||
const tokenizedText = await page.getTextContent();
|
||||
return tokenizedText.items.map(token => (token as TextItem).str).join('');
|
||||
};
|
||||
let reader = new FileReader();
|
||||
reader.readAsArrayBuffer(file);
|
||||
|
||||
reader.onload = async (event) => {
|
||||
try {
|
||||
const doc = await getDocument(event.target?.result!).promise;
|
||||
const pageTextPromises = [];
|
||||
for (let pageNo = 1; pageNo <= doc.numPages; pageNo++) {
|
||||
pageTextPromises.push(readPDFPage(doc, pageNo));
|
||||
}
|
||||
const pageTexts = await Promise.all(pageTextPromises);
|
||||
let content;
|
||||
if (pageTexts.length === 1)
|
||||
content = pageTexts[0];
|
||||
else
|
||||
content = pageTexts.map((p, i) => `Page ${i + 1}:\n${p}`).join('\n\n');
|
||||
resolve({
|
||||
blob: file,
|
||||
content: content
|
||||
});
|
||||
} catch (err) {
|
||||
reject(err);
|
||||
}
|
||||
};
|
||||
reader.onerror = reject;
|
||||
} else {
|
||||
resolve({
|
||||
blob: file
|
||||
});
|
||||
}
|
||||
};
|
||||
input.click();
|
||||
});
|
||||
}
|
||||
129
frontend/src/webWails.js
Normal file
129
frontend/src/webWails.js
Normal file
@@ -0,0 +1,129 @@
|
||||
import { webOpenOpenFileDialog } from './utils/web-file-operations'
|
||||
|
||||
function defineRuntime(name, func) {
|
||||
window.runtime[name] = func
|
||||
}
|
||||
|
||||
function defineApp(name, func) {
|
||||
window.go['backend_golang']['App'][name] = func
|
||||
}
|
||||
|
||||
if (!window.runtime) {
|
||||
window.runtime = {}
|
||||
document.title += ' WebUI'
|
||||
|
||||
// not implemented
|
||||
defineRuntime('EventsOnMultiple', () => {
|
||||
})
|
||||
defineRuntime('WindowSetLightTheme', () => {
|
||||
})
|
||||
defineRuntime('WindowSetDarkTheme', () => {
|
||||
})
|
||||
defineRuntime('WindowShow', () => {
|
||||
})
|
||||
defineRuntime('WindowHide', () => {
|
||||
})
|
||||
|
||||
// implemented
|
||||
defineRuntime('ClipboardGetText', async () => {
|
||||
return await navigator.clipboard.readText()
|
||||
})
|
||||
defineRuntime('ClipboardSetText', async (text) => {
|
||||
await navigator.clipboard.writeText(text)
|
||||
return true
|
||||
})
|
||||
defineRuntime('WindowSetTitle', (title) => {
|
||||
document.title = title
|
||||
})
|
||||
defineRuntime('BrowserOpenURL', (url) => {
|
||||
window.open(url, '_blank', 'noopener, noreferrer')
|
||||
})
|
||||
}
|
||||
|
||||
if (!window.go) {
|
||||
window.go = {}
|
||||
window.go['backend_golang'] = {}
|
||||
window.go['backend_golang']['App'] = {}
|
||||
|
||||
// not implemented
|
||||
defineApp('AddToDownloadList', async () => {
|
||||
})
|
||||
defineApp('ContinueDownload', async () => {
|
||||
})
|
||||
defineApp('ConvertData', async () => {
|
||||
})
|
||||
defineApp('ConvertModel', async () => {
|
||||
})
|
||||
defineApp('ConvertSafetensors', async () => {
|
||||
})
|
||||
defineApp('CopyFile', async () => {
|
||||
})
|
||||
defineApp('DeleteFile', async () => {
|
||||
})
|
||||
defineApp('DepCheck', async () => {
|
||||
})
|
||||
defineApp('DownloadFile', async () => {
|
||||
})
|
||||
defineApp('GetPyError', async () => {
|
||||
})
|
||||
defineApp('InstallPyDep', async () => {
|
||||
})
|
||||
defineApp('IsPortAvailable', async () => {
|
||||
})
|
||||
defineApp('MergeLora', async () => {
|
||||
})
|
||||
defineApp('OpenFileFolder', async () => {
|
||||
})
|
||||
defineApp('PauseDownload', async () => {
|
||||
})
|
||||
defineApp('ReadFileInfo', async () => {
|
||||
})
|
||||
defineApp('RestartApp', async () => {
|
||||
})
|
||||
defineApp('StartServer', async () => {
|
||||
})
|
||||
defineApp('StartWebGPUServer', async () => {
|
||||
})
|
||||
defineApp('UpdateApp', async () => {
|
||||
})
|
||||
defineApp('WslCommand', async () => {
|
||||
})
|
||||
defineApp('WslEnable', async () => {
|
||||
})
|
||||
defineApp('WslInstallUbuntu', async () => {
|
||||
})
|
||||
defineApp('WslIsEnabled', async () => {
|
||||
})
|
||||
defineApp('WslStart', async () => {
|
||||
})
|
||||
defineApp('WslStop', async () => {
|
||||
})
|
||||
|
||||
// implemented
|
||||
defineApp('FileExists', async () => {
|
||||
return false
|
||||
})
|
||||
defineApp('GetPlatform', async () => {
|
||||
return 'web'
|
||||
})
|
||||
defineApp('ListDirFiles', async () => {
|
||||
return []
|
||||
})
|
||||
defineApp('OpenOpenFileDialog', webOpenOpenFileDialog)
|
||||
defineApp('OpenSaveFileDialog', async (filterPattern, defaultFileName, savedContent) => {
|
||||
const saver = await import('file-saver')
|
||||
saver.saveAs(new Blob([savedContent], { type: 'text/plain;charset=utf-8' }), defaultFileName)
|
||||
return ''
|
||||
})
|
||||
defineApp('OpenSaveFileDialogBytes', async (filterPattern, defaultFileName, savedContent) => {
|
||||
const saver = await import('file-saver')
|
||||
saver.saveAs(new Blob([new Uint8Array(savedContent)], { type: 'octet/stream' }), defaultFileName)
|
||||
return ''
|
||||
})
|
||||
defineApp('ReadJson', async (fileName) => {
|
||||
return JSON.parse(localStorage.getItem(fileName))
|
||||
})
|
||||
defineApp('SaveJson', async (fileName, data) => {
|
||||
localStorage.setItem(fileName, JSON.stringify(data))
|
||||
})
|
||||
}
|
||||
@@ -1,13 +1,62 @@
|
||||
import {defineConfig} from 'vite';
|
||||
// @ts-ignore
|
||||
import { dependencies } from './package.json';
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
import {visualizer} from 'rollup-plugin-visualizer';
|
||||
import { visualizer } from 'rollup-plugin-visualizer';
|
||||
import topLevelAwait from 'vite-plugin-top-level-await';
|
||||
|
||||
// dependencies that exist anywhere
|
||||
const vendor = [
|
||||
'react', 'react-dom', 'react-router', 'react-router-dom',
|
||||
'@fluentui/react-icons',
|
||||
'mobx', 'mobx-react-lite',
|
||||
'i18next', 'react-i18next',
|
||||
'usehooks-ts', 'react-toastify',
|
||||
'classnames'
|
||||
];
|
||||
|
||||
const embedded = [
|
||||
// split @fluentui/react-components by components
|
||||
'@fluentui/react-components',
|
||||
|
||||
// dependencies that exist in single component
|
||||
'react-beautiful-dnd',
|
||||
'@magenta/music', 'html-midi-player',
|
||||
'react-markdown', 'rehype-highlight', 'rehype-raw', 'remark-breaks', 'remark-gfm'
|
||||
];
|
||||
|
||||
function renderChunks(deps: Record<string, string>) {
|
||||
let chunks = {};
|
||||
Object.keys(deps).forEach((key) => {
|
||||
if ([...vendor, ...embedded].includes(key)) return;
|
||||
chunks[key] = [key];
|
||||
});
|
||||
return chunks;
|
||||
}
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react(),
|
||||
plugins: [
|
||||
react(),
|
||||
visualizer({
|
||||
template: 'treemap',
|
||||
gzipSize: true,
|
||||
brotliSize: true
|
||||
})]
|
||||
}),
|
||||
topLevelAwait({
|
||||
promiseExportName: '__tla',
|
||||
promiseImportName: i => `__tla_${i}`
|
||||
})
|
||||
],
|
||||
build: {
|
||||
chunkSizeWarningLimit: 3000,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks: {
|
||||
vendor,
|
||||
...renderChunks(dependencies)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
2
frontend/wailsjs/go/backend_golang/App.d.ts
generated
vendored
2
frontend/wailsjs/go/backend_golang/App.d.ts
generated
vendored
@@ -52,7 +52,7 @@ export function RestartApp():Promise<void>;
|
||||
|
||||
export function SaveJson(arg1:string,arg2:any):Promise<void>;
|
||||
|
||||
export function StartServer(arg1:string,arg2:number,arg3:string,arg4:boolean):Promise<string>;
|
||||
export function StartServer(arg1:string,arg2:number,arg3:string,arg4:boolean,arg5:boolean):Promise<string>;
|
||||
|
||||
export function StartWebGPUServer(arg1:number,arg2:string):Promise<string>;
|
||||
|
||||
|
||||
4
frontend/wailsjs/go/backend_golang/App.js
generated
4
frontend/wailsjs/go/backend_golang/App.js
generated
@@ -102,8 +102,8 @@ export function SaveJson(arg1, arg2) {
|
||||
return window['go']['backend_golang']['App']['SaveJson'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StartServer(arg1, arg2, arg3, arg4) {
|
||||
return window['go']['backend_golang']['App']['StartServer'](arg1, arg2, arg3, arg4);
|
||||
export function StartServer(arg1, arg2, arg3, arg4, arg5) {
|
||||
return window['go']['backend_golang']['App']['StartServer'](arg1, arg2, arg3, arg4, arg5);
|
||||
}
|
||||
|
||||
export function StartWebGPUServer(arg1, arg2) {
|
||||
|
||||
1
main.go
1
main.go
@@ -67,6 +67,7 @@ var components embed.FS
|
||||
|
||||
func main() {
|
||||
if buildInfo, ok := debug.ReadBuildInfo(); !ok || strings.Contains(buildInfo.String(), "-ldflags") {
|
||||
backend.CopyEmbed(assets)
|
||||
os.RemoveAll("./py310/Lib/site-packages/cyac-1.7.dist-info")
|
||||
backend.CopyEmbed(cyac)
|
||||
backend.CopyEmbed(cyacInfo)
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.4.9",
|
||||
"version": "1.5.3",
|
||||
"introduction": {
|
||||
"en": "RWKV is an open-source, commercially usable large language model with high flexibility and great potential for development.\n### About This Tool\nThis tool aims to lower the barrier of entry for using large language models, making it accessible to everyone. It provides fully automated dependency and model management. You simply need to click and run, following the instructions, to deploy a local large language model. The tool itself is very compact and only requires a single executable file for one-click deployment.\nAdditionally, this tool offers an interface that is fully compatible with the OpenAI API. This means you can use any ChatGPT client as a client for RWKV, enabling capability expansion beyond just chat functionality.\n### Preset Configuration Rules at the Bottom\nThis tool comes with a series of preset configurations to reduce complexity. The naming rules for each configuration represent the following in order: device - required VRAM/memory - model size - model language.\nFor example, \"GPU-8G-3B-EN\" indicates that this configuration is for a graphics card with 8GB of VRAM, a model size of 3 billion parameters, and it uses an English language model.\nLarger model sizes have higher performance and VRAM requirements. Among configurations with the same model size, those with higher VRAM usage will have faster runtime.\nFor example, if you have 12GB of VRAM but running the \"GPU-12G-7B-EN\" configuration is slow, you can downgrade to \"GPU-8G-3B-EN\" for a significant speed improvement.\n### About RWKV\nRWKV is an RNN with Transformer-level LLM performance, which can also be directly trained like a GPT transformer (parallelizable). And it's 100% attention-free. You only need the hidden state at position t to compute the state at position t+1. You can use the \"GPT\" mode to quickly compute the hidden state for the \"RNN\" mode.<br/>So it's combining the best of RNN and transformer - great performance, fast inference, saves VRAM, fast training, \"infinite\" ctx_len, and free sentence embedding (using the final hidden state).",
|
||||
"zh": "RWKV是一个开源且允许商用的大语言模型,灵活性很高且极具发展潜力。\n### 关于本工具\n本工具旨在降低大语言模型的使用门槛,做到人人可用,本工具提供了全自动化的依赖和模型管理,你只需要直接点击运行,跟随引导,即可完成本地大语言模型的部署,工具本身体积极小,只需要一个exe即可完成一键部署。\n此外,本工具提供了与OpenAI API完全兼容的接口,这意味着你可以把任意ChatGPT客户端用作RWKV的客户端,实现能力拓展,而不局限于聊天。\n### 底部的预设配置规则\n本工具内置了一系列预设配置,以降低使用难度,每个配置名的规则,依次代表着:设备-所需显存/内存-模型规模-模型语言。\n例如,GPU-8G-3B-CN,表示该配置用于显卡,需要8G显存,模型规模为30亿参数,使用的是中文模型。\n模型规模越大,性能要求越高,显存要求也越高,而同样模型规模的配置中,显存占用越高的,运行速度越快。\n例如当你有12G显存,但运行GPU-12G-7B-CN配置速度比较慢,可降级成GPU-8G-3B-CN,将会大幅提速。\n### 关于RWKV\nRWKV是具有Transformer级别LLM性能的RNN,也可以像GPT Transformer一样直接进行训练(可并行化)。而且它是100% attention-free的。你只需在位置t处获得隐藏状态即可计算位置t + 1处的状态。你可以使用“GPT”模式快速计算用于“RNN”模式的隐藏状态。\n因此,它将RNN和Transformer的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。"
|
||||
@@ -15,6 +15,32 @@
|
||||
}
|
||||
],
|
||||
"models": [
|
||||
{
|
||||
"name": "RWKV-5-World-0.1B-v1-20230803-ctx4096.pth",
|
||||
"desc": {
|
||||
"en": "RWKV-5 Global Languages 0.1B v1",
|
||||
"zh": "RWKV-5 全球语言 0.1B v1",
|
||||
"ja": "RWKV-5 グローバル言語 0.1B v1"
|
||||
},
|
||||
"size": 385598386,
|
||||
"SHA256": "c844a3ee05bcb9065848cb05b10c48a3f381f5ac1953aad89e156ecdf31d7703",
|
||||
"lastUpdated": "2023-08-03T15:18:46",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-0.1B-v1-20230803-ctx4096.pth?download=true",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-0.1B-v1-20230803-ctx4096.pth?download=true"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-5-World-0.4B-v2-20231113-ctx4096.pth",
|
||||
"desc": {
|
||||
"en": "RWKV-5 Global Languages 0.4B v2",
|
||||
"zh": "RWKV-5 全球语言 0.4B v2",
|
||||
"ja": "RWKV-5 グローバル言語 0.4B v2"
|
||||
},
|
||||
"size": 923523954,
|
||||
"SHA256": "5a288c54c7f30b0e2d4af23991133fad2af2d5e59ec7ad850ffe78054a5e4f92",
|
||||
"lastUpdated": "2023-11-14T01:23:49",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-0.4B-v2-20231113-ctx4096.pth?download=true",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-0.4B-v2-20231113-ctx4096.pth?download=true"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-5-World-1B5-v2-20231025-ctx4096.pth",
|
||||
"desc": {
|
||||
@@ -28,6 +54,32 @@
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-1B5-v2-20231025-ctx4096.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-1B5-v2-20231025-ctx4096.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-5-World-3B-v2-20231113-ctx4096.pth",
|
||||
"desc": {
|
||||
"en": "RWKV-5 Global Languages 3B v2",
|
||||
"zh": "RWKV-5 全球语言 3B v2",
|
||||
"ja": "RWKV-5 グローバル言語 3B v2"
|
||||
},
|
||||
"size": 6126106674,
|
||||
"SHA256": "a4bd430343c6fd138b85bbc68bb20262d3a2f053ea57dc4b41078269af68ff9c",
|
||||
"lastUpdated": "2023-11-14T01:23:49",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-3B-v2-20231113-ctx4096.pth?download=true",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-3B-v2-20231113-ctx4096.pth?download=true"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-5-World-3B-v2-20231118-ctx16k.pth",
|
||||
"desc": {
|
||||
"en": "RWKV-5 Global Languages 3B v2 Ctx16k",
|
||||
"zh": "RWKV-5 全球语言 3B v2 16k上下文",
|
||||
"ja": "RWKV-5 グローバル言語 3B v2 16kコンテキスト"
|
||||
},
|
||||
"size": 6126106467,
|
||||
"SHA256": "efa5178d1c824b94ef17c6c9a456674e5581a8be832becbda9aba4dc533f88c2",
|
||||
"lastUpdated": "2023-11-19T04:21:04",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-3B-v2-20231118-ctx16k.pth?download=true",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-3B-v2-20231118-ctx16k.pth?download=true"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-World-CHNtuned-0.1B-v1-20230617-ctx4096.pth",
|
||||
"desc": {
|
||||
|
||||
Reference in New Issue
Block a user