Compare commits

..

14 Commits

Author SHA1 Message Date
josc146
b8712e0b89 release v1.5.0 2023-11-05 21:10:21 +08:00
josc146
37dda4333d chat attachment is now related to single message 2023-11-05 21:05:06 +08:00
josc146
64826b9af7 fix log encoding error 2023-11-05 21:00:31 +08:00
josc146
47b0c35441 update ngrok_connect 2023-11-04 20:22:28 +08:00
josc146
1dcda47013 improve startup process 2023-11-04 20:21:55 +08:00
josc146
1f81a1e5a8 upgrade to rwkv 0.8.20 2023-11-03 23:27:14 +08:00
josc146
35e92d2aef chore 2023-11-03 23:22:52 +08:00
josc146
0d99e5549e port occupied detection 2023-11-03 21:18:42 +08:00
josc146
fed1594ddc fix stop button status of Chat page 2023-10-30 21:09:23 +08:00
josc146
14b90bb36b improve dml mode performance (20% faster, https://github.com/BlinkDL/ChatRWKV/pull/181) 2023-10-30 20:24:57 +08:00
josc146
f86b7f1f08 python38 compatibility 2023-10-29 14:11:11 +08:00
josc146
54355d5a7a improve the compatibility between frontend presets and chatgpt api 2023-10-28 23:06:19 +08:00
josc146
ff7306349a improve memory usage of state cache 2023-10-28 23:04:49 +08:00
github-actions[bot]
77df56cddc release v1.4.9 2023-10-27 06:04:00 +00:00
23 changed files with 350 additions and 462 deletions

View File

@@ -2,40 +2,28 @@
### Features ### Features
- allow conversation with some document (.pdf, .txt) (Experimental) - chat attachment is now related to single message (Experimental)
- add `/file-to-text` api - port occupied detection
- allow avatarImg to be local absolute path
- base64 preset support
### Upgrades ### Upgrades
- upgrade to rwkv 0.8.16 (DirectML support; rwkv 5.2 no longer needs to ensure custom cuda kernel enabled) - upgrade to rwkv 0.8.20
- upgrade to webgpu 0.2.2 (WebGPU Mode is now recommended for AMD and Intel
Users) (https://github.com/josStorer/ai00_rwkv_server)
- upgrade python packages
### Improvements ### Improvements
- improve cuda kernel compatibility (compute compatibility 5.3, Jetson Nano, Nvidia 10 Series+) - improve the compatibility between frontend presets and chatgpt api
- RWKVType now no longer relies on the file name (use emb) - improve memory usage of state cache
- improve message interruption and retry for Chat page
- update sample.jsonl of LoRA finetune
- update api stop strategy for better custom user_name and assistant_name support
- edited chat message now is marked as Normal
- change default World series prefix to User/Assistant
### Chores ### Chores
- update manifest.json (RWKV-5) - update ngrok_connect
- update readme and client text description - python38 compatibility
- add pip --no-warn-script-location - adjust startup process
- mark rwkv raven series as old model
- chore
### Fixes ### Fixes
- fix linux kernel (partial revert 68228a45) - fix log encoding error
- fix the `make` command on Linux and macOS, no longer need manual operations on the wsl.go file. (#158, #173, #207) - fix stop button status of Chat page
## Install ## Install

View File

@@ -5,12 +5,15 @@ import (
"bufio" "bufio"
"embed" "embed"
"errors" "errors"
"fmt"
"io" "io"
"io/fs" "io/fs"
"net"
"os" "os"
"os/exec" "os/exec"
"path/filepath" "path/filepath"
"runtime" "runtime"
"strconv"
"strings" "strings"
) )
@@ -205,3 +208,12 @@ func Unzip(source, destination string) error {
} }
return nil return nil
} }
func (a *App) IsPortAvailable(port int) bool {
l, err := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%s", strconv.Itoa(port)))
if err != nil {
return false
}
defer l.Close()
return true
}

View File

@@ -2,16 +2,47 @@ import time
start_time = time.time() start_time = time.time()
import setuptools # avoid warnings import argparse
from typing import Union, Sequence
def get_args(args: Union[Sequence[str], None] = None):
parser = argparse.ArgumentParser()
group = parser.add_argument_group(title="server arguments")
group.add_argument(
"--port",
type=int,
default=8000,
help="port to run the server on (default: 8000)",
)
group.add_argument(
"--host",
type=str,
default="127.0.0.1",
help="host to run the server on (default: 127.0.0.1)",
)
group = parser.add_argument_group(title="mode arguments")
group.add_argument(
"--rwkv-beta",
action="store_true",
help="whether to use rwkv-beta (default: False)",
)
args = parser.parse_args(args)
return args
if __name__ == "__main__":
args = get_args()
import os import os
import sys import sys
import argparse
from typing import Sequence
from contextlib import asynccontextmanager
sys.path.append(os.path.dirname(os.path.realpath(__file__))) sys.path.append(os.path.dirname(os.path.realpath(__file__)))
import psutil import psutil
from contextlib import asynccontextmanager
from fastapi import Depends, FastAPI from fastapi import Depends, FastAPI
from fastapi.middleware.cors import CORSMiddleware from fastapi.middleware.cors import CORSMiddleware
import uvicorn import uvicorn
@@ -77,34 +108,7 @@ def exit():
parent.kill() parent.kill()
def get_args(args: Union[Sequence[str], None] = None):
parser = argparse.ArgumentParser()
group = parser.add_argument_group(title="server arguments")
group.add_argument(
"--port",
type=int,
default=8000,
help="port to run the server on (default: 8000)",
)
group.add_argument(
"--host",
type=str,
default="127.0.0.1",
help="host to run the server on (default: 127.0.0.1)",
)
group = parser.add_argument_group(title="mode arguments")
group.add_argument(
"--rwkv-beta",
action="store_true",
help="whether to use rwkv-beta (default: False)",
)
args = parser.parse_args(args)
return args
if __name__ == "__main__": if __name__ == "__main__":
args = get_args()
os.environ["RWKV_RUNNER_PARAMS"] = " ".join(sys.argv[1:]) os.environ["RWKV_RUNNER_PARAMS"] = " ".join(sys.argv[1:])
print("--- %s seconds ---" % (time.time() - start_time)) print("--- %s seconds ---" % (time.time() - start_time))
uvicorn.run("main:app", port=args.port, host=args.host, workers=1) uvicorn.run("main:app", port=args.port, host=args.host, workers=1)

