//  [python]
def __call__(
        self,
        attn: Attention,
        hidden_states: torch.FloatTensor,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        temb: Optional[torch.FloatTensor] = None,
        scale: float = 1.0,
    ) -> torch.Tensor:
        # Automatically recognize the resolution of the current attention layer and resize the masks accordingly
        downscale_factor = self.mask_resoltuion // hidden_states.shape[1]

        mask = None
        for factor in self.scale_factors:
            if downscale_factor == factor**2:
                shape = (self.shape[0] // factor, self.shape[1] // factor)
                mask = F.interpolate(self.mask, shape, mode="bicubic")  # B, 1, H, W
                break
        if mask is None:
            return self.default_processor(attn, hidden_states, encoder_hidden_states, attention_mask, temb, scale)

        # STARTS HERE
        residual = hidden_states
        # Save the input hidden_states for later use
        input_hidden_states = hidden_states

        # ================================================== #
        # =============== SELF ATTENTION 1 ================= #
        # ================================================== #

        if attn.spatial_norm is not None:
            hidden_states = attn.spatial_norm(hidden_states, temb)

        input_ndim = hidden_states.ndim

        if input_ndim == 4:
            batch_size, channel, height, width = hidden_states.shape
            hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)

        batch_size, sequence_length, _ = (
            hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
        )
        attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)

        if attn.group_norm is not None:
            hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)

        query = attn.to_q(hidden_states)

        if encoder_hidden_states is None:
            encoder_hidden_states = hidden_states
        elif attn.norm_cross:
            encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)

        key = attn.to_k(encoder_hidden_states)
        value = attn.to_v(encoder_hidden_states)

        query = attn.head_to_batch_dim(query)
        key = attn.head_to_batch_dim(key)
        value = attn.head_to_batch_dim(value)

        # self_attention_probs = attn.get_attention_scores(query, key, attention_mask) # We can't use post-softmax attention scores in this case
        self_attention_scores = get_attention_scores(
            attn, query, key, attention_mask
        )  # The custom function returns pre-softmax probabilities
        self_attention_probs = self_attention_scores.softmax(
            dim=-1
        )  # Manually compute the probabilities here, the scores will be reused in the second part of PAIntA
        self_attention_probs = self_attention_probs.to(query.dtype)

        hidden_states = torch.bmm(self_attention_probs, value)
        hidden_states = attn.batch_to_head_dim(hidden_states)

        # linear proj
        hidden_states = attn.to_out[0](hidden_states)
        # dropout
        hidden_states = attn.to_out[1](hidden_states)

        # x = x + self.attn1(self.norm1(x))

        if input_ndim == 4:
            hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)

        if attn.residual_connection:  # So many residuals everywhere
            hidden_states = hidden_states + residual

        self_attention_output_hidden_states = hidden_states / attn.rescale_output_factor

        # ================================================== #
        # ============ BasicTransformerBlock =============== #
        # ================================================== #
        # We use a hack by running the code from the BasicTransformerBlock that is between Self and Cross attentions here
        # The other option would've been modifying the BasicTransformerBlock and adding this functionality here.
        # I assumed that changing the BasicTransformerBlock would have been a bigger deal and decided to use this hack isntead.

        # The SelfAttention block recieves the normalized latents from the BasicTransformerBlock,
        # But the residual of the output is the non-normalized version.
        # Therefore we unnormalize the input hidden state here
        unnormalized_input_hidden_states = (
            input_hidden_states + self.transformer_block.norm1.bias
        ) * self.transformer_block.norm1.weight

        # TODO: return if neccessary
        # if self.use_ada_layer_norm_zero:
        #     attn_output = gate_msa.unsqueeze(1) * attn_output
        # elif self.use_ada_layer_norm_single:
        #     attn_output = gate_msa * attn_output

        transformer_hidden_states = self_attention_output_hidden_states + unnormalized_input_hidden_states
        if transformer_hidden_states.ndim == 4:
            transformer_hidden_states = transformer_hidden_states.squeeze(1)

        # TODO: return if neccessary
        # 2.5 GLIGEN Control
        # if gligen_kwargs is not None:
        #     transformer_hidden_states = self.fuser(transformer_hidden_states, gligen_kwargs["objs"])
        # NOTE: we experimented with using GLIGEN and HDPainter together, the results were not that great

        # 3. Cross-Attention
        if self.transformer_block.use_ada_layer_norm:
            # transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states, timestep)
            raise NotImplementedError()
        elif self.transformer_block.use_ada_layer_norm_zero or self.transformer_block.use_layer_norm:
            transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states)
        elif self.transformer_block.use_ada_layer_norm_single:
            # For PixArt norm2 isn't applied here:
            # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
            transformer_norm_hidden_states = transformer_hidden_states
        elif self.transformer_block.use_ada_layer_norm_continuous:
            # transformer_norm_hidden_states = self.transformer_block.norm2(transformer_hidden_states, added_cond_kwargs["pooled_text_emb"])
            raise NotImplementedError()
        else:
            raise ValueError("Incorrect norm")

        if self.transformer_block.pos_embed is not None and self.transformer_block.use_ada_layer_norm_single is False:
            transformer_norm_hidden_states = self.transformer_block.pos_embed(transformer_norm_hidden_states)

        # ================================================== #
        # ================= CROSS ATTENTION ================ #
        # ================================================== #

        # We do an initial pass of the CrossAttention up to obtaining the similarity matrix here.
        # The similarity matrix is used to obtain scaling coefficients for the attention matrix of the self attention
        # We reuse the previously computed self-attention matrix, and only repeat the steps after the softmax

        cross_attention_input_hidden_states = (
            transformer_norm_hidden_states  # Renaming the variable for the sake of readability
        )

        # TODO: check if classifier_free_guidance is being used before splitting here
        if self.do_classifier_free_guidance:
            # Our scaling coefficients depend only on the conditional part, so we split the inputs
            (
                _cross_attention_input_hidden_states_unconditional,
                cross_attention_input_hidden_states_conditional,
            ) = cross_attention_input_hidden_states.chunk(2)

            # Same split for the encoder_hidden_states i.e. the tokens
            # Since the SelfAttention processors don't get the encoder states as input, we inject them into the processor in the begining.
            _encoder_hidden_states_unconditional, encoder_hidden_states_conditional = self.encoder_hidden_states.chunk(
                2
            )
        else:
            cross_attention_input_hidden_states_conditional = cross_attention_input_hidden_states
            encoder_hidden_states_conditional = self.encoder_hidden_states.chunk(2)

        # Rename the variables for the sake of readability
        # The part below is the beginning of the __call__ function of the following CrossAttention layer
        cross_attention_hidden_states = cross_attention_input_hidden_states_conditional
        cross_attention_encoder_hidden_states = encoder_hidden_states_conditional

        attn2 = self.transformer_block.attn2

        if attn2.spatial_norm is not None:
            cross_attention_hidden_states = attn2.spatial_norm(cross_attention_hidden_states, temb)

        input_ndim = cross_attention_hidden_states.ndim

        if input_ndim == 4:
            batch_size, channel, height, width = cross_attention_hidden_states.shape
            cross_attention_hidden_states = cross_attention_hidden_states.view(
                batch_size, channel, height * width
            ).transpose(1, 2)

        (
            batch_size,
            sequence_length,
            _,
        ) = cross_attention_hidden_states.shape  # It is definitely a cross attention, so no need for an if block
        # TODO: change the attention_mask here
        attention_mask = attn2.prepare_attention_mask(
            None, sequence_length, batch_size
        )  # I assume the attention mask is the same...

        if attn2.group_norm is not None:
            cross_attention_hidden_states = attn2.group_norm(cross_attention_hidden_states.transpose(1, 2)).transpose(
                1, 2
            )

        query2 = attn2.to_q(cross_attention_hidden_states)

        if attn2.norm_cross:
            cross_attention_encoder_hidden_states = attn2.norm_encoder_hidden_states(
                cross_attention_encoder_hidden_states
            )

        key2 = attn2.to_k(cross_attention_encoder_hidden_states)
        query2 = attn2.head_to_batch_dim(query2)
        key2 = attn2.head_to_batch_dim(key2)

        cross_attention_probs = attn2.get_attention_scores(query2, key2, attention_mask)

        # CrossAttention ends here, the remaining part is not used

        # ================================================== #
        # ================ SELF ATTENTION 2 ================ #
        # ================================================== #
        # DEJA VU!

        mask = (mask > 0.5).to(self_attention_output_hidden_states.dtype)
        m = mask.to(self_attention_output_hidden_states.device)
        # m = rearrange(m, 'b c h w -> b (h w) c').contiguous()
        m = m.permute(0, 2, 3, 1).reshape((m.shape[0], -1, m.shape[1])).contiguous()  # B HW 1
        m = torch.matmul(m, m.permute(0, 2, 1)) + (1 - m)

        # # Compute scaling coefficients for the similarity matrix
        # # Select the cross attention values for the correct tokens only!
        # cross_attention_probs = cross_attention_probs.mean(dim = 0)
        # cross_attention_probs = cross_attention_probs[:, self.token_idx].sum(dim=1)

        # cross_attention_probs = cross_attention_probs.reshape(shape)
        # gaussian_smoothing = GaussianSmoothing(channels=1, kernel_size=3, sigma=0.5, dim=2).to(self_attention_output_hidden_states.device)
        # cross_attention_probs = gaussian_smoothing(cross_attention_probs.unsqueeze(0))[0] # optional smoothing
        # cross_attention_probs = cross_attention_probs.reshape(-1)
        # cross_attention_probs = ((cross_attention_probs - torch.median(cross_attention_probs.ravel())) / torch.max(cross_attention_probs.ravel())).clip(0, 1)

        # c = (1 - m) * cross_attention_probs.reshape(1, 1, -1) + m # PAIntA scaling coefficients

        # Compute scaling coefficients for the similarity matrix
        # Select the cross attention values for the correct tokens only!

        batch_size, dims, channels = cross_attention_probs.shape
        batch_size = batch_size // attn.heads
        cross_attention_probs = cross_attention_probs.reshape((batch_size, attn.heads, dims, channels))  # B, D, HW, T

        cross_attention_probs = cross_attention_probs.mean(dim=1)  # B, HW, T
        cross_attention_probs = cross_attention_probs[..., self.token_idx].sum(dim=-1)  # B, HW
        cross_attention_probs = cross_attention_probs.reshape((batch_size,) + shape)  # , B, H, W

        gaussian_smoothing = GaussianSmoothing(channels=1, kernel_size=3, sigma=0.5, dim=2).to(
            self_attention_output_hidden_states.device
        )
        cross_attention_probs = gaussian_smoothing(cross_attention_probs[:, None])[:, 0]  # optional smoothing B, H, W

        # Median normalization
        cross_attention_probs = cross_attention_probs.reshape(batch_size, -1)  # B, HW
        cross_attention_probs = (
            cross_attention_probs - cross_attention_probs.median(dim=-1, keepdim=True).values
        ) / cross_attention_probs.max(dim=-1, keepdim=True).values
        cross_attention_probs = cross_attention_probs.clip(0, 1)

        c = (1 - m) * cross_attention_probs.reshape(batch_size, 1, -1) + m
        c = c.repeat_interleave(attn.heads, 0)  # BD, HW
        if self.do_classifier_free_guidance:
            c = torch.cat([c, c])  # 2BD, HW

        # Rescaling the original self-attention matrix
        self_attention_scores_rescaled = self_attention_scores * c
        self_attention_probs_rescaled = self_attention_scores_rescaled.softmax(dim=-1)

        # Continuing the self attention normally using the new matrix
        hidden_states = torch.bmm(self_attention_probs_rescaled, value)
        hidden_states = attn.batch_to_head_dim(hidden_states)

        # linear proj
        hidden_states = attn.to_out[0](hidden_states)
        # dropout
        hidden_states = attn.to_out[1](hidden_states)

        if input_ndim == 4:
            hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)

        if attn.residual_connection:
            hidden_states = hidden_states + input_hidden_states

        hidden_states = hidden_states / attn.rescale_output_factor

        return hidden_states