

# 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 copy
import importlib.metadata
import json
import os
from dataclasses import dataclass
from typing import Any, Dict, Union

from packaging import version

from ..utils import is_torch_available, logging


if is_torch_available():
  import torch


SCREAMING_SNAKE_CASE__    				=     logging.get_logger(__name__)





@dataclass
class A__    :



 """simple docstring"""







 def __init__(		self :	Optional[int]     ,						A_ :	str=False     ,						A_ :	Tuple=False     ,						A_ :	Optional[Any]=6.0     ,						A_ :	int=None     ,						A_ :	str=False     ,						A_ :	Optional[int]=False     ,						A_ :	Dict=None     ,						A_ :	str="fp4"     ,						A_ :	Any=False     ,						**A_ :	int     ,						):






      '''simple docstring'''




      _lowerCAmelCase   :					Union[str, Any]        =    load_in_abit
      _lowerCAmelCase   :					List[Any]        =    load_in_abit
      _lowerCAmelCase   :					str        =    llm_inta_threshold
      _lowerCAmelCase   :					Dict        =    llm_inta_skip_modules
      _lowerCAmelCase   :					List[Any]        =    llm_inta_enable_fpaa_cpu_offload
      _lowerCAmelCase   :					Optional[int]        =    llm_inta_has_fpaa_weight
      _lowerCAmelCase   :					List[str]        =    bnb_abit_quant_type
      _lowerCAmelCase   :					Any        =    bnb_abit_use_double_quant

      if bnb_abit_compute_dtype is None:
           _lowerCAmelCase   :					Tuple        =    torch.floataa
      elif isinstance(UpperCAmelCase_     ,						UpperCAmelCase_       ):
           _lowerCAmelCase   :					int        =    getattr(UpperCAmelCase_     ,						UpperCAmelCase_       )
      elif isinstance(UpperCAmelCase_     ,						torch.dtype       ):
           _lowerCAmelCase   :					Tuple        =    bnb_abit_compute_dtype
      else:
           raise ValueError("bnb_4bit_compute_dtype must be a string or a torch.dtype"       )

      self.post_init()

 def    __magic_name__       (		self :	Any       ):






      '''simple docstring'''




      if not isinstance(self.llm_inta_threshold     ,						UpperCAmelCase_       ):
           raise ValueError("llm_int8_threshold must be a float"       )

      if self.llm_inta_skip_modules is not None and not isinstance(self.llm_inta_skip_modules     ,						UpperCAmelCase_       ):
           raise ValueError("llm_int8_skip_modules must be a list of strings"       )
      if not isinstance(self.llm_inta_enable_fpaa_cpu_offload     ,						UpperCAmelCase_       ):
           raise ValueError("llm_int8_enable_fp32_cpu_offload must be a boolean"       )

      if not isinstance(self.llm_inta_has_fpaa_weight     ,						UpperCAmelCase_       ):
           raise ValueError("llm_int8_has_fp16_weight must be a boolean"       )

      if self.bnb_abit_compute_dtype is not None and not isinstance(self.bnb_abit_compute_dtype     ,						torch.dtype       ):
           raise ValueError("bnb_4bit_compute_dtype must be torch.dtype"       )

      if not isinstance(self.bnb_abit_quant_type     ,						UpperCAmelCase_       ):
           raise ValueError("bnb_4bit_quant_type must be a string"       )

      if not isinstance(self.bnb_abit_use_double_quant     ,						UpperCAmelCase_       ):
           raise ValueError("bnb_4bit_use_double_quant must be a boolean"       )

      if self.load_in_abit and not version.parse(importlib.metadata.version("bitsandbytes"       )       ) >= version.parse(
          "0.39.0"       ):
           raise ValueError(
               "4 bit quantization requires bitsandbytes>=0.39.0 - please upgrade your bitsandbytes version"       )

 def    __magic_name__       (		self :	Dict       ):






      '''simple docstring'''




      return self.load_in_abit or self.load_in_abit

 def    __magic_name__       (		self :	str       ):






      '''simple docstring'''




      if self.load_in_abit:
           return "llm_int8"
      elif self.load_in_abit and self.bnb_abit_quant_type == "fp4":
           return "fp4"
      elif self.load_in_abit and self.bnb_abit_quant_type == "nf4":
           return "nf4"
      else:
           return None

 @classmethod
 def    __magic_name__       (		cls :	List[Any]     ,						A_ :	Dict     ,						A_ :	Dict     ,						**A_ :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Tuple        =    cls(**UpperCAmelCase_       )

      _lowerCAmelCase   :					Union[str, Any]        =    []
      for key, value in kwargs.items():
           if hasattr(UpperCAmelCase_     ,						UpperCAmelCase_       ):
                setattr(UpperCAmelCase_     ,						UpperCAmelCase_     ,						UpperCAmelCase_       )
                to_remove.append(UpperCAmelCase_       )
      for key in to_remove:
           kwargs.pop(UpperCAmelCase_     ,						UpperCAmelCase_       )

      if return_unused_kwargs:
           return config, kwargs
      else:
           return config

 def    __magic_name__       (		self :	List[Any]     ,						A_ :	str       ):






      '''simple docstring'''




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

           writer.write(UpperCAmelCase_       )

 def    __magic_name__       (		self :	List[str]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					str        =    copy.deepcopy(self.__dict__       )
      _lowerCAmelCase   :					int        =    str(output["bnb_4bit_compute_dtype"]       ).split("."       )[1]

      return output

 def __repr__(		self :	List[Any]       ):






      '''simple docstring'''




      return F'''{self.__class__.__name__} {self.to_json_string()}'''

 def    __magic_name__       (		self :	List[Any]     ,						A_ :	List[Any] = True       ):






      '''simple docstring'''




      if use_diff is True:
           _lowerCAmelCase   :					List[str]        =    self.to_diff_dict()
      else:
           _lowerCAmelCase   :					Union[str, Any]        =    self.to_dict()
      return json.dumps(UpperCAmelCase_     ,						indent=2     ,						sort_keys=UpperCAmelCase_       ) + "\n"


 def    __magic_name__       (		self :	Optional[int]       ):






      '''simple docstring'''




      _lowerCAmelCase   :					Tuple        =    self.to_dict()

      # get the default config dict
      _lowerCAmelCase   :					Optional[int]        =    BitsAndBytesConfig().to_dict()

      _lowerCAmelCase   :					Union[str, Any]        =    {}

      # only serialize values that differ from the default config
      for key, value in config_dict.items():
           if value != default_config_dict[key]:
                _lowerCAmelCase   :					List[Any]        =    value

      return serializable_config_dict









from __future__ import annotations







def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)       ->      List[Any]:

     """simple docstring"""







     print(f'''Vertex\tShortest Distance from vertex {src}'''				)
     for i, d in enumerate(SCREAMING_SNAKE_CASE				):
          print(f'''{i}\t\t{d}'''				)







def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)       ->      Tuple:

     """simple docstring"""







     for j in range(SCREAMING_SNAKE_CASE				):
          _lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase   :					Any        =    (graph[j][k] for k in ["src", "dst", "weight"])
          if distance[u] != float("inf"				) and distance[u] + w < distance[v]:
               return True
     return False







