






from unittest.mock import patch

import pyspark

from datasets.packaged_modules.spark.spark import (
    Spark,
    SparkExamplesIterable,
    _generate_iterable_examples,
)

from ..utils import (
    require_dill_gt_0_3_2,
    require_not_windows,
)

def      lowerCAmelCase__	(    _a       :			Optional[int]  ,      _a       :			Dict    ):
		snake_case_				:							Dict						 =       []
		for part_id in partition_order:
				snake_case_				:							Any						 =       df.where(F'''SPARK_PARTITION_ID() = {part_id}'''    ).collect()
				for row_idx, row in enumerate(_a    ):
						expected_row_ids_and_row_dicts.append((F'''{part_id}_{row_idx}''', row.asDict())    )
		return expected_row_ids_and_row_dicts

@require_not_windows
@require_dill_gt_0_3_2
def      lowerCAmelCase__	(    ):
		snake_case_				:							Optional[Any]						 =       pyspark.sql.SparkSession.builder.master("local[*]"    ).appName("pyspark"    ).getOrCreate()
		snake_case_				:							Tuple						 =       spark.range(1_00    ).repartition(1    )
		snake_case_				:							Optional[int]						 =       Spark(_a    )
		# The id ints will be converted to Pyarrow int64s, so each row will be 8 bytes. Setting a max_shard_size of 16 means
		# that each partition can hold 2 rows.
		spark_builder._repartition_df_if_needed(max_shard_size=16    )
		# Given that the dataframe has 100 rows and each partition has 2 rows, we expect 50 partitions.
		assert spark_builder.df.rdd.getNumPartitions() == 50

@require_not_windows
@require_dill_gt_0_3_2
def      lowerCAmelCase__	(    ):
		snake_case_				:							int						 =       pyspark.sql.SparkSession.builder.master("local[*]"    ).appName("pyspark"    ).getOrCreate()
		snake_case_				:							List[Any]						 =       spark.range(10    ).repartition(2    )
		snake_case_				:							Any						 =       [1, 0]
		snake_case_				:							str						 =       _generate_iterable_examples(_a  ,      _a    )  # Reverse the partitions.
		snake_case_				:							Optional[Any]						 =       _get_expected_row_ids_and_row_dicts_for_partition_order(_a  ,      _a    )

		for i, (row_id, row_dict) in enumerate(generate_fn()    ):
				snake_case_ ,       snake_case_				:							Optional[int]						 =       expected_row_ids_and_row_dicts[i]
				assert row_id == expected_row_id
				assert row_dict == expected_row_dict

@require_not_windows
@require_dill_gt_0_3_2
def      lowerCAmelCase__	(    ):
		snake_case_				:							str						 =       pyspark.sql.SparkSession.builder.master("local[*]"    ).appName("pyspark"    ).getOrCreate()
		snake_case_				:							List[str]						 =       spark.range(10    ).repartition(1    )
		snake_case_				:							Union[str, Any]						 =       SparkExamplesIterable(_a    )
		assert it.n_shards == 1
		for i, (row_id, row_dict) in enumerate(_a    ):
				assert row_id == F'''0_{i}'''
				assert row_dict == {"id": i}

@require_not_windows
@require_dill_gt_0_3_2
def      lowerCAmelCase__	(    ):
		snake_case_				:							str						 =       pyspark.sql.SparkSession.builder.master("local[*]"    ).appName("pyspark"    ).getOrCreate()
		snake_case_				:							Tuple						 =       spark.range(30    ).repartition(3    )
		# Mock the generator so that shuffle reverses the partition indices.
		with patch("numpy.random.Generator"    ) as generator_mock:
				snake_case_				:							str						 =       lambda _a    : x.reverse()
				snake_case_				:							Any						 =       _get_expected_row_ids_and_row_dicts_for_partition_order(_a  ,      [2, 1, 0]    )

				snake_case_				:							List[str]						 =       SparkExamplesIterable(_a    ).shuffle_data_sources(_a    )
				assert shuffled_it.n_shards == 3
				for i, (row_id, row_dict) in enumerate(_a    ):
						snake_case_ ,       snake_case_				:							str						 =       expected_row_ids_and_row_dicts[i]
						assert row_id == expected_row_id
						assert row_dict == expected_row_dict

