





import argparse
from typing import List

import evaluate
import numpy as np
import torch
from datasets import DatasetDict, load_dataset

# New Code #
# We'll be using StratifiedKFold for this example
from sklearn.model_selection import StratifiedKFold
from torch.optim import AdamW
from torch.utils.data import DataLoader
from transformers import AutoModelForSequenceClassification, AutoTokenizer, get_linear_schedule_with_warmup, set_seed

from accelerate import Accelerator, DistributedType


########################################################################
# This is a fully working simple example to use Accelerate,
# specifically showcasing how to perform Cross Validation,
# and builds off the `nlp_example.py` script.
#
# This example trains a Bert base model on GLUE MRPC
# in any of the following settings (with the same script):
#   - single CPU or single GPU
#   - multi GPUS (using PyTorch distributed mode)
#   - (multi) TPUs
#   - fp16 (mixed-precision) or fp32 (normal precision)
#
# To help focus on the differences in the code, building `DataLoaders`
# was refactored into its own function.
# New additions from the base script can be found quickly by
# looking for the # New Code # tags
#
# To run it in each of these various modes, follow the instructions
# in the readme for examples:
# https://github.com/huggingface/accelerate/tree/main/examples
#
########################################################################


UpperCamelCase__											= 16
UpperCamelCase__											= 32





def     _UpperCamelCase     (a__   :Accelerator   ,			a__   :DatasetDict   ,			a__   :List[int]   ,			a__   :List[int]   ,			a__   :int = 16       ):






							"""simple docstring"""





							UpperCamelCase__				     =			AutoTokenizer.from_pretrained("""bert-base-cased"""       )
							UpperCamelCase__				     =			DatasetDict(
							    {
							        """train""": dataset["""train"""].select(a__       ),
							        """validation""": dataset["""train"""].select(a__       ),
							        """test""": dataset["""validation"""],
							    }       )

							def tokenize_function(a__   :Optional[int]       ):
														# max_length=None => use the model max length (it's actually the default)
														UpperCamelCase__				     =			tokenizer(examples["""sentence1"""]   ,			examples["""sentence2"""]   ,			truncation=a__   ,			max_length=a__       )
														return outputs

							# Apply the method we just defined to all the examples in all the splits of the dataset
							# starting with the main process first:
							with accelerator.main_process_first():
														UpperCamelCase__				     =			datasets.map(
														    a__   ,			batched=a__   ,			remove_columns=["""idx""", """sentence1""", """sentence2"""]   ,			)

							# We also rename the 'label' column to 'labels' which is the expected name for labels by the models of the
							# transformers library
							UpperCamelCase__				     =			tokenized_datasets.rename_column("""label"""   ,			"""labels"""       )

							def collate_fn(a__   :int       ):
														# On TPU it's best to pad everything to the same length or training will be very slow.
														UpperCamelCase__				     =			128 if accelerator.distributed_type == DistributedType.TPU else None
														# When using mixed precision we want round multiples of 8/16
														if accelerator.mixed_precision == "fp8":
																					UpperCamelCase__				     =			16
														elif accelerator.mixed_precision != "no":
																					UpperCamelCase__				     =			8
														else:
																					UpperCamelCase__				     =			None

														return tokenizer.pad(
														    a__   ,			padding="""longest"""   ,			max_length=a__   ,			pad_to_multiple_of=a__   ,			return_tensors="""pt"""   ,			)

							# Instantiate dataloaders.
							UpperCamelCase__				     =			DataLoader(
							    tokenized_datasets["""train"""]   ,			shuffle=a__   ,			collate_fn=a__   ,			batch_size=a__       )
							UpperCamelCase__				     =			DataLoader(
							    tokenized_datasets["""validation"""]   ,			shuffle=a__   ,			collate_fn=a__   ,			batch_size=a__       )

							UpperCamelCase__				     =			DataLoader(
							    tokenized_datasets["""test"""]   ,			shuffle=a__   ,			collate_fn=a__   ,			batch_size=a__       )

							return train_dataloader, eval_dataloader, test_dataloader





