
# Copyright 2023 The HuggingFace Inc. 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 ast
import difflib
from collections.abc import Mapping
from typing import Any, Callable, Dict




class 	UpperCAmelCase_      (			_A					):


  '''simple docstring'''







  pass







def a__   (	A_,					A_,					A_=None,					A_=False ):






  '''simple docstring'''





  try:
    __magic_name__    					=	ast.parse(A_ )
  except SyntaxError as e:
    print("""The code generated by the agent is not valid.\n""",					A_ )
    return
  if state is None:
    __magic_name__    					=	{}
  __magic_name__    					=	None
  for idx, node in enumerate(expression.body ):
    try:
      __magic_name__    					=	evaluate_ast(A_,					A_,					A_ )
    except InterpretorError as e:
      __magic_name__    					=	f'''Evaluation of the code stopped at line {idx} before the end because of the following error'''
      if chat_mode:
        msg += (
            f'''. Copy paste the following error message and send it back to the agent:\nI get an error: \'{e}\''''
        )
      else:
        msg += f''':\n{e}'''
      print(A_ )
      break
    if line_result is not None:
      __magic_name__    					=	line_result

  return result

def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  if isinstance(A_,					ast.Assign ):
    # Assignement -> we evaluate the assignement which should update the state
    # We return the variable assigned as it may be used to determine the final result.
    return evaluate_assign(A_,					A_,					A_ )
  elif isinstance(A_,					ast.Call ):
    # Function call -> we return the value of the function call
    return evaluate_call(A_,					A_,					A_ )
  elif isinstance(A_,					ast.Constant ):
    # Constant -> just return the value
    return expression.value
  elif isinstance(A_,					ast.Dict ):
    # Dict -> evaluate all keys and values
    __magic_name__    					=	[evaluate_ast(A_,					A_,					A_ ) for k in expression.keys]
    __magic_name__    					=	[evaluate_ast(A_,					A_,					A_ ) for v in expression.values]
    return dict(zip(A_,					A_ ) )
  elif isinstance(A_,					ast.Expr ):
    # Expression -> evaluate the content
    return evaluate_ast(expression.value,					A_,					A_ )
  elif isinstance(A_,					ast.For ):
    # For loop -> execute the loop
    return evaluate_for(A_,					A_,					A_ )
  elif isinstance(A_,					ast.FormattedValue ):
    # Formatted value (part of f-string) -> evaluate the content and return
    return evaluate_ast(expression.value,					A_,					A_ )
  elif isinstance(A_,					ast.If ):
    # If -> execute the right branch
    return evaluate_if(A_,					A_,					A_ )
  elif hasattr(A_,					"""Index""" ) and isinstance(A_,					ast.Index ):
    return evaluate_ast(expression.value,					A_,					A_ )
  elif isinstance(A_,					ast.JoinedStr ):
    return "".join([str(evaluate_ast(A_,					A_,					A_ ) ) for v in expression.values] )
  elif isinstance(A_,					ast.List ):
    # List -> evaluate all elements
    return [evaluate_ast(A_,					A_,					A_ ) for elt in expression.elts]
  elif isinstance(A_,					ast.Name ):
    # Name -> pick up the value in the state
    return evaluate_name(A_,					A_,					A_ )
  elif isinstance(A_,					ast.Subscript ):
    # Subscript -> return the value of the indexing
    return evaluate_subscript(A_,					A_,					A_ )
  else:
    # For now we refuse anything else. Let's add things as we need them.
    raise InterpretorError(f'''{expression.__class__.__name__} is not supported.''' )

def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  __magic_name__    					=	assign.targets
  __magic_name__    					=	evaluate_ast(assign.value,					A_,					A_ )

  if len(A_ ) == 1:
    __magic_name__    					=	result
  else:
    if len(A_ ) != len(A_ ):
      raise InterpretorError(f'''Expected {len(A_ )} values but got {len(A_ )}.''' )
    for var_name, r in zip(A_,					A_ ):
      __magic_name__    					=	r
  return result

def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  if not isinstance(call.func,					ast.Name ):
    raise InterpretorError(
        f'''It is not permitted to evaluate other functions than the provided tools (tried to execute {call.func} of '''
        f'''type {type(call.func )}.''' )
  __magic_name__    					=	call.func.id
  if func_name not in tools:
    raise InterpretorError(
        f'''It is not permitted to evaluate other functions than the provided tools (tried to execute {call.func.id}).''' )

  __magic_name__    					=	tools[func_name]
  # Todo deal with args
  __magic_name__    					=	[evaluate_ast(A_,					A_,					A_ ) for arg in call.args]
  __magic_name__    					=	{keyword.arg: evaluate_ast(keyword.value,					A_,					A_ ) for keyword in call.keywords}
  return func(*A_,					**A_ )