@require_not_windows
@require_dill_gt_0_3_2
def      lowerCAmelCase__	(    ):
		snake_case_				:							Optional[int]						 =       pyspark.sql.SparkSession.builder.master("local[*]"    ).appName("pyspark"    ).getOrCreate()
		snake_case_				:							str						 =       spark.range(20    ).repartition(4    )

		# Partitions 0 and 2
		snake_case_				:							Optional[Any]						 =       SparkExamplesIterable(_a    ).shard_data_sources(worker_id=0  ,      num_workers=2    )
		assert shard_it_a.n_shards == 2
		snake_case_				:							Any						 =       _get_expected_row_ids_and_row_dicts_for_partition_order(_a  ,      [0, 2]    )
		for i, (row_id, row_dict) in enumerate(_a    ):
				snake_case_ ,       snake_case_				:							Any						 =       expected_row_ids_and_row_dicts_a[i]
				assert row_id == expected_row_id
				assert row_dict == expected_row_dict

		# Partitions 1 and 3
		snake_case_				:							str						 =       SparkExamplesIterable(_a    ).shard_data_sources(worker_id=1  ,      num_workers=2    )
		assert shard_it_a.n_shards == 2
		snake_case_				:							Optional[Any]						 =       _get_expected_row_ids_and_row_dicts_for_partition_order(_a  ,      [1, 3]    )
		for i, (row_id, row_dict) in enumerate(_a    ):
				snake_case_ ,       snake_case_				:							Optional[int]						 =       expected_row_ids_and_row_dicts_a[i]
				assert row_id == expected_row_id
				assert row_dict == expected_row_dict

@require_not_windows
@require_dill_gt_0_3_2
def      lowerCAmelCase__	(    ):
		snake_case_				:							List[Any]						 =       pyspark.sql.SparkSession.builder.master("local[*]"    ).appName("pyspark"    ).getOrCreate()
		snake_case_				:							int						 =       spark.range(1_00    ).repartition(1    )
		snake_case_				:							Union[str, Any]						 =       Spark(_a    )
		# Choose a small max_shard_size for maximum partitioning.
		spark_builder._repartition_df_if_needed(max_shard_size=1    )
		# The new number of partitions should not be greater than the number of rows.
		assert spark_builder.df.rdd.getNumPartitions() == 1_00








import copy
import os
from typing import Union

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


lowercase  :							int			  =    logging.get_logger(__name__)

