Skip to content

The most powerful and modular diffusion model GUI, api and backend with a graph/nodes interface. The fastest local inference engine in the world.

Use comfy kitchen apply rope in llama based models. (#16326)

comfyanonymous6cff1e974f82
diff --git a/comfy/text_encoders/llama.py b/comfy/text_encoders/llama.py
index eda2dfb39..80e568b7c 100644
--- a/comfy/text_encoders/llama.py
+++ b/comfy/text_encoders/llama.py
@@ -489,23 +489,17 @@ def precompute_freqs_cis(head_dim, position_ids, theta, rope_scale=None, rope_di
return out
-def apply_rope(xq, xk, freqs_cis):
- org_dtype = xq.dtype
- cos = freqs_cis[0]
- sin = freqs_cis[1]
- nsin = freqs_cis[2]
-
- q_embed = (xq * cos)
- q_split = q_embed.shape[-1] // 2
- q_embed[..., : q_split].addcmul_(xq[..., q_split :], nsin)
- q_embed[..., q_split :].addcmul_(xq[..., : q_split], sin)
+def rope_matrix(freqs_cis):
+ if torch.is_tensor(freqs_cis):
+ return freqs_cis
+ cos, sin, neg_sin = freqs_cis
+ half = sin.shape[-1]
+ matrix = torch.stack((cos[..., :half], neg_sin, sin, cos[..., half:]), dim=-1)
+ return matrix.reshape(*matrix.shape[:-1], 2, 2)
- k_embed = (xk * cos)
- k_split = k_embed.shape[-1] // 2
- k_embed[..., : k_split].addcmul_(xk[..., k_split :], nsin)
- k_embed[..., k_split :].addcmul_(xk[..., : k_split], sin)
- return q_embed.to(org_dtype), k_embed.to(org_dtype)
+def apply_rope(xq, xk, freqs_cis):
+ return comfy_kitchen.apply_rope_split_half(xq, xk, rope_matrix(freqs_cis))
class Attention(nn.Module):
@@ -861,12 +855,11 @@ class Llama2_(nn.Module):
if decode_buffers is None:
x = x.clone()
else:
- hidden_buffer, rotary_buffers = decode_buffers
+ hidden_buffer, rotary_buffer = decode_buffers
hidden_buffer.copy_(x)
x = hidden_buffer
- for buffer, value in zip(rotary_buffers, freqs_cis):
- buffer.copy_(value)
- freqs_cis = rotary_buffers
+ rotary_buffer.copy_(rope_matrix(freqs_cis))
+ freqs_cis = rotary_buffer
intermediate = None
all_intermediate = None
diff --git a/comfy/text_encoders/yue2.py b/comfy/text_encoders/yue2.py
index 85f0e9944..4df5d8c28 100644
--- a/comfy/text_encoders/yue2.py
+++ b/comfy/text_encoders/yue2.py
@@ -10,7 +10,7 @@ import comfy.model_prefetch
import comfy.ops
import comfy.utils
from comfy.ldm.yue2.model import model_config
-from comfy.text_encoders.llama import FixedKV, Llama2_
+from comfy.text_encoders.llama import FixedKV, Llama2_, rope_matrix
EOD = 151643
@@ -165,7 +165,7 @@ class YuE2TEModel(torch.nn.Module):
decode_buffers = None
if fixed_kv:
decode_buffers = (torch.empty((len(prefixes), 1, self.config.hidden_size), device=device, dtype=dtype),
- self.model.compute_freqs_cis(positions, device))
+ rope_matrix(self.model.compute_freqs_cis(positions, device)))
history = []
end = ABC_END if phase == "abc" else MUSIC_END
progress = comfy.utils.ProgressBar(max_tokens)