Skip to content

Commit

Permalink
Avoid unnecessary dtype conversions with rope encodings.
Browse files Browse the repository at this point in the history
  • Loading branch information
RyanJDick authored and hipsterusername committed Nov 29, 2024
1 parent be73dbb commit 021552f
Showing 1 changed file with 2 additions and 2 deletions.
4 changes: 2 additions & 2 deletions invokeai/backend/flux/math.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ def rope(pos: Tensor, dim: int, theta: int) -> Tensor:
out = torch.einsum("...n,d->...nd", pos, omega)
out = torch.stack([torch.cos(out), -torch.sin(out), torch.sin(out), torch.cos(out)], dim=-1)
out = rearrange(out, "b n d (i j) -> b n d i j", i=2, j=2)
return out.float()
return out.to(dtype=pos.dtype, device=pos.device)


def apply_rope(xq: Tensor, xk: Tensor, freqs_cis: Tensor) -> tuple[Tensor, Tensor]:
xq_ = xq.view(*xq.shape[:-1], -1, 1, 2)
xk_ = xk.view(*xk.shape[:-1], -1, 1, 2)
xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
return xq_out.view(*xq.shape).type_as(xq), xk_out.view(*xk.shape).type_as(xk)
return xq_out.view(*xq.shape), xk_out.view(*xk.shape)

0 comments on commit 021552f

Please sign in to comment.