
'''simple docstring'''


import os
import socket
from contextlib import contextmanager

import torch

from ..commands.config.default import write_basic_config  # noqa: F401
from ..state import PartialState
from .dataclasses import DistributedType
from .imports import is_deepspeed_available, is_tpu_available
from .transformer_engine import convert_model
from .versions import is_torch_version


if is_deepspeed_available():
   from deepspeed import DeepSpeedEngine

if is_tpu_available(check_device=False):
   import torch_xla.core.xla_model as xm



def  __snake_case     (    _UpperCAmelCase					:       List[str]):
   if is_torch_version('''<''',      '''2.0.0''') or not hasattr(_UpperCAmelCase,      '''_dynamo'''):
      return False
   return isinstance(_UpperCAmelCase,      torch._dynamo.eval_frame.OptimizedModule)



def  __snake_case     (    _UpperCAmelCase					:       List[str],      _UpperCAmelCase					:       bool = True):
   UpperCamelCase       =  (torch.nn.parallel.DistributedDataParallel, torch.nn.DataParallel)

   UpperCamelCase       =  is_compiled_module(_UpperCAmelCase)
   if is_compiled:
      UpperCamelCase       =  model
      UpperCamelCase       =  model._orig_mod

   if is_deepspeed_available():
      options += (DeepSpeedEngine,)

   while isinstance(_UpperCAmelCase,      _UpperCAmelCase):
      UpperCamelCase       =  model.module

   if not keep_fpaa_wrapper:
      UpperCamelCase       =  getattr(_UpperCAmelCase,      '''forward''')
      UpperCamelCase       =  model.__dict__.pop('''_original_forward''',      _UpperCAmelCase)
      if original_forward is not None:
         while hasattr(_UpperCAmelCase,      '''__wrapped__'''):
            UpperCamelCase       =  forward.__wrapped__
            if forward == original_forward:
               break
         UpperCamelCase       =  forward
      if getattr(_UpperCAmelCase,      '''_converted_to_transformer_engine''',      _UpperCAmelCase):
         convert_model(_UpperCAmelCase,      to_transformer_engine=_UpperCAmelCase)

   if is_compiled:
      UpperCamelCase       =  model
      UpperCamelCase       =  compiled_model

   return model



def  __snake_case     (    ):
   PartialState().wait_for_everyone()



def  __snake_case     (    _UpperCAmelCase					:       Dict,      _UpperCAmelCase					:       Optional[Any]):
   if PartialState().distributed_type == DistributedType.TPU:
      xm.save(_UpperCAmelCase,      _UpperCAmelCase)
   elif PartialState().local_process_index == 0:
      torch.save(_UpperCAmelCase,      _UpperCAmelCase)



@contextmanager
def  __snake_case     (    **_UpperCAmelCase					:       str):
   for key, value in kwargs.items():
      UpperCamelCase       =  str(_UpperCAmelCase)

   yield

   for key in kwargs:
      if key.upper() in os.environ:
         del os.environ[key.upper()]



def  __snake_case     (    _UpperCAmelCase					:       str):
   if not hasattr(_UpperCAmelCase,      '''__qualname__''') and not hasattr(_UpperCAmelCase,      '''__name__'''):
      UpperCamelCase       =  getattr(_UpperCAmelCase,      '''__class__''',      _UpperCAmelCase)
   if hasattr(_UpperCAmelCase,      '''__qualname__'''):
      return obj.__qualname__
   if hasattr(_UpperCAmelCase,      '''__name__'''):
      return obj.__name__
   return str(_UpperCAmelCase)



def  __snake_case     (    _UpperCAmelCase					:       List[str],      _UpperCAmelCase					:       List[Any]):
   for key, value in source.items():
      if isinstance(_UpperCAmelCase,      _UpperCAmelCase):
         UpperCamelCase       =  destination.setdefault(_UpperCAmelCase,      {})
         merge_dicts(_UpperCAmelCase,      _UpperCAmelCase)
      else:
         UpperCamelCase       =  value

   return destination



