

from abc import ABC, abstractmethod
from typing import List, Optional







class 			lowercase    (	lowercase_      ):




    def __init__( self	):
           # test for the above condition
           self.test()




    def    a							( self	):
           snake_case_          =   0
           snake_case_          =   False
           while not completed:
                  if counter == 1:
                         self.reset()
                  snake_case_          =   self.advance()
                  if not self.does_advance(snake_case	):
                         raise Exception(
                             'Custom Constraint is not defined correctly. self.does_advance(self.advance()) must be true.'	)

                  snake_case_    ,   snake_case_    ,   snake_case_          =   self.update(snake_case	)
                  counter += 1

                  if counter > 1_0000:
                         raise Exception('update() does not fulfill the constraint.'	)

           if self.remaining() != 0:
                  raise Exception('Custom Constraint is not defined correctly.'	)




    @abstractmethod
    def    a							( self	):
           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''	)




    @abstractmethod
    def    a							( self				,       snake_case	):
           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''	)




    @abstractmethod
    def    a							( self				,       snake_case	):
           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''	)




    @abstractmethod
    def    a							( self	):
           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''	)




    @abstractmethod
    def    a							( self	):
           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''	)




    @abstractmethod
    def    a							( self				,       snake_case=False	):
           raise NotImplementedError(
               F'''{self.__class__} is an abstract class. Only classes inheriting this class can be called.'''	)







