Compare commits
14 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b8712e0b89 | ||
|
|
37dda4333d | ||
|
|
64826b9af7 | ||
|
|
47b0c35441 | ||
|
|
1dcda47013 | ||
|
|
1f81a1e5a8 | ||
|
|
35e92d2aef | ||
|
|
0d99e5549e | ||
|
|
fed1594ddc | ||
|
|
14b90bb36b | ||
|
|
f86b7f1f08 | ||
|
|
54355d5a7a | ||
|
|
ff7306349a | ||
|
|
77df56cddc |
@@ -2,40 +2,28 @@
|
||||
|
||||
### Features
|
||||
|
||||
- allow conversation with some document (.pdf, .txt) (Experimental)
|
||||
- add `/file-to-text` api
|
||||
- allow avatarImg to be local absolute path
|
||||
- base64 preset support
|
||||
- chat attachment is now related to single message (Experimental)
|
||||
- port occupied detection
|
||||
|
||||
### Upgrades
|
||||
|
||||
- upgrade to rwkv 0.8.16 (DirectML support; rwkv 5.2 no longer needs to ensure custom cuda kernel enabled)
|
||||
- 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
|
||||
- upgrade to rwkv 0.8.20
|
||||
|
||||
### Improvements
|
||||
|
||||
- improve cuda kernel compatibility (compute compatibility 5.3, Jetson Nano, Nvidia 10 Series+)
|
||||
- RWKVType now no longer relies on the file name (use emb)
|
||||
- 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
|
||||
- improve the compatibility between frontend presets and chatgpt api
|
||||
- improve memory usage of state cache
|
||||
|
||||
### Chores
|
||||
|
||||
- update manifest.json (RWKV-5)
|
||||
- update readme and client text description
|
||||
- add pip --no-warn-script-location
|
||||
- mark rwkv raven series as old model
|
||||
- chore
|
||||
- update ngrok_connect
|
||||
- python38 compatibility
|
||||
- adjust startup process
|
||||
|
||||
### Fixes
|
||||
|
||||
- fix linux kernel (partial revert 68228a45)
|
||||
- fix the `make` command on Linux and macOS, no longer need manual operations on the wsl.go file. (#158, #173, #207)
|
||||
- fix log encoding error
|
||||
- fix stop button status of Chat page
|
||||
|
||||
## Install
|
||||
|
||||
|
||||
@@ -5,12 +5,15 @@ import (
|
||||
"bufio"
|
||||
"embed"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -205,3 +208,12 @@ func Unzip(source, destination string) error {
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
@@ -2,16 +2,47 @@ import 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 sys
|
||||
import argparse
|
||||
from typing import Sequence
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
sys.path.append(os.path.dirname(os.path.realpath(__file__)))
|
||||
|
||||
import psutil
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import Depends, FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
import uvicorn
|
||||
@@ -77,34 +108,7 @@ def exit():
|
||||
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__":
|
||||
args = get_args()
|
||||
os.environ["RWKV_RUNNER_PARAMS"] = " ".join(sys.argv[1:])
|
||||
print("--- %s seconds ---" % (time.time() - start_time))
|
||||
uvicorn.run("main:app", port=args.port, host=args.host, workers=1)
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -9,7 +9,7 @@ router = APIRouter()
|
||||
|
||||
trie = None
|
||||
dtrie: Dict = {}
|
||||
max_trie_len = 3000
|
||||
max_trie_len = 300
|
||||
loop_start_id = 1 # to prevent preloaded prompts from being deleted
|
||||
loop_del_trie_id = loop_start_id
|
||||
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
#include <cuda_fp16.h>
|
||||
#include <cuda_runtime.h>
|
||||
#include <torch/extension.h>
|
||||
#include <c10/cuda/CUDAGuard.h>
|
||||
#include <ATen/cuda/CUDAContext.h>
|
||||
|
||||
#define CUBLAS_CHECK(condition) \
|
||||
for (cublasStatus_t _cublas_check_status = (condition); \
|
||||
@@ -18,26 +20,13 @@
|
||||
"CUDA error " + std::string(cudaGetErrorString(_cuda_check_status)) + \
|
||||
" 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.
|
||||
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
|
||||
*/
|
||||
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_c_data_type =
|
||||
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_ldb = k;
|
||||
const int cublas_ldc = m;
|
||||
cublasHandle_t cublas_handle = get_cublas_handle();
|
||||
cublasHandle_t cublas_handle = at::cuda::getCurrentCUDABlasHandle();
|
||||
|
||||
#if CUDA_VERSION >= 11000
|
||||
cublasGemmAlgo_t algo = CUBLAS_GEMM_DEFAULT;
|
||||
|
||||
4
backend-python/rwkv_pip/cuda/rwkv5_op.cpp
vendored
4
backend-python/rwkv_pip/cuda/rwkv5_op.cpp
vendored
@@ -1,5 +1,6 @@
|
||||
#include <torch/extension.h>
|
||||
#include "ATen/ATen.h"
|
||||
#include <c10/cuda/CUDAGuard.h>
|
||||
typedef at::BFloat16 bf16;
|
||||
typedef at::Half fp16;
|
||||
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 forward_bf16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
|
||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
|
||||
cuda_forward_bf16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<bf16>(), k.data_ptr<bf16>(), v.data_ptr<bf16>(), w.data_ptr<float>(), u.data_ptr<bf16>(), y.data_ptr<bf16>());
|
||||
}
|
||||
void forward_fp16(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
|
||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
|
||||
cuda_forward_fp16(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp16>(), k.data_ptr<fp16>(), v.data_ptr<fp16>(), w.data_ptr<float>(), u.data_ptr<fp16>(), y.data_ptr<fp16>());
|
||||
}
|
||||
void forward_fp32(int64_t B, int64_t T, int64_t C, int64_t H, torch::Tensor &state, torch::Tensor &r, torch::Tensor &k, torch::Tensor &v, torch::Tensor &w, torch::Tensor &u, torch::Tensor &y) {
|
||||
const at::cuda::OptionalCUDAGuard device_guard(device_of(state));
|
||||
cuda_forward_fp32(B, T, C, H, state.data_ptr<float>(), r.data_ptr<fp32>(), k.data_ptr<fp32>(), v.data_ptr<fp32>(), w.data_ptr<float>(), u.data_ptr<fp32>(), y.data_ptr<fp32>());
|
||||
}
|
||||
|
||||
|
||||
523
backend-python/rwkv_pip/model.py
vendored
523
backend-python/rwkv_pip/model.py
vendored
@@ -171,10 +171,86 @@ if os.environ.get("RWKV_CUDA_ON") == "1":
|
||||
else:
|
||||
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
|
||||
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:
|
||||
output_dtype = a.dtype
|
||||
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:
|
||||
|
||||
def gemm(a, b, output_dtype: Optional[torch.dtype] = None):
|
||||
if output_dtype is None:
|
||||
output_dtype = a.dtype
|
||||
def matmul_float(a, b, output_dtype: Optional[torch.dtype] = None):
|
||||
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):
|
||||
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
|
||||
@@ -711,43 +749,9 @@ class RWKV(MyModule):
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(gemm(rx, rw))
|
||||
vx = torch.square(torch.relu(gemm(kx, kw)))
|
||||
out = r * gemm(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))
|
||||
r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
|
||||
vx = torch.square(torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)))
|
||||
out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
|
||||
return x + out, xx
|
||||
|
||||
########################################################################################################
|
||||
@@ -782,44 +786,9 @@ class RWKV(MyModule):
|
||||
kx = xx * k_mix + sx * (1 - k_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(gemm(rx, rw))
|
||||
vx = torch.square(torch.relu(gemm(kx, kw)))
|
||||
out = r * gemm(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))
|
||||
r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
|
||||
vx = torch.square(torch.relu(matmul(kx, kw, kmx, krx, kmy, kry)))
|
||||
out = r * matmul(vx, vw, vmx, vrx, vmy, vry)
|
||||
return x + out, xx[-1, :]
|
||||
|
||||
########################################################################################################
|
||||
@@ -865,9 +834,9 @@ class RWKV(MyModule):
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(gemm(rx, rw))
|
||||
k = gemm(kx, kw, output_dtype=torch.float32)
|
||||
v = gemm(vx, vw, output_dtype=torch.float32)
|
||||
r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
|
||||
k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
|
||||
v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
|
||||
|
||||
ww = t_first + k
|
||||
p = torch.maximum(pp, ww)
|
||||
@@ -879,65 +848,7 @@ class RWKV(MyModule):
|
||||
e1 = torch.exp(ww - p)
|
||||
e2 = torch.exp(k - p)
|
||||
|
||||
out = gemm(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)
|
||||
out = matmul(r * wkv, ow, omx, orx, omy, ory)
|
||||
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)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(gemm(rx, rw))
|
||||
k = gemm(kx, kw, output_dtype=torch.float32)
|
||||
v = gemm(vx, vw, output_dtype=torch.float32)
|
||||
r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
|
||||
k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
|
||||
v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
|
||||
|
||||
T = x.shape[0]
|
||||
for t in range(T):
|
||||
@@ -1004,72 +915,7 @@ class RWKV(MyModule):
|
||||
aa = e1 * aa + e2 * vv
|
||||
bb = e1 * bb + e2
|
||||
pp = p
|
||||
out = gemm(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)
|
||||
out = matmul(r * sx, ow, omx, orx, omy, ory)
|
||||
return x + out, xx[-1, :], aa, bb, pp
|
||||
|
||||
########################################################################################################
|
||||
@@ -1118,11 +964,11 @@ class RWKV(MyModule):
|
||||
H = t_decay.shape[0]
|
||||
S = x.shape[-1] // H
|
||||
|
||||
r = gemm(rx, rw, output_dtype=torch.float32).view(H, 1, S)
|
||||
k = gemm(kx, kw, output_dtype=torch.float32).view(H, S, 1)
|
||||
v = gemm(vx, vw, 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 = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(H, S, 1)
|
||||
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)
|
||||
s = a + t_decay * s
|
||||
|
||||
@@ -1131,7 +977,7 @@ class RWKV(MyModule):
|
||||
out.unsqueeze(0), num_groups=H, weight=lx_w, bias=lx_b
|
||||
).squeeze(0)
|
||||
out = out.to(dtype=x.dtype)
|
||||
out = gemm(out, ow)
|
||||
out = matmul(out, ow, omx, orx, omy, ory)
|
||||
|
||||
return x + out, xx, s
|
||||
|
||||
@@ -1194,14 +1040,22 @@ class RWKV(MyModule):
|
||||
w = w[:, :-T].reshape(-1, T, 2 * T - 1)
|
||||
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 = (
|
||||
gemm(kx, kw, output_dtype=torch.float32)
|
||||
matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
|
||||
.view(T, H, S)
|
||||
.transpose(0, 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
|
||||
s = ws * s + (k * wk) @ v
|
||||
@@ -1209,7 +1063,7 @@ class RWKV(MyModule):
|
||||
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 = out.to(dtype=x.dtype)
|
||||
out = gemm(out, ow)
|
||||
out = matmul(out, ow, omx, orx, omy, ory)
|
||||
|
||||
return x + out, xx[-1, :], s
|
||||
|
||||
@@ -1248,6 +1102,10 @@ class RWKV(MyModule):
|
||||
rrx,
|
||||
rmy,
|
||||
rry,
|
||||
gmx,
|
||||
grx,
|
||||
gmy,
|
||||
gry,
|
||||
omx,
|
||||
orx,
|
||||
omy,
|
||||
@@ -1262,12 +1120,12 @@ class RWKV(MyModule):
|
||||
H = t_decay.shape[0]
|
||||
S = x.shape[-1] // H
|
||||
|
||||
r = gemm(rx, rw, output_dtype=torch.float32).view(H, 1, S)
|
||||
k = gemm(kx, kw, output_dtype=torch.float32).view(H, S, 1)
|
||||
v = gemm(vx, vw, output_dtype=torch.float32).view(H, 1, S)
|
||||
g = F.silu(gemm(gx, gw))
|
||||
r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32).view(H, 1, S)
|
||||
k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32).view(H, S, 1)
|
||||
v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32).view(H, 1, S)
|
||||
g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
|
||||
|
||||
a = gemm(k, v)
|
||||
a = matmul(k, v)
|
||||
out = r @ (t_first * a + 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
|
||||
).squeeze(0)
|
||||
out = out.to(dtype=x.dtype) * g
|
||||
out = gemm(out, ow)
|
||||
out = matmul(out, ow, omx, orx, omy, ory)
|
||||
|
||||
return x + out, xx, s
|
||||
|
||||
@@ -1313,6 +1171,10 @@ class RWKV(MyModule):
|
||||
rrx,
|
||||
rmy,
|
||||
rry,
|
||||
gmx,
|
||||
grx,
|
||||
gmy,
|
||||
gry,
|
||||
omx,
|
||||
orx,
|
||||
omy,
|
||||
@@ -1342,15 +1204,23 @@ class RWKV(MyModule):
|
||||
w = w[:, :-T].reshape(-1, T, 2 * T - 1)
|
||||
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 = (
|
||||
gemm(kx, kw, output_dtype=torch.float32)
|
||||
matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
|
||||
.view(T, H, S)
|
||||
.transpose(0, 1)
|
||||
.transpose(-2, -1)
|
||||
)
|
||||
v = gemm(vx, vw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1)
|
||||
g = F.silu(gemm(gx, gw))
|
||||
v = (
|
||||
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
|
||||
s = ws * s + (k * wk) @ v
|
||||
@@ -1358,7 +1228,7 @@ class RWKV(MyModule):
|
||||
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 = out.to(dtype=x.dtype) * g
|
||||
out = gemm(out, ow)
|
||||
out = matmul(out, ow, omx, orx, omy, ory)
|
||||
|
||||
return x + out, xx[-1, :], s
|
||||
|
||||
@@ -1397,6 +1267,10 @@ class RWKV(MyModule):
|
||||
rrx,
|
||||
rmy,
|
||||
rry,
|
||||
gmx,
|
||||
grx,
|
||||
gmy,
|
||||
gry,
|
||||
omx,
|
||||
orx,
|
||||
omy,
|
||||
@@ -1413,29 +1287,37 @@ class RWKV(MyModule):
|
||||
S = x.shape[-1] // H
|
||||
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 = (
|
||||
gemm(kx, kw, output_dtype=torch.float32)
|
||||
matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
|
||||
.view(T, H, S)
|
||||
.transpose(0, 1)
|
||||
.transpose(-2, -1)
|
||||
)
|
||||
v = gemm(vx, vw, output_dtype=torch.float32).view(T, H, S).transpose(0, 1)
|
||||
g = F.silu(gemm(gx, gw))
|
||||
v = (
|
||||
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)
|
||||
for t in range(T):
|
||||
rt = r[:, t : t + 1, :]
|
||||
kt = k[:, :, 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)
|
||||
s = at + t_decay * s
|
||||
|
||||
out = out.reshape(T, H * S)
|
||||
out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b)
|
||||
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
|
||||
|
||||
@@ -1486,63 +1368,12 @@ class RWKV(MyModule):
|
||||
vx = xx * v_mix + sx * (1 - v_mix)
|
||||
rx = xx * r_mix + sx * (1 - r_mix)
|
||||
|
||||
r = torch.sigmoid(gemm(rx, rw))
|
||||
k = gemm(kx, kw, output_dtype=torch.float32)
|
||||
v = gemm(vx, vw, 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)
|
||||
r = torch.sigmoid(matmul(rx, rw, rmx, rrx, rmy, rry))
|
||||
k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
|
||||
v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
|
||||
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
|
||||
|
||||
# NOTE: decorate with @MyFunction causes JIT error
|
||||
@@ -1578,6 +1409,10 @@ class RWKV(MyModule):
|
||||
rrx,
|
||||
rmy,
|
||||
rry,
|
||||
gmx,
|
||||
grx,
|
||||
gmy,
|
||||
gry,
|
||||
omx,
|
||||
orx,
|
||||
omy,
|
||||
@@ -1594,10 +1429,10 @@ class RWKV(MyModule):
|
||||
N = x.shape[-1] // H
|
||||
T = x.shape[0]
|
||||
|
||||
r = gemm(rx, rw, output_dtype=torch.float32)
|
||||
k = gemm(kx, kw, output_dtype=torch.float32)
|
||||
v = gemm(vx, vw, output_dtype=torch.float32)
|
||||
g = F.silu(gemm(gx, gw))
|
||||
r = matmul(rx, rw, rmx, rrx, rmy, rry, output_dtype=torch.float32)
|
||||
k = matmul(kx, kw, kmx, krx, kmy, kry, output_dtype=torch.float32)
|
||||
v = matmul(vx, vw, vmx, vrx, vmy, vry, output_dtype=torch.float32)
|
||||
g = F.silu(matmul(gx, gw, gmx, grx, gmy, gry))
|
||||
|
||||
out, s = self.RUN_RWKV_5(
|
||||
1,
|
||||
@@ -1616,7 +1451,7 @@ class RWKV(MyModule):
|
||||
out = out.reshape(T, H * N)
|
||||
out = F.group_norm(out, num_groups=H, weight=lx_w, bias=lx_b)
|
||||
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
|
||||
|
||||
@@ -1703,13 +1538,9 @@ class RWKV(MyModule):
|
||||
"RWKV_CUDA_ON"
|
||||
] == "1" and "cuda" in str(dev)
|
||||
if cuda_applicable:
|
||||
ATT = (
|
||||
self.cuda_att_seq
|
||||
if wtype != torch.uint8
|
||||
else self.cuda_att_seq_i8
|
||||
)
|
||||
ATT = self.cuda_att_seq
|
||||
else:
|
||||
ATT = self.att_seq if wtype != torch.uint8 else self.att_seq_i8
|
||||
ATT = self.att_seq
|
||||
if self.version == 5:
|
||||
ATT = self.att_seq_v5
|
||||
elif self.version == 5.1:
|
||||
@@ -1718,16 +1549,16 @@ class RWKV(MyModule):
|
||||
ATT = self.att_seq_v5_2
|
||||
if cuda_applicable:
|
||||
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:
|
||||
ATT = self.att_one if wtype != torch.uint8 else self.att_one_i8
|
||||
ATT = self.att_one
|
||||
if self.version == 5:
|
||||
ATT = self.att_one_v5
|
||||
elif self.version == 5.1:
|
||||
ATT = self.att_one_v5_1
|
||||
elif self.version == 5.2:
|
||||
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)
|
||||
|
||||
@@ -1872,6 +1703,10 @@ class RWKV(MyModule):
|
||||
rrx,
|
||||
rmy,
|
||||
rry,
|
||||
gmx,
|
||||
grx,
|
||||
gmy,
|
||||
gry,
|
||||
omx,
|
||||
orx,
|
||||
omy,
|
||||
@@ -1944,7 +1779,7 @@ class RWKV(MyModule):
|
||||
x = x @ w["head.weight"]
|
||||
else:
|
||||
if seq_mode and full_output:
|
||||
x = self.mm8_seq(
|
||||
x = mm8_seq(
|
||||
x,
|
||||
w["head.weight"],
|
||||
w["head.weight_mx"],
|
||||
@@ -1953,7 +1788,7 @@ class RWKV(MyModule):
|
||||
w["head.weight_ry"],
|
||||
)
|
||||
else:
|
||||
x = self.mm8_one(
|
||||
x = mm8_one(
|
||||
x,
|
||||
w["head.weight"],
|
||||
w["head.weight_mx"],
|
||||
|
||||
BIN
backend-python/rwkv_pip/rwkv5.pyd
vendored
BIN
backend-python/rwkv_pip/rwkv5.pyd
vendored
Binary file not shown.
5
backend-python/rwkv_pip/utils.py
vendored
5
backend-python/rwkv_pip/utils.py
vendored
@@ -81,8 +81,9 @@ class PIPELINE:
|
||||
def sample_logits(self, logits, temperature=1.0, top_p=0.85, top_k=0):
|
||||
probs = F.softmax(logits.float(), dim=-1)
|
||||
top_k = int(top_k)
|
||||
if probs.device == torch.device("cpu"):
|
||||
probs = probs.numpy()
|
||||
# 'privateuseone' is the type of custom devices like `torch_directml.device()`
|
||||
if probs.device.type in ["cpu", "privateuseone"]:
|
||||
probs = probs.cpu().numpy()
|
||||
sorted_ids = np.argsort(probs)
|
||||
sorted_probs = probs[sorted_ids][::-1]
|
||||
cumulative_probs = np.cumsum(sorted_probs)
|
||||
|
||||
BIN
backend-python/rwkv_pip/wkv_cuda.pyd
vendored
BIN
backend-python/rwkv_pip/wkv_cuda.pyd
vendored
Binary file not shown.
@@ -10,7 +10,7 @@ logger = logging.getLogger()
|
||||
logger.setLevel(logging.INFO)
|
||||
formatter = logging.Formatter("%(asctime)s - %(levelname)s\n%(message)s")
|
||||
fh = logging.handlers.RotatingFileHandler(
|
||||
"api.log", mode="a", maxBytes=3 * 1024 * 1024, backupCount=3
|
||||
"api.log", mode="a", maxBytes=3 * 1024 * 1024, backupCount=3, encoding="utf-8"
|
||||
)
|
||||
fh.setFormatter(formatter)
|
||||
logger.addHandler(fh)
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
import os
|
||||
import sys
|
||||
import global_var
|
||||
|
||||
|
||||
def ngrok_connect():
|
||||
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"])
|
||||
http_tunnel = ngrok.connect(8000 if len(sys.argv) == 1 else int(sys.argv[1]))
|
||||
print(http_tunnel.public_url)
|
||||
http_tunnel = ngrok.connect(global_var.get(global_var.Args).port)
|
||||
print(f"ngrok url: {http_tunnel.public_url}")
|
||||
|
||||
@@ -261,5 +261,6 @@
|
||||
"The content of file": "ファイル",
|
||||
"is as follows. When replying to me, consider the file content and respond accordingly:": "の内容は以下の通りです。私に返信する際は、ファイルの内容を考慮して適切に返信してください:",
|
||||
"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.": "ポートが占有されています。設定ページで変更するか、ポートを占有しているプログラムを終了してください。"
|
||||
}
|
||||
@@ -261,5 +261,6 @@
|
||||
"The content of file": "文件",
|
||||
"is as follows. When replying to me, consider the file content and respond accordingly:": "内容如下。回复时考虑文件内容并做出相应回复:",
|
||||
"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.": "端口被占用。请在配置页面更改端口,或关闭占用端口的程序"
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
import React, { FC, MouseEventHandler, ReactElement } from 'react';
|
||||
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 { observer } from 'mobx-react-lite';
|
||||
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;
|
||||
|
||||
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 ?
|
||||
(_: 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.',
|
||||
'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.',
|
||||
'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 message = matchedError ? t(matchedError[1]) : error;
|
||||
|
||||
@@ -91,6 +91,7 @@ const MoreUtilsButton: FC<{ uuid: string, setEditing: (editing: boolean) => void
|
||||
onClick={() => {
|
||||
commonStore.conversationOrder.splice(commonStore.conversationOrder.indexOf(uuid), 1);
|
||||
delete commonStore.conversation[uuid];
|
||||
commonStore.setAttachment(uuid, null);
|
||||
}} />
|
||||
</MenuPopover>
|
||||
</Menu>;
|
||||
@@ -157,7 +158,21 @@ const ChatMessageItem: FC<{
|
||||
)}
|
||||
>
|
||||
{!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}
|
||||
className="grow"
|
||||
style={{ minWidth: 0 }}
|
||||
@@ -275,6 +290,11 @@ const ChatPanel: FC = observer(() => {
|
||||
commonStore.setConversation(commonStore.conversation);
|
||||
commonStore.conversationOrder.push(newId);
|
||||
commonStore.setConversationOrder(commonStore.conversationOrder);
|
||||
|
||||
if (commonStore.currentTempAttachment) {
|
||||
commonStore.setAttachment(newId, [commonStore.currentTempAttachment]);
|
||||
commonStore.setCurrentTempAttachment(null);
|
||||
}
|
||||
}
|
||||
|
||||
let startIndex = startUuid ? commonStore.conversationOrder.indexOf(startUuid) : 0;
|
||||
@@ -282,20 +302,21 @@ const ChatPanel: FC = observer(() => {
|
||||
let targetRange = commonStore.conversationOrder.slice(startIndex, endIndex);
|
||||
|
||||
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) => {
|
||||
if (uuid === welcomeUuid)
|
||||
return;
|
||||
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) {
|
||||
messages.push({ role: 'user', content: messageItem.content });
|
||||
} 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'
|
||||
temperature: apiParams.temperature,
|
||||
top_p: apiParams.topP,
|
||||
user_name: commonStore.activePreset?.userName,
|
||||
assistant_name: commonStore.activePreset?.assistantName,
|
||||
presystem: commonStore.activePreset?.presystem
|
||||
user_name: commonStore.activePreset?.userName || undefined,
|
||||
assistant_name: commonStore.activePreset?.assistantName || undefined,
|
||||
presystem: commonStore.activePreset?.presystem && undefined
|
||||
}),
|
||||
signal: chatSseController?.signal,
|
||||
onmessage(e) {
|
||||
scrollToBottom();
|
||||
if (e.data.trim() === '[DONE]') {
|
||||
if (answerId! in chatSseControllers)
|
||||
delete chatSseControllers[answerId!];
|
||||
commonStore.conversation[answerId!].done = true;
|
||||
commonStore.conversation[answerId!].content = commonStore.conversation[answerId!].content.trim();
|
||||
commonStore.setConversation(commonStore.conversation);
|
||||
@@ -381,6 +404,8 @@ const ChatPanel: FC = observer(() => {
|
||||
console.log('Connection closed');
|
||||
},
|
||||
onerror(err) {
|
||||
if (answerId! in chatSseControllers)
|
||||
delete chatSseControllers[answerId!];
|
||||
commonStore.conversation[answerId!].type = MessageType.Error;
|
||||
commonStore.conversation[answerId!].done = true;
|
||||
err = err.message || err;
|
||||
@@ -429,7 +454,7 @@ const ChatPanel: FC = observer(() => {
|
||||
onKeyDown={handleKeyDownOrClick}
|
||||
/>
|
||||
<div className="absolute right-2 bottom-2">
|
||||
{!commonStore.attachmentContent ?
|
||||
{!commonStore.currentTempAttachment ?
|
||||
<ToolTipButton
|
||||
desc={commonStore.attachmentUploading ?
|
||||
t('Uploading Attachment') :
|
||||
@@ -473,9 +498,12 @@ const ChatPanel: FC = observer(() => {
|
||||
attachmentContent = pages[0].page_content;
|
||||
else
|
||||
attachmentContent = pages.map((p, i) => `Page ${i + 1}:\n${p.page_content}`).join('\n\n');
|
||||
commonStore.setAttachmentName(attachmentName!);
|
||||
commonStore.setAttachmentSize(blob.size);
|
||||
commonStore.setAttachmentContent(attachmentContent);
|
||||
commonStore.setCurrentTempAttachment(
|
||||
{
|
||||
name: attachmentName!,
|
||||
size: blob.size,
|
||||
content: attachmentContent
|
||||
});
|
||||
} else {
|
||||
toast(r.statusText + '\n' + (await r.text()), {
|
||||
type: 'error'
|
||||
@@ -495,18 +523,16 @@ const ChatPanel: FC = observer(() => {
|
||||
<div>
|
||||
<ToolTipButton
|
||||
text={
|
||||
commonStore.attachmentName.replace(
|
||||
commonStore.currentTempAttachment.name.replace(
|
||||
new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...')
|
||||
}
|
||||
desc={`${commonStore.attachmentName} (${bytesToReadable(commonStore.attachmentSize)})`}
|
||||
desc={`${commonStore.currentTempAttachment.name} (${bytesToReadable(commonStore.currentTempAttachment.size)})`}
|
||||
size="small" shape="circular" appearance="secondary" />
|
||||
<ToolTipButton desc={t('Remove Attachment')}
|
||||
icon={<Dismiss16Regular />}
|
||||
size="small" shape="circular" appearance="subtle"
|
||||
onClick={() => {
|
||||
commonStore.setAttachmentName('');
|
||||
commonStore.setAttachmentSize(0);
|
||||
commonStore.setAttachmentContent('');
|
||||
commonStore.setCurrentTempAttachment(null);
|
||||
}} />
|
||||
</div>
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ export type SettingsType = {
|
||||
}
|
||||
|
||||
export const Settings: FC = observer(() => {
|
||||
const { t, i18n } = useTranslation();
|
||||
const { t } = useTranslation();
|
||||
const advancedHeaderRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
@@ -31,9 +31,13 @@ export type Status = {
|
||||
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 {
|
||||
// global
|
||||
@@ -55,9 +59,8 @@ class CommonStore {
|
||||
conversationOrder: string[] = [];
|
||||
activePreset: Preset | null = null;
|
||||
attachmentUploading: boolean = false;
|
||||
attachmentName: string = '';
|
||||
attachmentSize: number = 0;
|
||||
attachmentContent: string = '';
|
||||
attachments: { [uuid: string]: Attachment[] } = {};
|
||||
currentTempAttachment: Attachment | null = null;
|
||||
// completion
|
||||
completionPreset: CompletionPreset | null = null;
|
||||
completionGenerating: boolean = false;
|
||||
@@ -334,16 +337,19 @@ class CommonStore {
|
||||
this.attachmentUploading = value;
|
||||
}
|
||||
|
||||
setAttachmentName(value: string) {
|
||||
this.attachmentName = value;
|
||||
setAttachments(value: { [uuid: string]: Attachment[] }) {
|
||||
this.attachments = value;
|
||||
}
|
||||
|
||||
setAttachmentSize(value: number) {
|
||||
this.attachmentSize = value;
|
||||
setAttachment(uuid: string, value: Attachment[] | null) {
|
||||
if (value === null)
|
||||
delete this.attachments[uuid];
|
||||
else
|
||||
this.attachments[uuid] = value;
|
||||
}
|
||||
|
||||
setAttachmentContent(value: string) {
|
||||
this.attachmentContent = value;
|
||||
setCurrentTempAttachment(value: Attachment | null) {
|
||||
this.currentTempAttachment = value;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
2
frontend/wailsjs/go/backend_golang/App.d.ts
generated
vendored
2
frontend/wailsjs/go/backend_golang/App.d.ts
generated
vendored
@@ -28,6 +28,8 @@ export function GetPyError():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 MergeLora(arg1:string,arg2:boolean,arg3:number,arg4:string,arg5:string,arg6:string):Promise<string>;
|
||||
|
||||
4
frontend/wailsjs/go/backend_golang/App.js
generated
4
frontend/wailsjs/go/backend_golang/App.js
generated
@@ -54,6 +54,10 @@ export function 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) {
|
||||
return window['go']['backend_golang']['App']['ListDirFiles'](arg1);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"version": "1.4.8",
|
||||
"version": "1.4.9",
|
||||
"introduction": {
|
||||
"en": "RWKV is an open-source, commercially usable large language model with high flexibility and great potential for development.\n### About This Tool\nThis tool aims to lower the barrier of entry for using large language models, making it accessible to everyone. It provides fully automated dependency and model management. You simply need to click and run, following the instructions, to deploy a local large language model. The tool itself is very compact and only requires a single executable file for one-click deployment.\nAdditionally, this tool offers an interface that is fully compatible with the OpenAI API. This means you can use any ChatGPT client as a client for RWKV, enabling capability expansion beyond just chat functionality.\n### Preset Configuration Rules at the Bottom\nThis tool comes with a series of preset configurations to reduce complexity. The naming rules for each configuration represent the following in order: device - required VRAM/memory - model size - model language.\nFor example, \"GPU-8G-3B-EN\" indicates that this configuration is for a graphics card with 8GB of VRAM, a model size of 3 billion parameters, and it uses an English language model.\nLarger model sizes have higher performance and VRAM requirements. Among configurations with the same model size, those with higher VRAM usage will have faster runtime.\nFor example, if you have 12GB of VRAM but running the \"GPU-12G-7B-EN\" configuration is slow, you can downgrade to \"GPU-8G-3B-EN\" for a significant speed improvement.\n### About RWKV\nRWKV is an RNN with Transformer-level LLM performance, which can also be directly trained like a GPT transformer (parallelizable). And it's 100% attention-free. You only need the hidden state at position t to compute the state at position t+1. You can use the \"GPT\" mode to quickly compute the hidden state for the \"RNN\" mode.<br/>So it's combining the best of RNN and transformer - great performance, fast inference, saves VRAM, fast training, \"infinite\" ctx_len, and free sentence embedding (using the final hidden state).",
|
||||
"zh": "RWKV是一个开源且允许商用的大语言模型,灵活性很高且极具发展潜力。\n### 关于本工具\n本工具旨在降低大语言模型的使用门槛,做到人人可用,本工具提供了全自动化的依赖和模型管理,你只需要直接点击运行,跟随引导,即可完成本地大语言模型的部署,工具本身体积极小,只需要一个exe即可完成一键部署。\n此外,本工具提供了与OpenAI API完全兼容的接口,这意味着你可以把任意ChatGPT客户端用作RWKV的客户端,实现能力拓展,而不局限于聊天。\n### 底部的预设配置规则\n本工具内置了一系列预设配置,以降低使用难度,每个配置名的规则,依次代表着:设备-所需显存/内存-模型规模-模型语言。\n例如,GPU-8G-3B-CN,表示该配置用于显卡,需要8G显存,模型规模为30亿参数,使用的是中文模型。\n模型规模越大,性能要求越高,显存要求也越高,而同样模型规模的配置中,显存占用越高的,运行速度越快。\n例如当你有12G显存,但运行GPU-12G-7B-CN配置速度比较慢,可降级成GPU-8G-3B-CN,将会大幅提速。\n### 关于RWKV\nRWKV是具有Transformer级别LLM性能的RNN,也可以像GPT Transformer一样直接进行训练(可并行化)。而且它是100% attention-free的。你只需在位置t处获得隐藏状态即可计算位置t + 1处的状态。你可以使用“GPT”模式快速计算用于“RNN”模式的隐藏状态。\n因此,它将RNN和Transformer的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。"
|
||||
|
||||
Reference in New Issue
Block a user