

"""simple docstring"""






from typing import Optional, Tuple, Union

import flax
import flax.linen as nn
import jax
import jax.numpy as jnp
from flax.core.frozen_dict import FrozenDict

from ..configuration_utils import ConfigMixin, flax_register_to_config
from ..utils import BaseOutput
from .embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
from .modeling_flax_utils import FlaxModelMixin
from .unet_ad_blocks_flax import (
    FlaxCrossAttnDownBlockaD,
    FlaxDownBlockaD,
    FlaxUNetMidBlockaDCrossAttn,
)
@flax.struct.dataclass
class        _lowercase					(     __UpperCAmelCase     ):
     _lowerCamelCase     =       42
     _lowerCamelCase     =       42


class        _lowercase					(     nn.Module     ):
     _lowerCamelCase     =       42
     _lowerCamelCase     =       (16, 32, 96, 256)
     _lowerCamelCase     =       jnp.floataa







     def 	lowerCAmelCase__    (      self       ):
      __magic_name__     =      nn.Conv(
          self.block_out_channels[0] ,						kernel_size=(3, 3) ,						padding=((1, 1), (1, 1)) ,						dtype=self.dtype ,						)

      __magic_name__     =      []
      for i in range(len(self.block_out_channels       ) - 1       ):
       __magic_name__     =      self.block_out_channels[i]
       __magic_name__     =      self.block_out_channels[i + 1]
       __magic_name__     =      nn.Conv(
           UpperCamelCase_ ,						kernel_size=(3, 3) ,						padding=((1, 1), (1, 1)) ,						dtype=self.dtype ,						)
       blocks.append(UpperCamelCase_       )
       __magic_name__     =      nn.Conv(
           UpperCamelCase_ ,						kernel_size=(3, 3) ,						strides=(2, 2) ,						padding=((1, 1), (1, 1)) ,						dtype=self.dtype ,						)
       blocks.append(UpperCamelCase_       )
      __magic_name__     =      blocks

      __magic_name__     =      nn.Conv(
          self.conditioning_embedding_channels ,						kernel_size=(3, 3) ,						padding=((1, 1), (1, 1)) ,						kernel_init=nn.initializers.zeros_init() ,						bias_init=nn.initializers.zeros_init() ,						dtype=self.dtype ,						)







     def __call__(      self ,						UpperCamelCase_       ):
      __magic_name__     =      self.conv_in(UpperCamelCase_       )
      __magic_name__     =      nn.silu(UpperCamelCase_       )

      for block in self.blocks:
       __magic_name__     =      block(UpperCamelCase_       )
       __magic_name__     =      nn.silu(UpperCamelCase_       )

      __magic_name__     =      self.conv_out(UpperCamelCase_       )

      return embedding