class 			lowercase    (	lowercase_      ):




    def __init__( self				,       snake_case	):
           super(snake_case				,       self	).__init__()

           if not isinstance(snake_case				,       snake_case	) or len(snake_case	) == 0:
                  raise ValueError(F'''`token_ids` has to be a non-empty list, but is {token_ids}.'''	)
           if any((not isinstance(snake_case				,       snake_case	) or token_id < 0) for token_id in token_ids	):
                  raise ValueError(F'''Each list in `token_ids` has to be a list of positive integers, but is {token_ids}.'''	)

           snake_case_          =   token_ids

           snake_case_          =   len(self.token_ids	)
           snake_case_          =   -1  # the index of the currently fulfilled step
           snake_case_          =   False




    def    a							( self	):
           if self.completed:
                  return None
           return self.token_ids[self.fulfilled_idx + 1]




    def    a							( self				,       snake_case	):
           if not isinstance(snake_case				,       snake_case	):
                  raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(snake_case	)}'''	)

           if self.completed:
                  return False

           return token_id == self.token_ids[self.fulfilled_idx + 1]




    def    a							( self				,       snake_case	):
           if not isinstance(snake_case				,       snake_case	):
                  raise ValueError(F'''`token_id` has to be an `int`, but is {token_id} of type {type(snake_case	)}'''	)

           snake_case_          =   False
           snake_case_          =   False
           snake_case_          =   False

           if self.does_advance(snake_case	):
                  self.fulfilled_idx += 1
                  snake_case_          =   True
                  if self.fulfilled_idx == (self.seqlen - 1):
                         snake_case_          =   True
                  snake_case_          =   completed
           else:
                  # failed to make progress.
                  snake_case_          =   True
                  self.reset()
           return stepped, completed, reset




    def    a							( self	):
           snake_case_          =   False
           snake_case_          =   0




    def    a							( self	):
           return self.seqlen - (self.fulfilled_idx + 1)




    def    a							( self				,       snake_case=False	):
           snake_case_          =   PhrasalConstraint(self.token_ids	)

           if stateful:
                  snake_case_          =   self.seqlen
                  snake_case_          =   self.fulfilled_idx
                  snake_case_          =   self.completed

           return new_constraint







class 			lowercase    :




    def __init__( self				,       snake_case				,       snake_case=True	):
           snake_case_          =   max([len(snake_case	) for one in nested_token_ids]	)

           snake_case_          =   {}
           for token_ids in nested_token_ids:
                  snake_case_          =   root
                  for tidx, token_id in enumerate(snake_case	):
                         if token_id not in level:
                                snake_case_          =   {}

                         snake_case_          =   level[token_id]

           if no_subsets and self.has_subsets(snake_case				,       snake_case	):
                  raise ValueError(
                      'Each list in `nested_token_ids` can\'t be a complete subset of another list, but is'
                      F''' {nested_token_ids}.'''	)

           snake_case_          =   root




    def    a							( self				,       snake_case	):
           snake_case_          =   self.trie

           for current_token in current_seq:
                  snake_case_          =   start[current_token]

           snake_case_          =   list(start.keys()	)

           return next_tokens




    def    a							( self				,       snake_case	):
           snake_case_          =   self.next_tokens(snake_case	)

           return len(snake_case	) == 0




    def    a							( self				,       snake_case	):
           snake_case_          =   list(root.values()	)
           if len(snake_case	) == 0:
                  return 1
           else:
                  return sum([self.count_leaves(snake_case	) for nn in next_nodes]	)




    def    a							( self				,       snake_case				,       snake_case	):
           snake_case_          =   self.count_leaves(snake_case	)
           return len(snake_case	) != leaf_count







class 			lowercase    (	lowercase_      ):




    def __init__( self				,       snake_case	):
           super(snake_case				,       self	).__init__()

           if not isinstance(snake_case				,       snake_case	) or len(snake_case	) == 0:
                  raise ValueError(F'''`nested_token_ids` has to be a non-empty list, but is {nested_token_ids}.'''	)
           if any(not isinstance(snake_case				,       snake_case	) for token_ids in nested_token_ids	):
                  raise ValueError(F'''`nested_token_ids` has to be a list of lists, but is {nested_token_ids}.'''	)
           if any(
               any((not isinstance(snake_case				,       snake_case	) or token_id < 0) for token_id in token_ids	)
               for token_ids in nested_token_ids	):
                  raise ValueError(
                      F'''Each list in `nested_token_ids` has to be a list of positive integers, but is {nested_token_ids}.'''	)

           snake_case_          =   DisjunctiveTrie(snake_case	)
           snake_case_          =   nested_token_ids

           snake_case_          =   self.trie.max_height
           snake_case_          =   []
           snake_case_          =   False




    def    a							( self	):
           snake_case_          =   self.trie.next_tokens(self.current_seq	)

           if len(snake_case	) == 0:
                  return None
           else:
                  return token_list




    def    a							( self				,       snake_case	):
           if not isinstance(snake_case				,       snake_case	):
                  raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case	)}'''	)

           snake_case_          =   self.trie.next_tokens(self.current_seq	)

           return token_id in next_tokens




    def    a							( self				,       snake_case	):
           if not isinstance(snake_case				,       snake_case	):
                  raise ValueError(F'''`token_id` is supposed to be type `int`, but is {token_id} of type {type(snake_case	)}'''	)

           snake_case_          =   False
           snake_case_          =   False
           snake_case_          =   False

           if self.does_advance(snake_case	):
                  self.current_seq.append(snake_case	)
                  snake_case_          =   True
           else:
                  snake_case_          =   True
                  self.reset()

           snake_case_          =   self.trie.reached_leaf(self.current_seq	)
           snake_case_          =   completed

           return stepped, completed, reset




    def    a							( self	):
           snake_case_          =   False
           snake_case_          =   []




    def    a							( self	):
           if self.completed:
                  # since this can be completed without reaching max height
                  return 0
           else:
                  return self.seqlen - len(self.current_seq	)




    def    a							( self				,       snake_case=False	):
           snake_case_          =   DisjunctiveConstraint(self.token_ids	)

           if stateful:
                  snake_case_          =   self.seqlen
                  snake_case_          =   self.current_seq
                  snake_case_          =   self.completed

           return new_constraint







