






from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowerCamelCase	:							str				=logging.get_logger(__name__)

lowerCamelCase	:							Union[str, Any]				={
    "s-JoL/Open-Llama-V1": "https://huggingface.co/s-JoL/Open-Llama-V1/blob/main/config.json",
}





class 			__a  (    UpperCAmelCase__       ):
 _lowerCAmelCase       :       List[str]        = '''open-llama'''







 def __init__(		self					:   int							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=10_00_00							,   SCREAMING_SNAKE_CASE					:   Any=40_96							,   SCREAMING_SNAKE_CASE					:   Any=1_10_08							,   SCREAMING_SNAKE_CASE					:   Optional[Any]=32							,   SCREAMING_SNAKE_CASE					:   Dict=32							,   SCREAMING_SNAKE_CASE					:   str="silu"							,   SCREAMING_SNAKE_CASE					:   Optional[int]=20_48							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=0.0_2							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=1e-6							,   SCREAMING_SNAKE_CASE					:   Optional[Any]=True							,   SCREAMING_SNAKE_CASE					:   List[str]=0							,   SCREAMING_SNAKE_CASE					:   List[str]=1							,   SCREAMING_SNAKE_CASE					:   str=2							,   SCREAMING_SNAKE_CASE					:   int=False							,   SCREAMING_SNAKE_CASE					:   Any=True							,   SCREAMING_SNAKE_CASE					:   Union[str, Any]=0.1							,   SCREAMING_SNAKE_CASE					:   Optional[int]=0.1							,   SCREAMING_SNAKE_CASE					:   str=True							,   SCREAMING_SNAKE_CASE					:   Any=True							,   SCREAMING_SNAKE_CASE					:   List[str]=None							,   **SCREAMING_SNAKE_CASE					:   Optional[Any]							,   ):


      '''simple docstring'''






      UpperCamelCase__			:   Union[str, Any]       				=  vocab_size
      UpperCamelCase__			:   Optional[Any]       				=  max_position_embeddings
      UpperCamelCase__			:   List[Any]       				=  hidden_size
      UpperCamelCase__			:   Any       				=  intermediate_size
      UpperCamelCase__			:   List[Any]       				=  num_hidden_layers
      UpperCamelCase__			:   int       				=  num_attention_heads
      UpperCamelCase__			:   Optional[int]       				=  hidden_act
      UpperCamelCase__			:   str       				=  initializer_range
      UpperCamelCase__			:   Any       				=  rms_norm_eps
      UpperCamelCase__			:   Any       				=  use_cache
      UpperCamelCase__			:   Dict       				=  kwargs.pop(
          "use_memorry_efficient_attention"							,   __lowercase						)
      UpperCamelCase__			:   Tuple       				=  hidden_dropout_prob
      UpperCamelCase__			:   Union[str, Any]       				=  attention_dropout_prob
      UpperCamelCase__			:   Dict       				=  use_stable_embedding
      UpperCamelCase__			:   str       				=  shared_input_output_embedding
      UpperCamelCase__			:   Dict       				=  rope_scaling
      self._rope_scaling_validation()

      super().__init__(
          pad_token_id=__lowercase							,   bos_token_id=__lowercase							,   eos_token_id=__lowercase							,   tie_word_embeddings=__lowercase							,   **__lowercase							,   )







 def 					__lowercase					(		self					:   Any						):


      '''simple docstring'''






      if self.rope_scaling is None:
           return

      if not isinstance(self.rope_scaling							,   __lowercase						) or len(self.rope_scaling						) != 2:
           raise ValueError(
               "`rope_scaling` must be a dictionary with with two fields, `name` and `factor`, "
               F'got {self.rope_scaling}'						)
      UpperCamelCase__			:   List[str]       				=  self.rope_scaling.get("type"							,   __lowercase						)
      UpperCamelCase__			:   List[Any]       				=  self.rope_scaling.get("factor"							,   __lowercase						)
      if rope_scaling_type is None or rope_scaling_type not in ["linear", "dynamic"]:
           raise ValueError(
               F'`rope_scaling`\'s name field must be one of [\'linear\', \'dynamic\'], got {rope_scaling_type}'						)
      if rope_scaling_factor is None or not isinstance(__lowercase							,   __lowercase						) or rope_scaling_factor <= 1.0:
           raise ValueError(F'`rope_scaling`\'s factor field must be an float > 1, got {rope_scaling_factor}'						)





