INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Convert gradients to grayscale. This gives a saliency map.
def to_grayscale(cv2im): """Convert gradients to grayscale. This gives a saliency map.""" # How strongly does each position activate the output grayscale_im = np.sum(np.abs(cv2im), axis=0) # Normalize between min and 99th percentile im_max = np.percentile(grayscale_im, 99) im_min = np.min(grays...
Helper function for checking shape of label and prediction Parameters ---------- labels : list of `NDArray` The labels of the data. preds : list of `NDArray` Predicted values. wrap : boolean If True, wrap labels/preds in a list if they are single NDArray shape : boole...
def check_label_shapes(labels, preds, wrap=False, shape=False): """Helper function for checking shape of label and prediction Parameters ---------- labels : list of `NDArray` The labels of the data. preds : list of `NDArray` Predicted values. wrap : boolean If True, wr...
Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. Parameters ---------- metric : str or callable Specifies the metric to create. This argument must be one of the below: - Name of a metric. - An instance of `EvalMetric`. ...
def create(metric, *args, **kwargs): """Creates evaluation metric from metric names or instances of EvalMetric or a custom metric function. Parameters ---------- metric : str or callable Specifies the metric to create. This argument must be one of the below: - Name of a met...
Creates a custom evaluation metric that receives its inputs as numpy arrays. Parameters ---------- numpy_feval : callable(label, pred) Custom evaluation function that receives labels and predictions for a minibatch as numpy arrays and returns the corresponding custom metric as a floating po...
def np(numpy_feval, name=None, allow_extra_outputs=False): """Creates a custom evaluation metric that receives its inputs as numpy arrays. Parameters ---------- numpy_feval : callable(label, pred) Custom evaluation function that receives labels and predictions for a minibatch as numpy a...
Save configurations of metric. Can be recreated from configs with metric.create(``**config``)
def get_config(self): """Save configurations of metric. Can be recreated from configs with metric.create(``**config``) """ config = self._kwargs.copy() config.update({ 'metric': self.__class__.__name__, 'name': self.name, 'output_names': self.o...
Update the internal evaluation with named label and pred Parameters ---------- labels : OrderedDict of str -> NDArray name to array mapping for labels. preds : OrderedDict of str -> NDArray name to array mapping of predicted outputs.
def update_dict(self, label, pred): """Update the internal evaluation with named label and pred Parameters ---------- labels : OrderedDict of str -> NDArray name to array mapping for labels. preds : OrderedDict of str -> NDArray name to array mapping of ...
Resets the internal evaluation result to initial state.
def reset(self): """Resets the internal evaluation result to initial state.""" self.num_inst = 0 self.sum_metric = 0.0 self.global_num_inst = 0 self.global_sum_metric = 0.0
Gets the current evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations.
def get(self): """Gets the current evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self.num_inst == 0: return (self.name, float('nan')) e...
Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations.
def get_global(self): """Gets the current global evaluation result. Returns ------- names : list of str Name of the metrics. values : list of float Value of the evaluations. """ if self._has_global_stats: if self.global_num_inst ...
Returns zipped name and value pairs. Returns ------- list of tuples A (name, value) tuple list.
def get_name_value(self): """Returns zipped name and value pairs. Returns ------- list of tuples A (name, value) tuple list. """ name, value = self.get() if not isinstance(name, list): name = [name] if not isinstance(value, list): ...
Returns zipped name and value pairs for global results. Returns ------- list of tuples A (name, value) tuple list.
def get_global_name_value(self): """Returns zipped name and value pairs for global results. Returns ------- list of tuples A (name, value) tuple list. """ if self._has_global_stats: name, value = self.get_global() if not isinstance(nam...
Update various binary classification counts for a single (label, pred) pair. Parameters ---------- label : `NDArray` The labels of the data. pred : `NDArray` Predicted values.
def update_binary_stats(self, label, pred): """ Update various binary classification counts for a single (label, pred) pair. Parameters ---------- label : `NDArray` The labels of the data. pred : `NDArray` Predicted values. """ ...
Calculate the Matthew's Correlation Coefficent
def matthewscc(self, use_global=False): """ Calculate the Matthew's Correlation Coefficent """ if use_global: if not self.global_total_examples: return 0. true_pos = float(self.global_true_positives) false_pos = float(self.global_false...
Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. lazy : bool, default True If False...
def transform(self, fn, lazy=True): """Returns a new dataset with each sample transformed by the transformer function `fn`. Parameters ---------- fn : callable A transformer function that takes a sample as input and returns the transformed sample. ...
Returns a new dataset with the first element of each sample transformed by the transformer function `fn`. This is useful, for example, when you only want to transform data while keeping label as is. Parameters ---------- fn : callable A transformer function ...
def transform_first(self, fn, lazy=True): """Returns a new dataset with the first element of each sample transformed by the transformer function `fn`. This is useful, for example, when you only want to transform data while keeping label as is. Parameters ---------- ...
Forward the image through the LSTM network model Parameters ---------- img_: int of array Returns ---------- label_list: string of list
def forward_ocr(self, img_): """Forward the image through the LSTM network model Parameters ---------- img_: int of array Returns ---------- label_list: string of list """ img_ = cv2.resize(img_, (80, 30)) img_ = img_.transpose(1, 0) ...
Return a caffe_pb2.NetParameter object that defined in a prototxt file
def read_prototxt(fname): """Return a caffe_pb2.NetParameter object that defined in a prototxt file """ proto = caffe_pb2.NetParameter() with open(fname, 'r') as f: text_format.Merge(str(f.read()), proto) return proto
Returns layers in a caffe_pb2.NetParameter object
def get_layers(proto): """Returns layers in a caffe_pb2.NetParameter object """ if len(proto.layer): return proto.layer elif len(proto.layers): return proto.layers else: raise ValueError('Invalid proto file.')
Return a caffe_pb2.NetParameter object that defined in a binary caffemodel file
def read_caffemodel(prototxt_fname, caffemodel_fname): """Return a caffe_pb2.NetParameter object that defined in a binary caffemodel file """ if use_caffe: caffe.set_mode_cpu() net = caffe.Net(prototxt_fname, caffemodel_fname, caffe.TEST) layer_names = net._layer_names la...
Iterate over all layers
def layer_iter(layers, layer_names): """Iterate over all layers""" if use_caffe: for layer_idx, layer in enumerate(layers): layer_name = re.sub('[-/]', '_', layer_names[layer_idx]) layer_type = layer.type layer_blobs = layer.blobs yield (layer_name, layer_...
Set up the configure of profiler (only accepts keyword arguments). Parameters ---------- filename : string, output file for profile data profile_all : boolean, all profile types enabled profile_symbolic : boolean, whether to profile symbolic operators profile_imperative ...
def set_config(**kwargs): """Set up the configure of profiler (only accepts keyword arguments). Parameters ---------- filename : string, output file for profile data profile_all : boolean, all profile types enabled profile_symbolic : boolean, whether to profile symbolic ...
Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, optional The name of output trace file. Defaults to 'profile.json'.
def profiler_set_config(mode='symbolic', filename='profile.json'): """Set up the configure of profiler (Deprecated). Parameters ---------- mode : string, optional Indicates whether to enable the profiler, can be 'symbolic', or 'all'. Defaults to `symbolic`. filename : string, option...
Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profile kvstore `server` or `worker`. server can only be pro...
def set_state(state='stop', profile_process='worker'): """Set up the profiler state to 'run' or 'stop'. Parameters ---------- state : string, optional Indicates whether to run the profiler, can be 'stop' or 'run'. Default is `stop`. profile_process : string whether to profil...
Dump profile and stop profiler. Use this to save profile in advance in case your program cannot exit normally. Parameters ---------- finished : boolean Indicates whether to stop statistic output (dumping) after this dump. Default is True profile_process : string whether to p...
def dump(finished=True, profile_process='worker'): """Dump profile and stop profiler. Use this to save profile in advance in case your program cannot exit normally. Parameters ---------- finished : boolean Indicates whether to stop statistic output (dumping) after this dump. Default...
Return a printable string of aggregate profile stats. Parameters ---------- reset: boolean Indicates whether to clean aggeregate statistical data collected up to this point
def dumps(reset=False): """Return a printable string of aggregate profile stats. Parameters ---------- reset: boolean Indicates whether to clean aggeregate statistical data collected up to this point """ debug_str = ctypes.c_char_p() do_reset = 1 if reset is True else 0 check_ca...
Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
def pause(profile_process='worker'): """Pause profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ profile_proc...
Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker`
def resume(profile_process='worker'): """ Resume paused profiling. Parameters ---------- profile_process : string whether to profile kvstore `server` or `worker`. server can only be profiled when kvstore is of type dist. if this is not passed, defaults to `worker` """ ...
Set counter value. Parameters ---------- value : int Value for the counter
def set_value(self, value): """Set counter value. Parameters ---------- value : int Value for the counter """ check_call(_LIB.MXProfileSetCounter(self.handle, int(value)))
Increment counter value. Parameters ---------- value_change : int Amount by which to add to the counter
def increment(self, delta=1): """Increment counter value. Parameters ---------- value_change : int Amount by which to add to the counter """ check_call(_LIB.MXProfileAdjustCounter(self.handle, int(delta)))
Decrement counter value. Parameters ---------- value_change : int Amount by which to subtract from the counter
def decrement(self, delta=1): """Decrement counter value. Parameters ---------- value_change : int Amount by which to subtract from the counter """ check_call(_LIB.MXProfileAdjustCounter(self.handle, -int(delta)))
Set up the profiler state to record operator. Parameters ---------- scope : string, optional Indicates what scope the marker should refer to. Can be 'global', 'process', thread', task', and 'marker' Default is `process`.
def mark(self, scope='process'): """Set up the profiler state to record operator. Parameters ---------- scope : string, optional Indicates what scope the marker should refer to. Can be 'global', 'process', thread', task', and 'marker' Default is `proc...
r"""Get CUDA kernel from compiled module. Parameters ---------- name : str String name of the kernel. signature : str Function signature for the kernel. For example, if a kernel is declared as:: extern "C" __global__ void axpy(const f...
def get_kernel(self, name, signature): r"""Get CUDA kernel from compiled module. Parameters ---------- name : str String name of the kernel. signature : str Function signature for the kernel. For example, if a kernel is declared as:: ...
Launch cuda kernel. Parameters ---------- args : tuple of NDArray or numbers List of arguments for kernel. NDArrays are expected for pointer types (e.g. `float*`, `double*`) while numbers are expected for non-pointer types (e.g. `int`, `float`). ctx :...
def launch(self, args, ctx, grid_dims, block_dims, shared_mem=0): """Launch cuda kernel. Parameters ---------- args : tuple of NDArray or numbers List of arguments for kernel. NDArrays are expected for pointer types (e.g. `float*`, `double*`) while numbers are ex...
Clear the internal statistics to initial state.
def reset(self): """Clear the internal statistics to initial state.""" if getattr(self, 'num', None) is None: self.num_inst = 0 self.sum_metric = 0.0 else: self.num_inst = [0] * self.num self.sum_metric = [0.0] * self.num self.records = dic...
Update internal records. This function now only update internal buffer, sum_metric and num_inst are updated in _update() function instead when get() is called to return results. Params: ---------- labels: mx.nd.array (n * 6) or (n * 5), difficult column is optional 2...
def update(self, labels, preds): """ Update internal records. This function now only update internal buffer, sum_metric and num_inst are updated in _update() function instead when get() is called to return results. Params: ---------- labels: mx.nd.array (n * 6) o...
update num_inst and sum_metric
def _update(self): """ update num_inst and sum_metric """ aps = [] for k, v in self.records.items(): recall, prec = self._recall_prec(v, self.counts[k]) ap = self._average_precision(recall, prec) aps.append(ap) if self.num is not None and k < (self...
get recall and precision from internal records
def _recall_prec(self, record, count): """ get recall and precision from internal records """ record = np.delete(record, np.where(record[:, 1].astype(int) == 0)[0], axis=0) sorted_records = record[record[:,0].argsort()[::-1]] tp = np.cumsum(sorted_records[:, 1].astype(int) == 1) ...
calculate average precision Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float
def _average_precision(self, rec, prec): """ calculate average precision Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float """ # app...
Insert records according to key
def _insert(self, key, records, count): """ Insert records according to key """ if key not in self.records: assert key not in self.counts self.records[key] = records self.counts[key] = count else: self.records[key] = np.vstack((self.records[key], r...
calculate average precision, override the default one, special 11-point metric Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ---------- ap as float
def _average_precision(self, rec, prec): """ calculate average precision, override the default one, special 11-point metric Params: ---------- rec : numpy.array cumulated recall prec : numpy.array cumulated precision Returns: ...
symbol: the pre-trained network symbol arg_params: the argument parameters of the pre-trained model num_classes: the number of classes for the fine-tune datasets layer_name: the layer name before the last fully-connected layer
def get_fine_tune_model(symbol, arg_params, num_classes, layer_name, dtype='float32'): """ symbol: the pre-trained network symbol arg_params: the argument parameters of the pre-trained model num_classes: the number of classes for the fine-tune datasets layer_name: the layer name before the last full...
Description : generate list for lip images
def _list_images(self, root): """ Description : generate list for lip images """ self.labels = [] self.items = [] valid_unseen_sub_idx = [1, 2, 20, 22] skip_sub_idx = [21] if self._mode == 'train': sub_idx = ['s' + str(i) for i in range(1, 35...
Description : Align to lip position
def align_generation(self, file_nm, padding=75): """ Description : Align to lip position """ align = Align(self._align_root + '/' + file_nm + '.align') return nd.array(align.sentence(padding))
Switch on/off verbose mode Parameters ---------- verbose : bool switch on/off verbose mode print_func : function A function that computes statistics of initialized arrays. Takes an `NDArray` and returns an `str`. Defaults to mean absolute ...
def set_verbosity(self, verbose=False, print_func=None): """Switch on/off verbose mode Parameters ---------- verbose : bool switch on/off verbose mode print_func : function A function that computes statistics of initialized arrays. Takes an `N...
Internal verbose print function Parameters ---------- desc : InitDesc or str name of the array init : str initializer pattern arr : NDArray initialized array
def _verbose_print(self, desc, init, arr): """Internal verbose print function Parameters ---------- desc : InitDesc or str name of the array init : str initializer pattern arr : NDArray initialized array """ if self._ve...
Legacy initialization method. Parameters ---------- name : str Name of corresponding NDArray. arr : NDArray NDArray to be initialized.
def _legacy_init(self, name, arr): """Legacy initialization method. Parameters ---------- name : str Name of corresponding NDArray. arr : NDArray NDArray to be initialized. """ warnings.warn( "\033[91mCalling initializer with ...
save imglist to disk Parameters: ---------- fname : str saved filename
def save_imglist(self, fname=None, root=None, shuffle=False): """ save imglist to disk Parameters: ---------- fname : str saved filename """ def progress_bar(count, total, suffix=''): import sys bar_len = 24 filled_...
load class names from text file Parameters: ---------- filename: str file stores class names dirname: str file directory
def _load_class_names(self, filename, dirname): """ load class names from text file Parameters: ---------- filename: str file stores class names dirname: str file directory """ full_path = osp.join(dirname, filename) classe...
download and read data into numpy
def read_data(label, image): """ download and read data into numpy """ base_url = 'http://yann.lecun.com/exdb/mnist/' with gzip.open(download_file(base_url+label, os.path.join('data',label))) as flbl: magic, num = struct.unpack(">II", flbl.read(8)) label = np.fromstring(flbl.read(), ...
create data iterator with NDArrayIter
def get_mnist_iter(args, kv): """ create data iterator with NDArrayIter """ (train_lbl, train_img) = read_data( 'train-labels-idx1-ubyte.gz', 'train-images-idx3-ubyte.gz') (val_lbl, val_img) = read_data( 't10k-labels-idx1-ubyte.gz', 't10k-images-idx3-ubyte.gz') train = mx...
Function factory for file extension argparse assertion Args: extension (string): the file extension to assert Returns: string: the supplied extension, if assertion is successful.
def make_file_extension_assertion(extension): """Function factory for file extension argparse assertion Args: extension (string): the file extension to assert Returns: string: the supplied extension, if assertion is successful. """ def file_extension_assertion(file_...
generates the colormap for visualizing the segmentation mask Args: num_colors (int): the number of colors to generate in the output palette Returns: string: the supplied extension, if assertion is successful.
def get_palette(num_colors=256): """generates the colormap for visualizing the segmentation mask Args: num_colors (int): the number of colors to generate in the output palette Returns: string: the supplied extension, if assertion is successful. """ p...
get the (1, 3, h, w) np.array data for the supplied image Args: img_path (string): the input image path Returns: np.array: image data in a (1, 3, h, w) shape
def get_data(img_path): """get the (1, 3, h, w) np.array data for the supplied image Args: img_path (string): the input image path Returns: np.array: image data in a (1, 3, h, w) shape """ mean = np.array([123.68, 116.779, 103.939]) ...
Module main execution
def main(): """Module main execution""" # Initialization variables - update to change your model and execution context model_prefix = "FCN8s_VGG16" epoch = 19 # By default, MXNet will run on the CPU. Change to ctx = mx.gpu() to run on GPU. ctx = mx.cpu() fcnxs, fcnxs_args, fcnxs_auxs = mx....
check input imdbs, make sure they have same classes
def _check_classes(self): """ check input imdbs, make sure they have same classes """ try: self.classes = self.imdbs[0].classes self.num_classes = len(self.classes) except AttributeError: # fine, if no classes is provided pass ...
get total number of images, init indices Parameters ---------- shuffle : bool whether to shuffle the initial indices
def _load_image_set_index(self, shuffle): """ get total number of images, init indices Parameters ---------- shuffle : bool whether to shuffle the initial indices """ self.num_images = 0 for db in self.imdbs: self.num_images += db....
given index, find out sub-db and sub-index Parameters ---------- index : int index of a specific image Returns ---------- a tuple (sub-db, sub-index)
def _locate_index(self, index): """ given index, find out sub-db and sub-index Parameters ---------- index : int index of a specific image Returns ---------- a tuple (sub-db, sub-index) """ assert index >= 0 and index < self.n...
given image index, find out full path Parameters ---------- index: int index of a specific image Returns ---------- full path of this image
def image_path_from_index(self, index): """ given image index, find out full path Parameters ---------- index: int index of a specific image Returns ---------- full path of this image """ assert self.image_set_index is not Non...
Callback to checkpoint Module to prefix every epoch. Parameters ---------- mod : subclass of BaseModule The module to checkpoint. prefix : str The file prefix for this checkpoint. period : int How many epochs to wait before checkpointing. Defaults to 1. save_optimizer_st...
def module_checkpoint(mod, prefix, period=1, save_optimizer_states=False): """Callback to checkpoint Module to prefix every epoch. Parameters ---------- mod : subclass of BaseModule The module to checkpoint. prefix : str The file prefix for this checkpoint. period : int ...
A callback that saves a model checkpoint every few epochs. Each checkpoint is made up of a couple of binary files: a model description file and a parameters (weights and biases) file. The model description file is named `prefix`--symbol.json and the parameters file is named `prefix`-`epoch_number`.params ...
def do_checkpoint(prefix, period=1): """A callback that saves a model checkpoint every few epochs. Each checkpoint is made up of a couple of binary files: a model description file and a parameters (weights and biases) file. The model description file is named `prefix`--symbol.json and the parameters fil...
Callback to log the training evaluation result every period. Parameters ---------- period : int The number of batch to log the training evaluation metric. auto_reset : bool Reset the metric after each log. Returns ------- callback : function The callback function th...
def log_train_metric(period, auto_reset=False): """Callback to log the training evaluation result every period. Parameters ---------- period : int The number of batch to log the training evaluation metric. auto_reset : bool Reset the metric after each log. Returns ------- ...
install callback to executor. Supports installing to multiple exes. Parameters ---------- exe : mx.executor.Executor The Executor (returned by symbol.bind) to install to.
def install(self, exe): """install callback to executor. Supports installing to multiple exes. Parameters ---------- exe : mx.executor.Executor The Executor (returned by symbol.bind) to install to. """ exe.set_monitor_callback(self.stat_helper, self.m...
Start collecting stats for current batch. Call before calling forward.
def tic(self): """Start collecting stats for current batch. Call before calling forward.""" if self.step % self.interval == 0: for exe in self.exes: for array in exe.arg_arrays: array.wait_to_read() for array in exe.aux_arrays: ...
End collecting for current batch and return results. Call after computation of current batch. Returns ------- res : list of
def toc(self): """End collecting for current batch and return results. Call after computation of current batch. Returns ------- res : list of """ if not self.activated: return [] for exe in self.exes: for array in exe.arg_arrays: ...
End collecting and print results.
def toc_print(self): """End collecting and print results.""" res = self.toc() for n, k, v in res: logging.info('Batch: {:7d} {:30s} {:s}'.format(n, k, v))
make a random data iteration plan
def make_data_iter_plan(self): "make a random data iteration plan" # truncate each bucket into multiple of batch-size bucket_n_batches = [] for i in range(len(self.data)): bucket_n_batches.append(np.floor((self.data[i]) / self.batch_size)) self.data[i] = self.data...
Expand the pending files in the current stage. Parameters ---------- x: str The file to expand. pending : str The list of pending files to expand. stage: str The current stage for file expansion, used for matching the prefix of files.
def expand(x, pending, stage): """ Expand the pending files in the current stage. Parameters ---------- x: str The file to expand. pending : str The list of pending files to expand. stage: str The current stage for file expansion, used for matching the prefix of f...
Dataset loader with preprocessing.
def get_imagenet_iterator(root, batch_size, num_workers, data_shape=224, dtype='float32'): """Dataset loader with preprocessing.""" train_dir = os.path.join(root, 'train') train_transform, val_transform = get_imagenet_transforms(data_shape, dtype) logging.info("Loading image folder %s, this may take a b...
Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `pretrained_file_name`, use `mxnet.contrib.text.embedding.g...
def create(embedding_name, **kwargs): """Creates an instance of token embedding. Creates a token embedding instance by loading embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText. To get all the valid `embedding_name` and `pretrained_file_n...
Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `mxnet.contrib.text.embedding.create(embedding_name, pretrained_file_name)`. This method ret...
def get_pretrained_file_names(embedding_name=None): """Get valid token embedding names and their pre-trained file names. To load token embedding vectors from an externally hosted pre-trained token embedding file, such as those of GloVe and FastText, one should use `mxnet.contrib.text.embedding.create(...
Load embedding vectors from the pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index 0 of `self.idx_to_vec` maps to the pre-trained token embedding vector loaded from the file; otherw...
def _load_embedding(self, pretrained_file_path, elem_delim, init_unknown_vec, encoding='utf8'): """Load embedding vectors from the pre-trained token embedding file. For every unknown token, if its representation `self.unknown_token` is encountered in the pre-trained token embedding file, index...
Sets the mapping between token indices and token embedding vectors. Parameters ---------- token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding` One or multiple pre-trained token embeddings to load. If it is a list of multiple embeddings, the...
def _set_idx_to_vec_by_embeddings(self, token_embeddings, vocab_len, vocab_idx_to_token): """Sets the mapping between token indices and token embedding vectors. Parameters ---------- token_embeddings : instance or list `mxnet.contrib.text.embedding._TokenEmbedding` One or m...
Look up embedding vectors of tokens. Parameters ---------- tokens : str or list of strs A token or a list of tokens. lower_case_backup : bool, default False If False, each token in the original case will be looked up; if True, each token in the origi...
def get_vecs_by_tokens(self, tokens, lower_case_backup=False): """Look up embedding vectors of tokens. Parameters ---------- tokens : str or list of strs A token or a list of tokens. lower_case_backup : bool, default False If False, each token in the ori...
Updates embedding vectors for tokens. Parameters ---------- tokens : str or a list of strs A token or a list of tokens whose embedding vector are to be updated. new_vectors : mxnet.ndarray.NDArray An NDArray to be assigned to the embedding vectors of `tokens`. I...
def update_token_vectors(self, tokens, new_vectors): """Updates embedding vectors for tokens. Parameters ---------- tokens : str or a list of strs A token or a list of tokens whose embedding vector are to be updated. new_vectors : mxnet.ndarray.NDArray A...
Checks if a pre-trained token embedding file name is valid. Parameters ---------- pretrained_file_name : str The pre-trained token embedding file.
def _check_pretrained_file_names(cls, pretrained_file_name): """Checks if a pre-trained token embedding file name is valid. Parameters ---------- pretrained_file_name : str The pre-trained token embedding file. """ embedding_name = cls.__name__.lower() ...
Calculate gradient
def calc_grad(exe, exe_grads, params, X, Y, label_name=None, outgrad_f=None): """Calculate gradient""" exe.copy_params_from(params) exe.arg_dict['data'][:] = X if outgrad_f is None: exe.arg_dict[label_name][:] = Y exe.forward(is_train=True) exe.backward() else: exe.fo...
Generate the implementation of step HMC
def step_HMC(exe, exe_params, exe_grads, label_key, noise_precision, prior_precision, L=10, eps=1E-6): """Generate the implementation of step HMC""" init_params = {k: v.copyto(v.context) for k, v in exe_params.items()} end_params = {k: v.copyto(v.context) for k, v in exe_params.items()} init_momentums =...
Generate the implementation of HMC
def HMC(sym, data_inputs, X, Y, X_test, Y_test, sample_num, initializer=None, noise_precision=1 / 9.0, prior_precision=0.1, learning_rate=1E-6, L=10, dev=mx.gpu()): """Generate the implementation of HMC""" label_key = list(set(data_inputs.keys()) - set(['data']))[0] exe, exe_params, exe_grad...
Generate the implementation of SGD
def SGD(sym, data_inputs, X, Y, X_test, Y_test, total_iter_num, lr=None, lr_scheduler=None, prior_precision=1, out_grad_f=None, initializer=None, minibatch_size=100, dev=mx.gpu()): """Generate the implementation of SGD""" if out_grad_f is None: label_key = list(se...
Generate the implementation of SGLD
def SGLD(sym, X, Y, X_test, Y_test, total_iter_num, data_inputs=None, learning_rate=None, lr_scheduler=None, prior_precision=1, out_grad_f=None, initializer=None, minibatch_size=100, thin_interval=100, burn_in_iter_num=1000, task='classification', dev=mx.gp...
Generate the implementation of DistilledSGLD
def DistilledSGLD(teacher_sym, student_sym, teacher_data_inputs, student_data_inputs, X, Y, X_test, Y_test, total_iter_num, teacher_learning_rate, student_learning_rate, teacher_lr_scheduler=None, student_lr_scheduler=None, studen...
Get a list of architectures given our dockerfiles
def get_platforms(path: str = get_dockerfiles_path()) -> List[str]: """Get a list of architectures given our dockerfiles""" dockerfiles = glob.glob(os.path.join(path, "Dockerfile.*")) dockerfiles = list(filter(lambda x: x[-1] != '~', dockerfiles)) files = list(map(lambda x: re.sub(r"Dockerfile.(.*)", r"...
:return: docker tag to be used for the container
def get_docker_tag(platform: str, registry: str) -> str: """:return: docker tag to be used for the container""" platform = platform if any(x in platform for x in ['build.', 'publish.']) else 'build.{}'.format(platform) if not registry: registry = "mxnet_local" return "{0}/{1}".format(registry, p...
Build a container for the given platform :param platform: Platform :param docker_binary: docker binary to use (docker/nvidia-docker) :param registry: Dockerhub registry name :param num_retries: Number of retries to build the docker image :param no_cache: pass no-cache to docker to rebuild the images...
def build_docker(platform: str, docker_binary: str, registry: str, num_retries: int, no_cache: bool) -> str: """ Build a container for the given platform :param platform: Platform :param docker_binary: docker binary to use (docker/nvidia-docker) :param registry: Dockerhub registry name :param nu...
Get the image id of the local docker layer with the passed tag :param docker_tag: docker tag :return: Image id as string or None if tag does not exist
def _get_local_image_id(docker_binary, docker_tag): """ Get the image id of the local docker layer with the passed tag :param docker_tag: docker tag :return: Image id as string or None if tag does not exist """ cmd = [docker_binary, "images", "-q", docker_tag] image_id_b = check_output(cmd) ...
:return: ccache directory for the current platform
def default_ccache_dir() -> str: """:return: ccache directory for the current platform""" # Share ccache across containers if 'CCACHE_DIR' in os.environ: ccache_dir = os.path.realpath(os.environ['CCACHE_DIR']) try: os.makedirs(ccache_dir, exist_ok=True) return ccache_...
Run command in a container
def container_run(platform: str, nvidia_runtime: bool, docker_registry: str, shared_memory_size: str, local_ccache_dir: str, command: List[str], cleanup: Cleanup, environment: Dict[str, str], ...
Imports tagged container from the given docker registry
def load_docker_cache(tag, docker_registry) -> None: """Imports tagged container from the given docker registry""" if docker_registry: # noinspection PyBroadException try: import docker_cache logging.info('Docker cache download is enabled from registry %s', docker_registr...
Load a list of arrays into a list of arrays specified by slices.
def _load_general(data, targets, major_axis): """Load a list of arrays into a list of arrays specified by slices.""" for d_src, d_targets, axis in zip(data, targets, major_axis): # pylint: disable=too-many-nested-blocks if isinstance(d_targets, nd.NDArray): d_src.copyto(d_targets) el...
Load data into sliced arrays.
def _load_data(batch, targets, major_axis): """Load data into sliced arrays.""" if isinstance(batch, list): new_batch = [] for i in range(len(targets)): new_batch.append([b.data[i] for b in batch]) new_targets = [[dst for _, dst in d_target] for d_target in targets] _...
Merge outputs that lives on multiple context into one, so that they look like living on one context.
def _merge_multi_context(outputs, major_axis): """Merge outputs that lives on multiple context into one, so that they look like living on one context. """ rets = [] for tensors, axis in zip(outputs, major_axis): if axis >= 0: # pylint: disable=no-member,protected-access ...
Prepare the group2contexts, will duplicate the context if some ctx_group map to only one context.
def _prepare_group2ctxs(group2ctxs, ctx_len): """Prepare the group2contexts, will duplicate the context if some ctx_group map to only one context. """ if group2ctxs is None: return [None] * ctx_len elif isinstance(group2ctxs, list): assert(len(group2ctxs) == ctx_len), "length of grou...
Decide the slices for each context according to the workload. Parameters ---------- data_shapes : list list of (name, shape) specifying the shapes for the input data or label.
def decide_slices(self, data_shapes): """Decide the slices for each context according to the workload. Parameters ---------- data_shapes : list list of (name, shape) specifying the shapes for the input data or label. """ assert len(data_shapes) > 0 ma...
Collect internal arrays from executors.
def _collect_arrays(self): """Collect internal arrays from executors.""" # convenient data structures self.data_arrays = [[(self.slices[i], e.arg_dict[name]) for i, e in enumerate(self.execs)] for name, _ in self.data_shapes] self.state_arrays = [[e.arg_dict[...
Bind executors on their respective devices. Parameters ---------- data_shapes : list label_shapes : list shared_group : DataParallelExecutorGroup reshape : bool
def bind_exec(self, data_shapes, label_shapes, shared_group=None, reshape=False): """Bind executors on their respective devices. Parameters ---------- data_shapes : list label_shapes : list shared_group : DataParallelExecutorGroup reshape : bool """ ...
Reshape executors. Parameters ---------- data_shapes : list label_shapes : list
def reshape(self, data_shapes, label_shapes): """Reshape executors. Parameters ---------- data_shapes : list label_shapes : list """ if data_shapes == self.data_shapes and label_shapes == self.label_shapes: return if self._default_execs is Non...
Assign, i.e. copy parameters to all the executors. Parameters ---------- arg_params : dict A dictionary of name to `NDArray` parameter mapping. aux_params : dict A dictionary of name to `NDArray` auxiliary variable mapping. allow_extra : boolean, optional...
def set_params(self, arg_params, aux_params, allow_extra=False): """Assign, i.e. copy parameters to all the executors. Parameters ---------- arg_params : dict A dictionary of name to `NDArray` parameter mapping. aux_params : dict A dictionary of name to `...
Copy data from each executor to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ----- - This function will inplace update the...
def get_params(self, arg_params, aux_params): """ Copy data from each executor to `arg_params` and `aux_params`. Parameters ---------- arg_params : list of NDArray Target parameter arrays. aux_params : list of NDArray Target aux arrays. Notes ...
Split `data_batch` according to workload and run forward on each devices. Parameters ---------- data_batch : DataBatch Or could be any object implementing similar interface. is_train : bool The hint for the backend, indicating whether we are during training phase...
def forward(self, data_batch, is_train=None): """Split `data_batch` according to workload and run forward on each devices. Parameters ---------- data_batch : DataBatch Or could be any object implementing similar interface. is_train : bool The hint for the...
Get the shapes of the outputs.
def get_output_shapes(self): """Get the shapes of the outputs.""" outputs = self.execs[0].outputs shapes = [out.shape for out in outputs] concat_shapes = [] for key, the_shape, axis in zip(self.symbol.list_outputs(), shapes, self.output_layouts): the_shape = list(the...