def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  __magic_name__    					=	evaluate_ast(subscript.slice,					A_,					A_ )
  __magic_name__    					=	evaluate_ast(subscript.value,					A_,					A_ )
  if isinstance(A_,					(list, tuple) ):
    return value[int(A_ )]
  if index in value:
    return value[index]
  if isinstance(A_,					A_ ) and isinstance(A_,					A_ ):
    __magic_name__    					=	difflib.get_close_matches(A_,					list(value.keys() ) )
    if len(A_ ) > 0:
      return value[close_matches[0]]

  raise InterpretorError(f'''Could not index {value} with \'{index}\'.''' )

def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  if name.id in state:
    return state[name.id]
  __magic_name__    					=	difflib.get_close_matches(name.id,					list(state.keys() ) )
  if len(A_ ) > 0:
    return state[close_matches[0]]
  raise InterpretorError(f'''The variable `{name.id}` is not defined.''' )

def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  if len(condition.ops ) > 1:
    raise InterpretorError("""Cannot evaluate conditions with multiple operators""" )

  __magic_name__    					=	evaluate_ast(condition.left,					A_,					A_ )
  __magic_name__    					=	condition.ops[0]
  __magic_name__    					=	evaluate_ast(condition.comparators[0],					A_,					A_ )

  if isinstance(A_,					ast.Eq ):
    return left == right
  elif isinstance(A_,					ast.NotEq ):
    return left != right
  elif isinstance(A_,					ast.Lt ):
    return left < right
  elif isinstance(A_,					ast.LtE ):
    return left <= right
  elif isinstance(A_,					ast.Gt ):
    return left > right
  elif isinstance(A_,					ast.GtE ):
    return left >= right
  elif isinstance(A_,					ast.Is ):
    return left is right
  elif isinstance(A_,					ast.IsNot ):
    return left is not right
  elif isinstance(A_,					ast.In ):
    return left in right
  elif isinstance(A_,					ast.NotIn ):
    return left not in right
  else:
    raise InterpretorError(f'''Operator not supported: {comparator}''' )

def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  __magic_name__    					=	None
  if evaluate_condition(if_statement.test,					A_,					A_ ):
    for line in if_statement.body:
      __magic_name__    					=	evaluate_ast(A_,					A_,					A_ )
      if line_result is not None:
        __magic_name__    					=	line_result
  else:
    for line in if_statement.orelse:
      __magic_name__    					=	evaluate_ast(A_,					A_,					A_ )
      if line_result is not None:
        __magic_name__    					=	line_result
  return result





def a__   (	A_,					A_,					A_ ):






  '''simple docstring'''





  __magic_name__    					=	None
  __magic_name__    					=	evaluate_ast(for_loop.iter,					A_,					A_ )
  for counter in iterator:
    __magic_name__    					=	counter
    for expression in for_loop.body:
      __magic_name__    					=	evaluate_ast(A_,					A_,					A_ )
      if line_result is not None:
        __magic_name__    					=	line_result
  return result



import torch.nn as nn

from .imports import is_fpa_available


if is_fpa_available():
    import transformer_engine.pytorch as te

def a__   (	A_,					A_=True,					A_=True,					A_=True ):






  '''simple docstring'''





  if not is_fpa_available():
    raise ImportError("""Using `convert_model` requires transformer_engine to be installed.""" )
  for name, module in model.named_children():
    if isinstance(A_,					nn.Linear ) and to_transformer_engine and _convert_linear:
      # Return early if the linear layer weights are not multiples of 16
      if any(p % 16 != 0 for p in module.weight.shape ):
        return
      __magic_name__    					=	module.bias is not None
      __magic_name__    					=	te.Linear(
          module.in_features,					module.out_features,					bias=A_,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      if has_bias:
        __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    elif isinstance(A_,					nn.LayerNorm ) and to_transformer_engine and _convert_ln:
      __magic_name__    					=	te.LayerNorm(module.normalized_shape[0],					eps=module.eps,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    elif isinstance(A_,					te.Linear ) and not to_transformer_engine and _convert_linear:
      __magic_name__    					=	module.bias is not None
      __magic_name__    					=	nn.Linear(
          module.in_features,					module.out_features,					bias=A_,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      if has_bias:
        __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    elif isinstance(A_,					te.LayerNorm ) and not to_transformer_engine and _convert_ln:
      __magic_name__    					=	nn.LayerNorm(module.normalized_shape[0],					eps=module.eps,					params_dtype=module.weight.dtype )
      __magic_name__    					=	module.weight.data.clone()
      __magic_name__    					=	module.bias.data.clone()

      setattr(A_,					A_,					A_ )
    else:
      convert_model(
          A_,					to_transformer_engine=A_,					_convert_linear=_convert_linear,					_convert_ln=_convert_ln,					)





def a__   (	A_ ):






  '''simple docstring'''





  if not is_fpa_available():
    raise ImportError("""Using `has_transformer_engine_layers` requires transformer_engine to be installed.""" )
  for m in model.modules():
    if isinstance(A_,					(te.LayerNorm, te.Linear) ):
      return True
  return False