def  __snake_case     (    _UpperCAmelCase					:       int = None):
   if port is None:
      UpperCamelCase       =  2_9500
   with socket.socket(socket.AF_INET,      socket.SOCK_STREAM) as s:
      return s.connect_ex(('''localhost''', port)) == 0







'''simple docstring'''


import math
from typing import Optional

import numpy as np

from ...configuration_utils import PretrainedConfig
from ...utils import logging


snake_case_ :  Dict     =					logging.get_logger(__name__)

snake_case_ :  Union[str, Any]     =					{
    'facebook/encodec_24khz': 'https://huggingface.co/facebook/encodec_24khz/resolve/main/config.json',
    'facebook/encodec_48khz': 'https://huggingface.co/facebook/encodec_48khz/resolve/main/config.json',
}


class 						lowercase__	(  snake_case_   ):






   '''simple docstring'''







   _snake_case		   =							'''encodec'''







   def __init__(			self ,   lowerCamelCase__=[1.5, 3.0, 6.0, 12.0, 24.0] ,   lowerCamelCase__=2_4_0_0_0 ,   lowerCamelCase__=1 ,   lowerCamelCase__=False ,   lowerCamelCase__=None ,   lowerCamelCase__=None ,   lowerCamelCase__=1_2_8 ,   lowerCamelCase__=3_2 ,   lowerCamelCase__=1 ,   lowerCamelCase__=[8, 5, 4, 2] ,   lowerCamelCase__="weight_norm" ,   lowerCamelCase__=7 ,   lowerCamelCase__=7 ,   lowerCamelCase__=3 ,   lowerCamelCase__=2 ,   lowerCamelCase__=True ,   lowerCamelCase__="reflect" ,   lowerCamelCase__=2 ,   lowerCamelCase__=2 ,   lowerCamelCase__=1.0 ,   lowerCamelCase__=1_0_2_4 ,   lowerCamelCase__=None ,   lowerCamelCase__=True ,   **lowerCamelCase__ ,   ):

      '''simple docstring'''







      UpperCamelCase       =  target_bandwidths
      UpperCamelCase       =  sampling_rate
      UpperCamelCase       =  audio_channels
      UpperCamelCase       =  normalize
      UpperCamelCase       =  chunk_length_s
      UpperCamelCase       =  overlap
      UpperCamelCase       =  hidden_size
      UpperCamelCase       =  num_filters
      UpperCamelCase       =  num_residual_layers
      UpperCamelCase       =  upsampling_ratios
      UpperCamelCase       =  norm_type
      UpperCamelCase       =  kernel_size
      UpperCamelCase       =  last_kernel_size
      UpperCamelCase       =  residual_kernel_size
      UpperCamelCase       =  dilation_growth_rate
      UpperCamelCase       =  use_causal_conv
      UpperCamelCase       =  pad_mode
      UpperCamelCase       =  compress
      UpperCamelCase       =  num_lstm_layers
      UpperCamelCase       =  trim_right_ratio
      UpperCamelCase       =  codebook_size
      UpperCamelCase       =  codebook_dim if codebook_dim is not None else hidden_size
      UpperCamelCase       =  use_conv_shortcut

      if self.norm_type not in ["weight_norm", "time_group_norm"]:
         raise ValueError(
             f'self.norm_type must be one of `"weight_norm"`, `"time_group_norm"`), got {self.norm_type}'   )

      super().__init__(**lowerCamelCase__   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      if self.chunk_length_s is None:
         return None
      else:
         return int(self.chunk_length_s * self.sampling_rate   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      if self.chunk_length_s is None or self.overlap is None:
         return None
      else:
         return max(1 ,   int((1.0 - self.overlap) * self.chunk_length   )   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      UpperCamelCase       =  np.prod(self.upsampling_ratios   )
      return math.ceil(self.sampling_rate / hop_length   )







   @property
   def       UpperCAmelCase				(			self   ):

      '''simple docstring'''







      return int(1_0_0_0 * self.target_bandwidths[-1] // (self.frame_rate * 1_0)   )





