
def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			None:






						'''simple docstring'''

						_lowercase       :	List[Any]           =   generate_pascal_triangle(_UpperCAmelCase  )
						for row_idx in range(_UpperCAmelCase  ):
												# Print left spaces
												for _ in range(num_rows - row_idx - 1  ):
																		print(end=" "  )
												# Print row values
												for col_idx in range(row_idx + 1  ):
																		if col_idx != row_idx:
																								print(triangle[row_idx][col_idx] ,			end=" "  )
																		else:
																								print(triangle[row_idx][col_idx] ,			end=""  )
												print()



def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			list[list[int]]:






						'''simple docstring'''

						if not isinstance(_UpperCAmelCase ,			_UpperCAmelCase  ):
												raise TypeError("The input value of 'num_rows' should be 'int'"  )

						if num_rows == 0:
												return []
						elif num_rows < 0:
												raise ValueError(
												    "The input value of 'num_rows' should be greater than or equal to 0"  )

						_lowercase       :	list[list[int]]           =   []
						for current_row_idx in range(_UpperCAmelCase  ):
												_lowercase       :	str           =   populate_current_row(_UpperCAmelCase ,			_UpperCAmelCase  )
												triangle.append(_UpperCAmelCase  )
						return triangle



def 		UpperCamelCase     (       _UpperCAmelCase  :   list[list[int]] ,			_UpperCAmelCase  :   int  )   ->			list[int]:






						'''simple docstring'''

						_lowercase       :	Dict           =   [-1] * (current_row_idx + 1)
						# first and last elements of current row are equal to 1
						_lowercase      ,    _lowercase       :	List[str]           =   1, 1
						for current_col_idx in range(1 ,			_UpperCAmelCase  ):
												calculate_current_element(
												    _UpperCAmelCase ,			_UpperCAmelCase ,			_UpperCAmelCase ,			_UpperCAmelCase  )
						return current_row



def 		UpperCamelCase     (       _UpperCAmelCase  :   list[list[int]] ,			_UpperCAmelCase  :   list[int] ,			_UpperCAmelCase  :   int ,			_UpperCAmelCase  :   int ,			)   ->			None:






						'''simple docstring'''

						_lowercase       :	Tuple           =   triangle[current_row_idx - 1][current_col_idx - 1]
						_lowercase       :	Dict           =   triangle[current_row_idx - 1][current_col_idx]
						_lowercase       :	str           =   above_to_left_elt + above_to_right_elt



