'''simple docstring'''




import logging
import math
from functools import partial
from typing import Any, Callable, Dict, Iterable, List, Optional, Sequence, Tuple, Union

import torch

from .tensor_utils import tensor_tree_map, tree_map

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       Optional[int]     				=					[]
     if isinstance(UpperCamelCase__  ,       UpperCamelCase__							):
          for v in tree.values():
               shapes.extend(_fetch_dims(UpperCamelCase__							)							)
     elif isinstance(UpperCamelCase__  ,       (list, tuple)							):
          for t in tree:
               shapes.extend(_fetch_dims(UpperCamelCase__							)							)
     elif isinstance(UpperCamelCase__  ,       torch.Tensor							):
          shapes.append(tree.shape							)
     else:
          raise ValueError('Not supported'							)

     return shapes

@torch.jit.ignore
def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       str     				=					[]
     for d in reversed(UpperCamelCase__							):
          idx.append(flat_idx % d							)
          lowercase_					:       Any     				=					flat_idx // d

     return tuple(reversed(UpperCamelCase__							)							)

@torch.jit.ignore
def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_ = None  ,       SCREAMING_SNAKE_CASE_ = None  ,       ):

     # start_edges and end_edges both indicate whether, starting from any given
     # dimension, the start/end index is at the top/bottom edge of the
     # corresponding tensor, modeled as a tree
     def reduce_edge_list(SCREAMING_SNAKE_CASE_							) -> None:
          lowercase_					:       str     				=					True
          for i in range(len(UpperCamelCase__							)							):
               lowercase_					:       int     				=					-1 * (i + 1)
               l[reversed_idx] &= tally
               lowercase_					:       Dict     				=					l[reversed_idx]

     if start_edges is None:
          lowercase_					:       Optional[int]     				=					[s == 0 for s in start]
          reduce_edge_list(UpperCamelCase__							)
     if end_edges is None:
          lowercase_					:       List[str]     				=					[e == (d - 1) for e, d in zip(UpperCamelCase__  ,       UpperCamelCase__							)]
          reduce_edge_list(UpperCamelCase__							)

     # Base cases. Either start/end are empty and we're done, or the final,
     # one-dimensional tensor can be simply sliced
     if len(UpperCamelCase__							) == 0:
          return [()]
     elif len(UpperCamelCase__							) == 1:
          return [(slice(start[0]  ,       end[0] + 1							),)]

     lowercase_					:       List[Tuple[slice, ...]]     				=					[]
     lowercase_					:       List[slice]     				=					[]

     # Dimensions common to start and end can be selected directly
     for s, e in zip(UpperCamelCase__  ,       UpperCamelCase__							):
          if s == e:
               path_list.append(slice(UpperCamelCase__  ,       s + 1							)							)
          else:
               break

     lowercase_					:       Tuple[slice, ...]     				=					tuple(UpperCamelCase__							)
     lowercase_					:       List[str]     				=					len(UpperCamelCase__							)

     # start == end, and we're done
     if divergence_idx == len(UpperCamelCase__							):
          return [path]

     def upper() -> Tuple[Tuple[slice, ...], ...]:
          assert start_edges is not None
          assert end_edges is not None

          lowercase_					:       Optional[Any]     				=					start[divergence_idx]
          return tuple(
              path + (slice(UpperCamelCase__  ,       sdi + 1							),) + s
              for s in _get_minimal_slice_set(
                  start[divergence_idx + 1 :]  ,       [d - 1 for d in dims[divergence_idx + 1 :]]  ,       dims[divergence_idx + 1 :]  ,       start_edges=start_edges[divergence_idx + 1 :]  ,       end_edges=[True for _ in end_edges[divergence_idx + 1 :]]  ,       )							)

     def lower() -> Tuple[Tuple[slice, ...], ...]:
          assert start_edges is not None
          assert end_edges is not None

          lowercase_					:       str     				=					end[divergence_idx]
          return tuple(
              path + (slice(UpperCamelCase__  ,       edi + 1							),) + s
              for s in _get_minimal_slice_set(
                  [0 for _ in start[divergence_idx + 1 :]]  ,       end[divergence_idx + 1 :]  ,       dims[divergence_idx + 1 :]  ,       start_edges=[True for _ in start_edges[divergence_idx + 1 :]]  ,       end_edges=end_edges[divergence_idx + 1 :]  ,       )							)

     # If both start and end are at the edges of the subtree rooted at
     # divergence_idx, we can just select the whole subtree at once
     if start_edges[divergence_idx] and end_edges[divergence_idx]:
          slices.append(path + (slice(start[divergence_idx]  ,       end[divergence_idx] + 1							),)							)
     # If just start is at the edge, we can grab almost all of the subtree,
     # treating only the ragged bottom edge as an edge case
     elif start_edges[divergence_idx]:
          slices.append(path + (slice(start[divergence_idx]  ,       end[divergence_idx]							),)							)
          slices.extend(lower()							)
     # Analogous to the previous case, but the top is ragged this time
     elif end_edges[divergence_idx]:
          slices.extend(upper()							)
          slices.append(path + (slice(start[divergence_idx] + 1  ,       end[divergence_idx] + 1							),)							)
     # If both sides of the range are ragged, we need to handle both sides
     # separately. If there's contiguous meat in between them, we can index it
     # in one big chunk
     else:
          slices.extend(upper()							)
          lowercase_					:       Optional[Any]     				=					end[divergence_idx] - start[divergence_idx]
          if middle_ground > 1:
               slices.append(path + (slice(start[divergence_idx] + 1  ,       end[divergence_idx]							),)							)
          slices.extend(lower()							)

     return slices

