



from __future__ import annotations

import math
import random
from collections.abc import Collection
from typing import overload
class SCREAMING_SNAKE_CASE_						:






						def __init__(      self      :      int		,   _A      :      Collection[float] | None = None	)							->    None:







							"""simple docstring"""


							if components is None:
								snake_case_		:			Dict											=	[]
							snake_case_		:			Optional[Any]											=	list(_A	)






						def __len__(      self      :      Dict	)							->    int:







							"""simple docstring"""


							return len(self.__components	)






						def __str__(      self      :      Any	)							->    str:







							"""simple docstring"""


							return "(" + ",".join(map(_A		,   self.__components	)	) + ")"






						def __add__(      self      :      Optional[Any]		,   _A      :      Vector	)							->    Vector:







							"""simple docstring"""


							snake_case_		:			Optional[int]											=	len(self	)
							if size == len(_A	):
								snake_case_		:			Any											=	[self.__components[i] + other.component(_A	) for i in range(_A	)]
								return Vector(_A	)
							else:
								raise Exception('must have the same size'	)






						def __sub__(      self      :      List[Any]		,   _A      :      Vector	)							->    Vector:







							"""simple docstring"""


							snake_case_		:			str											=	len(self	)
							if size == len(_A	):
								snake_case_		:			List[str]											=	[self.__components[i] - other.component(_A	) for i in range(_A	)]
								return Vector(_A	)
							else:  # error case
								raise Exception('must have the same size'	)






						@overload
						def __mul__(      self      :      Any		,   _A      :      float	)							->    Vector:







							"""simple docstring"""


							...






						@overload
						def __mul__(      self      :      str		,   _A      :      Vector	)							->    float:







							"""simple docstring"""


							...






						def __mul__(      self      :      List[Any]		,   _A      :      float | Vector	)							->    float | Vector:







							"""simple docstring"""


							if isinstance(_A		,   (float, int)	):
								snake_case_		:			List[Any]											=	[c * other for c in self.__components]
								return Vector(_A	)
							elif isinstance(_A		,   _A	) and len(self	) == len(_A	):
								snake_case_		:			Tuple											=	len(self	)
								snake_case_		:			Dict											=	[self.__components[i] * other.component(_A	) for i in range(_A	)]
								return sum(_A	)
							else:  # error case
								raise Exception('invalid operand!'	)






						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    Vector:







							"""simple docstring"""


							return Vector(self.__components	)






						def UpperCAmelCase_				(      self      :      Tuple		,   _A      :      int	)							->    float:







							"""simple docstring"""


							if isinstance(_A		,   _A	) and -len(self.__components	) <= i < len(self.__components	):
								return self.__components[i]
							else:
								raise Exception('index out of range'	)






						def UpperCAmelCase_				(      self      :      Dict		,   _A      :      int		,   _A      :      float	)							->    None:







							"""simple docstring"""


							assert -len(self.__components	) <= pos < len(self.__components	)
							snake_case_		:			str											=	value






						def UpperCAmelCase_				(      self      :      Union[str, Any]	)							->    float:







							"""simple docstring"""


							if len(self.__components	) == 0:
								raise Exception('Vector is empty'	)
							snake_case_		:			int											=	[c**2 for c in self.__components]
							return math.sqrt(sum(_A	)	)






						def UpperCAmelCase_				(      self      :      str		,   _A      :      Vector		,   _A      :      bool = False	)							->    float:







							"""simple docstring"""


							snake_case_		:			str											=	self * other
							snake_case_		:			int											=	self.euclidean_length() * other.euclidean_length()
							if deg:
								return math.degrees(math.acos(num / den	)	)
							else:
								return math.acos(num / den	)


def 							SCREAMING_SNAKE_CASE__						(    __a   ):
	assert isinstance(__a   , __a   )
	return Vector([0] * dimension   )


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   ):
	assert isinstance(__a   , __a   ) and (isinstance(__a   , __a   ))
	snake_case_		:			Dict											=	[0] * dimension
	snake_case_		:			str											=	1
	return Vector(__a   )


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a   ):
	assert (
	    isinstance(__a   , __a   )
	    and isinstance(__a   , __a   )
	    and (isinstance(__a   , (int, float)   ))
	)
	return x * scalar + y


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a   ):
	random.seed(__a   )
	snake_case_		:			List[Any]											=	[random.randint(__a   , __a   ) for _ in range(__a   )]
	return Vector(__a   )