def 	_snake_case		(    SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)       ->      list[float]:

     """simple docstring"""







     _lowerCAmelCase   :					Tuple        =    [float("inf"				)] * vertex_count
     _lowerCAmelCase   :					int        =    0.0

     for _ in range(vertex_count - 1				):
          for j in range(SCREAMING_SNAKE_CASE				):
               _lowerCAmelCase      ,			_lowerCAmelCase      ,			_lowerCAmelCase   :					int        =    (graph[j][k] for k in ["src", "dst", "weight"])

               if distance[u] != float("inf"				) and distance[u] + w < distance[v]:
                    _lowerCAmelCase   :					List[str]        =    distance[u] + w

     _lowerCAmelCase   :					int        =    check_negative_cycle(SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE		,							SCREAMING_SNAKE_CASE				)
     if negative_cycle_exists:
          raise Exception("Negative cycle found"				)

     return distance


if __name__ == "__main__":
  import doctest

  doctest.testmod()

  __UpperCAmelCase    				=     int(input('Enter number of vertices: ').strip())
  __UpperCAmelCase    				=     int(input('Enter number of edges: ').strip())

  __UpperCAmelCase    				=     [{} for _ in range(E)]

  for i in range(E):
    print('Edge ', i + 1)
    __UpperCAmelCase				,__UpperCAmelCase				,__UpperCAmelCase    				=     (
        int(x)
        for x in input('Enter source, destination, weight: ').strip().split(' ')
    )
    __UpperCAmelCase    				=     {'src': src, 'dst': dest, 'weight': weight}

  __UpperCAmelCase    				=     int(input('\nEnter shortest path source:').strip())
  __UpperCAmelCase    				=     bellman_ford(graph, V, E, source)
  print_distance(shortest_distance, 0)