@flax_register_to_config
class        _lowercase					(     nn.Module   , __UpperCAmelCase   , __UpperCAmelCase     ):
     _lowerCamelCase     =       32
     _lowerCamelCase     =       4
     _lowerCamelCase     =       (
         '''CrossAttnDownBlock2D''',
         '''CrossAttnDownBlock2D''',
         '''CrossAttnDownBlock2D''',
         '''DownBlock2D''',
     )
     _lowerCamelCase     =       False
     _lowerCamelCase     =       (320, 640, 1280, 1280)
     _lowerCamelCase     =       2
     _lowerCamelCase     =       8
     _lowerCamelCase     =       None
     _lowerCamelCase     =       1280
     _lowerCamelCase     =       0.0
     _lowerCamelCase     =       False
     _lowerCamelCase     =       jnp.floataa
     _lowerCamelCase     =       True
     _lowerCamelCase     =       0
     _lowerCamelCase     =       '''rgb'''
     _lowerCamelCase     =       (16, 32, 96, 256)







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_       ):
      # init input tensors
      __magic_name__     =      (1, self.in_channels, self.sample_size, self.sample_size)
      __magic_name__     =      jnp.zeros(UpperCamelCase_ ,						dtype=jnp.floataa       )
      __magic_name__     =      jnp.ones((1,) ,						dtype=jnp.intaa       )
      __magic_name__     =      jnp.zeros((1, 1, self.cross_attention_dim) ,						dtype=jnp.floataa       )
      __magic_name__     =      (1, 3, self.sample_size * 8, self.sample_size * 8)
      __magic_name__     =      jnp.zeros(UpperCamelCase_ ,						dtype=jnp.floataa       )

      __magic_name__   ,						__magic_name__     =      jax.random.split(UpperCamelCase_       )
      __magic_name__     =      {'''params''': params_rng, '''dropout''': dropout_rng}

      return self.init(UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_       )["params"]







     def 	lowerCAmelCase__    (      self       ):
      __magic_name__     =      self.block_out_channels
      __magic_name__     =      block_out_channels[0] * 4

      # If `num_attention_heads` is not defined (which is the case for most models)
      # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
      # The reason for this behavior is to correct for incorrectly named variables that were introduced
      # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
      # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
      # which is why we correct for the naming here.
      __magic_name__     =      self.num_attention_heads or self.attention_head_dim

      # input
      __magic_name__     =      nn.Conv(
          block_out_channels[0] ,						kernel_size=(3, 3) ,						strides=(1, 1) ,						padding=((1, 1), (1, 1)) ,						dtype=self.dtype ,						)

      # time
      __magic_name__     =      FlaxTimesteps(
          block_out_channels[0] ,						flip_sin_to_cos=self.flip_sin_to_cos ,						freq_shift=self.config.freq_shift       )
      __magic_name__     =      FlaxTimestepEmbedding(UpperCamelCase_ ,						dtype=self.dtype       )

      __magic_name__     =      FlaxControlNetConditioningEmbedding(
          conditioning_embedding_channels=block_out_channels[0] ,						block_out_channels=self.conditioning_embedding_out_channels ,						)

      __magic_name__     =      self.only_cross_attention
      if isinstance(UpperCamelCase_ ,						UpperCamelCase_       ):
       __magic_name__     =      (only_cross_attention,) * len(self.down_block_types       )

      if isinstance(UpperCamelCase_ ,						UpperCamelCase_       ):
       __magic_name__     =      (num_attention_heads,) * len(self.down_block_types       )

      # down
      __magic_name__     =      []
      __magic_name__     =      []

      __magic_name__     =      block_out_channels[0]

      __magic_name__     =      nn.Conv(
          UpperCamelCase_ ,						kernel_size=(1, 1) ,						padding='''VALID''' ,						kernel_init=nn.initializers.zeros_init() ,						bias_init=nn.initializers.zeros_init() ,						dtype=self.dtype ,						)
      controlnet_down_blocks.append(UpperCamelCase_       )

      for i, down_block_type in enumerate(self.down_block_types       ):
       __magic_name__     =      output_channel
       __magic_name__     =      block_out_channels[i]
       __magic_name__     =      i == len(UpperCamelCase_       ) - 1

       if down_block_type == "CrossAttnDownBlock2D":
        __magic_name__     =      FlaxCrossAttnDownBlockaD(
            in_channels=UpperCamelCase_ ,						out_channels=UpperCamelCase_ ,						dropout=self.dropout ,						num_layers=self.layers_per_block ,						num_attention_heads=num_attention_heads[i] ,						add_downsample=not is_final_block ,						use_linear_projection=self.use_linear_projection ,						only_cross_attention=only_cross_attention[i] ,						dtype=self.dtype ,						)
       else:
        __magic_name__     =      FlaxDownBlockaD(
            in_channels=UpperCamelCase_ ,						out_channels=UpperCamelCase_ ,						dropout=self.dropout ,						num_layers=self.layers_per_block ,						add_downsample=not is_final_block ,						dtype=self.dtype ,						)

       down_blocks.append(UpperCamelCase_       )

       for _ in range(self.layers_per_block       ):
        __magic_name__     =      nn.Conv(
            UpperCamelCase_ ,						kernel_size=(1, 1) ,						padding='''VALID''' ,						kernel_init=nn.initializers.zeros_init() ,						bias_init=nn.initializers.zeros_init() ,						dtype=self.dtype ,						)
        controlnet_down_blocks.append(UpperCamelCase_       )

       if not is_final_block:
        __magic_name__     =      nn.Conv(
            UpperCamelCase_ ,						kernel_size=(1, 1) ,						padding='''VALID''' ,						kernel_init=nn.initializers.zeros_init() ,						bias_init=nn.initializers.zeros_init() ,						dtype=self.dtype ,						)
        controlnet_down_blocks.append(UpperCamelCase_       )

      __magic_name__     =      down_blocks
      __magic_name__     =      controlnet_down_blocks

      # mid
      __magic_name__     =      block_out_channels[-1]
      __magic_name__     =      FlaxUNetMidBlockaDCrossAttn(
          in_channels=UpperCamelCase_ ,						dropout=self.dropout ,						num_attention_heads=num_attention_heads[-1] ,						use_linear_projection=self.use_linear_projection ,						dtype=self.dtype ,						)

      __magic_name__     =      nn.Conv(
          UpperCamelCase_ ,						kernel_size=(1, 1) ,						padding='''VALID''' ,						kernel_init=nn.initializers.zeros_init() ,						bias_init=nn.initializers.zeros_init() ,						dtype=self.dtype ,						)







     def __call__(      self ,						UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_ = 1.0 ,						UpperCamelCase_ = True ,						UpperCamelCase_ = False ,						):
      __magic_name__     =      self.controlnet_conditioning_channel_order
      if channel_order == "bgr":
       __magic_name__     =      jnp.flip(UpperCamelCase_ ,						axis=1       )

      # 1. time
      if not isinstance(UpperCamelCase_ ,						jnp.ndarray       ):
       __magic_name__     =      jnp.array([timesteps] ,						dtype=jnp.intaa       )
      elif isinstance(UpperCamelCase_ ,						jnp.ndarray       ) and len(timesteps.shape       ) == 0:
       __magic_name__     =      timesteps.astype(dtype=jnp.floataa       )
       __magic_name__     =      jnp.expand_dims(UpperCamelCase_ ,						0       )

      __magic_name__     =      self.time_proj(UpperCamelCase_       )
      __magic_name__     =      self.time_embedding(UpperCamelCase_       )

      # 2. pre-process
      __magic_name__     =      jnp.transpose(UpperCamelCase_ ,						(0, 2, 3, 1)       )
      __magic_name__     =      self.conv_in(UpperCamelCase_       )

      __magic_name__     =      jnp.transpose(UpperCamelCase_ ,						(0, 2, 3, 1)       )
      __magic_name__     =      self.controlnet_cond_embedding(UpperCamelCase_       )
      sample += controlnet_cond

      # 3. down
      __magic_name__     =      (sample,)
      for down_block in self.down_blocks:
       if isinstance(UpperCamelCase_ ,						UpperCamelCase_       ):
        __magic_name__   ,						__magic_name__     =      down_block(UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_ ,						deterministic=not train       )
       else:
        __magic_name__   ,						__magic_name__     =      down_block(UpperCamelCase_ ,						UpperCamelCase_ ,						deterministic=not train       )
       down_block_res_samples += res_samples

      # 4. mid
      __magic_name__     =      self.mid_block(UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_ ,						deterministic=not train       )

      # 5. contronet blocks
      __magic_name__     =      ()
      for down_block_res_sample, controlnet_block in zip(UpperCamelCase_ ,						self.controlnet_down_blocks       ):
       __magic_name__     =      controlnet_block(UpperCamelCase_       )
       controlnet_down_block_res_samples += (down_block_res_sample,)

      __magic_name__     =      controlnet_down_block_res_samples

      __magic_name__     =      self.controlnet_mid_block(UpperCamelCase_       )

      # 6. scaling
      __magic_name__     =      [sample * conditioning_scale for sample in down_block_res_samples]
      mid_block_res_sample *= conditioning_scale

      if not return_dict:
       return (down_block_res_samples, mid_block_res_sample)

      return FlaxControlNetOutput(
          down_block_res_samples=UpperCamelCase_ ,						mid_block_res_sample=UpperCamelCase_       )




