




# Copyright 2021 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import json
import os
from dataclasses import dataclass
from enum import Enum
from typing import List, Optional, Union

import yaml

from ...utils import ComputeEnvironment, DistributedType, SageMakerDistributedType
from ...utils.constants import SAGEMAKER_PYTHON_VERSION, SAGEMAKER_PYTORCH_VERSION, SAGEMAKER_TRANSFORMERS_VERSION


_lowerCamelCase					:     List[Any]					  =  os.path.expanduser(
    os.getenv("HF_HOME", os.path.join(os.getenv("XDG_CACHE_HOME", "~/.cache"), "huggingface"))
)
_lowerCamelCase					:     Tuple					  =  os.path.join(hf_cache_home, "accelerate")
_lowerCamelCase					:     List[str]					  =  os.path.join(cache_dir, "default_config.yaml")
_lowerCamelCase					:     Optional[Any]					  =  os.path.join(cache_dir, "default_config.yaml")

# For backward compatibility: the default config is the json one if it's the only existing file.
if os.path.isfile(default_yaml_config_file) or not os.path.isfile(default_json_config_file):
	_lowerCamelCase					:     Any					  =  default_yaml_config_file
else:
	_lowerCamelCase					:     Any					  =  default_json_config_file




def 							_UpperCAmelCase     (UpperCamelCase_       :       Optional[int]				):
				'''simple docstring'''
				if config_file is not None:
								if not os.path.isfile(UpperCamelCase_				):
												raise FileNotFoundError(
												    F"The passed configuration file `{config_file}` does not exist. "
												    """Please pass an existing file to `accelerate launch`, or use the the default one """
												    """created through `accelerate config` and run `accelerate launch` """
												    """without the `--config_file` argument."""				)
				else:
								_lowerCAmelCase			:			List[Any]        =					default_config_file
				with open(UpperCamelCase_					,			"""r"""					,			encoding="""utf-8"""				) as f:
								if config_file.endswith(""".json"""				):
												if (
												    json.load(UpperCamelCase_				).get("""compute_environment"""					,			ComputeEnvironment.LOCAL_MACHINE				)
												    == ComputeEnvironment.LOCAL_MACHINE
												):
																_lowerCAmelCase			:			List[Any]        =					ClusterConfig
												else:
																_lowerCAmelCase			:			str        =					SageMakerConfig
												return config_class.from_json_file(json_file=UpperCamelCase_				)
								else:
												if (
												    yaml.safe_load(UpperCamelCase_				).get("""compute_environment"""					,			ComputeEnvironment.LOCAL_MACHINE				)
												    == ComputeEnvironment.LOCAL_MACHINE
												):
																_lowerCAmelCase			:			Any        =					ClusterConfig
												else:
																_lowerCAmelCase			:			Tuple        =					SageMakerConfig
												return config_class.from_yaml_file(yaml_file=UpperCamelCase_				)
