text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_handles(self, model, forward_handle, backward_handle):
""" Add handles to all non-container layers in the model. Recursively for non-container layers """ |
handles_list = []
for child in model.children():
if 'nn.modules.container' in str(type(child)):
handles_list.extend(self.add_handles(child, forward_handle, backward_handle))
else:
handles_list.append(child.register_forward_hook(forward_handle))
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove_attributes(self, model):
""" Removes the x and y attributes which were added by the forward handles Recursively searches for non-container layers """ |
for child in model.children():
if 'nn.modules.container' in str(type(child)):
self.remove_attributes(child)
else:
try:
del child.x
except AttributeError:
pass
try:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_xgboost_json(model):
""" This gets a JSON dump of an XGBoost model while ensuring the features names are their indexes. """ |
fnames = model.feature_names
model.feature_names = None
json_trees = model.get_dump(with_stats=True, dump_format="json")
model.feature_names = fnames
# this fixes a bug where XGBoost can return invalid JSON
json_trees = [t.replace(": inf,", ": 1000000000000.0,") for t in json_trees]
json_t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __dynamic_expected_value(self, y):
""" This computes the expected value conditioned on the given label value. """ |
return self.model.predict(self.data, np.ones(self.data.shape[0]) * y, output=self.model_output).mean(0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shap_values(self, X, nsamples=200, ranked_outputs=None, output_rank_order="max", rseed=None):
""" Return the values for the model applied to X. Parameters X ... |
return self.explainer.shap_values(X, nsamples, ranked_outputs, output_rank_order, rseed) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_html(out_file, plot_html):
""" Save html plots to an output file. """ |
internal_open = False
if type(out_file) == str:
out_file = open(out_file, "w")
internal_open = True
out_file.write("<html><head><script>\n")
# dump the js code
bundle_path = os.path.join(os.path.split(__file__)[0], "resources", "bundle.js")
with io.open(bundle_path, encoding="... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tensors_blocked_by_false(ops):
""" Follows a set of ops assuming their value is False and find blocked Switch paths. This is used to prune away parts of the ... |
blocked = []
def recurse(op):
if op.type == "Switch":
blocked.append(op.outputs[1]) # the true path is blocked since we assume the ops we trace are False
else:
for out in op.outputs:
for c in out.consumers():
recurse(c)
for op in o... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def phi_symbolic(self, i):
""" Get the SHAP value computation graph for a given model output. """ |
if self.phi_symbolics[i] is None:
# replace the gradients for all the non-linear activations
# we do this by hacking our way into the registry (TODO: find a public API for this if it exists)
reg = tf_ops._gradient_registry._registry
for n in op_handlers:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self, out, model_inputs, X):
""" Runs the model while also setting the learning phase flags to False. """ |
feed_dict = dict(zip(model_inputs, X))
for t in self.learning_phase_flags:
feed_dict[t] = False
return self.session.run(out, feed_dict) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def custom_grad(self, op, *grads):
""" Passes a gradient op creation request to the correct handler. """ |
return op_handlers[op.type](self, op, *grads) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_remote_experiments(experiments, thread_hosts, rate_limit=10):
""" Use ssh to run the experiments on remote machines in parallel. Parameters experiments :... |
global ssh_conn_per_min_limit
ssh_conn_per_min_limit = rate_limit
# first we kill any remaining workers from previous runs
# note we don't check_call because pkill kills our ssh call as well
thread_hosts = copy.copy(thread_hosts)
random.shuffle(thread_hosts)
for host in set(thread_hos... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kmeans(X, k, round_values=True):
""" Summarize a dataset with k mean samples weighted by the number of data points they each represent. Parameters X : numpy.... |
group_names = [str(i) for i in range(X.shape[1])]
if str(type(X)).endswith("'pandas.core.frame.DataFrame'>"):
group_names = X.columns
X = X.values
kmeans = KMeans(n_clusters=k, random_state=0).fit(X)
if round_values:
for i in range(k):
for j in range(X.shape[1]):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def embedding_plot(ind, shap_values, feature_names=None, method="pca", alpha=1.0, show=True):
""" Use the SHAP values as an embedding which we project to 2D for ... |
if feature_names is None:
feature_names = [labels['FEATURE'] % str(i) for i in range(shap_values.shape[1])]
ind = convert_name(ind, shap_values, feature_names)
if ind == "sum()":
cvals = shap_values.sum(1)
fname = "sum(SHAP values)"
else:
cvals = shap_values[:,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def runtime(X, y, model_generator, method_name):
""" Runtime transform = "negate" sort_order = 1 """ |
old_seed = np.random.seed()
np.random.seed(3293)
# average the method scores over several train/test splits
method_reps = []
for i in range(1):
X_train, X_test, y_train, _ = train_test_split(__toarray(X), y, test_size=100, random_state=i)
# define the model we are going to explai... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def local_accuracy(X, y, model_generator, method_name):
""" Local Accuracy transform = "identity" sort_order = 2 """ |
def score_map(true, pred):
""" Converts local accuracy from % of standard deviation to numerical scores for coloring.
"""
v = min(1.0, np.std(pred - true) / (np.std(true) + 1e-8))
if v < 1e-6:
return 1.0
elif v < 0.01:
return 0.9
elif v < 0.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __score_method(X, y, fcounts, model_generator, score_function, method_name, nreps=10, test_size=100, cache_dir="/tmp"):
""" Test an explanation method. """ |
old_seed = np.random.seed()
np.random.seed(3293)
# average the method scores over several train/test splits
method_reps = []
data_hash = hashlib.sha256(__toarray(X).flatten()).hexdigest() + hashlib.sha256(__toarray(y)).hexdigest()
for i in range(nreps):
X_train, X_test, y_train, y_te... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _estimate_transforms(self, nsamples):
""" Uses block matrix inversion identities to quickly estimate transforms. After a bit of matrix math we can isolate a ... |
M = len(self.coef)
mean_transform = np.zeros((M,M))
x_transform = np.zeros((M,M))
inds = np.arange(M, dtype=np.int)
for _ in tqdm(range(nsamples), "Estimating transforms"):
np.random.shuffle(inds)
cov_inv_SiSi = np.zeros((0,0))
cov_Si = np.ze... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def independentlinear60__ffnn():
""" 4-Layer Neural Network """ |
from keras.models import Sequential
from keras.layers import Dense
model = Sequential()
model.add(Dense(32, activation='relu', input_dim=60))
model.add(Dense(20, activation='relu'))
model.add(Dense(20, activation='relu'))
model.add(Dense(1))
model.compile(optimizer='adam',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cric__gbm():
""" Gradient Boosted Trees """ |
import xgboost
# max_depth and subsample match the params used for the full cric data in the paper
# learning_rate was set a bit higher to allow for faster runtimes
# n_estimators was chosen based on a train/test split of the data
model = xgboost.XGBClassifier(max_depth=5, n_estimators=400, learni... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lime_tabular_regression_1000(model, data):
""" LIME Tabular 1000 """ |
return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def shap_values(self, X, ranked_outputs=None, output_rank_order='max'):
""" Return approximate SHAP values for the model applied to the data given by X. Paramete... |
return self.explainer.shap_values(X, ranked_outputs, output_rank_order) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _agent_import_failed(trace):
"""Returns dummy agent class for if PyTorch etc. is not installed.""" |
class _AgentImportFailed(Trainer):
_name = "AgentImportFailed"
_default_config = with_common_config({})
def _setup(self, config):
raise ImportError(trace)
return _AgentImportFailed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(run_or_experiment, name=None, stop=None, config=None, resources_per_trial=None, num_samples=1, local_dir=None, upload_dir=None, trial_name_creator=None, l... |
experiment = run_or_experiment
if not isinstance(run_or_experiment, Experiment):
experiment = Experiment(
name, run_or_experiment, stop, config, resources_per_trial,
num_samples, local_dir, upload_dir, trial_name_creator, loggers,
sync_function, checkpoint_freq, chec... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_experiments(experiments, search_alg=None, scheduler=None, with_server=False, server_port=TuneServer.DEFAULT_PORT, verbose=2, resume=False, queue_trials=Fa... |
# This is important to do this here
# because it schematize the experiments
# and it conducts the implicit registration.
experiments = convert_to_experiment_list(experiments)
trials = []
for exp in experiments:
trials += run(
exp,
search_alg=search_alg,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _flush(self, close=False):
"""Flushes remaining output records in the output queues to plasma. None is used as special type of record that is propagated from... |
for channel in self.forward_channels:
if close is True:
channel.queue.put_next(None)
channel.queue._flush_writes()
for channels in self.shuffle_channels:
for channel in channels:
if close is True:
channel.queue.put_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_preprocessor(space):
"""Returns an appropriate preprocessor class for the given space.""" |
legacy_patch_shapes(space)
obs_shape = space.shape
if isinstance(space, gym.spaces.Discrete):
preprocessor = OneHotPreprocessor
elif obs_shape == ATARI_OBS_SHAPE:
preprocessor = GenericPixelPreprocessor
elif obs_shape == ATARI_RAM_OBS_SHAPE:
preprocessor = AtariRamPreproce... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def legacy_patch_shapes(space):
"""Assigns shapes to spaces that don't have shapes. This is only needed for older gym versions that don't set shapes properly for... |
if not hasattr(space, "shape"):
if isinstance(space, gym.spaces.Discrete):
space.shape = ()
elif isinstance(space, gym.spaces.Tuple):
shapes = []
for s in space.spaces:
shape = legacy_patch_shapes(s)
shapes.append(shape)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self):
"""Get a new batch from the internal ring buffer. Returns: buf: Data item saved from inqueue. released: True if the item is now removed from the r... |
if self.ttl[self.idx] <= 0:
self.buffers[self.idx] = self.inqueue.get(timeout=300.0)
self.ttl[self.idx] = self.cur_max_ttl
if self.cur_max_ttl < self.max_ttl:
self.cur_max_ttl += 1
buf = self.buffers[self.idx]
self.ttl[self.idx] -= 1
r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def train(self):
"""Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the... |
start = time.time()
result = self._train()
assert isinstance(result, dict), "_train() needs to return a dict."
# We do not modify internal state nor update this result if duplicate.
if RESULT_DUPLICATE in result:
return result
result = result.copy()
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, checkpoint_dir=None):
"""Saves the current model state to a checkpoint. Subclasses should override ``_save()`` instead to save state. This method ... |
checkpoint_dir = os.path.join(checkpoint_dir or self.logdir,
"checkpoint_{}".format(self._iteration))
if not os.path.exists(checkpoint_dir):
os.makedirs(checkpoint_dir)
checkpoint = self._save(checkpoint_dir)
saved_as_dict = False
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save_to_object(self):
"""Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object hol... |
tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir)
checkpoint_prefix = self.save(tmpdir)
data = {}
base_dir = os.path.dirname(checkpoint_prefix)
for path in os.listdir(base_dir):
path = os.path.join(base_dir, path)
if path.startswith(checkpoin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_from_object(self, obj):
"""Restores training state from a checkpoint object. These checkpoints are returned from calls to save_to_object(). """ |
info = pickle.loads(obj)
data = info["data"]
tmpdir = tempfile.mkdtemp("restore_from_object", dir=self.logdir)
checkpoint_path = os.path.join(tmpdir, info["checkpoint_name"])
for file_name, file_contents in data.items():
with open(os.path.join(tmpdir, file_name), "... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_model(self, export_formats, export_dir=None):
"""Exports model based on export_formats. Subclasses should override _export_model() to actually export ... |
export_dir = export_dir or self.logdir
return self._export_model(export_formats, export_dir) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def value(self, t):
"""See Schedule.value""" |
fraction = min(float(t) / max(1, self.schedule_timesteps), 1.0)
return self.initial_p + fraction * (self.final_p - self.initial_p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dump_json(json_info, json_file, overwrite=True):
"""Dump a whole json record into the given file. Overwrite the file if the overwrite flag set. Args: json_in... |
if overwrite:
mode = "w"
else:
mode = "w+"
try:
with open(json_file, mode) as f:
f.write(json.dumps(json_info))
except BaseException as e:
logging.error(e.message) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_json(json_file):
"""Parse a whole json record from the given file. Return None if the json file does not exists or exception occurs. Args: json_file (s... |
if not os.path.exists(json_file):
return None
try:
with open(json_file, "r") as f:
info_str = f.readlines()
info_str = "".join(info_str)
json_info = json.loads(info_str)
return unicode2str(json_info)
except BaseException as e:
logging... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def parse_multiple_json(json_file, offset=None):
"""Parse multiple json records from the given file. Seek to the offset as the start point before parsing if offs... |
json_info_list = []
if not os.path.exists(json_file):
return json_info_list
try:
with open(json_file, "r") as f:
if offset:
f.seek(offset)
for line in f:
if line[-1] != "\n":
# Incomplete line
b... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def unicode2str(content):
"""Convert the unicode element of the content to str recursively.""" |
if isinstance(content, dict):
result = {}
for key in content.keys():
result[unicode2str(key)] = unicode2str(content[key])
return result
elif isinstance(content, list):
return [unicode2str(element) for element in content]
elif isinstance(content, int) or isinstanc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def loss(self, xs, ys):
"""Computes the loss of the network.""" |
return float(
self.sess.run(
self.cross_entropy, feed_dict={
self.x: xs,
self.y_: ys
})) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grad(self, xs, ys):
"""Computes the gradients of the network.""" |
return self.sess.run(
self.cross_entropy_grads, feed_dict={
self.x: xs,
self.y_: ys
}) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_data(data_path, size, dataset):
"""Creates the queue and preprocessing operations for the dataset. Args: data_path: Filename for cifar10 data. size: Th... |
image_size = 32
if dataset == "cifar10":
label_bytes = 1
label_offset = 0
elif dataset == "cifar100":
label_bytes = 1
label_offset = 1
depth = 3
image_bytes = image_size * image_size * depth
record_bytes = label_bytes + label_offset + image_bytes
def load_tr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_input(data, batch_size, dataset, train):
"""Build CIFAR image and labels. Args: data_path: Filename for cifar10 data. batch_size: Input batch size. tra... |
image_size = 32
depth = 3
num_classes = 10 if dataset == "cifar10" else 100
images, labels = data
num_samples = images.shape[0] - images.shape[0] % batch_size
dataset = tf.contrib.data.Dataset.from_tensor_slices(
(images[:num_samples], labels[:num_samples]))
def map_train(image, la... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_or_update(cluster_config_file, min_workers, max_workers, no_restart, restart_only, yes, cluster_name):
"""Create or update a Ray cluster.""" |
if restart_only or no_restart:
assert restart_only != no_restart, "Cannot set both 'restart_only' " \
"and 'no_restart' at the same time!"
create_or_update_cluster(cluster_config_file, min_workers, max_workers,
no_restart, restart_only, yes, cluster_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def teardown(cluster_config_file, yes, workers_only, cluster_name):
"""Tear down the Ray cluster.""" |
teardown_cluster(cluster_config_file, yes, workers_only, cluster_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def kill_random_node(cluster_config_file, yes, cluster_name):
"""Kills a random Ray node. For testing purposes only.""" |
click.echo("Killed node with IP " +
kill_node(cluster_config_file, yes, cluster_name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def submit(cluster_config_file, docker, screen, tmux, stop, start, cluster_name, port_forward, script, script_args):
"""Uploads and runs a script on the specifie... |
assert not (screen and tmux), "Can specify only one of `screen` or `tmux`."
if start:
create_or_update_cluster(cluster_config_file, None, None, False, False,
True, cluster_name)
target = os.path.join("~", os.path.basename(script))
rsync(cluster_config_file, sc... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def build_graph(self):
"""Build a whole graph for the model.""" |
self.global_step = tf.Variable(0, trainable=False)
self._build_model()
if self.mode == "train":
self._build_train_op()
else:
# Additional initialization for the test network.
self.variables = ray.experimental.tf_utils.TensorFlowVariables(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mac(model, obs, h):
"""Forward pass of the multi-agent controller. Arguments: model: TorchModel class obs: Tensor of shape [B, n_agents, obs_size] h: List o... |
B, n_agents = obs.size(0), obs.size(1)
obs_flat = obs.reshape([B * n_agents, -1])
h_flat = [s.reshape([B * n_agents, -1]) for s in h]
q_flat, _, _, h_flat = model.forward({"obs": obs_flat}, h_flat)
return q_flat.reshape(
[B, n_agents, -1]), [s.reshape([B, n_agents, -1]) for s in h_flat] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def forward(self, rewards, actions, terminated, mask, obs, action_mask):
"""Forward pass of the loss. Arguments: rewards: Tensor of shape [B, T-1, n_agents] acti... |
B, T = obs.size(0), obs.size(1)
# Calculate estimated Q-Values
mac_out = []
h = [s.expand([B, self.n_agents, -1]) for s in self.model.state_init()]
for t in range(T):
q, h = _mac(self.model, obs[:, t], h)
mac_out.append(q)
mac_out = th.stack(mac... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_actor(name):
"""Get a named actor which was previously created. If the actor doesn't exist, an exception will be raised. Args: name: The name of the name... |
actor_name = _calculate_key(name)
pickled_state = _internal_kv_get(actor_name)
if pickled_state is None:
raise ValueError("The actor with name={} doesn't exist".format(name))
handle = pickle.loads(pickled_state)
return handle |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register_actor(name, actor_handle):
"""Register a named actor under a string key. Args: name: The name of the named actor. actor_handle: The actor object to ... |
if not isinstance(name, str):
raise TypeError("The name argument must be a string.")
if not isinstance(actor_handle, ray.actor.ActorHandle):
raise TypeError("The actor_handle argument must be an ActorHandle "
"object.")
actor_name = _calculate_key(name)
pickled_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_extraneous(config, schema):
"""Make sure all items of config are in schema""" |
if not isinstance(config, dict):
raise ValueError("Config {} is not a dictionary".format(config))
for k in config:
if k not in schema:
raise ValueError("Unexpected config key `{}` not in {}".format(
k, list(schema.keys())))
v, kreq = schema[k]
if v is... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate_config(config, schema=CLUSTER_CONFIG_SCHEMA):
"""Required Dicts indicate that no extra fields can be introduced.""" |
if not isinstance(config, dict):
raise ValueError("Config {} is not a dictionary".format(config))
check_required(config, schema)
check_extraneous(config, schema) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update(self, **kwargs):
"""Update the settings according to the keyword arguments. Args: kwargs: The keyword arguments to set corresponding fields. """ |
for arg in kwargs:
if hasattr(self, arg):
setattr(self, arg, kwargs[arg])
else:
raise ValueError("Invalid RayParams parameter in"
" update: %s" % arg)
self._check_usage() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_if_absent(self, **kwargs):
"""Update the settings when the target fields are None. Args: kwargs: The keyword arguments to set corresponding fields. ""... |
for arg in kwargs:
if hasattr(self, arg):
if getattr(self, arg) is None:
setattr(self, arg, kwargs[arg])
else:
raise ValueError("Invalid RayParams parameter in"
" update_if_absent: %s" % arg)
s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_actor_handle_id(actor_handle_id, num_forks):
"""Deterministically compute an actor handle ID. A new actor handle ID is generated when it is forked fr... |
assert isinstance(actor_handle_id, ActorHandleID)
handle_id_hash = hashlib.sha1()
handle_id_hash.update(actor_handle_id.binary())
handle_id_hash.update(str(num_forks).encode("ascii"))
handle_id = handle_id_hash.digest()
return ActorHandleID(handle_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_actor_handle_id_non_forked(actor_handle_id, current_task_id):
"""Deterministically compute an actor handle ID in the non-forked case. This code path ... |
assert isinstance(actor_handle_id, ActorHandleID)
assert isinstance(current_task_id, TaskID)
handle_id_hash = hashlib.sha1()
handle_id_hash.update(actor_handle_id.binary())
handle_id_hash.update(current_task_id.binary())
handle_id = handle_id_hash.digest()
return ActorHandleID(handle_id) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def method(*args, **kwargs):
"""Annotate an actor method. .. code-block:: python @ray.remote class Foo(object):
@ray.method(num_return_vals=2) def bar(self):
r... |
assert len(args) == 0
assert len(kwargs) == 1
assert "num_return_vals" in kwargs
num_return_vals = kwargs["num_return_vals"]
def annotate_method(method):
method.__ray_num_return_vals__ = num_return_vals
return method
return annotate_method |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exit_actor():
"""Intentionally exit the current actor. This function is used to disconnect an actor and exit the worker. Raises: Exception: An exception is r... |
worker = ray.worker.global_worker
if worker.mode == ray.WORKER_MODE and not worker.actor_id.is_nil():
# Disconnect the worker from the raylet. The point of
# this is so that when the worker kills itself below, the
# raylet won't push an error message to the driver.
worker.raylet... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_checkpoints_for_actor(actor_id):
"""Get the available checkpoints for the given actor ID, return a list sorted by checkpoint timestamp in descending orde... |
checkpoint_info = ray.worker.global_state.actor_checkpoint_info(actor_id)
if checkpoint_info is None:
return []
checkpoints = [
Checkpoint(checkpoint_id, timestamp) for checkpoint_id, timestamp in
zip(checkpoint_info["CheckpointIds"], checkpoint_info["Timestamps"])
]
return ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _actor_method_call(self, method_name, args=None, kwargs=None, num_return_vals=None):
"""Method execution stub for an actor handle. This is the function that ... |
worker = ray.worker.get_global_worker()
worker.check_connected()
function_signature = self._ray_method_signatures[method_name]
if args is None:
args = []
if kwargs is None:
kwargs = {}
args = signature.extend_args(function_signature, args, kwarg... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def optimize(self, sess, batch_index):
"""Run a single step of SGD. Runs a SGD step over a slice of the preloaded batch with size given by self._loaded_per_devic... |
feed_dict = {
self._batch_index: batch_index,
self._per_device_batch_size: self._loaded_per_device_batch_size,
self._max_seq_len: self._loaded_max_seq_len,
}
for tower in self._towers:
feed_dict.update(tower.loss_graph.extra_compute_grad_feed_dict... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _selection(candidate):
"""Perform selection action to candidates. For example, new gene = sample_1 + the 5th bit of sample2. Args: candidate: List of candida... |
sample_index1 = np.random.choice(len(candidate))
sample_index2 = np.random.choice(len(candidate))
sample_1 = candidate[sample_index1]
sample_2 = candidate[sample_index2]
select_index = np.random.choice(len(sample_1))
logger.info(
LOGGING_PREFIX + "Perform sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _crossover(candidate):
"""Perform crossover action to candidates. For example, new gene = 60% sample_1 + 40% sample_2. Args: candidate: List of candidate gen... |
sample_index1 = np.random.choice(len(candidate))
sample_index2 = np.random.choice(len(candidate))
sample_1 = candidate[sample_index1]
sample_2 = candidate[sample_index2]
cross_index = int(len(sample_1) * np.random.uniform(low=0.3, high=0.7))
logger.info(
LOGG... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mutation(candidate, rate=0.1):
"""Perform mutation action to candidates. For example, randomly change 10% of original sample Args: candidate: List of candid... |
sample_index = np.random.choice(len(candidate))
sample = candidate[sample_index]
idx_list = []
for i in range(int(max(len(sample) * rate, 1))):
idx = np.random.choice(len(sample))
idx_list.append(idx)
field = sample[idx] # one-hot encoding
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _train(self, trial):
"""Start one iteration of training and save remote id.""" |
assert trial.status == Trial.RUNNING, trial.status
remote = trial.runner.train.remote()
# Local Mode
if isinstance(remote, dict):
remote = _LocalWrapper(remote)
self._running[remote] = trial |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _start_trial(self, trial, checkpoint=None):
"""Starts trial and restores last result if trial was paused. Raises: ValueError if restoring from checkpoint fai... |
prior_status = trial.status
self.set_status(trial, Trial.RUNNING)
trial.runner = self._setup_runner(
trial,
reuse_allowed=checkpoint is not None
or trial._checkpoint.value is not None)
if not self.restore(trial, checkpoint):
if trial.statu... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stop_trial(self, trial, error=False, error_msg=None, stop_logger=True):
"""Stops this trial. Stops this trial, releasing all allocating resources. If stoppi... |
if stop_logger:
trial.close_logger()
if error:
self.set_status(trial, Trial.ERROR)
else:
self.set_status(trial, Trial.TERMINATED)
try:
trial.write_error_log(error_msg)
if hasattr(trial, "runner") and trial.runner:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def start_trial(self, trial, checkpoint=None):
"""Starts the trial. Will not return resources if trial repeatedly fails on start. Args: trial (Trial):
Trial to ... |
self._commit_resources(trial.resources)
try:
self._start_trial(trial, checkpoint)
except Exception as e:
logger.exception("Error starting runner for Trial %s", str(trial))
error_msg = traceback.format_exc()
time.sleep(2)
self._stop_tr... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def stop_trial(self, trial, error=False, error_msg=None, stop_logger=True):
"""Only returns resources if resources allocated.""" |
prior_status = trial.status
self._stop_trial(
trial, error=error, error_msg=error_msg, stop_logger=stop_logger)
if prior_status == Trial.RUNNING:
logger.debug("Returning resources for Trial %s.", str(trial))
self._return_resources(trial.resources)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def fetch_result(self, trial):
"""Fetches one result of the running trials. Returns: Result of the most recent trial training run.""" |
trial_future = self._find_item(self._running, trial)
if not trial_future:
raise ValueError("Trial was not running.")
self._running.pop(trial_future[0])
with warn_if_slow("fetch_result"):
result = ray.get(trial_future[0])
# For local mode
if isins... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def has_resources(self, resources):
"""Returns whether this runner has at least the specified resources. This refreshes the Ray cluster resources if the time sin... |
if time.time() - self._last_resource_refresh > self._refresh_period:
self._update_avail_resources()
currently_available = Resources.subtract(self._avail_resources,
self._committed_resources)
have_space = (
resources.cpu_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resource_string(self):
"""Returns a string describing the total resources available.""" |
if self._resources_initialized:
res_str = "{} CPUs, {} GPUs".format(self._avail_resources.cpu,
self._avail_resources.gpu)
if self._avail_resources.custom_resources:
custom = ", ".join(
"{} {}".format(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, trial, storage=Checkpoint.DISK):
"""Saves the trial's state to a checkpoint.""" |
trial._checkpoint.storage = storage
trial._checkpoint.last_result = trial.last_result
if storage == Checkpoint.MEMORY:
trial._checkpoint.value = trial.runner.save_to_object.remote()
else:
# Keeps only highest performing checkpoints if enabled
if trial... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def export_trial_if_needed(self, trial):
"""Exports model of this trial based on trial.export_formats. Return: A dict that maps ExportFormats to successfully exp... |
if trial.export_formats and len(trial.export_formats) > 0:
return ray.get(
trial.runner.export_model.remote(trial.export_formats))
return {} |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __generate_actor(self, instance_id, operator, input, output):
"""Generates an actor that will execute a particular instance of the logical operator Attribute... |
actor_id = (operator.id, instance_id)
# Record the physical dataflow graph (for debugging purposes)
self.__add_channel(actor_id, input, output)
# Select actor to construct
if operator.type == OpType.Source:
source = operator_instance.Source.remote(actor_id, operator,... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __generate_actors(self, operator, upstream_channels, downstream_channels):
"""Generates one actor for each instance of the given logical operator. Attributes... |
num_instances = operator.num_instances
logger.info("Generating {} actors of type {}...".format(
num_instances, operator.type))
in_channels = upstream_channels.pop(
operator.id) if upstream_channels else []
handles = []
for i in range(num_instances):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self):
"""Deploys and executes the physical dataflow.""" |
self._collect_garbage() # Make sure everything is clean
# TODO (john): Check if dataflow has any 'logical inconsistencies'
# For example, if there is a forward partitioning strategy but
# the number of downstream instances is larger than the number of
# upstream instances, some... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_parallelism(self, num_instances):
"""Sets the number of instances for the source operator of the stream. Attributes: num_instances (int):
The level of p... |
assert (num_instances > 0)
self.env._set_parallelism(self.src_operator_id, num_instances)
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def map(self, map_fn, name="Map"):
"""Applies a map operator to the stream. Attributes: map_fn (function):
The user-defined logic of the map. """ |
op = Operator(
_generate_uuid(),
OpType.Map,
name,
map_fn,
num_instances=self.env.config.parallelism)
return self.__register(op) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flat_map(self, flatmap_fn):
"""Applies a flatmap operator to the stream. Attributes: flatmap_fn (function):
The user-defined logic of the flatmap (e.g. spli... |
op = Operator(
_generate_uuid(),
OpType.FlatMap,
"FlatMap",
flatmap_fn,
num_instances=self.env.config.parallelism)
return self.__register(op) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def key_by(self, key_selector):
"""Applies a key_by operator to the stream. Attributes: key_attribute_index (int):
The index of the key attributed (assuming tup... |
op = Operator(
_generate_uuid(),
OpType.KeyBy,
"KeyBy",
other=key_selector,
num_instances=self.env.config.parallelism)
return self.__register(op) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def time_window(self, window_width_ms):
"""Applies a system time window to the stream. Attributes: window_width_ms (int):
The length of the window in ms. """ |
op = Operator(
_generate_uuid(),
OpType.TimeWindow,
"TimeWindow",
num_instances=self.env.config.parallelism,
other=window_width_ms)
return self.__register(op) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, filter_fn):
"""Applies a filter to the stream. Attributes: filter_fn (function):
The user-defined filter function. """ |
op = Operator(
_generate_uuid(),
OpType.Filter,
"Filter",
filter_fn,
num_instances=self.env.config.parallelism)
return self.__register(op) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def inspect(self, inspect_logic):
"""Inspects the content of the stream. Attributes: inspect_logic (function):
The user-defined inspect function. """ |
op = Operator(
_generate_uuid(),
OpType.Inspect,
"Inspect",
inspect_logic,
num_instances=self.env.config.parallelism)
return self.__register(op) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def sink(self):
"""Closes the stream with a sink operator.""" |
op = Operator(
_generate_uuid(),
OpType.Sink,
"Sink",
num_instances=self.env.config.parallelism)
return self.__register(op) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_log_filenames(self):
"""Update the list of log files to monitor.""" |
log_filenames = os.listdir(self.logs_dir)
for log_filename in log_filenames:
full_path = os.path.join(self.logs_dir, log_filename)
if full_path not in self.log_filenames:
self.log_filenames.add(full_path)
self.closed_file_infos.append(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def open_closed_files(self):
"""Open some closed files if they may have new lines. Opening more files may require us to close some of the already open files. """ |
if not self.can_open_more_files:
# If we can't open any more files. Close all of the files.
self.close_all_files()
files_with_no_updates = []
while len(self.closed_file_infos) > 0:
if (len(self.open_file_infos) >=
ray_constants.LOG_MONITO... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run(self):
"""Run the log monitor. This will query Redis once every second to check if there are new log files to monitor. It will also store those log files... |
while True:
self.update_log_filenames()
self.open_closed_files()
anything_published = self.check_log_files_and_publish_updates()
# If nothing was published, then wait a little bit before checking
# for logs to avoid using too much CPU.
if ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_configurations(self, experiments):
"""Chains generator given experiment specifications. Arguments: experiments (Experiment | list | dict):
Experiments t... |
experiment_list = convert_to_experiment_list(experiments)
for experiment in experiment_list:
self._trial_generator = itertools.chain(
self._trial_generator,
self._generate_trials(experiment.spec, experiment.name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def next_trials(self):
"""Provides a batch of Trial objects to be queued into the TrialRunner. A batch ends when self._trial_generator returns None. Returns: tri... |
trials = []
for trial in self._trial_generator:
if trial is None:
return trials
trials += [trial]
self._finished = True
return trials |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _generate_trials(self, experiment_spec, output_path=""):
"""Generates trials with configurations from `_suggest`. Creates a trial_id that is passed into `_su... |
if "run" not in experiment_spec:
raise TuneError("Must specify `run` in {}".format(experiment_spec))
for _ in range(experiment_spec.get("num_samples", 1)):
trial_id = Trial.generate_id()
while True:
suggested_config = self._suggest(trial_id)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def resolve_nested_dict(nested_dict):
"""Flattens a nested dict by joining keys into tuple of paths. Can then be passed into `format_vars`. """ |
res = {}
for k, v in nested_dict.items():
if isinstance(v, dict):
for k_, v_ in resolve_nested_dict(v).items():
res[(k, ) + k_] = v_
else:
res[(k, )] = v
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_board(args):
""" Run main entry for AutoMLBoard. Args: args: args parsed from command line """ |
init_config(args)
# backend service, should import after django settings initialized
from backend.collector import CollectorService
service = CollectorService(
args.logdir,
args.reload_interval,
standalone=False,
log_level=args.log_level)
service.run()
# front... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_config(args):
""" Initialize configs of the service. Do the following things: 1. automl board settings 2. database settings 3. django settings """ |
os.environ["AUTOMLBOARD_LOGDIR"] = args.logdir
os.environ["AUTOMLBOARD_LOGLEVEL"] = args.log_level
os.environ["AUTOMLBOARD_RELOAD_INTERVAL"] = str(args.reload_interval)
if args.db:
try:
db_address_reg = re.compile(r"(.*)://(.*):(.*)@(.*):(.*)/(.*)")
match = re.match(db_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_gpu_ids():
"""Get the IDs of the GPUs that are available to the worker. If the CUDA_VISIBLE_DEVICES environment variable was set when the worker started ... |
if _mode() == LOCAL_MODE:
raise Exception("ray.get_gpu_ids() currently does not work in PYTHON "
"MODE.")
all_resource_ids = global_worker.raylet_client.resource_ids()
assigned_ids = [
resource_id for resource_id, _ in all_resource_ids.get("GPU", [])
]
# If ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def error_info():
"""Return information about failed tasks.""" |
worker = global_worker
worker.check_connected()
return (global_state.error_messages(driver_id=worker.task_driver_id) +
global_state.error_messages(driver_id=DriverID.nil())) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _initialize_serialization(driver_id, worker=global_worker):
"""Initialize the serialization library. This defines a custom serializer for object IDs and also... |
serialization_context = pyarrow.default_serialization_context()
# Tell the serialization context to use the cloudpickle version that we
# ship with Ray.
serialization_context.set_pickle(pickle.dumps, pickle.loads)
pyarrow.register_torch_serialization_handlers(serialization_context)
for id_type... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_logs(redis_client, threads_stopped):
"""Prints log messages from workers on all of the nodes. Args: redis_client: A client to the primary Redis shard. ... |
pubsub_client = redis_client.pubsub(ignore_subscribe_messages=True)
pubsub_client.subscribe(ray.gcs_utils.LOG_FILE_CHANNEL)
localhost = services.get_node_ip_address()
try:
# Keep track of the number of consecutive log messages that have been
# received with no break in between. If this ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def print_error_messages_raylet(task_error_queue, threads_stopped):
"""Prints message received in the given output queue. This checks periodically if any un-rais... |
while True:
# Exit if we received a signal that we should stop.
if threads_stopped.is_set():
return
try:
error, t = task_error_queue.get(block=False)
except queue.Empty:
threads_stopped.wait(timeout=0.01)
continue
# Delay err... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.