


"""simple docstring"""







import itertools
from dataclasses import dataclass
from typing import List, Optional

import pyarrow as pa
import pyarrow.parquet as pq

import datasets
from datasets.table import table_cast


a__    :							str            =					datasets.utils.logging.get_logger(__name__)




@dataclass
class 			UpperCamelCase_     (			datasets.BuilderConfig):

	"""simple docstring"""





	snake_case__    :  int    =      10000
	snake_case__    :  Optional[List[str]]    =      None
	snake_case__    :  Optional[datasets.Features]    =      None




class 			UpperCamelCase_     (			datasets.ArrowBasedBuilder):

	"""simple docstring"""





	snake_case__    :  List[Any]    =      ParquetConfig




	def   UpperCAmelCase_				(			self      :    Optional[int]       )	->     Optional[int]:
						return datasets.DatasetInfo(features=self.config.features       )




	def   UpperCAmelCase_				(			self      :    Union[str, Any]      ,      UpperCAmelCase__      :    int       )	->     Dict:
						if not self.config.data_files:
											raise ValueError(F"""At least one data file must be specified, but got data_files={self.config.data_files}"""       )
						__SCREAMING_SNAKE_CASE						       =    dl_manager.download_and_extract(self.config.data_files       )
						if isinstance(UpperCAmelCase__      ,      (str, list, tuple)       ):
											__SCREAMING_SNAKE_CASE						       =    data_files
											if isinstance(UpperCAmelCase__      ,      UpperCAmelCase__       ):
																__SCREAMING_SNAKE_CASE						       =    [files]
											# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
											__SCREAMING_SNAKE_CASE						       =    [dl_manager.iter_files(UpperCAmelCase__       ) for file in files]
											return [datasets.SplitGenerator(name=datasets.Split.TRAIN      ,      gen_kwargs={"files": files}       )]
						__SCREAMING_SNAKE_CASE						       =    []
						for split_name, files in data_files.items():
											if isinstance(UpperCAmelCase__      ,      UpperCAmelCase__       ):
																__SCREAMING_SNAKE_CASE						       =    [files]
											# Use `dl_manager.iter_files` to skip hidden files in an extracted archive
											__SCREAMING_SNAKE_CASE						       =    [dl_manager.iter_files(UpperCAmelCase__       ) for file in files]
											# Infer features is they are stoed in the arrow schema
											if self.info.features is None:
																for file in itertools.chain.from_iterable(UpperCAmelCase__       ):
																					with open(UpperCAmelCase__      ,      "rb"       ) as f:
																										__SCREAMING_SNAKE_CASE						       =    datasets.Features.from_arrow_schema(pq.read_schema(UpperCAmelCase__       )       )
																					break
											splits.append(datasets.SplitGenerator(name=UpperCAmelCase__      ,      gen_kwargs={"files": files}       )       )
						return splits




	def   UpperCAmelCase_				(			self      :    Tuple      ,      UpperCAmelCase__      :    pa.Table       )	->     pa.Table:
						if self.info.features is not None:
											# more expensive cast to support nested features with keys in a different order
											# allows str <-> int/float or str to Audio for example
											__SCREAMING_SNAKE_CASE						       =    table_cast(UpperCAmelCase__      ,      self.info.features.arrow_schema       )
						return pa_table




	def   UpperCAmelCase_				(			self      :    List[str]      ,      UpperCAmelCase__      :    Optional[int]       )	->     Tuple:
						__SCREAMING_SNAKE_CASE						       =    self.info.features.arrow_schema if self.info.features is not None else None
						if self.info.features is not None and self.config.columns is not None:
											if sorted(field.name for field in schema       ) != sorted(self.config.columns       ):
																raise ValueError(
																    F"""Tried to load parquet data with columns '{self.config.columns}' with mismatching features '{self.info.features}'"""       )
						for file_idx, file in enumerate(itertools.chain.from_iterable(UpperCAmelCase__       )       ):
											with open(UpperCAmelCase__      ,      "rb"       ) as f:
																__SCREAMING_SNAKE_CASE						       =    pq.ParquetFile(UpperCAmelCase__       )
																try:
																					for batch_idx, record_batch in enumerate(
																					    parquet_file.iter_batches(batch_size=self.config.batch_size      ,      columns=self.config.columns       )       ):
																										__SCREAMING_SNAKE_CASE						       =    pa.Table.from_batches([record_batch]       )
																										# Uncomment for debugging (will print the Arrow table size and elements)
																										# logger.warning(f"pa_table: {pa_table} num rows: {pa_table.num_rows}")
																										# logger.warning('\n'.join(str(pa_table.slice(i, 1).to_pydict()) for i in range(pa_table.num_rows)))
																										yield F"""{file_idx}_{batch_idx}""", self._cast_table(UpperCAmelCase__       )
																except ValueError as e:
																					logger.error(F"""Failed to read file '{file}' with error {type(UpperCAmelCase__       )}: {e}"""       )
																					raise