class SCREAMING_SNAKE_CASE_						:






						def __init__(      self      :      List[Any]		,   _A      :      list[list[float]]		,   _A      :      int		,   _A      :      int	)							->    None:







							"""simple docstring"""


							snake_case_		:			Dict											=	matrix
							snake_case_		:			Tuple											=	w
							snake_case_		:			Any											=	h






						def __str__(      self      :      Union[str, Any]	)							->    str:







							"""simple docstring"""


							snake_case_		:			List[Any]											=	''
							for i in range(self.__height	):
								ans += "|"
								for j in range(self.__width	):
									if j < self.__width - 1:
										ans += str(self.__matrix[i][j]	) + ","
									else:
										ans += str(self.__matrix[i][j]	) + "|\n"
							return ans






						def __add__(      self      :      Optional[int]		,   _A      :      Matrix	)							->    Matrix:







							"""simple docstring"""


							if self.__width == other.width() and self.__height == other.height():
								snake_case_		:			Optional[Any]											=	[]
								for i in range(self.__height	):
									snake_case_		:			Optional[Any]											=	[
									    self.__matrix[i][j] + other.component(_A		,   _A	)
									    for j in range(self.__width	)
									]
									matrix.append(_A	)
								return Matrix(_A		,   self.__width		,   self.__height	)
							else:
								raise Exception('matrix must have the same dimension!'	)






						def __sub__(      self      :      Dict		,   _A      :      Matrix	)							->    Matrix:







							"""simple docstring"""


							if self.__width == other.width() and self.__height == other.height():
								snake_case_		:			List[str]											=	[]
								for i in range(self.__height	):
									snake_case_		:			Optional[int]											=	[
									    self.__matrix[i][j] - other.component(_A		,   _A	)
									    for j in range(self.__width	)
									]
									matrix.append(_A	)
								return Matrix(_A		,   self.__width		,   self.__height	)
							else:
								raise Exception('matrices must have the same dimension!'	)






						@overload
						def __mul__(      self      :      int		,   _A      :      float	)							->    Matrix:







							"""simple docstring"""


							...






						@overload
						def __mul__(      self      :      str		,   _A      :      Vector	)							->    Vector:







							"""simple docstring"""


							...






						def __mul__(      self      :      Union[str, Any]		,   _A      :      float | Vector	)							->    Vector | Matrix:







							"""simple docstring"""


							if isinstance(_A		,   _A	):  # matrix-vector
								if len(_A	) == self.__width:
									snake_case_		:			Optional[Any]											=	zero_vector(self.__height	)
									for i in range(self.__height	):
										snake_case_		:			Union[str, Any]											=	[
										    self.__matrix[i][j] * other.component(_A	)
										    for j in range(self.__width	)
										]
										ans.change_component(_A		,   sum(_A	)	)
									return ans
								else:
									raise Exception(
									    'vector must have the same size as the '
									    'number of columns of the matrix!'	)
							elif isinstance(_A		,   (int, float)	):  # matrix-scalar
								snake_case_		:			Tuple											=	[
								    [self.__matrix[i][j] * other for j in range(self.__width	)]
								    for i in range(self.__height	)
								]
								return Matrix(_A		,   self.__width		,   self.__height	)
							return None






						def UpperCAmelCase_				(      self      :      str	)							->    int:







							"""simple docstring"""


							return self.__height






						def UpperCAmelCase_				(      self      :      Tuple	)							->    int:







							"""simple docstring"""


							return self.__width






						def UpperCAmelCase_				(      self      :      List[Any]		,   _A      :      int		,   _A      :      int	)							->    float:







							"""simple docstring"""


							if 0 <= x < self.__height and 0 <= y < self.__width:
								return self.__matrix[x][y]
							else:
								raise Exception('change_component: indices out of bounds'	)






						def UpperCAmelCase_				(      self      :      str		,   _A      :      int		,   _A      :      int		,   _A      :      float	)							->    None:







							"""simple docstring"""


							if 0 <= x < self.__height and 0 <= y < self.__width:
								snake_case_		:			Optional[Any]											=	value
							else:
								raise Exception('change_component: indices out of bounds'	)






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      int		,   _A      :      int	)							->    float:







							"""simple docstring"""


							if self.__height != self.__width:
								raise Exception('Matrix is not square'	)
							snake_case_		:			Optional[int]											=	self.__matrix[:x] + self.__matrix[x + 1 :]
							for i in range(len(_A	)	):
								snake_case_		:			Any											=	minor[i][:y] + minor[i][y + 1 :]
							return Matrix(_A		,   self.__width - 1		,   self.__height - 1	).determinant()






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      int		,   _A      :      int	)							->    float:







							"""simple docstring"""


							if self.__height != self.__width:
								raise Exception('Matrix is not square'	)
							if 0 <= x < self.__height and 0 <= y < self.__width:
								return (-1) ** (x + y) * self.minor(_A		,   _A	)
							else:
								raise Exception('Indices out of bounds'	)






						def UpperCAmelCase_				(      self      :      List[str]	)							->    float:







							"""simple docstring"""


							if self.__height != self.__width:
								raise Exception('Matrix is not square'	)
							if self.__height < 1:
								raise Exception('Matrix has no element'	)
							elif self.__height == 1:
								return self.__matrix[0][0]
							elif self.__height == 2:
								return (
								    self.__matrix[0][0] * self.__matrix[1][1]
								    - self.__matrix[0][1] * self.__matrix[1][0]
								)
							else:
								snake_case_		:			str											=	[
								    self.__matrix[0][y] * self.cofactor(0		,   _A	) for y in range(self.__width	)
								]
								return sum(_A	)


