Compare commits

...

22 Commits

Author SHA1 Message Date
josc146
5853b8ca8d release v1.1.9 2023-06-06 00:13:35 +08:00
josc146
ebfc0ce672 add ResetConfigsButton to Home Page 2023-06-06 00:12:58 +08:00
josc146
e62fcd152a Improved cross-platform interaction 2023-06-05 23:11:22 +08:00
josc146
9bd9b9ecbd add requirements_without_cyac.txt 2023-06-05 22:58:56 +08:00
josc146
17faa9c5b8 dev config 2023-06-05 22:57:01 +08:00
josc146
4cd445bf77 OpenFileFolder for linux 2023-06-05 22:55:06 +08:00
josc146
4fb35845b0 improve the built-in download function, enhance the logic robustness and reliability in adverse network environments 2023-06-05 22:54:36 +08:00
josc146
f373f1caa8 release v1.1.8 2023-06-04 11:53:50 +08:00
josc146
4e75531651 fix the crash issue caused by temperature being 0 2023-06-04 11:53:33 +08:00
josc146
539c538d65 update manifest.json 2023-06-03 22:14:11 +08:00
josc146
d90186db33 update logo 2023-06-03 21:35:20 +08:00
josc146
a2d8729ae3 release v1.1.7 2023-06-03 20:34:51 +08:00
josc146
edc6ac7297 chore 2023-06-03 20:34:33 +08:00
josc146
e89e23621c update readme 2023-06-03 20:28:21 +08:00
josc146
6b9ec4c6fa add strategy guides 2023-06-03 20:18:57 +08:00
josc146
ced0966ffc display current strategy 2023-06-03 19:38:24 +08:00
josc146
966b912013 improve logs 2023-06-03 19:28:37 +08:00
josc146
dc71054e61 improve logs 2023-06-03 17:36:50 +08:00
josc146
408f3c1a4d release v1.1.6 2023-06-03 17:15:11 +08:00
josc146
38b775c937 add logs 2023-06-03 17:12:59 +08:00
josc146
f2ec1067bf MX, Tesla P, Quadro P, NVIDIA P, TITAN X, RTX A series, TITAN RTX and RTX TITAN Ada 2023-06-03 12:46:56 +08:00
josc146
b01584c49e chore 2023-06-03 00:10:31 +08:00
30 changed files with 433 additions and 152 deletions

2
.gitignore vendored
View File

@@ -17,3 +17,5 @@ __pycache__
*.exe
*.old
.DS_Store
*.log.*
*.log

19
.vscode/launch.json vendored
View File

@@ -10,9 +10,24 @@
"name": "Python",
"type": "python",
"request": "launch",
"program": "./backend-python/main.py",
"program": "${workspaceFolder}/backend-python/main.py",
"console": "integratedTerminal",
"justMyCode": false,
"justMyCode": false
},
{
"name": "Golang",
"type": "go",
"request": "launch",
"mode": "exec",
"program": "${workspaceFolder}/build/bin/testwails.exe",
"console": "integratedTerminal",
"preLaunchTask": "build dev"
},
{
"name": "Frontend",
"type": "node-terminal",
"request": "launch",
"command": "wails dev -browser"
}
]
}

40
.vscode/tasks.json vendored Normal file
View File

@@ -0,0 +1,40 @@
{
"version": "2.0.0",
"tasks": [
{
"label": "build dev",
"type": "shell",
"options": {
"cwd": "${workspaceFolder}",
"env": {
"CGO_ENABLED": "1"
}
},
"osx": {
"options": {
"env": {
"CGO_CFLAGS": "-mmacosx-version-min=10.13",
"CGO_LDFLAGS": "-framework UniformTypeIdentifiers -mmacosx-version-min=10.13"
}
}
},
"windows": {
"options": {
"env": {
"CGO_ENABLED": "0"
}
}
},
"command": "go",
"args": [
"build",
"-tags",
"dev",
"-gcflags",
"all=-N -l",
"-o",
"build/bin/testwails.exe"
]
}
]
}

View File

@@ -1,16 +1,22 @@
ifeq ($(OS), Windows_NT)
build: build-windows
else
else ifeq ($(shell uname -s), Darwin)
build: build-macos
else
build: build-linux
endif
build-windows:
@echo ---- build for windows
wails build -upx -ldflags "-s -w"
wails build -upx -ldflags "-s -w" -platform windows/amd64
build-macos:
@echo ---- build for macos
wails build -ldflags "-s -w"
wails build -ldflags "-s -w" -platform darwin/universal
build-linux:
@echo ---- build for linux
wails build -upx -ldflags "-s -w" -platform linux/amd64
dev:
wails dev

View File

