repo
stringlengths
7
55
path
stringlengths
4
223
func_name
stringlengths
1
134
original_string
stringlengths
75
104k
language
stringclasses
1 value
code
stringlengths
75
104k
code_tokens
listlengths
19
28.4k
docstring
stringlengths
1
46.9k
docstring_tokens
listlengths
1
1.97k
sha
stringlengths
40
40
url
stringlengths
87
315
partition
stringclasses
1 value
slundberg/shap
shap/benchmark/models.py
cric__lasso
def cric__lasso(): """ Lasso Regression """ model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
python
def cric__lasso(): """ Lasso Regression """ model = sklearn.linear_model.LogisticRegression(penalty="l1", C=0.002) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
[ "def", "cric__lasso", "(", ")", ":", "model", "=", "sklearn", ".", "linear_model", ".", "LogisticRegression", "(", "penalty", "=", "\"l1\"", ",", "C", "=", "0.002", ")", "# we want to explain the raw probability outputs of the trees", "model", ".", "predict", "=", ...
Lasso Regression
[ "Lasso", "Regression" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L133-L141
train
slundberg/shap
shap/benchmark/models.py
cric__ridge
def cric__ridge(): """ Ridge Regression """ model = sklearn.linear_model.LogisticRegression(penalty="l2") # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
python
def cric__ridge(): """ Ridge Regression """ model = sklearn.linear_model.LogisticRegression(penalty="l2") # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
[ "def", "cric__ridge", "(", ")", ":", "model", "=", "sklearn", ".", "linear_model", ".", "LogisticRegression", "(", "penalty", "=", "\"l2\"", ")", "# we want to explain the raw probability outputs of the trees", "model", ".", "predict", "=", "lambda", "X", ":", "mode...
Ridge Regression
[ "Ridge", "Regression" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L143-L151
train
slundberg/shap
shap/benchmark/models.py
cric__decision_tree
def cric__decision_tree(): """ Decision Tree """ model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
python
def cric__decision_tree(): """ Decision Tree """ model = sklearn.tree.DecisionTreeClassifier(random_state=0, max_depth=4) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
[ "def", "cric__decision_tree", "(", ")", ":", "model", "=", "sklearn", ".", "tree", ".", "DecisionTreeClassifier", "(", "random_state", "=", "0", ",", "max_depth", "=", "4", ")", "# we want to explain the raw probability outputs of the trees", "model", ".", "predict", ...
Decision Tree
[ "Decision", "Tree" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L153-L161
train
slundberg/shap
shap/benchmark/models.py
cric__random_forest
def cric__random_forest(): """ Random Forest """ model = sklearn.ensemble.RandomForestClassifier(100, random_state=0) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
python
def cric__random_forest(): """ Random Forest """ model = sklearn.ensemble.RandomForestClassifier(100, random_state=0) # we want to explain the raw probability outputs of the trees model.predict = lambda X: model.predict_proba(X)[:,1] return model
[ "def", "cric__random_forest", "(", ")", ":", "model", "=", "sklearn", ".", "ensemble", ".", "RandomForestClassifier", "(", "100", ",", "random_state", "=", "0", ")", "# we want to explain the raw probability outputs of the trees", "model", ".", "predict", "=", "lambda...
Random Forest
[ "Random", "Forest" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L163-L171
train
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
train
slundberg/shap
shap/benchmark/models.py
human__decision_tree
def human__decision_tree(): """ Decision Tree """ # build data N = 1000000 M = 3 X = np.zeros((N,M)) X.shape y = np.zeros(N) X[0, 0] = 1 y[0] = 8 X[1, 1] = 1 y[1] = 8 X[2, 0:2] = 1 y[2] = 4 # fit model xor_model = sklearn.tree.DecisionTreeRegressor(max_d...
python
def human__decision_tree(): """ Decision Tree """ # build data N = 1000000 M = 3 X = np.zeros((N,M)) X.shape y = np.zeros(N) X[0, 0] = 1 y[0] = 8 X[1, 1] = 1 y[1] = 8 X[2, 0:2] = 1 y[2] = 4 # fit model xor_model = sklearn.tree.DecisionTreeRegressor(max_d...
[ "def", "human__decision_tree", "(", ")", ":", "# build data", "N", "=", "1000000", "M", "=", "3", "X", "=", "np", ".", "zeros", "(", "(", "N", ",", "M", ")", ")", "X", ".", "shape", "y", "=", "np", ".", "zeros", "(", "N", ")", "X", "[", "0", ...
Decision Tree
[ "Decision", "Tree" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/models.py#L209-L230
train
slundberg/shap
shap/plots/summary.py
summary_plot
def summary_plot(shap_values, features=None, feature_names=None, max_display=None, plot_type="dot", color=None, axis_color="#333333", title=None, alpha=1, show=True, sort=True, color_bar=True, auto_size_plot=True, layered_violin_max_num_bins=20, class_names=None): """Create a SHAP ...
python
def summary_plot(shap_values, features=None, feature_names=None, max_display=None, plot_type="dot", color=None, axis_color="#333333", title=None, alpha=1, show=True, sort=True, color_bar=True, auto_size_plot=True, layered_violin_max_num_bins=20, class_names=None): """Create a SHAP ...
[ "def", "summary_plot", "(", "shap_values", ",", "features", "=", "None", ",", "feature_names", "=", "None", ",", "max_display", "=", "None", ",", "plot_type", "=", "\"dot\"", ",", "color", "=", "None", ",", "axis_color", "=", "\"#333333\"", ",", "title", "...
Create a SHAP summary plot, colored by feature values when they are provided. Parameters ---------- shap_values : numpy.array Matrix of SHAP values (# samples x # features) features : numpy.array or pandas.DataFrame or list Matrix of feature values (# samples x # features) or a feature...
[ "Create", "a", "SHAP", "summary", "plot", "colored", "by", "feature", "values", "when", "they", "are", "provided", "." ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/plots/summary.py#L18-L409
train
slundberg/shap
shap/benchmark/methods.py
kernel_shap_1000_meanref
def kernel_shap_1000_meanref(model, data): """ Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid """ return lambda X: KernelExplainer(model.predict, kmeans(data, 1)).shap_values(X, nsamples=1000, l1_reg=0)
python
def kernel_shap_1000_meanref(model, data): """ Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid """ return lambda X: KernelExplainer(model.predict, kmeans(data, 1)).shap_values(X, nsamples=1000, l1_reg=0)
[ "def", "kernel_shap_1000_meanref", "(", "model", ",", "data", ")", ":", "return", "lambda", "X", ":", "KernelExplainer", "(", "model", ".", "predict", ",", "kmeans", "(", "data", ",", "1", ")", ")", ".", "shap_values", "(", "X", ",", "nsamples", "=", "...
Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid
[ "Kernel", "SHAP", "1000", "mean", "ref", ".", "color", "=", "red_blue_circle", "(", "0", ".", "5", ")", "linestyle", "=", "solid" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L35-L40
train
slundberg/shap
shap/benchmark/methods.py
sampling_shap_1000
def sampling_shap_1000(model, data): """ IME 1000 color = red_blue_circle(0.5) linestyle = dashed """ return lambda X: SamplingExplainer(model.predict, data).shap_values(X, nsamples=1000)
python
def sampling_shap_1000(model, data): """ IME 1000 color = red_blue_circle(0.5) linestyle = dashed """ return lambda X: SamplingExplainer(model.predict, data).shap_values(X, nsamples=1000)
[ "def", "sampling_shap_1000", "(", "model", ",", "data", ")", ":", "return", "lambda", "X", ":", "SamplingExplainer", "(", "model", ".", "predict", ",", "data", ")", ".", "shap_values", "(", "X", ",", "nsamples", "=", "1000", ")" ]
IME 1000 color = red_blue_circle(0.5) linestyle = dashed
[ "IME", "1000", "color", "=", "red_blue_circle", "(", "0", ".", "5", ")", "linestyle", "=", "dashed" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L42-L47
train
slundberg/shap
shap/benchmark/methods.py
tree_shap_independent_200
def tree_shap_independent_200(model, data): """ TreeExplainer (independent) color = red_blue_circle(0) linestyle = dashed """ data_subsample = sklearn.utils.resample(data, replace=False, n_samples=min(200, data.shape[0]), random_state=0) return TreeExplainer(model, data_subsample, feature_depend...
python
def tree_shap_independent_200(model, data): """ TreeExplainer (independent) color = red_blue_circle(0) linestyle = dashed """ data_subsample = sklearn.utils.resample(data, replace=False, n_samples=min(200, data.shape[0]), random_state=0) return TreeExplainer(model, data_subsample, feature_depend...
[ "def", "tree_shap_independent_200", "(", "model", ",", "data", ")", ":", "data_subsample", "=", "sklearn", ".", "utils", ".", "resample", "(", "data", ",", "replace", "=", "False", ",", "n_samples", "=", "min", "(", "200", ",", "data", ".", "shape", "[",...
TreeExplainer (independent) color = red_blue_circle(0) linestyle = dashed
[ "TreeExplainer", "(", "independent", ")", "color", "=", "red_blue_circle", "(", "0", ")", "linestyle", "=", "dashed" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L56-L62
train
slundberg/shap
shap/benchmark/methods.py
mean_abs_tree_shap
def mean_abs_tree_shap(model, data): """ mean(|TreeExplainer|) color = red_blue_circle(0.25) linestyle = solid """ def f(X): v = TreeExplainer(model).shap_values(X) if isinstance(v, list): return [np.tile(np.abs(sv).mean(0), (X.shape[0], 1)) for sv in v] else: ...
python
def mean_abs_tree_shap(model, data): """ mean(|TreeExplainer|) color = red_blue_circle(0.25) linestyle = solid """ def f(X): v = TreeExplainer(model).shap_values(X) if isinstance(v, list): return [np.tile(np.abs(sv).mean(0), (X.shape[0], 1)) for sv in v] else: ...
[ "def", "mean_abs_tree_shap", "(", "model", ",", "data", ")", ":", "def", "f", "(", "X", ")", ":", "v", "=", "TreeExplainer", "(", "model", ")", ".", "shap_values", "(", "X", ")", "if", "isinstance", "(", "v", ",", "list", ")", ":", "return", "[", ...
mean(|TreeExplainer|) color = red_blue_circle(0.25) linestyle = solid
[ "mean", "(", "|TreeExplainer|", ")", "color", "=", "red_blue_circle", "(", "0", ".", "25", ")", "linestyle", "=", "solid" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L64-L75
train
slundberg/shap
shap/benchmark/methods.py
saabas
def saabas(model, data): """ Saabas color = red_blue_circle(0) linestyle = dotted """ return lambda X: TreeExplainer(model).shap_values(X, approximate=True)
python
def saabas(model, data): """ Saabas color = red_blue_circle(0) linestyle = dotted """ return lambda X: TreeExplainer(model).shap_values(X, approximate=True)
[ "def", "saabas", "(", "model", ",", "data", ")", ":", "return", "lambda", "X", ":", "TreeExplainer", "(", "model", ")", ".", "shap_values", "(", "X", ",", "approximate", "=", "True", ")" ]
Saabas color = red_blue_circle(0) linestyle = dotted
[ "Saabas", "color", "=", "red_blue_circle", "(", "0", ")", "linestyle", "=", "dotted" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L77-L82
train
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
train
slundberg/shap
shap/benchmark/methods.py
deep_shap
def deep_shap(model, data): """ Deep SHAP (DeepLIFT) """ if isinstance(model, KerasWrap): model = model.model explainer = DeepExplainer(model, kmeans(data, 1).data) def f(X): phi = explainer.shap_values(X) if type(phi) is list and len(phi) == 1: return phi[0] ...
python
def deep_shap(model, data): """ Deep SHAP (DeepLIFT) """ if isinstance(model, KerasWrap): model = model.model explainer = DeepExplainer(model, kmeans(data, 1).data) def f(X): phi = explainer.shap_values(X) if type(phi) is list and len(phi) == 1: return phi[0] ...
[ "def", "deep_shap", "(", "model", ",", "data", ")", ":", "if", "isinstance", "(", "model", ",", "KerasWrap", ")", ":", "model", "=", "model", ".", "model", "explainer", "=", "DeepExplainer", "(", "model", ",", "kmeans", "(", "data", ",", "1", ")", "....
Deep SHAP (DeepLIFT)
[ "Deep", "SHAP", "(", "DeepLIFT", ")" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L96-L109
train
slundberg/shap
shap/benchmark/methods.py
expected_gradients
def expected_gradients(model, data): """ Expected Gradients """ if isinstance(model, KerasWrap): model = model.model explainer = GradientExplainer(model, data) def f(X): phi = explainer.shap_values(X) if type(phi) is list and len(phi) == 1: return phi[0] e...
python
def expected_gradients(model, data): """ Expected Gradients """ if isinstance(model, KerasWrap): model = model.model explainer = GradientExplainer(model, data) def f(X): phi = explainer.shap_values(X) if type(phi) is list and len(phi) == 1: return phi[0] e...
[ "def", "expected_gradients", "(", "model", ",", "data", ")", ":", "if", "isinstance", "(", "model", ",", "KerasWrap", ")", ":", "model", "=", "model", ".", "model", "explainer", "=", "GradientExplainer", "(", "model", ",", "data", ")", "def", "f", "(", ...
Expected Gradients
[ "Expected", "Gradients" ]
b280cb81d498b9d98565cad8dd16fc88ae52649f
https://github.com/slundberg/shap/blob/b280cb81d498b9d98565cad8dd16fc88ae52649f/shap/benchmark/methods.py#L111-L124
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
ray-project/ray
python/ray/rllib/models/preprocessors.py
GenericPixelPreprocessor.transform
def transform(self, observation): """Downsamples images from (210, 160, 3) by the configured factor.""" self.check_shape(observation) scaled = observation[25:-25, :, :] if self._dim < 84: scaled = cv2.resize(scaled, (84, 84)) # OpenAI: Resize by half, then down to 42x...
python
def transform(self, observation): """Downsamples images from (210, 160, 3) by the configured factor.""" self.check_shape(observation) scaled = observation[25:-25, :, :] if self._dim < 84: scaled = cv2.resize(scaled, (84, 84)) # OpenAI: Resize by half, then down to 42x...
[ "def", "transform", "(", "self", ",", "observation", ")", ":", "self", ".", "check_shape", "(", "observation", ")", "scaled", "=", "observation", "[", "25", ":", "-", "25", ",", ":", ",", ":", "]", "if", "self", ".", "_dim", "<", "84", ":", "scaled...
Downsamples images from (210, 160, 3) by the configured factor.
[ "Downsamples", "images", "from", "(", "210", "160", "3", ")", "by", "the", "configured", "factor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/models/preprocessors.py#L105-L124
train
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
train
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
train
ray-project/ray
python/ray/tune/trainable.py
Trainable.delete_checkpoint
def delete_checkpoint(self, checkpoint_dir): """Removes subdirectory within checkpoint_folder Parameters ---------- checkpoint_dir : path to checkpoint """ if os.path.isfile(checkpoint_dir): shutil.rmtree(os.path.dirname(checkpoint_dir)) else: ...
python
def delete_checkpoint(self, checkpoint_dir): """Removes subdirectory within checkpoint_folder Parameters ---------- checkpoint_dir : path to checkpoint """ if os.path.isfile(checkpoint_dir): shutil.rmtree(os.path.dirname(checkpoint_dir)) else: ...
[ "def", "delete_checkpoint", "(", "self", ",", "checkpoint_dir", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "checkpoint_dir", ")", ":", "shutil", ".", "rmtree", "(", "os", ".", "path", ".", "dirname", "(", "checkpoint_dir", ")", ")", "else", ...
Removes subdirectory within checkpoint_folder Parameters ---------- checkpoint_dir : path to checkpoint
[ "Removes", "subdirectory", "within", "checkpoint_folder", "Parameters", "----------", "checkpoint_dir", ":", "path", "to", "checkpoint" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L213-L222
train
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
train
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
train
ray-project/ray
python/ray/tune/trainable.py
Trainable.restore
def restore(self, checkpoint_path): """Restores training state from a given model checkpoint. These checkpoints are returned from calls to save(). Subclasses should override ``_restore()`` instead to restore state. This method restores additional metadata saved with the checkpoint. ...
python
def restore(self, checkpoint_path): """Restores training state from a given model checkpoint. These checkpoints are returned from calls to save(). Subclasses should override ``_restore()`` instead to restore state. This method restores additional metadata saved with the checkpoint. ...
[ "def", "restore", "(", "self", ",", "checkpoint_path", ")", ":", "with", "open", "(", "checkpoint_path", "+", "\".tune_metadata\"", ",", "\"rb\"", ")", "as", "f", ":", "metadata", "=", "pickle", ".", "load", "(", "f", ")", "self", ".", "_experiment_id", ...
Restores training state from a given model checkpoint. These checkpoints are returned from calls to save(). Subclasses should override ``_restore()`` instead to restore state. This method restores additional metadata saved with the checkpoint.
[ "Restores", "training", "state", "from", "a", "given", "model", "checkpoint", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/trainable.py#L306-L332
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
ray-project/ray
examples/resnet/resnet_model.py
ResNet._build_model
def _build_model(self): """Build the core model within the graph.""" with tf.variable_scope("init"): x = self._conv("init_conv", self._images, 3, 3, 16, self._stride_arr(1)) strides = [1, 2, 2] activate_before_residual = [True, False, False] ...
python
def _build_model(self): """Build the core model within the graph.""" with tf.variable_scope("init"): x = self._conv("init_conv", self._images, 3, 3, 16, self._stride_arr(1)) strides = [1, 2, 2] activate_before_residual = [True, False, False] ...
[ "def", "_build_model", "(", "self", ")", ":", "with", "tf", ".", "variable_scope", "(", "\"init\"", ")", ":", "x", "=", "self", ".", "_conv", "(", "\"init_conv\"", ",", "self", ".", "_images", ",", "3", ",", "3", ",", "16", ",", "self", ".", "_stri...
Build the core model within the graph.
[ "Build", "the", "core", "model", "within", "the", "graph", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L65-L120
train
ray-project/ray
examples/resnet/resnet_model.py
ResNet._build_train_op
def _build_train_op(self): """Build training specific ops for the graph.""" num_gpus = self.hps.num_gpus if self.hps.num_gpus != 0 else 1 # The learning rate schedule is dependent on the number of gpus. boundaries = [int(20000 * i / np.sqrt(num_gpus)) for i in range(2, 5)] values...
python
def _build_train_op(self): """Build training specific ops for the graph.""" num_gpus = self.hps.num_gpus if self.hps.num_gpus != 0 else 1 # The learning rate schedule is dependent on the number of gpus. boundaries = [int(20000 * i / np.sqrt(num_gpus)) for i in range(2, 5)] values...
[ "def", "_build_train_op", "(", "self", ")", ":", "num_gpus", "=", "self", ".", "hps", ".", "num_gpus", "if", "self", ".", "hps", ".", "num_gpus", "!=", "0", "else", "1", "# The learning rate schedule is dependent on the number of gpus.", "boundaries", "=", "[", ...
Build training specific ops for the graph.
[ "Build", "training", "specific", "ops", "for", "the", "graph", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L122-L141
train
ray-project/ray
examples/resnet/resnet_model.py
ResNet._batch_norm
def _batch_norm(self, name, x): """Batch normalization.""" with tf.variable_scope(name): params_shape = [x.get_shape()[-1]] beta = tf.get_variable( "beta", params_shape, tf.float32, initializer=tf.constant_initializ...
python
def _batch_norm(self, name, x): """Batch normalization.""" with tf.variable_scope(name): params_shape = [x.get_shape()[-1]] beta = tf.get_variable( "beta", params_shape, tf.float32, initializer=tf.constant_initializ...
[ "def", "_batch_norm", "(", "self", ",", "name", ",", "x", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "params_shape", "=", "[", "x", ".", "get_shape", "(", ")", "[", "-", "1", "]", "]", "beta", "=", "tf", ".", "get_varia...
Batch normalization.
[ "Batch", "normalization", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L143-L201
train
ray-project/ray
examples/resnet/resnet_model.py
ResNet._decay
def _decay(self): """L2 weight decay loss.""" costs = [] for var in tf.trainable_variables(): if var.op.name.find(r"DW") > 0: costs.append(tf.nn.l2_loss(var)) return tf.multiply(self.hps.weight_decay_rate, tf.add_n(costs))
python
def _decay(self): """L2 weight decay loss.""" costs = [] for var in tf.trainable_variables(): if var.op.name.find(r"DW") > 0: costs.append(tf.nn.l2_loss(var)) return tf.multiply(self.hps.weight_decay_rate, tf.add_n(costs))
[ "def", "_decay", "(", "self", ")", ":", "costs", "=", "[", "]", "for", "var", "in", "tf", ".", "trainable_variables", "(", ")", ":", "if", "var", ".", "op", ".", "name", ".", "find", "(", "r\"DW\"", ")", ">", "0", ":", "costs", ".", "append", "...
L2 weight decay loss.
[ "L2", "weight", "decay", "loss", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L281-L288
train
ray-project/ray
examples/resnet/resnet_model.py
ResNet._conv
def _conv(self, name, x, filter_size, in_filters, out_filters, strides): """Convolution.""" with tf.variable_scope(name): n = filter_size * filter_size * out_filters kernel = tf.get_variable( "DW", [filter_size, filter_size, in_filters, out_filters], ...
python
def _conv(self, name, x, filter_size, in_filters, out_filters, strides): """Convolution.""" with tf.variable_scope(name): n = filter_size * filter_size * out_filters kernel = tf.get_variable( "DW", [filter_size, filter_size, in_filters, out_filters], ...
[ "def", "_conv", "(", "self", ",", "name", ",", "x", ",", "filter_size", ",", "in_filters", ",", "out_filters", ",", "strides", ")", ":", "with", "tf", ".", "variable_scope", "(", "name", ")", ":", "n", "=", "filter_size", "*", "filter_size", "*", "out_...
Convolution.
[ "Convolution", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L290-L299
train
ray-project/ray
examples/resnet/resnet_model.py
ResNet._fully_connected
def _fully_connected(self, x, out_dim): """FullyConnected layer for final output.""" x = tf.reshape(x, [self.hps.batch_size, -1]) w = tf.get_variable( "DW", [x.get_shape()[1], out_dim], initializer=tf.uniform_unit_scaling_initializer(factor=1.0)) b = tf.get_variab...
python
def _fully_connected(self, x, out_dim): """FullyConnected layer for final output.""" x = tf.reshape(x, [self.hps.batch_size, -1]) w = tf.get_variable( "DW", [x.get_shape()[1], out_dim], initializer=tf.uniform_unit_scaling_initializer(factor=1.0)) b = tf.get_variab...
[ "def", "_fully_connected", "(", "self", ",", "x", ",", "out_dim", ")", ":", "x", "=", "tf", ".", "reshape", "(", "x", ",", "[", "self", ".", "hps", ".", "batch_size", ",", "-", "1", "]", ")", "w", "=", "tf", ".", "get_variable", "(", "\"DW\"", ...
FullyConnected layer for final output.
[ "FullyConnected", "layer", "for", "final", "output", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/examples/resnet/resnet_model.py#L305-L313
train
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
train
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
train
ray-project/ray
python/ray/rllib/agents/qmix/qmix_policy_graph.py
QMixPolicyGraph._unpack_observation
def _unpack_observation(self, obs_batch): """Unpacks the action mask / tuple obs from agent grouping. Returns: obs (Tensor): flattened obs tensor of shape [B, n_agents, obs_size] mask (Tensor): action mask, if any """ unpacked = _unpack_obs( np.array(...
python
def _unpack_observation(self, obs_batch): """Unpacks the action mask / tuple obs from agent grouping. Returns: obs (Tensor): flattened obs tensor of shape [B, n_agents, obs_size] mask (Tensor): action mask, if any """ unpacked = _unpack_obs( np.array(...
[ "def", "_unpack_observation", "(", "self", ",", "obs_batch", ")", ":", "unpacked", "=", "_unpack_obs", "(", "np", ".", "array", "(", "obs_batch", ")", ",", "self", ".", "observation_space", ".", "original_space", ",", "tensorlib", "=", "np", ")", "if", "se...
Unpacks the action mask / tuple obs from agent grouping. Returns: obs (Tensor): flattened obs tensor of shape [B, n_agents, obs_size] mask (Tensor): action mask, if any
[ "Unpacks", "the", "action", "mask", "/", "tuple", "obs", "from", "agent", "grouping", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/agents/qmix/qmix_policy_graph.py#L356-L380
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
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
train
ray-project/ray
python/ray/actor.py
ActorClass.remote
def remote(self, *args, **kwargs): """Create an actor. Args: args: These arguments are forwarded directly to the actor constructor. kwargs: These arguments are forwarded directly to the actor constructor. Returns: A handle to ...
python
def remote(self, *args, **kwargs): """Create an actor. Args: args: These arguments are forwarded directly to the actor constructor. kwargs: These arguments are forwarded directly to the actor constructor. Returns: A handle to ...
[ "def", "remote", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "_remote", "(", "args", "=", "args", ",", "kwargs", "=", "kwargs", ")" ]
Create an actor. Args: args: These arguments are forwarded directly to the actor constructor. kwargs: These arguments are forwarded directly to the actor constructor. Returns: A handle to the newly created actor.
[ "Create", "an", "actor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L222-L234
train
ray-project/ray
python/ray/actor.py
ActorClass._remote
def _remote(self, args=None, kwargs=None, num_cpus=None, num_gpus=None, resources=None): """Create an actor. This method allows more flexibility than the remote method because resource requirements can be specified ...
python
def _remote(self, args=None, kwargs=None, num_cpus=None, num_gpus=None, resources=None): """Create an actor. This method allows more flexibility than the remote method because resource requirements can be specified ...
[ "def", "_remote", "(", "self", ",", "args", "=", "None", ",", "kwargs", "=", "None", ",", "num_cpus", "=", "None", ",", "num_gpus", "=", "None", ",", "resources", "=", "None", ")", ":", "if", "args", "is", "None", ":", "args", "=", "[", "]", "if"...
Create an actor. This method allows more flexibility than the remote method because resource requirements can be specified and override the defaults in the decorator. Args: args: The arguments to forward to the actor constructor. kwargs: The keyword arguments to...
[ "Create", "an", "actor", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L236-L347
train
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
train
ray-project/ray
python/ray/actor.py
ActorHandle._serialization_helper
def _serialization_helper(self, ray_forking): """This is defined in order to make pickling work. Args: ray_forking: True if this is being called because Ray is forking the actor handle and false if it is being called by pickling. Returns: A dictionary of...
python
def _serialization_helper(self, ray_forking): """This is defined in order to make pickling work. Args: ray_forking: True if this is being called because Ray is forking the actor handle and false if it is being called by pickling. Returns: A dictionary of...
[ "def", "_serialization_helper", "(", "self", ",", "ray_forking", ")", ":", "if", "ray_forking", ":", "actor_handle_id", "=", "compute_actor_handle_id", "(", "self", ".", "_ray_actor_handle_id", ",", "self", ".", "_ray_actor_forks", ")", "else", ":", "actor_handle_id...
This is defined in order to make pickling work. Args: ray_forking: True if this is being called because Ray is forking the actor handle and false if it is being called by pickling. Returns: A dictionary of the information needed to reconstruct the object.
[ "This", "is", "defined", "in", "order", "to", "make", "pickling", "work", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L578-L629
train
ray-project/ray
python/ray/actor.py
ActorHandle._deserialization_helper
def _deserialization_helper(self, state, ray_forking): """This is defined in order to make pickling work. Args: state: The serialized state of the actor handle. ray_forking: True if this is being called because Ray is forking the actor handle and false if it is b...
python
def _deserialization_helper(self, state, ray_forking): """This is defined in order to make pickling work. Args: state: The serialized state of the actor handle. ray_forking: True if this is being called because Ray is forking the actor handle and false if it is b...
[ "def", "_deserialization_helper", "(", "self", ",", "state", ",", "ray_forking", ")", ":", "worker", "=", "ray", ".", "worker", ".", "get_global_worker", "(", ")", "worker", ".", "check_connected", "(", ")", "if", "state", "[", "\"ray_forking\"", "]", ":", ...
This is defined in order to make pickling work. Args: state: The serialized state of the actor handle. ray_forking: True if this is being called because Ray is forking the actor handle and false if it is being called by pickling.
[ "This", "is", "defined", "in", "order", "to", "make", "pickling", "work", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/actor.py#L631-L672
train
ray-project/ray
python/ray/rllib/optimizers/multi_gpu_impl.py
LocalSyncParallelOptimizer.load_data
def load_data(self, sess, inputs, state_inputs): """Bulk loads the specified inputs into device memory. The shape of the inputs must conform to the shapes of the input placeholders this optimizer was constructed with. The data is split equally across all the devices. If the data is not...
python
def load_data(self, sess, inputs, state_inputs): """Bulk loads the specified inputs into device memory. The shape of the inputs must conform to the shapes of the input placeholders this optimizer was constructed with. The data is split equally across all the devices. If the data is not...
[ "def", "load_data", "(", "self", ",", "sess", ",", "inputs", ",", "state_inputs", ")", ":", "if", "log_once", "(", "\"load_data\"", ")", ":", "logger", ".", "info", "(", "\"Training on concatenated sample batches:\\n\\n{}\\n\"", ".", "format", "(", "summarize", ...
Bulk loads the specified inputs into device memory. The shape of the inputs must conform to the shapes of the input placeholders this optimizer was constructed with. The data is split equally across all the devices. If the data is not evenly divisible by the batch size, excess data wil...
[ "Bulk", "loads", "the", "specified", "inputs", "into", "device", "memory", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/rllib/optimizers/multi_gpu_impl.py#L118-L225
train
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
train
ray-project/ray
python/ray/tune/automl/genetic_searcher.py
GeneticSearch._next_generation
def _next_generation(self, sorted_trials): """Generate genes (encodings) for the next generation. Use the top K (_keep_top_ratio) trials of the last generation as candidates to generate the next generation. The action could be selection, crossover and mutation according corresponding ...
python
def _next_generation(self, sorted_trials): """Generate genes (encodings) for the next generation. Use the top K (_keep_top_ratio) trials of the last generation as candidates to generate the next generation. The action could be selection, crossover and mutation according corresponding ...
[ "def", "_next_generation", "(", "self", ",", "sorted_trials", ")", ":", "candidate", "=", "[", "]", "next_generation", "=", "[", "]", "num_population", "=", "self", ".", "_next_population_size", "(", "len", "(", "sorted_trials", ")", ")", "top_num", "=", "in...
Generate genes (encodings) for the next generation. Use the top K (_keep_top_ratio) trials of the last generation as candidates to generate the next generation. The action could be selection, crossover and mutation according corresponding ratio (_selection_bound, _crossover_bound). ...
[ "Generate", "genes", "(", "encodings", ")", "for", "the", "next", "generation", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/automl/genetic_searcher.py#L88-L122
train
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
train
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
train
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
train
ray-project/ray
python/ray/tune/scripts.py
list_trials
def list_trials(experiment_path, sort, output, filter_op, columns, result_columns): """Lists trials in the directory subtree starting at the given path.""" if columns: columns = columns.split(",") if result_columns: result_columns = result_columns.split(",") commands.list...
python
def list_trials(experiment_path, sort, output, filter_op, columns, result_columns): """Lists trials in the directory subtree starting at the given path.""" if columns: columns = columns.split(",") if result_columns: result_columns = result_columns.split(",") commands.list...
[ "def", "list_trials", "(", "experiment_path", ",", "sort", ",", "output", ",", "filter_op", ",", "columns", ",", "result_columns", ")", ":", "if", "columns", ":", "columns", "=", "columns", ".", "split", "(", "\",\"", ")", "if", "result_columns", ":", "res...
Lists trials in the directory subtree starting at the given path.
[ "Lists", "trials", "in", "the", "directory", "subtree", "starting", "at", "the", "given", "path", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/scripts.py#L42-L50
train
ray-project/ray
python/ray/tune/scripts.py
list_experiments
def list_experiments(project_path, sort, output, filter_op, columns): """Lists experiments in the directory subtree.""" if columns: columns = columns.split(",") commands.list_experiments(project_path, sort, output, filter_op, columns)
python
def list_experiments(project_path, sort, output, filter_op, columns): """Lists experiments in the directory subtree.""" if columns: columns = columns.split(",") commands.list_experiments(project_path, sort, output, filter_op, columns)
[ "def", "list_experiments", "(", "project_path", ",", "sort", ",", "output", ",", "filter_op", ",", "columns", ")", ":", "if", "columns", ":", "columns", "=", "columns", ".", "split", "(", "\",\"", ")", "commands", ".", "list_experiments", "(", "project_path"...
Lists experiments in the directory subtree.
[ "Lists", "experiments", "in", "the", "directory", "subtree", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/scripts.py#L75-L79
train
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
train
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
train
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
train
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
train
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
train
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.pause_trial
def pause_trial(self, trial): """Pauses the trial. If trial is in-flight, preserves return value in separate queue before pausing, which is restored when Trial is resumed. """ trial_future = self._find_item(self._running, trial) if trial_future: self._paused...
python
def pause_trial(self, trial): """Pauses the trial. If trial is in-flight, preserves return value in separate queue before pausing, which is restored when Trial is resumed. """ trial_future = self._find_item(self._running, trial) if trial_future: self._paused...
[ "def", "pause_trial", "(", "self", ",", "trial", ")", ":", "trial_future", "=", "self", ".", "_find_item", "(", "self", ".", "_running", ",", "trial", ")", "if", "trial_future", ":", "self", ".", "_paused", "[", "trial_future", "[", "0", "]", "]", "=",...
Pauses the trial. If trial is in-flight, preserves return value in separate queue before pausing, which is restored when Trial is resumed.
[ "Pauses", "the", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L246-L256
train
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.reset_trial
def reset_trial(self, trial, new_config, new_experiment_tag): """Tries to invoke `Trainable.reset_config()` to reset trial. Args: trial (Trial): Trial to be reset. new_config (dict): New configuration for Trial trainable. new_experiment_tag (str): New...
python
def reset_trial(self, trial, new_config, new_experiment_tag): """Tries to invoke `Trainable.reset_config()` to reset trial. Args: trial (Trial): Trial to be reset. new_config (dict): New configuration for Trial trainable. new_experiment_tag (str): New...
[ "def", "reset_trial", "(", "self", ",", "trial", ",", "new_config", ",", "new_experiment_tag", ")", ":", "trial", ".", "experiment_tag", "=", "new_experiment_tag", "trial", ".", "config", "=", "new_config", "trainable", "=", "trial", ".", "runner", "with", "wa...
Tries to invoke `Trainable.reset_config()` to reset trial. Args: trial (Trial): Trial to be reset. new_config (dict): New configuration for Trial trainable. new_experiment_tag (str): New experiment name for trial. Returns: ...
[ "Tries", "to", "invoke", "Trainable", ".", "reset_config", "()", "to", "reset", "trial", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L258-L276
train
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
train
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
train
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.debug_string
def debug_string(self): """Returns a human readable message for printing to the console.""" if self._resources_initialized: status = "Resources requested: {}/{} CPUs, {}/{} GPUs".format( self._committed_resources.cpu, self._avail_resources.cpu, self._committe...
python
def debug_string(self): """Returns a human readable message for printing to the console.""" if self._resources_initialized: status = "Resources requested: {}/{} CPUs, {}/{} GPUs".format( self._committed_resources.cpu, self._avail_resources.cpu, self._committe...
[ "def", "debug_string", "(", "self", ")", ":", "if", "self", ".", "_resources_initialized", ":", "status", "=", "\"Resources requested: {}/{} CPUs, {}/{} GPUs\"", ".", "format", "(", "self", ".", "_committed_resources", ".", "cpu", ",", "self", ".", "_avail_resources...
Returns a human readable message for printing to the console.
[ "Returns", "a", "human", "readable", "message", "for", "printing", "to", "the", "console", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L432-L449
train
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
train
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
train
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor._checkpoint_and_erase
def _checkpoint_and_erase(self, trial): """Checkpoints the model and erases old checkpoints if needed. Parameters ---------- trial : trial to save """ with warn_if_slow("save_to_disk"): trial._checkpoint.value = ray.get(trial.runner.save.remot...
python
def _checkpoint_and_erase(self, trial): """Checkpoints the model and erases old checkpoints if needed. Parameters ---------- trial : trial to save """ with warn_if_slow("save_to_disk"): trial._checkpoint.value = ray.get(trial.runner.save.remot...
[ "def", "_checkpoint_and_erase", "(", "self", ",", "trial", ")", ":", "with", "warn_if_slow", "(", "\"save_to_disk\"", ")", ":", "trial", ".", "_checkpoint", ".", "value", "=", "ray", ".", "get", "(", "trial", ".", "runner", ".", "save", ".", "remote", "(...
Checkpoints the model and erases old checkpoints if needed. Parameters ---------- trial : trial to save
[ "Checkpoints", "the", "model", "and", "erases", "old", "checkpoints", "if", "needed", ".", "Parameters", "----------", "trial", ":", "trial", "to", "save" ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L499-L514
train
ray-project/ray
python/ray/tune/ray_trial_executor.py
RayTrialExecutor.restore
def restore(self, trial, checkpoint=None): """Restores training state from a given model checkpoint. This will also sync the trial results to a new location if restoring on a different node. """ if checkpoint is None or checkpoint.value is None: checkpoint = trial._c...
python
def restore(self, trial, checkpoint=None): """Restores training state from a given model checkpoint. This will also sync the trial results to a new location if restoring on a different node. """ if checkpoint is None or checkpoint.value is None: checkpoint = trial._c...
[ "def", "restore", "(", "self", ",", "trial", ",", "checkpoint", "=", "None", ")", ":", "if", "checkpoint", "is", "None", "or", "checkpoint", ".", "value", "is", "None", ":", "checkpoint", "=", "trial", ".", "_checkpoint", "if", "checkpoint", "is", "None"...
Restores training state from a given model checkpoint. This will also sync the trial results to a new location if restoring on a different node.
[ "Restores", "training", "state", "from", "a", "given", "model", "checkpoint", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/tune/ray_trial_executor.py#L516-L545
train
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
train
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
train
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
train
ray-project/ray
python/ray/experimental/streaming/streaming.py
Environment._generate_channels
def _generate_channels(self, operator): """Generates all output data channels (see: DataChannel in communication.py) for all instances of the given logical operator. The function constructs one data channel for each pair of communicating operator instances (instance_1,instance_2...
python
def _generate_channels(self, operator): """Generates all output data channels (see: DataChannel in communication.py) for all instances of the given logical operator. The function constructs one data channel for each pair of communicating operator instances (instance_1,instance_2...
[ "def", "_generate_channels", "(", "self", ",", "operator", ")", ":", "channels", "=", "{", "}", "# destination operator id -> channels", "strategies", "=", "operator", ".", "partitioning_strategies", "for", "dst_operator", ",", "p_scheme", "in", "strategies", ".", "...
Generates all output data channels (see: DataChannel in communication.py) for all instances of the given logical operator. The function constructs one data channel for each pair of communicating operator instances (instance_1,instance_2), where instance_1 is an instance of the g...
[ "Generates", "all", "output", "data", "channels", "(", "see", ":", "DataChannel", "in", "communication", ".", "py", ")", "for", "all", "instances", "of", "the", "given", "logical", "operator", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L219-L253
train
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
train
ray-project/ray
python/ray/experimental/streaming/streaming.py
DataStream.__register
def __register(self, operator): """Registers the given logical operator to the environment and connects it to its upstream operator (if any). A call to this function adds a new edge to the logical topology. Attributes: operator (Operator): The metadata of the logical opera...
python
def __register(self, operator): """Registers the given logical operator to the environment and connects it to its upstream operator (if any). A call to this function adds a new edge to the logical topology. Attributes: operator (Operator): The metadata of the logical opera...
[ "def", "__register", "(", "self", ",", "operator", ")", ":", "self", ".", "env", ".", "operators", "[", "operator", ".", "id", "]", "=", "operator", "self", ".", "dst_operator_id", "=", "operator", ".", "id", "logger", ".", "debug", "(", "\"Adding new da...
Registers the given logical operator to the environment and connects it to its upstream operator (if any). A call to this function adds a new edge to the logical topology. Attributes: operator (Operator): The metadata of the logical operator.
[ "Registers", "the", "given", "logical", "operator", "to", "the", "environment", "and", "connects", "it", "to", "its", "upstream", "operator", "(", "if", "any", ")", "." ]
4eade036a0505e244c976f36aaa2d64386b5129b
https://github.com/ray-project/ray/blob/4eade036a0505e244c976f36aaa2d64386b5129b/python/ray/experimental/streaming/streaming.py#L429-L462
train
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
train
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
train