text
stringlengths
81
112k
Validate label and its shape. def _check_valid_label(self, label): """Validate label and its shape.""" if len(label.shape) != 2 or label.shape[1] < 5: msg = "Label with shape (1+, 5+) required, %s received." % str(label) raise RuntimeError(msg) valid_label = np.where(np.logical_and(label[:, 0] >= 0, label[:, 3] > label[:, 1], label[:, 4] > label[:, 2]))[0] if valid_label.size < 1: raise RuntimeError('Invalid label occurs.')
Helper function to estimate label shape def _estimate_label_shape(self): """Helper function to estimate label shape""" max_count = 0 self.reset() try: while True: label, _ = self.next_sample() label = self._parse_label(label) max_count = max(max_count, label.shape[0]) except StopIteration: pass self.reset() return (max_count, label.shape[1])
Helper function to parse object detection label. Format for raw label: n \t k \t ... \t [id \t xmin\t ymin \t xmax \t ymax \t ...] \t [repeat] where n is the width of header, 2 or larger k is the width of each object annotation, can be arbitrary, at least 5 def _parse_label(self, label): """Helper function to parse object detection label. Format for raw label: n \t k \t ... \t [id \t xmin\t ymin \t xmax \t ymax \t ...] \t [repeat] where n is the width of header, 2 or larger k is the width of each object annotation, can be arbitrary, at least 5 """ if isinstance(label, nd.NDArray): label = label.asnumpy() raw = label.ravel() if raw.size < 7: raise RuntimeError("Label shape is invalid: " + str(raw.shape)) header_width = int(raw[0]) obj_width = int(raw[1]) if (raw.size - header_width) % obj_width != 0: msg = "Label shape %s inconsistent with annotation width %d." \ %(str(raw.shape), obj_width) raise RuntimeError(msg) out = np.reshape(raw[header_width:], (-1, obj_width)) # remove bad ground-truths valid = np.where(np.logical_and(out[:, 3] > out[:, 1], out[:, 4] > out[:, 2]))[0] if valid.size < 1: raise RuntimeError('Encounter sample with no valid label.') return out[valid, :]
Reshape iterator for data_shape or label_shape. Parameters ---------- data_shape : tuple or None Reshape the data_shape to the new shape if not None label_shape : tuple or None Reshape label shape to new shape if not None def reshape(self, data_shape=None, label_shape=None): """Reshape iterator for data_shape or label_shape. Parameters ---------- data_shape : tuple or None Reshape the data_shape to the new shape if not None label_shape : tuple or None Reshape label shape to new shape if not None """ if data_shape is not None: self.check_data_shape(data_shape) self.provide_data = [(self.provide_data[0][0], (self.batch_size,) + data_shape)] self.data_shape = data_shape if label_shape is not None: self.check_label_shape(label_shape) self.provide_label = [(self.provide_label[0][0], (self.batch_size,) + label_shape)] self.label_shape = label_shape
Override the helper function for batchifying data def _batchify(self, batch_data, batch_label, start=0): """Override the helper function for batchifying data""" i = start batch_size = self.batch_size try: while i < batch_size: label, s = self.next_sample() data = self.imdecode(s) try: self.check_valid_image([data]) label = self._parse_label(label) data, label = self.augmentation_transform(data, label) self._check_valid_label(label) except RuntimeError as e: logging.debug('Invalid image, skipping: %s', str(e)) continue for datum in [data]: assert i < batch_size, 'Batch size must be multiples of augmenter output length' batch_data[i] = self.postprocess_data(datum) num_object = label.shape[0] batch_label[i][0:num_object] = nd.array(label) if num_object < batch_label[i].shape[0]: batch_label[i][num_object:] = -1 i += 1 except StopIteration: if not i: raise StopIteration return i
Override the function for returning next batch. def next(self): """Override the function for returning next batch.""" batch_size = self.batch_size c, h, w = self.data_shape # if last batch data is rolled over if self._cache_data is not None: # check both the data and label have values assert self._cache_label is not None, "_cache_label didn't have values" assert self._cache_idx is not None, "_cache_idx didn't have values" batch_data = self._cache_data batch_label = self._cache_label i = self._cache_idx else: batch_data = nd.zeros((batch_size, c, h, w)) batch_label = nd.empty(self.provide_label[0][1]) batch_label[:] = -1 i = self._batchify(batch_data, batch_label) # calculate the padding pad = batch_size - i # handle padding for the last batch if pad != 0: if self.last_batch_handle == 'discard': raise StopIteration # if the option is 'roll_over', throw StopIteration and cache the data elif self.last_batch_handle == 'roll_over' and \ self._cache_data is None: self._cache_data = batch_data self._cache_label = batch_label self._cache_idx = i raise StopIteration else: _ = self._batchify(batch_data, batch_label, i) if self.last_batch_handle == 'pad': self._allow_read = False else: self._cache_data = None self._cache_label = None self._cache_idx = None return io.DataBatch([batch_data], [batch_label], pad=pad)
Override Transforms input data with specified augmentations. def augmentation_transform(self, data, label): # pylint: disable=arguments-differ """Override Transforms input data with specified augmentations.""" for aug in self.auglist: data, label = aug(data, label) return (data, label)
Checks if the new label shape is valid def check_label_shape(self, label_shape): """Checks if the new label shape is valid""" if not len(label_shape) == 2: raise ValueError('label_shape should have length 2') if label_shape[0] < self.label_shape[0]: msg = 'Attempts to reduce label count from %d to %d, not allowed.' \ % (self.label_shape[0], label_shape[0]) raise ValueError(msg) if label_shape[1] != self.provide_label[0][1][2]: msg = 'label_shape object width inconsistent: %d vs %d.' \ % (self.provide_label[0][1][2], label_shape[1]) raise ValueError(msg)
Display next image with bounding boxes drawn. Parameters ---------- color : tuple Bounding box color in RGB, use None for random color thickness : int Bounding box border thickness mean : True or numpy.ndarray Compensate for the mean to have better visual effect std : True or numpy.ndarray Revert standard deviations clip : bool If true, clip to [0, 255] for better visual effect waitKey : None or int Hold the window for waitKey milliseconds if set, skip ploting if None window_name : str Plot window name if waitKey is set. id2labels : dict Mapping of labels id to labels name. Returns ------- numpy.ndarray Examples -------- >>> # use draw_next to get images with bounding boxes drawn >>> iterator = mx.image.ImageDetIter(1, (3, 600, 600), path_imgrec='train.rec') >>> for image in iterator.draw_next(waitKey=None): ... # display image >>> # or let draw_next display using cv2 module >>> for image in iterator.draw_next(waitKey=0, window_name='disp'): ... pass def draw_next(self, color=None, thickness=2, mean=None, std=None, clip=True, waitKey=None, window_name='draw_next', id2labels=None): """Display next image with bounding boxes drawn. Parameters ---------- color : tuple Bounding box color in RGB, use None for random color thickness : int Bounding box border thickness mean : True or numpy.ndarray Compensate for the mean to have better visual effect std : True or numpy.ndarray Revert standard deviations clip : bool If true, clip to [0, 255] for better visual effect waitKey : None or int Hold the window for waitKey milliseconds if set, skip ploting if None window_name : str Plot window name if waitKey is set. id2labels : dict Mapping of labels id to labels name. Returns ------- numpy.ndarray Examples -------- >>> # use draw_next to get images with bounding boxes drawn >>> iterator = mx.image.ImageDetIter(1, (3, 600, 600), path_imgrec='train.rec') >>> for image in iterator.draw_next(waitKey=None): ... # display image >>> # or let draw_next display using cv2 module >>> for image in iterator.draw_next(waitKey=0, window_name='disp'): ... pass """ try: import cv2 except ImportError as e: warnings.warn('Unable to import cv2, skip drawing: %s', str(e)) return count = 0 try: while True: label, s = self.next_sample() data = self.imdecode(s) try: self.check_valid_image([data]) label = self._parse_label(label) except RuntimeError as e: logging.debug('Invalid image, skipping: %s', str(e)) continue count += 1 data, label = self.augmentation_transform(data, label) image = data.asnumpy() # revert color_normalize if std is True: std = np.array([58.395, 57.12, 57.375]) elif std is not None: assert isinstance(std, np.ndarray) and std.shape[0] in [1, 3] if std is not None: image *= std if mean is True: mean = np.array([123.68, 116.28, 103.53]) elif mean is not None: assert isinstance(mean, np.ndarray) and mean.shape[0] in [1, 3] if mean is not None: image += mean # swap RGB image[:, :, (0, 1, 2)] = image[:, :, (2, 1, 0)] if clip: image = np.maximum(0, np.minimum(255, image)) if color: color = color[::-1] image = image.astype(np.uint8) height, width, _ = image.shape for i in range(label.shape[0]): x1 = int(label[i, 1] * width) if x1 < 0: continue y1 = int(label[i, 2] * height) x2 = int(label[i, 3] * width) y2 = int(label[i, 4] * height) bc = np.random.rand(3) * 255 if not color else color cv2.rectangle(image, (x1, y1), (x2, y2), bc, thickness) if id2labels is not None: cls_id = int(label[i, 0]) if cls_id in id2labels: cls_name = id2labels[cls_id] text = "{:s}".format(cls_name) font = cv2.FONT_HERSHEY_SIMPLEX font_scale = 0.5 text_height = cv2.getTextSize(text, font, font_scale, 2)[0][1] tc = (255, 255, 255) tpos = (x1 + 5, y1 + text_height + 5) cv2.putText(image, text, tpos, font, font_scale, tc, 2) if waitKey is not None: cv2.imshow(window_name, image) cv2.waitKey(waitKey) yield image except StopIteration: if not count: return
Synchronize label shape with the input iterator. This is useful when train/validation iterators have different label padding. Parameters ---------- it : ImageDetIter The other iterator to synchronize verbose : bool Print verbose log if true Returns ------- ImageDetIter The synchronized other iterator, the internal label shape is updated as well. Examples -------- >>> train_iter = mx.image.ImageDetIter(32, (3, 300, 300), path_imgrec='train.rec') >>> val_iter = mx.image.ImageDetIter(32, (3, 300, 300), path.imgrec='val.rec') >>> train_iter.label_shape (30, 6) >>> val_iter.label_shape (25, 6) >>> val_iter = train_iter.sync_label_shape(val_iter, verbose=False) >>> train_iter.label_shape (30, 6) >>> val_iter.label_shape (30, 6) def sync_label_shape(self, it, verbose=False): """Synchronize label shape with the input iterator. This is useful when train/validation iterators have different label padding. Parameters ---------- it : ImageDetIter The other iterator to synchronize verbose : bool Print verbose log if true Returns ------- ImageDetIter The synchronized other iterator, the internal label shape is updated as well. Examples -------- >>> train_iter = mx.image.ImageDetIter(32, (3, 300, 300), path_imgrec='train.rec') >>> val_iter = mx.image.ImageDetIter(32, (3, 300, 300), path.imgrec='val.rec') >>> train_iter.label_shape (30, 6) >>> val_iter.label_shape (25, 6) >>> val_iter = train_iter.sync_label_shape(val_iter, verbose=False) >>> train_iter.label_shape (30, 6) >>> val_iter.label_shape (30, 6) """ assert isinstance(it, ImageDetIter), 'Synchronize with invalid iterator.' train_label_shape = self.label_shape val_label_shape = it.label_shape assert train_label_shape[1] == val_label_shape[1], "object width mismatch." max_count = max(train_label_shape[0], val_label_shape[0]) if max_count > train_label_shape[0]: self.reshape(None, (max_count, train_label_shape[1])) if max_count > val_label_shape[0]: it.reshape(None, (max_count, val_label_shape[1])) if verbose and max_count > min(train_label_shape[0], val_label_shape[0]): logging.info('Resized label_shape to (%d, %d).', max_count, train_label_shape[1]) return it
Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. def _generate_base_anchors(base_size, scales, ratios): """ Generate anchor (reference) windows by enumerating aspect ratios X scales wrt a reference (0, 0, 15, 15) window. """ base_anchor = np.array([1, 1, base_size, base_size]) - 1 ratio_anchors = AnchorGenerator._ratio_enum(base_anchor, ratios) anchors = np.vstack([AnchorGenerator._scale_enum(ratio_anchors[i, :], scales) for i in range(ratio_anchors.shape[0])]) return anchors
Return width, height, x center, and y center for an anchor (window). def _whctrs(anchor): """ Return width, height, x center, and y center for an anchor (window). """ w = anchor[2] - anchor[0] + 1 h = anchor[3] - anchor[1] + 1 x_ctr = anchor[0] + 0.5 * (w - 1) y_ctr = anchor[1] + 0.5 * (h - 1) return w, h, x_ctr, y_ctr
Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). def _mkanchors(ws, hs, x_ctr, y_ctr): """ Given a vector of widths (ws) and heights (hs) around a center (x_ctr, y_ctr), output a set of anchors (windows). """ ws = ws[:, np.newaxis] hs = hs[:, np.newaxis] anchors = np.hstack((x_ctr - 0.5 * (ws - 1), y_ctr - 0.5 * (hs - 1), x_ctr + 0.5 * (ws - 1), y_ctr + 0.5 * (hs - 1))) return anchors
Enumerate a set of anchors for each aspect ratio wrt an anchor. def _ratio_enum(anchor, ratios): """ Enumerate a set of anchors for each aspect ratio wrt an anchor. """ w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor) size = w * h size_ratios = size / ratios ws = np.round(np.sqrt(size_ratios)) hs = np.round(ws * ratios) anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr) return anchors
Enumerate a set of anchors for each scale wrt an anchor. def _scale_enum(anchor, scales): """ Enumerate a set of anchors for each scale wrt an anchor. """ w, h, x_ctr, y_ctr = AnchorGenerator._whctrs(anchor) ws = w * scales hs = h * scales anchors = AnchorGenerator._mkanchors(ws, hs, x_ctr, y_ctr) return anchors
set atual shape of data def prepare_data(args): """ set atual shape of data """ rnn_type = args.config.get("arch", "rnn_type") num_rnn_layer = args.config.getint("arch", "num_rnn_layer") num_hidden_rnn_list = json.loads(args.config.get("arch", "num_hidden_rnn_list")) batch_size = args.config.getint("common", "batch_size") if rnn_type == 'lstm': init_c = [('l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] elif rnn_type == 'bilstm': forward_init_c = [('forward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] backward_init_c = [('backward_l%d_init_c' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] init_c = forward_init_c + backward_init_c forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] init_h = forward_init_h + backward_init_h elif rnn_type == 'gru': init_h = [('l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] elif rnn_type == 'bigru': forward_init_h = [('forward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] backward_init_h = [('backward_l%d_init_h' % l, (batch_size, num_hidden_rnn_list[l])) for l in range(num_rnn_layer)] init_h = forward_init_h + backward_init_h else: raise Exception('network type should be one of the lstm,bilstm,gru,bigru') if rnn_type == 'lstm' or rnn_type == 'bilstm': init_states = init_c + init_h elif rnn_type == 'gru' or rnn_type == 'bigru': init_states = init_h return init_states
define deep speech 2 network def arch(args, seq_len=None): """ define deep speech 2 network """ if isinstance(args, argparse.Namespace): mode = args.config.get("common", "mode") is_bucketing = args.config.getboolean("arch", "is_bucketing") if mode == "train" or is_bucketing: channel_num = args.config.getint("arch", "channel_num") conv_layer1_filter_dim = \ tuple(json.loads(args.config.get("arch", "conv_layer1_filter_dim"))) conv_layer1_stride = tuple(json.loads(args.config.get("arch", "conv_layer1_stride"))) conv_layer2_filter_dim = \ tuple(json.loads(args.config.get("arch", "conv_layer2_filter_dim"))) conv_layer2_stride = tuple(json.loads(args.config.get("arch", "conv_layer2_stride"))) rnn_type = args.config.get("arch", "rnn_type") num_rnn_layer = args.config.getint("arch", "num_rnn_layer") num_hidden_rnn_list = json.loads(args.config.get("arch", "num_hidden_rnn_list")) is_batchnorm = args.config.getboolean("arch", "is_batchnorm") if seq_len is None: seq_len = args.config.getint('arch', 'max_t_count') num_label = args.config.getint('arch', 'max_label_length') num_rear_fc_layers = args.config.getint("arch", "num_rear_fc_layers") num_hidden_rear_fc_list = json.loads(args.config.get("arch", "num_hidden_rear_fc_list")) act_type_rear_fc_list = json.loads(args.config.get("arch", "act_type_rear_fc_list")) # model symbol generation # input preparation data = mx.sym.Variable('data') label = mx.sym.Variable('label') net = mx.sym.Reshape(data=data, shape=(-4, -1, 1, 0, 0)) net = conv(net=net, channels=channel_num, filter_dimension=conv_layer1_filter_dim, stride=conv_layer1_stride, no_bias=is_batchnorm, name='conv1') if is_batchnorm: # batch norm normalizes axis 1 net = batchnorm(net, name="conv1_batchnorm") net = conv(net=net, channels=channel_num, filter_dimension=conv_layer2_filter_dim, stride=conv_layer2_stride, no_bias=is_batchnorm, name='conv2') if is_batchnorm: # batch norm normalizes axis 1 net = batchnorm(net, name="conv2_batchnorm") net = mx.sym.transpose(data=net, axes=(0, 2, 1, 3)) net = mx.sym.Reshape(data=net, shape=(0, 0, -3)) seq_len_after_conv_layer1 = int( math.floor((seq_len - conv_layer1_filter_dim[0]) / conv_layer1_stride[0])) + 1 seq_len_after_conv_layer2 = int( math.floor((seq_len_after_conv_layer1 - conv_layer2_filter_dim[0]) / conv_layer2_stride[0])) + 1 net = slice_symbol_to_seq_symobls(net=net, seq_len=seq_len_after_conv_layer2, axis=1) if rnn_type == "bilstm": net = bi_lstm_unroll(net=net, seq_len=seq_len_after_conv_layer2, num_hidden_lstm_list=num_hidden_rnn_list, num_lstm_layer=num_rnn_layer, dropout=0., is_batchnorm=is_batchnorm, is_bucketing=is_bucketing) elif rnn_type == "gru": net = gru_unroll(net=net, seq_len=seq_len_after_conv_layer2, num_hidden_gru_list=num_hidden_rnn_list, num_gru_layer=num_rnn_layer, dropout=0., is_batchnorm=is_batchnorm, is_bucketing=is_bucketing) elif rnn_type == "bigru": net = bi_gru_unroll(net=net, seq_len=seq_len_after_conv_layer2, num_hidden_gru_list=num_hidden_rnn_list, num_gru_layer=num_rnn_layer, dropout=0., is_batchnorm=is_batchnorm, is_bucketing=is_bucketing) else: raise Exception('rnn_type should be one of the followings, bilstm,gru,bigru') # rear fc layers net = sequence_fc(net=net, seq_len=seq_len_after_conv_layer2, num_layer=num_rear_fc_layers, prefix="rear", num_hidden_list=num_hidden_rear_fc_list, act_type_list=act_type_rear_fc_list, is_batchnorm=is_batchnorm) # warpctc layer net = warpctc_layer(net=net, seq_len=seq_len_after_conv_layer2, label=label, num_label=num_label, character_classes_count= (args.config.getint('arch', 'n_classes') + 1)) args.config.set('arch', 'max_t_count', str(seq_len_after_conv_layer2)) return net elif mode == 'load' or mode == 'predict': conv_layer1_filter_dim = \ tuple(json.loads(args.config.get("arch", "conv_layer1_filter_dim"))) conv_layer1_stride = tuple(json.loads(args.config.get("arch", "conv_layer1_stride"))) conv_layer2_filter_dim = \ tuple(json.loads(args.config.get("arch", "conv_layer2_filter_dim"))) conv_layer2_stride = tuple(json.loads(args.config.get("arch", "conv_layer2_stride"))) if seq_len is None: seq_len = args.config.getint('arch', 'max_t_count') seq_len_after_conv_layer1 = int( math.floor((seq_len - conv_layer1_filter_dim[0]) / conv_layer1_stride[0])) + 1 seq_len_after_conv_layer2 = int( math.floor((seq_len_after_conv_layer1 - conv_layer2_filter_dim[0]) / conv_layer2_stride[0])) + 1 args.config.set('arch', 'max_t_count', str(seq_len_after_conv_layer2)) else: raise Exception('mode must be the one of the followings - train,predict,load')
Description : run lipnet training code using argument info def main(): """ Description : run lipnet training code using argument info """ parser = argparse.ArgumentParser() parser.add_argument('--batch_size', type=int, default=64) parser.add_argument('--epochs', type=int, default=100) parser.add_argument('--image_path', type=str, default='./data/datasets/') parser.add_argument('--align_path', type=str, default='./data/align/') parser.add_argument('--dr_rate', type=float, default=0.5) parser.add_argument('--num_gpus', type=int, default=1) parser.add_argument('--num_workers', type=int, default=0) parser.add_argument('--model_path', type=str, default=None) config = parser.parse_args() trainer = Train(config) trainer.build_model(dr_rate=config.dr_rate, path=config.model_path) trainer.load_dataloader() trainer.run(epochs=config.epochs)
visualize [cls, conf, x1, y1, x2, y2] def vis_detection(im_orig, detections, class_names, thresh=0.7): """visualize [cls, conf, x1, y1, x2, y2]""" import matplotlib.pyplot as plt import random plt.imshow(im_orig) colors = [(random.random(), random.random(), random.random()) for _ in class_names] for [cls, conf, x1, y1, x2, y2] in detections: cls = int(cls) if cls > 0 and conf > thresh: rect = plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor=colors[cls], linewidth=3.5) plt.gca().add_patch(rect) plt.gca().text(x1, y1 - 2, '{:s} {:.3f}'.format(class_names[cls], conf), bbox=dict(facecolor=colors[cls], alpha=0.5), fontsize=12, color='white') plt.show()
Check the difference between predictions from MXNet and CoreML. def check_error(model, path, shapes, output = 'softmax_output', verbose = True): """ Check the difference between predictions from MXNet and CoreML. """ coreml_model = _coremltools.models.MLModel(path) input_data = {} input_data_copy = {} for ip in shapes: input_data[ip] = _np.random.rand(*shapes[ip]).astype('f') input_data_copy[ip] = _np.copy(input_data[ip]) dataIter = _mxnet.io.NDArrayIter(input_data_copy) mx_out = model.predict(dataIter).flatten() e_out_dict = coreml_model.predict(_mxnet_remove_batch(input_data)) e_out = e_out_dict[output].flatten() error = _np.linalg.norm(e_out - mx_out) if verbose: print("First few predictions from CoreML : %s" % e_out[0:10]) print("First few predictions from MXNet : %s" % e_out[0:10]) print("L2 Error on random data %s" % error) return error
Description : set gpu module def setting_ctx(num_gpus): """ Description : set gpu module """ if num_gpus > 0: ctx = [mx.gpu(i) for i in range(num_gpus)] else: ctx = [mx.cpu()] return ctx
Description : apply beam search for prediction result def char_beam_search(out): """ Description : apply beam search for prediction result """ out_conv = list() for idx in range(out.shape[0]): probs = out[idx] prob = probs.softmax().asnumpy() line_string_proposals = ctcBeamSearch(prob, ALPHABET, None, k=4, beamWidth=25) out_conv.append(line_string_proposals[0]) return out_conv
Description : build network def build_model(self, dr_rate=0, path=None): """ Description : build network """ #set network self.net = LipNet(dr_rate) self.net.hybridize() self.net.initialize(ctx=self.ctx) if path is not None: self.load_model(path) #set optimizer self.loss_fn = gluon.loss.CTCLoss() self.trainer = gluon.Trainer(self.net.collect_params(), \ optimizer='SGD')
Description : save parameter of network weight def save_model(self, epoch, loss): """ Description : save parameter of network weight """ prefix = 'checkpoint/epoches' file_name = "{prefix}_{epoch}_loss_{l:.4f}".format(prefix=prefix, epoch=str(epoch), l=loss) self.net.save_parameters(file_name)
Description : Setup the dataloader def load_dataloader(self): """ Description : Setup the dataloader """ input_transform = transforms.Compose([transforms.ToTensor(), \ transforms.Normalize((0.7136, 0.4906, 0.3283), \ (0.1138, 0.1078, 0.0917))]) training_dataset = LipsDataset(self.image_path, self.align_path, mode='train', transform=input_transform, seq_len=self.seq_len) self.train_dataloader = mx.gluon.data.DataLoader(training_dataset, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers) valid_dataset = LipsDataset(self.image_path, self.align_path, mode='valid', transform=input_transform, seq_len=self.seq_len) self.valid_dataloader = mx.gluon.data.DataLoader(valid_dataset, batch_size=self.batch_size, shuffle=True, num_workers=self.num_workers)
Description : training for LipNet def train(self, data, label, batch_size): """ Description : training for LipNet """ # pylint: disable=no-member sum_losses = 0 len_losses = 0 with autograd.record(): losses = [self.loss_fn(self.net(X), Y) for X, Y in zip(data, label)] for loss in losses: sum_losses += mx.nd.array(loss).sum().asscalar() len_losses += len(loss) loss.backward() self.trainer.step(batch_size) return sum_losses, len_losses
Description : Print sentence for prediction result def infer(self, input_data, input_label): """ Description : Print sentence for prediction result """ sum_losses = 0 len_losses = 0 for data, label in zip(input_data, input_label): pred = self.net(data) sum_losses += mx.nd.array(self.loss_fn(pred, label)).sum().asscalar() len_losses += len(data) pred_convert = char_beam_search(pred) label_convert = char_conv(label.asnumpy()) for target, pred in zip(label_convert, pred_convert): print("target:{t} pred:{p}".format(t=target, p=pred)) return sum_losses, len_losses
Description : training for LipNet def train_batch(self, dataloader): """ Description : training for LipNet """ sum_losses = 0 len_losses = 0 for input_data, input_label in tqdm(dataloader): data = gluon.utils.split_and_load(input_data, self.ctx, even_split=False) label = gluon.utils.split_and_load(input_label, self.ctx, even_split=False) batch_size = input_data.shape[0] sum_losses, len_losses = self.train(data, label, batch_size) sum_losses += sum_losses len_losses += len_losses return sum_losses, len_losses
Description : inference for LipNet def infer_batch(self, dataloader): """ Description : inference for LipNet """ sum_losses = 0 len_losses = 0 for input_data, input_label in dataloader: data = gluon.utils.split_and_load(input_data, self.ctx, even_split=False) label = gluon.utils.split_and_load(input_label, self.ctx, even_split=False) sum_losses, len_losses = self.infer(data, label) sum_losses += sum_losses len_losses += len_losses return sum_losses, len_losses
Description : Run training for LipNet def run(self, epochs): """ Description : Run training for LipNet """ best_loss = sys.maxsize for epoch in trange(epochs): iter_no = 0 ## train sum_losses, len_losses = self.train_batch(self.train_dataloader) if iter_no % 20 == 0: current_loss = sum_losses / len_losses print("[Train] epoch:{e} iter:{i} loss:{l:.4f}".format(e=epoch, i=iter_no, l=current_loss)) ## validating sum_val_losses, len_val_losses = self.infer_batch(self.valid_dataloader) current_val_loss = sum_val_losses / len_val_losses print("[Vaild] epoch:{e} iter:{i} loss:{l:.4f}".format(e=epoch, i=iter_no, l=current_val_loss)) if best_loss > current_val_loss: self.save_model(epoch, current_val_loss) best_loss = current_val_loss iter_no += 1
Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num) rng : numpy.random.RandomState Returns ------- ret : numpy.ndarray Sampling result. Shape --> (batch_num,) def sample_categorical(prob, rng): """Sample from independent categorical distributions Each batch is an independent categorical distribution. Parameters ---------- prob : numpy.ndarray Probability of the categorical distribution. Shape --> (batch_num, category_num) rng : numpy.random.RandomState Returns ------- ret : numpy.ndarray Sampling result. Shape --> (batch_num,) """ ret = numpy.empty(prob.shape[0], dtype=numpy.float32) for ind in range(prob.shape[0]): ret[ind] = numpy.searchsorted(numpy.cumsum(prob[ind]), rng.rand()).clip(min=0.0, max=prob.shape[ 1] - 0.5) return ret
Sample from independent normal distributions Each element is an independent normal distribution. Parameters ---------- mean : numpy.ndarray Means of the normal distribution. Shape --> (batch_num, sample_dim) var : numpy.ndarray Variance of the normal distribution. Shape --> (batch_num, sample_dim) rng : numpy.random.RandomState Returns ------- ret : numpy.ndarray The sampling result. Shape --> (batch_num, sample_dim) def sample_normal(mean, var, rng): """Sample from independent normal distributions Each element is an independent normal distribution. Parameters ---------- mean : numpy.ndarray Means of the normal distribution. Shape --> (batch_num, sample_dim) var : numpy.ndarray Variance of the normal distribution. Shape --> (batch_num, sample_dim) rng : numpy.random.RandomState Returns ------- ret : numpy.ndarray The sampling result. Shape --> (batch_num, sample_dim) """ ret = numpy.sqrt(var) * rng.randn(*mean.shape) + mean return ret
Sample from independent mixture of gaussian (MoG) distributions Each batch is an independent MoG distribution. Parameters ---------- prob : numpy.ndarray mixture probability of each gaussian. Shape --> (batch_num, center_num) mean : numpy.ndarray mean of each gaussian. Shape --> (batch_num, center_num, sample_dim) var : numpy.ndarray variance of each gaussian. Shape --> (batch_num, center_num, sample_dim) rng : numpy.random.RandomState Returns ------- ret : numpy.ndarray sampling result. Shape --> (batch_num, sample_dim) def sample_mog(prob, mean, var, rng): """Sample from independent mixture of gaussian (MoG) distributions Each batch is an independent MoG distribution. Parameters ---------- prob : numpy.ndarray mixture probability of each gaussian. Shape --> (batch_num, center_num) mean : numpy.ndarray mean of each gaussian. Shape --> (batch_num, center_num, sample_dim) var : numpy.ndarray variance of each gaussian. Shape --> (batch_num, center_num, sample_dim) rng : numpy.random.RandomState Returns ------- ret : numpy.ndarray sampling result. Shape --> (batch_num, sample_dim) """ gaussian_inds = sample_categorical(prob, rng).astype(numpy.int32) mean = mean[numpy.arange(mean.shape[0]), gaussian_inds, :] var = var[numpy.arange(mean.shape[0]), gaussian_inds, :] ret = sample_normal(mean=mean, var=var, rng=rng) return ret
NCE-Loss layer under subword-units input. def nce_loss_subwords( data, label, label_mask, label_weight, embed_weight, vocab_size, num_hidden): """NCE-Loss layer under subword-units input. """ # get subword-units embedding. label_units_embed = mx.sym.Embedding(data=label, input_dim=vocab_size, weight=embed_weight, output_dim=num_hidden) # get valid subword-units embedding with the help of label_mask # it's achieved by multiplying zeros to useless units in order to handle variable-length input. label_units_embed = mx.sym.broadcast_mul(lhs=label_units_embed, rhs=label_mask, name='label_units_embed') # sum over them to get label word embedding. label_embed = mx.sym.sum(label_units_embed, axis=2, name='label_embed') # by boardcast_mul and sum you can get prediction scores in all label_embed inputs, # which is easy to feed into LogisticRegressionOutput and make your code more concise. data = mx.sym.Reshape(data=data, shape=(-1, 1, num_hidden)) pred = mx.sym.broadcast_mul(data, label_embed) pred = mx.sym.sum(data=pred, axis=2) return mx.sym.LogisticRegressionOutput(data=pred, label=label_weight)
Download the BSDS500 dataset and return train and test iters. def get_dataset(prefetch=False): """Download the BSDS500 dataset and return train and test iters.""" if path.exists(data_dir): print( "Directory {} already exists, skipping.\n" "To force download and extraction, delete the directory and re-run." "".format(data_dir), file=sys.stderr, ) else: print("Downloading dataset...", file=sys.stderr) downloaded_file = download(dataset_url, dirname=datasets_tmpdir) print("done", file=sys.stderr) print("Extracting files...", end="", file=sys.stderr) os.makedirs(data_dir) os.makedirs(tmp_dir) with zipfile.ZipFile(downloaded_file) as archive: archive.extractall(tmp_dir) shutil.rmtree(datasets_tmpdir) shutil.copytree( path.join(tmp_dir, "BSDS500-master", "BSDS500", "data", "images"), path.join(data_dir, "images"), ) shutil.copytree( path.join(tmp_dir, "BSDS500-master", "BSDS500", "data", "groundTruth"), path.join(data_dir, "groundTruth"), ) shutil.rmtree(tmp_dir) print("done", file=sys.stderr) crop_size = 256 crop_size -= crop_size % upscale_factor input_crop_size = crop_size // upscale_factor input_transform = [CenterCropAug((crop_size, crop_size)), ResizeAug(input_crop_size)] target_transform = [CenterCropAug((crop_size, crop_size))] iters = ( ImagePairIter( path.join(data_dir, "images", "train"), (input_crop_size, input_crop_size), (crop_size, crop_size), batch_size, color_flag, input_transform, target_transform, ), ImagePairIter( path.join(data_dir, "images", "test"), (input_crop_size, input_crop_size), (crop_size, crop_size), test_batch_size, color_flag, input_transform, target_transform, ), ) return [PrefetchingIter(i) for i in iters] if prefetch else iters
Run evaluation on cpu. def evaluate(mod, data_iter, epoch, log_interval): """ Run evaluation on cpu. """ start = time.time() total_L = 0.0 nbatch = 0 density = 0 mod.set_states(value=0) for batch in data_iter: mod.forward(batch, is_train=False) outputs = mod.get_outputs(merge_multi_context=False) states = outputs[:-1] total_L += outputs[-1][0] mod.set_states(states=states) nbatch += 1 # don't include padding data in the test perplexity density += batch.data[1].mean() if (nbatch + 1) % log_interval == 0: logging.info("Eval batch %d loss : %.7f" % (nbatch, (total_L / density).asscalar())) data_iter.reset() loss = (total_L / density).asscalar() ppl = math.exp(loss) if loss < 100 else 1e37 end = time.time() logging.info('Iter[%d]\t\t CE loss %.7f, ppl %.7f. Eval duration = %.2f seconds ' % \ (epoch, loss, ppl, end - start)) return loss
get two list, each list contains two elements: name and nd.array value def _read(self): """get two list, each list contains two elements: name and nd.array value""" _, data_img_name, label_img_name = self.f.readline().strip('\n').split("\t") data = {} label = {} data[self.data_name], label[self.label_name] = self._read_img(data_img_name, label_img_name) return list(data.items()), list(label.items())
return one dict which contains "data" and "label" def next(self): """return one dict which contains "data" and "label" """ if self.iter_next(): self.data, self.label = self._read() return {self.data_name : self.data[0][1], self.label_name : self.label[0][1]} else: raise StopIteration
Convert from onnx operator to mxnet operator. The converter must specify conversions explicitly for incompatible name, and apply handlers to operator attributes. Parameters ---------- :param node_name : str name of the node to be translated. :param op_name : str Operator name, such as Convolution, FullyConnected :param attrs : dict Dict of operator attributes :param inputs: list list of inputs to the operator Returns ------- :return mxnet_sym Converted mxnet symbol def _convert_operator(self, node_name, op_name, attrs, inputs): """Convert from onnx operator to mxnet operator. The converter must specify conversions explicitly for incompatible name, and apply handlers to operator attributes. Parameters ---------- :param node_name : str name of the node to be translated. :param op_name : str Operator name, such as Convolution, FullyConnected :param attrs : dict Dict of operator attributes :param inputs: list list of inputs to the operator Returns ------- :return mxnet_sym Converted mxnet symbol """ if op_name in convert_map: op_name, new_attrs, inputs = convert_map[op_name](attrs, inputs, self) else: raise NotImplementedError("Operator {} not implemented.".format(op_name)) if isinstance(op_name, string_types): new_op = getattr(symbol, op_name, None) if not new_op: raise RuntimeError("Unable to map op_name {} to sym".format(op_name)) if node_name is None: mxnet_sym = new_op(*inputs, **new_attrs) else: mxnet_sym = new_op(name=node_name, *inputs, **new_attrs) return mxnet_sym return op_name
Construct symbol from onnx graph. Parameters ---------- graph : onnx protobuf object The loaded onnx graph Returns ------- sym :symbol.Symbol The returned mxnet symbol params : dict A dict of name: nd.array pairs, used as pretrained weights def from_onnx(self, graph): """Construct symbol from onnx graph. Parameters ---------- graph : onnx protobuf object The loaded onnx graph Returns ------- sym :symbol.Symbol The returned mxnet symbol params : dict A dict of name: nd.array pairs, used as pretrained weights """ # get input, output shapes self.model_metadata = self.get_graph_metadata(graph) # parse network inputs, aka parameters for init_tensor in graph.initializer: if not init_tensor.name.strip(): raise ValueError("Tensor's name is required.") self._params[init_tensor.name] = self._parse_array(init_tensor) # converting GraphProto message for i in graph.input: if i.name in self._params: # i is a param instead of input self._nodes[i.name] = symbol.Variable(name=i.name, shape=self._params[i.name].shape) else: self._nodes[i.name] = symbol.Variable(name=i.name) # constructing nodes, nodes are stored as directed acyclic graph # converting NodeProto message for node in graph.node: op_name = node.op_type node_name = node.name.strip() node_name = node_name if node_name else None onnx_attr = self._parse_attr(node.attribute) inputs = [self._nodes[i] for i in node.input] mxnet_sym = self._convert_operator(node_name, op_name, onnx_attr, inputs) for k, i in zip(list(node.output), range(len(mxnet_sym.list_outputs()))): self._nodes[k] = mxnet_sym[i] # splitting params into args and aux params for args in mxnet_sym.list_arguments(): if args in self._params: self.arg_dict.update({args: nd.array(self._params[args])}) for aux in mxnet_sym.list_auxiliary_states(): if aux in self._params: self.aux_dict.update({aux: nd.array(self._params[aux])}) # now return the outputs out = [self._nodes[i.name] for i in graph.output] if len(out) > 1: out = symbol.Group(out) else: out = out[0] return out, self.arg_dict, self.aux_dict
Get the model metadata from a given onnx graph. def get_graph_metadata(self, graph): """ Get the model metadata from a given onnx graph. """ _params = set() for tensor_vals in graph.initializer: _params.add(tensor_vals.name) input_data = [] for graph_input in graph.input: if graph_input.name not in _params: shape = [val.dim_value for val in graph_input.type.tensor_type.shape.dim] input_data.append((graph_input.name, tuple(shape))) output_data = [] for graph_out in graph.output: shape = [val.dim_value for val in graph_out.type.tensor_type.shape.dim] output_data.append((graph_out.name, tuple(shape))) metadata = {'input_tensor_data' : input_data, 'output_tensor_data' : output_data } return metadata
Construct SymbolBlock from onnx graph. Parameters ---------- graph : onnx protobuf object The loaded onnx graph ctx : Context or list of Context Loads the model into one or many context(s). Returns ------- sym_block :gluon.nn.SymbolBlock The returned gluon SymbolBlock def graph_to_gluon(self, graph, ctx): """Construct SymbolBlock from onnx graph. Parameters ---------- graph : onnx protobuf object The loaded onnx graph ctx : Context or list of Context Loads the model into one or many context(s). Returns ------- sym_block :gluon.nn.SymbolBlock The returned gluon SymbolBlock """ sym, arg_params, aux_params = self.from_onnx(graph) metadata = self.get_graph_metadata(graph) data_names = [input_tensor[0] for input_tensor in metadata['input_tensor_data']] data_inputs = [symbol.var(data_name) for data_name in data_names] from ....gluon import SymbolBlock net = SymbolBlock(outputs=sym, inputs=data_inputs) net_params = net.collect_params() for param in arg_params: if param in net_params: net_params[param].shape = arg_params[param].shape net_params[param]._load_init(arg_params[param], ctx=ctx) for param in aux_params: if param in net_params: net_params[param].shape = aux_params[param].shape net_params[param]._load_init(aux_params[param], ctx=ctx) return net
Grab data in TensorProto and convert to numpy array. def _parse_array(self, tensor_proto): """Grab data in TensorProto and convert to numpy array.""" try: from onnx.numpy_helper import to_array except ImportError: raise ImportError("Onnx and protobuf need to be installed. " + "Instructions to install - https://github.com/onnx/onnx") if len(tuple(tensor_proto.dims)) > 0: np_array = to_array(tensor_proto).reshape(tuple(tensor_proto.dims)) else: # If onnx's params are scalar values without dims mentioned. np_array = np.array([to_array(tensor_proto)]) return nd.array(np_array)
Convert a list of AttributeProto to a dict, with names as keys. def _parse_attr(self, attr_proto): """Convert a list of AttributeProto to a dict, with names as keys.""" attrs = {} for a in attr_proto: for f in ['f', 'i', 's']: if a.HasField(f): attrs[a.name] = getattr(a, f) # Needed for supporting python version > 3.5 if isinstance(attrs[a.name], bytes): attrs[a.name] = attrs[a.name].decode(encoding='utf-8') for f in ['floats', 'ints', 'strings']: if list(getattr(a, f)): assert a.name not in attrs, "Only one type of attr is allowed" attrs[a.name] = tuple(getattr(a, f)) for f in ['t', 'g']: if a.HasField(f): attrs[a.name] = getattr(a, f) for f in ['tensors', 'graphs']: if list(getattr(a, f)): raise NotImplementedError("Filed {} is not supported in mxnet.".format(f)) if a.name not in attrs: raise ValueError("Cannot parse attribute: \n{}\n.".format(a)) return attrs
Reshapes both modules for new input shapes. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically is ``data_iter.provide_label``. def reshape(self, data_shapes, label_shapes=None): """Reshapes both modules for new input shapes. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically is ``data_iter.provide_label``. """ super(SVRGModule, self).reshape(data_shapes, label_shapes=label_shapes) self._mod_aux.reshape(data_shapes, label_shapes=label_shapes)
Installs and initializes SVRGOptimizer. The SVRGOptimizer is a wrapper class for a regular optimizer that is passed in and a special AssignmentOptimizer to accumulate the full gradients. If KVStore is 'local' or None, the full gradients will be accumulated locally without pushing to the KVStore. Otherwise, additional keys will be pushed to accumulate the full gradients in the KVStore. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer : str or Optimizer Default `'sgd'` optimizer_params : dict Default `(('learning_rate', 0.01),)`. The default value is not a dictionary, just to avoid pylint warning of dangerous default values. force_init : bool Default ``False``, indicating whether we should force re-initializing the optimizer in the case an optimizer is already installed. def init_optimizer(self, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), force_init=False): """Installs and initializes SVRGOptimizer. The SVRGOptimizer is a wrapper class for a regular optimizer that is passed in and a special AssignmentOptimizer to accumulate the full gradients. If KVStore is 'local' or None, the full gradients will be accumulated locally without pushing to the KVStore. Otherwise, additional keys will be pushed to accumulate the full gradients in the KVStore. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer : str or Optimizer Default `'sgd'` optimizer_params : dict Default `(('learning_rate', 0.01),)`. The default value is not a dictionary, just to avoid pylint warning of dangerous default values. force_init : bool Default ``False``, indicating whether we should force re-initializing the optimizer in the case an optimizer is already installed. """ # Init dict for storing average of full gradients for each device self._param_dict = [{key: mx.nd.zeros(shape=value.shape, ctx=self._context[i]) for key, value in self.get_params()[0].items()} for i in range(self._ctx_len)] svrg_optimizer = self._create_optimizer(_SVRGOptimizer.__name__, default_opt=optimizer, kvstore=kvstore, optimizer_params=optimizer_params) super(SVRGModule, self).init_optimizer(kvstore=kvstore, optimizer=svrg_optimizer, optimizer_params=optimizer_params, force_init=force_init) # Init additional keys for accumulating full grads in KVStore if self._kvstore: for idx, param_on_devs in enumerate(self._exec_group.param_arrays): name = self._exec_group.param_names[idx] self._kvstore.init(name + "_full", mx.nd.zeros(shape=self._arg_params[name].shape)) if self._update_on_kvstore: self._kvstore.pull(name + "_full", param_on_devs, priority=-idx)
Helper function to create a svrg optimizer. SVRG optimizer encapsulates two optimizers and will redirect update() to the correct optimizer based on the key. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer: str Name for SVRGOptimizer default_opt : str or Optimizer that was passed in. optimizer_params : dict optimizer params that was passed in. def _create_optimizer(self, optimizer, default_opt, kvstore, optimizer_params): """Helper function to create a svrg optimizer. SVRG optimizer encapsulates two optimizers and will redirect update() to the correct optimizer based on the key. Parameters ---------- kvstore : str or KVStore Default `'local'`. optimizer: str Name for SVRGOptimizer default_opt : str or Optimizer that was passed in. optimizer_params : dict optimizer params that was passed in. """ # code partially copied from mxnet module.init_optimizer() to accomodate svrg_optimizer batch_size = self._exec_group.batch_size (kv_store, update_on_kvstore) = mx.model._create_kvstore(kvstore, self._ctx_len, self._arg_params) if kv_store and 'dist' in kv_store.type and '_sync' in kv_store.type: batch_size *= kv_store.num_workers rescale_grad = 1.0 / batch_size idx2name = {} if update_on_kvstore: idx2name.update(enumerate(self._exec_group.param_names)) else: for k in range(self._ctx_len): idx2name.update({i * self._ctx_len + k: n for i, n in enumerate(self._exec_group.param_names)}) # update idx2name to include new keys for key in self._param_dict[0].keys(): max_key = max(list(idx2name.keys())) + 1 idx2name[max_key] = key + "_full" optimizer_params = dict(optimizer_params) if 'rescale_grad' not in optimizer_params: optimizer_params['rescale_grad'] = rescale_grad optimizer_params["default_optimizer"] = default_opt optimizer_params["param_idx2name"] = idx2name optimizer = mx.optimizer.create(optimizer, **optimizer_params) return optimizer
Binds the symbols to construct executors for both two modules. This is necessary before one can perform computation with the SVRGModule. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically is ``data_iter.provide_label``. for_training : bool Default is ``True``. Whether the executors should be bound for training. inputs_need_grad : bool Default is ``False``. Whether the gradients to the input data need to be computed. Typically this is not needed. But this might be needed when implementing composition of modules. force_rebind : bool Default is ``False``. This function does nothing if the executors are already bound. But with this ``True``, the executors will be forced to rebind. shared_module : Module Default is ``None``. This is used in bucketing. When not ``None``, the shared module essentially corresponds to a different bucket -- a module with different symbol but with the same sets of parameters (e.g. unrolled RNNs with different lengths). def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binds the symbols to construct executors for both two modules. This is necessary before one can perform computation with the SVRGModule. Parameters ---------- data_shapes : list of (str, tuple) Typically is ``data_iter.provide_data``. label_shapes : list of (str, tuple) Typically is ``data_iter.provide_label``. for_training : bool Default is ``True``. Whether the executors should be bound for training. inputs_need_grad : bool Default is ``False``. Whether the gradients to the input data need to be computed. Typically this is not needed. But this might be needed when implementing composition of modules. force_rebind : bool Default is ``False``. This function does nothing if the executors are already bound. But with this ``True``, the executors will be forced to rebind. shared_module : Module Default is ``None``. This is used in bucketing. When not ``None``, the shared module essentially corresponds to a different bucket -- a module with different symbol but with the same sets of parameters (e.g. unrolled RNNs with different lengths). """ # force rebinding is typically used when one want to switch from # training to prediction phase. super(SVRGModule, self).bind(data_shapes, label_shapes, for_training, inputs_need_grad, force_rebind, shared_module, grad_req) if for_training: self._mod_aux.bind(data_shapes, label_shapes, for_training, inputs_need_grad, force_rebind, shared_module, grad_req)
Forward computation for both two modules. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or switching from training to predicting, module rebinding is required. See Also ---------- :meth:`BaseModule.forward`. Parameters ---------- data_batch : DataBatch Could be anything with similar API implemented. is_train : bool Default is ``None``, which means ``is_train`` takes the value of ``self.for_training``. def forward(self, data_batch, is_train=None): """Forward computation for both two modules. It supports data batches with different shapes, such as different batch sizes or different image sizes. If reshaping of data batch relates to modification of symbol or module, such as changing image layout ordering or switching from training to predicting, module rebinding is required. See Also ---------- :meth:`BaseModule.forward`. Parameters ---------- data_batch : DataBatch Could be anything with similar API implemented. is_train : bool Default is ``None``, which means ``is_train`` takes the value of ``self.for_training``. """ super(SVRGModule, self).forward(data_batch, is_train) if is_train: self._mod_aux.forward(data_batch, is_train)
Backward computation. See Also ---------- :meth:`BaseModule.backward`. Parameters ---------- out_grads : NDArray or list of NDArray, optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs that are not a loss function. def backward(self, out_grads=None): """Backward computation. See Also ---------- :meth:`BaseModule.backward`. Parameters ---------- out_grads : NDArray or list of NDArray, optional Gradient on the outputs to be propagated back. This parameter is only needed when bind is called on outputs that are not a loss function. """ super(SVRGModule, self).backward(out_grads) if self._mod_aux.binded: self._mod_aux.backward(out_grads)
Computes the gradients over all data w.r.t weights of past m epochs. For distributed env, it will accumulate full grads in the kvstore. Parameters ---------- train_data: DataIter Train data iterator def update_full_grads(self, train_data): """Computes the gradients over all data w.r.t weights of past m epochs. For distributed env, it will accumulate full grads in the kvstore. Parameters ---------- train_data: DataIter Train data iterator """ param_names = self._exec_group.param_names arg, aux = self.get_params() self._mod_aux.set_params(arg_params=arg, aux_params=aux) train_data.reset() nbatch = 0 padding = 0 for batch in train_data: self._mod_aux.forward(batch, is_train=True) self._mod_aux.backward() nbatch += 1 for ctx in range(self._ctx_len): for index, name in enumerate(param_names): grads = self._mod_aux._exec_group.grad_arrays[index][ctx] self._param_dict[ctx][name] = mx.nd.broadcast_add(self._param_dict[ctx][name], grads, axis=0) padding = batch.pad true_num_batch = nbatch - padding / train_data.batch_size for name in param_names: grad_list = [] for i in range(self._ctx_len): self._param_dict[i][name] /= true_num_batch grad_list.append(self._param_dict[i][name]) if self._kvstore: # If in distributed mode, push a list of gradients from each worker/device to the KVStore self._accumulate_kvstore(name, grad_list)
Accumulate gradients over all data in the KVStore. In distributed setting, each worker sees a portion of data. The full gradients will be aggregated from each worker in the KVStore. Parameters ---------- key: int or str Key in the KVStore. value: NDArray, RowSparseNDArray Average of the full gradients. def _accumulate_kvstore(self, key, value): """Accumulate gradients over all data in the KVStore. In distributed setting, each worker sees a portion of data. The full gradients will be aggregated from each worker in the KVStore. Parameters ---------- key: int or str Key in the KVStore. value: NDArray, RowSparseNDArray Average of the full gradients. """ # Accumulate full gradients for current epochs self._kvstore.push(key + "_full", value) self._kvstore._barrier() self._kvstore.pull(key + "_full", value) self._allocate_gradients(key, value)
Allocate average of full gradients accumulated in the KVStore to each device. Parameters ---------- key: int or str Key in the kvstore. value: List of NDArray, List of RowSparseNDArray A list of average of the full gradients in the KVStore. def _allocate_gradients(self, key, value): """Allocate average of full gradients accumulated in the KVStore to each device. Parameters ---------- key: int or str Key in the kvstore. value: List of NDArray, List of RowSparseNDArray A list of average of the full gradients in the KVStore. """ for i in range(self._ctx_len): self._param_dict[i][key] = value[i] / self._ctx_len
Calculates the gradient based on the SVRG update rule. Parameters ---------- g_curr_batch_curr_weight : NDArray gradients of current weight of self.mod w.r.t current batch of data g_curr_batch_special_weight: NDArray gradients of the weight of past m epochs of self._mod_special w.r.t current batch of data g_special_weight_all_batch: NDArray average of full gradients over full pass of data Returns ---------- Gradients calculated using SVRG update rule: grads = g_curr_batch_curr_weight - g_curr_batch_special_weight + g_special_weight_all_batch def _svrg_grads_update_rule(self, g_curr_batch_curr_weight, g_curr_batch_special_weight, g_special_weight_all_batch): """Calculates the gradient based on the SVRG update rule. Parameters ---------- g_curr_batch_curr_weight : NDArray gradients of current weight of self.mod w.r.t current batch of data g_curr_batch_special_weight: NDArray gradients of the weight of past m epochs of self._mod_special w.r.t current batch of data g_special_weight_all_batch: NDArray average of full gradients over full pass of data Returns ---------- Gradients calculated using SVRG update rule: grads = g_curr_batch_curr_weight - g_curr_batch_special_weight + g_special_weight_all_batch """ for index, grad in enumerate(g_curr_batch_curr_weight): grad -= g_curr_batch_special_weight[index] grad += g_special_weight_all_batch[index] return g_curr_batch_curr_weight
Calculates gradients based on the SVRG update rule. def _update_svrg_gradients(self): """Calculates gradients based on the SVRG update rule. """ param_names = self._exec_group.param_names for ctx in range(self._ctx_len): for index, name in enumerate(param_names): g_curr_batch_reg = self._exec_group.grad_arrays[index][ctx] g_curr_batch_special = self._mod_aux._exec_group.grad_arrays[index][ctx] g_special_weight_all_batch = self._param_dict[ctx][name] g_svrg = self._svrg_grads_update_rule(g_curr_batch_reg, g_curr_batch_special, g_special_weight_all_batch) self._exec_group.grad_arrays[index][ctx] = g_svrg
Trains the module parameters. Parameters ---------- train_data : DataIter Train DataIter. eval_data : DataIter If not ``None``, will be used as validation set and the performance after each epoch will be evaluated. eval_metric : str or EvalMetric Defaults to 'accuracy'. The performance measure used to display during training. Other possible predefined metrics are: 'ce' (CrossEntropy), 'f1', 'mae', 'mse', 'rmse', 'top_k_accuracy'. epoch_end_callback : function or list of functions Each callback will be called with the current `epoch`, `symbol`, `arg_params` and `aux_params`. batch_end_callback : function or list of function Each callback will be called with a `BatchEndParam`. kvstore : str or KVStore Defaults to 'local'. optimizer : str or Optimizer Defaults to 'sgd'. optimizer_params : dict Defaults to ``(('learning_rate', 0.01),)``. The parameters for the optimizer constructor. The default value is not a dict, just to avoid pylint warning on dangerous default values. eval_end_callback : function or list of function These will be called at the end of each full evaluation, with the metrics over the entire evaluation set. eval_batch_end_callback : function or list of function These will be called at the end of each mini-batch during evaluation. initializer : Initializer The initializer is called to initialize the module parameters when they are not already initialized. arg_params : dict Defaults to ``None``, if not ``None``, should be existing parameters from a trained model or loaded from a checkpoint (previously saved model). In this case, the value here will be used to initialize the module parameters, unless they are already initialized by the user via a call to `init_params` or `fit`. `arg_params` has a higher priority than `initializer`. aux_params : dict Defaults to ``None``. Similar to `arg_params`, except for auxiliary states. allow_missing : bool Defaults to ``False``. Indicates whether to allow missing parameters when `arg_params` and `aux_params` are not ``None``. If this is ``True``, then the missing parameters will be initialized via the `initializer`. force_rebind : bool Defaults to ``False``. Whether to force rebinding the executors if already bound. force_init : bool Defaults to ``False``. Indicates whether to force initialization even if the parameters are already initialized. begin_epoch : int Defaults to 0. Indicates the starting epoch. Usually, if resumed from a checkpoint saved at a previous training phase at epoch N, then this value should be N+1. num_epoch : int Number of epochs for training. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull. validation_metric: str or EvalMetric The performance measure used to display during validation. def fit(self, train_data, eval_data=None, eval_metric='acc', epoch_end_callback=None, batch_end_callback=None, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), eval_end_callback=None, eval_batch_end_callback=None, initializer=mx.init.Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_rebind=False, force_init=False, begin_epoch=0, num_epoch=None, validation_metric=None, monitor=None, sparse_row_id_fn=None): """Trains the module parameters. Parameters ---------- train_data : DataIter Train DataIter. eval_data : DataIter If not ``None``, will be used as validation set and the performance after each epoch will be evaluated. eval_metric : str or EvalMetric Defaults to 'accuracy'. The performance measure used to display during training. Other possible predefined metrics are: 'ce' (CrossEntropy), 'f1', 'mae', 'mse', 'rmse', 'top_k_accuracy'. epoch_end_callback : function or list of functions Each callback will be called with the current `epoch`, `symbol`, `arg_params` and `aux_params`. batch_end_callback : function or list of function Each callback will be called with a `BatchEndParam`. kvstore : str or KVStore Defaults to 'local'. optimizer : str or Optimizer Defaults to 'sgd'. optimizer_params : dict Defaults to ``(('learning_rate', 0.01),)``. The parameters for the optimizer constructor. The default value is not a dict, just to avoid pylint warning on dangerous default values. eval_end_callback : function or list of function These will be called at the end of each full evaluation, with the metrics over the entire evaluation set. eval_batch_end_callback : function or list of function These will be called at the end of each mini-batch during evaluation. initializer : Initializer The initializer is called to initialize the module parameters when they are not already initialized. arg_params : dict Defaults to ``None``, if not ``None``, should be existing parameters from a trained model or loaded from a checkpoint (previously saved model). In this case, the value here will be used to initialize the module parameters, unless they are already initialized by the user via a call to `init_params` or `fit`. `arg_params` has a higher priority than `initializer`. aux_params : dict Defaults to ``None``. Similar to `arg_params`, except for auxiliary states. allow_missing : bool Defaults to ``False``. Indicates whether to allow missing parameters when `arg_params` and `aux_params` are not ``None``. If this is ``True``, then the missing parameters will be initialized via the `initializer`. force_rebind : bool Defaults to ``False``. Whether to force rebinding the executors if already bound. force_init : bool Defaults to ``False``. Indicates whether to force initialization even if the parameters are already initialized. begin_epoch : int Defaults to 0. Indicates the starting epoch. Usually, if resumed from a checkpoint saved at a previous training phase at epoch N, then this value should be N+1. num_epoch : int Number of epochs for training. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull. validation_metric: str or EvalMetric The performance measure used to display during validation. """ assert num_epoch is not None, 'please specify number of epochs' self.bind(data_shapes=train_data.provide_data, label_shapes=train_data.provide_label, for_training=True, force_rebind=force_rebind) if monitor is not None: self.install_monitor(monitor) self.init_params(initializer=initializer, arg_params=arg_params, aux_params=aux_params, allow_missing=allow_missing, force_init=force_init) self.init_optimizer(kvstore=kvstore, optimizer=optimizer, optimizer_params=optimizer_params) if validation_metric is None: validation_metric = eval_metric if not isinstance(eval_metric, mx.metric.EvalMetric): eval_metric = mx.metric.create(eval_metric) ################################################################################ # training loop ################################################################################ for epoch in range(begin_epoch, num_epoch): eval_metric.reset() tic = time.time() if epoch % self.update_freq == 0: self.update_full_grads(train_data) train_data.reset() data_iter = iter(train_data) end_of_batch = False nbatch = 0 next_data_batch = next(data_iter) while not end_of_batch: data_batch = next_data_batch if monitor is not None: monitor.tic() self.forward_backward(data_batch) self.update() if isinstance(data_batch, list): self.update_metric(eval_metric, [db.label for db in data_batch], pre_sliced=True) else: self.update_metric(eval_metric, data_batch.label) try: # pre fetch next batch next_data_batch = next(data_iter) self.prepare(next_data_batch, sparse_row_id_fn=sparse_row_id_fn) except StopIteration: end_of_batch = True if monitor is not None: monitor.toc_print() if end_of_batch: eval_name_vals = eval_metric.get_name_value() if batch_end_callback is not None: batch_end_params = mx.model.BatchEndParam(epoch=epoch, nbatch=nbatch, eval_metric=eval_metric, locals=locals()) for callback in mx.base._as_list(batch_end_callback): callback(batch_end_params) nbatch += 1 for name, val in eval_name_vals: self.logger.info('Epoch[%d] Train-%s=%f', epoch, name, val) toc = time.time() self.logger.info('Epoch[%d] Time cost=%.3f', epoch, (toc - tic)) # sync aux params across devices arg_params, aux_params = self.get_params() self.set_params(arg_params, aux_params) if epoch_end_callback is not None: for callback in mx.base._as_list(epoch_end_callback): callback(epoch, self.symbol, arg_params, aux_params) # ---------------------------------------- # evaluation on validation set if eval_data: res = self.score(eval_data, validation_metric, score_end_callback=eval_end_callback, batch_end_callback=eval_batch_end_callback, epoch=epoch) for name, val in res: self.logger.info('Epoch[%d] Validation-%s=%f', epoch, name, val)
Prepares two modules for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_sparse` parameters based on the sparse_row_id_fn. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters, the `update()` updates the copy of parameters in KVStore, but doesn't broadcast the updated parameters to all devices / machines. The `prepare` function is used to broadcast `row_sparse` parameters with the next batch of data. Parameters ---------- data_batch : DataBatch The current batch of data for forward computation. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull. def prepare(self, data_batch, sparse_row_id_fn=None): """Prepares two modules for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_sparse` parameters based on the sparse_row_id_fn. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters, the `update()` updates the copy of parameters in KVStore, but doesn't broadcast the updated parameters to all devices / machines. The `prepare` function is used to broadcast `row_sparse` parameters with the next batch of data. Parameters ---------- data_batch : DataBatch The current batch of data for forward computation. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull. """ super(SVRGModule, self).prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn) self._mod_aux.prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn)
find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting def _load_image_set_index(self, shuffle): """ find out which indexes correspond to given image set (train or val) Parameters: ---------- shuffle : boolean whether to shuffle the image list Returns: ---------- entire list of images specified in the setting """ assert os.path.exists(self.list_file), 'Path does not exists: {}'.format(self.list_file) with open(self.list_file, 'r') as f: image_set_index = [x.strip() for x in f.readlines()] if shuffle: np.random.shuffle(image_set_index) return image_set_index
given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file def _label_path_from_index(self, index): """ given image index, find out annotation path Parameters: ---------- index: int index of a specific image Returns: ---------- full path of annotation file """ label_file = os.path.join(self.label_dir, index + self.label_extension) assert os.path.exists(label_file), 'Path does not exist: {}'.format(label_file) return label_file
preprocess all ground-truths Returns: ---------- labels packed in [num_images x max_num_objects x 5] tensor def _load_image_labels(self): """ preprocess all ground-truths Returns: ---------- labels packed in [num_images x max_num_objects x 5] tensor """ temp = [] # load ground-truths for idx in self.image_set_index: label_file = self._label_path_from_index(idx) with open(label_file, 'r') as f: label = [] for line in f.readlines(): temp_label = line.strip().split() assert len(temp_label) == 5, "Invalid label file" + label_file cls_id = int(temp_label[0]) x = float(temp_label[1]) y = float(temp_label[2]) half_width = float(temp_label[3]) / 2 half_height = float(temp_label[4]) / 2 xmin = x - half_width ymin = y - half_height xmax = x + half_width ymax = y + half_height label.append([cls_id, xmin, ymin, xmax, ymax]) temp.append(np.array(label)) return temp
Get registrator function. Parameters ---------- base_class : type base class for classes that will be reigstered nickname : str nickname of base_class for logging Returns ------- a registrator function def get_register_func(base_class, nickname): """Get registrator function. Parameters ---------- base_class : type base class for classes that will be reigstered nickname : str nickname of base_class for logging Returns ------- a registrator function """ if base_class not in _REGISTRY: _REGISTRY[base_class] = {} registry = _REGISTRY[base_class] def register(klass, name=None): """Register functions""" assert issubclass(klass, base_class), \ "Can only register subclass of %s"%base_class.__name__ if name is None: name = klass.__name__ name = name.lower() if name in registry: warnings.warn( "\033[91mNew %s %s.%s registered with name %s is" "overriding existing %s %s.%s\033[0m"%( nickname, klass.__module__, klass.__name__, name, nickname, registry[name].__module__, registry[name].__name__), UserWarning, stacklevel=2) registry[name] = klass return klass register.__doc__ = "Register %s to the %s factory"%(nickname, nickname) return register
Get registrator function that allow aliases. Parameters ---------- base_class : type base class for classes that will be reigstered nickname : str nickname of base_class for logging Returns ------- a registrator function def get_alias_func(base_class, nickname): """Get registrator function that allow aliases. Parameters ---------- base_class : type base class for classes that will be reigstered nickname : str nickname of base_class for logging Returns ------- a registrator function """ register = get_register_func(base_class, nickname) def alias(*aliases): """alias registrator""" def reg(klass): """registrator function""" for name in aliases: register(klass, name) return klass return reg return alias
Get creator function Parameters ---------- base_class : type base class for classes that will be reigstered nickname : str nickname of base_class for logging Returns ------- a creator function def get_create_func(base_class, nickname): """Get creator function Parameters ---------- base_class : type base class for classes that will be reigstered nickname : str nickname of base_class for logging Returns ------- a creator function """ if base_class not in _REGISTRY: _REGISTRY[base_class] = {} registry = _REGISTRY[base_class] def create(*args, **kwargs): """Create instance from config""" if len(args): name = args[0] args = args[1:] else: name = kwargs.pop(nickname) if isinstance(name, base_class): assert len(args) == 0 and len(kwargs) == 0, \ "%s is already an instance. Additional arguments are invalid"%(nickname) return name if isinstance(name, dict): return create(**name) assert isinstance(name, string_types), "%s must be of string type"%nickname if name.startswith('['): assert not args and not kwargs name, kwargs = json.loads(name) return create(name, **kwargs) elif name.startswith('{'): assert not args and not kwargs kwargs = json.loads(name) return create(**kwargs) name = name.lower() assert name in registry, \ "%s is not registered. Please register with %s.register first"%( str(name), nickname) return registry[name](*args, **kwargs) create.__doc__ = """Create a %s instance from config. Parameters ---------- %s : str or %s instance class name of desired instance. If is a instance, it will be returned directly. **kwargs : dict arguments to be passed to constructor"""%(nickname, nickname, base_class.__name__) return create
Parse arguments. def parse_args(): """Parse arguments.""" parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Diagnose script for checking the current system.') choices = ['python', 'pip', 'mxnet', 'os', 'hardware', 'network'] for choice in choices: parser.add_argument('--' + choice, default=1, type=int, help='Diagnose {}.'.format(choice)) parser.add_argument('--region', default='', type=str, help="Additional sites in which region(s) to test. \ Specify 'cn' for example to test mirror sites in China.") parser.add_argument('--timeout', default=10, type=int, help="Connection test timeout threshold, 0 to disable.") args = parser.parse_args() return args
Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py def clean_str(string): """Tokenization/string cleaning for all datasets except for SST. Original taken from https://github.com/yoonkim/CNN_sentence/blob/master/process_data.py """ string = re.sub(r"[^A-Za-z0-9(),!?\'\`]", " ", string) string = re.sub(r"\'s", " \'s", string) string = re.sub(r"\'ve", " \'ve", string) string = re.sub(r"n\'t", " n\'t", string) string = re.sub(r"\'re", " \'re", string) string = re.sub(r"\'d", " \'d", string) string = re.sub(r"\'ll", " \'ll", string) string = re.sub(r",", " , ", string) string = re.sub(r"!", " ! ", string) string = re.sub(r"\(", r" \( ", string) string = re.sub(r"\)", r" \) ", string) string = re.sub(r"\?", r" \? ", string) string = re.sub(r"\s{2,}", " ", string) return string.strip().lower()
Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. def load_data_and_labels(): """Loads MR polarity data from files, splits the data into words and generates labels. Returns split sentences and labels. """ # Load data from files pos_path = "./data/rt-polaritydata/rt-polarity.pos" neg_path = "./data/rt-polaritydata/rt-polarity.neg" if not os.path.exists(pos_path): os.system("git clone https://github.com/dennybritz/cnn-text-classification-tf.git") os.system('mv cnn-text-classification-tf/data .') os.system('rm -rf cnn-text-classification-tf') positive_examples = list(open(pos_path).readlines()) positive_examples = [s.strip() for s in positive_examples] negative_examples = list(open(neg_path).readlines()) negative_examples = [s.strip() for s in negative_examples] # Split by words x_text = positive_examples + negative_examples x_text = [clean_str(sent) for sent in x_text] x_text = [s.split(" ") for s in x_text] # Generate labels positive_labels = [1 for _ in positive_examples] negative_labels = [0 for _ in negative_examples] y = np.concatenate([positive_labels, negative_labels], 0) return [x_text, y]
Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. def pad_sentences(sentences, padding_word="</s>"): """Pads all sentences to the same length. The length is defined by the longest sentence. Returns padded sentences. """ sequence_length = max(len(x) for x in sentences) padded_sentences = [] for i, sentence in enumerate(sentences): num_padding = sequence_length - len(sentence) new_sentence = sentence + [padding_word] * num_padding padded_sentences.append(new_sentence) return padded_sentences
Maps sentencs and labels to vectors based on a vocabulary. def build_input_data(sentences, labels, vocabulary): """Maps sentencs and labels to vectors based on a vocabulary.""" x = np.array([[vocabulary[word] for word in sentence] for sentence in sentences]) y = np.array(labels) return [x, y]
Map sentences and labels to vectors based on a pretrained word2vec def build_input_data_with_word2vec(sentences, labels, word2vec_list): """ Map sentences and labels to vectors based on a pretrained word2vec """ x_vec = [] for sent in sentences: vec = [] for word in sent: if word in word2vec_list: vec.append(word2vec_list[word]) else: vec.append(word2vec_list['</s>']) x_vec.append(vec) x_vec = np.array(x_vec) y_vec = np.array(labels) return [x_vec, y_vec]
Loads and preprocessed data for the MR dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary. def load_data_with_word2vec(word2vec_list): """Loads and preprocessed data for the MR dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary. """ # Load and preprocess data sentences, labels = load_data_and_labels() sentences_padded = pad_sentences(sentences) # vocabulary, vocabulary_inv = build_vocab(sentences_padded) return build_input_data_with_word2vec(sentences_padded, labels, word2vec_list)
Loads and preprocessed data for the MR dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary. def load_data(): """Loads and preprocessed data for the MR dataset. Returns input vectors, labels, vocabulary, and inverse vocabulary. """ # Load and preprocess data sentences, labels = load_data_and_labels() sentences_padded = pad_sentences(sentences) vocabulary, vocabulary_inv = build_vocab(sentences_padded) x, y = build_input_data(sentences_padded, labels, vocabulary) return [x, y, vocabulary, vocabulary_inv]
Generates a batch iterator for a dataset. def batch_iter(data, batch_size, num_epochs): """Generates a batch iterator for a dataset.""" data = np.array(data) data_size = len(data) num_batches_per_epoch = int(len(data)/batch_size) + 1 for epoch in range(num_epochs): # Shuffle the data at each epoch shuffle_indices = np.random.permutation(np.arange(data_size)) shuffled_data = data[shuffle_indices] for batch_num in range(num_batches_per_epoch): start_index = batch_num * batch_size end_index = min((batch_num + 1) * batch_size, data_size) yield shuffled_data[start_index:end_index]
Load the pre-trained word2vec from file. def load_pretrained_word2vec(infile): """Load the pre-trained word2vec from file.""" if isinstance(infile, str): infile = open(infile) word2vec_list = {} for idx, line in enumerate(infile): if idx == 0: vocab_size, dim = line.strip().split() else: tks = line.strip().split() word2vec_list[tks[0]] = map(float, tks[1:]) return word2vec_list
return batch def generate_batch(im_tensor, im_info): """return batch""" data = [im_tensor, im_info] data_shapes = [('data', im_tensor.shape), ('im_info', im_info.shape)] data_batch = mx.io.DataBatch(data=data, label=None, provide_data=data_shapes, provide_label=None) return data_batch
VGG 16 layers network This is a modified version, with fc6/fc7 layers replaced by conv layers And the network is slightly smaller than original VGG 16 network def get_symbol(num_classes=1000, **kwargs): """ VGG 16 layers network This is a modified version, with fc6/fc7 layers replaced by conv layers And the network is slightly smaller than original VGG 16 network """ data = mx.symbol.Variable(name="data") label = mx.symbol.Variable(name="label") # group 1 conv1_1 = mx.symbol.Convolution( data=data, kernel=(3, 3), pad=(1, 1), num_filter=64, name="conv1_1") relu1_1 = mx.symbol.Activation(data=conv1_1, act_type="relu", name="relu1_1") conv1_2 = mx.symbol.Convolution( data=relu1_1, kernel=(3, 3), pad=(1, 1), num_filter=64, name="conv1_2") relu1_2 = mx.symbol.Activation(data=conv1_2, act_type="relu", name="relu1_2") pool1 = mx.symbol.Pooling( data=relu1_2, pool_type="max", kernel=(2, 2), stride=(2, 2), name="pool1") # group 2 conv2_1 = mx.symbol.Convolution( data=pool1, kernel=(3, 3), pad=(1, 1), num_filter=128, name="conv2_1") relu2_1 = mx.symbol.Activation(data=conv2_1, act_type="relu", name="relu2_1") conv2_2 = mx.symbol.Convolution( data=relu2_1, kernel=(3, 3), pad=(1, 1), num_filter=128, name="conv2_2") relu2_2 = mx.symbol.Activation(data=conv2_2, act_type="relu", name="relu2_2") pool2 = mx.symbol.Pooling( data=relu2_2, pool_type="max", kernel=(2, 2), stride=(2, 2), name="pool2") # group 3 conv3_1 = mx.symbol.Convolution( data=pool2, kernel=(3, 3), pad=(1, 1), num_filter=256, name="conv3_1") relu3_1 = mx.symbol.Activation(data=conv3_1, act_type="relu", name="relu3_1") conv3_2 = mx.symbol.Convolution( data=relu3_1, kernel=(3, 3), pad=(1, 1), num_filter=256, name="conv3_2") relu3_2 = mx.symbol.Activation(data=conv3_2, act_type="relu", name="relu3_2") conv3_3 = mx.symbol.Convolution( data=relu3_2, kernel=(3, 3), pad=(1, 1), num_filter=256, name="conv3_3") relu3_3 = mx.symbol.Activation(data=conv3_3, act_type="relu", name="relu3_3") pool3 = mx.symbol.Pooling( data=relu3_3, pool_type="max", kernel=(2, 2), stride=(2, 2), \ pooling_convention="full", name="pool3") # group 4 conv4_1 = mx.symbol.Convolution( data=pool3, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv4_1") relu4_1 = mx.symbol.Activation(data=conv4_1, act_type="relu", name="relu4_1") conv4_2 = mx.symbol.Convolution( data=relu4_1, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv4_2") relu4_2 = mx.symbol.Activation(data=conv4_2, act_type="relu", name="relu4_2") conv4_3 = mx.symbol.Convolution( data=relu4_2, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv4_3") relu4_3 = mx.symbol.Activation(data=conv4_3, act_type="relu", name="relu4_3") pool4 = mx.symbol.Pooling( data=relu4_3, pool_type="max", kernel=(2, 2), stride=(2, 2), name="pool4") # group 5 conv5_1 = mx.symbol.Convolution( data=pool4, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv5_1") relu5_1 = mx.symbol.Activation(data=conv5_1, act_type="relu", name="relu5_1") conv5_2 = mx.symbol.Convolution( data=relu5_1, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv5_2") relu5_2 = mx.symbol.Activation(data=conv5_2, act_type="relu", name="relu5_2") conv5_3 = mx.symbol.Convolution( data=relu5_2, kernel=(3, 3), pad=(1, 1), num_filter=512, name="conv5_3") relu5_3 = mx.symbol.Activation(data=conv5_3, act_type="relu", name="relu5_3") pool5 = mx.symbol.Pooling( data=relu5_3, pool_type="max", kernel=(3, 3), stride=(1, 1), pad=(1,1), name="pool5") # group 6 conv6 = mx.symbol.Convolution( data=pool5, kernel=(3, 3), pad=(6, 6), dilate=(6, 6), num_filter=1024, name="fc6") relu6 = mx.symbol.Activation(data=conv6, act_type="relu", name="relu6") # drop6 = mx.symbol.Dropout(data=relu6, p=0.5, name="drop6") # group 7 conv7 = mx.symbol.Convolution( data=relu6, kernel=(1, 1), pad=(0, 0), num_filter=1024, name="fc7") relu7 = mx.symbol.Activation(data=conv7, act_type="relu", name="relu7") # drop7 = mx.symbol.Dropout(data=relu7, p=0.5, name="drop7") gpool = mx.symbol.Pooling(data=relu7, pool_type='avg', kernel=(7, 7), global_pool=True, name='global_pool') conv8 = mx.symbol.Convolution(data=gpool, num_filter=num_classes, kernel=(1, 1), name='fc8') flat = mx.symbol.Flatten(data=conv8) softmax = mx.symbol.SoftmaxOutput(data=flat, name='softmax') return softmax
Get multi-layer perceptron def get_mlp(): """Get multi-layer perceptron""" data = mx.symbol.Variable('data') fc1 = mx.symbol.CaffeOp(data_0=data, num_weight=2, name='fc1', prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 128} }") act1 = mx.symbol.CaffeOp(data_0=fc1, prototxt="layer{type:\"TanH\"}") fc2 = mx.symbol.CaffeOp(data_0=act1, num_weight=2, name='fc2', prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 64} }") act2 = mx.symbol.CaffeOp(data_0=fc2, prototxt="layer{type:\"TanH\"}") fc3 = mx.symbol.CaffeOp(data_0=act2, num_weight=2, name='fc3', prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 10}}") if use_caffe_loss: label = mx.symbol.Variable('softmax_label') mlp = mx.symbol.CaffeLoss(data=fc3, label=label, grad_scale=1, name='softmax', prototxt="layer{type:\"SoftmaxWithLoss\"}") else: mlp = mx.symbol.SoftmaxOutput(data=fc3, name='softmax') return mlp
LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE (1998) def get_lenet(): """LeCun, Yann, Leon Bottou, Yoshua Bengio, and Patrick Haffner. "Gradient-based learning applied to document recognition." Proceedings of the IEEE (1998) """ data = mx.symbol.Variable('data') # first conv conv1 = mx.symbol.CaffeOp(data_0=data, num_weight=2, prototxt="layer{type:\"Convolution\" " "convolution_param { num_output: 20 kernel_size: 5 stride: 1} }") act1 = mx.symbol.CaffeOp(data_0=conv1, prototxt="layer{type:\"TanH\"}") pool1 = mx.symbol.CaffeOp(data_0=act1, prototxt="layer{type:\"Pooling\" pooling_param { pool: MAX kernel_size: 2 stride: 2}}") # second conv conv2 = mx.symbol.CaffeOp(data_0=pool1, num_weight=2, prototxt="layer{type:\"Convolution\" " "convolution_param { num_output: 50 kernel_size: 5 stride: 1} }") act2 = mx.symbol.CaffeOp(data_0=conv2, prototxt="layer{type:\"TanH\"}") pool2 = mx.symbol.CaffeOp(data_0=act2, prototxt="layer{type:\"Pooling\" pooling_param { pool: MAX kernel_size: 2 stride: 2}}") fc1 = mx.symbol.CaffeOp(data_0=pool2, num_weight=2, prototxt="layer{type:\"InnerProduct\" inner_product_param{num_output: 500} }") act3 = mx.symbol.CaffeOp(data_0=fc1, prototxt="layer{type:\"TanH\"}") # second fullc fc2 = mx.symbol.CaffeOp(data_0=act3, num_weight=2, prototxt="layer{type:\"InnerProduct\"inner_product_param{num_output: 10} }") if use_caffe_loss: label = mx.symbol.Variable('softmax_label') lenet = mx.symbol.CaffeLoss(data=fc2, label=label, grad_scale=1, name='softmax', prototxt="layer{type:\"SoftmaxWithLoss\"}") else: lenet = mx.symbol.SoftmaxOutput(data=fc2, name='softmax') return lenet
Parse the arguments def parse_args(): """Parse the arguments""" parser = argparse.ArgumentParser(description='train an image classifier on mnist') parser.add_argument('--network', type=str, default='lenet', help='the cnn to use (mlp | lenet | <path to network json file>') parser.add_argument('--caffe-loss', type=int, default=0, help='Use CaffeLoss symbol') parser.add_argument('--caffe-data', action='store_true', help='Use Caffe input-data layer only if specified') parser.add_argument('--data-dir', type=str, default='mnist/', help='the input data directory') parser.add_argument('--gpus', type=str, help='the gpus will be used, e.g "0,1,2,3"') parser.add_argument('--num-examples', type=int, default=60000, help='the number of training examples') parser.add_argument('--batch-size', type=int, default=128, help='the batch size') parser.add_argument('--lr', type=float, default=.1, help='the initial learning rate') parser.add_argument('--model-prefix', type=str, help='the prefix of the model to load/save') parser.add_argument('--save-model-prefix', type=str, help='the prefix of the model to save') parser.add_argument('--num-epochs', type=int, default=10, help='the number of training epochs') parser.add_argument('--load-epoch', type=int, help="load the model on an epoch using the model-prefix") parser.add_argument('--kv-store', type=str, default='local', help='the kvstore type') parser.add_argument('--lr-factor', type=float, default=1, help='times the lr with a factor for every lr-factor-epoch epoch') parser.add_argument('--lr-factor-epoch', type=float, default=1, help='the number of epoch to factor the lr, could be .5') return parser.parse_args()
Implements forward computation. is_train : bool, whether forwarding for training or testing. req : list of {'null', 'write', 'inplace', 'add'}, how to assign to out_data. 'null' means skip assignment, etc. in_data : list of NDArray, input data. out_data : list of NDArray, pre-allocated output buffers. aux : list of NDArray, mutable auxiliary states. Usually not used. def forward(self, is_train, req, in_data, out_data, aux): """Implements forward computation. is_train : bool, whether forwarding for training or testing. req : list of {'null', 'write', 'inplace', 'add'}, how to assign to out_data. 'null' means skip assignment, etc. in_data : list of NDArray, input data. out_data : list of NDArray, pre-allocated output buffers. aux : list of NDArray, mutable auxiliary states. Usually not used. """ data = in_data[0] label = in_data[1] pred = mx.nd.SoftmaxOutput(data, label) self.assign(out_data[0], req[0], pred)
Implements backward computation req : list of {'null', 'write', 'inplace', 'add'}, how to assign to in_grad out_grad : list of NDArray, gradient w.r.t. output data. in_grad : list of NDArray, gradient w.r.t. input data. This is the output buffer. def backward(self, req, out_grad, in_data, out_data, in_grad, aux): """Implements backward computation req : list of {'null', 'write', 'inplace', 'add'}, how to assign to in_grad out_grad : list of NDArray, gradient w.r.t. output data. in_grad : list of NDArray, gradient w.r.t. input data. This is the output buffer. """ label = in_data[1] pred = out_data[0] dx = pred - mx.nd.one_hot(label, 2) pos_cls_weight = self.positive_cls_weight scale_factor = ((1 + label * pos_cls_weight) / pos_cls_weight).reshape((pred.shape[0],1)) rescaled_dx = scale_factor * dx self.assign(in_grad[0], req[0], rescaled_dx)
Internal utility function to reset binding. def _reset_bind(self): """Internal utility function to reset binding.""" self.binded = False self._buckets = {} self._curr_module = None self._curr_bucket_key = None
A list of names for data required by this module. def data_names(self): """A list of names for data required by this module.""" if self.binded: return self._curr_module.data_names else: _, data_names, _ = self._call_sym_gen(self._default_bucket_key) return data_names
A list of names for the outputs of this module. def output_names(self): """A list of names for the outputs of this module.""" if self.binded: return self._curr_module.output_names else: symbol, _, _ = self._call_sym_gen(self._default_bucket_key) return symbol.list_outputs()
Gets current parameters. Returns ------- `(arg_params, aux_params)` A pair of dictionaries each mapping parameter names to NDArray values. def get_params(self): """Gets current parameters. Returns ------- `(arg_params, aux_params)` A pair of dictionaries each mapping parameter names to NDArray values. """ assert self.binded and self.params_initialized self._curr_module._params_dirty = self._params_dirty params = self._curr_module.get_params() self._params_dirty = False return params
Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Defaults to ``None``. Existing parameters. This has higher priority than `initializer`. aux_params : dict Defaults to ``None``. Existing auxiliary states. This has higher priority than `initializer`. allow_missing : bool Allow missing values in `arg_params` and `aux_params` (if not ``None``). In this case, missing values will be filled with `initializer`. force_init : bool Defaults to ``False``. allow_extra : boolean, optional Whether allow extra parameters that are not needed by symbol. If this is True, no error will be thrown when arg_params or aux_params contain extra parameters that is not needed by the executor. def init_params(self, initializer=Uniform(0.01), arg_params=None, aux_params=None, allow_missing=False, force_init=False, allow_extra=False): """Initializes parameters. Parameters ---------- initializer : Initializer arg_params : dict Defaults to ``None``. Existing parameters. This has higher priority than `initializer`. aux_params : dict Defaults to ``None``. Existing auxiliary states. This has higher priority than `initializer`. allow_missing : bool Allow missing values in `arg_params` and `aux_params` (if not ``None``). In this case, missing values will be filled with `initializer`. force_init : bool Defaults to ``False``. allow_extra : boolean, optional Whether allow extra parameters that are not needed by symbol. If this is True, no error will be thrown when arg_params or aux_params contain extra parameters that is not needed by the executor. """ if self.params_initialized and not force_init: return assert self.binded, 'call bind before initializing the parameters' self._curr_module.init_params(initializer=initializer, arg_params=arg_params, aux_params=aux_params, allow_missing=allow_missing, force_init=force_init, allow_extra=allow_extra) self._params_dirty = False self.params_initialized = True
Gets states from all devices. Parameters ---------- merge_multi_context : bool Default is `True`. In the case when data-parallelism is used, the states will be collected from multiple devices. A `True` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArrays or list of list of NDArrays If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are `NDArray`. def get_states(self, merge_multi_context=True): """Gets states from all devices. Parameters ---------- merge_multi_context : bool Default is `True`. In the case when data-parallelism is used, the states will be collected from multiple devices. A `True` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArrays or list of list of NDArrays If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are `NDArray`. """ assert self.binded and self.params_initialized return self._curr_module.get_states(merge_multi_context=merge_multi_context)
Sets value for states. Only one of states & values can be specified. Parameters ---------- states : list of list of NDArrays Source states arrays formatted like ``[[state1_dev1, state1_dev2], [state2_dev1, state2_dev2]]``. value : number A single scalar value for all state arrays. def set_states(self, states=None, value=None): """Sets value for states. Only one of states & values can be specified. Parameters ---------- states : list of list of NDArrays Source states arrays formatted like ``[[state1_dev1, state1_dev2], [state2_dev1, state2_dev2]]``. value : number A single scalar value for all state arrays. """ assert self.binded and self.params_initialized self._curr_module.set_states(states, value)
Binding for a `BucketingModule` means setting up the buckets and binding the executor for the default bucket key. Executors corresponding to other keys are bound afterwards with `switch_bucket`. Parameters ---------- data_shapes : list of (str, tuple) This should correspond to the symbol for the default bucket. label_shapes : list of (str, tuple) This should correspond to the symbol for the default bucket. for_training : bool Default is ``True``. inputs_need_grad : bool Default is ``False``. force_rebind : bool Default is ``False``. shared_module : BucketingModule Default is ``None``. This value is currently not used. grad_req : str, list of str, dict of str to str Requirement for gradient accumulation. Can be 'write', 'add', or 'null' (default to 'write'). Can be specified globally (str) or for each argument (list, dict). bucket_key : str (or any python object) bucket key for binding. by default use the default_bucket_key def bind(self, data_shapes, label_shapes=None, for_training=True, inputs_need_grad=False, force_rebind=False, shared_module=None, grad_req='write'): """Binding for a `BucketingModule` means setting up the buckets and binding the executor for the default bucket key. Executors corresponding to other keys are bound afterwards with `switch_bucket`. Parameters ---------- data_shapes : list of (str, tuple) This should correspond to the symbol for the default bucket. label_shapes : list of (str, tuple) This should correspond to the symbol for the default bucket. for_training : bool Default is ``True``. inputs_need_grad : bool Default is ``False``. force_rebind : bool Default is ``False``. shared_module : BucketingModule Default is ``None``. This value is currently not used. grad_req : str, list of str, dict of str to str Requirement for gradient accumulation. Can be 'write', 'add', or 'null' (default to 'write'). Can be specified globally (str) or for each argument (list, dict). bucket_key : str (or any python object) bucket key for binding. by default use the default_bucket_key """ # in case we already initialized params, keep it if self.params_initialized: arg_params, aux_params = self.get_params() # force rebinding is typically used when one want to switch from # training to prediction phase. if force_rebind: self._reset_bind() if self.binded: self.logger.warning('Already bound, ignoring bind()') return assert shared_module is None, 'shared_module for BucketingModule is not supported' self.for_training = for_training self.inputs_need_grad = inputs_need_grad self.binded = True self._grad_req = grad_req symbol, data_names, label_names = self._call_sym_gen(self._default_bucket_key) module = Module(symbol, data_names, label_names, logger=self.logger, context=self._context, work_load_list=self._work_load_list, fixed_param_names=self._fixed_param_names, state_names=self._state_names, group2ctxs=self._group2ctxs, compression_params=self._compression_params) module.bind(data_shapes, label_shapes, for_training, inputs_need_grad, force_rebind=False, shared_module=None, grad_req=self._grad_req) self._curr_module = module self._curr_bucket_key = self._default_bucket_key self._buckets[self._default_bucket_key] = module # copy back saved params, if already initialized if self.params_initialized: self.set_params(arg_params, aux_params)
Switches to a different bucket. This will change ``self.curr_module``. Parameters ---------- bucket_key : str (or any python object) The key of the target bucket. data_shapes : list of (str, tuple) Typically ``data_batch.provide_data``. label_shapes : list of (str, tuple) Typically ``data_batch.provide_label``. def switch_bucket(self, bucket_key, data_shapes, label_shapes=None): """Switches to a different bucket. This will change ``self.curr_module``. Parameters ---------- bucket_key : str (or any python object) The key of the target bucket. data_shapes : list of (str, tuple) Typically ``data_batch.provide_data``. label_shapes : list of (str, tuple) Typically ``data_batch.provide_label``. """ assert self.binded, 'call bind before switching bucket' if not bucket_key in self._buckets: symbol, data_names, label_names = self._call_sym_gen(bucket_key) module = Module(symbol, data_names, label_names, logger=self.logger, context=self._context, work_load_list=self._work_load_list, fixed_param_names=self._fixed_param_names, state_names=self._state_names, group2ctxs=self._group2ctxs, compression_params=self._compression_params) module.bind(data_shapes, label_shapes, self._curr_module.for_training, self._curr_module.inputs_need_grad, force_rebind=False, shared_module=self._buckets[self._default_bucket_key], grad_req=self._grad_req) if self._monitor is not None: module.install_monitor(self._monitor) self._buckets[bucket_key] = module self._curr_module = self._buckets[bucket_key] self._curr_bucket_key = bucket_key
Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Defaults to `'local'`. optimizer : str or Optimizer Defaults to `'sgd'` optimizer_params : dict Defaults to `(('learning_rate', 0.01),)`. The default value is not a dictionary, just to avoid pylint warning of dangerous default values. force_init : bool Defaults to ``False``, indicating whether we should force re-initializing the optimizer in the case an optimizer is already installed. def init_optimizer(self, kvstore='local', optimizer='sgd', optimizer_params=(('learning_rate', 0.01),), force_init=False): """Installs and initializes optimizers. Parameters ---------- kvstore : str or KVStore Defaults to `'local'`. optimizer : str or Optimizer Defaults to `'sgd'` optimizer_params : dict Defaults to `(('learning_rate', 0.01),)`. The default value is not a dictionary, just to avoid pylint warning of dangerous default values. force_init : bool Defaults to ``False``, indicating whether we should force re-initializing the optimizer in the case an optimizer is already installed. """ assert self.binded and self.params_initialized if self.optimizer_initialized and not force_init: self.logger.warning('optimizer already initialized, ignoring.') return self._curr_module.init_optimizer(kvstore, optimizer, optimizer_params, force_init=force_init) for mod in self._buckets.values(): if mod is not self._curr_module: mod.borrow_optimizer(self._curr_module) self.optimizer_initialized = True
Prepares the module for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_sparse` parameters based on the sparse_row_id_fn. Parameters ---------- data_batch : DataBatch The current batch of data for forward computation. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull. def prepare(self, data_batch, sparse_row_id_fn=None): '''Prepares the module for processing a data batch. Usually involves switching bucket and reshaping. For modules that contain `row_sparse` parameters in KVStore, it prepares the `row_sparse` parameters based on the sparse_row_id_fn. Parameters ---------- data_batch : DataBatch The current batch of data for forward computation. sparse_row_id_fn : A callback function The function takes `data_batch` as an input and returns a dict of str -> NDArray. The resulting dict is used for pulling row_sparse parameters from the kvstore, where the str key is the name of the param, and the value is the row id of the param to pull. ''' # perform bind if haven't done so assert self.binded and self.params_initialized bucket_key = data_batch.bucket_key original_bucket_key = self._curr_bucket_key data_shapes = data_batch.provide_data label_shapes = data_batch.provide_label self.switch_bucket(bucket_key, data_shapes, label_shapes) self._curr_module.prepare(data_batch, sparse_row_id_fn=sparse_row_id_fn) # switch back self.switch_bucket(original_bucket_key, None, None)
Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Defaults to ``None``, in which case `is_train` is take as ``self.for_training``. def forward(self, data_batch, is_train=None): """Forward computation. Parameters ---------- data_batch : DataBatch is_train : bool Defaults to ``None``, in which case `is_train` is take as ``self.for_training``. """ assert self.binded and self.params_initialized self.switch_bucket(data_batch.bucket_key, data_batch.provide_data, data_batch.provide_label) self._curr_module.forward(data_batch, is_train=is_train)
Backward computation. def backward(self, out_grads=None): """Backward computation.""" assert self.binded and self.params_initialized self._curr_module.backward(out_grads=out_grads)
Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters, this function does update the copy of parameters in KVStore, but doesn't broadcast the updated parameters to all devices / machines. Please call `prepare` to broadcast `row_sparse` parameters with the next batch of data. def update(self): """Updates parameters according to installed optimizer and the gradient computed in the previous forward-backward cycle. When KVStore is used to update parameters for multi-device or multi-machine training, a copy of the parameters are stored in KVStore. Note that for `row_sparse` parameters, this function does update the copy of parameters in KVStore, but doesn't broadcast the updated parameters to all devices / machines. Please call `prepare` to broadcast `row_sparse` parameters with the next batch of data. """ assert self.binded and self.params_initialized and self.optimizer_initialized self._params_dirty = True self._curr_module.update()
Gets outputs from a previous forward computation. Parameters ---------- merge_multi_context : bool Defaults to ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of numpy arrays or list of list of numpy arrays If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are numpy arrays. def get_outputs(self, merge_multi_context=True): """Gets outputs from a previous forward computation. Parameters ---------- merge_multi_context : bool Defaults to ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of numpy arrays or list of list of numpy arrays If `merge_multi_context` is ``True``, it is like ``[out1, out2]``. Otherwise, it is like ``[[out1_dev1, out1_dev2], [out2_dev1, out2_dev2]]``. All the output elements are numpy arrays. """ assert self.binded and self.params_initialized return self._curr_module.get_outputs(merge_multi_context=merge_multi_context)
Gets the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Defaults to ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArrays or list of list of NDArrays If `merge_multi_context` is ``True``, it is like ``[grad1, grad2]``. Otherwise, it is like ``[[grad1_dev1, grad1_dev2], [grad2_dev1, grad2_dev2]]``. All the output elements are `NDArray`. def get_input_grads(self, merge_multi_context=True): """Gets the gradients with respect to the inputs of the module. Parameters ---------- merge_multi_context : bool Defaults to ``True``. In the case when data-parallelism is used, the outputs will be collected from multiple devices. A ``True`` value indicate that we should merge the collected results so that they look like from a single executor. Returns ------- list of NDArrays or list of list of NDArrays If `merge_multi_context` is ``True``, it is like ``[grad1, grad2]``. Otherwise, it is like ``[[grad1_dev1, grad1_dev2], [grad2_dev1, grad2_dev2]]``. All the output elements are `NDArray`. """ assert self.binded and self.params_initialized and self.inputs_need_grad return self._curr_module.get_input_grads(merge_multi_context=merge_multi_context)
Evaluates and accumulates evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``. def update_metric(self, eval_metric, labels, pre_sliced=False): """Evaluates and accumulates evaluation metric on outputs of the last forward computation. Parameters ---------- eval_metric : EvalMetric labels : list of NDArray Typically ``data_batch.label``. """ assert self.binded and self.params_initialized self._curr_module.update_metric(eval_metric, labels, pre_sliced)
Installs monitor on all executors def install_monitor(self, mon): """Installs monitor on all executors """ assert self.binded self._monitor = mon for mod in self._buckets.values(): mod.install_monitor(mon)
Set status to recording/not recording. When recording, graph will be constructed for gradient computation. Parameters ---------- is_recording: bool Returns ------- previous state before this set. def set_recording(is_recording): #pylint: disable=redefined-outer-name """Set status to recording/not recording. When recording, graph will be constructed for gradient computation. Parameters ---------- is_recording: bool Returns ------- previous state before this set. """ prev = ctypes.c_int() check_call(_LIB.MXAutogradSetIsRecording( ctypes.c_int(is_recording), ctypes.byref(prev))) return bool(prev.value)
Set status to training/predicting. This affects ctx.is_train in operator running context. For example, Dropout will drop inputs randomly when train_mode=True while simply passing through if train_mode=False. Parameters ---------- train_mode: bool Returns ------- previous state before this set. def set_training(train_mode): #pylint: disable=redefined-outer-name """Set status to training/predicting. This affects ctx.is_train in operator running context. For example, Dropout will drop inputs randomly when train_mode=True while simply passing through if train_mode=False. Parameters ---------- train_mode: bool Returns ------- previous state before this set. """ prev = ctypes.c_int() check_call(_LIB.MXAutogradSetIsTraining( ctypes.c_int(train_mode), ctypes.byref(prev))) return bool(prev.value)