def 							SCREAMING_SNAKE_CASE__						(    __a   ):
	snake_case_		:			list[list[float]]											=	[[0] * n for _ in range(__a   )]
	return Matrix(__a   , __a   , __a   )


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a   , __a   ):
	random.seed(__a   )
	snake_case_		:			list[list[float]]											=	[
	    [random.randint(__a   , __a   ) for _ in range(__a   )] for _ in range(__a   )
	]
	return Matrix(__a   , __a   , __a   )








# XXX: we want transformers master here - in the absense of conftest manipulating sys.path:
# hack it in for now:
import sys
from pathlib import Path


_SCREAMING_SNAKE_CASE      	=		Path(__file__).resolve().parents[3] / """src"""
sys.path.insert(1, str(git_repo_path))

import dataclasses  # noqa
import io  # noqa
import itertools  # noqa
import json  # noqa
import os  # noqa
import unittest  # noqa
from copy import deepcopy  # noqa

from parameterized import parameterized  # noqa
from transformers import TrainingArguments, is_torch_available  # noqa
from transformers.deepspeed import is_deepspeed_available  # noqa
from transformers.file_utils import WEIGHTS_NAME  # noqa
from transformers.testing_utils import (  # noqa
    CaptureLogger,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    mockenv_context,
    require_deepspeed,
    require_torch_gpu,
    require_torch_multi_gpu,
    slow,
)
from transformers.trainer_utils import set_seed  # noqa


set_seed(42)

_SCREAMING_SNAKE_CASE      	=		{"""base""": """patrickvonplaten/wav2vec2_tiny_random""", """robust""": """patrickvonplaten/wav2vec2_tiny_random_robust"""}

_SCREAMING_SNAKE_CASE      	=		"""zero2"""
_SCREAMING_SNAKE_CASE      	=		"""zero3"""
_SCREAMING_SNAKE_CASE      	=		[ZEROa, ZEROa]


def 							SCREAMING_SNAKE_CASE__						(    __a   , __a   , __a   ):
	# customize the test name generator function as we want both params to appear in the sub-test
	# name, as by default it shows only the first param
	snake_case_		:			Tuple											=	parameterized.to_safe_name('_'.join(str(__a   ) for x in param.args   )   )
	return f"""{func.__name__}_{param_based_name}"""


# Cartesian-product of zero stages with models to test
_SCREAMING_SNAKE_CASE      	=		list(itertools.product(stages, models.keys()))