"""simple docstring"""






from __future__ import annotations

from sys import maxsize
from typing import Generic, TypeVar

__lowerCamelCase										=		TypeVar("T")





def 	lowercase      (   __UpperCamelCase						) ->      int:
 return (position - 1) // 2





def 	lowercase      (   __UpperCamelCase						) ->      int:
 return (2 * position) + 1





def 	lowercase      (   __UpperCamelCase						) ->      int:
 return (2 * position) + 2
class        _lowercase					(     Generic[T]     ):







     def __init__(      self       ):
      __magic_name__     =      []
      __magic_name__     =      {}
      __magic_name__     =      0







     def __len__(      self       ):
      return self.elements







     def __repr__(      self       ):
      return str(self.heap       )







     def 	lowerCAmelCase__    (      self       ):
      # Check if the priority queue is empty
      return self.elements == 0







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_ ,						UpperCamelCase_       ):
      # Add an element with given priority to the queue
      self.heap.append((elem, weight)       )
      __magic_name__     =      self.elements
      self.elements += 1
      self._bubble_up(UpperCamelCase_       )







     def 	lowerCAmelCase__    (      self       ):
      # Remove and return the element with lowest weight (highest priority)
      if self.elements > 1:
       self._swap_nodes(0 ,						self.elements - 1       )
      __magic_name__   ,						__magic_name__     =      self.heap.pop()
      del self.position_map[elem]
      self.elements -= 1
      if self.elements > 0:
       __magic_name__   ,						__magic_name__     =      self.heap[0]
       self._bubble_down(UpperCamelCase_       )
      return elem







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_ ,						UpperCamelCase_       ):
      # Update the weight of the given key
      __magic_name__     =      self.position_map[elem]
      __magic_name__     =      (elem, weight)
      if position > 0:
       __magic_name__     =      get_parent_position(UpperCamelCase_       )
       __magic_name__   ,						__magic_name__     =      self.heap[parent_position]
       if parent_weight > weight:
        self._bubble_up(UpperCamelCase_       )
       else:
        self._bubble_down(UpperCamelCase_       )
      else:
       self._bubble_down(UpperCamelCase_       )







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_       ):
      # Place a node at the proper position (upward movement) [to be used internally
      # only]
      __magic_name__     =      self.position_map[elem]
      if curr_pos == 0:
       return None
      __magic_name__     =      get_parent_position(UpperCamelCase_       )
      __magic_name__   ,						__magic_name__     =      self.heap[curr_pos]
      __magic_name__   ,						__magic_name__     =      self.heap[parent_position]
      if parent_weight > weight:
       self._swap_nodes(UpperCamelCase_ ,						UpperCamelCase_       )
       return self._bubble_up(UpperCamelCase_       )
      return None







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_       ):
      # Place a node at the proper position (downward movement) [to be used
      # internally only]
      __magic_name__     =      self.position_map[elem]
      __magic_name__   ,						__magic_name__     =      self.heap[curr_pos]
      __magic_name__     =      get_child_left_position(UpperCamelCase_       )
      __magic_name__     =      get_child_right_position(UpperCamelCase_       )
      if child_left_position < self.elements and child_right_position < self.elements:
       __magic_name__   ,						__magic_name__     =      self.heap[child_left_position]
       __magic_name__   ,						__magic_name__     =      self.heap[child_right_position]
       if child_right_weight < child_left_weight and child_right_weight < weight:
        self._swap_nodes(UpperCamelCase_ ,						UpperCamelCase_       )
        return self._bubble_down(UpperCamelCase_       )
      if child_left_position < self.elements:
       __magic_name__   ,						__magic_name__     =      self.heap[child_left_position]
       if child_left_weight < weight:
        self._swap_nodes(UpperCamelCase_ ,						UpperCamelCase_       )
        return self._bubble_down(UpperCamelCase_       )
      else:
       return None
      if child_right_position < self.elements:
       __magic_name__   ,						__magic_name__     =      self.heap[child_right_position]
       if child_right_weight < weight:
        self._swap_nodes(UpperCamelCase_ ,						UpperCamelCase_       )
        return self._bubble_down(UpperCamelCase_       )
      return None







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_ ,						UpperCamelCase_       ):
      # Swap the nodes at the given positions
      __magic_name__     =      self.heap[nodea_pos][0]
      __magic_name__     =      self.heap[nodea_pos][0]
      __magic_name__   ,						__magic_name__     =      (
          self.heap[nodea_pos],
          self.heap[nodea_pos],
      )
      __magic_name__     =      nodea_pos
      __magic_name__     =      nodea_pos