@torch.jit.ignore
def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       str     				=					t.shape[:no_batch_dims]
     lowercase_					:       Dict     				=					list(_flat_idx_to_idx(UpperCamelCase__  ,       UpperCamelCase__							)							)
     # _get_minimal_slice_set is inclusive
     lowercase_					:       List[str]     				=					list(_flat_idx_to_idx(flat_end - 1  ,       UpperCamelCase__							)							)

     # Get an ordered list of slices to perform
     lowercase_					:       Any     				=					_get_minimal_slice_set(
         UpperCamelCase__  ,       UpperCamelCase__  ,       UpperCamelCase__  ,       )

     lowercase_					:       Any     				=					[t[s] for s in slices]

     return torch.cat([s.view((-1,) + t.shape[no_batch_dims:]							) for s in sliced_tensors]							)

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_ = False  ,       SCREAMING_SNAKE_CASE_ = None  ,       SCREAMING_SNAKE_CASE_ = False  ,       ):
     if not (len(UpperCamelCase__							) > 0):
          raise ValueError('Must provide at least one input'							)

     lowercase_					:       str     				=					[shape[:no_batch_dims] for shape in _fetch_dims(UpperCamelCase__							)]
     lowercase_					:       Any     				=					tuple([max(UpperCamelCase__							) for s in zip(*UpperCamelCase__							)]							)

     def _prep_inputs(SCREAMING_SNAKE_CASE_							) -> torch.Tensor:
          if not low_mem:
               if not sum(t.shape[:no_batch_dims]							) == no_batch_dims:
                    lowercase_					:       List[Any]     				=					t.expand(orig_batch_dims + t.shape[no_batch_dims:]							)
               lowercase_					:       Union[str, Any]     				=					t.reshape(-1  ,       *t.shape[no_batch_dims:]							)
          else:
               lowercase_					:       Optional[Any]     				=					t.expand(orig_batch_dims + t.shape[no_batch_dims:]							)
          return t

     lowercase_					:       Dict[str, Any]     				=					tensor_tree_map(_prep_inputs  ,       UpperCamelCase__							)
     lowercase_					:       str     				=					None
     if _out is not None:
          lowercase_					:       Union[str, Any]     				=					tensor_tree_map(lambda SCREAMING_SNAKE_CASE_							: t.view([-1] + list(t.shape[no_batch_dims:]							)							)  ,       _out							)

     lowercase_					:       int     				=					1
     for d in orig_batch_dims:
          flat_batch_dim *= d

     lowercase_					:       Optional[Any]     				=					flat_batch_dim // chunk_size + (flat_batch_dim % chunk_size != 0)

     def _select_chunk(SCREAMING_SNAKE_CASE_							) -> torch.Tensor:
          return t[i : i + chunk_size] if t.shape[0] != 1 else t

     lowercase_					:       int     				=					0
     lowercase_					:       Optional[int]     				=					prepped_outputs
     for _ in range(UpperCamelCase__							):
          # Chunk the input
          if not low_mem:
               lowercase_					:       str     				=					_select_chunk
          else:
               lowercase_					:       Union[str, Any]     				=					partial(
                   _chunk_slice  ,       flat_start=UpperCamelCase__  ,       flat_end=min(UpperCamelCase__  ,       i + chunk_size							)  ,       no_batch_dims=len(UpperCamelCase__							)  ,       )

          lowercase_					:       Dict[str, Any]     				=					tensor_tree_map(UpperCamelCase__  ,       UpperCamelCase__							)

          # Run the layer on the chunk
          lowercase_					:       Any     				=					layer(**UpperCamelCase__							)

          # Allocate space for the output
          if out is None:
               lowercase_					:       List[str]     				=					tensor_tree_map(lambda SCREAMING_SNAKE_CASE_							: t.new_zeros((flat_batch_dim,) + t.shape[1:]							)  ,       UpperCamelCase__							)

          # Put the chunk in its pre-allocated space
          if isinstance(UpperCamelCase__  ,       UpperCamelCase__							):

               def assign(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							) -> None:
                    for k, v in da.items():
                         if isinstance(UpperCamelCase__  ,       UpperCamelCase__							):
                              assign(UpperCamelCase__  ,       da[k]							)
                         else:
                              if _add_into_out:
                                   v[i : i + chunk_size] += da[k]
                              else:
                                   lowercase_					:       List[Any]     				=					da[k]

               assign(UpperCamelCase__  ,       UpperCamelCase__							)
          elif isinstance(UpperCamelCase__  ,       UpperCamelCase__							):
               for xa, xa in zip(UpperCamelCase__  ,       UpperCamelCase__							):
                    if _add_into_out:
                         xa[i : i + chunk_size] += xa
                    else:
                         lowercase_					:       Union[str, Any]     				=					xa
          elif isinstance(UpperCamelCase__  ,       torch.Tensor							):
               if _add_into_out:
                    out[i : i + chunk_size] += output_chunk
               else:
                    lowercase_					:       List[Any]     				=					output_chunk
          else:
               raise ValueError('Not supported'							)

          i += chunk_size

     lowercase_					:       Optional[int]     				=					tensor_tree_map(lambda SCREAMING_SNAKE_CASE_							: t.view(orig_batch_dims + t.shape[1:]							)  ,       UpperCamelCase__							)

     return out






