Compare commits

...

52 Commits

Author SHA1 Message Date
josc146
ad65765ba8 release v1.5.7 2023-11-29 22:59:47 +08:00
josc146
d04fd7cb87 fix lib 2023-11-29 22:59:42 +08:00
github-actions[bot]
b398cbb591 release v1.5.6 2023-11-29 13:22:21 +00:00
josc146
19b97e985c release v1.5.6 2023-11-29 21:21:50 +08:00
josc146
93bf74a320 fix NoteOff 2023-11-29 21:21:42 +08:00
josc146
7daae23bbb update defaultConfigs 2023-11-29 21:21:29 +08:00
josc146
0d0a3f15cc chore 2023-11-29 21:21:14 +08:00
github-actions[bot]
04fbb38861 release v1.5.5 2023-11-29 11:32:40 +00:00
josc146
d666c6032b release v1.5.5 2023-11-29 19:31:56 +08:00
josc146
93e8660d69 add instruments i18n 2023-11-29 19:31:52 +08:00
josc146
e687cf02bb try to use local soundfont by default 2023-11-29 19:17:19 +08:00
josc146
e858f1477a update locales 2023-11-29 19:10:01 +08:00
josc146
a2062ae9cc feat: save MIDI tracks to generation area; playing tracks and audio preview are still under development 2023-11-29 19:04:41 +08:00
josc146
34112c79c7 fix autoPlayed midi cannot be stopped 2023-11-29 15:28:43 +08:00
josc146
b625b8a6d1 MIDI Recording and details improvement 2023-11-29 14:05:58 +08:00
josc146
14a13d5768 basic MIDI Input Audio Tracks 2023-11-28 15:34:06 +08:00
josc146
7ce464ecda improve details 2023-11-26 22:54:59 +08:00
github-actions[bot]
2c1f89383f release v1.5.4 2023-11-24 11:22:42 +00:00
josc146
e666c50f77 release v1.5.4 2023-11-24 19:22:07 +08:00
josc146
1b441752b0 chore 2023-11-24 19:21:58 +08:00
josc146
e01897b24d improve launch flow of webgpu mode 2023-11-24 19:21:14 +08:00
josc146
6146d910b4 improve launch flow of webgpu mode 2023-11-24 18:36:44 +08:00
josc146
0063c171f3 upgrade to rwkv 0.8.22 (rwkv6 support) 2023-11-24 17:55:16 +08:00
josc146
bea3c29c1c update defaultConfigs 2023-11-24 17:13:22 +08:00
josc146
5f543c2545 update manifest 2023-11-24 16:35:21 +08:00
josc146
177b2c54d9 allow reading attachments even if the model is offline 2023-11-24 16:25:21 +08:00
josc146
645e8e2f44 chore 2023-11-24 15:58:53 +08:00
josc146
f2d0dda2ff allow safetensors converter on macOS 2023-11-21 22:32:25 +08:00
josc146
3a449e7b46 fix fs watcher of macOS 2023-11-21 22:30:42 +08:00
github-actions[bot]
18d2ecb7a7 release v1.5.3 2023-11-20 16:22:32 +00:00
josc146
bb3a93b419 release v1.5.3 2023-11-21 00:21:09 +08:00
josc146
1334f0e5ba chore 2023-11-21 00:20:54 +08:00
josc146
8781416cfb add hf-mirror for cn users 2023-11-21 00:04:23 +08:00
josc146
a9819139b8 add sidePanel for Chat page 2023-11-20 23:47:39 +08:00
josc146
66e43c9d9b display lastModelName at the top (WorkHeader) 2023-11-20 23:27:44 +08:00
josc146
41e5bd5eb8 change ValuedSlider's step to 100 2023-11-20 23:25:39 +08:00
josc146
48fef0235b add webgpu nf4 2023-11-20 21:10:10 +08:00
josc146
d435436525 improve finetune error 2023-11-20 20:39:00 +08:00
josc146
cd7a9896dc improve styles 2023-11-20 20:16:55 +08:00
josc146
bbcc6b07b6 improve precision description 2023-11-20 20:13:30 +08:00
josc146
646bcd81c0 fix webgpu permission for macos 2023-11-20 20:12:20 +08:00
josc146
dbf0dccc9d add tokenizer(/switch-model) to /docs 2023-11-20 20:11:45 +08:00
josc146
437de2be20 improve lazy loading ui 2023-11-18 13:59:37 +08:00
josc146
f739c61197 fix a finetune bug 2023-11-17 22:37:21 +08:00
josc146
01d3c89ea4 add rwkv API URL Option; update OpenAI models Option 2023-11-17 22:16:49 +08:00
josc146
d18218f21a use local API when it's working, even if a custom API URL is provided 2023-11-17 21:53:29 +08:00
josc146
c8470e77fd fix state_cache of deploy mode 2023-11-17 21:32:11 +08:00
josc146
9ede7d7c6d strict default_stop 2023-11-17 21:18:52 +08:00
josc146
a59c4436c8 macos: change default webgpu backend to aarch64-apple-darwin 2023-11-17 21:16:08 +08:00
josc146
068be2bfc4 update setup comments 2023-11-17 20:47:33 +08:00
josc146
94a5dc4fb7 update setup.sh comments 2023-11-14 17:38:24 +08:00
github-actions[bot]
9f288de951 release v1.5.2 2023-11-09 14:11:40 +00:00
56 changed files with 3556 additions and 1123 deletions

View File

@@ -109,6 +109,7 @@ jobs:
go install github.com/wailsapp/wails/v2/cmd/wails@latest
rm ./backend-python/rwkv_pip/wkv_cuda.pyd
rm ./backend-python/rwkv_pip/rwkv5.pyd
rm ./backend-python/rwkv_pip/rwkv6.pyd
rm ./backend-python/rwkv_pip/beta/wkv_cuda.pyd
rm ./backend-python/get-pip.py
make
@@ -134,12 +135,14 @@ jobs:
- run: |
git clone https://github.com/josStorer/ai00_rwkv_server --depth=1
cd ai00_rwkv_server
cargo build --release
mv ./target/release/ai00_server ../backend-rust/webgpu_server
rustup target add aarch64-apple-darwin
cargo build --release --target aarch64-apple-darwin
mv ./target/aarch64-apple-darwin/release/ai00_server ../backend-rust/webgpu_server
cd ..
go install github.com/wailsapp/wails/v2/cmd/wails@latest
rm ./backend-python/rwkv_pip/wkv_cuda.pyd
rm ./backend-python/rwkv_pip/rwkv5.pyd
rm ./backend-python/rwkv_pip/rwkv6.pyd
rm ./backend-python/rwkv_pip/beta/wkv_cuda.pyd
rm ./backend-python/get-pip.py
make

2
.gitignore vendored
View File

@@ -18,7 +18,7 @@ __pycache__
/cmd-helper.bat
/install-py-dep.bat
/backend-python/wkv_cuda
/backend-python/rwkv5
/backend-python/rwkv*
*.exe
*.old
.DS_Store

View File

