





from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
					import tensorflow as tf

					from transformers.models.xglm.modeling_tf_xglm import (
					    TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
					    TFXGLMForCausalLM,
					    TFXGLMModel,
					)


@require_tf
class     A     :
			'''simple docstring'''




			__lowerCamelCase      :			Dict							     =       XGLMConfig
			__lowerCamelCase      :			Any							     =       {}
			__lowerCamelCase      :			Dict							     =       '''gelu'''






			def __init__(     self  :       Any				,      __lowerCAmelCase  :       int				,      __lowerCAmelCase  :       int=14				,      __lowerCAmelCase  :       List[str]=7				,      __lowerCAmelCase  :       Union[str, Any]=True				,      __lowerCAmelCase  :       List[str]=True				,      __lowerCAmelCase  :       Union[str, Any]=True				,      __lowerCAmelCase  :       List[Any]=99				,      __lowerCAmelCase  :       Any=32				,      __lowerCAmelCase  :       Dict=2				,      __lowerCAmelCase  :       Optional[Any]=4				,      __lowerCAmelCase  :       str=37				,      __lowerCAmelCase  :       List[Any]="gelu"				,      __lowerCAmelCase  :       Optional[Any]=0.1				,      __lowerCAmelCase  :       Any=0.1				,      __lowerCAmelCase  :       str=5_12				,      __lowerCAmelCase  :       Union[str, Any]=0.0_2				,      )      ->      List[Any]:







					"""simple docstring"""






					A__     =  parent
					A__     =  batch_size
					A__     =  seq_length
					A__     =  is_training
					A__     =  use_input_mask
					A__     =  use_labels
					A__     =  vocab_size
					A__     =  d_model
					A__     =  num_hidden_layers
					A__     =  num_attention_heads
					A__     =  ffn_dim
					A__     =  activation_function
					A__     =  activation_dropout
					A__     =  attention_dropout
					A__     =  max_position_embeddings
					A__     =  initializer_range
					A__     =  None
					A__     =  0
					A__     =  2
					A__     =  1






			def   a_			(     self  :       str  )      ->      List[str]:







					"""simple docstring"""






					return XGLMConfig.from_pretrained("""facebook/xglm-564M"""  )






			def   a_			(     self  :       Dict  )      ->      Optional[int]:







					"""simple docstring"""






					A__     =  tf.clip_by_value(
					    ids_tensor([self.batch_size, self.seq_length]				,      self.vocab_size  )				,      clip_value_min=0				,      clip_value_max=3  )

					A__     =  None
					if self.use_input_mask:
							A__     =  random_attention_mask([self.batch_size, self.seq_length]  )

					A__     =  self.get_config()

					A__     =  floats_tensor([self.num_hidden_layers, self.num_attention_heads]				,      2  )

					return (
					    config,
					    input_ids,
					    input_mask,
					    head_mask,
					)






			def   a_			(     self  :       str  )      ->      Tuple:







					"""simple docstring"""






					return XGLMConfig(
					    vocab_size=self.vocab_size				,      d_model=self.hidden_size				,      num_layers=self.num_hidden_layers				,      attention_heads=self.num_attention_heads				,      ffn_dim=self.ffn_dim				,      activation_function=self.activation_function				,      activation_dropout=self.activation_dropout				,      attention_dropout=self.attention_dropout				,      max_position_embeddings=self.max_position_embeddings				,      initializer_range=self.initializer_range				,      use_cache=__lowerCAmelCase				,      bos_token_id=self.bos_token_id				,      eos_token_id=self.eos_token_id				,      pad_token_id=self.pad_token_id				,      return_dict=__lowerCAmelCase				,      )







			def   a_			(     self  :       str  )      ->      Tuple:







					"""simple docstring"""






					A__     =  self.prepare_config_and_inputs()

					(
					    (
					    A__
					) ,     (
					    A__
					) ,     (
					    A__
					) ,     (
					    A__
					) ,     
					)     =  config_and_inputs

					A__     =  {
					    """input_ids""": input_ids,
					    """head_mask""": head_mask,
					}

					return config, inputs_dict