Binary file not shown.

View File

@@ -9,7 +9,7 @@ router = APIRouter()
trie = None trie = None
dtrie: Dict = {} dtrie: Dict = {}
max_trie_len = 3000 max_trie_len = 300
loop_start_id = 1 # to prevent preloaded prompts from being deleted loop_start_id = 1 # to prevent preloaded prompts from being deleted
loop_del_trie_id = loop_start_id loop_del_trie_id = loop_start_id

View File

@@ -3,6 +3,8 @@
#include <cuda_fp16.h> #include <cuda_fp16.h>
#include <cuda_runtime.h> #include <cuda_runtime.h>
#include <torch/extension.h> #include <torch/extension.h>
#include <c10/cuda/CUDAGuard.h>
#include <ATen/cuda/CUDAContext.h>
#define CUBLAS_CHECK(condition) \ #define CUBLAS_CHECK(condition) \
for (cublasStatus_t _cublas_check_status = (condition); \ for (cublasStatus_t _cublas_check_status = (condition); \
@@ -18,26 +20,13 @@
"CUDA error " + std::string(cudaGetErrorString(_cuda_check_status)) + \ "CUDA error " + std::string(cudaGetErrorString(_cuda_check_status)) + \
" at " + std::to_string(__LINE__)); " at " + std::to_string(__LINE__));
cublasHandle_t get_cublas_handle() {
static cublasHandle_t cublas_handle = []() {
cublasHandle_t handle = nullptr;
CUBLAS_CHECK(cublasCreate(&handle));
#if CUDA_VERSION < 11000
CUBLAS_CHECK(cublasSetMathMode(handle, CUBLAS_TENSOR_OP_MATH));
#else
CUBLAS_CHECK(cublasSetMathMode(handle, CUBLAS_DEFAULT_MATH));
#endif // CUDA_VERSION < 11000
return handle;
}();
return cublas_handle;
}
/* /*
NOTE: blas gemm is column-major by default, but we need row-major output. NOTE: blas gemm is column-major by default, but we need row-major output.
The data of row-major, transposed matrix is exactly the same as the The data of row-major, transposed matrix is exactly the same as the
column-major, non-transposed matrix, and C = A * B ---> C^T = B^T * A^T column-major, non-transposed matrix, and C = A * B ---> C^T = B^T * A^T
*/ */
void gemm_fp16_cublas(torch::Tensor a, torch::Tensor b, torch::Tensor c) { void gemm_fp16_cublas(torch::Tensor a, torch::Tensor b, torch::Tensor c) {
const at::cuda::OptionalCUDAGuard device_guard(device_of(a));
const auto cuda_data_type = CUDA_R_16F; const auto cuda_data_type = CUDA_R_16F;
const auto cuda_c_data_type = const auto cuda_c_data_type =
c.dtype() == torch::kFloat32 ? CUDA_R_32F : CUDA_R_16F; c.dtype() == torch::kFloat32 ? CUDA_R_32F : CUDA_R_16F;
@@ -55,7 +44,7 @@ void gemm_fp16_cublas(torch::Tensor a, torch::Tensor b, torch::Tensor c) {
const int cublas_lda = m; const int cublas_lda = m;
const int cublas_ldb = k; const int cublas_ldb = k;
const int cublas_ldc = m; const int cublas_ldc = m;
cublasHandle_t cublas_handle = get_cublas_handle(); cublasHandle_t cublas_handle = at::cuda::getCurrentCUDABlasHandle();
#if CUDA_VERSION >= 11000 #if CUDA_VERSION >= 11000
cublasGemmAlgo_t algo = CUBLAS_GEMM_DEFAULT; cublasGemmAlgo_t algo = CUBLAS_GEMM_DEFAULT;

View File

@@ -1,5 +1,6 @@
#include <torch/extension.h> #include <torch/extension.h>
#include "ATen/ATen.h" #include "ATen/ATen.h"
#include <c10/cuda/CUDAGuard.h>
typedef at::BFloat16 bf16; typedef at::BFloat16 bf16;
typedef at::Half fp16; typedef at::Half fp16;
typedef float fp32; typedef float fp32;
@@ -9,12 +10,15 @@ void cuda_forward_fp16(int B, int T, int C, int H, float *state, fp16 *r, fp16 *
void cuda_forward_fp32(int B, int T, int C, int H, float *state, fp32 *r, fp32 *k, fp32 *v, float *w, fp32 *u, fp32 *y); void cuda_forward_fp32(int B, int T, int C, int H, float *state, fp32 *r, fp32 *k, fp32 *v, float *w, fp32 *u, fp32 *y);
void forward_bf16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) { void forward_bf16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
cuda_forward_bf16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), w.data_ptr<float>(), u.data_ptr<bf16>(), y.data_ptr<bf16>()); cuda_forward_bf16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), w.data_ptr<float>(), u.data_ptr<bf16>(), y.data_ptr<bf16>());
} }
void forward_fp16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) { void forward_fp16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
cuda_forward_fp16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp16>(), k.data_ptr<fp16>(), v.data_ptr<fp16>(), w.data_ptr<float>(), u.data_ptr<fp16>(), y.data_ptr<fp16>()); cuda_forward_fp16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp16>(), k.data_ptr<fp16>(), v.data_ptr<fp16>(), w.data_ptr<float>(), u.data_ptr<fp16>(), y.data_ptr<fp16>());
} }
void forward_fp32(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) { void forward_fp32(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
cuda_forward_fp32(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp32>(), k.data_ptr<fp32>(), v.data_ptr<fp32>(), w.data_ptr<float>(), u.data_ptr<fp32>(), y.data_ptr<fp32>()); cuda_forward_fp32(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp32>(), k.data_ptr<fp32>(), v.data_ptr<fp32>(), w.data_ptr<float>(), u.data_ptr<fp32>(), y.data_ptr<fp32>());
} }

View File