@@ -1,14 +1,17 @@
## Changes
## Changes (v1.5.7 is a patch for v1.5.5 & v1.5.6)
### Improvements
- improve mobile webview
- add client upgrade progress
- improve user guide
- MIDI Input Audio Tracks (Experimental, playing tracks is not supported yet, please save to generation area to preview)
- fix autoPlayed midi cannot be stopped
- try to use local soundfont by default
- improve details
## Install
- Windows: https://github.com/josStorer/RWKV-Runner/blob/master/build/windows/Readme_Install.txt
- MacOS: https://github.com/josStorer/RWKV-Runner/blob/master/build/darwin/Readme_Install.txt
- Linux: https://github.com/josStorer/RWKV-Runner/blob/master/build/linux/Readme_Install.txt
- Server-Deploy-Examples: https://github.com/josStorer/RWKV-Runner/tree/master/deploy-examples
- Server-Deploy-Examples: https://github.com/josStorer/RWKV-Runner/tree/master/deploy-examples
#### MIDI Input Audio Tracks
![image](https://github.com/josStorer/RWKV-Runner/assets/13366013/e35e23a4-1942-4649-995d-eabf386722f7)

View File

@@ -8,15 +8,15 @@ endif
build-windows:
@echo ---- build for windows
wails build -upx -ldflags "-s -w" -platform windows/amd64
wails build -upx -ldflags '-s -w -extldflags "-static"' -platform windows/amd64
build-macos:
@echo ---- build for macos
wails build -ldflags "-s -w" -platform darwin/universal
wails build -ldflags '-s -w' -platform darwin/universal
build-linux:
@echo ---- build for linux
wails build -upx -ldflags "-s -w" -platform linux/amd64
wails build -upx -ldflags '-s -w' -platform linux/amd64
build-web:
@echo ---- build for web

View File

@@ -45,7 +45,7 @@ func (a *App) OnStartup(ctx context.Context) {
a.cmdPrefix = "cd " + a.exDir + " && "
}
os.Chmod("./backend-rust/webgpu_server", 0777)
os.Chmod(a.exDir+"backend-rust/webgpu_server", 0777)
os.Mkdir(a.exDir+"models", os.ModePerm)
os.Mkdir(a.exDir+"lora-models", os.ModePerm)
os.Mkdir(a.exDir+"finetune/json2binidx_tool/data", os.ModePerm)
@@ -55,6 +55,7 @@ func (a *App) OnStartup(ctx context.Context) {
}
a.downloadLoop()
a.midiLoop()
a.watchFs()
a.monitorHardware()
}
@@ -69,8 +70,8 @@ func (a *App) OnBeforeClose(ctx context.Context) bool {
func (a *App) watchFs() {
watcher, err := fsnotify.NewWatcher()
if err == nil {
watcher.Add("./lora-models")
watcher.Add("./models")
watcher.Add(a.exDir + "./lora-models")
watcher.Add(a.exDir + "./models")
go func() {
for {
select {

View File

@@ -33,9 +33,9 @@ type DownloadStatus struct {
var downloadList []*DownloadStatus
func existsInDownloadList(url string) bool {
func existsInDownloadList(path string, url string) bool {
for _, ds := range downloadList {
if ds.Url == url {
if ds.Path == path || ds.Url == url {
return true
}
}
@@ -88,7 +88,7 @@ func (a *App) ContinueDownload(url string) {
}
func (a *App) AddToDownloadList(path string, url string) {
if !existsInDownloadList(url) {
if !existsInDownloadList(a.exDir+path, url) {
downloadList = append(downloadList, &DownloadStatus{
resp: nil,
Name: filepath.Base(path),

164
backend-golang/midi.go Normal file
View File

@@ -0,0 +1,164 @@
package backend_golang
import (
"errors"
"fmt"
"time"
"github.com/mattrtaylor/go-rtmidi"
"github.com/wailsapp/wails/v2/pkg/runtime"
)
type Port struct {
Name string `json:"name"`
}
type MIDIMessage struct {
MessageType string `json:"messageType"`
Channel int `json:"channel"`
Note int `json:"note"`
Velocity int `json:"velocity"`
Control int `json:"control"`
Value int `json:"value"`
}
var ports []Port
var input rtmidi.MIDIIn
var out rtmidi.MIDIOut
var activeIndex int = -1
var lastNoteTime time.Time
func (a *App) midiLoop() {
var err error
input, err = rtmidi.NewMIDIInDefault()
if err != nil {
runtime.EventsEmit(a.ctx, "midiError", err.Error())
return
}
out, err = rtmidi.NewMIDIOutDefault()
if err != nil {
runtime.EventsEmit(a.ctx, "midiError", err.Error())
}
err = out.OpenPort(0, "")
if err != nil {
runtime.EventsEmit(a.ctx, "midiError", err.Error())
}
ticker := time.NewTicker(500 * time.Millisecond)
go func() {
for {
<-ticker.C
count, err := input.PortCount()
if err != nil {
continue
}
ports = make([]Port, count)
for i := 0; i < count; i++ {
name, err := input.PortName(i)
if err == nil {
ports[i].Name = name
}
}
runtime.EventsEmit(a.ctx, "midiPorts", &ports)
}
}()
}
func (a *App) OpenMidiPort(index int) error {
if input == nil {
return errors.New("failed to initialize MIDI input")
}
if activeIndex == index {
return nil
}
input.Destroy()
var err error
input, err = rtmidi.NewMIDIInDefault()
if err != nil {
return err
}
err = input.SetCallback(func(msg rtmidi.MIDIIn, bytes []byte, t float64) {
// https://www.midi.org/specifications-old/item/table-1-summary-of-midi-message
// https://www.rfc-editor.org/rfc/rfc6295.html
//
// msgType channel
// 1001 0000
//
msgType := bytes[0] >> 4
channel := bytes[0] & 0x0f
switch msgType {
case 0x8:
note := bytes[1]
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "NoteOff",
Channel: int(channel),
Note: int(note),
})
case 0x9:
elapsed := time.Since(lastNoteTime)
lastNoteTime = time.Now()
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "ElapsedTime",
Value: int(elapsed.Milliseconds()),
})
note := bytes[1]
velocity := bytes[2]
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "NoteOn",
Channel: int(channel),
Note: int(note),
Velocity: int(velocity),
})
case 0xb:
// control 12 => K1 knob, control 13 => K2 knob
control := bytes[1]
value := bytes[2]
runtime.EventsEmit(a.ctx, "midiMessage", &MIDIMessage{
MessageType: "ControlChange",
Channel: int(channel),
Control: int(control),
Value: int(value),
})
default:
fmt.Printf("Unknown midi message: %v\n", bytes)
}
})
if err != nil {
return err
}
err = input.OpenPort(index, "")
if err != nil {
return err
}
activeIndex = index
lastNoteTime = time.Now()
return nil
}
func (a *App) CloseMidiPort() error {
if input == nil {
return errors.New("failed to initialize MIDI input")
}
if activeIndex == -1 {
return nil
}
activeIndex = -1
input.Destroy()
var err error
input, err = rtmidi.NewMIDIInDefault()
if err != nil {
return err
}
return nil
}
func (a *App) PlayNote(msg MIDIMessage) error {
if out == nil {
return errors.New("failed to initialize MIDI output")
}
channelByte := byte(msg.Channel)
if msg.MessageType == "NoteOn" {
out.SendMessage([]byte{0x90 | channelByte, byte(msg.Note), byte(msg.Velocity)})
} else if msg.MessageType == "NoteOff" {
out.SendMessage([]byte{0x80 | channelByte, byte(msg.Note), byte(msg.Velocity)})
}
return nil
}

View File

@@ -35,6 +35,11 @@ default_stop = [
"\n\nQ",
"\n\nHuman",
"\n\nBob",
"\n\nAssistant",
"\n\nAnswer",
"\n\nA",
"\n\nBot",
"\n\nAlice",
]

View File

@@ -25,7 +25,7 @@ class SwitchModelBody(BaseModel):
"example": {
"model": "models/RWKV-4-World-3B-v1-20230619-ctx4096.pth",
"strategy": "cuda fp16",
"tokenizer": None,
"tokenizer": "",
"customCuda": False,
"deploy": False,
}

View File

@@ -73,12 +73,12 @@ class AddStateBody(BaseModel):
logits: Any
@router.post("/add-state", tags=["State Cache"])
# @router.post("/add-state", tags=["State Cache"])
def add_state(body: AddStateBody):
global trie, dtrie, loop_del_trie_id
if global_var.get(global_var.Deploy_Mode) is True:
raise HTTPException(status.HTTP_403_FORBIDDEN)
# if global_var.get(global_var.Deploy_Mode) is True:
# raise HTTPException(status.HTTP_403_FORBIDDEN)
if trie is None:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "trie not loaded")
@@ -157,12 +157,12 @@ def __get_a_dtrie_buff_size(dtrie_v):
return 54 * len(dtrie_v["tokens"]) + 491520 + 262144 + 28 # TODO
@router.post("/longest-prefix-state", tags=["State Cache"])
# @router.post("/longest-prefix-state", tags=["State Cache"])
def longest_prefix_state(body: LongestPrefixStateBody, request: Request):
global trie
if global_var.get(global_var.Deploy_Mode) is True:
raise HTTPException(status.HTTP_403_FORBIDDEN)
# if global_var.get(global_var.Deploy_Mode) is True:
# raise HTTPException(status.HTTP_403_FORBIDDEN)
if trie is None:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "trie not loaded")
@@ -200,12 +200,12 @@ def longest_prefix_state(body: LongestPrefixStateBody, request: Request):
}
@router.post("/save-state", tags=["State Cache"])
# @router.post("/save-state", tags=["State Cache"])
def save_state():
global trie
if global_var.get(global_var.Deploy_Mode) is True:
raise HTTPException(status.HTTP_403_FORBIDDEN)
# if global_var.get(global_var.Deploy_Mode) is True:
# raise HTTPException(status.HTTP_403_FORBIDDEN)
if trie is None:
raise HTTPException(status.HTTP_400_BAD_REQUEST, "trie not loaded")

87
backend-python/rwkv_pip/cuda/rwkv6.cu vendored Normal file
View File

@@ -0,0 +1,87 @@
#include <stdio.h>
#include <assert.h>
#include "ATen/ATen.h"
typedef at::BFloat16 bf16;
typedef at::Half fp16;
typedef float fp32;
template <typename F>
__global__ void kernel_forward(const int B, const int T, const int C, const int H, float *__restrict__ _state,
const F *__restrict__ const _r, const F *__restrict__ const _k, const F *__restrict__ const _v, const float *__restrict__ _w, const F *__restrict__ _u,
F *__restrict__ const _y)
{
const int b = blockIdx.x / H;
const int h = blockIdx.x % H;
const int i = threadIdx.x;
_u += h*_N_;
_state += h*_N_*_N_ + i*_N_; // wrong if B > 1 !!!
__shared__ float r[_N_], k[_N_], u[_N_], w[_N_];
float state[_N_];
#pragma unroll
for (int j = 0; j < _N_; j++)
state[j] = _state[j];
__syncthreads();
u[i] = float(_u[i]);
__syncthreads();
for (int t = b*T*C + h*_N_ + i; t < (b+1)*T*C + h*_N_ + i; t += C)
{
__syncthreads();
w[i] = _w[t];
r[i] = float(_r[t]);
k[i] = float(_k[t]);
__syncthreads();
const float v = float(_v[t]);
float y = 0;
#pragma unroll
for (int j = 0; j < _N_; j+=4)
{
const float4& r_ = (float4&)(r[j]);
const float4& k_ = (float4&)(k[j]);
const float4& w_ = (float4&)(w[j]);
const float4& u_ = (float4&)(u[j]);
float4& s = (float4&)(state[j]);
float4 x;
x.x = k_.x * v;
x.y = k_.y * v;
x.z = k_.z * v;
x.w = k_.w * v;
y += r_.x * (u_.x * x.x + s.x);
y += r_.y * (u_.y * x.y + s.y);
y += r_.z * (u_.z * x.z + s.z);
y += r_.w * (u_.w * x.w + s.w);
s.x = s.x * w_.x + x.x;
s.y = s.y * w_.y + x.y;
s.z = s.z * w_.z + x.z;
s.w = s.w * w_.w + x.w;
}
_y[t] = F(y);
}
#pragma unroll
for (int j = 0; j < _N_; j++)
_state[j] = state[j];
}
void cuda_forward_bf16(int B, int T, int C, int H, float *state, bf16 *r, bf16 *k, bf16 *v, float *w, bf16 *u, bf16 *y)
{
assert(H*_N_ == C);
kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
}
void cuda_forward_fp16(int B, int T, int C, int H, float *state, fp16 *r, fp16 *k, fp16 *v, float *w, fp16 *u, fp16 *y)
{
assert(H*_N_ == C);
kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
}
void cuda_forward_fp32(int B, int T, int C, int H, float *state, fp32 *r, fp32 *k, fp32 *v, float *w, fp32 *u, fp32 *y)
{
assert(H*_N_ == C);
kernel_forward<<<dim3(B * H), dim3(_N_)>>>(B, T, C, H, state, r, k, v, w, u, y);
}

View File

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

File diff suppressed because it is too large Load Diff

Binary file not shown.

BIN
backend-python/rwkv_pip/rwkv6.pyd vendored Normal file

Binary file not shown.

Binary file not shown.

View File

@@ -9,7 +9,7 @@ cd RWKV-Next-Web
git clone https://github.com/josStorer/RWKV-Runner --depth=1
python3 -m pip install torch torchvision torchaudio
python3 -m pip install -r RWKV-Runner/backend-python/requirements.txt
python3 ./RWKV-Runner/backend-python/main.py > log.txt &
python3 ./RWKV-Runner/backend-python/main.py > log.txt & # this is only an example, you should use screen or other tools to run it in background
if [ ! -d RWKV-Runner/models ]; then
mkdir RWKV-Runner/models
@@ -22,6 +22,6 @@ yarn install
yarn build
export PROXY_URL=""
export BASE_URL=http://127.0.0.1:8000
yarn start &
yarn start & # this is only an example, you should use screen or other tools to run it in background
curl http://127.0.0.1:8000/switch-model -X POST -H "Content-Type: application/json" -d '{"model":"./RWKV-Runner/models/RWKV-4-World-0.1B-v1-20230520-ctx4096.pth","strategy":"cpu fp32"}'

View File

@@ -9,6 +9,7 @@ call npm ci
call npm run build
cd ..
: optional: set ngrok_token=YOUR_NGROK_TOKEN
start python ./backend-python/main.py --webui
start "C:\Program Files (x86)\Microsoft\Edge\Application\msedge.exe" "http://127.0.0.1:8000"

View File

@@ -11,7 +11,8 @@ npm ci
npm run build
cd ..
python3 ./backend-python/main.py --webui > log.txt &
# optional: export ngrok_token=YOUR_NGROK_TOKEN
python3 ./backend-python/main.py --webui > log.txt & # this is only an example, you should use screen or other tools to run it in background
if [ ! -d models ]; then
mkdir models

View File

@@ -49,6 +49,10 @@ fi
echo "loading $loadModel"
modelInfo=$(python3 ./finetune/get_layer_and_embd.py $loadModel)
echo $modelInfo
python3 ./finetune/lora/train.py $modelInfo $@ --proj_dir lora-models --data_type binidx --lora \
--lora_parts=att,ffn,time,ln --strategy deepspeed_stage_2 --accelerator gpu
if [[ $modelInfo =~ "--n_layer" ]]; then
python3 ./finetune/lora/train.py $modelInfo $@ --proj_dir lora-models --data_type binidx --lora \
--lora_parts=att,ffn,time,ln --strategy deepspeed_stage_2 --accelerator gpu
else
echo "modelInfo is invalid"
exit 1
fi

File diff suppressed because it is too large Load Diff

View File

@@ -21,10 +21,12 @@
"i18next": "^22.4.15",
"mobx": "^6.9.0",
"mobx-react-lite": "^3.4.3",
"pdfjs-dist": "^4.0.189",
"react": "^18.2.0",
"react-beautiful-dnd": "^13.1.1",
"react-chartjs-2": "^5.2.0",
"react-dom": "^18.2.0",
"react-draggable": "^4.4.6",
"react-i18next": "^12.2.2",
"react-markdown": "^8.0.7",
"react-router": "^6.11.1",
@@ -50,6 +52,7 @@
"sass": "^1.62.1",
"tailwindcss": "^3.3.2",
"typescript": "^5.0.4",
"vite": "^4.3.6"
"vite": "^4.3.6",
"vite-plugin-top-level-await": "^1.3.1"
}
}

View File

@@ -82,7 +82,7 @@
"Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.": "モデルに鎮静剤を与えるようなもの。上位nの確率質量の結果を考えてみてください。0.1は上位10を考えており、質が高いが保守的で、1は全ての結果を考慮しており、質は低いが多様性があります。",
"Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.": "ポジティヴ値は、新しいトークンが今までのテキストに出現していたかどうかに基づいてこれらをペナルティとし、新しいトピックについて話す可能性を増加させます。",
"Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.": "ポジティブ値は、新しいトークンが既存のテキストでどれだけ頻繁に使われているかに基づいてペナルティを与え、モデルが同じ行を完全に繰り返す可能性を減らします。",
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality, and fp32 has the best quality.": "int8はVRAMの使用量が少ないですが、質が若干低いです。fp16は高品質、fp32は最高品質です。",
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality.": "int8はVRAMの使用量が少ないですが、質が若干低いです。fp16は高品質。",
"Number of the neural network layers loaded into VRAM, the more you load, the faster the speed, but it consumes more VRAM. (If your VRAM is not enough, it will fail to load)": "VRAMにロードされるニューラルネットワークの層の数。ロードする量が多いほど速度は速くなりますが、VRAMを多く消費します。(VRAMが不足している場合、ロードに失敗します)",
"Whether to use CPU to calculate the last output layer of the neural network with FP32 precision to obtain better quality.": "ネットワークの最終出力層をFP32精度で計算するためにCPUを使用するかどうか。",
"Downloads": "ダウンロード",
@@ -229,7 +229,7 @@
"Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "メモリが不足しています、仮想メモリ (WSL Swap) を増やすか小さなベースモデルを使用してみてください。",
"VRAM is not enough": "ビデオRAMが不足しています",
"Training data is not enough, reduce context length or add more data for training": "トレーニングデータが不足しています、コンテキストの長さを減らすか、トレーニング用のデータをさらに追加してください",
"You are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "トレーニングにWSL 1を使用していますWSL 2にアップグレードしてください。例:\"wsl --set-version Ubuntu-22.04 2\"を実行する",
"Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "Nvidia GPUが見つかりません。WindowsのGPUドライバが古すぎるか、トレーニングにWSL 1を使用している可能性がありますWSL 2にアップグレードしてください。例\"wsl --set-version Ubuntu-22.04 2\"を実行してください",
"Matched CUDA is not installed": "対応するCUDAがインストールされていません",
"Failed to convert data": "データの変換に失敗しました",
"Failed to merge model": "モデルのマージに失敗しました",
@@ -268,5 +268,37 @@
"Enable WebUI": "WebUIを有効化",
"Server is working on deployment mode, please close the terminal window manually": "サーバーはデプロイモードで動作しています、ターミナルウィンドウを手動で閉じてください",
"Server is working on deployment mode, please exit the program manually to stop the server": "サーバーはデプロイモードで動作しています、サーバーを停止するにはプログラムを手動で終了してください",
"You can increase the number of stored layers in Configs page to improve performance": "パフォーマンスを向上させるために、保存されるレイヤーの数を設定ページで増やすことができます"
"You can increase the number of stored layers in Configs page to improve performance": "パフォーマンスを向上させるために、保存されるレイヤーの数を設定ページで増やすことができます",
"Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "モデルの読み込みに失敗しました、仮想メモリ (WSL Swap) を増やすか小さなベースモデルを使用してみてください。",
"Save Conversation": "会話を保存",
"Use Hugging Face Mirror": "Hugging Faceミラーを使用",
"File is empty": "ファイルが空です",
"Open MIDI Input Audio Tracks": "MIDI入力オーディオトラックを開く",
"Track": "トラック",
"Play All": "すべて再生",
"Clear All": "すべてクリア",
"Scale View": "スケールビュー",
"Record": "録音",
"Play": "再生",
"New Track": "新規トラック",
"Select a track to preview the content": "トラックを選択して内容をプレビュー",
"Save to generation area": "生成エリアに保存",
"Piano": "ピアノ",
"Percussion": "パーカッション",
"Drum": "ドラム",
"Tuba": "チューバ",
"Marimba": "マリンバ",
"Bass": "ベース",
"Guitar": "ギター",
"Violin": "バイオリン",
"Trumpet": "トランペット",
"Sax": "サックス",
"Flute": "フルート",
"Lead": "リード",
"Pad": "パッド",
"MIDI Input": "MIDI入力",
"Select the MIDI input device to be used.": "使用するMIDI入力デバイスを選択します。",
"Start Time": "開始時間",
"Content Duration": "内容の長さ",
"Please select a MIDI device first": "まずMIDIデバイスを選択してください"
}

View File

@@ -82,7 +82,7 @@
"Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.": "就像给模型喂镇静剂. 考虑前 n% 概率质量的结果, 0.1 考虑前 10%, 质量更高, 但更保守, 1 考虑所有质量结果, 质量降低, 但更多样",
"Positive values penalize new tokens based on whether they appear in the text so far, increasing the model's likelihood to talk about new topics.": "存在惩罚. 正值根据新token在至今的文本中是否出现过, 来对其进行惩罚, 从而增加了模型涉及新话题的可能性",
"Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model's likelihood to repeat the same line verbatim.": "频率惩罚. 正值根据新token在至今的文本中出现的频率/次数, 来对其进行惩罚, 从而减少模型原封不动地重复相同句子的可能性",
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality, and fp32 has the best quality.": "int8占用显存更低, 但质量略微下降. fp16质量更好, fp32质量最好",
"int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality.": "int8占用显存更低, 但质量略微下降. fp16质量更好",
"Number of the neural network layers loaded into VRAM, the more you load, the faster the speed, but it consumes more VRAM. (If your VRAM is not enough, it will fail to load)": "载入显存的神经网络层数, 载入越多, 速度越快, 但显存消耗越大 (如果你的显存不够, 会载入失败)",
"Whether to use CPU to calculate the last output layer of the neural network with FP32 precision to obtain better quality.": "是否使用cpu以fp32精度计算神经网络的最后一层输出层, 以获得更好的质量",
"Downloads": "下载",
@@ -229,7 +229,7 @@
"Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "内存不足,尝试增加虚拟内存(WSL Swap),或使用一个更小规模的基底模型",
"VRAM is not enough": "显存不足",
"Training data is not enough, reduce context length or add more data for training": "训练数据不足,请减小上下文长度或增加训练数据",
"You are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "你正在使用WSL 1进行训练请升级到WSL 2。例如行\"wsl --set-version Ubuntu-22.04 2\"",
"Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run \"wsl --set-version Ubuntu-22.04 2\"": "没有找到Nvidia显卡。可能是因为你的windows显卡驱动太旧或者你正在使用WSL 1进行训练请升级到WSL 2。例如行\"wsl --set-version Ubuntu-22.04 2\"",
"Matched CUDA is not installed": "未安装匹配的CUDA",
"Failed to convert data": "数据转换失败",
"Failed to merge model": "合并模型失败",
@@ -268,5 +268,37 @@
"Enable WebUI": "启用WebUI",
"Server is working on deployment mode, please close the terminal window manually": "服务器正在部署模式下运行,请手动关闭终端窗口",
"Server is working on deployment mode, please exit the program manually to stop the server": "服务器正在部署模式下运行,请手动退出程序以停止服务器",
"You can increase the number of stored layers in Configs page to improve performance": "你可以在配置页面增加载入显存层数以提升性能"
"You can increase the number of stored layers in Configs page to improve performance": "你可以在配置页面增加载入显存层数以提升性能",
"Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.": "模型载入失败,尝试增加虚拟内存(WSL Swap),或使用一个更小规模的基底模型",
"Save Conversation": "保存对话",
"Use Hugging Face Mirror": "使用Hugging Face镜像源",
"File is empty": "文件为空",
"Open MIDI Input Audio Tracks": "打开MIDI输入音轨",
"Track": "音轨",
"Play All": "播放全部",
"Clear All": "清空",
"Scale View": "缩放视图",
"Record": "录制",
"Play": "播放",
"New Track": "新建音轨",
"Select a track to preview the content": "选择一个音轨以预览内容",
"Save to generation area": "保存到生成区",
"Piano": "钢琴",
"Percussion": "打击乐",
"Drum": "鼓",
"Tuba": "大号",
"Marimba": "马林巴",
"Bass": "贝斯",
"Guitar": "吉他",
"Violin": "小提琴",
"Trumpet": "小号",
"Sax": "萨克斯",
"Flute": "长笛",
"Lead": "主音",
"Pad": "和音",
"MIDI Input": "MIDI输入",
"Select the MIDI input device to be used.": "选择要使用的MIDI输入设备",
"Start Time": "开始时间",
"Content Duration": "内容时长",
"Please select a MIDI device first": "请先选择一个MIDI设备"
}

View File

@@ -4,7 +4,7 @@ import { Dropdown, Option } from '@fluentui/react-components';
import commonStore from '../stores/commonStore';
export const ConfigSelector: FC<{ size?: 'small' | 'medium' | 'large' }> = observer(({ size }) => {
return <Dropdown size={size} style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
return <Dropdown size={size} style={{ minWidth: 0 }} listbox={{ style: { minWidth: 'fit-content' } }}
value={commonStore.getCurrentModelConfig().name}
selectedOptions={[commonStore.currentModelConfigIndex.toString()]}
onOptionSelect={(_, data) => {

View File

@@ -1,5 +1,6 @@
import { FC, LazyExoticComponent, ReactNode, Suspense } from 'react';
import { useTranslation } from 'react-i18next';
import { Spinner } from '@fluentui/react-components';
interface LazyImportComponentProps {
lazyChildren: LazyExoticComponent<FC<any>>;
@@ -11,7 +12,10 @@ export const LazyImportComponent: FC<LazyImportComponentProps> = (props) => {
const { t } = useTranslation();
return (
<Suspense fallback={<div>{t('Loading...')}</div>}>
<Suspense fallback={
<div className="flex justify-center items-center h-full w-full">
<Spinner size="huge" label={t('Loading...')} />
</div>}>
<props.lazyChildren {...props.lazyProps}>
{props.children}
</props.lazyChildren>

View File

@@ -11,12 +11,13 @@ import { Button } from '@fluentui/react-components';
import { observer } from 'mobx-react-lite';
import { exit, getStatus, readRoot, switchModel, updateConfig } from '../apis';
import { toast } from 'react-toastify';
import { checkDependencies, getStrategy, toastWithButton } from '../utils';
import { checkDependencies, getHfDownloadUrl, getStrategy, toastWithButton } from '../utils';
import { useTranslation } from 'react-i18next';
import { ToolTipButton } from './ToolTipButton';
import { Play16Regular, Stop16Regular } from '@fluentui/react-icons';
import { useNavigate } from 'react-router';
import { WindowShow } from '../../wailsjs/runtime';
import { convertToSt } from '../utils/convert-to-st';
const mainButtonText = {
[ModelStatus.Offline]: 'Run',
@@ -57,13 +58,40 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
return;
}
const currentModelSource = commonStore.modelSourceList.find(item => item.name === modelName);
const showDownloadPrompt = (promptInfo: string, downloadName: string) => {
toastWithButton(promptInfo, t('Download'), () => {
const downloadUrl = currentModelSource?.downloadUrl;
if (downloadUrl) {
toastWithButton(`${t('Downloading')} ${downloadName}`, t('Check'), () => {
navigate({ pathname: '/downloads' });
},
{ autoClose: 3000 });
AddToDownloadList(modelPath, getHfDownloadUrl(downloadUrl));
} else {
toast(t('Can not find download url'), { type: 'error' });
}
});
};
if (webgpu) {
if (!['.st', '.safetensors'].some(ext => modelPath.endsWith(ext))) {
const stModelPath = modelPath.replace(/\.pth$/, '.st');
if (await FileExists(stModelPath)) {
modelPath = stModelPath;
} else if (!await FileExists(modelPath)) {
showDownloadPrompt(t('Model file not found'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
} else if (!currentModelSource?.isComplete) {
showDownloadPrompt(t('Model file download is not complete'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
} else {
toast(t('Please convert model to safe tensors format first'), { type: 'error' });
toastWithButton(t('Please convert model to safe tensors format first'), t('Convert'), () => {
convertToSt(navigate, modelConfig);
});
commonStore.setStatus({ status: ModelStatus.Offline });
return;
}
@@ -84,28 +112,13 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
return;
}
const currentModelSource = commonStore.modelSourceList.find(item => item.name === modelName);
const showDownloadPrompt = (promptInfo: string, downloadName: string) => {
toastWithButton(promptInfo, t('Download'), () => {
const downloadUrl = currentModelSource?.downloadUrl;
if (downloadUrl) {
toastWithButton(`${t('Downloading')} ${downloadName}`, t('Check'), () => {
navigate({ pathname: '/downloads' });
},
{ autoClose: 3000 });
AddToDownloadList(modelPath, downloadUrl);
} else {
toast(t('Can not find download url'), { type: 'error' });
}
});
};
if (!await FileExists(modelPath)) {
showDownloadPrompt(t('Model file not found'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
} else if (!currentModelSource?.isComplete) {
} else // If the user selects the .pth model with WebGPU mode, modelPath will be set to the .st model.
// However, if the .pth model is deleted, modelPath will exist and isComplete will be false.
if (!currentModelSource?.isComplete && modelPath.endsWith('.pth')) {
showDownloadPrompt(t('Model file download is not complete'), modelName);
commonStore.setStatus({ status: ModelStatus.Offline });
return;
@@ -138,6 +151,8 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
toast(t('Error') + ' - ' + errMsg, { type: 'error' });
});
setTimeout(WindowShow, 1000);
setTimeout(WindowShow, 2000);
setTimeout(WindowShow, 3000);
let timeoutCount = 6;
let loading = false;
@@ -154,7 +169,7 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
});
}
commonStore.setStatus({ status: ModelStatus.Loading });
toast(t('Loading Model'), { type: 'info' });
const loadingId = toast(t('Loading Model'), { type: 'info' });
if (!webgpu) {
updateConfig({
max_tokens: modelConfig.apiParameters.maxResponseToken,
@@ -240,6 +255,8 @@ export const RunButton: FC<{ onClickRun?: MouseEventHandler, iconMode?: boolean
}).catch((e) => {
commonStore.setStatus({ status: ModelStatus.Offline });
toast(t('Failed to switch model') + ' - ' + (e.message || e), { type: 'error' });
}).finally(() => {
toast.dismiss(loadingId);
});
}
}).catch(() => {

View File

@@ -6,6 +6,7 @@ import { ConfigSelector } from './ConfigSelector';
import { RunButton } from './RunButton';
import { PresenceBadgeStatus } from '@fluentui/react-badge';
import { useTranslation } from 'react-i18next';
import { useMediaQuery } from 'usehooks-ts';
const statusText = {
[ModelStatus.Offline]: 'Offline',
@@ -23,6 +24,7 @@ const badgeStatus: { [modelStatus: number]: PresenceBadgeStatus } = {
export const WorkHeader: FC = observer(() => {
const { t } = useTranslation();
const mq = useMediaQuery('(min-width: 640px)');
const port = commonStore.getCurrentModelConfig().apiParameters.apiPort;
return commonStore.platform === 'web' ?
@@ -33,6 +35,10 @@ export const WorkHeader: FC = observer(() => {
<PresenceBadge status={badgeStatus[commonStore.status.status]} />
<Text size={100}>{t('Model Status') + ': ' + t(statusText[commonStore.status.status])}</Text>
</div>
{commonStore.lastModelName && mq &&
<Text size={100}>
{commonStore.lastModelName}
</Text>}
<div className="flex items-center gap-2">
<ConfigSelector size="small" />
<RunButton iconMode />

View File

@@ -0,0 +1,40 @@
import React, { FC, lazy } from 'react';
import { useTranslation } from 'react-i18next';
import { Button, Dialog, DialogBody, DialogContent, DialogSurface, DialogTrigger } from '@fluentui/react-components';
import { CustomToastContainer } from '../../components/CustomToastContainer';
import { LazyImportComponent } from '../../components/LazyImportComponent';
import { flushMidiRecordingContent } from '../../utils';
import commonStore from '../../stores/commonStore';
const AudiotrackEditor = lazy(() => import('./AudiotrackEditor'));
export const AudiotrackButton: FC<{
size?: 'small' | 'medium' | 'large',
shape?: 'rounded' | 'circular' | 'square';
appearance?: 'secondary' | 'primary' | 'outline' | 'subtle' | 'transparent';
setPrompt: (prompt: string) => void;
}> = ({ size, shape, appearance, setPrompt }) => {
const { t } = useTranslation();
return <Dialog onOpenChange={(e, data) => {
if (!data.open) {
flushMidiRecordingContent();
commonStore.setRecordingTrackId('');
commonStore.setPlayingTrackId('');
}
}}>
<DialogTrigger disableButtonEnhancement>
<Button size={size} shape={shape} appearance={appearance}>
{t('Open MIDI Input Audio Tracks')}
</Button>
</DialogTrigger>
<DialogSurface style={{ paddingTop: 0, maxWidth: '90vw', width: 'fit-content' }}>
<DialogBody>
<DialogContent className="overflow-hidden">
<CustomToastContainer />
<LazyImportComponent lazyChildren={AudiotrackEditor} lazyProps={{ setPrompt }} />
</DialogContent>
</DialogBody>
</DialogSurface>
</Dialog>;
};

View File

@@ -0,0 +1,499 @@
import React, { FC, useEffect, useRef, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { useTranslation } from 'react-i18next';
import Draggable from 'react-draggable';
import { ToolTipButton } from '../../components/ToolTipButton';
import { v4 as uuid } from 'uuid';
import {
Add16Regular,
ArrowAutofitWidth20Regular,
Delete16Regular,
MusicNote220Regular,
Pause16Regular,
Play16Filled,
Play16Regular,
Record16Regular,
Stop16Filled
} from '@fluentui/react-icons';
import { Button, Card, DialogTrigger, Slider, Text, Tooltip } from '@fluentui/react-components';
import { useWindowSize } from 'usehooks-ts';
import commonStore from '../../stores/commonStore';
import classnames from 'classnames';
import {
InstrumentTypeNameMap,
InstrumentTypeTokenMap,
MidiMessage,
tracksMinimalTotalTime
} from '../../types/composition';
import { toast } from 'react-toastify';
import { ToastOptions } from 'react-toastify/dist/types';
import { flushMidiRecordingContent, refreshTracksTotalTime } from '../../utils';
import { PlayNote } from '../../../wailsjs/go/backend_golang/App';
import { t } from 'i18next';
const snapValue = 25;
const minimalMoveTime = 8; // 1000/125=8ms wait_events=125
const scaleMin = 0.05;
const scaleMax = 3;
const baseMoveTime = Math.round(minimalMoveTime / scaleMin);
const velocityEvents = 128;
const velocityBins = 12;
const velocityExp = 0.5;
const minimalTrackWidth = 80;
const trackInitOffsetPx = 10;
const pixelFix = 0.5;
const topToArrowIcon = 19;
const arrowIconToTracks = 23;
type TrackProps = {
id: string;
right: number;
scale: number;
isSelected: boolean;
onSelect: (id: string) => void;
};
const displayCurrentInstrumentType = () => {
const displayPanelId = 'instrument_panel_id';
const content: React.ReactNode =
<div className="flex gap-2 items-center">
{InstrumentTypeNameMap.map((name, i) =>
<Text key={name} style={{ whiteSpace: 'nowrap' }}
className={commonStore.instrumentType === i ? 'text-blue-600' : ''}
weight={commonStore.instrumentType === i ? 'bold' : 'regular'}
size={commonStore.instrumentType === i ? 300 : 100}
>{t(name)}</Text>)}
</div>;
const options: ToastOptions = {
type: 'default',
autoClose: 2000,
toastId: displayPanelId,
position: 'top-left',
style: {
width: 'fit-content'
}
};
if (toast.isActive(displayPanelId))
toast.update(displayPanelId, {
render: content,
...options
});
else
toast(content, options);
};
const velocityToBin = (velocity: number) => {
velocity = Math.max(0, Math.min(velocity, velocityEvents - 1));
const binsize = velocityEvents / (velocityBins - 1);
return Math.ceil((velocityEvents * ((Math.pow(velocityExp, (velocity / velocityEvents)) - 1.0) / (velocityExp - 1.0))) / binsize);
};
const midiMessageToToken = (msg: MidiMessage) => {
if (msg.messageType === 'NoteOn' || msg.messageType === 'NoteOff') {
const instrument = InstrumentTypeTokenMap[commonStore.instrumentType];
const note = msg.note.toString(16);
const velocity = velocityToBin(msg.velocity).toString(16);
return `${instrument}:${note}:${velocity} `;
} else if (msg.messageType === 'ElapsedTime') {
let time = Math.round(msg.value / minimalMoveTime);
const num = Math.floor(time / 125); // wait_events=125
time -= num * 125;
let ret = '';
for (let i = 0; i < num; i++) {
ret += 't125 ';
}
if (time > 0)
ret += `t${time} `;
return ret;
} else
return '';
};
let dropRecordingTime = false;
export const midiMessageHandler = async (data: MidiMessage) => {
if (data.messageType === 'ControlChange') {
commonStore.setInstrumentType(Math.round(data.value / 127 * (InstrumentTypeNameMap.length - 1)));
displayCurrentInstrumentType();
return;
}
if (commonStore.recordingTrackId) {
if (dropRecordingTime && data.messageType === 'ElapsedTime') {
dropRecordingTime = false;
return;
}
data = {
...data,
instrument: commonStore.instrumentType
};
commonStore.setRecordingRawContent([...commonStore.recordingRawContent, data]);
commonStore.setRecordingContent(commonStore.recordingContent + midiMessageToToken(data));
//TODO data.channel = data.instrument;
PlayNote(data);
}
};
const Track: React.FC<TrackProps> = observer(({
id,
right,
scale,
isSelected,
onSelect
}) => {
const { t } = useTranslation();
const trackIndex = commonStore.tracks.findIndex(t => t.id === id)!;
const track = commonStore.tracks[trackIndex];
const trackClass = isSelected ? 'bg-blue-600' : 'bg-gray-700';
const controlX = useRef(0);
return (
<Draggable
axis="x"
bounds={{ left: 0, right }}
grid={[snapValue, snapValue]}
position={{
x: (track.offsetTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue,
y: 0
}}
onStart={(e, data) => {
controlX.current = data.lastX;
}}
onStop={(e, data) => {
const delta = data.lastX - controlX.current;
let offsetTime = Math.round(Math.round(delta / snapValue * baseMoveTime * scale) / minimalMoveTime) * minimalMoveTime;
offsetTime = Math.min(Math.max(
offsetTime,
-track.offsetTime), commonStore.trackTotalTime - track.offsetTime);
const tracks = commonStore.tracks.slice();
tracks[trackIndex].offsetTime += offsetTime;
commonStore.setTracks(tracks);
refreshTracksTotalTime();
}}
>
<div
className={`p-1 cursor-move rounded whitespace-nowrap overflow-hidden ${trackClass}`}
style={{
width: `${Math.max(minimalTrackWidth,
track.contentTime / (baseMoveTime * scale) * snapValue
)}px`
}}
onClick={() => onSelect(id)}
>
<span className="text-white">{t('Track') + ' ' + (track.content || id)}</span>
</div>
</Draggable>
);
});
const AudiotrackEditor: FC<{ setPrompt: (prompt: string) => void }> = observer(({ setPrompt }) => {
const { t } = useTranslation();
const viewControlsContainerRef = useRef<HTMLDivElement>(null);
const currentTimeControlRef = useRef<HTMLDivElement>(null);
const playStartTimeControlRef = useRef<HTMLDivElement>(null);
const tracksEndLineRef = useRef<HTMLDivElement>(null);
const tracksRef = useRef<HTMLDivElement>(null);
const toolbarRef = useRef<HTMLDivElement>(null);
const toolbarButtonRef = useRef<HTMLDivElement>(null);
const toolbarSliderRef = useRef<HTMLInputElement>(null);
const contentPreviewRef = useRef<HTMLDivElement>(null);
const [refreshRef, setRefreshRef] = useState(false);
const windowSize = useWindowSize();
const scale = (scaleMin + scaleMax) - commonStore.trackScale;
const [selectedTrackId, setSelectedTrackId] = useState<string>('');
const playStartTimeControlX = useRef(0);
const selectedTrack = selectedTrackId ? commonStore.tracks.find(t => t.id === selectedTrackId) : undefined;
useEffect(() => {
if (toolbarSliderRef.current && toolbarSliderRef.current.parentElement)
toolbarSliderRef.current.parentElement.style.removeProperty('--fui-Slider--steps-percent');
}, []);
const scrollContentToBottom = () => {
if (contentPreviewRef.current)
contentPreviewRef.current.scrollTop = contentPreviewRef.current.scrollHeight;
};
useEffect(() => {
scrollContentToBottom();
}, [commonStore.recordingContent]);
useEffect(() => {
setRefreshRef(!refreshRef);
}, [windowSize, commonStore.tracks]);
const viewControlsContainerWidth = (toolbarRef.current && toolbarButtonRef.current && toolbarSliderRef.current) ?
toolbarRef.current.clientWidth - toolbarButtonRef.current.clientWidth - toolbarSliderRef.current.clientWidth - 16 // 16 = ml-2 mr-2
: 0;
const tracksWidth = viewControlsContainerWidth;
const timeOfTracksWidth = Math.floor(tracksWidth / snapValue) // number of moves
* baseMoveTime * scale;
const currentTimeControlWidth = (timeOfTracksWidth < commonStore.trackTotalTime)
? timeOfTracksWidth / commonStore.trackTotalTime * viewControlsContainerWidth
: 0;
const playStartTimeControlPosition = (commonStore.trackPlayStartTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue;
const tracksEndPosition = (commonStore.trackTotalTime - commonStore.trackCurrentTime) / (baseMoveTime * scale) * snapValue;
const moveableTracksWidth = (tracksEndLineRef.current && viewControlsContainerRef.current &&
((tracksEndLineRef.current.getBoundingClientRect().left - (viewControlsContainerRef.current.getBoundingClientRect().left + trackInitOffsetPx)) > 0))
? tracksEndLineRef.current.getBoundingClientRect().left - (viewControlsContainerRef.current.getBoundingClientRect().left + trackInitOffsetPx)
: Infinity;
return (
<div className="flex flex-col gap-2 overflow-hidden" style={{ width: '80vw', height: '80vh' }}>
<div className="mx-auto">
<Text size={100}>{`${commonStore.trackPlayStartTime} ms / ${commonStore.trackTotalTime} ms`}</Text>
</div>
<div className="flex pb-2 border-b" ref={toolbarRef}>
<div className="flex gap-2" ref={toolbarButtonRef}>
<ToolTipButton disabled desc={t('Play All') + ' (Unavailable)'} icon={<Play16Regular />} />
<ToolTipButton desc={t('Clear All')} icon={<Delete16Regular />} onClick={() => {
commonStore.setTracks([]);
commonStore.setTrackScale(1);
commonStore.setTrackTotalTime(tracksMinimalTotalTime);
commonStore.setTrackCurrentTime(0);
commonStore.setTrackPlayStartTime(0);
}} />
</div>
<div className="grow">
<div className="flex flex-col ml-2 mr-2" ref={viewControlsContainerRef}>
<div className="relative">
<Tooltip content={`${commonStore.trackTotalTime} ms`} showDelay={0} hideDelay={0}
relationship="description">
<div className="border-l absolute"
ref={tracksEndLineRef}
style={{
height: (tracksRef.current && commonStore.tracks.length > 0)
? tracksRef.current.clientHeight - arrowIconToTracks
: 0,
top: `${topToArrowIcon + arrowIconToTracks}px`,
left: `${tracksEndPosition + trackInitOffsetPx - pixelFix}px`
}} />
</Tooltip>
</div>
<Draggable axis="x" bounds={{
left: 0,
right: viewControlsContainerWidth - currentTimeControlWidth
}}
position={{
x: commonStore.trackCurrentTime / commonStore.trackTotalTime * viewControlsContainerWidth,
y: 0
}}
onDrag={(e, data) => {
setTimeout(() => {
let offset = 0;
if (currentTimeControlRef.current) {
const match = currentTimeControlRef.current.style.transform.match(/translate\((.+)px,/);
if (match)
offset = parseFloat(match[1]);
}
const offsetTime = commonStore.trackTotalTime / viewControlsContainerWidth * offset;
commonStore.setTrackCurrentTime(offsetTime);
}, 1);
}}
>
<div ref={currentTimeControlRef} className="h-2 bg-gray-700 cursor-move rounded"
style={{ width: currentTimeControlWidth }} />
</Draggable>
<div className={classnames(
'flex',
(playStartTimeControlPosition < 0 || playStartTimeControlPosition > viewControlsContainerWidth)
&& 'hidden'
)}>
<Draggable axis="x" bounds={{
left: 0,
right: (playStartTimeControlRef.current)
? Math.min(viewControlsContainerWidth - playStartTimeControlRef.current.clientWidth, moveableTracksWidth)
: 0
}}
grid={[snapValue, snapValue]}
position={{ x: playStartTimeControlPosition, y: 0 }}
onStart={(e, data) => {
playStartTimeControlX.current = data.lastX;
}}
onStop={(e, data) => {
const delta = data.lastX - playStartTimeControlX.current;
let offsetTime = Math.round(Math.round(delta / snapValue * baseMoveTime * scale) / minimalMoveTime) * minimalMoveTime;
offsetTime = Math.min(Math.max(
offsetTime,
-commonStore.trackPlayStartTime), commonStore.trackTotalTime - commonStore.trackPlayStartTime);
commonStore.setTrackPlayStartTime(commonStore.trackPlayStartTime + offsetTime);
}}
>
<div className="relative cursor-move"
ref={playStartTimeControlRef}>
<ArrowAutofitWidth20Regular />
<div className="border-l absolute border-gray-700"
style={{
height: (tracksRef.current && commonStore.tracks.length > 0)
? tracksRef.current.clientHeight
: 0,
top: '50%',
left: `calc(50% - ${pixelFix}px)`
}} />
</div>
</Draggable>
</div>
</div>
</div>
<Tooltip content={t('Scale View')! + ': ' + commonStore.trackScale} showDelay={0} hideDelay={0}
relationship="description">
<Slider ref={toolbarSliderRef} value={commonStore.trackScale} step={scaleMin} max={scaleMax} min={scaleMin}
onChange={(e, data) => {
commonStore.setTrackScale(data.value);
}}
/>
</Tooltip>
</div>
<div className="flex flex-col overflow-y-auto gap-1" ref={tracksRef}>
{commonStore.tracks.map(track =>
<div key={track.id} className="flex gap-2 pb-1 border-b">
<div className="flex gap-1 border-r h-7">
<ToolTipButton desc={commonStore.recordingTrackId === track.id ? t('Stop') : t('Record')}
icon={commonStore.recordingTrackId === track.id ? <Stop16Filled /> : <Record16Regular />}
size="small" shape="circular" appearance="subtle"
onClick={() => {
flushMidiRecordingContent();
commonStore.setPlayingTrackId('');
if (commonStore.recordingTrackId === track.id) {
commonStore.setRecordingTrackId('');
} else {
if (commonStore.activeMidiDeviceIndex === -1) {
toast(t('Please select a MIDI device first'), { type: 'warning' });
return;
}
dropRecordingTime = true;
setSelectedTrackId(track.id);
commonStore.setRecordingTrackId(track.id);
commonStore.setRecordingContent(track.content);
commonStore.setRecordingRawContent(track.rawContent.slice());
}
}} />
<ToolTipButton disabled
desc={commonStore.playingTrackId === track.id ? t('Stop') : t('Play') + ' (Unavailable)'}
icon={commonStore.playingTrackId === track.id ? <Pause16Regular /> : <Play16Filled />}
size="small" shape="circular" appearance="subtle"
onClick={() => {
flushMidiRecordingContent();
commonStore.setRecordingTrackId('');
if (commonStore.playingTrackId === track.id) {
commonStore.setPlayingTrackId('');
} else {
setSelectedTrackId(track.id);
commonStore.setPlayingTrackId(track.id);
}
}} />
<ToolTipButton desc={t('Delete')} icon={<Delete16Regular />} size="small" shape="circular"
appearance="subtle" onClick={() => {
const tracks = commonStore.tracks.slice().filter(t => t.id !== track.id);
commonStore.setTracks(tracks);
refreshTracksTotalTime();
}} />
</div>
<div className="relative grow overflow-hidden">
<div className="absolute" style={{ left: -0 }}>
<Track
id={track.id}
scale={scale}
right={Math.min(tracksWidth, moveableTracksWidth)}
isSelected={selectedTrackId === track.id}
onSelect={setSelectedTrackId}
/>
</div>
</div>
</div>)}
<div className="flex justify-between items-center">
<Button icon={<Add16Regular />} size="small" shape="circular"
appearance="subtle"
onClick={() => {
commonStore.setTracks([...commonStore.tracks, {
id: uuid(),
content: '',
rawContent: [],
offsetTime: 0,
contentTime: 0
}]);
}}>
{t('New Track')}
</Button>
<Text size={100}>
{t('Select a track to preview the content')}
</Text>
</div>
</div>
<div className="grow"></div>
{selectedTrack &&
<Card size="small" appearance="outline" style={{ minHeight: '150px', maxHeight: '200px' }}>
<div className="flex flex-col gap-1 overflow-hidden">
<Text size={100}>{`${t('Start Time')}: ${selectedTrack.offsetTime} ms`}</Text>
<Text size={100}>{`${t('Content Duration')}: ${selectedTrack.contentTime} ms`}</Text>
<div className="overflow-y-auto overflow-x-hidden" ref={contentPreviewRef}>
{selectedTrackId === commonStore.recordingTrackId
? commonStore.recordingContent
: selectedTrack.content}
</div>
</div>
</Card>
}
<DialogTrigger disableButtonEnhancement>
<Button icon={<MusicNote220Regular />} style={{ minHeight: '32px' }} onClick={() => {
flushMidiRecordingContent();
commonStore.setRecordingTrackId('');
commonStore.setPlayingTrackId('');
const timestamp = [];
const sortedTracks = commonStore.tracks.slice().sort((a, b) => a.offsetTime - b.offsetTime);
for (const track of sortedTracks) {
timestamp.push(track.offsetTime);
let accContentTime = 0;
for (const msg of track.rawContent) {
if (msg.messageType === 'ElapsedTime') {
accContentTime += msg.value;
timestamp.push(track.offsetTime + accContentTime);
}
}
}
const sortedTimestamp = timestamp.slice().sort((a, b) => a - b);
const globalMessages: MidiMessage[] = sortedTimestamp.reduce((messages, current, i) =>
[...messages, {
messageType: 'ElapsedTime',
value: current - (i === 0 ? 0 : sortedTimestamp[i - 1])
} as MidiMessage]
, [] as MidiMessage[]);
for (const track of sortedTracks) {
let currentTime = track.offsetTime;
let accContentTime = 0;
for (const msg of track.rawContent) {
if (msg.messageType === 'ElapsedTime') {
accContentTime += msg.value;
currentTime = track.offsetTime + accContentTime;
} else if (msg.messageType === 'NoteOn' || msg.messageType === 'NoteOff') {
const insertIndex = sortedTimestamp.findIndex(t => t >= currentTime);
globalMessages.splice(insertIndex + 1, 0, msg);
sortedTimestamp.splice(insertIndex + 1, 0, 0); // placeholder
}
}
}
const result = globalMessages.map(m => midiMessageToToken(m)).join('');
commonStore.setCompositionSubmittedPrompt(result);
setPrompt(result);
}}>
{t('Save to generation area')}
</Button>
</DialogTrigger>
</div>
);
});
export default AudiotrackEditor;

View File

@@ -16,8 +16,11 @@ import {
Attach16Regular,
Delete28Regular,
Dismiss16Regular,
Dismiss24Regular,
RecordStop28Regular,
Save28Regular
SaveRegular,
TextAlignJustify24Regular,
TextAlignJustifyRotate9024Regular
} from '@fluentui/react-icons';
import { CopyButton } from '../components/CopyButton';
import { ReadButton } from '../components/ReadButton';
@@ -26,9 +29,12 @@ import { WorkHeader } from '../components/WorkHeader';
import { DialogButton } from '../components/DialogButton';
import { OpenFileFolder, OpenOpenFileDialog, OpenSaveFileDialog } from '../../wailsjs/go/backend_golang/App';
import { absPathAsset, bytesToReadable, getServerRoot, toastWithButton } from '../utils';
import { PresetsButton } from './PresetsManager/PresetsButton';
import { useMediaQuery } from 'usehooks-ts';
import { botName, ConversationMessage, MessageType, userName, welcomeUuid } from '../types/chat';
import { Labeled } from '../components/Labeled';
import { ValuedSlider } from '../components/ValuedSlider';
import { PresetsButton } from './PresetsManager/PresetsButton';
import { webOpenOpenFileDialog } from '../utils/web-file-operations';
let chatSseControllers: {
[id: string]: AbortController
@@ -188,11 +194,125 @@ const ChatMessageItem: FC<{
</div>;
});
const SidePanel: FC = observer(() => {
const [t] = useTranslation();
const mq = useMediaQuery('(min-width: 640px)');
const params = commonStore.chatParams;
return <div
className={classnames(
'flex flex-col gap-1 h-full flex-shrink-0 transition-width duration-300 ease-in-out',
commonStore.sidePanelCollapsed ? 'w-0' : (mq ? 'w-64' : 'w-full'),
!commonStore.sidePanelCollapsed && 'ml-1')
}>
<div className="flex m-1">
<div className="grow" />
<PresetsButton tab="Chat" size="medium" shape="circular" appearance="subtle" />
<Button size="medium" shape="circular" appearance="subtle" icon={<Dismiss24Regular />}
onClick={() => commonStore.setSidePanelCollapsed(true)}
/>
</div>
<div className="flex flex-col gap-1 overflow-x-hidden overflow-y-auto p-1">
<Labeled flex breakline label={t('Max Response Token')}
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
content={
<ValuedSlider value={params.maxResponseToken} min={100} max={8100}
step={100}
input
onChange={(e, data) => {
commonStore.setChatParams({
maxResponseToken: data.value
});
}} />
} />
<Labeled flex breakline label={t('Temperature')}
desc={t('Sampling temperature, it\'s like giving alcohol to a model, the higher the stronger the randomness and creativity, while the lower, the more focused and deterministic it will be.')}
content={
<ValuedSlider value={params.temperature} min={0} max={2} step={0.1}
input
onChange={(e, data) => {
commonStore.setChatParams({
temperature: data.value
});
}} />
} />
<Labeled flex breakline label={t('Top_P')}
desc={t('Just like feeding sedatives to the model. Consider the results of the top n% probability mass, 0.1 considers the top 10%, with higher quality but more conservative, 1 considers all results, with lower quality but more diverse.')}
content={
<ValuedSlider value={params.topP} min={0} max={1} step={0.1} input
onChange={(e, data) => {
commonStore.setChatParams({
topP: data.value
});
}} />
} />
<Labeled flex breakline label={t('Presence Penalty')}
desc={t('Positive values penalize new tokens based on whether they appear in the text so far, increasing the model\'s likelihood to talk about new topics.')}
content={
<ValuedSlider value={params.presencePenalty} min={0} max={2}
step={0.1} input
onChange={(e, data) => {
commonStore.setChatParams({
presencePenalty: data.value
});
}} />
} />
<Labeled flex breakline label={t('Frequency Penalty')}
desc={t('Positive values penalize new tokens based on their existing frequency in the text so far, decreasing the model\'s likelihood to repeat the same line verbatim.')}
content={
<ValuedSlider value={params.frequencyPenalty} min={0} max={2}
step={0.1} input
onChange={(e, data) => {
commonStore.setChatParams({
frequencyPenalty: data.value
});
}} />
} />
</div>
<div className="grow" />
{/*<Button*/}
{/* icon={<FolderOpenVerticalRegular />}*/}
{/* onClick={() => {*/}
{/* }}>*/}
{/* {t('Load Conversation')}*/}
{/*</Button>*/}
<Button
icon={<SaveRegular />}
onClick={() => {
let savedContent: string = '';
const isWorldModel = commonStore.getCurrentModelConfig().modelParameters.modelName.toLowerCase().includes('world');
const user = isWorldModel ? 'User' : 'Bob';
const bot = isWorldModel ? 'Assistant' : 'Alice';
commonStore.conversationOrder.forEach((uuid) => {
if (uuid === welcomeUuid)
return;
const messageItem = commonStore.conversation[uuid];
if (messageItem.type !== MessageType.Error) {
savedContent += `${messageItem.sender === userName ? user : bot}: ${messageItem.content}\n\n`;
}
});
OpenSaveFileDialog('*.txt', 'conversation.txt', savedContent).then((path) => {
if (path)
toastWithButton(t('Conversation Saved'), t('Open'), () => {
OpenFileFolder(path, false);
});
}).catch(e => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
});
}}>
{t('Save Conversation')}
</Button>
</div>;
});
const ChatPanel: FC = observer(() => {
const { t } = useTranslation();
const bodyRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const mq = useMediaQuery('(min-width: 640px)');
if (commonStore.sidePanelCollapsed === 'auto')
commonStore.setSidePanelCollapsed(!mq);
const currentConfig = commonStore.getCurrentModelConfig();
const apiParams = currentConfig.apiParameters;
const port = apiParams.apiPort;
@@ -327,8 +447,10 @@ const ChatPanel: FC = observer(() => {
messages,
stream: true,
model: commonStore.settings.apiChatModelName, // 'gpt-3.5-turbo'
temperature: apiParams.temperature,
top_p: apiParams.topP,
temperature: commonStore.chatParams.temperature,
top_p: commonStore.chatParams.topP,
presence_penalty: commonStore.chatParams.presencePenalty,
frequency_penalty: commonStore.chatParams.frequencyPenalty,
user_name: commonStore.activePreset?.userName || undefined,
assistant_name: commonStore.activePreset?.assistantName || undefined,
presystem: commonStore.activePreset?.presystem && undefined
@@ -352,6 +474,8 @@ const ChatPanel: FC = observer(() => {
console.debug('json error', error);
return;
}
if (data.model)
commonStore.setLastModelName(data.model);
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
answer += data.choices[0]?.delta?.content || '';
commonStore.conversation[answerId!].content = answer;
@@ -389,185 +513,171 @@ const ChatPanel: FC = observer(() => {
}, []);
return (
<div className="flex flex-col w-full grow gap-4 pt-4 overflow-hidden">
<div ref={bodyRef} className="grow overflow-y-scroll overflow-x-hidden pr-2">
{commonStore.conversationOrder.map(uuid =>
<ChatMessageItem key={uuid} uuid={uuid} onSubmit={onSubmit} />
)}
</div>
<div className={classnames('flex items-end', mq ? 'gap-2' : '')}>
<PresetsButton tab="Chat" size={mq ? 'large' : 'small'} shape="circular" appearance="subtle" />
<DialogButton tooltip={t('Clear')}
icon={<Delete28Regular />}
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle" title={t('Clear')}
contentText={t('Are you sure you want to clear the conversation? It cannot be undone.')}
onConfirm={() => {
if (generating) {
for (const id in chatSseControllers) {
chatSseControllers[id].abort();
<div className="flex h-full grow pt-4 overflow-hidden">
<div className="relative flex flex-col w-full grow gap-4 overflow-hidden">
<Button className="absolute top-1 right-1" size="medium" shape="circular" appearance="subtle"
style={{ zIndex: 1 }}
icon={commonStore.sidePanelCollapsed ? <TextAlignJustify24Regular /> : <TextAlignJustifyRotate9024Regular />}
onClick={() => commonStore.setSidePanelCollapsed(!commonStore.sidePanelCollapsed)} />
<div ref={bodyRef} className="grow overflow-y-scroll overflow-x-hidden pr-2">
{commonStore.conversationOrder.map(uuid =>
<ChatMessageItem key={uuid} uuid={uuid} onSubmit={onSubmit} />
)}
</div>
<div className={classnames('flex items-end', mq ? 'gap-2' : '')}>
<DialogButton tooltip={t('Clear')}
icon={<Delete28Regular />}
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle" title={t('Clear')}
contentText={t('Are you sure you want to clear the conversation? It cannot be undone.')}
onConfirm={() => {
if (generating) {
for (const id in chatSseControllers) {
chatSseControllers[id].abort();
}
chatSseControllers = {};
}
chatSseControllers = {};
}
commonStore.setConversation({});
commonStore.setConversationOrder([]);
}} />
<div className="relative flex grow">
<Textarea
ref={inputRef}
style={{ minWidth: 0 }}
className="grow"
resize="vertical"
placeholder={t('Type your message here')!}
value={commonStore.currentInput}
onChange={(e) => commonStore.setCurrentInput(e.target.value)}
onKeyDown={handleKeyDownOrClick}
/>
<div className="absolute right-2 bottom-2">
{!commonStore.currentTempAttachment ?
<ToolTipButton
desc={commonStore.attachmentUploading ?
t('Uploading Attachment') :
t('Add An Attachment (Accepts pdf, txt)')}
icon={commonStore.attachmentUploading ?
<ArrowClockwise16Regular className="animate-spin" />
: <Attach16Regular />}
size="small" shape="circular" appearance="secondary"
onClick={() => {
if (commonStore.status.status === ModelStatus.Offline && !commonStore.settings.apiUrl && commonStore.platform !== 'web') {
toast(t('Please click the button in the top right corner to start the model'), { type: 'warning' });
return;
}
if (commonStore.attachmentUploading)
return;
OpenOpenFileDialog('*.txt;*.pdf').then(async filePath => {
if (!filePath)
commonStore.setConversation({});
commonStore.setConversationOrder([]);
}} />
<div className="relative flex grow">
<Textarea
ref={inputRef}
style={{ minWidth: 0 }}
className="grow"
resize="vertical"
placeholder={t('Type your message here')!}
value={commonStore.currentInput}
onChange={(e) => commonStore.setCurrentInput(e.target.value)}
onKeyDown={handleKeyDownOrClick}
/>
<div className="absolute right-2 bottom-2">
{!commonStore.currentTempAttachment ?
<ToolTipButton
desc={commonStore.attachmentUploading ?
t('Uploading Attachment') :
t('Add An Attachment (Accepts pdf, txt)')}
icon={commonStore.attachmentUploading ?
<ArrowClockwise16Regular className="animate-spin" />
: <Attach16Regular />}
size="small" shape="circular" appearance="secondary"
onClick={() => {
if (commonStore.attachmentUploading)
return;
commonStore.setAttachmentUploading(true);
let blob: Blob;
let attachmentName: string | undefined;
let attachmentContent: string | undefined;
if (commonStore.platform === 'web') {
const webReturn = filePath as any;
blob = webReturn.blob;
attachmentName = blob.name;
attachmentContent = webReturn.content;
} else {
// Both are slow. Communication between frontend and backend is slow. Use AssetServer Handler to read the file.
// const blob = new Blob([atob(info.content as unknown as string)]); // await fetch(`data:application/octet-stream;base64,${info.content}`).then(r => r.blob());
blob = await fetch(absPathAsset(filePath)).then(r => r.blob());
attachmentName = filePath.split(/[\\/]/).pop();
}
if (attachmentContent) {
commonStore.setCurrentTempAttachment(
{
name: attachmentName!,
size: blob.size,
content: attachmentContent
});
commonStore.setAttachmentUploading(false);
} else {
const urlPath = `/file-to-text?file_name=${attachmentName}`;
const bodyForm = new FormData();
bodyForm.append('file_data', blob, attachmentName);
fetch(getServerRoot(port) + urlPath, {
method: 'POST',
body: bodyForm
}).then(async r => {
if (r.status === 200) {
const pages = (await r.json()).pages as any[];
if (pages.length === 1)
attachmentContent = pages[0].page_content;
else
attachmentContent = pages.map((p, i) => `Page ${i + 1}:\n${p.page_content}`).join('\n\n');
commonStore.setCurrentTempAttachment(
{
name: attachmentName!,
size: blob.size,
content: attachmentContent!
});
} else {
toast(r.statusText + '\n' + (await r.text()), {
type: 'error'
const filterPattern = '*.txt;*.pdf';
const setUploading = () => commonStore.setAttachmentUploading(true);
// actually, status of web platform is always Offline
if (commonStore.platform === 'web' || commonStore.status.status === ModelStatus.Offline || currentConfig.modelParameters.device === 'WebGPU') {
webOpenOpenFileDialog({ filterPattern, fnStartLoading: setUploading }).then(webReturn => {
if (webReturn.content)
commonStore.setCurrentTempAttachment(
{
name: webReturn.blob.name,
size: webReturn.blob.size,
content: webReturn.content
});
}
commonStore.setAttachmentUploading(false);
}
).catch(e => {
else
toast(t('File is empty'), {
type: 'info',
autoClose: 1000
});
}).catch(e => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
}).finally(() => {
commonStore.setAttachmentUploading(false);
});
} else {
OpenOpenFileDialog(filterPattern).then(async filePath => {
if (!filePath)
return;
setUploading();
// Both are slow. Communication between frontend and backend is slow. Use AssetServer Handler to read the file.
// const blob = new Blob([atob(info.content as unknown as string)]); // await fetch(`data:application/octet-stream;base64,${info.content}`).then(r => r.blob());
const blob = await fetch(absPathAsset(filePath)).then(r => r.blob());
const attachmentName = filePath.split(/[\\/]/).pop();
const urlPath = `/file-to-text?file_name=${attachmentName}`;
const bodyForm = new FormData();
bodyForm.append('file_data', blob, attachmentName);
fetch(getServerRoot(port) + urlPath, {
method: 'POST',
body: bodyForm
}).then(async r => {
if (r.status === 200) {
const pages = (await r.json()).pages as any[];
let attachmentContent: string;
if (pages.length === 1)
attachmentContent = pages[0].page_content;
else
attachmentContent = pages.map((p, i) => `Page ${i + 1}:\n${p.page_content}`).join('\n\n');
if (attachmentContent)
commonStore.setCurrentTempAttachment(
{
name: attachmentName!,
size: blob.size,
content: attachmentContent!
});
else
toast(t('File is empty'), {
type: 'info',
autoClose: 1000
});
} else {
toast(r.statusText + '\n' + (await r.text()), {
type: 'error'
});
}
}
).catch(e => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
}).finally(() => {
commonStore.setAttachmentUploading(false);
});
}).catch(e => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
});
}
}).catch(e => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
});
}}
/> :
<div>
<ToolTipButton
text={
commonStore.currentTempAttachment.name.replace(
new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...')
}
desc={`${commonStore.currentTempAttachment.name} (${bytesToReadable(commonStore.currentTempAttachment.size)})`}
size="small" shape="circular" appearance="secondary" />
<ToolTipButton desc={t('Remove Attachment')}
icon={<Dismiss16Regular />}
size="small" shape="circular" appearance="subtle"
onClick={() => {
commonStore.setCurrentTempAttachment(null);
}} />
</div>
}
}}
/> :
<div>
<ToolTipButton
text={
commonStore.currentTempAttachment.name.replace(
new RegExp('(^[^\\.]{5})[^\\.]+'), '$1...')
}
desc={`${commonStore.currentTempAttachment.name} (${bytesToReadable(commonStore.currentTempAttachment.size)})`}
size="small" shape="circular" appearance="secondary" />
<ToolTipButton desc={t('Remove Attachment')}
icon={<Dismiss16Regular />}
size="small" shape="circular" appearance="subtle"
onClick={() => {
commonStore.setCurrentTempAttachment(null);
}} />
</div>
}
</div>
</div>
<ToolTipButton desc={generating ? t('Stop') : t('Send')}
icon={generating ? <RecordStop28Regular /> : <ArrowCircleUp28Regular />}
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle"
onClick={(e) => {
if (generating) {
for (const id in chatSseControllers) {
chatSseControllers[id].abort();
commonStore.conversation[id].type = MessageType.Error;
commonStore.conversation[id].done = true;
}
chatSseControllers = {};
commonStore.setConversation(commonStore.conversation);
commonStore.setConversationOrder([...commonStore.conversationOrder]);
} else {
handleKeyDownOrClick(e);
}
}} />
</div>
<ToolTipButton desc={generating ? t('Stop') : t('Send')}
icon={generating ? <RecordStop28Regular /> : <ArrowCircleUp28Regular />}
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle"
onClick={(e) => {
if (generating) {
for (const id in chatSseControllers) {
chatSseControllers[id].abort();
commonStore.conversation[id].type = MessageType.Error;
commonStore.conversation[id].done = true;
}
chatSseControllers = {};
commonStore.setConversation(commonStore.conversation);
commonStore.setConversationOrder([...commonStore.conversationOrder]);
} else {
handleKeyDownOrClick(e);
}
}} />
<ToolTipButton desc={t('Save')}
icon={<Save28Regular />}
size={mq ? 'large' : 'small'} shape="circular" appearance="subtle"
onClick={() => {
let savedContent: string = '';
const isWorldModel = commonStore.getCurrentModelConfig().modelParameters.modelName.toLowerCase().includes('world');
const user = isWorldModel ? 'User' : 'Bob';
const bot = isWorldModel ? 'Assistant' : 'Alice';
commonStore.conversationOrder.forEach((uuid) => {
if (uuid === welcomeUuid)
return;
const messageItem = commonStore.conversation[uuid];
if (messageItem.type !== MessageType.Error) {
savedContent += `${messageItem.sender === userName ? user : bot}: ${messageItem.content}\n\n`;
}
});
OpenSaveFileDialog('*.txt', 'conversation.txt', savedContent).then((path) => {
if (path)
toastWithButton(t('Conversation Saved'), t('Open'), () => {
OpenFileFolder(path, false);
});
}).catch(e => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
});
}} />
</div>
<SidePanel />
</div>
);
});

View File

@@ -29,8 +29,10 @@ const CompletionPanel: FC = observer(() => {
};
useEffect(() => {
if (inputRef.current)
if (inputRef.current) {
inputRef.current.style.height = '100%';
inputRef.current.style.maxHeight = '100%';
}
scrollToBottom();
}, []);
@@ -112,6 +114,8 @@ const CompletionPanel: FC = observer(() => {
console.debug('json error', error);
return;
}
if (data.model)
commonStore.setLastModelName(data.model);
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
answer += data.choices[0]?.text || data.choices[0]?.delta?.content || '';
setPrompt(prompt + answer.replace(/\s+$/, '') + params.injectEnd.replaceAll('\\n', '\n'));
@@ -173,7 +177,7 @@ const CompletionPanel: FC = observer(() => {
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
content={
<ValuedSlider value={params.maxResponseToken} min={100} max={8100}
step={400}
step={100}
input
onChange={(e, data) => {
setParams({

View File

@@ -2,7 +2,7 @@ import 'html-midi-player';
import React, { FC, useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { WorkHeader } from '../components/WorkHeader';
import { Button, Checkbox, Textarea } from '@fluentui/react-components';
import { Button, Checkbox, Dropdown, Option, Textarea } from '@fluentui/react-components';
import { Labeled } from '../components/Labeled';
import { ValuedSlider } from '../components/ValuedSlider';
import { useTranslation } from 'react-i18next';
@@ -16,10 +16,17 @@ import { PlayerElement, VisualizerElement } from 'html-midi-player';
import * as mm from '@magenta/music/esm/core.js';
import { NoteSequence } from '@magenta/music/esm/protobuf.js';
import { defaultCompositionPrompt } from './defaultConfigs';
import { FileExists, OpenFileFolder, OpenSaveFileDialogBytes } from '../../wailsjs/go/backend_golang/App';
import { getServerRoot, toastWithButton } from '../utils';
import {
CloseMidiPort,
FileExists,
OpenFileFolder,
OpenMidiPort,
OpenSaveFileDialogBytes
} from '../../wailsjs/go/backend_golang/App';
import { getServerRoot, getSoundFont, toastWithButton } from '../utils';
import { CompositionParams } from '../types/composition';
import { useMediaQuery } from 'usehooks-ts';
import { AudiotrackButton } from './AudiotrackManager/AudiotrackButton';
let compositionSseController: AbortController | null = null;
@@ -64,26 +71,16 @@ const CompositionPanel: FC = observer(() => {
};
const setSoundFont = async () => {
let soundUrl: string;
if (commonStore.compositionParams.useLocalSoundFont)
soundUrl = 'assets/sound-font';
else
soundUrl = !commonStore.settings.giteeUpdatesSource ?
`https://raw.githubusercontent.com/josStorer/sgm_plus/master` :
`https://gitee.com/josc146/sgm_plus/raw/master`;
const fallbackUrl = 'https://cdn.jsdelivr.net/gh/josstorer/sgm_plus';
await fetch(soundUrl + '/soundfont.json').then(r => {
if (!r.ok)
soundUrl = fallbackUrl;
}).catch(() => soundUrl = fallbackUrl);
if (playerRef.current) {
playerRef.current.soundFont = soundUrl;
playerRef.current.soundFont = await getSoundFont();
}
};
useEffect(() => {
if (inputRef.current)
if (inputRef.current) {
inputRef.current.style.height = '100%';
inputRef.current.style.maxHeight = '100%';
}
scrollToBottom();
if (playerRef.current && visualizerRef.current) {
@@ -119,7 +116,9 @@ const CompositionPanel: FC = observer(() => {
});
updateNs(ns);
if (autoPlay) {
playerRef.current?.start();
setTimeout(() => {
playerRef.current?.start();
});
}
});
});
@@ -167,6 +166,8 @@ const CompositionPanel: FC = observer(() => {
console.debug('json error', error);
return;
}
if (data.model)
commonStore.setLastModelName(data.model);
if (data.choices && Array.isArray(data.choices) && data.choices.length > 0) {
answer += data.choices[0]?.text || data.choices[0]?.delta?.content || '';
setPrompt(prompt + answer.replace(/\s+$/, ''));
@@ -263,6 +264,36 @@ const CompositionPanel: FC = observer(() => {
autoPlay: data.checked as boolean
});
}} />
{commonStore.platform !== 'web' &&
<Labeled flex breakline label={t('MIDI Input')}
desc={t('Select the MIDI input device to be used.')}
content={
<div className="flex flex-col gap-1">
<Dropdown style={{ minWidth: 0 }}
value={commonStore.activeMidiDeviceIndex === -1 ? t('None')! : commonStore.midiPorts[commonStore.activeMidiDeviceIndex].name}
selectedOptions={[commonStore.activeMidiDeviceIndex.toString()]}
onOptionSelect={(_, data) => {
if (data.optionValue) {
const index = Number(data.optionValue);
let action = (index === -1)
? () => CloseMidiPort()
: () => OpenMidiPort(index);
action().then(() => {
commonStore.setActiveMidiDeviceIndex(index);
}).catch((e) => {
toast(t('Error') + ' - ' + (e.message || e), { type: 'error', autoClose: 2500 });
});
}
}}>
<Option value={'-1'}>{t('None')!}</Option>
{commonStore.midiPorts.map((p, i) =>
<Option key={i} value={i.toString()}>{p.name}</Option>)
}
</Dropdown>
<AudiotrackButton setPrompt={setPrompt} />
</div>
} />
}
</div>
<div className="flex justify-between gap-2">
<ToolTipButton desc={t('Regenerate')} icon={<ArrowSync20Regular />} onClick={() => {

View File

@@ -26,7 +26,7 @@ import { Page } from '../components/Page';
import { useNavigate } from 'react-router';
import { RunButton } from '../components/RunButton';
import { updateConfig } from '../apis';
import { ConvertModel, ConvertSafetensors, FileExists, GetPyError } from '../../wailsjs/go/backend_golang/App';
import { ConvertModel, FileExists, GetPyError } from '../../wailsjs/go/backend_golang/App';
import { checkDependencies, getStrategy } from '../utils';
import { useTranslation } from 'react-i18next';
import { WindowShow } from '../../wailsjs/runtime';
@@ -35,6 +35,7 @@ import strategyZhImg from '../assets/images/strategy_zh.jpg';
import { ResetConfigsButton } from '../components/ResetConfigsButton';
import { useMediaQuery } from 'usehooks-ts';
import { ApiParameters, Device, ModelParameters, Precision } from '../types/configs';
import { convertToSt } from '../utils/convert-to-st';
const Configs: FC = observer(() => {
const { t } = useTranslation();
@@ -150,7 +151,7 @@ const Configs: FC = observer(() => {
desc={t('By default, the maximum number of tokens that can be answered in a single response, it can be changed by the user by specifying API parameters.')}
content={
<ValuedSlider value={selectedConfig.apiParameters.maxResponseToken} min={100} max={8100}
step={400}
step={100}
input
onChange={(e, data) => {
setSelectedConfigApiParams({
@@ -272,41 +273,7 @@ const Configs: FC = observer(() => {
}} /> :
<ToolTipButton text={t('Convert To Safe Tensors Format')}
desc=""
onClick={async () => {
if (commonStore.platform === 'darwin') {
toast(t('MacOS is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_safetensors.py)', { type: 'info' });
return;
} else if (commonStore.platform === 'linux') {
toast(t('Linux is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_safetensors.py)', { type: 'info' });
return;
}
const ok = await checkDependencies(navigate);
if (!ok)
return;
const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}`;
if (await FileExists(modelPath)) {
toast(t('Start Converting'), { autoClose: 1000, type: 'info' });
const newModelPath = modelPath.replace(/\.pth$/, '.st');
ConvertSafetensors(commonStore.settings.customPythonPath, modelPath, newModelPath).then(async () => {
if (!await FileExists(newModelPath)) {
toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' });
} else {
toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' });
}
}).catch(e => {
const errMsg = e.message || e;
if (errMsg.includes('path contains space'))
toast(`${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' });
else
toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' });
});
setTimeout(WindowShow, 1000);
} else {
toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' });
}
}} />
onClick={() => convertToSt(navigate, selectedConfig)} />
}
<Labeled label={t('Strategy')} content={
<Dropdown style={{ minWidth: 0 }} className="grow" value={t(selectedConfig.modelParameters.device)!}
@@ -328,7 +295,7 @@ const Configs: FC = observer(() => {
} />
{
selectedConfig.modelParameters.device !== 'Custom' && <Labeled label={t('Precision')}
desc={t('int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality, and fp32 has the best quality.')}
desc={t('int8 uses less VRAM, but has slightly lower quality. fp16 has higher quality.')}
content={
<Dropdown style={{ minWidth: 0 }} className="grow"
value={selectedConfig.modelParameters.precision}
@@ -340,8 +307,10 @@ const Configs: FC = observer(() => {
});
}
}}>
<Option>fp16</Option>
{selectedConfig.modelParameters.device !== 'CPU' && selectedConfig.modelParameters.device !== 'MPS' &&
<Option>fp16</Option>}
<Option>int8</Option>
{selectedConfig.modelParameters.device === 'WebGPU' && <Option>nf4</Option>}
{selectedConfig.modelParameters.device !== 'WebGPU' && <Option>fp32</Option>}
</Dropdown>
} />

View File

@@ -1,5 +1,6 @@
import React, { FC } from 'react';
import {
Checkbox,
createTableColumn,
DataGrid,
DataGridBody,
@@ -19,7 +20,7 @@ import commonStore from '../stores/commonStore';
import { BrowserOpenURL } from '../../wailsjs/runtime';
import { AddToDownloadList, OpenFileFolder } from '../../wailsjs/go/backend_golang/App';
import { Page } from '../components/Page';
import { bytesToGb, refreshModels, saveConfigs, toastWithButton } from '../utils';
import { bytesToGb, getHfDownloadUrl, refreshModels, saveConfigs, toastWithButton } from '../utils';
import { useTranslation } from 'react-i18next';
import { useNavigate } from 'react-router';
import { ModelSourceItem } from '../types/models';
@@ -139,7 +140,7 @@ const columns: TableColumnDefinition<ModelSourceItem>[] = [
navigate({ pathname: '/downloads' });
},
{ autoClose: 3000 });
AddToDownloadList(`${commonStore.settings.customModelsPath}/${item.name}`, item.downloadUrl!);
AddToDownloadList(`${commonStore.settings.customModelsPath}/${item.name}`, getHfDownloadUrl(item.downloadUrl!));
}} />}
{item.url && <ToolTipButton desc={t('Open Url')} icon={<Open20Regular />} onClick={() => {
BrowserOpenURL(item.url!);
@@ -160,10 +161,21 @@ const Models: FC = observer(() => {
<div className="flex flex-col gap-1">
<div className="flex justify-between items-center">
<Text weight="medium">{t('Model Source Manifest List')}</Text>
<ToolTipButton desc={t('Refresh')} icon={<ArrowClockwise20Regular />} onClick={() => {
refreshModels(false);
saveConfigs();
}} />
<div className="flex">
{commonStore.settings.language === 'zh' &&
<Checkbox className="select-none"
size="large" label={t('Use Hugging Face Mirror')}
checked={commonStore.settings.useHfMirror}
onChange={(_, data) => {
commonStore.setSettings({
useHfMirror: data.checked as boolean
});
}} />}
<ToolTipButton desc={t('Refresh')} icon={<ArrowClockwise20Regular />} onClick={() => {
refreshModels(false);
saveConfigs();
}} />
</div>
</div>
<Text size={100}>
{t('Provide JSON file URLs for the models manifest. Separate URLs with semicolons. The "models" field in JSON files will be parsed into the following table.')}

View File

@@ -108,7 +108,8 @@ const MessagesEditor: FC = observer(() => {
style={{ borderTopRightRadius: 0, borderBottomRightRadius: 0 }}>
<ReOrderDotsVertical20Regular />
</Card>
<Dropdown style={{ minWidth: 0, borderRadius: 0 }} listbox={{ style: { minWidth: 0 } }}
<Dropdown style={{ minWidth: 0, borderRadius: 0 }}
listbox={{ style: { minWidth: 'fit-content' } }}
value={t(item.role)!}
selectedOptions={[item.role]}
onOptionSelect={(_, data) => {

View File

@@ -23,7 +23,7 @@ export const GeneralSettings: FC = observer(() => {
return <div className="flex flex-col gap-2">
<Labeled label={t('Language')} flex spaceBetween content={
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 'fit-content' } }}
value={Languages[commonStore.settings.language]}
selectedOptions={[commonStore.settings.language]}
onOptionSelect={(_, data) => {
@@ -43,7 +43,7 @@ export const GeneralSettings: FC = observer(() => {
{
commonStore.platform === 'windows' &&
<Labeled label={t('DPI Scaling')} flex spaceBetween content={
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 0 } }}
<Dropdown style={{ minWidth: 0 }} listbox={{ style: { minWidth: 'fit-content' } }}
value={commonStore.settings.dpiScaling + '%'}
selectedOptions={[commonStore.settings.dpiScaling.toString()]}
onOptionSelect={(_, data) => {
@@ -89,7 +89,7 @@ export const AdvancedGeneralSettings: FC = observer(() => {
apiUrl: data.value
});
}} />
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 0 } }}
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 'fit-content' } }}
value="..." selectedOptions={[]} expandIcon={null}
onOptionSelect={(_, data) => {
commonStore.setSettings({
@@ -102,11 +102,21 @@ export const AdvancedGeneralSettings: FC = observer(() => {
});
if (commonStore.settings.apiCompletionModelName === 'rwkv')
commonStore.setSettings({
apiCompletionModelName: 'text-davinci-003'
apiCompletionModelName: 'gpt-3.5-turbo-instruct'
});
} else if (data.optionText === 'RWKV') {
if (commonStore.settings.apiChatModelName === 'gpt-3.5-turbo')
commonStore.setSettings({
apiChatModelName: 'rwkv'
});
if (commonStore.settings.apiCompletionModelName === 'gpt-3.5-turbo-instruct' || commonStore.settings.apiCompletionModelName === 'text-davinci-003')
commonStore.setSettings({
apiCompletionModelName: 'rwkv'
});
}
}}>
<Option value="">{t('Localhost')!}</Option>
<Option value="https://rwkv.ai-creator.net/chntuned">RWKV</Option>
<Option value="https://api.openai.com">OpenAI</Option>
</Dropdown>
</div>
@@ -130,7 +140,7 @@ export const AdvancedGeneralSettings: FC = observer(() => {
apiChatModelName: data.value
});
}} />
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 0 } }}
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 'fit-content' } }}
value="..." selectedOptions={[]} expandIcon={null}
onOptionSelect={(_, data) => {
if (data.optionValue) {
@@ -140,7 +150,7 @@ export const AdvancedGeneralSettings: FC = observer(() => {
}
}}>
{
['rwkv', 'gpt-4', 'gpt-4-0613', 'gpt-4-32k', 'gpt-4-32k-0613', 'gpt-3.5-turbo', 'gpt-3.5-turbo-0613', 'gpt-3.5-turbo-16k', 'gpt-3.5-turbo-16k-0613']
['rwkv', 'gpt-4-1106-preview', 'gpt-4', 'gpt-4-32k', 'gpt-4-0613', 'gpt-4-32k-0613', 'gpt-3.5-turbo-1106', 'gpt-3.5-turbo', 'gpt-3.5-turbo-16k']
.map((v, i) =>
<Option key={i} value={v}>{v}</Option>
)
@@ -158,7 +168,7 @@ export const AdvancedGeneralSettings: FC = observer(() => {
apiCompletionModelName: data.value
});
}} />
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 0 } }}
<Dropdown style={{ minWidth: '33px' }} listbox={{ style: { minWidth: 'fit-content', minHeight: 0 } }}
value="..." selectedOptions={[]} expandIcon={null}
onOptionSelect={(_, data) => {
if (data.optionValue) {
@@ -168,7 +178,7 @@ export const AdvancedGeneralSettings: FC = observer(() => {
}
}}>
{
['rwkv', 'text-davinci-003', 'text-davinci-002', 'text-curie-001', 'text-babbage-001', 'text-ada-001']
['rwkv', 'gpt-3.5-turbo-instruct', 'text-davinci-003', 'text-davinci-002', 'code-davinci-002', 'text-curie-001', 'text-babbage-001', 'text-ada-001']
.map((v, i) =>
<Option key={i} value={v}>{v}</Option>
)

View File

@@ -129,11 +129,12 @@ const errorsMap = Object.entries({
'python3 ./finetune/lora/train.py': 'Memory is not enough, try to increase the virtual memory (Swap of WSL) or use a smaller base model.',
'cuda out of memory': 'VRAM is not enough',
'valueerror: high <= 0': 'Training data is not enough, reduce context length or add more data for training',
'+= \'+ptx\'': 'You are using WSL 1 for training, please upgrade to WSL 2. e.g. Run "wsl --set-version Ubuntu-22.04 2"',
'+= \'+ptx\'': 'Can not find an Nvidia GPU. Perhaps the gpu driver of windows is too old, or you are using WSL 1 for training, please upgrade to WSL 2. e.g. Run "wsl --set-version Ubuntu-22.04 2"',
'size mismatch for blocks': 'Size mismatch for blocks. You are attempting to continue training from the LoRA model, but it does not match the base model. Please set LoRA model to None.',
'cuda_home environment variable is not set': 'Matched CUDA is not installed',
'unsupported gpu architecture': 'Matched CUDA is not installed',
'error building extension \'fused_adam\'': 'Matched CUDA is not installed'
'error building extension \'fused_adam\'': 'Matched CUDA is not installed',
'modelinfo is invalid': 'Failed to load model, try to increase the virtual memory (Swap of WSL) or use a smaller base model.'
});
export const wslHandler = (data: string) => {

View File

@@ -111,7 +111,7 @@ export const defaultPresets: CompletionPreset[] = [{
export const defaultModelConfigsMac: ModelConfig[] = [
{
name: 'MAC-0.1B-World',
name: 'GPU-2G-1B5-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
@@ -121,16 +121,15 @@ export const defaultModelConfigsMac: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-0.1B-v1-20230520-ctx4096.pth',
device: 'MPS',
precision: 'fp32',
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41,
customStrategy: 'mps fp32'
maxStoredLayers: 41
}
},
{
name: 'MAC-0.4B-World',
name: 'GPU-4G-3B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
@@ -140,12 +139,101 @@ export const defaultModelConfigsMac: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-0.4B-v1-20230529-ctx4096.pth',
device: 'MPS',
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'GPU-4G-3B-CN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-CHNtuned-3B-v1-20230625-ctx4096.pth',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'GPU-7G-7B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-7B-v1-20230626-ctx4096.pth',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'GPU-7G-7B-CN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-CHNtuned-7B-v1-20230709-ctx4096.pth',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-120M-Music',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.8,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-5-MIDI-120M-v1-20230728-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41,
customStrategy: 'mps fp32'
maxStoredLayers: 41
}
},
{
name: 'CPU-560M-Music',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.8,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-5-MIDI-560M-v1-20230902-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
@@ -159,26 +247,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
device: 'MPS',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41,
customStrategy: 'mps fp32'
}
},
{
name: 'MAC-1B5-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
device: 'MPS',
precision: 'fp32',
storedLayers: 41,
@@ -197,26 +266,7 @@ export const defaultModelConfigsMac: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
device: 'MPS',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41,
customStrategy: 'mps fp32'
}
},
{
name: 'MAC-3B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
device: 'MPS',
precision: 'fp32',
storedLayers: 41,
@@ -261,190 +311,29 @@ export const defaultModelConfigsMac: ModelConfig[] = [
maxStoredLayers: 41,
customStrategy: 'mps fp32'
}
},
{
name: 'CPU-120M-Music',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.8,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-120M-v1-20230714-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-560M-Music',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.8,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-560M-v1-20230717-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-6G-1B5-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-6G-1B5-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-12G-3B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-12G-3B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-12G-3B-CN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-CHNtuned-3B-v1-20230625-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-28G-7B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-7B-v1-20230626-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-28G-7B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-28G-7B-CN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-CHNtuned-7B-v1-20230709-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
}
];
export const defaultModelConfigs: ModelConfig[] = [
{
name: 'GPU-2G-1B5-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-2G-3B-World',
apiParameters: {
@@ -456,7 +345,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 6,
@@ -464,61 +353,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-2G-0.1B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-0.1B-v1-20230520-ctx4096.pth',
device: 'CUDA',
precision: 'fp32', // using fp16 will disable state cache (->)
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'GPU-2G-1B5-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 4,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-4G-0.4B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-0.4B-v1-20230529-ctx4096.pth',
device: 'CUDA',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'GPU-4G-1B5-World',
apiParameters: {
@@ -530,27 +364,9 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
device: 'CUDA',
precision: 'fp32',
storedLayers: 8,
maxStoredLayers: 41
}
},
{
name: 'GPU-4G-1B5-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
device: 'CUDA',
precision: 'int8',
precision: 'fp16',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
@@ -567,26 +383,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 24,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-4G-3B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 24,
@@ -632,25 +429,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-4G-7B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 8,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-4G-7B-CN',
apiParameters: {
@@ -670,25 +448,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-6G-1B5-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
device: 'CUDA',
precision: 'fp16',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-6G-3B-World',
apiParameters: {
@@ -700,26 +459,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-6G-3B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 41,
@@ -765,25 +505,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-6G-7B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 18,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-6G-7B-CN',
apiParameters: {
@@ -803,24 +524,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-8G-1B5-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
device: 'CUDA',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'GPU-8G-3B-World',
apiParameters: {
@@ -832,26 +535,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
device: 'CUDA',
precision: 'fp16',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-8G-3B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
device: 'CUDA',
precision: 'fp16',
storedLayers: 41,
@@ -897,25 +581,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-8G-7B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 27,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-8G-7B-CN',
apiParameters: {
@@ -954,25 +619,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-10G-7B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-10G-7B-CN',
apiParameters: {
@@ -992,25 +638,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-12G-14B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 24,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-16G-7B-World',
apiParameters: {
@@ -1030,25 +657,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-16G-7B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
device: 'CUDA',
precision: 'fp16',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-16G-7B-CN',
apiParameters: {
@@ -1068,63 +676,6 @@ export const defaultModelConfigs: ModelConfig[] = [
useCustomCuda: true
}
},
{
name: 'GPU-16G-14B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 37,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-18G-14B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
device: 'CUDA',
precision: 'int8',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'GPU-32G-14B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-14B-v12-Eng98%-Other2%-20230523-ctx8192.pth',
device: 'CUDA',
precision: 'fp16',
storedLayers: 41,
maxStoredLayers: 41,
useCustomCuda: true
}
},
{
name: 'CPU-120M-Music',
apiParameters: {
@@ -1136,7 +687,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-120M-v1-20230714-ctx4096.pth',
modelName: 'RWKV-5-MIDI-120M-v1-20230728-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
@@ -1154,7 +705,7 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-MIDI-560M-v1-20230717-ctx4096.pth',
modelName: 'RWKV-5-MIDI-560M-v1-20230902-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
@@ -1162,7 +713,7 @@ export const defaultModelConfigs: ModelConfig[] = [
}
},
{
name: 'CPU-6G-1B5-World',
name: 'AnyGPU-2G-1B5-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
@@ -1172,15 +723,15 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-1.5B-v1-fixed-20230612-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
modelName: 'RWKV-5-World-1B5-v2-20231025-ctx4096.pth',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-6G-1B5-EN',
name: 'AnyGPU-4G-3B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
@@ -1190,51 +741,15 @@ export const defaultModelConfigs: ModelConfig[] = [
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-1B5-v12-Eng98%-Other2%-20230520-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
modelName: 'RWKV-5-World-3B-v2-20231118-ctx16k.pth',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-12G-3B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-World-3B-v1-20230619-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-12G-3B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-3B-v12-Eng98%-Other2%-20230520-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-12G-3B-CN',
name: 'AnyGPU-4G-3B-CN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
@@ -1245,14 +760,14 @@ export const defaultModelConfigs: ModelConfig[] = [
},
modelParameters: {
modelName: 'RWKV-4-World-CHNtuned-3B-v1-20230625-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-28G-7B-World',
name: 'AnyGPU-7G-7B-World',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
@@ -1263,32 +778,14 @@ export const defaultModelConfigs: ModelConfig[] = [
},
modelParameters: {
modelName: 'RWKV-4-World-7B-v1-20230626-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-28G-7B-EN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
temperature: 1.0,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
},
modelParameters: {
modelName: 'RWKV-4-Raven-7B-v12-Eng98%-Other2%-20230521-ctx8192.pth',
device: 'CPU',
precision: 'fp32',
storedLayers: 41,
maxStoredLayers: 41
}
},
{
name: 'CPU-28G-7B-CN',
name: 'AnyGPU-7G-7B-CN',
apiParameters: {
apiPort: 8000,
maxResponseToken: 4100,
@@ -1299,8 +796,8 @@ export const defaultModelConfigs: ModelConfig[] = [
},
modelParameters: {
modelName: 'RWKV-4-World-CHNtuned-7B-v1-20230709-ctx4096.pth',
device: 'CPU',
precision: 'fp32',
device: 'WebGPU',
precision: 'nf4',
storedLayers: 41,
maxStoredLayers: 41
}

View File

@@ -1,5 +1,5 @@
import commonStore, { MonitorData, Platform } from './stores/commonStore';
import { GetPlatform, ListDirFiles, ReadJson } from '../wailsjs/go/backend_golang/App';
import { FileExists, GetPlatform, ListDirFiles, ReadJson } from '../wailsjs/go/backend_golang/App';
import { Cache, checkUpdate, downloadProgramFiles, LocalConfig, refreshLocalModels, refreshModels } from './utils';
import { getStatus } from './apis';
import { EventsOn, WindowSetTitle } from '../wailsjs/runtime';
@@ -7,6 +7,8 @@ import manifest from '../../manifest.json';
import { defaultModelConfigs, defaultModelConfigsMac } from './pages/defaultConfigs';
import { t } from 'i18next';
import { Preset } from './types/presets';
import { toast } from 'react-toastify';
import { MidiMessage, MidiPort } from './types/composition';
export async function startup() {
initPresets();
@@ -26,6 +28,7 @@ export async function startup() {
initLocalModelsNotify();
initLoraModels();
initHardwareMonitor();
initMidi();
}
await initConfig();
@@ -134,3 +137,22 @@ async function initHardwareMonitor() {
}
});
}
async function initMidi() {
EventsOn('midiError', (data: string) => {
if (commonStore.platform === 'windows')
toast('MIDI Error: ' + data, { type: 'error' });
});
EventsOn('midiPorts', (data: MidiPort[]) => {
commonStore.setMidiPorts(data);
});
EventsOn('midiMessage', async (data: MidiMessage) => {
await (await import('./pages/AudiotrackManager/AudiotrackEditor')).midiMessageHandler(data);
});
if (await FileExists('assets/sound-font/accordion/instrument.json')) {
commonStore.setCompositionParams({
...commonStore.compositionParams,
useLocalSoundFont: true
});
}
}

View File

@@ -7,9 +7,16 @@ import { defaultCompositionPrompt, defaultModelConfigs, defaultModelConfigsMac }
import { ChartData } from 'chart.js';
import { Preset } from '../types/presets';
import { AboutContent } from '../types/about';
import { Attachment, Conversation } from '../types/chat';
import { Attachment, ChatParams, Conversation } from '../types/chat';
import { CompletionPreset } from '../types/completion';
import { CompositionParams } from '../types/composition';
import {
CompositionParams,
InstrumentType,
MidiMessage,
MidiPort,
Track,
tracksMinimalTotalTime
} from '../types/composition';
import { ModelConfig } from '../types/configs';
import { DownloadStatus } from '../types/downloads';
import { IntroductionContent } from '../types/home';
@@ -51,6 +58,7 @@ class CommonStore {
monitorData: MonitorData | null = null;
depComplete: boolean = false;
platform: Platform = 'windows';
lastModelName: string = '';
// presets manager
editingPreset: Preset | null = null;
presets: Preset[] = [];
@@ -64,6 +72,14 @@ class CommonStore {
attachmentUploading: boolean = false;
attachments: { [uuid: string]: Attachment[] } = {};
currentTempAttachment: Attachment | null = null;
chatParams: ChatParams = {
maxResponseToken: 1000,
temperature: 1,
topP: 0.3,
presencePenalty: 0,
frequencyPenalty: 1
};
sidePanelCollapsed: boolean | 'auto' = 'auto';
// completion
completionPreset: CompletionPreset | null = null;
completionGenerating: boolean = false;
@@ -81,6 +97,20 @@ class CommonStore {
};
compositionGenerating: boolean = false;
compositionSubmittedPrompt: string = defaultCompositionPrompt;
// composition midi device
midiPorts: MidiPort[] = [];
activeMidiDeviceIndex: number = -1;
instrumentType: InstrumentType = InstrumentType.Piano;
// composition tracks
tracks: Track[] = [];
trackScale: number = 1;
trackTotalTime: number = tracksMinimalTotalTime;
trackCurrentTime: number = 0;
trackPlayStartTime: number = 0;
playingTrackId: string = '';
recordingTrackId: string = '';
recordingContent: string = ''; // used to improve performance of midiMessageHandler, and I'm too lazy to maintain an ID dictionary for this (although that would be better for realtime effects)
recordingRawContent: MidiMessage[] = [];
// configs
currentModelConfigIndex: number = 0;
modelConfigs: ModelConfig[] = [];
@@ -133,6 +163,7 @@ class CommonStore {
autoUpdatesCheck: true,
giteeUpdatesSource: getUserLanguage() === 'zh',
cnMirror: getUserLanguage() === 'zh',
useHfMirror: false,
host: '127.0.0.1',
dpiScaling: 100,
customModelsPath: './models',
@@ -232,6 +263,10 @@ class CommonStore {
this.about = value;
};
setLastModelName(value: string) {
this.lastModelName = value;
}
setDepComplete = (value: boolean, inSaveCache: boolean = true) => {
this.depComplete = value;
if (inSaveCache)
@@ -358,6 +393,62 @@ class CommonStore {
setCurrentTempAttachment(value: Attachment | null) {
this.currentTempAttachment = value;
}
setChatParams(value: Partial<ChatParams>) {
this.chatParams = { ...this.chatParams, ...value };
}
setSidePanelCollapsed(value: boolean | 'auto') {
this.sidePanelCollapsed = value;
}
setTracks(value: Track[]) {
this.tracks = value;
}
setTrackScale(value: number) {
this.trackScale = value;
}
setTrackTotalTime(value: number) {
this.trackTotalTime = value;
}
setTrackCurrentTime(value: number) {
this.trackCurrentTime = value;
}
setTrackPlayStartTime(value: number) {
this.trackPlayStartTime = value;
}
setMidiPorts(value: MidiPort[]) {
this.midiPorts = value;
}
setInstrumentType(value: InstrumentType) {
this.instrumentType = value;
}
setRecordingTrackId(value: string) {
this.recordingTrackId = value;
}
setActiveMidiDeviceIndex(value: number) {
this.activeMidiDeviceIndex = value;
}
setRecordingContent(value: string) {
this.recordingContent = value;
}
setRecordingRawContent(value: MidiMessage[]) {
this.recordingRawContent = value;
}
setPlayingTrackId(value: string) {
this.playingTrackId = value;
}
}
export default new CommonStore();

View File

@@ -1,3 +1,5 @@
import { ApiParameters } from './configs';
export const userName = 'M E';
export const botName = 'A I';
export const welcomeUuid = 'welcome';
@@ -31,4 +33,5 @@ export type Attachment = {
name: string;
size: number;
content: string;
}
}
export type ChatParams = Omit<ApiParameters, 'apiPort'>

View File

@@ -1,5 +1,7 @@
import { NoteSequence } from '@magenta/music/esm/protobuf';
export const tracksMinimalTotalTime = 5000;
export type CompositionParams = {
prompt: string,
maxResponseToken: number,
@@ -9,4 +11,74 @@ export type CompositionParams = {
useLocalSoundFont: boolean,
midi: ArrayBuffer | null,
ns: NoteSequence | null
}
}
export type Track = {
id: string;
content: string;
rawContent: MidiMessage[];
offsetTime: number;
contentTime: number;
};
export type MidiPort = {
name: string;
}
export type MessageType = 'NoteOff' | 'NoteOn' | 'ElapsedTime' | 'ControlChange';
export type MidiMessage = {
messageType: MessageType;
channel: number;
note: number;
velocity: number;
control: number;
value: number;
instrument: InstrumentType;
}
export enum InstrumentType {
Piano,
Percussion,
Drum,
Tuba,
Marimba,
Bass,
Guitar,
Violin,
Trumpet,
Sax,
Flute,
Lead,
Pad,
}
export const InstrumentTypeNameMap = [
'Piano',
'Percussion',
'Drum',
'Tuba',
'Marimba',
'Bass',
'Guitar',
'Violin',
'Trumpet',
'Sax',
'Flute',
'Lead',
'Pad'
];
export const InstrumentTypeTokenMap = [
'pi',
'p',
'd',
't',
'm',
'b',
'g',
'v',
'tr',
's',
'f',
'l',
'pa'
];

View File

@@ -7,7 +7,7 @@ export type ApiParameters = {
frequencyPenalty: number;
}
export type Device = 'CPU' | 'CUDA' | 'CUDA-Beta' | 'WebGPU' | 'MPS' | 'Custom';
export type Precision = 'fp16' | 'int8' | 'fp32';
export type Precision = 'fp16' | 'int8' | 'fp32' | 'nf4';
export type ModelParameters = {
// different models can not have the same name
modelName: string;

View File

@@ -10,6 +10,7 @@ export type SettingsType = {
autoUpdatesCheck: boolean
giteeUpdatesSource: boolean
cnMirror: boolean
useHfMirror: boolean
host: string
dpiScaling: number
customModelsPath: string

View File

@@ -0,0 +1,42 @@
import { toast } from 'react-toastify';
import commonStore from '../stores/commonStore';
import { t } from 'i18next';
import { checkDependencies } from './index';
import { ConvertSafetensors, FileExists, GetPyError } from '../../wailsjs/go/backend_golang/App';
import { WindowShow } from '../../wailsjs/runtime';
import { NavigateFunction } from 'react-router';
import { ModelConfig } from '../types/configs';
export const convertToSt = async (navigate: NavigateFunction, selectedConfig: ModelConfig) => {
if (commonStore.platform === 'linux') {
toast(t('Linux is not yet supported for performing this operation, please do it manually.') + ' (backend-python/convert_safetensors.py)', { type: 'info' });
return;
}
const ok = await checkDependencies(navigate);
if (!ok)
return;
const modelPath = `${commonStore.settings.customModelsPath}/${selectedConfig.modelParameters.modelName}`;
if (await FileExists(modelPath)) {
toast(t('Start Converting'), { autoClose: 1000, type: 'info' });
const newModelPath = modelPath.replace(/\.pth$/, '.st');
ConvertSafetensors(commonStore.settings.customPythonPath, modelPath, newModelPath).then(async () => {
if (!await FileExists(newModelPath)) {
if (commonStore.platform === 'windows')
toast(t('Convert Failed') + ' - ' + await GetPyError(), { type: 'error' });
} else {
toast(`${t('Convert Success')} - ${newModelPath}`, { type: 'success' });
}
}).catch(e => {
const errMsg = e.message || e;
if (errMsg.includes('path contains space'))
toast(`${t('Convert Failed')} - ${t('File Path Cannot Contain Space')}`, { type: 'error' });
else
toast(`${t('Convert Failed')} - ${e.message || e}`, { type: 'error' });
});
setTimeout(WindowShow, 1000);
} else {
toast(`${t('Model Not Found')} - ${modelPath}`, { type: 'error' });
}
};

View File

@@ -22,6 +22,7 @@ import { DownloadStatus } from '../types/downloads';
import { ModelSourceItem } from '../types/models';
import { Language, Languages, SettingsType } from '../types/settings';
import { DataProcessParameters, LoraFinetuneParameters } from '../types/train';
import { tracksMinimalTotalTime } from '../types/composition';
export type Cache = {
version: string
@@ -117,7 +118,7 @@ function initLastUnfinishedModelDownloads() {
{
name: item.name,
path: `${commonStore.settings.customModelsPath}/${item.name}`,
url: item.downloadUrl!,
url: getHfDownloadUrl(item.downloadUrl!),
transferred: item.localSize!,
size: item.size,
speed: 0,
@@ -178,14 +179,14 @@ export const getStrategy = (modelConfig: ModelConfig | undefined = undefined) =>
strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32';
break;
case 'WebGPU':
strategy += params.precision === 'int8' ? 'fp16i8' : 'fp16';
strategy += params.precision === 'nf4' ? 'fp16i4' : params.precision === 'int8' ? 'fp16i8' : 'fp16';
break;
case 'CUDA':
case 'CUDA-Beta':
if (avoidOverflow)
strategy = params.useCustomCuda ? 'cuda fp16 *1 -> ' : 'cuda fp32 *1 -> ';
strategy += 'cuda ';
strategy += params.precision === 'fp16' ? 'fp16' : params.precision === 'int8' ? 'fp16i8' : 'fp32';
strategy += params.precision === 'int8' ? 'fp16i8' : params.precision === 'fp32' ? 'fp32' : 'fp16';
if (params.storedLayers < params.maxStoredLayers)
strategy += ` *${params.storedLayers}+`;
break;
@@ -193,7 +194,7 @@ export const getStrategy = (modelConfig: ModelConfig | undefined = undefined) =>
if (avoidOverflow)
strategy = 'mps fp32 *1 -> ';
strategy += 'mps ';
strategy += params.precision === 'fp16' ? 'fp16' : params.precision === 'int8' ? 'fp16i8' : 'fp32';
strategy += params.precision === 'int8' ? 'fp32i8' : 'fp32';
break;
case 'Custom':
strategy = params.customStrategy || '';
@@ -290,12 +291,15 @@ export function bytesToReadable(size: number) {
}
export function getServerRoot(defaultLocalPort: number) {
const defaultRoot = `http://127.0.0.1:${defaultLocalPort}`;
if (commonStore.status.status !== ModelStatus.Offline)
return defaultRoot;
const customApiUrl = commonStore.settings.apiUrl.trim().replace(/\/$/, '');
if (customApiUrl)
return customApiUrl;
if (commonStore.platform === 'web')
return '';
return `http://127.0.0.1:${defaultLocalPort}`;
return defaultRoot;
}
export function absPathAsset(path: string) {
@@ -471,6 +475,64 @@ export function toastWithButton(text: string, buttonText: string, onClickButton:
return id;
}
export function getHfDownloadUrl(url: string) {
if (commonStore.settings.useHfMirror && url.includes('huggingface.co') && url.includes('resolve'))
return url.replace('huggingface.co', 'hf-mirror.com');
return url;
}
export function refreshTracksTotalTime() {
if (commonStore.tracks.length === 0) {
commonStore.setTrackTotalTime(tracksMinimalTotalTime);
commonStore.setTrackCurrentTime(0);
commonStore.setTrackPlayStartTime(0);
return;
}
const endTimes = commonStore.tracks.map(t => t.offsetTime + t.contentTime);
const totalTime = Math.max(...endTimes) + tracksMinimalTotalTime;
if (commonStore.trackPlayStartTime > totalTime)
commonStore.setTrackPlayStartTime(totalTime);
commonStore.setTrackTotalTime(totalTime);
}
export function flushMidiRecordingContent() {
const recordingTrackIndex = commonStore.tracks.findIndex(t => t.id === commonStore.recordingTrackId);
if (recordingTrackIndex >= 0) {
const recordingTrack = commonStore.tracks[recordingTrackIndex];
const tracks = commonStore.tracks.slice();
const contentTime = commonStore.recordingRawContent
.reduce((sum, current) =>
sum + (current.messageType === 'ElapsedTime' ? current.value : 0)
, 0);
tracks[recordingTrackIndex] = {
...recordingTrack,
content: commonStore.recordingContent,
rawContent: commonStore.recordingRawContent,
contentTime: contentTime
};
commonStore.setTracks(tracks);
refreshTracksTotalTime();
}
commonStore.setRecordingContent('');
commonStore.setRecordingRawContent([]);
}
export async function getSoundFont() {
let soundUrl: string;
if (commonStore.compositionParams.useLocalSoundFont)
soundUrl = 'assets/sound-font';
else
soundUrl = !commonStore.settings.giteeUpdatesSource ?
`https://raw.githubusercontent.com/josStorer/sgm_plus/master` :
`https://gitee.com/josc146/sgm_plus/raw/master`;
const fallbackUrl = 'https://cdn.jsdelivr.net/gh/josstorer/sgm_plus';
await fetch(soundUrl + '/soundfont.json').then(r => {
if (!r.ok)
soundUrl = fallbackUrl;
}).catch(() => soundUrl = fallbackUrl);
return soundUrl;
}
export function getSupportedCustomCudaFile(isBeta: boolean) {
if ([' 10', ' 16', ' 20', ' 30', 'MX', 'Tesla P', 'Quadro P', 'NVIDIA P', 'TITAN X', 'TITAN RTX', 'RTX A',
'Quadro RTX 4000', 'Quadro RTX 5000', 'Tesla T4', 'NVIDIA A10', 'NVIDIA A40'].some(v => commonStore.status.device_name.includes(v)))

View File

@@ -0,0 +1,72 @@
import { getDocument, GlobalWorkerOptions, PDFDocumentProxy } from 'pdfjs-dist';
import { TextItem } from 'pdfjs-dist/types/src/display/api';
export function webOpenOpenFileDialog({ filterPattern, fnStartLoading }: { filterPattern: string, fnStartLoading: Function | null }): Promise<{ blob: Blob, content?: string }> {
return new Promise((resolve, reject) => {
const input = document.createElement('input');
input.type = 'file';
input.accept = filterPattern
.replaceAll('*.txt', 'text/plain')
.replaceAll('*.', 'application/')
.replaceAll(';', ',');
input.onchange = async e => {
// @ts-ignore
const file: Blob = e.target?.files[0];
if (fnStartLoading && typeof fnStartLoading === 'function')
fnStartLoading();
if (!GlobalWorkerOptions.workerSrc)
// @ts-ignore
GlobalWorkerOptions.workerSrc = await import('pdfjs-dist/build/pdf.worker.min.mjs');
if (file.type === 'text/plain') {
const reader = new FileReader();
reader.readAsText(file, 'UTF-8');
reader.onload = event => {
const content = event.target?.result as string;
resolve({
blob: file,
content: content
});
};
reader.onerror = reject;
} else if (file.type === 'application/pdf') {
const readPDFPage = async (doc: PDFDocumentProxy, pageNo: number) => {
const page = await doc.getPage(pageNo);
const tokenizedText = await page.getTextContent();
return tokenizedText.items.map(token => (token as TextItem).str).join('');
};
let reader = new FileReader();
reader.readAsArrayBuffer(file);
reader.onload = async (event) => {
try {
const doc = await getDocument(event.target?.result!).promise;
const pageTextPromises = [];
for (let pageNo = 1; pageNo <= doc.numPages; pageNo++) {
pageTextPromises.push(readPDFPage(doc, pageNo));
}
const pageTexts = await Promise.all(pageTextPromises);
let content;
if (pageTexts.length === 1)
content = pageTexts[0];
else
content = pageTexts.map((p, i) => `Page ${i + 1}:\n${p}`).join('\n\n');
resolve({
blob: file,
content: content
});
} catch (err) {
reject(err);
}
};
reader.onerror = reject;
} else {
resolve({
blob: file
});
}
};
input.click();
});
}

View File

@@ -1,3 +1,5 @@
import { webOpenOpenFileDialog } from './utils/web-file-operations'
function defineRuntime(name, func) {
window.runtime[name] = func
}
@@ -107,37 +109,7 @@ if (!window.go) {
defineApp('ListDirFiles', async () => {
return []
})
defineApp('OpenOpenFileDialog', async (filterPattern) => {
return new Promise((resolve, reject) => {
const input = document.createElement('input')
input.type = 'file'
input.accept = filterPattern
.replaceAll('*.txt', 'text/plain')
.replaceAll('*.', 'application/')
.replaceAll(';', ',')
input.onchange = e => {
const file = e.target?.files[0]
if (file.type === 'text/plain') {
const reader = new FileReader()
reader.readAsText(file, 'UTF-8')
reader.onload = readerEvent => {
const content = readerEvent.target?.result
resolve({
blob: file,
content: content
})
}
} else {
resolve({
blob: file
})
}
}
input.click()
})
})
defineApp('OpenOpenFileDialog', webOpenOpenFileDialog)
defineApp('OpenSaveFileDialog', async (filterPattern, defaultFileName, savedContent) => {
const saver = await import('file-saver')
saver.saveAs(new Blob([savedContent], { type: 'text/plain;charset=utf-8' }), defaultFileName)

View File

@@ -3,6 +3,7 @@ import { dependencies } from './package.json';
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { visualizer } from 'rollup-plugin-visualizer';
import topLevelAwait from 'vite-plugin-top-level-await';
// dependencies that exist anywhere
const vendor = [
@@ -20,6 +21,7 @@ const embedded = [
// dependencies that exist in single component
'react-beautiful-dnd',
'react-draggable',
'@magenta/music', 'html-midi-player',
'react-markdown', 'rehype-highlight', 'rehype-raw', 'remark-breaks', 'remark-gfm'
];
@@ -35,12 +37,18 @@ function renderChunks(deps: Record<string, string>) {
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react(),
plugins: [
react(),
visualizer({
template: 'treemap',
gzipSize: true,
brotliSize: true
})],
}),
topLevelAwait({
promiseExportName: '__tla',
promiseImportName: i => `__tla_${i}`
})
],
build: {
chunkSizeWarningLimit: 3000,
rollupOptions: {

View File

@@ -4,6 +4,8 @@ import {backend_golang} from '../models';
export function AddToDownloadList(arg1:string,arg2:string):Promise<void>;
export function CloseMidiPort():Promise<void>;
export function ContinueDownload(arg1:string):Promise<void>;
export function ConvertData(arg1:string,arg2:string,arg3:string,arg4:string):Promise<string>;
@@ -36,6 +38,8 @@ export function MergeLora(arg1:string,arg2:boolean,arg3:number,arg4:string,arg5:
export function OpenFileFolder(arg1:string,arg2:boolean):Promise<void>;
export function OpenMidiPort(arg1:number):Promise<void>;
export function OpenOpenFileDialog(arg1:string):Promise<string>;
export function OpenSaveFileDialog(arg1:string,arg2:string,arg3:string):Promise<string>;
@@ -44,6 +48,8 @@ export function OpenSaveFileDialogBytes(arg1:string,arg2:string,arg3:Array<numbe
export function PauseDownload(arg1:string):Promise<void>;
export function PlayNote(arg1:backend_golang.MIDIMessage):Promise<void>;
export function ReadFileInfo(arg1:string):Promise<backend_golang.FileInfo>;
export function ReadJson(arg1:string):Promise<any>;

View File

@@ -6,6 +6,10 @@ export function AddToDownloadList(arg1, arg2) {
return window['go']['backend_golang']['App']['AddToDownloadList'](arg1, arg2);
}
export function CloseMidiPort() {
return window['go']['backend_golang']['App']['CloseMidiPort']();
}
export function ContinueDownload(arg1) {
return window['go']['backend_golang']['App']['ContinueDownload'](arg1);
}
@@ -70,6 +74,10 @@ export function OpenFileFolder(arg1, arg2) {
return window['go']['backend_golang']['App']['OpenFileFolder'](arg1, arg2);
}
export function OpenMidiPort(arg1) {
return window['go']['backend_golang']['App']['OpenMidiPort'](arg1);
}
export function OpenOpenFileDialog(arg1) {
return window['go']['backend_golang']['App']['OpenOpenFileDialog'](arg1);
}
@@ -86,6 +94,10 @@ export function PauseDownload(arg1) {
return window['go']['backend_golang']['App']['PauseDownload'](arg1);
}
export function PlayNote(arg1) {
return window['go']['backend_golang']['App']['PlayNote'](arg1);
}
export function ReadFileInfo(arg1) {
return window['go']['backend_golang']['App']['ReadFileInfo'](arg1);
}

View File

@@ -18,6 +18,28 @@ export namespace backend_golang {
this.modTime = source["modTime"];
}
}
export class MIDIMessage {
messageType: string;
channel: number;
note: number;
velocity: number;
control: number;
value: number;
static createFrom(source: any = {}) {
return new MIDIMessage(source);
}
constructor(source: any = {}) {
if ('string' === typeof source) source = JSON.parse(source);
this.messageType = source["messageType"];
this.channel = source["channel"];
this.note = source["note"];
this.velocity = source["velocity"];
this.control = source["control"];
this.value = source["value"];
}
}
}

1
go.mod
View File

@@ -5,6 +5,7 @@ go 1.20
require (
github.com/cavaliergopher/grab/v3 v3.0.1
github.com/fsnotify/fsnotify v1.6.0
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79
github.com/minio/selfupdate v0.6.0
github.com/nyaosorg/go-windows-su v0.2.1
github.com/ubuntu/gowsl v0.0.0-20230615094051-94945650cc1e

2
go.sum
View File

@@ -38,6 +38,8 @@ github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27k
github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM=
github.com/mattn/go-isatty v0.0.19 h1:JITubQf0MOLdlGRuRq+jtsDlekdYPia9ZFsB8h/APPA=
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79 h1:CA1UHN3RuY70DlC0RlvgtB1e8h3kYzmvK7s8CFe+Ohw=
github.com/mattrtaylor/go-rtmidi v0.0.0-20220428034745-af795b1c1a79/go.mod h1:oBuZjmjlKSj9CZKrNhcx/adNhHiiE0hZknECjIP8Z0Q=
github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU=
github.com/minio/selfupdate v0.6.0/go.mod h1:bO02GTIPCMQFTEvE5h4DjYB58bCoZ35XLeBf0buTDdM=
github.com/nyaosorg/go-windows-su v0.2.1 h1:5V0XavLyjOqPUp7psxxCvBISaneU4XmFPSMlejSl5sc=

View File

@@ -1,5 +1,5 @@
{
"version": "1.5.1",
"version": "1.5.6",
"introduction": {
"en": "RWKV is an open-source, commercially usable large language model with high flexibility and great potential for development.\n### About This Tool\nThis tool aims to lower the barrier of entry for using large language models, making it accessible to everyone. It provides fully automated dependency and model management. You simply need to click and run, following the instructions, to deploy a local large language model. The tool itself is very compact and only requires a single executable file for one-click deployment.\nAdditionally, this tool offers an interface that is fully compatible with the OpenAI API. This means you can use any ChatGPT client as a client for RWKV, enabling capability expansion beyond just chat functionality.\n### Preset Configuration Rules at the Bottom\nThis tool comes with a series of preset configurations to reduce complexity. The naming rules for each configuration represent the following in order: device - required VRAM/memory - model size - model language.\nFor example, \"GPU-8G-3B-EN\" indicates that this configuration is for a graphics card with 8GB of VRAM, a model size of 3 billion parameters, and it uses an English language model.\nLarger model sizes have higher performance and VRAM requirements. Among configurations with the same model size, those with higher VRAM usage will have faster runtime.\nFor example, if you have 12GB of VRAM but running the \"GPU-12G-7B-EN\" configuration is slow, you can downgrade to \"GPU-8G-3B-EN\" for a significant speed improvement.\n### About RWKV\nRWKV is an RNN with Transformer-level LLM performance, which can also be directly trained like a GPT transformer (parallelizable). And it's 100% attention-free. You only need the hidden state at position t to compute the state at position t+1. You can use the \"GPT\" mode to quickly compute the hidden state for the \"RNN\" mode.<br/>So it's combining the best of RNN and transformer - great performance, fast inference, saves VRAM, fast training, \"infinite\" ctx_len, and free sentence embedding (using the final hidden state).",
"zh": "RWKV是一个开源且允许商用的大语言模型灵活性很高且极具发展潜力。\n### 关于本工具\n本工具旨在降低大语言模型的使用门槛做到人人可用本工具提供了全自动化的依赖和模型管理你只需要直接点击运行跟随引导即可完成本地大语言模型的部署工具本身体积极小只需要一个exe即可完成一键部署。\n此外本工具提供了与OpenAI API完全兼容的接口这意味着你可以把任意ChatGPT客户端用作RWKV的客户端实现能力拓展而不局限于聊天。\n### 底部的预设配置规则\n本工具内置了一系列预设配置以降低使用难度每个配置名的规则依次代表着设备-所需显存/内存-模型规模-模型语言。\n例如GPU-8G-3B-CN表示该配置用于显卡需要8G显存模型规模为30亿参数使用的是中文模型。\n模型规模越大性能要求越高显存要求也越高而同样模型规模的配置中显存占用越高的运行速度越快。\n例如当你有12G显存但运行GPU-12G-7B-CN配置速度比较慢可降级成GPU-8G-3B-CN将会大幅提速。\n### 关于RWKV\nRWKV是具有Transformer级别LLM性能的RNN也可以像GPT Transformer一样直接进行训练可并行化。而且它是100% attention-free的。你只需在位置t处获得隐藏状态即可计算位置t + 1处的状态。你可以使用“GPT”模式快速计算用于“RNN”模式的隐藏状态。\n因此它将RNN和Transformer的优点结合起来 - 高性能、快速推理、节省显存、快速训练、“无限”上下文长度以及免费的语句嵌入(使用最终隐藏状态)。"
@@ -15,6 +15,32 @@
}
],
"models": [
{
"name": "RWKV-5-World-0.1B-v1-20230803-ctx4096.pth",
"desc": {
"en": "RWKV-5 Global Languages 0.1B v1",
"zh": "RWKV-5 全球语言 0.1B v1",
"ja": "RWKV-5 グローバル言語 0.1B v1"
},
"size": 385598386,
"SHA256": "c844a3ee05bcb9065848cb05b10c48a3f381f5ac1953aad89e156ecdf31d7703",
"lastUpdated": "2023-08-03T15:18:46",
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-0.1B-v1-20230803-ctx4096.pth?download=true",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-0.1B-v1-20230803-ctx4096.pth?download=true"
},
{
"name": "RWKV-5-World-0.4B-v2-20231113-ctx4096.pth",
"desc": {
"en": "RWKV-5 Global Languages 0.4B v2",
"zh": "RWKV-5 全球语言 0.4B v2",
"ja": "RWKV-5 グローバル言語 0.4B v2"
},
"size": 923523954,
"SHA256": "5a288c54c7f30b0e2d4af23991133fad2af2d5e59ec7ad850ffe78054a5e4f92",
"lastUpdated": "2023-11-14T01:23:49",
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-0.4B-v2-20231113-ctx4096.pth?download=true",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-0.4B-v2-20231113-ctx4096.pth?download=true"
},
{
"name": "RWKV-5-World-1B5-v2-20231025-ctx4096.pth",
"desc": {
@@ -28,6 +54,32 @@
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-1B5-v2-20231025-ctx4096.pth",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-1B5-v2-20231025-ctx4096.pth"
},
{
"name": "RWKV-5-World-3B-v2-20231113-ctx4096.pth",
"desc": {
"en": "RWKV-5 Global Languages 3B v2",
"zh": "RWKV-5 全球语言 3B v2",
"ja": "RWKV-5 グローバル言語 3B v2"
},
"size": 6126106674,
"SHA256": "a4bd430343c6fd138b85bbc68bb20262d3a2f053ea57dc4b41078269af68ff9c",
"lastUpdated": "2023-11-14T01:23:49",
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-3B-v2-20231113-ctx4096.pth?download=true",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-3B-v2-20231113-ctx4096.pth?download=true"
},
{
"name": "RWKV-5-World-3B-v2-20231118-ctx16k.pth",
"desc": {
"en": "RWKV-5 Global Languages 3B v2 Ctx16k",
"zh": "RWKV-5 全球语言 3B v2 16k上下文",
"ja": "RWKV-5 グローバル言語 3B v2 16kコンテキスト"
},
"size": 6126106467,
"SHA256": "efa5178d1c824b94ef17c6c9a456674e5581a8be832becbda9aba4dc533f88c2",
"lastUpdated": "2023-11-19T04:21:04",
"url": "https://huggingface.co/BlinkDL/rwkv-5-world/blob/main/RWKV-5-World-3B-v2-20231118-ctx16k.pth?download=true",
"downloadUrl": "https://huggingface.co/BlinkDL/rwkv-5-world/resolve/main/RWKV-5-World-3B-v2-20231118-ctx16k.pth?download=true"
},
{
"name": "RWKV-4-World-CHNtuned-0.1B-v1-20230617-ctx4096.pth",
"desc": {