Compare commits
39 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
673ecb489e | ||
|
|
5192e31bac | ||
|
|
9f080b63e0 | ||
|
|
77ce87d209 | ||
|
|
dc50cf84f2 | ||
|
|
f439b3d382 | ||
|
|
03a494e1f1 | ||
|
|
bac4582144 | ||
|
|
1676c5b7e6 | ||
|
|
c7ed4b07c2 | ||
|
|
bcb38d991a | ||
|
|
1176dba282 | ||
|
|
c741b2a203 | ||
|
|
41142f15fb | ||
|
|
cf55c4578b | ||
|
|
cc06669b3e | ||
|
|
2468425332 | ||
|
|
6cabef2d9b | ||
|
|
5c0513a3cc | ||
|
|
ec7d50431e | ||
|
|
f8cb9511e1 | ||
|
|
4d0d0a4dee | ||
|
|
28874585ea | ||
|
|
11f358c467 | ||
|
|
0a712da7fc | ||
|
|
89ddde9f3e | ||
|
|
5e4f6159be | ||
|
|
89c8545528 | ||
|
|
4eca1537a7 | ||
|
|
65d92d5da1 | ||
|
|
3aaf16b38b | ||
|
|
9a3657e6ea | ||
|
|
689c704dca | ||
|
|
29c8a27eed | ||
|
|
1d08719645 | ||
|
|
524d9e78e6 | ||
|
|
7989e93afe | ||
|
|
ecb5d6c6e4 | ||
|
|
8be85b1c7e |
5
.gitignore
vendored
5
.gitignore
vendored
@@ -13,4 +13,7 @@ __pycache__
|
||||
/backend-python/get-pip.py
|
||||
/py310
|
||||
*.zip
|
||||
/cmd-helper.bat
|
||||
/cmd-helper.bat
|
||||
/backend-python/wkv_cuda
|
||||
*.exe
|
||||
*.old
|
||||
|
||||
18
.vscode/launch.json
vendored
Normal file
18
.vscode/launch.json
vendored
Normal file
@@ -0,0 +1,18 @@
|
||||
{
|
||||
// Use IntelliSense to learn about possible attributes.
|
||||
// Hover to view descriptions of existing attributes.
|
||||
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
|
||||
//
|
||||
// Use Ctrl+Shift+P to Select Interpreter
|
||||
"version": "0.2.0",
|
||||
"configurations": [
|
||||
{
|
||||
"name": "Python",
|
||||
"type": "python",
|
||||
"request": "launch",
|
||||
"program": "./backend-python/main.py",
|
||||
"console": "integratedTerminal",
|
||||
"justMyCode": false,
|
||||
}
|
||||
]
|
||||
}
|
||||
2
.vscode/settings.json
vendored
2
.vscode/settings.json
vendored
@@ -2,6 +2,6 @@
|
||||
"[python]": {
|
||||
"editor.defaultFormatter": "ms-python.black-formatter"
|
||||
},
|
||||
"python.formatting.provider": "black",
|
||||
"python.formatting.provider": "none",
|
||||
"editor.formatOnSave": true
|
||||
}
|
||||
18
README.md
18
README.md
@@ -25,10 +25,14 @@ English | [简体中文](README_ZH.md)
|
||||
|
||||
[release-url]: https://github.com/josStorer/RWKV-Runner/releases/latest
|
||||
|
||||
[download-url]: https://github.com/josStorer/RWKV-Runner/releases/download/v1.0.0/RWKV-Runner_windows_x64.exe
|
||||
[download-url]: https://github.com/josStorer/RWKV-Runner/releases/download/v1.0.2/RWKV-Runner_windows_x64.exe
|
||||
|
||||
</div>
|
||||
|
||||
#### Default configs do not enable custom CUDA kernel acceleration, but I strongly recommend that you enable it and run with int8 precision, which is much faster and consumes much less VRAM. Go to the Configs page and turn on `Use Custom CUDA kernel to Accelerate`.
|
||||
|
||||
#### For different tasks, adjusting API parameters can achieve better results. For example, for translation tasks, you can try setting Temperature to 1 and Top_P to 0.3.
|
||||
|
||||
## Features
|
||||
|
||||
- RWKV model management and one-click startup
|
||||
@@ -45,10 +49,10 @@ English | [简体中文](README_ZH.md)
|
||||
|
||||
## Todo
|
||||
|
||||
- Model training functionality
|
||||
- CUDA operator int8 acceleration
|
||||
- macOS support
|
||||
- Linux support
|
||||
- [ ] Model training functionality
|
||||
- [x] CUDA operator int8 acceleration
|
||||
- [ ] macOS support
|
||||
- [ ] Linux support
|
||||
|
||||
## Related Repositories:
|
||||
|
||||
@@ -66,6 +70,10 @@ English | [简体中文](README_ZH.md)
|
||||
|
||||

|
||||
|
||||
### Completion
|
||||
|
||||

|
||||
|
||||
### Configuration
|
||||
|
||||