@@ -171,10 +171,86 @@ if os.environ.get("RWKV_CUDA_ON") == "1":
else: else:
os.environ["RWKV_CUDA_ON"] = "0" os.environ["RWKV_CUDA_ON"] = "0"
if os.environ.get("RWKV_CUDA_ON") == "1" and not DISABLE_CUBLAS_GEMM:
@MyStatic
def torch_mm8_seq(x, w, mx, rx, my, ry):
return x @ ((w.to(dtype=x.dtype) + 0.5) * ry * rx + my + mx)
@MyStatic
def torch_mm8_one(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":
@MyStatic @MyStatic
def gemm(a, b, output_dtype: Optional[torch.dtype] = None): def mm8_seq(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 torch_mm8_seq(x, w, mx, rx, my, ry)
@MyStatic
def mm8_one(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 torch_mm8_one(x, w, mx, rx, my, ry)
else:
@MyStatic
def mm8_seq(x, w, mx, rx, my, ry):
return torch_mm8_seq(x, w, mx, rx, my, ry)
@MyStatic
def mm8_one(x, w, mx, rx, my, ry):
return torch_mm8_one(x, w, mx, rx, my, ry)
def mm8(
x: torch.Tensor,
w: torch.Tensor,
mx: torch.Tensor,
rx: torch.Tensor,
my: torch.Tensor,
ry: torch.Tensor,
):
if len(x.shape) == 1:
return mm8_one(x, w, mx, rx, my, ry)
return mm8_seq(x, w, mx, rx, my, ry)
def matmul(
a,
b,
mx: Optional[torch.Tensor] = None,
rx: Optional[torch.Tensor] = None,
my: Optional[torch.Tensor] = None,
ry: Optional[torch.Tensor] = None,
output_dtype: Optional[torch.dtype] = None,
) -> torch.Tensor:
if output_dtype is None:
output_dtype = a.dtype
if b.dtype in [torch.float16, torch.bfloat16, torch.float32]:
assert a.dtype == b.dtype
return matmul_float(a, b, output_dtype=output_dtype)
elif b.dtype == torch.uint8:
assert mx is not None
assert rx is not None
assert my is not None
assert ry is not None
return mm8(a, b, mx, rx, my, ry).to(output_dtype)
else:
raise ValueError("Unsupported dtype")
if os.environ.get("RWKV_CUDA_ON") == "1" and not DISABLE_CUBLAS_GEMM:
def matmul_float(a, b, output_dtype: Optional[torch.dtype] = None):
if output_dtype is None: if output_dtype is None:
output_dtype = a.dtype output_dtype = a.dtype
if a.dtype == b.dtype == torch.float16 and a.device.type == "cuda": if a.dtype == b.dtype == torch.float16 and a.device.type == "cuda":
@@ -203,9 +279,7 @@ if os.environ.get("RWKV_CUDA_ON") == "1" and not DISABLE_CUBLAS_GEMM:
else: else:
def gemm(a, b, output_dtype: Optional[torch.dtype] = None): def matmul_float(a, b, output_dtype: Optional[torch.dtype] = None):
if output_dtype is None:
output_dtype = a.dtype
return (a @ b).to(output_dtype) return (a @ b).to(output_dtype)
@@ -644,42 +718,6 @@ class RWKV(MyModule):
def RUN_RWKV_5(self, B, T, C, H, state, r, k, v, w, u): def RUN_RWKV_5(self, B, T, C, H, state, r, k, v, w, u):
return self.RWKV_5.apply(B, T, C, H, state, r, k, v, w, u) return self.RWKV_5.apply(B, T, C, H, state, r, k, v, w, u)
@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 @MyFunction
@@ -711,43 +749,9 @@ class RWKV(MyModule):
kx = xx * k_mix + sx * (1 - k_mix) kx = xx * k_mix + sx * (1 - k_mix)
rx = xx * r_mix + sx * (1 - r_mix) rx = xx * r_mix + sx * (1 - r_mix)
r = torch.sigmoid(gemm(rx, rw)) r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
vx = torch.square(torch.relu(gemm(kx, kw))) vx = torch.square(torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)))
out = r * gemm(vx, vw) out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
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 return x + out, xx
######################################################################################################## ########################################################################################################
@@ -782,44 +786,9 @@ class RWKV(MyModule):
kx = xx * k_mix + sx * (1 - k_mix) kx = xx * k_mix + sx * (1 - k_mix)
rx = xx * r_mix + sx * (1 - r_mix) rx = xx * r_mix + sx * (1 - r_mix)
r = torch.sigmoid(gemm(rx, rw)) r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
vx = torch.square(torch.relu(gemm(kx, kw))) vx = torch.square(torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)))
out = r * gemm(vx, vw) out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
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, :] return x + out, xx[-1, :]
######################################################################################################## ########################################################################################################
@@ -865,9 +834,9 @@ class RWKV(MyModule):
vx = xx * v_mix + sx * (1 - v_mix) vx = xx * v_mix + sx * (1 - v_mix)
rx = xx * r_mix + sx * (1 - r_mix) rx = xx * r_mix + sx * (1 - r_mix)
r = torch.sigmoid(gemm(rx, rw)) r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
k = gemm(kx, kw, output_dtype=torch.float32) k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
v = gemm(vx, vw, output_dtype=torch.float32) v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
ww = t_first + k ww = t_first + k
p = torch.maximum(pp, ww) p = torch.maximum(pp, ww)
@@ -879,65 +848,7 @@ class RWKV(MyModule):
e1 = torch.exp(ww - p) e1 = torch.exp(ww - p)
e2 = torch.exp(k - p) e2 = torch.exp(k - p)
out = gemm(r * wkv, ow) out = matmul(r * wkv, ow, omx, orx, omy, ory)
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 return x + out, xx, e1 * aa + e2 * v, e1 * bb + e2, p
######################################################################################################## ########################################################################################################
@@ -984,9 +895,9 @@ class RWKV(MyModule):
vx = xx * v_mix + sx * (1 - v_mix) vx = xx * v_mix + sx * (1 - v_mix)
rx = xx * r_mix + sx * (1 - r_mix) rx = xx * r_mix + sx * (1 - r_mix)
r = torch.sigmoid(gemm(rx, rw)) r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
k = gemm(kx, kw, output_dtype=torch.float32) k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
v = gemm(vx, vw, output_dtype=torch.float32) v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
T = x.shape[0] T = x.shape[0]
for t in range(T): for t in range(T):
@@ -1004,72 +915,7 @@ class RWKV(MyModule):
aa = e1 * aa + e2 * vv aa = e1 * aa + e2 * vv
bb = e1 * bb + e2 bb = e1 * bb + e2
pp = p pp = p
out = gemm(r * sx, ow) out = matmul(r * sx, ow, omx, orx, omy, ory)
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 return x + out, xx[-1, :], aa, bb, pp
######################################################################################################## ########################################################################################################
@@ -1118,11 +964,11 @@ class RWKV(MyModule):
H = t_decay.shape[0] H = t_decay.shape[0]
S = x.shape[-1] // H S = x.shape[-1] // H
r = gemm(rx, rw, output_dtype=torch.float32).view(H, 1, S) r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(H, 1, S)
k = gemm(kx, kw, output_dtype=torch.float32).view(H, S, 1) k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(H, S, 1)
v = gemm(vx, vw, output_dtype=torch.float32).view(H, 1, S) v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(H, 1, S)
a = gemm(k, v) a = matmul(k, v)
out = r @ (t_first * a + s) out = r @ (t_first * a + s)
s = a + t_decay * s s = a + t_decay * s
@@ -1131,7 +977,7 @@ class RWKV(MyModule):
out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b
).squeeze(0) ).squeeze(0)
out = out.to(dtype=x.dtype) out = out.to(dtype=x.dtype)
out = gemm(out, ow) out = matmul(out, ow, omx, orx, omy, ory)
return x + out, xx, s return x + out, xx, s
@@ -1194,14 +1040,22 @@ class RWKV(MyModule):
w = w[:, :-T].reshape(-1, T, 2 * T - 1) w = w[:, :-T].reshape(-1, T, 2 * T - 1)
w = w[:, :, T - 1 :].reshape(H, T, T) w = w[:, :, T - 1 :].reshape(H, T, T)
r = gemm(rx, rw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1) r = (
matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32)
.view(T, H, S)
.transpose(0, 1)
)
k = ( k = (
gemm(kx, kw, output_dtype=torch.float32) matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
.view(T, H, S) .view(T, H, S)
.transpose(0, 1) .transpose(0, 1)
.transpose(-2, -1) .transpose(-2, -1)
) )
v = gemm(vx, vw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1) v = (
matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
.view(T, H, S)
.transpose(0, 1)
)
out = ((r @ k) * w) @ v + (r @ s) * wb out = ((r @ k) * w) @ v + (r @ s) * wb
s = ws * s + (k * wk) @ v s = ws * s + (k * wk) @ v
@@ -1209,7 +1063,7 @@ class RWKV(MyModule):
out = out.transpose(0, 1).contiguous().reshape(T, H * S) out = out.transpose(0, 1).contiguous().reshape(T, H * S)
out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b) out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b)
out = out.to(dtype=x.dtype) out = out.to(dtype=x.dtype)
out = gemm(out, ow) out = matmul(out, ow, omx, orx, omy, ory)
return x + out, xx[-1, :], s return x + out, xx[-1, :], s
@@ -1248,6 +1102,10 @@ class RWKV(MyModule):
rrx, rrx,
rmy, rmy,
rry, rry,
gmx,
grx,
gmy,
gry,
omx, omx,
orx, orx,
omy, omy,
@@ -1262,12 +1120,12 @@ class RWKV(MyModule):
H = t_decay.shape[0] H = t_decay.shape[0]
S = x.shape[-1] // H S = x.shape[-1] // H
r = gemm(rx, rw, output_dtype=torch.float32).view(H, 1, S) r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(H, 1, S)
k = gemm(kx, kw, output_dtype=torch.float32).view(H, S, 1) k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(H, S, 1)
v = gemm(vx, vw, output_dtype=torch.float32).view(H, 1, S) v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(H, 1, S)
g = F.silu(gemm(gx, gw)) g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
a = gemm(k, v) a = matmul(k, v)
out = r @ (t_first * a + s) out = r @ (t_first * a + s)
s = a + t_decay * s s = a + t_decay * s
@@ -1276,7 +1134,7 @@ class RWKV(MyModule):
out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b
).squeeze(0) ).squeeze(0)
out = out.to(dtype=x.dtype) * g out = out.to(dtype=x.dtype) * g
out = gemm(out, ow) out = matmul(out, ow, omx, orx, omy, ory)
return x + out, xx, s return x + out, xx, s
@@ -1313,6 +1171,10 @@ class RWKV(MyModule):
rrx, rrx,
rmy, rmy,
rry, rry,
gmx,
grx,
gmy,
gry,
omx, omx,
orx, orx,
omy, omy,
@@ -1342,15 +1204,23 @@ class RWKV(MyModule):
w = w[:, :-T].reshape(-1, T, 2 * T - 1) w = w[:, :-T].reshape(-1, T, 2 * T - 1)
w = w[:, :, T - 1 :].reshape(H, T, T) w = w[:, :, T - 1 :].reshape(H, T, T)
r = gemm(rx, rw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1) r = (
matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32)
.view(T, H, S)
.transpose(0, 1)
)
k = ( k = (
gemm(kx, kw, output_dtype=torch.float32) matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
.view(T, H, S) .view(T, H, S)
.transpose(0, 1) .transpose(0, 1)
.transpose(-2, -1) .transpose(-2, -1)
) )
v = gemm(vx, vw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1) v = (
g = F.silu(gemm(gx, gw)) matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
.view(T, H, S)
.transpose(0, 1)
)
g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
out = ((r @ k) * w) @ v + (r @ s) * wb out = ((r @ k) * w) @ v + (r @ s) * wb
s = ws * s + (k * wk) @ v s = ws * s + (k * wk) @ v
@@ -1358,7 +1228,7 @@ class RWKV(MyModule):
out = out.transpose(0, 1).contiguous().reshape(T, H * S) out = out.transpose(0, 1).contiguous().reshape(T, H * S)
out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b) out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b)
out = out.to(dtype=x.dtype) * g out = out.to(dtype=x.dtype) * g
out = gemm(out, ow) out = matmul(out, ow, omx, orx, omy, ory)
return x + out, xx[-1, :], s return x + out, xx[-1, :], s
@@ -1397,6 +1267,10 @@ class RWKV(MyModule):
rrx, rrx,
rmy, rmy,
rry, rry,
gmx,
grx,
gmy,
gry,
omx, omx,
orx, orx,
omy, omy,
@@ -1413,29 +1287,37 @@ class RWKV(MyModule):
S = x.shape[-1] // H S = x.shape[-1] // H
T = x.shape[0] T = x.shape[0]
r = gemm(rx, rw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1) r = (
matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32)
.view(T, H, S)
.transpose(0, 1)
)
k = ( k = (
gemm(kx, kw, output_dtype=torch.float32) matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
.view(T, H, S) .view(T, H, S)
.transpose(0, 1) .transpose(0, 1)
.transpose(-2, -1) .transpose(-2, -1)
) )
v = gemm(vx, vw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1) v = (
g = F.silu(gemm(gx, gw)) matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
.view(T, H, S)
.transpose(0, 1)
)
g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
out = torch.empty((T, H, S), dtype=r.dtype, device=r.device) out = torch.empty((T, H, S), dtype=r.dtype, device=r.device)
for t in range(T): for t in range(T):
rt = r[:, t : t + 1, :] rt = r[:, t : t + 1, :]
kt = k[:, :, t : t + 1] kt = k[:, :, t : t + 1]
vt = v[:, t : t + 1, :] vt = v[:, t : t + 1, :]
at = gemm(kt, vt) at = matmul(kt, vt)
out[t] = (rt @ (t_first * at + s)).squeeze(1) out[t] = (rt @ (t_first * at + s)).squeeze(1)
s = at + t_decay * s s = at + t_decay * s
out = out.reshape(T, H * S) out = out.reshape(T, H * S)
out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b) out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b)
out = out.to(dtype=x.dtype) * g out = out.to(dtype=x.dtype) * g
out = gemm(out, ow) out = matmul(out, ow, omx, orx, omy, ory)
return x + out, xx[-1, :], s return x + out, xx[-1, :], s
@@ -1486,63 +1368,12 @@ class RWKV(MyModule):
vx = xx * v_mix + sx * (1 - v_mix) vx = xx * v_mix + sx * (1 - v_mix)
rx = xx * r_mix + sx * (1 - r_mix) rx = xx * r_mix + sx * (1 - r_mix)
r = torch.sigmoid(gemm(rx, rw)) r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
k = gemm(kx, kw, output_dtype=torch.float32) k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
v = gemm(vx, vw, output_dtype=torch.float32) v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
y, aa, bb, pp = cuda_wkv(T, aa.shape[0], t_decay, t_first, k, v, aa, bb, pp)
out = gemm(r * y.to(x.dtype), 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.shape
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) 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) out = matmul(r * y.to(x.dtype), ow, omx, orx, omy, ory)
return x + out, xx[-1, :], aa, bb, pp return x + out, xx[-1, :], aa, bb, pp
# NOTE: decorate with @MyFunction causes JIT error # NOTE: decorate with @MyFunction causes JIT error
@@ -1578,6 +1409,10 @@ class RWKV(MyModule):
rrx, rrx,
rmy, rmy,
rry, rry,
gmx,
grx,
gmy,
gry,
omx, omx,
orx, orx,
omy, omy,
@@ -1594,10 +1429,10 @@ class RWKV(MyModule):
N = x.shape[-1] // H N = x.shape[-1] // H
T = x.shape[0] T = x.shape[0]
r = gemm(rx, rw, output_dtype=torch.float32) r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32)
k = gemm(kx, kw, output_dtype=torch.float32) k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
v = gemm(vx, vw, output_dtype=torch.float32) v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
g = F.silu(gemm(gx, gw)) g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
out, s = self.RUN_RWKV_5( out, s = self.RUN_RWKV_5(
1, 1,
@@ -1616,7 +1451,7 @@ class RWKV(MyModule):
out = out.reshape(T, H * N) out = out.reshape(T, H * N)
out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b) out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b)
out = out.to(dtype=x.dtype) * g out = out.to(dtype=x.dtype) * g
out = gemm(out, ow) out = matmul(out, ow, omx, orx, omy, ory)
return x + out, xx[-1, :], s return x + out, xx[-1, :], s
@@ -1703,13 +1538,9 @@ class RWKV(MyModule):
"RWKV_CUDA_ON" "RWKV_CUDA_ON"
] == "1" and "cuda" in str(dev) ] == "1" and "cuda" in str(dev)
if cuda_applicable: if cuda_applicable:
ATT = ( ATT = self.cuda_att_seq
self.cuda_att_seq
if wtype != torch.uint8
else self.cuda_att_seq_i8
)
else: else:
ATT = self.att_seq if wtype != torch.uint8 else self.att_seq_i8 ATT = self.att_seq
if self.version == 5: if self.version == 5:
ATT = self.att_seq_v5 ATT = self.att_seq_v5
elif self.version == 5.1: elif self.version == 5.1:
@@ -1718,16 +1549,16 @@ class RWKV(MyModule):
ATT = self.att_seq_v5_2 ATT = self.att_seq_v5_2
if cuda_applicable: if cuda_applicable:
ATT = self.cuda_att_seq_v5_2 ATT = self.cuda_att_seq_v5_2
FFN = self.ffn_seq if wtype != torch.uint8 else self.ffn_seq_i8 FFN = self.ffn_seq
else: else:
ATT = self.att_one if wtype != torch.uint8 else self.att_one_i8 ATT = self.att_one
if self.version == 5: if self.version == 5:
ATT = self.att_one_v5 ATT = self.att_one_v5
elif self.version == 5.1: elif self.version == 5.1:
ATT = self.att_one_v5_1 ATT = self.att_one_v5_1
elif self.version == 5.2: elif self.version == 5.2:
ATT = self.att_one_v5_1 # same as v5.1 ATT = self.att_one_v5_1 # same as v5.1
FFN = self.ffn_one if wtype != torch.uint8 else self.ffn_one_i8 FFN = self.ffn_one
x = x.to(dtype=atype, device=dev) x = x.to(dtype=atype, device=dev)
@@ -1872,6 +1703,10 @@ class RWKV(MyModule):
rrx, rrx,
rmy, rmy,
rry, rry,
gmx,
grx,
gmy,
gry,
omx, omx,
orx, orx,
omy, omy,
@@ -1944,7 +1779,7 @@ class RWKV(MyModule):
x = x @ w["head.weight"] x = x @ w["head.weight"]
else: else:
if seq_mode and full_output: if seq_mode and full_output:
x = self.mm8_seq( x = mm8_seq(
x, x,
w["head.weight"], w["head.weight"],
w["head.weight_mx"], w["head.weight_mx"],
@@ -1953,7 +1788,7 @@ class RWKV(MyModule):
w["head.weight_ry"], w["head.weight_ry"],
) )
else: else:
x = self.mm8_one( x = mm8_one(
x, x,
w["head.weight"], w["head.weight"],
w["head.weight_mx"], w["head.weight_mx"],

Binary file not shown.

View File

@@ -81,8 +81,9 @@ class PIPELINE:
def sample_logits(self, logits, temperature=1.0, top_p=0.85, top_k=0): def sample_logits(self, logits, temperature=1.0, top_p=0.85, top_k=0):
probs = F.softmax(logits.float(), dim=-1) probs = F.softmax(logits.float(), dim=-1)
top_k = int(top_k) top_k = int(top_k)
if probs.device == torch.device("cpu"): # 'privateuseone' is the type of custom devices like `torch_directml.device()`
probs = probs.numpy() if probs.device.type in ["cpu", "privateuseone"]:
probs = probs.cpu().numpy()
sorted_ids = np.argsort(probs) sorted_ids = np.argsort(probs)
sorted_probs = probs[sorted_ids][::-1] sorted_probs = probs[sorted_ids][::-1]
cumulative_probs = np.cumsum(sorted_probs) cumulative_probs = np.cumsum(sorted_probs)

Binary file not shown.

View File

@@ -10,7 +10,7 @@ logger = logging.getLogger()
logger.setLevel(logging.INFO) logger.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(levelname)s\n%(message)s") formatter = logging.Formatter("%(asctime)s - %(levelname)s\n%(message)s")
fh = logging.handlers.RotatingFileHandler( fh = logging.handlers.RotatingFileHandler(
"api.log", mode="a", maxBytes=3 * 1024 * 1024, backupCount=3 "api.log", mode="a", maxBytes=3 * 1024 * 1024, backupCount=3, encoding="utf-8"
) )
fh.setFormatter(formatter) fh.setFormatter(formatter)
logger.addHandler(fh) logger.addHandler(fh)

View File

@@ -1,11 +1,13 @@
import os import os
import sys import global_var
def ngrok_connect(): def ngrok_connect():
from pyngrok import ngrok, conf from pyngrok import ngrok, conf
conf.set_default(conf.PyngrokConfig(ngrok_path="./ngrok")) conf.set_default(
conf.PyngrokConfig(ngrok_path="./ngrok.exe" if os.name == "nt" else "./ngrok")
)
ngrok.set_auth_token(os.environ["ngrok_token"]) ngrok.set_auth_token(os.environ["ngrok_token"])
http_tunnel = ngrok.connect(8000 if len(sys.argv) == 1 else int(sys.argv[1])) http_tunnel = ngrok.connect(global_var.get(global_var.Args).port)
print(http_tunnel.public_url) print(f"ngrok url: {http_tunnel.public_url}")

View File

@@ -261,5 +261,6 @@
"The content of file": "ファイル", "The content of file": "ファイル",
"is as follows. When replying to me, consider the file content and respond accordingly:": "の内容は以下の通りです。私に返信する際は、ファイルの内容を考慮して適切に返信してください:", "is as follows. When replying to me, consider the file content and respond accordingly:": "の内容は以下の通りです。私に返信する際は、ファイルの内容を考慮して適切に返信してください:",
"What's the file name": "ファイル名は何ですか", "What's the file name": "ファイル名は何ですか",
"The file name is: ": "ファイル名は次のとおりです: " "The file name is: ": "ファイル名は次のとおりです: ",
"Port is occupied. Change it in Configs page or close the program that occupies the port.": "ポートが占有されています。設定ページで変更するか、ポートを占有しているプログラムを終了してください。"
} }

