
'''simple docstring'''

from typing import Optional

import torch
import torch.utils.checkpoint
from torch import Tensor, nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


_UpperCAmelCase :   str			    =	logging.get_logger(__name__)

# General docstring
_UpperCAmelCase :   List[Any]			    =	"""ResNetConfig"""

# Base docstring
_UpperCAmelCase :   Dict			    =	"""microsoft/resnet-50"""
_UpperCAmelCase :   Tuple			    =	[1, 2048, 7, 7]

# Image classification docstring
_UpperCAmelCase :   Union[str, Any]			    =	"""microsoft/resnet-50"""
_UpperCAmelCase :   Tuple			    =	"""tiger cat"""

_UpperCAmelCase :   Any			    =	[
    """microsoft/resnet-50""",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]

class       UpperCAmelCase					(       nn.Module			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case	,       _snake_case	,       _snake_case = 3	,       _snake_case = 1	,       _snake_case = "relu"  )					->     Optional[Any]:
				super().__init__()
				_UpperCamelCase							:			Dict     =   nn.Convad(
				    a__	,       a__	,       kernel_size=a__	,       stride=a__	,       padding=kernel_size // 2	,       bias=a__  )
				_UpperCamelCase							:			str     =   nn.BatchNormad(a__  )
				_UpperCamelCase							:			List[Any]     =   ACTaFN[activation] if activation is not None else nn.Identity()




		def _lowercase	(     self	,       _snake_case  )					->     Tensor:
				_UpperCamelCase							:			int     =   self.convolution(a__  )
				_UpperCamelCase							:			Any     =   self.normalization(a__  )
				_UpperCamelCase							:			Optional[int]     =   self.activation(a__  )
				return hidden_state







class       UpperCAmelCase					(       nn.Module			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case  )					->     str:
				super().__init__()
				_UpperCamelCase							:			Dict     =   ResNetConvLayer(
				    config.num_channels	,       config.embedding_size	,       kernel_size=7	,       stride=2	,       activation=config.hidden_act  )
				_UpperCamelCase							:			List[Any]     =   nn.MaxPoolad(kernel_size=3	,       stride=2	,       padding=1  )
				_UpperCamelCase							:			Tuple     =   config.num_channels




		def _lowercase	(     self	,       _snake_case  )					->     Tensor:
				_UpperCamelCase							:			Optional[Any]     =   pixel_values.shape[1]
				if num_channels != self.num_channels:
						raise ValueError(
						    '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.'''  )
				_UpperCamelCase							:			Optional[int]     =   self.embedder(a__  )
				_UpperCamelCase							:			int     =   self.pooler(a__  )
				return embedding







class       UpperCAmelCase					(       nn.Module			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case	,       _snake_case	,       _snake_case = 2  )					->     Optional[Any]:
				super().__init__()
				_UpperCamelCase							:			Optional[Any]     =   nn.Convad(a__	,       a__	,       kernel_size=1	,       stride=a__	,       bias=a__  )
				_UpperCamelCase							:			Tuple     =   nn.BatchNormad(a__  )




		def _lowercase	(     self	,       _snake_case  )					->     Tensor:
				_UpperCamelCase							:			Any     =   self.convolution(a__  )
				_UpperCamelCase							:			str     =   self.normalization(a__  )
				return hidden_state







class       UpperCAmelCase					(       nn.Module			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case	,       _snake_case	,       _snake_case = 1	,       _snake_case = "relu"  )					->     List[str]:
				super().__init__()
				_UpperCamelCase							:			int     =   in_channels != out_channels or stride != 1
				_UpperCamelCase							:			Tuple     =   (
				    ResNetShortCut(a__	,       a__	,       stride=a__  ) if should_apply_shortcut else nn.Identity()
				)
				_UpperCamelCase							:			Optional[int]     =   nn.Sequential(
				    ResNetConvLayer(a__	,       a__	,       stride=a__  )	,       ResNetConvLayer(a__	,       a__	,       activation=a__  )	,       )
				_UpperCamelCase							:			Union[str, Any]     =   ACTaFN[activation]




		def _lowercase	(     self	,       _snake_case  )					->     Union[str, Any]:
				_UpperCamelCase							:			int     =   hidden_state
				_UpperCamelCase							:			Dict     =   self.layer(a__  )
				_UpperCamelCase							:			Any     =   self.shortcut(a__  )
				hidden_state += residual
				_UpperCamelCase							:			List[Any]     =   self.activation(a__  )
				return hidden_state







class       UpperCAmelCase					(       nn.Module			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case	,       _snake_case	,       _snake_case = 1	,       _snake_case = "relu"	,       _snake_case = 4  )					->     List[Any]:
				super().__init__()
				_UpperCamelCase							:			Optional[int]     =   in_channels != out_channels or stride != 1
				_UpperCamelCase							:			List[Any]     =   out_channels // reduction
				_UpperCamelCase							:			List[str]     =   (
				    ResNetShortCut(a__	,       a__	,       stride=a__  ) if should_apply_shortcut else nn.Identity()
				)
				_UpperCamelCase							:			int     =   nn.Sequential(
				    ResNetConvLayer(a__	,       a__	,       kernel_size=1  )	,       ResNetConvLayer(a__	,       a__	,       stride=a__  )	,       ResNetConvLayer(a__	,       a__	,       kernel_size=1	,       activation=a__  )	,       )
				_UpperCamelCase							:			Dict     =   ACTaFN[activation]




		def _lowercase	(     self	,       _snake_case  )					->     Any:
				_UpperCamelCase							:			List[str]     =   hidden_state
				_UpperCamelCase							:			List[Any]     =   self.layer(a__  )
				_UpperCamelCase							:			List[Any]     =   self.shortcut(a__  )
				hidden_state += residual
				_UpperCamelCase							:			Optional[Any]     =   self.activation(a__  )
				return hidden_state







class       UpperCAmelCase					(       nn.Module			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case	,       _snake_case	,       _snake_case	,       _snake_case = 2	,       _snake_case = 2	,       )					->     Any:
				super().__init__()

				_UpperCamelCase							:			Optional[int]     =   ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer

				_UpperCamelCase							:			Tuple     =   nn.Sequential(
				    # downsampling is done in the first layer with stride of 2
				    layer(a__	,       a__	,       stride=a__	,       activation=config.hidden_act  )	,       *[layer(a__	,       a__	,       activation=config.hidden_act  ) for _ in range(depth - 1  )]	,       )




		def _lowercase	(     self	,       _snake_case  )					->     Tensor:
				_UpperCamelCase							:			Union[str, Any]     =   input
				for layer in self.layers:
						_UpperCamelCase							:			str     =   layer(a__  )
				return hidden_state







class       UpperCAmelCase					(       nn.Module			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case  )					->     Union[str, Any]:
				super().__init__()
				_UpperCamelCase							:			Optional[int]     =   nn.ModuleList([]  )
				# based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
				self.stages.append(
				    ResNetStage(
				        a__	,       config.embedding_size	,       config.hidden_sizes[0]	,       stride=2 if config.downsample_in_first_stage else 1	,       depth=config.depths[0]	,       )  )
				_UpperCamelCase							:			Tuple     =   zip(config.hidden_sizes	,       config.hidden_sizes[1:]  )
				for (in_channels, out_channels), depth in zip(a__	,       config.depths[1:]  ):
						self.stages.append(ResNetStage(a__	,       a__	,       a__	,       depth=a__  )  )




		def _lowercase	(     self	,       _snake_case	,       _snake_case = False	,       _snake_case = True  )					->     BaseModelOutputWithNoAttention:
				_UpperCamelCase							:			Dict     =   () if output_hidden_states else None

				for stage_module in self.stages:
						if output_hidden_states:
								_UpperCamelCase							:			Optional[int]     =   hidden_states + (hidden_state,)

						_UpperCamelCase							:			Tuple     =   stage_module(a__  )

				if output_hidden_states:
						_UpperCamelCase							:			Optional[Any]     =   hidden_states + (hidden_state,)

				if not return_dict:
						return tuple(v for v in [hidden_state, hidden_states] if v is not None  )

				return BaseModelOutputWithNoAttention(
				    last_hidden_state=a__	,       hidden_states=a__	,       )







class       UpperCAmelCase					(       lowercase_			):





		"""simple docstring"""





		A__	: List[Any]    =     ResNetConfig
		A__	: Optional[Any]    =     "resnet"
		A__	: str    =     "pixel_values"
		A__	: Optional[int]    =     True
		def _lowercase	(     self	,       _snake_case  )					->     Dict:





				if isinstance(a__	,       nn.Convad  ):
						nn.init.kaiming_normal_(module.weight	,       mode='''fan_out'''	,       nonlinearity='''relu'''  )
				elif isinstance(a__	,       (nn.BatchNormad, nn.GroupNorm)  ):
						nn.init.constant_(module.weight	,       1  )
						nn.init.constant_(module.bias	,       0  )




		def _lowercase	(     self	,       _snake_case	,       _snake_case=False  )					->     Optional[int]:





				if isinstance(a__	,       a__  ):
						_UpperCamelCase							:			Union[str, Any]     =   value







_UpperCAmelCase :   Dict			    =	R"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it
    as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

_UpperCAmelCase :   Optional[Any]			    =	R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__call__`] for details.

        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""

@add_start_docstrings(
    'The bare ResNet model outputting raw features without any specific head on top.'	,		lowercase_	,		)
class       UpperCAmelCase					(       lowercase_			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case  )					->     Tuple:
				super().__init__(a__  )
				_UpperCamelCase							:			int     =   config
				_UpperCamelCase							:			Any     =   ResNetEmbeddings(a__  )
				_UpperCamelCase							:			Dict     =   ResNetEncoder(a__  )
				_UpperCamelCase							:			Dict     =   nn.AdaptiveAvgPoolad((1, 1)  )
				# Initialize weights and apply final processing
				self.post_init()




		@add_start_docstrings_to_model_forward(a__  )
		@add_code_sample_docstrings(
		    checkpoint=_CHECKPOINT_FOR_DOC	,       output_type=a__	,       config_class=_CONFIG_FOR_DOC	,       modality='''vision'''	,       expected_output=_EXPECTED_OUTPUT_SHAPE	,       )
		def _lowercase	(     self	,       _snake_case	,       _snake_case = None	,       _snake_case = None  )					->     BaseModelOutputWithPoolingAndNoAttention:
				_UpperCamelCase							:			List[str]     =   (
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)
				_UpperCamelCase							:			List[str]     =   return_dict if return_dict is not None else self.config.use_return_dict

				_UpperCamelCase							:			int     =   self.embedder(a__  )

				_UpperCamelCase							:			Any     =   self.encoder(
				    a__	,       output_hidden_states=a__	,       return_dict=a__  )

				_UpperCamelCase							:			Any     =   encoder_outputs[0]

				_UpperCamelCase							:			int     =   self.pooler(a__  )

				if not return_dict:
						return (last_hidden_state, pooled_output) + encoder_outputs[1:]

				return BaseModelOutputWithPoolingAndNoAttention(
				    last_hidden_state=a__	,       pooler_output=a__	,       hidden_states=encoder_outputs.hidden_states	,       )







@add_start_docstrings(
    '\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '	,		lowercase_	,		)
class       UpperCAmelCase					(       lowercase_			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case  )					->     List[Any]:
				super().__init__(a__  )
				_UpperCamelCase							:			Union[str, Any]     =   config.num_labels
				_UpperCamelCase							:			Optional[int]     =   ResNetModel(a__  )
				# classification head
				_UpperCamelCase							:			List[str]     =   nn.Sequential(
				    nn.Flatten()	,       nn.Linear(config.hidden_sizes[-1]	,       config.num_labels  ) if config.num_labels > 0 else nn.Identity()	,       )
				# initialize weights and apply final processing
				self.post_init()




		@add_start_docstrings_to_model_forward(a__  )
		@add_code_sample_docstrings(
		    checkpoint=_IMAGE_CLASS_CHECKPOINT	,       output_type=a__	,       config_class=_CONFIG_FOR_DOC	,       expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT	,       )
		def _lowercase	(     self	,       _snake_case = None	,       _snake_case = None	,       _snake_case = None	,       _snake_case = None	,       )					->     ImageClassifierOutputWithNoAttention:
				_UpperCamelCase							:			Union[str, Any]     =   return_dict if return_dict is not None else self.config.use_return_dict

				_UpperCamelCase							:			Tuple     =   self.resnet(a__	,       output_hidden_states=a__	,       return_dict=a__  )

				_UpperCamelCase							:			Optional[Any]     =   outputs.pooler_output if return_dict else outputs[1]

				_UpperCamelCase							:			Optional[Any]     =   self.classifier(a__  )

				_UpperCamelCase							:			Any     =   None

				if labels is not None:
						if self.config.problem_type is None:
								if self.num_labels == 1:
										_UpperCamelCase							:			List[Any]     =   """regression"""
								elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
										_UpperCamelCase							:			List[Any]     =   """single_label_classification"""
								else:
										_UpperCamelCase							:			Union[str, Any]     =   """multi_label_classification"""
						if self.config.problem_type == "regression":
								_UpperCamelCase							:			Any     =   MSELoss()
								if self.num_labels == 1:
										_UpperCamelCase							:			Optional[Any]     =   loss_fct(logits.squeeze()	,       labels.squeeze()  )
								else:
										_UpperCamelCase							:			Any     =   loss_fct(a__	,       a__  )
						elif self.config.problem_type == "single_label_classification":
								_UpperCamelCase							:			int     =   CrossEntropyLoss()
								_UpperCamelCase							:			List[Any]     =   loss_fct(logits.view(-1	,       self.num_labels  )	,       labels.view(-1  )  )
						elif self.config.problem_type == "multi_label_classification":
								_UpperCamelCase							:			List[str]     =   BCEWithLogitsLoss()
								_UpperCamelCase							:			int     =   loss_fct(a__	,       a__  )

				if not return_dict:
						_UpperCamelCase							:			int     =   (logits,) + outputs[2:]
						return (loss,) + output if loss is not None else output

				return ImageClassifierOutputWithNoAttention(loss=a__	,       logits=a__	,       hidden_states=outputs.hidden_states  )







@add_start_docstrings(
    '\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    '	,		lowercase_	,		)
class       UpperCAmelCase					(       lowercase_	,		lowercase_			):





		"""simple docstring"""





		def __init__(     self	,       _snake_case  )					->     int:
				super().__init__(a__  )
				super()._init_backbone(a__  )

				_UpperCamelCase							:			Optional[int]     =   [config.embedding_size] + config.hidden_sizes
				_UpperCamelCase							:			str     =   ResNetEmbeddings(a__  )
				_UpperCamelCase							:			Any     =   ResNetEncoder(a__  )

				# initialize weights and apply final processing
				self.post_init()




		@add_start_docstrings_to_model_forward(a__  )
		@replace_return_docstrings(output_type=a__	,       config_class=_CONFIG_FOR_DOC  )
		def _lowercase	(     self	,       _snake_case	,       _snake_case = None	,       _snake_case = None  )					->     BackboneOutput:
				_UpperCamelCase							:			int     =   return_dict if return_dict is not None else self.config.use_return_dict
				_UpperCamelCase							:			Union[str, Any]     =   (
				    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
				)

				_UpperCamelCase							:			List[str]     =   self.embedder(a__  )

				_UpperCamelCase							:			List[Any]     =   self.encoder(a__	,       output_hidden_states=a__	,       return_dict=a__  )

				_UpperCamelCase							:			Optional[int]     =   outputs.hidden_states

				_UpperCamelCase							:			Tuple     =   ()
				for idx, stage in enumerate(self.stage_names  ):
						if stage in self.out_features:
								feature_maps += (hidden_states[idx],)

				if not return_dict:
						_UpperCamelCase							:			Union[str, Any]     =   (feature_maps,)
						if output_hidden_states:
								output += (outputs.hidden_states,)
						return output

				return BackboneOutput(
				    feature_maps=a__	,       hidden_states=outputs.hidden_states if output_hidden_states else None	,       attentions=a__	,       )













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 	UpperCamelCase	(							snake_case__  : List[Any]						,snake_case__  : List[str]	):




     '''simple docstring'''






     __snake_case      :int 							=    []
     for part_id in partition_order:
          __snake_case      :int 							=    df.where(f'''SPARK_PARTITION_ID() = {part_id}'''	).collect()
          for row_idx, row in enumerate(snake_case__	):
               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 	UpperCamelCase	(							):




     '''simple docstring'''






     __snake_case      :List[str] 							=    pyspark.sql.SparkSession.builder.master("""local[*]"""	).appName("""pyspark"""	).getOrCreate()
     __snake_case      :Any 							=    spark.range(100	).repartition(1	)
     __snake_case      :int 							=    Spark(snake_case__	)
     # 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 	UpperCamelCase	(							):




     '''simple docstring'''






     __snake_case      :Tuple 							=    pyspark.sql.SparkSession.builder.master("""local[*]"""	).appName("""pyspark"""	).getOrCreate()
     __snake_case      :int 							=    spark.range(10	).repartition(2	)
     __snake_case      :str 							=    [1, 0]
     __snake_case      :List[Any] 							=    _generate_iterable_examples(snake_case__						,snake_case__	)  # Reverse the partitions.
     __snake_case      :Union[str, Any] 							=    _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__						,snake_case__	)

     for i, (row_id, row_dict) in enumerate(generate_fn()	):
          __snake_case							,			__snake_case      :Union[str, Any] 							=    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 	UpperCamelCase	(							):




     '''simple docstring'''






     __snake_case      :Union[str, Any] 							=    pyspark.sql.SparkSession.builder.master("""local[*]"""	).appName("""pyspark"""	).getOrCreate()
     __snake_case      :Tuple 							=    spark.range(10	).repartition(1	)
     __snake_case      :Dict 							=    SparkExamplesIterable(snake_case__	)
     assert it.n_shards == 1
     for i, (row_id, row_dict) in enumerate(snake_case__	):
          assert row_id == f'''0_{i}'''
          assert row_dict == {"id": i}






@require_not_windows
@require_dill_gt_0_3_2
def 	UpperCamelCase	(							):




     '''simple docstring'''






     __snake_case      :List[str] 							=    pyspark.sql.SparkSession.builder.master("""local[*]"""	).appName("""pyspark"""	).getOrCreate()
     __snake_case      :Union[str, Any] 							=    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      :Dict 							=    lambda snake_case__	: x.reverse()
          __snake_case      :int 							=    _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__						,[2, 1, 0]	)

          __snake_case      :Dict 							=    SparkExamplesIterable(snake_case__	).shuffle_data_sources(snake_case__	)
          assert shuffled_it.n_shards == 3
          for i, (row_id, row_dict) in enumerate(snake_case__	):
               __snake_case							,			__snake_case      :List[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 	UpperCamelCase	(							):




     '''simple docstring'''






     __snake_case      :Union[str, Any] 							=    pyspark.sql.SparkSession.builder.master("""local[*]"""	).appName("""pyspark"""	).getOrCreate()
     __snake_case      :Tuple 							=    spark.range(20	).repartition(4	)

     # Partitions 0 and 2
     __snake_case      :List[Any] 							=    SparkExamplesIterable(snake_case__	).shard_data_sources(worker_id=0						,num_workers=2	)
     assert shard_it_a.n_shards == 2
     __snake_case      :Dict 							=    _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__						,[0, 2]	)
     for i, (row_id, row_dict) in enumerate(snake_case__	):
          __snake_case							,			__snake_case      :Tuple 							=    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(snake_case__	).shard_data_sources(worker_id=1						,num_workers=2	)
     assert shard_it_a.n_shards == 2
     __snake_case      :Optional[int] 							=    _get_expected_row_ids_and_row_dicts_for_partition_order(snake_case__						,[1, 3]	)
     for i, (row_id, row_dict) in enumerate(snake_case__	):
          __snake_case							,			__snake_case      :Dict 							=    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 	UpperCamelCase	(							):




     '''simple docstring'''






     __snake_case      :Union[str, Any] 							=    pyspark.sql.SparkSession.builder.master("""local[*]"""	).appName("""pyspark"""	).getOrCreate()
     __snake_case      :Tuple 							=    spark.range(100	).repartition(1	)
     __snake_case      :Dict 							=    Spark(snake_case__	)
     # 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() == 100