from collections import defaultdict
from typing import Optional

from ..image_utils import load_image
from ..utils import (
    add_end_docstrings,
    is_torch_available,
    logging,
    requires_backends,
)
from .base import PIPELINE_INIT_ARGS, ChunkPipeline


if is_torch_available():
		import torch

		from ..models.auto.modeling_auto import MODEL_FOR_MASK_GENERATION_MAPPING

lowercase__				:     Dict 		=						logging.get_logger(__name__)
@add_end_docstrings(UpperCAmelCase__			)
class 		UpperCAmelCase   (				UpperCAmelCase__			):







						'''simple docstring'''





						def __init__(						self							:     Optional[Any]       ,	**__lowercase							:     Union[str, Any]						):






							"""simple docstring"""






							super().__init__(**__lowercase						)
							requires_backends(self       ,	"vision"						)
							requires_backends(self       ,	"torch"						)

							if self.framework != "pt":
								raise ValueError(f"The {self.__class__} is only available in PyTorch."						)

							self.check_model_type(__lowercase						)






						def        snake_case__						(						self							:     Optional[int]       ,	**__lowercase							:     Optional[Any]						):






							"""simple docstring"""






							snake_case_		    =     {}
							snake_case_		    =     {}
							snake_case_		    =     {}
							# preprocess args
							if "points_per_batch" in kwargs:
								snake_case_		    =     kwargs["points_per_batch"]
							if "points_per_crop" in kwargs:
								snake_case_		    =     kwargs["points_per_crop"]
							if "crops_n_layers" in kwargs:
								snake_case_		    =     kwargs["crops_n_layers"]
							if "crop_overlap_ratio" in kwargs:
								snake_case_		    =     kwargs["crop_overlap_ratio"]
							if "crop_n_points_downscale_factor" in kwargs:
								snake_case_		    =     kwargs["crop_n_points_downscale_factor"]
							# postprocess args
							if "pred_iou_thresh" in kwargs:
								snake_case_		    =     kwargs["pred_iou_thresh"]
							if "stability_score_offset" in kwargs:
								snake_case_		    =     kwargs["stability_score_offset"]
							if "mask_threshold" in kwargs:
								snake_case_		    =     kwargs["mask_threshold"]
							if "stability_score_thresh" in kwargs:
								snake_case_		    =     kwargs["stability_score_thresh"]
							if "crops_nms_thresh" in kwargs:
								snake_case_		    =     kwargs["crops_nms_thresh"]
							if "output_rle_mask" in kwargs:
								snake_case_		    =     kwargs["output_rle_mask"]
							if "output_bboxes_mask" in kwargs:
								snake_case_		    =     kwargs["output_bboxes_mask"]
							return preprocess_kwargs, forward_params, postprocess_kwargs






						def __call__(						self							:     Optional[int]       ,	__lowercase							:     List[str]       ,	*__lowercase							:     Optional[Any]       ,	__lowercase							:     Dict=None       ,	__lowercase							:     List[str]=None       ,	**__lowercase							:     Optional[Any]						):






							"""simple docstring"""






							return super().__call__(__lowercase       ,	*__lowercase       ,	num_workers=__lowercase       ,	batch_size=__lowercase       ,	**__lowercase						)






						def        snake_case__						(						self							:     str       ,	__lowercase							:     int       ,	__lowercase							:     List[str]=64       ,	__lowercase							:     int = 0       ,	__lowercase							:     float = 5_12 / 15_00       ,	__lowercase							:     Optional[int] = 32       ,	__lowercase							:     Optional[int] = 1       ,	):






							"""simple docstring"""






							snake_case_		    =     load_image(__lowercase						)
							snake_case_		    =     self.image_processor.size["longest_edge"]
							snake_case_    ,      snake_case_    ,      snake_case_    ,      snake_case_		    =     self.image_processor.generate_crop_boxes(
							    __lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase						)
							snake_case_		    =     self.image_processor(images=__lowercase       ,	return_tensors="pt"						)

							with self.device_placement():
								if self.framework == "pt":
									snake_case_		    =     self.get_inference_context()
									with inference_context():
										snake_case_		    =     self._ensure_tensor_on_device(__lowercase       ,	device=self.device						)
										snake_case_		    =     self.model.get_image_embeddings(model_inputs.pop("pixel_values"						)						)
										snake_case_		    =     image_embeddings

							snake_case_		    =     grid_points.shape[1]
							snake_case_		    =     points_per_batch if points_per_batch is not None else n_points

							if points_per_batch <= 0:
								raise ValueError(
								    "Cannot have points_per_batch<=0. Must be >=1 to returned batched outputs. "
								    "To return all points at once, set points_per_batch to None"						)

							for i in range(0       ,	__lowercase       ,	__lowercase						):
								snake_case_		    =     grid_points[:, i : i + points_per_batch, :, :]
								snake_case_		    =     input_labels[:, i : i + points_per_batch]
								snake_case_		    =     i == n_points - points_per_batch
								yield {
								    "input_points": batched_points,
								    "input_labels": labels,
								    "input_boxes": crop_boxes,
								    "is_last": is_last,
								    **model_inputs,
								}






						def        snake_case__						(						self							:     Tuple       ,	__lowercase							:     Union[str, Any]       ,	__lowercase							:     Union[str, Any]=0.88       ,	__lowercase							:     Union[str, Any]=0.95       ,	__lowercase							:     int=0       ,	__lowercase							:     int=1       ,	):






							"""simple docstring"""






							snake_case_		    =     model_inputs.pop("input_boxes"						)
							snake_case_		    =     model_inputs.pop("is_last"						)
							snake_case_		    =     model_inputs.pop("original_sizes"						).tolist()
							snake_case_		    =     model_inputs.pop("reshaped_input_sizes"						).tolist()

							snake_case_		    =     self.model(**__lowercase						)

							# post processing happens here in order to avoid CPU GPU copies of ALL the masks
							snake_case_		    =     model_outputs["pred_masks"]
							snake_case_		    =     self.image_processor.post_process_masks(
							    __lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	binarize=__lowercase						)
							snake_case_		    =     model_outputs["iou_scores"]
							snake_case_    ,      snake_case_    ,      snake_case_		    =     self.image_processor.filter_masks(
							    masks[0]       ,	iou_scores[0]       ,	original_sizes[0]       ,	input_boxes[0]       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase       ,	)
							return {
							    "masks": masks,
							    "is_last": is_last,
							    "boxes": boxes,
							    "iou_scores": iou_scores,
							}






						def        snake_case__						(						self							:     str       ,	__lowercase							:     Any       ,	__lowercase							:     Optional[int]=False       ,	__lowercase							:     int=False       ,	__lowercase							:     List[str]=0.7       ,	):






							"""simple docstring"""






							snake_case_		    =     []
							snake_case_		    =     []
							snake_case_		    =     []
							for model_output in model_outputs:
								all_scores.append(model_output.pop("iou_scores"						)						)
								all_masks.extend(model_output.pop("masks"						)						)
								all_boxes.append(model_output.pop("boxes"						)						)

							snake_case_		    =     torch.cat(__lowercase						)
							snake_case_		    =     torch.cat(__lowercase						)
							snake_case_    ,      snake_case_    ,      snake_case_    ,      snake_case_		    =     self.image_processor.post_process_for_mask_generation(
							    __lowercase       ,	__lowercase       ,	__lowercase       ,	__lowercase						)

							snake_case_		    =     defaultdict(__lowercase						)
							for output in model_outputs:
								for k, v in output.items():
									extra[k].append(__lowercase						)

							snake_case_		    =     {}
							if output_rle_mask:
								snake_case_		    =     rle_mask

							if output_bboxes_mask:
								snake_case_		    =     bounding_boxes

							return {"masks": output_masks, "scores": iou_scores, **optional, **extra}