lowercase  :							Any			  =    {
    '''BAAI/AltCLIP''': '''https://huggingface.co/BAAI/AltCLIP/resolve/main/config.json''',
    # See all AltCLIP models at https://huggingface.co/models?filter=altclip
}




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   int						=					'altclip_text_model'






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=25_0002		,				_SCREAMING_SNAKE_CASE=1024		,				_SCREAMING_SNAKE_CASE=24		,				_SCREAMING_SNAKE_CASE=16		,				_SCREAMING_SNAKE_CASE=4096		,				_SCREAMING_SNAKE_CASE="gelu"		,				_SCREAMING_SNAKE_CASE=0.1		,				_SCREAMING_SNAKE_CASE=0.1		,				_SCREAMING_SNAKE_CASE=514		,				_SCREAMING_SNAKE_CASE=1		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=1e-05		,				_SCREAMING_SNAKE_CASE=1		,				_SCREAMING_SNAKE_CASE=0		,				_SCREAMING_SNAKE_CASE=2		,				_SCREAMING_SNAKE_CASE="absolute"		,				_SCREAMING_SNAKE_CASE=True		,				_SCREAMING_SNAKE_CASE=768		,				**_SCREAMING_SNAKE_CASE		,				) ->				List[str]:
								super().__init__(pad_token_id=_SCREAMING_SNAKE_CASE		,				bos_token_id=_SCREAMING_SNAKE_CASE		,				eos_token_id=_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Optional[Any]						 =       vocab_size
								snake_case_				:							List[str]						 =       hidden_size
								snake_case_				:							Dict						 =       num_hidden_layers
								snake_case_				:							List[str]						 =       num_attention_heads
								snake_case_				:							Optional[int]						 =       hidden_act
								snake_case_				:							Optional[Any]						 =       intermediate_size
								snake_case_				:							List[str]						 =       hidden_dropout_prob
								snake_case_				:							Union[str, Any]						 =       attention_probs_dropout_prob
								snake_case_				:							Optional[Any]						 =       max_position_embeddings
								snake_case_				:							Any						 =       type_vocab_size
								snake_case_				:							int						 =       initializer_range
								snake_case_				:							str						 =       initializer_factor
								snake_case_				:							List[str]						 =       layer_norm_eps
								snake_case_				:							Any						 =       position_embedding_type
								snake_case_				:							Optional[int]						 =       use_cache
								snake_case_				:							int						 =       project_dim




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   List[Any]						=					'altclip_vision_model'






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=768		,				_SCREAMING_SNAKE_CASE=3072		,				_SCREAMING_SNAKE_CASE=512		,				_SCREAMING_SNAKE_CASE=12		,				_SCREAMING_SNAKE_CASE=12		,				_SCREAMING_SNAKE_CASE=3		,				_SCREAMING_SNAKE_CASE=224		,				_SCREAMING_SNAKE_CASE=32		,				_SCREAMING_SNAKE_CASE="quick_gelu"		,				_SCREAMING_SNAKE_CASE=1e-5		,				_SCREAMING_SNAKE_CASE=0.0		,				_SCREAMING_SNAKE_CASE=0.02		,				_SCREAMING_SNAKE_CASE=1.0		,				**_SCREAMING_SNAKE_CASE		,				) ->				Optional[Any]:
								super().__init__(**_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Tuple						 =       hidden_size
								snake_case_				:							Dict						 =       intermediate_size
								snake_case_				:							Optional[int]						 =       projection_dim
								snake_case_				:							int						 =       num_hidden_layers
								snake_case_				:							Union[str, Any]						 =       num_attention_heads
								snake_case_				:							int						 =       num_channels
								snake_case_				:							Optional[int]						 =       patch_size
								snake_case_				:							Dict						 =       image_size
								snake_case_				:							Tuple						 =       initializer_range
								snake_case_				:							Optional[Any]						 =       initializer_factor
								snake_case_				:							Any						 =       attention_dropout
								snake_case_				:							Tuple						 =       layer_norm_eps
								snake_case_				:							int						 =       hidden_act






						@classmethod
						def       _lowerCAmelCase       (	cls		,				_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				"PretrainedConfig":
								cls._set_token_in_kwargs(_SCREAMING_SNAKE_CASE				)

								snake_case_ ,       snake_case_				:							str						 =       cls.get_config_dict(_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)

								# get the vision config dict if we are loading from AltCLIPConfig
								if config_dict.get("model_type"				) == "altclip":
										snake_case_				:							List[Any]						 =       config_dict["vision_config"]

								if "model_type" in config_dict and hasattr(cls		,				"model_type"				) and config_dict["model_type"] != cls.model_type:
										logger.warning(
										    f'''You are using a model of type {config_dict['model_type']} to instantiate a model of type '''
										    f'''{cls.model_type}. This is not supported for all configurations of models and can yield errors.'''				)

								return cls.from_dict(_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				)




class 		UpperCAmelCase_						(	SCREAMING_SNAKE_CASE__					):


						'''simple docstring'''




						A     :   str						=					'altclip'
						A     :   Dict						=					True






						def __init__(	self		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE=None		,				_SCREAMING_SNAKE_CASE=768		,				_SCREAMING_SNAKE_CASE=2.6592		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[int]:
								# If `_config_dict` exist, we use them for the backward compatibility.
								# We pop out these 2 attributes before calling `super().__init__` to avoid them being saved (which causes a lot
								# of confusion!).
								snake_case_				:							Optional[Any]						 =       kwargs.pop("text_config_dict"		,				_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Dict						 =       kwargs.pop("vision_config_dict"		,				_SCREAMING_SNAKE_CASE				)

								super().__init__(**_SCREAMING_SNAKE_CASE				)

								# Instead of simply assigning `[text|vision]_config_dict` to `[text|vision]_config`, we use the values in
								# `[text|vision]_config_dict` to update the values in `[text|vision]_config`. The values should be same in most
								# cases, but we don't want to break anything regarding `_config_dict` that existed before commit `8827e1b2`.
								if text_config_dict is not None:
										if text_config is None:
												snake_case_				:							Any						 =       {}

										# This is the complete result when using `text_config_dict`.
										snake_case_				:							str						 =       AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE				).to_dict()

										# Give a warning if the values exist in both `_text_config_dict` and `text_config` but being different.
										for key, value in _text_config_dict.items():
												if key in text_config and value != text_config[key] and key not in ["transformers_version"]:
														# If specified in `text_config_dict`
														if key in text_config_dict:
																snake_case_				:							Optional[Any]						 =       (
																    f'''`{key}` is found in both `text_config_dict` and `text_config` but with different values. '''
																    f'''The value `text_config_dict["{key}"]` will be used instead.'''
																)
														# If inferred from default argument values (just to be super careful)
														else:
																snake_case_				:							Dict						 =       (
																    f'''`text_config_dict` is provided which will be used to initialize `AltCLIPTextConfig`. The '''
																    f'''value `text_config["{key}"]` will be overriden.'''
																)
														logger.warning(_SCREAMING_SNAKE_CASE				)

            # Update all values in `text_config` with the ones in `_text_config_dict`.
										text_config.update(_text_config_dict				)

								if vision_config_dict is not None:
										if vision_config is None:
												snake_case_				:							str						 =       {}

										# This is the complete result when using `vision_config_dict`.
										snake_case_				:							Optional[Any]						 =       AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE				).to_dict()
										# convert keys to string instead of integer
										if "id2label" in _vision_config_dict:
												snake_case_				:							Any						 =       {
												    str(_SCREAMING_SNAKE_CASE				): value for key, value in _vision_config_dict["id2label"].items()
												}

										# Give a warning if the values exist in both `_vision_config_dict` and `vision_config` but being different.
										for key, value in _vision_config_dict.items():
												if key in vision_config and value != vision_config[key] and key not in ["transformers_version"]:
														# If specified in `vision_config_dict`
														if key in vision_config_dict:
																snake_case_				:							Dict						 =       (
																    f'''`{key}` is found in both `vision_config_dict` and `vision_config` but with different '''
																    f'''values. The value `vision_config_dict["{key}"]` will be used instead.'''
																)
														# If inferred from default argument values (just to be super careful)
														else:
																snake_case_				:							Optional[Any]						 =       (
																    f'''`vision_config_dict` is provided which will be used to initialize `AltCLIPVisionConfig`. '''
																    f'''The value `vision_config["{key}"]` will be overriden.'''
																)
														logger.warning(_SCREAMING_SNAKE_CASE				)

            # Update all values in `vision_config` with the ones in `_vision_config_dict`.
										vision_config.update(_vision_config_dict				)

								if text_config is None:
										snake_case_				:							Tuple						 =       {}
										logger.info("`text_config` is `None`. Initializing the `AltCLIPTextConfig` with default values."				)

								if vision_config is None:
										snake_case_				:							Optional[Any]						 =       {}
										logger.info("`vision_config` is `None`. initializing the `AltCLIPVisionConfig` with default values."				)

								snake_case_				:							List[Any]						 =       AltCLIPTextConfig(**_SCREAMING_SNAKE_CASE				)
								snake_case_				:							Union[str, Any]						 =       AltCLIPVisionConfig(**_SCREAMING_SNAKE_CASE				)

								snake_case_				:							Optional[int]						 =       projection_dim
								snake_case_				:							Tuple						 =       logit_scale_init_value
								snake_case_				:							List[Any]						 =       1.0






						@classmethod
						def       _lowerCAmelCase       (	cls		,				_SCREAMING_SNAKE_CASE		,				_SCREAMING_SNAKE_CASE		,				**_SCREAMING_SNAKE_CASE				) ->				Optional[Any]:
								return cls(text_config=text_config.to_dict()		,				vision_config=vision_config.to_dict()		,				**_SCREAMING_SNAKE_CASE				)






						def       _lowerCAmelCase       (	self				) ->				List[str]:
								snake_case_				:							Any						 =       copy.deepcopy(self.__dict__				)
								snake_case_				:							Union[str, Any]						 =       self.text_config.to_dict()
								snake_case_				:							List[Any]						 =       self.vision_config.to_dict()
								snake_case_				:							Tuple						 =       self.__class__.model_type
								return output