def     _UpperCamelCase     (a__   :Any   ,			a__   :int       ):






							"""simple docstring"""





							UpperCamelCase__				     =			[]
							# Download the dataset
							UpperCamelCase__				     =			load_dataset("""glue"""   ,			"""mrpc"""       )
							# Create our splits
							UpperCamelCase__				     =			StratifiedKFold(n_splits=int(args.num_folds       )       )
							# Initialize accelerator
							UpperCamelCase__				     =			Accelerator(cpu=args.cpu   ,			mixed_precision=args.mixed_precision       )
							# Sample hyper-parameters for learning rate, batch size, seed and a few other HPs
							UpperCamelCase__				     =			config["""lr"""]
							UpperCamelCase__				     =			int(config["""num_epochs"""]       )
							UpperCamelCase__				     =			int(config["""seed"""]       )
							UpperCamelCase__				     =			int(config["""batch_size"""]       )

							UpperCamelCase__				     =			evaluate.load("""glue"""   ,			"""mrpc"""       )

							# If the batch size is too big we use gradient accumulation
							UpperCamelCase__				     =			1
							if batch_size > MAX_GPU_BATCH_SIZE and accelerator.distributed_type != DistributedType.TPU:
														UpperCamelCase__				     =			batch_size // MAX_GPU_BATCH_SIZE
														UpperCamelCase__				     =			MAX_GPU_BATCH_SIZE

							set_seed(a__       )

							# New Code #
							# Create our folds:
							UpperCamelCase__				     =			kfold.split(np.zeros(datasets["""train"""].num_rows       )   ,			datasets["""train"""]["""label"""]       )
							UpperCamelCase__				     =			[]
							# Iterate over them
							for i, (train_idxs, valid_idxs) in enumerate(a__       ):
														UpperCamelCase__     ,     UpperCamelCase__     ,     UpperCamelCase__				     =			get_fold_dataloaders(
														    a__   ,			a__   ,			a__   ,			a__   ,			)
														# Instantiate the model (we build the model here so that the seed also control new weights initialization)
														UpperCamelCase__				     =			AutoModelForSequenceClassification.from_pretrained("""bert-base-cased"""   ,			return_dict=a__       )

														# We could avoid this line since the accelerator is set with `device_placement=True` (default value).
														# Note that if you are placing tensors on devices manually, this line absolutely needs to be before the optimizer
														# creation otherwise training will not work on TPU (`accelerate` will kindly throw an error to make us aware of that).
														UpperCamelCase__				     =			model.to(accelerator.device       )

														# Instantiate optimizer
														UpperCamelCase__				     =			AdamW(params=model.parameters()   ,			lr=a__       )

														# Instantiate scheduler
														UpperCamelCase__				     =			get_linear_schedule_with_warmup(
														    optimizer=a__   ,			num_warmup_steps=100   ,			num_training_steps=(len(a__       ) * num_epochs) // gradient_accumulation_steps   ,			)

														# Prepare everything
														# There is no specific order to remember, we just need to unpack the objects in the same order we gave them to the
														# prepare method.
														UpperCamelCase__     ,     UpperCamelCase__     ,     UpperCamelCase__     ,     UpperCamelCase__     ,     UpperCamelCase__				     =			accelerator.prepare(
														    a__   ,			a__   ,			a__   ,			a__   ,			a__       )

														# Now we train the model
														for epoch in range(a__       ):
																					model.train()
																					for step, batch in enumerate(a__       ):
																												# We could avoid this line since we set the accelerator with `device_placement=True`.
																												batch.to(accelerator.device       )
																												UpperCamelCase__				     =			model(**a__       )
																												UpperCamelCase__				     =			outputs.loss
																												UpperCamelCase__				     =			loss / gradient_accumulation_steps
																												accelerator.backward(a__       )
																												if step % gradient_accumulation_steps == 0:
																																			optimizer.step()
																																			lr_scheduler.step()
																																			optimizer.zero_grad()

																					model.eval()
																					for step, batch in enumerate(a__       ):
																												# We could avoid this line since we set the accelerator with `device_placement=True`.
																												batch.to(accelerator.device       )
																												with torch.no_grad():
																																			UpperCamelCase__				     =			model(**a__       )
																												UpperCamelCase__				     =			outputs.logits.argmax(dim=-1       )
																												UpperCamelCase__     ,     UpperCamelCase__				     =			accelerator.gather_for_metrics((predictions, batch["""labels"""])       )
																												metric.add_batch(
																												    predictions=a__   ,			references=a__   ,			)

																					UpperCamelCase__				     =			metric.compute()
																					# Use accelerator.print to print only on the main process.
																					accelerator.print(f"""epoch {epoch}:"""   ,			a__       )

														# New Code #
														# We also run predictions on the test set at the very end
														UpperCamelCase__				     =			[]
														for step, batch in enumerate(a__       ):
																					# We could avoid this line since we set the accelerator with `device_placement=True`.
																					batch.to(accelerator.device       )
																					with torch.no_grad():
																												UpperCamelCase__				     =			model(**a__       )
																					UpperCamelCase__				     =			outputs.logits
																					UpperCamelCase__     ,     UpperCamelCase__				     =			accelerator.gather_for_metrics((predictions, batch["""labels"""])       )
																					fold_predictions.append(predictions.cpu()       )
																					if i == 0:
																												# We need all of the test predictions
																												test_references.append(references.cpu()       )
        # Use accelerator.print to print only on the main process.
														test_predictions.append(torch.cat(a__   ,			dim=0       )       )
														# We now need to release all our memory and get rid of the current model, optimizer, etc
														accelerator.free_memory()
							# New Code #
							# Finally we check the accuracy of our folded results:
							UpperCamelCase__				     =			torch.cat(a__   ,			dim=0       )
							UpperCamelCase__				     =			torch.stack(a__   ,			dim=0       ).sum(dim=0       ).div(int(args.num_folds       )       ).argmax(dim=-1       )
							UpperCamelCase__				     =			metric.compute(predictions=a__   ,			references=a__       )
							accelerator.print("""Average test metrics from all folds:"""   ,			a__       )





def     _UpperCamelCase     ():






							"""simple docstring"""





							UpperCamelCase__				     =			argparse.ArgumentParser(description="""Simple example of training script."""       )
							parser.add_argument(
							    """--mixed_precision"""   ,			type=a__   ,			default=a__   ,			choices=["""no""", """fp16""", """bf16""", """fp8"""]   ,			help="""Whether to use mixed precision. Choose"""
							    """between fp16 and bf16 (bfloat16). Bf16 requires PyTorch >= 1.10."""
							    """and an Nvidia Ampere GPU."""   ,			)
							parser.add_argument("""--cpu"""   ,			action="""store_true"""   ,			help="""If passed, will train on the CPU."""       )
							# New Code #
							parser.add_argument("""--num_folds"""   ,			type=a__   ,			default=3   ,			help="""The number of splits to perform across the dataset"""       )
							UpperCamelCase__				     =			parser.parse_args()
							UpperCamelCase__				     =			{"""lr""": 2e-5, """num_epochs""": 3, """seed""": 42, """batch_size""": 16}
							training_function(a__   ,			a__       )


if __name__ == "__main__":
					main()











import unittest

from transformers import (
    MODEL_FOR_CAUSAL_LM_MAPPING,
    TF_MODEL_FOR_CAUSAL_LM_MAPPING,
    TextGenerationPipeline,
    logging,
    pipeline,
)
from transformers.testing_utils import (
    CaptureLogger,
    is_pipeline_test,
    require_accelerate,
    require_tf,
    require_torch,
    require_torch_gpu,
    require_torch_or_tf,
)

from .test_pipelines_common import ANY

@is_pipeline_test
@require_torch_or_tf
class        __SCREAMING_SNAKE_CASE					(     unittest.TestCase       ):
							snake_case     :      Union[str, Any]						     =       MODEL_FOR_CAUSAL_LM_MAPPING
							snake_case     :      List[str]						     =       TF_MODEL_FOR_CAUSAL_LM_MAPPING






							@require_torch
							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			pipeline(task="""text-generation"""  , model="""sshleifer/tiny-ctrl"""  , framework="""pt"""  )
														# Using `do_sample=False` to force deterministic output
														UpperCamelCase__				     =			text_generator("""This is a test"""  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope."""
														                """ oscope. FiliFili@@"""
														            )
														        }
														    ]  , )

														UpperCamelCase__				     =			text_generator(["""This is a test""", """This is a second test"""]  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [
														            {
														                """generated_text""": (
														                    """This is a test ☃ ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy oscope."""
														                    """ oscope. FiliFili@@"""
														                )
														            }
														        ],
														        [
														            {
														                """generated_text""": (
														                    """This is a second test ☃ segmental segmental segmental 议议eski eski flutter flutter Lacy"""
														                    """ oscope. oscope. FiliFili@@"""
														                )
														            }
														        ],
														    ]  , )

														UpperCamelCase__				     =			text_generator("""This is a test"""  , do_sample=__lowerCAmelCase  , num_return_sequences=2  , return_tensors=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														        {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														    ]  , )
														UpperCamelCase__				     =			text_generator.model.config.eos_token_id
														UpperCamelCase__				     =			"""<pad>"""
														UpperCamelCase__				     =			text_generator(
														    ["""This is a test""", """This is a second test"""]  , do_sample=__lowerCAmelCase  , num_return_sequences=2  , batch_size=2  , return_tensors=__lowerCAmelCase  , )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														        ],
														        [
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														            {"""generated_token_ids""": ANY(__lowerCAmelCase  )},
														        ],
														    ]  , )






							@require_tf
							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			pipeline(task="""text-generation"""  , model="""sshleifer/tiny-ctrl"""  , framework="""tf"""  )

														# Using `do_sample=False` to force deterministic output
														UpperCamelCase__				     =			text_generator("""This is a test"""  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵"""
														                """ please,"""
														            )
														        }
														    ]  , )

														UpperCamelCase__				     =			text_generator(["""This is a test""", """This is a second test"""]  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [
														            {
														                """generated_text""": (
														                    """This is a test FeyFeyFey(Croatis.), s.), Cannes Cannes Cannes 閲閲Cannes Cannes Cannes 攵"""
														                    """ please,"""
														                )
														            }
														        ],
														        [
														            {
														                """generated_text""": (
														                    """This is a second test Chieftain Chieftain prefecture prefecture prefecture Cannes Cannes"""
														                    """ Cannes 閲閲Cannes Cannes Cannes 攵 please,"""
														                )
														            }
														        ],
														    ]  , )






							def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  , __lowerCAmelCase  ):
														UpperCamelCase__				     =			TextGenerationPipeline(model=__lowerCAmelCase  , tokenizer=__lowerCAmelCase  )
														return text_generator, ["This is a test", "Another test"]






							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			"""Hello I believe in"""
														UpperCamelCase__				     =			pipeline("""text-generation"""  , model="""hf-internal-testing/tiny-random-gpt2"""  )
														UpperCamelCase__				     =			text_generator(__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [{"""generated_text""": """Hello I believe in fe fe fe fe fe fe fe fe fe fe fe fe"""}]  , )

														UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , stop_sequence=""" fe"""  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": """Hello I believe in fe"""}]  )






							def 				_lowerCamelCase		(						self  , __lowerCAmelCase  , __lowerCAmelCase  ):
														UpperCamelCase__				     =			text_generator.model
														UpperCamelCase__				     =			text_generator.tokenizer

														UpperCamelCase__				     =			text_generator("""This is a test"""  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test"""  )  )

														UpperCamelCase__				     =			text_generator("""This is a test"""  , return_full_text=__lowerCAmelCase  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertNotIn("""This is a test"""  , outputs[0]["""generated_text"""]  )

														UpperCamelCase__				     =			pipeline(task="""text-generation"""  , model=__lowerCAmelCase  , tokenizer=__lowerCAmelCase  , return_full_text=__lowerCAmelCase  )
														UpperCamelCase__				     =			text_generator("""This is a test"""  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertNotIn("""This is a test"""  , outputs[0]["""generated_text"""]  )

														UpperCamelCase__				     =			text_generator("""This is a test"""  , return_full_text=__lowerCAmelCase  )
														self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														self.assertTrue(outputs[0]["""generated_text"""].startswith("""This is a test"""  )  )

														UpperCamelCase__				     =			text_generator(["""This is great !""", """Something else"""]  , num_return_sequences=2  , do_sample=__lowerCAmelCase  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
														        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
														    ]  , )

														if text_generator.tokenizer.pad_token is not None:
																					UpperCamelCase__				     =			text_generator(
																					    ["""This is great !""", """Something else"""]  , num_return_sequences=2  , batch_size=2  , do_sample=__lowerCAmelCase  )
																					self.assertEqual(
																					    __lowerCAmelCase  , [
																					        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
																					        [{"""generated_text""": ANY(__lowerCAmelCase  )}, {"""generated_text""": ANY(__lowerCAmelCase  )}],
																					    ]  , )

														with self.assertRaises(__lowerCAmelCase  ):
																					UpperCamelCase__				     =			text_generator("""test"""  , return_full_text=__lowerCAmelCase  , return_text=__lowerCAmelCase  )
														with self.assertRaises(__lowerCAmelCase  ):
																					UpperCamelCase__				     =			text_generator("""test"""  , return_full_text=__lowerCAmelCase  , return_tensors=__lowerCAmelCase  )
														with self.assertRaises(__lowerCAmelCase  ):
																					UpperCamelCase__				     =			text_generator("""test"""  , return_text=__lowerCAmelCase  , return_tensors=__lowerCAmelCase  )

														# Empty prompt is slighly special
														# it requires BOS token to exist.
														# Special case for Pegasus which will always append EOS so will
														# work even without BOS.
														if (
														    text_generator.tokenizer.bos_token_id is not None
														    or "Pegasus" in tokenizer.__class__.__name__
														    or "Git" in model.__class__.__name__
														):
																					UpperCamelCase__				     =			text_generator(""""""  )
																					self.assertEqual(__lowerCAmelCase  , [{"""generated_text""": ANY(__lowerCAmelCase  )}]  )
														else:
																					with self.assertRaises((ValueError, AssertionError)  ):
																												UpperCamelCase__				     =			text_generator(""""""  )

														if text_generator.framework == "tf":
																					# TF generation does not support max_new_tokens, and it's impossible
																					# to control long generation with only max_length without
																					# fancy calculation, dismissing tests for now.
																					return
														# We don't care about infinite range models.
														# They already work.
														# Skip this test for XGLM, since it uses sinusoidal positional embeddings which are resized on-the-fly.
														UpperCamelCase__				     =			["""RwkvForCausalLM""", """XGLMForCausalLM""", """GPTNeoXForCausalLM"""]
														if (
														    tokenizer.model_max_length < 10000
														    and text_generator.model.__class__.__name__ not in EXTRA_MODELS_CAN_HANDLE_LONG_INPUTS
														):
																					# Handling of large generations
																					with self.assertRaises((RuntimeError, IndexError, ValueError, AssertionError)  ):
																												text_generator("""This is a test""" * 500  , max_new_tokens=20  )

																					UpperCamelCase__				     =			text_generator("""This is a test""" * 500  , handle_long_generation="""hole"""  , max_new_tokens=20  )
																					# Hole strategy cannot work
																					with self.assertRaises(__lowerCAmelCase  ):
																												text_generator(
																												    """This is a test""" * 500  , handle_long_generation="""hole"""  , max_new_tokens=tokenizer.model_max_length + 10  , )






							@require_torch
							@require_accelerate
							@require_torch_gpu
							def 				_lowerCamelCase		(						self  ):
														import torch

														# Classic `model_kwargs`
														UpperCamelCase__				     =			pipeline(
														    model="""hf-internal-testing/tiny-random-bloom"""  , model_kwargs={"""device_map""": """auto""", """torch_dtype""": torch.bfloataa}  , )
														self.assertEqual(pipe.model.device  , torch.device(0  )  )
														self.assertEqual(pipe.model.lm_head.weight.dtype  , torch.bfloataa  )
														UpperCamelCase__				     =			pipe("""This is a test"""  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test test test test test test test test test test test test test test test test"""
														                """ test"""
														            )
														        }
														    ]  , )

														# Upgraded those two to real pipeline arguments (they just get sent for the model as they're unlikely to mean anything else.)
														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device_map="""auto"""  , torch_dtype=torch.bfloataa  )
														self.assertEqual(pipe.model.device  , torch.device(0  )  )
														self.assertEqual(pipe.model.lm_head.weight.dtype  , torch.bfloataa  )
														UpperCamelCase__				     =			pipe("""This is a test"""  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test test test test test test test test test test test test test test test test"""
														                """ test"""
														            )
														        }
														    ]  , )

														# torch_dtype will be automatically set to float32 if not provided - check: https://github.com/huggingface/transformers/pull/20602
														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device_map="""auto"""  )
														self.assertEqual(pipe.model.device  , torch.device(0  )  )
														self.assertEqual(pipe.model.lm_head.weight.dtype  , torch.floataa  )
														UpperCamelCase__				     =			pipe("""This is a test"""  )
														self.assertEqual(
														    __lowerCAmelCase  , [
														        {
														            """generated_text""": (
														                """This is a test test test test test test test test test test test test test test test test"""
														                """ test"""
														            )
														        }
														    ]  , )






							@require_torch
							@require_torch_gpu
							def 				_lowerCamelCase		(						self  ):
														import torch

														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device=0  , torch_dtype=torch.floataa  )
														pipe("""This is a test"""  )






							@require_torch
							@require_accelerate
							@require_torch_gpu
							def 				_lowerCamelCase		(						self  ):
														import torch

														UpperCamelCase__				     =			pipeline(model="""hf-internal-testing/tiny-random-bloom"""  , device_map="""auto"""  , torch_dtype=torch.floataa  )
														pipe("""This is a test"""  , do_sample=__lowerCAmelCase  , top_p=0.5  )







							def 				_lowerCamelCase		(						self  ):
														UpperCamelCase__				     =			"""Hello world"""
														UpperCamelCase__				     =			pipeline("""text-generation"""  , model="""hf-internal-testing/tiny-random-gpt2"""  )
														if text_generator.model.framework == "tf":
																					UpperCamelCase__				     =			logging.get_logger("""transformers.generation.tf_utils"""  )
														else:
																					UpperCamelCase__				     =			logging.get_logger("""transformers.generation.utils"""  )
														UpperCamelCase__				     =			"""Both `max_new_tokens`"""  # The beggining of the message to be checked in this test

														# Both are set by the user -> log warning
														with CaptureLogger(__lowerCAmelCase  ) as cl:
																					UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , max_length=10  , max_new_tokens=1  )
														self.assertIn(__lowerCAmelCase  , cl.out  )

														# The user only sets one -> no warning
														with CaptureLogger(__lowerCAmelCase  ) as cl:
																					UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , max_new_tokens=1  )
														self.assertNotIn(__lowerCAmelCase  , cl.out  )

														with CaptureLogger(__lowerCAmelCase  ) as cl:
																					UpperCamelCase__				     =			text_generator(__lowerCAmelCase  , max_length=10  )
														self.assertNotIn(__lowerCAmelCase  , cl.out  )