class 			lowercase    :




    def __init__( self				,       snake_case	):
           snake_case_          =   constraints

           # max # of steps required to fulfill a given constraint
           snake_case_          =   max([c.seqlen for c in constraints]	)
           snake_case_          =   len(snake_case	)
           snake_case_          =   False

           self.init_state()




    def    a							( self	):
           snake_case_          =   []
           snake_case_          =   None
           snake_case_          =   [constraint.copy(stateful=snake_case	) for constraint in self.constraints]




    def    a							( self	):
           snake_case_          =   0
           if self.inprogress_constraint:
                  # extra points for having a constraint mid-fulfilled
                  add += self.max_seqlen - self.inprogress_constraint.remaining()

           return (len(self.complete_constraints	) * self.max_seqlen) + add




    def    a							( self	):
           snake_case_          =   []
           if self.inprogress_constraint is None:
                  for constraint in self.pending_constraints:  # "pending" == "unfulfilled yet"
                         snake_case_          =   constraint.advance()
                         if isinstance(snake_case				,       snake_case	):
                                token_list.append(snake_case	)
                         elif isinstance(snake_case				,       snake_case	):
                                token_list.extend(snake_case	)
           else:
                  snake_case_          =   self.inprogress_constraint.advance()
                  if isinstance(snake_case				,       snake_case	):
                         token_list.append(snake_case	)
                  elif isinstance(snake_case				,       snake_case	):
                         token_list.extend(snake_case	)

           if len(snake_case	) == 0:
                  return None
           else:
                  return token_list




    def    a							( self				,       snake_case	):
           self.init_state()

           if token_ids is not None:
                  for token in token_ids:
                         # completes or steps **one** constraint
                         snake_case_    ,   snake_case_          =   self.add(snake_case	)

                         # the entire list of constraints are fulfilled
                         if self.completed:
                                break




    def    a							( self				,       snake_case	):
           if not isinstance(snake_case				,       snake_case	):
                  raise ValueError(F'''`token_id` should be an `int`, but is `{token_id}`.'''	)

           snake_case_    ,   snake_case_          =   False, False

           if self.completed:
                  snake_case_          =   True
                  snake_case_          =   False
                  return complete, stepped

           if self.inprogress_constraint is not None:
                  # In the middle of fulfilling a constraint. If the `token_id` *does* makes an incremental progress to current
                  # job, simply update the state

                  snake_case_    ,   snake_case_    ,   snake_case_          =   self.inprogress_constraint.update(snake_case	)
                  if reset:
                         # 1. If the next token breaks the progress, then we must restart.
                         #     e.g. constraint = "I love pies" and sequence so far is "I love" but `token_id` == "books".

                         #     But that doesn't mean we self.init_state(), since we only reset the state for this particular
                         #     constraint, not the full list of constraints.

                         self.pending_constraints.append(self.inprogress_constraint.copy(stateful=snake_case	)	)
                         snake_case_          =   None

                  if complete:
                         # 2. If the next token completes the constraint, move it to completed list, set
                         #     inprogress to None. If there are no pending constraints either, then this full list of constraints
                         #     is complete.

                         self.complete_constraints.append(self.inprogress_constraint	)
                         snake_case_          =   None

                         if len(self.pending_constraints	) == 0:
                                # we're done!
                                snake_case_          =   True

           else:
                  # Not in the middle of fulfilling a constraint. So does this `token_id` helps us step towards any of our list
                  # of constraints?

                  for cidx, pending_constraint in enumerate(self.pending_constraints	):
                         if pending_constraint.does_advance(snake_case	):
                                snake_case_    ,   snake_case_    ,   snake_case_          =   pending_constraint.update(snake_case	)

                                if not stepped:
                                       raise Exception(
                                           '`constraint.update(token_id)` is not yielding incremental progress, '
                                           'even though `constraint.does_advance(token_id)` is true.'	)

                                if complete:
                                       self.complete_constraints.append(snake_case	)
                                       snake_case_          =   None

                                if not complete and stepped:
                                       snake_case_          =   pending_constraint

                                if complete or stepped:
                                       # If we made any progress at all, then it's at least not a "pending constraint".

                                       snake_case_          =   (
                                           self.pending_constraints[:cidx] + self.pending_constraints[cidx + 1 :]
                                       )

                                       if len(self.pending_constraints	) == 0 and self.inprogress_constraint is None:
                                              # If there's no longer any pending after this and no inprogress either, then we must be
                                              # complete.

                                              snake_case_          =   True

                                       break  # prevent accidentally stepping through multiple constraints with just one token.

           return complete, stepped




    def    a							( self				,       snake_case=True	):
           snake_case_          =   ConstraintListState(self.constraints	)  # we actually never though self.constraints objects
           # throughout this process. So it's at initialization state.

           if stateful:
                  snake_case_          =   [
                      constraint.copy(stateful=snake_case	) for constraint in self.complete_constraints
                  ]
                  if self.inprogress_constraint is not None:
                         snake_case_          =   self.inprogress_constraint.copy(stateful=snake_case	)
                  snake_case_          =   [constraint.copy() for constraint in self.pending_constraints]

           return new_state







import gc
import unittest

from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline
from diffusers.utils import is_flax_available, load_image, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
					import jax
					import jax.numpy as jnp
					from flax.jax_utils import replicate
					from flax.training.common_utils import shard