def 		UpperCamelCase     (       _UpperCAmelCase  :   int  )   ->			list[list[int]]:






						'''simple docstring'''

						if not isinstance(_UpperCAmelCase ,			_UpperCAmelCase  ):
												raise TypeError("The input value of 'num_rows' should be 'int'"  )

						if num_rows == 0:
												return []
						elif num_rows < 0:
												raise ValueError(
												    "The input value of 'num_rows' should be greater than or equal to 0"  )

						_lowercase       :	list[list[int]]           =   [[1]]

						for row_index in range(1 ,			_UpperCAmelCase  ):
												_lowercase       :	Any           =   [0] + result[-1] + [0]
												_lowercase       :	str           =   row_index + 1
												# Calculate the number of distinct elements in a row
												_lowercase       :	Optional[Any]           =   sum(divmod(_UpperCAmelCase ,			2  )  )
												_lowercase       :	Optional[int]           =   [
												    temp_row[i - 1] + temp_row[i] for i in range(1 ,			distinct_elements + 1  )
												]
												_lowercase       :	Dict           =   row_first_half[: (row_index + 1) // 2]
												row_second_half.reverse()
												_lowercase       :	Tuple           =   row_first_half + row_second_half
												result.append(_UpperCAmelCase  )

						return result



def 		UpperCamelCase     (       )   ->			None:






						'''simple docstring'''

						from collections.abc import Callable
						from timeit import timeit

						def benchmark_a_function(_UpperCAmelCase  :   Callable ,			_UpperCAmelCase  :   int  ) -> None:
												_lowercase       :	Any           =   f"""{func.__name__}({value})"""
												_lowercase       :	List[Any]           =   timeit(f"""__main__.{call}""" ,			setup="import __main__"  )
												# print(f"{call:38} = {func(value)} -- {timing:.4f} seconds")
												print(f"""{call:38} -- {timing:.4f} seconds"""  )

						for value in range(15  ):  # (1, 7, 14):
												for func in (generate_pascal_triangle, generate_pascal_triangle_optimized):
																		benchmark_a_function(_UpperCAmelCase ,			_UpperCAmelCase  )
												print()


if __name__ == "__main__":
							import doctest

							doctest.testmod()
							benchmark()






import torch
import torch.nn as nn
from transformers import CLIPConfig, CLIPVisionModel, PreTrainedModel

from ...utils import logging


UpperCamelCase_						:     int	       =							logging.get_logger(__name__)



def 		UpperCamelCase     (       _UpperCAmelCase  :   Optional[int] ,			_UpperCAmelCase  :   Dict  )   ->			Any:






						'''simple docstring'''

						_lowercase       :	List[Any]           =   nn.functional.normalize(_UpperCAmelCase  )
						_lowercase       :	List[str]           =   nn.functional.normalize(_UpperCAmelCase  )
						return torch.mm(_UpperCAmelCase ,			normalized_text_embeds.t()  )




class   __lowercase						(						__snake_case       ):
	_A       =   CLIPConfig

	_A       =   ["CLIPEncoderLayer"]






	def __init__(self				: List[str]      ,	snake_case				: CLIPConfig    ) ->			Optional[int]:
							super().__init__(snake_case    )

							_lowercase       :	Tuple           =   CLIPVisionModel(config.vision_config    )
							_lowercase       :	Any           =   nn.Linear(config.vision_config.hidden_size      ,	config.projection_dim      ,	bias=snake_case    )

							_lowercase       :	int           =   nn.Parameter(torch.ones(17      ,	config.projection_dim    )      ,	requires_grad=snake_case    )
							_lowercase       :	str           =   nn.Parameter(torch.ones(3      ,	config.projection_dim    )      ,	requires_grad=snake_case    )

							_lowercase       :	Any           =   nn.Parameter(torch.ones(17    )      ,	requires_grad=snake_case    )
							_lowercase       :	Dict           =   nn.Parameter(torch.ones(3    )      ,	requires_grad=snake_case    )






	@torch.no_grad()
	def       _a(self				: int      ,	snake_case				: Tuple      ,	snake_case				: Optional[Any]    ) ->			Union[str, Any]:
							_lowercase       :	str           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	List[Any]           =   self.visual_projection(snake_case    )

							# we always cast to float32 as this does not cause significant overhead and is compatible with bfloat16
							_lowercase       :	str           =   cosine_distance(snake_case      ,	self.special_care_embeds    ).cpu().float().numpy()
							_lowercase       :	Optional[int]           =   cosine_distance(snake_case      ,	self.concept_embeds    ).cpu().float().numpy()

							_lowercase       :	List[str]           =   []
							_lowercase       :	int           =   image_embeds.shape[0]
							for i in range(snake_case    ):
													_lowercase       :	int           =   {"special_scores": {}, "special_care": [], "concept_scores": {}, "bad_concepts": []}

													# increase this value to create a stronger `nfsw` filter
													# at the cost of increasing the possibility of filtering benign images
													_lowercase       :	Optional[int]           =   0.0

													for concept_idx in range(len(special_cos_dist[0]    )    ):
																			_lowercase       :	Union[str, Any]           =   special_cos_dist[i][concept_idx]
																			_lowercase       :	Optional[int]           =   self.special_care_embeds_weights[concept_idx].item()
																			_lowercase       :	Optional[int]           =   round(concept_cos - concept_threshold + adjustment      ,	3    )
																			if result_img["special_scores"][concept_idx] > 0:
																									result_img["special_care"].append({concept_idx, result_img["special_scores"][concept_idx]}    )
																									_lowercase       :	Union[str, Any]           =   0.01

													for concept_idx in range(len(cos_dist[0]    )    ):
																			_lowercase       :	Tuple           =   cos_dist[i][concept_idx]
																			_lowercase       :	Union[str, Any]           =   self.concept_embeds_weights[concept_idx].item()
																			_lowercase       :	str           =   round(concept_cos - concept_threshold + adjustment      ,	3    )
																			if result_img["concept_scores"][concept_idx] > 0:
																									result_img["bad_concepts"].append(snake_case    )

													result.append(snake_case    )

							_lowercase       :	Dict           =   [len(res["bad_concepts"]    ) > 0 for res in result]

							return images, has_nsfw_concepts






	@torch.no_grad()
	def       _a(self				: str      ,	snake_case				: torch.FloatTensor      ,	snake_case				: torch.FloatTensor    ) ->			List[str]:
							_lowercase       :	Dict           =   self.vision_model(snake_case    )[1]  # pooled_output
							_lowercase       :	Any           =   self.visual_projection(snake_case    )

							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.special_care_embeds    )
							_lowercase       :	Optional[Any]           =   cosine_distance(snake_case      ,	self.concept_embeds    )

							# increase this value to create a stronger `nsfw` filter
							# at the cost of increasing the possibility of filtering benign images
							_lowercase       :	Optional[int]           =   0.0

							_lowercase       :	Optional[int]           =   special_cos_dist - self.special_care_embeds_weights + adjustment
							# special_scores = special_scores.round(decimals=3)
							_lowercase       :	List[str]           =   torch.any(special_scores > 0      ,	dim=1    )
							_lowercase       :	List[Any]           =   special_care * 0.01
							_lowercase       :	Optional[Any]           =   special_adjustment.unsqueeze(1    ).expand(-1      ,	cos_dist.shape[1]    )

							_lowercase       :	Any           =   (cos_dist - self.concept_embeds_weights) + special_adjustment
							# concept_scores = concept_scores.round(decimals=3)
							_lowercase       :	List[Any]           =   torch.any(concept_scores > 0      ,	dim=1    )

							return images, has_nsfw_concepts




