




'''simple docstring'''




import csv
import json
import logging
import os
import re
import subprocess
import tempfile
import unittest
import zipfile
from pathlib import Path
from typing import Optional
from unittest import mock

import torch

# We use TF to parse the logs
from accelerate import Accelerator
from accelerate.test_utils.testing import (
    MockingTestCase,
    TempDirTestCase,
    require_comet_ml,
    require_tensorboard,
    require_wandb,
    skip,
)
from accelerate.tracking import CometMLTracker, GeneralTracker
from accelerate.utils import ProjectConfiguration, is_comet_ml_available, is_tensorboard_available


if is_comet_ml_available():
     from comet_ml import OfflineExperiment

if is_tensorboard_available():
     import struct

     import tensorboard.compat.proto.event_pba as event_pba

a_   :	str							   = logging.getLogger(__name__)


@require_tensorboard
class 						__UpperCamelCase (				unittest.TestCase       ):






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							='''test_project_with_config'''
              with tempfile.TemporaryDirectory() as dirpath:
                     lowerCamelCase_							=Accelerator(log_with='''tensorboard''',	project_dir=lowerCAmelCase						)
                     lowerCamelCase_							={'''num_iterations''': 12, '''learning_rate''': 1e-2, '''some_boolean''': False, '''some_string''': '''some_value'''}
                     accelerator.init_trackers(lowerCAmelCase,	lowerCAmelCase						)
                     accelerator.end_training()
                     for child in Path(f'''{dirpath}/{project_name}'''						).glob('''*/**'''						):
                            lowerCamelCase_							=list(filter(lambda lowerCAmelCase						: x.is_file(),	child.iterdir()						)						)[0]
                     self.assertNotEqual(str(lowerCAmelCase						),	''''''						)






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							='''test_project_with_log'''
              with tempfile.TemporaryDirectory() as dirpath:
                     lowerCamelCase_							=Accelerator(log_with='''tensorboard''',	project_dir=lowerCAmelCase						)
                     accelerator.init_trackers(lowerCAmelCase						)
                     lowerCamelCase_							={'''total_loss''': 0.1, '''iteration''': 1, '''my_text''': '''some_value'''}
                     accelerator.log(lowerCAmelCase,	step=0						)
                     accelerator.end_training()
                     # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
                     # Names are randomly generated each time
                     lowerCamelCase_							=list(filter(lambda lowerCAmelCase						: x.is_file(),	Path(f'''{dirpath}/{project_name}'''						).iterdir()						)						)[0]
                     self.assertNotEqual(str(lowerCAmelCase						),	''''''						)






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							='''test_project_with_log'''
              with tempfile.TemporaryDirectory() as dirpath:
                     lowerCamelCase_							=Accelerator(log_with='''tensorboard''',	project_dir=lowerCAmelCase						)
                     accelerator.init_trackers(lowerCAmelCase						)
                     lowerCamelCase_							={'''tensor''': torch.tensor(1						)}
                     accelerator.log(lowerCAmelCase,	step=0						)
                     accelerator.end_training()
                     # Logged values are stored in the outermost-tfevents file and can be read in as a TFRecord
                     # Names are randomly generated each time
                     lowerCamelCase_							=list(filter(lambda lowerCAmelCase						: x.is_file(),	Path(f'''{dirpath}/{project_name}'''						).iterdir()						)						)[0]
                     # Reading implementation based on https://github.com/pytorch/pytorch/issues/45327#issuecomment-703757685
                     with open(lowerCAmelCase,	'''rb'''						) as f:
                            lowerCamelCase_							=f.read()
                     lowerCamelCase_							=False
                     while data:
                            lowerCamelCase_							=struct.unpack('''Q''',	data[:8]						)

                            lowerCamelCase_							=data[12 : 12 + int(header[0]						)]  # 8+4
                            lowerCamelCase_							=data[12 + int(header[0]						) + 4 :]
                            lowerCamelCase_							=event_pba.Event()

                            event.ParseFromString(lowerCAmelCase						)
                            if event.HasField('''summary'''						):
                                   for value in event.summary.value:
                                          if value.simple_value == 1.0 and value.tag == "tensor":
                                                 lowerCamelCase_							=True
                     self.assertTrue(lowerCAmelCase,	'''Converted tensor was not found in the log file!'''						)






       def   lowercase__  (							self						):



              """simple docstring"""







              with self.assertRaisesRegex(lowerCAmelCase,	'''Logging with `tensorboard` requires a `logging_dir`'''						):
                     lowerCamelCase_							=Accelerator(log_with='''tensorboard'''						)
              with tempfile.TemporaryDirectory() as dirpath:
                     lowerCamelCase_							=Accelerator(log_with='''tensorboard''',	project_dir=lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=ProjectConfiguration(total_limit=30						)
              with tempfile.TemporaryDirectory() as dirpath:
                     lowerCamelCase_							=Accelerator(log_with='''tensorboard''',	project_dir=lowerCAmelCase,	project_config=lowerCAmelCase						)





@require_wandb
@mock.patch.dict(os.environ    ,      {'WANDB_MODE': 'offline'}       )
class 						__UpperCamelCase (				lowerCamelCase__    ,      lowerCamelCase__       ):






       def   lowercase__  (							self						):



              """simple docstring"""







              super().setUp()
              # wandb let's us override where logs are stored to via the WANDB_DIR env var
              self.add_mocks(mock.patch.dict(os.environ,	{'''WANDB_DIR''': self.tmpdir}						)						)






       @staticmethod
       def   lowercase__  (							lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase = True						):



              """simple docstring"""







              lowerCamelCase_							=Rf'''{section} ([\S\s]*?)\n\n'''
              if record:
                     lowerCamelCase_							=Rf'''Record: {pattern}'''
              lowerCamelCase_							=re.findall(lowerCAmelCase,	lowerCAmelCase						)[0]
              # A config
              if section == "config" or section == "history":
                     lowerCamelCase_							=re.findall(R'''"([a-zA-Z0-9_.,]+)''',	lowerCAmelCase						)
                     return {key: val for key, val in zip(cleaned_record[0::2],	cleaned_record[1::2]						)}
              # Everything else
              else:
                     return dict(re.findall(R'''(\w+): "([^\s]+)"''',	lowerCAmelCase						)						)






       @skip
       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							='''test_project_with_config'''
              lowerCamelCase_							=Accelerator(log_with='''wandb'''						)
              lowerCamelCase_							={'''num_iterations''': 12, '''learning_rate''': 1e-2, '''some_boolean''': False, '''some_string''': '''some_value'''}
              lowerCamelCase_							={'''wandb''': {'''tags''': ['''my_tag''']}}
              accelerator.init_trackers(lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase						)
              lowerCamelCase_							={'''total_loss''': 0.1, '''iteration''': 1, '''my_text''': '''some_value'''}
              accelerator.log(lowerCAmelCase,	step=0						)
              accelerator.end_training()
              # The latest offline log is stored at wandb/latest-run/*.wandb
              for child in Path(f'''{self.tmpdir}/wandb/latest-run'''						).glob('''*'''						):
                     if child.is_file() and child.suffix == ".wandb":
                            lowerCamelCase_							=subprocess.check_output(
                                ['''wandb''', '''sync''', '''--view''', '''--verbose''', str(lowerCAmelCase						)],	env=os.environ.copy()						).decode('''utf8''',	'''ignore'''						)
                            break

        # Check HPS through careful parsing and cleaning
              lowerCamelCase_							=self.parse_log(lowerCAmelCase,	'''config'''						)
              self.assertEqual(logged_items['''num_iterations'''],	'''12'''						)
              self.assertEqual(logged_items['''learning_rate'''],	'''0.01'''						)
              self.assertEqual(logged_items['''some_boolean'''],	'''false'''						)
              self.assertEqual(logged_items['''some_string'''],	'''some_value'''						)
              self.assertEqual(logged_items['''some_string'''],	'''some_value'''						)

              # Run tags
              lowerCamelCase_							=self.parse_log(lowerCAmelCase,	'''run''',	lowerCAmelCase						)
              self.assertEqual(logged_items['''tags'''],	'''my_tag'''						)

              # Actual logging
              lowerCamelCase_							=self.parse_log(lowerCAmelCase,	'''history'''						)
              self.assertEqual(logged_items['''total_loss'''],	'''0.1'''						)
              self.assertEqual(logged_items['''iteration'''],	'''1'''						)
              self.assertEqual(logged_items['''my_text'''],	'''some_value'''						)
              self.assertEqual(logged_items['''_step'''],	'''0'''						)





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



       """simple docstring"""
       lowerCamelCase_							=run_name
       lowerCamelCase_							=OfflineExperiment(project_name=__snake_case     , offline_directory=__snake_case     )
       logger.info(F'''Initialized offline CometML project {self.run_name}'''     )
       logger.info('''Make sure to log any initial configurations with `self.store_init_configuration` before training!'''     )


@require_comet_ml
@mock.patch.object(lowerCamelCase__    ,      '__init__'    ,      lowerCamelCase__       )
class 						__UpperCamelCase (				unittest.TestCase       ):






       @staticmethod
       def   lowercase__  (							lowerCAmelCase,	lowerCAmelCase,	lowerCAmelCase = False						):



              """simple docstring"""







              for log in log_list:
                     lowerCamelCase_							=json.loads(lowerCAmelCase						)['''payload''']
                     if is_param and "param" in j.keys():
                            if j["param"]["paramName"] == key:
                                   return j["param"]["paramValue"]
                     if "log_other" in j.keys():
                            if j["log_other"]["key"] == key:
                                   return j["log_other"]["val"]
                     if "metric" in j.keys():
                            if j["metric"]["metricName"] == key:
                                   return j["metric"]["metricValue"]






       def   lowercase__  (							self						):



              """simple docstring"""







              with tempfile.TemporaryDirectory() as d:
                     lowerCamelCase_							=CometMLTracker('''test_project_with_config''',	lowerCAmelCase						)
                     lowerCamelCase_							=Accelerator(log_with=lowerCAmelCase						)
                     lowerCamelCase_							={'''num_iterations''': 12, '''learning_rate''': 1e-2, '''some_boolean''': False, '''some_string''': '''some_value'''}
                     accelerator.init_trackers(lowerCAmelCase,	lowerCAmelCase						)
                     accelerator.end_training()
                     lowerCamelCase_							=os.listdir(lowerCAmelCase						)[0]  # Comet is nice, it's just a zip file here
                     # We parse the raw logs
                     lowerCamelCase_							=os.path.join(lowerCAmelCase,	lowerCAmelCase						)
                     lowerCamelCase_							=zipfile.ZipFile(lowerCAmelCase,	'''r'''						)
                     lowerCamelCase_							=archive.open('''messages.json'''						).read().decode('''utf-8'''						)
              lowerCamelCase_							=log.split('''\n'''						)[:-1]
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''num_iterations''',	lowerCAmelCase						),	12						)
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''learning_rate''',	lowerCAmelCase						),	0.0_1						)
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''some_boolean''',	lowerCAmelCase						),	lowerCAmelCase						)
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''some_string''',	lowerCAmelCase						),	'''some_value'''						)






       def   lowercase__  (							self						):



              """simple docstring"""







              with tempfile.TemporaryDirectory() as d:
                     lowerCamelCase_							=CometMLTracker('''test_project_with_config''',	lowerCAmelCase						)
                     lowerCamelCase_							=Accelerator(log_with=lowerCAmelCase						)
                     accelerator.init_trackers(lowerCAmelCase						)
                     lowerCamelCase_							={'''total_loss''': 0.1, '''iteration''': 1, '''my_text''': '''some_value'''}
                     accelerator.log(lowerCAmelCase,	step=0						)
                     accelerator.end_training()
                     lowerCamelCase_							=os.listdir(lowerCAmelCase						)[0]  # Comet is nice, it's just a zip file here
                     # We parse the raw logs
                     lowerCamelCase_							=os.path.join(lowerCAmelCase,	lowerCAmelCase						)
                     lowerCamelCase_							=zipfile.ZipFile(lowerCAmelCase,	'''r'''						)
                     lowerCamelCase_							=archive.open('''messages.json'''						).read().decode('''utf-8'''						)
              lowerCamelCase_							=log.split('''\n'''						)[:-1]
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''curr_step''',	lowerCAmelCase						),	0						)
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''total_loss'''						),	0.1						)
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''iteration'''						),	1						)
              self.assertEqual(self.get_value_from_key(lowerCAmelCase,	'''my_text'''						),	'''some_value'''						)





class 						__UpperCamelCase (				lowerCamelCase__       ):
       lowercase			:					str   		=[
           'total_loss',
           'iteration',
           'my_text',
           'learning_rate',
           'num_iterations',
           'some_boolean',
           'some_string',
       ]

       lowercase			:					int   		='my_custom_tracker'
       lowercase			:					str   		=False






       def __init__(							self,	lowerCAmelCase						):



              """simple docstring"""







              lowerCamelCase_							=open(f'''{dir}/log.csv''',	'''w+'''						)
              lowerCamelCase_							=csv.DictWriter(self.f,	fieldnames=self._col_names						)
              self.writer.writeheader()






       @property
       def   lowercase__  (							self						):



              """simple docstring"""







              return self.writer






       def   lowercase__  (							self,	lowerCAmelCase						):



              """simple docstring"""







              logger.info('''Call init'''						)
              self.writer.writerow(lowerCAmelCase						)






       def   lowercase__  (							self,	lowerCAmelCase,	lowerCAmelCase						):



              """simple docstring"""







              logger.info('''Call log'''						)
              self.writer.writerow(lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              self.f.close()





class 						__UpperCamelCase (				unittest.TestCase       ):






       def   lowercase__  (							self						):



              """simple docstring"""







              with tempfile.TemporaryDirectory() as d:
                     lowerCamelCase_							=MyCustomTracker(lowerCAmelCase						)
                     lowerCamelCase_							=Accelerator(log_with=lowerCAmelCase						)
                     lowerCamelCase_							={'''num_iterations''': 12, '''learning_rate''': 1e-2, '''some_boolean''': False, '''some_string''': '''some_value'''}
                     accelerator.init_trackers('''Some name''',	lowerCAmelCase						)
                     accelerator.end_training()
                     with open(f'''{d}/log.csv''',	'''r'''						) as f:
                            lowerCamelCase_							=csv.DictReader(lowerCAmelCase						)
                            lowerCamelCase_							=next(lowerCAmelCase						)
                            lowerCamelCase_							={
                                '''total_loss''': '''''',
                                '''iteration''': '''''',
                                '''my_text''': '''''',
                                '''learning_rate''': '''0.01''',
                                '''num_iterations''': '''12''',
                                '''some_boolean''': '''False''',
                                '''some_string''': '''some_value''',
                            }
                            self.assertDictEqual(lowerCAmelCase,	lowerCAmelCase						)






       def   lowercase__  (							self						):



              """simple docstring"""







              with tempfile.TemporaryDirectory() as d:
                     lowerCamelCase_							=MyCustomTracker(lowerCAmelCase						)
                     lowerCamelCase_							=Accelerator(log_with=lowerCAmelCase						)
                     accelerator.init_trackers('''Some name'''						)
                     lowerCamelCase_							={'''total_loss''': 0.1, '''iteration''': 1, '''my_text''': '''some_value'''}
                     accelerator.log(lowerCAmelCase,	step=0						)
                     accelerator.end_training()
                     with open(f'''{d}/log.csv''',	'''r'''						) as f:
                            lowerCamelCase_							=csv.DictReader(lowerCAmelCase						)
                            lowerCamelCase_							=next(lowerCAmelCase						)
                            lowerCamelCase_							={
                                '''total_loss''': '''0.1''',
                                '''iteration''': '''1''',
                                '''my_text''': '''some_value''',
                                '''learning_rate''': '''''',
                                '''num_iterations''': '''''',
                                '''some_boolean''': '''''',
                                '''some_string''': '''''',
                            }
                            self.assertDictEqual(lowerCAmelCase,	lowerCAmelCase						)










'''simple docstring'''




from typing import List, Optional, Tuple

from tokenizers import pre_tokenizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_clip import CLIPTokenizer


a_   :	Tuple							   = logging.get_logger(__name__)

a_   :	str							   = {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt""", """tokenizer_file""": """tokenizer.json"""}

a_   :	Tuple							   = {
    """vocab_file""": {
        """openai/clip-vit-base-patch32""": """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """openai/clip-vit-base-patch32""": """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """openai/clip-vit-base-patch32""": (
            """https://huggingface.co/openai/clip-vit-base-patch32/resolve/main/tokenizer.json"""
        ),
    },
}

a_   :	str							   = {
    """openai/clip-vit-base-patch32""": 77,
}


class 						__UpperCamelCase (				lowerCamelCase__       ):
       lowercase			:					Union[str, Any]   		=VOCAB_FILES_NAMES
       lowercase			:					Optional[int]   		=PRETRAINED_VOCAB_FILES_MAP
       lowercase			:					Any   		=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
       lowercase			:					str   		=['input_ids', 'attention_mask']
       lowercase			:					List[Any]   		=CLIPTokenizer






       def __init__(							self,	lowerCAmelCase=None,	lowerCAmelCase=None,	lowerCAmelCase=None,	lowerCAmelCase="<|endoftext|>",	lowerCAmelCase="<|startoftext|>",	lowerCAmelCase="<|endoftext|>",	lowerCAmelCase="<|endoftext|>",	**lowerCAmelCase,	):



              """simple docstring"""







              super().__init__(
                  lowerCAmelCase,	lowerCAmelCase,	tokenizer_file=lowerCAmelCase,	unk_token=lowerCAmelCase,	bos_token=lowerCAmelCase,	eos_token=lowerCAmelCase,	pad_token=lowerCAmelCase,	**lowerCAmelCase,	)

              if not isinstance(self.backend_tokenizer.pre_tokenizer,	pre_tokenizers.Sequence						):
                     raise ValueError(
                         '''The `backend_tokenizer` provided does not match the expected format. The CLIP tokenizer has been'''
                         ''' heavily modified from transformers version 4.17.0. You need to convert the tokenizer you are using'''
                         ''' to be compatible with this version.The easiest way to do so is'''
                         ''' `CLIPTokenizerFast.from_pretrained("path_to_local_folder_or_hub_repo, from_slow=True)`. If you want'''
                         ''' to use your existing tokenizer, you will have to revert to a version prior to 4.17.0 of'''
                         ''' transformers.'''						)

              self._wrap_decode_method_backend_tokenizer()






       def   lowercase__  (							self						):



              """simple docstring"""







              lowerCamelCase_							=self.backend_tokenizer.decode

              def new_decode_method(*lowerCAmelCase,	**lowerCAmelCase						):
                     lowerCamelCase_							=orig_decode_method(*lowerCAmelCase,	**lowerCAmelCase						)
                     lowerCamelCase_							=text.replace(self.backend_tokenizer.model.end_of_word_suffix,	''' '''						).strip()
                     return text

              lowerCamelCase_							=new_decode_method






       def   lowercase__  (							self,	lowerCAmelCase,	lowerCAmelCase = None						):



              """simple docstring"""







              lowerCamelCase_							=[self.bos_token_id]
              lowerCamelCase_							=[self.eos_token_id]

              if token_ids_a is None:
                     return bos_token + token_ids_a + eos_token
              return bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token






       def   lowercase__  (							self,	lowerCAmelCase,	lowerCAmelCase = None						):



              """simple docstring"""







              lowerCamelCase_							=[self.bos_token_id]
              lowerCamelCase_							=[self.eos_token_id]

              if token_ids_a is None:
                     return len(bos_token + token_ids_a + eos_token						) * [0]
              return len(bos_token + token_ids_a + eos_token + eos_token + token_ids_a + eos_token						) * [0]






       def   lowercase__  (							self,	lowerCAmelCase,	lowerCAmelCase = None						):



              """simple docstring"""







              lowerCamelCase_							=self._tokenizer.model.save(lowerCAmelCase,	name=lowerCAmelCase						)
              return tuple(lowerCAmelCase						)




