id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
24,400 | 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 |
24,401 | 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 |
24,402 | 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 |
24,403 | 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 |
24,404 | 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 |
24,405 | 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 |
24,406 | 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 |
24,407 | 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 |
24,408 | 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 |
24,409 | 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 |
24,410 | 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 |
24,411 | 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 |
24,412 | 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 |
24,413 | 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 |
24,414 | 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 |
24,415 | 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 |
24,416 | 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 |
24,417 | 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 |
24,418 | 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 |
24,419 | 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 |
24,420 | 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 |
24,421 | 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 |
24,422 | 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 |
24,423 | 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 |
24,424 | 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 |
24,425 | 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 |
24,426 | 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 |
24,427 | 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 |
24,428 | 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 |
24,429 | 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 |
24,430 | 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 |
24,431 | 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 |
24,432 | 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 |
24,433 | 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 |
24,434 | 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 |
24,435 | 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 |
24,436 | 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 |
24,437 | 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 |
24,438 | 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 |
24,439 | 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 |
24,440 | 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 |
24,441 | 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 |
24,442 | 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 |
24,443 | 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 |
24,444 | 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 |
24,445 | 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 |
24,446 | 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 |
24,447 | 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 |
24,448 | 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 |
24,449 | 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 |
24,450 | 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 |
24,451 | 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 |
24,452 | 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 |
24,453 | 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 |
24,454 | 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 |
24,455 | 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 |
24,456 | 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 |
24,457 | 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 |
24,458 | 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 |
24,459 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._initialize | def _initialize(self):
"""Initialize collector worker thread, Log path will be checked first.
Records in DB backend will be cleared.
"""
if not os.path.exists(self._logdir):
raise CollectorError("Log directory %s not exists" % self._logdir)
self.logger.info("Collector started, taking %s as parent directory"
"for all job logs." % self._logdir)
# clear old records
JobRecord.objects.filter().delete()
TrialRecord.objects.filter().delete()
ResultRecord.objects.filter().delete() | python | def _initialize(self):
"""Initialize collector worker thread, Log path will be checked first.
Records in DB backend will be cleared.
"""
if not os.path.exists(self._logdir):
raise CollectorError("Log directory %s not exists" % self._logdir)
self.logger.info("Collector started, taking %s as parent directory"
"for all job logs." % self._logdir)
# clear old records
JobRecord.objects.filter().delete()
TrialRecord.objects.filter().delete()
ResultRecord.objects.filter().delete() | [
"def",
"_initialize",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_logdir",
")",
":",
"raise",
"CollectorError",
"(",
"\"Log directory %s not exists\"",
"%",
"self",
".",
"_logdir",
")",
"self",
".",
"logger",
".",
"info",
"(",
"\"Collector started, taking %s as parent directory\"",
"\"for all job logs.\"",
"%",
"self",
".",
"_logdir",
")",
"# clear old records",
"JobRecord",
".",
"objects",
".",
"filter",
"(",
")",
".",
"delete",
"(",
")",
"TrialRecord",
".",
"objects",
".",
"filter",
"(",
")",
".",
"delete",
"(",
")",
"ResultRecord",
".",
"objects",
".",
"filter",
"(",
")",
".",
"delete",
"(",
")"
] | Initialize collector worker thread, Log path will be checked first.
Records in DB backend will be cleared. | [
"Initialize",
"collector",
"worker",
"thread",
"Log",
"path",
"will",
"be",
"checked",
"first",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L117-L131 |
24,460 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector.sync_job_info | def sync_job_info(self, job_name):
"""Load information of the job with the given job name.
1. Traverse each experiment sub-directory and sync information
for each trial.
2. Create or update the job information, together with the job
meta file.
Args:
job_name (str) name of the Tune experiment
"""
job_path = os.path.join(self._logdir, job_name)
if job_name not in self._monitored_jobs:
self._create_job_info(job_path)
self._monitored_jobs.add(job_name)
else:
self._update_job_info(job_path)
expr_dirs = filter(lambda d: os.path.isdir(os.path.join(job_path, d)),
os.listdir(job_path))
for expr_dir_name in expr_dirs:
self.sync_trial_info(job_path, expr_dir_name)
self._update_job_info(job_path) | python | def sync_job_info(self, job_name):
"""Load information of the job with the given job name.
1. Traverse each experiment sub-directory and sync information
for each trial.
2. Create or update the job information, together with the job
meta file.
Args:
job_name (str) name of the Tune experiment
"""
job_path = os.path.join(self._logdir, job_name)
if job_name not in self._monitored_jobs:
self._create_job_info(job_path)
self._monitored_jobs.add(job_name)
else:
self._update_job_info(job_path)
expr_dirs = filter(lambda d: os.path.isdir(os.path.join(job_path, d)),
os.listdir(job_path))
for expr_dir_name in expr_dirs:
self.sync_trial_info(job_path, expr_dir_name)
self._update_job_info(job_path) | [
"def",
"sync_job_info",
"(",
"self",
",",
"job_name",
")",
":",
"job_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_logdir",
",",
"job_name",
")",
"if",
"job_name",
"not",
"in",
"self",
".",
"_monitored_jobs",
":",
"self",
".",
"_create_job_info",
"(",
"job_path",
")",
"self",
".",
"_monitored_jobs",
".",
"add",
"(",
"job_name",
")",
"else",
":",
"self",
".",
"_update_job_info",
"(",
"job_path",
")",
"expr_dirs",
"=",
"filter",
"(",
"lambda",
"d",
":",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"join",
"(",
"job_path",
",",
"d",
")",
")",
",",
"os",
".",
"listdir",
"(",
"job_path",
")",
")",
"for",
"expr_dir_name",
"in",
"expr_dirs",
":",
"self",
".",
"sync_trial_info",
"(",
"job_path",
",",
"expr_dir_name",
")",
"self",
".",
"_update_job_info",
"(",
"job_path",
")"
] | Load information of the job with the given job name.
1. Traverse each experiment sub-directory and sync information
for each trial.
2. Create or update the job information, together with the job
meta file.
Args:
job_name (str) name of the Tune experiment | [
"Load",
"information",
"of",
"the",
"job",
"with",
"the",
"given",
"job",
"name",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L140-L165 |
24,461 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector.sync_trial_info | def sync_trial_info(self, job_path, expr_dir_name):
"""Load information of the trial from the given experiment directory.
Create or update the trial information, together with the trial
meta file.
Args:
job_path(str)
expr_dir_name(str)
"""
expr_name = expr_dir_name[-8:]
expr_path = os.path.join(job_path, expr_dir_name)
if expr_name not in self._monitored_trials:
self._create_trial_info(expr_path)
self._monitored_trials.add(expr_name)
else:
self._update_trial_info(expr_path) | python | def sync_trial_info(self, job_path, expr_dir_name):
"""Load information of the trial from the given experiment directory.
Create or update the trial information, together with the trial
meta file.
Args:
job_path(str)
expr_dir_name(str)
"""
expr_name = expr_dir_name[-8:]
expr_path = os.path.join(job_path, expr_dir_name)
if expr_name not in self._monitored_trials:
self._create_trial_info(expr_path)
self._monitored_trials.add(expr_name)
else:
self._update_trial_info(expr_path) | [
"def",
"sync_trial_info",
"(",
"self",
",",
"job_path",
",",
"expr_dir_name",
")",
":",
"expr_name",
"=",
"expr_dir_name",
"[",
"-",
"8",
":",
"]",
"expr_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"job_path",
",",
"expr_dir_name",
")",
"if",
"expr_name",
"not",
"in",
"self",
".",
"_monitored_trials",
":",
"self",
".",
"_create_trial_info",
"(",
"expr_path",
")",
"self",
".",
"_monitored_trials",
".",
"add",
"(",
"expr_name",
")",
"else",
":",
"self",
".",
"_update_trial_info",
"(",
"expr_path",
")"
] | Load information of the trial from the given experiment directory.
Create or update the trial information, together with the trial
meta file.
Args:
job_path(str)
expr_dir_name(str) | [
"Load",
"information",
"of",
"the",
"trial",
"from",
"the",
"given",
"experiment",
"directory",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L167-L185 |
24,462 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._create_job_info | def _create_job_info(self, job_dir):
"""Create information for given job.
Meta file will be loaded if exists, and the job information will
be saved in db backend.
Args:
job_dir (str): Directory path of the job.
"""
meta = self._build_job_meta(job_dir)
self.logger.debug("Create job: %s" % meta)
job_record = JobRecord.from_json(meta)
job_record.save() | python | def _create_job_info(self, job_dir):
"""Create information for given job.
Meta file will be loaded if exists, and the job information will
be saved in db backend.
Args:
job_dir (str): Directory path of the job.
"""
meta = self._build_job_meta(job_dir)
self.logger.debug("Create job: %s" % meta)
job_record = JobRecord.from_json(meta)
job_record.save() | [
"def",
"_create_job_info",
"(",
"self",
",",
"job_dir",
")",
":",
"meta",
"=",
"self",
".",
"_build_job_meta",
"(",
"job_dir",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Create job: %s\"",
"%",
"meta",
")",
"job_record",
"=",
"JobRecord",
".",
"from_json",
"(",
"meta",
")",
"job_record",
".",
"save",
"(",
")"
] | Create information for given job.
Meta file will be loaded if exists, and the job information will
be saved in db backend.
Args:
job_dir (str): Directory path of the job. | [
"Create",
"information",
"for",
"given",
"job",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L187-L201 |
24,463 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._update_job_info | def _update_job_info(cls, job_dir):
"""Update information for given job.
Meta file will be loaded if exists, and the job information in
in db backend will be updated.
Args:
job_dir (str): Directory path of the job.
Return:
Updated dict of job meta info
"""
meta_file = os.path.join(job_dir, JOB_META_FILE)
meta = parse_json(meta_file)
if meta:
logging.debug("Update job info for %s" % meta["job_id"])
JobRecord.objects \
.filter(job_id=meta["job_id"]) \
.update(end_time=timestamp2date(meta["end_time"])) | python | def _update_job_info(cls, job_dir):
"""Update information for given job.
Meta file will be loaded if exists, and the job information in
in db backend will be updated.
Args:
job_dir (str): Directory path of the job.
Return:
Updated dict of job meta info
"""
meta_file = os.path.join(job_dir, JOB_META_FILE)
meta = parse_json(meta_file)
if meta:
logging.debug("Update job info for %s" % meta["job_id"])
JobRecord.objects \
.filter(job_id=meta["job_id"]) \
.update(end_time=timestamp2date(meta["end_time"])) | [
"def",
"_update_job_info",
"(",
"cls",
",",
"job_dir",
")",
":",
"meta_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"job_dir",
",",
"JOB_META_FILE",
")",
"meta",
"=",
"parse_json",
"(",
"meta_file",
")",
"if",
"meta",
":",
"logging",
".",
"debug",
"(",
"\"Update job info for %s\"",
"%",
"meta",
"[",
"\"job_id\"",
"]",
")",
"JobRecord",
".",
"objects",
".",
"filter",
"(",
"job_id",
"=",
"meta",
"[",
"\"job_id\"",
"]",
")",
".",
"update",
"(",
"end_time",
"=",
"timestamp2date",
"(",
"meta",
"[",
"\"end_time\"",
"]",
")",
")"
] | Update information for given job.
Meta file will be loaded if exists, and the job information in
in db backend will be updated.
Args:
job_dir (str): Directory path of the job.
Return:
Updated dict of job meta info | [
"Update",
"information",
"for",
"given",
"job",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L204-L223 |
24,464 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._create_trial_info | def _create_trial_info(self, expr_dir):
"""Create information for given trial.
Meta file will be loaded if exists, and the trial information
will be saved in db backend.
Args:
expr_dir (str): Directory path of the experiment.
"""
meta = self._build_trial_meta(expr_dir)
self.logger.debug("Create trial for %s" % meta)
trial_record = TrialRecord.from_json(meta)
trial_record.save() | python | def _create_trial_info(self, expr_dir):
"""Create information for given trial.
Meta file will be loaded if exists, and the trial information
will be saved in db backend.
Args:
expr_dir (str): Directory path of the experiment.
"""
meta = self._build_trial_meta(expr_dir)
self.logger.debug("Create trial for %s" % meta)
trial_record = TrialRecord.from_json(meta)
trial_record.save() | [
"def",
"_create_trial_info",
"(",
"self",
",",
"expr_dir",
")",
":",
"meta",
"=",
"self",
".",
"_build_trial_meta",
"(",
"expr_dir",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Create trial for %s\"",
"%",
"meta",
")",
"trial_record",
"=",
"TrialRecord",
".",
"from_json",
"(",
"meta",
")",
"trial_record",
".",
"save",
"(",
")"
] | Create information for given trial.
Meta file will be loaded if exists, and the trial information
will be saved in db backend.
Args:
expr_dir (str): Directory path of the experiment. | [
"Create",
"information",
"for",
"given",
"trial",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L225-L239 |
24,465 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._update_trial_info | def _update_trial_info(self, expr_dir):
"""Update information for given trial.
Meta file will be loaded if exists, and the trial information
in db backend will be updated.
Args:
expr_dir(str)
"""
trial_id = expr_dir[-8:]
meta_file = os.path.join(expr_dir, EXPR_META_FILE)
meta = parse_json(meta_file)
result_file = os.path.join(expr_dir, EXPR_RESULT_FILE)
offset = self._result_offsets.get(trial_id, 0)
results, new_offset = parse_multiple_json(result_file, offset)
self._add_results(results, trial_id)
self._result_offsets[trial_id] = new_offset
if meta:
TrialRecord.objects \
.filter(trial_id=trial_id) \
.update(trial_status=meta["status"],
end_time=timestamp2date(meta.get("end_time", None)))
elif len(results) > 0:
metrics = {
"episode_reward": results[-1].get("episode_reward_mean", None),
"accuracy": results[-1].get("mean_accuracy", None),
"loss": results[-1].get("loss", None)
}
if results[-1].get("done"):
TrialRecord.objects \
.filter(trial_id=trial_id) \
.update(trial_status="TERMINATED",
end_time=results[-1].get("date", None),
metrics=str(metrics))
else:
TrialRecord.objects \
.filter(trial_id=trial_id) \
.update(metrics=str(metrics)) | python | def _update_trial_info(self, expr_dir):
"""Update information for given trial.
Meta file will be loaded if exists, and the trial information
in db backend will be updated.
Args:
expr_dir(str)
"""
trial_id = expr_dir[-8:]
meta_file = os.path.join(expr_dir, EXPR_META_FILE)
meta = parse_json(meta_file)
result_file = os.path.join(expr_dir, EXPR_RESULT_FILE)
offset = self._result_offsets.get(trial_id, 0)
results, new_offset = parse_multiple_json(result_file, offset)
self._add_results(results, trial_id)
self._result_offsets[trial_id] = new_offset
if meta:
TrialRecord.objects \
.filter(trial_id=trial_id) \
.update(trial_status=meta["status"],
end_time=timestamp2date(meta.get("end_time", None)))
elif len(results) > 0:
metrics = {
"episode_reward": results[-1].get("episode_reward_mean", None),
"accuracy": results[-1].get("mean_accuracy", None),
"loss": results[-1].get("loss", None)
}
if results[-1].get("done"):
TrialRecord.objects \
.filter(trial_id=trial_id) \
.update(trial_status="TERMINATED",
end_time=results[-1].get("date", None),
metrics=str(metrics))
else:
TrialRecord.objects \
.filter(trial_id=trial_id) \
.update(metrics=str(metrics)) | [
"def",
"_update_trial_info",
"(",
"self",
",",
"expr_dir",
")",
":",
"trial_id",
"=",
"expr_dir",
"[",
"-",
"8",
":",
"]",
"meta_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"expr_dir",
",",
"EXPR_META_FILE",
")",
"meta",
"=",
"parse_json",
"(",
"meta_file",
")",
"result_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"expr_dir",
",",
"EXPR_RESULT_FILE",
")",
"offset",
"=",
"self",
".",
"_result_offsets",
".",
"get",
"(",
"trial_id",
",",
"0",
")",
"results",
",",
"new_offset",
"=",
"parse_multiple_json",
"(",
"result_file",
",",
"offset",
")",
"self",
".",
"_add_results",
"(",
"results",
",",
"trial_id",
")",
"self",
".",
"_result_offsets",
"[",
"trial_id",
"]",
"=",
"new_offset",
"if",
"meta",
":",
"TrialRecord",
".",
"objects",
".",
"filter",
"(",
"trial_id",
"=",
"trial_id",
")",
".",
"update",
"(",
"trial_status",
"=",
"meta",
"[",
"\"status\"",
"]",
",",
"end_time",
"=",
"timestamp2date",
"(",
"meta",
".",
"get",
"(",
"\"end_time\"",
",",
"None",
")",
")",
")",
"elif",
"len",
"(",
"results",
")",
">",
"0",
":",
"metrics",
"=",
"{",
"\"episode_reward\"",
":",
"results",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"\"episode_reward_mean\"",
",",
"None",
")",
",",
"\"accuracy\"",
":",
"results",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"\"mean_accuracy\"",
",",
"None",
")",
",",
"\"loss\"",
":",
"results",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"\"loss\"",
",",
"None",
")",
"}",
"if",
"results",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"\"done\"",
")",
":",
"TrialRecord",
".",
"objects",
".",
"filter",
"(",
"trial_id",
"=",
"trial_id",
")",
".",
"update",
"(",
"trial_status",
"=",
"\"TERMINATED\"",
",",
"end_time",
"=",
"results",
"[",
"-",
"1",
"]",
".",
"get",
"(",
"\"date\"",
",",
"None",
")",
",",
"metrics",
"=",
"str",
"(",
"metrics",
")",
")",
"else",
":",
"TrialRecord",
".",
"objects",
".",
"filter",
"(",
"trial_id",
"=",
"trial_id",
")",
".",
"update",
"(",
"metrics",
"=",
"str",
"(",
"metrics",
")",
")"
] | Update information for given trial.
Meta file will be loaded if exists, and the trial information
in db backend will be updated.
Args:
expr_dir(str) | [
"Update",
"information",
"for",
"given",
"trial",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L241-L281 |
24,466 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._build_job_meta | def _build_job_meta(cls, job_dir):
"""Build meta file for job.
Args:
job_dir (str): Directory path of the job.
Return:
A dict of job meta info.
"""
meta_file = os.path.join(job_dir, JOB_META_FILE)
meta = parse_json(meta_file)
if not meta:
job_name = job_dir.split("/")[-1]
user = os.environ.get("USER", None)
meta = {
"job_id": job_name,
"job_name": job_name,
"user": user,
"type": "ray",
"start_time": os.path.getctime(job_dir),
"end_time": None,
"best_trial_id": None,
}
if meta.get("start_time", None):
meta["start_time"] = timestamp2date(meta["start_time"])
return meta | python | def _build_job_meta(cls, job_dir):
"""Build meta file for job.
Args:
job_dir (str): Directory path of the job.
Return:
A dict of job meta info.
"""
meta_file = os.path.join(job_dir, JOB_META_FILE)
meta = parse_json(meta_file)
if not meta:
job_name = job_dir.split("/")[-1]
user = os.environ.get("USER", None)
meta = {
"job_id": job_name,
"job_name": job_name,
"user": user,
"type": "ray",
"start_time": os.path.getctime(job_dir),
"end_time": None,
"best_trial_id": None,
}
if meta.get("start_time", None):
meta["start_time"] = timestamp2date(meta["start_time"])
return meta | [
"def",
"_build_job_meta",
"(",
"cls",
",",
"job_dir",
")",
":",
"meta_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"job_dir",
",",
"JOB_META_FILE",
")",
"meta",
"=",
"parse_json",
"(",
"meta_file",
")",
"if",
"not",
"meta",
":",
"job_name",
"=",
"job_dir",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"1",
"]",
"user",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"\"USER\"",
",",
"None",
")",
"meta",
"=",
"{",
"\"job_id\"",
":",
"job_name",
",",
"\"job_name\"",
":",
"job_name",
",",
"\"user\"",
":",
"user",
",",
"\"type\"",
":",
"\"ray\"",
",",
"\"start_time\"",
":",
"os",
".",
"path",
".",
"getctime",
"(",
"job_dir",
")",
",",
"\"end_time\"",
":",
"None",
",",
"\"best_trial_id\"",
":",
"None",
",",
"}",
"if",
"meta",
".",
"get",
"(",
"\"start_time\"",
",",
"None",
")",
":",
"meta",
"[",
"\"start_time\"",
"]",
"=",
"timestamp2date",
"(",
"meta",
"[",
"\"start_time\"",
"]",
")",
"return",
"meta"
] | Build meta file for job.
Args:
job_dir (str): Directory path of the job.
Return:
A dict of job meta info. | [
"Build",
"meta",
"file",
"for",
"job",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L284-L312 |
24,467 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._build_trial_meta | def _build_trial_meta(cls, expr_dir):
"""Build meta file for trial.
Args:
expr_dir (str): Directory path of the experiment.
Return:
A dict of trial meta info.
"""
meta_file = os.path.join(expr_dir, EXPR_META_FILE)
meta = parse_json(meta_file)
if not meta:
job_id = expr_dir.split("/")[-2]
trial_id = expr_dir[-8:]
params = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE))
meta = {
"trial_id": trial_id,
"job_id": job_id,
"status": "RUNNING",
"type": "TUNE",
"start_time": os.path.getctime(expr_dir),
"end_time": None,
"progress_offset": 0,
"result_offset": 0,
"params": params
}
if not meta.get("start_time", None):
meta["start_time"] = os.path.getctime(expr_dir)
if isinstance(meta["start_time"], float):
meta["start_time"] = timestamp2date(meta["start_time"])
if meta.get("end_time", None):
meta["end_time"] = timestamp2date(meta["end_time"])
meta["params"] = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE))
return meta | python | def _build_trial_meta(cls, expr_dir):
"""Build meta file for trial.
Args:
expr_dir (str): Directory path of the experiment.
Return:
A dict of trial meta info.
"""
meta_file = os.path.join(expr_dir, EXPR_META_FILE)
meta = parse_json(meta_file)
if not meta:
job_id = expr_dir.split("/")[-2]
trial_id = expr_dir[-8:]
params = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE))
meta = {
"trial_id": trial_id,
"job_id": job_id,
"status": "RUNNING",
"type": "TUNE",
"start_time": os.path.getctime(expr_dir),
"end_time": None,
"progress_offset": 0,
"result_offset": 0,
"params": params
}
if not meta.get("start_time", None):
meta["start_time"] = os.path.getctime(expr_dir)
if isinstance(meta["start_time"], float):
meta["start_time"] = timestamp2date(meta["start_time"])
if meta.get("end_time", None):
meta["end_time"] = timestamp2date(meta["end_time"])
meta["params"] = parse_json(os.path.join(expr_dir, EXPR_PARARM_FILE))
return meta | [
"def",
"_build_trial_meta",
"(",
"cls",
",",
"expr_dir",
")",
":",
"meta_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"expr_dir",
",",
"EXPR_META_FILE",
")",
"meta",
"=",
"parse_json",
"(",
"meta_file",
")",
"if",
"not",
"meta",
":",
"job_id",
"=",
"expr_dir",
".",
"split",
"(",
"\"/\"",
")",
"[",
"-",
"2",
"]",
"trial_id",
"=",
"expr_dir",
"[",
"-",
"8",
":",
"]",
"params",
"=",
"parse_json",
"(",
"os",
".",
"path",
".",
"join",
"(",
"expr_dir",
",",
"EXPR_PARARM_FILE",
")",
")",
"meta",
"=",
"{",
"\"trial_id\"",
":",
"trial_id",
",",
"\"job_id\"",
":",
"job_id",
",",
"\"status\"",
":",
"\"RUNNING\"",
",",
"\"type\"",
":",
"\"TUNE\"",
",",
"\"start_time\"",
":",
"os",
".",
"path",
".",
"getctime",
"(",
"expr_dir",
")",
",",
"\"end_time\"",
":",
"None",
",",
"\"progress_offset\"",
":",
"0",
",",
"\"result_offset\"",
":",
"0",
",",
"\"params\"",
":",
"params",
"}",
"if",
"not",
"meta",
".",
"get",
"(",
"\"start_time\"",
",",
"None",
")",
":",
"meta",
"[",
"\"start_time\"",
"]",
"=",
"os",
".",
"path",
".",
"getctime",
"(",
"expr_dir",
")",
"if",
"isinstance",
"(",
"meta",
"[",
"\"start_time\"",
"]",
",",
"float",
")",
":",
"meta",
"[",
"\"start_time\"",
"]",
"=",
"timestamp2date",
"(",
"meta",
"[",
"\"start_time\"",
"]",
")",
"if",
"meta",
".",
"get",
"(",
"\"end_time\"",
",",
"None",
")",
":",
"meta",
"[",
"\"end_time\"",
"]",
"=",
"timestamp2date",
"(",
"meta",
"[",
"\"end_time\"",
"]",
")",
"meta",
"[",
"\"params\"",
"]",
"=",
"parse_json",
"(",
"os",
".",
"path",
".",
"join",
"(",
"expr_dir",
",",
"EXPR_PARARM_FILE",
")",
")",
"return",
"meta"
] | Build meta file for trial.
Args:
expr_dir (str): Directory path of the experiment.
Return:
A dict of trial meta info. | [
"Build",
"meta",
"file",
"for",
"trial",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L315-L354 |
24,468 | ray-project/ray | python/ray/tune/automlboard/backend/collector.py | Collector._add_results | def _add_results(self, results, trial_id):
"""Add a list of results into db.
Args:
results (list): A list of json results.
trial_id (str): Id of the trial.
"""
for result in results:
self.logger.debug("Appending result: %s" % result)
result["trial_id"] = trial_id
result_record = ResultRecord.from_json(result)
result_record.save() | python | def _add_results(self, results, trial_id):
"""Add a list of results into db.
Args:
results (list): A list of json results.
trial_id (str): Id of the trial.
"""
for result in results:
self.logger.debug("Appending result: %s" % result)
result["trial_id"] = trial_id
result_record = ResultRecord.from_json(result)
result_record.save() | [
"def",
"_add_results",
"(",
"self",
",",
"results",
",",
"trial_id",
")",
":",
"for",
"result",
"in",
"results",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Appending result: %s\"",
"%",
"result",
")",
"result",
"[",
"\"trial_id\"",
"]",
"=",
"trial_id",
"result_record",
"=",
"ResultRecord",
".",
"from_json",
"(",
"result",
")",
"result_record",
".",
"save",
"(",
")"
] | Add a list of results into db.
Args:
results (list): A list of json results.
trial_id (str): Id of the trial. | [
"Add",
"a",
"list",
"of",
"results",
"into",
"db",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/backend/collector.py#L356-L367 |
24,469 | ray-project/ray | python/ray/rllib/models/lstm.py | add_time_dimension | def add_time_dimension(padded_inputs, seq_lens):
"""Adds a time dimension to padded inputs.
Arguments:
padded_inputs (Tensor): a padded batch of sequences. That is,
for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
A, B, C are sequence elements and * denotes padding.
seq_lens (Tensor): the sequence lengths within the input batch,
suitable for passing to tf.nn.dynamic_rnn().
Returns:
Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...].
"""
# Sequence lengths have to be specified for LSTM batch inputs. The
# input batch must be padded to the max seq length given here. That is,
# batch_size == len(seq_lens) * max(seq_lens)
padded_batch_size = tf.shape(padded_inputs)[0]
max_seq_len = padded_batch_size // tf.shape(seq_lens)[0]
# Dynamically reshape the padded batch to introduce a time dimension.
new_batch_size = padded_batch_size // max_seq_len
new_shape = ([new_batch_size, max_seq_len] +
padded_inputs.get_shape().as_list()[1:])
return tf.reshape(padded_inputs, new_shape) | python | def add_time_dimension(padded_inputs, seq_lens):
"""Adds a time dimension to padded inputs.
Arguments:
padded_inputs (Tensor): a padded batch of sequences. That is,
for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
A, B, C are sequence elements and * denotes padding.
seq_lens (Tensor): the sequence lengths within the input batch,
suitable for passing to tf.nn.dynamic_rnn().
Returns:
Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...].
"""
# Sequence lengths have to be specified for LSTM batch inputs. The
# input batch must be padded to the max seq length given here. That is,
# batch_size == len(seq_lens) * max(seq_lens)
padded_batch_size = tf.shape(padded_inputs)[0]
max_seq_len = padded_batch_size // tf.shape(seq_lens)[0]
# Dynamically reshape the padded batch to introduce a time dimension.
new_batch_size = padded_batch_size // max_seq_len
new_shape = ([new_batch_size, max_seq_len] +
padded_inputs.get_shape().as_list()[1:])
return tf.reshape(padded_inputs, new_shape) | [
"def",
"add_time_dimension",
"(",
"padded_inputs",
",",
"seq_lens",
")",
":",
"# Sequence lengths have to be specified for LSTM batch inputs. The",
"# input batch must be padded to the max seq length given here. That is,",
"# batch_size == len(seq_lens) * max(seq_lens)",
"padded_batch_size",
"=",
"tf",
".",
"shape",
"(",
"padded_inputs",
")",
"[",
"0",
"]",
"max_seq_len",
"=",
"padded_batch_size",
"//",
"tf",
".",
"shape",
"(",
"seq_lens",
")",
"[",
"0",
"]",
"# Dynamically reshape the padded batch to introduce a time dimension.",
"new_batch_size",
"=",
"padded_batch_size",
"//",
"max_seq_len",
"new_shape",
"=",
"(",
"[",
"new_batch_size",
",",
"max_seq_len",
"]",
"+",
"padded_inputs",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
":",
"]",
")",
"return",
"tf",
".",
"reshape",
"(",
"padded_inputs",
",",
"new_shape",
")"
] | Adds a time dimension to padded inputs.
Arguments:
padded_inputs (Tensor): a padded batch of sequences. That is,
for seq_lens=[1, 2, 2], then inputs=[A, *, B, B, C, C], where
A, B, C are sequence elements and * denotes padding.
seq_lens (Tensor): the sequence lengths within the input batch,
suitable for passing to tf.nn.dynamic_rnn().
Returns:
Reshaped tensor of shape [NUM_SEQUENCES, MAX_SEQ_LEN, ...]. | [
"Adds",
"a",
"time",
"dimension",
"to",
"padded",
"inputs",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/lstm.py#L95-L119 |
24,470 | ray-project/ray | python/ray/rllib/models/lstm.py | chop_into_sequences | def chop_into_sequences(episode_ids,
unroll_ids,
agent_indices,
feature_columns,
state_columns,
max_seq_len,
dynamic_max=True,
_extra_padding=0):
"""Truncate and pad experiences into fixed-length sequences.
Arguments:
episode_ids (list): List of episode ids for each step.
unroll_ids (list): List of identifiers for the sample batch. This is
used to make sure sequences are cut between sample batches.
agent_indices (list): List of agent ids for each step. Note that this
has to be combined with episode_ids for uniqueness.
feature_columns (list): List of arrays containing features.
state_columns (list): List of arrays containing LSTM state values.
max_seq_len (int): Max length of sequences before truncation.
dynamic_max (bool): Whether to dynamically shrink the max seq len.
For example, if max len is 20 and the actual max seq len in the
data is 7, it will be shrunk to 7.
_extra_padding (int): Add extra padding to the end of sequences.
Returns:
f_pad (list): Padded feature columns. These will be of shape
[NUM_SEQUENCES * MAX_SEQ_LEN, ...].
s_init (list): Initial states for each sequence, of shape
[NUM_SEQUENCES, ...].
seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES].
Examples:
>>> f_pad, s_init, seq_lens = chop_into_sequences(
episode_ids=[1, 1, 5, 5, 5, 5],
unroll_ids=[4, 4, 4, 4, 4, 4],
agent_indices=[0, 0, 0, 0, 0, 0],
feature_columns=[[4, 4, 8, 8, 8, 8],
[1, 1, 0, 1, 1, 0]],
state_columns=[[4, 5, 4, 5, 5, 5]],
max_seq_len=3)
>>> print(f_pad)
[[4, 4, 0, 8, 8, 8, 8, 0, 0],
[1, 1, 0, 0, 1, 1, 0, 0, 0]]
>>> print(s_init)
[[4, 4, 5]]
>>> print(seq_lens)
[2, 3, 1]
"""
prev_id = None
seq_lens = []
seq_len = 0
unique_ids = np.add(
np.add(episode_ids, agent_indices),
np.array(unroll_ids) << 32)
for uid in unique_ids:
if (prev_id is not None and uid != prev_id) or \
seq_len >= max_seq_len:
seq_lens.append(seq_len)
seq_len = 0
seq_len += 1
prev_id = uid
if seq_len:
seq_lens.append(seq_len)
assert sum(seq_lens) == len(unique_ids)
# Dynamically shrink max len as needed to optimize memory usage
if dynamic_max:
max_seq_len = max(seq_lens) + _extra_padding
feature_sequences = []
for f in feature_columns:
f = np.array(f)
f_pad = np.zeros((len(seq_lens) * max_seq_len, ) + np.shape(f)[1:])
seq_base = 0
i = 0
for l in seq_lens:
for seq_offset in range(l):
f_pad[seq_base + seq_offset] = f[i]
i += 1
seq_base += max_seq_len
assert i == len(unique_ids), f
feature_sequences.append(f_pad)
initial_states = []
for s in state_columns:
s = np.array(s)
s_init = []
i = 0
for l in seq_lens:
s_init.append(s[i])
i += l
initial_states.append(np.array(s_init))
return feature_sequences, initial_states, np.array(seq_lens) | python | def chop_into_sequences(episode_ids,
unroll_ids,
agent_indices,
feature_columns,
state_columns,
max_seq_len,
dynamic_max=True,
_extra_padding=0):
"""Truncate and pad experiences into fixed-length sequences.
Arguments:
episode_ids (list): List of episode ids for each step.
unroll_ids (list): List of identifiers for the sample batch. This is
used to make sure sequences are cut between sample batches.
agent_indices (list): List of agent ids for each step. Note that this
has to be combined with episode_ids for uniqueness.
feature_columns (list): List of arrays containing features.
state_columns (list): List of arrays containing LSTM state values.
max_seq_len (int): Max length of sequences before truncation.
dynamic_max (bool): Whether to dynamically shrink the max seq len.
For example, if max len is 20 and the actual max seq len in the
data is 7, it will be shrunk to 7.
_extra_padding (int): Add extra padding to the end of sequences.
Returns:
f_pad (list): Padded feature columns. These will be of shape
[NUM_SEQUENCES * MAX_SEQ_LEN, ...].
s_init (list): Initial states for each sequence, of shape
[NUM_SEQUENCES, ...].
seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES].
Examples:
>>> f_pad, s_init, seq_lens = chop_into_sequences(
episode_ids=[1, 1, 5, 5, 5, 5],
unroll_ids=[4, 4, 4, 4, 4, 4],
agent_indices=[0, 0, 0, 0, 0, 0],
feature_columns=[[4, 4, 8, 8, 8, 8],
[1, 1, 0, 1, 1, 0]],
state_columns=[[4, 5, 4, 5, 5, 5]],
max_seq_len=3)
>>> print(f_pad)
[[4, 4, 0, 8, 8, 8, 8, 0, 0],
[1, 1, 0, 0, 1, 1, 0, 0, 0]]
>>> print(s_init)
[[4, 4, 5]]
>>> print(seq_lens)
[2, 3, 1]
"""
prev_id = None
seq_lens = []
seq_len = 0
unique_ids = np.add(
np.add(episode_ids, agent_indices),
np.array(unroll_ids) << 32)
for uid in unique_ids:
if (prev_id is not None and uid != prev_id) or \
seq_len >= max_seq_len:
seq_lens.append(seq_len)
seq_len = 0
seq_len += 1
prev_id = uid
if seq_len:
seq_lens.append(seq_len)
assert sum(seq_lens) == len(unique_ids)
# Dynamically shrink max len as needed to optimize memory usage
if dynamic_max:
max_seq_len = max(seq_lens) + _extra_padding
feature_sequences = []
for f in feature_columns:
f = np.array(f)
f_pad = np.zeros((len(seq_lens) * max_seq_len, ) + np.shape(f)[1:])
seq_base = 0
i = 0
for l in seq_lens:
for seq_offset in range(l):
f_pad[seq_base + seq_offset] = f[i]
i += 1
seq_base += max_seq_len
assert i == len(unique_ids), f
feature_sequences.append(f_pad)
initial_states = []
for s in state_columns:
s = np.array(s)
s_init = []
i = 0
for l in seq_lens:
s_init.append(s[i])
i += l
initial_states.append(np.array(s_init))
return feature_sequences, initial_states, np.array(seq_lens) | [
"def",
"chop_into_sequences",
"(",
"episode_ids",
",",
"unroll_ids",
",",
"agent_indices",
",",
"feature_columns",
",",
"state_columns",
",",
"max_seq_len",
",",
"dynamic_max",
"=",
"True",
",",
"_extra_padding",
"=",
"0",
")",
":",
"prev_id",
"=",
"None",
"seq_lens",
"=",
"[",
"]",
"seq_len",
"=",
"0",
"unique_ids",
"=",
"np",
".",
"add",
"(",
"np",
".",
"add",
"(",
"episode_ids",
",",
"agent_indices",
")",
",",
"np",
".",
"array",
"(",
"unroll_ids",
")",
"<<",
"32",
")",
"for",
"uid",
"in",
"unique_ids",
":",
"if",
"(",
"prev_id",
"is",
"not",
"None",
"and",
"uid",
"!=",
"prev_id",
")",
"or",
"seq_len",
">=",
"max_seq_len",
":",
"seq_lens",
".",
"append",
"(",
"seq_len",
")",
"seq_len",
"=",
"0",
"seq_len",
"+=",
"1",
"prev_id",
"=",
"uid",
"if",
"seq_len",
":",
"seq_lens",
".",
"append",
"(",
"seq_len",
")",
"assert",
"sum",
"(",
"seq_lens",
")",
"==",
"len",
"(",
"unique_ids",
")",
"# Dynamically shrink max len as needed to optimize memory usage",
"if",
"dynamic_max",
":",
"max_seq_len",
"=",
"max",
"(",
"seq_lens",
")",
"+",
"_extra_padding",
"feature_sequences",
"=",
"[",
"]",
"for",
"f",
"in",
"feature_columns",
":",
"f",
"=",
"np",
".",
"array",
"(",
"f",
")",
"f_pad",
"=",
"np",
".",
"zeros",
"(",
"(",
"len",
"(",
"seq_lens",
")",
"*",
"max_seq_len",
",",
")",
"+",
"np",
".",
"shape",
"(",
"f",
")",
"[",
"1",
":",
"]",
")",
"seq_base",
"=",
"0",
"i",
"=",
"0",
"for",
"l",
"in",
"seq_lens",
":",
"for",
"seq_offset",
"in",
"range",
"(",
"l",
")",
":",
"f_pad",
"[",
"seq_base",
"+",
"seq_offset",
"]",
"=",
"f",
"[",
"i",
"]",
"i",
"+=",
"1",
"seq_base",
"+=",
"max_seq_len",
"assert",
"i",
"==",
"len",
"(",
"unique_ids",
")",
",",
"f",
"feature_sequences",
".",
"append",
"(",
"f_pad",
")",
"initial_states",
"=",
"[",
"]",
"for",
"s",
"in",
"state_columns",
":",
"s",
"=",
"np",
".",
"array",
"(",
"s",
")",
"s_init",
"=",
"[",
"]",
"i",
"=",
"0",
"for",
"l",
"in",
"seq_lens",
":",
"s_init",
".",
"append",
"(",
"s",
"[",
"i",
"]",
")",
"i",
"+=",
"l",
"initial_states",
".",
"append",
"(",
"np",
".",
"array",
"(",
"s_init",
")",
")",
"return",
"feature_sequences",
",",
"initial_states",
",",
"np",
".",
"array",
"(",
"seq_lens",
")"
] | Truncate and pad experiences into fixed-length sequences.
Arguments:
episode_ids (list): List of episode ids for each step.
unroll_ids (list): List of identifiers for the sample batch. This is
used to make sure sequences are cut between sample batches.
agent_indices (list): List of agent ids for each step. Note that this
has to be combined with episode_ids for uniqueness.
feature_columns (list): List of arrays containing features.
state_columns (list): List of arrays containing LSTM state values.
max_seq_len (int): Max length of sequences before truncation.
dynamic_max (bool): Whether to dynamically shrink the max seq len.
For example, if max len is 20 and the actual max seq len in the
data is 7, it will be shrunk to 7.
_extra_padding (int): Add extra padding to the end of sequences.
Returns:
f_pad (list): Padded feature columns. These will be of shape
[NUM_SEQUENCES * MAX_SEQ_LEN, ...].
s_init (list): Initial states for each sequence, of shape
[NUM_SEQUENCES, ...].
seq_lens (list): List of sequence lengths, of shape [NUM_SEQUENCES].
Examples:
>>> f_pad, s_init, seq_lens = chop_into_sequences(
episode_ids=[1, 1, 5, 5, 5, 5],
unroll_ids=[4, 4, 4, 4, 4, 4],
agent_indices=[0, 0, 0, 0, 0, 0],
feature_columns=[[4, 4, 8, 8, 8, 8],
[1, 1, 0, 1, 1, 0]],
state_columns=[[4, 5, 4, 5, 5, 5]],
max_seq_len=3)
>>> print(f_pad)
[[4, 4, 0, 8, 8, 8, 8, 0, 0],
[1, 1, 0, 0, 1, 1, 0, 0, 0]]
>>> print(s_init)
[[4, 4, 5]]
>>> print(seq_lens)
[2, 3, 1] | [
"Truncate",
"and",
"pad",
"experiences",
"into",
"fixed",
"-",
"length",
"sequences",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/lstm.py#L123-L217 |
24,471 | ray-project/ray | python/ray/tune/schedulers/pbt.py | explore | def explore(config, mutations, resample_probability, custom_explore_fn):
"""Return a config perturbed as specified.
Args:
config (dict): Original hyperparameter configuration.
mutations (dict): Specification of mutations to perform as documented
in the PopulationBasedTraining scheduler.
resample_probability (float): Probability of allowing resampling of a
particular variable.
custom_explore_fn (func): Custom explore fn applied after built-in
config perturbations are.
"""
new_config = copy.deepcopy(config)
for key, distribution in mutations.items():
if isinstance(distribution, dict):
new_config.update({
key: explore(config[key], mutations[key], resample_probability,
None)
})
elif isinstance(distribution, list):
if random.random() < resample_probability or \
config[key] not in distribution:
new_config[key] = random.choice(distribution)
elif random.random() > 0.5:
new_config[key] = distribution[max(
0,
distribution.index(config[key]) - 1)]
else:
new_config[key] = distribution[min(
len(distribution) - 1,
distribution.index(config[key]) + 1)]
else:
if random.random() < resample_probability:
new_config[key] = distribution()
elif random.random() > 0.5:
new_config[key] = config[key] * 1.2
else:
new_config[key] = config[key] * 0.8
if type(config[key]) is int:
new_config[key] = int(new_config[key])
if custom_explore_fn:
new_config = custom_explore_fn(new_config)
assert new_config is not None, \
"Custom explore fn failed to return new config"
logger.info("[explore] perturbed config from {} -> {}".format(
config, new_config))
return new_config | python | def explore(config, mutations, resample_probability, custom_explore_fn):
"""Return a config perturbed as specified.
Args:
config (dict): Original hyperparameter configuration.
mutations (dict): Specification of mutations to perform as documented
in the PopulationBasedTraining scheduler.
resample_probability (float): Probability of allowing resampling of a
particular variable.
custom_explore_fn (func): Custom explore fn applied after built-in
config perturbations are.
"""
new_config = copy.deepcopy(config)
for key, distribution in mutations.items():
if isinstance(distribution, dict):
new_config.update({
key: explore(config[key], mutations[key], resample_probability,
None)
})
elif isinstance(distribution, list):
if random.random() < resample_probability or \
config[key] not in distribution:
new_config[key] = random.choice(distribution)
elif random.random() > 0.5:
new_config[key] = distribution[max(
0,
distribution.index(config[key]) - 1)]
else:
new_config[key] = distribution[min(
len(distribution) - 1,
distribution.index(config[key]) + 1)]
else:
if random.random() < resample_probability:
new_config[key] = distribution()
elif random.random() > 0.5:
new_config[key] = config[key] * 1.2
else:
new_config[key] = config[key] * 0.8
if type(config[key]) is int:
new_config[key] = int(new_config[key])
if custom_explore_fn:
new_config = custom_explore_fn(new_config)
assert new_config is not None, \
"Custom explore fn failed to return new config"
logger.info("[explore] perturbed config from {} -> {}".format(
config, new_config))
return new_config | [
"def",
"explore",
"(",
"config",
",",
"mutations",
",",
"resample_probability",
",",
"custom_explore_fn",
")",
":",
"new_config",
"=",
"copy",
".",
"deepcopy",
"(",
"config",
")",
"for",
"key",
",",
"distribution",
"in",
"mutations",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"distribution",
",",
"dict",
")",
":",
"new_config",
".",
"update",
"(",
"{",
"key",
":",
"explore",
"(",
"config",
"[",
"key",
"]",
",",
"mutations",
"[",
"key",
"]",
",",
"resample_probability",
",",
"None",
")",
"}",
")",
"elif",
"isinstance",
"(",
"distribution",
",",
"list",
")",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"resample_probability",
"or",
"config",
"[",
"key",
"]",
"not",
"in",
"distribution",
":",
"new_config",
"[",
"key",
"]",
"=",
"random",
".",
"choice",
"(",
"distribution",
")",
"elif",
"random",
".",
"random",
"(",
")",
">",
"0.5",
":",
"new_config",
"[",
"key",
"]",
"=",
"distribution",
"[",
"max",
"(",
"0",
",",
"distribution",
".",
"index",
"(",
"config",
"[",
"key",
"]",
")",
"-",
"1",
")",
"]",
"else",
":",
"new_config",
"[",
"key",
"]",
"=",
"distribution",
"[",
"min",
"(",
"len",
"(",
"distribution",
")",
"-",
"1",
",",
"distribution",
".",
"index",
"(",
"config",
"[",
"key",
"]",
")",
"+",
"1",
")",
"]",
"else",
":",
"if",
"random",
".",
"random",
"(",
")",
"<",
"resample_probability",
":",
"new_config",
"[",
"key",
"]",
"=",
"distribution",
"(",
")",
"elif",
"random",
".",
"random",
"(",
")",
">",
"0.5",
":",
"new_config",
"[",
"key",
"]",
"=",
"config",
"[",
"key",
"]",
"*",
"1.2",
"else",
":",
"new_config",
"[",
"key",
"]",
"=",
"config",
"[",
"key",
"]",
"*",
"0.8",
"if",
"type",
"(",
"config",
"[",
"key",
"]",
")",
"is",
"int",
":",
"new_config",
"[",
"key",
"]",
"=",
"int",
"(",
"new_config",
"[",
"key",
"]",
")",
"if",
"custom_explore_fn",
":",
"new_config",
"=",
"custom_explore_fn",
"(",
"new_config",
")",
"assert",
"new_config",
"is",
"not",
"None",
",",
"\"Custom explore fn failed to return new config\"",
"logger",
".",
"info",
"(",
"\"[explore] perturbed config from {} -> {}\"",
".",
"format",
"(",
"config",
",",
"new_config",
")",
")",
"return",
"new_config"
] | Return a config perturbed as specified.
Args:
config (dict): Original hyperparameter configuration.
mutations (dict): Specification of mutations to perform as documented
in the PopulationBasedTraining scheduler.
resample_probability (float): Probability of allowing resampling of a
particular variable.
custom_explore_fn (func): Custom explore fn applied after built-in
config perturbations are. | [
"Return",
"a",
"config",
"perturbed",
"as",
"specified",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L41-L87 |
24,472 | ray-project/ray | python/ray/tune/schedulers/pbt.py | make_experiment_tag | def make_experiment_tag(orig_tag, config, mutations):
"""Appends perturbed params to the trial name to show in the console."""
resolved_vars = {}
for k in mutations.keys():
resolved_vars[("config", k)] = config[k]
return "{}@perturbed[{}]".format(orig_tag, format_vars(resolved_vars)) | python | def make_experiment_tag(orig_tag, config, mutations):
"""Appends perturbed params to the trial name to show in the console."""
resolved_vars = {}
for k in mutations.keys():
resolved_vars[("config", k)] = config[k]
return "{}@perturbed[{}]".format(orig_tag, format_vars(resolved_vars)) | [
"def",
"make_experiment_tag",
"(",
"orig_tag",
",",
"config",
",",
"mutations",
")",
":",
"resolved_vars",
"=",
"{",
"}",
"for",
"k",
"in",
"mutations",
".",
"keys",
"(",
")",
":",
"resolved_vars",
"[",
"(",
"\"config\"",
",",
"k",
")",
"]",
"=",
"config",
"[",
"k",
"]",
"return",
"\"{}@perturbed[{}]\"",
".",
"format",
"(",
"orig_tag",
",",
"format_vars",
"(",
"resolved_vars",
")",
")"
] | Appends perturbed params to the trial name to show in the console. | [
"Appends",
"perturbed",
"params",
"to",
"the",
"trial",
"name",
"to",
"show",
"in",
"the",
"console",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L90-L96 |
24,473 | ray-project/ray | python/ray/tune/schedulers/pbt.py | PopulationBasedTraining._exploit | def _exploit(self, trial_executor, trial, trial_to_clone):
"""Transfers perturbed state from trial_to_clone -> trial.
If specified, also logs the updated hyperparam state."""
trial_state = self._trial_state[trial]
new_state = self._trial_state[trial_to_clone]
if not new_state.last_checkpoint:
logger.info("[pbt]: no checkpoint for trial."
" Skip exploit for Trial {}".format(trial))
return
new_config = explore(trial_to_clone.config, self._hyperparam_mutations,
self._resample_probability,
self._custom_explore_fn)
logger.info("[exploit] transferring weights from trial "
"{} (score {}) -> {} (score {})".format(
trial_to_clone, new_state.last_score, trial,
trial_state.last_score))
if self._log_config:
self._log_config_on_step(trial_state, new_state, trial,
trial_to_clone, new_config)
new_tag = make_experiment_tag(trial_state.orig_tag, new_config,
self._hyperparam_mutations)
reset_successful = trial_executor.reset_trial(trial, new_config,
new_tag)
if reset_successful:
trial_executor.restore(
trial, Checkpoint.from_object(new_state.last_checkpoint))
else:
trial_executor.stop_trial(trial, stop_logger=False)
trial.config = new_config
trial.experiment_tag = new_tag
trial_executor.start_trial(
trial, Checkpoint.from_object(new_state.last_checkpoint))
self._num_perturbations += 1
# Transfer over the last perturbation time as well
trial_state.last_perturbation_time = new_state.last_perturbation_time | python | def _exploit(self, trial_executor, trial, trial_to_clone):
"""Transfers perturbed state from trial_to_clone -> trial.
If specified, also logs the updated hyperparam state."""
trial_state = self._trial_state[trial]
new_state = self._trial_state[trial_to_clone]
if not new_state.last_checkpoint:
logger.info("[pbt]: no checkpoint for trial."
" Skip exploit for Trial {}".format(trial))
return
new_config = explore(trial_to_clone.config, self._hyperparam_mutations,
self._resample_probability,
self._custom_explore_fn)
logger.info("[exploit] transferring weights from trial "
"{} (score {}) -> {} (score {})".format(
trial_to_clone, new_state.last_score, trial,
trial_state.last_score))
if self._log_config:
self._log_config_on_step(trial_state, new_state, trial,
trial_to_clone, new_config)
new_tag = make_experiment_tag(trial_state.orig_tag, new_config,
self._hyperparam_mutations)
reset_successful = trial_executor.reset_trial(trial, new_config,
new_tag)
if reset_successful:
trial_executor.restore(
trial, Checkpoint.from_object(new_state.last_checkpoint))
else:
trial_executor.stop_trial(trial, stop_logger=False)
trial.config = new_config
trial.experiment_tag = new_tag
trial_executor.start_trial(
trial, Checkpoint.from_object(new_state.last_checkpoint))
self._num_perturbations += 1
# Transfer over the last perturbation time as well
trial_state.last_perturbation_time = new_state.last_perturbation_time | [
"def",
"_exploit",
"(",
"self",
",",
"trial_executor",
",",
"trial",
",",
"trial_to_clone",
")",
":",
"trial_state",
"=",
"self",
".",
"_trial_state",
"[",
"trial",
"]",
"new_state",
"=",
"self",
".",
"_trial_state",
"[",
"trial_to_clone",
"]",
"if",
"not",
"new_state",
".",
"last_checkpoint",
":",
"logger",
".",
"info",
"(",
"\"[pbt]: no checkpoint for trial.\"",
"\" Skip exploit for Trial {}\"",
".",
"format",
"(",
"trial",
")",
")",
"return",
"new_config",
"=",
"explore",
"(",
"trial_to_clone",
".",
"config",
",",
"self",
".",
"_hyperparam_mutations",
",",
"self",
".",
"_resample_probability",
",",
"self",
".",
"_custom_explore_fn",
")",
"logger",
".",
"info",
"(",
"\"[exploit] transferring weights from trial \"",
"\"{} (score {}) -> {} (score {})\"",
".",
"format",
"(",
"trial_to_clone",
",",
"new_state",
".",
"last_score",
",",
"trial",
",",
"trial_state",
".",
"last_score",
")",
")",
"if",
"self",
".",
"_log_config",
":",
"self",
".",
"_log_config_on_step",
"(",
"trial_state",
",",
"new_state",
",",
"trial",
",",
"trial_to_clone",
",",
"new_config",
")",
"new_tag",
"=",
"make_experiment_tag",
"(",
"trial_state",
".",
"orig_tag",
",",
"new_config",
",",
"self",
".",
"_hyperparam_mutations",
")",
"reset_successful",
"=",
"trial_executor",
".",
"reset_trial",
"(",
"trial",
",",
"new_config",
",",
"new_tag",
")",
"if",
"reset_successful",
":",
"trial_executor",
".",
"restore",
"(",
"trial",
",",
"Checkpoint",
".",
"from_object",
"(",
"new_state",
".",
"last_checkpoint",
")",
")",
"else",
":",
"trial_executor",
".",
"stop_trial",
"(",
"trial",
",",
"stop_logger",
"=",
"False",
")",
"trial",
".",
"config",
"=",
"new_config",
"trial",
".",
"experiment_tag",
"=",
"new_tag",
"trial_executor",
".",
"start_trial",
"(",
"trial",
",",
"Checkpoint",
".",
"from_object",
"(",
"new_state",
".",
"last_checkpoint",
")",
")",
"self",
".",
"_num_perturbations",
"+=",
"1",
"# Transfer over the last perturbation time as well",
"trial_state",
".",
"last_perturbation_time",
"=",
"new_state",
".",
"last_perturbation_time"
] | Transfers perturbed state from trial_to_clone -> trial.
If specified, also logs the updated hyperparam state. | [
"Transfers",
"perturbed",
"state",
"from",
"trial_to_clone",
"-",
">",
"trial",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L258-L297 |
24,474 | ray-project/ray | python/ray/tune/schedulers/pbt.py | PopulationBasedTraining._quantiles | def _quantiles(self):
"""Returns trials in the lower and upper `quantile` of the population.
If there is not enough data to compute this, returns empty lists."""
trials = []
for trial, state in self._trial_state.items():
if state.last_score is not None and not trial.is_finished():
trials.append(trial)
trials.sort(key=lambda t: self._trial_state[t].last_score)
if len(trials) <= 1:
return [], []
else:
return (trials[:int(math.ceil(len(trials) * PBT_QUANTILE))],
trials[int(math.floor(-len(trials) * PBT_QUANTILE)):]) | python | def _quantiles(self):
"""Returns trials in the lower and upper `quantile` of the population.
If there is not enough data to compute this, returns empty lists."""
trials = []
for trial, state in self._trial_state.items():
if state.last_score is not None and not trial.is_finished():
trials.append(trial)
trials.sort(key=lambda t: self._trial_state[t].last_score)
if len(trials) <= 1:
return [], []
else:
return (trials[:int(math.ceil(len(trials) * PBT_QUANTILE))],
trials[int(math.floor(-len(trials) * PBT_QUANTILE)):]) | [
"def",
"_quantiles",
"(",
"self",
")",
":",
"trials",
"=",
"[",
"]",
"for",
"trial",
",",
"state",
"in",
"self",
".",
"_trial_state",
".",
"items",
"(",
")",
":",
"if",
"state",
".",
"last_score",
"is",
"not",
"None",
"and",
"not",
"trial",
".",
"is_finished",
"(",
")",
":",
"trials",
".",
"append",
"(",
"trial",
")",
"trials",
".",
"sort",
"(",
"key",
"=",
"lambda",
"t",
":",
"self",
".",
"_trial_state",
"[",
"t",
"]",
".",
"last_score",
")",
"if",
"len",
"(",
"trials",
")",
"<=",
"1",
":",
"return",
"[",
"]",
",",
"[",
"]",
"else",
":",
"return",
"(",
"trials",
"[",
":",
"int",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"trials",
")",
"*",
"PBT_QUANTILE",
")",
")",
"]",
",",
"trials",
"[",
"int",
"(",
"math",
".",
"floor",
"(",
"-",
"len",
"(",
"trials",
")",
"*",
"PBT_QUANTILE",
")",
")",
":",
"]",
")"
] | Returns trials in the lower and upper `quantile` of the population.
If there is not enough data to compute this, returns empty lists. | [
"Returns",
"trials",
"in",
"the",
"lower",
"and",
"upper",
"quantile",
"of",
"the",
"population",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/schedulers/pbt.py#L299-L314 |
24,475 | ray-project/ray | python/ray/rllib/models/fcnet.py | FullyConnectedNetwork._build_layers | def _build_layers(self, inputs, num_outputs, options):
"""Process the flattened inputs.
Note that dict inputs will be flattened into a vector. To define a
model that processes the components separately, use _build_layers_v2().
"""
hiddens = options.get("fcnet_hiddens")
activation = get_activation_fn(options.get("fcnet_activation"))
with tf.name_scope("fc_net"):
i = 1
last_layer = inputs
for size in hiddens:
label = "fc{}".format(i)
last_layer = slim.fully_connected(
last_layer,
size,
weights_initializer=normc_initializer(1.0),
activation_fn=activation,
scope=label)
i += 1
label = "fc_out"
output = slim.fully_connected(
last_layer,
num_outputs,
weights_initializer=normc_initializer(0.01),
activation_fn=None,
scope=label)
return output, last_layer | python | def _build_layers(self, inputs, num_outputs, options):
"""Process the flattened inputs.
Note that dict inputs will be flattened into a vector. To define a
model that processes the components separately, use _build_layers_v2().
"""
hiddens = options.get("fcnet_hiddens")
activation = get_activation_fn(options.get("fcnet_activation"))
with tf.name_scope("fc_net"):
i = 1
last_layer = inputs
for size in hiddens:
label = "fc{}".format(i)
last_layer = slim.fully_connected(
last_layer,
size,
weights_initializer=normc_initializer(1.0),
activation_fn=activation,
scope=label)
i += 1
label = "fc_out"
output = slim.fully_connected(
last_layer,
num_outputs,
weights_initializer=normc_initializer(0.01),
activation_fn=None,
scope=label)
return output, last_layer | [
"def",
"_build_layers",
"(",
"self",
",",
"inputs",
",",
"num_outputs",
",",
"options",
")",
":",
"hiddens",
"=",
"options",
".",
"get",
"(",
"\"fcnet_hiddens\"",
")",
"activation",
"=",
"get_activation_fn",
"(",
"options",
".",
"get",
"(",
"\"fcnet_activation\"",
")",
")",
"with",
"tf",
".",
"name_scope",
"(",
"\"fc_net\"",
")",
":",
"i",
"=",
"1",
"last_layer",
"=",
"inputs",
"for",
"size",
"in",
"hiddens",
":",
"label",
"=",
"\"fc{}\"",
".",
"format",
"(",
"i",
")",
"last_layer",
"=",
"slim",
".",
"fully_connected",
"(",
"last_layer",
",",
"size",
",",
"weights_initializer",
"=",
"normc_initializer",
"(",
"1.0",
")",
",",
"activation_fn",
"=",
"activation",
",",
"scope",
"=",
"label",
")",
"i",
"+=",
"1",
"label",
"=",
"\"fc_out\"",
"output",
"=",
"slim",
".",
"fully_connected",
"(",
"last_layer",
",",
"num_outputs",
",",
"weights_initializer",
"=",
"normc_initializer",
"(",
"0.01",
")",
",",
"activation_fn",
"=",
"None",
",",
"scope",
"=",
"label",
")",
"return",
"output",
",",
"last_layer"
] | Process the flattened inputs.
Note that dict inputs will be flattened into a vector. To define a
model that processes the components separately, use _build_layers_v2(). | [
"Process",
"the",
"flattened",
"inputs",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/fcnet.py#L17-L46 |
24,476 | ray-project/ray | python/ray/rllib/agents/trainer.py | with_base_config | def with_base_config(base_config, extra_config):
"""Returns the given config dict merged with a base agent conf."""
config = copy.deepcopy(base_config)
config.update(extra_config)
return config | python | def with_base_config(base_config, extra_config):
"""Returns the given config dict merged with a base agent conf."""
config = copy.deepcopy(base_config)
config.update(extra_config)
return config | [
"def",
"with_base_config",
"(",
"base_config",
",",
"extra_config",
")",
":",
"config",
"=",
"copy",
".",
"deepcopy",
"(",
"base_config",
")",
"config",
".",
"update",
"(",
"extra_config",
")",
"return",
"config"
] | Returns the given config dict merged with a base agent conf. | [
"Returns",
"the",
"given",
"config",
"dict",
"merged",
"with",
"a",
"base",
"agent",
"conf",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/trainer.py#L241-L246 |
24,477 | ray-project/ray | python/ray/rllib/agents/registry.py | get_agent_class | def get_agent_class(alg):
"""Returns the class of a known agent given its name."""
try:
return _get_agent_class(alg)
except ImportError:
from ray.rllib.agents.mock import _agent_import_failed
return _agent_import_failed(traceback.format_exc()) | python | def get_agent_class(alg):
"""Returns the class of a known agent given its name."""
try:
return _get_agent_class(alg)
except ImportError:
from ray.rllib.agents.mock import _agent_import_failed
return _agent_import_failed(traceback.format_exc()) | [
"def",
"get_agent_class",
"(",
"alg",
")",
":",
"try",
":",
"return",
"_get_agent_class",
"(",
"alg",
")",
"except",
"ImportError",
":",
"from",
"ray",
".",
"rllib",
".",
"agents",
".",
"mock",
"import",
"_agent_import_failed",
"return",
"_agent_import_failed",
"(",
"traceback",
".",
"format_exc",
"(",
")",
")"
] | Returns the class of a known agent given its name. | [
"Returns",
"the",
"class",
"of",
"a",
"known",
"agent",
"given",
"its",
"name",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/registry.py#L112-L119 |
24,478 | ray-project/ray | python/ray/reporter.py | determine_ip_address | def determine_ip_address():
"""Return the first IP address for an ethernet interface on the system."""
addrs = [
x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e"
for x in v if x.family == AddressFamily.AF_INET
]
return addrs[0] | python | def determine_ip_address():
"""Return the first IP address for an ethernet interface on the system."""
addrs = [
x.address for k, v in psutil.net_if_addrs().items() if k[0] == "e"
for x in v if x.family == AddressFamily.AF_INET
]
return addrs[0] | [
"def",
"determine_ip_address",
"(",
")",
":",
"addrs",
"=",
"[",
"x",
".",
"address",
"for",
"k",
",",
"v",
"in",
"psutil",
".",
"net_if_addrs",
"(",
")",
".",
"items",
"(",
")",
"if",
"k",
"[",
"0",
"]",
"==",
"\"e\"",
"for",
"x",
"in",
"v",
"if",
"x",
".",
"family",
"==",
"AddressFamily",
".",
"AF_INET",
"]",
"return",
"addrs",
"[",
"0",
"]"
] | Return the first IP address for an ethernet interface on the system. | [
"Return",
"the",
"first",
"IP",
"address",
"for",
"an",
"ethernet",
"interface",
"on",
"the",
"system",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L61-L67 |
24,479 | ray-project/ray | python/ray/reporter.py | Reporter.run | def run(self):
"""Run the reporter."""
while True:
try:
self.perform_iteration()
except Exception:
traceback.print_exc()
pass
time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000) | python | def run(self):
"""Run the reporter."""
while True:
try:
self.perform_iteration()
except Exception:
traceback.print_exc()
pass
time.sleep(ray_constants.REPORTER_UPDATE_INTERVAL_MS / 1000) | [
"def",
"run",
"(",
"self",
")",
":",
"while",
"True",
":",
"try",
":",
"self",
".",
"perform_iteration",
"(",
")",
"except",
"Exception",
":",
"traceback",
".",
"print_exc",
"(",
")",
"pass",
"time",
".",
"sleep",
"(",
"ray_constants",
".",
"REPORTER_UPDATE_INTERVAL_MS",
"/",
"1000",
")"
] | Run the reporter. | [
"Run",
"the",
"reporter",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/reporter.py#L172-L181 |
24,480 | ray-project/ray | python/ray/serialization.py | check_serializable | def check_serializable(cls):
"""Throws an exception if Ray cannot serialize this class efficiently.
Args:
cls (type): The class to be serialized.
Raises:
Exception: An exception is raised if Ray cannot serialize this class
efficiently.
"""
if is_named_tuple(cls):
# This case works.
return
if not hasattr(cls, "__new__"):
print("The class {} does not have a '__new__' attribute and is "
"probably an old-stye class. Please make it a new-style class "
"by inheriting from 'object'.")
raise RayNotDictionarySerializable("The class {} does not have a "
"'__new__' attribute and is "
"probably an old-style class. We "
"do not support this. Please make "
"it a new-style class by "
"inheriting from 'object'."
.format(cls))
try:
obj = cls.__new__(cls)
except Exception:
raise RayNotDictionarySerializable("The class {} has overridden "
"'__new__', so Ray may not be able "
"to serialize it efficiently."
.format(cls))
if not hasattr(obj, "__dict__"):
raise RayNotDictionarySerializable("Objects of the class {} do not "
"have a '__dict__' attribute, so "
"Ray cannot serialize it "
"efficiently.".format(cls))
if hasattr(obj, "__slots__"):
raise RayNotDictionarySerializable("The class {} uses '__slots__', so "
"Ray may not be able to serialize "
"it efficiently.".format(cls)) | python | def check_serializable(cls):
"""Throws an exception if Ray cannot serialize this class efficiently.
Args:
cls (type): The class to be serialized.
Raises:
Exception: An exception is raised if Ray cannot serialize this class
efficiently.
"""
if is_named_tuple(cls):
# This case works.
return
if not hasattr(cls, "__new__"):
print("The class {} does not have a '__new__' attribute and is "
"probably an old-stye class. Please make it a new-style class "
"by inheriting from 'object'.")
raise RayNotDictionarySerializable("The class {} does not have a "
"'__new__' attribute and is "
"probably an old-style class. We "
"do not support this. Please make "
"it a new-style class by "
"inheriting from 'object'."
.format(cls))
try:
obj = cls.__new__(cls)
except Exception:
raise RayNotDictionarySerializable("The class {} has overridden "
"'__new__', so Ray may not be able "
"to serialize it efficiently."
.format(cls))
if not hasattr(obj, "__dict__"):
raise RayNotDictionarySerializable("Objects of the class {} do not "
"have a '__dict__' attribute, so "
"Ray cannot serialize it "
"efficiently.".format(cls))
if hasattr(obj, "__slots__"):
raise RayNotDictionarySerializable("The class {} uses '__slots__', so "
"Ray may not be able to serialize "
"it efficiently.".format(cls)) | [
"def",
"check_serializable",
"(",
"cls",
")",
":",
"if",
"is_named_tuple",
"(",
"cls",
")",
":",
"# This case works.",
"return",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"\"__new__\"",
")",
":",
"print",
"(",
"\"The class {} does not have a '__new__' attribute and is \"",
"\"probably an old-stye class. Please make it a new-style class \"",
"\"by inheriting from 'object'.\"",
")",
"raise",
"RayNotDictionarySerializable",
"(",
"\"The class {} does not have a \"",
"\"'__new__' attribute and is \"",
"\"probably an old-style class. We \"",
"\"do not support this. Please make \"",
"\"it a new-style class by \"",
"\"inheriting from 'object'.\"",
".",
"format",
"(",
"cls",
")",
")",
"try",
":",
"obj",
"=",
"cls",
".",
"__new__",
"(",
"cls",
")",
"except",
"Exception",
":",
"raise",
"RayNotDictionarySerializable",
"(",
"\"The class {} has overridden \"",
"\"'__new__', so Ray may not be able \"",
"\"to serialize it efficiently.\"",
".",
"format",
"(",
"cls",
")",
")",
"if",
"not",
"hasattr",
"(",
"obj",
",",
"\"__dict__\"",
")",
":",
"raise",
"RayNotDictionarySerializable",
"(",
"\"Objects of the class {} do not \"",
"\"have a '__dict__' attribute, so \"",
"\"Ray cannot serialize it \"",
"\"efficiently.\"",
".",
"format",
"(",
"cls",
")",
")",
"if",
"hasattr",
"(",
"obj",
",",
"\"__slots__\"",
")",
":",
"raise",
"RayNotDictionarySerializable",
"(",
"\"The class {} uses '__slots__', so \"",
"\"Ray may not be able to serialize \"",
"\"it efficiently.\"",
".",
"format",
"(",
"cls",
")",
")"
] | Throws an exception if Ray cannot serialize this class efficiently.
Args:
cls (type): The class to be serialized.
Raises:
Exception: An exception is raised if Ray cannot serialize this class
efficiently. | [
"Throws",
"an",
"exception",
"if",
"Ray",
"cannot",
"serialize",
"this",
"class",
"efficiently",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/serialization.py#L16-L55 |
24,481 | ray-project/ray | python/ray/serialization.py | is_named_tuple | def is_named_tuple(cls):
"""Return True if cls is a namedtuple and False otherwise."""
b = cls.__bases__
if len(b) != 1 or b[0] != tuple:
return False
f = getattr(cls, "_fields", None)
if not isinstance(f, tuple):
return False
return all(type(n) == str for n in f) | python | def is_named_tuple(cls):
"""Return True if cls is a namedtuple and False otherwise."""
b = cls.__bases__
if len(b) != 1 or b[0] != tuple:
return False
f = getattr(cls, "_fields", None)
if not isinstance(f, tuple):
return False
return all(type(n) == str for n in f) | [
"def",
"is_named_tuple",
"(",
"cls",
")",
":",
"b",
"=",
"cls",
".",
"__bases__",
"if",
"len",
"(",
"b",
")",
"!=",
"1",
"or",
"b",
"[",
"0",
"]",
"!=",
"tuple",
":",
"return",
"False",
"f",
"=",
"getattr",
"(",
"cls",
",",
"\"_fields\"",
",",
"None",
")",
"if",
"not",
"isinstance",
"(",
"f",
",",
"tuple",
")",
":",
"return",
"False",
"return",
"all",
"(",
"type",
"(",
"n",
")",
"==",
"str",
"for",
"n",
"in",
"f",
")"
] | Return True if cls is a namedtuple and False otherwise. | [
"Return",
"True",
"if",
"cls",
"is",
"a",
"namedtuple",
"and",
"False",
"otherwise",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/serialization.py#L58-L66 |
24,482 | ray-project/ray | python/ray/tune/registry.py | register_trainable | def register_trainable(name, trainable):
"""Register a trainable function or class.
Args:
name (str): Name to register.
trainable (obj): Function or tune.Trainable class. Functions must
take (config, status_reporter) as arguments and will be
automatically converted into a class during registration.
"""
from ray.tune.trainable import Trainable
from ray.tune.function_runner import wrap_function
if isinstance(trainable, type):
logger.debug("Detected class for trainable.")
elif isinstance(trainable, FunctionType):
logger.debug("Detected function for trainable.")
trainable = wrap_function(trainable)
elif callable(trainable):
logger.warning(
"Detected unknown callable for trainable. Converting to class.")
trainable = wrap_function(trainable)
if not issubclass(trainable, Trainable):
raise TypeError("Second argument must be convertable to Trainable",
trainable)
_global_registry.register(TRAINABLE_CLASS, name, trainable) | python | def register_trainable(name, trainable):
"""Register a trainable function or class.
Args:
name (str): Name to register.
trainable (obj): Function or tune.Trainable class. Functions must
take (config, status_reporter) as arguments and will be
automatically converted into a class during registration.
"""
from ray.tune.trainable import Trainable
from ray.tune.function_runner import wrap_function
if isinstance(trainable, type):
logger.debug("Detected class for trainable.")
elif isinstance(trainable, FunctionType):
logger.debug("Detected function for trainable.")
trainable = wrap_function(trainable)
elif callable(trainable):
logger.warning(
"Detected unknown callable for trainable. Converting to class.")
trainable = wrap_function(trainable)
if not issubclass(trainable, Trainable):
raise TypeError("Second argument must be convertable to Trainable",
trainable)
_global_registry.register(TRAINABLE_CLASS, name, trainable) | [
"def",
"register_trainable",
"(",
"name",
",",
"trainable",
")",
":",
"from",
"ray",
".",
"tune",
".",
"trainable",
"import",
"Trainable",
"from",
"ray",
".",
"tune",
".",
"function_runner",
"import",
"wrap_function",
"if",
"isinstance",
"(",
"trainable",
",",
"type",
")",
":",
"logger",
".",
"debug",
"(",
"\"Detected class for trainable.\"",
")",
"elif",
"isinstance",
"(",
"trainable",
",",
"FunctionType",
")",
":",
"logger",
".",
"debug",
"(",
"\"Detected function for trainable.\"",
")",
"trainable",
"=",
"wrap_function",
"(",
"trainable",
")",
"elif",
"callable",
"(",
"trainable",
")",
":",
"logger",
".",
"warning",
"(",
"\"Detected unknown callable for trainable. Converting to class.\"",
")",
"trainable",
"=",
"wrap_function",
"(",
"trainable",
")",
"if",
"not",
"issubclass",
"(",
"trainable",
",",
"Trainable",
")",
":",
"raise",
"TypeError",
"(",
"\"Second argument must be convertable to Trainable\"",
",",
"trainable",
")",
"_global_registry",
".",
"register",
"(",
"TRAINABLE_CLASS",
",",
"name",
",",
"trainable",
")"
] | Register a trainable function or class.
Args:
name (str): Name to register.
trainable (obj): Function or tune.Trainable class. Functions must
take (config, status_reporter) as arguments and will be
automatically converted into a class during registration. | [
"Register",
"a",
"trainable",
"function",
"or",
"class",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/registry.py#L24-L50 |
24,483 | ray-project/ray | python/ray/tune/registry.py | register_env | def register_env(name, env_creator):
"""Register a custom environment for use with RLlib.
Args:
name (str): Name to register.
env_creator (obj): Function that creates an env.
"""
if not isinstance(env_creator, FunctionType):
raise TypeError("Second argument must be a function.", env_creator)
_global_registry.register(ENV_CREATOR, name, env_creator) | python | def register_env(name, env_creator):
"""Register a custom environment for use with RLlib.
Args:
name (str): Name to register.
env_creator (obj): Function that creates an env.
"""
if not isinstance(env_creator, FunctionType):
raise TypeError("Second argument must be a function.", env_creator)
_global_registry.register(ENV_CREATOR, name, env_creator) | [
"def",
"register_env",
"(",
"name",
",",
"env_creator",
")",
":",
"if",
"not",
"isinstance",
"(",
"env_creator",
",",
"FunctionType",
")",
":",
"raise",
"TypeError",
"(",
"\"Second argument must be a function.\"",
",",
"env_creator",
")",
"_global_registry",
".",
"register",
"(",
"ENV_CREATOR",
",",
"name",
",",
"env_creator",
")"
] | Register a custom environment for use with RLlib.
Args:
name (str): Name to register.
env_creator (obj): Function that creates an env. | [
"Register",
"a",
"custom",
"environment",
"for",
"use",
"with",
"RLlib",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/registry.py#L53-L63 |
24,484 | ray-project/ray | python/ray/rllib/evaluation/metrics.py | get_learner_stats | def get_learner_stats(grad_info):
"""Return optimization stats reported from the policy graph.
Example:
>>> grad_info = evaluator.learn_on_batch(samples)
>>> print(get_stats(grad_info))
{"vf_loss": ..., "policy_loss": ...}
"""
if LEARNER_STATS_KEY in grad_info:
return grad_info[LEARNER_STATS_KEY]
multiagent_stats = {}
for k, v in grad_info.items():
if type(v) is dict:
if LEARNER_STATS_KEY in v:
multiagent_stats[k] = v[LEARNER_STATS_KEY]
return multiagent_stats | python | def get_learner_stats(grad_info):
"""Return optimization stats reported from the policy graph.
Example:
>>> grad_info = evaluator.learn_on_batch(samples)
>>> print(get_stats(grad_info))
{"vf_loss": ..., "policy_loss": ...}
"""
if LEARNER_STATS_KEY in grad_info:
return grad_info[LEARNER_STATS_KEY]
multiagent_stats = {}
for k, v in grad_info.items():
if type(v) is dict:
if LEARNER_STATS_KEY in v:
multiagent_stats[k] = v[LEARNER_STATS_KEY]
return multiagent_stats | [
"def",
"get_learner_stats",
"(",
"grad_info",
")",
":",
"if",
"LEARNER_STATS_KEY",
"in",
"grad_info",
":",
"return",
"grad_info",
"[",
"LEARNER_STATS_KEY",
"]",
"multiagent_stats",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"grad_info",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"v",
")",
"is",
"dict",
":",
"if",
"LEARNER_STATS_KEY",
"in",
"v",
":",
"multiagent_stats",
"[",
"k",
"]",
"=",
"v",
"[",
"LEARNER_STATS_KEY",
"]",
"return",
"multiagent_stats"
] | Return optimization stats reported from the policy graph.
Example:
>>> grad_info = evaluator.learn_on_batch(samples)
>>> print(get_stats(grad_info))
{"vf_loss": ..., "policy_loss": ...} | [
"Return",
"optimization",
"stats",
"reported",
"from",
"the",
"policy",
"graph",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L23-L41 |
24,485 | ray-project/ray | python/ray/rllib/evaluation/metrics.py | collect_metrics | def collect_metrics(local_evaluator=None,
remote_evaluators=[],
timeout_seconds=180):
"""Gathers episode metrics from PolicyEvaluator instances."""
episodes, num_dropped = collect_episodes(
local_evaluator, remote_evaluators, timeout_seconds=timeout_seconds)
metrics = summarize_episodes(episodes, episodes, num_dropped)
return metrics | python | def collect_metrics(local_evaluator=None,
remote_evaluators=[],
timeout_seconds=180):
"""Gathers episode metrics from PolicyEvaluator instances."""
episodes, num_dropped = collect_episodes(
local_evaluator, remote_evaluators, timeout_seconds=timeout_seconds)
metrics = summarize_episodes(episodes, episodes, num_dropped)
return metrics | [
"def",
"collect_metrics",
"(",
"local_evaluator",
"=",
"None",
",",
"remote_evaluators",
"=",
"[",
"]",
",",
"timeout_seconds",
"=",
"180",
")",
":",
"episodes",
",",
"num_dropped",
"=",
"collect_episodes",
"(",
"local_evaluator",
",",
"remote_evaluators",
",",
"timeout_seconds",
"=",
"timeout_seconds",
")",
"metrics",
"=",
"summarize_episodes",
"(",
"episodes",
",",
"episodes",
",",
"num_dropped",
")",
"return",
"metrics"
] | Gathers episode metrics from PolicyEvaluator instances. | [
"Gathers",
"episode",
"metrics",
"from",
"PolicyEvaluator",
"instances",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L45-L53 |
24,486 | ray-project/ray | python/ray/rllib/evaluation/metrics.py | collect_episodes | def collect_episodes(local_evaluator=None,
remote_evaluators=[],
timeout_seconds=180):
"""Gathers new episodes metrics tuples from the given evaluators."""
pending = [
a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators
]
collected, _ = ray.wait(
pending, num_returns=len(pending), timeout=timeout_seconds * 1.0)
num_metric_batches_dropped = len(pending) - len(collected)
if pending and len(collected) == 0:
raise ValueError(
"Timed out waiting for metrics from workers. You can configure "
"this timeout with `collect_metrics_timeout`.")
metric_lists = ray_get_and_free(collected)
if local_evaluator:
metric_lists.append(local_evaluator.get_metrics())
episodes = []
for metrics in metric_lists:
episodes.extend(metrics)
return episodes, num_metric_batches_dropped | python | def collect_episodes(local_evaluator=None,
remote_evaluators=[],
timeout_seconds=180):
"""Gathers new episodes metrics tuples from the given evaluators."""
pending = [
a.apply.remote(lambda ev: ev.get_metrics()) for a in remote_evaluators
]
collected, _ = ray.wait(
pending, num_returns=len(pending), timeout=timeout_seconds * 1.0)
num_metric_batches_dropped = len(pending) - len(collected)
if pending and len(collected) == 0:
raise ValueError(
"Timed out waiting for metrics from workers. You can configure "
"this timeout with `collect_metrics_timeout`.")
metric_lists = ray_get_and_free(collected)
if local_evaluator:
metric_lists.append(local_evaluator.get_metrics())
episodes = []
for metrics in metric_lists:
episodes.extend(metrics)
return episodes, num_metric_batches_dropped | [
"def",
"collect_episodes",
"(",
"local_evaluator",
"=",
"None",
",",
"remote_evaluators",
"=",
"[",
"]",
",",
"timeout_seconds",
"=",
"180",
")",
":",
"pending",
"=",
"[",
"a",
".",
"apply",
".",
"remote",
"(",
"lambda",
"ev",
":",
"ev",
".",
"get_metrics",
"(",
")",
")",
"for",
"a",
"in",
"remote_evaluators",
"]",
"collected",
",",
"_",
"=",
"ray",
".",
"wait",
"(",
"pending",
",",
"num_returns",
"=",
"len",
"(",
"pending",
")",
",",
"timeout",
"=",
"timeout_seconds",
"*",
"1.0",
")",
"num_metric_batches_dropped",
"=",
"len",
"(",
"pending",
")",
"-",
"len",
"(",
"collected",
")",
"if",
"pending",
"and",
"len",
"(",
"collected",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"\"Timed out waiting for metrics from workers. You can configure \"",
"\"this timeout with `collect_metrics_timeout`.\"",
")",
"metric_lists",
"=",
"ray_get_and_free",
"(",
"collected",
")",
"if",
"local_evaluator",
":",
"metric_lists",
".",
"append",
"(",
"local_evaluator",
".",
"get_metrics",
"(",
")",
")",
"episodes",
"=",
"[",
"]",
"for",
"metrics",
"in",
"metric_lists",
":",
"episodes",
".",
"extend",
"(",
"metrics",
")",
"return",
"episodes",
",",
"num_metric_batches_dropped"
] | Gathers new episodes metrics tuples from the given evaluators. | [
"Gathers",
"new",
"episodes",
"metrics",
"tuples",
"from",
"the",
"given",
"evaluators",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L57-L79 |
24,487 | ray-project/ray | python/ray/rllib/evaluation/metrics.py | _partition | def _partition(episodes):
"""Divides metrics data into true rollouts vs off-policy estimates."""
from ray.rllib.evaluation.sampler import RolloutMetrics
rollouts, estimates = [], []
for e in episodes:
if isinstance(e, RolloutMetrics):
rollouts.append(e)
elif isinstance(e, OffPolicyEstimate):
estimates.append(e)
else:
raise ValueError("Unknown metric type: {}".format(e))
return rollouts, estimates | python | def _partition(episodes):
"""Divides metrics data into true rollouts vs off-policy estimates."""
from ray.rllib.evaluation.sampler import RolloutMetrics
rollouts, estimates = [], []
for e in episodes:
if isinstance(e, RolloutMetrics):
rollouts.append(e)
elif isinstance(e, OffPolicyEstimate):
estimates.append(e)
else:
raise ValueError("Unknown metric type: {}".format(e))
return rollouts, estimates | [
"def",
"_partition",
"(",
"episodes",
")",
":",
"from",
"ray",
".",
"rllib",
".",
"evaluation",
".",
"sampler",
"import",
"RolloutMetrics",
"rollouts",
",",
"estimates",
"=",
"[",
"]",
",",
"[",
"]",
"for",
"e",
"in",
"episodes",
":",
"if",
"isinstance",
"(",
"e",
",",
"RolloutMetrics",
")",
":",
"rollouts",
".",
"append",
"(",
"e",
")",
"elif",
"isinstance",
"(",
"e",
",",
"OffPolicyEstimate",
")",
":",
"estimates",
".",
"append",
"(",
"e",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Unknown metric type: {}\"",
".",
"format",
"(",
"e",
")",
")",
"return",
"rollouts",
",",
"estimates"
] | Divides metrics data into true rollouts vs off-policy estimates. | [
"Divides",
"metrics",
"data",
"into",
"true",
"rollouts",
"vs",
"off",
"-",
"policy",
"estimates",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/metrics.py#L163-L176 |
24,488 | ray-project/ray | python/ray/tune/trial_executor.py | TrialExecutor.set_status | def set_status(self, trial, status):
"""Sets status and checkpoints metadata if needed.
Only checkpoints metadata if trial status is a terminal condition.
PENDING, PAUSED, and RUNNING switches have checkpoints taken care of
in the TrialRunner.
Args:
trial (Trial): Trial to checkpoint.
status (Trial.status): Status to set trial to.
"""
trial.status = status
if status in [Trial.TERMINATED, Trial.ERROR]:
self.try_checkpoint_metadata(trial) | python | def set_status(self, trial, status):
"""Sets status and checkpoints metadata if needed.
Only checkpoints metadata if trial status is a terminal condition.
PENDING, PAUSED, and RUNNING switches have checkpoints taken care of
in the TrialRunner.
Args:
trial (Trial): Trial to checkpoint.
status (Trial.status): Status to set trial to.
"""
trial.status = status
if status in [Trial.TERMINATED, Trial.ERROR]:
self.try_checkpoint_metadata(trial) | [
"def",
"set_status",
"(",
"self",
",",
"trial",
",",
"status",
")",
":",
"trial",
".",
"status",
"=",
"status",
"if",
"status",
"in",
"[",
"Trial",
".",
"TERMINATED",
",",
"Trial",
".",
"ERROR",
"]",
":",
"self",
".",
"try_checkpoint_metadata",
"(",
"trial",
")"
] | Sets status and checkpoints metadata if needed.
Only checkpoints metadata if trial status is a terminal condition.
PENDING, PAUSED, and RUNNING switches have checkpoints taken care of
in the TrialRunner.
Args:
trial (Trial): Trial to checkpoint.
status (Trial.status): Status to set trial to. | [
"Sets",
"status",
"and",
"checkpoints",
"metadata",
"if",
"needed",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L30-L43 |
24,489 | ray-project/ray | python/ray/tune/trial_executor.py | TrialExecutor.try_checkpoint_metadata | def try_checkpoint_metadata(self, trial):
"""Checkpoints metadata.
Args:
trial (Trial): Trial to checkpoint.
"""
if trial._checkpoint.storage == Checkpoint.MEMORY:
logger.debug("Not saving data for trial w/ memory checkpoint.")
return
try:
logger.debug("Saving trial metadata.")
self._cached_trial_state[trial.trial_id] = trial.__getstate__()
except Exception:
logger.exception("Error checkpointing trial metadata.") | python | def try_checkpoint_metadata(self, trial):
"""Checkpoints metadata.
Args:
trial (Trial): Trial to checkpoint.
"""
if trial._checkpoint.storage == Checkpoint.MEMORY:
logger.debug("Not saving data for trial w/ memory checkpoint.")
return
try:
logger.debug("Saving trial metadata.")
self._cached_trial_state[trial.trial_id] = trial.__getstate__()
except Exception:
logger.exception("Error checkpointing trial metadata.") | [
"def",
"try_checkpoint_metadata",
"(",
"self",
",",
"trial",
")",
":",
"if",
"trial",
".",
"_checkpoint",
".",
"storage",
"==",
"Checkpoint",
".",
"MEMORY",
":",
"logger",
".",
"debug",
"(",
"\"Not saving data for trial w/ memory checkpoint.\"",
")",
"return",
"try",
":",
"logger",
".",
"debug",
"(",
"\"Saving trial metadata.\"",
")",
"self",
".",
"_cached_trial_state",
"[",
"trial",
".",
"trial_id",
"]",
"=",
"trial",
".",
"__getstate__",
"(",
")",
"except",
"Exception",
":",
"logger",
".",
"exception",
"(",
"\"Error checkpointing trial metadata.\"",
")"
] | Checkpoints metadata.
Args:
trial (Trial): Trial to checkpoint. | [
"Checkpoints",
"metadata",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L45-L58 |
24,490 | ray-project/ray | python/ray/tune/trial_executor.py | TrialExecutor.unpause_trial | def unpause_trial(self, trial):
"""Sets PAUSED trial to pending to allow scheduler to start."""
assert trial.status == Trial.PAUSED, trial.status
self.set_status(trial, Trial.PENDING) | python | def unpause_trial(self, trial):
"""Sets PAUSED trial to pending to allow scheduler to start."""
assert trial.status == Trial.PAUSED, trial.status
self.set_status(trial, Trial.PENDING) | [
"def",
"unpause_trial",
"(",
"self",
",",
"trial",
")",
":",
"assert",
"trial",
".",
"status",
"==",
"Trial",
".",
"PAUSED",
",",
"trial",
".",
"status",
"self",
".",
"set_status",
"(",
"trial",
",",
"Trial",
".",
"PENDING",
")"
] | Sets PAUSED trial to pending to allow scheduler to start. | [
"Sets",
"PAUSED",
"trial",
"to",
"pending",
"to",
"allow",
"scheduler",
"to",
"start",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L114-L117 |
24,491 | ray-project/ray | python/ray/tune/trial_executor.py | TrialExecutor.resume_trial | def resume_trial(self, trial):
"""Resumes PAUSED trials. This is a blocking call."""
assert trial.status == Trial.PAUSED, trial.status
self.start_trial(trial) | python | def resume_trial(self, trial):
"""Resumes PAUSED trials. This is a blocking call."""
assert trial.status == Trial.PAUSED, trial.status
self.start_trial(trial) | [
"def",
"resume_trial",
"(",
"self",
",",
"trial",
")",
":",
"assert",
"trial",
".",
"status",
"==",
"Trial",
".",
"PAUSED",
",",
"trial",
".",
"status",
"self",
".",
"start_trial",
"(",
"trial",
")"
] | Resumes PAUSED trials. This is a blocking call. | [
"Resumes",
"PAUSED",
"trials",
".",
"This",
"is",
"a",
"blocking",
"call",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trial_executor.py#L119-L123 |
24,492 | ray-project/ray | python/ray/tune/suggest/nevergrad.py | NevergradSearch.on_trial_complete | def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to Nevergrad unless early terminated or errored.
The result is internally negated when interacting with Nevergrad
so that Nevergrad Optimizers can "maximize" this value,
as it minimizes on default.
"""
ng_trial_info = self._live_trial_mapping.pop(trial_id)
if result:
self._nevergrad_opt.tell(ng_trial_info, -result[self._reward_attr]) | python | def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to Nevergrad unless early terminated or errored.
The result is internally negated when interacting with Nevergrad
so that Nevergrad Optimizers can "maximize" this value,
as it minimizes on default.
"""
ng_trial_info = self._live_trial_mapping.pop(trial_id)
if result:
self._nevergrad_opt.tell(ng_trial_info, -result[self._reward_attr]) | [
"def",
"on_trial_complete",
"(",
"self",
",",
"trial_id",
",",
"result",
"=",
"None",
",",
"error",
"=",
"False",
",",
"early_terminated",
"=",
"False",
")",
":",
"ng_trial_info",
"=",
"self",
".",
"_live_trial_mapping",
".",
"pop",
"(",
"trial_id",
")",
"if",
"result",
":",
"self",
".",
"_nevergrad_opt",
".",
"tell",
"(",
"ng_trial_info",
",",
"-",
"result",
"[",
"self",
".",
"_reward_attr",
"]",
")"
] | Passes the result to Nevergrad unless early terminated or errored.
The result is internally negated when interacting with Nevergrad
so that Nevergrad Optimizers can "maximize" this value,
as it minimizes on default. | [
"Passes",
"the",
"result",
"to",
"Nevergrad",
"unless",
"early",
"terminated",
"or",
"errored",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/nevergrad.py#L109-L122 |
24,493 | ray-project/ray | python/ray/import_thread.py | ImportThread.start | def start(self):
"""Start the import thread."""
self.t = threading.Thread(target=self._run, name="ray_import_thread")
# Making the thread a daemon causes it to exit
# when the main thread exits.
self.t.daemon = True
self.t.start() | python | def start(self):
"""Start the import thread."""
self.t = threading.Thread(target=self._run, name="ray_import_thread")
# Making the thread a daemon causes it to exit
# when the main thread exits.
self.t.daemon = True
self.t.start() | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"t",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"self",
".",
"_run",
",",
"name",
"=",
"\"ray_import_thread\"",
")",
"# Making the thread a daemon causes it to exit",
"# when the main thread exits.",
"self",
".",
"t",
".",
"daemon",
"=",
"True",
"self",
".",
"t",
".",
"start",
"(",
")"
] | Start the import thread. | [
"Start",
"the",
"import",
"thread",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/import_thread.py#L36-L42 |
24,494 | ray-project/ray | python/ray/import_thread.py | ImportThread._process_key | def _process_key(self, key):
"""Process the given export key from redis."""
# Handle the driver case first.
if self.mode != ray.WORKER_MODE:
if key.startswith(b"FunctionsToRun"):
with profiling.profile("fetch_and_run_function"):
self.fetch_and_execute_function_to_run(key)
# Return because FunctionsToRun are the only things that
# the driver should import.
return
if key.startswith(b"RemoteFunction"):
with profiling.profile("register_remote_function"):
(self.worker.function_actor_manager.
fetch_and_register_remote_function(key))
elif key.startswith(b"FunctionsToRun"):
with profiling.profile("fetch_and_run_function"):
self.fetch_and_execute_function_to_run(key)
elif key.startswith(b"ActorClass"):
# Keep track of the fact that this actor class has been
# exported so that we know it is safe to turn this worker
# into an actor of that class.
self.worker.function_actor_manager.imported_actor_classes.add(key)
# TODO(rkn): We may need to bring back the case of
# fetching actor classes here.
else:
raise Exception("This code should be unreachable.") | python | def _process_key(self, key):
"""Process the given export key from redis."""
# Handle the driver case first.
if self.mode != ray.WORKER_MODE:
if key.startswith(b"FunctionsToRun"):
with profiling.profile("fetch_and_run_function"):
self.fetch_and_execute_function_to_run(key)
# Return because FunctionsToRun are the only things that
# the driver should import.
return
if key.startswith(b"RemoteFunction"):
with profiling.profile("register_remote_function"):
(self.worker.function_actor_manager.
fetch_and_register_remote_function(key))
elif key.startswith(b"FunctionsToRun"):
with profiling.profile("fetch_and_run_function"):
self.fetch_and_execute_function_to_run(key)
elif key.startswith(b"ActorClass"):
# Keep track of the fact that this actor class has been
# exported so that we know it is safe to turn this worker
# into an actor of that class.
self.worker.function_actor_manager.imported_actor_classes.add(key)
# TODO(rkn): We may need to bring back the case of
# fetching actor classes here.
else:
raise Exception("This code should be unreachable.") | [
"def",
"_process_key",
"(",
"self",
",",
"key",
")",
":",
"# Handle the driver case first.",
"if",
"self",
".",
"mode",
"!=",
"ray",
".",
"WORKER_MODE",
":",
"if",
"key",
".",
"startswith",
"(",
"b\"FunctionsToRun\"",
")",
":",
"with",
"profiling",
".",
"profile",
"(",
"\"fetch_and_run_function\"",
")",
":",
"self",
".",
"fetch_and_execute_function_to_run",
"(",
"key",
")",
"# Return because FunctionsToRun are the only things that",
"# the driver should import.",
"return",
"if",
"key",
".",
"startswith",
"(",
"b\"RemoteFunction\"",
")",
":",
"with",
"profiling",
".",
"profile",
"(",
"\"register_remote_function\"",
")",
":",
"(",
"self",
".",
"worker",
".",
"function_actor_manager",
".",
"fetch_and_register_remote_function",
"(",
"key",
")",
")",
"elif",
"key",
".",
"startswith",
"(",
"b\"FunctionsToRun\"",
")",
":",
"with",
"profiling",
".",
"profile",
"(",
"\"fetch_and_run_function\"",
")",
":",
"self",
".",
"fetch_and_execute_function_to_run",
"(",
"key",
")",
"elif",
"key",
".",
"startswith",
"(",
"b\"ActorClass\"",
")",
":",
"# Keep track of the fact that this actor class has been",
"# exported so that we know it is safe to turn this worker",
"# into an actor of that class.",
"self",
".",
"worker",
".",
"function_actor_manager",
".",
"imported_actor_classes",
".",
"add",
"(",
"key",
")",
"# TODO(rkn): We may need to bring back the case of",
"# fetching actor classes here.",
"else",
":",
"raise",
"Exception",
"(",
"\"This code should be unreachable.\"",
")"
] | Process the given export key from redis. | [
"Process",
"the",
"given",
"export",
"key",
"from",
"redis",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/import_thread.py#L87-L113 |
24,495 | ray-project/ray | python/ray/import_thread.py | ImportThread.fetch_and_execute_function_to_run | def fetch_and_execute_function_to_run(self, key):
"""Run on arbitrary function on the worker."""
(driver_id, serialized_function,
run_on_other_drivers) = self.redis_client.hmget(
key, ["driver_id", "function", "run_on_other_drivers"])
if (utils.decode(run_on_other_drivers) == "False"
and self.worker.mode == ray.SCRIPT_MODE
and driver_id != self.worker.task_driver_id.binary()):
return
try:
# Deserialize the function.
function = pickle.loads(serialized_function)
# Run the function.
function({"worker": self.worker})
except Exception:
# If an exception was thrown when the function was run, we record
# the traceback and notify the scheduler of the failure.
traceback_str = traceback.format_exc()
# Log the error message.
utils.push_error_to_driver(
self.worker,
ray_constants.FUNCTION_TO_RUN_PUSH_ERROR,
traceback_str,
driver_id=ray.DriverID(driver_id)) | python | def fetch_and_execute_function_to_run(self, key):
"""Run on arbitrary function on the worker."""
(driver_id, serialized_function,
run_on_other_drivers) = self.redis_client.hmget(
key, ["driver_id", "function", "run_on_other_drivers"])
if (utils.decode(run_on_other_drivers) == "False"
and self.worker.mode == ray.SCRIPT_MODE
and driver_id != self.worker.task_driver_id.binary()):
return
try:
# Deserialize the function.
function = pickle.loads(serialized_function)
# Run the function.
function({"worker": self.worker})
except Exception:
# If an exception was thrown when the function was run, we record
# the traceback and notify the scheduler of the failure.
traceback_str = traceback.format_exc()
# Log the error message.
utils.push_error_to_driver(
self.worker,
ray_constants.FUNCTION_TO_RUN_PUSH_ERROR,
traceback_str,
driver_id=ray.DriverID(driver_id)) | [
"def",
"fetch_and_execute_function_to_run",
"(",
"self",
",",
"key",
")",
":",
"(",
"driver_id",
",",
"serialized_function",
",",
"run_on_other_drivers",
")",
"=",
"self",
".",
"redis_client",
".",
"hmget",
"(",
"key",
",",
"[",
"\"driver_id\"",
",",
"\"function\"",
",",
"\"run_on_other_drivers\"",
"]",
")",
"if",
"(",
"utils",
".",
"decode",
"(",
"run_on_other_drivers",
")",
"==",
"\"False\"",
"and",
"self",
".",
"worker",
".",
"mode",
"==",
"ray",
".",
"SCRIPT_MODE",
"and",
"driver_id",
"!=",
"self",
".",
"worker",
".",
"task_driver_id",
".",
"binary",
"(",
")",
")",
":",
"return",
"try",
":",
"# Deserialize the function.",
"function",
"=",
"pickle",
".",
"loads",
"(",
"serialized_function",
")",
"# Run the function.",
"function",
"(",
"{",
"\"worker\"",
":",
"self",
".",
"worker",
"}",
")",
"except",
"Exception",
":",
"# If an exception was thrown when the function was run, we record",
"# the traceback and notify the scheduler of the failure.",
"traceback_str",
"=",
"traceback",
".",
"format_exc",
"(",
")",
"# Log the error message.",
"utils",
".",
"push_error_to_driver",
"(",
"self",
".",
"worker",
",",
"ray_constants",
".",
"FUNCTION_TO_RUN_PUSH_ERROR",
",",
"traceback_str",
",",
"driver_id",
"=",
"ray",
".",
"DriverID",
"(",
"driver_id",
")",
")"
] | Run on arbitrary function on the worker. | [
"Run",
"on",
"arbitrary",
"function",
"on",
"the",
"worker",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/import_thread.py#L115-L140 |
24,496 | ray-project/ray | python/ray/rllib/evaluation/policy_graph.py | clip_action | def clip_action(action, space):
"""Called to clip actions to the specified range of this policy.
Arguments:
action: Single action.
space: Action space the actions should be present in.
Returns:
Clipped batch of actions.
"""
if isinstance(space, gym.spaces.Box):
return np.clip(action, space.low, space.high)
elif isinstance(space, gym.spaces.Tuple):
if type(action) not in (tuple, list):
raise ValueError("Expected tuple space for actions {}: {}".format(
action, space))
out = []
for a, s in zip(action, space.spaces):
out.append(clip_action(a, s))
return out
else:
return action | python | def clip_action(action, space):
"""Called to clip actions to the specified range of this policy.
Arguments:
action: Single action.
space: Action space the actions should be present in.
Returns:
Clipped batch of actions.
"""
if isinstance(space, gym.spaces.Box):
return np.clip(action, space.low, space.high)
elif isinstance(space, gym.spaces.Tuple):
if type(action) not in (tuple, list):
raise ValueError("Expected tuple space for actions {}: {}".format(
action, space))
out = []
for a, s in zip(action, space.spaces):
out.append(clip_action(a, s))
return out
else:
return action | [
"def",
"clip_action",
"(",
"action",
",",
"space",
")",
":",
"if",
"isinstance",
"(",
"space",
",",
"gym",
".",
"spaces",
".",
"Box",
")",
":",
"return",
"np",
".",
"clip",
"(",
"action",
",",
"space",
".",
"low",
",",
"space",
".",
"high",
")",
"elif",
"isinstance",
"(",
"space",
",",
"gym",
".",
"spaces",
".",
"Tuple",
")",
":",
"if",
"type",
"(",
"action",
")",
"not",
"in",
"(",
"tuple",
",",
"list",
")",
":",
"raise",
"ValueError",
"(",
"\"Expected tuple space for actions {}: {}\"",
".",
"format",
"(",
"action",
",",
"space",
")",
")",
"out",
"=",
"[",
"]",
"for",
"a",
",",
"s",
"in",
"zip",
"(",
"action",
",",
"space",
".",
"spaces",
")",
":",
"out",
".",
"append",
"(",
"clip_action",
"(",
"a",
",",
"s",
")",
")",
"return",
"out",
"else",
":",
"return",
"action"
] | Called to clip actions to the specified range of this policy.
Arguments:
action: Single action.
space: Action space the actions should be present in.
Returns:
Clipped batch of actions. | [
"Called",
"to",
"clip",
"actions",
"to",
"the",
"specified",
"range",
"of",
"this",
"policy",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/evaluation/policy_graph.py#L265-L287 |
24,497 | ray-project/ray | python/ray/tune/suggest/skopt.py | SkOptSearch.on_trial_complete | def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to skopt unless early terminated or errored.
The result is internally negated when interacting with Skopt
so that Skopt Optimizers can "maximize" this value,
as it minimizes on default.
"""
skopt_trial_info = self._live_trial_mapping.pop(trial_id)
if result:
self._skopt_opt.tell(skopt_trial_info, -result[self._reward_attr]) | python | def on_trial_complete(self,
trial_id,
result=None,
error=False,
early_terminated=False):
"""Passes the result to skopt unless early terminated or errored.
The result is internally negated when interacting with Skopt
so that Skopt Optimizers can "maximize" this value,
as it minimizes on default.
"""
skopt_trial_info = self._live_trial_mapping.pop(trial_id)
if result:
self._skopt_opt.tell(skopt_trial_info, -result[self._reward_attr]) | [
"def",
"on_trial_complete",
"(",
"self",
",",
"trial_id",
",",
"result",
"=",
"None",
",",
"error",
"=",
"False",
",",
"early_terminated",
"=",
"False",
")",
":",
"skopt_trial_info",
"=",
"self",
".",
"_live_trial_mapping",
".",
"pop",
"(",
"trial_id",
")",
"if",
"result",
":",
"self",
".",
"_skopt_opt",
".",
"tell",
"(",
"skopt_trial_info",
",",
"-",
"result",
"[",
"self",
".",
"_reward_attr",
"]",
")"
] | Passes the result to skopt unless early terminated or errored.
The result is internally negated when interacting with Skopt
so that Skopt Optimizers can "maximize" this value,
as it minimizes on default. | [
"Passes",
"the",
"result",
"to",
"skopt",
"unless",
"early",
"terminated",
"or",
"errored",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/skopt.py#L121-L134 |
24,498 | ray-project/ray | python/ray/services.py | address_to_ip | def address_to_ip(address):
"""Convert a hostname to a numerical IP addresses in an address.
This should be a no-op if address already contains an actual numerical IP
address.
Args:
address: This can be either a string containing a hostname (or an IP
address) and a port or it can be just an IP address.
Returns:
The same address but with the hostname replaced by a numerical IP
address.
"""
address_parts = address.split(":")
ip_address = socket.gethostbyname(address_parts[0])
# Make sure localhost isn't resolved to the loopback ip
if ip_address == "127.0.0.1":
ip_address = get_node_ip_address()
return ":".join([ip_address] + address_parts[1:]) | python | def address_to_ip(address):
"""Convert a hostname to a numerical IP addresses in an address.
This should be a no-op if address already contains an actual numerical IP
address.
Args:
address: This can be either a string containing a hostname (or an IP
address) and a port or it can be just an IP address.
Returns:
The same address but with the hostname replaced by a numerical IP
address.
"""
address_parts = address.split(":")
ip_address = socket.gethostbyname(address_parts[0])
# Make sure localhost isn't resolved to the loopback ip
if ip_address == "127.0.0.1":
ip_address = get_node_ip_address()
return ":".join([ip_address] + address_parts[1:]) | [
"def",
"address_to_ip",
"(",
"address",
")",
":",
"address_parts",
"=",
"address",
".",
"split",
"(",
"\":\"",
")",
"ip_address",
"=",
"socket",
".",
"gethostbyname",
"(",
"address_parts",
"[",
"0",
"]",
")",
"# Make sure localhost isn't resolved to the loopback ip",
"if",
"ip_address",
"==",
"\"127.0.0.1\"",
":",
"ip_address",
"=",
"get_node_ip_address",
"(",
")",
"return",
"\":\"",
".",
"join",
"(",
"[",
"ip_address",
"]",
"+",
"address_parts",
"[",
"1",
":",
"]",
")"
] | Convert a hostname to a numerical IP addresses in an address.
This should be a no-op if address already contains an actual numerical IP
address.
Args:
address: This can be either a string containing a hostname (or an IP
address) and a port or it can be just an IP address.
Returns:
The same address but with the hostname replaced by a numerical IP
address. | [
"Convert",
"a",
"hostname",
"to",
"a",
"numerical",
"IP",
"addresses",
"in",
"an",
"address",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L174-L193 |
24,499 | ray-project/ray | python/ray/services.py | get_node_ip_address | def get_node_ip_address(address="8.8.8.8:53"):
"""Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node.
"""
ip_address, port = address.split(":")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# This command will raise an exception if there is no internet
# connection.
s.connect((ip_address, int(port)))
node_ip_address = s.getsockname()[0]
except Exception as e:
node_ip_address = "127.0.0.1"
# [Errno 101] Network is unreachable
if e.errno == 101:
try:
# try get node ip address from host name
host_name = socket.getfqdn(socket.gethostname())
node_ip_address = socket.gethostbyname(host_name)
except Exception:
pass
finally:
s.close()
return node_ip_address | python | def get_node_ip_address(address="8.8.8.8:53"):
"""Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node.
"""
ip_address, port = address.split(":")
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# This command will raise an exception if there is no internet
# connection.
s.connect((ip_address, int(port)))
node_ip_address = s.getsockname()[0]
except Exception as e:
node_ip_address = "127.0.0.1"
# [Errno 101] Network is unreachable
if e.errno == 101:
try:
# try get node ip address from host name
host_name = socket.getfqdn(socket.gethostname())
node_ip_address = socket.gethostbyname(host_name)
except Exception:
pass
finally:
s.close()
return node_ip_address | [
"def",
"get_node_ip_address",
"(",
"address",
"=",
"\"8.8.8.8:53\"",
")",
":",
"ip_address",
",",
"port",
"=",
"address",
".",
"split",
"(",
"\":\"",
")",
"s",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_DGRAM",
")",
"try",
":",
"# This command will raise an exception if there is no internet",
"# connection.",
"s",
".",
"connect",
"(",
"(",
"ip_address",
",",
"int",
"(",
"port",
")",
")",
")",
"node_ip_address",
"=",
"s",
".",
"getsockname",
"(",
")",
"[",
"0",
"]",
"except",
"Exception",
"as",
"e",
":",
"node_ip_address",
"=",
"\"127.0.0.1\"",
"# [Errno 101] Network is unreachable",
"if",
"e",
".",
"errno",
"==",
"101",
":",
"try",
":",
"# try get node ip address from host name",
"host_name",
"=",
"socket",
".",
"getfqdn",
"(",
"socket",
".",
"gethostname",
"(",
")",
")",
"node_ip_address",
"=",
"socket",
".",
"gethostbyname",
"(",
"host_name",
")",
"except",
"Exception",
":",
"pass",
"finally",
":",
"s",
".",
"close",
"(",
")",
"return",
"node_ip_address"
] | Determine the IP address of the local node.
Args:
address (str): The IP address and port of any known live service on the
network you care about.
Returns:
The IP address of the current node. | [
"Determine",
"the",
"IP",
"address",
"of",
"the",
"local",
"node",
"."
] | 4eade036a0505e244c976f36aaa2d64386b5129b | https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/services.py#L196-L226 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.