@slow
@require_flax
class 			lowercase    (	unittest.TestCase      ):




				def    a							( self	):
											# clean up the VRAM after each test
											super().tearDown()
											gc.collect()




				def    a							( self	):
											snake_case_    ,   snake_case_          =   FlaxControlNetModel.from_pretrained(
											    'lllyasviel/sd-controlnet-canny'				,       from_pt=snake_case				,       dtype=jnp.bfloataa	)
											snake_case_    ,   snake_case_          =   FlaxStableDiffusionControlNetPipeline.from_pretrained(
											    'runwayml/stable-diffusion-v1-5'				,       controlnet=snake_case				,       from_pt=snake_case				,       dtype=jnp.bfloataa	)
											snake_case_          =   controlnet_params

											snake_case_          =   'bird'
											snake_case_          =   jax.device_count()
											snake_case_          =   pipe.prepare_text_inputs([prompts] * num_samples	)

											snake_case_          =   load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png'	)
											snake_case_          =   pipe.prepare_image_inputs([canny_image] * num_samples	)

											snake_case_          =   jax.random.PRNGKey(0	)
											snake_case_          =   jax.random.split(snake_case				,       jax.device_count()	)

											snake_case_          =   replicate(snake_case	)
											snake_case_          =   shard(snake_case	)
											snake_case_          =   shard(snake_case	)

											snake_case_          =   pipe(
											    prompt_ids=snake_case				,       image=snake_case				,       params=snake_case				,       prng_seed=snake_case				,       num_inference_steps=50				,       jit=snake_case				,       ).images
											assert images.shape == (jax.device_count(), 1, 768, 512, 3)

											snake_case_          =   images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]	)
											snake_case_          =   images[0, 253:256, 253:256, -1]

											snake_case_          =   jnp.asarray(jax.device_get(image_slice.flatten()	)	)
											snake_case_          =   jnp.array(
											    [0.16_79_69, 0.11_66_99, 0.08_15_43, 0.15_42_97, 0.13_28_12, 0.10_88_87, 0.16_99_22, 0.16_99_22, 0.20_50_78]	)
											print(F'''output_slice: {output_slice}'''	)
											assert jnp.abs(output_slice - expected_slice	).max() < 1e-2




				def    a							( self	):
											snake_case_    ,   snake_case_          =   FlaxControlNetModel.from_pretrained(
											    'lllyasviel/sd-controlnet-openpose'				,       from_pt=snake_case				,       dtype=jnp.bfloataa	)
											snake_case_    ,   snake_case_          =   FlaxStableDiffusionControlNetPipeline.from_pretrained(
											    'runwayml/stable-diffusion-v1-5'				,       controlnet=snake_case				,       from_pt=snake_case				,       dtype=jnp.bfloataa	)
											snake_case_          =   controlnet_params

											snake_case_          =   'Chef in the kitchen'
											snake_case_          =   jax.device_count()
											snake_case_          =   pipe.prepare_text_inputs([prompts] * num_samples	)

											snake_case_          =   load_image(
											    'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png'	)
											snake_case_          =   pipe.prepare_image_inputs([pose_image] * num_samples	)

											snake_case_          =   jax.random.PRNGKey(0	)
											snake_case_          =   jax.random.split(snake_case				,       jax.device_count()	)

											snake_case_          =   replicate(snake_case	)
											snake_case_          =   shard(snake_case	)
											snake_case_          =   shard(snake_case	)

											snake_case_          =   pipe(
											    prompt_ids=snake_case				,       image=snake_case				,       params=snake_case				,       prng_seed=snake_case				,       num_inference_steps=50				,       jit=snake_case				,       ).images
											assert images.shape == (jax.device_count(), 1, 768, 512, 3)

											snake_case_          =   images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]	)
											snake_case_          =   images[0, 253:256, 253:256, -1]

											snake_case_          =   jnp.asarray(jax.device_get(image_slice.flatten()	)	)
											snake_case_          =   jnp.array(
											    [[0.27_14_84, 0.26_17_19, 0.27_53_91, 0.27_73_44, 0.27_92_97, 0.29_10_16, 0.29_49_22, 0.30_27_34, 0.30_27_34]]	)
											print(F'''output_slice: {output_slice}'''	)
											assert jnp.abs(output_slice - expected_slice	).max() < 1e-2