@dataclass
class 				__snake_case     :
				lowerCAmelCase__			=   42
				lowerCAmelCase__			=   42
				lowerCAmelCase__			=   42
				lowerCAmelCase__			=   42



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[int]					)     ->			Tuple:





								'''simple docstring'''




								_lowerCAmelCase			:			Any        =					self.__dict__
								# For serialization, it's best to convert Enums to strings (or their underlying value type).
								for key, value in result.items():
												if isinstance(_UpperCAmelCase						,		_UpperCAmelCase					):
																_lowerCAmelCase			:			Union[str, Any]        =					value.value
												if isinstance(_UpperCAmelCase						,		_UpperCAmelCase					) and not bool(_UpperCAmelCase					):
																_lowerCAmelCase			:			str        =					None
								_lowerCAmelCase			:			List[str]        =					{k: v for k, v in result.items() if v is not None}
								return result



				@classmethod
				def 					SCREAMING_SNAKE_CASE				(					cls					:						List[Any]						,		_UpperCAmelCase					:						int=None					)     ->			Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			Union[str, Any]        =					default_json_config_file if json_file is None else json_file
								with open(_UpperCAmelCase						,		"""r"""						,		encoding="""utf-8"""					) as f:
												_lowerCAmelCase			:			Optional[int]        =					json.load(_UpperCAmelCase					)
								if "compute_environment" not in config_dict:
												_lowerCAmelCase			:			Dict        =					ComputeEnvironment.LOCAL_MACHINE
								if "mixed_precision" not in config_dict:
												_lowerCAmelCase			:			int        =					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
								if "fp16" in config_dict:  # Convert the config to the new format.
												del config_dict["fp16"]
								if "dynamo_backend" in config_dict:  # Convert the config to the new format.
												_lowerCAmelCase			:			Tuple        =					config_dict.pop("""dynamo_backend"""					)
												_lowerCAmelCase			:			str        =					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
								if "use_cpu" not in config_dict:
												_lowerCAmelCase			:			Dict        =					False
								return cls(**_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[Any]						,		_UpperCAmelCase					:						Optional[int]					)     ->			List[str]:





								'''simple docstring'''




								with open(_UpperCAmelCase						,		"""w"""						,		encoding="""utf-8"""					) as f:
												_lowerCAmelCase			:			str        =					json.dumps(self.to_dict()						,		indent=2						,		sort_keys=_UpperCAmelCase					) + """\n"""
												f.write(_UpperCAmelCase					)



				@classmethod
				def 					SCREAMING_SNAKE_CASE				(					cls					:						List[Any]						,		_UpperCAmelCase					:						str=None					)     ->			Optional[Any]:





								'''simple docstring'''




								_lowerCAmelCase			:			List[str]        =					default_yaml_config_file if yaml_file is None else yaml_file
								with open(_UpperCAmelCase						,		"""r"""						,		encoding="""utf-8"""					) as f:
												_lowerCAmelCase			:			int        =					yaml.safe_load(_UpperCAmelCase					)
								if "compute_environment" not in config_dict:
												_lowerCAmelCase			:			Any        =					ComputeEnvironment.LOCAL_MACHINE

								if "mixed_precision" not in config_dict:
												_lowerCAmelCase			:			Union[str, Any]        =					"""fp16""" if ("""fp16""" in config_dict and config_dict["""fp16"""]) else None
								if isinstance(config_dict["""mixed_precision"""]						,		_UpperCAmelCase					) and not config_dict["mixed_precision"]:
												_lowerCAmelCase			:			Tuple        =					"""no"""
								if "fp16" in config_dict:  # Convert the config to the new format.
												del config_dict["fp16"]
								if "dynamo_backend" in config_dict:  # Convert the config to the new format.
												_lowerCAmelCase			:			Any        =					config_dict.pop("""dynamo_backend"""					)
												_lowerCAmelCase			:			Union[str, Any]        =					{} if dynamo_backend == """NO""" else {"""dynamo_backend""": dynamo_backend}
								if "use_cpu" not in config_dict:
												_lowerCAmelCase			:			int        =					False
								return cls(**_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Optional[Any]						,		_UpperCAmelCase					:						Optional[Any]					)     ->			Dict:





								'''simple docstring'''




								with open(_UpperCAmelCase						,		"""w"""						,		encoding="""utf-8"""					) as f:
												yaml.safe_dump(self.to_dict()						,		_UpperCAmelCase					)



				def 					SCREAMING_SNAKE_CASE				(					self					:						Any					)     ->			Dict:





								'''simple docstring'''




								if isinstance(self.compute_environment						,		_UpperCAmelCase					):
												_lowerCAmelCase			:			Optional[Any]        =					ComputeEnvironment(self.compute_environment					)
								if isinstance(self.distributed_type						,		_UpperCAmelCase					):
												if self.compute_environment == ComputeEnvironment.AMAZON_SAGEMAKER:
																_lowerCAmelCase			:			Optional[int]        =					SageMakerDistributedType(self.distributed_type					)
												else:
																_lowerCAmelCase			:			Dict        =					DistributedType(self.distributed_type					)
								if self.dynamo_config is None:
												_lowerCAmelCase			:			int        =					{}