class       UpperCAmelCase__  :






   """simple docstring"""
   def __init__(self       ,				_a = 512       ,				)    ->     Optional[int]:
        lowercase_					:       List[Any]     				=					max_chunk_size
        lowercase_					:       Optional[int]     				=					None
        lowercase_					:       Optional[tuple]     				=					None
   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a				)    ->     int:
        logging.info('Tuning chunk size...'				)

        if min_chunk_size >= self.max_chunk_size:
             return min_chunk_size

        lowercase_					:       List[int]     				=					[2**l for l in range(int(math.log(self.max_chunk_size       ,				2				)				) + 1				)]
        lowercase_					:       Union[str, Any]     				=					[c for c in candidates if c > min_chunk_size]
        lowercase_					:       Dict     				=					[min_chunk_size] + candidates
        candidates[-1] += 4

        def test_chunk_size(_a				) -> bool:
             try:
                  with torch.no_grad():
                       fn(*__a       ,				chunk_size=__a				)
                  return True
             except RuntimeError:
                  return False

        lowercase_					:       Optional[Any]     				=					0
        lowercase_					:       Optional[int]     				=					len(__a				) - 1
        while i > min_viable_chunk_size_index:
             lowercase_					:       List[str]     				=					test_chunk_size(candidates[i]				)
             if not viable:
                  lowercase_					:       int     				=					(min_viable_chunk_size_index + i) // 2
             else:
                  lowercase_					:       Union[str, Any]     				=					i
                  lowercase_					:       Dict     				=					(i + len(__a				) - 1) // 2

        return candidates[min_viable_chunk_size_index]
   def 		_lowerCamelCase (self       ,				_a       ,				_a				)    ->     bool:
        lowercase_					:       Dict     				=					True
        for aa, aa in zip(__a       ,				__a				):
             assert type(__a				) == type(__a				)
             if isinstance(__a       ,				(list, tuple)				):
                  consistent &= self._compare_arg_caches(__a       ,				__a				)
             elif isinstance(__a       ,				__a				):
                  lowercase_					:       str     				=					[v for _, v in sorted(aa.items()       ,				key=lambda _a				: x[0]				)]
                  lowercase_					:       List[str]     				=					[v for _, v in sorted(aa.items()       ,				key=lambda _a				: x[0]				)]
                  consistent &= self._compare_arg_caches(__a       ,				__a				)
             else:
                  consistent &= aa == aa

        return consistent





   def 		_lowerCamelCase (self       ,				_a       ,				_a       ,				_a       ,				)    ->     int:
        lowercase_					:       List[str]     				=					True
        lowercase_					:       tuple     				=					tree_map(lambda _a				: a.shape if isinstance(__a       ,				torch.Tensor				) else a       ,				__a       ,				__a				)
        if self.cached_arg_data is not None:
             # If args have changed shape/value, we need to re-tune
             assert len(self.cached_arg_data				) == len(__a				)
             lowercase_					:       Any     				=					self._compare_arg_caches(self.cached_arg_data       ,				__a				)
        else:
             # Otherwise, we can reuse the precomputed value
             lowercase_					:       int     				=					False

        if not consistent:
             lowercase_					:       Optional[Any]     				=					self._determine_favorable_chunk_size(
                 __a       ,				__a       ,				__a       ,				)
             lowercase_					:       List[Any]     				=					arg_data

        assert self.cached_chunk_size is not None

        return self.cached_chunk_size





