ding.utils.default_helper¶
ding.utils.default_helper
¶
LimitedSpaceContainer
¶
Overview
A space simulator.
Interfaces:
__init__, get_residual_space, release_space
__init__(min_val, max_val)
¶
Overview
Set min_val and max_val of the container, also set cur to min_val for initialization.
Arguments:
- min_val (:obj:int): Min volume of the container, usually 0.
- max_val (:obj:int): Max volume of the container.
get_residual_space()
¶
Overview
Get all residual pieces of space. Set cur to max_val
Arguments:
- ret (:obj:int): Residual space, calculated by max_val - cur.
acquire_space()
¶
Overview
Try to get one pice of space. If there is one, return True; Otherwise return False.
Returns:
- flag (:obj:bool): Whether there is any piece of residual space.
release_space()
¶
Overview
Release only one piece of space. Decrement cur, but ensure it won't be negative.
increase_space()
¶
Overview
Increase one piece in space. Increment max_val.
decrease_space()
¶
Overview
Decrease one piece in space. Decrement max_val.
RunningMeanStd
¶
Bases: object
Overview
Wrapper to update new variable, new mean, and new count
Interfaces:
__init__, update, reset, new_shape
Properties:
- mean, std, _epsilon, _shape, _mean, _var, _count
mean
property
¶
Overview
Property mean gotten from self._mean
std
property
¶
Overview
Property std calculated from self._var and the epsilon value of self._epsilon
__init__(epsilon=0.0001, shape=(), device=torch.device('cpu'))
¶
Overview
Initialize self. See help(type(self)) for accurate signature; setup the properties.
Arguments:
- env (:obj:gym.Env): the environment to wrap.
- epsilon (:obj:Float): the epsilon used for self for the std output
- shape (:obj: np.array): the np array shape used for the expression of this wrapper on attibutes of mean and variance
update(x)
¶
Overview
Update mean, variable, and count
Arguments:
- x: the batch
reset()
¶
Overview
Resets the state of the environment and reset properties: _mean, _var, _count
new_shape(obs_shape, act_shape, rew_shape)
staticmethod
¶
Overview
Get new shape of observation, acton, and reward; in this case unchanged.
Arguments:
obs_shape (:obj:Any), act_shape (:obj:Any), rew_shape (:obj:Any)
Returns:
obs_shape (:obj:Any), act_shape (:obj:Any), rew_shape (:obj:Any)
get_shape0(data)
¶
Overview
Get shape[0] of data's torch tensor or treetensor
Arguments:
- data (:obj:Union[List,Dict,torch.Tensor,ttorch.Tensor]): data to be analysed
Returns:
- shape[0] (:obj:int): first dimension length of data, usually the batchsize.
lists_to_dicts(data, recursive=False)
¶
Overview
Transform a list of dicts to a dict of lists.
Arguments:
- data (:obj:Union[List[Union[dict, NamedTuple]], Tuple[Union[dict, NamedTuple]]]):
A dict of lists need to be transformed
- recursive (:obj:bool): whether recursively deals with dict element
Returns:
- newdata (:obj:Union[Mapping[object, object], NamedTuple]): A list of dicts as a result
Example:
>>> from ding.utils import *
>>> lists_to_dicts([{1: 1, 10: 3}, {1: 2, 10: 4}])
dicts_to_lists(data)
¶
Overview
Transform a dict of lists to a list of dicts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
- data (
|
obj: |
required |
Returns:
| Type | Description |
|---|---|
List[Mapping[object, object]]
|
|
Example
from ding.utils import * dicts_to_lists({1: [1, 2], 10: [3, 4]}) [{1: 1, 10: 3}, {1: 2, 10: 4}]
override(cls)
¶
Overview
Annotation for documenting method overrides.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
- cls (
|
obj: |
required |
squeeze(data)
¶
Overview
Squeeze data from tuple, list or dict to single object
Arguments:
- data (:obj:object): data to be squeezed
Example:
>>> a = (4, )
>>> a = squeeze(a)
>>> print(a)
>>> 4
default_get(data, name, default_value=None, default_fn=None, judge_fn=None)
¶
Overview
Getting the value by input, checks generically on the inputs with at least data and name. If name exists in data, get the value at name; else, add name to default_get_set with value generated by default_fn (or directly as default_value) that is checked by judge_fn to be legal.
Arguments:
- data(:obj:dict): Data input dictionary
- name(:obj:str): Key name
- default_value(:obj:Optional[Any]) = None,
- default_fn(:obj:Optional[Callable]) = Value
- judge_fn(:obj:Optional[Callable]) = None
Returns:
- ret(:obj:list): Splitted data
- residual(:obj:list): Residule list
list_split(data, step)
¶
Overview
Split list of data by step.
Arguments:
- data(:obj:list): List of data for spliting
- step(:obj:int): Number of step for spliting
Returns:
- ret(:obj:list): List of splitted data.
- residual(:obj:list): Residule list. This value is None when data divides steps.
Example:
>>> list_split([1,2,3,4],2)
([[1, 2], [3, 4]], None)
>>> list_split([1,2,3,4],3)
([[1, 2, 3]], [4])
error_wrapper(fn, default_ret, warning_msg='')
¶
Overview
wrap the function, so that any Exception in the function will be catched and return the default_ret
Arguments:
- fn (:obj:Callable): the function to be wraped
- default_ret (:obj:obj): the default return when an Exception occurred in the function
Returns:
- wrapper (:obj:Callable): the wrapped function
Examples:
>>> # Used to checkfor Fakelink (Refer to utils.linklink_dist_helper.py)
>>> def get_rank(): # Get the rank of linklink model, return 0 if use FakeLink.
>>> if is_fake_link:
>>> return 0
>>> return error_wrapper(link.get_rank, 0)()
deep_merge_dicts(original, new_dict)
¶
Overview
Merge two dicts by calling deep_update
Arguments:
- original (:obj:dict): Dict 1.
- new_dict (:obj:dict): Dict 2.
Returns:
- merged_dict (:obj:dict): A new dict that is d1 and d2 deeply merged.
deep_update(original, new_dict, new_keys_allowed=False, whitelist=None, override_all_if_type_changes=None)
¶
Overview
Update original dict with values from new_dict recursively.
Arguments:
- original (:obj:dict): Dictionary with default values.
- new_dict (:obj:dict): Dictionary with values to be updated
- new_keys_allowed (:obj:bool): Whether new keys are allowed.
- whitelist (:obj:Optional[List[str]]):
List of keys that correspond to dict
values where new subkeys can be introduced. This is only at the top
level.
- override_all_if_type_changes(:obj:Optional[List[str]]):
List of top level
keys with value=dict, for which we always simply override the
entire value (:obj:dict), if the "type" key in that value dict changes.
.. note::
If new key is introduced in new_dict, then if new_keys_allowed is not
True, an error will be thrown. Further, for sub-dicts, if the key is
in the whitelist, then new subkeys can be introduced.
flatten_dict(data, delimiter='/')
¶
Overview
Flatten the dict, see example
Arguments:
- data (:obj:dict): Original nested dict
- delimiter (str): Delimiter of the keys of the new dict
Returns:
- data (:obj:dict): Flattened nested dict
Example:
>>> a
{'a': {'b': 100}}
>>> flatten_dict(a)
set_pkg_seed(seed, use_cuda=True)
¶
Overview
Side effect function to set seed for random, numpy random, and torch's manual seed. This is usaually used in entry scipt in the section of setting random seed for all package and instance
Argument:
- seed(:obj:int): Set seed
- use_cuda(:obj:bool) Whether use cude
Examples:
>>> # ../entry/xxxenv_xxxpolicy_main.py
>>> ...
# Set random seed for all package and instance
>>> collector_env.seed(seed)
>>> evaluator_env.seed(seed, dynamic_seed=False)
>>> set_pkg_seed(seed, use_cuda=cfg.policy.cuda)
>>> ...
# Set up RL Policy, etc.
>>> ...
one_time_warning(warning_msg)
cached
¶
Overview
Print warning message only once.
Arguments:
- warning_msg (:obj:str): Warning message.
split_fn(data, indices, start, end)
¶
Overview
Split data by indices
Arguments:
- data (:obj:Union[List, Dict, torch.Tensor, ttorch.Tensor]): data to be analysed
- indices (:obj:np.ndarray): indices to split
- start (:obj:int): start index
- end (:obj:int): end index
split_data_generator(data, split_size, shuffle=True)
¶
Overview
Split data into batches
Arguments:
- data (:obj:dict): data to be analysed
- split_size (:obj:int): split size
- shuffle (:obj:bool): whether shuffle
make_key_as_identifier(data)
¶
Overview
Make the key of dict into legal python identifier string so that it is
compatible with some python magic method such as __getattr.
Arguments:
- data (:obj:Dict[str, Any]): The original dict data.
Return:
- new_data (:obj:Dict[str, Any]): The new dict data with legal identifier keys.
remove_illegal_item(data)
¶
Overview
Remove illegal item in dict info, like str, which is not compatible with Tensor.
Arguments:
- data (:obj:Dict[str, Any]): The original dict data.
Return:
- new_data (:obj:Dict[str, Any]): The new dict data without legal items.
Full Source Code
../ding/utils/default_helper.py