View File

@@ -261,5 +261,6 @@
"The content of file": "文件", "The content of file": "文件",
"is as follows. When replying to me, consider the file content and respond accordingly:": "内容如下。回复时考虑文件内容并做出相应回复:", "is as follows. When replying to me, consider the file content and respond accordingly:": "内容如下。回复时考虑文件内容并做出相应回复:",
"What's the file name": "文件名是什么", "What's the file name": "文件名是什么",
"The file name is: ": "文件名是:" "The file name is: ": "文件名是:",
"Port is occupied. Change it in Configs page or close the program that occupies the port.": "端口被占用。请在配置页面更改端口,或关闭占用端口的程序"
} }

View File

@@ -1,6 +1,12 @@
import React, { FC, MouseEventHandler, ReactElement } from 'react'; import React, { FC, MouseEventHandler, ReactElement } from 'react';
import commonStore, { ModelStatus } from '../stores/commonStore'; import commonStore, { ModelStatus } from '../stores/commonStore';
import { AddToDownloadList, FileExists, StartServer, StartWebGPUServer } from '../../wailsjs/go/backend_golang/App'; import {
AddToDownloadList,
FileExists,
IsPortAvailable,
StartServer,
StartWebGPUServer
} from '../../wailsjs/go/backend_golang/App';
import { Button } from '@fluentui/react-components'; import { Button } from '@fluentui/react-components';
import { observer } from 'mobx-react-lite'; import { observer } from 'mobx-react-lite';
import { exit, getStatus, readRoot, switchModel, updateConfig } from '../apis'; import { exit, getStatus, readRoot, switchModel, updateConfig } from '../apis';
@@ -107,8 +113,15 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
const port = modelConfig.apiParameters.apiPort; const port = modelConfig.apiParameters.apiPort;
await exit(1000).catch(() => { if (!await IsPortAvailable(port)) {
}); await exit(1000).catch(() => {
});
if (!await IsPortAvailable(port)) {
toast(t('Port is occupied. Change it in Configs page or close the program that occupies the port.'), { type: 'error' });
commonStore.setStatus({ status: ModelStatus.Offline });
return;
}
}
const startServer = webgpu ? const startServer = webgpu ?
(_: string, port: number, host: string) => StartWebGPUServer(port, host) (_: string, port: number, host: string) => StartWebGPUServer(port, host)
@@ -211,7 +224,7 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
'invalid header or archive is corrupted': 'The model file is corrupted, please download again.', 'invalid header or archive is corrupted': 'The model file is corrupted, please download again.',
'no NVIDIA driver': 'Found no NVIDIA driver, please install the latest driver.', 'no NVIDIA driver': 'Found no NVIDIA driver, please install the latest driver.',
'CUDA out of memory': 'VRAM is not enough, please reduce stored layers or use a lower precision in Configs page.', 'CUDA out of memory': 'VRAM is not enough, please reduce stored layers or use a lower precision in Configs page.',
'Ninja is required to load C++ extensions': 'Failed to enable custom CUDA kernel, ninja is required to load C++ extensions. You may be using the CPU version of PyTorch, please reinstall PyTorch with CUDA. Or if you are using a custom Python interpreter, you must compile the CUDA kernel by yourself or disable Custom CUDA kernel acceleration.', 'Ninja is required to load C++ extensions': 'Failed to enable custom CUDA kernel, ninja is required to load C++ extensions. You may be using the CPU version of PyTorch, please reinstall PyTorch with CUDA. Or if you are using a custom Python interpreter, you must compile the CUDA kernel by yourself or disable Custom CUDA kernel acceleration.'
}; };
const matchedError = Object.entries(errorsMap).find(([key, _]) => error.includes(key)); const matchedError = Object.entries(errorsMap).find(([key, _]) => error.includes(key));
const message = matchedError ? t(matchedError[1]) : error; const message = matchedError ? t(matchedError[1]) : error;