class        _lowercase					(     Generic[T]     ):







     def __init__(      self       ):
      __magic_name__     =      {}
      __magic_name__     =      0







     def __repr__(      self       ):
      return str(self.connections       )







     def __len__(      self       ):
      return self.nodes







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_       ):
      # Add a node in the graph if it is not in the graph
      if node not in self.connections:
       __magic_name__     =      {}
       self.nodes += 1







     def 	lowerCAmelCase__    (      self ,						UpperCamelCase_ ,						UpperCamelCase_ ,						UpperCamelCase_       ):
      # Add an edge between 2 nodes in the graph
      self.add_node(UpperCamelCase_       )
      self.add_node(UpperCamelCase_       )
      __magic_name__     =      weight
      __magic_name__     =      weight





def 	lowercase      (   __UpperCamelCase      ,   ) ->      tuple[dict[T, int], dict[T, T | None]]:
 __magic_name__     =      {node: maxsize for node in graph.connections}
 __magic_name__     =      {node: None for node in graph.connections}

 __magic_name__     =      MinPriorityQueue()
 for node, weight in dist.items():
  priority_queue.push(__UpperCamelCase      ,   __UpperCamelCase						)

 if priority_queue.is_empty():
  return dist, parent

 # initialization
 __magic_name__     =      priority_queue.extract_min()
 __magic_name__     =      0
 for neighbour in graph.connections[node]:
  if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
   __magic_name__     =      dist[node] + graph.connections[node][neighbour]
   priority_queue.update_key(__UpperCamelCase      ,   dist[neighbour]						)
   __magic_name__     =      node

    # running prim's algorithm
 while not priority_queue.is_empty():
  __magic_name__     =      priority_queue.extract_min()
  for neighbour in graph.connections[node]:
   if dist[neighbour] > dist[node] + graph.connections[node][neighbour]:
    __magic_name__     =      dist[node] + graph.connections[node][neighbour]
    priority_queue.update_key(__UpperCamelCase      ,   dist[neighbour]						)
    __magic_name__     =      node
 return dist, parent