|
||||
|
||||
22
README_ZH.md
22
README_ZH.md
@@ -14,7 +14,7 @@ API兼容的接口,这意味着一切ChatGPT客户端都是RWKV客户端。
|
||||
|
||||
[English](README.md) | 简体中文
|
||||
|
||||
[预览](#Preview) | [下载][download-url]
|
||||
[视频演示](https://www.bilibili.com/video/BV1hM4y1v76R) | [预览](#Preview) | [下载][download-url]
|
||||
|
||||
[license-image]: http://img.shields.io/badge/license-MIT-blue.svg
|
||||
|
||||
@@ -24,10 +24,16 @@ API兼容的接口,这意味着一切ChatGPT客户端都是RWKV客户端。
|
||||
|
||||
[release-url]: https://github.com/josStorer/RWKV-Runner/releases/latest
|
||||
|
||||
[download-url]: https://github.com/josStorer/RWKV-Runner/releases/download/v1.0.0/RWKV-Runner_windows_x64.exe
|
||||
[download-url]: https://github.com/josStorer/RWKV-Runner/releases/download/v1.0.2/RWKV-Runner_windows_x64.exe
|
||||
|
||||
</div>
|
||||
|
||||
#### 注意 目前RWKV中文模型质量一般,推荐使用英文模型体验实际RWKV能力
|
||||
|
||||
#### 预设配置没有开启自定义CUDA算子加速,但我强烈建议你开启它并使用int8量化运行,速度非常快,且显存消耗少得多。前往配置页面,打开`使用自定义CUDA算子加速`
|
||||
|
||||
#### 对于不同的任务,调整API参数会获得更好的效果,例如对于翻译任务,你可以尝试设置Temperature为1,Top_P为0.3
|
||||
|
||||
## 功能
|
||||
|
||||
- RWKV模型管理,一键启动
|
||||
@@ -43,10 +49,10 @@ API兼容的接口,这意味着一切ChatGPT客户端都是RWKV客户端。
|
||||
|
||||
## Todo
|
||||
|
||||
- 模型训练功能
|
||||
- CUDA算子int8提速
|
||||
- macOS支持
|
||||
- linux支持
|
||||
- [ ] 模型训练功能
|
||||
- [x] CUDA算子int8提速
|
||||
- [ ] macOS支持
|
||||
- [ ] linux支持
|
||||
|
||||
## 相关仓库:
|
||||
|
||||
@@ -64,6 +70,10 @@ API兼容的接口,这意味着一切ChatGPT客户端都是RWKV客户端。
|
||||
|
||||

|
||||
|
||||
### 补全
|
||||
|
||||

|
||||
|
||||
### 配置
|
||||
|
||||

|
||||
|
||||
@@ -3,6 +3,7 @@ package backend_golang
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
@@ -92,6 +93,26 @@ func (a *App) DeleteFile(path string) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) CopyFile(src string, dst string) error {
|
||||
sourceFile, err := os.Open(src)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sourceFile.Close()
|
||||
|
||||
destFile, err := os.Create(dst)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer destFile.Close()
|
||||
|
||||
_, err = io.Copy(destFile, sourceFile)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (a *App) OpenFileFolder(path string) error {
|
||||
absPath, err := filepath.Abs(path)
|
||||
if err != nil {
|
||||
|
||||
@@ -6,12 +6,12 @@ import (
|
||||
"strconv"
|
||||
)
|
||||
|
||||
func (a *App) StartServer(port int) (string, error) {
|
||||
func (a *App) StartServer(port int, host string) (string, error) {
|
||||
python, err := GetPython()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return Cmd(python, "./backend-python/main.py", strconv.Itoa(port))
|
||||
return Cmd(python, "./backend-python/main.py", strconv.Itoa(port), host)
|
||||
}
|
||||
|
||||
func (a *App) ConvertModel(modelPath string, strategy string, outPath string) (string, error) {
|
||||
@@ -48,7 +48,7 @@ func (a *App) InstallPyDep(cnMirror bool) (string, error) {
|
||||
return "", err
|
||||
}
|
||||
ChangeFileLine("./py310/python310._pth", 3, "Lib\\site-packages")
|
||||
_, err = Cmd(python, "-m", "pip", "install", "torch", "torchvision", "torchaudio", "--index-url", "https://download.pytorch.org/whl/cu117")
|
||||
_, err = Cmd(python, "-m", "pip", "install", "torch==1.13.1", "torchvision==0.14.1", "torchaudio==0.13.1", "--index-url", "https://download.pytorch.org/whl/cu117")
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import GPUtil
|
||||
import torch
|
||||
import rwkv
|
||||
import langchain
|
||||
|
||||
@@ -64,5 +64,9 @@ def debug():
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
uvicorn.run("main:app", port=8000 if len(sys.argv) == 1 else int(sys.argv[1]))
|
||||
uvicorn.run(
|
||||
"main:app",
|
||||
port=8000 if len(sys.argv) < 2 else int(sys.argv[1]),
|
||||
host="127.0.0.1" if len(sys.argv) < 3 else sys.argv[2],
|
||||
)
|
||||
# debug()
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -11,6 +11,10 @@ import global_var
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
interface = ":"
|
||||
user = "Bob"
|
||||
bot = "Alice"
|
||||
|
||||
|
||||
class Message(BaseModel):
|
||||
role: str
|
||||
@@ -40,11 +44,36 @@ async def chat_completions(body: ChatCompletionBody, request: Request):
|
||||
else:
|
||||
raise HTTPException(status.HTTP_400_BAD_REQUEST, "no question found")
|
||||
|
||||
completion_text = ""
|
||||
completion_text = f"""
|
||||
The following is a coherent verbose detailed conversation between a girl named {bot} and her friend {user}. \
|
||||
{bot} is very intelligent, creative and friendly. \
|
||||
{bot} is unlikely to disagree with {user}, and {bot} doesn't like to ask {user} questions. \
|
||||
{bot} likes to tell {user} a lot about herself and her opinions. \
|
||||
{bot} usually gives {user} kind, helpful and informative advices.\n
|
||||
"""
|
||||
for message in body.messages:
|
||||
if message.role == "user":
|
||||
if message.role == "system":
|
||||
completion_text = (
|
||||
f"The following is a coherent verbose detailed conversation between a girl named {bot} and her friend {user}. "
|
||||
+ message.content.replace("\\n", "\n")
|
||||
.replace("\r\n", "\n")
|
||||
.replace("\n\n", "\n")
|
||||
.replace("\n", " ")
|
||||
.strip()
|
||||
.replace("You are", f"{bot} is")
|
||||
.replace("you are", f"{bot} is")
|
||||
.replace("You're", f"{bot} is")
|
||||
.replace("you're", f"{bot} is")
|
||||
.replace("You", f"{bot}")
|
||||
.replace("you", f"{bot}")
|
||||
.replace("Your", f"{bot}'s")
|
||||
.replace("your", f"{bot}'s")
|
||||
.replace("你", f"{bot}")
|
||||
+ "\n\n"
|
||||
)
|
||||
elif message.role == "user":
|
||||
completion_text += (
|
||||
"Bob: "
|
||||
f"{user}{interface} "
|
||||
+ message.content.replace("\\n", "\n")
|
||||
.replace("\r\n", "\n")
|
||||
.replace("\n\n", "\n")
|
||||
@@ -53,14 +82,14 @@ async def chat_completions(body: ChatCompletionBody, request: Request):
|
||||
)
|
||||
elif message.role == "assistant":
|
||||
completion_text += (
|
||||
"Alice: "
|
||||
f"{bot}{interface} "
|
||||
+ message.content.replace("\\n", "\n")
|
||||
.replace("\r\n", "\n")
|
||||
.replace("\n\n", "\n")
|
||||
.strip()
|
||||
+ "\n\n"
|
||||
)
|
||||
completion_text += "Alice:"
|
||||
completion_text += f"{bot}{interface}"
|
||||
|
||||
async def eval_rwkv():
|
||||
while completion_lock.locked():
|
||||
@@ -73,7 +102,7 @@ async def chat_completions(body: ChatCompletionBody, request: Request):
|
||||
for response, delta in rwkv_generate(
|
||||
model,
|
||||
completion_text,
|
||||
stop="\n\nBob" if body.stop is None else body.stop,
|
||||
stop=f"\n\n{user}" if body.stop is None else body.stop,
|
||||
):
|
||||
if await request.is_disconnected():
|
||||
break
|
||||
@@ -90,8 +119,9 @@ async def chat_completions(body: ChatCompletionBody, request: Request):
|
||||
],
|
||||
}
|
||||
)
|
||||
# torch_gc()
|
||||
completion_lock.release()
|
||||
if await request.is_disconnected():
|
||||
completion_lock.release()
|
||||
return
|
||||
yield json.dumps(
|
||||
{
|
||||
@@ -112,12 +142,13 @@ async def chat_completions(body: ChatCompletionBody, request: Request):
|
||||
for response, delta in rwkv_generate(
|
||||
model,
|
||||
completion_text,
|
||||
stop="\n\nBob" if body.stop is None else body.stop,
|
||||
stop=f"\n\n{user}" if body.stop is None else body.stop,
|
||||
):
|
||||
if await request.is_disconnected():
|
||||
break
|
||||
# torch_gc()
|
||||
completion_lock.release()
|
||||
if await request.is_disconnected():
|
||||
completion_lock.release()
|
||||
return
|
||||
yield {
|
||||
"response": response,
|
||||
@@ -133,8 +164,6 @@ async def chat_completions(body: ChatCompletionBody, request: Request):
|
||||
}
|
||||
],
|
||||
}
|
||||
# torch_gc()
|
||||
completion_lock.release()
|
||||
|
||||
if body.stream:
|
||||
return EventSourceResponse(eval_rwkv())
|
||||
@@ -182,8 +211,9 @@ async def completions(body: CompletionBody, request: Request):
|
||||
],
|
||||
}
|
||||
)
|
||||
# torch_gc()
|
||||
completion_lock.release()
|
||||
if await request.is_disconnected():
|
||||
completion_lock.release()
|
||||
return
|
||||
yield json.dumps(
|
||||
{
|
||||
@@ -206,8 +236,9 @@ async def completions(body: CompletionBody, request: Request):
|
||||
):
|
||||
if await request.is_disconnected():
|
||||
break
|
||||
# torch_gc()
|
||||
completion_lock.release()
|
||||
if await request.is_disconnected():
|
||||
completion_lock.release()
|
||||
return
|
||||
yield {
|
||||
"response": response,
|
||||
@@ -220,8 +251,6 @@ async def completions(body: CompletionBody, request: Request):
|
||||
}
|
||||
],
|
||||
}
|
||||
# torch_gc()
|
||||
completion_lock.release()
|
||||
|
||||
if body.stream:
|
||||
return EventSourceResponse(eval_rwkv())
|
||||
|
||||
@@ -6,6 +6,7 @@ from langchain.llms import RWKV
|
||||
from utils.rwkv import *
|
||||
from utils.torch import *
|
||||
import global_var
|
||||
import GPUtil
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -13,6 +14,7 @@ router = APIRouter()
|
||||
class SwitchModelBody(BaseModel):
|
||||
model: str
|
||||
strategy: str
|
||||
customCuda: bool = False
|
||||
|
||||
|
||||
@router.post("/switch-model")
|
||||
@@ -25,6 +27,8 @@ def switch_model(body: SwitchModelBody, response: Response):
|
||||
global_var.set(global_var.Model, None)
|
||||
torch_gc()
|
||||
|
||||
os.environ["RWKV_CUDA_ON"] = "1" if body.customCuda else "0"
|
||||
|
||||
global_var.set(global_var.Model_Status, global_var.ModelStatus.Loading)
|
||||
try:
|
||||
global_var.set(
|
||||
@@ -63,4 +67,13 @@ def update_config(body: ModelConfigBody):
|
||||
|
||||
@router.get("/status")
|
||||
def status():
|
||||
return {"status": global_var.get(global_var.Model_Status)}
|
||||
gpus = GPUtil.getGPUs()
|
||||
if len(gpus) == 0:
|
||||
device_name = "CPU"
|
||||
else:
|
||||
device_name = gpus[0].name
|
||||
return {
|
||||
"status": global_var.get(global_var.Model_Status),
|
||||
"pid": os.getpid(),
|
||||
"device_name": device_name,
|
||||
}
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import os
|
||||
import pathlib
|
||||
from typing import Dict
|
||||
from langchain.llms import RWKV
|
||||
from pydantic import BaseModel
|
||||
@@ -34,6 +36,9 @@ def get_rwkv_config(model: RWKV) -> ModelConfigBody:
|
||||
)
|
||||
|
||||
|
||||
os.environ["TORCH_EXTENSIONS_DIR"] = f"{pathlib.Path(__file__).parent.parent.resolve()}"
|
||||
|
||||
|
||||
def rwkv_generate(model: RWKV, prompt: str, stop: str = None):
|
||||
model.model_state = None
|
||||
model.model_tokens = []
|
||||
|
||||
BIN
backend-python/wkv_cuda_utils/wkv_cuda10_30.pyd
Normal file
BIN
backend-python/wkv_cuda_utils/wkv_cuda10_30.pyd
Normal file
Binary file not shown.
BIN
backend-python/wkv_cuda_utils/wkv_cuda40.pyd
Normal file
BIN
backend-python/wkv_cuda_utils/wkv_cuda40.pyd
Normal file
Binary file not shown.
734
backend-python/wkv_cuda_utils/wkv_cuda_model.py
Normal file
734
backend-python/wkv_cuda_utils/wkv_cuda_model.py
Normal file
@@ -0,0 +1,734 @@
|
||||
########################################################################################################
|
||||
# The RWKV Language Model - https://github.com/BlinkDL/RWKV-LM
|
||||
########################################################################################################
|
||||
|
||||
import types, gc, os, time, re
|
||||
import torch
|
||||
from torch.nn import functional as F
|
||||
torch.backends.cudnn.benchmark = True
|
||||
torch.backends.cudnn.allow_tf32 = True
|
||||
torch.backends.cuda.matmul.allow_tf32 = True
|
||||
current_path = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# https://zhuanlan.zhihu.com/p/612879065
|
||||
def LoadPreCompileLibrary(file):
|
||||
import importlib
|
||||
import os
|
||||
|
||||
import torch
|
||||
|
||||
# load the custom_op_library and register the custom ops
|
||||
lib_dir = os.path.dirname(__file__)
|
||||
if os.name == "nt":
|
||||
# Register the main torchvision library location on the default DLL path
|
||||
import ctypes
|
||||
import sys
|
||||
|
||||
kernel32 = ctypes.WinDLL("kernel32.dll", use_last_error=True)
|
||||
with_load_library_flags = hasattr(kernel32, "AddDllDirectory")
|
||||
prev_error_mode = kernel32.SetErrorMode(0x0001)
|
||||
|
||||
if with_load_library_flags:
|
||||
kernel32.AddDllDirectory.restype = ctypes.c_void_p
|
||||
|
||||
if sys.version_info >= (3, 8):
|
||||
os.add_dll_directory(lib_dir)
|
||||
elif with_load_library_flags:
|
||||
res = kernel32.AddDllDirectory(lib_dir)
|
||||
if res is None:
|
||||
err = ctypes.WinError(ctypes.get_last_error())
|
||||
err.strerror += f' Error adding "{lib_dir}" to the DLL directories.'
|
||||
raise ValueError(err)
|
||||
|
||||
kernel32.SetErrorMode(prev_error_mode)
|
||||
|
||||
loader_details = (
|
||||
importlib.machinery.ExtensionFileLoader,
|
||||
importlib.machinery.EXTENSION_SUFFIXES,
|
||||
)
|
||||
|
||||
extfinder = importlib.machinery.FileFinder(lib_dir, loader_details)
|
||||
ext_specs = extfinder.find_spec(file)
|
||||
if ext_specs is None:
|
||||
return False
|
||||
|
||||
try:
|
||||
torch.ops.load_library(ext_specs.origin)
|
||||
except OSError as exc:
|
||||
return False
|
||||
return True
|
||||
|
||||
########################################################################################################
|
||||
|
||||
if os.environ.get('RWKV_JIT_ON') != '0':
|
||||
os.environ["RWKV_JIT_ON"] = '1'
|
||||
MyModule = torch.jit.ScriptModule
|
||||
MyFunction = torch.jit.script_method
|
||||
MyStatic = torch.jit.script
|
||||
else:
|
||||
MyModule = torch.nn.Module
|
||||
def __nop(ob):
|
||||
return ob
|
||||
MyFunction = __nop
|
||||
MyStatic = __nop
|
||||
|
||||
if os.environ.get('RWKV_CUDA_ON') == '1':
|
||||
if LoadPreCompileLibrary('wkv_cuda') is False:
|
||||
from torch.utils.cpp_extension import load
|
||||
load(
|
||||
name=f"wkv_cuda",
|
||||
sources=[f"{current_path}/cuda/wrapper.cpp", f"{current_path}/cuda/operators.cu"],
|
||||
verbose=True,
|
||||
extra_cuda_cflags=["-t 4", "-std=c++17", "--use_fast_math", "-O3", "--extra-device-vectorization"],
|
||||
is_python_module=False)
|
||||
|
||||
@MyStatic
|
||||
def cuda_wkv(T: int, C: int, w, u, k, v, aa, bb, pp):
|
||||
assert 1 * C % min(C, 32) == 0
|
||||
assert k.dtype == v.dtype == torch.float16 or k.dtype == v.dtype == torch.float32
|
||||
assert w.dtype == u.dtype == aa.dtype == bb.dtype == pp.dtype == torch.float32
|
||||
w = w.contiguous()
|
||||
u = u.contiguous()
|
||||
k = k.contiguous()
|
||||
v = v.contiguous()
|
||||
y = torch.empty((T, C), device=w.device, memory_format=torch.contiguous_format, dtype=k.dtype)
|
||||
torch.ops.rwkv.wkv_forward(1, T, C, w, u, k, v, y, aa, bb, pp)
|
||||
return y, aa, bb, pp
|
||||
@MyStatic
|
||||
def cuda_mm8_seq(B: int, N: int, M: int, x, w, mx, rx, my, ry):
|
||||
assert x.dtype == mx.dtype == rx.dtype == my.dtype == ry.dtype
|
||||
assert x.dtype == torch.float32 or x.dtype == torch.float16
|
||||
assert w.dtype == torch.uint8
|
||||
assert x.shape == [B, N]
|
||||
assert w.shape == [N, M]
|
||||
assert rx.shape == mx.shape == [M]
|
||||
assert ry.shape == my.shape == [N, 1]
|
||||
y = torch.empty((B, M), device=w.device, dtype=x.dtype)
|
||||
torch.ops.rwkv.mm8_seq(B, N, M, x, w, mx, rx, my, ry, y)
|
||||
return y
|
||||
@MyStatic
|
||||
def cuda_mm8_one(N: int, M: int, x, w, mx, rx, my, ry):
|
||||
assert x.dtype == mx.dtype == rx.dtype == my.dtype == ry.dtype
|
||||
assert x.dtype == torch.float32 or x.dtype == torch.float16
|
||||
assert w.dtype == torch.uint8
|
||||
assert x.shape == [N]
|
||||
assert w.shape == [N, M]
|
||||
assert rx.shape == mx.shape == [M]
|
||||
assert ry.shape == my.shape == [N, 1]
|
||||
y = torch.zeros((M,), device=w.device, dtype=torch.float32)
|
||||
torch.ops.rwkv.mm8_one(N, M, x, w, mx, rx, my, ry, y)
|
||||
return y.to(dtype=x.dtype)
|
||||
else:
|
||||
os.environ["RWKV_CUDA_ON"] = '0'
|
||||
|
||||
########################################################################################################
|
||||
|
||||
class RWKV(MyModule):
|
||||
def __init__(self, model, strategy, verbose = True, convert_and_save_and_exit = None):
|
||||
super().__init__()
|
||||
if verbose:
|
||||
prxxx = lambda *args, **kwargs: print(*args, **kwargs)
|
||||
else:
|
||||
prxxx = lambda *args, **kwargs: None
|
||||
|
||||
STRATEGY_REGEX = r"^(?:(?:^|->) *(?:cuda(?::[\d]+)?|cpu|mps) (?:fp(?:16|32)|bf16)(?:i8|i4|i3)?(?: \*[\d]+\+?)? *)+$"
|
||||
if not re.match(STRATEGY_REGEX, strategy):
|
||||
raise ValueError("Invalid strategy. Please read https://pypi.org/project/rwkv/")
|
||||
|
||||
strategy = ('->'.join([x.strip() for x in strategy.split('->')])).replace('->', ' -> ')
|
||||
self.args = types.SimpleNamespace()
|
||||
args = self.args
|
||||
args.MODEL_NAME = model
|
||||
args.strategy_string = strategy
|
||||
|
||||
# Rescale for fp16 mode: set x = x/2 every X layer (to avoid fp16 overflow)
|
||||
self.RESCALE_LAYER = 6 if 'fp16' in strategy else 0
|
||||
prxxx(f'RWKV_JIT_ON {os.environ["RWKV_JIT_ON"]} RWKV_CUDA_ON {os.environ["RWKV_CUDA_ON"]} RESCALE_LAYER {self.RESCALE_LAYER}\n')
|
||||
|
||||
args.MODEL_NAME = args.MODEL_NAME.strip()
|
||||
if not args.MODEL_NAME.endswith('.pth'):
|
||||
args.MODEL_NAME += '.pth'
|
||||
prxxx(f'Loading {args.MODEL_NAME} ...')
|
||||
with torch.no_grad():
|
||||
self.w = torch.load(args.MODEL_NAME, map_location='cpu') # load model to CPU first
|
||||
gc.collect()
|
||||
w = self.w
|
||||
|
||||
ALREADY_CONVERTED = False
|
||||
if '_strategy' in w:
|
||||
ALREADY_CONVERTED = True
|
||||
assert convert_and_save_and_exit == None # you should only convert a raw model
|
||||
prxxx(f"Converted model: strategy {w['_strategy']}, version {w['_version']}\n")
|
||||
assert w['_strategy'] == args.strategy_string # if you are using a new strategy, re-convert the model
|
||||
assert float(w['_version']) >= 0.7 # sometimes you should re-convert using latest convert_model.py
|
||||
assert w['_rescale_layer'] == self.RESCALE_LAYER
|
||||
del w['_strategy']
|
||||
del w['_version']
|
||||
del w['_rescale_layer']
|
||||
|
||||
args.n_embd = w['emb.weight'].shape[1]
|
||||
args.n_layer = 0
|
||||
keys = list(w.keys())
|
||||
for x in keys:
|
||||
layer_id = int(x.split('.')[1]) if ('blocks.' in x) else 0
|
||||
args.n_layer = max(args.n_layer, layer_id+1)
|
||||
|
||||
####################### Compute strategy
|
||||
|
||||
s = [x.strip().split(' ') for x in strategy.split('->')]
|
||||
plan = [0] * len(s)
|
||||
stream_i = -1
|
||||
stream_count = 0
|
||||
to_allocate = args.n_layer + 1
|
||||
allocated = 0
|
||||
free_slots = 0
|
||||
for i in range(len(s)):
|
||||
si = s[i]
|
||||
si1 = si[1]
|
||||
if si1.startswith('fp32'): si[1] = [torch.float]
|
||||
elif si1.startswith('fp16'): si[1] = [torch.float16]
|
||||
elif si1.startswith('bf16'): si[1] = [torch.bfloat16]
|
||||
if si1.endswith('i8'): si[1] += [torch.uint8]
|
||||
else: si[1] += [si[1][0]]
|
||||
if len(si) > 2:
|
||||
ss = si[2]
|
||||
assert ss.startswith('*')
|
||||
if ss.endswith('+'):
|
||||
plan[i] = int(ss[1:-1])
|
||||
stream_i = i
|
||||
else:
|
||||
plan[i] = int(ss[1:])
|
||||
allocated += plan[i]
|
||||
if allocated >= to_allocate:
|
||||
plan[i] += to_allocate - allocated
|
||||
break
|
||||
else:
|
||||
free_slots += 1
|
||||
if stream_i < 0:
|
||||
if free_slots > 0 and to_allocate > allocated:
|
||||
for i in range(len(s)):
|
||||
if plan[i] == 0:
|
||||
plan[i] = (to_allocate - allocated) // free_slots
|
||||
allocated += plan[i]
|
||||
free_slots -= 1
|
||||
if to_allocate > allocated:
|
||||
plan[len(s)-1] += to_allocate - allocated
|
||||
else:
|
||||
if to_allocate > allocated:
|
||||
stream_count = to_allocate - allocated
|
||||
plan[stream_i] += stream_count
|
||||
prxxx(f'Strategy: (total {args.n_layer}+1={args.n_layer+1} layers)')
|
||||
for i in range(len(s)):
|
||||
ss = s[i]
|
||||
if i != stream_i:
|
||||
prxxx(f'* {ss[0]} {str(ss[1]).replace("torch.","")}, store {plan[i]} layers')
|
||||
else:
|
||||
prxxx(f'* {ss[0]} {str(ss[1]).replace("torch.","")}, store {plan[i]-stream_count} layers, stream {stream_count} layers')
|
||||
plan[i] += (0 if i == 0 else plan[i-1])
|
||||
self.strategy = [None] * (args.n_layer + 1)
|
||||
strategy = self.strategy
|
||||
for n in range(args.n_layer + 1):
|
||||
for i in range(len(s)):
|
||||
if n < plan[i]:
|
||||
strategy[n] = types.SimpleNamespace()
|
||||
strategy[n].device = s[i][0]
|
||||
strategy[n].atype = s[i][1][0]
|
||||
strategy[n].wtype = s[i][1][1]
|
||||
strategy[n].stream = False
|
||||
if i == stream_i and n >= (plan[i] - stream_count):
|
||||
strategy[n].stream = True
|
||||
break
|
||||
prxxx(f"{n}-{strategy[n].device}-{str(strategy[n].atype).replace('torch.','')}-{str(strategy[n].wtype).replace('torch.','')}{'-stream' if strategy[n].stream else ''}",end=' ')
|
||||
prxxx()
|
||||
|
||||
####################### Load weights to self.w
|
||||
|
||||
if not ALREADY_CONVERTED:
|
||||
try: # precompute embedding
|
||||
w['emb.weight'] = F.layer_norm(w['emb.weight'], (args.n_embd,), weight=w['blocks.0.ln0.weight'], bias=w['blocks.0.ln0.bias'])
|
||||
except:
|
||||
w['emb.weight'] = F.layer_norm(w['emb.weight'].float(), (args.n_embd,), weight=w['blocks.0.ln0.weight'].float(), bias=w['blocks.0.ln0.bias'].float())
|
||||
del w['blocks.0.ln0.weight']
|
||||
del w['blocks.0.ln0.bias']
|
||||
|
||||
print_need_newline = False
|
||||
keys = list(w.keys())
|
||||
for x in keys:
|
||||
w[x].requires_grad = False
|
||||
layer_id = int(x.split('.')[1]) if ('blocks.' in x) else 0
|
||||
if ('ln_out.' in x) or ('head.' in x):
|
||||
layer_id = args.n_layer
|
||||
dd = strategy[layer_id]
|
||||
DEVICE = dd.device
|
||||
ATYPE = dd.atype
|
||||
WTYPE = dd.wtype
|
||||
|
||||
if not ALREADY_CONVERTED:
|
||||
if self.RESCALE_LAYER > 0:
|
||||
if 'att.output.weight' in x:
|
||||
w[x] = w[x] / (2 ** int(layer_id // self.RESCALE_LAYER))
|
||||
if 'ffn.value.weight' in x:
|
||||
w[x] = w[x] / (2 ** int(layer_id // self.RESCALE_LAYER))
|
||||
|
||||
if '.time_' in x:
|
||||
w[x] = w[x].squeeze()
|
||||
if 'key.weight' in x or 'value.weight' in x or 'receptance.weight' in x or 'output.weight' in x or 'head.weight' in x:
|
||||
w[x] = w[x].t()
|
||||
|
||||
if '.time_decay' in x: # need fp32 for this
|
||||
w[x] = -torch.exp(w[x].float())
|
||||
elif '.time_first' in x: # need fp32 for this
|
||||
w[x] = w[x].float()
|
||||
else:
|
||||
if (len(w[x].shape) == 2) and ('emb' not in x):
|
||||
if WTYPE != torch.uint8:
|
||||
w[x] = w[x].to(dtype=WTYPE)
|
||||
else:
|
||||
w[x] = w[x].float()
|
||||
|
||||
if w[x].shape[0] > w[x].shape[1]:
|
||||
w[x+'_my'] = torch.amin(w[x], dim=1).unsqueeze(1)
|
||||
w[x] = w[x] - w[x+'_my']
|
||||
w[x+'_mx'] = torch.amin(w[x], dim=0)
|
||||
w[x] = w[x] - w[x+'_mx']
|
||||
w[x+'_rx'] = torch.amax(w[x], dim=0)
|
||||
w[x] = w[x] / w[x+'_rx']
|
||||
w[x+'_ry'] = torch.amax(w[x], dim=1).unsqueeze(1)
|
||||
w[x] = w[x] / w[x+'_ry']
|
||||
else:
|
||||
w[x+'_mx'] = torch.amin(w[x], dim=0)
|
||||
w[x] = w[x] - w[x+'_mx']
|
||||
w[x+'_my'] = torch.amin(w[x], dim=1).unsqueeze(1)
|
||||
w[x] = w[x] - w[x+'_my']
|
||||
w[x+'_rx'] = torch.amax(w[x], dim=0)
|
||||
w[x] = w[x] / w[x+'_rx']
|
||||
w[x+'_ry'] = torch.amax(w[x], dim=1).unsqueeze(1)
|
||||
w[x] = w[x] / w[x+'_ry']
|
||||
|
||||
w[x] = torch.clip(torch.floor(w[x] * 256), min=0, max=255).to(dtype=torch.uint8)
|
||||
w[x+'_mx'] = w[x+'_mx'].to(dtype=ATYPE).contiguous()
|
||||
w[x+'_rx'] = (w[x+'_rx'] / 16).to(dtype=ATYPE).contiguous()
|
||||
w[x+'_my'] = w[x+'_my'].to(dtype=ATYPE).contiguous()
|
||||
w[x+'_ry'] = (w[x+'_ry'] / 16).to(dtype=ATYPE).contiguous()
|
||||
else:
|
||||
w[x] = w[x].to(dtype=ATYPE)
|
||||
|
||||
if convert_and_save_and_exit == None:
|
||||
if 'emb.' in x:
|
||||
w[x] = w[x].contiguous()
|
||||
elif (dd.stream) and (x.endswith('key.weight') or x.endswith('value.weight') or x.endswith('receptance.weight') or x.endswith('output.weight')):
|
||||
try:
|
||||
w[x] = w[x].contiguous().pin_memory() # if you see "CUDA error: out of memory" here, that's out of CPU RAM, not VRAM. Get more RAM :)
|
||||
except:
|
||||
print('Note: You are running out of RAM. Get more CPU RAM. Now this will run much slower.')
|
||||
elif DEVICE != 'cpu':
|
||||
w[x] = w[x].to(device=DEVICE).contiguous()
|
||||
|
||||
if (dd.stream) or (DEVICE != 'cpu'):
|
||||
try:
|
||||
w[x+'_mx'] = w[x+'_mx'].to(device=DEVICE).contiguous()
|
||||
w[x+'_rx'] = w[x+'_rx'].to(device=DEVICE).contiguous()
|
||||
w[x+'_my'] = w[x+'_my'].to(device=DEVICE).contiguous()
|
||||
w[x+'_ry'] = w[x+'_ry'].to(device=DEVICE).contiguous()
|
||||
except:
|
||||
pass
|
||||
|
||||
if 'ffn.value.weight' in x:
|
||||
gc.collect()
|
||||
if 'cuda' in args.strategy_string:
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
shape = [i for i in w[x].shape if i != 1]
|
||||
if len(shape) > 1:
|
||||
shape = f" {str(shape[0]).rjust(5)} {str(shape[1]).rjust(5)}"
|
||||
else:
|
||||
shape = f" {str(shape[0]).rjust(5)} "
|
||||
if layer_id == 0 or layer_id >= args.n_layer-1:
|
||||
if print_need_newline:
|
||||
prxxx('\n', end = '')
|
||||
print_need_newline = False
|
||||
dt = str(w[x].dtype).replace('torch.', '')
|
||||
dt = dt.replace('float32', 'f32').replace('bfloat16', 'bf16').replace('float16', 'f16').replace('uint8', 'i8')
|
||||
prxxx(x.ljust(32), dt.rjust(4), str(w[x].device).rjust(8), shape, ' (pinned)' if w[x].is_pinned() else '')
|
||||
else:
|
||||
print_need_newline = True
|
||||
prxxx('.', end = '', flush = True)
|
||||
|
||||
if convert_and_save_and_exit:
|
||||
w['_strategy'] = args.strategy_string
|
||||
w['_rescale_layer'] = self.RESCALE_LAYER
|
||||
w['_version'] = '0.7'
|
||||
if not convert_and_save_and_exit.endswith('.pth'):
|
||||
convert_and_save_and_exit += '.pth'
|
||||
prxxx(f'Saving to {convert_and_save_and_exit}...')
|
||||
torch.save(w, convert_and_save_and_exit)
|
||||
prxxx(f'Converted and saved. Now this will exit.')
|
||||
exit(0)
|
||||
|
||||
gc.collect()
|
||||
if 'cuda' in args.strategy_string:
|
||||
torch.cuda.empty_cache()
|
||||
|
||||
@MyFunction
|
||||
def torch_mm8_seq(self, x, w, mx, rx, my, ry):
|
||||
return x @ ((w.to(dtype=x.dtype) + 0.5) * ry * rx + my + mx)
|
||||
|
||||
@MyFunction
|
||||
def torch_mm8_one(self, x, w, mx, rx, my, ry):
|
||||
return x @ ((w.to(dtype=x.dtype) + 0.5) * ry * rx + my + mx)
|
||||
|
||||
if os.environ.get('RWKV_CUDA_ON') == '1':
|
||||
@MyFunction
|
||||
def mm8_seq(self, x, w, mx, rx, my, ry):
|
||||
if w.device.type == 'cuda' and x.dtype == torch.float16:
|
||||
B, N, M = x.shape[0], w.shape[0], w.shape[1]
|
||||
return cuda_mm8_seq(B, N, M, x, w, mx, rx, my, ry)
|
||||
else:
|
||||
return self.torch_mm8_seq(x, w, mx, rx, my, ry)
|
||||
@MyFunction
|
||||
def mm8_one(self, x, w, mx, rx, my, ry):
|
||||
if w.device.type == 'cuda':
|
||||
N, M = w.shape[0], w.shape[1]
|
||||
return cuda_mm8_one(N, M, x, w, mx, rx, my, ry)
|
||||
else:
|
||||
return self.torch_mm8_one(x, w, mx, rx, my, ry)
|
||||
else:
|
||||
@MyFunction
|
||||
def mm8_seq(self, x, w, mx, rx, my, ry):
|
||||
return self.torch_mm8_seq(x, w, mx, rx, my, ry)
|
||||
@MyFunction
|
||||
def mm8_one(self, x, w, mx, rx, my, ry):
|
||||
return self.torch_mm8_one(x, w, mx, rx, my, ry)
|
||||
|
||||
########################################################################################################
|
||||
|
||||
@MyFunction
|
||||
def ffn_one(self, x, sx, ln_w, ln_b, k_mix, r_mix, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(rx @ rw)
|
||||
vx = torch.square(torch.relu(kx @ kw))
|
||||
out = r * (vx @ vw)
|
||||
return x + out, xx
|
||||
|
||||
@MyFunction
|
||||
def ffn_one_i8(self, x, sx, ln_w, ln_b, k_mix, r_mix, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(self.mm8_one(rx, rw, rmx, rrx, rmy, rry))
|
||||
vx = torch.square(torch.relu(self.mm8_one(kx, kw, kmx, krx, kmy, kry)))
|
||||
out = r * (self.mm8_one(vx, vw, vmx, vrx, vmy, vry))
|
||||
return x + out, xx
|
||||
|
||||
########################################################################################################
|
||||
|
||||
@MyFunction
|
||||
def ffn_seq(self, x, sx, ln_w, ln_b, k_mix, r_mix, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(rx @ rw)
|
||||
vx = torch.square(torch.relu(kx @ kw))
|
||||
out = r * (vx @ vw)
|
||||
return x + out, xx[-1,:]
|
||||
|
||||
@MyFunction
|
||||
def ffn_seq_i8(self, x, sx, ln_w, ln_b, k_mix, r_mix, kw, vw, rw, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(self.mm8_seq(rx, rw, rmx, rrx, rmy, rry))
|
||||
vx = torch.square(torch.relu(self.mm8_seq(kx, kw, kmx, krx, kmy, kry)))
|
||||
out = r * (self.mm8_seq(vx, vw, vmx, vrx, vmy, vry))
|
||||
return x + out, xx[-1,:]
|
||||
|
||||
########################################################################################################
|
||||
|
||||
@MyFunction
|
||||
def att_one(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(rx @ rw)
|
||||
k = (kx @ kw).float()
|
||||
v = (vx @ vw).float()
|
||||
|
||||
ww = t_first + k
|
||||
p = torch.maximum(pp, ww)
|
||||
e1 = torch.exp(pp - p)
|
||||
e2 = torch.exp(ww - p)
|
||||
wkv = ((e1 * aa + e2 * v) / (e1 * bb + e2)).to(dtype=x.dtype)
|
||||
ww = t_decay + pp
|
||||
p = torch.maximum(ww, k)
|
||||
e1 = torch.exp(ww - p)
|
||||
e2 = torch.exp(k - p)
|
||||
|
||||
out = (r * wkv) @ ow
|
||||
return x + out, xx, e1 * aa + e2 * v, e1 * bb + e2, p
|
||||
|
||||
@MyFunction
|
||||
def att_one_i8(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(self.mm8_one(rx, rw, rmx, rrx, rmy, rry))
|
||||
k = (self.mm8_one(kx, kw, kmx, krx, kmy, kry)).float()
|
||||
v = (self.mm8_one(vx, vw, vmx, vrx, vmy, vry)).float()
|
||||
|
||||
ww = t_first + k
|
||||
p = torch.maximum(pp, ww)
|
||||
e1 = torch.exp(pp - p)
|
||||
e2 = torch.exp(ww - p)
|
||||
wkv = ((e1 * aa + e2 * v) / (e1 * bb + e2)).to(dtype=x.dtype)
|
||||
ww = t_decay + pp
|
||||
p = torch.maximum(ww, k)
|
||||
e1 = torch.exp(ww - p)
|
||||
e2 = torch.exp(k - p)
|
||||
|
||||
out = self.mm8_one(r * wkv, ow, omx, orx, omy, ory)
|
||||
return x + out, xx, e1 * aa + e2 * v, e1 * bb + e2, p
|
||||
|
||||
########################################################################################################
|
||||
|
||||
@MyFunction
|
||||
def att_seq(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(rx @ rw)
|
||||
k = (kx @ kw).float()
|
||||
v = (vx @ vw).float()
|
||||
|
||||
T = x.shape[0]
|
||||
for t in range(T):
|
||||
kk = k[t]
|
||||
vv = v[t]
|
||||
ww = t_first + kk
|
||||
p = torch.maximum(pp, ww)
|
||||
e1 = torch.exp(pp - p)
|
||||
e2 = torch.exp(ww - p)
|
||||
sx[t] = ((e1 * aa + e2 * vv) / (e1 * bb + e2)).to(dtype=x.dtype)
|
||||
ww = t_decay + pp
|
||||
p = torch.maximum(ww, kk)
|
||||
e1 = torch.exp(ww - p)
|
||||
e2 = torch.exp(kk - p)
|
||||
aa = e1 * aa + e2 * vv
|
||||
bb = e1 * bb + e2
|
||||
pp = p
|
||||
out = (r * sx) @ ow
|
||||
return x + out, xx[-1,:], aa, bb, pp
|
||||
|
||||
@MyFunction
|
||||
def att_seq_i8(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
|
||||
xx = F.layer_norm(x, (x.shape[-1],), weight=ln_w, bias=ln_b)
|
||||
sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(self.mm8_seq(rx, rw, rmx, rrx, rmy, rry))
|
||||
k = self.mm8_seq(kx, kw, kmx, krx, kmy, kry).float()
|
||||
v = self.mm8_seq(vx, vw, vmx, vrx, vmy, vry).float()
|
||||
|
||||
T = x.shape[0]
|
||||
for t in range(T):
|
||||
kk = k[t]
|
||||
vv = v[t]
|
||||
ww = t_first + kk
|
||||
p = torch.maximum(pp, ww)
|
||||
e1 = torch.exp(pp - p)
|
||||
e2 = torch.exp(ww - p)
|
||||
sx[t] = ((e1 * aa + e2 * vv) / (e1 * bb + e2)).to(dtype=x.dtype)
|
||||
ww = t_decay + pp
|
||||
p = torch.maximum(ww, kk)
|
||||
e1 = torch.exp(ww - p)
|
||||
e2 = torch.exp(kk - p)
|
||||
aa = e1 * aa + e2 * vv
|
||||
bb = e1 * bb + e2
|
||||
pp = p
|
||||
out = self.mm8_seq(r * sx, ow, omx, orx, omy, ory)
|
||||
return x + out, xx[-1,:], aa, bb, pp
|
||||
|
||||
########################################################################################################
|
||||
|
||||
if os.environ["RWKV_CUDA_ON"] == '1':
|
||||
@MyFunction
|
||||
def cuda_att_seq(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
|
||||
T, C = x.size()
|
||||
xx = F.layer_norm(x, (C,), weight=ln_w, bias=ln_b)
|
||||
sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(rx @ rw)
|
||||
k = kx @ kw
|
||||
v = vx @ vw
|
||||
y, aa, bb, pp = cuda_wkv(T, C, t_decay, t_first, k, v, aa, bb, pp)
|
||||
|
||||
out = (r * y) @ ow
|
||||
return x + out, xx[-1,:], aa, bb, pp
|
||||
|
||||
@MyFunction
|
||||
def cuda_att_seq_i8(self, x, sx, aa, bb, pp, ln_w, ln_b, k_mix, v_mix, r_mix, t_decay, t_first, kw, vw, rw, ow, kmx, krx, kmy, kry, vmx, vrx, vmy, vry, rmx, rrx, rmy, rry, omx, orx, omy, ory):
|
||||
T, C = x.size()
|
||||
xx = F.layer_norm(x, (C,), weight=ln_w, bias=ln_b)
|
||||
sx = torch.cat((sx.unsqueeze(0), xx[:-1,:]))
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(self.mm8_seq(rx, rw, rmx, rrx, rmy, rry))
|
||||
k = self.mm8_seq(kx, kw, kmx, krx, kmy, kry)
|
||||
v = self.mm8_seq(vx, vw, vmx, vrx, vmy, vry)
|
||||
y, aa, bb, pp = cuda_wkv(T, C, t_decay, t_first, k, v, aa, bb, pp)
|
||||
|
||||
out = self.mm8_seq(r * y, ow, omx, orx, omy, ory)
|
||||
return x + out, xx[-1,:], aa, bb, pp
|
||||
|
||||
########################################################################################################
|
||||
|
||||
def forward(self, tokens, state, full_output=False):
|
||||
with torch.no_grad():
|
||||
w = self.w
|
||||
args = self.args
|
||||
|
||||
if state == None:
|
||||
state = [None] * args.n_layer * 5
|
||||
for i in range(args.n_layer): # state: 0=att_xx 1=att_aa 2=att_bb 3=att_pp 4=ffn_xx
|
||||
dd = self.strategy[i]
|
||||
dev = dd.device
|
||||
atype = dd.atype
|
||||
state[i*5+0] = torch.zeros(args.n_embd, dtype=atype, requires_grad=False, device=dev).contiguous()
|
||||
state[i*5+1] = torch.zeros(args.n_embd, dtype=torch.float, requires_grad=False, device=dev).contiguous()
|
||||
state[i*5+2] = torch.zeros(args.n_embd, dtype=torch.float, requires_grad=False, device=dev).contiguous()
|
||||
state[i*5+3] = torch.zeros(args.n_embd, dtype=torch.float, requires_grad=False, device=dev).contiguous() - 1e30
|
||||
state[i*5+4] = torch.zeros(args.n_embd, dtype=atype, requires_grad=False, device=dev).contiguous()
|
||||
|
||||
seq_mode = len(tokens) > 1
|
||||
|
||||
x = w['emb.weight'][tokens if seq_mode else tokens[0]]
|
||||
|
||||
for i in range(args.n_layer):
|
||||
bbb = f'blocks.{i}.'
|
||||
att = f'blocks.{i}.att.'
|
||||
ffn = f'blocks.{i}.ffn.'
|
||||
dd = self.strategy[i]
|
||||
dev = dd.device
|
||||
atype = dd.atype
|
||||
wtype = dd.wtype
|
||||
if seq_mode:
|
||||
if 'cuda' in str(dev) and os.environ["RWKV_CUDA_ON"] == '1':
|
||||
ATT = self.cuda_att_seq if wtype != torch.uint8 else self.cuda_att_seq_i8
|
||||
else:
|
||||
ATT = self.att_seq if wtype != torch.uint8 else self.att_seq_i8
|
||||
FFN = self.ffn_seq if wtype != torch.uint8 else self.ffn_seq_i8
|
||||
else:
|
||||
ATT = self.att_one if wtype != torch.uint8 else self.att_one_i8
|
||||
FFN = self.ffn_one if wtype != torch.uint8 else self.ffn_one_i8
|
||||
|
||||
x = x.to(dtype=atype, device=dev)
|
||||
|
||||
kw = w[f'{att}key.weight']
|
||||
vw = w[f'{att}value.weight']
|
||||
rw = w[f'{att}receptance.weight']
|
||||
ow = w[f'{att}output.weight']
|
||||
if dd.stream:
|
||||
kw = kw.to(device=dev, non_blocking=True)
|
||||
vw = vw.to(device=dev, non_blocking=True)
|
||||
rw = rw.to(device=dev, non_blocking=True)
|
||||
ow = ow.to(device=dev, non_blocking=True)
|
||||
kmx = w[f'{att}key.weight_mx'] if wtype == torch.uint8 else x
|
||||
krx = w[f'{att}key.weight_rx'] if wtype == torch.uint8 else x
|
||||
kmy = w[f'{att}key.weight_my'] if wtype == torch.uint8 else x
|
||||
kry = w[f'{att}key.weight_ry'] if wtype == torch.uint8 else x
|
||||
vmx = w[f'{att}value.weight_mx'] if wtype == torch.uint8 else x
|
||||
vrx = w[f'{att}value.weight_rx'] if wtype == torch.uint8 else x
|
||||
vmy = w[f'{att}value.weight_my'] if wtype == torch.uint8 else x
|
||||
vry = w[f'{att}value.weight_ry'] if wtype == torch.uint8 else x
|
||||
rmx = w[f'{att}receptance.weight_mx'] if wtype == torch.uint8 else x
|
||||
rrx = w[f'{att}receptance.weight_rx'] if wtype == torch.uint8 else x
|
||||
rmy = w[f'{att}receptance.weight_my'] if wtype == torch.uint8 else x
|
||||
rry = w[f'{att}receptance.weight_ry'] if wtype == torch.uint8 else x
|
||||
omx = w[f'{att}output.weight_mx'] if wtype == torch.uint8 else x
|
||||
orx = w[f'{att}output.weight_rx'] if wtype == torch.uint8 else x
|
||||
omy = w[f'{att}output.weight_my'] if wtype == torch.uint8 else x
|
||||
ory = w[f'{att}output.weight_ry'] if wtype == torch.uint8 else x
|
||||
x, state[i*5+0], state[i*5+1], state[i*5+2], state[i*5+3] = ATT(
|
||||
x, state[i*5+0], state[i*5+1], state[i*5+2], state[i*5+3],
|
||||
w[f'{bbb}ln1.weight'], w[f'{bbb}ln1.bias'],
|
||||
w[f'{att}time_mix_k'], w[f'{att}time_mix_v'], w[f'{att}time_mix_r'],
|
||||
w[f'{att}time_decay'], w[f'{att}time_first'],
|
||||
kw, vw, rw, ow,
|
||||
kmx, krx, kmy, kry,
|
||||
vmx, vrx, vmy, vry,
|
||||
rmx, rrx, rmy, rry,
|
||||
omx, orx, omy, ory,
|
||||
)
|
||||
if dd.stream:
|
||||
del kw, vw, rw, ow
|
||||
|
||||
kw = w[f'{ffn}key.weight']
|
||||
vw = w[f'{ffn}value.weight']
|
||||
rw = w[f'{ffn}receptance.weight']
|
||||
if dd.stream:
|
||||
kw = kw.to(device=dev, non_blocking=True)
|
||||
vw = vw.to(device=dev, non_blocking=True)
|
||||
rw = rw.to(device=dev, non_blocking=True)
|
||||
kmx = w[f'{ffn}key.weight_mx'] if wtype == torch.uint8 else x
|
||||
krx = w[f'{ffn}key.weight_rx'] if wtype == torch.uint8 else x
|
||||
kmy = w[f'{ffn}key.weight_my'] if wtype == torch.uint8 else x
|
||||
kry = w[f'{ffn}key.weight_ry'] if wtype == torch.uint8 else x
|
||||
vmx = w[f'{ffn}value.weight_mx'] if wtype == torch.uint8 else x
|
||||
vrx = w[f'{ffn}value.weight_rx'] if wtype == torch.uint8 else x
|
||||
vmy = w[f'{ffn}value.weight_my'] if wtype == torch.uint8 else x
|
||||
vry = w[f'{ffn}value.weight_ry'] if wtype == torch.uint8 else x
|
||||
rmx = w[f'{ffn}receptance.weight_mx'] if wtype == torch.uint8 else x
|
||||
rrx = w[f'{ffn}receptance.weight_rx'] if wtype == torch.uint8 else x
|
||||
rmy = w[f'{ffn}receptance.weight_my'] if wtype == torch.uint8 else x
|
||||
rry = w[f'{ffn}receptance.weight_ry'] if wtype == torch.uint8 else x
|
||||
x, state[i*5+4] = FFN(
|
||||
x, state[i*5+4],
|
||||
w[f'{bbb}ln2.weight'], w[f'{bbb}ln2.bias'],
|
||||
w[f'{ffn}time_mix_k'], w[f'{ffn}time_mix_r'],
|
||||
kw, vw, rw,
|
||||
kmx, krx, kmy, kry,
|
||||
vmx, vrx, vmy, vry,
|
||||
rmx, rrx, rmy, rry,
|
||||
)
|
||||
if dd.stream:
|
||||
del kw, vw, rw
|
||||
|
||||
if self.RESCALE_LAYER > 0:
|
||||
if (i+1) % self.RESCALE_LAYER == 0:
|
||||
x = x / 2
|
||||
|
||||
dd = self.strategy[args.n_layer]
|
||||
x = x[-1,:] if (seq_mode and (not full_output)) else x
|
||||
x = x.to(dtype=dd.atype, device=dd.device)
|
||||
|
||||
x = F.layer_norm(x, (args.n_embd,), weight=w['ln_out.weight'], bias=w['ln_out.bias'])
|
||||
if w['head.weight'].dtype != torch.uint8:
|
||||
x = x @ w['head.weight']
|
||||
else:
|
||||
if seq_mode and full_output:
|
||||
x = self.mm8_seq(x, w['head.weight'], w['head.weight_mx'], w['head.weight_rx'], w['head.weight_my'], w['head.weight_ry'])
|
||||
else:
|
||||
x = self.mm8_one(x, w['head.weight'], w['head.weight_mx'], w['head.weight_rx'], w['head.weight_my'], w['head.weight_ry'])
|
||||
|
||||
return x.float(), state
|
||||
@@ -20,11 +20,11 @@
|
||||
"Manage Models": "管理模型",
|
||||
"Model": "模型",
|
||||
"Model Parameters": "模型参数",
|
||||
"Frequency Penalty *": "Frequency Penalty *",
|
||||
"Presence Penalty *": "Presence Penalty *",
|
||||
"Top_P *": "Top_P *",
|
||||
"Temperature *": "Temperature *",
|
||||
"Max Response Token *": "最大响应 Token *",
|
||||
"Frequency Penalty": "Frequency Penalty",
|
||||
"Presence Penalty": "Presence Penalty",
|
||||
"Top_P": "Top_P",
|
||||
"Temperature": "Temperature",
|
||||
"Max Response Token": "最大响应 Token",
|
||||
"API Port": "API 端口",
|
||||
"Hover your mouse over the text to view a detailed description. Settings marked with * will take effect immediately after being saved.": "把鼠标悬停在文本上查看详细描述. 标记了星号 * 的设置在保存后会立即生效.",
|
||||
"Default API Parameters": "默认 API 参数",
|
||||
@@ -75,14 +75,14 @@
|
||||
"New Version Available": "新版本可用",
|
||||
"Update": "更新",
|
||||
"Please click the button in the top right corner to start the model": "请点击右上角的按钮启动模型",
|
||||
"Update Error, Please restart this program": "更新出错, 请重启本程序",
|
||||
"Update Error": "更新出错",
|
||||
"Open the following URL with your browser to view the API documentation": "使用浏览器打开以下地址查看API文档",
|
||||
"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.": "默认情况下, 单个回复最多回答的token数目, 用户可以通过自行指定API参数改变这个值",
|
||||
"Sampling temperature, the higher the stronger the randomness and creativity, while the lower, the more focused and deterministic it will be.": "采样温度, 越大随机性越强, 更具创造力, 越小则越保守稳定",
|
||||
"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, and is faster, 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, and fp32 has the best quality.": "int8占用显存更低, 但质量略微下降. fp16质量更好, fp32质量最好",
|
||||
"Number of the neural network layers loaded into VRAM, the more you load, the faster the speed, but it consumes more VRAM.": "载入显存的神经网络层数, 载入越多, 速度越快, 但显存消耗越大",
|
||||
"Whether to use CPU to calculate the last output layer of the neural network with FP32 precision to obtain better quality.": "是否使用cpu以fp32精度计算神经网络的最后一层输出层, 以获得更好的质量",
|
||||
"Downloads": "下载",
|
||||
@@ -97,5 +97,24 @@
|
||||
"This is the latest version": "已是最新版",
|
||||
"Use Tsinghua Pip Mirrors": "使用清华大学Pip镜像源",
|
||||
"Model Config Exception": "模型配置异常",
|
||||
"Use Gitee Updates Source": "使用Gitee更新源"
|
||||
"Use Gitee Updates Source": "使用Gitee更新源",
|
||||
"Use Custom CUDA kernel to Accelerate": "使用自定义CUDA算子加速",
|
||||
"Enabling this option can greatly improve inference speed, but there may be compatibility issues. If it fails to start, please turn off this option.": "开启这个选项能大大提升推理速度,但可能存在兼容性问题,如果启动失败,请关闭此选项",
|
||||
"Supported custom cuda file not found": "没有找到支持的自定义cuda文件",
|
||||
"Failed to copy custom cuda file": "自定义cuda文件复制失败",
|
||||
"Downloading update, please wait. If it is not completed, please manually download the program from GitHub and replace the original program.": "正在下载更新,请等待。如果一直未完成,请从Github手动下载并覆盖原程序",
|
||||
"Completion": "补全",
|
||||
"Parameters": "参数",
|
||||
"Stop Sequences": "停止词",
|
||||
"When this content appears in the response result, the generation will end.": "响应结果出现该内容时就结束生成",
|
||||
"Reset": "重置",
|
||||
"Generate": "生成",
|
||||
"Writer": "写作",
|
||||
"Translator": "翻译",
|
||||
"Catgirl": "猫娘",
|
||||
"Explain Code": "代码解释",
|
||||
"Werewolf": "狼人杀",
|
||||
"Blank": "空白",
|
||||
"The following is an epic science fiction masterpiece that is immortalized, with delicate descriptions and grand depictions of interstellar civilization wars.\nChapter 1.\n": "以下是不朽的科幻史诗巨著,描写细腻,刻画了宏大的星际文明战争。\n第一章\n",
|
||||
"API Host": "API主机"
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
import commonStore, { ModelStatus } from '../stores/commonStore';
|
||||
import commonStore, { Status } from '../stores/commonStore';
|
||||
|
||||
export const readRoot = async () => {
|
||||
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
|
||||
@@ -36,15 +36,15 @@ export const updateConfig = async (body: any) => {
|
||||
});
|
||||
};
|
||||
|
||||
export const getStatus = async (timeout?: number): Promise<ModelStatus | undefined> => {
|
||||
export const getStatus = async (timeout?: number): Promise<Status | undefined> => {
|
||||
const controller = new AbortController();
|
||||
if (timeout)
|
||||
setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
|
||||
let ret: ModelStatus | undefined;
|
||||
let ret: Status | undefined;
|
||||
await fetch(`http://127.0.0.1:${port}/status`, { signal: controller.signal }).then(r => r.json()).then(data => {
|
||||
ret = data.status;
|
||||
ret = data;
|
||||
}).catch(() => {
|
||||
});
|
||||
return ret;
|
||||
|
||||
@@ -3,18 +3,25 @@ import { Label, Tooltip } from '@fluentui/react-components';
|
||||
import classnames from 'classnames';
|
||||
|
||||
export const Labeled: FC<{
|
||||
label: string; desc?: string | null, content: ReactElement, flex?: boolean, spaceBetween?: boolean
|
||||
label: string;
|
||||
desc?: string | null,
|
||||
content: ReactElement,
|
||||
flex?: boolean,
|
||||
spaceBetween?: boolean,
|
||||
breakline?: boolean
|
||||
}> = ({
|
||||
label,
|
||||
desc,
|
||||
content,
|
||||
flex,
|
||||
spaceBetween
|
||||
spaceBetween,
|
||||
breakline
|
||||
}) => {
|
||||
return (
|
||||
<div className={classnames(
|
||||
'items-center',
|
||||
!breakline ? 'items-center' : '',
|
||||
flex ? 'flex' : 'grid grid-cols-2',
|
||||
breakline ? 'flex-col' : '',
|
||||
spaceBetween && 'justify-between')
|
||||
}>
|
||||
{desc ?
|
||||
|
||||
@@ -2,6 +2,7 @@ import React, { FC, MouseEventHandler, ReactElement } from 'react';
|
||||
import commonStore, { ModelStatus } from '../stores/commonStore';
|
||||
import {
|
||||
AddToDownloadList,
|
||||
CopyFile,
|
||||
DepCheck,
|
||||
FileExists,
|
||||
InstallPyDep,
|
||||
@@ -9,10 +10,10 @@ import {
|
||||
} from '../../wailsjs/go/backend_golang/App';
|
||||
import { Button } from '@fluentui/react-components';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { exit, readRoot, switchModel, updateConfig } from '../apis';
|
||||
import { exit, getStatus, readRoot, switchModel, updateConfig } from '../apis';
|
||||
import { toast } from 'react-toastify';
|
||||
import manifest from '../../../manifest.json';
|
||||
import { getStrategy, saveCache, toastWithButton } from '../utils';
|
||||
import { getStrategy, getSupportedCustomCudaFile, saveCache, toastWithButton } from '../utils';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { ToolTipButton } from './ToolTipButton';
|
||||
import { Play16Regular, Stop16Regular } from '@fluentui/react-icons';
|
||||
@@ -42,8 +43,8 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
const navigate = useNavigate();
|
||||
|
||||
const onClickMainButton = async () => {
|
||||
if (commonStore.modelStatus === ModelStatus.Offline) {
|
||||
commonStore.setModelStatus(ModelStatus.Starting);
|
||||
if (commonStore.status.modelStatus === ModelStatus.Offline) {
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Starting });
|
||||
|
||||
const modelConfig = commonStore.getCurrentModelConfig();
|
||||
let modelName = '';
|
||||
@@ -53,7 +54,7 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
modelPath = `./${manifest.localModelDir}/${modelName}`;
|
||||
} else {
|
||||
toast(t('Model Config Exception'), { type: 'error' });
|
||||
commonStore.setModelStatus(ModelStatus.Offline);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Offline });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -79,10 +80,11 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
}
|
||||
});
|
||||
if (depErrorMsg) {
|
||||
commonStore.setModelStatus(ModelStatus.Offline);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Offline });
|
||||
return;
|
||||
}
|
||||
commonStore.setDepComplete(true);
|
||||
CopyFile('./backend-python/wkv_cuda_utils/wkv_cuda_model.py', './py310/Lib/site-packages/rwkv/model.py');
|
||||
saveCache();
|
||||
}
|
||||
|
||||
@@ -100,7 +102,7 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
}
|
||||
});
|
||||
|
||||
commonStore.setModelStatus(ModelStatus.Offline);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Offline });
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -108,18 +110,22 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
|
||||
await exit(1000).catch(() => {
|
||||
});
|
||||
StartServer(port);
|
||||
StartServer(port, commonStore.settings.host);
|
||||
setTimeout(WindowShow, 1000);
|
||||
|
||||
let timeoutCount = 6;
|
||||
let loading = false;
|
||||
const intervalId = setInterval(() => {
|
||||
readRoot()
|
||||
.then(r => {
|
||||
.then(async r => {
|
||||
if (r.ok && !loading) {
|
||||
clearInterval(intervalId);
|
||||
commonStore.setModelStatus(ModelStatus.Loading);
|
||||
loading = true;
|
||||
clearInterval(intervalId);
|
||||
await getStatus().then(status => {
|
||||
if (status)
|
||||
commonStore.setStatus(status);
|
||||
});
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Loading });
|
||||
toast(t('Loading Model'), { type: 'info' });
|
||||
updateConfig({
|
||||
max_tokens: modelConfig.apiParameters.maxResponseToken,
|
||||
@@ -128,56 +134,78 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
|
||||
presence_penalty: modelConfig.apiParameters.presencePenalty,
|
||||
frequency_penalty: modelConfig.apiParameters.frequencyPenalty
|
||||
});
|
||||
|
||||
let customCudaFile = '';
|
||||
if (modelConfig.modelParameters.useCustomCuda) {
|
||||
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');
|
||||
});
|
||||
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' });
|
||||
}
|
||||
|
||||
switchModel({
|
||||
model: `${manifest.localModelDir}/${modelConfig.modelParameters.modelName}`,
|
||||
strategy: getStrategy(modelConfig)
|
||||
strategy: getStrategy(modelConfig),
|
||||
customCuda: customCudaFile !== ''
|
||||
}).then((r) => {
|
||||
if (r.ok) {
|
||||
commonStore.setModelStatus(ModelStatus.Working);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Working });
|
||||
toastWithButton(t('Startup Completed'), t('Chat'), () => {
|
||||
navigate({ pathname: '/chat' });
|
||||
}, { type: 'success', autoClose: 3000 });
|
||||
} else if (r.status === 304) {
|
||||
toast(t('Loading Model'), { type: 'info' });
|
||||
} else {
|
||||
commonStore.setModelStatus(ModelStatus.Offline);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Offline });
|
||||
toast(t('Failed to switch model'), { type: 'error' });
|
||||
}
|
||||
}).catch(() => {
|
||||
commonStore.setModelStatus(ModelStatus.Offline);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Offline });
|
||||
toast(t('Failed to switch model'), { type: 'error' });
|
||||
});
|
||||
}
|
||||
}).catch(() => {
|
||||
if (timeoutCount <= 0) {
|
||||
clearInterval(intervalId);
|
||||
commonStore.setModelStatus(ModelStatus.Offline);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Offline });
|
||||
}
|
||||
});
|
||||
|
||||
timeoutCount--;
|
||||
}, 1000);
|
||||
} else {
|
||||
commonStore.setModelStatus(ModelStatus.Offline);
|
||||
commonStore.setStatus({ modelStatus: ModelStatus.Offline });
|
||||
exit();
|
||||
}
|
||||
};
|
||||
|
||||
const onClick = async (e: any) => {
|
||||
if (commonStore.modelStatus === ModelStatus.Offline)
|
||||
if (commonStore.status.modelStatus === ModelStatus.Offline)
|
||||
await onClickRun?.(e);
|
||||
await onClickMainButton();
|
||||
};
|
||||
|
||||
return (iconMode ?
|
||||
<ToolTipButton disabled={commonStore.modelStatus === ModelStatus.Starting}
|
||||
icon={iconModeButtonIcon[commonStore.modelStatus]}
|
||||
desc={t(mainButtonText[commonStore.modelStatus])}
|
||||
<ToolTipButton disabled={commonStore.status.modelStatus === ModelStatus.Starting}
|
||||
icon={iconModeButtonIcon[commonStore.status.modelStatus]}
|
||||
desc={t(mainButtonText[commonStore.status.modelStatus])}
|
||||
size="small" onClick={onClick} />
|
||||
:
|
||||
<Button disabled={commonStore.modelStatus === ModelStatus.Starting} appearance="primary" size="large"
|
||||
<Button disabled={commonStore.status.modelStatus === ModelStatus.Starting} appearance="primary" size="large"
|
||||
onClick={onClick}>
|
||||
{t(mainButtonText[commonStore.modelStatus])}
|
||||
{t(mainButtonText[commonStore.status.modelStatus])}
|
||||
</Button>
|
||||
);
|
||||
});
|
||||
|
||||
46
frontend/src/components/WorkHeader.tsx
Normal file
46
frontend/src/components/WorkHeader.tsx
Normal file
@@ -0,0 +1,46 @@
|
||||
import React, { FC } from 'react';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { Divider, PresenceBadge, Text } from '@fluentui/react-components';
|
||||
import commonStore, { ModelStatus } from '../stores/commonStore';
|
||||
import { ConfigSelector } from './ConfigSelector';
|
||||
import { RunButton } from './RunButton';
|
||||
import { PresenceBadgeStatus } from '@fluentui/react-badge';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
|
||||
const statusText = {
|
||||
[ModelStatus.Offline]: 'Offline',
|
||||
[ModelStatus.Starting]: 'Starting',
|
||||
[ModelStatus.Loading]: 'Loading',
|
||||
[ModelStatus.Working]: 'Working'
|
||||
};
|
||||
|
||||
const badgeStatus: { [modelStatus: number]: PresenceBadgeStatus } = {
|
||||
[ModelStatus.Offline]: 'unknown',
|
||||
[ModelStatus.Starting]: 'away',
|
||||
[ModelStatus.Loading]: 'away',
|
||||
[ModelStatus.Working]: 'available'
|
||||
};
|
||||
|
||||
export const WorkHeader: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
|
||||
|
||||
return (
|
||||
<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.modelStatus]} />
|
||||
<Text size={100}>{t('Model Status') + ': ' + t(statusText[commonStore.status.modelStatus])}</Text>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ConfigSelector size="small" />
|
||||
<RunButton iconMode />
|
||||
</div>
|
||||
</div>
|
||||
<Text size={100}>
|
||||
{t('This tool\'s API is compatible with OpenAI API. It can be used with any ChatGPT tool you like. Go to the settings of some ChatGPT tool, replace the \'https://api.openai.com\' part in the API address with \'') + `http://127.0.0.1:${port}` + '\'.'}
|
||||
</Text>
|
||||
<Divider style={{ flexGrow: 0 }} />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -1,11 +1,8 @@
|
||||
import React, { FC, useEffect, useRef, useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { RunButton } from '../components/RunButton';
|
||||
import { Avatar, Divider, PresenceBadge, Text, Textarea } from '@fluentui/react-components';
|
||||
import { Avatar, PresenceBadge, Textarea } from '@fluentui/react-components';
|
||||
import commonStore, { ModelStatus } from '../stores/commonStore';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { PresenceBadgeStatus } from '@fluentui/react-badge';
|
||||
import { ConfigSelector } from '../components/ConfigSelector';
|
||||
import { v4 as uuid } from 'uuid';
|
||||
import classnames from 'classnames';
|
||||
import { fetchEventSource } from '@microsoft/fetch-event-source';
|
||||
@@ -17,6 +14,7 @@ import { ArrowCircleUp28Regular, Delete28Regular, RecordStop28Regular } from '@f
|
||||
import { CopyButton } from '../components/CopyButton';
|
||||
import { ReadButton } from '../components/ReadButton';
|
||||
import { toast } from 'react-toastify';
|
||||
import { WorkHeader } from '../components/WorkHeader';
|
||||
|
||||
export const userName = 'M E';
|
||||
export const botName = 'A I';
|
||||
@@ -65,6 +63,7 @@ const ChatPanel: FC = observer(() => {
|
||||
useEffect(() => {
|
||||
if (inputRef.current)
|
||||
inputRef.current.style.maxHeight = '16rem';
|
||||
scrollToBottom();
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -94,7 +93,7 @@ const ChatPanel: FC = observer(() => {
|
||||
e.stopPropagation();
|
||||
if (e.type === 'click' || (e.keyCode === 13 && !e.shiftKey)) {
|
||||
e.preventDefault();
|
||||
if (commonStore.modelStatus === ModelStatus.Offline) {
|
||||
if (commonStore.status.modelStatus === ModelStatus.Offline) {
|
||||
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
|
||||
return;
|
||||
}
|
||||
@@ -292,40 +291,10 @@ const ChatPanel: FC = observer(() => {
|
||||
);
|
||||
});
|
||||
|
||||
const statusText = {
|
||||
[ModelStatus.Offline]: 'Offline',
|
||||
[ModelStatus.Starting]: 'Starting',
|
||||
[ModelStatus.Loading]: 'Loading',
|
||||
[ModelStatus.Working]: 'Working'
|
||||
};
|
||||
|
||||
const badgeStatus: { [modelStatus: number]: PresenceBadgeStatus } = {
|
||||
[ModelStatus.Offline]: 'unknown',
|
||||
[ModelStatus.Starting]: 'away',
|
||||
[ModelStatus.Loading]: 'away',
|
||||
[ModelStatus.Working]: 'available'
|
||||
};
|
||||
|
||||
export const Chat: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
|
||||
|
||||
return (
|
||||
<div className="flex flex-col gap-1 p-2 h-full overflow-hidden">
|
||||
<div className="flex justify-between items-center">
|
||||
<div className="flex items-center gap-2">
|
||||
<PresenceBadge status={badgeStatus[commonStore.modelStatus]} />
|
||||
<Text size={100}>{t('Model Status') + ': ' + t(statusText[commonStore.modelStatus])}</Text>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<ConfigSelector size="small" />
|
||||
<RunButton iconMode />
|
||||
</div>
|
||||
</div>
|
||||
<Text size={100}>
|
||||
{t('This tool\'s API is compatible with OpenAI API. It can be used with any ChatGPT tool you like. Go to the settings of some ChatGPT tool, replace the \'https://api.openai.com\' part in the API address with \'') + `http://127.0.0.1:${port}` + '\'.'}
|
||||
</Text>
|
||||
<Divider style={{ flexGrow: 0 }} />
|
||||
<WorkHeader />
|
||||
<ChatPanel />
|
||||
</div>
|
||||
);
|
||||
|
||||
309
frontend/src/pages/Completion.tsx
Normal file
309
frontend/src/pages/Completion.tsx
Normal file
@@ -0,0 +1,309 @@
|
||||
import React, { FC, useEffect, useRef } from 'react';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
import { WorkHeader } from '../components/WorkHeader';
|
||||
import { Button, Dropdown, Input, Option, Textarea } from '@fluentui/react-components';
|
||||
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';
|
||||
|
||||
export type CompletionParams = Omit<ApiParameters, 'apiPort'> & { stop: string }
|
||||
|
||||
export type CompletionPreset = {
|
||||
name: string,
|
||||
prompt: string,
|
||||
params: CompletionParams
|
||||
}
|
||||
|
||||
export const defaultPresets: CompletionPreset[] = [{
|
||||
name: 'Writer',
|
||||
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',
|
||||
params: {
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1,
|
||||
topP: 0.5,
|
||||
presencePenalty: 0.4,
|
||||
frequencyPenalty: 0.4,
|
||||
stop: ''
|
||||
}
|
||||
}, {
|
||||
name: 'Translator',
|
||||
prompt: '',
|
||||
params: {
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1,
|
||||
topP: 0.5,
|
||||
presencePenalty: 0.4,
|
||||
frequencyPenalty: 0.4,
|
||||
stop: ''
|
||||
}
|
||||
}, {
|
||||
name: 'Catgirl',
|
||||
prompt: '',
|
||||
params: {
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1,
|
||||
topP: 0.5,
|
||||
presencePenalty: 0.4,
|
||||
frequencyPenalty: 0.4,
|
||||
stop: ''
|
||||
}
|
||||
}, {
|
||||
name: 'Explain Code',
|
||||
prompt: '',
|
||||
params: {
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1,
|
||||
topP: 0.5,
|
||||
presencePenalty: 0.4,
|
||||
frequencyPenalty: 0.4,
|
||||
stop: ''
|
||||
}
|
||||
}, {
|
||||
name: 'Werewolf',
|
||||
prompt: '',
|
||||
params: {
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1,
|
||||
topP: 0.5,
|
||||
presencePenalty: 0.4,
|
||||
frequencyPenalty: 0.4,
|
||||
stop: ''
|
||||
}
|
||||
}, {
|
||||
name: 'Blank',
|
||||
prompt: '',
|
||||
params: {
|
||||
maxResponseToken: 4100,
|
||||
temperature: 1,
|
||||
topP: 0.5,
|
||||
presencePenalty: 0.4,
|
||||
frequencyPenalty: 0.4,
|
||||
stop: ''
|
||||
}
|
||||
}];
|
||||
|
||||
const CompletionPanel: FC = observer(() => {
|
||||
const { t } = useTranslation();
|
||||
const inputRef = useRef<HTMLTextAreaElement>(null);
|
||||
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
|
||||
const sseControllerRef = useRef<AbortController | null>(null);
|
||||
|
||||
const scrollToBottom = () => {
|
||||
if (inputRef.current)
|
||||
inputRef.current.scrollTop = inputRef.current.scrollHeight;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
if (inputRef.current)
|
||||
inputRef.current.style.height = '100%';
|
||||
scrollToBottom();
|
||||
}, []);
|
||||
|
||||
const setPreset = (preset: CompletionPreset) => {
|
||||
commonStore.setCompletionPreset({
|
||||
...preset,
|
||||
prompt: t(preset.prompt)
|
||||
});
|
||||
};
|
||||
|
||||
if (!commonStore.completionPreset)
|
||||
setPreset(defaultPresets[0]);
|
||||
|
||||
const name = commonStore.completionPreset!.name;
|
||||
|
||||
const prompt = commonStore.completionPreset!.prompt;
|
||||
const setPrompt = (prompt: string) => {
|
||||
commonStore.setCompletionPreset({
|
||||
...commonStore.completionPreset!,
|
||||
prompt
|
||||
});
|
||||
};
|
||||
|
||||
const params = commonStore.completionPreset!.params;
|
||||
const setParams = (newParams: Partial<CompletionParams>) => {
|
||||
commonStore.setCompletionPreset({
|
||||
...commonStore.completionPreset!,
|
||||
params: {
|
||||
...commonStore.completionPreset!.params,
|
||||
...newParams
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const onSubmit = (prompt: string) => {
|
||||
if (commonStore.status.modelStatus === ModelStatus.Offline) {
|
||||
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
|
||||
return;
|
||||
}
|
||||
|
||||
let answer = '';
|
||||
sseControllerRef.current = new AbortController();
|
||||
fetchEventSource(`http://127.0.0.1:${port}/completions`, // https://api.openai.com/v1/completions || http://127.0.0.1:${port}/completions
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
Authorization: `Bearer sk-`
|
||||
},
|
||||
body: JSON.stringify({
|
||||
prompt,
|
||||
stream: true,
|
||||
model: 'text-davinci-003',
|
||||
max_tokens: params.maxResponseToken,
|
||||
temperature: params.temperature,
|
||||
top_p: params.topP,
|
||||
presence_penalty: params.presencePenalty,
|
||||
frequency_penalty: params.frequencyPenalty,
|
||||
stop: params.stop || undefined
|
||||
}),
|
||||
signal: sseControllerRef.current?.signal,
|
||||
onmessage(e) {
|
||||
console.log('sse message', e);
|
||||
scrollToBottom();
|
||||
if (e.data === '[DONE]') {
|
||||
commonStore.setCompletionGenerating(false);
|
||||
return;
|
||||
}
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(e.data);
|
||||
} catch (error) {
|
||||
console.debug('json error', error);
|
||||
return;
|
||||
}
|
||||
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
|
||||
answer += data.choices[0].text;
|
||||
setPrompt(prompt + answer);
|
||||
}
|
||||
},
|
||||
onclose() {
|
||||
console.log('Connection closed');
|
||||
},
|
||||
onerror(err) {
|
||||
commonStore.setCompletionGenerating(false);
|
||||
throw err;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex flex-col sm:flex-row gap-2 overflow-hidden grow">
|
||||
<Textarea
|
||||
ref={inputRef}
|
||||
className="grow"
|
||||
value={prompt}
|
||||
onChange={(e) => setPrompt(e.target.value)}
|
||||
/>
|
||||
<div className="flex flex-col gap-1 max-h-48 sm:max-w-sm sm:max-h-full">
|
||||
<Dropdown style={{ minWidth: 0 }}
|
||||
value={t(commonStore.completionPreset!.name)!}
|
||||
selectedOptions={[commonStore.completionPreset!.name]}
|
||||
onOptionSelect={(_, data) => {
|
||||
if (data.optionValue) {
|
||||
setPreset(defaultPresets.find((preset) => preset.name === data.optionValue)!);
|
||||
}
|
||||
}}>
|
||||
{
|
||||
defaultPresets.map((preset) =>
|
||||
<Option key={preset.name} value={preset.name}>{t(preset.name)!}</Option>)
|
||||
}
|
||||
</Dropdown>
|
||||
<div className="flex flex-col gap-1 overflow-x-hidden overflow-y-auto">
|
||||
<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={400}
|
||||
input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
maxResponseToken: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Temperature')}
|
||||
desc={t('Sampling temperature, 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('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
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<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={-2} max={2}
|
||||
step={0.1} input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
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={-2} max={2}
|
||||
step={0.1} input
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
frequencyPenalty: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled flex breakline label={t('Stop Sequences')}
|
||||
desc={t('When this content appears in the response result, the generation will end.')}
|
||||
content={
|
||||
<Input value={params.stop}
|
||||
onChange={(e, data) => {
|
||||
setParams({
|
||||
stop: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
</div>
|
||||
<div className="grow" />
|
||||
<div className="flex justify-between gap-2">
|
||||
<Button className="grow" onClick={() => {
|
||||
setPreset(defaultPresets.find((preset) => preset.name === name)!);
|
||||
}}>{t('Reset')}</Button>
|
||||
<Button className="grow" appearance="primary" onClick={() => {
|
||||
if (commonStore.completionGenerating) {
|
||||
sseControllerRef.current?.abort();
|
||||
commonStore.setCompletionGenerating(false);
|
||||
} else {
|
||||
commonStore.setCompletionGenerating(true);
|
||||
onSubmit(prompt);
|
||||
}
|
||||
}}>{!commonStore.completionGenerating ? t('Generate') : t('Stop')}</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
||||
export const Completion: FC = observer(() => {
|
||||
return (
|
||||
<div className="flex flex-col gap-1 p-2 h-full overflow-hidden">
|
||||
<WorkHeader />
|
||||
<CompletionPanel />
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -39,6 +39,7 @@ export type ModelParameters = {
|
||||
storedLayers: number;
|
||||
maxStoredLayers: number;
|
||||
enableHighPrecisionForLastLayer: boolean;
|
||||
useCustomCuda?: boolean;
|
||||
}
|
||||
|
||||
export type ModelConfig = {
|
||||
@@ -60,7 +61,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 4,
|
||||
@@ -79,7 +80,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
@@ -98,7 +99,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 24,
|
||||
@@ -136,7 +137,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 8,
|
||||
@@ -174,7 +175,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
@@ -193,7 +194,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
@@ -231,7 +232,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 18,
|
||||
@@ -269,7 +270,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
@@ -307,7 +308,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
@@ -345,7 +346,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 22,
|
||||
@@ -383,7 +384,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
@@ -421,7 +422,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-14B-v11x-Eng99%-Other1%-20230501-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'int8',
|
||||
storedLayers: 41,
|
||||
@@ -440,7 +441,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-14B-v11x-Eng99%-Other1%-20230501-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
|
||||
device: 'CUDA',
|
||||
precision: 'fp16',
|
||||
storedLayers: 41,
|
||||
@@ -459,7 +460,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-1B5-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
@@ -478,7 +479,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-3B-v11-Eng99%-Other1%-20230425-ctx4096.pth',
|
||||
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
@@ -516,7 +517,7 @@ export const defaultModelConfigs: ModelConfig[] = [
|
||||
frequencyPenalty: 0.4
|
||||
},
|
||||
modelParameters: {
|
||||
modelName: 'RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth',
|
||||
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
|
||||
device: 'CPU',
|
||||
precision: 'fp32',
|
||||
storedLayers: 41,
|
||||
@@ -642,7 +643,7 @@ export const Configs: FC = observer(() => {
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('Max Response Token *')}
|
||||
<Labeled 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={selectedConfig.apiParameters.maxResponseToken} min={100} max={8100}
|
||||
@@ -654,7 +655,7 @@ export const Configs: FC = observer(() => {
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('Temperature *')}
|
||||
<Labeled label={t('Temperature') + ' *'}
|
||||
desc={t('Sampling temperature, the higher the stronger the randomness and creativity, while the lower, the more focused and deterministic it will be.')}
|
||||
content={
|
||||
<ValuedSlider value={selectedConfig.apiParameters.temperature} min={0} max={2} step={0.1}
|
||||
@@ -665,7 +666,7 @@ export const Configs: FC = observer(() => {
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('Top_P *')}
|
||||
<Labeled label={t('Top_P') + ' *'}
|
||||
desc={t('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={selectedConfig.apiParameters.topP} min={0} max={1} step={0.1} input
|
||||
@@ -675,7 +676,7 @@ export const Configs: FC = observer(() => {
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('Presence Penalty *')}
|
||||
<Labeled 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={selectedConfig.apiParameters.presencePenalty} min={-2} max={2}
|
||||
@@ -686,7 +687,7 @@ export const Configs: FC = observer(() => {
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('Frequency Penalty *')}
|
||||
<Labeled 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={selectedConfig.apiParameters.frequencyPenalty} min={-2} max={2}
|
||||
@@ -754,7 +755,7 @@ export const Configs: FC = observer(() => {
|
||||
</Dropdown>
|
||||
} />
|
||||
<Labeled label={t('Precision')}
|
||||
desc={t('int8 uses less VRAM, and is faster, 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, and fp32 has the best quality.')}
|
||||
content={
|
||||
<Dropdown style={{ minWidth: 0 }} className="grow"
|
||||
value={selectedConfig.modelParameters.precision}
|
||||
@@ -771,6 +772,7 @@ export const Configs: FC = observer(() => {
|
||||
<Option>fp32</Option>
|
||||
</Dropdown>
|
||||
} />
|
||||
<div />
|
||||
<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={
|
||||
@@ -792,6 +794,16 @@ export const Configs: FC = observer(() => {
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
<Labeled label={t('Use Custom CUDA kernel to Accelerate')}
|
||||
desc={t('Enabling this option can greatly improve inference speed, but there may be compatibility issues. If it fails to start, please turn off this option.')}
|
||||
content={
|
||||
<Switch checked={selectedConfig.modelParameters.useCustomCuda}
|
||||
onChange={(e, data) => {
|
||||
setSelectedConfigModelParams({
|
||||
useCustomCuda: data.checked
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import React, { FC } from 'react';
|
||||
import { Page } from '../components/Page';
|
||||
import { Dropdown, Option, Switch } from '@fluentui/react-components';
|
||||
import { Dropdown, Input, Option, Switch } from '@fluentui/react-components';
|
||||
import { Labeled } from '../components/Labeled';
|
||||
import commonStore from '../stores/commonStore';
|
||||
import { observer } from 'mobx-react-lite';
|
||||
@@ -20,6 +20,7 @@ export type SettingsType = {
|
||||
autoUpdatesCheck: boolean
|
||||
giteeUpdatesSource: boolean
|
||||
cnMirror: boolean
|
||||
host: string
|
||||
}
|
||||
|
||||
export const Settings: FC = observer(() => {
|
||||
@@ -87,6 +88,14 @@ export const Settings: FC = observer(() => {
|
||||
}} />
|
||||
} />
|
||||
}
|
||||
<Labeled label={t('API Host')} flex spaceBetween content={
|
||||
<Input value={commonStore.settings.host}
|
||||
onChange={(e, data) => {
|
||||
commonStore.setSettings({
|
||||
host: data.value
|
||||
});
|
||||
}} />
|
||||
} />
|
||||
</div>
|
||||
} />
|
||||
);
|
||||
|
||||
@@ -3,6 +3,7 @@ import { Configs } from './Configs';
|
||||
import {
|
||||
ArrowDownload20Regular,
|
||||
Chat20Regular,
|
||||
ClipboardEdit20Regular,
|
||||
DataUsageSettings20Regular,
|
||||
DocumentSettings20Regular,
|
||||
Home20Regular,
|
||||
@@ -17,6 +18,7 @@ import { Train } from './Train';
|
||||
import { Settings } from './Settings';
|
||||
import { About } from './About';
|
||||
import { Downloads } from './Downloads';
|
||||
import { Completion } from './Completion';
|
||||
|
||||
type NavigationItem = {
|
||||
label: string;
|
||||
@@ -41,6 +43,13 @@ export const pages: NavigationItem[] = [
|
||||
element: <Chat />,
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Completion',
|
||||
path: '/completion',
|
||||
icon: <ClipboardEdit20Regular />,
|
||||
element: <Completion />,
|
||||
top: true
|
||||
},
|
||||
{
|
||||
label: 'Configs',
|
||||
path: '/configs',
|
||||
|
||||
@@ -1,12 +1,26 @@
|
||||
import commonStore from './stores/commonStore';
|
||||
import { ReadJson } from '../wailsjs/go/backend_golang/App';
|
||||
import { Cache, checkUpdate, downloadProgramFiles, LocalConfig, refreshModels, saveCache } from './utils';
|
||||
import { FileExists, ReadJson } from '../wailsjs/go/backend_golang/App';
|
||||
import {
|
||||
Cache,
|
||||
checkUpdate,
|
||||
deleteDynamicProgramFiles,
|
||||
downloadProgramFiles,
|
||||
LocalConfig,
|
||||
refreshModels,
|
||||
saveCache
|
||||
} from './utils';
|
||||
import { getStatus } from './apis';
|
||||
import { EventsOn } from '../wailsjs/runtime';
|
||||
import { defaultModelConfigs } from './pages/Configs';
|
||||
|
||||
export async function startup() {
|
||||
downloadProgramFiles();
|
||||
FileExists('cache.json').then((exists) => {
|
||||
if (exists)
|
||||
downloadProgramFiles();
|
||||
else {
|
||||
deleteDynamicProgramFiles().then(downloadProgramFiles);
|
||||
}
|
||||
});
|
||||
EventsOn('downloadList', (data) => {
|
||||
if (data)
|
||||
commonStore.setDownloadList(data);
|
||||
@@ -21,12 +35,12 @@ export async function startup() {
|
||||
|
||||
getStatus(500).then(status => { // depends on config api port
|
||||
if (status)
|
||||
commonStore.setModelStatus(status);
|
||||
commonStore.setStatus(status);
|
||||
});
|
||||
}
|
||||
|
||||
async function initRemoteText() {
|
||||
await fetch('https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/manifest.json', { cache: 'no-cache' })
|
||||
await fetch('https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/manifest.json', { cache: 'no-cache' })
|
||||
.then(r => r.json()).then((data) => {
|
||||
if (data.introduction)
|
||||
commonStore.setIntroduction(data.introduction);
|
||||
|
||||
@@ -10,6 +10,7 @@ import { SettingsType } from '../pages/Settings';
|
||||
import { IntroductionContent } from '../pages/Home';
|
||||
import { AboutContent } from '../pages/About';
|
||||
import i18n from 'i18next';
|
||||
import { CompletionPreset } from '../pages/Completion';
|
||||
|
||||
export enum ModelStatus {
|
||||
Offline,
|
||||
@@ -18,20 +19,33 @@ export enum ModelStatus {
|
||||
Working,
|
||||
}
|
||||
|
||||
export type Status = {
|
||||
modelStatus: ModelStatus;
|
||||
pid: number;
|
||||
device_name: string;
|
||||
}
|
||||
|
||||
class CommonStore {
|
||||
// global
|
||||
modelStatus: ModelStatus = ModelStatus.Offline;
|
||||
status: Status = {
|
||||
modelStatus: ModelStatus.Offline,
|
||||
pid: 0,
|
||||
device_name: 'CPU'
|
||||
};
|
||||
depComplete: boolean = false;
|
||||
// home
|
||||
introduction: IntroductionContent = manifest.introduction;
|
||||
// chat
|
||||
conversations: Conversations = {};
|
||||
conversationsOrder: string[] = [];
|
||||
// completion
|
||||
completionPreset: CompletionPreset | null = null;
|
||||
completionGenerating: boolean = false;
|
||||
// configs
|
||||
currentModelConfigIndex: number = 0;
|
||||
modelConfigs: ModelConfig[] = [];
|
||||
// models
|
||||
modelSourceManifestList: string = 'https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/manifest.json;';
|
||||
modelSourceManifestList: string = 'https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/manifest.json;';
|
||||
modelSourceList: ModelSourceItem[] = [];
|
||||
// downloads
|
||||
downloadList: DownloadStatus[] = [];
|
||||
@@ -41,7 +55,8 @@ class CommonStore {
|
||||
darkMode: !isSystemLightMode(),
|
||||
autoUpdatesCheck: true,
|
||||
giteeUpdatesSource: getUserLanguage() === 'zh',
|
||||
cnMirror: getUserLanguage() === 'zh'
|
||||
cnMirror: getUserLanguage() === 'zh',
|
||||
host: '127.0.0.1'
|
||||
};
|
||||
// about
|
||||
about: AboutContent = manifest.about;
|
||||
@@ -54,8 +69,8 @@ class CommonStore {
|
||||
return this.modelConfigs[this.currentModelConfigIndex];
|
||||
};
|
||||
|
||||
setModelStatus = (status: ModelStatus) => {
|
||||
this.modelStatus = status;
|
||||
setStatus = (status: Partial<Status>) => {
|
||||
this.status = { ...this.status, ...status };
|
||||
};
|
||||
|
||||
setCurrentConfigIndex = (index: number, saveConfig: boolean = true) => {
|
||||
@@ -145,6 +160,14 @@ class CommonStore {
|
||||
setConversationsOrder = (value: string[]) => {
|
||||
this.conversationsOrder = value;
|
||||
};
|
||||
|
||||
setCompletionPreset(value: CompletionPreset) {
|
||||
this.completionPreset = value;
|
||||
}
|
||||
|
||||
setCompletionGenerating(value: boolean) {
|
||||
this.completionGenerating = value;
|
||||
}
|
||||
}
|
||||
|
||||
export default new CommonStore();
|
||||
@@ -1,7 +1,6 @@
|
||||
import {
|
||||
AddToDownloadList,
|
||||
DeleteFile,
|
||||
DownloadFile,
|
||||
FileExists,
|
||||
ListDirFiles,
|
||||
ReadJson,
|
||||
@@ -178,21 +177,24 @@ export function downloadProgramFiles() {
|
||||
manifest.programFiles.forEach(({ url, path }) => {
|
||||
FileExists(path).then(exists => {
|
||||
if (!exists)
|
||||
AddToDownloadList(path, url);
|
||||
AddToDownloadList(path, url.replace('@master', '@v' + manifest.version));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export function forceDownloadProgramFiles() {
|
||||
manifest.programFiles.forEach(({ url, path }) => {
|
||||
DownloadFile(path, url);
|
||||
AddToDownloadList(path, url.replace('@master', '@v' + manifest.version));
|
||||
});
|
||||
}
|
||||
|
||||
export function deletePythonProgramFiles() {
|
||||
export async function deleteDynamicProgramFiles() {
|
||||
let promises: Promise<void>[] = [];
|
||||
manifest.programFiles.forEach(({ path }) => {
|
||||
if (path.endsWith('.py') && !path.includes('get-pip.py'))
|
||||
DeleteFile(path);
|
||||
if ((path.endsWith('.py') && !path.includes('get-pip.py')) || path.includes('requirements') || path.endsWith('.pyd'))
|
||||
promises.push(DeleteFile(path));
|
||||
});
|
||||
return await Promise.allSettled(promises).catch(() => {
|
||||
});
|
||||
}
|
||||
|
||||
@@ -223,10 +225,15 @@ export async function checkUpdate(notifyEvenLatest: boolean = false) {
|
||||
`https://github.com/josStorer/RWKV-Runner/releases/download/${versionTag}/RWKV-Runner_windows_x64.exe` :
|
||||
`https://gitee.com/josc146/RWKV-Runner/releases/download/${versionTag}/RWKV-Runner_windows_x64.exe`;
|
||||
toastWithButton(t('New Version Available') + ': ' + versionTag, t('Update'), () => {
|
||||
deletePythonProgramFiles();
|
||||
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: 10000
|
||||
});
|
||||
setTimeout(() => {
|
||||
UpdateApp(updateUrl).catch((e) => {
|
||||
toast(t('Update Error, Please restart this program') + ' - ' + e.message || e, {
|
||||
toast(t('Update Error') + ' - ' + e.message || e, {
|
||||
type: 'error',
|
||||
position: 'bottom-left',
|
||||
autoClose: false
|
||||
@@ -257,13 +264,30 @@ export async function checkUpdate(notifyEvenLatest: boolean = false) {
|
||||
}
|
||||
|
||||
export function toastWithButton(text: string, buttonText: string, onClickButton: () => void, options?: ToastOptions) {
|
||||
return toast(
|
||||
let triggered = false;
|
||||
const id = toast(
|
||||
<div className="flex flex-row items-center justify-between">
|
||||
<div>{text}</div>
|
||||
<Button appearance="primary" onClick={onClickButton}>{buttonText}</Button>
|
||||
<Button appearance="primary" onClick={() => {
|
||||
if (!triggered) {
|
||||
triggered = true;
|
||||
toast.dismiss(id);
|
||||
onClickButton();
|
||||
}
|
||||
}}>{buttonText}</Button>
|
||||
</div>,
|
||||
{
|
||||
type: 'info',
|
||||
...options
|
||||
});
|
||||
return id;
|
||||
}
|
||||
|
||||
export function getSupportedCustomCudaFile() {
|
||||
if ([' 10', ' 16', ' 20', ' 30'].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)))
|
||||
return './backend-python/wkv_cuda_utils/wkv_cuda40.pyd';
|
||||
else
|
||||
return '';
|
||||
}
|
||||
4
frontend/wailsjs/go/backend_golang/App.d.ts
vendored
4
frontend/wailsjs/go/backend_golang/App.d.ts
vendored
@@ -8,6 +8,8 @@ export function ContinueDownload(arg1:string):Promise<void>;
|
||||
|
||||
export function ConvertModel(arg1:string,arg2:string,arg3:string):Promise<string>;
|
||||
|
||||
export function CopyFile(arg1:string,arg2:string):Promise<void>;
|
||||
|
||||
export function DeleteFile(arg1:string):Promise<void>;
|
||||
|
||||
export function DepCheck():Promise<void>;
|
||||
@@ -32,6 +34,6 @@ export function ReadJson(arg1:string):Promise<any>;
|
||||
|
||||
export function SaveJson(arg1:string,arg2:any):Promise<void>;
|
||||
|
||||
export function StartServer(arg1:number):Promise<string>;
|
||||
export function StartServer(arg1:number,arg2:string):Promise<string>;
|
||||
|
||||
export function UpdateApp(arg1:string):Promise<boolean>;
|
||||
|
||||
@@ -14,6 +14,10 @@ export function ConvertModel(arg1, arg2, arg3) {
|
||||
return window['go']['backend_golang']['App']['ConvertModel'](arg1, arg2, arg3);
|
||||
}
|
||||
|
||||
export function CopyFile(arg1, arg2) {
|
||||
return window['go']['backend_golang']['App']['CopyFile'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function DeleteFile(arg1) {
|
||||
return window['go']['backend_golang']['App']['DeleteFile'](arg1);
|
||||
}
|
||||
@@ -62,8 +66,8 @@ export function SaveJson(arg1, arg2) {
|
||||
return window['go']['backend_golang']['App']['SaveJson'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function StartServer(arg1) {
|
||||
return window['go']['backend_golang']['App']['StartServer'](arg1);
|
||||
export function StartServer(arg1, arg2) {
|
||||
return window['go']['backend_golang']['App']['StartServer'](arg1, arg2);
|
||||
}
|
||||
|
||||
export function UpdateApp(arg1) {
|
||||
|
||||
@@ -1,61 +1,73 @@
|
||||
{
|
||||
"version": "1.0.0",
|
||||
"version": "1.0.6",
|
||||
"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的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。"
|
||||
},
|
||||
"about": {
|
||||
"en": "<div align=\"center\">\n\nProject Source Code:\nhttps://github.com/josStorer/RWKV-Runner\nAuthor: [@josStorer](https://github.com/josStorer)\n\nRelated Repositories:\nRWKV-4-Raven: https://huggingface.co/BlinkDL/rwkv-4-raven/tree/main\nChatRWKV: https://github.com/BlinkDL/ChatRWKV\nRWKV-LM: https://github.com/BlinkDL/RWKV-LM\n\n</div>",
|
||||
"zh": "<div align=\"center\">\n\n本项目源码:\nhttps://github.com/josStorer/RWKV-Runner\n作者: [@josStorer](https://github.com/josStorer)\n\n相关仓库:\nRWKV-4-Raven: https://huggingface.co/BlinkDL/rwkv-4-raven/tree/main\nChatRWKV: https://github.com/BlinkDL/ChatRWKV\nRWKV-LM: https://github.com/BlinkDL/RWKV-LM\n\n</div>"
|
||||
"zh": "<div align=\"center\">\n\n本项目源码:\nhttps://github.com/josStorer/RWKV-Runner\n作者: [@josStorer](https://github.com/josStorer)\n演示与常见问题说明视频: https://www.bilibili.com/video/BV1hM4y1v76R\n\n相关仓库:\nRWKV-4-Raven: https://huggingface.co/BlinkDL/rwkv-4-raven/tree/main\nChatRWKV: https://github.com/BlinkDL/ChatRWKV\nRWKV-LM: https://github.com/BlinkDL/RWKV-LM\n\n</div>"
|
||||
},
|
||||
"localModelDir": "models",
|
||||
"programFiles": [
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/requirements.txt",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/requirements.txt",
|
||||
"path": "backend-python/requirements.txt"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/requirements_versions.txt",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/requirements_versions.txt",
|
||||
"path": "backend-python/requirements_versions.txt"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/main.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/main.py",
|
||||
"path": "backend-python/main.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/global_var.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/global_var.py",
|
||||
"path": "backend-python/global_var.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/convert_model.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/convert_model.py",
|
||||
"path": "backend-python/convert_model.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/dep_check.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/dep_check.py",
|
||||
"path": "backend-python/dep_check.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/routes/completion.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/routes/completion.py",
|
||||
"path": "backend-python/routes/completion.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/routes/config.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/routes/config.py",
|
||||
"path": "backend-python/routes/config.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/utils/ngrok.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/utils/ngrok.py",
|
||||
"path": "backend-python/utils/ngrok.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/utils/rwkv.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/utils/rwkv.py",
|
||||
"path": "backend-python/utils/rwkv.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/utils/torch.py",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/utils/torch.py",
|
||||
"path": "backend-python/utils/torch.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner/backend-python/20B_tokenizer.json",
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/wkv_cuda_utils/wkv_cuda10_30.pyd",
|
||||
"path": "backend-python/wkv_cuda_utils/wkv_cuda10_30.pyd"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/wkv_cuda_utils/wkv_cuda40.pyd",
|
||||
"path": "backend-python/wkv_cuda_utils/wkv_cuda40.pyd"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/wkv_cuda_utils/wkv_cuda_model.py",
|
||||
"path": "backend-python/wkv_cuda_utils/wkv_cuda_model.py"
|
||||
},
|
||||
{
|
||||
"url": "https://cdn.jsdelivr.net/gh/josstorer/RWKV-Runner@master/backend-python/20B_tokenizer.json",
|
||||
"path": "backend-python/20B_tokenizer.json"
|
||||
},
|
||||
{
|
||||
@@ -76,6 +88,18 @@
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-3B-v11-Eng99%25-Other1%25-20230425-ctx4096.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-3B-v11-Eng99%25-Other1%25-20230425-ctx4096.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth",
|
||||
"desc": {
|
||||
"en": "English 3B v12",
|
||||
"zh": "英文 3B v12"
|
||||
},
|
||||
"size": 5969345074,
|
||||
"SHA256": "1eea1845acfe9729dfdaec66a8d1aeb91a1287d94bebbca5529c13c050540b33",
|
||||
"lastUpdated": "2023-05-21T07:13:25",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-3B-v12-Eng98%25-Other2%25-20230520-ctx4096.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-3B-v12-Eng98%25-Other2%25-20230520-ctx4096.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-7B-v10x-Eng49%-Chn50%-Other1%-20230423-ctx4096.pth",
|
||||
"desc": {
|
||||
@@ -100,6 +124,18 @@
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-7B-v11-Eng49%25-Chn49%25-Jpn1%25-Other1%25-20230430-ctx8192.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-7B-v11-Eng49%25-Chn49%25-Jpn1%25-Other1%25-20230430-ctx8192.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth",
|
||||
"desc": {
|
||||
"en": "English 7B v12",
|
||||
"zh": "英文 7B v12"
|
||||
},
|
||||
"size": 14785389618,
|
||||
"SHA256": "5a725eaeb9e09b724de6c97e6845dd0283097c7920acd05b46852ab7afa9ec32",
|
||||
"lastUpdated": "2023-05-22T10:32:17",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-7B-v12-Eng98%25-Other2%25-20230521-ctx8192.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-7B-v12-Eng98%25-Other2%25-20230521-ctx8192.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-7B-v11x-Eng99%-Other1%-20230429-ctx8192.pth",
|
||||
"desc": {
|
||||
@@ -124,6 +160,18 @@
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-1B5-v11-Eng99%25-Other1%25-20230425-ctx4096.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-1B5-v11-Eng99%25-Other1%25-20230425-ctx4096.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth",
|
||||
"desc": {
|
||||
"en": "English 1B5 v12",
|
||||
"zh": "英文 1B5 v12"
|
||||
},
|
||||
"size": 3030279730,
|
||||
"SHA256": "6bbbffb3ee2372dfa9ef49c599e9a2bc0a01b94b6a264ba9bf5bd524fc38f723",
|
||||
"lastUpdated": "2023-05-21T07:08:56",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-1B5-v12-Eng98%25-Other2%25-20230520-ctx4096.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-1B5-v12-Eng98%25-Other2%25-20230520-ctx4096.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-3B-v11-Eng49%-Chn49%-Jpn1%-Other1%-20230429-ctx4096.pth",
|
||||
"desc": {
|
||||
@@ -136,6 +184,18 @@
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-3B-v11-Eng49%25-Chn49%25-Jpn1%25-Other1%25-20230429-ctx4096.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-3B-v11-Eng49%25-Chn49%25-Jpn1%25-Other1%25-20230429-ctx4096.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth",
|
||||
"desc": {
|
||||
"en": "English 14B v12",
|
||||
"zh": "英文 14B v12"
|
||||
},
|
||||
"size": 28297309490,
|
||||
"SHA256": "1193b5a9ceab572e4dbb9ed1d798eab7bf4793d18904d08bd4bf183579338ae7",
|
||||
"lastUpdated": "2023-05-23T11:22:41",
|
||||
"url": "https://huggingface.co/BlinkDL/rwkv-4-raven/blob/main/RWKV-4-Raven-14B-v12-Eng98%25-Other2%25-20230523-ctx8192.pth",
|
||||
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-4-raven/resolve/main/RWKV-4-Raven-14B-v12-Eng98%25-Other2%25-20230523-ctx8192.pth"
|
||||
},
|
||||
{
|
||||
"name": "RWKV-4-Raven-14B-v11x-Eng99%-Other1%-20230501-ctx8192.pth",
|
||||
"desc": {
|
||||
|
||||
Reference in New Issue
Block a user