@slow
@require_deepspeed
@require_torch_gpu
class SCREAMING_SNAKE_CASE_						(					snake_case_					):






						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      Tuple		,   _A      :      Optional[Any]		,   _A      :      Optional[int]	)							->    Dict:







							"""simple docstring"""


							self.run_and_check(
							    stage=_A		,   model=_A		,   distributed=_A		,   fpaa=_A		,   )






						@require_torch_multi_gpu
						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      int		,   _A      :      Any		,   _A      :      int	)							->    Dict:







							"""simple docstring"""


							self.run_and_check(
							    stage=_A		,   model=_A		,   distributed=_A		,   fpaa=_A		,   )






						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      str		,   _A      :      List[str]		,   _A      :      str	)							->    Tuple:







							"""simple docstring"""


							self.run_and_check(
							    stage=_A		,   model=_A		,   distributed=_A		,   fpaa=_A		,   )






						@require_torch_multi_gpu
						@parameterized.expand(_A		,   name_func=_A	)
						def UpperCAmelCase_				(      self      :      Optional[int]		,   _A      :      int		,   _A      :      Union[str, Any]	)							->    List[Any]:







							"""simple docstring"""


							self.run_and_check(
							    stage=_A		,   model=_A		,   distributed=_A		,   fpaa=_A		,   )






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      Union[str, Any]	)							->    Any:







							"""simple docstring"""


							pass






						def UpperCAmelCase_				(      self      :      List[str]		,   _A      :      str		,   _A      :      str		,   _A      :      int = 10		,   _A      :      bool = True		,   _A      :      bool = True		,   _A      :      bool = True		,   )							->    Any:







							"""simple docstring"""


							snake_case_		:			Dict											=	models[model]

							snake_case_		:			str											=	self.run_trainer(
							    stage=_A		,   model_name=_A		,   eval_steps=_A		,   num_train_epochs=1		,   distributed=_A		,   fpaa=_A		,   )

							self.do_checks(_A	)

							return output_dir






						def UpperCAmelCase_				(      self      :      Any		,   _A      :      str		,   _A      :      str		,   _A      :      int = 10		,   _A      :      int = 1		,   _A      :      bool = True		,   _A      :      bool = True		,   )							->    Dict:







							"""simple docstring"""


							snake_case_		:			str											=	self.get_auto_remove_tmp_dir('./xxx'		,   after=_A	)
							snake_case_		:			Tuple											=	F"""
            --model_name_or_path {model_name}
            --dataset_name hf-internal-testing/librispeech_asr_dummy
            --dataset_config_name clean
            --train_split_name validation
            --validation_split_name validation
            --output_dir {output_dir}
            --num_train_epochs {str(_A	)}
            --per_device_train_batch_size 2
            --per_device_eval_batch_size 2
            --evaluation_strategy steps
            --learning_rate 5e-4
            --warmup_steps 8
            --orthography timit
            --preprocessing_num_workers 1
            --group_by_length
            --freeze_feature_extractor
            --report_to none
            --save_steps 0
            --eval_steps {eval_steps}
            --report_to none
        """.split()

							if fpaa:
								args.extend(['--fp16']	)

							# currently ds_config_wav2vec2_zero.json requires "zero_optimization.find_unused_parameters": true,
							# hence the separate config files
							snake_case_		:			Any											=	F"""--deepspeed {self.test_file_dir_str}/ds_config_wav2vec2_{stage}.json""".split()
							snake_case_		:			str											=	[F"""{self.examples_dir_str}/research_projects/wav2vec2/run_asr.py"""]
							snake_case_		:			int											=	self.get_launcher(_A	)

							snake_case_		:			List[str]											=	launcher + script + args + ds_args
							# keep for quick debug
							# print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
							execute_subprocess_async(_A		,   env=self.get_env()	)

							return output_dir






						def UpperCAmelCase_				(      self      :      Optional[Any]		,   _A      :      Optional[Any]=False	)							->    List[str]:







							"""simple docstring"""


							snake_case_		:			str											=	min(2		,   get_gpu_count()	) if distributed else 1
							return F"""deepspeed --num_nodes 1 --num_gpus {num_gpus}""".split()

