o
    8wi2                     @   sx  d dl Z d dlZd dlmZ d dlmZmZ d dlmZm	Z	 d dl
mZmZmZ d dlmZ d dlmZ deeeeef ef  d	eeef fd
dZdeeef d	eeef fddZd deeef deded	eeef fddZdeeef d	eeef fddZdeeef d	eeef fddZded	efddZdeeeeef f deded	eeeeef f fddZdS )!    N)	Namespace)MappingMutableMapping)asdictis_dataclass)AnyOptionalUnion)Tensor)_NUMPY_AVAILABLEparamsreturnc                 C   s"   t | tr	t| } | du ri } | S )zEnsure parameters are a dict or convert to dict if necessary.

    Args:
        params: Target to be converted to a dictionary

    Returns:
        params as a dictionary

    N)
isinstancer   varsr    r   ^/home/ubuntu/sommelier/.venv/lib/python3.10/site-packages/lightning_fabric/utilities/logger.py_convert_params   s
   
r   c                    s(   dt dt fdd  fdd|  D S )zSanitize callable params dict, e.g. ``{'a': <function_**** at 0x****>} -> {'a': 'function_****'}``.

    Args:
        params: Dictionary containing the hyperparameters

    Returns:
        dictionary with all callables sanitized

    valr   c                 S   sX   t | r| jS t| r*z|  }t|r| jW S |W S  ty)   t| dd  Y S w | S )N__name__)inspectisclassr   callable	Exceptiongetattr)r   _valr   r   r   _sanitize_callable:   s   
z5_sanitize_callable_params.<locals>._sanitize_callablec                    s   i | ]	\}}| |qS r   r   ).0keyr   r   r   r   
<dictcomp>J   s    z-_sanitize_callable_params.<locals>.<dictcomp>)r   itemsr   r   r   r   _sanitize_callable_params/   s   r"   / 	delimiter
parent_keyc           	      C   s   i }|   D ]f\}}|r|| t| nt|}t|r&t|ts&t|}n	t|tr/t|}t|tr@i |t	|||d}qt|t
rhtdd |D rht|D ]\}}i |t	|| d| |d}qRq|||< q|S )a  Flatten hierarchical dict, e.g. ``{'a': {'b': 'c'}} -> {'a/b': 'c'}``.

    Args:
        params: Dictionary containing the hyperparameters
        delimiter: Delimiter to express the hierarchy. Defaults to ``'/'``.

    Returns:
        Flattened dict.

    Examples:
        >>> _flatten_dict({'a': {'b': 'c'}})
        {'a/b': 'c'}
        >>> _flatten_dict({'a': {'b': 123}})
        {'a/b': 123}
        >>> _flatten_dict({5: {'a': 123}})
        {'5/a': 123}
        >>> _flatten_dict({"dl": [{"a": 1, "c": 3}, {"b": 2, "d": 5}], "l": [1, 2, 3, 4]})
        {'dl/0/a': 1, 'dl/0/c': 3, 'dl/1/b': 2, 'dl/1/d': 5, 'l': [1, 2, 3, 4]}

    )r&   r%   c                 s   s    | ]}t |tV  qd S )N)r   r   )r   itemr   r   r   	<genexpr>m   s    z _flatten_dict.<locals>.<genexpr>r#   )r!   strr   r   typer   r   r   r   _flatten_dictlistall	enumerate)	r   r%   r&   resultkvnew_keyir'   r   r   r   r+   M   s   


"
r+   c                 C   sn   | D ]2}t rddl}t| | |j|j|jfr| |  | |< t| | tt	t
ttfvr4t| | | |< q| S )a  Returns params with non-primitvies converted to strings for logging.

    >>> import torch
    >>> params = {"float": 0.3,
    ...           "int": 1,
    ...           "string": "abc",
    ...           "bool": True,
    ...           "list": [1, 2, 3],
    ...           "namespace": Namespace(foo=3),
    ...           "layer": torch.nn.BatchNorm1d}
    >>> import pprint
    >>> pprint.pprint(_sanitize_params(params))  # doctest: +NORMALIZE_WHITESPACE
    {'bool': True,
        'float': 0.3,
        'int': 1,
        'layer': "<class 'torch.nn.modules.batchnorm.BatchNorm1d'>",
        'list': '[1, 2, 3]',
        'namespace': 'Namespace(foo=3)',
        'string': 'abc'}

    r   N)r   numpyr   bool_integerfloatingr'   r*   boolintfloatr)   r
   )r   r0   npr   r   r   _sanitize_paramsu   s   r<   c                 C   s   dd |   D S )z5Convert non-serializable objects in params to string.c                 S   s&   i | ]\}}|t |st|n|qS r   )_is_json_serializabler)   r   r0   r1   r   r   r   r       s   & z._convert_json_serializable.<locals>.<dictcomp>r!   r   r   r   r   _convert_json_serializable   s   r@   valuec              	   C   sL   | du st | ttttttfrdS zt|  W dS  t	t
fy%   Y dS w )z/Test whether a variable can be encoded as json.NTF)r   r8   r9   r:   r)   r,   dictjsondumps	TypeErrorOverflowError)rA   r   r   r   r=      s   
r=   metricsprefix	separatorc                    s     s| S  fdd|   D S )al  Insert prefix before each key in a dict, separated by the separator.

    Args:
        metrics: Dictionary with metric names as keys and measured quantities as values
        prefix: Prefix to insert before each key
        separator: Separates prefix and original key name

    Returns:
        Dictionary with prefix and separator inserted before each key

    c                    s"   i | ]\}}   | |qS r   r   r>   rH   rI   r   r   r       s   " z_add_prefix.<locals>.<dictcomp>r?   )rG   rH   rI   r   rJ   r   _add_prefix   s   rK   )r#   r$   )r   rC   argparser   collections.abcr   r   dataclassesr   r   typingr   r   r	   torchr
   "lightning_fabric.utilities.importsr   rB   r)   r   r"   r+   r<   r@   r8   r=   r:   rK   r   r   r   r   <module>   s.   .","("!