text
stringlengths
81
112k
Lasso Regression 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
Ridge Regression 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
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
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
Gradient Boosted Trees def cric__gbm(): """ Gradient Boosted Trees """ import xgboost # max_depth and subsample match the params used for the full cric data in the paper # learning_rate was set a bit higher to allow for faster runtimes # n_estimators was chosen based on a train/test split of the data model = xgboost.XGBClassifier(max_depth=5, n_estimators=400, learning_rate=0.01, subsample=0.2, n_jobs=8, random_state=0) # we want to explain the margin, not the transformed probability outputs model.__orig_predict = model.predict model.predict = lambda X: model.__orig_predict(X, output_margin=True) # pylint: disable=E1123 return model
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_depth=2) xor_model.fit(X, y) return xor_model
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_names list as shorthand feature_names : list Names of the features (length # features) max_display : int How many top features to include in the plot (default is 20, or 7 for interaction plots) plot_type : "dot" (default) or "violin" What type of summary plot to produce 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 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_names list as shorthand feature_names : list Names of the features (length # features) max_display : int How many top features to include in the plot (default is 20, or 7 for interaction plots) plot_type : "dot" (default) or "violin" What type of summary plot to produce """ multi_class = False if isinstance(shap_values, list): multi_class = True plot_type = "bar" # only type supported for now else: assert len(shap_values.shape) != 1, "Summary plots need a matrix of shap_values, not a vector." # default color: if color is None: if plot_type == 'layered_violin': color = "coolwarm" elif multi_class: color = lambda i: colors.red_blue_circle(i/len(shap_values)) else: color = colors.blue_rgb # convert from a DataFrame or other types if str(type(features)) == "<class 'pandas.core.frame.DataFrame'>": if feature_names is None: feature_names = features.columns features = features.values elif isinstance(features, list): if feature_names is None: feature_names = features features = None elif (features is not None) and len(features.shape) == 1 and feature_names is None: feature_names = features features = None num_features = (shap_values[0].shape[1] if multi_class else shap_values.shape[1]) if feature_names is None: feature_names = np.array([labels['FEATURE'] % str(i) for i in range(num_features)]) # plotting SHAP interaction values if not multi_class and len(shap_values.shape) == 3: if max_display is None: max_display = 7 else: max_display = min(len(feature_names), max_display) sort_inds = np.argsort(-np.abs(shap_values.sum(1)).sum(0)) # get plotting limits delta = 1.0 / (shap_values.shape[1] ** 2) slow = np.nanpercentile(shap_values, delta) shigh = np.nanpercentile(shap_values, 100 - delta) v = max(abs(slow), abs(shigh)) slow = -v shigh = v pl.figure(figsize=(1.5 * max_display + 1, 0.8 * max_display + 1)) pl.subplot(1, max_display, 1) proj_shap_values = shap_values[:, sort_inds[0], sort_inds] proj_shap_values[:, 1:] *= 2 # because off diag effects are split in half summary_plot( proj_shap_values, features[:, sort_inds] if features is not None else None, feature_names=feature_names[sort_inds], sort=False, show=False, color_bar=False, auto_size_plot=False, max_display=max_display ) pl.xlim((slow, shigh)) pl.xlabel("") title_length_limit = 11 pl.title(shorten_text(feature_names[sort_inds[0]], title_length_limit)) for i in range(1, min(len(sort_inds), max_display)): ind = sort_inds[i] pl.subplot(1, max_display, i + 1) proj_shap_values = shap_values[:, ind, sort_inds] proj_shap_values *= 2 proj_shap_values[:, i] /= 2 # because only off diag effects are split in half summary_plot( proj_shap_values, features[:, sort_inds] if features is not None else None, sort=False, feature_names=["" for i in range(len(feature_names))], show=False, color_bar=False, auto_size_plot=False, max_display=max_display ) pl.xlim((slow, shigh)) pl.xlabel("") if i == min(len(sort_inds), max_display) // 2: pl.xlabel(labels['INTERACTION_VALUE']) pl.title(shorten_text(feature_names[ind], title_length_limit)) pl.tight_layout(pad=0, w_pad=0, h_pad=0.0) pl.subplots_adjust(hspace=0, wspace=0.1) if show: pl.show() return if max_display is None: max_display = 20 if sort: # order features by the sum of their effect magnitudes if multi_class: feature_order = np.argsort(np.sum(np.mean(np.abs(shap_values), axis=0), axis=0)) else: feature_order = np.argsort(np.sum(np.abs(shap_values), axis=0)) feature_order = feature_order[-min(max_display, len(feature_order)):] else: feature_order = np.flip(np.arange(min(max_display, num_features)), 0) row_height = 0.4 if auto_size_plot: pl.gcf().set_size_inches(8, len(feature_order) * row_height + 1.5) pl.axvline(x=0, color="#999999", zorder=-1) if plot_type == "dot": for pos, i in enumerate(feature_order): pl.axhline(y=pos, color="#cccccc", lw=0.5, dashes=(1, 5), zorder=-1) shaps = shap_values[:, i] values = None if features is None else features[:, i] inds = np.arange(len(shaps)) np.random.shuffle(inds) if values is not None: values = values[inds] shaps = shaps[inds] colored_feature = True try: values = np.array(values, dtype=np.float64) # make sure this can be numeric except: colored_feature = False N = len(shaps) # hspacing = (np.max(shaps) - np.min(shaps)) / 200 # curr_bin = [] nbins = 100 quant = np.round(nbins * (shaps - np.min(shaps)) / (np.max(shaps) - np.min(shaps) + 1e-8)) inds = np.argsort(quant + np.random.randn(N) * 1e-6) layer = 0 last_bin = -1 ys = np.zeros(N) for ind in inds: if quant[ind] != last_bin: layer = 0 ys[ind] = np.ceil(layer / 2) * ((layer % 2) * 2 - 1) layer += 1 last_bin = quant[ind] ys *= 0.9 * (row_height / np.max(ys + 1)) if features is not None and colored_feature: # trim the color range, but prevent the color range from collapsing vmin = np.nanpercentile(values, 5) vmax = np.nanpercentile(values, 95) if vmin == vmax: vmin = np.nanpercentile(values, 1) vmax = np.nanpercentile(values, 99) if vmin == vmax: vmin = np.min(values) vmax = np.max(values) assert features.shape[0] == len(shaps), "Feature and SHAP matrices must have the same number of rows!" # plot the nan values in the interaction feature as grey nan_mask = np.isnan(values) pl.scatter(shaps[nan_mask], pos + ys[nan_mask], color="#777777", vmin=vmin, vmax=vmax, s=16, alpha=alpha, linewidth=0, zorder=3, rasterized=len(shaps) > 500) # plot the non-nan values colored by the trimmed feature value cvals = values[np.invert(nan_mask)].astype(np.float64) cvals_imp = cvals.copy() cvals_imp[np.isnan(cvals)] = (vmin + vmax) / 2.0 cvals[cvals_imp > vmax] = vmax cvals[cvals_imp < vmin] = vmin pl.scatter(shaps[np.invert(nan_mask)], pos + ys[np.invert(nan_mask)], cmap=colors.red_blue, vmin=vmin, vmax=vmax, s=16, c=cvals, alpha=alpha, linewidth=0, zorder=3, rasterized=len(shaps) > 500) else: pl.scatter(shaps, pos + ys, s=16, alpha=alpha, linewidth=0, zorder=3, color=color if colored_feature else "#777777", rasterized=len(shaps) > 500) elif plot_type == "violin": for pos, i in enumerate(feature_order): pl.axhline(y=pos, color="#cccccc", lw=0.5, dashes=(1, 5), zorder=-1) if features is not None: global_low = np.nanpercentile(shap_values[:, :len(feature_names)].flatten(), 1) global_high = np.nanpercentile(shap_values[:, :len(feature_names)].flatten(), 99) for pos, i in enumerate(feature_order): shaps = shap_values[:, i] shap_min, shap_max = np.min(shaps), np.max(shaps) rng = shap_max - shap_min xs = np.linspace(np.min(shaps) - rng * 0.2, np.max(shaps) + rng * 0.2, 100) if np.std(shaps) < (global_high - global_low) / 100: ds = gaussian_kde(shaps + np.random.randn(len(shaps)) * (global_high - global_low) / 100)(xs) else: ds = gaussian_kde(shaps)(xs) ds /= np.max(ds) * 3 values = features[:, i] window_size = max(10, len(values) // 20) smooth_values = np.zeros(len(xs) - 1) sort_inds = np.argsort(shaps) trailing_pos = 0 leading_pos = 0 running_sum = 0 back_fill = 0 for j in range(len(xs) - 1): while leading_pos < len(shaps) and xs[j] >= shaps[sort_inds[leading_pos]]: running_sum += values[sort_inds[leading_pos]] leading_pos += 1 if leading_pos - trailing_pos > 20: running_sum -= values[sort_inds[trailing_pos]] trailing_pos += 1 if leading_pos - trailing_pos > 0: smooth_values[j] = running_sum / (leading_pos - trailing_pos) for k in range(back_fill): smooth_values[j - k - 1] = smooth_values[j] else: back_fill += 1 vmin = np.nanpercentile(values, 5) vmax = np.nanpercentile(values, 95) if vmin == vmax: vmin = np.nanpercentile(values, 1) vmax = np.nanpercentile(values, 99) if vmin == vmax: vmin = np.min(values) vmax = np.max(values) pl.scatter(shaps, np.ones(shap_values.shape[0]) * pos, s=9, cmap=colors.red_blue, vmin=vmin, vmax=vmax, c=values, alpha=alpha, linewidth=0, zorder=1) # smooth_values -= nxp.nanpercentile(smooth_values, 5) # smooth_values /= np.nanpercentile(smooth_values, 95) smooth_values -= vmin if vmax - vmin > 0: smooth_values /= vmax - vmin for i in range(len(xs) - 1): if ds[i] > 0.05 or ds[i + 1] > 0.05: pl.fill_between([xs[i], xs[i + 1]], [pos + ds[i], pos + ds[i + 1]], [pos - ds[i], pos - ds[i + 1]], color=colors.red_blue(smooth_values[i]), zorder=2) else: parts = pl.violinplot(shap_values[:, feature_order], range(len(feature_order)), points=200, vert=False, widths=0.7, showmeans=False, showextrema=False, showmedians=False) for pc in parts['bodies']: pc.set_facecolor(color) pc.set_edgecolor('none') pc.set_alpha(alpha) elif plot_type == "layered_violin": # courtesy of @kodonnell num_x_points = 200 bins = np.linspace(0, features.shape[0], layered_violin_max_num_bins + 1).round(0).astype( 'int') # the indices of the feature data corresponding to each bin shap_min, shap_max = np.min(shap_values), np.max(shap_values) x_points = np.linspace(shap_min, shap_max, num_x_points) # loop through each feature and plot: for pos, ind in enumerate(feature_order): # decide how to handle: if #unique < layered_violin_max_num_bins then split by unique value, otherwise use bins/percentiles. # to keep simpler code, in the case of uniques, we just adjust the bins to align with the unique counts. feature = features[:, ind] unique, counts = np.unique(feature, return_counts=True) if unique.shape[0] <= layered_violin_max_num_bins: order = np.argsort(unique) thesebins = np.cumsum(counts[order]) thesebins = np.insert(thesebins, 0, 0) else: thesebins = bins nbins = thesebins.shape[0] - 1 # order the feature data so we can apply percentiling order = np.argsort(feature) # x axis is located at y0 = pos, with pos being there for offset y0 = np.ones(num_x_points) * pos # calculate kdes: ys = np.zeros((nbins, num_x_points)) for i in range(nbins): # get shap values in this bin: shaps = shap_values[order[thesebins[i]:thesebins[i + 1]], ind] # if there's only one element, then we can't if shaps.shape[0] == 1: warnings.warn( "not enough data in bin #%d for feature %s, so it'll be ignored. Try increasing the number of records to plot." % (i, feature_names[ind])) # to ignore it, just set it to the previous y-values (so the area between them will be zero). Not ys is already 0, so there's # nothing to do if i == 0 if i > 0: ys[i, :] = ys[i - 1, :] continue # save kde of them: note that we add a tiny bit of gaussian noise to avoid singular matrix errors ys[i, :] = gaussian_kde(shaps + np.random.normal(loc=0, scale=0.001, size=shaps.shape[0]))(x_points) # scale it up so that the 'size' of each y represents the size of the bin. For continuous data this will # do nothing, but when we've gone with the unqique option, this will matter - e.g. if 99% are male and 1% # female, we want the 1% to appear a lot smaller. size = thesebins[i + 1] - thesebins[i] bin_size_if_even = features.shape[0] / nbins relative_bin_size = size / bin_size_if_even ys[i, :] *= relative_bin_size # now plot 'em. We don't plot the individual strips, as this can leave whitespace between them. # instead, we plot the full kde, then remove outer strip and plot over it, etc., to ensure no # whitespace ys = np.cumsum(ys, axis=0) width = 0.8 scale = ys.max() * 2 / width # 2 is here as we plot both sides of x axis for i in range(nbins - 1, -1, -1): y = ys[i, :] / scale c = pl.get_cmap(color)(i / ( nbins - 1)) if color in pl.cm.datad else color # if color is a cmap, use it, otherwise use a color pl.fill_between(x_points, pos - y, pos + y, facecolor=c) pl.xlim(shap_min, shap_max) elif not multi_class and plot_type == "bar": feature_inds = feature_order[:max_display] y_pos = np.arange(len(feature_inds)) global_shap_values = np.abs(shap_values).mean(0) pl.barh(y_pos, global_shap_values[feature_inds], 0.7, align='center', color=color) pl.yticks(y_pos, fontsize=13) pl.gca().set_yticklabels([feature_names[i] for i in feature_inds]) elif multi_class and plot_type == "bar": if class_names is None: class_names = ["Class "+str(i) for i in range(len(shap_values))] feature_inds = feature_order[:max_display] y_pos = np.arange(len(feature_inds)) left_pos = np.zeros(len(feature_inds)) class_inds = np.argsort([-np.abs(shap_values[i]).mean() for i in range(len(shap_values))]) for i,ind in enumerate(class_inds): global_shap_values = np.abs(shap_values[ind]).mean(0) pl.barh( y_pos, global_shap_values[feature_inds], 0.7, left=left_pos, align='center', color=color(i), label=class_names[ind] ) left_pos += global_shap_values[feature_inds] pl.yticks(y_pos, fontsize=13) pl.gca().set_yticklabels([feature_names[i] for i in feature_inds]) pl.legend(frameon=False, fontsize=12) # draw the color bar if color_bar and features is not None and plot_type != "bar" and \ (plot_type != "layered_violin" or color in pl.cm.datad): import matplotlib.cm as cm m = cm.ScalarMappable(cmap=colors.red_blue if plot_type != "layered_violin" else pl.get_cmap(color)) m.set_array([0, 1]) cb = pl.colorbar(m, ticks=[0, 1], aspect=1000) cb.set_ticklabels([labels['FEATURE_VALUE_LOW'], labels['FEATURE_VALUE_HIGH']]) cb.set_label(labels['FEATURE_VALUE'], size=12, labelpad=0) cb.ax.tick_params(labelsize=11, length=0) cb.set_alpha(1) cb.outline.set_visible(False) bbox = cb.ax.get_window_extent().transformed(pl.gcf().dpi_scale_trans.inverted()) cb.ax.set_aspect((bbox.height - 0.9) * 20) # cb.draw_all() pl.gca().xaxis.set_ticks_position('bottom') pl.gca().yaxis.set_ticks_position('none') pl.gca().spines['right'].set_visible(False) pl.gca().spines['top'].set_visible(False) pl.gca().spines['left'].set_visible(False) pl.gca().tick_params(color=axis_color, labelcolor=axis_color) pl.yticks(range(len(feature_order)), [feature_names[i] for i in feature_order], fontsize=13) if plot_type != "bar": pl.gca().tick_params('y', length=20, width=0.5, which='major') pl.gca().tick_params('x', labelsize=11) pl.ylim(-1, len(feature_order)) if plot_type == "bar": pl.xlabel(labels['GLOBAL_VALUE'], fontsize=13) else: pl.xlabel(labels['VALUE'], fontsize=13) if show: pl.show()
Kernel SHAP 1000 mean ref. color = red_blue_circle(0.5) linestyle = solid 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)
IME 1000 color = red_blue_circle(0.5) linestyle = dashed 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)
TreeExplainer (independent) color = red_blue_circle(0) linestyle = dashed 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_dependence="independent").shap_values
mean(|TreeExplainer|) color = red_blue_circle(0.25) linestyle = solid 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: return np.tile(np.abs(v).mean(0), (X.shape[0], 1)) return f
Saabas color = red_blue_circle(0) linestyle = dotted def saabas(model, data): """ Saabas color = red_blue_circle(0) linestyle = dotted """ return lambda X: TreeExplainer(model).shap_values(X, approximate=True)
LIME Tabular 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)
Deep SHAP (DeepLIFT) 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] else: return phi return f
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] else: return phi return f
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 X.shape[0] == # samples) on which to explain the model's output. ranked_outputs : None or int If ranked_outputs is None then we explain all the outputs in a multi-output model. If ranked_outputs is a positive integer then we only explain that many of the top model outputs (where "top" is determined by output_rank_order). Note that this causes a pair of values to be returned (shap_values, indexes), where shap_values is a list of numpy arrays for each of the output ranks, and indexes is a matrix that indicates for each sample which output indexes were choses as "top". output_rank_order : "max", "min", or "max_abs" How to order the model outputs when using ranked_outputs, either by maximum, minimum, or maximum absolute value. Returns ------- For a models with a single output this returns a tensor of SHAP values with the same shape as X. For a model with multiple outputs this returns a list of SHAP value tensors, each of which are the same shape as X. If ranked_outputs is None then this list of tensors matches the number of model outputs. If ranked_outputs is a positive integer a pair is returned (shap_values, indexes), where shap_values is a list of tensors with a length of ranked_outputs, and indexes is a matrix that indicates for each sample which output indexes were chosen as "top". 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 == 'pytorch': torch.tensor A tensor (or list of tensors) of samples (where X.shape[0] == # samples) on which to explain the model's output. ranked_outputs : None or int If ranked_outputs is None then we explain all the outputs in a multi-output model. If ranked_outputs is a positive integer then we only explain that many of the top model outputs (where "top" is determined by output_rank_order). Note that this causes a pair of values to be returned (shap_values, indexes), where shap_values is a list of numpy arrays for each of the output ranks, and indexes is a matrix that indicates for each sample which output indexes were choses as "top". output_rank_order : "max", "min", or "max_abs" How to order the model outputs when using ranked_outputs, either by maximum, minimum, or maximum absolute value. Returns ------- For a models with a single output this returns a tensor of SHAP values with the same shape as X. For a model with multiple outputs this returns a list of SHAP value tensors, each of which are the same shape as X. If ranked_outputs is None then this list of tensors matches the number of model outputs. If ranked_outputs is a positive integer a pair is returned (shap_values, indexes), where shap_values is a list of tensors with a length of ranked_outputs, and indexes is a matrix that indicates for each sample which output indexes were chosen as "top". """ return self.explainer.shap_values(X, ranked_outputs, output_rank_order)
Returns dummy agent class for if PyTorch etc. is not installed. def _agent_import_failed(trace): """Returns dummy agent class for if PyTorch etc. is not installed.""" class _AgentImportFailed(Trainer): _name = "AgentImportFailed" _default_config = with_common_config({}) def _setup(self, config): raise ImportError(trace) return _AgentImportFailed
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 class, or the string identifier of a trainable function or class registered in the tune registry. If Experiment, then Tune will execute training based on Experiment.spec. name (str): Name of experiment. stop (dict): The stopping criteria. The keys may be any field in the return result of 'train()', whichever is reached first. Defaults to empty dict. config (dict): Algorithm-specific configuration for Tune variant generation (e.g. env, hyperparams). Defaults to empty dict. Custom search algorithms may ignore this. resources_per_trial (dict): Machine resources to allocate per trial, e.g. ``{"cpu": 64, "gpu": 8}``. Note that GPUs will not be assigned unless you specify them here. Defaults to 1 CPU and 0 GPUs in ``Trainable.default_resource_request()``. num_samples (int): Number of times to sample from the hyperparameter space. Defaults to 1. If `grid_search` is provided as an argument, the grid will be repeated `num_samples` of times. local_dir (str): Local dir to save training results to. Defaults to ``~/ray_results``. upload_dir (str): Optional URI to sync training results to (e.g. ``s3://bucket``). trial_name_creator (func): Optional function for generating the trial string representation. loggers (list): List of logger creators to be used with each Trial. If None, defaults to ray.tune.logger.DEFAULT_LOGGERS. See `ray/tune/logger.py`. sync_function (func|str): Function for syncing the local_dir to upload_dir. If string, then it must be a string template for syncer to run. If not provided, the sync command defaults to standard S3 or gsutil sync comamnds. checkpoint_freq (int): How many training iterations between checkpoints. A value of 0 (default) disables checkpointing. checkpoint_at_end (bool): Whether to checkpoint at the end of the experiment regardless of the checkpoint_freq. Default is False. export_formats (list): List of formats that exported at the end of the experiment. Default is None. max_failures (int): Try to recover a trial from its last checkpoint at least this many times. Only applies if checkpointing is enabled. Setting to -1 will lead to infinite recovery retries. Defaults to 3. restore (str): Path to checkpoint. Only makes sense to set if running 1 trial. Defaults to None. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. Choose among FIFO (default), MedianStopping, AsyncHyperBand, and HyperBand. with_server (bool): Starts a background Tune server. Needed for using the Client API. server_port (int): Port number for launching TuneServer. verbose (int): 0, 1, or 2. Verbosity mode. 0 = silent, 1 = only status updates, 2 = status and trial results. resume (bool|"prompt"): If checkpoint exists, the experiment will resume from there. If resume is "prompt", Tune will prompt if checkpoint detected. queue_trials (bool): Whether to queue trials when the cluster does not currently have enough resources to launch one. This should be set to True when running on an autoscaling cluster to enable automatic scale-up. reuse_actors (bool): Whether to reuse actors between different trials when possible. This can drastically speed up experiments that start and stop actors often (e.g., PBT in time-multiplexing mode). This requires trials to have the same resource requirements. trial_executor (TrialExecutor): Manage the execution of trials. raise_on_failed_trial (bool): Raise TuneError if there exists failed trial (of ERROR state) when the experiments complete. Returns: List of Trial objects. Raises: TuneError if any trials failed and `raise_on_failed_trial` is True. Examples: >>> tune.run(mytrainable, scheduler=PopulationBasedTraining()) >>> tune.run(mytrainable, num_samples=5, reuse_actors=True) >>> tune.run( "PG", num_samples=5, config={ "env": "CartPole-v0", "lr": tune.sample_from(lambda _: np.random.rand()) } ) 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_at_end=False, export_formats=None, max_failures=3, restore=None, search_alg=None, scheduler=None, with_server=False, server_port=TuneServer.DEFAULT_PORT, verbose=2, resume=False, queue_trials=False, reuse_actors=False, trial_executor=None, raise_on_failed_trial=True): """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 class, or the string identifier of a trainable function or class registered in the tune registry. If Experiment, then Tune will execute training based on Experiment.spec. name (str): Name of experiment. stop (dict): The stopping criteria. The keys may be any field in the return result of 'train()', whichever is reached first. Defaults to empty dict. config (dict): Algorithm-specific configuration for Tune variant generation (e.g. env, hyperparams). Defaults to empty dict. Custom search algorithms may ignore this. resources_per_trial (dict): Machine resources to allocate per trial, e.g. ``{"cpu": 64, "gpu": 8}``. Note that GPUs will not be assigned unless you specify them here. Defaults to 1 CPU and 0 GPUs in ``Trainable.default_resource_request()``. num_samples (int): Number of times to sample from the hyperparameter space. Defaults to 1. If `grid_search` is provided as an argument, the grid will be repeated `num_samples` of times. local_dir (str): Local dir to save training results to. Defaults to ``~/ray_results``. upload_dir (str): Optional URI to sync training results to (e.g. ``s3://bucket``). trial_name_creator (func): Optional function for generating the trial string representation. loggers (list): List of logger creators to be used with each Trial. If None, defaults to ray.tune.logger.DEFAULT_LOGGERS. See `ray/tune/logger.py`. sync_function (func|str): Function for syncing the local_dir to upload_dir. If string, then it must be a string template for syncer to run. If not provided, the sync command defaults to standard S3 or gsutil sync comamnds. checkpoint_freq (int): How many training iterations between checkpoints. A value of 0 (default) disables checkpointing. checkpoint_at_end (bool): Whether to checkpoint at the end of the experiment regardless of the checkpoint_freq. Default is False. export_formats (list): List of formats that exported at the end of the experiment. Default is None. max_failures (int): Try to recover a trial from its last checkpoint at least this many times. Only applies if checkpointing is enabled. Setting to -1 will lead to infinite recovery retries. Defaults to 3. restore (str): Path to checkpoint. Only makes sense to set if running 1 trial. Defaults to None. search_alg (SearchAlgorithm): Search Algorithm. Defaults to BasicVariantGenerator. scheduler (TrialScheduler): Scheduler for executing the experiment. Choose among FIFO (default), MedianStopping, AsyncHyperBand, and HyperBand. with_server (bool): Starts a background Tune server. Needed for using the Client API. server_port (int): Port number for launching TuneServer. verbose (int): 0, 1, or 2. Verbosity mode. 0 = silent, 1 = only status updates, 2 = status and trial results. resume (bool|"prompt"): If checkpoint exists, the experiment will resume from there. If resume is "prompt", Tune will prompt if checkpoint detected. queue_trials (bool): Whether to queue trials when the cluster does not currently have enough resources to launch one. This should be set to True when running on an autoscaling cluster to enable automatic scale-up. reuse_actors (bool): Whether to reuse actors between different trials when possible. This can drastically speed up experiments that start and stop actors often (e.g., PBT in time-multiplexing mode). This requires trials to have the same resource requirements. trial_executor (TrialExecutor): Manage the execution of trials. raise_on_failed_trial (bool): Raise TuneError if there exists failed trial (of ERROR state) when the experiments complete. Returns: List of Trial objects. Raises: TuneError if any trials failed and `raise_on_failed_trial` is True. Examples: >>> tune.run(mytrainable, scheduler=PopulationBasedTraining()) >>> tune.run(mytrainable, num_samples=5, reuse_actors=True) >>> tune.run( "PG", num_samples=5, config={ "env": "CartPole-v0", "lr": tune.sample_from(lambda _: np.random.rand()) } ) """ experiment = run_or_experiment if not isinstance(run_or_experiment, Experiment): experiment = Experiment( name, run_or_experiment, stop, config, resources_per_trial, num_samples, local_dir, upload_dir, trial_name_creator, loggers, sync_function, checkpoint_freq, checkpoint_at_end, export_formats, max_failures, restore) else: logger.debug("Ignoring some parameters passed into tune.run.") checkpoint_dir = _find_checkpoint_dir(experiment) should_restore = _prompt_restore(checkpoint_dir, resume) runner = None if should_restore: try: runner = TrialRunner.restore(checkpoint_dir, search_alg, scheduler, trial_executor) except Exception: logger.exception("Runner restore failed. Restarting experiment.") else: logger.info("Starting a new experiment.") if not runner: scheduler = scheduler or FIFOScheduler() search_alg = search_alg or BasicVariantGenerator() search_alg.add_configurations([experiment]) runner = TrialRunner( search_alg, scheduler=scheduler, metadata_checkpoint_dir=checkpoint_dir, launch_web_server=with_server, server_port=server_port, verbose=bool(verbose > 1), queue_trials=queue_trials, reuse_actors=reuse_actors, trial_executor=trial_executor) if verbose: print(runner.debug_string(max_debug=99999)) last_debug = 0 while not runner.is_finished(): runner.step() if time.time() - last_debug > DEBUG_PRINT_INTERVAL: if verbose: print(runner.debug_string()) last_debug = time.time() if verbose: print(runner.debug_string(max_debug=99999)) wait_for_log_sync() errored_trials = [] for trial in runner.get_trials(): if trial.status != Trial.TERMINATED: errored_trials += [trial] if errored_trials: if raise_on_failed_trial: raise TuneError("Trials did not complete", errored_trials) else: logger.error("Trials did not complete: %s", errored_trials) return runner.get_trials()
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_experiments( >>> experiments=experiment_spec, >>> scheduler=MedianStoppingRule(...)) >>> run_experiments( >>> experiments=experiment_spec, >>> search_alg=SearchAlgorithm(), >>> scheduler=MedianStoppingRule(...)) Returns: List of Trial objects, holding data for each executed trial. def run_experiments(experiments, search_alg=None, scheduler=None, with_server=False, server_port=TuneServer.DEFAULT_PORT, verbose=2, resume=False, queue_trials=False, reuse_actors=False, trial_executor=None, raise_on_failed_trial=True): """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_experiments( >>> experiments=experiment_spec, >>> scheduler=MedianStoppingRule(...)) >>> run_experiments( >>> experiments=experiment_spec, >>> search_alg=SearchAlgorithm(), >>> scheduler=MedianStoppingRule(...)) Returns: List of Trial objects, holding data for each executed trial. """ # This is important to do this here # because it schematize the experiments # and it conducts the implicit registration. experiments = convert_to_experiment_list(experiments) trials = [] for exp in experiments: trials += run( exp, search_alg=search_alg, scheduler=scheduler, with_server=with_server, server_port=server_port, verbose=verbose, resume=resume, queue_trials=queue_trials, reuse_actors=reuse_actors, trial_executor=trial_executor, raise_on_failed_trial=raise_on_failed_trial) return trials
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 marked as 'closed' (True) or not (False) after flushing. 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 the channel should be also marked as 'closed' (True) or not (False) after flushing. """ for channel in self.forward_channels: if close is True: channel.queue.put_next(None) channel.queue._flush_writes() for channels in self.shuffle_channels: for channel in channels: if close is True: channel.queue.put_next(None) channel.queue._flush_writes() for channels in self.shuffle_key_channels: for channel in channels: if close is True: channel.queue.put_next(None) channel.queue._flush_writes() for channels in self.round_robin_channels: for channel in channels: if close is True: channel.queue.put_next(None) channel.queue._flush_writes()
Returns an appropriate preprocessor class for the given space. def get_preprocessor(space): """Returns an appropriate preprocessor class for the given space.""" legacy_patch_shapes(space) obs_shape = space.shape if isinstance(space, gym.spaces.Discrete): preprocessor = OneHotPreprocessor elif obs_shape == ATARI_OBS_SHAPE: preprocessor = GenericPixelPreprocessor elif obs_shape == ATARI_RAM_OBS_SHAPE: preprocessor = AtariRamPreprocessor elif isinstance(space, gym.spaces.Tuple): preprocessor = TupleFlatteningPreprocessor elif isinstance(space, gym.spaces.Dict): preprocessor = DictFlatteningPreprocessor else: preprocessor = NoPreprocessor return preprocessor
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. 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.shape = () elif isinstance(space, gym.spaces.Tuple): shapes = [] for s in space.spaces: shape = legacy_patch_shapes(s) shapes.append(shape) space.shape = tuple(shapes) return space.shape
Downsamples images from (210, 160, 3) by the configured factor. 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 42x42 (essentially mipmapping). # If we resize directly we lose pixels that, when mapped to 42x42, # aren't close enough to the pixel boundary. scaled = cv2.resize(scaled, (self._dim, self._dim)) if self._grayscale: scaled = scaled.mean(2) scaled = scaled.astype(np.float32) # Rescale needed for maintaining 1 channel scaled = np.reshape(scaled, [self._dim, self._dim, 1]) if self._zero_mean: scaled = (scaled - 128) / 128 else: scaled *= 1.0 / 255.0 return scaled
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. 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(timeout=300.0) self.ttl[self.idx] = self.cur_max_ttl if self.cur_max_ttl < self.max_ttl: self.cur_max_ttl += 1 buf = self.buffers[self.idx] self.ttl[self.idx] -= 1 released = self.ttl[self.idx] <= 0 if released: self.buffers[self.idx] = None self.idx = (self.idx + 1) % len(self.buffers) return buf, released
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 seconds this iteration took to run. This may be overriden in order to override the system-computed time difference. `time_total_s` (float): Accumulated time in seconds for this entire experiment. `experiment_id` (str): Unique string identifier for this experiment. This id is preserved across checkpoint / restore calls. `training_iteration` (int): The index of this training iteration, e.g. call to train(). `pid` (str): The pid of the training process. `date` (str): A formatted date of when the result was processed. `timestamp` (str): A UNIX timestamp of when the result was processed. `hostname` (str): Hostname of the machine hosting the training process. `node_ip` (str): Node ip of the machine hosting the training process. Returns: A dict that describes training progress. 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_this_iter_s` (float): Time in seconds this iteration took to run. This may be overriden in order to override the system-computed time difference. `time_total_s` (float): Accumulated time in seconds for this entire experiment. `experiment_id` (str): Unique string identifier for this experiment. This id is preserved across checkpoint / restore calls. `training_iteration` (int): The index of this training iteration, e.g. call to train(). `pid` (str): The pid of the training process. `date` (str): A formatted date of when the result was processed. `timestamp` (str): A UNIX timestamp of when the result was processed. `hostname` (str): Hostname of the machine hosting the training process. `node_ip` (str): Node ip of the machine hosting the training process. Returns: A dict that describes training progress. """ start = time.time() result = self._train() assert isinstance(result, dict), "_train() needs to return a dict." # We do not modify internal state nor update this result if duplicate. if RESULT_DUPLICATE in result: return result result = result.copy() self._iteration += 1 self._iterations_since_restore += 1 if result.get(TIME_THIS_ITER_S) is not None: time_this_iter = result[TIME_THIS_ITER_S] else: time_this_iter = time.time() - start self._time_total += time_this_iter self._time_since_restore += time_this_iter result.setdefault(DONE, False) # self._timesteps_total should only be tracked if increments provided if result.get(TIMESTEPS_THIS_ITER) is not None: if self._timesteps_total is None: self._timesteps_total = 0 self._timesteps_total += result[TIMESTEPS_THIS_ITER] self._timesteps_since_restore += result[TIMESTEPS_THIS_ITER] # self._episodes_total should only be tracked if increments provided if result.get(EPISODES_THIS_ITER) is not None: if self._episodes_total is None: self._episodes_total = 0 self._episodes_total += result[EPISODES_THIS_ITER] # self._timesteps_total should not override user-provided total result.setdefault(TIMESTEPS_TOTAL, self._timesteps_total) result.setdefault(EPISODES_TOTAL, self._episodes_total) result.setdefault(TRAINING_ITERATION, self._iteration) # Provides auto-filled neg_mean_loss for avoiding regressions if result.get("mean_loss"): result.setdefault("neg_mean_loss", -result["mean_loss"]) now = datetime.today() result.update( experiment_id=self._experiment_id, date=now.strftime("%Y-%m-%d_%H-%M-%S"), timestamp=int(time.mktime(now.timetuple())), time_this_iter_s=time_this_iter, time_total_s=self._time_total, pid=os.getpid(), hostname=os.uname()[1], node_ip=self._local_ip, config=self.config, time_since_restore=self._time_since_restore, timesteps_since_restore=self._timesteps_since_restore, iterations_since_restore=self._iterations_since_restore) self._log_result(result) return result
Removes subdirectory within checkpoint_folder Parameters ---------- checkpoint_dir : path to 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: shutil.rmtree(checkpoint_dir)
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 path that may be passed to restore(). 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 checkpoint. Returns: Checkpoint path that may be passed to restore(). """ checkpoint_dir = os.path.join(checkpoint_dir or self.logdir, "checkpoint_{}".format(self._iteration)) if not os.path.exists(checkpoint_dir): os.makedirs(checkpoint_dir) checkpoint = self._save(checkpoint_dir) saved_as_dict = False if isinstance(checkpoint, string_types): if (not checkpoint.startswith(checkpoint_dir) or checkpoint == checkpoint_dir): raise ValueError( "The returned checkpoint path must be within the " "given checkpoint dir {}: {}".format( checkpoint_dir, checkpoint)) if not os.path.exists(checkpoint): raise ValueError( "The returned checkpoint path does not exist: {}".format( checkpoint)) checkpoint_path = checkpoint elif isinstance(checkpoint, dict): saved_as_dict = True checkpoint_path = os.path.join(checkpoint_dir, "checkpoint") with open(checkpoint_path, "wb") as f: pickle.dump(checkpoint, f) else: raise ValueError( "`_save` must return a dict or string type: {}".format( str(type(checkpoint)))) with open(checkpoint_path + ".tune_metadata", "wb") as f: pickle.dump({ "experiment_id": self._experiment_id, "iteration": self._iteration, "timesteps_total": self._timesteps_total, "time_total": self._time_total, "episodes_total": self._episodes_total, "saved_as_dict": saved_as_dict }, f) return checkpoint_path
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. 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_prefix = self.save(tmpdir) data = {} base_dir = os.path.dirname(checkpoint_prefix) for path in os.listdir(base_dir): path = os.path.join(base_dir, path) if path.startswith(checkpoint_prefix): with open(path, "rb") as f: data[os.path.basename(path)] = f.read() out = io.BytesIO() data_dict = pickle.dumps({ "checkpoint_name": os.path.basename(checkpoint_prefix), "data": data, }) if len(data_dict) > 10e6: # getting pretty large logger.info("Checkpoint size is {} bytes".format(len(data_dict))) out.write(data_dict) shutil.rmtree(tmpdir) return out.getvalue()
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): """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. """ with open(checkpoint_path + ".tune_metadata", "rb") as f: metadata = pickle.load(f) self._experiment_id = metadata["experiment_id"] self._iteration = metadata["iteration"] self._timesteps_total = metadata["timesteps_total"] self._time_total = metadata["time_total"] self._episodes_total = metadata["episodes_total"] saved_as_dict = metadata["saved_as_dict"] if saved_as_dict: with open(checkpoint_path, "rb") as loaded_state: checkpoint_dict = pickle.load(loaded_state) self._restore(checkpoint_dict) else: self._restore(checkpoint_path) self._time_since_restore = 0.0 self._timesteps_since_restore = 0 self._iterations_since_restore = 0 self._restored = True
Restores training state from a checkpoint object. These checkpoints are returned from calls to save_to_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) checkpoint_path = os.path.join(tmpdir, info["checkpoint_name"]) for file_name, file_contents in data.items(): with open(os.path.join(tmpdir, file_name), "wb") as f: f.write(file_contents) self.restore(checkpoint_path) shutil.rmtree(tmpdir)
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. Defaults to self.logdir. Return: A dict that maps ExportFormats to successfully exported models. 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. export_dir (str): Optional dir to place the exported model. Defaults to self.logdir. Return: A dict that maps ExportFormats to successfully exported models. """ export_dir = export_dir or self.logdir return self._export_model(export_formats, export_dir)
See Schedule.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)
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) 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 overwrite: mode = "w" else: mode = "w+" try: with open(json_file, mode) as f: f.write(json.dumps(json_info)) except BaseException as e: logging.error(e.message)
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. 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 try: with open(json_file, "r") as f: info_str = f.readlines() info_str = "".join(info_str) json_info = json.loads(info_str) return unicode2str(json_info) except BaseException as e: logging.error(e.message) return 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. offset (int): Initial seek position of the file. Returns: A dict of json info. New offset after parsing. 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. offset (int): Initial seek position of the file. Returns: A dict of json info. New offset after parsing. """ json_info_list = [] if not os.path.exists(json_file): return json_info_list try: with open(json_file, "r") as f: if offset: f.seek(offset) for line in f: if line[-1] != "\n": # Incomplete line break json_info = json.loads(line) json_info_list.append(json_info) offset += len(line) except BaseException as e: logging.error(e.message) return json_info_list, offset
Convert the unicode element of the content to str recursively. def unicode2str(content): """Convert the unicode element of the content to str recursively.""" if isinstance(content, dict): result = {} for key in content.keys(): result[unicode2str(key)] = unicode2str(content[key]) return result elif isinstance(content, list): return [unicode2str(element) for element in content] elif isinstance(content, int) or isinstance(content, float): return content else: return content.encode("utf-8")
Computes the loss of the network. 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 }))
Computes the gradients of the network. 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 })
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. 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 extracting the images and labels. """ image_size = 32 if dataset == "cifar10": label_bytes = 1 label_offset = 0 elif dataset == "cifar100": label_bytes = 1 label_offset = 1 depth = 3 image_bytes = image_size * image_size * depth record_bytes = label_bytes + label_offset + image_bytes def load_transform(value): # Convert these examples to dense labels and processed images. record = tf.reshape(tf.decode_raw(value, tf.uint8), [record_bytes]) label = tf.cast(tf.slice(record, [label_offset], [label_bytes]), tf.int32) # Convert from string to [depth * height * width] to # [depth, height, width]. depth_major = tf.reshape( tf.slice(record, [label_bytes], [image_bytes]), [depth, image_size, image_size]) # Convert from [depth, height, width] to [height, width, depth]. image = tf.cast(tf.transpose(depth_major, [1, 2, 0]), tf.float32) return (image, label) # Read examples from files in the filename queue. data_files = tf.gfile.Glob(data_path) data = tf.contrib.data.FixedLengthRecordDataset(data_files, record_bytes=record_bytes) data = data.map(load_transform) data = data.batch(size) iterator = data.make_one_shot_iterator() return iterator.get_next()
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: Batches of labels of size [batch_size, num_classes]. Raises: ValueError: When the specified dataset is not supported. 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 [batch_size, image_size, image_size, 3]. labels: Batches of labels of size [batch_size, num_classes]. Raises: ValueError: When the specified dataset is not supported. """ image_size = 32 depth = 3 num_classes = 10 if dataset == "cifar10" else 100 images, labels = data num_samples = images.shape[0] - images.shape[0] % batch_size dataset = tf.contrib.data.Dataset.from_tensor_slices( (images[:num_samples], labels[:num_samples])) def map_train(image, label): image = tf.image.resize_image_with_crop_or_pad(image, image_size + 4, image_size + 4) image = tf.random_crop(image, [image_size, image_size, 3]) image = tf.image.random_flip_left_right(image) image = tf.image.per_image_standardization(image) return (image, label) def map_test(image, label): image = tf.image.resize_image_with_crop_or_pad(image, image_size, image_size) image = tf.image.per_image_standardization(image) return (image, label) dataset = dataset.map(map_train if train else map_test) dataset = dataset.batch(batch_size) dataset = dataset.repeat() if train: dataset = dataset.shuffle(buffer_size=16 * batch_size) images, labels = dataset.make_one_shot_iterator().get_next() images = tf.reshape(images, [batch_size, image_size, image_size, depth]) labels = tf.reshape(labels, [batch_size, 1]) indices = tf.reshape(tf.range(0, batch_size, 1), [batch_size, 1]) labels = tf.sparse_to_dense( tf.concat([indices, labels], 1), [batch_size, num_classes], 1.0, 0.0) assert len(images.get_shape()) == 4 assert images.get_shape()[0] == batch_size assert images.get_shape()[-1] == 3 assert len(labels.get_shape()) == 2 assert labels.get_shape()[0] == batch_size assert labels.get_shape()[1] == num_classes if not train: tf.summary.image("images", images) return images, labels
Create or update a Ray cluster. def create_or_update(cluster_config_file, min_workers, max_workers, no_restart, restart_only, yes, cluster_name): """Create or update a Ray cluster.""" if restart_only or no_restart: assert restart_only != no_restart, "Cannot set both 'restart_only' " \ "and 'no_restart' at the same time!" create_or_update_cluster(cluster_config_file, min_workers, max_workers, no_restart, restart_only, yes, cluster_name)
Tear down the Ray cluster. 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)
Kills a random Ray node. For testing purposes only. 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))
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)) 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)) """ assert not (screen and tmux), "Can specify only one of `screen` or `tmux`." if start: create_or_update_cluster(cluster_config_file, None, None, False, False, True, cluster_name) target = os.path.join("~", os.path.basename(script)) rsync(cluster_config_file, script, target, cluster_name, down=False) cmd = " ".join(["python", target] + list(script_args)) exec_cluster(cluster_config_file, cmd, docker, screen, tmux, stop, False, cluster_name, port_forward)
Build a whole graph for the model. def build_graph(self): """Build a whole graph for the model.""" self.global_step = tf.Variable(0, trainable=False) self._build_model() if self.mode == "train": self._build_train_op() else: # Additional initialization for the test network. self.variables = ray.experimental.tf_utils.TensorFlowVariables( self.cost) self.summaries = tf.summary.merge_all()
Build the core model within the graph. 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] if self.hps.use_bottleneck: res_func = self._bottleneck_residual filters = [16, 64, 128, 256] else: res_func = self._residual filters = [16, 16, 32, 64] with tf.variable_scope("unit_1_0"): x = res_func(x, filters[0], filters[1], self._stride_arr( strides[0]), activate_before_residual[0]) for i in range(1, self.hps.num_residual_units): with tf.variable_scope("unit_1_%d" % i): x = res_func(x, filters[1], filters[1], self._stride_arr(1), False) with tf.variable_scope("unit_2_0"): x = res_func(x, filters[1], filters[2], self._stride_arr( strides[1]), activate_before_residual[1]) for i in range(1, self.hps.num_residual_units): with tf.variable_scope("unit_2_%d" % i): x = res_func(x, filters[2], filters[2], self._stride_arr(1), False) with tf.variable_scope("unit_3_0"): x = res_func(x, filters[2], filters[3], self._stride_arr( strides[2]), activate_before_residual[2]) for i in range(1, self.hps.num_residual_units): with tf.variable_scope("unit_3_%d" % i): x = res_func(x, filters[3], filters[3], self._stride_arr(1), False) with tf.variable_scope("unit_last"): x = self._batch_norm("final_bn", x) x = self._relu(x, self.hps.relu_leakiness) x = self._global_avg_pool(x) with tf.variable_scope("logit"): logits = self._fully_connected(x, self.hps.num_classes) self.predictions = tf.nn.softmax(logits) with tf.variable_scope("costs"): xent = tf.nn.softmax_cross_entropy_with_logits( logits=logits, labels=self.labels) self.cost = tf.reduce_mean(xent, name="xent") self.cost += self._decay() if self.mode == "eval": tf.summary.scalar("cost", self.cost)
Build training specific ops for the graph. 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 = [0.1, 0.01, 0.001, 0.0001] self.lrn_rate = tf.train.piecewise_constant(self.global_step, boundaries, values) tf.summary.scalar("learning rate", self.lrn_rate) if self.hps.optimizer == "sgd": optimizer = tf.train.GradientDescentOptimizer(self.lrn_rate) elif self.hps.optimizer == "mom": optimizer = tf.train.MomentumOptimizer(self.lrn_rate, 0.9) apply_op = optimizer.minimize(self.cost, global_step=self.global_step) train_ops = [apply_op] + self._extra_train_ops self.train_op = tf.group(*train_ops) self.variables = ray.experimental.tf_utils.TensorFlowVariables( self.train_op)
Batch normalization. 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_initializer(0.0, tf.float32)) gamma = tf.get_variable( "gamma", params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32)) if self.mode == "train": mean, variance = tf.nn.moments(x, [0, 1, 2], name="moments") moving_mean = tf.get_variable( "moving_mean", params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32), trainable=False) moving_variance = tf.get_variable( "moving_variance", params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32), trainable=False) self._extra_train_ops.append( moving_averages.assign_moving_average( moving_mean, mean, 0.9)) self._extra_train_ops.append( moving_averages.assign_moving_average( moving_variance, variance, 0.9)) else: mean = tf.get_variable( "moving_mean", params_shape, tf.float32, initializer=tf.constant_initializer(0.0, tf.float32), trainable=False) variance = tf.get_variable( "moving_variance", params_shape, tf.float32, initializer=tf.constant_initializer(1.0, tf.float32), trainable=False) tf.summary.histogram(mean.op.name, mean) tf.summary.histogram(variance.op.name, variance) # elipson used to be 1e-5. Maybe 0.001 solves NaN problem in deeper # net. y = tf.nn.batch_normalization(x, mean, variance, beta, gamma, 0.001) y.set_shape(x.get_shape()) return y
L2 weight decay loss. 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))
Convolution. 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], tf.float32, initializer=tf.random_normal_initializer( stddev=np.sqrt(2.0 / n))) return tf.nn.conv2d(x, kernel, strides, padding="SAME")
FullyConnected layer for final output. 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_variable( "biases", [out_dim], initializer=tf.constant_initializer()) return tf.nn.xw_plus_b(x, w, b)
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_size] 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: Tensor of shape [B, n_agents, h_size] """ B, n_agents = obs.size(0), obs.size(1) obs_flat = obs.reshape([B * n_agents, -1]) h_flat = [s.reshape([B * n_agents, -1]) for s in h] q_flat, _, _, h_flat = model.forward({"obs": obs_flat}, h_flat) return q_flat.reshape( [B, n_agents, -1]), [s.reshape([B, n_agents, -1]) for s in h_flat]
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, obs_size] action_mask: Tensor of shape [B, T, n_agents, n_actions] 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: Tensor of shape [B, T-1, n_agents] obs: Tensor of shape [B, T, n_agents, obs_size] action_mask: Tensor of shape [B, T, n_agents, n_actions] """ B, T = obs.size(0), obs.size(1) # Calculate estimated Q-Values mac_out = [] h = [s.expand([B, self.n_agents, -1]) for s in self.model.state_init()] for t in range(T): q, h = _mac(self.model, obs[:, t], h) mac_out.append(q) mac_out = th.stack(mac_out, dim=1) # Concat over time # Pick the Q-Values for the actions taken -> [B * n_agents, T-1] chosen_action_qvals = th.gather( mac_out[:, :-1], dim=3, index=actions.unsqueeze(3)).squeeze(3) # Calculate the Q-Values necessary for the target target_mac_out = [] target_h = [ s.expand([B, self.n_agents, -1]) for s in self.target_model.state_init() ] for t in range(T): target_q, target_h = _mac(self.target_model, obs[:, t], target_h) target_mac_out.append(target_q) # We don't need the first timesteps Q-Value estimate for targets target_mac_out = th.stack( target_mac_out[1:], dim=1) # Concat across time # Mask out unavailable actions target_mac_out[action_mask[:, 1:] == 0] = -9999999 # Max over target Q-Values if self.double_q: # Get actions that maximise live Q (for double q-learning) mac_out[action_mask == 0] = -9999999 cur_max_actions = mac_out[:, 1:].max(dim=3, keepdim=True)[1] target_max_qvals = th.gather(target_mac_out, 3, cur_max_actions).squeeze(3) else: target_max_qvals = target_mac_out.max(dim=3)[0] # Mix if self.mixer is not None: # TODO(ekl) add support for handling global state? This is just # treating the stacked agent obs as the state. chosen_action_qvals = self.mixer(chosen_action_qvals, obs[:, :-1]) target_max_qvals = self.target_mixer(target_max_qvals, obs[:, 1:]) # Calculate 1-step Q-Learning targets targets = rewards + self.gamma * (1 - terminated) * target_max_qvals # Td-error td_error = (chosen_action_qvals - targets.detach()) mask = mask.expand_as(td_error) # 0-out the targets that came from padded data masked_td_error = td_error * mask # Normal L2 loss, take mean over actual data loss = (masked_td_error**2).sum() / mask.sum() return loss, mask, masked_td_error, chosen_action_qvals, targets
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 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(obs_batch), self.observation_space.original_space, tensorlib=np) if self.has_action_mask: obs = np.concatenate( [o["obs"] for o in unpacked], axis=1).reshape([len(obs_batch), self.n_agents, self.obs_size]) action_mask = np.concatenate( [o["action_mask"] for o in unpacked], axis=1).reshape( [len(obs_batch), self.n_agents, self.n_actions]) else: obs = np.concatenate( unpacked, axis=1).reshape([len(obs_batch), self.n_agents, self.obs_size]) action_mask = np.ones( [len(obs_batch), self.n_agents, self.n_actions]) return obs, action_mask
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. 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) pickled_state = _internal_kv_get(actor_name) if pickled_state is None: raise ValueError("The actor with name={} doesn't exist".format(name)) handle = pickle.loads(pickled_state) return handle
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 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.") if not isinstance(actor_handle, ray.actor.ActorHandle): raise TypeError("The actor_handle argument must be an ActorHandle " "object.") actor_name = _calculate_key(name) pickled_state = pickle.dumps(actor_handle) # Add the actor to Redis if it does not already exist. already_exists = _internal_kv_put(actor_name, pickled_state) if already_exists: # If the registration fails, then erase the new actor handle that # was added when pickling the actor handle. actor_handle._ray_new_actor_handles.pop() raise ValueError( "Error: the actor with name={} already exists".format(name))
Make sure all items of config are in schema def check_extraneous(config, schema): """Make sure all items of config are in schema""" if not isinstance(config, dict): raise ValueError("Config {} is not a dictionary".format(config)) for k in config: if k not in schema: raise ValueError("Unexpected config key `{}` not in {}".format( k, list(schema.keys()))) v, kreq = schema[k] if v is None: continue elif isinstance(v, type): if not isinstance(config[k], v): if v is str and isinstance(config[k], string_types): continue raise ValueError( "Config key `{}` has wrong type {}, expected {}".format( k, type(config[k]).__name__, v.__name__)) else: check_extraneous(config[k], v)
Required Dicts indicate that no extra fields can be introduced. 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)
Update the settings according to the keyword arguments. Args: kwargs: The keyword arguments to set corresponding fields. def update(self, **kwargs): """Update the settings according to the keyword arguments. Args: kwargs: The keyword arguments to set corresponding fields. """ for arg in kwargs: if hasattr(self, arg): setattr(self, arg, kwargs[arg]) else: raise ValueError("Invalid RayParams parameter in" " update: %s" % arg) self._check_usage()
Update the settings when the target fields are None. Args: kwargs: The keyword arguments to set corresponding fields. def update_if_absent(self, **kwargs): """Update the settings when the target fields are None. Args: kwargs: The keyword arguments to set corresponding fields. """ for arg in kwargs: if hasattr(self, arg): if getattr(self, arg) is None: setattr(self, arg, kwargs[arg]) else: raise ValueError("Invalid RayParams parameter in" " update_if_absent: %s" % arg) self._check_usage()
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 times the original actor handle has been forked so far. Returns: An ID for the new actor handle. 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): The original actor handle ID. num_forks: The number of times the original actor handle has been forked so far. Returns: An ID for the new actor handle. """ assert isinstance(actor_handle_id, ActorHandleID) handle_id_hash = hashlib.sha1() handle_id_hash.update(actor_handle_id.binary()) handle_id_hash.update(str(num_forks).encode("ascii")) handle_id = handle_id_hash.digest() return ActorHandleID(handle_id)
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 deterministic function of the actor ID, the previous actor handle ID and the current task ID. TODO(rkn): It may be possible to cause problems by closing over multiple actor handles in a remote function, which then get unpickled and give rise to the same actor handle IDs. Args: actor_handle_id: The original actor handle ID. current_task_id: The ID of the task that is unpickling the handle. Returns: An ID for the new actor handle. 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 actor handle is used, a new actor handle ID will be generated on the fly as a deterministic function of the actor ID, the previous actor handle ID and the current task ID. TODO(rkn): It may be possible to cause problems by closing over multiple actor handles in a remote function, which then get unpickled and give rise to the same actor handle IDs. Args: actor_handle_id: The original actor handle ID. current_task_id: The ID of the task that is unpickling the handle. Returns: An ID for the new actor handle. """ assert isinstance(actor_handle_id, ActorHandleID) assert isinstance(current_task_id, TaskID) handle_id_hash = hashlib.sha1() handle_id_hash.update(actor_handle_id.binary()) handle_id_hash.update(current_task_id.binary()) handle_id = handle_id_hash.digest() return ActorHandleID(handle_id)
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 that should be returned by invocations of this actor 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_return_vals: The number of object IDs that should be returned by invocations of this actor method. """ assert len(args) == 0 assert len(kwargs) == 1 assert "num_return_vals" in kwargs num_return_vals = kwargs["num_return_vals"] def annotate_method(method): method.__ray_num_return_vals__ = num_return_vals return method return annotate_method
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. 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 == ray.WORKER_MODE and not worker.actor_id.is_nil(): # Disconnect the worker from the raylet. The point of # this is so that when the worker kills itself below, the # raylet won't push an error message to the driver. worker.raylet_client.disconnect() ray.disconnect() # Disconnect global state from GCS. ray.global_state.disconnect() sys.exit(0) assert False, "This process should have terminated." else: raise Exception("exit_actor called on a non-actor worker.")
Get the available checkpoints for the given actor ID, return a list sorted by checkpoint timestamp in descending order. 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 [] checkpoints = [ Checkpoint(checkpoint_id, timestamp) for checkpoint_id, timestamp in zip(checkpoint_info["CheckpointIds"], checkpoint_info["Timestamps"]) ] return sorted( checkpoints, key=lambda checkpoint: checkpoint.timestamp, reverse=True, )
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. 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 the newly created actor. """ return self._remote(args=args, kwargs=kwargs)
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 forward to the actor constructor. num_cpus: The number of CPUs required by the actor creation task. num_gpus: The number of GPUs required by the actor creation task. resources: The custom resources required by the actor creation task. Returns: A handle to the newly created actor. 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 and override the defaults in the decorator. Args: args: The arguments to forward to the actor constructor. kwargs: The keyword arguments to forward to the actor constructor. num_cpus: The number of CPUs required by the actor creation task. num_gpus: The number of GPUs required by the actor creation task. resources: The custom resources required by the actor creation task. Returns: A handle to the newly created actor. """ if args is None: args = [] if kwargs is None: kwargs = {} worker = ray.worker.get_global_worker() if worker.mode is None: raise Exception("Actors cannot be created before ray.init() " "has been called.") actor_id = ActorID(_random_string()) # The actor cursor is a dummy object representing the most recent # actor method invocation. For each subsequent method invocation, # the current cursor should be added as a dependency, and then # updated to reflect the new invocation. actor_cursor = None # Set the actor's default resources if not already set. First three # conditions are to check that no resources were specified in the # decorator. Last three conditions are to check that no resources were # specified when _remote() was called. if (self._num_cpus is None and self._num_gpus is None and self._resources is None and num_cpus is None and num_gpus is None and resources is None): # In the default case, actors acquire no resources for # their lifetime, and actor methods will require 1 CPU. cpus_to_use = ray_constants.DEFAULT_ACTOR_CREATION_CPU_SIMPLE actor_method_cpu = ray_constants.DEFAULT_ACTOR_METHOD_CPU_SIMPLE else: # If any resources are specified (here or in decorator), then # all resources are acquired for the actor's lifetime and no # resources are associated with methods. cpus_to_use = (ray_constants.DEFAULT_ACTOR_CREATION_CPU_SPECIFIED if self._num_cpus is None else self._num_cpus) actor_method_cpu = ray_constants.DEFAULT_ACTOR_METHOD_CPU_SPECIFIED # Do not export the actor class or the actor if run in LOCAL_MODE # Instead, instantiate the actor locally and add it to the worker's # dictionary if worker.mode == ray.LOCAL_MODE: worker.actors[actor_id] = self._modified_class( *copy.deepcopy(args), **copy.deepcopy(kwargs)) else: # Export the actor. if not self._exported: worker.function_actor_manager.export_actor_class( self._modified_class, self._actor_method_names) self._exported = True resources = ray.utils.resources_from_resource_arguments( cpus_to_use, self._num_gpus, self._resources, num_cpus, num_gpus, resources) # If the actor methods require CPU resources, then set the required # placement resources. If actor_placement_resources is empty, then # the required placement resources will be the same as resources. actor_placement_resources = {} assert actor_method_cpu in [0, 1] if actor_method_cpu == 1: actor_placement_resources = resources.copy() actor_placement_resources["CPU"] += 1 function_name = "__init__" function_signature = self._method_signatures[function_name] creation_args = signature.extend_args(function_signature, args, kwargs) function_descriptor = FunctionDescriptor( self._modified_class.__module__, function_name, self._modified_class.__name__) [actor_cursor] = worker.submit_task( function_descriptor, creation_args, actor_creation_id=actor_id, max_actor_reconstructions=self._max_reconstructions, num_return_vals=1, resources=resources, placement_resources=actor_placement_resources) assert isinstance(actor_cursor, ObjectID) actor_handle = ActorHandle( actor_id, self._modified_class.__module__, self._class_name, actor_cursor, self._actor_method_names, self._method_signatures, self._actor_method_num_return_vals, actor_cursor, actor_method_cpu, worker.task_driver_id) # We increment the actor counter by 1 to account for the actor creation # task. actor_handle._ray_actor_counter += 1 return actor_handle
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: The name of the actor method to execute. args: A list of arguments for the actor method. kwargs: A dictionary of keyword arguments for the actor method. num_return_vals (int): The number of return values for the method. Returns: object_ids: A list of object IDs returned by the remote actor method. 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.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: The name of the actor method to execute. args: A list of arguments for the actor method. kwargs: A dictionary of keyword arguments for the actor method. num_return_vals (int): The number of return values for the method. Returns: object_ids: A list of object IDs returned by the remote actor method. """ worker = ray.worker.get_global_worker() worker.check_connected() function_signature = self._ray_method_signatures[method_name] if args is None: args = [] if kwargs is None: kwargs = {} args = signature.extend_args(function_signature, args, kwargs) # Execute functions locally if Ray is run in LOCAL_MODE # Copy args to prevent the function from mutating them. if worker.mode == ray.LOCAL_MODE: return getattr(worker.actors[self._ray_actor_id], method_name)(*copy.deepcopy(args)) function_descriptor = FunctionDescriptor( self._ray_module_name, method_name, self._ray_class_name) with self._ray_actor_lock: object_ids = worker.submit_task( function_descriptor, args, actor_id=self._ray_actor_id, actor_handle_id=self._ray_actor_handle_id, actor_counter=self._ray_actor_counter, actor_creation_dummy_object_id=( self._ray_actor_creation_dummy_object_id), execution_dependencies=[self._ray_actor_cursor], new_actor_handles=self._ray_new_actor_handles, # We add one for the dummy return ID. num_return_vals=num_return_vals + 1, resources={"CPU": self._ray_actor_method_cpus}, placement_resources={}, driver_id=self._ray_actor_driver_id, ) # Update the actor counter and cursor to reflect the most recent # invocation. self._ray_actor_counter += 1 # The last object returned is the dummy object that should be # passed in to the next actor method. Do not return it to the user. self._ray_actor_cursor = object_ids.pop() # We have notified the backend of the new actor handles to expect # since the last task was submitted, so clear the list. self._ray_new_actor_handles = [] if len(object_ids) == 1: object_ids = object_ids[0] elif len(object_ids) == 0: object_ids = None return object_ids
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. 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 the information needed to reconstruct the object. """ if ray_forking: actor_handle_id = compute_actor_handle_id( self._ray_actor_handle_id, self._ray_actor_forks) else: actor_handle_id = self._ray_actor_handle_id # Note: _ray_actor_cursor and _ray_actor_creation_dummy_object_id # could be None. state = { "actor_id": self._ray_actor_id, "actor_handle_id": actor_handle_id, "module_name": self._ray_module_name, "class_name": self._ray_class_name, "actor_cursor": self._ray_actor_cursor, "actor_method_names": self._ray_actor_method_names, "method_signatures": self._ray_method_signatures, "method_num_return_vals": self._ray_method_num_return_vals, # Actors in local mode don't have dummy objects. "actor_creation_dummy_object_id": self. _ray_actor_creation_dummy_object_id, "actor_method_cpus": self._ray_actor_method_cpus, "actor_driver_id": self._ray_actor_driver_id, "ray_forking": ray_forking } if ray_forking: self._ray_actor_forks += 1 new_actor_handle_id = actor_handle_id else: # The execution dependency for a pickled actor handle is never safe # to release, since it could be unpickled and submit another # dependent task at any time. Therefore, we notify the backend of a # random handle ID that will never actually be used. new_actor_handle_id = ActorHandleID(_random_string()) # Notify the backend to expect this new actor handle. The backend will # not release the cursor for any new handles until the first task for # each of the new handles is submitted. # NOTE(swang): There is currently no garbage collection for actor # handles until the actor itself is removed. self._ray_new_actor_handles.append(new_actor_handle_id) return state
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. 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 being called by pickling. """ worker = ray.worker.get_global_worker() worker.check_connected() if state["ray_forking"]: actor_handle_id = state["actor_handle_id"] else: # Right now, if the actor handle has been pickled, we create a # temporary actor handle id for invocations. # TODO(pcm): This still leads to a lot of actor handles being # created, there should be a better way to handle pickled # actor handles. # TODO(swang): Accessing the worker's current task ID is not # thread-safe. # TODO(swang): Unpickling the same actor handle twice in the same # task will break the application, and unpickling it twice in the # same actor is likely a performance bug. We should consider # logging a warning in these cases. actor_handle_id = compute_actor_handle_id_non_forked( state["actor_handle_id"], worker.current_task_id) self.__init__( state["actor_id"], state["module_name"], state["class_name"], state["actor_cursor"], state["actor_method_names"], state["method_signatures"], state["method_num_return_vals"], state["actor_creation_dummy_object_id"], state["actor_method_cpus"], # This is the driver ID of the driver that owns the actor, not # necessarily the driver that owns this actor handle. state["actor_driver_id"], actor_handle_id=actor_handle_id)
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 will be discarded. Args: sess: TensorFlow session. inputs: List of arrays matching the input placeholders, of shape [BATCH_SIZE, ...]. state_inputs: List of RNN input arrays. These arrays have size [BATCH_SIZE / MAX_SEQ_LEN, ...]. Returns: The number of tuples loaded per device. 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 evenly divisible by the batch size, excess data will be discarded. Args: sess: TensorFlow session. inputs: List of arrays matching the input placeholders, of shape [BATCH_SIZE, ...]. state_inputs: List of RNN input arrays. These arrays have size [BATCH_SIZE / MAX_SEQ_LEN, ...]. Returns: The number of tuples loaded per device. """ if log_once("load_data"): logger.info( "Training on concatenated sample batches:\n\n{}\n".format( summarize({ "placeholders": self.loss_inputs, "inputs": inputs, "state_inputs": state_inputs }))) feed_dict = {} assert len(self.loss_inputs) == len(inputs + state_inputs), \ (self.loss_inputs, inputs, state_inputs) # Let's suppose we have the following input data, and 2 devices: # 1 2 3 4 5 6 7 <- state inputs shape # A A A B B B C C C D D D E E E F F F G G G <- inputs shape # The data is truncated and split across devices as follows: # |---| seq len = 3 # |---------------------------------| seq batch size = 6 seqs # |----------------| per device batch size = 9 tuples if len(state_inputs) > 0: smallest_array = state_inputs[0] seq_len = len(inputs[0]) // len(state_inputs[0]) self._loaded_max_seq_len = seq_len else: smallest_array = inputs[0] self._loaded_max_seq_len = 1 sequences_per_minibatch = ( self.max_per_device_batch_size // self._loaded_max_seq_len * len( self.devices)) if sequences_per_minibatch < 1: logger.warn( ("Target minibatch size is {}, however the rollout sequence " "length is {}, hence the minibatch size will be raised to " "{}.").format(self.max_per_device_batch_size, self._loaded_max_seq_len, self._loaded_max_seq_len * len(self.devices))) sequences_per_minibatch = 1 if len(smallest_array) < sequences_per_minibatch: # Dynamically shrink the batch size if insufficient data sequences_per_minibatch = make_divisible_by( len(smallest_array), len(self.devices)) if log_once("data_slicing"): logger.info( ("Divided {} rollout sequences, each of length {}, among " "{} devices.").format( len(smallest_array), self._loaded_max_seq_len, len(self.devices))) if sequences_per_minibatch < len(self.devices): raise ValueError( "Must load at least 1 tuple sequence per device. Try " "increasing `sgd_minibatch_size` or reducing `max_seq_len` " "to ensure that at least one sequence fits per device.") self._loaded_per_device_batch_size = (sequences_per_minibatch // len( self.devices) * self._loaded_max_seq_len) if len(state_inputs) > 0: # First truncate the RNN state arrays to the sequences_per_minib. state_inputs = [ make_divisible_by(arr, sequences_per_minibatch) for arr in state_inputs ] # Then truncate the data inputs to match inputs = [arr[:len(state_inputs[0]) * seq_len] for arr in inputs] assert len(state_inputs[0]) * seq_len == len(inputs[0]), \ (len(state_inputs[0]), sequences_per_minibatch, seq_len, len(inputs[0])) for ph, arr in zip(self.loss_inputs, inputs + state_inputs): feed_dict[ph] = arr truncated_len = len(inputs[0]) else: for ph, arr in zip(self.loss_inputs, inputs + state_inputs): truncated_arr = make_divisible_by(arr, sequences_per_minibatch) feed_dict[ph] = truncated_arr truncated_len = len(truncated_arr) sess.run([t.init_op for t in self._towers], feed_dict=feed_dict) self.num_tuples_loaded = truncated_len tuples_per_device = truncated_len // len(self.devices) assert tuples_per_device > 0, "No data loaded?" assert tuples_per_device % self._loaded_per_device_batch_size == 0 return tuples_per_device
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: sess: TensorFlow session. batch_index: Offset into the preloaded data. This value must be between `0` and `tuples_per_device`. The amount of data to process is at most `max_per_device_batch_size`. Returns: The outputs of extra_ops evaluated over the batch. 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-device gradients. Args: sess: TensorFlow session. batch_index: Offset into the preloaded data. This value must be between `0` and `tuples_per_device`. The amount of data to process is at most `max_per_device_batch_size`. Returns: The outputs of extra_ops evaluated over the batch. """ feed_dict = { self._batch_index: batch_index, self._per_device_batch_size: self._loaded_per_device_batch_size, self._max_seq_len: self._loaded_max_seq_len, } for tower in self._towers: feed_dict.update(tower.loss_graph.extra_compute_grad_feed_dict()) fetches = {"train": self._train_op} for tower in self._towers: fetches.update(tower.loss_graph.extra_compute_grad_fetches()) return sess.run(fetches, feed_dict=feed_dict)
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). Args: sorted_trials: List of finished trials with top performance ones first. Returns: A list of new genes (encodings) 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 ratio (_selection_bound, _crossover_bound). Args: sorted_trials: List of finished trials with top performance ones first. Returns: A list of new genes (encodings) """ candidate = [] next_generation = [] num_population = self._next_population_size(len(sorted_trials)) top_num = int(max(num_population * self._keep_top_ratio, 2)) for i in range(top_num): candidate.append(sorted_trials[i].extra_arg) next_generation.append(sorted_trials[i].extra_arg) for i in range(top_num, num_population): flip_coin = np.random.uniform() if flip_coin < self._selection_bound: next_generation.append(GeneticSearch._selection(candidate)) else: if flip_coin < self._selection_bound + self._crossover_bound: next_generation.append(GeneticSearch._crossover(candidate)) else: next_generation.append(GeneticSearch._mutation(candidate)) return next_generation
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]]) >>> gene2 = np.array([[0, 1, 0], [1, 0], [0, 1]]) >>> new_gene = _selection([gene1, gene2]) >>> # new_gene could be gene1 overwritten with the >>> # 2nd parameter of gene2 >>> # in which case: >>> # new_gene[0] = gene1[0] >>> # new_gene[1] = gene2[1] >>> # new_gene[2] = gene1[0] Returns: New gene (encoding) 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.array([[0, 0, 1], [0, 1], [1, 0]]) >>> gene2 = np.array([[0, 1, 0], [1, 0], [0, 1]]) >>> new_gene = _selection([gene1, gene2]) >>> # new_gene could be gene1 overwritten with the >>> # 2nd parameter of gene2 >>> # in which case: >>> # new_gene[0] = gene1[0] >>> # new_gene[1] = gene2[1] >>> # new_gene[2] = gene1[0] Returns: New gene (encoding) """ sample_index1 = np.random.choice(len(candidate)) sample_index2 = np.random.choice(len(candidate)) sample_1 = candidate[sample_index1] sample_2 = candidate[sample_index2] select_index = np.random.choice(len(sample_1)) logger.info( LOGGING_PREFIX + "Perform selection from %sth to %sth at index=%s", sample_index2, sample_index1, select_index) next_gen = [] for i in range(len(sample_1)): if i is select_index: next_gen.append(sample_2[i]) else: next_gen.append(sample_1[i]) return next_gen
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]]) >>> gene2 = np.array([[0, 1, 0], [1, 0], [0, 1]]) >>> new_gene = _crossover([gene1, gene2]) >>> # new_gene could be the first [n=1] parameters of >>> # gene1 + the rest of gene2 >>> # in which case: >>> # new_gene[0] = gene1[0] >>> # new_gene[1] = gene2[1] >>> # new_gene[2] = gene1[1] Returns: New gene (encoding) 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([[0, 0, 1], [0, 1], [1, 0]]) >>> gene2 = np.array([[0, 1, 0], [1, 0], [0, 1]]) >>> new_gene = _crossover([gene1, gene2]) >>> # new_gene could be the first [n=1] parameters of >>> # gene1 + the rest of gene2 >>> # in which case: >>> # new_gene[0] = gene1[0] >>> # new_gene[1] = gene2[1] >>> # new_gene[2] = gene1[1] Returns: New gene (encoding) """ sample_index1 = np.random.choice(len(candidate)) sample_index2 = np.random.choice(len(candidate)) sample_1 = candidate[sample_index1] sample_2 = candidate[sample_index2] cross_index = int(len(sample_1) * np.random.uniform(low=0.3, high=0.7)) logger.info( LOGGING_PREFIX + "Perform crossover between %sth and %sth at index=%s", sample_index1, sample_index2, cross_index) next_gen = [] for i in range(len(sample_1)): if i > cross_index: next_gen.append(sample_2[i]) else: next_gen.append(sample_1[i]) return next_gen
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.array([[0, 0, 1], [0, 1], [1, 0]]) >>> new_gene = _mutation([gene1]) >>> # new_gene could be the gene1 with the 3rd parameter changed >>> # new_gene[0] = gene1[0] >>> # new_gene[1] = gene1[1] >>> # new_gene[2] = [0, 1] != gene1[2] Returns: New gene (encoding) 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 represent 3 parameters >>> gene1 = np.array([[0, 0, 1], [0, 1], [1, 0]]) >>> new_gene = _mutation([gene1]) >>> # new_gene could be the gene1 with the 3rd parameter changed >>> # new_gene[0] = gene1[0] >>> # new_gene[1] = gene1[1] >>> # new_gene[2] = [0, 1] != gene1[2] Returns: New gene (encoding) """ sample_index = np.random.choice(len(candidate)) sample = candidate[sample_index] idx_list = [] for i in range(int(max(len(sample) * rate, 1))): idx = np.random.choice(len(sample)) idx_list.append(idx) field = sample[idx] # one-hot encoding field[np.argmax(field)] = 0 bit = np.random.choice(field.shape[0]) field[bit] = 1 logger.info(LOGGING_PREFIX + "Perform mutation on %sth at index=%s", sample_index, str(idx_list)) return sample
Lists trials in the directory subtree starting at the given path. 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_trials(experiment_path, sort, output, filter_op, columns, result_columns)
Lists experiments in the directory subtree. 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)
Start one iteration of training and save remote id. def _train(self, trial): """Start one iteration of training and save remote id.""" assert trial.status == Trial.RUNNING, trial.status remote = trial.runner.train.remote() # Local Mode if isinstance(remote, dict): remote = _LocalWrapper(remote) self._running[remote] = trial
Starts trial and restores last result if trial was paused. Raises: ValueError if restoring from checkpoint fails. 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._setup_runner( trial, reuse_allowed=checkpoint is not None or trial._checkpoint.value is not None) if not self.restore(trial, checkpoint): if trial.status == Trial.ERROR: raise RuntimeError( "Restore from checkpoint failed for Trial {}.".format( str(trial))) previous_run = self._find_item(self._paused, trial) if (prior_status == Trial.PAUSED and previous_run): # If Trial was in flight when paused, self._paused stores result. self._paused.pop(previous_run[0]) self._running[previous_run[0]] = trial else: self._train(trial)
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 (str): Optional error message. stop_logger (bool): Whether to shut down the trial logger. 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. Args: error (bool): Whether to mark this trial as terminated in error. error_msg (str): Optional error message. stop_logger (bool): Whether to shut down the trial logger. """ if stop_logger: trial.close_logger() if error: self.set_status(trial, Trial.ERROR) else: self.set_status(trial, Trial.TERMINATED) try: trial.write_error_log(error_msg) if hasattr(trial, "runner") and trial.runner: if (not error and self._reuse_actors and self._cached_actor is None): logger.debug("Reusing actor for {}".format(trial.runner)) self._cached_actor = trial.runner else: logger.info( "Destroying actor for trial {}. If your trainable is " "slow to initialize, consider setting " "reuse_actors=True to reduce actor creation " "overheads.".format(trial)) trial.runner.stop.remote() trial.runner.__ray_terminate__.remote() except Exception: logger.exception("Error stopping runner for Trial %s", str(trial)) self.set_status(trial, Trial.ERROR) finally: trial.runner = 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): """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. """ self._commit_resources(trial.resources) try: self._start_trial(trial, checkpoint) except Exception as e: logger.exception("Error starting runner for Trial %s", str(trial)) error_msg = traceback.format_exc() time.sleep(2) self._stop_trial(trial, error=True, error_msg=error_msg) if isinstance(e, AbortTrialExecution): return # don't retry fatal Tune errors try: # This forces the trial to not start from checkpoint. trial.clear_checkpoint() logger.info( "Trying to start runner for Trial %s without checkpoint.", str(trial)) self._start_trial(trial) except Exception: logger.exception( "Error starting runner for Trial %s, aborting!", str(trial)) error_msg = traceback.format_exc() self._stop_trial(trial, error=True, error_msg=error_msg)
Only returns resources if resources allocated. def stop_trial(self, trial, error=False, error_msg=None, stop_logger=True): """Only returns resources if resources allocated.""" prior_status = trial.status self._stop_trial( trial, error=error, error_msg=error_msg, stop_logger=stop_logger) if prior_status == Trial.RUNNING: logger.debug("Returning resources for Trial %s.", str(trial)) self._return_resources(trial.resources) out = self._find_item(self._running, trial) for result_id in out: self._running.pop(result_id)
Pauses the trial. If trial is in-flight, preserves return value in separate queue before pausing, which is restored when Trial is resumed. 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[trial_future[0]] = trial super(RayTrialExecutor, self).pause_trial(trial)
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: True if `reset_config` is successful else False. 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 experiment name for trial. Returns: True if `reset_config` is successful else False. """ trial.experiment_tag = new_experiment_tag trial.config = new_config trainable = trial.runner with warn_if_slow("reset_config"): reset_val = ray.get(trainable.reset_config.remote(new_config)) return reset_val
Fetches one result of the running trials. Returns: Result of the most recent trial training run. def fetch_result(self, trial): """Fetches one result of the running trials. Returns: Result of the most recent trial training run.""" trial_future = self._find_item(self._running, trial) if not trial_future: raise ValueError("Trial was not running.") self._running.pop(trial_future[0]) with warn_if_slow("fetch_result"): result = ray.get(trial_future[0]) # For local mode if isinstance(result, _LocalWrapper): result = result.unwrap() return result
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): """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. """ if time.time() - self._last_resource_refresh > self._refresh_period: self._update_avail_resources() currently_available = Resources.subtract(self._avail_resources, self._committed_resources) have_space = ( resources.cpu_total() <= currently_available.cpu and resources.gpu_total() <= currently_available.gpu and all( resources.get_res_total(res) <= currently_available.get(res) for res in resources.custom_resources)) if have_space: return True can_overcommit = self._queue_trials if (resources.cpu_total() > 0 and currently_available.cpu <= 0) or \ (resources.gpu_total() > 0 and currently_available.gpu <= 0) or \ any((resources.get_res_total(res_name) > 0 and currently_available.get(res_name) <= 0) for res_name in resources.custom_resources): can_overcommit = False # requested resource is already saturated if can_overcommit: logger.warning( "Allowing trial to start even though the " "cluster does not have enough free resources. Trial actors " "may appear to hang until enough resources are added to the " "cluster (e.g., via autoscaling). You can disable this " "behavior by specifying `queue_trials=False` in " "ray.tune.run().") return True return False
Returns a human readable message for printing to the console. 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._committed_resources.gpu, self._avail_resources.gpu) customs = ", ".join([ "{}/{} {}".format( self._committed_resources.get_res_total(name), self._avail_resources.get_res_total(name), name) for name in self._avail_resources.custom_resources ]) if customs: status += " ({})".format(customs) return status else: return "Resources requested: ?"
Returns a string describing the total resources available. def resource_string(self): """Returns a string describing the total resources available.""" if self._resources_initialized: res_str = "{} CPUs, {} GPUs".format(self._avail_resources.cpu, self._avail_resources.gpu) if self._avail_resources.custom_resources: custom = ", ".join( "{} {}".format( self._avail_resources.get_res_total(name), name) for name in self._avail_resources.custom_resources) res_str += " ({})".format(custom) return res_str else: return "? CPUs, ? GPUs"
Saves the trial's state to a checkpoint. def save(self, trial, storage=Checkpoint.DISK): """Saves the trial's state to a checkpoint.""" trial._checkpoint.storage = storage trial._checkpoint.last_result = trial.last_result if storage == Checkpoint.MEMORY: trial._checkpoint.value = trial.runner.save_to_object.remote() else: # Keeps only highest performing checkpoints if enabled if trial.keep_checkpoints_num: try: last_attr_val = trial.last_result[ trial.checkpoint_score_attr] if (trial.compare_checkpoints(last_attr_val) and not math.isnan(last_attr_val)): trial.best_checkpoint_attr_value = last_attr_val self._checkpoint_and_erase(trial) except KeyError: logger.warning( "Result dict has no key: {}. keep" "_checkpoints_num flag will not work".format( trial.checkpoint_score_attr)) else: with warn_if_slow("save_to_disk"): trial._checkpoint.value = ray.get( trial.runner.save.remote()) return trial._checkpoint.value
Checkpoints the model and erases old checkpoints if needed. Parameters ---------- trial : trial to save 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.remote()) if len(trial.history) >= trial.keep_checkpoints_num: ray.get(trial.runner.delete_checkpoint.remote(trial.history[-1])) trial.history.pop() trial.history.insert(0, trial._checkpoint.value)
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. 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._checkpoint if checkpoint is None or checkpoint.value is None: return True if trial.runner is None: logger.error("Unable to restore - no runner.") self.set_status(trial, Trial.ERROR) return False try: value = checkpoint.value if checkpoint.storage == Checkpoint.MEMORY: assert type(value) != Checkpoint, type(value) trial.runner.restore_from_object.remote(value) else: worker_ip = ray.get(trial.runner.current_ip.remote()) trial.sync_logger_to_new_location(worker_ip) with warn_if_slow("restore_from_disk"): ray.get(trial.runner.restore.remote(value)) trial.last_result = checkpoint.last_result return True except Exception: logger.exception("Error restoring runner for Trial %s.", trial) self.set_status(trial, Trial.ERROR) return False
Exports model of this trial based on trial.export_formats. Return: A dict that maps ExportFormats to successfully exported models. 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( trial.runner.export_model.remote(trial.export_formats)) return {}
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 input channels of the instance (see: DataInput in communication.py). input (DataOutput): The output gate that manages output channels of the instance (see: DataOutput in communication.py). 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 logical operator. input (DataInput): The input gate that manages input channels of the instance (see: DataInput in communication.py). input (DataOutput): The output gate that manages output channels of the instance (see: DataOutput in communication.py). """ actor_id = (operator.id, instance_id) # Record the physical dataflow graph (for debugging purposes) self.__add_channel(actor_id, input, output) # Select actor to construct if operator.type == OpType.Source: source = operator_instance.Source.remote(actor_id, operator, input, output) source.register_handle.remote(source) return source.start.remote() elif operator.type == OpType.Map: map = operator_instance.Map.remote(actor_id, operator, input, output) map.register_handle.remote(map) return map.start.remote() elif operator.type == OpType.FlatMap: flatmap = operator_instance.FlatMap.remote(actor_id, operator, input, output) flatmap.register_handle.remote(flatmap) return flatmap.start.remote() elif operator.type == OpType.Filter: filter = operator_instance.Filter.remote(actor_id, operator, input, output) filter.register_handle.remote(filter) return filter.start.remote() elif operator.type == OpType.Reduce: reduce = operator_instance.Reduce.remote(actor_id, operator, input, output) reduce.register_handle.remote(reduce) return reduce.start.remote() elif operator.type == OpType.TimeWindow: pass elif operator.type == OpType.KeyBy: keyby = operator_instance.KeyBy.remote(actor_id, operator, input, output) keyby.register_handle.remote(keyby) return keyby.start.remote() elif operator.type == OpType.Sum: sum = operator_instance.Reduce.remote(actor_id, operator, input, output) # Register target handle at state actor state_actor = operator.state_actor if state_actor is not None: state_actor.register_target.remote(sum) # Register own handle sum.register_handle.remote(sum) return sum.start.remote() elif operator.type == OpType.Sink: pass elif operator.type == OpType.Inspect: inspect = operator_instance.Inspect.remote(actor_id, operator, input, output) inspect.register_handle.remote(inspect) return inspect.start.remote() elif operator.type == OpType.ReadTextFile: # TODO (john): Colocate the source with the input file read = operator_instance.ReadTextFile.remote( actor_id, operator, input, output) read.register_handle.remote(read) return read.start.remote() else: # TODO (john): Add support for other types of operators sys.exit("Unrecognized or unsupported {} operator type.".format( operator.type))
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 list of all downstream channels for all instances of the operator. 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 list of all upstream channels for all instances of the operator. downstream_channels (list): A list of all downstream channels for all instances of the operator. """ num_instances = operator.num_instances logger.info("Generating {} actors of type {}...".format( num_instances, operator.type)) in_channels = upstream_channels.pop( operator.id) if upstream_channels else [] handles = [] for i in range(num_instances): # Collect input and output channels for the particular instance ip = [ channel for channel in in_channels if channel.dst_instance_id == i ] if in_channels else [] op = [ channel for channels_list in downstream_channels.values() for channel in channels_list if channel.src_instance_id == i ] log = "Constructed {} input and {} output channels " log += "for the {}-th instance of the {} operator." logger.debug(log.format(len(ip), len(op), i, operator.type)) input_gate = DataInput(ip) output_gate = DataOutput(op, operator.partitioning_strategies) handle = self.__generate_actor(i, operator, input_gate, output_gate) if handle: handles.append(handle) return handles
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 given operator and instance_2 is an instance of a direct downstream operator. The number of total channels generated depends on the partitioning strategy specified by the user. 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), where instance_1 is an instance of the given operator and instance_2 is an instance of a direct downstream operator. The number of total channels generated depends on the partitioning strategy specified by the user. """ channels = {} # destination operator id -> channels strategies = operator.partitioning_strategies for dst_operator, p_scheme in strategies.items(): num_dest_instances = self.operators[dst_operator].num_instances entry = channels.setdefault(dst_operator, []) if p_scheme.strategy == PStrategy.Forward: for i in range(operator.num_instances): # ID of destination instance to connect id = i % num_dest_instances channel = DataChannel(self, operator.id, dst_operator, i, id) entry.append(channel) elif p_scheme.strategy in all_to_all_strategies: for i in range(operator.num_instances): for j in range(num_dest_instances): channel = DataChannel(self, operator.id, dst_operator, i, j) entry.append(channel) else: # TODO (john): Add support for other partitioning strategies sys.exit("Unrecognized or unsupported partitioning strategy.") return channels
Deploys and executes the physical dataflow. def execute(self): """Deploys and executes the physical dataflow.""" self._collect_garbage() # Make sure everything is clean # TODO (john): Check if dataflow has any 'logical inconsistencies' # For example, if there is a forward partitioning strategy but # the number of downstream instances is larger than the number of # upstream instances, some of the downstream instances will not be # used at all # Each operator instance is implemented as a Ray actor # Actors are deployed in topological order, as we traverse the # logical dataflow from sources to sinks. At each step, data # producers wait for acknowledge from consumers before starting # generating data. upstream_channels = {} for node in nx.topological_sort(self.logical_topo): operator = self.operators[node] # Generate downstream data channels downstream_channels = self._generate_channels(operator) # Instantiate Ray actors handles = self.__generate_actors(operator, upstream_channels, downstream_channels) if handles: self.actor_handles.extend(handles) upstream_channels.update(downstream_channels) logger.debug("Running...") return self.actor_handles
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. 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 operator. """ self.env.operators[operator.id] = operator self.dst_operator_id = operator.id logger.debug("Adding new dataflow edge ({},{}) --> ({},{})".format( self.src_operator_id, self.env.operators[self.src_operator_id].name, self.dst_operator_id, self.env.operators[self.dst_operator_id].name)) # Update logical dataflow graphs self.env._add_edge(self.src_operator_id, self.dst_operator_id) # Keep track of the partitioning strategy and the destination operator src_operator = self.env.operators[self.src_operator_id] if self.is_partitioned is True: partitioning, _ = src_operator._get_partition_strategy(self.id) src_operator._set_partition_strategy(_generate_uuid(), partitioning, operator.id) elif src_operator.type == OpType.KeyBy: # Set the output partitioning strategy to shuffle by key partitioning = PScheme(PStrategy.ShuffleByKey) src_operator._set_partition_strategy(_generate_uuid(), partitioning, operator.id) else: # No partitioning strategy has been defined - set default partitioning = PScheme(PStrategy.Forward) src_operator._set_partition_strategy(_generate_uuid(), partitioning, operator.id) return self.__expand()
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. 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._set_parallelism(self.src_operator_id, num_instances) return self
Applies a map operator to the stream. Attributes: map_fn (function): The user-defined logic of the 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_instances=self.env.config.parallelism) return self.__register(op)