@@ -14,7 +14,7 @@ API兼容的接口这意味着一切ChatGPT客户端都是RWKV客户端。
[English](README.md) | 简体中文
[视频演示](https://www.bilibili.com/video/BV1hM4y1v76R) | [疑难解答](https://www.bilibili.com/read/cv23921171) | [预览](#Preview) | [下载][download-url]
[视频演示](https://www.bilibili.com/video/BV1hM4y1v76R) | [疑难解答](https://www.bilibili.com/read/cv23921171) | [预览](#Preview) | [下载][download-url] | [懒人包](https://pan.baidu.com/s/1wchIUHgne3gncIiLIeKBEQ?pwd=1111)
[license-image]: http://img.shields.io/badge/license-MIT-blue.svg

View File

@@ -1,6 +1,7 @@
package backend_golang
import (
"context"
"path/filepath"
"time"
@@ -18,6 +19,7 @@ func (a *App) DownloadFile(path string, url string) error {
type DownloadStatus struct {
resp *grab.Response
cancel context.CancelFunc
Name string `json:"name"`
Path string `json:"path"`
Url string `json:"url"`
@@ -29,7 +31,7 @@ type DownloadStatus struct {
Done bool `json:"done"`
}
var downloadList []DownloadStatus
var downloadList []*DownloadStatus
func existsInDownloadList(url string) bool {
for _, ds := range downloadList {
@@ -41,49 +43,58 @@ func existsInDownloadList(url string) bool {
}
func (a *App) PauseDownload(url string) {
for i, ds := range downloadList {
for _, ds := range downloadList {
if ds.Url == url {
if ds.resp != nil {
ds.resp.Cancel()
}
downloadList[i] = DownloadStatus{
resp: ds.resp,
Name: ds.Name,
Path: ds.Path,
Url: ds.Url,
Downloading: false,
if ds.cancel != nil {
ds.cancel()
}
ds.resp = nil
ds.Downloading = false
ds.Speed = 0
break
}
}
}
func (a *App) ContinueDownload(url string) {
for i, ds := range downloadList {
for _, ds := range downloadList {
if ds.Url == url {
client := grab.NewClient()
req, _ := grab.NewRequest(ds.Path, ds.Url)
resp := client.Do(req)
if !ds.Downloading && ds.resp == nil && !ds.Done {
ds.Downloading = true
downloadList[i] = DownloadStatus{
resp: resp,
Name: ds.Name,
Path: ds.Path,
Url: ds.Url,
Downloading: true,
req, err := grab.NewRequest(ds.Path, ds.Url)
if err != nil {
ds.Downloading = false
break
}
// if PauseDownload() is called before the request finished, ds.Downloading will be false
// if the user keeps clicking pause and resume, it may result in multiple requests being successfully downloaded at the same time
// so we have to create a context and cancel it when PauseDownload() is called
ctx, cancel := context.WithCancel(context.Background())
ds.cancel = cancel
req = req.WithContext(ctx)
resp := grab.DefaultClient.Do(req)
if resp != nil && resp.HTTPResponse != nil &&
resp.HTTPResponse.StatusCode >= 200 && resp.HTTPResponse.StatusCode < 300 {
ds.resp = resp
} else {
ds.Downloading = false
}
}
break
}
}
}
func (a *App) AddToDownloadList(path string, url string) {
if !existsInDownloadList(url) {
downloadList = append(downloadList, DownloadStatus{
downloadList = append(downloadList, &DownloadStatus{
resp: nil,
Name: filepath.Base(path),
Path: a.exDir + path,
Url: url,
Downloading: true,
Downloading: false,
})
a.ContinueDownload(url)
} else {
@@ -96,32 +107,17 @@ func (a *App) downloadLoop() {
go func() {
for {
<-ticker.C
for i, ds := range downloadList {
transferred := int64(0)
size := int64(0)
speed := float64(0)
progress := float64(0)
downloading := ds.Downloading
done := false
for _, ds := range downloadList {
if ds.resp != nil {
transferred = ds.resp.BytesComplete()
size = ds.resp.Size()
speed = ds.resp.BytesPerSecond()
progress = 100 * ds.resp.Progress()
downloading = !ds.resp.IsComplete()
done = ds.resp.Progress() == 1
}
downloadList[i] = DownloadStatus{
resp: ds.resp,
Name: ds.Name,
Path: ds.Path,
Url: ds.Url,
Transferred: transferred,
Size: size,
Speed: speed,
Progress: progress,
Downloading: downloading,
Done: done,
ds.Transferred = ds.resp.BytesComplete()
ds.Size = ds.resp.Size()
ds.Speed = ds.resp.BytesPerSecond()
ds.Progress = 100 * ds.resp.Progress()
ds.Downloading = !ds.resp.IsComplete()
ds.Done = ds.resp.Progress() == 1
if !ds.Downloading {
ds.resp = nil
}
}
}
runtime.EventsEmit(a.ctx, "downloadList", downloadList)

View File

@@ -140,7 +140,12 @@ func (a *App) OpenFileFolder(path string) error {
}
return nil
case "linux":
println("unsupported OS")
cmd := exec.Command("xdg-open", absPath)
err := cmd.Run()
if err != nil {
return err
}
return nil
}
return errors.New("unsupported OS")
}

View File

@@ -1,7 +1,6 @@
import GPUtil
import torch
import rwkv
import langchain
import fastapi
import uvicorn
import sse_starlette

View File

@@ -4,17 +4,18 @@ import sys
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import psutil
from fastapi import FastAPI
from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware
import uvicorn
from utils.rwkv import *
from utils.torch import *
from utils.ngrok import *
from utils.log import log_middleware
from routes import completion, config, state_cache
import global_var
app = FastAPI()
app = FastAPI(dependencies=[Depends(log_middleware)])
app.add_middleware(
CORSMiddleware,
@@ -42,7 +43,7 @@ def init():
@app.get("/")
def read_root():
return {"Hello": "World!", "pid": os.getpid()}
return {"Hello": "World!"}
@app.post("/exit")
@@ -60,7 +61,7 @@ def debug():
strategy="cuda fp16",
tokens_path="20B_tokenizer.json",
)
d = model.tokenizer.decode([])
d = model.pipeline.decode([])
print(d)

Binary file not shown.

View File

@@ -7,6 +7,7 @@ from fastapi import APIRouter, Request, status, HTTPException
from sse_starlette.sse import EventSourceResponse
from pydantic import BaseModel
from utils.rwkv import *
from utils.log import quick_log
import global_var
router = APIRouter()
@@ -26,6 +27,8 @@ class ChatCompletionBody(ModelConfigBody):
completion_lock = Lock()
requests_num = 0
@router.post("/v1/chat/completions")
@router.post("/chat/completions")
@@ -106,12 +109,32 @@ The following is a coherent verbose detailed conversation between a girl named {
completion_text += f"{bot}{interface}"
async def eval_rwkv():
global requests_num
requests_num = requests_num + 1
quick_log(request, None, "Start Waiting. RequestsNum: " + str(requests_num))
while completion_lock.locked():
if await request.is_disconnected():
requests_num = requests_num - 1
print(f"{request.client} Stop Waiting (Lock)")
quick_log(
request,
None,
"Stop Waiting (Lock). RequestsNum: " + str(requests_num),
)
return
await asyncio.sleep(0.1)
else:
completion_lock.acquire()
if await request.is_disconnected():
completion_lock.release()
requests_num = requests_num - 1
print(f"{request.client} Stop Waiting (Lock)")
quick_log(
request,
None,
"Stop Waiting (Lock). RequestsNum: " + str(requests_num),
)
return
set_rwkv_config(model, global_var.get(global_var.Model_Config))
set_rwkv_config(model, body)
if body.stream:
@@ -135,9 +158,21 @@ The following is a coherent verbose detailed conversation between a girl named {
}
)
# torch_gc()
requests_num = requests_num - 1
completion_lock.release()
if await request.is_disconnected():
print(f"{request.client} Stop Waiting")
quick_log(
request,
body,
response + "\nStop Waiting. RequestsNum: " + str(requests_num),
)
return
quick_log(
request,
body,
response + "\nFinished. RequestsNum: " + str(requests_num),
)
yield json.dumps(
{
"response": response,
@@ -161,9 +196,21 @@ The following is a coherent verbose detailed conversation between a girl named {
if await request.is_disconnected():
break
# torch_gc()
requests_num = requests_num - 1
completion_lock.release()
if await request.is_disconnected():
print(f"{request.client} Stop Waiting")
quick_log(
request,
body,
response + "\nStop Waiting. RequestsNum: " + str(requests_num),
)
return
quick_log(
request,
body,
response + "\nFinished. RequestsNum: " + str(requests_num),
)
yield {
"response": response,
"model": "rwkv",
@@ -182,7 +229,10 @@ The following is a coherent verbose detailed conversation between a girl named {
if body.stream:
return EventSourceResponse(eval_rwkv())
else:
return await eval_rwkv().__anext__()
try:
return await eval_rwkv().__anext__()
except StopAsyncIteration:
return None
class CompletionBody(ModelConfigBody):
@@ -203,12 +253,32 @@ async def completions(body: CompletionBody, request: Request):
raise HTTPException(status.HTTP_400_BAD_REQUEST, "prompt not found")
async def eval_rwkv():
global requests_num
requests_num = requests_num + 1
quick_log(request, None, "Start Waiting. RequestsNum: " + str(requests_num))
while completion_lock.locked():
if await request.is_disconnected():
requests_num = requests_num - 1
print(f"{request.client} Stop Waiting (Lock)")
quick_log(
request,
None,
"Stop Waiting (Lock). RequestsNum: " + str(requests_num),
)
return
await asyncio.sleep(0.1)
else:
completion_lock.acquire()
if await request.is_disconnected():
completion_lock.release()
requests_num = requests_num - 1
print(f"{request.client} Stop Waiting (Lock)")
quick_log(
request,
None,
"Stop Waiting (Lock). RequestsNum: " + str(requests_num),
)
return
set_rwkv_config(model, global_var.get(global_var.Model_Config))
set_rwkv_config(model, body)
if body.stream:
@@ -229,9 +299,21 @@ async def completions(body: CompletionBody, request: Request):
}
)
# torch_gc()
requests_num = requests_num - 1
completion_lock.release()
if await request.is_disconnected():
print(f"{request.client} Stop Waiting")
quick_log(
request,
body,
response + "\nStop Waiting. RequestsNum: " + str(requests_num),
)
return
quick_log(
request,
body,
response + "\nFinished. RequestsNum: " + str(requests_num),
)
yield json.dumps(
{
"response": response,
@@ -252,9 +334,21 @@ async def completions(body: CompletionBody, request: Request):
if await request.is_disconnected():
break
# torch_gc()
requests_num = requests_num - 1
completion_lock.release()
if await request.is_disconnected():
print(f"{request.client} Stop Waiting")
quick_log(
request,
body,
response + "\nStop Waiting. RequestsNum: " + str(requests_num),
)
return
quick_log(
request,
body,
response + "\nFinished. RequestsNum: " + str(requests_num),
)
yield {
"response": response,
"model": "rwkv",
@@ -270,4 +364,7 @@ async def completions(body: CompletionBody, request: Request):
if body.stream:
return EventSourceResponse(eval_rwkv())
else:
return await eval_rwkv().__anext__()
try:
return await eval_rwkv().__anext__()
except StopAsyncIteration:
return None

View File

@@ -0,0 +1,32 @@
import json
import logging
from typing import Any
from fastapi import Request
logger = logging.getLogger()
logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s\n%(message)s")
fh = logging.handlers.RotatingFileHandler(
"api.log", mode="a", maxBytes=3 * 1024 * 1024, backupCount=3
)
fh.setFormatter(formatter)
logger.addHandler(fh)
def quick_log(request: Request, body: Any, response: str):
logger.info(
f"Client: {request.client}\nUrl: {request.url}\n"
+ (
f"Body: {json.dumps(body.__dict__, default=vars, ensure_ascii=False)}\n"
if body
else ""
)
+ (f"Response:\n{response}\n" if response else "")
)
async def log_middleware(request: Request):
logger.info(
f"Client: {request.client}\nUrl: {request.url}\nBody: {await request.body()}\n"
)

View File

@@ -204,7 +204,10 @@ def set_rwkv_config(model: RWKV, body: ModelConfigBody):
if body.max_tokens is not None:
model.max_tokens_per_generation = body.max_tokens
if body.temperature is not None:
model.temperature = body.temperature
if body.temperature < 0.1:
model.temperature = 0.1
else:
model.temperature = body.temperature
if body.top_p is not None:
model.top_p = body.top_p
if body.presence_penalty is not None:

BIN
build/appicon.png vendored

Binary file not shown.

Before

Width:  |  Height:  |  Size: 102 KiB

After

Width:  |  Height:  |  Size: 120 KiB

BIN
build/windows/icon.ico vendored

Binary file not shown.

Before

Width:  |  Height:  |  Size: 147 KiB

After

Width:  |  Height:  |  Size: 167 KiB

View File

@@ -88,6 +88,7 @@
"Downloads": "下载",
"Pause": "暂停",
"Continue": "继续",
"Resume": "继续",
"Check": "查看",
"Model file not found": "模型文件不存在",
"Can not find download url": "找不到下载地址",
@@ -134,8 +135,10 @@
"Advanced": "高级",
"Custom Python Path": "自定义Python路径",
"Custom Models Path": "自定义模型路径",
"MacOS is not supported yet, please convert manually.": "暂不支持MacOS, 请手动转换",
"Microsoft Visual C++ Redistributable is not installed, would you like to download it?": "微软VC++组件未安装, 是否下载?",
"Path Cannot Contain Space": "路径不能包含空格",
"Failed to switch model, please try starting the program with administrator privileges.": "切换模型失败, 请尝试以管理员权限启动程序"
"Failed to switch model, please try starting the program with administrator privileges.": "切换模型失败, 请尝试以管理员权限启动程序",
"Current Strategy": "当前Strategy",
"MacOS is not yet supported for performing this operation, please do it manually.": "MacOS尚未支持此操作, 请手动执行",
"Linux is not yet supported for performing this operation, please do it manually.": "Linux尚未支持此操作, 请手动执行"
}

View File

Before

Width:  |  Height:  |  Size: 4.4 KiB

After

Width:  |  Height:  |  Size: 4.4 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 115 KiB

View File

@@ -0,0 +1,46 @@
import { FC, ReactElement } from 'react';
import {
Button,
Dialog,
DialogActions,
DialogBody,
DialogContent,
DialogSurface,
DialogTitle,
DialogTrigger
} from '@fluentui/react-components';
import { ToolTipButton } from './ToolTipButton';
import { useTranslation } from 'react-i18next';
export const DialogButton: FC<{
icon: ReactElement,
tooltip: string,
title: string,
contentText: string,
onConfirm: () => void
}> = ({ tooltip, icon, title, contentText, onConfirm }) => {
const { t } = useTranslation();
return <Dialog>
<DialogTrigger disableButtonEnhancement>
<ToolTipButton desc={tooltip} icon={icon} />
</DialogTrigger>
<DialogSurface>
<DialogBody>
<DialogTitle>{title}</DialogTitle>
<DialogContent>
{contentText}
</DialogContent>
<DialogActions>
<DialogTrigger disableButtonEnhancement>
<Button appearance="secondary">{t('Cancel')}</Button>
</DialogTrigger>
<DialogTrigger disableButtonEnhancement>
<Button appearance="primary" onClick={onConfirm}>{t('Confirm')}
</Button>
</DialogTrigger>
</DialogActions>
</DialogBody>
</DialogSurface>
</Dialog>;
};

View File

@@ -5,17 +5,23 @@ import classnames from 'classnames';
export const Labeled: FC<{
label: string;
desc?: string | null,
descComponent?: ReactElement,
content: ReactElement,
flex?: boolean,
spaceBetween?: boolean,
breakline?: boolean
breakline?: boolean,
onMouseEnter?: () => void
onMouseLeave?: () => void
}> = ({
label,
desc,
descComponent,
content,
flex,
spaceBetween,
breakline
breakline,
onMouseEnter,
onMouseLeave
}) => {
return (
<div className={classnames(
@@ -24,11 +30,11 @@ export const Labeled: FC<{
breakline ? 'flex-col' : '',
spaceBetween && 'justify-between')
}>
{desc ?
<Tooltip content={desc} showDelay={0} hideDelay={0} relationship="description">
<Label>{label}</Label>
{(desc || descComponent) ?
<Tooltip content={descComponent ? descComponent : desc!} showDelay={0} hideDelay={0} relationship="description">
<Label onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>{label}</Label>
</Tooltip> :
<Label>{label}</Label>
<Label onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>{label}</Label>
}
{content}
</div>

View File

@@ -0,0 +1,17 @@
import React, { FC } from 'react';
import { DialogButton } from './DialogButton';
import { useTranslation } from 'react-i18next';
import { ArrowReset20Regular } from '@fluentui/react-icons';
import commonStore from '../stores/commonStore';
import { defaultModelConfigs } from '../pages/Configs';
export const ResetConfigsButton: FC<{ afterConfirm?: () => void }> = ({ afterConfirm }) => {
const { t } = useTranslation();
return <DialogButton icon={<ArrowReset20Regular />} tooltip={t('Reset All Configs')} title={t('Reset All Configs')}
contentText={t('Are you sure you want to reset all configs? This will obtain the latest preset configs, but will override your custom configs and cannot be undone.')}
onConfirm={() => {
commonStore.setModelConfigs(defaultModelConfigs, false);
commonStore.setCurrentConfigIndex(0, true);
afterConfirm?.();
}} />;
};

View File

@@ -142,23 +142,28 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
});
let customCudaFile = '';
if (modelConfig.modelParameters.device != 'CPU' && modelConfig.modelParameters.useCustomCuda) {
customCudaFile = getSupportedCustomCudaFile();
if (customCudaFile && commonStore.platform === 'windows') {
FileExists('./py310/Lib/site-packages/rwkv/model.py').then((exist) => {
// defensive measure. As Python has already been launched, will only take effect the next time it runs.
if (!exist) CopyFile('./backend-python/wkv_cuda_utils/wkv_cuda_model.py', './py310/Lib/site-packages/rwkv/model.py');
});
await CopyFile(customCudaFile, './py310/Lib/site-packages/rwkv/wkv_cuda.pyd').catch(() => {
FileExists('./py310/Lib/site-packages/rwkv/wkv_cuda.pyd').then((exist) => {
if (!exist) {
customCudaFile = '';
toast(t('Failed to copy custom cuda file'), { type: 'error' });
}
if ((modelConfig.modelParameters.device === 'CUDA' || modelConfig.modelParameters.device === 'Custom')
&& modelConfig.modelParameters.useCustomCuda) {
if (commonStore.platform === 'windows') {
customCudaFile = getSupportedCustomCudaFile();
if (customCudaFile) {
FileExists('./py310/Lib/site-packages/rwkv/model.py').then((exist) => {
// defensive measure. As Python has already been launched, will only take effect the next time it runs.
if (!exist) CopyFile('./backend-python/wkv_cuda_utils/wkv_cuda_model.py', './py310/Lib/site-packages/rwkv/model.py');
});
});
} else
toast(t('Supported custom cuda file not found'), { type: 'warning' });
await CopyFile(customCudaFile, './py310/Lib/site-packages/rwkv/wkv_cuda.pyd').catch(() => {
FileExists('./py310/Lib/site-packages/rwkv/wkv_cuda.pyd').then((exist) => {
if (!exist) {
customCudaFile = '';
toast(t('Failed to copy custom cuda file'), { type: 'error' });
}
});
});
} else
toast(t('Supported custom cuda file not found'), { type: 'warning' });
} else {
customCudaFile = 'any';
}
}
switchModel({
@@ -179,7 +184,10 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
}
}).catch(() => {
commonStore.setStatus({ status: ModelStatus.Offline });
toast(t('Failed to switch model, please try starting the program with administrator privileges.'), { type: 'error' });
if (commonStore.platform === 'windows')
toast(t('Failed to switch model, please try starting the program with administrator privileges.'), { type: 'error' });
else
toast(t('Failed to switch model'), { type: 'error' });
});
}
}).catch(() => {

View File

@@ -6,7 +6,7 @@ import App from './App';
import { HashRouter } from 'react-router-dom';
import { startup } from './startup';
import './_locales/i18n-react';
import { WindowSetAlwaysOnTop } from '../wailsjs/runtime';
import { WindowShow } from '../wailsjs/runtime';
startup().then(() => {
const container = document.getElementById('root');
@@ -20,6 +20,5 @@ startup().then(() => {
);
// force display the window
WindowSetAlwaysOnTop(true);
WindowSetAlwaysOnTop(false);
WindowShow();
});

View File

@@ -7,7 +7,7 @@ import { v4 as uuid } from 'uuid';
import classnames from 'classnames';
import { fetchEventSource } from '@microsoft/fetch-event-source';
import { ConversationPair, getConversationPairs, Record } from '../utils/get-conversation-pairs';
import logo from '../../../build/appicon.jpg';
import logo from '../assets/images/logo.jpg';
import MarkdownRender from '../components/MarkdownRender';
import { ToolTipButton } from '../components/ToolTipButton';
import { ArrowCircleUp28Regular, Delete28Regular, RecordStop28Regular } from '@fluentui/react-icons';

View File

@@ -1,26 +1,5 @@
import {
Button,
Dialog,
DialogActions,
DialogBody,
DialogContent,
DialogSurface,
DialogTitle,
DialogTrigger,
Dropdown,
Input,
Label,
Option,
Select,
Switch
} from '@fluentui/react-components';
import {
AddCircle20Regular,
ArrowReset20Regular,
DataUsageSettings20Regular,
Delete20Regular,
Save20Regular
} from '@fluentui/react-icons';
import { Dropdown, Input, Label, Option, Select, Switch, Text } from '@fluentui/react-components';
import { AddCircle20Regular, DataUsageSettings20Regular, Delete20Regular, Save20Regular } from '@fluentui/react-icons';
import React, { FC } from 'react';
import { Section } from '../components/Section';
import { Labeled } from '../components/Labeled';
@@ -38,6 +17,9 @@ import { ConvertModel, FileExists } from '../../wailsjs/go/backend_golang/App';
import { getStrategy, refreshLocalModels } from '../utils';
import { useTranslation } from 'react-i18next';
import { WindowShow } from '../../wailsjs/runtime/runtime';
import strategyImg from '../assets/images/strategy.jpg';
import strategyZhImg from '../assets/images/strategy_zh.jpg';
import { ResetConfigsButton } from '../components/ResetConfigsButton';
export type ApiParameters = {
apiPort: number
@@ -632,6 +614,7 @@ export const Configs: FC = observer(() => {
const { t } = useTranslation();
const [selectedIndex, setSelectedIndex] = React.useState(commonStore.currentModelConfigIndex);
const [selectedConfig, setSelectedConfig] = React.useState(commonStore.modelConfigs[selectedIndex]);
const [displayStrategyImg, setDisplayStrategyImg] = React.useState(false);
const navigate = useNavigate();
const port = selectedConfig.apiParameters.apiPort;
@@ -700,31 +683,10 @@ export const Configs: FC = observer(() => {
commonStore.deleteModelConfig(selectedIndex);
updateSelectedIndex(Math.min(selectedIndex, commonStore.modelConfigs.length - 1));
}} />
<Dialog>
<DialogTrigger disableButtonEnhancement>
<ToolTipButton desc={t('Reset All Configs')} icon={<ArrowReset20Regular />} />
</DialogTrigger>
<DialogSurface>
<DialogBody>
<DialogTitle>{t('Reset All Configs')}</DialogTitle>
<DialogContent>
{t('Are you sure you want to reset all configs? This will obtain the latest preset configs, but will override your custom configs and cannot be undone.')}
</DialogContent>
<DialogActions>
<DialogTrigger disableButtonEnhancement>
<Button appearance="secondary">{t('Cancel')}</Button>
</DialogTrigger>
<DialogTrigger disableButtonEnhancement>
<Button appearance="primary" onClick={() => {
commonStore.setModelConfigs(defaultModelConfigs, false); // updateSelectedIndex() will save configs
updateSelectedIndex(0);
}}>{t('Confirm')}
</Button>
</DialogTrigger>
</DialogActions>
</DialogBody>
</DialogSurface>
</Dialog>
<ResetConfigsButton afterConfirm={() => {
setSelectedIndex(0);
setSelectedConfig(commonStore.modelConfigs[0]);
}} />
<ToolTipButton desc={t('Save Config')} icon={<Save20Regular />} onClick={onClickSave} />
</div>
<div className="flex items-center gap-4">
@@ -836,7 +798,10 @@ export const Configs: FC = observer(() => {
} />
<ToolTipButton text={t('Convert')} desc={t('Convert model with these configs')} onClick={async () => {
if (commonStore.platform == 'darwin') {
toast(t('MacOS is not supported yet, please convert manually.'), { type: 'info' });
toast(t('MacOS is not yet supported for performing this operation, please do it manually.'), { type: 'info' });
return;
} else if (commonStore.platform == 'linux') {
toast(t('Linux is not yet supported for performing this operation, please do it manually.'), { type: 'info' });
return;
}
@@ -895,9 +860,14 @@ export const Configs: FC = observer(() => {
</Dropdown>
} />
}
{selectedConfig.modelParameters.device == 'CUDA' && <div />}
{
selectedConfig.modelParameters.device == 'CUDA' && <Labeled label={t('Stored Layers')}
selectedConfig.modelParameters.device == 'CUDA' &&
<Labeled label={t('Current Strategy')}
content={<Text> {getStrategy(selectedConfig)} </Text>} />
}
{
selectedConfig.modelParameters.device == 'CUDA' &&
<Labeled label={t('Stored Layers')}
desc={t('Number of the neural network layers loaded into VRAM, the more you load, the faster the speed, but it consumes more VRAM.')}
content={
<ValuedSlider value={selectedConfig.modelParameters.storedLayers} min={0}
@@ -922,9 +892,16 @@ export const Configs: FC = observer(() => {
}} />
} />
}
{
displayStrategyImg &&
<img style={{ width: '80vh', height: 'auto', zIndex: 100 }} className="fixed left-0 top-0"
src={commonStore.settings.language === 'zh' ? strategyZhImg : strategyImg} />
}
{
selectedConfig.modelParameters.device == 'Custom' &&
<Labeled label="Strategy" desc="https://github.com/BlinkDL/ChatRWKV/blob/main/ChatRWKV-strategy.png"
<Labeled label="Strategy"
onMouseEnter={() => setDisplayStrategyImg(true)}
onMouseLeave={() => setDisplayStrategyImg(false)}
content={
<Input className="grow" placeholder="cuda:0 fp16 *20 -> cuda:1 fp16"
value={selectedConfig.modelParameters.customStrategy}

View File

@@ -53,7 +53,7 @@ export const Downloads: FC = observer(() => {
<div className="flex items-center gap-2">
<ProgressBar className="grow" value={status.progress} max={100} />
{!status.done &&
<ToolTipButton desc={status.downloading ? t('Pause') : t('Continue')}
<ToolTipButton desc={status.downloading ? t('Pause') : t('Resume')}
icon={status.downloading ? <Pause20Regular /> : <Play20Regular />}
onClick={() => {
if (status.downloading)

View File

@@ -17,6 +17,7 @@ import { ConfigSelector } from '../components/ConfigSelector';
import MarkdownRender from '../components/MarkdownRender';
import commonStore from '../stores/commonStore';
import { Completion } from './Completion';
import { ResetConfigsButton } from '../components/ResetConfigsButton';
export type IntroductionContent = { [lang: string]: string }
@@ -65,7 +66,8 @@ export const Home: FC = observer(() => {
return (
<div className="flex flex-col justify-between h-full">
<img className="rounded-xl select-none hidden sm:block" src={banner} />
<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">
@@ -85,6 +87,7 @@ export const Home: FC = observer(() => {
<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>

View File

@@ -309,9 +309,9 @@ export function toastWithButton(text: string, buttonText: string, onClickButton:
}
export function getSupportedCustomCudaFile() {
if ([' 10', ' 16', ' 20', ' 30', 'P40', 'P104', 'P106'].some(v => commonStore.status.device_name.includes(v)))
if ([' 10', ' 16', ' 20', ' 30', 'MX', 'Tesla P', 'Quadro P', 'NVIDIA P', 'TITAN X', 'TITAN RTX', 'RTX A'].some(v => commonStore.status.device_name.includes(v)))
return './backend-python/wkv_cuda_utils/wkv_cuda10_30.pyd';
else if ([' 40'].some(v => commonStore.status.device_name.includes(v)))
else if ([' 40', 'RTX TITAN Ada'].some(v => commonStore.status.device_name.includes(v)))
return './backend-python/wkv_cuda_utils/wkv_cuda40.pyd';
else
return '';

View File

@@ -1,5 +1,5 @@
{
"version": "1.1.5",
"version": "1.1.9",
"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的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。"
@@ -285,7 +285,8 @@
"SHA256": "ac36770931776c5aa179690918c9a3b0b5f4ebe3301ea3574a7e182209778788",
"lastUpdated": "2023-05-29T13:25:53",
"url": "https://huggingface.co/BlinkDL/rwkv-4-world/blob/main/RWKV-4-World-1.5B-v1-OnlyForTest_57%25_trained-20230529-ctx4096.pth",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-1.5B-v1-OnlyForTest_57%25_trained-20230529-ctx4096.pth"
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-1.5B-v1-OnlyForTest_57%25_trained-20230529-ctx4096.pth",
"hide": true
},
{
"name": "RWKV-4-World-3B-v1-OnlyForTest_35%_trained-20230529-ctx4096.pth",
@@ -297,7 +298,32 @@
"SHA256": "e4ee6e91a80d56de43bc79841f3a8be3b7b215d7d9788f79c467b9b1f7f03cb8",
"lastUpdated": "2023-05-29T13:25:53",
"url": "https://huggingface.co/BlinkDL/rwkv-4-world/blob/main/RWKV-4-World-3B-v1-OnlyForTest_35%25_trained-20230529-ctx4096.pth",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-3B-v1-OnlyForTest_35%25_trained-20230529-ctx4096.pth"
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-3B-v1-OnlyForTest_35%25_trained-20230529-ctx4096.pth",
"hide": true
},
{
"name": "RWKV-4-World-1.5B-v1-OnlyForTest_81%_trained-20230603-ctx4096.pth",
"desc": {
"en": "100+ Languages 1.5B v1 Test",
"zh": "100+ 语言 1.5B v1 测试"
},
"size": 3155281581,
"SHA256": "044fb10daa71f4c012493ac8ef455c8c3301095b5f009dae58f0f6382a53e23c",
"lastUpdated": "2023-06-03T13:57:20",
"url": "https://huggingface.co/BlinkDL/rwkv-4-world/blob/main/RWKV-4-World-1.5B-v1-OnlyForTest_81%25_trained-20230603-ctx4096.pth",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-1.5B-v1-OnlyForTest_81%25_trained-20230603-ctx4096.pth"
},
{
"name": "RWKV-4-World-3B-v1-OnlyForTest_52%_trained-20230603-ctx4096.pth",
"desc": {
"en": "100+ Languages 3B v1 Test",
"zh": "100+ 语言 3B v1 测试"
},
"size": 6125597613,
"SHA256": "aad3671078a0c686368add4f4b695a76c2ba1ddd505a64c0949bb003beeee9a3",
"lastUpdated": "2023-06-03T13:57:20",
"url": "https://huggingface.co/BlinkDL/rwkv-4-world/blob/main/RWKV-4-World-3B-v1-OnlyForTest_52%25_trained-20230603-ctx4096.pth",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-world/resolve/main/RWKV-4-World-3B-v1-OnlyForTest_52%25_trained-20230603-ctx4096.pth"
},
{
"name": "RWKV-4-World-0.4B-v1-20230529-ctx4096.pth",