repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
ray-project/ray
python/ray/utils.py
ensure_str
def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. To keep six with lower version, see Issue 4169, we copy this function from six == 1.12.0. TODO(yuhguo): remove this function when six >= 1.12.0. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if six.PY3: text_type = str binary_type = bytes else: text_type = unicode # noqa: F821 binary_type = str if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if six.PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif six.PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s
python
def ensure_str(s, encoding="utf-8", errors="strict"): """Coerce *s* to `str`. To keep six with lower version, see Issue 4169, we copy this function from six == 1.12.0. TODO(yuhguo): remove this function when six >= 1.12.0. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str` """ if six.PY3: text_type = str binary_type = bytes else: text_type = unicode # noqa: F821 binary_type = str if not isinstance(s, (text_type, binary_type)): raise TypeError("not expecting type '%s'" % type(s)) if six.PY2 and isinstance(s, text_type): s = s.encode(encoding, errors) elif six.PY3 and isinstance(s, binary_type): s = s.decode(encoding, errors) return s
[ "def", "ensure_str", "(", "s", ",", "encoding", "=", "\"utf-8\"", ",", "errors", "=", "\"strict\"", ")", ":", "if", "six", ".", "PY3", ":", "text_type", "=", "str", "binary_type", "=", "bytes", "else", ":", "text_type", "=", "unicode", "# noqa: F821", "binary_type", "=", "str", "if", "not", "isinstance", "(", "s", ",", "(", "text_type", ",", "binary_type", ")", ")", ":", "raise", "TypeError", "(", "\"not expecting type '%s'\"", "%", "type", "(", "s", ")", ")", "if", "six", ".", "PY2", "and", "isinstance", "(", "s", ",", "text_type", ")", ":", "s", "=", "s", ".", "encode", "(", "encoding", ",", "errors", ")", "elif", "six", ".", "PY3", "and", "isinstance", "(", "s", ",", "binary_type", ")", ":", "s", "=", "s", ".", "decode", "(", "encoding", ",", "errors", ")", "return", "s" ]
Coerce *s* to `str`. To keep six with lower version, see Issue 4169, we copy this function from six == 1.12.0. TODO(yuhguo): remove this function when six >= 1.12.0. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str`
[ "Coerce", "*", "s", "*", "to", "str", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L184-L212
train
ray-project/ray
python/ray/utils.py
get_cuda_visible_devices
def get_cuda_visible_devices(): """Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable. Returns: if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with the IDs of the GPUs. If it is not set, this returns None. """ gpu_ids_str = os.environ.get("CUDA_VISIBLE_DEVICES", None) if gpu_ids_str is None: return None if gpu_ids_str == "": return [] return [int(i) for i in gpu_ids_str.split(",")]
python
def get_cuda_visible_devices(): """Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable. Returns: if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with the IDs of the GPUs. If it is not set, this returns None. """ gpu_ids_str = os.environ.get("CUDA_VISIBLE_DEVICES", None) if gpu_ids_str is None: return None if gpu_ids_str == "": return [] return [int(i) for i in gpu_ids_str.split(",")]
[ "def", "get_cuda_visible_devices", "(", ")", ":", "gpu_ids_str", "=", "os", ".", "environ", ".", "get", "(", "\"CUDA_VISIBLE_DEVICES\"", ",", "None", ")", "if", "gpu_ids_str", "is", "None", ":", "return", "None", "if", "gpu_ids_str", "==", "\"\"", ":", "return", "[", "]", "return", "[", "int", "(", "i", ")", "for", "i", "in", "gpu_ids_str", ".", "split", "(", "\",\"", ")", "]" ]
Get the device IDs in the CUDA_VISIBLE_DEVICES environment variable. Returns: if CUDA_VISIBLE_DEVICES is set, this returns a list of integers with the IDs of the GPUs. If it is not set, this returns None.
[ "Get", "the", "device", "IDs", "in", "the", "CUDA_VISIBLE_DEVICES", "environment", "variable", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L230-L245
train
ray-project/ray
python/ray/utils.py
resources_from_resource_arguments
def resources_from_resource_arguments(default_num_cpus, default_num_gpus, default_resources, runtime_num_cpus, runtime_num_gpus, runtime_resources): """Determine a task's resource requirements. Args: default_num_cpus: The default number of CPUs required by this function or actor method. default_num_gpus: The default number of GPUs required by this function or actor method. default_resources: The default custom resources required by this function or actor method. runtime_num_cpus: The number of CPUs requested when the task was invoked. runtime_num_gpus: The number of GPUs requested when the task was invoked. runtime_resources: The custom resources requested when the task was invoked. Returns: A dictionary of the resource requirements for the task. """ if runtime_resources is not None: resources = runtime_resources.copy() elif default_resources is not None: resources = default_resources.copy() else: resources = {} if "CPU" in resources or "GPU" in resources: raise ValueError("The resources dictionary must not " "contain the key 'CPU' or 'GPU'") assert default_num_cpus is not None resources["CPU"] = (default_num_cpus if runtime_num_cpus is None else runtime_num_cpus) if runtime_num_gpus is not None: resources["GPU"] = runtime_num_gpus elif default_num_gpus is not None: resources["GPU"] = default_num_gpus return resources
python
def resources_from_resource_arguments(default_num_cpus, default_num_gpus, default_resources, runtime_num_cpus, runtime_num_gpus, runtime_resources): """Determine a task's resource requirements. Args: default_num_cpus: The default number of CPUs required by this function or actor method. default_num_gpus: The default number of GPUs required by this function or actor method. default_resources: The default custom resources required by this function or actor method. runtime_num_cpus: The number of CPUs requested when the task was invoked. runtime_num_gpus: The number of GPUs requested when the task was invoked. runtime_resources: The custom resources requested when the task was invoked. Returns: A dictionary of the resource requirements for the task. """ if runtime_resources is not None: resources = runtime_resources.copy() elif default_resources is not None: resources = default_resources.copy() else: resources = {} if "CPU" in resources or "GPU" in resources: raise ValueError("The resources dictionary must not " "contain the key 'CPU' or 'GPU'") assert default_num_cpus is not None resources["CPU"] = (default_num_cpus if runtime_num_cpus is None else runtime_num_cpus) if runtime_num_gpus is not None: resources["GPU"] = runtime_num_gpus elif default_num_gpus is not None: resources["GPU"] = default_num_gpus return resources
[ "def", "resources_from_resource_arguments", "(", "default_num_cpus", ",", "default_num_gpus", ",", "default_resources", ",", "runtime_num_cpus", ",", "runtime_num_gpus", ",", "runtime_resources", ")", ":", "if", "runtime_resources", "is", "not", "None", ":", "resources", "=", "runtime_resources", ".", "copy", "(", ")", "elif", "default_resources", "is", "not", "None", ":", "resources", "=", "default_resources", ".", "copy", "(", ")", "else", ":", "resources", "=", "{", "}", "if", "\"CPU\"", "in", "resources", "or", "\"GPU\"", "in", "resources", ":", "raise", "ValueError", "(", "\"The resources dictionary must not \"", "\"contain the key 'CPU' or 'GPU'\"", ")", "assert", "default_num_cpus", "is", "not", "None", "resources", "[", "\"CPU\"", "]", "=", "(", "default_num_cpus", "if", "runtime_num_cpus", "is", "None", "else", "runtime_num_cpus", ")", "if", "runtime_num_gpus", "is", "not", "None", ":", "resources", "[", "\"GPU\"", "]", "=", "runtime_num_gpus", "elif", "default_num_gpus", "is", "not", "None", ":", "resources", "[", "\"GPU\"", "]", "=", "default_num_gpus", "return", "resources" ]
Determine a task's resource requirements. Args: default_num_cpus: The default number of CPUs required by this function or actor method. default_num_gpus: The default number of GPUs required by this function or actor method. default_resources: The default custom resources required by this function or actor method. runtime_num_cpus: The number of CPUs requested when the task was invoked. runtime_num_gpus: The number of GPUs requested when the task was invoked. runtime_resources: The custom resources requested when the task was invoked. Returns: A dictionary of the resource requirements for the task.
[ "Determine", "a", "task", "s", "resource", "requirements", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L257-L299
train
ray-project/ray
python/ray/utils.py
setup_logger
def setup_logger(logging_level, logging_format): """Setup default logging for ray.""" logger = logging.getLogger("ray") if type(logging_level) is str: logging_level = logging.getLevelName(logging_level.upper()) logger.setLevel(logging_level) global _default_handler if _default_handler is None: _default_handler = logging.StreamHandler() logger.addHandler(_default_handler) _default_handler.setFormatter(logging.Formatter(logging_format)) logger.propagate = False
python
def setup_logger(logging_level, logging_format): """Setup default logging for ray.""" logger = logging.getLogger("ray") if type(logging_level) is str: logging_level = logging.getLevelName(logging_level.upper()) logger.setLevel(logging_level) global _default_handler if _default_handler is None: _default_handler = logging.StreamHandler() logger.addHandler(_default_handler) _default_handler.setFormatter(logging.Formatter(logging_format)) logger.propagate = False
[ "def", "setup_logger", "(", "logging_level", ",", "logging_format", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"ray\"", ")", "if", "type", "(", "logging_level", ")", "is", "str", ":", "logging_level", "=", "logging", ".", "getLevelName", "(", "logging_level", ".", "upper", "(", ")", ")", "logger", ".", "setLevel", "(", "logging_level", ")", "global", "_default_handler", "if", "_default_handler", "is", "None", ":", "_default_handler", "=", "logging", ".", "StreamHandler", "(", ")", "logger", ".", "addHandler", "(", "_default_handler", ")", "_default_handler", ".", "setFormatter", "(", "logging", ".", "Formatter", "(", "logging_format", ")", ")", "logger", ".", "propagate", "=", "False" ]
Setup default logging for ray.
[ "Setup", "default", "logging", "for", "ray", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L305-L316
train
ray-project/ray
python/ray/utils.py
vmstat
def vmstat(stat): """Run vmstat and get a particular statistic. Args: stat: The statistic that we are interested in retrieving. Returns: The parsed output. """ out = subprocess.check_output(["vmstat", "-s"]) stat = stat.encode("ascii") for line in out.split(b"\n"): line = line.strip() if stat in line: return int(line.split(b" ")[0]) raise ValueError("Can't find {} in 'vmstat' output.".format(stat))
python
def vmstat(stat): """Run vmstat and get a particular statistic. Args: stat: The statistic that we are interested in retrieving. Returns: The parsed output. """ out = subprocess.check_output(["vmstat", "-s"]) stat = stat.encode("ascii") for line in out.split(b"\n"): line = line.strip() if stat in line: return int(line.split(b" ")[0]) raise ValueError("Can't find {} in 'vmstat' output.".format(stat))
[ "def", "vmstat", "(", "stat", ")", ":", "out", "=", "subprocess", ".", "check_output", "(", "[", "\"vmstat\"", ",", "\"-s\"", "]", ")", "stat", "=", "stat", ".", "encode", "(", "\"ascii\"", ")", "for", "line", "in", "out", ".", "split", "(", "b\"\\n\"", ")", ":", "line", "=", "line", ".", "strip", "(", ")", "if", "stat", "in", "line", ":", "return", "int", "(", "line", ".", "split", "(", "b\" \"", ")", "[", "0", "]", ")", "raise", "ValueError", "(", "\"Can't find {} in 'vmstat' output.\"", ".", "format", "(", "stat", ")", ")" ]
Run vmstat and get a particular statistic. Args: stat: The statistic that we are interested in retrieving. Returns: The parsed output.
[ "Run", "vmstat", "and", "get", "a", "particular", "statistic", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L321-L336
train
ray-project/ray
python/ray/utils.py
sysctl
def sysctl(command): """Run a sysctl command and parse the output. Args: command: A sysctl command with an argument, for example, ["sysctl", "hw.memsize"]. Returns: The parsed output. """ out = subprocess.check_output(command) result = out.split(b" ")[1] try: return int(result) except ValueError: return result
python
def sysctl(command): """Run a sysctl command and parse the output. Args: command: A sysctl command with an argument, for example, ["sysctl", "hw.memsize"]. Returns: The parsed output. """ out = subprocess.check_output(command) result = out.split(b" ")[1] try: return int(result) except ValueError: return result
[ "def", "sysctl", "(", "command", ")", ":", "out", "=", "subprocess", ".", "check_output", "(", "command", ")", "result", "=", "out", ".", "split", "(", "b\" \"", ")", "[", "1", "]", "try", ":", "return", "int", "(", "result", ")", "except", "ValueError", ":", "return", "result" ]
Run a sysctl command and parse the output. Args: command: A sysctl command with an argument, for example, ["sysctl", "hw.memsize"]. Returns: The parsed output.
[ "Run", "a", "sysctl", "command", "and", "parse", "the", "output", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L341-L356
train
ray-project/ray
python/ray/utils.py
get_system_memory
def get_system_memory(): """Return the total amount of system memory in bytes. Returns: The total amount of system memory in bytes. """ # Try to accurately figure out the memory limit if we are in a docker # container. Note that this file is not specific to Docker and its value is # often much larger than the actual amount of memory. docker_limit = None memory_limit_filename = "/sys/fs/cgroup/memory/memory.limit_in_bytes" if os.path.exists(memory_limit_filename): with open(memory_limit_filename, "r") as f: docker_limit = int(f.read()) # Use psutil if it is available. psutil_memory_in_bytes = None try: import psutil psutil_memory_in_bytes = psutil.virtual_memory().total except ImportError: pass if psutil_memory_in_bytes is not None: memory_in_bytes = psutil_memory_in_bytes elif sys.platform == "linux" or sys.platform == "linux2": # Handle Linux. bytes_in_kilobyte = 1024 memory_in_bytes = vmstat("total memory") * bytes_in_kilobyte else: # Handle MacOS. memory_in_bytes = sysctl(["sysctl", "hw.memsize"]) if docker_limit is not None: return min(docker_limit, memory_in_bytes) else: return memory_in_bytes
python
def get_system_memory(): """Return the total amount of system memory in bytes. Returns: The total amount of system memory in bytes. """ # Try to accurately figure out the memory limit if we are in a docker # container. Note that this file is not specific to Docker and its value is # often much larger than the actual amount of memory. docker_limit = None memory_limit_filename = "/sys/fs/cgroup/memory/memory.limit_in_bytes" if os.path.exists(memory_limit_filename): with open(memory_limit_filename, "r") as f: docker_limit = int(f.read()) # Use psutil if it is available. psutil_memory_in_bytes = None try: import psutil psutil_memory_in_bytes = psutil.virtual_memory().total except ImportError: pass if psutil_memory_in_bytes is not None: memory_in_bytes = psutil_memory_in_bytes elif sys.platform == "linux" or sys.platform == "linux2": # Handle Linux. bytes_in_kilobyte = 1024 memory_in_bytes = vmstat("total memory") * bytes_in_kilobyte else: # Handle MacOS. memory_in_bytes = sysctl(["sysctl", "hw.memsize"]) if docker_limit is not None: return min(docker_limit, memory_in_bytes) else: return memory_in_bytes
[ "def", "get_system_memory", "(", ")", ":", "# Try to accurately figure out the memory limit if we are in a docker", "# container. Note that this file is not specific to Docker and its value is", "# often much larger than the actual amount of memory.", "docker_limit", "=", "None", "memory_limit_filename", "=", "\"/sys/fs/cgroup/memory/memory.limit_in_bytes\"", "if", "os", ".", "path", ".", "exists", "(", "memory_limit_filename", ")", ":", "with", "open", "(", "memory_limit_filename", ",", "\"r\"", ")", "as", "f", ":", "docker_limit", "=", "int", "(", "f", ".", "read", "(", ")", ")", "# Use psutil if it is available.", "psutil_memory_in_bytes", "=", "None", "try", ":", "import", "psutil", "psutil_memory_in_bytes", "=", "psutil", ".", "virtual_memory", "(", ")", ".", "total", "except", "ImportError", ":", "pass", "if", "psutil_memory_in_bytes", "is", "not", "None", ":", "memory_in_bytes", "=", "psutil_memory_in_bytes", "elif", "sys", ".", "platform", "==", "\"linux\"", "or", "sys", ".", "platform", "==", "\"linux2\"", ":", "# Handle Linux.", "bytes_in_kilobyte", "=", "1024", "memory_in_bytes", "=", "vmstat", "(", "\"total memory\"", ")", "*", "bytes_in_kilobyte", "else", ":", "# Handle MacOS.", "memory_in_bytes", "=", "sysctl", "(", "[", "\"sysctl\"", ",", "\"hw.memsize\"", "]", ")", "if", "docker_limit", "is", "not", "None", ":", "return", "min", "(", "docker_limit", ",", "memory_in_bytes", ")", "else", ":", "return", "memory_in_bytes" ]
Return the total amount of system memory in bytes. Returns: The total amount of system memory in bytes.
[ "Return", "the", "total", "amount", "of", "system", "memory", "in", "bytes", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L359-L395
train
ray-project/ray
python/ray/utils.py
get_shared_memory_bytes
def get_shared_memory_bytes(): """Get the size of the shared memory file system. Returns: The size of the shared memory file system in bytes. """ # Make sure this is only called on Linux. assert sys.platform == "linux" or sys.platform == "linux2" shm_fd = os.open("/dev/shm", os.O_RDONLY) try: shm_fs_stats = os.fstatvfs(shm_fd) # The value shm_fs_stats.f_bsize is the block size and the # value shm_fs_stats.f_bavail is the number of available # blocks. shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail finally: os.close(shm_fd) return shm_avail
python
def get_shared_memory_bytes(): """Get the size of the shared memory file system. Returns: The size of the shared memory file system in bytes. """ # Make sure this is only called on Linux. assert sys.platform == "linux" or sys.platform == "linux2" shm_fd = os.open("/dev/shm", os.O_RDONLY) try: shm_fs_stats = os.fstatvfs(shm_fd) # The value shm_fs_stats.f_bsize is the block size and the # value shm_fs_stats.f_bavail is the number of available # blocks. shm_avail = shm_fs_stats.f_bsize * shm_fs_stats.f_bavail finally: os.close(shm_fd) return shm_avail
[ "def", "get_shared_memory_bytes", "(", ")", ":", "# Make sure this is only called on Linux.", "assert", "sys", ".", "platform", "==", "\"linux\"", "or", "sys", ".", "platform", "==", "\"linux2\"", "shm_fd", "=", "os", ".", "open", "(", "\"/dev/shm\"", ",", "os", ".", "O_RDONLY", ")", "try", ":", "shm_fs_stats", "=", "os", ".", "fstatvfs", "(", "shm_fd", ")", "# The value shm_fs_stats.f_bsize is the block size and the", "# value shm_fs_stats.f_bavail is the number of available", "# blocks.", "shm_avail", "=", "shm_fs_stats", ".", "f_bsize", "*", "shm_fs_stats", ".", "f_bavail", "finally", ":", "os", ".", "close", "(", "shm_fd", ")", "return", "shm_avail" ]
Get the size of the shared memory file system. Returns: The size of the shared memory file system in bytes.
[ "Get", "the", "size", "of", "the", "shared", "memory", "file", "system", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L398-L417
train
ray-project/ray
python/ray/utils.py
check_oversized_pickle
def check_oversized_pickle(pickled, name, obj_type, worker): """Send a warning message if the pickled object is too large. Args: pickled: the pickled object. name: name of the pickled object. obj_type: type of the pickled object, can be 'function', 'remote function', 'actor', or 'object'. worker: the worker used to send warning message. """ length = len(pickled) if length <= ray_constants.PICKLE_OBJECT_WARNING_SIZE: return warning_message = ( "Warning: The {} {} has size {} when pickled. " "It will be stored in Redis, which could cause memory issues. " "This may mean that its definition uses a large array or other object." ).format(obj_type, name, length) push_error_to_driver( worker, ray_constants.PICKLING_LARGE_OBJECT_PUSH_ERROR, warning_message, driver_id=worker.task_driver_id)
python
def check_oversized_pickle(pickled, name, obj_type, worker): """Send a warning message if the pickled object is too large. Args: pickled: the pickled object. name: name of the pickled object. obj_type: type of the pickled object, can be 'function', 'remote function', 'actor', or 'object'. worker: the worker used to send warning message. """ length = len(pickled) if length <= ray_constants.PICKLE_OBJECT_WARNING_SIZE: return warning_message = ( "Warning: The {} {} has size {} when pickled. " "It will be stored in Redis, which could cause memory issues. " "This may mean that its definition uses a large array or other object." ).format(obj_type, name, length) push_error_to_driver( worker, ray_constants.PICKLING_LARGE_OBJECT_PUSH_ERROR, warning_message, driver_id=worker.task_driver_id)
[ "def", "check_oversized_pickle", "(", "pickled", ",", "name", ",", "obj_type", ",", "worker", ")", ":", "length", "=", "len", "(", "pickled", ")", "if", "length", "<=", "ray_constants", ".", "PICKLE_OBJECT_WARNING_SIZE", ":", "return", "warning_message", "=", "(", "\"Warning: The {} {} has size {} when pickled. \"", "\"It will be stored in Redis, which could cause memory issues. \"", "\"This may mean that its definition uses a large array or other object.\"", ")", ".", "format", "(", "obj_type", ",", "name", ",", "length", ")", "push_error_to_driver", "(", "worker", ",", "ray_constants", ".", "PICKLING_LARGE_OBJECT_PUSH_ERROR", ",", "warning_message", ",", "driver_id", "=", "worker", ".", "task_driver_id", ")" ]
Send a warning message if the pickled object is too large. Args: pickled: the pickled object. name: name of the pickled object. obj_type: type of the pickled object, can be 'function', 'remote function', 'actor', or 'object'. worker: the worker used to send warning message.
[ "Send", "a", "warning", "message", "if", "the", "pickled", "object", "is", "too", "large", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L420-L442
train
ray-project/ray
python/ray/utils.py
thread_safe_client
def thread_safe_client(client, lock=None): """Create a thread-safe proxy which locks every method call for the given client. Args: client: the client object to be guarded. lock: the lock object that will be used to lock client's methods. If None, a new lock will be used. Returns: A thread-safe proxy for the given client. """ if lock is None: lock = threading.Lock() return _ThreadSafeProxy(client, lock)
python
def thread_safe_client(client, lock=None): """Create a thread-safe proxy which locks every method call for the given client. Args: client: the client object to be guarded. lock: the lock object that will be used to lock client's methods. If None, a new lock will be used. Returns: A thread-safe proxy for the given client. """ if lock is None: lock = threading.Lock() return _ThreadSafeProxy(client, lock)
[ "def", "thread_safe_client", "(", "client", ",", "lock", "=", "None", ")", ":", "if", "lock", "is", "None", ":", "lock", "=", "threading", ".", "Lock", "(", ")", "return", "_ThreadSafeProxy", "(", "client", ",", "lock", ")" ]
Create a thread-safe proxy which locks every method call for the given client. Args: client: the client object to be guarded. lock: the lock object that will be used to lock client's methods. If None, a new lock will be used. Returns: A thread-safe proxy for the given client.
[ "Create", "a", "thread", "-", "safe", "proxy", "which", "locks", "every", "method", "call", "for", "the", "given", "client", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L482-L496
train
ray-project/ray
python/ray/utils.py
try_to_create_directory
def try_to_create_directory(directory_path): """Attempt to create a directory that is globally readable/writable. Args: directory_path: The path of the directory to create. """ logger = logging.getLogger("ray") directory_path = os.path.expanduser(directory_path) if not os.path.exists(directory_path): try: os.makedirs(directory_path) except OSError as e: if e.errno != errno.EEXIST: raise e logger.warning( "Attempted to create '{}', but the directory already " "exists.".format(directory_path)) # Change the log directory permissions so others can use it. This is # important when multiple people are using the same machine. try: os.chmod(directory_path, 0o0777) except OSError as e: # Silently suppress the PermissionError that is thrown by the chmod. # This is done because the user attempting to change the permissions # on a directory may not own it. The chmod is attempted whether the # directory is new or not to avoid race conditions. # ray-project/ray/#3591 if e.errno in [errno.EACCES, errno.EPERM]: pass else: raise
python
def try_to_create_directory(directory_path): """Attempt to create a directory that is globally readable/writable. Args: directory_path: The path of the directory to create. """ logger = logging.getLogger("ray") directory_path = os.path.expanduser(directory_path) if not os.path.exists(directory_path): try: os.makedirs(directory_path) except OSError as e: if e.errno != errno.EEXIST: raise e logger.warning( "Attempted to create '{}', but the directory already " "exists.".format(directory_path)) # Change the log directory permissions so others can use it. This is # important when multiple people are using the same machine. try: os.chmod(directory_path, 0o0777) except OSError as e: # Silently suppress the PermissionError that is thrown by the chmod. # This is done because the user attempting to change the permissions # on a directory may not own it. The chmod is attempted whether the # directory is new or not to avoid race conditions. # ray-project/ray/#3591 if e.errno in [errno.EACCES, errno.EPERM]: pass else: raise
[ "def", "try_to_create_directory", "(", "directory_path", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"ray\"", ")", "directory_path", "=", "os", ".", "path", ".", "expanduser", "(", "directory_path", ")", "if", "not", "os", ".", "path", ".", "exists", "(", "directory_path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "directory_path", ")", "except", "OSError", "as", "e", ":", "if", "e", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "e", "logger", ".", "warning", "(", "\"Attempted to create '{}', but the directory already \"", "\"exists.\"", ".", "format", "(", "directory_path", ")", ")", "# Change the log directory permissions so others can use it. This is", "# important when multiple people are using the same machine.", "try", ":", "os", ".", "chmod", "(", "directory_path", ",", "0o0777", ")", "except", "OSError", "as", "e", ":", "# Silently suppress the PermissionError that is thrown by the chmod.", "# This is done because the user attempting to change the permissions", "# on a directory may not own it. The chmod is attempted whether the", "# directory is new or not to avoid race conditions.", "# ray-project/ray/#3591", "if", "e", ".", "errno", "in", "[", "errno", ".", "EACCES", ",", "errno", ".", "EPERM", "]", ":", "pass", "else", ":", "raise" ]
Attempt to create a directory that is globally readable/writable. Args: directory_path: The path of the directory to create.
[ "Attempt", "to", "create", "a", "directory", "that", "is", "globally", "readable", "/", "writable", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/utils.py#L503-L533
train
ray-project/ray
python/ray/experimental/array/distributed/core.py
subblocks
def subblocks(a, *ranges): """ This function produces a distributed array from a subset of the blocks in the `a`. The result and `a` will have the same number of dimensions. For example, subblocks(a, [0, 1], [2, 4]) will produce a DistArray whose objectids are [[a.objectids[0, 2], a.objectids[0, 4]], [a.objectids[1, 2], a.objectids[1, 4]]] We allow the user to pass in an empty list [] to indicate the full range. """ ranges = list(ranges) if len(ranges) != a.ndim: raise Exception("sub_blocks expects to receive a number of ranges " "equal to a.ndim, but it received {} ranges and " "a.ndim = {}.".format(len(ranges), a.ndim)) for i in range(len(ranges)): # We allow the user to pass in an empty list to indicate the full # range. if ranges[i] == []: ranges[i] = range(a.num_blocks[i]) if not np.alltrue(ranges[i] == np.sort(ranges[i])): raise Exception("Ranges passed to sub_blocks must be sorted, but " "the {}th range is {}.".format(i, ranges[i])) if ranges[i][0] < 0: raise Exception("Values in the ranges passed to sub_blocks must " "be at least 0, but the {}th range is {}.".format( i, ranges[i])) if ranges[i][-1] >= a.num_blocks[i]: raise Exception("Values in the ranges passed to sub_blocks must " "be less than the relevant number of blocks, but " "the {}th range is {}, and a.num_blocks = {}." .format(i, ranges[i], a.num_blocks)) last_index = [r[-1] for r in ranges] last_block_shape = DistArray.compute_block_shape(last_index, a.shape) shape = [(len(ranges[i]) - 1) * BLOCK_SIZE + last_block_shape[i] for i in range(a.ndim)] result = DistArray(shape) for index in np.ndindex(*result.num_blocks): result.objectids[index] = a.objectids[tuple( ranges[i][index[i]] for i in range(a.ndim))] return result
python
def subblocks(a, *ranges): """ This function produces a distributed array from a subset of the blocks in the `a`. The result and `a` will have the same number of dimensions. For example, subblocks(a, [0, 1], [2, 4]) will produce a DistArray whose objectids are [[a.objectids[0, 2], a.objectids[0, 4]], [a.objectids[1, 2], a.objectids[1, 4]]] We allow the user to pass in an empty list [] to indicate the full range. """ ranges = list(ranges) if len(ranges) != a.ndim: raise Exception("sub_blocks expects to receive a number of ranges " "equal to a.ndim, but it received {} ranges and " "a.ndim = {}.".format(len(ranges), a.ndim)) for i in range(len(ranges)): # We allow the user to pass in an empty list to indicate the full # range. if ranges[i] == []: ranges[i] = range(a.num_blocks[i]) if not np.alltrue(ranges[i] == np.sort(ranges[i])): raise Exception("Ranges passed to sub_blocks must be sorted, but " "the {}th range is {}.".format(i, ranges[i])) if ranges[i][0] < 0: raise Exception("Values in the ranges passed to sub_blocks must " "be at least 0, but the {}th range is {}.".format( i, ranges[i])) if ranges[i][-1] >= a.num_blocks[i]: raise Exception("Values in the ranges passed to sub_blocks must " "be less than the relevant number of blocks, but " "the {}th range is {}, and a.num_blocks = {}." .format(i, ranges[i], a.num_blocks)) last_index = [r[-1] for r in ranges] last_block_shape = DistArray.compute_block_shape(last_index, a.shape) shape = [(len(ranges[i]) - 1) * BLOCK_SIZE + last_block_shape[i] for i in range(a.ndim)] result = DistArray(shape) for index in np.ndindex(*result.num_blocks): result.objectids[index] = a.objectids[tuple( ranges[i][index[i]] for i in range(a.ndim))] return result
[ "def", "subblocks", "(", "a", ",", "*", "ranges", ")", ":", "ranges", "=", "list", "(", "ranges", ")", "if", "len", "(", "ranges", ")", "!=", "a", ".", "ndim", ":", "raise", "Exception", "(", "\"sub_blocks expects to receive a number of ranges \"", "\"equal to a.ndim, but it received {} ranges and \"", "\"a.ndim = {}.\"", ".", "format", "(", "len", "(", "ranges", ")", ",", "a", ".", "ndim", ")", ")", "for", "i", "in", "range", "(", "len", "(", "ranges", ")", ")", ":", "# We allow the user to pass in an empty list to indicate the full", "# range.", "if", "ranges", "[", "i", "]", "==", "[", "]", ":", "ranges", "[", "i", "]", "=", "range", "(", "a", ".", "num_blocks", "[", "i", "]", ")", "if", "not", "np", ".", "alltrue", "(", "ranges", "[", "i", "]", "==", "np", ".", "sort", "(", "ranges", "[", "i", "]", ")", ")", ":", "raise", "Exception", "(", "\"Ranges passed to sub_blocks must be sorted, but \"", "\"the {}th range is {}.\"", ".", "format", "(", "i", ",", "ranges", "[", "i", "]", ")", ")", "if", "ranges", "[", "i", "]", "[", "0", "]", "<", "0", ":", "raise", "Exception", "(", "\"Values in the ranges passed to sub_blocks must \"", "\"be at least 0, but the {}th range is {}.\"", ".", "format", "(", "i", ",", "ranges", "[", "i", "]", ")", ")", "if", "ranges", "[", "i", "]", "[", "-", "1", "]", ">=", "a", ".", "num_blocks", "[", "i", "]", ":", "raise", "Exception", "(", "\"Values in the ranges passed to sub_blocks must \"", "\"be less than the relevant number of blocks, but \"", "\"the {}th range is {}, and a.num_blocks = {}.\"", ".", "format", "(", "i", ",", "ranges", "[", "i", "]", ",", "a", ".", "num_blocks", ")", ")", "last_index", "=", "[", "r", "[", "-", "1", "]", "for", "r", "in", "ranges", "]", "last_block_shape", "=", "DistArray", ".", "compute_block_shape", "(", "last_index", ",", "a", ".", "shape", ")", "shape", "=", "[", "(", "len", "(", "ranges", "[", "i", "]", ")", "-", "1", ")", "*", "BLOCK_SIZE", "+", "last_block_shape", "[", "i", "]", "for", "i", "in", "range", "(", "a", ".", "ndim", ")", "]", "result", "=", "DistArray", "(", "shape", ")", "for", "index", "in", "np", ".", "ndindex", "(", "*", "result", ".", "num_blocks", ")", ":", "result", ".", "objectids", "[", "index", "]", "=", "a", ".", "objectids", "[", "tuple", "(", "ranges", "[", "i", "]", "[", "index", "[", "i", "]", "]", "for", "i", "in", "range", "(", "a", ".", "ndim", ")", ")", "]", "return", "result" ]
This function produces a distributed array from a subset of the blocks in the `a`. The result and `a` will have the same number of dimensions. For example, subblocks(a, [0, 1], [2, 4]) will produce a DistArray whose objectids are [[a.objectids[0, 2], a.objectids[0, 4]], [a.objectids[1, 2], a.objectids[1, 4]]] We allow the user to pass in an empty list [] to indicate the full range.
[ "This", "function", "produces", "a", "distributed", "array", "from", "a", "subset", "of", "the", "blocks", "in", "the", "a", ".", "The", "result", "and", "a", "will", "have", "the", "same", "number", "of", "dimensions", ".", "For", "example", "subblocks", "(", "a", "[", "0", "1", "]", "[", "2", "4", "]", ")", "will", "produce", "a", "DistArray", "whose", "objectids", "are", "[[", "a", ".", "objectids", "[", "0", "2", "]", "a", ".", "objectids", "[", "0", "4", "]]", "[", "a", ".", "objectids", "[", "1", "2", "]", "a", ".", "objectids", "[", "1", "4", "]]]", "We", "allow", "the", "user", "to", "pass", "in", "an", "empty", "list", "[]", "to", "indicate", "the", "full", "range", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/core.py#L204-L245
train
ray-project/ray
python/ray/experimental/array/distributed/core.py
DistArray.assemble
def assemble(self): """Assemble an array from a distributed array of object IDs.""" first_block = ray.get(self.objectids[(0, ) * self.ndim]) dtype = first_block.dtype result = np.zeros(self.shape, dtype=dtype) for index in np.ndindex(*self.num_blocks): lower = DistArray.compute_block_lower(index, self.shape) upper = DistArray.compute_block_upper(index, self.shape) result[[slice(l, u) for (l, u) in zip(lower, upper)]] = ray.get( self.objectids[index]) return result
python
def assemble(self): """Assemble an array from a distributed array of object IDs.""" first_block = ray.get(self.objectids[(0, ) * self.ndim]) dtype = first_block.dtype result = np.zeros(self.shape, dtype=dtype) for index in np.ndindex(*self.num_blocks): lower = DistArray.compute_block_lower(index, self.shape) upper = DistArray.compute_block_upper(index, self.shape) result[[slice(l, u) for (l, u) in zip(lower, upper)]] = ray.get( self.objectids[index]) return result
[ "def", "assemble", "(", "self", ")", ":", "first_block", "=", "ray", ".", "get", "(", "self", ".", "objectids", "[", "(", "0", ",", ")", "*", "self", ".", "ndim", "]", ")", "dtype", "=", "first_block", ".", "dtype", "result", "=", "np", ".", "zeros", "(", "self", ".", "shape", ",", "dtype", "=", "dtype", ")", "for", "index", "in", "np", ".", "ndindex", "(", "*", "self", ".", "num_blocks", ")", ":", "lower", "=", "DistArray", ".", "compute_block_lower", "(", "index", ",", "self", ".", "shape", ")", "upper", "=", "DistArray", ".", "compute_block_upper", "(", "index", ",", "self", ".", "shape", ")", "result", "[", "[", "slice", "(", "l", ",", "u", ")", "for", "(", "l", ",", "u", ")", "in", "zip", "(", "lower", ",", "upper", ")", "]", "]", "=", "ray", ".", "get", "(", "self", ".", "objectids", "[", "index", "]", ")", "return", "result" ]
Assemble an array from a distributed array of object IDs.
[ "Assemble", "an", "array", "from", "a", "distributed", "array", "of", "object", "IDs", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/core.py#L58-L68
train
ray-project/ray
python/ray/rllib/agents/impala/vtrace.py
multi_log_probs_from_logits_and_actions
def multi_log_probs_from_logits_and_actions(policy_logits, actions): """Computes action log-probs from policy logits and actions. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size and ACTION_SPACE refers to the list of numbers each representing a number of actions. Args: policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing a softmax policy. actions: A list with length of ACTION_SPACE of int32 tensors of shapes [T, B], ..., [T, B] with actions. Returns: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B], ..., [T, B] corresponding to the sampling log probability of the chosen action w.r.t. the policy. """ log_probs = [] for i in range(len(policy_logits)): log_probs.append(-tf.nn.sparse_softmax_cross_entropy_with_logits( logits=policy_logits[i], labels=actions[i])) return log_probs
python
def multi_log_probs_from_logits_and_actions(policy_logits, actions): """Computes action log-probs from policy logits and actions. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size and ACTION_SPACE refers to the list of numbers each representing a number of actions. Args: policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing a softmax policy. actions: A list with length of ACTION_SPACE of int32 tensors of shapes [T, B], ..., [T, B] with actions. Returns: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B], ..., [T, B] corresponding to the sampling log probability of the chosen action w.r.t. the policy. """ log_probs = [] for i in range(len(policy_logits)): log_probs.append(-tf.nn.sparse_softmax_cross_entropy_with_logits( logits=policy_logits[i], labels=actions[i])) return log_probs
[ "def", "multi_log_probs_from_logits_and_actions", "(", "policy_logits", ",", "actions", ")", ":", "log_probs", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "policy_logits", ")", ")", ":", "log_probs", ".", "append", "(", "-", "tf", ".", "nn", ".", "sparse_softmax_cross_entropy_with_logits", "(", "logits", "=", "policy_logits", "[", "i", "]", ",", "labels", "=", "actions", "[", "i", "]", ")", ")", "return", "log_probs" ]
Computes action log-probs from policy logits and actions. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size and ACTION_SPACE refers to the list of numbers each representing a number of actions. Args: policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing a softmax policy. actions: A list with length of ACTION_SPACE of int32 tensors of shapes [T, B], ..., [T, B] with actions. Returns: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B], ..., [T, B] corresponding to the sampling log probability of the chosen action w.r.t. the policy.
[ "Computes", "action", "log", "-", "probs", "from", "policy", "logits", "and", "actions", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/impala/vtrace.py#L54-L91
train
ray-project/ray
python/ray/rllib/agents/impala/vtrace.py
from_logits
def from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, name="vtrace_from_logits"): """multi_from_logits wrapper used only for tests""" res = multi_from_logits( [behaviour_policy_logits], [target_policy_logits], [actions], discounts, rewards, values, bootstrap_value, clip_rho_threshold=clip_rho_threshold, clip_pg_rho_threshold=clip_pg_rho_threshold, name=name) return VTraceFromLogitsReturns( vs=res.vs, pg_advantages=res.pg_advantages, log_rhos=res.log_rhos, behaviour_action_log_probs=tf.squeeze( res.behaviour_action_log_probs, axis=0), target_action_log_probs=tf.squeeze( res.target_action_log_probs, axis=0), )
python
def from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, name="vtrace_from_logits"): """multi_from_logits wrapper used only for tests""" res = multi_from_logits( [behaviour_policy_logits], [target_policy_logits], [actions], discounts, rewards, values, bootstrap_value, clip_rho_threshold=clip_rho_threshold, clip_pg_rho_threshold=clip_pg_rho_threshold, name=name) return VTraceFromLogitsReturns( vs=res.vs, pg_advantages=res.pg_advantages, log_rhos=res.log_rhos, behaviour_action_log_probs=tf.squeeze( res.behaviour_action_log_probs, axis=0), target_action_log_probs=tf.squeeze( res.target_action_log_probs, axis=0), )
[ "def", "from_logits", "(", "behaviour_policy_logits", ",", "target_policy_logits", ",", "actions", ",", "discounts", ",", "rewards", ",", "values", ",", "bootstrap_value", ",", "clip_rho_threshold", "=", "1.0", ",", "clip_pg_rho_threshold", "=", "1.0", ",", "name", "=", "\"vtrace_from_logits\"", ")", ":", "res", "=", "multi_from_logits", "(", "[", "behaviour_policy_logits", "]", ",", "[", "target_policy_logits", "]", ",", "[", "actions", "]", ",", "discounts", ",", "rewards", ",", "values", ",", "bootstrap_value", ",", "clip_rho_threshold", "=", "clip_rho_threshold", ",", "clip_pg_rho_threshold", "=", "clip_pg_rho_threshold", ",", "name", "=", "name", ")", "return", "VTraceFromLogitsReturns", "(", "vs", "=", "res", ".", "vs", ",", "pg_advantages", "=", "res", ".", "pg_advantages", ",", "log_rhos", "=", "res", ".", "log_rhos", ",", "behaviour_action_log_probs", "=", "tf", ".", "squeeze", "(", "res", ".", "behaviour_action_log_probs", ",", "axis", "=", "0", ")", ",", "target_action_log_probs", "=", "tf", ".", "squeeze", "(", "res", ".", "target_action_log_probs", ",", "axis", "=", "0", ")", ",", ")" ]
multi_from_logits wrapper used only for tests
[ "multi_from_logits", "wrapper", "used", "only", "for", "tests" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/impala/vtrace.py#L94-L124
train
ray-project/ray
python/ray/rllib/agents/impala/vtrace.py
multi_from_logits
def multi_from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, name="vtrace_from_logits"): r"""V-trace for softmax policies. Calculates V-trace actor critic targets for softmax polices as described in "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures" by Espeholt, Soyer, Munos et al. Target policy refers to the policy we are interested in improving and behaviour policy refers to the policy that generated the given rewards and actions. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size and ACTION_SPACE refers to the list of numbers each representing a number of actions. Args: behaviour_policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing the softmax behaviour policy. target_policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing the softmax target policy. actions: A list with length of ACTION_SPACE of int32 tensors of shapes [T, B], ..., [T, B] with actions sampled from the behaviour policy. discounts: A float32 tensor of shape [T, B] with the discount encountered when following the behaviour policy. rewards: A float32 tensor of shape [T, B] with the rewards generated by following the behaviour policy. values: A float32 tensor of shape [T, B] with the value function estimates wrt. the target policy. bootstrap_value: A float32 of shape [B] with the value function estimate at time T. clip_rho_threshold: A scalar float32 tensor with the clipping threshold for importance weights (rho) when calculating the baseline targets (vs). rho^bar in the paper. clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). name: The name scope that all V-trace operations will be created in. Returns: A `VTraceFromLogitsReturns` namedtuple with the following fields: vs: A float32 tensor of shape [T, B]. Can be used as target to train a baseline (V(x_t) - vs_t)^2. pg_advantages: A float 32 tensor of shape [T, B]. Can be used as an estimate of the advantage in the calculation of policy gradients. log_rhos: A float32 tensor of shape [T, B] containing the log importance sampling weights (log rhos). behaviour_action_log_probs: A float32 tensor of shape [T, B] containing behaviour policy action log probabilities (log \mu(a_t)). target_action_log_probs: A float32 tensor of shape [T, B] containing target policy action probabilities (log \pi(a_t)). """ for i in range(len(behaviour_policy_logits)): behaviour_policy_logits[i] = tf.convert_to_tensor( behaviour_policy_logits[i], dtype=tf.float32) target_policy_logits[i] = tf.convert_to_tensor( target_policy_logits[i], dtype=tf.float32) actions[i] = tf.convert_to_tensor(actions[i], dtype=tf.int32) # Make sure tensor ranks are as expected. # The rest will be checked by from_action_log_probs. behaviour_policy_logits[i].shape.assert_has_rank(3) target_policy_logits[i].shape.assert_has_rank(3) actions[i].shape.assert_has_rank(2) with tf.name_scope( name, values=[ behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value ]): target_action_log_probs = multi_log_probs_from_logits_and_actions( target_policy_logits, actions) behaviour_action_log_probs = multi_log_probs_from_logits_and_actions( behaviour_policy_logits, actions) log_rhos = get_log_rhos(target_action_log_probs, behaviour_action_log_probs) vtrace_returns = from_importance_weights( log_rhos=log_rhos, discounts=discounts, rewards=rewards, values=values, bootstrap_value=bootstrap_value, clip_rho_threshold=clip_rho_threshold, clip_pg_rho_threshold=clip_pg_rho_threshold) return VTraceFromLogitsReturns( log_rhos=log_rhos, behaviour_action_log_probs=behaviour_action_log_probs, target_action_log_probs=target_action_log_probs, **vtrace_returns._asdict())
python
def multi_from_logits(behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, name="vtrace_from_logits"): r"""V-trace for softmax policies. Calculates V-trace actor critic targets for softmax polices as described in "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures" by Espeholt, Soyer, Munos et al. Target policy refers to the policy we are interested in improving and behaviour policy refers to the policy that generated the given rewards and actions. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size and ACTION_SPACE refers to the list of numbers each representing a number of actions. Args: behaviour_policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing the softmax behaviour policy. target_policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing the softmax target policy. actions: A list with length of ACTION_SPACE of int32 tensors of shapes [T, B], ..., [T, B] with actions sampled from the behaviour policy. discounts: A float32 tensor of shape [T, B] with the discount encountered when following the behaviour policy. rewards: A float32 tensor of shape [T, B] with the rewards generated by following the behaviour policy. values: A float32 tensor of shape [T, B] with the value function estimates wrt. the target policy. bootstrap_value: A float32 of shape [B] with the value function estimate at time T. clip_rho_threshold: A scalar float32 tensor with the clipping threshold for importance weights (rho) when calculating the baseline targets (vs). rho^bar in the paper. clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). name: The name scope that all V-trace operations will be created in. Returns: A `VTraceFromLogitsReturns` namedtuple with the following fields: vs: A float32 tensor of shape [T, B]. Can be used as target to train a baseline (V(x_t) - vs_t)^2. pg_advantages: A float 32 tensor of shape [T, B]. Can be used as an estimate of the advantage in the calculation of policy gradients. log_rhos: A float32 tensor of shape [T, B] containing the log importance sampling weights (log rhos). behaviour_action_log_probs: A float32 tensor of shape [T, B] containing behaviour policy action log probabilities (log \mu(a_t)). target_action_log_probs: A float32 tensor of shape [T, B] containing target policy action probabilities (log \pi(a_t)). """ for i in range(len(behaviour_policy_logits)): behaviour_policy_logits[i] = tf.convert_to_tensor( behaviour_policy_logits[i], dtype=tf.float32) target_policy_logits[i] = tf.convert_to_tensor( target_policy_logits[i], dtype=tf.float32) actions[i] = tf.convert_to_tensor(actions[i], dtype=tf.int32) # Make sure tensor ranks are as expected. # The rest will be checked by from_action_log_probs. behaviour_policy_logits[i].shape.assert_has_rank(3) target_policy_logits[i].shape.assert_has_rank(3) actions[i].shape.assert_has_rank(2) with tf.name_scope( name, values=[ behaviour_policy_logits, target_policy_logits, actions, discounts, rewards, values, bootstrap_value ]): target_action_log_probs = multi_log_probs_from_logits_and_actions( target_policy_logits, actions) behaviour_action_log_probs = multi_log_probs_from_logits_and_actions( behaviour_policy_logits, actions) log_rhos = get_log_rhos(target_action_log_probs, behaviour_action_log_probs) vtrace_returns = from_importance_weights( log_rhos=log_rhos, discounts=discounts, rewards=rewards, values=values, bootstrap_value=bootstrap_value, clip_rho_threshold=clip_rho_threshold, clip_pg_rho_threshold=clip_pg_rho_threshold) return VTraceFromLogitsReturns( log_rhos=log_rhos, behaviour_action_log_probs=behaviour_action_log_probs, target_action_log_probs=target_action_log_probs, **vtrace_returns._asdict())
[ "def", "multi_from_logits", "(", "behaviour_policy_logits", ",", "target_policy_logits", ",", "actions", ",", "discounts", ",", "rewards", ",", "values", ",", "bootstrap_value", ",", "clip_rho_threshold", "=", "1.0", ",", "clip_pg_rho_threshold", "=", "1.0", ",", "name", "=", "\"vtrace_from_logits\"", ")", ":", "for", "i", "in", "range", "(", "len", "(", "behaviour_policy_logits", ")", ")", ":", "behaviour_policy_logits", "[", "i", "]", "=", "tf", ".", "convert_to_tensor", "(", "behaviour_policy_logits", "[", "i", "]", ",", "dtype", "=", "tf", ".", "float32", ")", "target_policy_logits", "[", "i", "]", "=", "tf", ".", "convert_to_tensor", "(", "target_policy_logits", "[", "i", "]", ",", "dtype", "=", "tf", ".", "float32", ")", "actions", "[", "i", "]", "=", "tf", ".", "convert_to_tensor", "(", "actions", "[", "i", "]", ",", "dtype", "=", "tf", ".", "int32", ")", "# Make sure tensor ranks are as expected.", "# The rest will be checked by from_action_log_probs.", "behaviour_policy_logits", "[", "i", "]", ".", "shape", ".", "assert_has_rank", "(", "3", ")", "target_policy_logits", "[", "i", "]", ".", "shape", ".", "assert_has_rank", "(", "3", ")", "actions", "[", "i", "]", ".", "shape", ".", "assert_has_rank", "(", "2", ")", "with", "tf", ".", "name_scope", "(", "name", ",", "values", "=", "[", "behaviour_policy_logits", ",", "target_policy_logits", ",", "actions", ",", "discounts", ",", "rewards", ",", "values", ",", "bootstrap_value", "]", ")", ":", "target_action_log_probs", "=", "multi_log_probs_from_logits_and_actions", "(", "target_policy_logits", ",", "actions", ")", "behaviour_action_log_probs", "=", "multi_log_probs_from_logits_and_actions", "(", "behaviour_policy_logits", ",", "actions", ")", "log_rhos", "=", "get_log_rhos", "(", "target_action_log_probs", ",", "behaviour_action_log_probs", ")", "vtrace_returns", "=", "from_importance_weights", "(", "log_rhos", "=", "log_rhos", ",", "discounts", "=", "discounts", ",", "rewards", "=", "rewards", ",", "values", "=", "values", ",", "bootstrap_value", "=", "bootstrap_value", ",", "clip_rho_threshold", "=", "clip_rho_threshold", ",", "clip_pg_rho_threshold", "=", "clip_pg_rho_threshold", ")", "return", "VTraceFromLogitsReturns", "(", "log_rhos", "=", "log_rhos", ",", "behaviour_action_log_probs", "=", "behaviour_action_log_probs", ",", "target_action_log_probs", "=", "target_action_log_probs", ",", "*", "*", "vtrace_returns", ".", "_asdict", "(", ")", ")" ]
r"""V-trace for softmax policies. Calculates V-trace actor critic targets for softmax polices as described in "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures" by Espeholt, Soyer, Munos et al. Target policy refers to the policy we are interested in improving and behaviour policy refers to the policy that generated the given rewards and actions. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size and ACTION_SPACE refers to the list of numbers each representing a number of actions. Args: behaviour_policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing the softmax behaviour policy. target_policy_logits: A list with length of ACTION_SPACE of float32 tensors of shapes [T, B, ACTION_SPACE[0]], ..., [T, B, ACTION_SPACE[-1]] with un-normalized log-probabilities parameterizing the softmax target policy. actions: A list with length of ACTION_SPACE of int32 tensors of shapes [T, B], ..., [T, B] with actions sampled from the behaviour policy. discounts: A float32 tensor of shape [T, B] with the discount encountered when following the behaviour policy. rewards: A float32 tensor of shape [T, B] with the rewards generated by following the behaviour policy. values: A float32 tensor of shape [T, B] with the value function estimates wrt. the target policy. bootstrap_value: A float32 of shape [B] with the value function estimate at time T. clip_rho_threshold: A scalar float32 tensor with the clipping threshold for importance weights (rho) when calculating the baseline targets (vs). rho^bar in the paper. clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). name: The name scope that all V-trace operations will be created in. Returns: A `VTraceFromLogitsReturns` namedtuple with the following fields: vs: A float32 tensor of shape [T, B]. Can be used as target to train a baseline (V(x_t) - vs_t)^2. pg_advantages: A float 32 tensor of shape [T, B]. Can be used as an estimate of the advantage in the calculation of policy gradients. log_rhos: A float32 tensor of shape [T, B] containing the log importance sampling weights (log rhos). behaviour_action_log_probs: A float32 tensor of shape [T, B] containing behaviour policy action log probabilities (log \mu(a_t)). target_action_log_probs: A float32 tensor of shape [T, B] containing target policy action probabilities (log \pi(a_t)).
[ "r", "V", "-", "trace", "for", "softmax", "policies", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/impala/vtrace.py#L127-L244
train
ray-project/ray
python/ray/rllib/agents/impala/vtrace.py
from_importance_weights
def from_importance_weights(log_rhos, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, name="vtrace_from_importance_weights"): r"""V-trace from log importance weights. Calculates V-trace actor critic targets as described in "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures" by Espeholt, Soyer, Munos et al. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size. This code also supports the case where all tensors have the same number of additional dimensions, e.g., `rewards` is [T, B, C], `values` is [T, B, C], `bootstrap_value` is [B, C]. Args: log_rhos: A float32 tensor of shape [T, B] representing the log importance sampling weights, i.e. log(target_policy(a) / behaviour_policy(a)). V-trace performs operations on rhos in log-space for numerical stability. discounts: A float32 tensor of shape [T, B] with discounts encountered when following the behaviour policy. rewards: A float32 tensor of shape [T, B] containing rewards generated by following the behaviour policy. values: A float32 tensor of shape [T, B] with the value function estimates wrt. the target policy. bootstrap_value: A float32 of shape [B] with the value function estimate at time T. clip_rho_threshold: A scalar float32 tensor with the clipping threshold for importance weights (rho) when calculating the baseline targets (vs). rho^bar in the paper. If None, no clipping is applied. clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). If None, no clipping is applied. name: The name scope that all V-trace operations will be created in. Returns: A VTraceReturns namedtuple (vs, pg_advantages) where: vs: A float32 tensor of shape [T, B]. Can be used as target to train a baseline (V(x_t) - vs_t)^2. pg_advantages: A float32 tensor of shape [T, B]. Can be used as the advantage in the calculation of policy gradients. """ log_rhos = tf.convert_to_tensor(log_rhos, dtype=tf.float32) discounts = tf.convert_to_tensor(discounts, dtype=tf.float32) rewards = tf.convert_to_tensor(rewards, dtype=tf.float32) values = tf.convert_to_tensor(values, dtype=tf.float32) bootstrap_value = tf.convert_to_tensor(bootstrap_value, dtype=tf.float32) if clip_rho_threshold is not None: clip_rho_threshold = tf.convert_to_tensor( clip_rho_threshold, dtype=tf.float32) if clip_pg_rho_threshold is not None: clip_pg_rho_threshold = tf.convert_to_tensor( clip_pg_rho_threshold, dtype=tf.float32) # Make sure tensor ranks are consistent. rho_rank = log_rhos.shape.ndims # Usually 2. values.shape.assert_has_rank(rho_rank) bootstrap_value.shape.assert_has_rank(rho_rank - 1) discounts.shape.assert_has_rank(rho_rank) rewards.shape.assert_has_rank(rho_rank) if clip_rho_threshold is not None: clip_rho_threshold.shape.assert_has_rank(0) if clip_pg_rho_threshold is not None: clip_pg_rho_threshold.shape.assert_has_rank(0) with tf.name_scope( name, values=[log_rhos, discounts, rewards, values, bootstrap_value]): rhos = tf.exp(log_rhos) if clip_rho_threshold is not None: clipped_rhos = tf.minimum( clip_rho_threshold, rhos, name="clipped_rhos") tf.summary.histogram("clipped_rhos_1000", tf.minimum(1000.0, rhos)) tf.summary.scalar( "num_of_clipped_rhos", tf.reduce_sum( tf.cast( tf.equal(clipped_rhos, clip_rho_threshold), tf.int32))) tf.summary.scalar("size_of_clipped_rhos", tf.size(clipped_rhos)) else: clipped_rhos = rhos cs = tf.minimum(1.0, rhos, name="cs") # Append bootstrapped value to get [v1, ..., v_t+1] values_t_plus_1 = tf.concat( [values[1:], tf.expand_dims(bootstrap_value, 0)], axis=0) deltas = clipped_rhos * ( rewards + discounts * values_t_plus_1 - values) # All sequences are reversed, computation starts from the back. sequences = ( tf.reverse(discounts, axis=[0]), tf.reverse(cs, axis=[0]), tf.reverse(deltas, axis=[0]), ) # V-trace vs are calculated through a scan from the back to the # beginning of the given trajectory. def scanfunc(acc, sequence_item): discount_t, c_t, delta_t = sequence_item return delta_t + discount_t * c_t * acc initial_values = tf.zeros_like(bootstrap_value) vs_minus_v_xs = tf.scan( fn=scanfunc, elems=sequences, initializer=initial_values, parallel_iterations=1, back_prop=False, name="scan") # Reverse the results back to original order. vs_minus_v_xs = tf.reverse(vs_minus_v_xs, [0], name="vs_minus_v_xs") # Add V(x_s) to get v_s. vs = tf.add(vs_minus_v_xs, values, name="vs") # Advantage for policy gradient. vs_t_plus_1 = tf.concat( [vs[1:], tf.expand_dims(bootstrap_value, 0)], axis=0) if clip_pg_rho_threshold is not None: clipped_pg_rhos = tf.minimum( clip_pg_rho_threshold, rhos, name="clipped_pg_rhos") else: clipped_pg_rhos = rhos pg_advantages = ( clipped_pg_rhos * (rewards + discounts * vs_t_plus_1 - values)) # Make sure no gradients backpropagated through the returned values. return VTraceReturns( vs=tf.stop_gradient(vs), pg_advantages=tf.stop_gradient(pg_advantages))
python
def from_importance_weights(log_rhos, discounts, rewards, values, bootstrap_value, clip_rho_threshold=1.0, clip_pg_rho_threshold=1.0, name="vtrace_from_importance_weights"): r"""V-trace from log importance weights. Calculates V-trace actor critic targets as described in "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures" by Espeholt, Soyer, Munos et al. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size. This code also supports the case where all tensors have the same number of additional dimensions, e.g., `rewards` is [T, B, C], `values` is [T, B, C], `bootstrap_value` is [B, C]. Args: log_rhos: A float32 tensor of shape [T, B] representing the log importance sampling weights, i.e. log(target_policy(a) / behaviour_policy(a)). V-trace performs operations on rhos in log-space for numerical stability. discounts: A float32 tensor of shape [T, B] with discounts encountered when following the behaviour policy. rewards: A float32 tensor of shape [T, B] containing rewards generated by following the behaviour policy. values: A float32 tensor of shape [T, B] with the value function estimates wrt. the target policy. bootstrap_value: A float32 of shape [B] with the value function estimate at time T. clip_rho_threshold: A scalar float32 tensor with the clipping threshold for importance weights (rho) when calculating the baseline targets (vs). rho^bar in the paper. If None, no clipping is applied. clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). If None, no clipping is applied. name: The name scope that all V-trace operations will be created in. Returns: A VTraceReturns namedtuple (vs, pg_advantages) where: vs: A float32 tensor of shape [T, B]. Can be used as target to train a baseline (V(x_t) - vs_t)^2. pg_advantages: A float32 tensor of shape [T, B]. Can be used as the advantage in the calculation of policy gradients. """ log_rhos = tf.convert_to_tensor(log_rhos, dtype=tf.float32) discounts = tf.convert_to_tensor(discounts, dtype=tf.float32) rewards = tf.convert_to_tensor(rewards, dtype=tf.float32) values = tf.convert_to_tensor(values, dtype=tf.float32) bootstrap_value = tf.convert_to_tensor(bootstrap_value, dtype=tf.float32) if clip_rho_threshold is not None: clip_rho_threshold = tf.convert_to_tensor( clip_rho_threshold, dtype=tf.float32) if clip_pg_rho_threshold is not None: clip_pg_rho_threshold = tf.convert_to_tensor( clip_pg_rho_threshold, dtype=tf.float32) # Make sure tensor ranks are consistent. rho_rank = log_rhos.shape.ndims # Usually 2. values.shape.assert_has_rank(rho_rank) bootstrap_value.shape.assert_has_rank(rho_rank - 1) discounts.shape.assert_has_rank(rho_rank) rewards.shape.assert_has_rank(rho_rank) if clip_rho_threshold is not None: clip_rho_threshold.shape.assert_has_rank(0) if clip_pg_rho_threshold is not None: clip_pg_rho_threshold.shape.assert_has_rank(0) with tf.name_scope( name, values=[log_rhos, discounts, rewards, values, bootstrap_value]): rhos = tf.exp(log_rhos) if clip_rho_threshold is not None: clipped_rhos = tf.minimum( clip_rho_threshold, rhos, name="clipped_rhos") tf.summary.histogram("clipped_rhos_1000", tf.minimum(1000.0, rhos)) tf.summary.scalar( "num_of_clipped_rhos", tf.reduce_sum( tf.cast( tf.equal(clipped_rhos, clip_rho_threshold), tf.int32))) tf.summary.scalar("size_of_clipped_rhos", tf.size(clipped_rhos)) else: clipped_rhos = rhos cs = tf.minimum(1.0, rhos, name="cs") # Append bootstrapped value to get [v1, ..., v_t+1] values_t_plus_1 = tf.concat( [values[1:], tf.expand_dims(bootstrap_value, 0)], axis=0) deltas = clipped_rhos * ( rewards + discounts * values_t_plus_1 - values) # All sequences are reversed, computation starts from the back. sequences = ( tf.reverse(discounts, axis=[0]), tf.reverse(cs, axis=[0]), tf.reverse(deltas, axis=[0]), ) # V-trace vs are calculated through a scan from the back to the # beginning of the given trajectory. def scanfunc(acc, sequence_item): discount_t, c_t, delta_t = sequence_item return delta_t + discount_t * c_t * acc initial_values = tf.zeros_like(bootstrap_value) vs_minus_v_xs = tf.scan( fn=scanfunc, elems=sequences, initializer=initial_values, parallel_iterations=1, back_prop=False, name="scan") # Reverse the results back to original order. vs_minus_v_xs = tf.reverse(vs_minus_v_xs, [0], name="vs_minus_v_xs") # Add V(x_s) to get v_s. vs = tf.add(vs_minus_v_xs, values, name="vs") # Advantage for policy gradient. vs_t_plus_1 = tf.concat( [vs[1:], tf.expand_dims(bootstrap_value, 0)], axis=0) if clip_pg_rho_threshold is not None: clipped_pg_rhos = tf.minimum( clip_pg_rho_threshold, rhos, name="clipped_pg_rhos") else: clipped_pg_rhos = rhos pg_advantages = ( clipped_pg_rhos * (rewards + discounts * vs_t_plus_1 - values)) # Make sure no gradients backpropagated through the returned values. return VTraceReturns( vs=tf.stop_gradient(vs), pg_advantages=tf.stop_gradient(pg_advantages))
[ "def", "from_importance_weights", "(", "log_rhos", ",", "discounts", ",", "rewards", ",", "values", ",", "bootstrap_value", ",", "clip_rho_threshold", "=", "1.0", ",", "clip_pg_rho_threshold", "=", "1.0", ",", "name", "=", "\"vtrace_from_importance_weights\"", ")", ":", "log_rhos", "=", "tf", ".", "convert_to_tensor", "(", "log_rhos", ",", "dtype", "=", "tf", ".", "float32", ")", "discounts", "=", "tf", ".", "convert_to_tensor", "(", "discounts", ",", "dtype", "=", "tf", ".", "float32", ")", "rewards", "=", "tf", ".", "convert_to_tensor", "(", "rewards", ",", "dtype", "=", "tf", ".", "float32", ")", "values", "=", "tf", ".", "convert_to_tensor", "(", "values", ",", "dtype", "=", "tf", ".", "float32", ")", "bootstrap_value", "=", "tf", ".", "convert_to_tensor", "(", "bootstrap_value", ",", "dtype", "=", "tf", ".", "float32", ")", "if", "clip_rho_threshold", "is", "not", "None", ":", "clip_rho_threshold", "=", "tf", ".", "convert_to_tensor", "(", "clip_rho_threshold", ",", "dtype", "=", "tf", ".", "float32", ")", "if", "clip_pg_rho_threshold", "is", "not", "None", ":", "clip_pg_rho_threshold", "=", "tf", ".", "convert_to_tensor", "(", "clip_pg_rho_threshold", ",", "dtype", "=", "tf", ".", "float32", ")", "# Make sure tensor ranks are consistent.", "rho_rank", "=", "log_rhos", ".", "shape", ".", "ndims", "# Usually 2.", "values", ".", "shape", ".", "assert_has_rank", "(", "rho_rank", ")", "bootstrap_value", ".", "shape", ".", "assert_has_rank", "(", "rho_rank", "-", "1", ")", "discounts", ".", "shape", ".", "assert_has_rank", "(", "rho_rank", ")", "rewards", ".", "shape", ".", "assert_has_rank", "(", "rho_rank", ")", "if", "clip_rho_threshold", "is", "not", "None", ":", "clip_rho_threshold", ".", "shape", ".", "assert_has_rank", "(", "0", ")", "if", "clip_pg_rho_threshold", "is", "not", "None", ":", "clip_pg_rho_threshold", ".", "shape", ".", "assert_has_rank", "(", "0", ")", "with", "tf", ".", "name_scope", "(", "name", ",", "values", "=", "[", "log_rhos", ",", "discounts", ",", "rewards", ",", "values", ",", "bootstrap_value", "]", ")", ":", "rhos", "=", "tf", ".", "exp", "(", "log_rhos", ")", "if", "clip_rho_threshold", "is", "not", "None", ":", "clipped_rhos", "=", "tf", ".", "minimum", "(", "clip_rho_threshold", ",", "rhos", ",", "name", "=", "\"clipped_rhos\"", ")", "tf", ".", "summary", ".", "histogram", "(", "\"clipped_rhos_1000\"", ",", "tf", ".", "minimum", "(", "1000.0", ",", "rhos", ")", ")", "tf", ".", "summary", ".", "scalar", "(", "\"num_of_clipped_rhos\"", ",", "tf", ".", "reduce_sum", "(", "tf", ".", "cast", "(", "tf", ".", "equal", "(", "clipped_rhos", ",", "clip_rho_threshold", ")", ",", "tf", ".", "int32", ")", ")", ")", "tf", ".", "summary", ".", "scalar", "(", "\"size_of_clipped_rhos\"", ",", "tf", ".", "size", "(", "clipped_rhos", ")", ")", "else", ":", "clipped_rhos", "=", "rhos", "cs", "=", "tf", ".", "minimum", "(", "1.0", ",", "rhos", ",", "name", "=", "\"cs\"", ")", "# Append bootstrapped value to get [v1, ..., v_t+1]", "values_t_plus_1", "=", "tf", ".", "concat", "(", "[", "values", "[", "1", ":", "]", ",", "tf", ".", "expand_dims", "(", "bootstrap_value", ",", "0", ")", "]", ",", "axis", "=", "0", ")", "deltas", "=", "clipped_rhos", "*", "(", "rewards", "+", "discounts", "*", "values_t_plus_1", "-", "values", ")", "# All sequences are reversed, computation starts from the back.", "sequences", "=", "(", "tf", ".", "reverse", "(", "discounts", ",", "axis", "=", "[", "0", "]", ")", ",", "tf", ".", "reverse", "(", "cs", ",", "axis", "=", "[", "0", "]", ")", ",", "tf", ".", "reverse", "(", "deltas", ",", "axis", "=", "[", "0", "]", ")", ",", ")", "# V-trace vs are calculated through a scan from the back to the", "# beginning of the given trajectory.", "def", "scanfunc", "(", "acc", ",", "sequence_item", ")", ":", "discount_t", ",", "c_t", ",", "delta_t", "=", "sequence_item", "return", "delta_t", "+", "discount_t", "*", "c_t", "*", "acc", "initial_values", "=", "tf", ".", "zeros_like", "(", "bootstrap_value", ")", "vs_minus_v_xs", "=", "tf", ".", "scan", "(", "fn", "=", "scanfunc", ",", "elems", "=", "sequences", ",", "initializer", "=", "initial_values", ",", "parallel_iterations", "=", "1", ",", "back_prop", "=", "False", ",", "name", "=", "\"scan\"", ")", "# Reverse the results back to original order.", "vs_minus_v_xs", "=", "tf", ".", "reverse", "(", "vs_minus_v_xs", ",", "[", "0", "]", ",", "name", "=", "\"vs_minus_v_xs\"", ")", "# Add V(x_s) to get v_s.", "vs", "=", "tf", ".", "add", "(", "vs_minus_v_xs", ",", "values", ",", "name", "=", "\"vs\"", ")", "# Advantage for policy gradient.", "vs_t_plus_1", "=", "tf", ".", "concat", "(", "[", "vs", "[", "1", ":", "]", ",", "tf", ".", "expand_dims", "(", "bootstrap_value", ",", "0", ")", "]", ",", "axis", "=", "0", ")", "if", "clip_pg_rho_threshold", "is", "not", "None", ":", "clipped_pg_rhos", "=", "tf", ".", "minimum", "(", "clip_pg_rho_threshold", ",", "rhos", ",", "name", "=", "\"clipped_pg_rhos\"", ")", "else", ":", "clipped_pg_rhos", "=", "rhos", "pg_advantages", "=", "(", "clipped_pg_rhos", "*", "(", "rewards", "+", "discounts", "*", "vs_t_plus_1", "-", "values", ")", ")", "# Make sure no gradients backpropagated through the returned values.", "return", "VTraceReturns", "(", "vs", "=", "tf", ".", "stop_gradient", "(", "vs", ")", ",", "pg_advantages", "=", "tf", ".", "stop_gradient", "(", "pg_advantages", ")", ")" ]
r"""V-trace from log importance weights. Calculates V-trace actor critic targets as described in "IMPALA: Scalable Distributed Deep-RL with Importance Weighted Actor-Learner Architectures" by Espeholt, Soyer, Munos et al. In the notation used throughout documentation and comments, T refers to the time dimension ranging from 0 to T-1. B refers to the batch size. This code also supports the case where all tensors have the same number of additional dimensions, e.g., `rewards` is [T, B, C], `values` is [T, B, C], `bootstrap_value` is [B, C]. Args: log_rhos: A float32 tensor of shape [T, B] representing the log importance sampling weights, i.e. log(target_policy(a) / behaviour_policy(a)). V-trace performs operations on rhos in log-space for numerical stability. discounts: A float32 tensor of shape [T, B] with discounts encountered when following the behaviour policy. rewards: A float32 tensor of shape [T, B] containing rewards generated by following the behaviour policy. values: A float32 tensor of shape [T, B] with the value function estimates wrt. the target policy. bootstrap_value: A float32 of shape [B] with the value function estimate at time T. clip_rho_threshold: A scalar float32 tensor with the clipping threshold for importance weights (rho) when calculating the baseline targets (vs). rho^bar in the paper. If None, no clipping is applied. clip_pg_rho_threshold: A scalar float32 tensor with the clipping threshold on rho_s in \rho_s \delta log \pi(a|x) (r + \gamma v_{s+1} - V(x_s)). If None, no clipping is applied. name: The name scope that all V-trace operations will be created in. Returns: A VTraceReturns namedtuple (vs, pg_advantages) where: vs: A float32 tensor of shape [T, B]. Can be used as target to train a baseline (V(x_t) - vs_t)^2. pg_advantages: A float32 tensor of shape [T, B]. Can be used as the advantage in the calculation of policy gradients.
[ "r", "V", "-", "trace", "from", "log", "importance", "weights", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/impala/vtrace.py#L247-L386
train
ray-project/ray
python/ray/rllib/agents/impala/vtrace.py
get_log_rhos
def get_log_rhos(target_action_log_probs, behaviour_action_log_probs): """With the selected log_probs for multi-discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace.""" t = tf.stack(target_action_log_probs) b = tf.stack(behaviour_action_log_probs) log_rhos = tf.reduce_sum(t - b, axis=0) return log_rhos
python
def get_log_rhos(target_action_log_probs, behaviour_action_log_probs): """With the selected log_probs for multi-discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace.""" t = tf.stack(target_action_log_probs) b = tf.stack(behaviour_action_log_probs) log_rhos = tf.reduce_sum(t - b, axis=0) return log_rhos
[ "def", "get_log_rhos", "(", "target_action_log_probs", ",", "behaviour_action_log_probs", ")", ":", "t", "=", "tf", ".", "stack", "(", "target_action_log_probs", ")", "b", "=", "tf", ".", "stack", "(", "behaviour_action_log_probs", ")", "log_rhos", "=", "tf", ".", "reduce_sum", "(", "t", "-", "b", ",", "axis", "=", "0", ")", "return", "log_rhos" ]
With the selected log_probs for multi-discrete actions of behaviour and target policies we compute the log_rhos for calculating the vtrace.
[ "With", "the", "selected", "log_probs", "for", "multi", "-", "discrete", "actions", "of", "behaviour", "and", "target", "policies", "we", "compute", "the", "log_rhos", "for", "calculating", "the", "vtrace", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/impala/vtrace.py#L389-L395
train
ray-project/ray
python/ray/tune/examples/tune_mnist_async_hyperband.py
weight_variable
def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)
python
def weight_variable(shape): """weight_variable generates a weight variable of a given shape.""" initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial)
[ "def", "weight_variable", "(", "shape", ")", ":", "initial", "=", "tf", ".", "truncated_normal", "(", "shape", ",", "stddev", "=", "0.1", ")", "return", "tf", ".", "Variable", "(", "initial", ")" ]
weight_variable generates a weight variable of a given shape.
[ "weight_variable", "generates", "a", "weight", "variable", "of", "a", "given", "shape", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/examples/tune_mnist_async_hyperband.py#L121-L124
train
ray-project/ray
python/ray/tune/examples/tune_mnist_async_hyperband.py
bias_variable
def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
python
def bias_variable(shape): """bias_variable generates a bias variable of a given shape.""" initial = tf.constant(0.1, shape=shape) return tf.Variable(initial)
[ "def", "bias_variable", "(", "shape", ")", ":", "initial", "=", "tf", ".", "constant", "(", "0.1", ",", "shape", "=", "shape", ")", "return", "tf", ".", "Variable", "(", "initial", ")" ]
bias_variable generates a bias variable of a given shape.
[ "bias_variable", "generates", "a", "bias", "variable", "of", "a", "given", "shape", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/examples/tune_mnist_async_hyperband.py#L127-L130
train
ray-project/ray
python/ray/tune/commands.py
print_format_output
def print_format_output(dataframe): """Prints output of given dataframe to fit into terminal. Returns: table (pd.DataFrame): Final outputted dataframe. dropped_cols (list): Columns dropped due to terminal size. empty_cols (list): Empty columns (dropped on default). """ print_df = pd.DataFrame() dropped_cols = [] empty_cols = [] # column display priority is based on the info_keys passed in for i, col in enumerate(dataframe): if dataframe[col].isnull().all(): # Don't add col to print_df if is fully empty empty_cols += [col] continue print_df[col] = dataframe[col] test_table = tabulate(print_df, headers="keys", tablefmt="psql") if str(test_table).index("\n") > TERM_WIDTH: # Drop all columns beyond terminal width print_df.drop(col, axis=1, inplace=True) dropped_cols += list(dataframe.columns)[i:] break table = tabulate( print_df, headers="keys", tablefmt="psql", showindex="never") print(table) if dropped_cols: print("Dropped columns:", dropped_cols) print("Please increase your terminal size to view remaining columns.") if empty_cols: print("Empty columns:", empty_cols) return table, dropped_cols, empty_cols
python
def print_format_output(dataframe): """Prints output of given dataframe to fit into terminal. Returns: table (pd.DataFrame): Final outputted dataframe. dropped_cols (list): Columns dropped due to terminal size. empty_cols (list): Empty columns (dropped on default). """ print_df = pd.DataFrame() dropped_cols = [] empty_cols = [] # column display priority is based on the info_keys passed in for i, col in enumerate(dataframe): if dataframe[col].isnull().all(): # Don't add col to print_df if is fully empty empty_cols += [col] continue print_df[col] = dataframe[col] test_table = tabulate(print_df, headers="keys", tablefmt="psql") if str(test_table).index("\n") > TERM_WIDTH: # Drop all columns beyond terminal width print_df.drop(col, axis=1, inplace=True) dropped_cols += list(dataframe.columns)[i:] break table = tabulate( print_df, headers="keys", tablefmt="psql", showindex="never") print(table) if dropped_cols: print("Dropped columns:", dropped_cols) print("Please increase your terminal size to view remaining columns.") if empty_cols: print("Empty columns:", empty_cols) return table, dropped_cols, empty_cols
[ "def", "print_format_output", "(", "dataframe", ")", ":", "print_df", "=", "pd", ".", "DataFrame", "(", ")", "dropped_cols", "=", "[", "]", "empty_cols", "=", "[", "]", "# column display priority is based on the info_keys passed in", "for", "i", ",", "col", "in", "enumerate", "(", "dataframe", ")", ":", "if", "dataframe", "[", "col", "]", ".", "isnull", "(", ")", ".", "all", "(", ")", ":", "# Don't add col to print_df if is fully empty", "empty_cols", "+=", "[", "col", "]", "continue", "print_df", "[", "col", "]", "=", "dataframe", "[", "col", "]", "test_table", "=", "tabulate", "(", "print_df", ",", "headers", "=", "\"keys\"", ",", "tablefmt", "=", "\"psql\"", ")", "if", "str", "(", "test_table", ")", ".", "index", "(", "\"\\n\"", ")", ">", "TERM_WIDTH", ":", "# Drop all columns beyond terminal width", "print_df", ".", "drop", "(", "col", ",", "axis", "=", "1", ",", "inplace", "=", "True", ")", "dropped_cols", "+=", "list", "(", "dataframe", ".", "columns", ")", "[", "i", ":", "]", "break", "table", "=", "tabulate", "(", "print_df", ",", "headers", "=", "\"keys\"", ",", "tablefmt", "=", "\"psql\"", ",", "showindex", "=", "\"never\"", ")", "print", "(", "table", ")", "if", "dropped_cols", ":", "print", "(", "\"Dropped columns:\"", ",", "dropped_cols", ")", "print", "(", "\"Please increase your terminal size to view remaining columns.\"", ")", "if", "empty_cols", ":", "print", "(", "\"Empty columns:\"", ",", "empty_cols", ")", "return", "table", ",", "dropped_cols", ",", "empty_cols" ]
Prints output of given dataframe to fit into terminal. Returns: table (pd.DataFrame): Final outputted dataframe. dropped_cols (list): Columns dropped due to terminal size. empty_cols (list): Empty columns (dropped on default).
[ "Prints", "output", "of", "given", "dataframe", "to", "fit", "into", "terminal", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/commands.py#L72-L108
train
ray-project/ray
python/ray/tune/commands.py
list_trials
def list_trials(experiment_path, sort=None, output=None, filter_op=None, info_keys=None, result_keys=None): """Lists trials in the directory subtree starting at the given path. Args: experiment_path (str): Directory where trials are located. Corresponds to Experiment.local_dir/Experiment.name. sort (str): Key to sort by. output (str): Name of file where output is saved. filter_op (str): Filter operation in the format "<column> <operator> <value>". info_keys (list): Keys that are displayed. result_keys (list): Keys of last result that are displayed. """ _check_tabulate() experiment_state = _get_experiment_state( experiment_path, exit_on_fail=True) checkpoint_dicts = experiment_state["checkpoints"] checkpoint_dicts = [flatten_dict(g) for g in checkpoint_dicts] checkpoints_df = pd.DataFrame(checkpoint_dicts) if not info_keys: info_keys = DEFAULT_EXPERIMENT_INFO_KEYS if not result_keys: result_keys = DEFAULT_RESULT_KEYS result_keys = ["last_result:{}".format(k) for k in result_keys] col_keys = [ k for k in list(info_keys) + result_keys if k in checkpoints_df ] checkpoints_df = checkpoints_df[col_keys] if "last_update_time" in checkpoints_df: with pd.option_context("mode.use_inf_as_null", True): datetime_series = checkpoints_df["last_update_time"].dropna() datetime_series = datetime_series.apply( lambda t: datetime.fromtimestamp(t).strftime(TIMESTAMP_FORMAT)) checkpoints_df["last_update_time"] = datetime_series if "logdir" in checkpoints_df: # logdir often too verbose to view in table, so drop experiment_path checkpoints_df["logdir"] = checkpoints_df["logdir"].str.replace( experiment_path, "") if filter_op: col, op, val = filter_op.split(" ") col_type = checkpoints_df[col].dtype if is_numeric_dtype(col_type): val = float(val) elif is_string_dtype(col_type): val = str(val) # TODO(Andrew): add support for datetime and boolean else: raise ValueError("Unsupported dtype for \"{}\": {}".format( val, col_type)) op = OPERATORS[op] filtered_index = op(checkpoints_df[col], val) checkpoints_df = checkpoints_df[filtered_index] if sort: if sort not in checkpoints_df: raise KeyError("Sort Index \"{}\" not in: {}".format( sort, list(checkpoints_df))) checkpoints_df = checkpoints_df.sort_values(by=sort) print_format_output(checkpoints_df) if output: file_extension = os.path.splitext(output)[1].lower() if file_extension in (".p", ".pkl", ".pickle"): checkpoints_df.to_pickle(output) elif file_extension == ".csv": checkpoints_df.to_csv(output, index=False) else: raise ValueError("Unsupported filetype: {}".format(output)) print("Output saved at:", output)
python
def list_trials(experiment_path, sort=None, output=None, filter_op=None, info_keys=None, result_keys=None): """Lists trials in the directory subtree starting at the given path. Args: experiment_path (str): Directory where trials are located. Corresponds to Experiment.local_dir/Experiment.name. sort (str): Key to sort by. output (str): Name of file where output is saved. filter_op (str): Filter operation in the format "<column> <operator> <value>". info_keys (list): Keys that are displayed. result_keys (list): Keys of last result that are displayed. """ _check_tabulate() experiment_state = _get_experiment_state( experiment_path, exit_on_fail=True) checkpoint_dicts = experiment_state["checkpoints"] checkpoint_dicts = [flatten_dict(g) for g in checkpoint_dicts] checkpoints_df = pd.DataFrame(checkpoint_dicts) if not info_keys: info_keys = DEFAULT_EXPERIMENT_INFO_KEYS if not result_keys: result_keys = DEFAULT_RESULT_KEYS result_keys = ["last_result:{}".format(k) for k in result_keys] col_keys = [ k for k in list(info_keys) + result_keys if k in checkpoints_df ] checkpoints_df = checkpoints_df[col_keys] if "last_update_time" in checkpoints_df: with pd.option_context("mode.use_inf_as_null", True): datetime_series = checkpoints_df["last_update_time"].dropna() datetime_series = datetime_series.apply( lambda t: datetime.fromtimestamp(t).strftime(TIMESTAMP_FORMAT)) checkpoints_df["last_update_time"] = datetime_series if "logdir" in checkpoints_df: # logdir often too verbose to view in table, so drop experiment_path checkpoints_df["logdir"] = checkpoints_df["logdir"].str.replace( experiment_path, "") if filter_op: col, op, val = filter_op.split(" ") col_type = checkpoints_df[col].dtype if is_numeric_dtype(col_type): val = float(val) elif is_string_dtype(col_type): val = str(val) # TODO(Andrew): add support for datetime and boolean else: raise ValueError("Unsupported dtype for \"{}\": {}".format( val, col_type)) op = OPERATORS[op] filtered_index = op(checkpoints_df[col], val) checkpoints_df = checkpoints_df[filtered_index] if sort: if sort not in checkpoints_df: raise KeyError("Sort Index \"{}\" not in: {}".format( sort, list(checkpoints_df))) checkpoints_df = checkpoints_df.sort_values(by=sort) print_format_output(checkpoints_df) if output: file_extension = os.path.splitext(output)[1].lower() if file_extension in (".p", ".pkl", ".pickle"): checkpoints_df.to_pickle(output) elif file_extension == ".csv": checkpoints_df.to_csv(output, index=False) else: raise ValueError("Unsupported filetype: {}".format(output)) print("Output saved at:", output)
[ "def", "list_trials", "(", "experiment_path", ",", "sort", "=", "None", ",", "output", "=", "None", ",", "filter_op", "=", "None", ",", "info_keys", "=", "None", ",", "result_keys", "=", "None", ")", ":", "_check_tabulate", "(", ")", "experiment_state", "=", "_get_experiment_state", "(", "experiment_path", ",", "exit_on_fail", "=", "True", ")", "checkpoint_dicts", "=", "experiment_state", "[", "\"checkpoints\"", "]", "checkpoint_dicts", "=", "[", "flatten_dict", "(", "g", ")", "for", "g", "in", "checkpoint_dicts", "]", "checkpoints_df", "=", "pd", ".", "DataFrame", "(", "checkpoint_dicts", ")", "if", "not", "info_keys", ":", "info_keys", "=", "DEFAULT_EXPERIMENT_INFO_KEYS", "if", "not", "result_keys", ":", "result_keys", "=", "DEFAULT_RESULT_KEYS", "result_keys", "=", "[", "\"last_result:{}\"", ".", "format", "(", "k", ")", "for", "k", "in", "result_keys", "]", "col_keys", "=", "[", "k", "for", "k", "in", "list", "(", "info_keys", ")", "+", "result_keys", "if", "k", "in", "checkpoints_df", "]", "checkpoints_df", "=", "checkpoints_df", "[", "col_keys", "]", "if", "\"last_update_time\"", "in", "checkpoints_df", ":", "with", "pd", ".", "option_context", "(", "\"mode.use_inf_as_null\"", ",", "True", ")", ":", "datetime_series", "=", "checkpoints_df", "[", "\"last_update_time\"", "]", ".", "dropna", "(", ")", "datetime_series", "=", "datetime_series", ".", "apply", "(", "lambda", "t", ":", "datetime", ".", "fromtimestamp", "(", "t", ")", ".", "strftime", "(", "TIMESTAMP_FORMAT", ")", ")", "checkpoints_df", "[", "\"last_update_time\"", "]", "=", "datetime_series", "if", "\"logdir\"", "in", "checkpoints_df", ":", "# logdir often too verbose to view in table, so drop experiment_path", "checkpoints_df", "[", "\"logdir\"", "]", "=", "checkpoints_df", "[", "\"logdir\"", "]", ".", "str", ".", "replace", "(", "experiment_path", ",", "\"\"", ")", "if", "filter_op", ":", "col", ",", "op", ",", "val", "=", "filter_op", ".", "split", "(", "\" \"", ")", "col_type", "=", "checkpoints_df", "[", "col", "]", ".", "dtype", "if", "is_numeric_dtype", "(", "col_type", ")", ":", "val", "=", "float", "(", "val", ")", "elif", "is_string_dtype", "(", "col_type", ")", ":", "val", "=", "str", "(", "val", ")", "# TODO(Andrew): add support for datetime and boolean", "else", ":", "raise", "ValueError", "(", "\"Unsupported dtype for \\\"{}\\\": {}\"", ".", "format", "(", "val", ",", "col_type", ")", ")", "op", "=", "OPERATORS", "[", "op", "]", "filtered_index", "=", "op", "(", "checkpoints_df", "[", "col", "]", ",", "val", ")", "checkpoints_df", "=", "checkpoints_df", "[", "filtered_index", "]", "if", "sort", ":", "if", "sort", "not", "in", "checkpoints_df", ":", "raise", "KeyError", "(", "\"Sort Index \\\"{}\\\" not in: {}\"", ".", "format", "(", "sort", ",", "list", "(", "checkpoints_df", ")", ")", ")", "checkpoints_df", "=", "checkpoints_df", ".", "sort_values", "(", "by", "=", "sort", ")", "print_format_output", "(", "checkpoints_df", ")", "if", "output", ":", "file_extension", "=", "os", ".", "path", ".", "splitext", "(", "output", ")", "[", "1", "]", ".", "lower", "(", ")", "if", "file_extension", "in", "(", "\".p\"", ",", "\".pkl\"", ",", "\".pickle\"", ")", ":", "checkpoints_df", ".", "to_pickle", "(", "output", ")", "elif", "file_extension", "==", "\".csv\"", ":", "checkpoints_df", ".", "to_csv", "(", "output", ",", "index", "=", "False", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported filetype: {}\"", ".", "format", "(", "output", ")", ")", "print", "(", "\"Output saved at:\"", ",", "output", ")" ]
Lists trials in the directory subtree starting at the given path. Args: experiment_path (str): Directory where trials are located. Corresponds to Experiment.local_dir/Experiment.name. sort (str): Key to sort by. output (str): Name of file where output is saved. filter_op (str): Filter operation in the format "<column> <operator> <value>". info_keys (list): Keys that are displayed. result_keys (list): Keys of last result that are displayed.
[ "Lists", "trials", "in", "the", "directory", "subtree", "starting", "at", "the", "given", "path", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/commands.py#L128-L208
train
ray-project/ray
python/ray/tune/commands.py
list_experiments
def list_experiments(project_path, sort=None, output=None, filter_op=None, info_keys=None): """Lists experiments in the directory subtree. Args: project_path (str): Directory where experiments are located. Corresponds to Experiment.local_dir. sort (str): Key to sort by. output (str): Name of file where output is saved. filter_op (str): Filter operation in the format "<column> <operator> <value>". info_keys (list): Keys that are displayed. """ _check_tabulate() base, experiment_folders, _ = next(os.walk(project_path)) experiment_data_collection = [] for experiment_dir in experiment_folders: experiment_state = _get_experiment_state( os.path.join(base, experiment_dir)) if not experiment_state: logger.debug("No experiment state found in %s", experiment_dir) continue checkpoints = pd.DataFrame(experiment_state["checkpoints"]) runner_data = experiment_state["runner_data"] # Format time-based values. time_values = { "start_time": runner_data.get("_start_time"), "last_updated": experiment_state.get("timestamp"), } formatted_time_values = { key: datetime.fromtimestamp(val).strftime(TIMESTAMP_FORMAT) if val else None for key, val in time_values.items() } experiment_data = { "name": experiment_dir, "total_trials": checkpoints.shape[0], "running_trials": (checkpoints["status"] == Trial.RUNNING).sum(), "terminated_trials": ( checkpoints["status"] == Trial.TERMINATED).sum(), "error_trials": (checkpoints["status"] == Trial.ERROR).sum(), } experiment_data.update(formatted_time_values) experiment_data_collection.append(experiment_data) if not experiment_data_collection: print("No experiments found!") sys.exit(0) info_df = pd.DataFrame(experiment_data_collection) if not info_keys: info_keys = DEFAULT_PROJECT_INFO_KEYS col_keys = [k for k in list(info_keys) if k in info_df] if not col_keys: print("None of keys {} in experiment data!".format(info_keys)) sys.exit(0) info_df = info_df[col_keys] if filter_op: col, op, val = filter_op.split(" ") col_type = info_df[col].dtype if is_numeric_dtype(col_type): val = float(val) elif is_string_dtype(col_type): val = str(val) # TODO(Andrew): add support for datetime and boolean else: raise ValueError("Unsupported dtype for \"{}\": {}".format( val, col_type)) op = OPERATORS[op] filtered_index = op(info_df[col], val) info_df = info_df[filtered_index] if sort: if sort not in info_df: raise KeyError("Sort Index \"{}\" not in: {}".format( sort, list(info_df))) info_df = info_df.sort_values(by=sort) print_format_output(info_df) if output: file_extension = os.path.splitext(output)[1].lower() if file_extension in (".p", ".pkl", ".pickle"): info_df.to_pickle(output) elif file_extension == ".csv": info_df.to_csv(output, index=False) else: raise ValueError("Unsupported filetype: {}".format(output)) print("Output saved at:", output)
python
def list_experiments(project_path, sort=None, output=None, filter_op=None, info_keys=None): """Lists experiments in the directory subtree. Args: project_path (str): Directory where experiments are located. Corresponds to Experiment.local_dir. sort (str): Key to sort by. output (str): Name of file where output is saved. filter_op (str): Filter operation in the format "<column> <operator> <value>". info_keys (list): Keys that are displayed. """ _check_tabulate() base, experiment_folders, _ = next(os.walk(project_path)) experiment_data_collection = [] for experiment_dir in experiment_folders: experiment_state = _get_experiment_state( os.path.join(base, experiment_dir)) if not experiment_state: logger.debug("No experiment state found in %s", experiment_dir) continue checkpoints = pd.DataFrame(experiment_state["checkpoints"]) runner_data = experiment_state["runner_data"] # Format time-based values. time_values = { "start_time": runner_data.get("_start_time"), "last_updated": experiment_state.get("timestamp"), } formatted_time_values = { key: datetime.fromtimestamp(val).strftime(TIMESTAMP_FORMAT) if val else None for key, val in time_values.items() } experiment_data = { "name": experiment_dir, "total_trials": checkpoints.shape[0], "running_trials": (checkpoints["status"] == Trial.RUNNING).sum(), "terminated_trials": ( checkpoints["status"] == Trial.TERMINATED).sum(), "error_trials": (checkpoints["status"] == Trial.ERROR).sum(), } experiment_data.update(formatted_time_values) experiment_data_collection.append(experiment_data) if not experiment_data_collection: print("No experiments found!") sys.exit(0) info_df = pd.DataFrame(experiment_data_collection) if not info_keys: info_keys = DEFAULT_PROJECT_INFO_KEYS col_keys = [k for k in list(info_keys) if k in info_df] if not col_keys: print("None of keys {} in experiment data!".format(info_keys)) sys.exit(0) info_df = info_df[col_keys] if filter_op: col, op, val = filter_op.split(" ") col_type = info_df[col].dtype if is_numeric_dtype(col_type): val = float(val) elif is_string_dtype(col_type): val = str(val) # TODO(Andrew): add support for datetime and boolean else: raise ValueError("Unsupported dtype for \"{}\": {}".format( val, col_type)) op = OPERATORS[op] filtered_index = op(info_df[col], val) info_df = info_df[filtered_index] if sort: if sort not in info_df: raise KeyError("Sort Index \"{}\" not in: {}".format( sort, list(info_df))) info_df = info_df.sort_values(by=sort) print_format_output(info_df) if output: file_extension = os.path.splitext(output)[1].lower() if file_extension in (".p", ".pkl", ".pickle"): info_df.to_pickle(output) elif file_extension == ".csv": info_df.to_csv(output, index=False) else: raise ValueError("Unsupported filetype: {}".format(output)) print("Output saved at:", output)
[ "def", "list_experiments", "(", "project_path", ",", "sort", "=", "None", ",", "output", "=", "None", ",", "filter_op", "=", "None", ",", "info_keys", "=", "None", ")", ":", "_check_tabulate", "(", ")", "base", ",", "experiment_folders", ",", "_", "=", "next", "(", "os", ".", "walk", "(", "project_path", ")", ")", "experiment_data_collection", "=", "[", "]", "for", "experiment_dir", "in", "experiment_folders", ":", "experiment_state", "=", "_get_experiment_state", "(", "os", ".", "path", ".", "join", "(", "base", ",", "experiment_dir", ")", ")", "if", "not", "experiment_state", ":", "logger", ".", "debug", "(", "\"No experiment state found in %s\"", ",", "experiment_dir", ")", "continue", "checkpoints", "=", "pd", ".", "DataFrame", "(", "experiment_state", "[", "\"checkpoints\"", "]", ")", "runner_data", "=", "experiment_state", "[", "\"runner_data\"", "]", "# Format time-based values.", "time_values", "=", "{", "\"start_time\"", ":", "runner_data", ".", "get", "(", "\"_start_time\"", ")", ",", "\"last_updated\"", ":", "experiment_state", ".", "get", "(", "\"timestamp\"", ")", ",", "}", "formatted_time_values", "=", "{", "key", ":", "datetime", ".", "fromtimestamp", "(", "val", ")", ".", "strftime", "(", "TIMESTAMP_FORMAT", ")", "if", "val", "else", "None", "for", "key", ",", "val", "in", "time_values", ".", "items", "(", ")", "}", "experiment_data", "=", "{", "\"name\"", ":", "experiment_dir", ",", "\"total_trials\"", ":", "checkpoints", ".", "shape", "[", "0", "]", ",", "\"running_trials\"", ":", "(", "checkpoints", "[", "\"status\"", "]", "==", "Trial", ".", "RUNNING", ")", ".", "sum", "(", ")", ",", "\"terminated_trials\"", ":", "(", "checkpoints", "[", "\"status\"", "]", "==", "Trial", ".", "TERMINATED", ")", ".", "sum", "(", ")", ",", "\"error_trials\"", ":", "(", "checkpoints", "[", "\"status\"", "]", "==", "Trial", ".", "ERROR", ")", ".", "sum", "(", ")", ",", "}", "experiment_data", ".", "update", "(", "formatted_time_values", ")", "experiment_data_collection", ".", "append", "(", "experiment_data", ")", "if", "not", "experiment_data_collection", ":", "print", "(", "\"No experiments found!\"", ")", "sys", ".", "exit", "(", "0", ")", "info_df", "=", "pd", ".", "DataFrame", "(", "experiment_data_collection", ")", "if", "not", "info_keys", ":", "info_keys", "=", "DEFAULT_PROJECT_INFO_KEYS", "col_keys", "=", "[", "k", "for", "k", "in", "list", "(", "info_keys", ")", "if", "k", "in", "info_df", "]", "if", "not", "col_keys", ":", "print", "(", "\"None of keys {} in experiment data!\"", ".", "format", "(", "info_keys", ")", ")", "sys", ".", "exit", "(", "0", ")", "info_df", "=", "info_df", "[", "col_keys", "]", "if", "filter_op", ":", "col", ",", "op", ",", "val", "=", "filter_op", ".", "split", "(", "\" \"", ")", "col_type", "=", "info_df", "[", "col", "]", ".", "dtype", "if", "is_numeric_dtype", "(", "col_type", ")", ":", "val", "=", "float", "(", "val", ")", "elif", "is_string_dtype", "(", "col_type", ")", ":", "val", "=", "str", "(", "val", ")", "# TODO(Andrew): add support for datetime and boolean", "else", ":", "raise", "ValueError", "(", "\"Unsupported dtype for \\\"{}\\\": {}\"", ".", "format", "(", "val", ",", "col_type", ")", ")", "op", "=", "OPERATORS", "[", "op", "]", "filtered_index", "=", "op", "(", "info_df", "[", "col", "]", ",", "val", ")", "info_df", "=", "info_df", "[", "filtered_index", "]", "if", "sort", ":", "if", "sort", "not", "in", "info_df", ":", "raise", "KeyError", "(", "\"Sort Index \\\"{}\\\" not in: {}\"", ".", "format", "(", "sort", ",", "list", "(", "info_df", ")", ")", ")", "info_df", "=", "info_df", ".", "sort_values", "(", "by", "=", "sort", ")", "print_format_output", "(", "info_df", ")", "if", "output", ":", "file_extension", "=", "os", ".", "path", ".", "splitext", "(", "output", ")", "[", "1", "]", ".", "lower", "(", ")", "if", "file_extension", "in", "(", "\".p\"", ",", "\".pkl\"", ",", "\".pickle\"", ")", ":", "info_df", ".", "to_pickle", "(", "output", ")", "elif", "file_extension", "==", "\".csv\"", ":", "info_df", ".", "to_csv", "(", "output", ",", "index", "=", "False", ")", "else", ":", "raise", "ValueError", "(", "\"Unsupported filetype: {}\"", ".", "format", "(", "output", ")", ")", "print", "(", "\"Output saved at:\"", ",", "output", ")" ]
Lists experiments in the directory subtree. Args: project_path (str): Directory where experiments are located. Corresponds to Experiment.local_dir. sort (str): Key to sort by. output (str): Name of file where output is saved. filter_op (str): Filter operation in the format "<column> <operator> <value>". info_keys (list): Keys that are displayed.
[ "Lists", "experiments", "in", "the", "directory", "subtree", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/commands.py#L211-L309
train
ray-project/ray
python/ray/tune/commands.py
add_note
def add_note(path, filename="note.txt"): """Opens a txt file at the given path where user can add and save notes. Args: path (str): Directory where note will be saved. filename (str): Name of note. Defaults to "note.txt" """ path = os.path.expanduser(path) assert os.path.isdir(path), "{} is not a valid directory.".format(path) filepath = os.path.join(path, filename) exists = os.path.isfile(filepath) try: subprocess.call([EDITOR, filepath]) except Exception as exc: logger.error("Editing note failed!") raise exc if exists: print("Note updated at:", filepath) else: print("Note created at:", filepath)
python
def add_note(path, filename="note.txt"): """Opens a txt file at the given path where user can add and save notes. Args: path (str): Directory where note will be saved. filename (str): Name of note. Defaults to "note.txt" """ path = os.path.expanduser(path) assert os.path.isdir(path), "{} is not a valid directory.".format(path) filepath = os.path.join(path, filename) exists = os.path.isfile(filepath) try: subprocess.call([EDITOR, filepath]) except Exception as exc: logger.error("Editing note failed!") raise exc if exists: print("Note updated at:", filepath) else: print("Note created at:", filepath)
[ "def", "add_note", "(", "path", ",", "filename", "=", "\"note.txt\"", ")", ":", "path", "=", "os", ".", "path", ".", "expanduser", "(", "path", ")", "assert", "os", ".", "path", ".", "isdir", "(", "path", ")", ",", "\"{} is not a valid directory.\"", ".", "format", "(", "path", ")", "filepath", "=", "os", ".", "path", ".", "join", "(", "path", ",", "filename", ")", "exists", "=", "os", ".", "path", ".", "isfile", "(", "filepath", ")", "try", ":", "subprocess", ".", "call", "(", "[", "EDITOR", ",", "filepath", "]", ")", "except", "Exception", "as", "exc", ":", "logger", ".", "error", "(", "\"Editing note failed!\"", ")", "raise", "exc", "if", "exists", ":", "print", "(", "\"Note updated at:\"", ",", "filepath", ")", "else", ":", "print", "(", "\"Note created at:\"", ",", "filepath", ")" ]
Opens a txt file at the given path where user can add and save notes. Args: path (str): Directory where note will be saved. filename (str): Name of note. Defaults to "note.txt"
[ "Opens", "a", "txt", "file", "at", "the", "given", "path", "where", "user", "can", "add", "and", "save", "notes", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/commands.py#L312-L333
train
ray-project/ray
python/ray/tune/automlboard/frontend/query.py
query_job
def query_job(request): """Rest API to query the job info, with the given job_id. The url pattern should be like this: curl http://<server>:<port>/query_job?job_id=<job_id> The response may be: { "running_trials": 0, "start_time": "2018-07-19 20:49:40", "current_round": 1, "failed_trials": 0, "best_trial_id": "2067R2ZD", "name": "asynchyperband_test", "job_id": "asynchyperband_test", "user": "Grady", "type": "RAY TUNE", "total_trials": 4, "end_time": "2018-07-19 20:50:10", "progress": 100, "success_trials": 4 } """ job_id = request.GET.get("job_id") jobs = JobRecord.objects.filter(job_id=job_id) trials = TrialRecord.objects.filter(job_id=job_id) total_num = len(trials) running_num = sum(t.trial_status == Trial.RUNNING for t in trials) success_num = sum(t.trial_status == Trial.TERMINATED for t in trials) failed_num = sum(t.trial_status == Trial.ERROR for t in trials) if total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) if len(jobs) == 0: resp = "Unkonwn job id %s.\n" % job_id else: job = jobs[0] result = { "job_id": job.job_id, "name": job.name, "user": job.user, "type": job.type, "start_time": job.start_time, "end_time": job.end_time, "success_trials": success_num, "failed_trials": failed_num, "running_trials": running_num, "total_trials": total_num, "best_trial_id": job.best_trial_id, "progress": progress } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
python
def query_job(request): """Rest API to query the job info, with the given job_id. The url pattern should be like this: curl http://<server>:<port>/query_job?job_id=<job_id> The response may be: { "running_trials": 0, "start_time": "2018-07-19 20:49:40", "current_round": 1, "failed_trials": 0, "best_trial_id": "2067R2ZD", "name": "asynchyperband_test", "job_id": "asynchyperband_test", "user": "Grady", "type": "RAY TUNE", "total_trials": 4, "end_time": "2018-07-19 20:50:10", "progress": 100, "success_trials": 4 } """ job_id = request.GET.get("job_id") jobs = JobRecord.objects.filter(job_id=job_id) trials = TrialRecord.objects.filter(job_id=job_id) total_num = len(trials) running_num = sum(t.trial_status == Trial.RUNNING for t in trials) success_num = sum(t.trial_status == Trial.TERMINATED for t in trials) failed_num = sum(t.trial_status == Trial.ERROR for t in trials) if total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) if len(jobs) == 0: resp = "Unkonwn job id %s.\n" % job_id else: job = jobs[0] result = { "job_id": job.job_id, "name": job.name, "user": job.user, "type": job.type, "start_time": job.start_time, "end_time": job.end_time, "success_trials": success_num, "failed_trials": failed_num, "running_trials": running_num, "total_trials": total_num, "best_trial_id": job.best_trial_id, "progress": progress } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
[ "def", "query_job", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "jobs", "=", "JobRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "job_id", ")", "trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "job_id", ")", "total_num", "=", "len", "(", "trials", ")", "running_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "RUNNING", "for", "t", "in", "trials", ")", "success_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "TERMINATED", "for", "t", "in", "trials", ")", "failed_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "ERROR", "for", "t", "in", "trials", ")", "if", "total_num", "==", "0", ":", "progress", "=", "0", "else", ":", "progress", "=", "int", "(", "float", "(", "success_num", ")", "/", "total_num", "*", "100", ")", "if", "len", "(", "jobs", ")", "==", "0", ":", "resp", "=", "\"Unkonwn job id %s.\\n\"", "%", "job_id", "else", ":", "job", "=", "jobs", "[", "0", "]", "result", "=", "{", "\"job_id\"", ":", "job", ".", "job_id", ",", "\"name\"", ":", "job", ".", "name", ",", "\"user\"", ":", "job", ".", "user", ",", "\"type\"", ":", "job", ".", "type", ",", "\"start_time\"", ":", "job", ".", "start_time", ",", "\"end_time\"", ":", "job", ".", "end_time", ",", "\"success_trials\"", ":", "success_num", ",", "\"failed_trials\"", ":", "failed_num", ",", "\"running_trials\"", ":", "running_num", ",", "\"total_trials\"", ":", "total_num", ",", "\"best_trial_id\"", ":", "job", ".", "best_trial_id", ",", "\"progress\"", ":", "progress", "}", "resp", "=", "json", ".", "dumps", "(", "result", ")", "return", "HttpResponse", "(", "resp", ",", "content_type", "=", "\"application/json;charset=utf-8\"", ")" ]
Rest API to query the job info, with the given job_id. The url pattern should be like this: curl http://<server>:<port>/query_job?job_id=<job_id> The response may be: { "running_trials": 0, "start_time": "2018-07-19 20:49:40", "current_round": 1, "failed_trials": 0, "best_trial_id": "2067R2ZD", "name": "asynchyperband_test", "job_id": "asynchyperband_test", "user": "Grady", "type": "RAY TUNE", "total_trials": 4, "end_time": "2018-07-19 20:50:10", "progress": 100, "success_trials": 4 }
[ "Rest", "API", "to", "query", "the", "job", "info", "with", "the", "given", "job_id", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/query.py#L14-L71
train
ray-project/ray
python/ray/tune/automlboard/frontend/query.py
query_trial
def query_trial(request): """Rest API to query the trial info, with the given trial_id. The url pattern should be like this: curl http://<server>:<port>/query_trial?trial_id=<trial_id> The response may be: { "app_url": "None", "trial_status": "TERMINATED", "params": {'a': 1, 'b': 2}, "job_id": "asynchyperband_test", "end_time": "2018-07-19 20:49:44", "start_time": "2018-07-19 20:49:40", "trial_id": "2067R2ZD", } """ trial_id = request.GET.get("trial_id") trials = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time") if len(trials) == 0: resp = "Unkonwn trial id %s.\n" % trials else: trial = trials[0] result = { "trial_id": trial.trial_id, "job_id": trial.job_id, "trial_status": trial.trial_status, "start_time": trial.start_time, "end_time": trial.end_time, "params": trial.params } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
python
def query_trial(request): """Rest API to query the trial info, with the given trial_id. The url pattern should be like this: curl http://<server>:<port>/query_trial?trial_id=<trial_id> The response may be: { "app_url": "None", "trial_status": "TERMINATED", "params": {'a': 1, 'b': 2}, "job_id": "asynchyperband_test", "end_time": "2018-07-19 20:49:44", "start_time": "2018-07-19 20:49:40", "trial_id": "2067R2ZD", } """ trial_id = request.GET.get("trial_id") trials = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time") if len(trials) == 0: resp = "Unkonwn trial id %s.\n" % trials else: trial = trials[0] result = { "trial_id": trial.trial_id, "job_id": trial.job_id, "trial_status": trial.trial_status, "start_time": trial.start_time, "end_time": trial.end_time, "params": trial.params } resp = json.dumps(result) return HttpResponse(resp, content_type="application/json;charset=utf-8")
[ "def", "query_trial", "(", "request", ")", ":", "trial_id", "=", "request", ".", "GET", ".", "get", "(", "\"trial_id\"", ")", "trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "trial_id", "=", "trial_id", ")", ".", "order_by", "(", "\"-start_time\"", ")", "if", "len", "(", "trials", ")", "==", "0", ":", "resp", "=", "\"Unkonwn trial id %s.\\n\"", "%", "trials", "else", ":", "trial", "=", "trials", "[", "0", "]", "result", "=", "{", "\"trial_id\"", ":", "trial", ".", "trial_id", ",", "\"job_id\"", ":", "trial", ".", "job_id", ",", "\"trial_status\"", ":", "trial", ".", "trial_status", ",", "\"start_time\"", ":", "trial", ".", "start_time", ",", "\"end_time\"", ":", "trial", ".", "end_time", ",", "\"params\"", ":", "trial", ".", "params", "}", "resp", "=", "json", ".", "dumps", "(", "result", ")", "return", "HttpResponse", "(", "resp", ",", "content_type", "=", "\"application/json;charset=utf-8\"", ")" ]
Rest API to query the trial info, with the given trial_id. The url pattern should be like this: curl http://<server>:<port>/query_trial?trial_id=<trial_id> The response may be: { "app_url": "None", "trial_status": "TERMINATED", "params": {'a': 1, 'b': 2}, "job_id": "asynchyperband_test", "end_time": "2018-07-19 20:49:44", "start_time": "2018-07-19 20:49:40", "trial_id": "2067R2ZD", }
[ "Rest", "API", "to", "query", "the", "trial", "info", "with", "the", "given", "trial_id", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/query.py#L74-L110
train
ray-project/ray
python/ray/tune/schedulers/median_stopping_rule.py
MedianStoppingRule.on_trial_result
def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`. """ if trial in self._stopped_trials: assert not self._hard_stop return TrialScheduler.CONTINUE # fall back to FIFO time = result[self._time_attr] self._results[trial].append(result) median_result = self._get_median_result(time) best_result = self._best_result(trial) if self._verbose: logger.info("Trial {} best res={} vs median res={} at t={}".format( trial, best_result, median_result, time)) if best_result < median_result and time > self._grace_period: if self._verbose: logger.info("MedianStoppingRule: " "early stopping {}".format(trial)) self._stopped_trials.add(trial) if self._hard_stop: return TrialScheduler.STOP else: return TrialScheduler.PAUSE else: return TrialScheduler.CONTINUE
python
def on_trial_result(self, trial_runner, trial, result): """Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`. """ if trial in self._stopped_trials: assert not self._hard_stop return TrialScheduler.CONTINUE # fall back to FIFO time = result[self._time_attr] self._results[trial].append(result) median_result = self._get_median_result(time) best_result = self._best_result(trial) if self._verbose: logger.info("Trial {} best res={} vs median res={} at t={}".format( trial, best_result, median_result, time)) if best_result < median_result and time > self._grace_period: if self._verbose: logger.info("MedianStoppingRule: " "early stopping {}".format(trial)) self._stopped_trials.add(trial) if self._hard_stop: return TrialScheduler.STOP else: return TrialScheduler.PAUSE else: return TrialScheduler.CONTINUE
[ "def", "on_trial_result", "(", "self", ",", "trial_runner", ",", "trial", ",", "result", ")", ":", "if", "trial", "in", "self", ".", "_stopped_trials", ":", "assert", "not", "self", ".", "_hard_stop", "return", "TrialScheduler", ".", "CONTINUE", "# fall back to FIFO", "time", "=", "result", "[", "self", ".", "_time_attr", "]", "self", ".", "_results", "[", "trial", "]", ".", "append", "(", "result", ")", "median_result", "=", "self", ".", "_get_median_result", "(", "time", ")", "best_result", "=", "self", ".", "_best_result", "(", "trial", ")", "if", "self", ".", "_verbose", ":", "logger", ".", "info", "(", "\"Trial {} best res={} vs median res={} at t={}\"", ".", "format", "(", "trial", ",", "best_result", ",", "median_result", ",", "time", ")", ")", "if", "best_result", "<", "median_result", "and", "time", ">", "self", ".", "_grace_period", ":", "if", "self", ".", "_verbose", ":", "logger", ".", "info", "(", "\"MedianStoppingRule: \"", "\"early stopping {}\"", ".", "format", "(", "trial", ")", ")", "self", ".", "_stopped_trials", ".", "add", "(", "trial", ")", "if", "self", ".", "_hard_stop", ":", "return", "TrialScheduler", ".", "STOP", "else", ":", "return", "TrialScheduler", ".", "PAUSE", "else", ":", "return", "TrialScheduler", ".", "CONTINUE" ]
Callback for early stopping. This stopping rule stops a running trial if the trial's best objective value by step `t` is strictly worse than the median of the running averages of all completed trials' objectives reported up to step `t`.
[ "Callback", "for", "early", "stopping", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/median_stopping_rule.py#L56-L85
train
ray-project/ray
python/ray/tune/schedulers/median_stopping_rule.py
MedianStoppingRule.on_trial_remove
def on_trial_remove(self, trial_runner, trial): """Marks trial as completed if it is paused and has previously ran.""" if trial.status is Trial.PAUSED and trial in self._results: self._completed_trials.add(trial)
python
def on_trial_remove(self, trial_runner, trial): """Marks trial as completed if it is paused and has previously ran.""" if trial.status is Trial.PAUSED and trial in self._results: self._completed_trials.add(trial)
[ "def", "on_trial_remove", "(", "self", ",", "trial_runner", ",", "trial", ")", ":", "if", "trial", ".", "status", "is", "Trial", ".", "PAUSED", "and", "trial", "in", "self", ".", "_results", ":", "self", ".", "_completed_trials", ".", "add", "(", "trial", ")" ]
Marks trial as completed if it is paused and has previously ran.
[ "Marks", "trial", "as", "completed", "if", "it", "is", "paused", "and", "has", "previously", "ran", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/median_stopping_rule.py#L91-L94
train
ray-project/ray
python/ray/tune/automlboard/models/models.py
JobRecord.from_json
def from_json(cls, json_info): """Build a Job instance from a json string.""" if json_info is None: return None return JobRecord( job_id=json_info["job_id"], name=json_info["job_name"], user=json_info["user"], type=json_info["type"], start_time=json_info["start_time"])
python
def from_json(cls, json_info): """Build a Job instance from a json string.""" if json_info is None: return None return JobRecord( job_id=json_info["job_id"], name=json_info["job_name"], user=json_info["user"], type=json_info["type"], start_time=json_info["start_time"])
[ "def", "from_json", "(", "cls", ",", "json_info", ")", ":", "if", "json_info", "is", "None", ":", "return", "None", "return", "JobRecord", "(", "job_id", "=", "json_info", "[", "\"job_id\"", "]", ",", "name", "=", "json_info", "[", "\"job_name\"", "]", ",", "user", "=", "json_info", "[", "\"user\"", "]", ",", "type", "=", "json_info", "[", "\"type\"", "]", ",", "start_time", "=", "json_info", "[", "\"start_time\"", "]", ")" ]
Build a Job instance from a json string.
[ "Build", "a", "Job", "instance", "from", "a", "json", "string", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L20-L29
train
ray-project/ray
python/ray/tune/automlboard/models/models.py
TrialRecord.from_json
def from_json(cls, json_info): """Build a Trial instance from a json string.""" if json_info is None: return None return TrialRecord( trial_id=json_info["trial_id"], job_id=json_info["job_id"], trial_status=json_info["status"], start_time=json_info["start_time"], params=json_info["params"])
python
def from_json(cls, json_info): """Build a Trial instance from a json string.""" if json_info is None: return None return TrialRecord( trial_id=json_info["trial_id"], job_id=json_info["job_id"], trial_status=json_info["status"], start_time=json_info["start_time"], params=json_info["params"])
[ "def", "from_json", "(", "cls", ",", "json_info", ")", ":", "if", "json_info", "is", "None", ":", "return", "None", "return", "TrialRecord", "(", "trial_id", "=", "json_info", "[", "\"trial_id\"", "]", ",", "job_id", "=", "json_info", "[", "\"job_id\"", "]", ",", "trial_status", "=", "json_info", "[", "\"status\"", "]", ",", "start_time", "=", "json_info", "[", "\"start_time\"", "]", ",", "params", "=", "json_info", "[", "\"params\"", "]", ")" ]
Build a Trial instance from a json string.
[ "Build", "a", "Trial", "instance", "from", "a", "json", "string", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L48-L57
train
ray-project/ray
python/ray/tune/automlboard/models/models.py
ResultRecord.from_json
def from_json(cls, json_info): """Build a Result instance from a json string.""" if json_info is None: return None return ResultRecord( trial_id=json_info["trial_id"], timesteps_total=json_info["timesteps_total"], done=json_info.get("done", None), episode_reward_mean=json_info.get("episode_reward_mean", None), mean_accuracy=json_info.get("mean_accuracy", None), mean_loss=json_info.get("mean_loss", None), trainning_iteration=json_info.get("training_iteration", None), timesteps_this_iter=json_info.get("timesteps_this_iter", None), time_this_iter_s=json_info.get("time_this_iter_s", None), time_total_s=json_info.get("time_total_s", None), date=json_info.get("date", None), hostname=json_info.get("hostname", None), node_ip=json_info.get("node_ip", None), config=json_info.get("config", None))
python
def from_json(cls, json_info): """Build a Result instance from a json string.""" if json_info is None: return None return ResultRecord( trial_id=json_info["trial_id"], timesteps_total=json_info["timesteps_total"], done=json_info.get("done", None), episode_reward_mean=json_info.get("episode_reward_mean", None), mean_accuracy=json_info.get("mean_accuracy", None), mean_loss=json_info.get("mean_loss", None), trainning_iteration=json_info.get("training_iteration", None), timesteps_this_iter=json_info.get("timesteps_this_iter", None), time_this_iter_s=json_info.get("time_this_iter_s", None), time_total_s=json_info.get("time_total_s", None), date=json_info.get("date", None), hostname=json_info.get("hostname", None), node_ip=json_info.get("node_ip", None), config=json_info.get("config", None))
[ "def", "from_json", "(", "cls", ",", "json_info", ")", ":", "if", "json_info", "is", "None", ":", "return", "None", "return", "ResultRecord", "(", "trial_id", "=", "json_info", "[", "\"trial_id\"", "]", ",", "timesteps_total", "=", "json_info", "[", "\"timesteps_total\"", "]", ",", "done", "=", "json_info", ".", "get", "(", "\"done\"", ",", "None", ")", ",", "episode_reward_mean", "=", "json_info", ".", "get", "(", "\"episode_reward_mean\"", ",", "None", ")", ",", "mean_accuracy", "=", "json_info", ".", "get", "(", "\"mean_accuracy\"", ",", "None", ")", ",", "mean_loss", "=", "json_info", ".", "get", "(", "\"mean_loss\"", ",", "None", ")", ",", "trainning_iteration", "=", "json_info", ".", "get", "(", "\"training_iteration\"", ",", "None", ")", ",", "timesteps_this_iter", "=", "json_info", ".", "get", "(", "\"timesteps_this_iter\"", ",", "None", ")", ",", "time_this_iter_s", "=", "json_info", ".", "get", "(", "\"time_this_iter_s\"", ",", "None", ")", ",", "time_total_s", "=", "json_info", ".", "get", "(", "\"time_total_s\"", ",", "None", ")", ",", "date", "=", "json_info", ".", "get", "(", "\"date\"", ",", "None", ")", ",", "hostname", "=", "json_info", ".", "get", "(", "\"hostname\"", ",", "None", ")", ",", "node_ip", "=", "json_info", ".", "get", "(", "\"node_ip\"", ",", "None", ")", ",", "config", "=", "json_info", ".", "get", "(", "\"config\"", ",", "None", ")", ")" ]
Build a Result instance from a json string.
[ "Build", "a", "Result", "instance", "from", "a", "json", "string", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/models/models.py#L80-L98
train
ray-project/ray
python/ray/rllib/evaluation/postprocessing.py
compute_advantages
def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True): """Given a rollout, compute its value targets and the advantage. Args: rollout (SampleBatch): SampleBatch of a single trajectory last_r (float): Value estimation for last observation gamma (float): Discount factor. lambda_ (float): Parameter for GAE use_gae (bool): Using Generalized Advantage Estamation Returns: SampleBatch (SampleBatch): Object with experience from rollout and processed rewards. """ traj = {} trajsize = len(rollout[SampleBatch.ACTIONS]) for key in rollout: traj[key] = np.stack(rollout[key]) if use_gae: assert SampleBatch.VF_PREDS in rollout, "Values not found!" vpred_t = np.concatenate( [rollout[SampleBatch.VF_PREDS], np.array([last_r])]) delta_t = ( traj[SampleBatch.REWARDS] + gamma * vpred_t[1:] - vpred_t[:-1]) # This formula for the advantage comes # "Generalized Advantage Estimation": https://arxiv.org/abs/1506.02438 traj[Postprocessing.ADVANTAGES] = discount(delta_t, gamma * lambda_) traj[Postprocessing.VALUE_TARGETS] = ( traj[Postprocessing.ADVANTAGES] + traj[SampleBatch.VF_PREDS]).copy().astype(np.float32) else: rewards_plus_v = np.concatenate( [rollout[SampleBatch.REWARDS], np.array([last_r])]) traj[Postprocessing.ADVANTAGES] = discount(rewards_plus_v, gamma)[:-1] # TODO(ekl): support using a critic without GAE traj[Postprocessing.VALUE_TARGETS] = np.zeros_like( traj[Postprocessing.ADVANTAGES]) traj[Postprocessing.ADVANTAGES] = traj[ Postprocessing.ADVANTAGES].copy().astype(np.float32) assert all(val.shape[0] == trajsize for val in traj.values()), \ "Rollout stacked incorrectly!" return SampleBatch(traj)
python
def compute_advantages(rollout, last_r, gamma=0.9, lambda_=1.0, use_gae=True): """Given a rollout, compute its value targets and the advantage. Args: rollout (SampleBatch): SampleBatch of a single trajectory last_r (float): Value estimation for last observation gamma (float): Discount factor. lambda_ (float): Parameter for GAE use_gae (bool): Using Generalized Advantage Estamation Returns: SampleBatch (SampleBatch): Object with experience from rollout and processed rewards. """ traj = {} trajsize = len(rollout[SampleBatch.ACTIONS]) for key in rollout: traj[key] = np.stack(rollout[key]) if use_gae: assert SampleBatch.VF_PREDS in rollout, "Values not found!" vpred_t = np.concatenate( [rollout[SampleBatch.VF_PREDS], np.array([last_r])]) delta_t = ( traj[SampleBatch.REWARDS] + gamma * vpred_t[1:] - vpred_t[:-1]) # This formula for the advantage comes # "Generalized Advantage Estimation": https://arxiv.org/abs/1506.02438 traj[Postprocessing.ADVANTAGES] = discount(delta_t, gamma * lambda_) traj[Postprocessing.VALUE_TARGETS] = ( traj[Postprocessing.ADVANTAGES] + traj[SampleBatch.VF_PREDS]).copy().astype(np.float32) else: rewards_plus_v = np.concatenate( [rollout[SampleBatch.REWARDS], np.array([last_r])]) traj[Postprocessing.ADVANTAGES] = discount(rewards_plus_v, gamma)[:-1] # TODO(ekl): support using a critic without GAE traj[Postprocessing.VALUE_TARGETS] = np.zeros_like( traj[Postprocessing.ADVANTAGES]) traj[Postprocessing.ADVANTAGES] = traj[ Postprocessing.ADVANTAGES].copy().astype(np.float32) assert all(val.shape[0] == trajsize for val in traj.values()), \ "Rollout stacked incorrectly!" return SampleBatch(traj)
[ "def", "compute_advantages", "(", "rollout", ",", "last_r", ",", "gamma", "=", "0.9", ",", "lambda_", "=", "1.0", ",", "use_gae", "=", "True", ")", ":", "traj", "=", "{", "}", "trajsize", "=", "len", "(", "rollout", "[", "SampleBatch", ".", "ACTIONS", "]", ")", "for", "key", "in", "rollout", ":", "traj", "[", "key", "]", "=", "np", ".", "stack", "(", "rollout", "[", "key", "]", ")", "if", "use_gae", ":", "assert", "SampleBatch", ".", "VF_PREDS", "in", "rollout", ",", "\"Values not found!\"", "vpred_t", "=", "np", ".", "concatenate", "(", "[", "rollout", "[", "SampleBatch", ".", "VF_PREDS", "]", ",", "np", ".", "array", "(", "[", "last_r", "]", ")", "]", ")", "delta_t", "=", "(", "traj", "[", "SampleBatch", ".", "REWARDS", "]", "+", "gamma", "*", "vpred_t", "[", "1", ":", "]", "-", "vpred_t", "[", ":", "-", "1", "]", ")", "# This formula for the advantage comes", "# \"Generalized Advantage Estimation\": https://arxiv.org/abs/1506.02438", "traj", "[", "Postprocessing", ".", "ADVANTAGES", "]", "=", "discount", "(", "delta_t", ",", "gamma", "*", "lambda_", ")", "traj", "[", "Postprocessing", ".", "VALUE_TARGETS", "]", "=", "(", "traj", "[", "Postprocessing", ".", "ADVANTAGES", "]", "+", "traj", "[", "SampleBatch", ".", "VF_PREDS", "]", ")", ".", "copy", "(", ")", ".", "astype", "(", "np", ".", "float32", ")", "else", ":", "rewards_plus_v", "=", "np", ".", "concatenate", "(", "[", "rollout", "[", "SampleBatch", ".", "REWARDS", "]", ",", "np", ".", "array", "(", "[", "last_r", "]", ")", "]", ")", "traj", "[", "Postprocessing", ".", "ADVANTAGES", "]", "=", "discount", "(", "rewards_plus_v", ",", "gamma", ")", "[", ":", "-", "1", "]", "# TODO(ekl): support using a critic without GAE", "traj", "[", "Postprocessing", ".", "VALUE_TARGETS", "]", "=", "np", ".", "zeros_like", "(", "traj", "[", "Postprocessing", ".", "ADVANTAGES", "]", ")", "traj", "[", "Postprocessing", ".", "ADVANTAGES", "]", "=", "traj", "[", "Postprocessing", ".", "ADVANTAGES", "]", ".", "copy", "(", ")", ".", "astype", "(", "np", ".", "float32", ")", "assert", "all", "(", "val", ".", "shape", "[", "0", "]", "==", "trajsize", "for", "val", "in", "traj", ".", "values", "(", ")", ")", ",", "\"Rollout stacked incorrectly!\"", "return", "SampleBatch", "(", "traj", ")" ]
Given a rollout, compute its value targets and the advantage. Args: rollout (SampleBatch): SampleBatch of a single trajectory last_r (float): Value estimation for last observation gamma (float): Discount factor. lambda_ (float): Parameter for GAE use_gae (bool): Using Generalized Advantage Estamation Returns: SampleBatch (SampleBatch): Object with experience from rollout and processed rewards.
[ "Given", "a", "rollout", "compute", "its", "value", "targets", "and", "the", "advantage", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/postprocessing.py#L23-L70
train
ray-project/ray
python/ray/monitor.py
Monitor.xray_heartbeat_batch_handler
def xray_heartbeat_batch_handler(self, unused_channel, data): """Handle an xray heartbeat batch message from Redis.""" gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) heartbeat_data = gcs_entries.Entries(0) message = (ray.gcs_utils.HeartbeatBatchTableData. GetRootAsHeartbeatBatchTableData(heartbeat_data, 0)) for j in range(message.BatchLength()): heartbeat_message = message.Batch(j) num_resources = heartbeat_message.ResourcesAvailableLabelLength() static_resources = {} dynamic_resources = {} for i in range(num_resources): dyn = heartbeat_message.ResourcesAvailableLabel(i) static = heartbeat_message.ResourcesTotalLabel(i) dynamic_resources[dyn] = ( heartbeat_message.ResourcesAvailableCapacity(i)) static_resources[static] = ( heartbeat_message.ResourcesTotalCapacity(i)) # Update the load metrics for this raylet. client_id = ray.utils.binary_to_hex(heartbeat_message.ClientId()) ip = self.raylet_id_to_ip_map.get(client_id) if ip: self.load_metrics.update(ip, static_resources, dynamic_resources) else: logger.warning( "Monitor: " "could not find ip for client {}".format(client_id))
python
def xray_heartbeat_batch_handler(self, unused_channel, data): """Handle an xray heartbeat batch message from Redis.""" gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) heartbeat_data = gcs_entries.Entries(0) message = (ray.gcs_utils.HeartbeatBatchTableData. GetRootAsHeartbeatBatchTableData(heartbeat_data, 0)) for j in range(message.BatchLength()): heartbeat_message = message.Batch(j) num_resources = heartbeat_message.ResourcesAvailableLabelLength() static_resources = {} dynamic_resources = {} for i in range(num_resources): dyn = heartbeat_message.ResourcesAvailableLabel(i) static = heartbeat_message.ResourcesTotalLabel(i) dynamic_resources[dyn] = ( heartbeat_message.ResourcesAvailableCapacity(i)) static_resources[static] = ( heartbeat_message.ResourcesTotalCapacity(i)) # Update the load metrics for this raylet. client_id = ray.utils.binary_to_hex(heartbeat_message.ClientId()) ip = self.raylet_id_to_ip_map.get(client_id) if ip: self.load_metrics.update(ip, static_resources, dynamic_resources) else: logger.warning( "Monitor: " "could not find ip for client {}".format(client_id))
[ "def", "xray_heartbeat_batch_handler", "(", "self", ",", "unused_channel", ",", "data", ")", ":", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "data", ",", "0", ")", "heartbeat_data", "=", "gcs_entries", ".", "Entries", "(", "0", ")", "message", "=", "(", "ray", ".", "gcs_utils", ".", "HeartbeatBatchTableData", ".", "GetRootAsHeartbeatBatchTableData", "(", "heartbeat_data", ",", "0", ")", ")", "for", "j", "in", "range", "(", "message", ".", "BatchLength", "(", ")", ")", ":", "heartbeat_message", "=", "message", ".", "Batch", "(", "j", ")", "num_resources", "=", "heartbeat_message", ".", "ResourcesAvailableLabelLength", "(", ")", "static_resources", "=", "{", "}", "dynamic_resources", "=", "{", "}", "for", "i", "in", "range", "(", "num_resources", ")", ":", "dyn", "=", "heartbeat_message", ".", "ResourcesAvailableLabel", "(", "i", ")", "static", "=", "heartbeat_message", ".", "ResourcesTotalLabel", "(", "i", ")", "dynamic_resources", "[", "dyn", "]", "=", "(", "heartbeat_message", ".", "ResourcesAvailableCapacity", "(", "i", ")", ")", "static_resources", "[", "static", "]", "=", "(", "heartbeat_message", ".", "ResourcesTotalCapacity", "(", "i", ")", ")", "# Update the load metrics for this raylet.", "client_id", "=", "ray", ".", "utils", ".", "binary_to_hex", "(", "heartbeat_message", ".", "ClientId", "(", ")", ")", "ip", "=", "self", ".", "raylet_id_to_ip_map", ".", "get", "(", "client_id", ")", "if", "ip", ":", "self", ".", "load_metrics", ".", "update", "(", "ip", ",", "static_resources", ",", "dynamic_resources", ")", "else", ":", "logger", ".", "warning", "(", "\"Monitor: \"", "\"could not find ip for client {}\"", ".", "format", "(", "client_id", ")", ")" ]
Handle an xray heartbeat batch message from Redis.
[ "Handle", "an", "xray", "heartbeat", "batch", "message", "from", "Redis", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L102-L135
train
ray-project/ray
python/ray/monitor.py
Monitor._xray_clean_up_entries_for_driver
def _xray_clean_up_entries_for_driver(self, driver_id): """Remove this driver's object/task entries from redis. Removes control-state entries of all tasks and task return objects belonging to the driver. Args: driver_id: The driver id. """ xray_task_table_prefix = ( ray.gcs_utils.TablePrefix_RAYLET_TASK_string.encode("ascii")) xray_object_table_prefix = ( ray.gcs_utils.TablePrefix_OBJECT_string.encode("ascii")) task_table_objects = self.state.task_table() driver_id_hex = binary_to_hex(driver_id) driver_task_id_bins = set() for task_id_hex, task_info in task_table_objects.items(): task_table_object = task_info["TaskSpec"] task_driver_id_hex = task_table_object["DriverID"] if driver_id_hex != task_driver_id_hex: # Ignore tasks that aren't from this driver. continue driver_task_id_bins.add(hex_to_binary(task_id_hex)) # Get objects associated with the driver. object_table_objects = self.state.object_table() driver_object_id_bins = set() for object_id, _ in object_table_objects.items(): task_id_bin = ray._raylet.compute_task_id(object_id).binary() if task_id_bin in driver_task_id_bins: driver_object_id_bins.add(object_id.binary()) def to_shard_index(id_bin): return binary_to_object_id(id_bin).redis_shard_hash() % len( self.state.redis_clients) # Form the redis keys to delete. sharded_keys = [[] for _ in range(len(self.state.redis_clients))] for task_id_bin in driver_task_id_bins: sharded_keys[to_shard_index(task_id_bin)].append( xray_task_table_prefix + task_id_bin) for object_id_bin in driver_object_id_bins: sharded_keys[to_shard_index(object_id_bin)].append( xray_object_table_prefix + object_id_bin) # Remove with best effort. for shard_index in range(len(sharded_keys)): keys = sharded_keys[shard_index] if len(keys) == 0: continue redis = self.state.redis_clients[shard_index] num_deleted = redis.delete(*keys) logger.info("Monitor: " "Removed {} dead redis entries of the " "driver from redis shard {}.".format( num_deleted, shard_index)) if num_deleted != len(keys): logger.warning("Monitor: " "Failed to remove {} relevant redis " "entries from redis shard {}.".format( len(keys) - num_deleted, shard_index))
python
def _xray_clean_up_entries_for_driver(self, driver_id): """Remove this driver's object/task entries from redis. Removes control-state entries of all tasks and task return objects belonging to the driver. Args: driver_id: The driver id. """ xray_task_table_prefix = ( ray.gcs_utils.TablePrefix_RAYLET_TASK_string.encode("ascii")) xray_object_table_prefix = ( ray.gcs_utils.TablePrefix_OBJECT_string.encode("ascii")) task_table_objects = self.state.task_table() driver_id_hex = binary_to_hex(driver_id) driver_task_id_bins = set() for task_id_hex, task_info in task_table_objects.items(): task_table_object = task_info["TaskSpec"] task_driver_id_hex = task_table_object["DriverID"] if driver_id_hex != task_driver_id_hex: # Ignore tasks that aren't from this driver. continue driver_task_id_bins.add(hex_to_binary(task_id_hex)) # Get objects associated with the driver. object_table_objects = self.state.object_table() driver_object_id_bins = set() for object_id, _ in object_table_objects.items(): task_id_bin = ray._raylet.compute_task_id(object_id).binary() if task_id_bin in driver_task_id_bins: driver_object_id_bins.add(object_id.binary()) def to_shard_index(id_bin): return binary_to_object_id(id_bin).redis_shard_hash() % len( self.state.redis_clients) # Form the redis keys to delete. sharded_keys = [[] for _ in range(len(self.state.redis_clients))] for task_id_bin in driver_task_id_bins: sharded_keys[to_shard_index(task_id_bin)].append( xray_task_table_prefix + task_id_bin) for object_id_bin in driver_object_id_bins: sharded_keys[to_shard_index(object_id_bin)].append( xray_object_table_prefix + object_id_bin) # Remove with best effort. for shard_index in range(len(sharded_keys)): keys = sharded_keys[shard_index] if len(keys) == 0: continue redis = self.state.redis_clients[shard_index] num_deleted = redis.delete(*keys) logger.info("Monitor: " "Removed {} dead redis entries of the " "driver from redis shard {}.".format( num_deleted, shard_index)) if num_deleted != len(keys): logger.warning("Monitor: " "Failed to remove {} relevant redis " "entries from redis shard {}.".format( len(keys) - num_deleted, shard_index))
[ "def", "_xray_clean_up_entries_for_driver", "(", "self", ",", "driver_id", ")", ":", "xray_task_table_prefix", "=", "(", "ray", ".", "gcs_utils", ".", "TablePrefix_RAYLET_TASK_string", ".", "encode", "(", "\"ascii\"", ")", ")", "xray_object_table_prefix", "=", "(", "ray", ".", "gcs_utils", ".", "TablePrefix_OBJECT_string", ".", "encode", "(", "\"ascii\"", ")", ")", "task_table_objects", "=", "self", ".", "state", ".", "task_table", "(", ")", "driver_id_hex", "=", "binary_to_hex", "(", "driver_id", ")", "driver_task_id_bins", "=", "set", "(", ")", "for", "task_id_hex", ",", "task_info", "in", "task_table_objects", ".", "items", "(", ")", ":", "task_table_object", "=", "task_info", "[", "\"TaskSpec\"", "]", "task_driver_id_hex", "=", "task_table_object", "[", "\"DriverID\"", "]", "if", "driver_id_hex", "!=", "task_driver_id_hex", ":", "# Ignore tasks that aren't from this driver.", "continue", "driver_task_id_bins", ".", "add", "(", "hex_to_binary", "(", "task_id_hex", ")", ")", "# Get objects associated with the driver.", "object_table_objects", "=", "self", ".", "state", ".", "object_table", "(", ")", "driver_object_id_bins", "=", "set", "(", ")", "for", "object_id", ",", "_", "in", "object_table_objects", ".", "items", "(", ")", ":", "task_id_bin", "=", "ray", ".", "_raylet", ".", "compute_task_id", "(", "object_id", ")", ".", "binary", "(", ")", "if", "task_id_bin", "in", "driver_task_id_bins", ":", "driver_object_id_bins", ".", "add", "(", "object_id", ".", "binary", "(", ")", ")", "def", "to_shard_index", "(", "id_bin", ")", ":", "return", "binary_to_object_id", "(", "id_bin", ")", ".", "redis_shard_hash", "(", ")", "%", "len", "(", "self", ".", "state", ".", "redis_clients", ")", "# Form the redis keys to delete.", "sharded_keys", "=", "[", "[", "]", "for", "_", "in", "range", "(", "len", "(", "self", ".", "state", ".", "redis_clients", ")", ")", "]", "for", "task_id_bin", "in", "driver_task_id_bins", ":", "sharded_keys", "[", "to_shard_index", "(", "task_id_bin", ")", "]", ".", "append", "(", "xray_task_table_prefix", "+", "task_id_bin", ")", "for", "object_id_bin", "in", "driver_object_id_bins", ":", "sharded_keys", "[", "to_shard_index", "(", "object_id_bin", ")", "]", ".", "append", "(", "xray_object_table_prefix", "+", "object_id_bin", ")", "# Remove with best effort.", "for", "shard_index", "in", "range", "(", "len", "(", "sharded_keys", ")", ")", ":", "keys", "=", "sharded_keys", "[", "shard_index", "]", "if", "len", "(", "keys", ")", "==", "0", ":", "continue", "redis", "=", "self", ".", "state", ".", "redis_clients", "[", "shard_index", "]", "num_deleted", "=", "redis", ".", "delete", "(", "*", "keys", ")", "logger", ".", "info", "(", "\"Monitor: \"", "\"Removed {} dead redis entries of the \"", "\"driver from redis shard {}.\"", ".", "format", "(", "num_deleted", ",", "shard_index", ")", ")", "if", "num_deleted", "!=", "len", "(", "keys", ")", ":", "logger", ".", "warning", "(", "\"Monitor: \"", "\"Failed to remove {} relevant redis \"", "\"entries from redis shard {}.\"", ".", "format", "(", "len", "(", "keys", ")", "-", "num_deleted", ",", "shard_index", ")", ")" ]
Remove this driver's object/task entries from redis. Removes control-state entries of all tasks and task return objects belonging to the driver. Args: driver_id: The driver id.
[ "Remove", "this", "driver", "s", "object", "/", "task", "entries", "from", "redis", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L137-L199
train
ray-project/ray
python/ray/monitor.py
Monitor.xray_driver_removed_handler
def xray_driver_removed_handler(self, unused_channel, data): """Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data. """ gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) driver_data = gcs_entries.Entries(0) message = ray.gcs_utils.DriverTableData.GetRootAsDriverTableData( driver_data, 0) driver_id = message.DriverId() logger.info("Monitor: " "XRay Driver {} has been removed.".format( binary_to_hex(driver_id))) self._xray_clean_up_entries_for_driver(driver_id)
python
def xray_driver_removed_handler(self, unused_channel, data): """Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data. """ gcs_entries = ray.gcs_utils.GcsTableEntry.GetRootAsGcsTableEntry( data, 0) driver_data = gcs_entries.Entries(0) message = ray.gcs_utils.DriverTableData.GetRootAsDriverTableData( driver_data, 0) driver_id = message.DriverId() logger.info("Monitor: " "XRay Driver {} has been removed.".format( binary_to_hex(driver_id))) self._xray_clean_up_entries_for_driver(driver_id)
[ "def", "xray_driver_removed_handler", "(", "self", ",", "unused_channel", ",", "data", ")", ":", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "data", ",", "0", ")", "driver_data", "=", "gcs_entries", ".", "Entries", "(", "0", ")", "message", "=", "ray", ".", "gcs_utils", ".", "DriverTableData", ".", "GetRootAsDriverTableData", "(", "driver_data", ",", "0", ")", "driver_id", "=", "message", ".", "DriverId", "(", ")", "logger", ".", "info", "(", "\"Monitor: \"", "\"XRay Driver {} has been removed.\"", ".", "format", "(", "binary_to_hex", "(", "driver_id", ")", ")", ")", "self", ".", "_xray_clean_up_entries_for_driver", "(", "driver_id", ")" ]
Handle a notification that a driver has been removed. Args: unused_channel: The message channel. data: The message data.
[ "Handle", "a", "notification", "that", "a", "driver", "has", "been", "removed", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L201-L217
train
ray-project/ray
python/ray/monitor.py
Monitor.process_messages
def process_messages(self, max_messages=10000): """Process all messages ready in the subscription channels. This reads messages from the subscription channels and calls the appropriate handlers until there are no messages left. Args: max_messages: The maximum number of messages to process before returning. """ subscribe_clients = [self.primary_subscribe_client] for subscribe_client in subscribe_clients: for _ in range(max_messages): message = subscribe_client.get_message() if message is None: # Continue on to the next subscribe client. break # Parse the message. channel = message["channel"] data = message["data"] # Determine the appropriate message handler. if channel == ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL: # Similar functionality as raylet info channel message_handler = self.xray_heartbeat_batch_handler elif channel == ray.gcs_utils.XRAY_DRIVER_CHANNEL: # Handles driver death. message_handler = self.xray_driver_removed_handler else: raise Exception("This code should be unreachable.") # Call the handler. message_handler(channel, data)
python
def process_messages(self, max_messages=10000): """Process all messages ready in the subscription channels. This reads messages from the subscription channels and calls the appropriate handlers until there are no messages left. Args: max_messages: The maximum number of messages to process before returning. """ subscribe_clients = [self.primary_subscribe_client] for subscribe_client in subscribe_clients: for _ in range(max_messages): message = subscribe_client.get_message() if message is None: # Continue on to the next subscribe client. break # Parse the message. channel = message["channel"] data = message["data"] # Determine the appropriate message handler. if channel == ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL: # Similar functionality as raylet info channel message_handler = self.xray_heartbeat_batch_handler elif channel == ray.gcs_utils.XRAY_DRIVER_CHANNEL: # Handles driver death. message_handler = self.xray_driver_removed_handler else: raise Exception("This code should be unreachable.") # Call the handler. message_handler(channel, data)
[ "def", "process_messages", "(", "self", ",", "max_messages", "=", "10000", ")", ":", "subscribe_clients", "=", "[", "self", ".", "primary_subscribe_client", "]", "for", "subscribe_client", "in", "subscribe_clients", ":", "for", "_", "in", "range", "(", "max_messages", ")", ":", "message", "=", "subscribe_client", ".", "get_message", "(", ")", "if", "message", "is", "None", ":", "# Continue on to the next subscribe client.", "break", "# Parse the message.", "channel", "=", "message", "[", "\"channel\"", "]", "data", "=", "message", "[", "\"data\"", "]", "# Determine the appropriate message handler.", "if", "channel", "==", "ray", ".", "gcs_utils", ".", "XRAY_HEARTBEAT_BATCH_CHANNEL", ":", "# Similar functionality as raylet info channel", "message_handler", "=", "self", ".", "xray_heartbeat_batch_handler", "elif", "channel", "==", "ray", ".", "gcs_utils", ".", "XRAY_DRIVER_CHANNEL", ":", "# Handles driver death.", "message_handler", "=", "self", ".", "xray_driver_removed_handler", "else", ":", "raise", "Exception", "(", "\"This code should be unreachable.\"", ")", "# Call the handler.", "message_handler", "(", "channel", ",", "data", ")" ]
Process all messages ready in the subscription channels. This reads messages from the subscription channels and calls the appropriate handlers until there are no messages left. Args: max_messages: The maximum number of messages to process before returning.
[ "Process", "all", "messages", "ready", "in", "the", "subscription", "channels", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L219-L252
train
ray-project/ray
python/ray/monitor.py
Monitor._maybe_flush_gcs
def _maybe_flush_gcs(self): """Experimental: issue a flush request to the GCS. The purpose of this feature is to control GCS memory usage. To activate this feature, Ray must be compiled with the flag RAY_USE_NEW_GCS set, and Ray must be started at run time with the flag as well. """ if not self.issue_gcs_flushes: return if self.gcs_flush_policy is None: serialized = self.redis.get("gcs_flushing_policy") if serialized is None: # Client has not set any policy; by default flushing is off. return self.gcs_flush_policy = pickle.loads(serialized) if not self.gcs_flush_policy.should_flush(self.redis_shard): return max_entries_to_flush = self.gcs_flush_policy.num_entries_to_flush() num_flushed = self.redis_shard.execute_command( "HEAD.FLUSH {}".format(max_entries_to_flush)) logger.info("Monitor: num_flushed {}".format(num_flushed)) # This flushes event log and log files. ray.experimental.flush_redis_unsafe(self.redis) self.gcs_flush_policy.record_flush()
python
def _maybe_flush_gcs(self): """Experimental: issue a flush request to the GCS. The purpose of this feature is to control GCS memory usage. To activate this feature, Ray must be compiled with the flag RAY_USE_NEW_GCS set, and Ray must be started at run time with the flag as well. """ if not self.issue_gcs_flushes: return if self.gcs_flush_policy is None: serialized = self.redis.get("gcs_flushing_policy") if serialized is None: # Client has not set any policy; by default flushing is off. return self.gcs_flush_policy = pickle.loads(serialized) if not self.gcs_flush_policy.should_flush(self.redis_shard): return max_entries_to_flush = self.gcs_flush_policy.num_entries_to_flush() num_flushed = self.redis_shard.execute_command( "HEAD.FLUSH {}".format(max_entries_to_flush)) logger.info("Monitor: num_flushed {}".format(num_flushed)) # This flushes event log and log files. ray.experimental.flush_redis_unsafe(self.redis) self.gcs_flush_policy.record_flush()
[ "def", "_maybe_flush_gcs", "(", "self", ")", ":", "if", "not", "self", ".", "issue_gcs_flushes", ":", "return", "if", "self", ".", "gcs_flush_policy", "is", "None", ":", "serialized", "=", "self", ".", "redis", ".", "get", "(", "\"gcs_flushing_policy\"", ")", "if", "serialized", "is", "None", ":", "# Client has not set any policy; by default flushing is off.", "return", "self", ".", "gcs_flush_policy", "=", "pickle", ".", "loads", "(", "serialized", ")", "if", "not", "self", ".", "gcs_flush_policy", ".", "should_flush", "(", "self", ".", "redis_shard", ")", ":", "return", "max_entries_to_flush", "=", "self", ".", "gcs_flush_policy", ".", "num_entries_to_flush", "(", ")", "num_flushed", "=", "self", ".", "redis_shard", ".", "execute_command", "(", "\"HEAD.FLUSH {}\"", ".", "format", "(", "max_entries_to_flush", ")", ")", "logger", ".", "info", "(", "\"Monitor: num_flushed {}\"", ".", "format", "(", "num_flushed", ")", ")", "# This flushes event log and log files.", "ray", ".", "experimental", ".", "flush_redis_unsafe", "(", "self", ".", "redis", ")", "self", ".", "gcs_flush_policy", ".", "record_flush", "(", ")" ]
Experimental: issue a flush request to the GCS. The purpose of this feature is to control GCS memory usage. To activate this feature, Ray must be compiled with the flag RAY_USE_NEW_GCS set, and Ray must be started at run time with the flag as well.
[ "Experimental", ":", "issue", "a", "flush", "request", "to", "the", "GCS", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L264-L293
train
ray-project/ray
python/ray/monitor.py
Monitor.run
def run(self): """Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly. """ # Initialize the subscription channel. self.subscribe(ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL) self.subscribe(ray.gcs_utils.XRAY_DRIVER_CHANNEL) # TODO(rkn): If there were any dead clients at startup, we should clean # up the associated state in the state tables. # Handle messages from the subscription channels. while True: # Update the mapping from raylet client ID to IP address. # This is only used to update the load metrics for the autoscaler. self.update_raylet_map() # Process autoscaling actions if self.autoscaler: self.autoscaler.update() self._maybe_flush_gcs() # Process a round of messages. self.process_messages() # Wait for a heartbeat interval before processing the next round of # messages. time.sleep(ray._config.heartbeat_timeout_milliseconds() * 1e-3)
python
def run(self): """Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly. """ # Initialize the subscription channel. self.subscribe(ray.gcs_utils.XRAY_HEARTBEAT_BATCH_CHANNEL) self.subscribe(ray.gcs_utils.XRAY_DRIVER_CHANNEL) # TODO(rkn): If there were any dead clients at startup, we should clean # up the associated state in the state tables. # Handle messages from the subscription channels. while True: # Update the mapping from raylet client ID to IP address. # This is only used to update the load metrics for the autoscaler. self.update_raylet_map() # Process autoscaling actions if self.autoscaler: self.autoscaler.update() self._maybe_flush_gcs() # Process a round of messages. self.process_messages() # Wait for a heartbeat interval before processing the next round of # messages. time.sleep(ray._config.heartbeat_timeout_milliseconds() * 1e-3)
[ "def", "run", "(", "self", ")", ":", "# Initialize the subscription channel.", "self", ".", "subscribe", "(", "ray", ".", "gcs_utils", ".", "XRAY_HEARTBEAT_BATCH_CHANNEL", ")", "self", ".", "subscribe", "(", "ray", ".", "gcs_utils", ".", "XRAY_DRIVER_CHANNEL", ")", "# TODO(rkn): If there were any dead clients at startup, we should clean", "# up the associated state in the state tables.", "# Handle messages from the subscription channels.", "while", "True", ":", "# Update the mapping from raylet client ID to IP address.", "# This is only used to update the load metrics for the autoscaler.", "self", ".", "update_raylet_map", "(", ")", "# Process autoscaling actions", "if", "self", ".", "autoscaler", ":", "self", ".", "autoscaler", ".", "update", "(", ")", "self", ".", "_maybe_flush_gcs", "(", ")", "# Process a round of messages.", "self", ".", "process_messages", "(", ")", "# Wait for a heartbeat interval before processing the next round of", "# messages.", "time", ".", "sleep", "(", "ray", ".", "_config", ".", "heartbeat_timeout_milliseconds", "(", ")", "*", "1e-3", ")" ]
Run the monitor. This function loops forever, checking for messages about dead database clients and cleaning up state accordingly.
[ "Run", "the", "monitor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/monitor.py#L295-L325
train
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
index
def index(request): """View for the home page.""" recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects.order_by("-start_time")[0:500] total_num = len(recent_trials) running_num = sum(t.trial_status == Trial.RUNNING for t in recent_trials) success_num = sum( t.trial_status == Trial.TERMINATED for t in recent_trials) failed_num = sum(t.trial_status == Trial.ERROR for t in recent_trials) job_records = [] for recent_job in recent_jobs: job_records.append(get_job_info(recent_job)) context = { "log_dir": AUTOMLBOARD_LOG_DIR, "reload_interval": AUTOMLBOARD_RELOAD_INTERVAL, "recent_jobs": job_records, "job_num": len(job_records), "trial_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num } return render(request, "index.html", context)
python
def index(request): """View for the home page.""" recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects.order_by("-start_time")[0:500] total_num = len(recent_trials) running_num = sum(t.trial_status == Trial.RUNNING for t in recent_trials) success_num = sum( t.trial_status == Trial.TERMINATED for t in recent_trials) failed_num = sum(t.trial_status == Trial.ERROR for t in recent_trials) job_records = [] for recent_job in recent_jobs: job_records.append(get_job_info(recent_job)) context = { "log_dir": AUTOMLBOARD_LOG_DIR, "reload_interval": AUTOMLBOARD_RELOAD_INTERVAL, "recent_jobs": job_records, "job_num": len(job_records), "trial_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num } return render(request, "index.html", context)
[ "def", "index", "(", "request", ")", ":", "recent_jobs", "=", "JobRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", ":", "100", "]", "recent_trials", "=", "TrialRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", ":", "500", "]", "total_num", "=", "len", "(", "recent_trials", ")", "running_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "RUNNING", "for", "t", "in", "recent_trials", ")", "success_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "TERMINATED", "for", "t", "in", "recent_trials", ")", "failed_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "ERROR", "for", "t", "in", "recent_trials", ")", "job_records", "=", "[", "]", "for", "recent_job", "in", "recent_jobs", ":", "job_records", ".", "append", "(", "get_job_info", "(", "recent_job", ")", ")", "context", "=", "{", "\"log_dir\"", ":", "AUTOMLBOARD_LOG_DIR", ",", "\"reload_interval\"", ":", "AUTOMLBOARD_RELOAD_INTERVAL", ",", "\"recent_jobs\"", ":", "job_records", ",", "\"job_num\"", ":", "len", "(", "job_records", ")", ",", "\"trial_num\"", ":", "total_num", ",", "\"running_num\"", ":", "running_num", ",", "\"success_num\"", ":", "success_num", ",", "\"failed_num\"", ":", "failed_num", "}", "return", "render", "(", "request", ",", "\"index.html\"", ",", "context", ")" ]
View for the home page.
[ "View", "for", "the", "home", "page", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L17-L41
train
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
job
def job(request): """View for a single job.""" job_id = request.GET.get("job_id") recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") trial_records = [] for recent_trial in recent_trials: trial_records.append(get_trial_info(recent_trial)) current_job = JobRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time")[0] if len(trial_records) > 0: param_keys = trial_records[0]["params"].keys() else: param_keys = [] # TODO: support custom metrics here metric_keys = ["episode_reward", "accuracy", "loss"] context = { "current_job": get_job_info(current_job), "recent_jobs": recent_jobs, "recent_trials": trial_records, "param_keys": param_keys, "param_num": len(param_keys), "metric_keys": metric_keys, "metric_num": len(metric_keys) } return render(request, "job.html", context)
python
def job(request): """View for a single job.""" job_id = request.GET.get("job_id") recent_jobs = JobRecord.objects.order_by("-start_time")[0:100] recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") trial_records = [] for recent_trial in recent_trials: trial_records.append(get_trial_info(recent_trial)) current_job = JobRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time")[0] if len(trial_records) > 0: param_keys = trial_records[0]["params"].keys() else: param_keys = [] # TODO: support custom metrics here metric_keys = ["episode_reward", "accuracy", "loss"] context = { "current_job": get_job_info(current_job), "recent_jobs": recent_jobs, "recent_trials": trial_records, "param_keys": param_keys, "param_num": len(param_keys), "metric_keys": metric_keys, "metric_num": len(metric_keys) } return render(request, "job.html", context)
[ "def", "job", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "recent_jobs", "=", "JobRecord", ".", "objects", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", ":", "100", "]", "recent_trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "job_id", ")", ".", "order_by", "(", "\"-start_time\"", ")", "trial_records", "=", "[", "]", "for", "recent_trial", "in", "recent_trials", ":", "trial_records", ".", "append", "(", "get_trial_info", "(", "recent_trial", ")", ")", "current_job", "=", "JobRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "job_id", ")", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", "]", "if", "len", "(", "trial_records", ")", ">", "0", ":", "param_keys", "=", "trial_records", "[", "0", "]", "[", "\"params\"", "]", ".", "keys", "(", ")", "else", ":", "param_keys", "=", "[", "]", "# TODO: support custom metrics here", "metric_keys", "=", "[", "\"episode_reward\"", ",", "\"accuracy\"", ",", "\"loss\"", "]", "context", "=", "{", "\"current_job\"", ":", "get_job_info", "(", "current_job", ")", ",", "\"recent_jobs\"", ":", "recent_jobs", ",", "\"recent_trials\"", ":", "trial_records", ",", "\"param_keys\"", ":", "param_keys", ",", "\"param_num\"", ":", "len", "(", "param_keys", ")", ",", "\"metric_keys\"", ":", "metric_keys", ",", "\"metric_num\"", ":", "len", "(", "metric_keys", ")", "}", "return", "render", "(", "request", ",", "\"job.html\"", ",", "context", ")" ]
View for a single job.
[ "View", "for", "a", "single", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L44-L74
train
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
trial
def trial(request): """View for a single trial.""" job_id = request.GET.get("job_id") trial_id = request.GET.get("trial_id") recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") recent_results = ResultRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-date")[0:2000] current_trial = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time")[0] context = { "job_id": job_id, "trial_id": trial_id, "current_trial": current_trial, "recent_results": recent_results, "recent_trials": recent_trials } return render(request, "trial.html", context)
python
def trial(request): """View for a single trial.""" job_id = request.GET.get("job_id") trial_id = request.GET.get("trial_id") recent_trials = TrialRecord.objects \ .filter(job_id=job_id) \ .order_by("-start_time") recent_results = ResultRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-date")[0:2000] current_trial = TrialRecord.objects \ .filter(trial_id=trial_id) \ .order_by("-start_time")[0] context = { "job_id": job_id, "trial_id": trial_id, "current_trial": current_trial, "recent_results": recent_results, "recent_trials": recent_trials } return render(request, "trial.html", context)
[ "def", "trial", "(", "request", ")", ":", "job_id", "=", "request", ".", "GET", ".", "get", "(", "\"job_id\"", ")", "trial_id", "=", "request", ".", "GET", ".", "get", "(", "\"trial_id\"", ")", "recent_trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "job_id", ")", ".", "order_by", "(", "\"-start_time\"", ")", "recent_results", "=", "ResultRecord", ".", "objects", ".", "filter", "(", "trial_id", "=", "trial_id", ")", ".", "order_by", "(", "\"-date\"", ")", "[", "0", ":", "2000", "]", "current_trial", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "trial_id", "=", "trial_id", ")", ".", "order_by", "(", "\"-start_time\"", ")", "[", "0", "]", "context", "=", "{", "\"job_id\"", ":", "job_id", ",", "\"trial_id\"", ":", "trial_id", ",", "\"current_trial\"", ":", "current_trial", ",", "\"recent_results\"", ":", "recent_results", ",", "\"recent_trials\"", ":", "recent_trials", "}", "return", "render", "(", "request", ",", "\"trial.html\"", ",", "context", ")" ]
View for a single trial.
[ "View", "for", "a", "single", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L77-L97
train
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
get_job_info
def get_job_info(current_job): """Get job information for current job.""" trials = TrialRecord.objects.filter(job_id=current_job.job_id) total_num = len(trials) running_num = sum(t.trial_status == Trial.RUNNING for t in trials) success_num = sum(t.trial_status == Trial.TERMINATED for t in trials) failed_num = sum(t.trial_status == Trial.ERROR for t in trials) if total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) winner = get_winner(trials) job_info = { "job_id": current_job.job_id, "job_name": current_job.name, "user": current_job.user, "type": current_job.type, "start_time": current_job.start_time, "end_time": current_job.end_time, "total_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num, "best_trial_id": current_job.best_trial_id, "progress": progress, "winner": winner } return job_info
python
def get_job_info(current_job): """Get job information for current job.""" trials = TrialRecord.objects.filter(job_id=current_job.job_id) total_num = len(trials) running_num = sum(t.trial_status == Trial.RUNNING for t in trials) success_num = sum(t.trial_status == Trial.TERMINATED for t in trials) failed_num = sum(t.trial_status == Trial.ERROR for t in trials) if total_num == 0: progress = 0 else: progress = int(float(success_num) / total_num * 100) winner = get_winner(trials) job_info = { "job_id": current_job.job_id, "job_name": current_job.name, "user": current_job.user, "type": current_job.type, "start_time": current_job.start_time, "end_time": current_job.end_time, "total_num": total_num, "running_num": running_num, "success_num": success_num, "failed_num": failed_num, "best_trial_id": current_job.best_trial_id, "progress": progress, "winner": winner } return job_info
[ "def", "get_job_info", "(", "current_job", ")", ":", "trials", "=", "TrialRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "current_job", ".", "job_id", ")", "total_num", "=", "len", "(", "trials", ")", "running_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "RUNNING", "for", "t", "in", "trials", ")", "success_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "TERMINATED", "for", "t", "in", "trials", ")", "failed_num", "=", "sum", "(", "t", ".", "trial_status", "==", "Trial", ".", "ERROR", "for", "t", "in", "trials", ")", "if", "total_num", "==", "0", ":", "progress", "=", "0", "else", ":", "progress", "=", "int", "(", "float", "(", "success_num", ")", "/", "total_num", "*", "100", ")", "winner", "=", "get_winner", "(", "trials", ")", "job_info", "=", "{", "\"job_id\"", ":", "current_job", ".", "job_id", ",", "\"job_name\"", ":", "current_job", ".", "name", ",", "\"user\"", ":", "current_job", ".", "user", ",", "\"type\"", ":", "current_job", ".", "type", ",", "\"start_time\"", ":", "current_job", ".", "start_time", ",", "\"end_time\"", ":", "current_job", ".", "end_time", ",", "\"total_num\"", ":", "total_num", ",", "\"running_num\"", ":", "running_num", ",", "\"success_num\"", ":", "success_num", ",", "\"failed_num\"", ":", "failed_num", ",", "\"best_trial_id\"", ":", "current_job", ".", "best_trial_id", ",", "\"progress\"", ":", "progress", ",", "\"winner\"", ":", "winner", "}", "return", "job_info" ]
Get job information for current job.
[ "Get", "job", "information", "for", "current", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L100-L131
train
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
get_trial_info
def get_trial_info(current_trial): """Get job information for current trial.""" if current_trial.end_time and ("_" in current_trial.end_time): # end time is parsed from result.json and the format # is like: yyyy-mm-dd_hh-MM-ss, which will be converted # to yyyy-mm-dd hh:MM:ss here time_obj = datetime.datetime.strptime(current_trial.end_time, "%Y-%m-%d_%H-%M-%S") end_time = time_obj.strftime("%Y-%m-%d %H:%M:%S") else: end_time = current_trial.end_time if current_trial.metrics: metrics = eval(current_trial.metrics) else: metrics = None trial_info = { "trial_id": current_trial.trial_id, "job_id": current_trial.job_id, "trial_status": current_trial.trial_status, "start_time": current_trial.start_time, "end_time": end_time, "params": eval(current_trial.params.encode("utf-8")), "metrics": metrics } return trial_info
python
def get_trial_info(current_trial): """Get job information for current trial.""" if current_trial.end_time and ("_" in current_trial.end_time): # end time is parsed from result.json and the format # is like: yyyy-mm-dd_hh-MM-ss, which will be converted # to yyyy-mm-dd hh:MM:ss here time_obj = datetime.datetime.strptime(current_trial.end_time, "%Y-%m-%d_%H-%M-%S") end_time = time_obj.strftime("%Y-%m-%d %H:%M:%S") else: end_time = current_trial.end_time if current_trial.metrics: metrics = eval(current_trial.metrics) else: metrics = None trial_info = { "trial_id": current_trial.trial_id, "job_id": current_trial.job_id, "trial_status": current_trial.trial_status, "start_time": current_trial.start_time, "end_time": end_time, "params": eval(current_trial.params.encode("utf-8")), "metrics": metrics } return trial_info
[ "def", "get_trial_info", "(", "current_trial", ")", ":", "if", "current_trial", ".", "end_time", "and", "(", "\"_\"", "in", "current_trial", ".", "end_time", ")", ":", "# end time is parsed from result.json and the format", "# is like: yyyy-mm-dd_hh-MM-ss, which will be converted", "# to yyyy-mm-dd hh:MM:ss here", "time_obj", "=", "datetime", ".", "datetime", ".", "strptime", "(", "current_trial", ".", "end_time", ",", "\"%Y-%m-%d_%H-%M-%S\"", ")", "end_time", "=", "time_obj", ".", "strftime", "(", "\"%Y-%m-%d %H:%M:%S\"", ")", "else", ":", "end_time", "=", "current_trial", ".", "end_time", "if", "current_trial", ".", "metrics", ":", "metrics", "=", "eval", "(", "current_trial", ".", "metrics", ")", "else", ":", "metrics", "=", "None", "trial_info", "=", "{", "\"trial_id\"", ":", "current_trial", ".", "trial_id", ",", "\"job_id\"", ":", "current_trial", ".", "job_id", ",", "\"trial_status\"", ":", "current_trial", ".", "trial_status", ",", "\"start_time\"", ":", "current_trial", ".", "start_time", ",", "\"end_time\"", ":", "end_time", ",", "\"params\"", ":", "eval", "(", "current_trial", ".", "params", ".", "encode", "(", "\"utf-8\"", ")", ")", ",", "\"metrics\"", ":", "metrics", "}", "return", "trial_info" ]
Get job information for current trial.
[ "Get", "job", "information", "for", "current", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L134-L161
train
ray-project/ray
python/ray/tune/automlboard/frontend/view.py
get_winner
def get_winner(trials): """Get winner trial of a job.""" winner = {} # TODO: sort_key should be customized here sort_key = "accuracy" if trials and len(trials) > 0: first_metrics = get_trial_info(trials[0])["metrics"] if first_metrics and not first_metrics.get("accuracy", None): sort_key = "episode_reward" max_metric = float("-Inf") for t in trials: metrics = get_trial_info(t).get("metrics", None) if metrics and metrics.get(sort_key, None): current_metric = float(metrics[sort_key]) if current_metric > max_metric: winner["trial_id"] = t.trial_id winner["metric"] = sort_key + ": " + str(current_metric) max_metric = current_metric return winner
python
def get_winner(trials): """Get winner trial of a job.""" winner = {} # TODO: sort_key should be customized here sort_key = "accuracy" if trials and len(trials) > 0: first_metrics = get_trial_info(trials[0])["metrics"] if first_metrics and not first_metrics.get("accuracy", None): sort_key = "episode_reward" max_metric = float("-Inf") for t in trials: metrics = get_trial_info(t).get("metrics", None) if metrics and metrics.get(sort_key, None): current_metric = float(metrics[sort_key]) if current_metric > max_metric: winner["trial_id"] = t.trial_id winner["metric"] = sort_key + ": " + str(current_metric) max_metric = current_metric return winner
[ "def", "get_winner", "(", "trials", ")", ":", "winner", "=", "{", "}", "# TODO: sort_key should be customized here", "sort_key", "=", "\"accuracy\"", "if", "trials", "and", "len", "(", "trials", ")", ">", "0", ":", "first_metrics", "=", "get_trial_info", "(", "trials", "[", "0", "]", ")", "[", "\"metrics\"", "]", "if", "first_metrics", "and", "not", "first_metrics", ".", "get", "(", "\"accuracy\"", ",", "None", ")", ":", "sort_key", "=", "\"episode_reward\"", "max_metric", "=", "float", "(", "\"-Inf\"", ")", "for", "t", "in", "trials", ":", "metrics", "=", "get_trial_info", "(", "t", ")", ".", "get", "(", "\"metrics\"", ",", "None", ")", "if", "metrics", "and", "metrics", ".", "get", "(", "sort_key", ",", "None", ")", ":", "current_metric", "=", "float", "(", "metrics", "[", "sort_key", "]", ")", "if", "current_metric", ">", "max_metric", ":", "winner", "[", "\"trial_id\"", "]", "=", "t", ".", "trial_id", "winner", "[", "\"metric\"", "]", "=", "sort_key", "+", "\": \"", "+", "str", "(", "current_metric", ")", "max_metric", "=", "current_metric", "return", "winner" ]
Get winner trial of a job.
[ "Get", "winner", "trial", "of", "a", "job", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/frontend/view.py#L164-L182
train
ray-project/ray
python/ray/tune/config_parser.py
make_parser
def make_parser(parser_creator=None, **kwargs): """Returns a base argument parser for the ray.tune tool. Args: parser_creator: A constructor for the parser class. kwargs: Non-positional args to be passed into the parser class constructor. """ if parser_creator: parser = parser_creator(**kwargs) else: parser = argparse.ArgumentParser(**kwargs) # Note: keep this in sync with rllib/train.py parser.add_argument( "--run", default=None, type=str, help="The algorithm or model to train. This may refer to the name " "of a built-on algorithm (e.g. RLLib's DQN or PPO), or a " "user-defined trainable function or class registered in the " "tune registry.") parser.add_argument( "--stop", default="{}", type=json.loads, help="The stopping criteria, specified in JSON. The keys may be any " "field returned by 'train()' e.g. " "'{\"time_total_s\": 600, \"training_iteration\": 100000}' to stop " "after 600 seconds or 100k iterations, whichever is reached first.") parser.add_argument( "--config", default="{}", type=json.loads, help="Algorithm-specific configuration (e.g. env, hyperparams), " "specified in JSON.") parser.add_argument( "--resources-per-trial", default=None, type=json_to_resources, help="Override the machine resources to allocate per trial, e.g. " "'{\"cpu\": 64, \"gpu\": 8}'. Note that GPUs will not be assigned " "unless you specify them here. For RLlib, you probably want to " "leave this alone and use RLlib configs to control parallelism.") parser.add_argument( "--num-samples", default=1, type=int, help="Number of times to repeat each trial.") parser.add_argument( "--local-dir", default=DEFAULT_RESULTS_DIR, type=str, help="Local dir to save training results to. Defaults to '{}'.".format( DEFAULT_RESULTS_DIR)) parser.add_argument( "--upload-dir", default="", type=str, help="Optional URI to sync training results to (e.g. s3://bucket).") parser.add_argument( "--trial-name-creator", default=None, help="Optional creator function for the trial string, used in " "generating a trial directory.") parser.add_argument( "--sync-function", default=None, help="Function for syncing the local_dir to upload_dir. If string, " "then it must be a string template for syncer to run and needs to " "include replacement fields '{local_dir}' and '{remote_dir}'.") parser.add_argument( "--loggers", default=None, help="List of logger creators to be used with each Trial. " "Defaults to ray.tune.logger.DEFAULT_LOGGERS.") parser.add_argument( "--checkpoint-freq", default=0, type=int, help="How many training iterations between checkpoints. " "A value of 0 (default) disables checkpointing.") parser.add_argument( "--checkpoint-at-end", action="store_true", help="Whether to checkpoint at the end of the experiment. " "Default is False.") parser.add_argument( "--keep-checkpoints-num", default=None, type=int, help="Number of last checkpoints to keep. Others get " "deleted. Default (None) keeps all checkpoints.") parser.add_argument( "--checkpoint-score-attr", default="training_iteration", type=str, help="Specifies by which attribute to rank the best checkpoint. " "Default is increasing order. If attribute starts with min- it " "will rank attribute in decreasing order. Example: " "min-validation_loss") parser.add_argument( "--export-formats", default=None, help="List of formats that exported at the end of the experiment. " "Default is None. For RLlib, 'checkpoint' and 'model' are " "supported for TensorFlow policy graphs.") parser.add_argument( "--max-failures", default=3, type=int, help="Try to recover a trial from its last checkpoint at least this " "many times. Only applies if checkpointing is enabled.") parser.add_argument( "--scheduler", default="FIFO", type=str, help="FIFO (default), MedianStopping, AsyncHyperBand, " "HyperBand, or HyperOpt.") parser.add_argument( "--scheduler-config", default="{}", type=json.loads, help="Config options to pass to the scheduler.") # Note: this currently only makes sense when running a single trial parser.add_argument( "--restore", default=None, type=str, help="If specified, restore from this checkpoint.") return parser
python
def make_parser(parser_creator=None, **kwargs): """Returns a base argument parser for the ray.tune tool. Args: parser_creator: A constructor for the parser class. kwargs: Non-positional args to be passed into the parser class constructor. """ if parser_creator: parser = parser_creator(**kwargs) else: parser = argparse.ArgumentParser(**kwargs) # Note: keep this in sync with rllib/train.py parser.add_argument( "--run", default=None, type=str, help="The algorithm or model to train. This may refer to the name " "of a built-on algorithm (e.g. RLLib's DQN or PPO), or a " "user-defined trainable function or class registered in the " "tune registry.") parser.add_argument( "--stop", default="{}", type=json.loads, help="The stopping criteria, specified in JSON. The keys may be any " "field returned by 'train()' e.g. " "'{\"time_total_s\": 600, \"training_iteration\": 100000}' to stop " "after 600 seconds or 100k iterations, whichever is reached first.") parser.add_argument( "--config", default="{}", type=json.loads, help="Algorithm-specific configuration (e.g. env, hyperparams), " "specified in JSON.") parser.add_argument( "--resources-per-trial", default=None, type=json_to_resources, help="Override the machine resources to allocate per trial, e.g. " "'{\"cpu\": 64, \"gpu\": 8}'. Note that GPUs will not be assigned " "unless you specify them here. For RLlib, you probably want to " "leave this alone and use RLlib configs to control parallelism.") parser.add_argument( "--num-samples", default=1, type=int, help="Number of times to repeat each trial.") parser.add_argument( "--local-dir", default=DEFAULT_RESULTS_DIR, type=str, help="Local dir to save training results to. Defaults to '{}'.".format( DEFAULT_RESULTS_DIR)) parser.add_argument( "--upload-dir", default="", type=str, help="Optional URI to sync training results to (e.g. s3://bucket).") parser.add_argument( "--trial-name-creator", default=None, help="Optional creator function for the trial string, used in " "generating a trial directory.") parser.add_argument( "--sync-function", default=None, help="Function for syncing the local_dir to upload_dir. If string, " "then it must be a string template for syncer to run and needs to " "include replacement fields '{local_dir}' and '{remote_dir}'.") parser.add_argument( "--loggers", default=None, help="List of logger creators to be used with each Trial. " "Defaults to ray.tune.logger.DEFAULT_LOGGERS.") parser.add_argument( "--checkpoint-freq", default=0, type=int, help="How many training iterations between checkpoints. " "A value of 0 (default) disables checkpointing.") parser.add_argument( "--checkpoint-at-end", action="store_true", help="Whether to checkpoint at the end of the experiment. " "Default is False.") parser.add_argument( "--keep-checkpoints-num", default=None, type=int, help="Number of last checkpoints to keep. Others get " "deleted. Default (None) keeps all checkpoints.") parser.add_argument( "--checkpoint-score-attr", default="training_iteration", type=str, help="Specifies by which attribute to rank the best checkpoint. " "Default is increasing order. If attribute starts with min- it " "will rank attribute in decreasing order. Example: " "min-validation_loss") parser.add_argument( "--export-formats", default=None, help="List of formats that exported at the end of the experiment. " "Default is None. For RLlib, 'checkpoint' and 'model' are " "supported for TensorFlow policy graphs.") parser.add_argument( "--max-failures", default=3, type=int, help="Try to recover a trial from its last checkpoint at least this " "many times. Only applies if checkpointing is enabled.") parser.add_argument( "--scheduler", default="FIFO", type=str, help="FIFO (default), MedianStopping, AsyncHyperBand, " "HyperBand, or HyperOpt.") parser.add_argument( "--scheduler-config", default="{}", type=json.loads, help="Config options to pass to the scheduler.") # Note: this currently only makes sense when running a single trial parser.add_argument( "--restore", default=None, type=str, help="If specified, restore from this checkpoint.") return parser
[ "def", "make_parser", "(", "parser_creator", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "parser_creator", ":", "parser", "=", "parser_creator", "(", "*", "*", "kwargs", ")", "else", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "*", "*", "kwargs", ")", "# Note: keep this in sync with rllib/train.py", "parser", ".", "add_argument", "(", "\"--run\"", ",", "default", "=", "None", ",", "type", "=", "str", ",", "help", "=", "\"The algorithm or model to train. This may refer to the name \"", "\"of a built-on algorithm (e.g. RLLib's DQN or PPO), or a \"", "\"user-defined trainable function or class registered in the \"", "\"tune registry.\"", ")", "parser", ".", "add_argument", "(", "\"--stop\"", ",", "default", "=", "\"{}\"", ",", "type", "=", "json", ".", "loads", ",", "help", "=", "\"The stopping criteria, specified in JSON. The keys may be any \"", "\"field returned by 'train()' e.g. \"", "\"'{\\\"time_total_s\\\": 600, \\\"training_iteration\\\": 100000}' to stop \"", "\"after 600 seconds or 100k iterations, whichever is reached first.\"", ")", "parser", ".", "add_argument", "(", "\"--config\"", ",", "default", "=", "\"{}\"", ",", "type", "=", "json", ".", "loads", ",", "help", "=", "\"Algorithm-specific configuration (e.g. env, hyperparams), \"", "\"specified in JSON.\"", ")", "parser", ".", "add_argument", "(", "\"--resources-per-trial\"", ",", "default", "=", "None", ",", "type", "=", "json_to_resources", ",", "help", "=", "\"Override the machine resources to allocate per trial, e.g. \"", "\"'{\\\"cpu\\\": 64, \\\"gpu\\\": 8}'. Note that GPUs will not be assigned \"", "\"unless you specify them here. For RLlib, you probably want to \"", "\"leave this alone and use RLlib configs to control parallelism.\"", ")", "parser", ".", "add_argument", "(", "\"--num-samples\"", ",", "default", "=", "1", ",", "type", "=", "int", ",", "help", "=", "\"Number of times to repeat each trial.\"", ")", "parser", ".", "add_argument", "(", "\"--local-dir\"", ",", "default", "=", "DEFAULT_RESULTS_DIR", ",", "type", "=", "str", ",", "help", "=", "\"Local dir to save training results to. Defaults to '{}'.\"", ".", "format", "(", "DEFAULT_RESULTS_DIR", ")", ")", "parser", ".", "add_argument", "(", "\"--upload-dir\"", ",", "default", "=", "\"\"", ",", "type", "=", "str", ",", "help", "=", "\"Optional URI to sync training results to (e.g. s3://bucket).\"", ")", "parser", ".", "add_argument", "(", "\"--trial-name-creator\"", ",", "default", "=", "None", ",", "help", "=", "\"Optional creator function for the trial string, used in \"", "\"generating a trial directory.\"", ")", "parser", ".", "add_argument", "(", "\"--sync-function\"", ",", "default", "=", "None", ",", "help", "=", "\"Function for syncing the local_dir to upload_dir. If string, \"", "\"then it must be a string template for syncer to run and needs to \"", "\"include replacement fields '{local_dir}' and '{remote_dir}'.\"", ")", "parser", ".", "add_argument", "(", "\"--loggers\"", ",", "default", "=", "None", ",", "help", "=", "\"List of logger creators to be used with each Trial. \"", "\"Defaults to ray.tune.logger.DEFAULT_LOGGERS.\"", ")", "parser", ".", "add_argument", "(", "\"--checkpoint-freq\"", ",", "default", "=", "0", ",", "type", "=", "int", ",", "help", "=", "\"How many training iterations between checkpoints. \"", "\"A value of 0 (default) disables checkpointing.\"", ")", "parser", ".", "add_argument", "(", "\"--checkpoint-at-end\"", ",", "action", "=", "\"store_true\"", ",", "help", "=", "\"Whether to checkpoint at the end of the experiment. \"", "\"Default is False.\"", ")", "parser", ".", "add_argument", "(", "\"--keep-checkpoints-num\"", ",", "default", "=", "None", ",", "type", "=", "int", ",", "help", "=", "\"Number of last checkpoints to keep. Others get \"", "\"deleted. Default (None) keeps all checkpoints.\"", ")", "parser", ".", "add_argument", "(", "\"--checkpoint-score-attr\"", ",", "default", "=", "\"training_iteration\"", ",", "type", "=", "str", ",", "help", "=", "\"Specifies by which attribute to rank the best checkpoint. \"", "\"Default is increasing order. If attribute starts with min- it \"", "\"will rank attribute in decreasing order. Example: \"", "\"min-validation_loss\"", ")", "parser", ".", "add_argument", "(", "\"--export-formats\"", ",", "default", "=", "None", ",", "help", "=", "\"List of formats that exported at the end of the experiment. \"", "\"Default is None. For RLlib, 'checkpoint' and 'model' are \"", "\"supported for TensorFlow policy graphs.\"", ")", "parser", ".", "add_argument", "(", "\"--max-failures\"", ",", "default", "=", "3", ",", "type", "=", "int", ",", "help", "=", "\"Try to recover a trial from its last checkpoint at least this \"", "\"many times. Only applies if checkpointing is enabled.\"", ")", "parser", ".", "add_argument", "(", "\"--scheduler\"", ",", "default", "=", "\"FIFO\"", ",", "type", "=", "str", ",", "help", "=", "\"FIFO (default), MedianStopping, AsyncHyperBand, \"", "\"HyperBand, or HyperOpt.\"", ")", "parser", ".", "add_argument", "(", "\"--scheduler-config\"", ",", "default", "=", "\"{}\"", ",", "type", "=", "json", ".", "loads", ",", "help", "=", "\"Config options to pass to the scheduler.\"", ")", "# Note: this currently only makes sense when running a single trial", "parser", ".", "add_argument", "(", "\"--restore\"", ",", "default", "=", "None", ",", "type", "=", "str", ",", "help", "=", "\"If specified, restore from this checkpoint.\"", ")", "return", "parser" ]
Returns a base argument parser for the ray.tune tool. Args: parser_creator: A constructor for the parser class. kwargs: Non-positional args to be passed into the parser class constructor.
[ "Returns", "a", "base", "argument", "parser", "for", "the", "ray", ".", "tune", "tool", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L18-L151
train
ray-project/ray
python/ray/tune/config_parser.py
to_argv
def to_argv(config): """Converts configuration to a command line argument format.""" argv = [] for k, v in config.items(): if "-" in k: raise ValueError("Use '_' instead of '-' in `{}`".format(k)) if v is None: continue if not isinstance(v, bool) or v: # for argparse flags argv.append("--{}".format(k.replace("_", "-"))) if isinstance(v, string_types): argv.append(v) elif isinstance(v, bool): pass else: argv.append(json.dumps(v, cls=_SafeFallbackEncoder)) return argv
python
def to_argv(config): """Converts configuration to a command line argument format.""" argv = [] for k, v in config.items(): if "-" in k: raise ValueError("Use '_' instead of '-' in `{}`".format(k)) if v is None: continue if not isinstance(v, bool) or v: # for argparse flags argv.append("--{}".format(k.replace("_", "-"))) if isinstance(v, string_types): argv.append(v) elif isinstance(v, bool): pass else: argv.append(json.dumps(v, cls=_SafeFallbackEncoder)) return argv
[ "def", "to_argv", "(", "config", ")", ":", "argv", "=", "[", "]", "for", "k", ",", "v", "in", "config", ".", "items", "(", ")", ":", "if", "\"-\"", "in", "k", ":", "raise", "ValueError", "(", "\"Use '_' instead of '-' in `{}`\"", ".", "format", "(", "k", ")", ")", "if", "v", "is", "None", ":", "continue", "if", "not", "isinstance", "(", "v", ",", "bool", ")", "or", "v", ":", "# for argparse flags", "argv", ".", "append", "(", "\"--{}\"", ".", "format", "(", "k", ".", "replace", "(", "\"_\"", ",", "\"-\"", ")", ")", ")", "if", "isinstance", "(", "v", ",", "string_types", ")", ":", "argv", ".", "append", "(", "v", ")", "elif", "isinstance", "(", "v", ",", "bool", ")", ":", "pass", "else", ":", "argv", ".", "append", "(", "json", ".", "dumps", "(", "v", ",", "cls", "=", "_SafeFallbackEncoder", ")", ")", "return", "argv" ]
Converts configuration to a command line argument format.
[ "Converts", "configuration", "to", "a", "command", "line", "argument", "format", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L154-L170
train
ray-project/ray
python/ray/tune/config_parser.py
create_trial_from_spec
def create_trial_from_spec(spec, output_path, parser, **trial_kwargs): """Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_parser. output_path (str); A specific output path within the local_dir. Typically the name of the experiment. parser (ArgumentParser): An argument parser object from make_parser. trial_kwargs: Extra keyword arguments used in instantiating the Trial. Returns: A trial object with corresponding parameters to the specification. """ try: args = parser.parse_args(to_argv(spec)) except SystemExit: raise TuneError("Error parsing args, see above message", spec) if "resources_per_trial" in spec: trial_kwargs["resources"] = json_to_resources( spec["resources_per_trial"]) return Trial( # Submitting trial via server in py2.7 creates Unicode, which does not # convert to string in a straightforward manner. trainable_name=spec["run"], # json.load leads to str -> unicode in py2.7 config=spec.get("config", {}), local_dir=os.path.join(args.local_dir, output_path), # json.load leads to str -> unicode in py2.7 stopping_criterion=spec.get("stop", {}), checkpoint_freq=args.checkpoint_freq, checkpoint_at_end=args.checkpoint_at_end, keep_checkpoints_num=args.keep_checkpoints_num, checkpoint_score_attr=args.checkpoint_score_attr, export_formats=spec.get("export_formats", []), # str(None) doesn't create None restore_path=spec.get("restore"), upload_dir=args.upload_dir, trial_name_creator=spec.get("trial_name_creator"), loggers=spec.get("loggers"), # str(None) doesn't create None sync_function=spec.get("sync_function"), max_failures=args.max_failures, **trial_kwargs)
python
def create_trial_from_spec(spec, output_path, parser, **trial_kwargs): """Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_parser. output_path (str); A specific output path within the local_dir. Typically the name of the experiment. parser (ArgumentParser): An argument parser object from make_parser. trial_kwargs: Extra keyword arguments used in instantiating the Trial. Returns: A trial object with corresponding parameters to the specification. """ try: args = parser.parse_args(to_argv(spec)) except SystemExit: raise TuneError("Error parsing args, see above message", spec) if "resources_per_trial" in spec: trial_kwargs["resources"] = json_to_resources( spec["resources_per_trial"]) return Trial( # Submitting trial via server in py2.7 creates Unicode, which does not # convert to string in a straightforward manner. trainable_name=spec["run"], # json.load leads to str -> unicode in py2.7 config=spec.get("config", {}), local_dir=os.path.join(args.local_dir, output_path), # json.load leads to str -> unicode in py2.7 stopping_criterion=spec.get("stop", {}), checkpoint_freq=args.checkpoint_freq, checkpoint_at_end=args.checkpoint_at_end, keep_checkpoints_num=args.keep_checkpoints_num, checkpoint_score_attr=args.checkpoint_score_attr, export_formats=spec.get("export_formats", []), # str(None) doesn't create None restore_path=spec.get("restore"), upload_dir=args.upload_dir, trial_name_creator=spec.get("trial_name_creator"), loggers=spec.get("loggers"), # str(None) doesn't create None sync_function=spec.get("sync_function"), max_failures=args.max_failures, **trial_kwargs)
[ "def", "create_trial_from_spec", "(", "spec", ",", "output_path", ",", "parser", ",", "*", "*", "trial_kwargs", ")", ":", "try", ":", "args", "=", "parser", ".", "parse_args", "(", "to_argv", "(", "spec", ")", ")", "except", "SystemExit", ":", "raise", "TuneError", "(", "\"Error parsing args, see above message\"", ",", "spec", ")", "if", "\"resources_per_trial\"", "in", "spec", ":", "trial_kwargs", "[", "\"resources\"", "]", "=", "json_to_resources", "(", "spec", "[", "\"resources_per_trial\"", "]", ")", "return", "Trial", "(", "# Submitting trial via server in py2.7 creates Unicode, which does not", "# convert to string in a straightforward manner.", "trainable_name", "=", "spec", "[", "\"run\"", "]", ",", "# json.load leads to str -> unicode in py2.7", "config", "=", "spec", ".", "get", "(", "\"config\"", ",", "{", "}", ")", ",", "local_dir", "=", "os", ".", "path", ".", "join", "(", "args", ".", "local_dir", ",", "output_path", ")", ",", "# json.load leads to str -> unicode in py2.7", "stopping_criterion", "=", "spec", ".", "get", "(", "\"stop\"", ",", "{", "}", ")", ",", "checkpoint_freq", "=", "args", ".", "checkpoint_freq", ",", "checkpoint_at_end", "=", "args", ".", "checkpoint_at_end", ",", "keep_checkpoints_num", "=", "args", ".", "keep_checkpoints_num", ",", "checkpoint_score_attr", "=", "args", ".", "checkpoint_score_attr", ",", "export_formats", "=", "spec", ".", "get", "(", "\"export_formats\"", ",", "[", "]", ")", ",", "# str(None) doesn't create None", "restore_path", "=", "spec", ".", "get", "(", "\"restore\"", ")", ",", "upload_dir", "=", "args", ".", "upload_dir", ",", "trial_name_creator", "=", "spec", ".", "get", "(", "\"trial_name_creator\"", ")", ",", "loggers", "=", "spec", ".", "get", "(", "\"loggers\"", ")", ",", "# str(None) doesn't create None", "sync_function", "=", "spec", ".", "get", "(", "\"sync_function\"", ")", ",", "max_failures", "=", "args", ".", "max_failures", ",", "*", "*", "trial_kwargs", ")" ]
Creates a Trial object from parsing the spec. Arguments: spec (dict): A resolved experiment specification. Arguments should The args here should correspond to the command line flags in ray.tune.config_parser. output_path (str); A specific output path within the local_dir. Typically the name of the experiment. parser (ArgumentParser): An argument parser object from make_parser. trial_kwargs: Extra keyword arguments used in instantiating the Trial. Returns: A trial object with corresponding parameters to the specification.
[ "Creates", "a", "Trial", "object", "from", "parsing", "the", "spec", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/config_parser.py#L173-L218
train
ray-project/ray
python/ray/autoscaler/gcp/node_provider.py
wait_for_compute_zone_operation
def wait_for_compute_zone_operation(compute, project_name, operation, zone): """Poll for compute zone operation until finished.""" logger.info("wait_for_compute_zone_operation: " "Waiting for operation {} to finish...".format( operation["name"])) for _ in range(MAX_POLLS): result = compute.zoneOperations().get( project=project_name, operation=operation["name"], zone=zone).execute() if "error" in result: raise Exception(result["error"]) if result["status"] == "DONE": logger.info("wait_for_compute_zone_operation: " "Operation {} finished.".format(operation["name"])) break time.sleep(POLL_INTERVAL) return result
python
def wait_for_compute_zone_operation(compute, project_name, operation, zone): """Poll for compute zone operation until finished.""" logger.info("wait_for_compute_zone_operation: " "Waiting for operation {} to finish...".format( operation["name"])) for _ in range(MAX_POLLS): result = compute.zoneOperations().get( project=project_name, operation=operation["name"], zone=zone).execute() if "error" in result: raise Exception(result["error"]) if result["status"] == "DONE": logger.info("wait_for_compute_zone_operation: " "Operation {} finished.".format(operation["name"])) break time.sleep(POLL_INTERVAL) return result
[ "def", "wait_for_compute_zone_operation", "(", "compute", ",", "project_name", ",", "operation", ",", "zone", ")", ":", "logger", ".", "info", "(", "\"wait_for_compute_zone_operation: \"", "\"Waiting for operation {} to finish...\"", ".", "format", "(", "operation", "[", "\"name\"", "]", ")", ")", "for", "_", "in", "range", "(", "MAX_POLLS", ")", ":", "result", "=", "compute", ".", "zoneOperations", "(", ")", ".", "get", "(", "project", "=", "project_name", ",", "operation", "=", "operation", "[", "\"name\"", "]", ",", "zone", "=", "zone", ")", ".", "execute", "(", ")", "if", "\"error\"", "in", "result", ":", "raise", "Exception", "(", "result", "[", "\"error\"", "]", ")", "if", "result", "[", "\"status\"", "]", "==", "\"DONE\"", ":", "logger", ".", "info", "(", "\"wait_for_compute_zone_operation: \"", "\"Operation {} finished.\"", ".", "format", "(", "operation", "[", "\"name\"", "]", ")", ")", "break", "time", ".", "sleep", "(", "POLL_INTERVAL", ")", "return", "result" ]
Poll for compute zone operation until finished.
[ "Poll", "for", "compute", "zone", "operation", "until", "finished", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/gcp/node_provider.py#L22-L42
train
ray-project/ray
python/ray/experimental/signal.py
_get_task_id
def _get_task_id(source): """Return the task id associated to the generic source of the signal. Args: source: source of the signal, it can be either an object id returned by a task, a task id, or an actor handle. Returns: - If source is an object id, return id of task which creted object. - If source is an actor handle, return id of actor's task creator. - If source is a task id, return same task id. """ if type(source) is ray.actor.ActorHandle: return source._ray_actor_id else: if type(source) is ray.TaskID: return source else: return ray._raylet.compute_task_id(source)
python
def _get_task_id(source): """Return the task id associated to the generic source of the signal. Args: source: source of the signal, it can be either an object id returned by a task, a task id, or an actor handle. Returns: - If source is an object id, return id of task which creted object. - If source is an actor handle, return id of actor's task creator. - If source is a task id, return same task id. """ if type(source) is ray.actor.ActorHandle: return source._ray_actor_id else: if type(source) is ray.TaskID: return source else: return ray._raylet.compute_task_id(source)
[ "def", "_get_task_id", "(", "source", ")", ":", "if", "type", "(", "source", ")", "is", "ray", ".", "actor", ".", "ActorHandle", ":", "return", "source", ".", "_ray_actor_id", "else", ":", "if", "type", "(", "source", ")", "is", "ray", ".", "TaskID", ":", "return", "source", "else", ":", "return", "ray", ".", "_raylet", ".", "compute_task_id", "(", "source", ")" ]
Return the task id associated to the generic source of the signal. Args: source: source of the signal, it can be either an object id returned by a task, a task id, or an actor handle. Returns: - If source is an object id, return id of task which creted object. - If source is an actor handle, return id of actor's task creator. - If source is a task id, return same task id.
[ "Return", "the", "task", "id", "associated", "to", "the", "generic", "source", "of", "the", "signal", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L36-L54
train
ray-project/ray
python/ray/experimental/signal.py
send
def send(signal): """Send signal. The signal has a unique identifier that is computed from (1) the id of the actor or task sending this signal (i.e., the actor or task calling this function), and (2) an index that is incremented every time this source sends a signal. This index starts from 1. Args: signal: Signal to be sent. """ if hasattr(ray.worker.global_worker, "actor_creation_task_id"): source_key = ray.worker.global_worker.actor_id.hex() else: # No actors; this function must have been called from a task source_key = ray.worker.global_worker.current_task_id.hex() encoded_signal = ray.utils.binary_to_hex(cloudpickle.dumps(signal)) ray.worker.global_worker.redis_client.execute_command( "XADD " + source_key + " * signal " + encoded_signal)
python
def send(signal): """Send signal. The signal has a unique identifier that is computed from (1) the id of the actor or task sending this signal (i.e., the actor or task calling this function), and (2) an index that is incremented every time this source sends a signal. This index starts from 1. Args: signal: Signal to be sent. """ if hasattr(ray.worker.global_worker, "actor_creation_task_id"): source_key = ray.worker.global_worker.actor_id.hex() else: # No actors; this function must have been called from a task source_key = ray.worker.global_worker.current_task_id.hex() encoded_signal = ray.utils.binary_to_hex(cloudpickle.dumps(signal)) ray.worker.global_worker.redis_client.execute_command( "XADD " + source_key + " * signal " + encoded_signal)
[ "def", "send", "(", "signal", ")", ":", "if", "hasattr", "(", "ray", ".", "worker", ".", "global_worker", ",", "\"actor_creation_task_id\"", ")", ":", "source_key", "=", "ray", ".", "worker", ".", "global_worker", ".", "actor_id", ".", "hex", "(", ")", "else", ":", "# No actors; this function must have been called from a task", "source_key", "=", "ray", ".", "worker", ".", "global_worker", ".", "current_task_id", ".", "hex", "(", ")", "encoded_signal", "=", "ray", ".", "utils", ".", "binary_to_hex", "(", "cloudpickle", ".", "dumps", "(", "signal", ")", ")", "ray", ".", "worker", ".", "global_worker", ".", "redis_client", ".", "execute_command", "(", "\"XADD \"", "+", "source_key", "+", "\" * signal \"", "+", "encoded_signal", ")" ]
Send signal. The signal has a unique identifier that is computed from (1) the id of the actor or task sending this signal (i.e., the actor or task calling this function), and (2) an index that is incremented every time this source sends a signal. This index starts from 1. Args: signal: Signal to be sent.
[ "Send", "signal", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L57-L76
train
ray-project/ray
python/ray/experimental/signal.py
receive
def receive(sources, timeout=None): """Get all outstanding signals from sources. A source can be either (1) an object ID returned by the task (we want to receive signals from), or (2) an actor handle. When invoked by the same entity E (where E can be an actor, task or driver), for each source S in sources, this function returns all signals generated by S since the last receive() was invoked by E on S. If this is the first call on S, this function returns all past signals generated by S so far. Note that different actors, tasks or drivers that call receive() on the same source S will get independent copies of the signals generated by S. Args: sources: List of sources from which the caller waits for signals. A source is either an object ID returned by a task (in this case the object ID is used to identify that task), or an actor handle. If the user passes the IDs of multiple objects returned by the same task, this function returns a copy of the signals generated by that task for each object ID. timeout: Maximum time (in seconds) this function waits to get a signal from a source in sources. If None, the timeout is infinite. Returns: A list of pairs (S, sig), where S is a source in the sources argument, and sig is a signal generated by S since the last time receive() was called on S. Thus, for each S in sources, the return list can contain zero or multiple entries. """ # If None, initialize the timeout to a huge value (i.e., over 30,000 years # in this case) to "approximate" infinity. if timeout is None: timeout = 10**12 if timeout < 0: raise ValueError("The 'timeout' argument cannot be less than 0.") if not hasattr(ray.worker.global_worker, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0") signal_counters = ray.worker.global_worker.signal_counters # Map the ID of each source task to the source itself. task_id_to_sources = defaultdict(lambda: []) for s in sources: task_id_to_sources[_get_task_id(s).hex()].append(s) # Construct the redis query. query = "XREAD BLOCK " # Multiply by 1000x since timeout is in sec and redis expects ms. query += str(1000 * timeout) query += " STREAMS " query += " ".join([task_id for task_id in task_id_to_sources]) query += " " query += " ".join([ ray.utils.decode(signal_counters[ray.utils.hex_to_binary(task_id)]) for task_id in task_id_to_sources ]) answers = ray.worker.global_worker.redis_client.execute_command(query) if not answers: return [] results = [] # Decoding is a little bit involved. Iterate through all the answers: for i, answer in enumerate(answers): # Make sure the answer corresponds to a source, s, in sources. task_id = ray.utils.decode(answer[0]) task_source_list = task_id_to_sources[task_id] # The list of results for source s is stored in answer[1] for r in answer[1]: for s in task_source_list: if r[1][1].decode("ascii") == ACTOR_DIED_STR: results.append((s, ActorDiedSignal())) else: # Now it gets tricky: r[0] is the redis internal sequence # id signal_counters[ray.utils.hex_to_binary(task_id)] = r[0] # r[1] contains a list with elements (key, value), in our # case we only have one key "signal" and the value is the # signal. signal = cloudpickle.loads( ray.utils.hex_to_binary(r[1][1])) results.append((s, signal)) return results
python
def receive(sources, timeout=None): """Get all outstanding signals from sources. A source can be either (1) an object ID returned by the task (we want to receive signals from), or (2) an actor handle. When invoked by the same entity E (where E can be an actor, task or driver), for each source S in sources, this function returns all signals generated by S since the last receive() was invoked by E on S. If this is the first call on S, this function returns all past signals generated by S so far. Note that different actors, tasks or drivers that call receive() on the same source S will get independent copies of the signals generated by S. Args: sources: List of sources from which the caller waits for signals. A source is either an object ID returned by a task (in this case the object ID is used to identify that task), or an actor handle. If the user passes the IDs of multiple objects returned by the same task, this function returns a copy of the signals generated by that task for each object ID. timeout: Maximum time (in seconds) this function waits to get a signal from a source in sources. If None, the timeout is infinite. Returns: A list of pairs (S, sig), where S is a source in the sources argument, and sig is a signal generated by S since the last time receive() was called on S. Thus, for each S in sources, the return list can contain zero or multiple entries. """ # If None, initialize the timeout to a huge value (i.e., over 30,000 years # in this case) to "approximate" infinity. if timeout is None: timeout = 10**12 if timeout < 0: raise ValueError("The 'timeout' argument cannot be less than 0.") if not hasattr(ray.worker.global_worker, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0") signal_counters = ray.worker.global_worker.signal_counters # Map the ID of each source task to the source itself. task_id_to_sources = defaultdict(lambda: []) for s in sources: task_id_to_sources[_get_task_id(s).hex()].append(s) # Construct the redis query. query = "XREAD BLOCK " # Multiply by 1000x since timeout is in sec and redis expects ms. query += str(1000 * timeout) query += " STREAMS " query += " ".join([task_id for task_id in task_id_to_sources]) query += " " query += " ".join([ ray.utils.decode(signal_counters[ray.utils.hex_to_binary(task_id)]) for task_id in task_id_to_sources ]) answers = ray.worker.global_worker.redis_client.execute_command(query) if not answers: return [] results = [] # Decoding is a little bit involved. Iterate through all the answers: for i, answer in enumerate(answers): # Make sure the answer corresponds to a source, s, in sources. task_id = ray.utils.decode(answer[0]) task_source_list = task_id_to_sources[task_id] # The list of results for source s is stored in answer[1] for r in answer[1]: for s in task_source_list: if r[1][1].decode("ascii") == ACTOR_DIED_STR: results.append((s, ActorDiedSignal())) else: # Now it gets tricky: r[0] is the redis internal sequence # id signal_counters[ray.utils.hex_to_binary(task_id)] = r[0] # r[1] contains a list with elements (key, value), in our # case we only have one key "signal" and the value is the # signal. signal = cloudpickle.loads( ray.utils.hex_to_binary(r[1][1])) results.append((s, signal)) return results
[ "def", "receive", "(", "sources", ",", "timeout", "=", "None", ")", ":", "# If None, initialize the timeout to a huge value (i.e., over 30,000 years", "# in this case) to \"approximate\" infinity.", "if", "timeout", "is", "None", ":", "timeout", "=", "10", "**", "12", "if", "timeout", "<", "0", ":", "raise", "ValueError", "(", "\"The 'timeout' argument cannot be less than 0.\"", ")", "if", "not", "hasattr", "(", "ray", ".", "worker", ".", "global_worker", ",", "\"signal_counters\"", ")", ":", "ray", ".", "worker", ".", "global_worker", ".", "signal_counters", "=", "defaultdict", "(", "lambda", ":", "b\"0\"", ")", "signal_counters", "=", "ray", ".", "worker", ".", "global_worker", ".", "signal_counters", "# Map the ID of each source task to the source itself.", "task_id_to_sources", "=", "defaultdict", "(", "lambda", ":", "[", "]", ")", "for", "s", "in", "sources", ":", "task_id_to_sources", "[", "_get_task_id", "(", "s", ")", ".", "hex", "(", ")", "]", ".", "append", "(", "s", ")", "# Construct the redis query.", "query", "=", "\"XREAD BLOCK \"", "# Multiply by 1000x since timeout is in sec and redis expects ms.", "query", "+=", "str", "(", "1000", "*", "timeout", ")", "query", "+=", "\" STREAMS \"", "query", "+=", "\" \"", ".", "join", "(", "[", "task_id", "for", "task_id", "in", "task_id_to_sources", "]", ")", "query", "+=", "\" \"", "query", "+=", "\" \"", ".", "join", "(", "[", "ray", ".", "utils", ".", "decode", "(", "signal_counters", "[", "ray", ".", "utils", ".", "hex_to_binary", "(", "task_id", ")", "]", ")", "for", "task_id", "in", "task_id_to_sources", "]", ")", "answers", "=", "ray", ".", "worker", ".", "global_worker", ".", "redis_client", ".", "execute_command", "(", "query", ")", "if", "not", "answers", ":", "return", "[", "]", "results", "=", "[", "]", "# Decoding is a little bit involved. Iterate through all the answers:", "for", "i", ",", "answer", "in", "enumerate", "(", "answers", ")", ":", "# Make sure the answer corresponds to a source, s, in sources.", "task_id", "=", "ray", ".", "utils", ".", "decode", "(", "answer", "[", "0", "]", ")", "task_source_list", "=", "task_id_to_sources", "[", "task_id", "]", "# The list of results for source s is stored in answer[1]", "for", "r", "in", "answer", "[", "1", "]", ":", "for", "s", "in", "task_source_list", ":", "if", "r", "[", "1", "]", "[", "1", "]", ".", "decode", "(", "\"ascii\"", ")", "==", "ACTOR_DIED_STR", ":", "results", ".", "append", "(", "(", "s", ",", "ActorDiedSignal", "(", ")", ")", ")", "else", ":", "# Now it gets tricky: r[0] is the redis internal sequence", "# id", "signal_counters", "[", "ray", ".", "utils", ".", "hex_to_binary", "(", "task_id", ")", "]", "=", "r", "[", "0", "]", "# r[1] contains a list with elements (key, value), in our", "# case we only have one key \"signal\" and the value is the", "# signal.", "signal", "=", "cloudpickle", ".", "loads", "(", "ray", ".", "utils", ".", "hex_to_binary", "(", "r", "[", "1", "]", "[", "1", "]", ")", ")", "results", ".", "append", "(", "(", "s", ",", "signal", ")", ")", "return", "results" ]
Get all outstanding signals from sources. A source can be either (1) an object ID returned by the task (we want to receive signals from), or (2) an actor handle. When invoked by the same entity E (where E can be an actor, task or driver), for each source S in sources, this function returns all signals generated by S since the last receive() was invoked by E on S. If this is the first call on S, this function returns all past signals generated by S so far. Note that different actors, tasks or drivers that call receive() on the same source S will get independent copies of the signals generated by S. Args: sources: List of sources from which the caller waits for signals. A source is either an object ID returned by a task (in this case the object ID is used to identify that task), or an actor handle. If the user passes the IDs of multiple objects returned by the same task, this function returns a copy of the signals generated by that task for each object ID. timeout: Maximum time (in seconds) this function waits to get a signal from a source in sources. If None, the timeout is infinite. Returns: A list of pairs (S, sig), where S is a source in the sources argument, and sig is a signal generated by S since the last time receive() was called on S. Thus, for each S in sources, the return list can contain zero or multiple entries.
[ "Get", "all", "outstanding", "signals", "from", "sources", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L79-L166
train
ray-project/ray
python/ray/experimental/signal.py
reset
def reset(): """ Reset the worker state associated with any signals that this worker has received so far. If the worker calls receive() on a source next, it will get all the signals generated by that source starting with index = 1. """ if hasattr(ray.worker.global_worker, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0")
python
def reset(): """ Reset the worker state associated with any signals that this worker has received so far. If the worker calls receive() on a source next, it will get all the signals generated by that source starting with index = 1. """ if hasattr(ray.worker.global_worker, "signal_counters"): ray.worker.global_worker.signal_counters = defaultdict(lambda: b"0")
[ "def", "reset", "(", ")", ":", "if", "hasattr", "(", "ray", ".", "worker", ".", "global_worker", ",", "\"signal_counters\"", ")", ":", "ray", ".", "worker", ".", "global_worker", ".", "signal_counters", "=", "defaultdict", "(", "lambda", ":", "b\"0\"", ")" ]
Reset the worker state associated with any signals that this worker has received so far. If the worker calls receive() on a source next, it will get all the signals generated by that source starting with index = 1.
[ "Reset", "the", "worker", "state", "associated", "with", "any", "signals", "that", "this", "worker", "has", "received", "so", "far", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/signal.py#L184-L193
train
ray-project/ray
python/ray/rllib/utils/debug.py
log_once
def log_once(key): """Returns True if this is the "first" call for a given key. Various logging settings can adjust the definition of "first". Example: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement") """ global _last_logged if _disabled: return False elif key not in _logged: _logged.add(key) _last_logged = time.time() return True elif _periodic_log and time.time() - _last_logged > 60.0: _logged.clear() _last_logged = time.time() return False else: return False
python
def log_once(key): """Returns True if this is the "first" call for a given key. Various logging settings can adjust the definition of "first". Example: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement") """ global _last_logged if _disabled: return False elif key not in _logged: _logged.add(key) _last_logged = time.time() return True elif _periodic_log and time.time() - _last_logged > 60.0: _logged.clear() _last_logged = time.time() return False else: return False
[ "def", "log_once", "(", "key", ")", ":", "global", "_last_logged", "if", "_disabled", ":", "return", "False", "elif", "key", "not", "in", "_logged", ":", "_logged", ".", "add", "(", "key", ")", "_last_logged", "=", "time", ".", "time", "(", ")", "return", "True", "elif", "_periodic_log", "and", "time", ".", "time", "(", ")", "-", "_last_logged", ">", "60.0", ":", "_logged", ".", "clear", "(", ")", "_last_logged", "=", "time", ".", "time", "(", ")", "return", "False", "else", ":", "return", "False" ]
Returns True if this is the "first" call for a given key. Various logging settings can adjust the definition of "first". Example: >>> if log_once("some_key"): ... logger.info("Some verbose logging statement")
[ "Returns", "True", "if", "this", "is", "the", "first", "call", "for", "a", "given", "key", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/debug.py#L18-L41
train
ray-project/ray
python/ray/experimental/api.py
get
def get(object_ids): """Get a single or a collection of remote objects from the object store. This method is identical to `ray.get` except it adds support for tuples, ndarrays and dictionaries. Args: object_ids: Object ID of the object to get, a list, tuple, ndarray of object IDs to get or a dict of {key: object ID}. Returns: A Python object, a list of Python objects or a dict of {key: object}. """ if isinstance(object_ids, (tuple, np.ndarray)): return ray.get(list(object_ids)) elif isinstance(object_ids, dict): keys_to_get = [ k for k, v in object_ids.items() if isinstance(v, ray.ObjectID) ] ids_to_get = [ v for k, v in object_ids.items() if isinstance(v, ray.ObjectID) ] values = ray.get(ids_to_get) result = object_ids.copy() for key, value in zip(keys_to_get, values): result[key] = value return result else: return ray.get(object_ids)
python
def get(object_ids): """Get a single or a collection of remote objects from the object store. This method is identical to `ray.get` except it adds support for tuples, ndarrays and dictionaries. Args: object_ids: Object ID of the object to get, a list, tuple, ndarray of object IDs to get or a dict of {key: object ID}. Returns: A Python object, a list of Python objects or a dict of {key: object}. """ if isinstance(object_ids, (tuple, np.ndarray)): return ray.get(list(object_ids)) elif isinstance(object_ids, dict): keys_to_get = [ k for k, v in object_ids.items() if isinstance(v, ray.ObjectID) ] ids_to_get = [ v for k, v in object_ids.items() if isinstance(v, ray.ObjectID) ] values = ray.get(ids_to_get) result = object_ids.copy() for key, value in zip(keys_to_get, values): result[key] = value return result else: return ray.get(object_ids)
[ "def", "get", "(", "object_ids", ")", ":", "if", "isinstance", "(", "object_ids", ",", "(", "tuple", ",", "np", ".", "ndarray", ")", ")", ":", "return", "ray", ".", "get", "(", "list", "(", "object_ids", ")", ")", "elif", "isinstance", "(", "object_ids", ",", "dict", ")", ":", "keys_to_get", "=", "[", "k", "for", "k", ",", "v", "in", "object_ids", ".", "items", "(", ")", "if", "isinstance", "(", "v", ",", "ray", ".", "ObjectID", ")", "]", "ids_to_get", "=", "[", "v", "for", "k", ",", "v", "in", "object_ids", ".", "items", "(", ")", "if", "isinstance", "(", "v", ",", "ray", ".", "ObjectID", ")", "]", "values", "=", "ray", ".", "get", "(", "ids_to_get", ")", "result", "=", "object_ids", ".", "copy", "(", ")", "for", "key", ",", "value", "in", "zip", "(", "keys_to_get", ",", "values", ")", ":", "result", "[", "key", "]", "=", "value", "return", "result", "else", ":", "return", "ray", ".", "get", "(", "object_ids", ")" ]
Get a single or a collection of remote objects from the object store. This method is identical to `ray.get` except it adds support for tuples, ndarrays and dictionaries. Args: object_ids: Object ID of the object to get, a list, tuple, ndarray of object IDs to get or a dict of {key: object ID}. Returns: A Python object, a list of Python objects or a dict of {key: object}.
[ "Get", "a", "single", "or", "a", "collection", "of", "remote", "objects", "from", "the", "object", "store", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/api.py#L9-L38
train
ray-project/ray
python/ray/experimental/api.py
wait
def wait(object_ids, num_returns=1, timeout=None): """Return a list of IDs that are ready and a list of IDs that are not. This method is identical to `ray.wait` except it adds support for tuples and ndarrays. Args: object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)): List like of object IDs for objects that may or may not be ready. Note that these IDs must be unique. num_returns (int): The number of object IDs that should be returned. timeout (float): The maximum amount of time in seconds to wait before returning. Returns: A list of object IDs that are ready and a list of the remaining object IDs. """ if isinstance(object_ids, (tuple, np.ndarray)): return ray.wait( list(object_ids), num_returns=num_returns, timeout=timeout) return ray.wait(object_ids, num_returns=num_returns, timeout=timeout)
python
def wait(object_ids, num_returns=1, timeout=None): """Return a list of IDs that are ready and a list of IDs that are not. This method is identical to `ray.wait` except it adds support for tuples and ndarrays. Args: object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)): List like of object IDs for objects that may or may not be ready. Note that these IDs must be unique. num_returns (int): The number of object IDs that should be returned. timeout (float): The maximum amount of time in seconds to wait before returning. Returns: A list of object IDs that are ready and a list of the remaining object IDs. """ if isinstance(object_ids, (tuple, np.ndarray)): return ray.wait( list(object_ids), num_returns=num_returns, timeout=timeout) return ray.wait(object_ids, num_returns=num_returns, timeout=timeout)
[ "def", "wait", "(", "object_ids", ",", "num_returns", "=", "1", ",", "timeout", "=", "None", ")", ":", "if", "isinstance", "(", "object_ids", ",", "(", "tuple", ",", "np", ".", "ndarray", ")", ")", ":", "return", "ray", ".", "wait", "(", "list", "(", "object_ids", ")", ",", "num_returns", "=", "num_returns", ",", "timeout", "=", "timeout", ")", "return", "ray", ".", "wait", "(", "object_ids", ",", "num_returns", "=", "num_returns", ",", "timeout", "=", "timeout", ")" ]
Return a list of IDs that are ready and a list of IDs that are not. This method is identical to `ray.wait` except it adds support for tuples and ndarrays. Args: object_ids (List[ObjectID], Tuple(ObjectID), np.array(ObjectID)): List like of object IDs for objects that may or may not be ready. Note that these IDs must be unique. num_returns (int): The number of object IDs that should be returned. timeout (float): The maximum amount of time in seconds to wait before returning. Returns: A list of object IDs that are ready and a list of the remaining object IDs.
[ "Return", "a", "list", "of", "IDs", "that", "are", "ready", "and", "a", "list", "of", "IDs", "that", "are", "not", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/api.py#L41-L63
train
ray-project/ray
python/ray/tune/experiment.py
_raise_deprecation_note
def _raise_deprecation_note(deprecated, replacement, soft=False): """User notification for deprecated parameter. Arguments: deprecated (str): Deprecated parameter. replacement (str): Replacement parameter to use instead. soft (bool): Fatal if True. """ error_msg = ("`{deprecated}` is deprecated. Please use `{replacement}`. " "`{deprecated}` will be removed in future versions of " "Ray.".format(deprecated=deprecated, replacement=replacement)) if soft: logger.warning(error_msg) else: raise DeprecationWarning(error_msg)
python
def _raise_deprecation_note(deprecated, replacement, soft=False): """User notification for deprecated parameter. Arguments: deprecated (str): Deprecated parameter. replacement (str): Replacement parameter to use instead. soft (bool): Fatal if True. """ error_msg = ("`{deprecated}` is deprecated. Please use `{replacement}`. " "`{deprecated}` will be removed in future versions of " "Ray.".format(deprecated=deprecated, replacement=replacement)) if soft: logger.warning(error_msg) else: raise DeprecationWarning(error_msg)
[ "def", "_raise_deprecation_note", "(", "deprecated", ",", "replacement", ",", "soft", "=", "False", ")", ":", "error_msg", "=", "(", "\"`{deprecated}` is deprecated. Please use `{replacement}`. \"", "\"`{deprecated}` will be removed in future versions of \"", "\"Ray.\"", ".", "format", "(", "deprecated", "=", "deprecated", ",", "replacement", "=", "replacement", ")", ")", "if", "soft", ":", "logger", ".", "warning", "(", "error_msg", ")", "else", ":", "raise", "DeprecationWarning", "(", "error_msg", ")" ]
User notification for deprecated parameter. Arguments: deprecated (str): Deprecated parameter. replacement (str): Replacement parameter to use instead. soft (bool): Fatal if True.
[ "User", "notification", "for", "deprecated", "parameter", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L18-L32
train
ray-project/ray
python/ray/tune/experiment.py
convert_to_experiment_list
def convert_to_experiment_list(experiments): """Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments. """ exp_list = experiments # Transform list if necessary if experiments is None: exp_list = [] elif isinstance(experiments, Experiment): exp_list = [experiments] elif type(experiments) is dict: exp_list = [ Experiment.from_json(name, spec) for name, spec in experiments.items() ] # Validate exp_list if (type(exp_list) is list and all(isinstance(exp, Experiment) for exp in exp_list)): if len(exp_list) > 1: logger.warning("All experiments will be " "using the same SearchAlgorithm.") else: raise TuneError("Invalid argument: {}".format(experiments)) return exp_list
python
def convert_to_experiment_list(experiments): """Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments. """ exp_list = experiments # Transform list if necessary if experiments is None: exp_list = [] elif isinstance(experiments, Experiment): exp_list = [experiments] elif type(experiments) is dict: exp_list = [ Experiment.from_json(name, spec) for name, spec in experiments.items() ] # Validate exp_list if (type(exp_list) is list and all(isinstance(exp, Experiment) for exp in exp_list)): if len(exp_list) > 1: logger.warning("All experiments will be " "using the same SearchAlgorithm.") else: raise TuneError("Invalid argument: {}".format(experiments)) return exp_list
[ "def", "convert_to_experiment_list", "(", "experiments", ")", ":", "exp_list", "=", "experiments", "# Transform list if necessary", "if", "experiments", "is", "None", ":", "exp_list", "=", "[", "]", "elif", "isinstance", "(", "experiments", ",", "Experiment", ")", ":", "exp_list", "=", "[", "experiments", "]", "elif", "type", "(", "experiments", ")", "is", "dict", ":", "exp_list", "=", "[", "Experiment", ".", "from_json", "(", "name", ",", "spec", ")", "for", "name", ",", "spec", "in", "experiments", ".", "items", "(", ")", "]", "# Validate exp_list", "if", "(", "type", "(", "exp_list", ")", "is", "list", "and", "all", "(", "isinstance", "(", "exp", ",", "Experiment", ")", "for", "exp", "in", "exp_list", ")", ")", ":", "if", "len", "(", "exp_list", ")", ">", "1", ":", "logger", ".", "warning", "(", "\"All experiments will be \"", "\"using the same SearchAlgorithm.\"", ")", "else", ":", "raise", "TuneError", "(", "\"Invalid argument: {}\"", ".", "format", "(", "experiments", ")", ")", "return", "exp_list" ]
Produces a list of Experiment objects. Converts input from dict, single experiment, or list of experiments to list of experiments. If input is None, will return an empty list. Arguments: experiments (Experiment | list | dict): Experiments to run. Returns: List of experiments.
[ "Produces", "a", "list", "of", "Experiment", "objects", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L180-L215
train
ray-project/ray
python/ray/tune/experiment.py
Experiment.from_json
def from_json(cls, name, spec): """Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experiment. """ if "run" not in spec: raise TuneError("No trainable specified!") # Special case the `env` param for RLlib by automatically # moving it into the `config` section. if "env" in spec: spec["config"] = spec.get("config", {}) spec["config"]["env"] = spec["env"] del spec["env"] spec = copy.deepcopy(spec) run_value = spec.pop("run") try: exp = cls(name, run_value, **spec) except TypeError: raise TuneError("Improper argument from JSON: {}.".format(spec)) return exp
python
def from_json(cls, name, spec): """Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experiment. """ if "run" not in spec: raise TuneError("No trainable specified!") # Special case the `env` param for RLlib by automatically # moving it into the `config` section. if "env" in spec: spec["config"] = spec.get("config", {}) spec["config"]["env"] = spec["env"] del spec["env"] spec = copy.deepcopy(spec) run_value = spec.pop("run") try: exp = cls(name, run_value, **spec) except TypeError: raise TuneError("Improper argument from JSON: {}.".format(spec)) return exp
[ "def", "from_json", "(", "cls", ",", "name", ",", "spec", ")", ":", "if", "\"run\"", "not", "in", "spec", ":", "raise", "TuneError", "(", "\"No trainable specified!\"", ")", "# Special case the `env` param for RLlib by automatically", "# moving it into the `config` section.", "if", "\"env\"", "in", "spec", ":", "spec", "[", "\"config\"", "]", "=", "spec", ".", "get", "(", "\"config\"", ",", "{", "}", ")", "spec", "[", "\"config\"", "]", "[", "\"env\"", "]", "=", "spec", "[", "\"env\"", "]", "del", "spec", "[", "\"env\"", "]", "spec", "=", "copy", ".", "deepcopy", "(", "spec", ")", "run_value", "=", "spec", ".", "pop", "(", "\"run\"", ")", "try", ":", "exp", "=", "cls", "(", "name", ",", "run_value", ",", "*", "*", "spec", ")", "except", "TypeError", ":", "raise", "TuneError", "(", "\"Improper argument from JSON: {}.\"", ".", "format", "(", "spec", ")", ")", "return", "exp" ]
Generates an Experiment object from JSON. Args: name (str): Name of Experiment. spec (dict): JSON configuration of experiment.
[ "Generates", "an", "Experiment", "object", "from", "JSON", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L118-L142
train
ray-project/ray
python/ray/tune/experiment.py
Experiment._register_if_needed
def _register_if_needed(cls, run_object): """Registers Trainable or Function at runtime. Assumes already registered if run_object is a string. Does not register lambdas because they could be part of variant generation. Also, does not inspect interface of given run_object. Arguments: run_object (str|function|class): Trainable to run. If string, assumes it is an ID and does not modify it. Otherwise, returns a string corresponding to the run_object name. Returns: A string representing the trainable identifier. """ if isinstance(run_object, six.string_types): return run_object elif isinstance(run_object, types.FunctionType): if run_object.__name__ == "<lambda>": logger.warning( "Not auto-registering lambdas - resolving as variant.") return run_object else: name = run_object.__name__ register_trainable(name, run_object) return name elif isinstance(run_object, type): name = run_object.__name__ register_trainable(name, run_object) return name else: raise TuneError("Improper 'run' - not string nor trainable.")
python
def _register_if_needed(cls, run_object): """Registers Trainable or Function at runtime. Assumes already registered if run_object is a string. Does not register lambdas because they could be part of variant generation. Also, does not inspect interface of given run_object. Arguments: run_object (str|function|class): Trainable to run. If string, assumes it is an ID and does not modify it. Otherwise, returns a string corresponding to the run_object name. Returns: A string representing the trainable identifier. """ if isinstance(run_object, six.string_types): return run_object elif isinstance(run_object, types.FunctionType): if run_object.__name__ == "<lambda>": logger.warning( "Not auto-registering lambdas - resolving as variant.") return run_object else: name = run_object.__name__ register_trainable(name, run_object) return name elif isinstance(run_object, type): name = run_object.__name__ register_trainable(name, run_object) return name else: raise TuneError("Improper 'run' - not string nor trainable.")
[ "def", "_register_if_needed", "(", "cls", ",", "run_object", ")", ":", "if", "isinstance", "(", "run_object", ",", "six", ".", "string_types", ")", ":", "return", "run_object", "elif", "isinstance", "(", "run_object", ",", "types", ".", "FunctionType", ")", ":", "if", "run_object", ".", "__name__", "==", "\"<lambda>\"", ":", "logger", ".", "warning", "(", "\"Not auto-registering lambdas - resolving as variant.\"", ")", "return", "run_object", "else", ":", "name", "=", "run_object", ".", "__name__", "register_trainable", "(", "name", ",", "run_object", ")", "return", "name", "elif", "isinstance", "(", "run_object", ",", "type", ")", ":", "name", "=", "run_object", ".", "__name__", "register_trainable", "(", "name", ",", "run_object", ")", "return", "name", "else", ":", "raise", "TuneError", "(", "\"Improper 'run' - not string nor trainable.\"", ")" ]
Registers Trainable or Function at runtime. Assumes already registered if run_object is a string. Does not register lambdas because they could be part of variant generation. Also, does not inspect interface of given run_object. Arguments: run_object (str|function|class): Trainable to run. If string, assumes it is an ID and does not modify it. Otherwise, returns a string corresponding to the run_object name. Returns: A string representing the trainable identifier.
[ "Registers", "Trainable", "or", "Function", "at", "runtime", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/experiment.py#L145-L177
train
ray-project/ray
python/ray/experimental/array/distributed/linalg.py
tsqr
def tsqr(a): """Perform a QR decomposition of a tall-skinny matrix. Args: a: A distributed matrix with shape MxN (suppose K = min(M, N)). Returns: A tuple of q (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble(), then q_full.shape == (M, K). - np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True. - If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N). - np.allclose(r, np.triu(r)) == True. """ if len(a.shape) != 2: raise Exception("tsqr requires len(a.shape) == 2, but a.shape is " "{}".format(a.shape)) if a.num_blocks[1] != 1: raise Exception("tsqr requires a.num_blocks[1] == 1, but a.num_blocks " "is {}".format(a.num_blocks)) num_blocks = a.num_blocks[0] K = int(np.ceil(np.log2(num_blocks))) + 1 q_tree = np.empty((num_blocks, K), dtype=object) current_rs = [] for i in range(num_blocks): block = a.objectids[i, 0] q, r = ra.linalg.qr.remote(block) q_tree[i, 0] = q current_rs.append(r) for j in range(1, K): new_rs = [] for i in range(int(np.ceil(1.0 * len(current_rs) / 2))): stacked_rs = ra.vstack.remote(*current_rs[(2 * i):(2 * i + 2)]) q, r = ra.linalg.qr.remote(stacked_rs) q_tree[i, j] = q new_rs.append(r) current_rs = new_rs assert len(current_rs) == 1, "len(current_rs) = " + str(len(current_rs)) # handle the special case in which the whole DistArray "a" fits in one # block and has fewer rows than columns, this is a bit ugly so think about # how to remove it if a.shape[0] >= a.shape[1]: q_shape = a.shape else: q_shape = [a.shape[0], a.shape[0]] q_num_blocks = core.DistArray.compute_num_blocks(q_shape) q_objectids = np.empty(q_num_blocks, dtype=object) q_result = core.DistArray(q_shape, q_objectids) # reconstruct output for i in range(num_blocks): q_block_current = q_tree[i, 0] ith_index = i for j in range(1, K): if np.mod(ith_index, 2) == 0: lower = [0, 0] upper = [a.shape[1], core.BLOCK_SIZE] else: lower = [a.shape[1], 0] upper = [2 * a.shape[1], core.BLOCK_SIZE] ith_index //= 2 q_block_current = ra.dot.remote( q_block_current, ra.subarray.remote(q_tree[ith_index, j], lower, upper)) q_result.objectids[i] = q_block_current r = current_rs[0] return q_result, ray.get(r)
python
def tsqr(a): """Perform a QR decomposition of a tall-skinny matrix. Args: a: A distributed matrix with shape MxN (suppose K = min(M, N)). Returns: A tuple of q (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble(), then q_full.shape == (M, K). - np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True. - If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N). - np.allclose(r, np.triu(r)) == True. """ if len(a.shape) != 2: raise Exception("tsqr requires len(a.shape) == 2, but a.shape is " "{}".format(a.shape)) if a.num_blocks[1] != 1: raise Exception("tsqr requires a.num_blocks[1] == 1, but a.num_blocks " "is {}".format(a.num_blocks)) num_blocks = a.num_blocks[0] K = int(np.ceil(np.log2(num_blocks))) + 1 q_tree = np.empty((num_blocks, K), dtype=object) current_rs = [] for i in range(num_blocks): block = a.objectids[i, 0] q, r = ra.linalg.qr.remote(block) q_tree[i, 0] = q current_rs.append(r) for j in range(1, K): new_rs = [] for i in range(int(np.ceil(1.0 * len(current_rs) / 2))): stacked_rs = ra.vstack.remote(*current_rs[(2 * i):(2 * i + 2)]) q, r = ra.linalg.qr.remote(stacked_rs) q_tree[i, j] = q new_rs.append(r) current_rs = new_rs assert len(current_rs) == 1, "len(current_rs) = " + str(len(current_rs)) # handle the special case in which the whole DistArray "a" fits in one # block and has fewer rows than columns, this is a bit ugly so think about # how to remove it if a.shape[0] >= a.shape[1]: q_shape = a.shape else: q_shape = [a.shape[0], a.shape[0]] q_num_blocks = core.DistArray.compute_num_blocks(q_shape) q_objectids = np.empty(q_num_blocks, dtype=object) q_result = core.DistArray(q_shape, q_objectids) # reconstruct output for i in range(num_blocks): q_block_current = q_tree[i, 0] ith_index = i for j in range(1, K): if np.mod(ith_index, 2) == 0: lower = [0, 0] upper = [a.shape[1], core.BLOCK_SIZE] else: lower = [a.shape[1], 0] upper = [2 * a.shape[1], core.BLOCK_SIZE] ith_index //= 2 q_block_current = ra.dot.remote( q_block_current, ra.subarray.remote(q_tree[ith_index, j], lower, upper)) q_result.objectids[i] = q_block_current r = current_rs[0] return q_result, ray.get(r)
[ "def", "tsqr", "(", "a", ")", ":", "if", "len", "(", "a", ".", "shape", ")", "!=", "2", ":", "raise", "Exception", "(", "\"tsqr requires len(a.shape) == 2, but a.shape is \"", "\"{}\"", ".", "format", "(", "a", ".", "shape", ")", ")", "if", "a", ".", "num_blocks", "[", "1", "]", "!=", "1", ":", "raise", "Exception", "(", "\"tsqr requires a.num_blocks[1] == 1, but a.num_blocks \"", "\"is {}\"", ".", "format", "(", "a", ".", "num_blocks", ")", ")", "num_blocks", "=", "a", ".", "num_blocks", "[", "0", "]", "K", "=", "int", "(", "np", ".", "ceil", "(", "np", ".", "log2", "(", "num_blocks", ")", ")", ")", "+", "1", "q_tree", "=", "np", ".", "empty", "(", "(", "num_blocks", ",", "K", ")", ",", "dtype", "=", "object", ")", "current_rs", "=", "[", "]", "for", "i", "in", "range", "(", "num_blocks", ")", ":", "block", "=", "a", ".", "objectids", "[", "i", ",", "0", "]", "q", ",", "r", "=", "ra", ".", "linalg", ".", "qr", ".", "remote", "(", "block", ")", "q_tree", "[", "i", ",", "0", "]", "=", "q", "current_rs", ".", "append", "(", "r", ")", "for", "j", "in", "range", "(", "1", ",", "K", ")", ":", "new_rs", "=", "[", "]", "for", "i", "in", "range", "(", "int", "(", "np", ".", "ceil", "(", "1.0", "*", "len", "(", "current_rs", ")", "/", "2", ")", ")", ")", ":", "stacked_rs", "=", "ra", ".", "vstack", ".", "remote", "(", "*", "current_rs", "[", "(", "2", "*", "i", ")", ":", "(", "2", "*", "i", "+", "2", ")", "]", ")", "q", ",", "r", "=", "ra", ".", "linalg", ".", "qr", ".", "remote", "(", "stacked_rs", ")", "q_tree", "[", "i", ",", "j", "]", "=", "q", "new_rs", ".", "append", "(", "r", ")", "current_rs", "=", "new_rs", "assert", "len", "(", "current_rs", ")", "==", "1", ",", "\"len(current_rs) = \"", "+", "str", "(", "len", "(", "current_rs", ")", ")", "# handle the special case in which the whole DistArray \"a\" fits in one", "# block and has fewer rows than columns, this is a bit ugly so think about", "# how to remove it", "if", "a", ".", "shape", "[", "0", "]", ">=", "a", ".", "shape", "[", "1", "]", ":", "q_shape", "=", "a", ".", "shape", "else", ":", "q_shape", "=", "[", "a", ".", "shape", "[", "0", "]", ",", "a", ".", "shape", "[", "0", "]", "]", "q_num_blocks", "=", "core", ".", "DistArray", ".", "compute_num_blocks", "(", "q_shape", ")", "q_objectids", "=", "np", ".", "empty", "(", "q_num_blocks", ",", "dtype", "=", "object", ")", "q_result", "=", "core", ".", "DistArray", "(", "q_shape", ",", "q_objectids", ")", "# reconstruct output", "for", "i", "in", "range", "(", "num_blocks", ")", ":", "q_block_current", "=", "q_tree", "[", "i", ",", "0", "]", "ith_index", "=", "i", "for", "j", "in", "range", "(", "1", ",", "K", ")", ":", "if", "np", ".", "mod", "(", "ith_index", ",", "2", ")", "==", "0", ":", "lower", "=", "[", "0", ",", "0", "]", "upper", "=", "[", "a", ".", "shape", "[", "1", "]", ",", "core", ".", "BLOCK_SIZE", "]", "else", ":", "lower", "=", "[", "a", ".", "shape", "[", "1", "]", ",", "0", "]", "upper", "=", "[", "2", "*", "a", ".", "shape", "[", "1", "]", ",", "core", ".", "BLOCK_SIZE", "]", "ith_index", "//=", "2", "q_block_current", "=", "ra", ".", "dot", ".", "remote", "(", "q_block_current", ",", "ra", ".", "subarray", ".", "remote", "(", "q_tree", "[", "ith_index", ",", "j", "]", ",", "lower", ",", "upper", ")", ")", "q_result", ".", "objectids", "[", "i", "]", "=", "q_block_current", "r", "=", "current_rs", "[", "0", "]", "return", "q_result", ",", "ray", ".", "get", "(", "r", ")" ]
Perform a QR decomposition of a tall-skinny matrix. Args: a: A distributed matrix with shape MxN (suppose K = min(M, N)). Returns: A tuple of q (a DistArray) and r (a numpy array) satisfying the following. - If q_full = ray.get(DistArray, q).assemble(), then q_full.shape == (M, K). - np.allclose(np.dot(q_full.T, q_full), np.eye(K)) == True. - If r_val = ray.get(np.ndarray, r), then r_val.shape == (K, N). - np.allclose(r, np.triu(r)) == True.
[ "Perform", "a", "QR", "decomposition", "of", "a", "tall", "-", "skinny", "matrix", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/linalg.py#L15-L84
train
ray-project/ray
python/ray/experimental/array/distributed/linalg.py
modified_lu
def modified_lu(q): """Perform a modified LU decomposition of a matrix. This takes a matrix q with orthonormal columns, returns l, u, s such that q - s = l * u. Args: q: A two dimensional orthonormal matrix q. Returns: A tuple of a lower triangular matrix l, an upper triangular matrix u, and a a vector representing a diagonal matrix s such that q - s = l * u. """ q = q.assemble() m, b = q.shape[0], q.shape[1] S = np.zeros(b) q_work = np.copy(q) for i in range(b): S[i] = -1 * np.sign(q_work[i, i]) q_work[i, i] -= S[i] # Scale ith column of L by diagonal element. q_work[(i + 1):m, i] /= q_work[i, i] # Perform Schur complement update. q_work[(i + 1):m, (i + 1):b] -= np.outer(q_work[(i + 1):m, i], q_work[i, (i + 1):b]) L = np.tril(q_work) for i in range(b): L[i, i] = 1 U = np.triu(q_work)[:b, :] # TODO(rkn): Get rid of the put below. return ray.get(core.numpy_to_dist.remote(ray.put(L))), U, S
python
def modified_lu(q): """Perform a modified LU decomposition of a matrix. This takes a matrix q with orthonormal columns, returns l, u, s such that q - s = l * u. Args: q: A two dimensional orthonormal matrix q. Returns: A tuple of a lower triangular matrix l, an upper triangular matrix u, and a a vector representing a diagonal matrix s such that q - s = l * u. """ q = q.assemble() m, b = q.shape[0], q.shape[1] S = np.zeros(b) q_work = np.copy(q) for i in range(b): S[i] = -1 * np.sign(q_work[i, i]) q_work[i, i] -= S[i] # Scale ith column of L by diagonal element. q_work[(i + 1):m, i] /= q_work[i, i] # Perform Schur complement update. q_work[(i + 1):m, (i + 1):b] -= np.outer(q_work[(i + 1):m, i], q_work[i, (i + 1):b]) L = np.tril(q_work) for i in range(b): L[i, i] = 1 U = np.triu(q_work)[:b, :] # TODO(rkn): Get rid of the put below. return ray.get(core.numpy_to_dist.remote(ray.put(L))), U, S
[ "def", "modified_lu", "(", "q", ")", ":", "q", "=", "q", ".", "assemble", "(", ")", "m", ",", "b", "=", "q", ".", "shape", "[", "0", "]", ",", "q", ".", "shape", "[", "1", "]", "S", "=", "np", ".", "zeros", "(", "b", ")", "q_work", "=", "np", ".", "copy", "(", "q", ")", "for", "i", "in", "range", "(", "b", ")", ":", "S", "[", "i", "]", "=", "-", "1", "*", "np", ".", "sign", "(", "q_work", "[", "i", ",", "i", "]", ")", "q_work", "[", "i", ",", "i", "]", "-=", "S", "[", "i", "]", "# Scale ith column of L by diagonal element.", "q_work", "[", "(", "i", "+", "1", ")", ":", "m", ",", "i", "]", "/=", "q_work", "[", "i", ",", "i", "]", "# Perform Schur complement update.", "q_work", "[", "(", "i", "+", "1", ")", ":", "m", ",", "(", "i", "+", "1", ")", ":", "b", "]", "-=", "np", ".", "outer", "(", "q_work", "[", "(", "i", "+", "1", ")", ":", "m", ",", "i", "]", ",", "q_work", "[", "i", ",", "(", "i", "+", "1", ")", ":", "b", "]", ")", "L", "=", "np", ".", "tril", "(", "q_work", ")", "for", "i", "in", "range", "(", "b", ")", ":", "L", "[", "i", ",", "i", "]", "=", "1", "U", "=", "np", ".", "triu", "(", "q_work", ")", "[", ":", "b", ",", ":", "]", "# TODO(rkn): Get rid of the put below.", "return", "ray", ".", "get", "(", "core", ".", "numpy_to_dist", ".", "remote", "(", "ray", ".", "put", "(", "L", ")", ")", ")", ",", "U", ",", "S" ]
Perform a modified LU decomposition of a matrix. This takes a matrix q with orthonormal columns, returns l, u, s such that q - s = l * u. Args: q: A two dimensional orthonormal matrix q. Returns: A tuple of a lower triangular matrix l, an upper triangular matrix u, and a a vector representing a diagonal matrix s such that q - s = l * u.
[ "Perform", "a", "modified", "LU", "decomposition", "of", "a", "matrix", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/array/distributed/linalg.py#L91-L125
train
ray-project/ray
python/ray/tune/trial_runner.py
_naturalize
def _naturalize(string): """Provides a natural representation for string for nice sorting.""" splits = re.split("([0-9]+)", string) return [int(text) if text.isdigit() else text.lower() for text in splits]
python
def _naturalize(string): """Provides a natural representation for string for nice sorting.""" splits = re.split("([0-9]+)", string) return [int(text) if text.isdigit() else text.lower() for text in splits]
[ "def", "_naturalize", "(", "string", ")", ":", "splits", "=", "re", ".", "split", "(", "\"([0-9]+)\"", ",", "string", ")", "return", "[", "int", "(", "text", ")", "if", "text", ".", "isdigit", "(", ")", "else", "text", ".", "lower", "(", ")", "for", "text", "in", "splits", "]" ]
Provides a natural representation for string for nice sorting.
[ "Provides", "a", "natural", "representation", "for", "string", "for", "nice", "sorting", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L30-L33
train
ray-project/ray
python/ray/tune/trial_runner.py
_find_newest_ckpt
def _find_newest_ckpt(ckpt_dir): """Returns path to most recently modified checkpoint.""" full_paths = [ os.path.join(ckpt_dir, fname) for fname in os.listdir(ckpt_dir) if fname.startswith("experiment_state") and fname.endswith(".json") ] return max(full_paths)
python
def _find_newest_ckpt(ckpt_dir): """Returns path to most recently modified checkpoint.""" full_paths = [ os.path.join(ckpt_dir, fname) for fname in os.listdir(ckpt_dir) if fname.startswith("experiment_state") and fname.endswith(".json") ] return max(full_paths)
[ "def", "_find_newest_ckpt", "(", "ckpt_dir", ")", ":", "full_paths", "=", "[", "os", ".", "path", ".", "join", "(", "ckpt_dir", ",", "fname", ")", "for", "fname", "in", "os", ".", "listdir", "(", "ckpt_dir", ")", "if", "fname", ".", "startswith", "(", "\"experiment_state\"", ")", "and", "fname", ".", "endswith", "(", "\".json\"", ")", "]", "return", "max", "(", "full_paths", ")" ]
Returns path to most recently modified checkpoint.
[ "Returns", "path", "to", "most", "recently", "modified", "checkpoint", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L36-L42
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.checkpoint
def checkpoint(self): """Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantiated. """ if not self._metadata_checkpoint_dir: return metadata_checkpoint_dir = self._metadata_checkpoint_dir if not os.path.exists(metadata_checkpoint_dir): os.makedirs(metadata_checkpoint_dir) runner_state = { "checkpoints": list( self.trial_executor.get_checkpoints().values()), "runner_data": self.__getstate__(), "timestamp": time.time() } tmp_file_name = os.path.join(metadata_checkpoint_dir, ".tmp_checkpoint") with open(tmp_file_name, "w") as f: json.dump(runner_state, f, indent=2, cls=_TuneFunctionEncoder) os.rename( tmp_file_name, os.path.join(metadata_checkpoint_dir, TrialRunner.CKPT_FILE_TMPL.format(self._session_str))) return metadata_checkpoint_dir
python
def checkpoint(self): """Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantiated. """ if not self._metadata_checkpoint_dir: return metadata_checkpoint_dir = self._metadata_checkpoint_dir if not os.path.exists(metadata_checkpoint_dir): os.makedirs(metadata_checkpoint_dir) runner_state = { "checkpoints": list( self.trial_executor.get_checkpoints().values()), "runner_data": self.__getstate__(), "timestamp": time.time() } tmp_file_name = os.path.join(metadata_checkpoint_dir, ".tmp_checkpoint") with open(tmp_file_name, "w") as f: json.dump(runner_state, f, indent=2, cls=_TuneFunctionEncoder) os.rename( tmp_file_name, os.path.join(metadata_checkpoint_dir, TrialRunner.CKPT_FILE_TMPL.format(self._session_str))) return metadata_checkpoint_dir
[ "def", "checkpoint", "(", "self", ")", ":", "if", "not", "self", ".", "_metadata_checkpoint_dir", ":", "return", "metadata_checkpoint_dir", "=", "self", ".", "_metadata_checkpoint_dir", "if", "not", "os", ".", "path", ".", "exists", "(", "metadata_checkpoint_dir", ")", ":", "os", ".", "makedirs", "(", "metadata_checkpoint_dir", ")", "runner_state", "=", "{", "\"checkpoints\"", ":", "list", "(", "self", ".", "trial_executor", ".", "get_checkpoints", "(", ")", ".", "values", "(", ")", ")", ",", "\"runner_data\"", ":", "self", ".", "__getstate__", "(", ")", ",", "\"timestamp\"", ":", "time", ".", "time", "(", ")", "}", "tmp_file_name", "=", "os", ".", "path", ".", "join", "(", "metadata_checkpoint_dir", ",", "\".tmp_checkpoint\"", ")", "with", "open", "(", "tmp_file_name", ",", "\"w\"", ")", "as", "f", ":", "json", ".", "dump", "(", "runner_state", ",", "f", ",", "indent", "=", "2", ",", "cls", "=", "_TuneFunctionEncoder", ")", "os", ".", "rename", "(", "tmp_file_name", ",", "os", ".", "path", ".", "join", "(", "metadata_checkpoint_dir", ",", "TrialRunner", ".", "CKPT_FILE_TMPL", ".", "format", "(", "self", ".", "_session_str", ")", ")", ")", "return", "metadata_checkpoint_dir" ]
Saves execution state to `self._metadata_checkpoint_dir`. Overwrites the current session checkpoint, which starts when self is instantiated.
[ "Saves", "execution", "state", "to", "self", ".", "_metadata_checkpoint_dir", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L167-L193
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.restore
def restore(cls, metadata_checkpoint_dir, search_alg=None, scheduler=None, trial_executor=None): """Restores all checkpointed trials from previous run. Requires user to manually re-register their objects. Also stops all ongoing trials. Args: metadata_checkpoint_dir (str): Path to metadata checkpoints. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. trial_executor (TrialExecutor): Manage the execution of trials. Returns: runner (TrialRunner): A TrialRunner to resume experiments from. """ newest_ckpt_path = _find_newest_ckpt(metadata_checkpoint_dir) with open(newest_ckpt_path, "r") as f: runner_state = json.load(f, cls=_TuneFunctionDecoder) logger.warning("".join([ "Attempting to resume experiment from {}. ".format( metadata_checkpoint_dir), "This feature is experimental, " "and may not work with all search algorithms. ", "This will ignore any new changes to the specification." ])) from ray.tune.suggest import BasicVariantGenerator runner = TrialRunner( search_alg or BasicVariantGenerator(), scheduler=scheduler, trial_executor=trial_executor) runner.__setstate__(runner_state["runner_data"]) trials = [] for trial_cp in runner_state["checkpoints"]: new_trial = Trial(trial_cp["trainable_name"]) new_trial.__setstate__(trial_cp) trials += [new_trial] for trial in sorted( trials, key=lambda t: t.last_update_time, reverse=True): runner.add_trial(trial) return runner
python
def restore(cls, metadata_checkpoint_dir, search_alg=None, scheduler=None, trial_executor=None): """Restores all checkpointed trials from previous run. Requires user to manually re-register their objects. Also stops all ongoing trials. Args: metadata_checkpoint_dir (str): Path to metadata checkpoints. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. trial_executor (TrialExecutor): Manage the execution of trials. Returns: runner (TrialRunner): A TrialRunner to resume experiments from. """ newest_ckpt_path = _find_newest_ckpt(metadata_checkpoint_dir) with open(newest_ckpt_path, "r") as f: runner_state = json.load(f, cls=_TuneFunctionDecoder) logger.warning("".join([ "Attempting to resume experiment from {}. ".format( metadata_checkpoint_dir), "This feature is experimental, " "and may not work with all search algorithms. ", "This will ignore any new changes to the specification." ])) from ray.tune.suggest import BasicVariantGenerator runner = TrialRunner( search_alg or BasicVariantGenerator(), scheduler=scheduler, trial_executor=trial_executor) runner.__setstate__(runner_state["runner_data"]) trials = [] for trial_cp in runner_state["checkpoints"]: new_trial = Trial(trial_cp["trainable_name"]) new_trial.__setstate__(trial_cp) trials += [new_trial] for trial in sorted( trials, key=lambda t: t.last_update_time, reverse=True): runner.add_trial(trial) return runner
[ "def", "restore", "(", "cls", ",", "metadata_checkpoint_dir", ",", "search_alg", "=", "None", ",", "scheduler", "=", "None", ",", "trial_executor", "=", "None", ")", ":", "newest_ckpt_path", "=", "_find_newest_ckpt", "(", "metadata_checkpoint_dir", ")", "with", "open", "(", "newest_ckpt_path", ",", "\"r\"", ")", "as", "f", ":", "runner_state", "=", "json", ".", "load", "(", "f", ",", "cls", "=", "_TuneFunctionDecoder", ")", "logger", ".", "warning", "(", "\"\"", ".", "join", "(", "[", "\"Attempting to resume experiment from {}. \"", ".", "format", "(", "metadata_checkpoint_dir", ")", ",", "\"This feature is experimental, \"", "\"and may not work with all search algorithms. \"", ",", "\"This will ignore any new changes to the specification.\"", "]", ")", ")", "from", "ray", ".", "tune", ".", "suggest", "import", "BasicVariantGenerator", "runner", "=", "TrialRunner", "(", "search_alg", "or", "BasicVariantGenerator", "(", ")", ",", "scheduler", "=", "scheduler", ",", "trial_executor", "=", "trial_executor", ")", "runner", ".", "__setstate__", "(", "runner_state", "[", "\"runner_data\"", "]", ")", "trials", "=", "[", "]", "for", "trial_cp", "in", "runner_state", "[", "\"checkpoints\"", "]", ":", "new_trial", "=", "Trial", "(", "trial_cp", "[", "\"trainable_name\"", "]", ")", "new_trial", ".", "__setstate__", "(", "trial_cp", ")", "trials", "+=", "[", "new_trial", "]", "for", "trial", "in", "sorted", "(", "trials", ",", "key", "=", "lambda", "t", ":", "t", ".", "last_update_time", ",", "reverse", "=", "True", ")", ":", "runner", ".", "add_trial", "(", "trial", ")", "return", "runner" ]
Restores all checkpointed trials from previous run. Requires user to manually re-register their objects. Also stops all ongoing trials. Args: metadata_checkpoint_dir (str): Path to metadata checkpoints. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. trial_executor (TrialExecutor): Manage the execution of trials. Returns: runner (TrialRunner): A TrialRunner to resume experiments from.
[ "Restores", "all", "checkpointed", "trials", "from", "previous", "run", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L196-L245
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.is_finished
def is_finished(self): """Returns whether all trials have finished running.""" if self._total_time > self._global_time_limit: logger.warning("Exceeded global time limit {} / {}".format( self._total_time, self._global_time_limit)) return True trials_done = all(trial.is_finished() for trial in self._trials) return trials_done and self._search_alg.is_finished()
python
def is_finished(self): """Returns whether all trials have finished running.""" if self._total_time > self._global_time_limit: logger.warning("Exceeded global time limit {} / {}".format( self._total_time, self._global_time_limit)) return True trials_done = all(trial.is_finished() for trial in self._trials) return trials_done and self._search_alg.is_finished()
[ "def", "is_finished", "(", "self", ")", ":", "if", "self", ".", "_total_time", ">", "self", ".", "_global_time_limit", ":", "logger", ".", "warning", "(", "\"Exceeded global time limit {} / {}\"", ".", "format", "(", "self", ".", "_total_time", ",", "self", ".", "_global_time_limit", ")", ")", "return", "True", "trials_done", "=", "all", "(", "trial", ".", "is_finished", "(", ")", "for", "trial", "in", "self", ".", "_trials", ")", "return", "trials_done", "and", "self", ".", "_search_alg", ".", "is_finished", "(", ")" ]
Returns whether all trials have finished running.
[ "Returns", "whether", "all", "trials", "have", "finished", "running", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L247-L256
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.step
def step(self): """Runs one step of the trial event loop. Callers should typically run this method repeatedly in a loop. They may inspect or modify the runner's state in between calls to step(). """ if self.is_finished(): raise TuneError("Called step when all trials finished?") with warn_if_slow("on_step_begin"): self.trial_executor.on_step_begin() next_trial = self._get_next_trial() # blocking if next_trial is not None: with warn_if_slow("start_trial"): self.trial_executor.start_trial(next_trial) elif self.trial_executor.get_running_trials(): self._process_events() # blocking else: for trial in self._trials: if trial.status == Trial.PENDING: if not self.has_resources(trial.resources): raise TuneError( ("Insufficient cluster resources to launch trial: " "trial requested {} but the cluster has only {}. " "Pass `queue_trials=True` in " "ray.tune.run() or on the command " "line to queue trials until the cluster scales " "up. {}").format( trial.resources.summary_string(), self.trial_executor.resource_string(), trial._get_trainable_cls().resource_help( trial.config))) elif trial.status == Trial.PAUSED: raise TuneError( "There are paused trials, but no more pending " "trials with sufficient resources.") try: with warn_if_slow("experiment_checkpoint"): self.checkpoint() except Exception: logger.exception("Trial Runner checkpointing failed.") self._iteration += 1 if self._server: with warn_if_slow("server"): self._process_requests() if self.is_finished(): self._server.shutdown() with warn_if_slow("on_step_end"): self.trial_executor.on_step_end()
python
def step(self): """Runs one step of the trial event loop. Callers should typically run this method repeatedly in a loop. They may inspect or modify the runner's state in between calls to step(). """ if self.is_finished(): raise TuneError("Called step when all trials finished?") with warn_if_slow("on_step_begin"): self.trial_executor.on_step_begin() next_trial = self._get_next_trial() # blocking if next_trial is not None: with warn_if_slow("start_trial"): self.trial_executor.start_trial(next_trial) elif self.trial_executor.get_running_trials(): self._process_events() # blocking else: for trial in self._trials: if trial.status == Trial.PENDING: if not self.has_resources(trial.resources): raise TuneError( ("Insufficient cluster resources to launch trial: " "trial requested {} but the cluster has only {}. " "Pass `queue_trials=True` in " "ray.tune.run() or on the command " "line to queue trials until the cluster scales " "up. {}").format( trial.resources.summary_string(), self.trial_executor.resource_string(), trial._get_trainable_cls().resource_help( trial.config))) elif trial.status == Trial.PAUSED: raise TuneError( "There are paused trials, but no more pending " "trials with sufficient resources.") try: with warn_if_slow("experiment_checkpoint"): self.checkpoint() except Exception: logger.exception("Trial Runner checkpointing failed.") self._iteration += 1 if self._server: with warn_if_slow("server"): self._process_requests() if self.is_finished(): self._server.shutdown() with warn_if_slow("on_step_end"): self.trial_executor.on_step_end()
[ "def", "step", "(", "self", ")", ":", "if", "self", ".", "is_finished", "(", ")", ":", "raise", "TuneError", "(", "\"Called step when all trials finished?\"", ")", "with", "warn_if_slow", "(", "\"on_step_begin\"", ")", ":", "self", ".", "trial_executor", ".", "on_step_begin", "(", ")", "next_trial", "=", "self", ".", "_get_next_trial", "(", ")", "# blocking", "if", "next_trial", "is", "not", "None", ":", "with", "warn_if_slow", "(", "\"start_trial\"", ")", ":", "self", ".", "trial_executor", ".", "start_trial", "(", "next_trial", ")", "elif", "self", ".", "trial_executor", ".", "get_running_trials", "(", ")", ":", "self", ".", "_process_events", "(", ")", "# blocking", "else", ":", "for", "trial", "in", "self", ".", "_trials", ":", "if", "trial", ".", "status", "==", "Trial", ".", "PENDING", ":", "if", "not", "self", ".", "has_resources", "(", "trial", ".", "resources", ")", ":", "raise", "TuneError", "(", "(", "\"Insufficient cluster resources to launch trial: \"", "\"trial requested {} but the cluster has only {}. \"", "\"Pass `queue_trials=True` in \"", "\"ray.tune.run() or on the command \"", "\"line to queue trials until the cluster scales \"", "\"up. {}\"", ")", ".", "format", "(", "trial", ".", "resources", ".", "summary_string", "(", ")", ",", "self", ".", "trial_executor", ".", "resource_string", "(", ")", ",", "trial", ".", "_get_trainable_cls", "(", ")", ".", "resource_help", "(", "trial", ".", "config", ")", ")", ")", "elif", "trial", ".", "status", "==", "Trial", ".", "PAUSED", ":", "raise", "TuneError", "(", "\"There are paused trials, but no more pending \"", "\"trials with sufficient resources.\"", ")", "try", ":", "with", "warn_if_slow", "(", "\"experiment_checkpoint\"", ")", ":", "self", ".", "checkpoint", "(", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "\"Trial Runner checkpointing failed.\"", ")", "self", ".", "_iteration", "+=", "1", "if", "self", ".", "_server", ":", "with", "warn_if_slow", "(", "\"server\"", ")", ":", "self", ".", "_process_requests", "(", ")", "if", "self", ".", "is_finished", "(", ")", ":", "self", ".", "_server", ".", "shutdown", "(", ")", "with", "warn_if_slow", "(", "\"on_step_end\"", ")", ":", "self", ".", "trial_executor", ".", "on_step_end", "(", ")" ]
Runs one step of the trial event loop. Callers should typically run this method repeatedly in a loop. They may inspect or modify the runner's state in between calls to step().
[ "Runs", "one", "step", "of", "the", "trial", "event", "loop", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L258-L308
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.add_trial
def add_trial(self, trial): """Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue. """ trial.set_verbose(self._verbose) self._trials.append(trial) with warn_if_slow("scheduler.on_trial_add"): self._scheduler_alg.on_trial_add(self, trial) self.trial_executor.try_checkpoint_metadata(trial)
python
def add_trial(self, trial): """Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue. """ trial.set_verbose(self._verbose) self._trials.append(trial) with warn_if_slow("scheduler.on_trial_add"): self._scheduler_alg.on_trial_add(self, trial) self.trial_executor.try_checkpoint_metadata(trial)
[ "def", "add_trial", "(", "self", ",", "trial", ")", ":", "trial", ".", "set_verbose", "(", "self", ".", "_verbose", ")", "self", ".", "_trials", ".", "append", "(", "trial", ")", "with", "warn_if_slow", "(", "\"scheduler.on_trial_add\"", ")", ":", "self", ".", "_scheduler_alg", ".", "on_trial_add", "(", "self", ",", "trial", ")", "self", ".", "trial_executor", ".", "try_checkpoint_metadata", "(", "trial", ")" ]
Adds a new trial to this TrialRunner. Trials may be added at any time. Args: trial (Trial): Trial to queue.
[ "Adds", "a", "new", "trial", "to", "this", "TrialRunner", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L322-L334
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.debug_string
def debug_string(self, max_debug=MAX_DEBUG_TRIALS): """Returns a human readable message for printing to the console.""" messages = self._debug_messages() states = collections.defaultdict(set) limit_per_state = collections.Counter() for t in self._trials: states[t.status].add(t) # Show at most max_debug total, but divide the limit fairly while max_debug > 0: start_num = max_debug for s in states: if limit_per_state[s] >= len(states[s]): continue max_debug -= 1 limit_per_state[s] += 1 if max_debug == start_num: break for local_dir in sorted({t.local_dir for t in self._trials}): messages.append("Result logdir: {}".format(local_dir)) num_trials_per_state = { state: len(trials) for state, trials in states.items() } total_number_of_trials = sum(num_trials_per_state.values()) if total_number_of_trials > 0: messages.append("Number of trials: {} ({})" "".format(total_number_of_trials, num_trials_per_state)) for state, trials in sorted(states.items()): limit = limit_per_state[state] messages.append("{} trials:".format(state)) sorted_trials = sorted( trials, key=lambda t: _naturalize(t.experiment_tag)) if len(trials) > limit: tail_length = limit // 2 first = sorted_trials[:tail_length] for t in first: messages.append(" - {}:\t{}".format( t, t.progress_string())) messages.append( " ... {} not shown".format(len(trials) - tail_length * 2)) last = sorted_trials[-tail_length:] for t in last: messages.append(" - {}:\t{}".format( t, t.progress_string())) else: for t in sorted_trials: messages.append(" - {}:\t{}".format( t, t.progress_string())) return "\n".join(messages) + "\n"
python
def debug_string(self, max_debug=MAX_DEBUG_TRIALS): """Returns a human readable message for printing to the console.""" messages = self._debug_messages() states = collections.defaultdict(set) limit_per_state = collections.Counter() for t in self._trials: states[t.status].add(t) # Show at most max_debug total, but divide the limit fairly while max_debug > 0: start_num = max_debug for s in states: if limit_per_state[s] >= len(states[s]): continue max_debug -= 1 limit_per_state[s] += 1 if max_debug == start_num: break for local_dir in sorted({t.local_dir for t in self._trials}): messages.append("Result logdir: {}".format(local_dir)) num_trials_per_state = { state: len(trials) for state, trials in states.items() } total_number_of_trials = sum(num_trials_per_state.values()) if total_number_of_trials > 0: messages.append("Number of trials: {} ({})" "".format(total_number_of_trials, num_trials_per_state)) for state, trials in sorted(states.items()): limit = limit_per_state[state] messages.append("{} trials:".format(state)) sorted_trials = sorted( trials, key=lambda t: _naturalize(t.experiment_tag)) if len(trials) > limit: tail_length = limit // 2 first = sorted_trials[:tail_length] for t in first: messages.append(" - {}:\t{}".format( t, t.progress_string())) messages.append( " ... {} not shown".format(len(trials) - tail_length * 2)) last = sorted_trials[-tail_length:] for t in last: messages.append(" - {}:\t{}".format( t, t.progress_string())) else: for t in sorted_trials: messages.append(" - {}:\t{}".format( t, t.progress_string())) return "\n".join(messages) + "\n"
[ "def", "debug_string", "(", "self", ",", "max_debug", "=", "MAX_DEBUG_TRIALS", ")", ":", "messages", "=", "self", ".", "_debug_messages", "(", ")", "states", "=", "collections", ".", "defaultdict", "(", "set", ")", "limit_per_state", "=", "collections", ".", "Counter", "(", ")", "for", "t", "in", "self", ".", "_trials", ":", "states", "[", "t", ".", "status", "]", ".", "add", "(", "t", ")", "# Show at most max_debug total, but divide the limit fairly", "while", "max_debug", ">", "0", ":", "start_num", "=", "max_debug", "for", "s", "in", "states", ":", "if", "limit_per_state", "[", "s", "]", ">=", "len", "(", "states", "[", "s", "]", ")", ":", "continue", "max_debug", "-=", "1", "limit_per_state", "[", "s", "]", "+=", "1", "if", "max_debug", "==", "start_num", ":", "break", "for", "local_dir", "in", "sorted", "(", "{", "t", ".", "local_dir", "for", "t", "in", "self", ".", "_trials", "}", ")", ":", "messages", ".", "append", "(", "\"Result logdir: {}\"", ".", "format", "(", "local_dir", ")", ")", "num_trials_per_state", "=", "{", "state", ":", "len", "(", "trials", ")", "for", "state", ",", "trials", "in", "states", ".", "items", "(", ")", "}", "total_number_of_trials", "=", "sum", "(", "num_trials_per_state", ".", "values", "(", ")", ")", "if", "total_number_of_trials", ">", "0", ":", "messages", ".", "append", "(", "\"Number of trials: {} ({})\"", "\"\"", ".", "format", "(", "total_number_of_trials", ",", "num_trials_per_state", ")", ")", "for", "state", ",", "trials", "in", "sorted", "(", "states", ".", "items", "(", ")", ")", ":", "limit", "=", "limit_per_state", "[", "state", "]", "messages", ".", "append", "(", "\"{} trials:\"", ".", "format", "(", "state", ")", ")", "sorted_trials", "=", "sorted", "(", "trials", ",", "key", "=", "lambda", "t", ":", "_naturalize", "(", "t", ".", "experiment_tag", ")", ")", "if", "len", "(", "trials", ")", ">", "limit", ":", "tail_length", "=", "limit", "//", "2", "first", "=", "sorted_trials", "[", ":", "tail_length", "]", "for", "t", "in", "first", ":", "messages", ".", "append", "(", "\" - {}:\\t{}\"", ".", "format", "(", "t", ",", "t", ".", "progress_string", "(", ")", ")", ")", "messages", ".", "append", "(", "\" ... {} not shown\"", ".", "format", "(", "len", "(", "trials", ")", "-", "tail_length", "*", "2", ")", ")", "last", "=", "sorted_trials", "[", "-", "tail_length", ":", "]", "for", "t", "in", "last", ":", "messages", ".", "append", "(", "\" - {}:\\t{}\"", ".", "format", "(", "t", ",", "t", ".", "progress_string", "(", ")", ")", ")", "else", ":", "for", "t", "in", "sorted_trials", ":", "messages", ".", "append", "(", "\" - {}:\\t{}\"", ".", "format", "(", "t", ",", "t", ".", "progress_string", "(", ")", ")", ")", "return", "\"\\n\"", ".", "join", "(", "messages", ")", "+", "\"\\n\"" ]
Returns a human readable message for printing to the console.
[ "Returns", "a", "human", "readable", "message", "for", "printing", "to", "the", "console", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L336-L390
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._get_next_trial
def _get_next_trial(self): """Replenishes queue. Blocks if all trials queued have finished, but search algorithm is still not finished. """ trials_done = all(trial.is_finished() for trial in self._trials) wait_for_trial = trials_done and not self._search_alg.is_finished() self._update_trial_queue(blocking=wait_for_trial) with warn_if_slow("choose_trial_to_run"): trial = self._scheduler_alg.choose_trial_to_run(self) return trial
python
def _get_next_trial(self): """Replenishes queue. Blocks if all trials queued have finished, but search algorithm is still not finished. """ trials_done = all(trial.is_finished() for trial in self._trials) wait_for_trial = trials_done and not self._search_alg.is_finished() self._update_trial_queue(blocking=wait_for_trial) with warn_if_slow("choose_trial_to_run"): trial = self._scheduler_alg.choose_trial_to_run(self) return trial
[ "def", "_get_next_trial", "(", "self", ")", ":", "trials_done", "=", "all", "(", "trial", ".", "is_finished", "(", ")", "for", "trial", "in", "self", ".", "_trials", ")", "wait_for_trial", "=", "trials_done", "and", "not", "self", ".", "_search_alg", ".", "is_finished", "(", ")", "self", ".", "_update_trial_queue", "(", "blocking", "=", "wait_for_trial", ")", "with", "warn_if_slow", "(", "\"choose_trial_to_run\"", ")", ":", "trial", "=", "self", ".", "_scheduler_alg", ".", "choose_trial_to_run", "(", "self", ")", "return", "trial" ]
Replenishes queue. Blocks if all trials queued have finished, but search algorithm is still not finished.
[ "Replenishes", "queue", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L423-L434
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._checkpoint_trial_if_needed
def _checkpoint_trial_if_needed(self, trial): """Checkpoints trial based off trial.last_result.""" if trial.should_checkpoint(): # Save trial runtime if possible if hasattr(trial, "runner") and trial.runner: self.trial_executor.save(trial, storage=Checkpoint.DISK) self.trial_executor.try_checkpoint_metadata(trial)
python
def _checkpoint_trial_if_needed(self, trial): """Checkpoints trial based off trial.last_result.""" if trial.should_checkpoint(): # Save trial runtime if possible if hasattr(trial, "runner") and trial.runner: self.trial_executor.save(trial, storage=Checkpoint.DISK) self.trial_executor.try_checkpoint_metadata(trial)
[ "def", "_checkpoint_trial_if_needed", "(", "self", ",", "trial", ")", ":", "if", "trial", ".", "should_checkpoint", "(", ")", ":", "# Save trial runtime if possible", "if", "hasattr", "(", "trial", ",", "\"runner\"", ")", "and", "trial", ".", "runner", ":", "self", ".", "trial_executor", ".", "save", "(", "trial", ",", "storage", "=", "Checkpoint", ".", "DISK", ")", "self", ".", "trial_executor", ".", "try_checkpoint_metadata", "(", "trial", ")" ]
Checkpoints trial based off trial.last_result.
[ "Checkpoints", "trial", "based", "off", "trial", ".", "last_result", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L506-L512
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._try_recover
def _try_recover(self, trial, error_msg): """Tries to recover trial. Notifies SearchAlgorithm and Scheduler if failure to recover. Args: trial (Trial): Trial to recover. error_msg (str): Error message from prior to invoking this method. """ try: self.trial_executor.stop_trial( trial, error=error_msg is not None, error_msg=error_msg, stop_logger=False) trial.result_logger.flush() if self.trial_executor.has_resources(trial.resources): logger.info("Attempting to recover" " trial state from last checkpoint.") self.trial_executor.start_trial(trial) if trial.status == Trial.ERROR: raise RuntimeError("Trial did not start correctly.") else: logger.debug("Notifying Scheduler and requeueing trial.") self._requeue_trial(trial) except Exception: logger.exception("Error recovering trial from checkpoint, abort.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True)
python
def _try_recover(self, trial, error_msg): """Tries to recover trial. Notifies SearchAlgorithm and Scheduler if failure to recover. Args: trial (Trial): Trial to recover. error_msg (str): Error message from prior to invoking this method. """ try: self.trial_executor.stop_trial( trial, error=error_msg is not None, error_msg=error_msg, stop_logger=False) trial.result_logger.flush() if self.trial_executor.has_resources(trial.resources): logger.info("Attempting to recover" " trial state from last checkpoint.") self.trial_executor.start_trial(trial) if trial.status == Trial.ERROR: raise RuntimeError("Trial did not start correctly.") else: logger.debug("Notifying Scheduler and requeueing trial.") self._requeue_trial(trial) except Exception: logger.exception("Error recovering trial from checkpoint, abort.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True)
[ "def", "_try_recover", "(", "self", ",", "trial", ",", "error_msg", ")", ":", "try", ":", "self", ".", "trial_executor", ".", "stop_trial", "(", "trial", ",", "error", "=", "error_msg", "is", "not", "None", ",", "error_msg", "=", "error_msg", ",", "stop_logger", "=", "False", ")", "trial", ".", "result_logger", ".", "flush", "(", ")", "if", "self", ".", "trial_executor", ".", "has_resources", "(", "trial", ".", "resources", ")", ":", "logger", ".", "info", "(", "\"Attempting to recover\"", "\" trial state from last checkpoint.\"", ")", "self", ".", "trial_executor", ".", "start_trial", "(", "trial", ")", "if", "trial", ".", "status", "==", "Trial", ".", "ERROR", ":", "raise", "RuntimeError", "(", "\"Trial did not start correctly.\"", ")", "else", ":", "logger", ".", "debug", "(", "\"Notifying Scheduler and requeueing trial.\"", ")", "self", ".", "_requeue_trial", "(", "trial", ")", "except", "Exception", ":", "logger", ".", "exception", "(", "\"Error recovering trial from checkpoint, abort.\"", ")", "self", ".", "_scheduler_alg", ".", "on_trial_error", "(", "self", ",", "trial", ")", "self", ".", "_search_alg", ".", "on_trial_complete", "(", "trial", ".", "trial_id", ",", "error", "=", "True", ")" ]
Tries to recover trial. Notifies SearchAlgorithm and Scheduler if failure to recover. Args: trial (Trial): Trial to recover. error_msg (str): Error message from prior to invoking this method.
[ "Tries", "to", "recover", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L514-L542
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._requeue_trial
def _requeue_trial(self, trial): """Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress. """ self._scheduler_alg.on_trial_error(self, trial) self.trial_executor.set_status(trial, Trial.PENDING) with warn_if_slow("scheduler.on_trial_add"): self._scheduler_alg.on_trial_add(self, trial)
python
def _requeue_trial(self, trial): """Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress. """ self._scheduler_alg.on_trial_error(self, trial) self.trial_executor.set_status(trial, Trial.PENDING) with warn_if_slow("scheduler.on_trial_add"): self._scheduler_alg.on_trial_add(self, trial)
[ "def", "_requeue_trial", "(", "self", ",", "trial", ")", ":", "self", ".", "_scheduler_alg", ".", "on_trial_error", "(", "self", ",", "trial", ")", "self", ".", "trial_executor", ".", "set_status", "(", "trial", ",", "Trial", ".", "PENDING", ")", "with", "warn_if_slow", "(", "\"scheduler.on_trial_add\"", ")", ":", "self", ".", "_scheduler_alg", ".", "on_trial_add", "(", "self", ",", "trial", ")" ]
Notification to TrialScheduler and requeue trial. This does not notify the SearchAlgorithm because the function evaluation is still in progress.
[ "Notification", "to", "TrialScheduler", "and", "requeue", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L544-L553
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner._update_trial_queue
def _update_trial_queue(self, blocking=False, timeout=600): """Adds next trials to queue if possible. Note that the timeout is currently unexposed to the user. Args: blocking (bool): Blocks until either a trial is available or is_finished (timeout or search algorithm finishes). timeout (int): Seconds before blocking times out. """ trials = self._search_alg.next_trials() if blocking and not trials: start = time.time() # Checking `is_finished` instead of _search_alg.is_finished # is fine because blocking only occurs if all trials are # finished and search_algorithm is not yet finished while (not trials and not self.is_finished() and time.time() - start < timeout): logger.info("Blocking for next trial...") trials = self._search_alg.next_trials() time.sleep(1) for trial in trials: self.add_trial(trial)
python
def _update_trial_queue(self, blocking=False, timeout=600): """Adds next trials to queue if possible. Note that the timeout is currently unexposed to the user. Args: blocking (bool): Blocks until either a trial is available or is_finished (timeout or search algorithm finishes). timeout (int): Seconds before blocking times out. """ trials = self._search_alg.next_trials() if blocking and not trials: start = time.time() # Checking `is_finished` instead of _search_alg.is_finished # is fine because blocking only occurs if all trials are # finished and search_algorithm is not yet finished while (not trials and not self.is_finished() and time.time() - start < timeout): logger.info("Blocking for next trial...") trials = self._search_alg.next_trials() time.sleep(1) for trial in trials: self.add_trial(trial)
[ "def", "_update_trial_queue", "(", "self", ",", "blocking", "=", "False", ",", "timeout", "=", "600", ")", ":", "trials", "=", "self", ".", "_search_alg", ".", "next_trials", "(", ")", "if", "blocking", "and", "not", "trials", ":", "start", "=", "time", ".", "time", "(", ")", "# Checking `is_finished` instead of _search_alg.is_finished", "# is fine because blocking only occurs if all trials are", "# finished and search_algorithm is not yet finished", "while", "(", "not", "trials", "and", "not", "self", ".", "is_finished", "(", ")", "and", "time", ".", "time", "(", ")", "-", "start", "<", "timeout", ")", ":", "logger", ".", "info", "(", "\"Blocking for next trial...\"", ")", "trials", "=", "self", ".", "_search_alg", ".", "next_trials", "(", ")", "time", ".", "sleep", "(", "1", ")", "for", "trial", "in", "trials", ":", "self", ".", "add_trial", "(", "trial", ")" ]
Adds next trials to queue if possible. Note that the timeout is currently unexposed to the user. Args: blocking (bool): Blocks until either a trial is available or is_finished (timeout or search algorithm finishes). timeout (int): Seconds before blocking times out.
[ "Adds", "next", "trials", "to", "queue", "if", "possible", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L555-L578
train
ray-project/ray
python/ray/tune/trial_runner.py
TrialRunner.stop_trial
def stop_trial(self, trial): """Stops trial. Trials may be stopped at any time. If trial is in state PENDING or PAUSED, calls `on_trial_remove` for scheduler and `on_trial_complete(..., early_terminated=True) for search_alg. Otherwise waits for result for the trial and calls `on_trial_complete` for scheduler and search_alg if RUNNING. """ error = False error_msg = None if trial.status in [Trial.ERROR, Trial.TERMINATED]: return elif trial.status in [Trial.PENDING, Trial.PAUSED]: self._scheduler_alg.on_trial_remove(self, trial) self._search_alg.on_trial_complete( trial.trial_id, early_terminated=True) elif trial.status is Trial.RUNNING: try: result = self.trial_executor.fetch_result(trial) trial.update_last_result(result, terminate=True) self._scheduler_alg.on_trial_complete(self, trial, result) self._search_alg.on_trial_complete( trial.trial_id, result=result) except Exception: error_msg = traceback.format_exc() logger.exception("Error processing event.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True) error = True self.trial_executor.stop_trial(trial, error=error, error_msg=error_msg)
python
def stop_trial(self, trial): """Stops trial. Trials may be stopped at any time. If trial is in state PENDING or PAUSED, calls `on_trial_remove` for scheduler and `on_trial_complete(..., early_terminated=True) for search_alg. Otherwise waits for result for the trial and calls `on_trial_complete` for scheduler and search_alg if RUNNING. """ error = False error_msg = None if trial.status in [Trial.ERROR, Trial.TERMINATED]: return elif trial.status in [Trial.PENDING, Trial.PAUSED]: self._scheduler_alg.on_trial_remove(self, trial) self._search_alg.on_trial_complete( trial.trial_id, early_terminated=True) elif trial.status is Trial.RUNNING: try: result = self.trial_executor.fetch_result(trial) trial.update_last_result(result, terminate=True) self._scheduler_alg.on_trial_complete(self, trial, result) self._search_alg.on_trial_complete( trial.trial_id, result=result) except Exception: error_msg = traceback.format_exc() logger.exception("Error processing event.") self._scheduler_alg.on_trial_error(self, trial) self._search_alg.on_trial_complete(trial.trial_id, error=True) error = True self.trial_executor.stop_trial(trial, error=error, error_msg=error_msg)
[ "def", "stop_trial", "(", "self", ",", "trial", ")", ":", "error", "=", "False", "error_msg", "=", "None", "if", "trial", ".", "status", "in", "[", "Trial", ".", "ERROR", ",", "Trial", ".", "TERMINATED", "]", ":", "return", "elif", "trial", ".", "status", "in", "[", "Trial", ".", "PENDING", ",", "Trial", ".", "PAUSED", "]", ":", "self", ".", "_scheduler_alg", ".", "on_trial_remove", "(", "self", ",", "trial", ")", "self", ".", "_search_alg", ".", "on_trial_complete", "(", "trial", ".", "trial_id", ",", "early_terminated", "=", "True", ")", "elif", "trial", ".", "status", "is", "Trial", ".", "RUNNING", ":", "try", ":", "result", "=", "self", ".", "trial_executor", ".", "fetch_result", "(", "trial", ")", "trial", ".", "update_last_result", "(", "result", ",", "terminate", "=", "True", ")", "self", ".", "_scheduler_alg", ".", "on_trial_complete", "(", "self", ",", "trial", ",", "result", ")", "self", ".", "_search_alg", ".", "on_trial_complete", "(", "trial", ".", "trial_id", ",", "result", "=", "result", ")", "except", "Exception", ":", "error_msg", "=", "traceback", ".", "format_exc", "(", ")", "logger", ".", "exception", "(", "\"Error processing event.\"", ")", "self", ".", "_scheduler_alg", ".", "on_trial_error", "(", "self", ",", "trial", ")", "self", ".", "_search_alg", ".", "on_trial_complete", "(", "trial", ".", "trial_id", ",", "error", "=", "True", ")", "error", "=", "True", "self", ".", "trial_executor", ".", "stop_trial", "(", "trial", ",", "error", "=", "error", ",", "error_msg", "=", "error_msg", ")" ]
Stops trial. Trials may be stopped at any time. If trial is in state PENDING or PAUSED, calls `on_trial_remove` for scheduler and `on_trial_complete(..., early_terminated=True) for search_alg. Otherwise waits for result for the trial and calls `on_trial_complete` for scheduler and search_alg if RUNNING.
[ "Stops", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_runner.py#L588-L620
train
ray-project/ray
examples/cython/cython_main.py
run_func
def run_func(func, *args, **kwargs): """Helper function for running examples""" ray.init() func = ray.remote(func) # NOTE: kwargs not allowed for now result = ray.get(func.remote(*args)) # Inspect the stack to get calling example caller = inspect.stack()[1][3] print("%s: %s" % (caller, str(result))) return result
python
def run_func(func, *args, **kwargs): """Helper function for running examples""" ray.init() func = ray.remote(func) # NOTE: kwargs not allowed for now result = ray.get(func.remote(*args)) # Inspect the stack to get calling example caller = inspect.stack()[1][3] print("%s: %s" % (caller, str(result))) return result
[ "def", "run_func", "(", "func", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "ray", ".", "init", "(", ")", "func", "=", "ray", ".", "remote", "(", "func", ")", "# NOTE: kwargs not allowed for now", "result", "=", "ray", ".", "get", "(", "func", ".", "remote", "(", "*", "args", ")", ")", "# Inspect the stack to get calling example", "caller", "=", "inspect", ".", "stack", "(", ")", "[", "1", "]", "[", "3", "]", "print", "(", "\"%s: %s\"", "%", "(", "caller", ",", "str", "(", "result", ")", ")", ")", "return", "result" ]
Helper function for running examples
[ "Helper", "function", "for", "running", "examples" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L13-L26
train
ray-project/ray
examples/cython/cython_main.py
example6
def example6(): """Cython simple class""" ray.init() cls = ray.remote(cyth.simple_class) a1 = cls.remote() a2 = cls.remote() result1 = ray.get(a1.increment.remote()) result2 = ray.get(a2.increment.remote()) print(result1, result2)
python
def example6(): """Cython simple class""" ray.init() cls = ray.remote(cyth.simple_class) a1 = cls.remote() a2 = cls.remote() result1 = ray.get(a1.increment.remote()) result2 = ray.get(a2.increment.remote()) print(result1, result2)
[ "def", "example6", "(", ")", ":", "ray", ".", "init", "(", ")", "cls", "=", "ray", ".", "remote", "(", "cyth", ".", "simple_class", ")", "a1", "=", "cls", ".", "remote", "(", ")", "a2", "=", "cls", ".", "remote", "(", ")", "result1", "=", "ray", ".", "get", "(", "a1", ".", "increment", ".", "remote", "(", ")", ")", "result2", "=", "ray", ".", "get", "(", "a2", ".", "increment", ".", "remote", "(", ")", ")", "print", "(", "result1", ",", "result2", ")" ]
Cython simple class
[ "Cython", "simple", "class" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L73-L85
train
ray-project/ray
examples/cython/cython_main.py
example8
def example8(): """Cython with blas. NOTE: requires scipy""" # See cython_blas.pyx for argument documentation mat = np.array([[[2.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [2.0, 2.0]]], dtype=np.float32) result = np.zeros((2, 2), np.float32, order="C") run_func(cyth.compute_kernel_matrix, "L", "T", 2, 2, 1.0, mat, 0, 2, 1.0, result, 2 )
python
def example8(): """Cython with blas. NOTE: requires scipy""" # See cython_blas.pyx for argument documentation mat = np.array([[[2.0, 2.0], [2.0, 2.0]], [[2.0, 2.0], [2.0, 2.0]]], dtype=np.float32) result = np.zeros((2, 2), np.float32, order="C") run_func(cyth.compute_kernel_matrix, "L", "T", 2, 2, 1.0, mat, 0, 2, 1.0, result, 2 )
[ "def", "example8", "(", ")", ":", "# See cython_blas.pyx for argument documentation", "mat", "=", "np", ".", "array", "(", "[", "[", "[", "2.0", ",", "2.0", "]", ",", "[", "2.0", ",", "2.0", "]", "]", ",", "[", "[", "2.0", ",", "2.0", "]", ",", "[", "2.0", ",", "2.0", "]", "]", "]", ",", "dtype", "=", "np", ".", "float32", ")", "result", "=", "np", ".", "zeros", "(", "(", "2", ",", "2", ")", ",", "np", ".", "float32", ",", "order", "=", "\"C\"", ")", "run_func", "(", "cyth", ".", "compute_kernel_matrix", ",", "\"L\"", ",", "\"T\"", ",", "2", ",", "2", ",", "1.0", ",", "mat", ",", "0", ",", "2", ",", "1.0", ",", "result", ",", "2", ")" ]
Cython with blas. NOTE: requires scipy
[ "Cython", "with", "blas", ".", "NOTE", ":", "requires", "scipy" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/cython/cython_main.py#L96-L116
train
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_adjust_nstep
def _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones): """Rewrites the given trajectory fragments to encode n-step rewards. reward[i] = ( reward[i] * gamma**0 + reward[i+1] * gamma**1 + ... + reward[i+n_step-1] * gamma**(n_step-1)) The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs. At the end of the trajectory, n is truncated to fit in the traj length. """ assert not any(dones[:-1]), "Unexpected done in middle of trajectory" traj_length = len(rewards) for i in range(traj_length): for j in range(1, n_step): if i + j < traj_length: new_obs[i] = new_obs[i + j] dones[i] = dones[i + j] rewards[i] += gamma**j * rewards[i + j]
python
def _adjust_nstep(n_step, gamma, obs, actions, rewards, new_obs, dones): """Rewrites the given trajectory fragments to encode n-step rewards. reward[i] = ( reward[i] * gamma**0 + reward[i+1] * gamma**1 + ... + reward[i+n_step-1] * gamma**(n_step-1)) The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs. At the end of the trajectory, n is truncated to fit in the traj length. """ assert not any(dones[:-1]), "Unexpected done in middle of trajectory" traj_length = len(rewards) for i in range(traj_length): for j in range(1, n_step): if i + j < traj_length: new_obs[i] = new_obs[i + j] dones[i] = dones[i + j] rewards[i] += gamma**j * rewards[i + j]
[ "def", "_adjust_nstep", "(", "n_step", ",", "gamma", ",", "obs", ",", "actions", ",", "rewards", ",", "new_obs", ",", "dones", ")", ":", "assert", "not", "any", "(", "dones", "[", ":", "-", "1", "]", ")", ",", "\"Unexpected done in middle of trajectory\"", "traj_length", "=", "len", "(", "rewards", ")", "for", "i", "in", "range", "(", "traj_length", ")", ":", "for", "j", "in", "range", "(", "1", ",", "n_step", ")", ":", "if", "i", "+", "j", "<", "traj_length", ":", "new_obs", "[", "i", "]", "=", "new_obs", "[", "i", "+", "j", "]", "dones", "[", "i", "]", "=", "dones", "[", "i", "+", "j", "]", "rewards", "[", "i", "]", "+=", "gamma", "**", "j", "*", "rewards", "[", "i", "+", "j", "]" ]
Rewrites the given trajectory fragments to encode n-step rewards. reward[i] = ( reward[i] * gamma**0 + reward[i+1] * gamma**1 + ... + reward[i+n_step-1] * gamma**(n_step-1)) The ith new_obs is also adjusted to point to the (i+n_step-1)'th new obs. At the end of the trajectory, n is truncated to fit in the traj length.
[ "Rewrites", "the", "given", "trajectory", "fragments", "to", "encode", "n", "-", "step", "rewards", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L603-L625
train
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_reduce_mean_ignore_inf
def _reduce_mean_ignore_inf(x, axis): """Same as tf.reduce_mean() but ignores -inf values.""" mask = tf.not_equal(x, tf.float32.min) x_zeroed = tf.where(mask, x, tf.zeros_like(x)) return (tf.reduce_sum(x_zeroed, axis) / tf.reduce_sum( tf.cast(mask, tf.float32), axis))
python
def _reduce_mean_ignore_inf(x, axis): """Same as tf.reduce_mean() but ignores -inf values.""" mask = tf.not_equal(x, tf.float32.min) x_zeroed = tf.where(mask, x, tf.zeros_like(x)) return (tf.reduce_sum(x_zeroed, axis) / tf.reduce_sum( tf.cast(mask, tf.float32), axis))
[ "def", "_reduce_mean_ignore_inf", "(", "x", ",", "axis", ")", ":", "mask", "=", "tf", ".", "not_equal", "(", "x", ",", "tf", ".", "float32", ".", "min", ")", "x_zeroed", "=", "tf", ".", "where", "(", "mask", ",", "x", ",", "tf", ".", "zeros_like", "(", "x", ")", ")", "return", "(", "tf", ".", "reduce_sum", "(", "x_zeroed", ",", "axis", ")", "/", "tf", ".", "reduce_sum", "(", "tf", ".", "cast", "(", "mask", ",", "tf", ".", "float32", ")", ",", "axis", ")", ")" ]
Same as tf.reduce_mean() but ignores -inf values.
[ "Same", "as", "tf", ".", "reduce_mean", "()", "but", "ignores", "-", "inf", "values", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L652-L657
train
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_huber_loss
def _huber_loss(x, delta=1.0): """Reference: https://en.wikipedia.org/wiki/Huber_loss""" return tf.where( tf.abs(x) < delta, tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta))
python
def _huber_loss(x, delta=1.0): """Reference: https://en.wikipedia.org/wiki/Huber_loss""" return tf.where( tf.abs(x) < delta, tf.square(x) * 0.5, delta * (tf.abs(x) - 0.5 * delta))
[ "def", "_huber_loss", "(", "x", ",", "delta", "=", "1.0", ")", ":", "return", "tf", ".", "where", "(", "tf", ".", "abs", "(", "x", ")", "<", "delta", ",", "tf", ".", "square", "(", "x", ")", "*", "0.5", ",", "delta", "*", "(", "tf", ".", "abs", "(", "x", ")", "-", "0.5", "*", "delta", ")", ")" ]
Reference: https://en.wikipedia.org/wiki/Huber_loss
[ "Reference", ":", "https", ":", "//", "en", ".", "wikipedia", ".", "org", "/", "wiki", "/", "Huber_loss" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L660-L664
train
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_minimize_and_clip
def _minimize_and_clip(optimizer, objective, var_list, clip_val=10): """Minimized `objective` using `optimizer` w.r.t. variables in `var_list` while ensure the norm of the gradients for each variable is clipped to `clip_val` """ gradients = optimizer.compute_gradients(objective, var_list=var_list) for i, (grad, var) in enumerate(gradients): if grad is not None: gradients[i] = (tf.clip_by_norm(grad, clip_val), var) return gradients
python
def _minimize_and_clip(optimizer, objective, var_list, clip_val=10): """Minimized `objective` using `optimizer` w.r.t. variables in `var_list` while ensure the norm of the gradients for each variable is clipped to `clip_val` """ gradients = optimizer.compute_gradients(objective, var_list=var_list) for i, (grad, var) in enumerate(gradients): if grad is not None: gradients[i] = (tf.clip_by_norm(grad, clip_val), var) return gradients
[ "def", "_minimize_and_clip", "(", "optimizer", ",", "objective", ",", "var_list", ",", "clip_val", "=", "10", ")", ":", "gradients", "=", "optimizer", ".", "compute_gradients", "(", "objective", ",", "var_list", "=", "var_list", ")", "for", "i", ",", "(", "grad", ",", "var", ")", "in", "enumerate", "(", "gradients", ")", ":", "if", "grad", "is", "not", "None", ":", "gradients", "[", "i", "]", "=", "(", "tf", ".", "clip_by_norm", "(", "grad", ",", "clip_val", ")", ",", "var", ")", "return", "gradients" ]
Minimized `objective` using `optimizer` w.r.t. variables in `var_list` while ensure the norm of the gradients for each variable is clipped to `clip_val`
[ "Minimized", "objective", "using", "optimizer", "w", ".", "r", ".", "t", ".", "variables", "in", "var_list", "while", "ensure", "the", "norm", "of", "the", "gradients", "for", "each", "variable", "is", "clipped", "to", "clip_val" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L667-L676
train
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
_scope_vars
def _scope_vars(scope, trainable_only=False): """ Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- vars: [tf.Variable] list of variables in `scope`. """ return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.VARIABLES, scope=scope if isinstance(scope, str) else scope.name)
python
def _scope_vars(scope, trainable_only=False): """ Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- vars: [tf.Variable] list of variables in `scope`. """ return tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES if trainable_only else tf.GraphKeys.VARIABLES, scope=scope if isinstance(scope, str) else scope.name)
[ "def", "_scope_vars", "(", "scope", ",", "trainable_only", "=", "False", ")", ":", "return", "tf", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", "if", "trainable_only", "else", "tf", ".", "GraphKeys", ".", "VARIABLES", ",", "scope", "=", "scope", "if", "isinstance", "(", "scope", ",", "str", ")", "else", "scope", ".", "name", ")" ]
Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- vars: [tf.Variable] list of variables in `scope`.
[ "Get", "variables", "inside", "a", "scope", "The", "scope", "can", "be", "specified", "as", "a", "string" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L679-L700
train
ray-project/ray
python/ray/rllib/agents/dqn/dqn_policy_graph.py
QNetwork.noisy_layer
def noisy_layer(self, prefix, action_in, out_size, sigma0, non_linear=True): """ a common dense layer: y = w^{T}x + b a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + (b+\epsilon_b*\sigma_b) where \epsilon are random variables sampled from factorized normal distributions and \sigma are trainable variables which are expected to vanish along the training procedure """ in_size = int(action_in.shape[1]) epsilon_in = tf.random_normal(shape=[in_size]) epsilon_out = tf.random_normal(shape=[out_size]) epsilon_in = self.f_epsilon(epsilon_in) epsilon_out = self.f_epsilon(epsilon_out) epsilon_w = tf.matmul( a=tf.expand_dims(epsilon_in, -1), b=tf.expand_dims(epsilon_out, 0)) epsilon_b = epsilon_out sigma_w = tf.get_variable( name=prefix + "_sigma_w", shape=[in_size, out_size], dtype=tf.float32, initializer=tf.random_uniform_initializer( minval=-1.0 / np.sqrt(float(in_size)), maxval=1.0 / np.sqrt(float(in_size)))) # TF noise generation can be unreliable on GPU # If generating the noise on the CPU, # lowering sigma0 to 0.1 may be helpful sigma_b = tf.get_variable( name=prefix + "_sigma_b", shape=[out_size], dtype=tf.float32, # 0.5~GPU, 0.1~CPU initializer=tf.constant_initializer( sigma0 / np.sqrt(float(in_size)))) w = tf.get_variable( name=prefix + "_fc_w", shape=[in_size, out_size], dtype=tf.float32, initializer=layers.xavier_initializer()) b = tf.get_variable( name=prefix + "_fc_b", shape=[out_size], dtype=tf.float32, initializer=tf.zeros_initializer()) action_activation = tf.nn.xw_plus_b(action_in, w + sigma_w * epsilon_w, b + sigma_b * epsilon_b) if not non_linear: return action_activation return tf.nn.relu(action_activation)
python
def noisy_layer(self, prefix, action_in, out_size, sigma0, non_linear=True): """ a common dense layer: y = w^{T}x + b a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + (b+\epsilon_b*\sigma_b) where \epsilon are random variables sampled from factorized normal distributions and \sigma are trainable variables which are expected to vanish along the training procedure """ in_size = int(action_in.shape[1]) epsilon_in = tf.random_normal(shape=[in_size]) epsilon_out = tf.random_normal(shape=[out_size]) epsilon_in = self.f_epsilon(epsilon_in) epsilon_out = self.f_epsilon(epsilon_out) epsilon_w = tf.matmul( a=tf.expand_dims(epsilon_in, -1), b=tf.expand_dims(epsilon_out, 0)) epsilon_b = epsilon_out sigma_w = tf.get_variable( name=prefix + "_sigma_w", shape=[in_size, out_size], dtype=tf.float32, initializer=tf.random_uniform_initializer( minval=-1.0 / np.sqrt(float(in_size)), maxval=1.0 / np.sqrt(float(in_size)))) # TF noise generation can be unreliable on GPU # If generating the noise on the CPU, # lowering sigma0 to 0.1 may be helpful sigma_b = tf.get_variable( name=prefix + "_sigma_b", shape=[out_size], dtype=tf.float32, # 0.5~GPU, 0.1~CPU initializer=tf.constant_initializer( sigma0 / np.sqrt(float(in_size)))) w = tf.get_variable( name=prefix + "_fc_w", shape=[in_size, out_size], dtype=tf.float32, initializer=layers.xavier_initializer()) b = tf.get_variable( name=prefix + "_fc_b", shape=[out_size], dtype=tf.float32, initializer=tf.zeros_initializer()) action_activation = tf.nn.xw_plus_b(action_in, w + sigma_w * epsilon_w, b + sigma_b * epsilon_b) if not non_linear: return action_activation return tf.nn.relu(action_activation)
[ "def", "noisy_layer", "(", "self", ",", "prefix", ",", "action_in", ",", "out_size", ",", "sigma0", ",", "non_linear", "=", "True", ")", ":", "in_size", "=", "int", "(", "action_in", ".", "shape", "[", "1", "]", ")", "epsilon_in", "=", "tf", ".", "random_normal", "(", "shape", "=", "[", "in_size", "]", ")", "epsilon_out", "=", "tf", ".", "random_normal", "(", "shape", "=", "[", "out_size", "]", ")", "epsilon_in", "=", "self", ".", "f_epsilon", "(", "epsilon_in", ")", "epsilon_out", "=", "self", ".", "f_epsilon", "(", "epsilon_out", ")", "epsilon_w", "=", "tf", ".", "matmul", "(", "a", "=", "tf", ".", "expand_dims", "(", "epsilon_in", ",", "-", "1", ")", ",", "b", "=", "tf", ".", "expand_dims", "(", "epsilon_out", ",", "0", ")", ")", "epsilon_b", "=", "epsilon_out", "sigma_w", "=", "tf", ".", "get_variable", "(", "name", "=", "prefix", "+", "\"_sigma_w\"", ",", "shape", "=", "[", "in_size", ",", "out_size", "]", ",", "dtype", "=", "tf", ".", "float32", ",", "initializer", "=", "tf", ".", "random_uniform_initializer", "(", "minval", "=", "-", "1.0", "/", "np", ".", "sqrt", "(", "float", "(", "in_size", ")", ")", ",", "maxval", "=", "1.0", "/", "np", ".", "sqrt", "(", "float", "(", "in_size", ")", ")", ")", ")", "# TF noise generation can be unreliable on GPU", "# If generating the noise on the CPU,", "# lowering sigma0 to 0.1 may be helpful", "sigma_b", "=", "tf", ".", "get_variable", "(", "name", "=", "prefix", "+", "\"_sigma_b\"", ",", "shape", "=", "[", "out_size", "]", ",", "dtype", "=", "tf", ".", "float32", ",", "# 0.5~GPU, 0.1~CPU", "initializer", "=", "tf", ".", "constant_initializer", "(", "sigma0", "/", "np", ".", "sqrt", "(", "float", "(", "in_size", ")", ")", ")", ")", "w", "=", "tf", ".", "get_variable", "(", "name", "=", "prefix", "+", "\"_fc_w\"", ",", "shape", "=", "[", "in_size", ",", "out_size", "]", ",", "dtype", "=", "tf", ".", "float32", ",", "initializer", "=", "layers", ".", "xavier_initializer", "(", ")", ")", "b", "=", "tf", ".", "get_variable", "(", "name", "=", "prefix", "+", "\"_fc_b\"", ",", "shape", "=", "[", "out_size", "]", ",", "dtype", "=", "tf", ".", "float32", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "action_activation", "=", "tf", ".", "nn", ".", "xw_plus_b", "(", "action_in", ",", "w", "+", "sigma_w", "*", "epsilon_w", ",", "b", "+", "sigma_b", "*", "epsilon_b", ")", "if", "not", "non_linear", ":", "return", "action_activation", "return", "tf", ".", "nn", ".", "relu", "(", "action_activation", ")" ]
a common dense layer: y = w^{T}x + b a noisy layer: y = (w + \epsilon_w*\sigma_w)^{T}x + (b+\epsilon_b*\sigma_b) where \epsilon are random variables sampled from factorized normal distributions and \sigma are trainable variables which are expected to vanish along the training procedure
[ "a", "common", "dense", "layer", ":", "y", "=", "w^", "{", "T", "}", "x", "+", "b", "a", "noisy", "layer", ":", "y", "=", "(", "w", "+", "\\", "epsilon_w", "*", "\\", "sigma_w", ")", "^", "{", "T", "}", "x", "+", "(", "b", "+", "\\", "epsilon_b", "*", "\\", "sigma_b", ")", "where", "\\", "epsilon", "are", "random", "variables", "sampled", "from", "factorized", "normal", "distributions", "and", "\\", "sigma", "are", "trainable", "variables", "which", "are", "expected", "to", "vanish", "along", "the", "training", "procedure" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/dqn/dqn_policy_graph.py#L256-L308
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.get_custom_getter
def get_custom_getter(self): """Returns a custom getter that this class's methods must be called All methods of this class must be called under a variable scope that was passed this custom getter. Example: ```python network = ConvNetBuilder(...) with tf.variable_scope("cg", custom_getter=network.get_custom_getter()): network.conv(...) # Call more methods of network here ``` Currently, this custom getter only does anything if self.use_tf_layers is True. In that case, it causes variables to be stored as dtype self.variable_type, then casted to the requested dtype, instead of directly storing the variable as the requested dtype. """ def inner_custom_getter(getter, *args, **kwargs): if not self.use_tf_layers: return getter(*args, **kwargs) requested_dtype = kwargs["dtype"] if not (requested_dtype == tf.float32 and self.variable_dtype == tf.float16): kwargs["dtype"] = self.variable_dtype var = getter(*args, **kwargs) if var.dtype.base_dtype != requested_dtype: var = tf.cast(var, requested_dtype) return var return inner_custom_getter
python
def get_custom_getter(self): """Returns a custom getter that this class's methods must be called All methods of this class must be called under a variable scope that was passed this custom getter. Example: ```python network = ConvNetBuilder(...) with tf.variable_scope("cg", custom_getter=network.get_custom_getter()): network.conv(...) # Call more methods of network here ``` Currently, this custom getter only does anything if self.use_tf_layers is True. In that case, it causes variables to be stored as dtype self.variable_type, then casted to the requested dtype, instead of directly storing the variable as the requested dtype. """ def inner_custom_getter(getter, *args, **kwargs): if not self.use_tf_layers: return getter(*args, **kwargs) requested_dtype = kwargs["dtype"] if not (requested_dtype == tf.float32 and self.variable_dtype == tf.float16): kwargs["dtype"] = self.variable_dtype var = getter(*args, **kwargs) if var.dtype.base_dtype != requested_dtype: var = tf.cast(var, requested_dtype) return var return inner_custom_getter
[ "def", "get_custom_getter", "(", "self", ")", ":", "def", "inner_custom_getter", "(", "getter", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "not", "self", ".", "use_tf_layers", ":", "return", "getter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "requested_dtype", "=", "kwargs", "[", "\"dtype\"", "]", "if", "not", "(", "requested_dtype", "==", "tf", ".", "float32", "and", "self", ".", "variable_dtype", "==", "tf", ".", "float16", ")", ":", "kwargs", "[", "\"dtype\"", "]", "=", "self", ".", "variable_dtype", "var", "=", "getter", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "var", ".", "dtype", ".", "base_dtype", "!=", "requested_dtype", ":", "var", "=", "tf", ".", "cast", "(", "var", ",", "requested_dtype", ")", "return", "var", "return", "inner_custom_getter" ]
Returns a custom getter that this class's methods must be called All methods of this class must be called under a variable scope that was passed this custom getter. Example: ```python network = ConvNetBuilder(...) with tf.variable_scope("cg", custom_getter=network.get_custom_getter()): network.conv(...) # Call more methods of network here ``` Currently, this custom getter only does anything if self.use_tf_layers is True. In that case, it causes variables to be stored as dtype self.variable_type, then casted to the requested dtype, instead of directly storing the variable as the requested dtype.
[ "Returns", "a", "custom", "getter", "that", "this", "class", "s", "methods", "must", "be", "called" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L58-L89
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.switch_to_aux_top_layer
def switch_to_aux_top_layer(self): """Context that construct cnn in the auxiliary arm.""" if self.aux_top_layer is None: raise RuntimeError("Empty auxiliary top layer in the network.") saved_top_layer = self.top_layer saved_top_size = self.top_size self.top_layer = self.aux_top_layer self.top_size = self.aux_top_size yield self.aux_top_layer = self.top_layer self.aux_top_size = self.top_size self.top_layer = saved_top_layer self.top_size = saved_top_size
python
def switch_to_aux_top_layer(self): """Context that construct cnn in the auxiliary arm.""" if self.aux_top_layer is None: raise RuntimeError("Empty auxiliary top layer in the network.") saved_top_layer = self.top_layer saved_top_size = self.top_size self.top_layer = self.aux_top_layer self.top_size = self.aux_top_size yield self.aux_top_layer = self.top_layer self.aux_top_size = self.top_size self.top_layer = saved_top_layer self.top_size = saved_top_size
[ "def", "switch_to_aux_top_layer", "(", "self", ")", ":", "if", "self", ".", "aux_top_layer", "is", "None", ":", "raise", "RuntimeError", "(", "\"Empty auxiliary top layer in the network.\"", ")", "saved_top_layer", "=", "self", ".", "top_layer", "saved_top_size", "=", "self", ".", "top_size", "self", ".", "top_layer", "=", "self", ".", "aux_top_layer", "self", ".", "top_size", "=", "self", ".", "aux_top_size", "yield", "self", ".", "aux_top_layer", "=", "self", ".", "top_layer", "self", ".", "aux_top_size", "=", "self", ".", "top_size", "self", ".", "top_layer", "=", "saved_top_layer", "self", ".", "top_size", "=", "saved_top_size" ]
Context that construct cnn in the auxiliary arm.
[ "Context", "that", "construct", "cnn", "in", "the", "auxiliary", "arm", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L92-L104
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.conv
def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode="SAME", input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, activation="relu", bias=0.0): """Construct a conv2d layer on top of cnn.""" if input_layer is None: input_layer = self.top_layer if num_channels_in is None: num_channels_in = self.top_size kernel_initializer = None if stddev is not None: kernel_initializer = tf.truncated_normal_initializer(stddev=stddev) name = "conv" + str(self.counts["conv"]) self.counts["conv"] += 1 with tf.variable_scope(name): strides = [1, d_height, d_width, 1] if self.data_format == "NCHW": strides = [strides[0], strides[3], strides[1], strides[2]] if mode != "SAME_RESNET": conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding=mode, kernel_initializer=kernel_initializer) else: # Special padding mode for ResNet models if d_height == 1 and d_width == 1: conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="SAME", kernel_initializer=kernel_initializer) else: rate = 1 # Unused (for 'a trous' convolutions) kernel_height_effective = k_height + (k_height - 1) * ( rate - 1) pad_h_beg = (kernel_height_effective - 1) // 2 pad_h_end = kernel_height_effective - 1 - pad_h_beg kernel_width_effective = k_width + (k_width - 1) * ( rate - 1) pad_w_beg = (kernel_width_effective - 1) // 2 pad_w_end = kernel_width_effective - 1 - pad_w_beg padding = [[0, 0], [pad_h_beg, pad_h_end], [pad_w_beg, pad_w_end], [0, 0]] if self.data_format == "NCHW": padding = [ padding[0], padding[3], padding[1], padding[2] ] input_layer = tf.pad(input_layer, padding) conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="VALID", kernel_initializer=kernel_initializer) if use_batch_norm is None: use_batch_norm = self.use_batch_norm if not use_batch_norm: if bias is not None: biases = self.get_variable( "biases", [num_out_channels], self.variable_dtype, self.dtype, initializer=tf.constant_initializer(bias)) biased = tf.reshape( tf.nn.bias_add( conv, biases, data_format=self.data_format), conv.get_shape()) else: biased = conv else: self.top_layer = conv self.top_size = num_out_channels biased = self.batch_norm(**self.batch_norm_config) if activation == "relu": conv1 = tf.nn.relu(biased) elif activation == "linear" or activation is None: conv1 = biased elif activation == "tanh": conv1 = tf.nn.tanh(biased) else: raise KeyError("Invalid activation type \"%s\"" % activation) self.top_layer = conv1 self.top_size = num_out_channels return conv1
python
def conv(self, num_out_channels, k_height, k_width, d_height=1, d_width=1, mode="SAME", input_layer=None, num_channels_in=None, use_batch_norm=None, stddev=None, activation="relu", bias=0.0): """Construct a conv2d layer on top of cnn.""" if input_layer is None: input_layer = self.top_layer if num_channels_in is None: num_channels_in = self.top_size kernel_initializer = None if stddev is not None: kernel_initializer = tf.truncated_normal_initializer(stddev=stddev) name = "conv" + str(self.counts["conv"]) self.counts["conv"] += 1 with tf.variable_scope(name): strides = [1, d_height, d_width, 1] if self.data_format == "NCHW": strides = [strides[0], strides[3], strides[1], strides[2]] if mode != "SAME_RESNET": conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding=mode, kernel_initializer=kernel_initializer) else: # Special padding mode for ResNet models if d_height == 1 and d_width == 1: conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="SAME", kernel_initializer=kernel_initializer) else: rate = 1 # Unused (for 'a trous' convolutions) kernel_height_effective = k_height + (k_height - 1) * ( rate - 1) pad_h_beg = (kernel_height_effective - 1) // 2 pad_h_end = kernel_height_effective - 1 - pad_h_beg kernel_width_effective = k_width + (k_width - 1) * ( rate - 1) pad_w_beg = (kernel_width_effective - 1) // 2 pad_w_end = kernel_width_effective - 1 - pad_w_beg padding = [[0, 0], [pad_h_beg, pad_h_end], [pad_w_beg, pad_w_end], [0, 0]] if self.data_format == "NCHW": padding = [ padding[0], padding[3], padding[1], padding[2] ] input_layer = tf.pad(input_layer, padding) conv = self._conv2d_impl( input_layer, num_channels_in, num_out_channels, kernel_size=[k_height, k_width], strides=[d_height, d_width], padding="VALID", kernel_initializer=kernel_initializer) if use_batch_norm is None: use_batch_norm = self.use_batch_norm if not use_batch_norm: if bias is not None: biases = self.get_variable( "biases", [num_out_channels], self.variable_dtype, self.dtype, initializer=tf.constant_initializer(bias)) biased = tf.reshape( tf.nn.bias_add( conv, biases, data_format=self.data_format), conv.get_shape()) else: biased = conv else: self.top_layer = conv self.top_size = num_out_channels biased = self.batch_norm(**self.batch_norm_config) if activation == "relu": conv1 = tf.nn.relu(biased) elif activation == "linear" or activation is None: conv1 = biased elif activation == "tanh": conv1 = tf.nn.tanh(biased) else: raise KeyError("Invalid activation type \"%s\"" % activation) self.top_layer = conv1 self.top_size = num_out_channels return conv1
[ "def", "conv", "(", "self", ",", "num_out_channels", ",", "k_height", ",", "k_width", ",", "d_height", "=", "1", ",", "d_width", "=", "1", ",", "mode", "=", "\"SAME\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ",", "use_batch_norm", "=", "None", ",", "stddev", "=", "None", ",", "activation", "=", "\"relu\"", ",", "bias", "=", "0.0", ")", ":", "if", "input_layer", "is", "None", ":", "input_layer", "=", "self", ".", "top_layer", "if", "num_channels_in", "is", "None", ":", "num_channels_in", "=", "self", ".", "top_size", "kernel_initializer", "=", "None", "if", "stddev", "is", "not", "None", ":", "kernel_initializer", "=", "tf", ".", "truncated_normal_initializer", "(", "stddev", "=", "stddev", ")", "name", "=", "\"conv\"", "+", "str", "(", "self", ".", "counts", "[", "\"conv\"", "]", ")", "self", ".", "counts", "[", "\"conv\"", "]", "+=", "1", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "strides", "=", "[", "1", ",", "d_height", ",", "d_width", ",", "1", "]", "if", "self", ".", "data_format", "==", "\"NCHW\"", ":", "strides", "=", "[", "strides", "[", "0", "]", ",", "strides", "[", "3", "]", ",", "strides", "[", "1", "]", ",", "strides", "[", "2", "]", "]", "if", "mode", "!=", "\"SAME_RESNET\"", ":", "conv", "=", "self", ".", "_conv2d_impl", "(", "input_layer", ",", "num_channels_in", ",", "num_out_channels", ",", "kernel_size", "=", "[", "k_height", ",", "k_width", "]", ",", "strides", "=", "[", "d_height", ",", "d_width", "]", ",", "padding", "=", "mode", ",", "kernel_initializer", "=", "kernel_initializer", ")", "else", ":", "# Special padding mode for ResNet models", "if", "d_height", "==", "1", "and", "d_width", "==", "1", ":", "conv", "=", "self", ".", "_conv2d_impl", "(", "input_layer", ",", "num_channels_in", ",", "num_out_channels", ",", "kernel_size", "=", "[", "k_height", ",", "k_width", "]", ",", "strides", "=", "[", "d_height", ",", "d_width", "]", ",", "padding", "=", "\"SAME\"", ",", "kernel_initializer", "=", "kernel_initializer", ")", "else", ":", "rate", "=", "1", "# Unused (for 'a trous' convolutions)", "kernel_height_effective", "=", "k_height", "+", "(", "k_height", "-", "1", ")", "*", "(", "rate", "-", "1", ")", "pad_h_beg", "=", "(", "kernel_height_effective", "-", "1", ")", "//", "2", "pad_h_end", "=", "kernel_height_effective", "-", "1", "-", "pad_h_beg", "kernel_width_effective", "=", "k_width", "+", "(", "k_width", "-", "1", ")", "*", "(", "rate", "-", "1", ")", "pad_w_beg", "=", "(", "kernel_width_effective", "-", "1", ")", "//", "2", "pad_w_end", "=", "kernel_width_effective", "-", "1", "-", "pad_w_beg", "padding", "=", "[", "[", "0", ",", "0", "]", ",", "[", "pad_h_beg", ",", "pad_h_end", "]", ",", "[", "pad_w_beg", ",", "pad_w_end", "]", ",", "[", "0", ",", "0", "]", "]", "if", "self", ".", "data_format", "==", "\"NCHW\"", ":", "padding", "=", "[", "padding", "[", "0", "]", ",", "padding", "[", "3", "]", ",", "padding", "[", "1", "]", ",", "padding", "[", "2", "]", "]", "input_layer", "=", "tf", ".", "pad", "(", "input_layer", ",", "padding", ")", "conv", "=", "self", ".", "_conv2d_impl", "(", "input_layer", ",", "num_channels_in", ",", "num_out_channels", ",", "kernel_size", "=", "[", "k_height", ",", "k_width", "]", ",", "strides", "=", "[", "d_height", ",", "d_width", "]", ",", "padding", "=", "\"VALID\"", ",", "kernel_initializer", "=", "kernel_initializer", ")", "if", "use_batch_norm", "is", "None", ":", "use_batch_norm", "=", "self", ".", "use_batch_norm", "if", "not", "use_batch_norm", ":", "if", "bias", "is", "not", "None", ":", "biases", "=", "self", ".", "get_variable", "(", "\"biases\"", ",", "[", "num_out_channels", "]", ",", "self", ".", "variable_dtype", ",", "self", ".", "dtype", ",", "initializer", "=", "tf", ".", "constant_initializer", "(", "bias", ")", ")", "biased", "=", "tf", ".", "reshape", "(", "tf", ".", "nn", ".", "bias_add", "(", "conv", ",", "biases", ",", "data_format", "=", "self", ".", "data_format", ")", ",", "conv", ".", "get_shape", "(", ")", ")", "else", ":", "biased", "=", "conv", "else", ":", "self", ".", "top_layer", "=", "conv", "self", ".", "top_size", "=", "num_out_channels", "biased", "=", "self", ".", "batch_norm", "(", "*", "*", "self", ".", "batch_norm_config", ")", "if", "activation", "==", "\"relu\"", ":", "conv1", "=", "tf", ".", "nn", ".", "relu", "(", "biased", ")", "elif", "activation", "==", "\"linear\"", "or", "activation", "is", "None", ":", "conv1", "=", "biased", "elif", "activation", "==", "\"tanh\"", ":", "conv1", "=", "tf", ".", "nn", ".", "tanh", "(", "biased", ")", "else", ":", "raise", "KeyError", "(", "\"Invalid activation type \\\"%s\\\"\"", "%", "activation", ")", "self", ".", "top_layer", "=", "conv1", "self", ".", "top_size", "=", "num_out_channels", "return", "conv1" ]
Construct a conv2d layer on top of cnn.
[ "Construct", "a", "conv2d", "layer", "on", "top", "of", "cnn", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L143-L243
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder._pool
def _pool(self, pool_name, pool_function, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in): """Construct a pooling layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = num_channels_in name = pool_name + str(self.counts[pool_name]) self.counts[pool_name] += 1 if self.use_tf_layers: pool = pool_function( input_layer, [k_height, k_width], [d_height, d_width], padding=mode, data_format=self.channel_pos, name=name) else: if self.data_format == "NHWC": ksize = [1, k_height, k_width, 1] strides = [1, d_height, d_width, 1] else: ksize = [1, 1, k_height, k_width] strides = [1, 1, d_height, d_width] pool = tf.nn.max_pool( input_layer, ksize, strides, padding=mode, data_format=self.data_format, name=name) self.top_layer = pool return pool
python
def _pool(self, pool_name, pool_function, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in): """Construct a pooling layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = num_channels_in name = pool_name + str(self.counts[pool_name]) self.counts[pool_name] += 1 if self.use_tf_layers: pool = pool_function( input_layer, [k_height, k_width], [d_height, d_width], padding=mode, data_format=self.channel_pos, name=name) else: if self.data_format == "NHWC": ksize = [1, k_height, k_width, 1] strides = [1, d_height, d_width, 1] else: ksize = [1, 1, k_height, k_width] strides = [1, 1, d_height, d_width] pool = tf.nn.max_pool( input_layer, ksize, strides, padding=mode, data_format=self.data_format, name=name) self.top_layer = pool return pool
[ "def", "_pool", "(", "self", ",", "pool_name", ",", "pool_function", ",", "k_height", ",", "k_width", ",", "d_height", ",", "d_width", ",", "mode", ",", "input_layer", ",", "num_channels_in", ")", ":", "if", "input_layer", "is", "None", ":", "input_layer", "=", "self", ".", "top_layer", "else", ":", "self", ".", "top_size", "=", "num_channels_in", "name", "=", "pool_name", "+", "str", "(", "self", ".", "counts", "[", "pool_name", "]", ")", "self", ".", "counts", "[", "pool_name", "]", "+=", "1", "if", "self", ".", "use_tf_layers", ":", "pool", "=", "pool_function", "(", "input_layer", ",", "[", "k_height", ",", "k_width", "]", ",", "[", "d_height", ",", "d_width", "]", ",", "padding", "=", "mode", ",", "data_format", "=", "self", ".", "channel_pos", ",", "name", "=", "name", ")", "else", ":", "if", "self", ".", "data_format", "==", "\"NHWC\"", ":", "ksize", "=", "[", "1", ",", "k_height", ",", "k_width", ",", "1", "]", "strides", "=", "[", "1", ",", "d_height", ",", "d_width", ",", "1", "]", "else", ":", "ksize", "=", "[", "1", ",", "1", ",", "k_height", ",", "k_width", "]", "strides", "=", "[", "1", ",", "1", ",", "d_height", ",", "d_width", "]", "pool", "=", "tf", ".", "nn", ".", "max_pool", "(", "input_layer", ",", "ksize", ",", "strides", ",", "padding", "=", "mode", ",", "data_format", "=", "self", ".", "data_format", ",", "name", "=", "name", ")", "self", ".", "top_layer", "=", "pool", "return", "pool" ]
Construct a pooling layer.
[ "Construct", "a", "pooling", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L245-L275
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.mpool
def mpool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): """Construct a max pooling layer.""" return self._pool("mpool", pooling_layers.max_pooling2d, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in)
python
def mpool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): """Construct a max pooling layer.""" return self._pool("mpool", pooling_layers.max_pooling2d, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in)
[ "def", "mpool", "(", "self", ",", "k_height", ",", "k_width", ",", "d_height", "=", "2", ",", "d_width", "=", "2", ",", "mode", "=", "\"VALID\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ")", ":", "return", "self", ".", "_pool", "(", "\"mpool\"", ",", "pooling_layers", ".", "max_pooling2d", ",", "k_height", ",", "k_width", ",", "d_height", ",", "d_width", ",", "mode", ",", "input_layer", ",", "num_channels_in", ")" ]
Construct a max pooling layer.
[ "Construct", "a", "max", "pooling", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L277-L288
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.apool
def apool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): """Construct an average pooling layer.""" return self._pool("apool", pooling_layers.average_pooling2d, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in)
python
def apool(self, k_height, k_width, d_height=2, d_width=2, mode="VALID", input_layer=None, num_channels_in=None): """Construct an average pooling layer.""" return self._pool("apool", pooling_layers.average_pooling2d, k_height, k_width, d_height, d_width, mode, input_layer, num_channels_in)
[ "def", "apool", "(", "self", ",", "k_height", ",", "k_width", ",", "d_height", "=", "2", ",", "d_width", "=", "2", ",", "mode", "=", "\"VALID\"", ",", "input_layer", "=", "None", ",", "num_channels_in", "=", "None", ")", ":", "return", "self", ".", "_pool", "(", "\"apool\"", ",", "pooling_layers", ".", "average_pooling2d", ",", "k_height", ",", "k_width", ",", "d_height", ",", "d_width", ",", "mode", ",", "input_layer", ",", "num_channels_in", ")" ]
Construct an average pooling layer.
[ "Construct", "an", "average", "pooling", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L290-L301
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder._batch_norm_without_layers
def _batch_norm_without_layers(self, input_layer, decay, use_scale, epsilon): """Batch normalization on `input_layer` without tf.layers.""" shape = input_layer.shape num_channels = shape[3] if self.data_format == "NHWC" else shape[1] beta = self.get_variable( "beta", [num_channels], tf.float32, tf.float32, initializer=tf.zeros_initializer()) if use_scale: gamma = self.get_variable( "gamma", [num_channels], tf.float32, tf.float32, initializer=tf.ones_initializer()) else: gamma = tf.constant(1.0, tf.float32, [num_channels]) moving_mean = tf.get_variable( "moving_mean", [num_channels], tf.float32, initializer=tf.zeros_initializer(), trainable=False) moving_variance = tf.get_variable( "moving_variance", [num_channels], tf.float32, initializer=tf.ones_initializer(), trainable=False) if self.phase_train: bn, batch_mean, batch_variance = tf.nn.fused_batch_norm( input_layer, gamma, beta, epsilon=epsilon, data_format=self.data_format, is_training=True) mean_update = moving_averages.assign_moving_average( moving_mean, batch_mean, decay=decay, zero_debias=False) variance_update = moving_averages.assign_moving_average( moving_variance, batch_variance, decay=decay, zero_debias=False) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, mean_update) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, variance_update) else: bn, _, _ = tf.nn.fused_batch_norm( input_layer, gamma, beta, mean=moving_mean, variance=moving_variance, epsilon=epsilon, data_format=self.data_format, is_training=False) return bn
python
def _batch_norm_without_layers(self, input_layer, decay, use_scale, epsilon): """Batch normalization on `input_layer` without tf.layers.""" shape = input_layer.shape num_channels = shape[3] if self.data_format == "NHWC" else shape[1] beta = self.get_variable( "beta", [num_channels], tf.float32, tf.float32, initializer=tf.zeros_initializer()) if use_scale: gamma = self.get_variable( "gamma", [num_channels], tf.float32, tf.float32, initializer=tf.ones_initializer()) else: gamma = tf.constant(1.0, tf.float32, [num_channels]) moving_mean = tf.get_variable( "moving_mean", [num_channels], tf.float32, initializer=tf.zeros_initializer(), trainable=False) moving_variance = tf.get_variable( "moving_variance", [num_channels], tf.float32, initializer=tf.ones_initializer(), trainable=False) if self.phase_train: bn, batch_mean, batch_variance = tf.nn.fused_batch_norm( input_layer, gamma, beta, epsilon=epsilon, data_format=self.data_format, is_training=True) mean_update = moving_averages.assign_moving_average( moving_mean, batch_mean, decay=decay, zero_debias=False) variance_update = moving_averages.assign_moving_average( moving_variance, batch_variance, decay=decay, zero_debias=False) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, mean_update) tf.add_to_collection(tf.GraphKeys.UPDATE_OPS, variance_update) else: bn, _, _ = tf.nn.fused_batch_norm( input_layer, gamma, beta, mean=moving_mean, variance=moving_variance, epsilon=epsilon, data_format=self.data_format, is_training=False) return bn
[ "def", "_batch_norm_without_layers", "(", "self", ",", "input_layer", ",", "decay", ",", "use_scale", ",", "epsilon", ")", ":", "shape", "=", "input_layer", ".", "shape", "num_channels", "=", "shape", "[", "3", "]", "if", "self", ".", "data_format", "==", "\"NHWC\"", "else", "shape", "[", "1", "]", "beta", "=", "self", ".", "get_variable", "(", "\"beta\"", ",", "[", "num_channels", "]", ",", "tf", ".", "float32", ",", "tf", ".", "float32", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ")", "if", "use_scale", ":", "gamma", "=", "self", ".", "get_variable", "(", "\"gamma\"", ",", "[", "num_channels", "]", ",", "tf", ".", "float32", ",", "tf", ".", "float32", ",", "initializer", "=", "tf", ".", "ones_initializer", "(", ")", ")", "else", ":", "gamma", "=", "tf", ".", "constant", "(", "1.0", ",", "tf", ".", "float32", ",", "[", "num_channels", "]", ")", "moving_mean", "=", "tf", ".", "get_variable", "(", "\"moving_mean\"", ",", "[", "num_channels", "]", ",", "tf", ".", "float32", ",", "initializer", "=", "tf", ".", "zeros_initializer", "(", ")", ",", "trainable", "=", "False", ")", "moving_variance", "=", "tf", ".", "get_variable", "(", "\"moving_variance\"", ",", "[", "num_channels", "]", ",", "tf", ".", "float32", ",", "initializer", "=", "tf", ".", "ones_initializer", "(", ")", ",", "trainable", "=", "False", ")", "if", "self", ".", "phase_train", ":", "bn", ",", "batch_mean", ",", "batch_variance", "=", "tf", ".", "nn", ".", "fused_batch_norm", "(", "input_layer", ",", "gamma", ",", "beta", ",", "epsilon", "=", "epsilon", ",", "data_format", "=", "self", ".", "data_format", ",", "is_training", "=", "True", ")", "mean_update", "=", "moving_averages", ".", "assign_moving_average", "(", "moving_mean", ",", "batch_mean", ",", "decay", "=", "decay", ",", "zero_debias", "=", "False", ")", "variance_update", "=", "moving_averages", ".", "assign_moving_average", "(", "moving_variance", ",", "batch_variance", ",", "decay", "=", "decay", ",", "zero_debias", "=", "False", ")", "tf", ".", "add_to_collection", "(", "tf", ".", "GraphKeys", ".", "UPDATE_OPS", ",", "mean_update", ")", "tf", ".", "add_to_collection", "(", "tf", ".", "GraphKeys", ".", "UPDATE_OPS", ",", "variance_update", ")", "else", ":", "bn", ",", "_", ",", "_", "=", "tf", ".", "nn", ".", "fused_batch_norm", "(", "input_layer", ",", "gamma", ",", "beta", ",", "mean", "=", "moving_mean", ",", "variance", "=", "moving_variance", ",", "epsilon", "=", "epsilon", ",", "data_format", "=", "self", ".", "data_format", ",", "is_training", "=", "False", ")", "return", "bn" ]
Batch normalization on `input_layer` without tf.layers.
[ "Batch", "normalization", "on", "input_layer", "without", "tf", ".", "layers", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L411-L466
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.batch_norm
def batch_norm(self, input_layer=None, decay=0.999, scale=False, epsilon=0.001): """Adds a Batch Normalization layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = None name = "batchnorm" + str(self.counts["batchnorm"]) self.counts["batchnorm"] += 1 with tf.variable_scope(name) as scope: if self.use_tf_layers: bn = tf.contrib.layers.batch_norm( input_layer, decay=decay, scale=scale, epsilon=epsilon, is_training=self.phase_train, fused=True, data_format=self.data_format, scope=scope) else: bn = self._batch_norm_without_layers(input_layer, decay, scale, epsilon) self.top_layer = bn self.top_size = bn.shape[ 3] if self.data_format == "NHWC" else bn.shape[1] self.top_size = int(self.top_size) return bn
python
def batch_norm(self, input_layer=None, decay=0.999, scale=False, epsilon=0.001): """Adds a Batch Normalization layer.""" if input_layer is None: input_layer = self.top_layer else: self.top_size = None name = "batchnorm" + str(self.counts["batchnorm"]) self.counts["batchnorm"] += 1 with tf.variable_scope(name) as scope: if self.use_tf_layers: bn = tf.contrib.layers.batch_norm( input_layer, decay=decay, scale=scale, epsilon=epsilon, is_training=self.phase_train, fused=True, data_format=self.data_format, scope=scope) else: bn = self._batch_norm_without_layers(input_layer, decay, scale, epsilon) self.top_layer = bn self.top_size = bn.shape[ 3] if self.data_format == "NHWC" else bn.shape[1] self.top_size = int(self.top_size) return bn
[ "def", "batch_norm", "(", "self", ",", "input_layer", "=", "None", ",", "decay", "=", "0.999", ",", "scale", "=", "False", ",", "epsilon", "=", "0.001", ")", ":", "if", "input_layer", "is", "None", ":", "input_layer", "=", "self", ".", "top_layer", "else", ":", "self", ".", "top_size", "=", "None", "name", "=", "\"batchnorm\"", "+", "str", "(", "self", ".", "counts", "[", "\"batchnorm\"", "]", ")", "self", ".", "counts", "[", "\"batchnorm\"", "]", "+=", "1", "with", "tf", ".", "variable_scope", "(", "name", ")", "as", "scope", ":", "if", "self", ".", "use_tf_layers", ":", "bn", "=", "tf", ".", "contrib", ".", "layers", ".", "batch_norm", "(", "input_layer", ",", "decay", "=", "decay", ",", "scale", "=", "scale", ",", "epsilon", "=", "epsilon", ",", "is_training", "=", "self", ".", "phase_train", ",", "fused", "=", "True", ",", "data_format", "=", "self", ".", "data_format", ",", "scope", "=", "scope", ")", "else", ":", "bn", "=", "self", ".", "_batch_norm_without_layers", "(", "input_layer", ",", "decay", ",", "scale", ",", "epsilon", ")", "self", ".", "top_layer", "=", "bn", "self", ".", "top_size", "=", "bn", ".", "shape", "[", "3", "]", "if", "self", ".", "data_format", "==", "\"NHWC\"", "else", "bn", ".", "shape", "[", "1", "]", "self", ".", "top_size", "=", "int", "(", "self", ".", "top_size", ")", "return", "bn" ]
Adds a Batch Normalization layer.
[ "Adds", "a", "Batch", "Normalization", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L468-L499
train
ray-project/ray
python/ray/experimental/sgd/tfbench/convnet_builder.py
ConvNetBuilder.lrn
def lrn(self, depth_radius, bias, alpha, beta): """Adds a local response normalization layer.""" name = "lrn" + str(self.counts["lrn"]) self.counts["lrn"] += 1 self.top_layer = tf.nn.lrn( self.top_layer, depth_radius, bias, alpha, beta, name=name) return self.top_layer
python
def lrn(self, depth_radius, bias, alpha, beta): """Adds a local response normalization layer.""" name = "lrn" + str(self.counts["lrn"]) self.counts["lrn"] += 1 self.top_layer = tf.nn.lrn( self.top_layer, depth_radius, bias, alpha, beta, name=name) return self.top_layer
[ "def", "lrn", "(", "self", ",", "depth_radius", ",", "bias", ",", "alpha", ",", "beta", ")", ":", "name", "=", "\"lrn\"", "+", "str", "(", "self", ".", "counts", "[", "\"lrn\"", "]", ")", "self", ".", "counts", "[", "\"lrn\"", "]", "+=", "1", "self", ".", "top_layer", "=", "tf", ".", "nn", ".", "lrn", "(", "self", ".", "top_layer", ",", "depth_radius", ",", "bias", ",", "alpha", ",", "beta", ",", "name", "=", "name", ")", "return", "self", ".", "top_layer" ]
Adds a local response normalization layer.
[ "Adds", "a", "local", "response", "normalization", "layer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/sgd/tfbench/convnet_builder.py#L501-L507
train
ray-project/ray
python/ray/experimental/internal_kv.py
_internal_kv_get
def _internal_kv_get(key): """Fetch the value of a binary key.""" worker = ray.worker.get_global_worker() if worker.mode == ray.worker.LOCAL_MODE: return _local.get(key) return worker.redis_client.hget(key, "value")
python
def _internal_kv_get(key): """Fetch the value of a binary key.""" worker = ray.worker.get_global_worker() if worker.mode == ray.worker.LOCAL_MODE: return _local.get(key) return worker.redis_client.hget(key, "value")
[ "def", "_internal_kv_get", "(", "key", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "worker", ".", "mode", "==", "ray", ".", "worker", ".", "LOCAL_MODE", ":", "return", "_local", ".", "get", "(", "key", ")", "return", "worker", ".", "redis_client", ".", "hget", "(", "key", ",", "\"value\"", ")" ]
Fetch the value of a binary key.
[ "Fetch", "the", "value", "of", "a", "binary", "key", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/internal_kv.py#L15-L22
train
ray-project/ray
python/ray/experimental/internal_kv.py
_internal_kv_put
def _internal_kv_put(key, value, overwrite=False): """Globally associates a value with a given binary key. This only has an effect if the key does not already have a value. Returns: already_exists (bool): whether the value already exists. """ worker = ray.worker.get_global_worker() if worker.mode == ray.worker.LOCAL_MODE: exists = key in _local if not exists or overwrite: _local[key] = value return exists if overwrite: updated = worker.redis_client.hset(key, "value", value) else: updated = worker.redis_client.hsetnx(key, "value", value) return updated == 0
python
def _internal_kv_put(key, value, overwrite=False): """Globally associates a value with a given binary key. This only has an effect if the key does not already have a value. Returns: already_exists (bool): whether the value already exists. """ worker = ray.worker.get_global_worker() if worker.mode == ray.worker.LOCAL_MODE: exists = key in _local if not exists or overwrite: _local[key] = value return exists if overwrite: updated = worker.redis_client.hset(key, "value", value) else: updated = worker.redis_client.hsetnx(key, "value", value) return updated == 0
[ "def", "_internal_kv_put", "(", "key", ",", "value", ",", "overwrite", "=", "False", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "worker", ".", "mode", "==", "ray", ".", "worker", ".", "LOCAL_MODE", ":", "exists", "=", "key", "in", "_local", "if", "not", "exists", "or", "overwrite", ":", "_local", "[", "key", "]", "=", "value", "return", "exists", "if", "overwrite", ":", "updated", "=", "worker", ".", "redis_client", ".", "hset", "(", "key", ",", "\"value\"", ",", "value", ")", "else", ":", "updated", "=", "worker", ".", "redis_client", ".", "hsetnx", "(", "key", ",", "\"value\"", ",", "value", ")", "return", "updated", "==", "0" ]
Globally associates a value with a given binary key. This only has an effect if the key does not already have a value. Returns: already_exists (bool): whether the value already exists.
[ "Globally", "associates", "a", "value", "with", "a", "given", "binary", "key", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/internal_kv.py#L25-L45
train
ray-project/ray
python/ray/rllib/optimizers/aso_tree_aggregator.py
TreeAggregator.init
def init(self, aggregators): """Deferred init so that we can pass in previously created workers.""" assert len(aggregators) == self.num_aggregation_workers, aggregators if len(self.remote_evaluators) < self.num_aggregation_workers: raise ValueError( "The number of aggregation workers should not exceed the " "number of total evaluation workers ({} vs {})".format( self.num_aggregation_workers, len(self.remote_evaluators))) assigned_evaluators = collections.defaultdict(list) for i, ev in enumerate(self.remote_evaluators): assigned_evaluators[i % self.num_aggregation_workers].append(ev) self.workers = aggregators for i, worker in enumerate(self.workers): worker.init.remote( self.broadcasted_weights, assigned_evaluators[i], self.max_sample_requests_in_flight_per_worker, self.replay_proportion, self.replay_buffer_num_slots, self.train_batch_size, self.sample_batch_size) self.agg_tasks = TaskPool() for agg in self.workers: agg.set_weights.remote(self.broadcasted_weights) self.agg_tasks.add(agg, agg.get_train_batches.remote()) self.initialized = True
python
def init(self, aggregators): """Deferred init so that we can pass in previously created workers.""" assert len(aggregators) == self.num_aggregation_workers, aggregators if len(self.remote_evaluators) < self.num_aggregation_workers: raise ValueError( "The number of aggregation workers should not exceed the " "number of total evaluation workers ({} vs {})".format( self.num_aggregation_workers, len(self.remote_evaluators))) assigned_evaluators = collections.defaultdict(list) for i, ev in enumerate(self.remote_evaluators): assigned_evaluators[i % self.num_aggregation_workers].append(ev) self.workers = aggregators for i, worker in enumerate(self.workers): worker.init.remote( self.broadcasted_weights, assigned_evaluators[i], self.max_sample_requests_in_flight_per_worker, self.replay_proportion, self.replay_buffer_num_slots, self.train_batch_size, self.sample_batch_size) self.agg_tasks = TaskPool() for agg in self.workers: agg.set_weights.remote(self.broadcasted_weights) self.agg_tasks.add(agg, agg.get_train_batches.remote()) self.initialized = True
[ "def", "init", "(", "self", ",", "aggregators", ")", ":", "assert", "len", "(", "aggregators", ")", "==", "self", ".", "num_aggregation_workers", ",", "aggregators", "if", "len", "(", "self", ".", "remote_evaluators", ")", "<", "self", ".", "num_aggregation_workers", ":", "raise", "ValueError", "(", "\"The number of aggregation workers should not exceed the \"", "\"number of total evaluation workers ({} vs {})\"", ".", "format", "(", "self", ".", "num_aggregation_workers", ",", "len", "(", "self", ".", "remote_evaluators", ")", ")", ")", "assigned_evaluators", "=", "collections", ".", "defaultdict", "(", "list", ")", "for", "i", ",", "ev", "in", "enumerate", "(", "self", ".", "remote_evaluators", ")", ":", "assigned_evaluators", "[", "i", "%", "self", ".", "num_aggregation_workers", "]", ".", "append", "(", "ev", ")", "self", ".", "workers", "=", "aggregators", "for", "i", ",", "worker", "in", "enumerate", "(", "self", ".", "workers", ")", ":", "worker", ".", "init", ".", "remote", "(", "self", ".", "broadcasted_weights", ",", "assigned_evaluators", "[", "i", "]", ",", "self", ".", "max_sample_requests_in_flight_per_worker", ",", "self", ".", "replay_proportion", ",", "self", ".", "replay_buffer_num_slots", ",", "self", ".", "train_batch_size", ",", "self", ".", "sample_batch_size", ")", "self", ".", "agg_tasks", "=", "TaskPool", "(", ")", "for", "agg", "in", "self", ".", "workers", ":", "agg", ".", "set_weights", ".", "remote", "(", "self", ".", "broadcasted_weights", ")", "self", ".", "agg_tasks", ".", "add", "(", "agg", ",", "agg", ".", "get_train_batches", ".", "remote", "(", ")", ")", "self", ".", "initialized", "=", "True" ]
Deferred init so that we can pass in previously created workers.
[ "Deferred", "init", "so", "that", "we", "can", "pass", "in", "previously", "created", "workers", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/aso_tree_aggregator.py#L57-L84
train
ray-project/ray
python/ray/internal/internal_api.py
free
def free(object_ids, local_only=False, delete_creating_tasks=False): """Free a list of IDs from object stores. This function is a low-level API which should be used in restricted scenarios. If local_only is false, the request will be send to all object stores. This method will not return any value to indicate whether the deletion is successful or not. This function is an instruction to object store. If the some of the objects are in use, object stores will delete them later when the ref count is down to 0. Args: object_ids (List[ObjectID]): List of object IDs to delete. local_only (bool): Whether only deleting the list of objects in local object store or all object stores. delete_creating_tasks (bool): Whether also delete the object creating tasks. """ worker = ray.worker.get_global_worker() if ray.worker._mode() == ray.worker.LOCAL_MODE: return if isinstance(object_ids, ray.ObjectID): object_ids = [object_ids] if not isinstance(object_ids, list): raise TypeError("free() expects a list of ObjectID, got {}".format( type(object_ids))) # Make sure that the values are object IDs. for object_id in object_ids: if not isinstance(object_id, ray.ObjectID): raise TypeError("Attempting to call `free` on the value {}, " "which is not an ray.ObjectID.".format(object_id)) worker.check_connected() with profiling.profile("ray.free"): if len(object_ids) == 0: return worker.raylet_client.free_objects(object_ids, local_only, delete_creating_tasks)
python
def free(object_ids, local_only=False, delete_creating_tasks=False): """Free a list of IDs from object stores. This function is a low-level API which should be used in restricted scenarios. If local_only is false, the request will be send to all object stores. This method will not return any value to indicate whether the deletion is successful or not. This function is an instruction to object store. If the some of the objects are in use, object stores will delete them later when the ref count is down to 0. Args: object_ids (List[ObjectID]): List of object IDs to delete. local_only (bool): Whether only deleting the list of objects in local object store or all object stores. delete_creating_tasks (bool): Whether also delete the object creating tasks. """ worker = ray.worker.get_global_worker() if ray.worker._mode() == ray.worker.LOCAL_MODE: return if isinstance(object_ids, ray.ObjectID): object_ids = [object_ids] if not isinstance(object_ids, list): raise TypeError("free() expects a list of ObjectID, got {}".format( type(object_ids))) # Make sure that the values are object IDs. for object_id in object_ids: if not isinstance(object_id, ray.ObjectID): raise TypeError("Attempting to call `free` on the value {}, " "which is not an ray.ObjectID.".format(object_id)) worker.check_connected() with profiling.profile("ray.free"): if len(object_ids) == 0: return worker.raylet_client.free_objects(object_ids, local_only, delete_creating_tasks)
[ "def", "free", "(", "object_ids", ",", "local_only", "=", "False", ",", "delete_creating_tasks", "=", "False", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "if", "ray", ".", "worker", ".", "_mode", "(", ")", "==", "ray", ".", "worker", ".", "LOCAL_MODE", ":", "return", "if", "isinstance", "(", "object_ids", ",", "ray", ".", "ObjectID", ")", ":", "object_ids", "=", "[", "object_ids", "]", "if", "not", "isinstance", "(", "object_ids", ",", "list", ")", ":", "raise", "TypeError", "(", "\"free() expects a list of ObjectID, got {}\"", ".", "format", "(", "type", "(", "object_ids", ")", ")", ")", "# Make sure that the values are object IDs.", "for", "object_id", "in", "object_ids", ":", "if", "not", "isinstance", "(", "object_id", ",", "ray", ".", "ObjectID", ")", ":", "raise", "TypeError", "(", "\"Attempting to call `free` on the value {}, \"", "\"which is not an ray.ObjectID.\"", ".", "format", "(", "object_id", ")", ")", "worker", ".", "check_connected", "(", ")", "with", "profiling", ".", "profile", "(", "\"ray.free\"", ")", ":", "if", "len", "(", "object_ids", ")", "==", "0", ":", "return", "worker", ".", "raylet_client", ".", "free_objects", "(", "object_ids", ",", "local_only", ",", "delete_creating_tasks", ")" ]
Free a list of IDs from object stores. This function is a low-level API which should be used in restricted scenarios. If local_only is false, the request will be send to all object stores. This method will not return any value to indicate whether the deletion is successful or not. This function is an instruction to object store. If the some of the objects are in use, object stores will delete them later when the ref count is down to 0. Args: object_ids (List[ObjectID]): List of object IDs to delete. local_only (bool): Whether only deleting the list of objects in local object store or all object stores. delete_creating_tasks (bool): Whether also delete the object creating tasks.
[ "Free", "a", "list", "of", "IDs", "from", "object", "stores", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/internal/internal_api.py#L11-L55
train
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
CollectorService.run
def run(self): """Start the collector worker thread. If running in standalone mode, the current thread will wait until the collector thread ends. """ self.collector.start() if self.standalone: self.collector.join()
python
def run(self): """Start the collector worker thread. If running in standalone mode, the current thread will wait until the collector thread ends. """ self.collector.start() if self.standalone: self.collector.join()
[ "def", "run", "(", "self", ")", ":", "self", ".", "collector", ".", "start", "(", ")", "if", "self", ".", "standalone", ":", "self", ".", "collector", ".", "join", "(", ")" ]
Start the collector worker thread. If running in standalone mode, the current thread will wait until the collector thread ends.
[ "Start", "the", "collector", "worker", "thread", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L47-L55
train
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
CollectorService.init_logger
def init_logger(cls, log_level): """Initialize logger settings.""" logger = logging.getLogger("AutoMLBoard") handler = logging.StreamHandler() formatter = logging.Formatter("[%(levelname)s %(asctime)s] " "%(filename)s: %(lineno)d " "%(message)s") handler.setFormatter(formatter) logger.setLevel(log_level) logger.addHandler(handler) return logger
python
def init_logger(cls, log_level): """Initialize logger settings.""" logger = logging.getLogger("AutoMLBoard") handler = logging.StreamHandler() formatter = logging.Formatter("[%(levelname)s %(asctime)s] " "%(filename)s: %(lineno)d " "%(message)s") handler.setFormatter(formatter) logger.setLevel(log_level) logger.addHandler(handler) return logger
[ "def", "init_logger", "(", "cls", ",", "log_level", ")", ":", "logger", "=", "logging", ".", "getLogger", "(", "\"AutoMLBoard\"", ")", "handler", "=", "logging", ".", "StreamHandler", "(", ")", "formatter", "=", "logging", ".", "Formatter", "(", "\"[%(levelname)s %(asctime)s] \"", "\"%(filename)s: %(lineno)d \"", "\"%(message)s\"", ")", "handler", ".", "setFormatter", "(", "formatter", ")", "logger", ".", "setLevel", "(", "log_level", ")", "logger", ".", "addHandler", "(", "handler", ")", "return", "logger" ]
Initialize logger settings.
[ "Initialize", "logger", "settings", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L62-L72
train
ray-project/ray
python/ray/tune/automlboard/backend/collector.py
Collector.run
def run(self): """Run the main event loop for collector thread. In each round the collector traverse the results log directory and reload trial information from the status files. """ self._initialize() self._do_collect() while not self._is_finished: time.sleep(self._reload_interval) self._do_collect() self.logger.info("Collector stopped.")
python
def run(self): """Run the main event loop for collector thread. In each round the collector traverse the results log directory and reload trial information from the status files. """ self._initialize() self._do_collect() while not self._is_finished: time.sleep(self._reload_interval) self._do_collect() self.logger.info("Collector stopped.")
[ "def", "run", "(", "self", ")", ":", "self", ".", "_initialize", "(", ")", "self", ".", "_do_collect", "(", ")", "while", "not", "self", ".", "_is_finished", ":", "time", ".", "sleep", "(", "self", ".", "_reload_interval", ")", "self", ".", "_do_collect", "(", ")", "self", ".", "logger", ".", "info", "(", "\"Collector stopped.\"", ")" ]
Run the main event loop for collector thread. In each round the collector traverse the results log directory and reload trial information from the status files.
[ "Run", "the", "main", "event", "loop", "for", "collector", "thread", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L98-L111
train