"""simple docstring"""







import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


a__    :							Union[str, Any]            =					logging.get_logger(__name__)




def        UpperCAmelCase__	(lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    R"\w+[.]\d+"
					__SCREAMING_SNAKE_CASE						       =    re.findall(lowerCAmelCase_  ,						lowerCAmelCase_       )
					for pat in pats:
										__SCREAMING_SNAKE_CASE						       =    key.replace(lowerCAmelCase_  ,						"_".join(pat.split("."       )       )       )
					return key




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("scale",)
					if (
					    any("norm" in str_ for str_ in pt_tuple_key       )
					    and (pt_tuple_key[-1] == "bias")
					    and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
					    and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
					):
										__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("scale",)
										return renamed_pt_tuple_key, pt_tensor
					elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
										__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("scale",)
										return renamed_pt_tuple_key, pt_tensor

					# embedding
					if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
										__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("embedding",)
										return renamed_pt_tuple_key, pt_tensor

					# conv layer
					__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("kernel",)
					if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
										__SCREAMING_SNAKE_CASE						       =    pt_tensor.transpose(2  ,						3  ,						1  ,						0       )
										return renamed_pt_tuple_key, pt_tensor

					# linear layer
					__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("kernel",)
					if pt_tuple_key[-1] == "weight":
										__SCREAMING_SNAKE_CASE						       =    pt_tensor.T
										return renamed_pt_tuple_key, pt_tensor

					# old PyTorch layer norm weight
					__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("weight",)
					if pt_tuple_key[-1] == "gamma":
										return renamed_pt_tuple_key, pt_tensor

					# old PyTorch layer norm bias
					__SCREAMING_SNAKE_CASE						       =    pt_tuple_key[:-1] + ("bias",)
					if pt_tuple_key[-1] == "beta":
										return renamed_pt_tuple_key, pt_tensor

					return pt_tuple_key, pt_tensor




def        UpperCAmelCase__	(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_=42       ):




					'''simple docstring'''


					__SCREAMING_SNAKE_CASE						       =    {k: v.numpy() for k, v in pt_state_dict.items()}

					# Step 2: Since the model is stateless, get random Flax params
					__SCREAMING_SNAKE_CASE						       =    flax_model.init_weights(PRNGKey(lowerCAmelCase_       )       )

					__SCREAMING_SNAKE_CASE						       =    flatten_dict(lowerCAmelCase_       )
					__SCREAMING_SNAKE_CASE						       =    {}

					# Need to change some parameters name to match Flax names
					for pt_key, pt_tensor in pt_state_dict.items():
										__SCREAMING_SNAKE_CASE						       =    rename_key(lowerCAmelCase_       )
										__SCREAMING_SNAKE_CASE						       =    tuple(renamed_pt_key.split("."       )       )

										# Correctly rename weight parameters
										__SCREAMING_SNAKE_CASE       ,  __SCREAMING_SNAKE_CASE						       =    rename_key_and_reshape_tensor(lowerCAmelCase_  ,						lowerCAmelCase_  ,						lowerCAmelCase_       )

										if flax_key in random_flax_state_dict:
															if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
																				raise ValueError(
																				    f"""PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape """
																				    f"""{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."""       )

        # also add unexpected weight so that warning is thrown
										__SCREAMING_SNAKE_CASE						       =    jnp.asarray(lowerCAmelCase_       )

					return unflatten_dict(lowerCAmelCase_       )