@require_tf
class     A     (SCREAMING_SNAKE_CASE  ,	SCREAMING_SNAKE_CASE  ,	unittest.TestCase       ):
			'''simple docstring'''




			__lowerCamelCase      :			Union[str, Any]							     =       (TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
			__lowerCamelCase      :			Dict							     =       (TFXGLMForCausalLM,) if is_tf_available() else ()
			__lowerCamelCase      :			str							     =       (
			    {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {}
			)
			__lowerCamelCase      :			int							     =       False
			__lowerCamelCase      :			str							     =       False
			__lowerCamelCase      :			Optional[Any]							     =       False






			def   a_			(     self  :       Optional[int]  )      ->      Union[str, Any]:







					"""simple docstring"""






					A__     =  TFXGLMModelTester(self  )
					A__     =  ConfigTester(self				,      config_class=__lowerCAmelCase				,      n_embd=37  )






			def   a_			(     self  :       Optional[int]  )      ->      List[str]:







					"""simple docstring"""






					self.config_tester.run_common_tests()






			@slow
			def   a_			(     self  :       Tuple  )      ->      Optional[Any]:







					"""simple docstring"""






					for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A__     =  TFXGLMModel.from_pretrained(__lowerCAmelCase  )
							self.assertIsNotNone(__lowerCAmelCase  )







			@unittest.skip(reason="""Currently, model embeddings are going to undergo a major refactor."""  )
			def   a_			(     self  :       List[str]  )      ->      List[Any]:







					"""simple docstring"""






					super().test_resize_token_embeddings()


@require_tf
class     A     (unittest.TestCase       ):
			'''simple docstring'''




			@slow
			def   a_			(     self  :       Optional[Any]				,      __lowerCAmelCase  :       int=True  )      ->      List[str]:







					"""simple docstring"""






					A__     =  TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""  )
					A__     =  tf.convert_to_tensor([[2, 2_68, 98_65]]				,      dtype=tf.intaa  )  # The dog
					# </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
					# fmt: off
					A__     =  [2, 2_68, 98_65, 67, 11, 19_88, 5_72_52, 98_65, 5, 9_84, 67, 19_88, 21_38_38, 16_58, 53, 7_04_46, 33, 66_57, 2_78, 15_81]
					# fmt: on
					A__     =  model.generate(__lowerCAmelCase				,      do_sample=__lowerCAmelCase				,      num_beams=1  )
					if verify_outputs:
							self.assertListEqual(output_ids[0].numpy().tolist()				,      __lowerCAmelCase  )






			@slow
			def   a_			(     self  :       Union[str, Any]  )      ->      List[str]:







					"""simple docstring"""






					A__     =  XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""  )
					A__     =  TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""  )

					tf.random.set_seed(0  )
					A__     =  tokenizer("""Today is a nice day and"""				,      return_tensors="""tf"""  )
					A__     =  tokenized.input_ids
					# forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
					with tf.device(""":/CPU:0"""  ):
							A__     =  model.generate(__lowerCAmelCase				,      do_sample=__lowerCAmelCase				,      seed=[7, 0]  )
					A__     =  tokenizer.decode(output_ids[0]				,      skip_special_tokens=__lowerCAmelCase  )

					A__     =  (
					    """Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due"""
					)
					self.assertEqual(__lowerCAmelCase				,      __lowerCAmelCase  )







			@slow
			def   a_			(     self  :       int  )      ->      int:







					"""simple docstring"""






					A__     =  TFXGLMForCausalLM.from_pretrained("""facebook/xglm-564M"""  )
					A__     =  XGLMTokenizer.from_pretrained("""facebook/xglm-564M"""  )

					A__     =  """left"""

					# use different length sentences to test batching
					A__     =  [
					    """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
					    """left-padding, such as in batched generation. The output for the sequence below should be the same """
					    """regardless of whether left padding is applied or not. When""",
					    """Hello, my dog is a little""",
					]

					A__     =  tokenizer(__lowerCAmelCase				,      return_tensors="""tf"""				,      padding=__lowerCAmelCase  )
					A__     =  inputs["""input_ids"""]

					A__     =  model.generate(input_ids=__lowerCAmelCase				,      attention_mask=inputs["""attention_mask"""]				,      max_new_tokens=12  )

					A__     =  tokenizer(sentences[0]				,      return_tensors="""tf"""  ).input_ids
					A__     =  model.generate(input_ids=__lowerCAmelCase				,      max_new_tokens=12  )

					A__     =  tokenizer(sentences[1]				,      return_tensors="""tf"""  ).input_ids
					A__     =  model.generate(input_ids=__lowerCAmelCase				,      max_new_tokens=12  )

					A__     =  tokenizer.batch_decode(__lowerCAmelCase				,      skip_special_tokens=__lowerCAmelCase  )
					A__     =  tokenizer.decode(output_non_padded[0]				,      skip_special_tokens=__lowerCAmelCase  )
					A__     =  tokenizer.decode(output_padded[0]				,      skip_special_tokens=__lowerCAmelCase  )

					A__     =  [
					    """This is an extremelly long sentence that only exists to test the ability of the model to cope with """
					    """left-padding, such as in batched generation. The output for the sequence below should be the same """
					    """regardless of whether left padding is applied or not. When left padding is applied, the sequence will be """
					    """a single""",
					    """Hello, my dog is a little bit of a shy one, but he is very friendly""",
					]
					self.assertListEqual(__lowerCAmelCase				,      __lowerCAmelCase  )
					self.assertListEqual(__lowerCAmelCase				,      [non_padded_sentence, padded_sentence]  )










import multiprocessing
from typing import TYPE_CHECKING, Optional, Union

from .. import Dataset, Features, config
from ..formatting import query_table
from ..packaged_modules.sql.sql import Sql
from ..utils import logging
from .abc import AbstractDatasetInputStream


if TYPE_CHECKING:
					import sqlitea

					import sqlalchemy


class     A     (SCREAMING_SNAKE_CASE       ):
			'''simple docstring'''




			def __init__(     self  :       Any				,      __lowerCAmelCase  :       Union[str, "sqlalchemy.sql.Selectable"]				,      __lowerCAmelCase  :       Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]				,      __lowerCAmelCase  :       Optional[Features] = None				,      __lowerCAmelCase  :       str = None				,      __lowerCAmelCase  :       bool = False				,      **__lowerCAmelCase  :       Dict				,      )      ->      Any:







					"""simple docstring"""






					super().__init__(features=__lowerCAmelCase				,      cache_dir=__lowerCAmelCase				,      keep_in_memory=__lowerCAmelCase				,      **__lowerCAmelCase  )
					A__     =  Sql(
					    cache_dir=__lowerCAmelCase				,      features=__lowerCAmelCase				,      sql=__lowerCAmelCase				,      con=__lowerCAmelCase				,      **__lowerCAmelCase				,      )







			def   a_			(     self  :       Optional[int]  )      ->      Optional[int]:







					"""simple docstring"""






					A__     =  None
					A__     =  None
					A__     =  None
					A__     =  None

					self.builder.download_and_prepare(
					    download_config=__lowerCAmelCase				,      download_mode=__lowerCAmelCase				,      verification_mode=__lowerCAmelCase				,      base_path=__lowerCAmelCase				,      )

					# Build dataset for splits
					A__     =  self.builder.as_dataset(
					    split="""train"""				,      verification_mode=__lowerCAmelCase				,      in_memory=self.keep_in_memory  )
					return dataset


class     A     :
			'''simple docstring'''




			def __init__(     self  :       Optional[int]				,      __lowerCAmelCase  :       Dataset				,      __lowerCAmelCase  :       str				,      __lowerCAmelCase  :       Union[str, "sqlalchemy.engine.Connection", "sqlalchemy.engine.Engine", "sqlite3.Connection"]				,      __lowerCAmelCase  :       Optional[int] = None				,      __lowerCAmelCase  :       Optional[int] = None				,      **__lowerCAmelCase  :       List[Any]				,      )      ->      Any:







					"""simple docstring"""






					if num_proc is not None and num_proc <= 0:
							raise ValueError(f'num_proc {num_proc} must be an integer > 0.'  )

					A__     =  dataset
					A__     =  name
					A__     =  con
					A__     =  batch_size if batch_size else config.DEFAULT_MAX_BATCH_SIZE
					A__     =  num_proc
					A__     =  to_sql_kwargs






			def   a_			(     self  :       Any  )      ->      int:







					"""simple docstring"""






					A__     =  self.to_sql_kwargs.pop("""sql"""				,      __lowerCAmelCase  )
					A__     =  self.to_sql_kwargs.pop("""con"""				,      __lowerCAmelCase  )
					A__     =  self.to_sql_kwargs.pop("""index"""				,      __lowerCAmelCase  )

					A__     =  self._write(index=__lowerCAmelCase				,      **self.to_sql_kwargs  )
					return written






			def   a_			(     self  :       Union[str, Any]				,      __lowerCAmelCase  :       Optional[Any]  )      ->      Optional[Any]:







					"""simple docstring"""






					A__ ,     A__ ,     A__     =  args
					A__     =  {**to_sql_kwargs, """if_exists""": """append"""} if offset > 0 else to_sql_kwargs
					A__     =  query_table(
					    table=self.dataset.data				,      key=slice(__lowerCAmelCase				,      offset + self.batch_size  )				,      indices=self.dataset._indices				,      )
					A__     =  batch.to_pandas()
					A__     =  df.to_sql(self.name				,      self.con				,      index=__lowerCAmelCase				,      **__lowerCAmelCase  )
					return num_rows or len(__lowerCAmelCase  )







			def   a_			(     self  :       Optional[int]				,      __lowerCAmelCase  :       Tuple				,      **__lowerCAmelCase  :       Dict  )      ->      int:







					"""simple docstring"""






					A__     =  0

					if self.num_proc is None or self.num_proc == 1:
							for offset in logging.tqdm(
							    range(0				,      len(self.dataset  )				,      self.batch_size  )				,      unit="""ba"""				,      disable=not logging.is_progress_bar_enabled()				,      desc="""Creating SQL from Arrow format"""				,      ):
									written += self._batch_sql((offset, index, to_sql_kwargs)  )
					else:
							A__ ,     A__     =  len(self.dataset  ), self.batch_size
							with multiprocessing.Pool(self.num_proc  ) as pool:
									for num_rows in logging.tqdm(
									    pool.imap(
									        self._batch_sql				,      [(offset, index, to_sql_kwargs) for offset in range(0				,      __lowerCAmelCase				,      __lowerCAmelCase  )]				,      )				,      total=(num_rows // batch_size) + 1 if num_rows % batch_size else num_rows // batch_size				,      unit="""ba"""				,      disable=not logging.is_progress_bar_enabled()				,      desc="""Creating SQL from Arrow format"""				,      ):
											written += num_rows

					return written



