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,200
slundberg/shap
shap/benchmark/plots.py
_human_score_map
def _human_score_map(human_consensus, methods_attrs): """ Converts human agreement differences to numerical scores for coloring. """ v = 1 - min(np.sum(np.abs(methods_attrs - human_consensus)) / (np.abs(human_consensus).sum() + 1), 1.0) return v
python
def _human_score_map(human_consensus, methods_attrs): """ Converts human agreement differences to numerical scores for coloring. """ v = 1 - min(np.sum(np.abs(methods_attrs - human_consensus)) / (np.abs(human_consensus).sum() + 1), 1.0) return v
[ "def", "_human_score_map", "(", "human_consensus", ",", "methods_attrs", ")", ":", "v", "=", "1", "-", "min", "(", "np", ".", "sum", "(", "np", ".", "abs", "(", "methods_attrs", "-", "human_consensus", ")", ")", "/", "(", "np", ".", "abs", "(", "huma...
Converts human agreement differences to numerical scores for coloring.
[ "Converts", "human", "agreement", "differences", "to", "numerical", "scores", "for", "coloring", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/plots.py#L370-L375
24,201
slundberg/shap
shap/plots/force_matplotlib.py
draw_bars
def draw_bars(out_value, features, feature_type, width_separators, width_bar): """Draw the bars and separators.""" rectangle_list = [] separator_list = [] pre_val = out_value for index, features in zip(range(len(features)), features): if feature_type == 'positive': left_boun...
python
def draw_bars(out_value, features, feature_type, width_separators, width_bar): """Draw the bars and separators.""" rectangle_list = [] separator_list = [] pre_val = out_value for index, features in zip(range(len(features)), features): if feature_type == 'positive': left_boun...
[ "def", "draw_bars", "(", "out_value", ",", "features", ",", "feature_type", ",", "width_separators", ",", "width_bar", ")", ":", "rectangle_list", "=", "[", "]", "separator_list", "=", "[", "]", "pre_val", "=", "out_value", "for", "index", ",", "features", "...
Draw the bars and separators.
[ "Draw", "the", "bars", "and", "separators", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/plots/force_matplotlib.py#L15-L77
24,202
slundberg/shap
shap/plots/force_matplotlib.py
format_data
def format_data(data): """Format data.""" # Format negative features neg_features = np.array([[data['features'][x]['effect'], data['features'][x]['value'], data['featureNames'][x]] for x in data['features'].keys() if da...
python
def format_data(data): """Format data.""" # Format negative features neg_features = np.array([[data['features'][x]['effect'], data['features'][x]['value'], data['featureNames'][x]] for x in data['features'].keys() if da...
[ "def", "format_data", "(", "data", ")", ":", "# Format negative features", "neg_features", "=", "np", ".", "array", "(", "[", "[", "data", "[", "'features'", "]", "[", "x", "]", "[", "'effect'", "]", ",", "data", "[", "'features'", "]", "[", "x", "]", ...
Format data.
[ "Format", "data", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/plots/force_matplotlib.py#L199-L253
24,203
slundberg/shap
shap/plots/force_matplotlib.py
draw_additive_plot
def draw_additive_plot(data, figsize, show, text_rotation=0): """Draw additive plot.""" # Turn off interactive plot if show == False: plt.ioff() # Format data neg_features, total_neg, pos_features, total_pos = format_data(data) # Compute overall metrics base_value = data['b...
python
def draw_additive_plot(data, figsize, show, text_rotation=0): """Draw additive plot.""" # Turn off interactive plot if show == False: plt.ioff() # Format data neg_features, total_neg, pos_features, total_pos = format_data(data) # Compute overall metrics base_value = data['b...
[ "def", "draw_additive_plot", "(", "data", ",", "figsize", ",", "show", ",", "text_rotation", "=", "0", ")", ":", "# Turn off interactive plot", "if", "show", "==", "False", ":", "plt", ".", "ioff", "(", ")", "# Format data", "neg_features", ",", "total_neg", ...
Draw additive plot.
[ "Draw", "additive", "plot", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/plots/force_matplotlib.py#L333-L397
24,204
slundberg/shap
setup.py
try_run_setup
def try_run_setup(**kwargs): """ Fails gracefully when various install steps don't work. """ try: run_setup(**kwargs) except Exception as e: print(str(e)) if "xgboost" in str(e).lower(): kwargs["test_xgboost"] = False print("Couldn't install XGBoost for t...
python
def try_run_setup(**kwargs): """ Fails gracefully when various install steps don't work. """ try: run_setup(**kwargs) except Exception as e: print(str(e)) if "xgboost" in str(e).lower(): kwargs["test_xgboost"] = False print("Couldn't install XGBoost for t...
[ "def", "try_run_setup", "(", "*", "*", "kwargs", ")", ":", "try", ":", "run_setup", "(", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "print", "(", "str", "(", "e", ")", ")", "if", "\"xgboost\"", "in", "str", "(", "e", ")", "."...
Fails gracefully when various install steps don't work.
[ "Fails", "gracefully", "when", "various", "install", "steps", "don", "t", "work", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/setup.py#L101-L122
24,205
slundberg/shap
shap/explainers/deep/deep_pytorch.py
deeplift_grad
def deeplift_grad(module, grad_input, grad_output): """The backward hook which computes the deeplift gradient for an nn.Module """ # first, get the module type module_type = module.__class__.__name__ # first, check the module is supported if module_type in op_handler: if op_handler[m...
python
def deeplift_grad(module, grad_input, grad_output): """The backward hook which computes the deeplift gradient for an nn.Module """ # first, get the module type module_type = module.__class__.__name__ # first, check the module is supported if module_type in op_handler: if op_handler[m...
[ "def", "deeplift_grad", "(", "module", ",", "grad_input", ",", "grad_output", ")", ":", "# first, get the module type", "module_type", "=", "module", ".", "__class__", ".", "__name__", "# first, check the module is supported", "if", "module_type", "in", "op_handler", ":...
The backward hook which computes the deeplift gradient for an nn.Module
[ "The", "backward", "hook", "which", "computes", "the", "deeplift", "gradient", "for", "an", "nn", ".", "Module" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_pytorch.py#L194-L206
24,206
slundberg/shap
shap/explainers/deep/deep_pytorch.py
add_interim_values
def add_interim_values(module, input, output): """The forward hook used to save interim tensors, detached from the graph. Used to calculate the multipliers """ try: del module.x except AttributeError: pass try: del module.y except AttributeError: pass modu...
python
def add_interim_values(module, input, output): """The forward hook used to save interim tensors, detached from the graph. Used to calculate the multipliers """ try: del module.x except AttributeError: pass try: del module.y except AttributeError: pass modu...
[ "def", "add_interim_values", "(", "module", ",", "input", ",", "output", ")", ":", "try", ":", "del", "module", ".", "x", "except", "AttributeError", ":", "pass", "try", ":", "del", "module", ".", "y", "except", "AttributeError", ":", "pass", "module_type"...
The forward hook used to save interim tensors, detached from the graph. Used to calculate the multipliers
[ "The", "forward", "hook", "used", "to", "save", "interim", "tensors", "detached", "from", "the", "graph", ".", "Used", "to", "calculate", "the", "multipliers" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_pytorch.py#L209-L245
24,207
slundberg/shap
shap/explainers/deep/deep_pytorch.py
get_target_input
def get_target_input(module, input, output): """A forward hook which saves the tensor - attached to its graph. Used if we want to explain the interim outputs of a model """ try: del module.target_input except AttributeError: pass setattr(module, 'target_input', input)
python
def get_target_input(module, input, output): """A forward hook which saves the tensor - attached to its graph. Used if we want to explain the interim outputs of a model """ try: del module.target_input except AttributeError: pass setattr(module, 'target_input', input)
[ "def", "get_target_input", "(", "module", ",", "input", ",", "output", ")", ":", "try", ":", "del", "module", ".", "target_input", "except", "AttributeError", ":", "pass", "setattr", "(", "module", ",", "'target_input'", ",", "input", ")" ]
A forward hook which saves the tensor - attached to its graph. Used if we want to explain the interim outputs of a model
[ "A", "forward", "hook", "which", "saves", "the", "tensor", "-", "attached", "to", "its", "graph", ".", "Used", "if", "we", "want", "to", "explain", "the", "interim", "outputs", "of", "a", "model" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_pytorch.py#L248-L256
24,208
slundberg/shap
shap/explainers/deep/deep_pytorch.py
PyTorchDeepExplainer.add_handles
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)): ...
python
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)): ...
[ "def", "add_handles", "(", "self", ",", "model", ",", "forward_handle", ",", "backward_handle", ")", ":", "handles_list", "=", "[", "]", "for", "child", "in", "model", ".", "children", "(", ")", ":", "if", "'nn.modules.container'", "in", "str", "(", "type"...
Add handles to all non-container layers in the model. Recursively for non-container layers
[ "Add", "handles", "to", "all", "non", "-", "container", "layers", "in", "the", "model", ".", "Recursively", "for", "non", "-", "container", "layers" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_pytorch.py#L64-L76
24,209
slundberg/shap
shap/explainers/deep/deep_pytorch.py
PyTorchDeepExplainer.remove_attributes
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_a...
python
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_a...
[ "def", "remove_attributes", "(", "self", ",", "model", ")", ":", "for", "child", "in", "model", ".", "children", "(", ")", ":", "if", "'nn.modules.container'", "in", "str", "(", "type", "(", "child", ")", ")", ":", "self", ".", "remove_attributes", "(", ...
Removes the x and y attributes which were added by the forward handles Recursively searches for non-container layers
[ "Removes", "the", "x", "and", "y", "attributes", "which", "were", "added", "by", "the", "forward", "handles", "Recursively", "searches", "for", "non", "-", "container", "layers" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_pytorch.py#L78-L94
24,210
slundberg/shap
shap/explainers/tree.py
get_xgboost_json
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 fi...
python
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 fi...
[ "def", "get_xgboost_json", "(", "model", ")", ":", "fnames", "=", "model", ".", "feature_names", "model", ".", "feature_names", "=", "None", "json_trees", "=", "model", ".", "get_dump", "(", "with_stats", "=", "True", ",", "dump_format", "=", "\"json\"", ")"...
This gets a JSON dump of an XGBoost model while ensuring the features names are their indexes.
[ "This", "gets", "a", "JSON", "dump", "of", "an", "XGBoost", "model", "while", "ensuring", "the", "features", "names", "are", "their", "indexes", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/tree.py#L907-L919
24,211
slundberg/shap
shap/explainers/tree.py
TreeExplainer.__dynamic_expected_value
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)
python
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)
[ "def", "__dynamic_expected_value", "(", "self", ",", "y", ")", ":", "return", "self", ".", "model", ".", "predict", "(", "self", ".", "data", ",", "np", ".", "ones", "(", "self", ".", "data", ".", "shape", "[", "0", "]", ")", "*", "y", ",", "outp...
This computes the expected value conditioned on the given label value.
[ "This", "computes", "the", "expected", "value", "conditioned", "on", "the", "given", "label", "value", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/tree.py#L125-L129
24,212
slundberg/shap
shap/explainers/gradient.py
GradientExplainer.shap_values
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 : list, if framework == 'tensorflow': numpy.array, or pandas.DataFrame if framework == 'pyt...
python
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 : list, if framework == 'tensorflow': numpy.array, or pandas.DataFrame if framework == 'pyt...
[ "def", "shap_values", "(", "self", ",", "X", ",", "nsamples", "=", "200", ",", "ranked_outputs", "=", "None", ",", "output_rank_order", "=", "\"max\"", ",", "rseed", "=", "None", ")", ":", "return", "self", ".", "explainer", ".", "shap_values", "(", "X",...
Return the values for the model applied to X. Parameters ---------- X : list, if framework == 'tensorflow': numpy.array, or pandas.DataFrame if framework == 'pytorch': torch.tensor A tensor (or list of tensors) of samples (where X.shape[0] == # samples) on wh...
[ "Return", "the", "values", "for", "the", "model", "applied", "to", "X", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/gradient.py#L75-L112
24,213
slundberg/shap
shap/plots/force.py
save_html
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....
python
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....
[ "def", "save_html", "(", "out_file", ",", "plot_html", ")", ":", "internal_open", "=", "False", "if", "type", "(", "out_file", ")", "==", "str", ":", "out_file", "=", "open", "(", "out_file", ",", "\"w\"", ")", "internal_open", "=", "True", "out_file", "...
Save html plots to an output file.
[ "Save", "html", "plots", "to", "an", "output", "file", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/plots/force.py#L217-L239
24,214
slundberg/shap
shap/explainers/deep/deep_tf.py
tensors_blocked_by_false
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 model graph that are only used during the training phase (like dropout, batch norm, etc.). """ blocked = [] def recurse(op): i...
python
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 model graph that are only used during the training phase (like dropout, batch norm, etc.). """ blocked = [] def recurse(op): i...
[ "def", "tensors_blocked_by_false", "(", "ops", ")", ":", "blocked", "=", "[", "]", "def", "recurse", "(", "op", ")", ":", "if", "op", ".", "type", "==", "\"Switch\"", ":", "blocked", ".", "append", "(", "op", ".", "outputs", "[", "1", "]", ")", "# ...
Follows a set of ops assuming their value is False and find blocked Switch paths. This is used to prune away parts of the model graph that are only used during the training phase (like dropout, batch norm, etc.).
[ "Follows", "a", "set", "of", "ops", "assuming", "their", "value", "is", "False", "and", "find", "blocked", "Switch", "paths", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_tf.py#L290-L307
24,215
slundberg/shap
shap/explainers/deep/deep_tf.py
TFDeepExplainer.phi_symbolic
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 t...
python
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 t...
[ "def", "phi_symbolic", "(", "self", ",", "i", ")", ":", "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...
Get the SHAP value computation graph for a given model output.
[ "Get", "the", "SHAP", "value", "computation", "graph", "for", "a", "given", "model", "output", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_tf.py#L178-L214
24,216
slundberg/shap
shap/explainers/deep/deep_tf.py
TFDeepExplainer.run
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)
python
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)
[ "def", "run", "(", "self", ",", "out", ",", "model_inputs", ",", "X", ")", ":", "feed_dict", "=", "dict", "(", "zip", "(", "model_inputs", ",", "X", ")", ")", "for", "t", "in", "self", ".", "learning_phase_flags", ":", "feed_dict", "[", "t", "]", "...
Runs the model while also setting the learning phase flags to False.
[ "Runs", "the", "model", "while", "also", "setting", "the", "learning", "phase", "flags", "to", "False", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_tf.py#L276-L282
24,217
slundberg/shap
shap/explainers/deep/deep_tf.py
TFDeepExplainer.custom_grad
def custom_grad(self, op, *grads): """ Passes a gradient op creation request to the correct handler. """ return op_handlers[op.type](self, op, *grads)
python
def custom_grad(self, op, *grads): """ Passes a gradient op creation request to the correct handler. """ return op_handlers[op.type](self, op, *grads)
[ "def", "custom_grad", "(", "self", ",", "op", ",", "*", "grads", ")", ":", "return", "op_handlers", "[", "op", ".", "type", "]", "(", "self", ",", "op", ",", "*", "grads", ")" ]
Passes a gradient op creation request to the correct handler.
[ "Passes", "a", "gradient", "op", "creation", "request", "to", "the", "correct", "handler", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/deep_tf.py#L284-L287
24,218
slundberg/shap
shap/benchmark/experiments.py
run_remote_experiments
def run_remote_experiments(experiments, thread_hosts, rate_limit=10): """ Use ssh to run the experiments on remote machines in parallel. Parameters ---------- experiments : iterable Output of shap.benchmark.experiments(...). thread_hosts : list of strings Each host has the format "...
python
def run_remote_experiments(experiments, thread_hosts, rate_limit=10): """ Use ssh to run the experiments on remote machines in parallel. Parameters ---------- experiments : iterable Output of shap.benchmark.experiments(...). thread_hosts : list of strings Each host has the format "...
[ "def", "run_remote_experiments", "(", "experiments", ",", "thread_hosts", ",", "rate_limit", "=", "10", ")", ":", "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_ca...
Use ssh to run the experiments on remote machines in parallel. Parameters ---------- experiments : iterable Output of shap.benchmark.experiments(...). thread_hosts : list of strings Each host has the format "host_name:path_to_python_binary" and can appear multiple times in the ...
[ "Use", "ssh", "to", "run", "the", "experiments", "on", "remote", "machines", "in", "parallel", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/experiments.py#L322-L372
24,219
slundberg/shap
shap/explainers/kernel.py
kmeans
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.array or pandas.DataFrame Matrix of data samples to summarize (# samples x # features) k : int Number of m...
python
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.array or pandas.DataFrame Matrix of data samples to summarize (# samples x # features) k : int Number of m...
[ "def", "kmeans", "(", "X", ",", "k", ",", "round_values", "=", "True", ")", ":", "group_names", "=", "[", "str", "(", "i", ")", "for", "i", "in", "range", "(", "X", ".", "shape", "[", "1", "]", ")", "]", "if", "str", "(", "type", "(", "X", ...
Summarize a dataset with k mean samples weighted by the number of data points they each represent. Parameters ---------- X : numpy.array or pandas.DataFrame Matrix of data samples to summarize (# samples x # features) k : int Number of means to use for approximation. round_val...
[ "Summarize", "a", "dataset", "with", "k", "mean", "samples", "weighted", "by", "the", "number", "of", "data", "points", "they", "each", "represent", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/kernel.py#L18-L50
24,220
slundberg/shap
shap/plots/embedding.py
embedding_plot
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 visualization. Parameters ---------- ind : int or string If this is an int it is the index of the feature to use to color the embeddin...
python
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 visualization. Parameters ---------- ind : int or string If this is an int it is the index of the feature to use to color the embeddin...
[ "def", "embedding_plot", "(", "ind", ",", "shap_values", ",", "feature_names", "=", "None", ",", "method", "=", "\"pca\"", ",", "alpha", "=", "1.0", ",", "show", "=", "True", ")", ":", "if", "feature_names", "is", "None", ":", "feature_names", "=", "[", ...
Use the SHAP values as an embedding which we project to 2D for visualization. Parameters ---------- ind : int or string If this is an int it is the index of the feature to use to color the embedding. If this is a string it is either the name of the feature, or it can have the form "...
[ "Use", "the", "SHAP", "values", "as", "an", "embedding", "which", "we", "project", "to", "2D", "for", "visualization", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/plots/embedding.py#L14-L78
24,221
slundberg/shap
shap/benchmark/metrics.py
runtime
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, _ =...
python
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, _ =...
[ "def", "runtime", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ")", ":", "old_seed", "=", "np", ".", "random", ".", "seed", "(", ")", "np", ".", "random", ".", "seed", "(", "3293", ")", "# average the method scores over several train/test ...
Runtime transform = "negate" sort_order = 1
[ "Runtime", "transform", "=", "negate", "sort_order", "=", "1" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L22-L54
24,222
slundberg/shap
shap/benchmark/metrics.py
local_accuracy
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) / ...
python
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) / ...
[ "def", "local_accuracy", "(", "X", ",", "y", ",", "model_generator", ",", "method_name", ")", ":", "def", "score_map", "(", "true", ",", "pred", ")", ":", "\"\"\" Converts local accuracy from % of standard deviation to numerical scores for coloring.\n \"\"\"", "v", ...
Local Accuracy transform = "identity" sort_order = 2
[ "Local", "Accuracy", "transform", "=", "identity", "sort_order", "=", "2" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L56-L90
24,223
slundberg/shap
shap/benchmark/metrics.py
__score_method
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...
python
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...
[ "def", "__score_method", "(", "X", ",", "y", ",", "fcounts", ",", "model_generator", ",", "score_function", ",", "method_name", ",", "nreps", "=", "10", ",", "test_size", "=", "100", ",", "cache_dir", "=", "\"/tmp\"", ")", ":", "old_seed", "=", "np", "."...
Test an explanation method.
[ "Test", "an", "explanation", "method", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/metrics.py#L446-L495
24,224
slundberg/shap
shap/explainers/linear.py
LinearExplainer._estimate_transforms
def _estimate_transforms(self, nsamples): """ Uses block matrix inversion identities to quickly estimate transforms. After a bit of matrix math we can isolate a transform matrix (# features x # features) that is independent of any sample we are explaining. It is the result of averaging over ...
python
def _estimate_transforms(self, nsamples): """ Uses block matrix inversion identities to quickly estimate transforms. After a bit of matrix math we can isolate a transform matrix (# features x # features) that is independent of any sample we are explaining. It is the result of averaging over ...
[ "def", "_estimate_transforms", "(", "self", ",", "nsamples", ")", ":", "M", "=", "len", "(", "self", ".", "coef", ")", "mean_transform", "=", "np", ".", "zeros", "(", "(", "M", ",", "M", ")", ")", "x_transform", "=", "np", ".", "zeros", "(", "(", ...
Uses block matrix inversion identities to quickly estimate transforms. After a bit of matrix math we can isolate a transform matrix (# features x # features) that is independent of any sample we are explaining. It is the result of averaging over all feature permutations, but we just use a fixed...
[ "Uses", "block", "matrix", "inversion", "identities", "to", "quickly", "estimate", "transforms", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/linear.py#L113-L175
24,225
slundberg/shap
shap/benchmark/models.py
independentlinear60__ffnn
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')) ...
python
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')) ...
[ "def", "independentlinear60__ffnn", "(", ")", ":", "from", "keras", ".", "models", "import", "Sequential", "from", "keras", ".", "layers", "import", "Dense", "model", "=", "Sequential", "(", ")", "model", ".", "add", "(", "Dense", "(", "32", ",", "activati...
4-Layer Neural Network
[ "4", "-", "Layer", "Neural", "Network" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L114-L130
24,226
slundberg/shap
shap/benchmark/models.py
cric__gbm
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 = xgbo...
python
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 = xgbo...
[ "def", "cric__gbm", "(", ")", ":", "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", "=",...
Gradient Boosted Trees
[ "Gradient", "Boosted", "Trees" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L173-L187
24,227
slundberg/shap
shap/benchmark/methods.py
lime_tabular_regression_1000
def lime_tabular_regression_1000(model, data): """ LIME Tabular 1000 """ return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000)
python
def lime_tabular_regression_1000(model, data): """ LIME Tabular 1000 """ return lambda X: other.LimeTabularExplainer(model.predict, data, mode="regression").attributions(X, nsamples=1000)
[ "def", "lime_tabular_regression_1000", "(", "model", ",", "data", ")", ":", "return", "lambda", "X", ":", "other", ".", "LimeTabularExplainer", "(", "model", ".", "predict", ",", "data", ",", "mode", "=", "\"regression\"", ")", ".", "attributions", "(", "X",...
LIME Tabular 1000
[ "LIME", "Tabular", "1000" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L91-L94
24,228
slundberg/shap
shap/explainers/deep/__init__.py
DeepExplainer.shap_values
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. Parameters ---------- X : list, if framework == 'tensorflow': numpy.array, or pandas.DataFrame if framework ==...
python
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. Parameters ---------- X : list, if framework == 'tensorflow': numpy.array, or pandas.DataFrame if framework ==...
[ "def", "shap_values", "(", "self", ",", "X", ",", "ranked_outputs", "=", "None", ",", "output_rank_order", "=", "'max'", ")", ":", "return", "self", ".", "explainer", ".", "shap_values", "(", "X", ",", "ranked_outputs", ",", "output_rank_order", ")" ]
Return approximate SHAP values for the model applied to the data given by X. Parameters ---------- X : list, if framework == 'tensorflow': numpy.array, or pandas.DataFrame if framework == 'pytorch': torch.tensor A tensor (or list of tensors) of samples (where...
[ "Return", "approximate", "SHAP", "values", "for", "the", "model", "applied", "to", "the", "data", "given", "by", "X", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/explainers/deep/__init__.py#L86-L119
24,229
ray-project/ray
python/ray/rllib/agents/mock.py
_agent_import_failed
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 _Age...
python
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 _Age...
[ "def", "_agent_import_failed", "(", "trace", ")", ":", "class", "_AgentImportFailed", "(", "Trainer", ")", ":", "_name", "=", "\"AgentImportFailed\"", "_default_config", "=", "with_common_config", "(", "{", "}", ")", "def", "_setup", "(", "self", ",", "config", ...
Returns dummy agent class for if PyTorch etc. is not installed.
[ "Returns", "dummy", "agent", "class", "for", "if", "PyTorch", "etc", ".", "is", "not", "installed", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/mock.py#L108-L118
24,230
ray-project/ray
python/ray/tune/tune.py
run
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, loggers=None, sync_function=None, checkpoint_freq=0, checkpoint...
python
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, loggers=None, sync_function=None, checkpoint_freq=0, checkpoint...
[ "def", "run", "(", "run_or_experiment", ",", "name", "=", "None", ",", "stop", "=", "None", ",", "config", "=", "None", ",", "resources_per_trial", "=", "None", ",", "num_samples", "=", "1", ",", "local_dir", "=", "None", ",", "upload_dir", "=", "None", ...
Executes training. Args: run_or_experiment (function|class|str|Experiment): If function|class|str, this is the algorithm or model to train. This may refer to the name of a built-on algorithm (e.g. RLLib's DQN or PPO), a user-defined trainable function or clas...
[ "Executes", "training", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/tune.py#L68-L257
24,231
ray-project/ray
python/ray/tune/tune.py
run_experiments
def run_experiments(experiments, search_alg=None, scheduler=None, with_server=False, server_port=TuneServer.DEFAULT_PORT, verbose=2, resume=False, queue_trials=False, ...
python
def run_experiments(experiments, search_alg=None, scheduler=None, with_server=False, server_port=TuneServer.DEFAULT_PORT, verbose=2, resume=False, queue_trials=False, ...
[ "def", "run_experiments", "(", "experiments", ",", "search_alg", "=", "None", ",", "scheduler", "=", "None", ",", "with_server", "=", "False", ",", "server_port", "=", "TuneServer", ".", "DEFAULT_PORT", ",", "verbose", "=", "2", ",", "resume", "=", "False", ...
Runs and blocks until all trials finish. Examples: >>> experiment_spec = Experiment("experiment", my_func) >>> run_experiments(experiments=experiment_spec) >>> experiment_spec = {"experiment": {"run": my_func}} >>> run_experiments(experiments=experiment_spec) >>> run_exper...
[ "Runs", "and", "blocks", "until", "all", "trials", "finish", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/tune.py#L260-L312
24,232
ray-project/ray
python/ray/experimental/streaming/communication.py
DataOutput._flush
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 sources to sink to notify that the end of data in a stream. Attributes: close (bool): A flag denoting whether t...
python
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 sources to sink to notify that the end of data in a stream. Attributes: close (bool): A flag denoting whether t...
[ "def", "_flush", "(", "self", ",", "close", "=", "False", ")", ":", "for", "channel", "in", "self", ".", "forward_channels", ":", "if", "close", "is", "True", ":", "channel", ".", "queue", ".", "put_next", "(", "None", ")", "channel", ".", "queue", "...
Flushes remaining output records in the output queues to plasma. None is used as special type of record that is propagated from sources to sink to notify that the end of data in a stream. Attributes: close (bool): A flag denoting whether the channel should be also mar...
[ "Flushes", "remaining", "output", "records", "in", "the", "output", "queues", "to", "plasma", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/communication.py#L205-L233
24,233
ray-project/ray
python/ray/rllib/models/preprocessors.py
get_preprocessor
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 = Generi...
python
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 = Generi...
[ "def", "get_preprocessor", "(", "space", ")", ":", "legacy_patch_shapes", "(", "space", ")", "obs_shape", "=", "space", ".", "shape", "if", "isinstance", "(", "space", ",", "gym", ".", "spaces", ".", "Discrete", ")", ":", "preprocessor", "=", "OneHotPreproce...
Returns an appropriate preprocessor class for the given space.
[ "Returns", "an", "appropriate", "preprocessor", "class", "for", "the", "given", "space", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/preprocessors.py#L242-L261
24,234
ray-project/ray
python/ray/rllib/models/preprocessors.py
legacy_patch_shapes
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 Tuple and Discrete spaces. """ if not hasattr(space, "shape"): if isinstance(space, gym.spaces.Discrete): space.shap...
python
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 Tuple and Discrete spaces. """ if not hasattr(space, "shape"): if isinstance(space, gym.spaces.Discrete): space.shap...
[ "def", "legacy_patch_shapes", "(", "space", ")", ":", "if", "not", "hasattr", "(", "space", ",", "\"shape\"", ")", ":", "if", "isinstance", "(", "space", ",", "gym", ".", "spaces", ".", "Discrete", ")", ":", "space", ".", "shape", "=", "(", ")", "eli...
Assigns shapes to spaces that don't have shapes. This is only needed for older gym versions that don't set shapes properly for Tuple and Discrete spaces.
[ "Assigns", "shapes", "to", "spaces", "that", "don", "t", "have", "shapes", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/preprocessors.py#L264-L281
24,235
ray-project/ray
python/ray/rllib/optimizers/aso_minibatch_buffer.py
MinibatchBuffer.get
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 ring buffer. """ if self.ttl[self.idx] <= 0: self.buffers[self.idx] = self.inqueue.get(timeou...
python
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 ring buffer. """ if self.ttl[self.idx] <= 0: self.buffers[self.idx] = self.inqueue.get(timeou...
[ "def", "get", "(", "self", ")", ":", "if", "self", ".", "ttl", "[", "self", ".", "idx", "]", "<=", "0", ":", "self", ".", "buffers", "[", "self", ".", "idx", "]", "=", "self", ".", "inqueue", ".", "get", "(", "timeout", "=", "300.0", ")", "se...
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 ring buffer.
[ "Get", "a", "new", "batch", "from", "the", "internal", "ring", "buffer", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/aso_minibatch_buffer.py#L30-L48
24,236
ray-project/ray
python/ray/tune/trainable.py
Trainable.train
def train(self): """Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the following fields in the result: `done` (bool): training is terminated. Filled only if not provided. `time_t...
python
def train(self): """Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the following fields in the result: `done` (bool): training is terminated. Filled only if not provided. `time_t...
[ "def", "train", "(", "self", ")", ":", "start", "=", "time", ".", "time", "(", ")", "result", "=", "self", ".", "_train", "(", ")", "assert", "isinstance", "(", "result", ",", "dict", ")", ",", "\"_train() needs to return a dict.\"", "# We do not modify inte...
Runs one logical iteration of training. Subclasses should override ``_train()`` instead to return results. This class automatically fills the following fields in the result: `done` (bool): training is terminated. Filled only if not provided. `time_this_iter_s` (float): Time in...
[ "Runs", "one", "logical", "iteration", "of", "training", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L111-L211
24,237
ray-project/ray
python/ray/tune/trainable.py
Trainable.save
def save(self, checkpoint_dir=None): """Saves the current model state to a checkpoint. Subclasses should override ``_save()`` instead to save state. This method dumps additional metadata alongside the saved path. Args: checkpoint_dir (str): Optional dir to place the checkpo...
python
def save(self, checkpoint_dir=None): """Saves the current model state to a checkpoint. Subclasses should override ``_save()`` instead to save state. This method dumps additional metadata alongside the saved path. Args: checkpoint_dir (str): Optional dir to place the checkpo...
[ "def", "save", "(", "self", ",", "checkpoint_dir", "=", "None", ")", ":", "checkpoint_dir", "=", "os", ".", "path", ".", "join", "(", "checkpoint_dir", "or", "self", ".", "logdir", ",", "\"checkpoint_{}\"", ".", "format", "(", "self", ".", "_iteration", ...
Saves the current model state to a checkpoint. Subclasses should override ``_save()`` instead to save state. This method dumps additional metadata alongside the saved path. Args: checkpoint_dir (str): Optional dir to place the checkpoint. Returns: Checkpoint pa...
[ "Saves", "the", "current", "model", "state", "to", "a", "checkpoint", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L224-L273
24,238
ray-project/ray
python/ray/tune/trainable.py
Trainable.save_to_object
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 holding checkpoint data. """ tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir) checkpoint...
python
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 holding checkpoint data. """ tmpdir = tempfile.mkdtemp("save_to_object", dir=self.logdir) checkpoint...
[ "def", "save_to_object", "(", "self", ")", ":", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", "\"save_to_object\"", ",", "dir", "=", "self", ".", "logdir", ")", "checkpoint_prefix", "=", "self", ".", "save", "(", "tmpdir", ")", "data", "=", "{", "}", ...
Saves the current model state to a Python object. It also saves to disk but does not return the checkpoint path. Returns: Object holding checkpoint data.
[ "Saves", "the", "current", "model", "state", "to", "a", "Python", "object", ".", "It", "also", "saves", "to", "disk", "but", "does", "not", "return", "the", "checkpoint", "path", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L275-L304
24,239
ray-project/ray
python/ray/tune/trainable.py
Trainable.restore_from_object
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) ...
python
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) ...
[ "def", "restore_from_object", "(", "self", ",", "obj", ")", ":", "info", "=", "pickle", ".", "loads", "(", "obj", ")", "data", "=", "info", "[", "\"data\"", "]", "tmpdir", "=", "tempfile", ".", "mkdtemp", "(", "\"restore_from_object\"", ",", "dir", "=", ...
Restores training state from a checkpoint object. These checkpoints are returned from calls to save_to_object().
[ "Restores", "training", "state", "from", "a", "checkpoint", "object", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L334-L350
24,240
ray-project/ray
python/ray/tune/trainable.py
Trainable.export_model
def export_model(self, export_formats, export_dir=None): """Exports model based on export_formats. Subclasses should override _export_model() to actually export model to local directory. Args: export_formats (list): List of formats that should be exported. expor...
python
def export_model(self, export_formats, export_dir=None): """Exports model based on export_formats. Subclasses should override _export_model() to actually export model to local directory. Args: export_formats (list): List of formats that should be exported. expor...
[ "def", "export_model", "(", "self", ",", "export_formats", ",", "export_dir", "=", "None", ")", ":", "export_dir", "=", "export_dir", "or", "self", ".", "logdir", "return", "self", ".", "_export_model", "(", "export_formats", ",", "export_dir", ")" ]
Exports model based on export_formats. Subclasses should override _export_model() to actually export model to local directory. Args: export_formats (list): List of formats that should be exported. export_dir (str): Optional dir to place the exported model. ...
[ "Exports", "model", "based", "on", "export_formats", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L352-L367
24,241
ray-project/ray
python/ray/rllib/utils/schedules.py
LinearSchedule.value
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)
python
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)
[ "def", "value", "(", "self", ",", "t", ")", ":", "fraction", "=", "min", "(", "float", "(", "t", ")", "/", "max", "(", "1", ",", "self", ".", "schedule_timesteps", ")", ",", "1.0", ")", "return", "self", ".", "initial_p", "+", "fraction", "*", "(...
See Schedule.value
[ "See", "Schedule", ".", "value" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/utils/schedules.py#L105-L108
24,242
ray-project/ray
python/ray/tune/automlboard/common/utils.py
dump_json
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_info (dict): Information dict to be dumped. json_file (str): File path to be dumped to. overwrite(boolean) """ if o...
python
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_info (dict): Information dict to be dumped. json_file (str): File path to be dumped to. overwrite(boolean) """ if o...
[ "def", "dump_json", "(", "json_info", ",", "json_file", ",", "overwrite", "=", "True", ")", ":", "if", "overwrite", ":", "mode", "=", "\"w\"", "else", ":", "mode", "=", "\"w+\"", "try", ":", "with", "open", "(", "json_file", ",", "mode", ")", "as", "...
Dump a whole json record into the given file. Overwrite the file if the overwrite flag set. Args: json_info (dict): Information dict to be dumped. json_file (str): File path to be dumped to. overwrite(boolean)
[ "Dump", "a", "whole", "json", "record", "into", "the", "given", "file", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/common/utils.py#L11-L30
24,243
ray-project/ray
python/ray/tune/automlboard/common/utils.py
parse_json
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 (str): File path to be parsed. Returns: A dict of json info. """ if not os.path.exists(json_file): return None...
python
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 (str): File path to be parsed. Returns: A dict of json info. """ if not os.path.exists(json_file): return None...
[ "def", "parse_json", "(", "json_file", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "json_file", ")", ":", "return", "None", "try", ":", "with", "open", "(", "json_file", ",", "\"r\"", ")", "as", "f", ":", "info_str", "=", "f", "."...
Parse a whole json record from the given file. Return None if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. Returns: A dict of json info.
[ "Parse", "a", "whole", "json", "record", "from", "the", "given", "file", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/common/utils.py#L33-L55
24,244
ray-project/ray
python/ray/tune/automlboard/common/utils.py
parse_multiple_json
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 offset set. return empty list if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. ...
python
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 offset set. return empty list if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. ...
[ "def", "parse_multiple_json", "(", "json_file", ",", "offset", "=", "None", ")", ":", "json_info_list", "=", "[", "]", "if", "not", "os", ".", "path", ".", "exists", "(", "json_file", ")", ":", "return", "json_info_list", "try", ":", "with", "open", "(",...
Parse multiple json records from the given file. Seek to the offset as the start point before parsing if offset set. return empty list if the json file does not exists or exception occurs. Args: json_file (str): File path to be parsed. offset (int): Initial seek position of the file. ...
[ "Parse", "multiple", "json", "records", "from", "the", "given", "file", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/common/utils.py#L58-L92
24,245
ray-project/ray
python/ray/tune/automlboard/common/utils.py
unicode2str
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): r...
python
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): r...
[ "def", "unicode2str", "(", "content", ")", ":", "if", "isinstance", "(", "content", ",", "dict", ")", ":", "result", "=", "{", "}", "for", "key", "in", "content", ".", "keys", "(", ")", ":", "result", "[", "unicode2str", "(", "key", ")", "]", "=", ...
Convert the unicode element of the content to str recursively.
[ "Convert", "the", "unicode", "element", "of", "the", "content", "to", "str", "recursively", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automlboard/common/utils.py#L100-L112
24,246
ray-project/ray
examples/lbfgs/driver.py
LinearModel.loss
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 }))
python
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 }))
[ "def", "loss", "(", "self", ",", "xs", ",", "ys", ")", ":", "return", "float", "(", "self", ".", "sess", ".", "run", "(", "self", ".", "cross_entropy", ",", "feed_dict", "=", "{", "self", ".", "x", ":", "xs", ",", "self", ".", "y_", ":", "ys", ...
Computes the loss of the network.
[ "Computes", "the", "loss", "of", "the", "network", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/lbfgs/driver.py#L63-L70
24,247
ray-project/ray
examples/lbfgs/driver.py
LinearModel.grad
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 })
python
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 })
[ "def", "grad", "(", "self", ",", "xs", ",", "ys", ")", ":", "return", "self", ".", "sess", ".", "run", "(", "self", ".", "cross_entropy_grads", ",", "feed_dict", "=", "{", "self", ".", "x", ":", "xs", ",", "self", ".", "y_", ":", "ys", "}", ")"...
Computes the gradients of the network.
[ "Computes", "the", "gradients", "of", "the", "network", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/lbfgs/driver.py#L72-L78
24,248
ray-project/ray
examples/resnet/cifar_input.py
build_data
def build_data(data_path, size, dataset): """Creates the queue and preprocessing operations for the dataset. Args: data_path: Filename for cifar10 data. size: The number of images in the dataset. dataset: The dataset we are using. Returns: queue: A Tensorflow queue for extr...
python
def build_data(data_path, size, dataset): """Creates the queue and preprocessing operations for the dataset. Args: data_path: Filename for cifar10 data. size: The number of images in the dataset. dataset: The dataset we are using. Returns: queue: A Tensorflow queue for extr...
[ "def", "build_data", "(", "data_path", ",", "size", ",", "dataset", ")", ":", "image_size", "=", "32", "if", "dataset", "==", "\"cifar10\"", ":", "label_bytes", "=", "1", "label_offset", "=", "0", "elif", "dataset", "==", "\"cifar100\"", ":", "label_bytes", ...
Creates the queue and preprocessing operations for the dataset. Args: data_path: Filename for cifar10 data. size: The number of images in the dataset. dataset: The dataset we are using. Returns: queue: A Tensorflow queue for extracting the images and labels.
[ "Creates", "the", "queue", "and", "preprocessing", "operations", "for", "the", "dataset", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/cifar_input.py#L12-L54
24,249
ray-project/ray
examples/resnet/cifar_input.py
build_input
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. train: True if we are training and false if we are testing. Returns: images: Batches of images of size [...
python
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. train: True if we are training and false if we are testing. Returns: images: Batches of images of size [...
[ "def", "build_input", "(", "data", ",", "batch_size", ",", "dataset", ",", "train", ")", ":", "image_size", "=", "32", "depth", "=", "3", "num_classes", "=", "10", "if", "dataset", "==", "\"cifar10\"", "else", "100", "images", ",", "labels", "=", "data",...
Build CIFAR image and labels. Args: data_path: Filename for cifar10 data. batch_size: Input batch size. train: True if we are training and false if we are testing. Returns: images: Batches of images of size [batch_size, image_size, image_size, 3]. labels: Ba...
[ "Build", "CIFAR", "image", "and", "labels", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/cifar_input.py#L57-L116
24,250
ray-project/ray
python/ray/scripts/scripts.py
create_or_update
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'...
python
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'...
[ "def", "create_or_update", "(", "cluster_config_file", ",", "min_workers", ",", "max_workers", ",", "no_restart", ",", "restart_only", ",", "yes", ",", "cluster_name", ")", ":", "if", "restart_only", "or", "no_restart", ":", "assert", "restart_only", "!=", "no_res...
Create or update a Ray cluster.
[ "Create", "or", "update", "a", "Ray", "cluster", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/scripts/scripts.py#L453-L460
24,251
ray-project/ray
python/ray/scripts/scripts.py
teardown
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)
python
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)
[ "def", "teardown", "(", "cluster_config_file", ",", "yes", ",", "workers_only", ",", "cluster_name", ")", ":", "teardown_cluster", "(", "cluster_config_file", ",", "yes", ",", "workers_only", ",", "cluster_name", ")" ]
Tear down the Ray cluster.
[ "Tear", "down", "the", "Ray", "cluster", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/scripts/scripts.py#L482-L484
24,252
ray-project/ray
python/ray/scripts/scripts.py
kill_random_node
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))
python
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))
[ "def", "kill_random_node", "(", "cluster_config_file", ",", "yes", ",", "cluster_name", ")", ":", "click", ".", "echo", "(", "\"Killed node with IP \"", "+", "kill_node", "(", "cluster_config_file", ",", "yes", ",", "cluster_name", ")", ")" ]
Kills a random Ray node. For testing purposes only.
[ "Kills", "a", "random", "Ray", "node", ".", "For", "testing", "purposes", "only", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/scripts/scripts.py#L501-L504
24,253
ray-project/ray
python/ray/scripts/scripts.py
submit
def submit(cluster_config_file, docker, screen, tmux, stop, start, cluster_name, port_forward, script, script_args): """Uploads and runs a script on the specified cluster. The script is automatically synced to the following location: os.path.join("~", os.path.basename(script)) """ a...
python
def submit(cluster_config_file, docker, screen, tmux, stop, start, cluster_name, port_forward, script, script_args): """Uploads and runs a script on the specified cluster. The script is automatically synced to the following location: os.path.join("~", os.path.basename(script)) """ a...
[ "def", "submit", "(", "cluster_config_file", ",", "docker", ",", "screen", ",", "tmux", ",", "stop", ",", "start", ",", "cluster_name", ",", "port_forward", ",", "script", ",", "script_args", ")", ":", "assert", "not", "(", "screen", "and", "tmux", ")", ...
Uploads and runs a script on the specified cluster. The script is automatically synced to the following location: os.path.join("~", os.path.basename(script))
[ "Uploads", "and", "runs", "a", "script", "on", "the", "specified", "cluster", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/scripts/scripts.py#L590-L609
24,254
ray-project/ray
examples/resnet/resnet_model.py
ResNet.build_graph
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....
python
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....
[ "def", "build_graph", "(", "self", ")", ":", "self", ".", "global_step", "=", "tf", ".", "Variable", "(", "0", ",", "trainable", "=", "False", ")", "self", ".", "_build_model", "(", ")", "if", "self", ".", "mode", "==", "\"train\"", ":", "self", ".",...
Build a whole graph for the model.
[ "Build", "a", "whole", "graph", "for", "the", "model", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L49-L59
24,255
ray-project/ray
python/ray/rllib/agents/qmix/qmix_policy_graph.py
_mac
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 of tensors of shape [B, n_agents, h_size] Returns: q_vals: Tensor of shape [B, n_agents, n_actions] h: Ten...
python
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 of tensors of shape [B, n_agents, h_size] Returns: q_vals: Tensor of shape [B, n_agents, n_actions] h: Ten...
[ "def", "_mac", "(", "model", ",", "obs", ",", "h", ")", ":", "B", ",", "n_agents", "=", "obs", ".", "size", "(", "0", ")", ",", "obs", ".", "size", "(", "1", ")", "obs_flat", "=", "obs", ".", "reshape", "(", "[", "B", "*", "n_agents", ",", ...
Forward pass of the multi-agent controller. Arguments: model: TorchModel class obs: Tensor of shape [B, n_agents, obs_size] h: List of tensors of shape [B, n_agents, h_size] Returns: q_vals: Tensor of shape [B, n_agents, n_actions] h: Tensor of shape [B, n_agents, h_siz...
[ "Forward", "pass", "of", "the", "multi", "-", "agent", "controller", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/qmix/qmix_policy_graph.py#L409-L426
24,256
ray-project/ray
python/ray/rllib/agents/qmix/qmix_policy_graph.py
QMixLoss.forward
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] actions: Tensor of shape [B, T-1, n_agents] terminated: Tensor of shape [B, T-1, n_agents] mask: T...
python
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] actions: Tensor of shape [B, T-1, n_agents] terminated: Tensor of shape [B, T-1, n_agents] mask: T...
[ "def", "forward", "(", "self", ",", "rewards", ",", "actions", ",", "terminated", ",", "mask", ",", "obs", ",", "action_mask", ")", ":", "B", ",", "T", "=", "obs", ".", "size", "(", "0", ")", ",", "obs", ".", "size", "(", "1", ")", "# Calculate e...
Forward pass of the loss. Arguments: rewards: Tensor of shape [B, T-1, n_agents] actions: Tensor of shape [B, T-1, n_agents] terminated: Tensor of shape [B, T-1, n_agents] mask: Tensor of shape [B, T-1, n_agents] obs: Tensor of shape [B, T, n_agents, ...
[ "Forward", "pass", "of", "the", "loss", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/qmix/qmix_policy_graph.py#L49-L122
24,257
ray-project/ray
python/ray/experimental/named_actors.py
get_actor
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 named actor. Returns: The ActorHandle object corresponding to the name. """ actor_name = _calculate_key(name) pickle...
python
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 named actor. Returns: The ActorHandle object corresponding to the name. """ actor_name = _calculate_key(name) pickle...
[ "def", "get_actor", "(", "name", ")", ":", "actor_name", "=", "_calculate_key", "(", "name", ")", "pickled_state", "=", "_internal_kv_get", "(", "actor_name", ")", "if", "pickled_state", "is", "None", ":", "raise", "ValueError", "(", "\"The actor with name={} does...
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 named actor. Returns: The ActorHandle object corresponding to the name.
[ "Get", "a", "named", "actor", "which", "was", "previously", "created", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/named_actors.py#L22-L38
24,258
ray-project/ray
python/ray/experimental/named_actors.py
register_actor
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 be associated with this name """ if not isinstance(name, str): raise TypeError("The name argument must be a string.") ...
python
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 be associated with this name """ if not isinstance(name, str): raise TypeError("The name argument must be a string.") ...
[ "def", "register_actor", "(", "name", ",", "actor_handle", ")", ":", "if", "not", "isinstance", "(", "name", ",", "str", ")", ":", "raise", "TypeError", "(", "\"The name argument must be a string.\"", ")", "if", "not", "isinstance", "(", "actor_handle", ",", "...
Register a named actor under a string key. Args: name: The name of the named actor. actor_handle: The actor object to be associated with this name
[ "Register", "a", "named", "actor", "under", "a", "string", "key", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/named_actors.py#L41-L63
24,259
ray-project/ray
python/ray/autoscaler/autoscaler.py
check_extraneous
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 {}".f...
python
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 {}".f...
[ "def", "check_extraneous", "(", "config", ",", "schema", ")", ":", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"Config {} is not a dictionary\"", ".", "format", "(", "config", ")", ")", "for", "k", "in", "...
Make sure all items of config are in schema
[ "Make", "sure", "all", "items", "of", "config", "are", "in", "schema" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/autoscaler.py#L681-L701
24,260
ray-project/ray
python/ray/autoscaler/autoscaler.py
validate_config
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)
python
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)
[ "def", "validate_config", "(", "config", ",", "schema", "=", "CLUSTER_CONFIG_SCHEMA", ")", ":", "if", "not", "isinstance", "(", "config", ",", "dict", ")", ":", "raise", "ValueError", "(", "\"Config {} is not a dictionary\"", ".", "format", "(", "config", ")", ...
Required Dicts indicate that no extra fields can be introduced.
[ "Required", "Dicts", "indicate", "that", "no", "extra", "fields", "can", "be", "introduced", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/autoscaler/autoscaler.py#L704-L710
24,261
ray-project/ray
python/ray/parameter.py
RayParams.update
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:...
python
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:...
[ "def", "update", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "arg", "in", "kwargs", ":", "if", "hasattr", "(", "self", ",", "arg", ")", ":", "setattr", "(", "self", ",", "arg", ",", "kwargs", "[", "arg", "]", ")", "else", ":", "raise...
Update the settings according to the keyword arguments. Args: kwargs: The keyword arguments to set corresponding fields.
[ "Update", "the", "settings", "according", "to", "the", "keyword", "arguments", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/parameter.py#L149-L162
24,262
ray-project/ray
python/ray/parameter.py
RayParams.update_if_absent
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: ...
python
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: ...
[ "def", "update_if_absent", "(", "self", ",", "*", "*", "kwargs", ")", ":", "for", "arg", "in", "kwargs", ":", "if", "hasattr", "(", "self", ",", "arg", ")", ":", "if", "getattr", "(", "self", ",", "arg", ")", "is", "None", ":", "setattr", "(", "s...
Update the settings when the target fields are None. Args: kwargs: The keyword arguments to set corresponding fields.
[ "Update", "the", "settings", "when", "the", "target", "fields", "are", "None", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/parameter.py#L164-L178
24,263
ray-project/ray
python/ray/actor.py
compute_actor_handle_id
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 from another actor handle. The new handle ID is computed as hash(old_handle_id || num_forks). Args: actor_handle_id (common.ObjectID): ...
python
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 from another actor handle. The new handle ID is computed as hash(old_handle_id || num_forks). Args: actor_handle_id (common.ObjectID): ...
[ "def", "compute_actor_handle_id", "(", "actor_handle_id", ",", "num_forks", ")", ":", "assert", "isinstance", "(", "actor_handle_id", ",", "ActorHandleID", ")", "handle_id_hash", "=", "hashlib", ".", "sha1", "(", ")", "handle_id_hash", ".", "update", "(", "actor_h...
Deterministically compute an actor handle ID. A new actor handle ID is generated when it is forked from another actor handle. The new handle ID is computed as hash(old_handle_id || num_forks). Args: actor_handle_id (common.ObjectID): The original actor handle ID. num_forks: The number of t...
[ "Deterministically", "compute", "an", "actor", "handle", "ID", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L27-L46
24,264
ray-project/ray
python/ray/actor.py
compute_actor_handle_id_non_forked
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 is used whenever an actor handle is pickled and unpickled (for example, if a remote function closes over an actor handle). Then, whenever the ...
python
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 is used whenever an actor handle is pickled and unpickled (for example, if a remote function closes over an actor handle). Then, whenever the ...
[ "def", "compute_actor_handle_id_non_forked", "(", "actor_handle_id", ",", "current_task_id", ")", ":", "assert", "isinstance", "(", "actor_handle_id", ",", "ActorHandleID", ")", "assert", "isinstance", "(", "current_task_id", ",", "TaskID", ")", "handle_id_hash", "=", ...
Deterministically compute an actor handle ID in the non-forked case. This code path is used whenever an actor handle is pickled and unpickled (for example, if a remote function closes over an actor handle). Then, whenever the actor handle is used, a new actor handle ID will be generated on the fly as a...
[ "Deterministically", "compute", "an", "actor", "handle", "ID", "in", "the", "non", "-", "forked", "case", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L49-L75
24,265
ray-project/ray
python/ray/actor.py
method
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): return 1, 2 f = Foo.remote() _, _ = f.bar.remote() Args: num_retu...
python
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): return 1, 2 f = Foo.remote() _, _ = f.bar.remote() Args: num_retu...
[ "def", "method", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "assert", "len", "(", "args", ")", "==", "0", "assert", "len", "(", "kwargs", ")", "==", "1", "assert", "\"num_return_vals\"", "in", "kwargs", "num_return_vals", "=", "kwargs", "[", ...
Annotate an actor method. .. code-block:: python @ray.remote class Foo(object): @ray.method(num_return_vals=2) def bar(self): return 1, 2 f = Foo.remote() _, _ = f.bar.remote() Args: num_return_vals: The number of object IDs th...
[ "Annotate", "an", "actor", "method", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L78-L106
24,266
ray-project/ray
python/ray/actor.py
exit_actor
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 raised if this is a driver or this worker is not an actor. """ worker = ray.worker.global_worker if worker.mode ==...
python
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 raised if this is a driver or this worker is not an actor. """ worker = ray.worker.global_worker if worker.mode ==...
[ "def", "exit_actor", "(", ")", ":", "worker", "=", "ray", ".", "worker", ".", "global_worker", "if", "worker", ".", "mode", "==", "ray", ".", "WORKER_MODE", "and", "not", "worker", ".", "actor_id", ".", "is_nil", "(", ")", ":", "# Disconnect the worker fro...
Intentionally exit the current actor. This function is used to disconnect an actor and exit the worker. Raises: Exception: An exception is raised if this is a driver or this worker is not an actor.
[ "Intentionally", "exit", "the", "current", "actor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L736-L757
24,267
ray-project/ray
python/ray/actor.py
get_checkpoints_for_actor
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 order. """ checkpoint_info = ray.worker.global_state.actor_checkpoint_info(actor_id) if checkpoint_info is None: return [] checkpoi...
python
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 order. """ checkpoint_info = ray.worker.global_state.actor_checkpoint_info(actor_id) if checkpoint_info is None: return [] checkpoi...
[ "def", "get_checkpoints_for_actor", "(", "actor_id", ")", ":", "checkpoint_info", "=", "ray", ".", "worker", ".", "global_state", ".", "actor_checkpoint_info", "(", "actor_id", ")", "if", "checkpoint_info", "is", "None", ":", "return", "[", "]", "checkpoints", "...
Get the available checkpoints for the given actor ID, return a list sorted by checkpoint timestamp in descending order.
[ "Get", "the", "available", "checkpoints", "for", "the", "given", "actor", "ID", "return", "a", "list", "sorted", "by", "checkpoint", "timestamp", "in", "descending", "order", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L869-L884
24,268
ray-project/ray
python/ray/actor.py
ActorHandle._actor_method_call
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 executes when `actor.metho...
python
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 executes when `actor.metho...
[ "def", "_actor_method_call", "(", "self", ",", "method_name", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "num_return_vals", "=", "None", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "worker", ".", "ch...
Method execution stub for an actor handle. This is the function that executes when `actor.method_name.remote(*args, **kwargs)` is called. Instead of executing locally, the method is packaged as a task and scheduled to the remote actor instance. Args: method_name: Th...
[ "Method", "execution", "stub", "for", "an", "actor", "handle", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L442-L515
24,269
ray-project/ray
python/ray/rllib/optimizers/multi_gpu_impl.py
LocalSyncParallelOptimizer.optimize
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_device_batch_size and offset given by the batch_index argument. Updates shared model weights based on the averaged per-dev...
python
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_device_batch_size and offset given by the batch_index argument. Updates shared model weights based on the averaged per-dev...
[ "def", "optimize", "(", "self", ",", "sess", ",", "batch_index", ")", ":", "feed_dict", "=", "{", "self", ".", "_batch_index", ":", "batch_index", ",", "self", ".", "_per_device_batch_size", ":", "self", ".", "_loaded_per_device_batch_size", ",", "self", ".", ...
Run a single step of SGD. Runs a SGD step over a slice of the preloaded batch with size given by self._loaded_per_device_batch_size and offset given by the batch_index argument. Updates shared model weights based on the averaged per-device gradients. Args: ...
[ "Run", "a", "single", "step", "of", "SGD", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/multi_gpu_impl.py#L227-L258
24,270
ray-project/ray
python/ray/tune/automl/genetic_searcher.py
GeneticSearch._selection
def _selection(candidate): """Perform selection action to candidates. For example, new gene = sample_1 + the 5th bit of sample2. Args: candidate: List of candidate genes (encodings). Examples: >>> # Genes that represent 3 parameters >>> gene1 = np.a...
python
def _selection(candidate): """Perform selection action to candidates. For example, new gene = sample_1 + the 5th bit of sample2. Args: candidate: List of candidate genes (encodings). Examples: >>> # Genes that represent 3 parameters >>> gene1 = np.a...
[ "def", "_selection", "(", "candidate", ")", ":", "sample_index1", "=", "np", ".", "random", ".", "choice", "(", "len", "(", "candidate", ")", ")", "sample_index2", "=", "np", ".", "random", ".", "choice", "(", "len", "(", "candidate", ")", ")", "sample...
Perform selection action to candidates. For example, new gene = sample_1 + the 5th bit of sample2. Args: candidate: List of candidate genes (encodings). Examples: >>> # Genes that represent 3 parameters >>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0]]) ...
[ "Perform", "selection", "action", "to", "candidates", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automl/genetic_searcher.py#L140-L178
24,271
ray-project/ray
python/ray/tune/automl/genetic_searcher.py
GeneticSearch._crossover
def _crossover(candidate): """Perform crossover action to candidates. For example, new gene = 60% sample_1 + 40% sample_2. Args: candidate: List of candidate genes (encodings). Examples: >>> # Genes that represent 3 parameters >>> gene1 = np.array([...
python
def _crossover(candidate): """Perform crossover action to candidates. For example, new gene = 60% sample_1 + 40% sample_2. Args: candidate: List of candidate genes (encodings). Examples: >>> # Genes that represent 3 parameters >>> gene1 = np.array([...
[ "def", "_crossover", "(", "candidate", ")", ":", "sample_index1", "=", "np", ".", "random", ".", "choice", "(", "len", "(", "candidate", ")", ")", "sample_index2", "=", "np", ".", "random", ".", "choice", "(", "len", "(", "candidate", ")", ")", "sample...
Perform crossover action to candidates. For example, new gene = 60% sample_1 + 40% sample_2. Args: candidate: List of candidate genes (encodings). Examples: >>> # Genes that represent 3 parameters >>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0]]) ...
[ "Perform", "crossover", "action", "to", "candidates", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automl/genetic_searcher.py#L181-L220
24,272
ray-project/ray
python/ray/tune/automl/genetic_searcher.py
GeneticSearch._mutation
def _mutation(candidate, rate=0.1): """Perform mutation action to candidates. For example, randomly change 10% of original sample Args: candidate: List of candidate genes (encodings). rate: Percentage of mutation bits Examples: >>> # Genes that repr...
python
def _mutation(candidate, rate=0.1): """Perform mutation action to candidates. For example, randomly change 10% of original sample Args: candidate: List of candidate genes (encodings). rate: Percentage of mutation bits Examples: >>> # Genes that repr...
[ "def", "_mutation", "(", "candidate", ",", "rate", "=", "0.1", ")", ":", "sample_index", "=", "np", ".", "random", ".", "choice", "(", "len", "(", "candidate", ")", ")", "sample", "=", "candidate", "[", "sample_index", "]", "idx_list", "=", "[", "]", ...
Perform mutation action to candidates. For example, randomly change 10% of original sample Args: candidate: List of candidate genes (encodings). rate: Percentage of mutation bits Examples: >>> # Genes that represent 3 parameters >>> gene1 = np.a...
[ "Perform", "mutation", "action", "to", "candidates", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automl/genetic_searcher.py#L223-L258
24,273
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor._train
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...
python
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...
[ "def", "_train", "(", "self", ",", "trial", ")", ":", "assert", "trial", ".", "status", "==", "Trial", ".", "RUNNING", ",", "trial", ".", "status", "remote", "=", "trial", ".", "runner", ".", "train", ".", "remote", "(", ")", "# Local Mode", "if", "i...
Start one iteration of training and save remote id.
[ "Start", "one", "iteration", "of", "training", "and", "save", "remote", "id", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L107-L117
24,274
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor._start_trial
def _start_trial(self, trial, checkpoint=None): """Starts trial and restores last result if trial was paused. Raises: ValueError if restoring from checkpoint fails. """ prior_status = trial.status self.set_status(trial, Trial.RUNNING) trial.runner = self._set...
python
def _start_trial(self, trial, checkpoint=None): """Starts trial and restores last result if trial was paused. Raises: ValueError if restoring from checkpoint fails. """ prior_status = trial.status self.set_status(trial, Trial.RUNNING) trial.runner = self._set...
[ "def", "_start_trial", "(", "self", ",", "trial", ",", "checkpoint", "=", "None", ")", ":", "prior_status", "=", "trial", ".", "status", "self", ".", "set_status", "(", "trial", ",", "Trial", ".", "RUNNING", ")", "trial", ".", "runner", "=", "self", "....
Starts trial and restores last result if trial was paused. Raises: ValueError if restoring from checkpoint fails.
[ "Starts", "trial", "and", "restores", "last", "result", "if", "trial", "was", "paused", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L119-L143
24,275
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor._stop_trial
def _stop_trial(self, trial, error=False, error_msg=None, stop_logger=True): """Stops this trial. Stops this trial, releasing all allocating resources. If stopping the trial fails, the run will be marked as terminated in error, but no exception will be thrown. ...
python
def _stop_trial(self, trial, error=False, error_msg=None, stop_logger=True): """Stops this trial. Stops this trial, releasing all allocating resources. If stopping the trial fails, the run will be marked as terminated in error, but no exception will be thrown. ...
[ "def", "_stop_trial", "(", "self", ",", "trial", ",", "error", "=", "False", ",", "error_msg", "=", "None", ",", "stop_logger", "=", "True", ")", ":", "if", "stop_logger", ":", "trial", ".", "close_logger", "(", ")", "if", "error", ":", "self", ".", ...
Stops this trial. Stops this trial, releasing all allocating resources. If stopping the trial fails, the run will be marked as terminated in error, but no exception will be thrown. Args: error (bool): Whether to mark this trial as terminated in error. error_msg ...
[ "Stops", "this", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L145-L186
24,276
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.start_trial
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 be started. checkpoint (Checkpoint): A Python object or path storing the state of trial. ...
python
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 be started. checkpoint (Checkpoint): A Python object or path storing the state of trial. ...
[ "def", "start_trial", "(", "self", ",", "trial", ",", "checkpoint", "=", "None", ")", ":", "self", ".", "_commit_resources", "(", "trial", ".", "resources", ")", "try", ":", "self", ".", "_start_trial", "(", "trial", ",", "checkpoint", ")", "except", "Ex...
Starts the trial. Will not return resources if trial repeatedly fails on start. Args: trial (Trial): Trial to be started. checkpoint (Checkpoint): A Python object or path storing the state of trial.
[ "Starts", "the", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L188-L221
24,277
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.stop_trial
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: ...
python
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: ...
[ "def", "stop_trial", "(", "self", ",", "trial", ",", "error", "=", "False", ",", "error_msg", "=", "None", ",", "stop_logger", "=", "True", ")", ":", "prior_status", "=", "trial", ".", "status", "self", ".", "_stop_trial", "(", "trial", ",", "error", "...
Only returns resources if resources allocated.
[ "Only", "returns", "resources", "if", "resources", "allocated", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L229-L239
24,278
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.fetch_result
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...
python
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...
[ "def", "fetch_result", "(", "self", ",", "trial", ")", ":", "trial_future", "=", "self", ".", "_find_item", "(", "self", ".", "_running", ",", "trial", ")", "if", "not", "trial_future", ":", "raise", "ValueError", "(", "\"Trial was not running.\"", ")", "sel...
Fetches one result of the running trials. Returns: Result of the most recent trial training run.
[ "Fetches", "one", "result", "of", "the", "running", "trials", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L305-L320
24,279
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.has_resources
def has_resources(self, resources): """Returns whether this runner has at least the specified resources. This refreshes the Ray cluster resources if the time since last update has exceeded self._refresh_period. This also assumes that the cluster is not resizing very frequently. ...
python
def has_resources(self, resources): """Returns whether this runner has at least the specified resources. This refreshes the Ray cluster resources if the time since last update has exceeded self._refresh_period. This also assumes that the cluster is not resizing very frequently. ...
[ "def", "has_resources", "(", "self", ",", "resources", ")", ":", "if", "time", ".", "time", "(", ")", "-", "self", ".", "_last_resource_refresh", ">", "self", ".", "_refresh_period", ":", "self", ".", "_update_avail_resources", "(", ")", "currently_available",...
Returns whether this runner has at least the specified resources. This refreshes the Ray cluster resources if the time since last update has exceeded self._refresh_period. This also assumes that the cluster is not resizing very frequently.
[ "Returns", "whether", "this", "runner", "has", "at", "least", "the", "specified", "resources", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L389-L430
24,280
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.resource_string
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_re...
python
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_re...
[ "def", "resource_string", "(", "self", ")", ":", "if", "self", ".", "_resources_initialized", ":", "res_str", "=", "\"{} CPUs, {} GPUs\"", ".", "format", "(", "self", ".", "_avail_resources", ".", "cpu", ",", "self", ".", "_avail_resources", ".", "gpu", ")", ...
Returns a string describing the total resources available.
[ "Returns", "a", "string", "describing", "the", "total", "resources", "available", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L451-L465
24,281
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.save
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()...
python
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()...
[ "def", "save", "(", "self", ",", "trial", ",", "storage", "=", "Checkpoint", ".", "DISK", ")", ":", "trial", ".", "_checkpoint", ".", "storage", "=", "storage", "trial", ".", "_checkpoint", ".", "last_result", "=", "trial", ".", "last_result", "if", "sto...
Saves the trial's state to a checkpoint.
[ "Saves", "the", "trial", "s", "state", "to", "a", "checkpoint", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L471-L497
24,282
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.export_trial_if_needed
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 exported models. """ if trial.export_formats and len(trial.export_formats) > 0: return ray.get( ...
python
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 exported models. """ if trial.export_formats and len(trial.export_formats) > 0: return ray.get( ...
[ "def", "export_trial_if_needed", "(", "self", ",", "trial", ")", ":", "if", "trial", ".", "export_formats", "and", "len", "(", "trial", ".", "export_formats", ")", ">", "0", ":", "return", "ray", ".", "get", "(", "trial", ".", "runner", ".", "export_mode...
Exports model of this trial based on trial.export_formats. Return: A dict that maps ExportFormats to successfully exported models.
[ "Exports", "model", "of", "this", "trial", "based", "on", "trial", ".", "export_formats", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L547-L556
24,283
ray-project/ray
python/ray/experimental/streaming/streaming.py
Environment.__generate_actor
def __generate_actor(self, instance_id, operator, input, output): """Generates an actor that will execute a particular instance of the logical operator Attributes: instance_id (UUID): The id of the instance the actor will execute. operator (Operator): The metadata of the...
python
def __generate_actor(self, instance_id, operator, input, output): """Generates an actor that will execute a particular instance of the logical operator Attributes: instance_id (UUID): The id of the instance the actor will execute. operator (Operator): The metadata of the...
[ "def", "__generate_actor", "(", "self", ",", "instance_id", ",", "operator", ",", "input", ",", "output", ")", ":", "actor_id", "=", "(", "operator", ".", "id", ",", "instance_id", ")", "# Record the physical dataflow graph (for debugging purposes)", "self", ".", ...
Generates an actor that will execute a particular instance of the logical operator Attributes: instance_id (UUID): The id of the instance the actor will execute. operator (Operator): The metadata of the logical operator. input (DataInput): The input gate that manages...
[ "Generates", "an", "actor", "that", "will", "execute", "a", "particular", "instance", "of", "the", "logical", "operator" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L96-L169
24,284
ray-project/ray
python/ray/experimental/streaming/streaming.py
Environment.__generate_actors
def __generate_actors(self, operator, upstream_channels, downstream_channels): """Generates one actor for each instance of the given logical operator. Attributes: operator (Operator): The logical operator metadata. upstream_channels (list): A li...
python
def __generate_actors(self, operator, upstream_channels, downstream_channels): """Generates one actor for each instance of the given logical operator. Attributes: operator (Operator): The logical operator metadata. upstream_channels (list): A li...
[ "def", "__generate_actors", "(", "self", ",", "operator", ",", "upstream_channels", ",", "downstream_channels", ")", ":", "num_instances", "=", "operator", ".", "num_instances", "logger", ".", "info", "(", "\"Generating {} actors of type {}...\"", ".", "format", "(", ...
Generates one actor for each instance of the given logical operator. Attributes: operator (Operator): The logical operator metadata. upstream_channels (list): A list of all upstream channels for all instances of the operator. downstream_channels (list): A...
[ "Generates", "one", "actor", "for", "each", "instance", "of", "the", "given", "logical", "operator", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L173-L210
24,285
ray-project/ray
python/ray/experimental/streaming/streaming.py
Environment.execute
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 downstre...
python
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 downstre...
[ "def", "execute", "(", "self", ")", ":", "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 insta...
Deploys and executes the physical dataflow.
[ "Deploys", "and", "executes", "the", "physical", "dataflow", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L306-L332
24,286
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.set_parallelism
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 parallelism for the source operator of the stream. """ assert (num_instances > 0) self.env._se...
python
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 parallelism for the source operator of the stream. """ assert (num_instances > 0) self.env._se...
[ "def", "set_parallelism", "(", "self", ",", "num_instances", ")", ":", "assert", "(", "num_instances", ">", "0", ")", "self", ".", "env", ".", "_set_parallelism", "(", "self", ".", "src_operator_id", ",", "num_instances", ")", "return", "self" ]
Sets the number of instances for the source operator of the stream. Attributes: num_instances (int): The level of parallelism for the source operator of the stream.
[ "Sets", "the", "number", "of", "instances", "for", "the", "source", "operator", "of", "the", "stream", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L467-L476
24,287
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.map
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_insta...
python
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_insta...
[ "def", "map", "(", "self", ",", "map_fn", ",", "name", "=", "\"Map\"", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "Map", ",", "name", ",", "map_fn", ",", "num_instances", "=", "self", ".", "env", ".", "con...
Applies a map operator to the stream. Attributes: map_fn (function): The user-defined logic of the map.
[ "Applies", "a", "map", "operator", "to", "the", "stream", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L521-L533
24,288
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.flat_map
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. split()). """ op = Operator( _generate_uuid(), OpType.FlatMap, "FlatM...
python
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. split()). """ op = Operator( _generate_uuid(), OpType.FlatMap, "FlatM...
[ "def", "flat_map", "(", "self", ",", "flatmap_fn", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "FlatMap", ",", "\"FlatMap\"", ",", "flatmap_fn", ",", "num_instances", "=", "self", ".", "env", ".", "config", ".", ...
Applies a flatmap operator to the stream. Attributes: flatmap_fn (function): The user-defined logic of the flatmap (e.g. split()).
[ "Applies", "a", "flatmap", "operator", "to", "the", "stream", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L536-L549
24,289
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.key_by
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 tuple records). """ op = Operator( _generate_uuid(), OpType.KeyBy, "...
python
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 tuple records). """ op = Operator( _generate_uuid(), OpType.KeyBy, "...
[ "def", "key_by", "(", "self", ",", "key_selector", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "KeyBy", ",", "\"KeyBy\"", ",", "other", "=", "key_selector", ",", "num_instances", "=", "self", ".", "env", ".", "...
Applies a key_by operator to the stream. Attributes: key_attribute_index (int): The index of the key attributed (assuming tuple records).
[ "Applies", "a", "key_by", "operator", "to", "the", "stream", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L553-L566
24,290
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.time_window
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", nu...
python
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", nu...
[ "def", "time_window", "(", "self", ",", "window_width_ms", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "TimeWindow", ",", "\"TimeWindow\"", ",", "num_instances", "=", "self", ".", "env", ".", "config", ".", "parall...
Applies a system time window to the stream. Attributes: window_width_ms (int): The length of the window in ms.
[ "Applies", "a", "system", "time", "window", "to", "the", "stream", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L605-L617
24,291
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.filter
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_insta...
python
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_insta...
[ "def", "filter", "(", "self", ",", "filter_fn", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "Filter", ",", "\"Filter\"", ",", "filter_fn", ",", "num_instances", "=", "self", ".", "env", ".", "config", ".", "par...
Applies a filter to the stream. Attributes: filter_fn (function): The user-defined filter function.
[ "Applies", "a", "filter", "to", "the", "stream", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L620-L632
24,292
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.inspect
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, ...
python
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, ...
[ "def", "inspect", "(", "self", ",", "inspect_logic", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "Inspect", ",", "\"Inspect\"", ",", "inspect_logic", ",", "num_instances", "=", "self", ".", "env", ".", "config", ...
Inspects the content of the stream. Attributes: inspect_logic (function): The user-defined inspect function.
[ "Inspects", "the", "content", "of", "the", "stream", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L644-L656
24,293
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.sink
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)
python
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)
[ "def", "sink", "(", "self", ")", ":", "op", "=", "Operator", "(", "_generate_uuid", "(", ")", ",", "OpType", ".", "Sink", ",", "\"Sink\"", ",", "num_instances", "=", "self", ".", "env", ".", "config", ".", "parallelism", ")", "return", "self", ".", "...
Closes the stream with a sink operator.
[ "Closes", "the", "stream", "with", "a", "sink", "operator", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L661-L668
24,294
ray-project/ray
python/ray/log_monitor.py
LogMonitor.update_log_filenames
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....
python
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....
[ "def", "update_log_filenames", "(", "self", ")", ":", "log_filenames", "=", "os", ".", "listdir", "(", "self", ".", "logs_dir", ")", "for", "log_filename", "in", "log_filenames", ":", "full_path", "=", "os", ".", "path", ".", "join", "(", "self", ".", "l...
Update the list of log files to monitor.
[ "Update", "the", "list", "of", "log", "files", "to", "monitor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/log_monitor.py#L90-L104
24,295
ray-project/ray
python/ray/log_monitor.py
LogMonitor.open_closed_files
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. s...
python
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. s...
[ "def", "open_closed_files", "(", "self", ")", ":", "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", "("...
Open some closed files if they may have new lines. Opening more files may require us to close some of the already open files.
[ "Open", "some", "closed", "files", "if", "they", "may", "have", "new", "lines", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/log_monitor.py#L106-L160
24,296
ray-project/ray
python/ray/log_monitor.py
LogMonitor.run
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 in Redis. """ while True: self.update_log_filenames() self.open_closed_files() an...
python
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 in Redis. """ while True: self.update_log_filenames() self.open_closed_files() an...
[ "def", "run", "(", "self", ")", ":", "while", "True", ":", "self", ".", "update_log_filenames", "(", ")", "self", ".", "open_closed_files", "(", ")", "anything_published", "=", "self", ".", "check_log_files_and_publish_updates", "(", ")", "# If nothing was publish...
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 in Redis.
[ "Run", "the", "log", "monitor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/log_monitor.py#L210-L223
24,297
ray-project/ray
python/ray/tune/suggest/suggestion.py
SuggestionAlgorithm.add_configurations
def add_configurations(self, experiments): """Chains generator given experiment specifications. Arguments: experiments (Experiment | list | dict): Experiments to run. """ experiment_list = convert_to_experiment_list(experiments) for experiment in experiment_list: ...
python
def add_configurations(self, experiments): """Chains generator given experiment specifications. Arguments: experiments (Experiment | list | dict): Experiments to run. """ experiment_list = convert_to_experiment_list(experiments) for experiment in experiment_list: ...
[ "def", "add_configurations", "(", "self", ",", "experiments", ")", ":", "experiment_list", "=", "convert_to_experiment_list", "(", "experiments", ")", "for", "experiment", "in", "experiment_list", ":", "self", ".", "_trial_generator", "=", "itertools", ".", "chain",...
Chains generator given experiment specifications. Arguments: experiments (Experiment | list | dict): Experiments to run.
[ "Chains", "generator", "given", "experiment", "specifications", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/suggestion.py#L43-L53
24,298
ray-project/ray
python/ray/tune/suggest/suggestion.py
SuggestionAlgorithm.next_trials
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: trials (list): Returns a list of trials. """ trials = [] for trial in self._trial_generator: ...
python
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: trials (list): Returns a list of trials. """ trials = [] for trial in self._trial_generator: ...
[ "def", "next_trials", "(", "self", ")", ":", "trials", "=", "[", "]", "for", "trial", "in", "self", ".", "_trial_generator", ":", "if", "trial", "is", "None", ":", "return", "trials", "trials", "+=", "[", "trial", "]", "self", ".", "_finished", "=", ...
Provides a batch of Trial objects to be queued into the TrialRunner. A batch ends when self._trial_generator returns None. Returns: trials (list): Returns a list of trials.
[ "Provides", "a", "batch", "of", "Trial", "objects", "to", "be", "queued", "into", "the", "TrialRunner", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/suggestion.py#L55-L71
24,299
ray-project/ray
python/ray/tune/suggest/suggestion.py
SuggestionAlgorithm._generate_trials
def _generate_trials(self, experiment_spec, output_path=""): """Generates trials with configurations from `_suggest`. Creates a trial_id that is passed into `_suggest`. Yields: Trial objects constructed according to `spec` """ if "run" not in experiment_spec: ...
python
def _generate_trials(self, experiment_spec, output_path=""): """Generates trials with configurations from `_suggest`. Creates a trial_id that is passed into `_suggest`. Yields: Trial objects constructed according to `spec` """ if "run" not in experiment_spec: ...
[ "def", "_generate_trials", "(", "self", ",", "experiment_spec", ",", "output_path", "=", "\"\"", ")", ":", "if", "\"run\"", "not", "in", "experiment_spec", ":", "raise", "TuneError", "(", "\"Must specify `run` in {}\"", ".", "format", "(", "experiment_spec", ")", ...
Generates trials with configurations from `_suggest`. Creates a trial_id that is passed into `_suggest`. Yields: Trial objects constructed according to `spec`
[ "Generates", "trials", "with", "configurations", "from", "_suggest", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/suggest/suggestion.py#L73-L102