'''simple docstring'''




import argparse
import json
from pathlib import Path

import torch
import torchaudio
from datasets import load_dataset
from huggingface_hub import hf_hub_download

from transformers import ASTConfig, ASTFeatureExtractor, ASTForAudioClassification
from transformers.utils import logging


logging.set_verbosity_info()
_A								=   logging.get_logger(__name__)

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       List[Any]     				=					ASTConfig()

     if "10-10" in model_name:
          pass
     elif "speech-commands" in model_name:
          lowercase_					:       List[Any]     				=					128
     elif "12-12" in model_name:
          lowercase_					:       Tuple     				=					12
          lowercase_					:       List[Any]     				=					12
     elif "14-14" in model_name:
          lowercase_					:       List[str]     				=					14
          lowercase_					:       Optional[Any]     				=					14
     elif "16-16" in model_name:
          lowercase_					:       Union[str, Any]     				=					16
          lowercase_					:       List[str]     				=					16
     else:
          raise ValueError('Model not supported'							)

     lowercase_					:       Optional[Any]     				=					'huggingface/label-files'
     if "speech-commands" in model_name:
          lowercase_					:       List[str]     				=					35
          lowercase_					:       int     				=					'speech-commands-v2-id2label.json'
     else:
          lowercase_					:       Union[str, Any]     				=					527
          lowercase_					:       int     				=					'audioset-id2label.json'

     lowercase_					:       Union[str, Any]     				=					json.load(open(hf_hub_download(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       repo_type='dataset'							)  ,       'r'							)							)
     lowercase_					:       Union[str, Any]     				=					{int(SCREAMING_SNAKE_CASE_							): v for k, v in idalabel.items()}
     lowercase_					:       Optional[int]     				=					idalabel
     lowercase_					:       Optional[int]     				=					{v: k for k, v in idalabel.items()}

     return config

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     if "module.v" in name:
          lowercase_					:       Dict     				=					name.replace('module.v'  ,       'audio_spectrogram_transformer'							)
     if "cls_token" in name:
          lowercase_					:       Optional[Any]     				=					name.replace('cls_token'  ,       'embeddings.cls_token'							)
     if "dist_token" in name:
          lowercase_					:       Any     				=					name.replace('dist_token'  ,       'embeddings.distillation_token'							)
     if "pos_embed" in name:
          lowercase_					:       List[str]     				=					name.replace('pos_embed'  ,       'embeddings.position_embeddings'							)
     if "patch_embed.proj" in name:
          lowercase_					:       int     				=					name.replace('patch_embed.proj'  ,       'embeddings.patch_embeddings.projection'							)
     # transformer blocks
     if "blocks" in name:
          lowercase_					:       Optional[Any]     				=					name.replace('blocks'  ,       'encoder.layer'							)
     if "attn.proj" in name:
          lowercase_					:       Optional[int]     				=					name.replace('attn.proj'  ,       'attention.output.dense'							)
     if "attn" in name:
          lowercase_					:       Dict     				=					name.replace('attn'  ,       'attention.self'							)
     if "norm1" in name:
          lowercase_					:       int     				=					name.replace('norm1'  ,       'layernorm_before'							)
     if "norm2" in name:
          lowercase_					:       Optional[int]     				=					name.replace('norm2'  ,       'layernorm_after'							)
     if "mlp.fc1" in name:
          lowercase_					:       Optional[int]     				=					name.replace('mlp.fc1'  ,       'intermediate.dense'							)
     if "mlp.fc2" in name:
          lowercase_					:       int     				=					name.replace('mlp.fc2'  ,       'output.dense'							)
     # final layernorm
     if "audio_spectrogram_transformer.norm" in name:
          lowercase_					:       int     				=					name.replace('audio_spectrogram_transformer.norm'  ,       'audio_spectrogram_transformer.layernorm'							)
     # classifier head
     if "module.mlp_head.0" in name:
          lowercase_					:       Dict     				=					name.replace('module.mlp_head.0'  ,       'classifier.layernorm'							)
     if "module.mlp_head.1" in name:
          lowercase_					:       List[Any]     				=					name.replace('module.mlp_head.1'  ,       'classifier.dense'							)

     return name

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							):
     for key in orig_state_dict.copy().keys():
          lowercase_					:       List[str]     				=					orig_state_dict.pop(SCREAMING_SNAKE_CASE_							)

          if "qkv" in key:
               lowercase_					:       List[str]     				=					key.split('.'							)
               lowercase_					:       int     				=					int(key_split[3]							)
               lowercase_					:       Tuple     				=					config.hidden_size
               if "weight" in key:
                    lowercase_					:       Tuple     				=					val[:dim, :]
                    lowercase_					:       Union[str, Any]     				=					val[dim : dim * 2, :]
                    lowercase_					:       Optional[int]     				=					val[-dim:, :]
               else:
                    lowercase_					:       Optional[Any]     				=					val[:dim]
                    lowercase_					:       Any     				=					val[dim : dim * 2]
                    lowercase_					:       Tuple     				=					val[-dim:]
          else:
               lowercase_					:       Optional[Any]     				=					val

     return orig_state_dict