View File

@@ -91,6 +91,7 @@ const MoreUtilsButton: FC<{ uuid: string, setEditing: (editing: boolean) => void
onClick={() => { onClick={() => {
commonStore.conversationOrder.splice(commonStore.conversationOrder.indexOf(uuid), 1); commonStore.conversationOrder.splice(commonStore.conversationOrder.indexOf(uuid), 1);
delete commonStore.conversation[uuid]; delete commonStore.conversation[uuid];
commonStore.setAttachment(uuid, null);
}} /> }} />
</MenuPopover> </MenuPopover>
</Menu>; </Menu>;
@@ -157,7 +158,21 @@ const ChatMessageItem: FC<{
)} )}
> >
{!editing ? {!editing ?
<MarkdownRender>{messageItem.content}</MarkdownRender> : <div className="flex flex-col">
<MarkdownRender>{messageItem.content}</MarkdownRender>
{uuid in commonStore.attachments &&
<div className="flex grow">
<div className="grow" />
<ToolTipButton className="whitespace-nowrap"
text={
commonStore.attachments[uuid][0].name.replace(
new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...')
}
desc={`${commonStore.attachments[uuid][0].name} (${bytesToReadable(commonStore.attachments[uuid][0].size)})`}
size="small" shape="circular" appearance="secondary" />
</div>
}
</div> :
<Textarea ref={textareaRef} <Textarea ref={textareaRef}
className="grow" className="grow"
style={{ minWidth: 0 }} style={{ minWidth: 0 }}
@@ -275,6 +290,11 @@ const ChatPanel: FC = observer(() => {
commonStore.setConversation(commonStore.conversation); commonStore.setConversation(commonStore.conversation);
commonStore.conversationOrder.push(newId); commonStore.conversationOrder.push(newId);
commonStore.setConversationOrder(commonStore.conversationOrder); commonStore.setConversationOrder(commonStore.conversationOrder);
if (commonStore.currentTempAttachment) {
commonStore.setAttachment(newId, [commonStore.currentTempAttachment]);
commonStore.setCurrentTempAttachment(null);
}
} }
let startIndex = startUuid ? commonStore.conversationOrder.indexOf(startUuid) : 0; let startIndex = startUuid ? commonStore.conversationOrder.indexOf(startUuid) : 0;
@@ -282,20 +302,21 @@ const ChatPanel: FC = observer(() => {
let targetRange = commonStore.conversationOrder.slice(startIndex, endIndex); let targetRange = commonStore.conversationOrder.slice(startIndex, endIndex);
const messages: ConversationMessage[] = []; const messages: ConversationMessage[] = [];
if (commonStore.attachmentContent) {
messages.push({
role: 'user',
content: t('The content of file') + ` "${commonStore.attachmentName}" `
+ t('is as follows. When replying to me, consider the file content and respond accordingly:')
+ '\n\n' + commonStore.attachmentContent
});
messages.push({ role: 'user', content: t('What\'s the file name') });
messages.push({ role: 'assistant', content: t('The file name is: ') + commonStore.attachmentName });
}
targetRange.forEach((uuid, index) => { targetRange.forEach((uuid, index) => {
if (uuid === welcomeUuid) if (uuid === welcomeUuid)
return; return;
const messageItem = commonStore.conversation[uuid]; const messageItem = commonStore.conversation[uuid];
if (uuid in commonStore.attachments) {
const attachment = commonStore.attachments[uuid][0];
messages.push({
role: 'user',
content: t('The content of file') + ` "${attachment.name}" `
+ t('is as follows. When replying to me, consider the file content and respond accordingly:')
+ '\n\n' + attachment.content
});
messages.push({ role: 'user', content: t('What\'s the file name') });
messages.push({ role: 'assistant', content: t('The file name is: ') + attachment.name });
}
if (messageItem.done && messageItem.type === MessageType.Normal && messageItem.sender === userName) { if (messageItem.done && messageItem.type === MessageType.Normal && messageItem.sender === userName) {
messages.push({ role: 'user', content: messageItem.content }); messages.push({ role: 'user', content: messageItem.content });
} else if (messageItem.done && messageItem.type === MessageType.Normal && messageItem.sender === botName) { } else if (messageItem.done && messageItem.type === MessageType.Normal && messageItem.sender === botName) {
@@ -339,14 +360,16 @@ const ChatPanel: FC = observer(() => {
model: commonStore.settings.apiChatModelName, // 'gpt-3.5-turbo' model: commonStore.settings.apiChatModelName, // 'gpt-3.5-turbo'
temperature: apiParams.temperature, temperature: apiParams.temperature,
top_p: apiParams.topP, top_p: apiParams.topP,
user_name: commonStore.activePreset?.userName, user_name: commonStore.activePreset?.userName || undefined,
assistant_name: commonStore.activePreset?.assistantName, assistant_name: commonStore.activePreset?.assistantName || undefined,
presystem: commonStore.activePreset?.presystem presystem: commonStore.activePreset?.presystem && undefined
}), }),
signal: chatSseController?.signal, signal: chatSseController?.signal,
onmessage(e) { onmessage(e) {
scrollToBottom(); scrollToBottom();
if (e.data.trim() === '[DONE]') { if (e.data.trim() === '[DONE]') {
if (answerId! in chatSseControllers)
delete chatSseControllers[answerId!];
commonStore.conversation[answerId!].done = true; commonStore.conversation[answerId!].done = true;
commonStore.conversation[answerId!].content = commonStore.conversation[answerId!].content.trim(); commonStore.conversation[answerId!].content = commonStore.conversation[answerId!].content.trim();
commonStore.setConversation(commonStore.conversation); commonStore.setConversation(commonStore.conversation);
@@ -381,6 +404,8 @@ const ChatPanel: FC = observer(() => {
console.log('Connection closed'); console.log('Connection closed');
}, },
onerror(err) { onerror(err) {
if (answerId! in chatSseControllers)
delete chatSseControllers[answerId!];
commonStore.conversation[answerId!].type = MessageType.Error; commonStore.conversation[answerId!].type = MessageType.Error;
commonStore.conversation[answerId!].done = true; commonStore.conversation[answerId!].done = true;
err = err.message || err; err = err.message || err;
@@ -429,7 +454,7 @@ const ChatPanel: FC = observer(() => {
onKeyDown={handleKeyDownOrClick} onKeyDown={handleKeyDownOrClick}
/> />
<div className="absolute right-2 bottom-2"> <div className="absolute right-2 bottom-2">
{!commonStore.attachmentContent ? {!commonStore.currentTempAttachment ?
<ToolTipButton <ToolTipButton
desc={commonStore.attachmentUploading ? desc={commonStore.attachmentUploading ?
t('Uploading Attachment') : t('Uploading Attachment') :
@@ -473,9 +498,12 @@ const ChatPanel: FC = observer(() => {
attachmentContent = pages[0].page_content; attachmentContent = pages[0].page_content;
else else
attachmentContent = pages.map((p, i) => `Page ${i + 1}:\n${p.page_content}`).join('\n\n'); attachmentContent = pages.map((p, i) => `Page ${i + 1}:\n${p.page_content}`).join('\n\n');
commonStore.setAttachmentName(attachmentName!); commonStore.setCurrentTempAttachment(
commonStore.setAttachmentSize(blob.size); {
commonStore.setAttachmentContent(attachmentContent); name: attachmentName!,
size: blob.size,
content: attachmentContent
});
} else { } else {
toast(r.statusText + '\n' + (await r.text()), { toast(r.statusText + '\n' + (await r.text()), {
type: 'error' type: 'error'
@@ -495,18 +523,16 @@ const ChatPanel: FC = observer(() => {
<div> <div>
<ToolTipButton <ToolTipButton
text={ text={
commonStore.attachmentName.replace( commonStore.currentTempAttachment.name.replace(
new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...') new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...')
} }
desc={`${commonStore.attachmentName} (${bytesToReadable(commonStore.attachmentSize)})`} desc={`${commonStore.currentTempAttachment.name} (${bytesToReadable(commonStore.currentTempAttachment.size)})`}
size="small" shape="circular" appearance="secondary" /> size="small" shape="circular" appearance="secondary" />
<ToolTipButton desc={t('Remove Attachment')} <ToolTipButton desc={t('Remove Attachment')}
icon={<Dismiss16Regular />} icon={<Dismiss16Regular />}
size="small" shape="circular" appearance="subtle" size="small" shape="circular" appearance="subtle"
onClick={() => { onClick={() => {
commonStore.setAttachmentName(''); commonStore.setCurrentTempAttachment(null);
commonStore.setAttachmentSize(0);
commonStore.setAttachmentContent('');
}} /> }} />
</div> </div>
} }

View File

@@ -42,7 +42,7 @@ export type SettingsType = {
} }
export const Settings: FC = observer(() => { export const Settings: FC = observer(() => {
const { t, i18n } = useTranslation(); const { t } = useTranslation();
const advancedHeaderRef = useRef<HTMLDivElement>(null); const advancedHeaderRef = useRef<HTMLDivElement>(null);
useEffect(() => { useEffect(() => {

View File

@@ -31,9 +31,13 @@ export type Status = {
device_name: string; device_name: string;
} }
export type Platform = 'windows' | 'darwin' | 'linux'; export type Attachment = {
name: string;
size: number;
content: string;
}
const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']; export type Platform = 'windows' | 'darwin' | 'linux';
class CommonStore { class CommonStore {
// global // global
@@ -55,9 +59,8 @@ class CommonStore {
conversationOrder: string[] = []; conversationOrder: string[] = [];
activePreset: Preset | null = null; activePreset: Preset | null = null;
attachmentUploading: boolean = false; attachmentUploading: boolean = false;
attachmentName: string = ''; attachments: { [uuid: string]: Attachment[] } = {};
attachmentSize: number = 0; currentTempAttachment: Attachment | null = null;
attachmentContent: string = '';
// completion // completion
completionPreset: CompletionPreset | null = null; completionPreset: CompletionPreset | null = null;
completionGenerating: boolean = false; completionGenerating: boolean = false;
@@ -334,16 +337,19 @@ class CommonStore {
this.attachmentUploading = value; this.attachmentUploading = value;
} }
setAttachmentName(value: string) { setAttachments(value: { [uuid: string]: Attachment[] }) {
this.attachmentName = value; this.attachments = value;
} }
setAttachmentSize(value: number) { setAttachment(uuid: string, value: Attachment[] | null) {
this.attachmentSize = value; if (value === null)
delete this.attachments[uuid];
else
this.attachments[uuid] = value;
} }
setAttachmentContent(value: string) { setCurrentTempAttachment(value: Attachment | null) {
this.attachmentContent = value; this.currentTempAttachment = value;
} }
} }

View File

@@ -28,6 +28,8 @@ export function GetPyError():Promise<string>;
export function InstallPyDep(arg1:string,arg2:boolean):Promise<string>; export function InstallPyDep(arg1:string,arg2:boolean):Promise<string>;
export function IsPortAvailable(arg1:number):Promise<boolean>;
export function ListDirFiles(arg1:string):Promise<Array<backend_golang.FileInfo>>; export function ListDirFiles(arg1:string):Promise<Array<backend_golang.FileInfo>>;
export function MergeLora(arg1:string,arg2:boolean,arg3:number,arg4:string,arg5:string,arg6:string):Promise<string>; export function MergeLora(arg1:string,arg2:boolean,arg3:number,arg4:string,arg5:string,arg6:string):Promise<string>;

View File

@@ -54,6 +54,10 @@ export function InstallPyDep(arg1, arg2) {
return window['go']['backend_golang']['App']['InstallPyDep'](arg1, arg2); return window['go']['backend_golang']['App']['InstallPyDep'](arg1, arg2);
} }
export function IsPortAvailable(arg1) {
return window['go']['backend_golang']['App']['IsPortAvailable'](arg1);
}
export function ListDirFiles(arg1) { export function ListDirFiles(arg1) {
return window['go']['backend_golang']['App']['ListDirFiles'](arg1); return window['go']['backend_golang']['App']['ListDirFiles'](arg1);
} }

View File

@@ -1,5 +1,5 @@
{ {
"version": "1.4.8", "version": "1.4.9",
"introduction": { "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).", "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的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。" "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的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。"