





import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
    from transformers import (
        FlaxBertModel,
        FlaxCLIPVisionModel,
        FlaxVisionTextDualEncoderModel,
        FlaxViTModel,
        VisionTextDualEncoderConfig,
        VisionTextDualEncoderProcessor,
    )
    from transformers.modeling_flax_pytorch_utils import (
        convert_pytorch_state_dict_to_flax,
        load_flax_weights_in_pytorch_model,
    )


if is_torch_available():
    import torch

    from transformers import VisionTextDualEncoderModel

if is_vision_available():
    from PIL import Image


def  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase				)    ->  Optional[Any]:
    if isinstance(_UpperCAmelCase		,			collections.abc.Iterable				):
        return x
    return (x, x)

@require_flax
class      lowerCAmelCase							:
 def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   str			)    ->			str:
     pass
 def   A_			(   self						:   List[Any]			)    ->			str:
     pass
 def   A_			(   self						:   str			)    ->			Any:
     pass
 def   A_			(   self						:   Optional[int]    ,  UpperCAmelCase						:   np.ndarray    ,  UpperCAmelCase						:   np.ndarray    ,  UpperCAmelCase						:   float			)    ->			List[str]:
     lowerCamelCase__					:   Optional[int]      				=	np.abs((a - b)			).max()
     self.assertLessEqual(UpperCAmelCase    ,  UpperCAmelCase    ,  F"""Difference between torch and flax is {diff} (>= {tol})."""			)
 def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   int    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   Dict    ,  UpperCAmelCase						:   int=None    ,  **UpperCAmelCase						:   Tuple			)    ->			List[str]:
     lowerCamelCase__					:   int      				=	VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase    ,  UpperCAmelCase			)

     lowerCamelCase__					:   List[str]      				=	FlaxVisionTextDualEncoderModel(UpperCAmelCase			)

     lowerCamelCase__					:   str      				=	model(input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase			)

     self.assertEqual(output['text_embeds'].shape    ,  (input_ids.shape[0], config.projection_dim)			)
     self.assertEqual(output['image_embeds'].shape    ,  (pixel_values.shape[0], config.projection_dim)			)
 def   A_			(   self						:   Union[str, Any]    ,  UpperCAmelCase						:   List[str]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   Any=None    ,  **UpperCAmelCase						:   List[Any]			)    ->			Union[str, Any]:
     lowerCamelCase__				,							lowerCamelCase__					:   List[Any]      				=	self.get_vision_text_model(UpperCAmelCase    ,  UpperCAmelCase			)
     lowerCamelCase__					:   int      				=	{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__					:   Dict      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase			)

     lowerCamelCase__					:   Optional[int]      				=	model(input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase			)

     self.assertEqual(output['text_embeds'].shape    ,  (input_ids.shape[0], model.config.projection_dim)			)
     self.assertEqual(output['image_embeds'].shape    ,  (pixel_values.shape[0], model.config.projection_dim)			)
 def   A_			(   self						:   Tuple    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   Any    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   List[Any]=None    ,  **UpperCAmelCase						:   Dict			)    ->			Optional[int]:
     lowerCamelCase__				,							lowerCamelCase__					:   int      				=	self.get_vision_text_model(UpperCAmelCase    ,  UpperCAmelCase			)
     lowerCamelCase__					:   List[Any]      				=	{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__					:   List[Any]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase			)

     lowerCamelCase__					:   Dict      				=	model(input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase			)
     lowerCamelCase__					:   str      				=	output[0]

     with tempfile.TemporaryDirectory() as tmpdirname:
         model.save_pretrained(UpperCAmelCase			)
         lowerCamelCase__					:   Optional[Any]      				=	FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase			)

         lowerCamelCase__					:   int      				=	model(input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase			)
         lowerCamelCase__					:   Union[str, Any]      				=	after_output[0]
         lowerCamelCase__					:   Tuple      				=	np.amax(np.abs(out_a - out_a			)			)
         self.assertLessEqual(UpperCAmelCase    ,  1e-3			)
 def   A_			(   self						:   Any    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Union[str, Any]    ,  UpperCAmelCase						:   Any    ,  UpperCAmelCase						:   Tuple=None    ,  **UpperCAmelCase						:   List[str]			)    ->			Optional[int]:
     lowerCamelCase__				,							lowerCamelCase__					:   Tuple      				=	self.get_vision_text_model(UpperCAmelCase    ,  UpperCAmelCase			)
     lowerCamelCase__					:   Tuple      				=	{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__					:   str      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase			)

     lowerCamelCase__					:   str      				=	model(
         input_ids=UpperCAmelCase    ,  pixel_values=UpperCAmelCase    ,  attention_mask=UpperCAmelCase    ,  output_attentions=UpperCAmelCase			)

     lowerCamelCase__					:   str      				=	output.vision_model_output.attentions
     self.assertEqual(len(UpperCAmelCase			)    ,  vision_config.num_hidden_layers			)

     # in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
     lowerCamelCase__					:   Any      				=	to_atuple(vision_model.config.image_size			)
     lowerCamelCase__					:   List[Any]      				=	to_atuple(vision_model.config.patch_size			)
     lowerCamelCase__					:   List[str]      				=	(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
     lowerCamelCase__					:   List[str]      				=	num_patches + 1
     self.assertEqual(vision_attentions[0].shape[-3:]    ,  (vision_config.num_attention_heads, seq_len, seq_len)			)

     lowerCamelCase__					:   str      				=	output.text_model_output.attentions
     self.assertEqual(len(UpperCAmelCase			)    ,  text_config.num_hidden_layers			)

     self.assertEqual(
         text_attentions[0].shape[-3:]    ,  (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])    ,  )
 def   A_			(   self						:   str    ,  UpperCAmelCase						:   Optional[Any]    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   str			)    ->			List[Any]:
     pt_model.to(UpperCAmelCase			)
     pt_model.eval()

     # prepare inputs
     lowerCamelCase__					:   List[str]      				=	inputs_dict
     lowerCamelCase__					:   Tuple      				=	{k: torch.tensor(v.tolist()			) for k, v in flax_inputs.items()}

     with torch.no_grad():
         lowerCamelCase__					:   Tuple      				=	pt_model(**UpperCAmelCase			).to_tuple()

     lowerCamelCase__					:   List[Any]      				=	fx_model(**UpperCAmelCase			).to_tuple()
     self.assertEqual(len(UpperCAmelCase			)    ,  len(UpperCAmelCase			)    ,  'Output lengths differ between Flax and PyTorch'			)
     for fx_output, pt_output in zip(fx_outputs[:4]    ,  pt_outputs[:4]			):
         self.assert_almost_equals(UpperCAmelCase    ,  pt_output.numpy()    ,  4e-2			)

     # PT -> Flax
     with tempfile.TemporaryDirectory() as tmpdirname:
         pt_model.save_pretrained(UpperCAmelCase			)
         lowerCamelCase__					:   Optional[int]      				=	FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase    ,  from_pt=UpperCAmelCase			)

     lowerCamelCase__					:   str      				=	fx_model_loaded(**UpperCAmelCase			).to_tuple()
     self.assertEqual(len(UpperCAmelCase			)    ,  len(UpperCAmelCase			)    ,  'Output lengths differ between Flax and PyTorch'			)
     for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]    ,  pt_outputs[:4]			):
         self.assert_almost_equals(UpperCAmelCase    ,  pt_output.numpy()    ,  4e-2			)

     # Flax -> PT
     with tempfile.TemporaryDirectory() as tmpdirname:
         fx_model.save_pretrained(UpperCAmelCase			)
         lowerCamelCase__					:   Any      				=	VisionTextDualEncoderModel.from_pretrained(UpperCAmelCase    ,  from_flax=UpperCAmelCase			)

     pt_model_loaded.to(UpperCAmelCase			)
     pt_model_loaded.eval()

     with torch.no_grad():
         lowerCamelCase__					:   int      				=	pt_model_loaded(**UpperCAmelCase			).to_tuple()

     self.assertEqual(len(UpperCAmelCase			)    ,  len(UpperCAmelCase			)    ,  'Output lengths differ between Flax and PyTorch'			)
     for fx_output, pt_output_loaded in zip(fx_outputs[:4]    ,  pt_outputs_loaded[:4]			):
         self.assert_almost_equals(UpperCAmelCase    ,  pt_output_loaded.numpy()    ,  4e-2			)
 def   A_			(   self						:   List[str]    ,  UpperCAmelCase						:   Optional[Any]    ,  UpperCAmelCase						:   str    ,  UpperCAmelCase						:   str			)    ->			List[Any]:
     lowerCamelCase__					:   List[str]      				=	VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase    ,  UpperCAmelCase			)

     lowerCamelCase__					:   List[str]      				=	VisionTextDualEncoderModel(UpperCAmelCase			)
     lowerCamelCase__					:   Tuple      				=	FlaxVisionTextDualEncoderModel(UpperCAmelCase			)

     lowerCamelCase__					:   Union[str, Any]      				=	convert_pytorch_state_dict_to_flax(pt_model.state_dict()    ,  UpperCAmelCase			)
     lowerCamelCase__					:   Optional[Any]      				=	fx_state

     self.check_pt_flax_equivalence(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)
 def   A_			(   self						:   Any    ,  UpperCAmelCase						:   Optional[int]    ,  UpperCAmelCase						:   Tuple    ,  UpperCAmelCase						:   Union[str, Any]			)    ->			str:
     lowerCamelCase__					:   Optional[Any]      				=	VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase    ,  UpperCAmelCase			)

     lowerCamelCase__					:   Optional[Any]      				=	VisionTextDualEncoderModel(UpperCAmelCase			)
     lowerCamelCase__					:   str      				=	FlaxVisionTextDualEncoderModel(UpperCAmelCase			)

     lowerCamelCase__					:   str      				=	load_flax_weights_in_pytorch_model(UpperCAmelCase    ,  fx_model.params			)

     self.check_pt_flax_equivalence(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)
 def   A_			(   self						:   Union[str, Any]			)    ->			Union[str, Any]:
     lowerCamelCase__					:   Tuple      				=	self.prepare_config_and_inputs()
     self.check_model_from_pretrained_configs(**UpperCAmelCase			)
 def   A_			(   self						:   Any			)    ->			List[str]:
     lowerCamelCase__					:   List[Any]      				=	self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_from_pretrained(**UpperCAmelCase			)
 def   A_			(   self						:   Union[str, Any]			)    ->			Dict:
     lowerCamelCase__					:   Union[str, Any]      				=	self.prepare_config_and_inputs()
     self.check_save_load(**UpperCAmelCase			)
 def   A_			(   self						:   str			)    ->			int:
     lowerCamelCase__					:   List[Any]      				=	self.prepare_config_and_inputs()
     self.check_vision_text_output_attention(**UpperCAmelCase			)
 @is_pt_flax_cross_test
 def   A_			(   self						:   List[Any]			)    ->			Union[str, Any]:
     lowerCamelCase__					:   int      				=	self.prepare_config_and_inputs()
     lowerCamelCase__					:   int      				=	config_inputs_dict.pop('vision_config'			)
     lowerCamelCase__					:   Any      				=	config_inputs_dict.pop('text_config'			)

     lowerCamelCase__					:   Union[str, Any]      				=	config_inputs_dict

     self.check_equivalence_pt_to_flax(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)
     self.check_equivalence_flax_to_pt(UpperCAmelCase    ,  UpperCAmelCase    ,  UpperCAmelCase			)







 @slow
 def   A_			(   self						:   Tuple			)    ->			Optional[int]:
     lowerCamelCase__				,							lowerCamelCase__					:   Dict      				=	self.get_pretrained_model_and_inputs()

     lowerCamelCase__					:   Tuple      				=	model_a(**UpperCAmelCase			)
     lowerCamelCase__					:   Optional[Any]      				=	outputs[0]

     with tempfile.TemporaryDirectory() as tmp_dirname:
         model_a.save_pretrained(UpperCAmelCase			)
         lowerCamelCase__					:   List[str]      				=	FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase			)

         lowerCamelCase__					:   str      				=	model_a(**UpperCAmelCase			)
         lowerCamelCase__					:   Dict      				=	after_outputs[0]
         lowerCamelCase__					:   List[str]      				=	np.amax(np.abs(out_a - out_a			)			)
         self.assertLessEqual(UpperCAmelCase    ,  1e-5			)


