def forward(self, x):
return x * self.gamma.view(1,-1,1,1)
class RoPEAttention(torch.nn.Module):
"""
Rotary Position Embedding (RoPE) Attention module.
code
Assistant
User
what size should condition be
Assistant
User
like random number of channel and batch size but all other is same as input>
Assistant
Yes, you can design the tensor such that its batch size matches the input tensor, while the spatial dimensions (height and width) are the same or can be adjusted to fit through transformations. The number of channels in the tensor can be different. Here’s how you can handle and set up the tensor appropriately:
This module implements a multi-head attention mechanism for vision transformers with Rotary Position Embeddings.
It applies RoPE to the query and key projections before computing attention, uses QK norm,
Flash Attention v2 and scales alpha to allow interpolation and extrapolation to new resolutions
Args:
channels (int): Number of input and output channels.
heads (int): Number of attention heads.
baseSize (int): The base resolution RoPE will be scaled around.
"""
def __init__(self, channels, heads, baseSize):
super().__init__()
self.channels = channels
self.heads = heads
self.baseSize=baseSize
self.headDim = channels // heads
self.qProj = torch.nn.Conv2d(channels, channels, 1)
self.kProj = torch.nn.Conv2d(channels, channels, 1)
self.vProj = torch.nn.Conv2d(channels, channels, 1)
self.outProj = torch.nn.Conv2d(channels, channels, 1)
self.qLayerNorm=torch.nn.GroupNorm(1,heads)
self.kLayerNorm=torch.nn.GroupNorm(1,heads)
def createRotationMatrix(self, height, width, channels):
scalingH=height/self.baseSize if height>self.baseSize else 1.0
scalingW=width/self.baseSize if width>self.baseSize else 1.0
t = torch.arange(height * width, dtype=torch.float32)
tX = (t % width).float()
tY = torch.div(t, width, rounding_mode='floor').float()
freqsX = 1.0 / ((100.0*scalingW) ** (torch.arange(0, channels, 2).float() / channels))
freqsY = 1.0 / ((100.0*scalingH) ** (torch.arange(0, channels, 2).float() / channels))
freqsX = torch.outer(tX, freqsX)
freqsY = torch.outer(tY, freqsY)
freqsCisX = torch.polar(torch.ones_like(freqsX), freqsX)
freqsCisY = torch.polar(torch.ones_like(freqsY), freqsY)
freqsCis = torch.cat([freqsCisX, freqsCisY], dim=-1)
freqsCis = freqsCis.view(height, width, channels)
return freqsCis
def rotate(self, q, k):
batchSize, channels, height, width = q.shape
freqsCis = self.createRotationMatrix(height, width, channels).to(q.device)
q = q.permute(0, 2, 3, 1).contiguous()
k = k.permute(0, 2, 3, 1).contiguous()
qRot = q * freqsCis.real - q.roll(shifts=1, dims=-1) * freqsCis.imag
kRot = k * freqsCis.real - k.roll(shifts=1, dims=-1) * freqsCis.imag
return qRot.permute(0, 3, 1, 2), kRot.permute(0, 3, 1, 2)
def forward(self, x):
batchSize, channels, height, width = x.shape
q = self.qProj(x)
k = self.kProj(x)
v = self.vProj(x)
q, k = self.rotate(q, k)
q = q.view(batchSize, self.heads, self.headDim, height * width).transpose(2, 3)
k = k.view(batchSize, self.heads, self.headDim, height * width).transpose(2, 3)
v = v.view(batchSize, self.heads, self.headDim, height * width).transpose(2, 3).contiguous()
q=self.qLayerNorm(q)
k=self.kLayerNorm(k)
#Temporarily converting to bf16 to use Flash Attention v2
with torch.nn.attention.sdpa_kernel(torch.nn.attention.SDPBackend.FLASH_ATTENTION), torch.amp.autocast('cuda',enabled=True,dtype=torch.bfloat16):
attnOutput = torch.nn.functional.scaled_dot_product_attention(q, k, v)
attnOutput = attnOutput.float().transpose(2, 3).contiguous().view(batchSize, channels, height, width)
return self.outProj(attnOutput)
class DiTBlock(torch.nn.Module):
def init(self,channels,heads,conditionC):
super().init()
self.norm1=AdaLN(conditionC,channels)
self.norm2=torch.nn.GroupNorm(1,channels,eps=1e-6)
self.attn=RoPEAttention(channels,heads,8)
class DiT(torch.nn.Module):
"""
Diffusion Transformer (DiT) model.
code
This class implements a Diffusion Transformer, which is a transformer-based architecture
designed for image generation. It applies a series of DiT blocks to process the input,
incorporating time step and condition information.
Args:
channels (int): Number of channels in each transformer block.
nBlocks (int): Number of DiT blocks in the model.
nHeads (int): Number of attention heads
inC (int): Number of input channels.
outC (int): Number of output channels.
conditionC (int): Number of conditioning channels
patchSize (int, optional): Size of patches for patchification. Defaults to 1. Increasing this
will speed up training and lower VRAM requirements, at the expense of generation quality
and potential artifacts. The final convolution layer attempts to mitigate this effect
"""
def __init__(self,channels,nBlocks,inC,outC,conditionC,nHeads=8,patchSize=1):
super().__init__()
self.patchify=torch.nn.PixelUnshuffle(patchSize)
self.inProj=torch.nn.Conv2d(inC*patchSize**2,channels,kernel_size=1)
self.blocks=torch.nn.ModuleList()
for i in range(nBlocks):
self.blocks.append(DiTBlock(channels,nHeads,conditionC))
self.outProj=torch.nn.Conv2d(channels,outC*patchSize**2,kernel_size=1)
self.unpatchify=torch.nn.PixelShuffle(patchSize)
self.finalConv=torch.nn.Conv2d(outC,outC,kernel_size=3,padding='same')
def forward(self,x,condition):
#print
x=self.patchify(x)
#condition=self.patchify(condition)
#print(condition.shape)
x=self.inProj(x)
for block in self.blocks:
x=block(x,condition)
x=self.outProj(x)
x=self.unpatchify(x)
x=self.finalConv(x)
return x
add cross attention, input is torch.Size([16, 4, 32, 32])
To incorporate cross-attention into your existing architecture, you'll need to make some structural enhancements, mainly by adding a mechanism that combines information from two different sources (queries from the main input and keys/values from some other input). This is common in tasks like multi-modal learning or conditioning on external information.
In your context, it sounds like you want to create a mechanism that uses the input (of shape [16, 4, 32, 32]) to attend over another form of input, like conditioning or contextual information. Here's a revised version of your model with cross-attention layers added to the DiTBlock. I'm assuming the condition input will serve as the secondary input over which to perform the cross-attention:
First, you need to modify the RoPEAttention to include cross-attention:
With these changes, you've added a cross-attention layer into the DiTBlock, which attends the main input over a secondary input, given in the form of condition. Adjust condition such that its shape is compatible with your cross-attention logic, typically involving reshaping or projection similar to your primary input.
To effectively incorporate cross-attention, the size of the condition tensor should be compatible with the main input tensor after they've both gone through their respective linear (or convolutional) projections. Specifically, the key aspects to consider for ensuring compatibility in your transformer-based architecture are:
Spatial Dimensions: While the main input to your model is of size [16, 4, 32, 32] (batch size, channels, height, width), the condition tensor should have spatial dimensions that match or can be related to those of the main input, depending on how you model the cross-attention interaction. The spatial dimensions could be the same, or, if necessary, you can perform operations like interpolation or stride-based downsampling to adjust them.
Channel Dimensions: The RoPECrossAttention layer should apply a convolutional or linear projection over the condition that matches the dimensionality of the query/keys being created from the main input. The conditioning's channel dimension should be transformable to match whatever is expected in the forward call to self.qProj and self.kProj in the cross-attention. This typically means when you project key and value (the condition side), they should match the number of channels used for queries.
Here’s a potential way to manage the condition:
Batch Size: Must match the batch size of the main input (16 in this case) because each element in the batch needs its corresponding paired condition information.
Channels: While not strictly necessary to start with the same number, you'll need enough channels in the condition so that after passing through any linear or convolution layers, the resultant channel size can match the key/query size post-projection.
Height and Width: Should align or be transformable to align with the dimensions of the main input (32x32 in this case) after any needed linear or convolutional projections.
Here’s a simple example assuming you have 4 channels in condition, with an eventual intention to use a size [16, 4, 32, 32], possibly processed via a convolution to build compatible keys and values:
python
# condition: starting as something like [16, cond_channels, 32, 32]
condition = torch.randn(16, 4, 32, 32) # Example shape
# This condition will be passed through a projection layer
Before integrating condition into your cross-attention, ensure its final structure after projections (using self.kProj, self.vProj or similar transformations) matches the expected form used within your cross-attention mechanism. This alignment usually involves linear layers to upscale or downscale these tensors to suitable dimensions as you did with the RoPEAttention setup (self.qProj, self.kProj, self.vProj).
condition
condition
condition
Batch Size: Must match the input’s batch size (e.g., 16) because cross-attention processes each item in the batch independently and needs corresponding conditioning information.
Channels: Can differ from the input tensor. You can project these channels to a size compatible with your attention layer through learned weights like linear or convolutional layers.
Spatial Dimensions: Should match [32, 32] in your case to align with the input tensor. If the initial condition tensor has different spatial dimensions, you might need to preprocess it (e.g., by using interpolation, pooling, or strided convolutions).
Here’s a general setup for preparing condition:
python
import torch
# Randomly chosen number of condition channels
condition_channels = 8
batch_size = 16
# Random condition tensor with potentially varying channels
condition = torch.randn(batch_size, condition_channels, 32, 32)
# Example of projecting condition channels to match desired model input channels:
projector = torch.nn.Conv2d(condition_channels, target_channels, kernel_size=1)
condition_projected = projector(condition)
# Now, condition_projected can be used in the cross-attention module
# where target_channels matches what you need for the cross-attention keys/values.
Additional Considerations
Projecting Channel Dimensions: Use a convolution (e.g., with 1x1 kernel) or a linear layer to reshape the condition channels to match your model's key/value needs. This projection aligns the channels to match the effective dimensions needed by the attention mechanism.
Handling Different Spatial Sizes: If the condition tensor originally has different spatial dimensions, you might use spatial transformations:
Feature pooling(e.g., torch.nn.AdaptiveAvgPool2d or max pooling)
Upsampling/Downsampling(e.g., bilinear interpolation using torch.nn.functional.interpolate)
Experimental Tuning: You might experiment with different configurations of condition_channels and transformations to see how they impact model performance and computational efficiency during cross-attention operations.