From d0b5bc8682459b84e008fdb9ed48444c255532da Mon Sep 17 00:00:00 2001 From: frodo821 Date: Tue, 27 Feb 2024 04:38:47 +0900 Subject: [PATCH] =?UTF-8?q?=E3=83=A2=E3=83=87=E3=83=AB=E3=81=AE=E3=83=9E?= =?UTF-8?q?=E3=83=BC=E3=82=B8=E3=81=AB=E7=90=83=E9=9D=A2=E7=B7=9A=E5=BD=A2?= =?UTF-8?q?=E8=A3=9C=E9=96=93=E3=82=92=E4=BD=BF=E3=81=88=E3=82=8B=E3=82=88?= =?UTF-8?q?=E3=81=86=E3=81=AB=E3=81=97=E3=81=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- webui_merge.py | 31 +++++++++++++++++++++++++++++-- 1 file changed, 29 insertions(+), 2 deletions(-) diff --git a/webui_merge.py b/webui_merge.py index 69f7e8d..a2517e7 100644 --- a/webui_merge.py +++ b/webui_merge.py @@ -102,6 +102,25 @@ def merge_style(model_name_a, model_name_b, weight, output_name, style_triple_li return output_style_path, list(new_style2id.keys()) +def lerp_tensors(t, v0, v1): + return v0 * (1 - t) + v1 * t + +def slerp_tensors(t, v0, v1, dot_thres = 0.998): + device = v0.device + v0c = v0.cpu().numpy() + v1c = v1.cpu().numpy() + + dot = np.sum(v0c * v1c / (np.linalg.norm(v0c) * np.linalg.norm(v1c))) + + if abs(dot) > dot_thres: + return lerp_tensors(t, v0, v1) + + th0 = np.arccos(dot) + sin_th0 = np.sin(th0) + th_t = th0 * t + + return torch.from_numpy(v0c * np.sin(th0 - th_t) / sin_th0 + v1c * np.sin(th_t) / sin_th0).to(device) + def merge_models( model_path_a, model_path_b, @@ -110,6 +129,7 @@ def merge_models( speech_style_weight, tempo_weight, output_name, + use_slerp_instead_of_lerp, ): """model Aを起点に、model Bの各要素を重み付けしてマージする。 safetensors形式を前提とする。""" @@ -137,8 +157,8 @@ def merge_models( else: continue merged_model_weight[key] = ( - model_a_weight[key] * (1 - weight) + model_b_weight[key] * weight - ) + slerp_tensors if use_slerp_instead_of_lerp else lerp_tensors + )(weight, model_a_weight[key], model_b_weight[key]) merged_model_path = os.path.join( assets_root, output_name, f"{output_name}.safetensors" @@ -171,6 +191,7 @@ def merge_models_gr( voice_pitch_weight, speech_style_weight, tempo_weight, + use_slerp_instead_of_lerp, ): if output_name == "": return "Error: 新しいモデル名を入力してください。" @@ -182,6 +203,7 @@ def merge_models_gr( speech_style_weight, tempo_weight, output_name, + use_slerp_instead_of_lerp, ) return f"Success: モデルを{merged_model_path}に保存しました。" @@ -359,6 +381,10 @@ with gr.Blocks(theme=GRADIO_THEME) as app: maximum=1, step=0.1, ) + use_slerp_instead_of_lerp = gr.Checkbox( + label="lerpのかわりにslerpを使う", + value=False, + ) with gr.Column(variant="panel"): gr.Markdown("## モデルファイル(safetensors)のマージ") model_merge_button = gr.Button("モデルファイルのマージ", variant="primary") @@ -429,6 +455,7 @@ with gr.Blocks(theme=GRADIO_THEME) as app: voice_pitch_slider, speech_style_slider, tempo_slider, + use_slerp_instead_of_lerp, ], outputs=[info_model_merge], )