@require_flax
class      lowerCAmelCase							(      __UpperCamelCase,						unittest.TestCase    ):
 def   A_			(   self						:   Any			)    ->			Dict:
     lowerCamelCase__					:   Any      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         'hf-internal-testing/tiny-random-vit'    ,  'hf-internal-testing/tiny-bert'    ,  vision_from_pt=UpperCAmelCase    ,  text_from_pt=UpperCAmelCase    ,  )
     lowerCamelCase__					:   Dict      				=	13
     lowerCamelCase__					:   Optional[Any]      				=	floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]			)
     lowerCamelCase__					:   Dict      				=	ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size			)
     lowerCamelCase__					:   str      				=	random_attention_mask([batch_size, 4]			)
     lowerCamelCase__					:   Union[str, Any]      				=	{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs
 def   A_			(   self						:   Dict    ,  UpperCAmelCase						:   int    ,  UpperCAmelCase						:   Tuple			)    ->			List[str]:
     lowerCamelCase__					:   Tuple      				=	FlaxViTModel(UpperCAmelCase			)
     lowerCamelCase__					:   List[Any]      				=	FlaxBertModel(UpperCAmelCase			)
     return vision_model, text_model







 def   A_			(   self						:   Any			)    ->			str:
     lowerCamelCase__					:   str      				=	FlaxViTModelTester(self			)
     lowerCamelCase__					:   int      				=	FlaxBertModelTester(self			)
     lowerCamelCase__					:   Any      				=	vit_model_tester.prepare_config_and_inputs()
     lowerCamelCase__					:   Tuple      				=	bert_model_tester.prepare_config_and_inputs()

     lowerCamelCase__				,							lowerCamelCase__					:   Dict      				=	vision_config_and_inputs

     lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__					:   List[Any]      				=	text_config_and_inputs

     # make sure that cross attention layers are added
     return {
         "text_config": text_config,
         "vision_config": vision_config,
         "pixel_values": pixel_values,
         "attention_mask": attention_mask,
         "input_ids": input_ids,
         "token_type_ids": token_type_ids,
     }


@require_torch
class      lowerCAmelCase							(      __UpperCamelCase,						unittest.TestCase    ):
 def   A_			(   self						:   Optional[Any]			)    ->			List[Any]:
     lowerCamelCase__					:   Optional[int]      				=	FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
         'hf-internal-testing/tiny-random-clip'    ,  'hf-internal-testing/tiny-bert'    ,  vision_from_pt=UpperCAmelCase    ,  text_from_pt=UpperCAmelCase    ,  )
     lowerCamelCase__					:   List[Any]      				=	13
     lowerCamelCase__					:   Optional[int]      				=	floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]			)
     lowerCamelCase__					:   Dict      				=	ids_tensor([batch_size, 4]    ,  model.config.text_config.vocab_size			)
     lowerCamelCase__					:   Optional[int]      				=	random_attention_mask([batch_size, 4]			)
     lowerCamelCase__					:   List[Any]      				=	{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs
 def   A_			(   self						:   Optional[Any]    ,  UpperCAmelCase						:   List[Any]    ,  UpperCAmelCase						:   List[str]			)    ->			str:
     lowerCamelCase__					:   Tuple      				=	FlaxCLIPVisionModel(UpperCAmelCase			)
     lowerCamelCase__					:   str      				=	FlaxBertModel(UpperCAmelCase			)
     return vision_model, text_model







 def   A_			(   self						:   List[Any]			)    ->			Any:
     lowerCamelCase__					:   Dict      				=	FlaxCLIPVisionModelTester(self			)
     lowerCamelCase__					:   Tuple      				=	FlaxBertModelTester(self			)
     lowerCamelCase__					:   str      				=	clip_model_tester.prepare_config_and_inputs()
     lowerCamelCase__					:   List[str]      				=	bert_model_tester.prepare_config_and_inputs()

     lowerCamelCase__				,							lowerCamelCase__					:   Optional[int]      				=	vision_config_and_inputs

     lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__				,							lowerCamelCase__					:   Optional[Any]      				=	text_config_and_inputs

     # make sure that cross attention layers are added
     return {
         "text_config": text_config,
         "vision_config": vision_config,
         "pixel_values": pixel_values,
         "attention_mask": attention_mask,
         "input_ids": input_ids,
         "token_type_ids": token_type_ids,
     }


@require_flax
@require_vision
class      lowerCAmelCase							(      unittest.TestCase    ):
 @slow
 def   A_			(   self						:   Optional[int]			)    ->			List[str]:
     lowerCamelCase__					:   Optional[int]      				=	FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'    ,  logit_scale_init_value=1.0			)
     lowerCamelCase__					:   List[str]      				=	VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'			)

     lowerCamelCase__					:   Tuple      				=	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'			)
     lowerCamelCase__					:   List[str]      				=	processor(
         text=['una foto di un gatto', 'una foto di un cane']    ,  images=UpperCAmelCase    ,  padding=UpperCAmelCase    ,  return_tensors='np'			)

     lowerCamelCase__					:   Any      				=	model(**UpperCAmelCase			)

     # verify the logits
     self.assertEqual(outputs.logits_per_image.shape    ,  (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])			)
     self.assertEqual(
         outputs.logits_per_text.shape    ,  (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])    ,  )

     lowerCamelCase__					:   Dict      				=	np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]			)

     self.assertTrue(np.allclose(outputs.logits_per_image    ,  UpperCAmelCase    ,  atol=1e-3			)			)












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  SCREAMING_SNAKE_CASE   ( _UpperCAmelCase		,			_UpperCAmelCase				)    ->  Any:
    lowerCamelCase__					:   Any      				=	[]
    for part_id in partition_order:
        lowerCamelCase__					:   List[str]      				=	df.where(F"""SPARK_PARTITION_ID() = {part_id}"""				).collect()
        for row_idx, row in enumerate(_UpperCAmelCase				):
            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  SCREAMING_SNAKE_CASE   ( )    ->  List[Any]:
    lowerCamelCase__					:   List[str]      				=	pyspark.sql.SparkSession.builder.master('local[*]'				).appName('pyspark'				).getOrCreate()
    lowerCamelCase__					:   Any      				=	spark.range(100				).repartition(1				)
    lowerCamelCase__					:   str      				=	Spark(_UpperCAmelCase				)
    # 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  SCREAMING_SNAKE_CASE   ( )    ->  Tuple:
    lowerCamelCase__					:   Any      				=	pyspark.sql.SparkSession.builder.master('local[*]'				).appName('pyspark'				).getOrCreate()
    lowerCamelCase__					:   Optional[int]      				=	spark.range(10				).repartition(2				)
    lowerCamelCase__					:   Dict      				=	[1, 0]
    lowerCamelCase__					:   str      				=	_generate_iterable_examples(_UpperCAmelCase		,			_UpperCAmelCase				)  # Reverse the partitions.
    lowerCamelCase__					:   Any      				=	_get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase		,			_UpperCAmelCase				)

    for i, (row_id, row_dict) in enumerate(generate_fn()				):
        lowerCamelCase__				,							lowerCamelCase__					:   Tuple      				=	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  SCREAMING_SNAKE_CASE   ( )    ->  Optional[Any]:
    lowerCamelCase__					:   Dict      				=	pyspark.sql.SparkSession.builder.master('local[*]'				).appName('pyspark'				).getOrCreate()
    lowerCamelCase__					:   Dict      				=	spark.range(10				).repartition(1				)
    lowerCamelCase__					:   List[str]      				=	SparkExamplesIterable(_UpperCAmelCase				)
    assert it.n_shards == 1
    for i, (row_id, row_dict) in enumerate(_UpperCAmelCase				):
        assert row_id == F"""0_{i}"""
        assert row_dict == {"id": i}


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

        lowerCamelCase__					:   Tuple      				=	SparkExamplesIterable(_UpperCAmelCase				).shuffle_data_sources(_UpperCAmelCase				)
        assert shuffled_it.n_shards == 3
        for i, (row_id, row_dict) in enumerate(_UpperCAmelCase				):
            lowerCamelCase__				,							lowerCamelCase__					:   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  SCREAMING_SNAKE_CASE   ( )    ->  Optional[Any]:
    lowerCamelCase__					:   Optional[Any]      				=	pyspark.sql.SparkSession.builder.master('local[*]'				).appName('pyspark'				).getOrCreate()
    lowerCamelCase__					:   Tuple      				=	spark.range(20				).repartition(4				)

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

    # Partitions 1 and 3
    lowerCamelCase__					:   Dict      				=	SparkExamplesIterable(_UpperCAmelCase				).shard_data_sources(worker_id=1		,			num_workers=2				)
    assert shard_it_a.n_shards == 2
    lowerCamelCase__					:   Optional[int]      				=	_get_expected_row_ids_and_row_dicts_for_partition_order(_UpperCAmelCase		,			[1, 3]				)
    for i, (row_id, row_dict) in enumerate(_UpperCAmelCase				):
        lowerCamelCase__				,							lowerCamelCase__					:   Any      				=	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  SCREAMING_SNAKE_CASE   ( )    ->  Dict:
    lowerCamelCase__					:   int      				=	pyspark.sql.SparkSession.builder.master('local[*]'				).appName('pyspark'				).getOrCreate()
    lowerCamelCase__					:   str      				=	spark.range(100				).repartition(1				)
    lowerCamelCase__					:   Dict      				=	Spark(_UpperCAmelCase				)
    # 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