def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_							):
     lowercase_					:       List[Any]     				=					[
         'module.v.head.weight',
         'module.v.head.bias',
         'module.v.head_dist.weight',
         'module.v.head_dist.bias',
     ]
     for k in ignore_keys:
          state_dict.pop(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							)

@torch.no_grad()
def _UpperCamelCase   (       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_=False							):
     lowercase_					:       Dict     				=					get_audio_spectrogram_transformer_config(SCREAMING_SNAKE_CASE_							)

     lowercase_					:       Optional[int]     				=					{
         'ast-finetuned-audioset-10-10-0.4593': (
             'https://www.dropbox.com/s/ca0b1v2nlxzyeb4/audioset_10_10_0.4593.pth?dl=1'
         ),
         'ast-finetuned-audioset-10-10-0.450': (
             'https://www.dropbox.com/s/1tv0hovue1bxupk/audioset_10_10_0.4495.pth?dl=1'
         ),
         'ast-finetuned-audioset-10-10-0.448': (
             'https://www.dropbox.com/s/6u5sikl4b9wo4u5/audioset_10_10_0.4483.pth?dl=1'
         ),
         'ast-finetuned-audioset-10-10-0.448-v2': (
             'https://www.dropbox.com/s/kt6i0v9fvfm1mbq/audioset_10_10_0.4475.pth?dl=1'
         ),
         'ast-finetuned-audioset-12-12-0.447': (
             'https://www.dropbox.com/s/snfhx3tizr4nuc8/audioset_12_12_0.4467.pth?dl=1'
         ),
         'ast-finetuned-audioset-14-14-0.443': (
             'https://www.dropbox.com/s/z18s6pemtnxm4k7/audioset_14_14_0.4431.pth?dl=1'
         ),
         'ast-finetuned-audioset-16-16-0.442': (
             'https://www.dropbox.com/s/mdsa4t1xmcimia6/audioset_16_16_0.4422.pth?dl=1'
         ),
         'ast-finetuned-speech-commands-v2': (
             'https://www.dropbox.com/s/q0tbqpwv44pquwy/speechcommands_10_10_0.9812.pth?dl=1'
         ),
     }

     # load original state_dict
     lowercase_					:       Dict     				=					model_name_to_url[model_name]
     lowercase_					:       Optional[Any]     				=					torch.hub.load_state_dict_from_url(SCREAMING_SNAKE_CASE_  ,       map_location='cpu'							)
     # remove some keys
     remove_keys(SCREAMING_SNAKE_CASE_							)
     # rename some keys
     lowercase_					:       str     				=					convert_state_dict(SCREAMING_SNAKE_CASE_  ,       SCREAMING_SNAKE_CASE_							)

     # load 🤗 model
     lowercase_					:       Optional[Any]     				=					ASTForAudioClassification(SCREAMING_SNAKE_CASE_							)
     model.eval()

     model.load_state_dict(SCREAMING_SNAKE_CASE_							)

     # verify outputs on dummy input
     # source: https://github.com/YuanGongND/ast/blob/79e873b8a54d0a3b330dd522584ff2b9926cd581/src/run.py#L62
     lowercase_					:       Tuple     				=					-4.267_7393 if 'speech-commands' not in model_name else -6.84_5978
     lowercase_					:       str     				=					4.568_9974 if 'speech-commands' not in model_name else 5.565_4526
     lowercase_					:       str     				=					1_024 if 'speech-commands' not in model_name else 128
     lowercase_					:       Dict     				=					ASTFeatureExtractor(mean=SCREAMING_SNAKE_CASE_  ,       std=SCREAMING_SNAKE_CASE_  ,       max_length=SCREAMING_SNAKE_CASE_							)

     if "speech-commands" in model_name:
          lowercase_					:       Optional[Any]     				=					load_dataset('speech_commands'  ,       'v0.02'  ,       split='validation'							)
          lowercase_					:       Any     				=					dataset[0]['audio']['array']
     else:
          lowercase_					:       Any     				=					hf_hub_download(
              repo_id='nielsr/audio-spectogram-transformer-checkpoint'  ,       filename='sample_audio.flac'  ,       repo_type='dataset'  ,       )

          lowercase_				,lowercase_					:       Union[str, Any]     				=					torchaudio.load(SCREAMING_SNAKE_CASE_							)
          lowercase_					:       str     				=					waveform.squeeze().numpy()

     lowercase_					:       str     				=					feature_extractor(SCREAMING_SNAKE_CASE_  ,       sampling_rate=16_000  ,       return_tensors='pt'							)

     # forward pass
     lowercase_					:       Tuple     				=					model(**SCREAMING_SNAKE_CASE_							)
     lowercase_					:       Tuple     				=					outputs.logits

     if model_name == "ast-finetuned-audioset-10-10-0.4593":
          lowercase_					:       int     				=					torch.tensor([-0.8760, -7.0042, -8.6602]							)
     elif model_name == "ast-finetuned-audioset-10-10-0.450":
          lowercase_					:       Optional[int]     				=					torch.tensor([-1.1986, -7.0903, -8.2718]							)
     elif model_name == "ast-finetuned-audioset-10-10-0.448":
          lowercase_					:       Optional[Any]     				=					torch.tensor([-2.6128, -8.0080, -9.4344]							)
     elif model_name == "ast-finetuned-audioset-10-10-0.448-v2":
          lowercase_					:       List[str]     				=					torch.tensor([-1.5080, -7.4534, -8.8917]							)
     elif model_name == "ast-finetuned-audioset-12-12-0.447":
          lowercase_					:       List[str]     				=					torch.tensor([-0.5050, -6.5833, -8.0843]							)
     elif model_name == "ast-finetuned-audioset-14-14-0.443":
          lowercase_					:       Any     				=					torch.tensor([-0.3826, -7.0336, -8.2413]							)
     elif model_name == "ast-finetuned-audioset-16-16-0.442":
          lowercase_					:       List[str]     				=					torch.tensor([-1.2113, -6.9101, -8.3470]							)
     elif model_name == "ast-finetuned-speech-commands-v2":
          lowercase_					:       Optional[Any]     				=					torch.tensor([6.1589, -8.0566, -8.7984]							)
     else:
          raise ValueError('Unknown model name'							)
     if not torch.allclose(logits[0, :3]  ,       SCREAMING_SNAKE_CASE_  ,       atol=1e-4							):
          raise ValueError('Logits don\'t match'							)
     print('Looks ok!'							)

     if pytorch_dump_folder_path is not None:
          Path(SCREAMING_SNAKE_CASE_							).mkdir(exist_ok=SCREAMING_SNAKE_CASE_							)
          print(f'''Saving model {model_name} to {pytorch_dump_folder_path}'''							)
          model.save_pretrained(SCREAMING_SNAKE_CASE_							)
          print(f'''Saving feature extractor to {pytorch_dump_folder_path}'''							)
          feature_extractor.save_pretrained(SCREAMING_SNAKE_CASE_							)

     if push_to_hub:
          print('Pushing model and feature extractor to the hub...'							)
          model.push_to_hub(f'''MIT/{model_name}'''							)
          feature_extractor.push_to_hub(f'''MIT/{model_name}'''							)


if __name__ == "__main__":
 _A								=   argparse.ArgumentParser()
 # Required parameters
 parser.add_argument(
     '--model_name',
     default='ast-finetuned-audioset-10-10-0.4593',
     type=str,
     help='Name of the Audio Spectrogram Transformer model you\'d like to convert.',
 )
 parser.add_argument(
     '--pytorch_dump_folder_path', default=None, type=str, help='Path to the output PyTorch model directory.'
 )
 parser.add_argument(
     '--push_to_hub', action='store_true', help='Whether or not to push the converted model to the 🤗 hub.'
 )

 _A								=   parser.parse_args()
 convert_audio_spectrogram_transformer_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)