@dataclass
class 				__snake_case     (_a						):
				lowerCAmelCase__			=   42
				lowerCAmelCase__			=   0
				lowerCAmelCase__			=   1
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   "static"
				lowerCAmelCase__			=   False
				lowerCAmelCase__			=   "main"

				# args for deepspeed_plugin
				lowerCAmelCase__			=   None
				# args for fsdp
				lowerCAmelCase__			=   None
				# args for megatron_lm
				lowerCAmelCase__			=   None
				# args for ipex
				lowerCAmelCase__			=   None
				# args for TPU
				lowerCAmelCase__			=   False

				# args for TPU pods
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   False
				lowerCAmelCase__			=   False
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None

				# args for dynamo
				lowerCAmelCase__			=   None



				def 					SCREAMING_SNAKE_CASE				(					self					:						Any					)     ->			Dict:





								'''simple docstring'''




								if self.deepspeed_config is None:
												_lowerCAmelCase			:			Optional[int]        =					{}
								if self.fsdp_config is None:
												_lowerCAmelCase			:			Dict        =					{}
								if self.megatron_lm_config is None:
												_lowerCAmelCase			:			Optional[Any]        =					{}
								if self.ipex_config is None:
												_lowerCAmelCase			:			Union[str, Any]        =					{}
								return super().__post_init__()






@dataclass
class 				__snake_case     (_a						):
				lowerCAmelCase__			=   42
				lowerCAmelCase__			=   42
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   "us-east-1"
				lowerCAmelCase__			=   1
				lowerCAmelCase__			=   "all"
				lowerCAmelCase__			=   F'''accelerate-sagemaker-{num_machines}'''
				lowerCAmelCase__			=   SAGEMAKER_PYTORCH_VERSION
				lowerCAmelCase__			=   SAGEMAKER_TRANSFORMERS_VERSION
				lowerCAmelCase__			=   SAGEMAKER_PYTHON_VERSION
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None
				lowerCAmelCase__			=   None







import argparse

import torch

from transformers import HubertConfig, HubertForSequenceClassification, WavaVecaFeatureExtractor, logging


logging.set_verbosity_info()
_lowerCamelCase					:     List[str]					  =  logging.get_logger(__name__)

_lowerCamelCase					:     Tuple					  =  ["UtteranceLevel"]




@torch.no_grad()
def 							_UpperCAmelCase     (UpperCamelCase_       :       Optional[Any]					,			UpperCamelCase_       :       List[Any]					,			UpperCamelCase_       :       Tuple					,			UpperCamelCase_       :       Dict				):
				'''simple docstring'''
				_lowerCAmelCase			:			List[str]        =					torch.load(UpperCamelCase_					,			map_location="""cpu"""				)
				if checkpoint["Config"]["downstream_expert"]["modelrc"]["select"] not in SUPPORTED_MODELS:
								raise NotImplementedError(F"The supported s3prl models are {SUPPORTED_MODELS}"				)

				_lowerCAmelCase			:			List[str]        =					checkpoint["""Downstream"""]

				_lowerCAmelCase			:			Optional[int]        =					HubertConfig.from_pretrained(UpperCamelCase_				)
				_lowerCAmelCase			:			str        =					HubertForSequenceClassification.from_pretrained(UpperCamelCase_					,			config=UpperCamelCase_				)
				_lowerCAmelCase			:			Union[str, Any]        =					WavaVecaFeatureExtractor.from_pretrained(
				    UpperCamelCase_					,			return_attention_mask=UpperCamelCase_					,			do_normalize=UpperCamelCase_				)

				if hf_congfig.use_weighted_layer_sum:
								_lowerCAmelCase			:			int        =					checkpoint["""Featurizer"""]["""weights"""]

				_lowerCAmelCase			:			Optional[int]        =					downstream_dict["""projector.weight"""]
				_lowerCAmelCase			:			int        =					downstream_dict["""projector.bias"""]
				_lowerCAmelCase			:			Dict        =					downstream_dict["""model.post_net.linear.weight"""]
				_lowerCAmelCase			:			Dict        =					downstream_dict["""model.post_net.linear.bias"""]

				hf_feature_extractor.save_pretrained(UpperCamelCase_				)
				hf_model.save_pretrained(UpperCamelCase_				)


if __name__ == "__main__":
	_lowerCamelCase					:     Any					  =  argparse.ArgumentParser()
	parser.add_argument(
	    "--base_model_name", default=None, type=str, help="Name of the huggingface pretrained base model."
	)
	parser.add_argument("--config_path", default=None, type=str, help="Path to the huggingface classifier config.")
	parser.add_argument("--checkpoint_path", default=None, type=str, help="Path to the s3prl checkpoint.")
	parser.add_argument("--model_dump_path", default=None, type=str, help="Path to the final converted model.")
	_lowerCamelCase					:     Dict					  =  parser.parse_args()
	convert_saprl_checkpoint(args.base_model_name, args.config_path, args.checkpoint_path, args.model_dump_path)

