_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q26200
_decode_and_evaluate
train
def _decode_and_evaluate(decoder: checkpoint_decoder.CheckpointDecoder, checkpoint: int, output_name: str, queue: multiprocessing.Queue): """ Decodes and evaluates using given checkpoint_decoder
python
{ "resource": "" }
q26201
TrainingModel._generate_fixed_param_names
train
def _generate_fixed_param_names(self, param_names: List[str], strategy: str) -> List[str]: """ Generate a fixed parameter list given a list of all parameter names and a strategy. """ # Number of encoder/decoder layers in model. if isinstance(self.config.config_encoder, Em...
python
{ "resource": "" }
q26202
TrainingModel.get_gradients
train
def get_gradients(self) -> Dict[str, List[mx.nd.NDArray]]: """ Returns a mapping of parameters names to gradient arrays. Parameter names are prefixed with the device. """ # We may have None if
python
{ "resource": "" }
q26203
TrainingModel.get_global_gradient_norm
train
def get_global_gradient_norm(self) -> float: """ Returns global gradient norm. """ # average norm across executors: exec_norms = [global_norm([arr for arr in exe.grad_arrays if arr is not None]) for exe in self.executors]
python
{ "resource": "" }
q26204
TrainingModel.rescale_gradients
train
def rescale_gradients(self, scale: float): """ Rescales gradient arrays of executors by scale. """ for exe in self.executors: for arr in exe.grad_arrays:
python
{ "resource": "" }
q26205
TrainingModel.prepare_batch
train
def prepare_batch(self, batch: mx.io.DataBatch): """ Pre-fetches the
python
{ "resource": "" }
q26206
TrainingModel.evaluate
train
def evaluate(self, eval_iter: data_io.BaseParallelSampleIter, eval_metric: mx.metric.EvalMetric): """ Resets and recomputes evaluation metric on given data iterator. """ for eval_batch in eval_iter:
python
{ "resource": "" }
q26207
TrainingModel.optimizer
train
def optimizer(self) -> Union[mx.optimizer.Optimizer, SockeyeOptimizer]: """ Returns the optimizer of the underlying module. """
python
{ "resource": "" }
q26208
TrainingModel.initialize_optimizer
train
def initialize_optimizer(self, config: OptimizerConfig): """ Initializes the optimizer of the underlying module with an optimizer config. """ self.module.init_optimizer(kvstore=config.kvstore,
python
{ "resource": "" }
q26209
TrainingModel.initialize_parameters
train
def initialize_parameters(self, initializer: mx.init.Initializer, allow_missing_params: bool): """ Initializes the parameters of the underlying module. :param initializer: Parameter initializer. :param allow_missing_params: Whether to allow missing parameters. """ self.m...
python
{ "resource": "" }
q26210
TrainingModel.log_parameters
train
def log_parameters(self): """ Logs information about model parameters. """ arg_params, aux_params = self.module.get_params() total_parameters = 0 fixed_parameters = 0 learned_parameters = 0 info = [] # type: List[str] for name, array in sorted(arg...
python
{ "resource": "" }
q26211
TrainingModel.save_params_to_file
train
def save_params_to_file(self, fname: str): """ Synchronizes parameters across devices, saves the parameters to disk, and updates self.params and self.aux_params. :param fname: Filename to write parameters to. """ arg_params, aux_params = self.module.get_params()
python
{ "resource": "" }
q26212
TrainingModel.load_params_from_file
train
def load_params_from_file(self, fname: str, allow_missing_params: bool = False): """ Loads parameters from a file and sets the parameters of the underlying module and this model instance. :param fname: File name to load parameters from. :param allow_missing_params: If set, the given par...
python
{ "resource": "" }
q26213
TrainingModel.install_monitor
train
def install_monitor(self, monitor_pattern: str, monitor_stat_func_name: str): """ Installs an MXNet monitor onto the underlying module. :param monitor_pattern: Pattern string. :param monitor_stat_func_name: Name of monitor statistics function. """ self._monitor = mx.moni...
python
{ "resource": "" }
q26214
TrainState.save
train
def save(self, fname: str): """ Saves this training state to fname. """
python
{ "resource": "" }
q26215
EarlyStoppingTrainer._step
train
def _step(self, model: TrainingModel, batch: mx.io.DataBatch, checkpoint_interval: int, metric_train: mx.metric.EvalMetric, metric_loss: Optional[mx.metric.EvalMetric] = None): """ Performs an update to model given a batch and updates...
python
{ "resource": "" }
q26216
EarlyStoppingTrainer._update_metrics
train
def _update_metrics(self, metric_train: mx.metric.EvalMetric, metric_val: mx.metric.EvalMetric): """ Updates metrics for current checkpoint. If a process manager is given, also collects previous decoding results and spawns a new decoding process. ...
python
{ "resource": "" }
q26217
EarlyStoppingTrainer._cleanup
train
def _cleanup(self, lr_decay_opt_states_reset: str, process_manager: Optional['DecoderProcessManager'] = None, keep_training_state = False): """ Cleans parameter files, training state directory and waits for remaining decoding processes. """ utils.cleanup_params_files(sel...
python
{ "resource": "" }
q26218
EarlyStoppingTrainer._adjust_learning_rate
train
def _adjust_learning_rate(self, has_improved: bool, lr_decay_param_reset: bool, lr_decay_opt_states_reset: str): """ Adjusts the optimizer learning rate if required. """ if self.optimizer_config.lr_scheduler is not None: if issubclass(type(self.optimizer_config.lr_scheduler),...
python
{ "resource": "" }
q26219
EarlyStoppingTrainer._create_eval_metric
train
def _create_eval_metric(metric_name: str) -> mx.metric.EvalMetric: """ Creates an EvalMetric given a metric names. """ # output_names refers to the list of outputs this metric should use to update itself, e.g. the softmax output if metric_name == C.ACCURACY: return ut...
python
{ "resource": "" }
q26220
EarlyStoppingTrainer._create_eval_metric_composite
train
def _create_eval_metric_composite(metric_names: List[str]) -> mx.metric.CompositeEvalMetric: """ Creates a composite EvalMetric given a list of metric names. """
python
{ "resource": "" }
q26221
EarlyStoppingTrainer._update_best_params_link
train
def _update_best_params_link(self): """ Updates the params.best link to the latest best parameter file. """ best_params_path = self.best_params_fname actual_best_params_fname = C.PARAMS_NAME % self.state.best_checkpoint
python
{ "resource": "" }
q26222
EarlyStoppingTrainer._check_args
train
def _check_args(self, metrics: List[str], early_stopping_metric: str, lr_decay_opt_states_reset: str, lr_decay_param_reset: bool, cp_decoder: Optional[checkpoint_decoder.CheckpointDecoder] = None): """ He...
python
{ "resource": "" }
q26223
EarlyStoppingTrainer._save_params
train
def _save_params(self): """ Saves model parameters at current checkpoint and optionally cleans up older parameter files to save disk space. """ self.model.save_params_to_file(self.current_params_fname)
python
{ "resource": "" }
q26224
EarlyStoppingTrainer._save_training_state
train
def _save_training_state(self, train_iter: data_io.BaseParallelSampleIter): """ Saves current training state. """ # Create temporary directory for storing the state of the optimization process training_state_dirname = os.path.join(self.model.output_dir, C.TRAINING_STATE_TEMP_DIRN...
python
{ "resource": "" }
q26225
EarlyStoppingTrainer._load_training_state
train
def _load_training_state(self, train_iter: data_io.BaseParallelSampleIter): """ Loads the full training state from disk. :param train_iter: training data iterator. """ # (1) Parameters params_fname = os.path.join(self.training_state_dirname, C.TRAINING_STATE_PARAMS_NAME)...
python
{ "resource": "" }
q26226
DecoderProcessManager.start_decoder
train
def start_decoder(self, checkpoint: int): """ Starts a new CheckpointDecoder process and returns. No other process may exist. :param checkpoint: The checkpoint to decode. """ assert self.decoder_process is None output_name = os.path.join(self.output_folder, C.DECODE_OUT_...
python
{ "resource": "" }
q26227
DecoderProcessManager.collect_results
train
def collect_results(self) -> Optional[Tuple[int, Dict[str, float]]]: """ Returns the decoded checkpoint and the decoder metrics or None if the queue is empty. """ self.wait_to_finish() if self.decoder_metric_queue.empty(): if self._results_pending:
python
{ "resource": "" }
q26228
DecoderProcessManager.update_process_died_status
train
def update_process_died_status(self): """ Update the flag indicating whether any process exited and did not provide a result. """ # There is a result pending, the process is no longer alive, yet there is no result in the
python
{ "resource": "" }
q26229
average
train
def average(param_paths: Iterable[str]) -> Dict[str, mx.nd.NDArray]: """ Averages parameters from a list of .params file paths. :param param_paths: List of paths to parameter files. :return: Averaged parameter dictionary. """ all_arg_params = [] all_aux_params = [] for path in param_pat...
python
{ "resource": "" }
q26230
find_checkpoints
train
def find_checkpoints(model_path: str, size=4, strategy="best", metric: str = C.PERPLEXITY) -> List[str]: """ Finds N best points from .metrics file according to strategy. :param model_path: Path to model. :param size: Number of checkpoints to combine. :param strategy: Combination strategy. :par...
python
{ "resource": "" }
q26231
main
train
def main(): """ Commandline interface to average parameters. """ setup_main_logger(console=True, file_logging=False) params = argparse.ArgumentParser(description="Averages parameters from
python
{ "resource": "" }
q26232
get_lr_scheduler
train
def get_lr_scheduler(scheduler_type: str, updates_per_checkpoint: int, learning_rate_half_life: int, learning_rate_reduce_factor: float, learning_rate_reduce_num_not_improved: int, learning_rate_schedule: Optional[L...
python
{ "resource": "" }
q26233
LearningRateScheduler._warmup
train
def _warmup(self, num_updates): """ Returns linearly increasing fraction of base_lr. """ assert self.base_lr is not None if not self.warmup: return self.base_lr
python
{ "resource": "" }
q26234
LearningRateSchedulerFixedStep.parse_schedule_str
train
def parse_schedule_str(schedule_str: str) -> List[Tuple[float, int]]: """ Parse learning schedule string. :param schedule_str: String in form rate1:num_updates1[,rate2:num_updates2,...] :return: List of tuples (learning_rate, num_updates). """ schedule = list()
python
{ "resource": "" }
q26235
copy_mx_model_to
train
def copy_mx_model_to(model_path, model_epoch, output_folder): """ Copy mxnet models to new path. :param model_path: Model path without -symbol.json and -%04d.params :param model_epoch: Epoch of the pretrained model :param output_folder: Output folder :return: New folder where the files are move...
python
{ "resource": "" }
q26236
crop_resize_image
train
def crop_resize_image(image: np.ndarray, size) -> np.ndarray: """ Resize the input image. :param image: Original image which is a PIL object. :param size: Tuple of height and width to resize the image to. :return: Resized image which is a PIL object """ width, height = image.size if wi...
python
{ "resource": "" }
q26237
load_preprocess_images
train
def load_preprocess_images(image_paths: List[str], image_size: tuple) -> List[np.ndarray]: """ Load and pre-process the images specified with absolute paths. :param image_paths: List of images specified with paths. :param image_size: Tuple to resize the image to (Channels, Height, Width) :return: A...
python
{ "resource": "" }
q26238
load_features
train
def load_features(paths: List[str], expected_shape: Optional[tuple] = None) -> List[np.ndarray]: """ Load features specified with absolute paths. :param paths: List of files specified with paths. :param expected_shape: Optional expected shape.
python
{ "resource": "" }
q26239
save_features
train
def save_features(paths: List[str], datas: List[np.ndarray], compressed: bool = False) -> List: """ Save features specified with absolute paths. :param paths: List of files specified with paths.
python
{ "resource": "" }
q26240
zero_pad_features
train
def zero_pad_features(features: List[np.ndarray], target_shape: tuple) -> List[np.ndarray]: """ Zero pad to numpy array. :param features: List of numpy arrays. :param target_shape: Target shape of each numpy array in the list feat. Note: target_shape should be g...
python
{ "resource": "" }
q26241
get_initializer
train
def get_initializer(default_init_type: str, default_init_scale: float, default_init_xavier_rand_type: str, default_init_xavier_factor_type: str, embed_init_type: str, embed_init_sigma: float, rnn_init_type: str, extra_initializers: Optional[List[Tuple[str, mx.initializer.Initiali...
python
{ "resource": "" }
q26242
regular_folder
train
def regular_folder() -> Callable: """ Returns a method that can be used in argument parsing to check the argument is a directory. :return: A method that can be used as a type in argparse.
python
{ "resource": "" }
q26243
int_greater_or_equal
train
def int_greater_or_equal(threshold: int) -> Callable: """ Returns a method that can be used in argument parsing to check that the int argument is greater or equal to `threshold`. :param threshold: The threshold that we assume the cli argument value is greater or equal to. :return: A method that can be ...
python
{ "resource": "" }
q26244
float_greater_or_equal
train
def float_greater_or_equal(threshold: float) -> Callable: """ Returns a method that can be used in argument parsing to check that the float argument is greater or equal to `threshold`. :param threshold: The threshold that we assume the cli argument value is greater or equal to. :return: A method that c...
python
{ "resource": "" }
q26245
learning_schedule
train
def learning_schedule() -> Callable: """ Returns a method that can be used in argument parsing to check that the argument is a valid learning rate schedule string. :return: A method that can be used as a type in argparse. """ def parse(schedule_str): try: schedule = Learnin...
python
{ "resource": "" }
q26246
simple_dict
train
def simple_dict() -> Callable: """ A simple dictionary format that does not require spaces or quoting. Supported types: bool, int, float :return: A method that can be used as a type in argparse. """ def parse(dict_str: str): def _parse(value: str): if value == "True": ...
python
{ "resource": "" }
q26247
file_or_stdin
train
def file_or_stdin() -> Callable: """ Returns a file descriptor from stdin or opening a file from a given path. """ def parse(path): if path is None or path == "-":
python
{ "resource": "" }
q26248
_extract
train
def _extract(param_names: List[str], params: Dict[str, mx.nd.NDArray], ext_params: Dict[str, np.ndarray]) -> List[str]: """ Extract specific parameters from a given base. :param param_names: Names of parameters to be extracted. :param params: Mapping from parameter names to th...
python
{ "resource": "" }
q26249
extract
train
def extract(param_path: str, param_names: List[str], list_all: bool) -> Dict[str, np.ndarray]: """ Extract specific parameters given their names. :param param_path: Path to the parameter file. :param param_names: Names of parameters to be extracted. :param list_all: List nam...
python
{ "resource": "" }
q26250
main
train
def main(): """ Commandline interface to extract parameters. """ setup_main_logger(console=True, file_logging=False) params = argparse.ArgumentParser(description="Extract specific parameters.")
python
{ "resource": "" }
q26251
Decoder.register
train
def register(cls, config_type: Type[DecoderConfig], suffix: str): """ Registers decoder type for configuration. Suffix is appended to decoder prefix. :param config_type: Configuration type for decoder. :param suffix: String to append to decoder prefix. :return: Class decorator....
python
{ "resource": "" }
q26252
Decoder.get_decoder
train
def get_decoder(cls, config: DecoderConfig, prefix: str) -> 'Decoder': """ Creates decoder based on config type. :param config: Decoder config. :param prefix: Prefix to prepend for decoder. :return: Decoder instance. """ config_type = type(config) if con...
python
{ "resource": "" }
q26253
Decoder.decode_sequence
train
def decode_sequence(self, source_encoded: mx.sym.Symbol, source_encoded_lengths: mx.sym.Symbol, source_encoded_max_length: int, target_embed: mx.sym.Symbol, target_embed_lengths: mx.sym.Symbol, ...
python
{ "resource": "" }
q26254
Decoder.decode_step
train
def decode_step(self, step: int, target_embed_prev: mx.sym.Symbol, source_encoded_max_length: int, *states: mx.sym.Symbol) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, List[mx.sym.Symbol]]: """ Decodes a single time step given the...
python
{ "resource": "" }
q26255
Decoder.init_states
train
def init_states(self, source_encoded: mx.sym.Symbol, source_encoded_lengths: mx.sym.Symbol, source_encoded_max_length: int) -> List[mx.sym.Symbol]: """ Returns a list of symbolic states that represent the initial states of this decoder. ...
python
{ "resource": "" }
q26256
Decoder.state_shapes
train
def state_shapes(self, batch_size: int, target_max_length: int, source_encoded_max_length: int, source_encoded_depth: int) -> List[mx.io.DataDesc]: """ Returns a list of shape descriptions given batch size, encoded sourc...
python
{ "resource": "" }
q26257
JSONOutputHandler.handle
train
def handle(self, t_input: inference.TranslatorInput, t_output: inference.TranslatorOutput, t_walltime: float = 0.): """ Outputs a JSON object of the fields in the `TranslatorOutput` object. """
python
{ "resource": "" }
q26258
_add_graph_level
train
def _add_graph_level(graph, level, parent_ids, names, scores, normalized_scores, include_pad): """Adds a level to the passed graph""" for i, parent_id in enumerate(parent_ids): if not include_pad and names[i] == PAD_TOKEN: continue new_node = (level, i) p...
python
{ "resource": "" }
q26259
get_data_iters_and_vocabs
train
def get_data_iters_and_vocabs(args: argparse.Namespace, model_folder: Optional[str]) -> Tuple['data_io.BaseParallelSampleIter', List[vocab.Vocab], vocab.Vocab, model.ModelConfig]: """ Loads the data iterators and v...
python
{ "resource": "" }
q26260
get_image_cnn_encoder
train
def get_image_cnn_encoder(config: ImageLoadedCnnEncoderConfig) -> 'Encoder': """ Creates a image encoder. :param config: Configuration for image encoder. :return: Encoder instance. """ encoders = list() # type: List[Encoder] max_seq_len = config.encoded_seq_len if not config.no_global...
python
{ "resource": "" }
q26261
ImageLoadedCnnEncoder.get_initializers
train
def get_initializers(self) -> List[Tuple[str, mx.init.Initializer]]: """ Get the initializers of the network, considering the pretrained models. :return: List of tuples (string name, mxnet initializer) """ patterns_vals = [] # Load from args/auxs for k in self.ar...
python
{ "resource": "" }
q26262
ImageLoadedCnnEncoder.get_fixed_param_names
train
def get_fixed_param_names(self) -> List[str]: """ Get the fixed params of the network. :return: List of strings, names of the layers """
python
{ "resource": "" }
q26263
get_bucket
train
def get_bucket(seq_len: int, buckets: List[int]) -> Optional[int]: """ Given sequence length and a list of buckets, return corresponding bucket. :param seq_len: Sequence length. :param buckets: List of buckets. :return: Chosen
python
{ "resource": "" }
q26264
calculate_length_statistics
train
def calculate_length_statistics(source_iterables: Sequence[Iterable[Any]], target_iterable: Iterable[Any], max_seq_len_source: int, max_seq_len_target: int) -> 'LengthStatistics': """ Returns mean and standard deviat...
python
{ "resource": "" }
q26265
are_none
train
def are_none(sequences: Sequence[Sized]) -> bool: """ Returns True if all sequences are None. """ if not sequences:
python
{ "resource": "" }
q26266
are_token_parallel
train
def are_token_parallel(sequences: Sequence[Sized]) -> bool: """ Returns True if all sequences in the list have the same length. """ if not sequences or
python
{ "resource": "" }
q26267
get_num_shards
train
def get_num_shards(num_samples: int, samples_per_shard: int, min_num_shards: int) -> int: """ Returns the number of shards. :param num_samples: Number of training data samples. :param samples_per_shard: Samples per shard. :param min_num_shards:
python
{ "resource": "" }
q26268
get_scoring_data_iters
train
def get_scoring_data_iters(sources: List[str], target: str, source_vocabs: List[vocab.Vocab], target_vocab: vocab.Vocab, batch_size: int, batch_num_devices: int, ...
python
{ "resource": "" }
q26269
describe_data_and_buckets
train
def describe_data_and_buckets(data_statistics: DataStatistics, bucket_batch_sizes: List[BucketBatchSize]): """ Describes statistics across buckets """ check_condition(len(bucket_batch_sizes) == len(data_statistics.buckets), "Number of bucket batch sizes (%d) does not match number of ...
python
{ "resource": "" }
q26270
read_content
train
def read_content(path: str, limit: Optional[int] = None) -> Iterator[List[str]]: """ Returns a list of tokens for each line in path up to a limit. :param path: Path to files containing sentences. :param limit: How many lines to read from path. :return: Iterator over lists of words. """ with...
python
{ "resource": "" }
q26271
tokens2ids
train
def tokens2ids(tokens: Iterable[str], vocab: Dict[str, int]) -> List[int]: """ Returns sequence of integer ids given a sequence of tokens and vocab. :param tokens: List of string tokens. :param
python
{ "resource": "" }
q26272
strids2ids
train
def strids2ids(tokens: Iterable[str]) -> List[int]: """ Returns sequence of integer ids given a
python
{ "resource": "" }
q26273
ids2strids
train
def ids2strids(ids: Iterable[int]) -> str: """ Returns a string representation of a sequence of
python
{ "resource": "" }
q26274
ids2tokens
train
def ids2tokens(token_ids: Iterable[int], vocab_inv: Dict[int, str], exclude_set: Set[int]) -> Iterator[str]: """ Transforms a list of token IDs into a list of words, excluding any IDs in `exclude_set`. :param token_ids: The list of token IDs. :param vocab_inv: The inverse ...
python
{ "resource": "" }
q26275
create_sequence_readers
train
def create_sequence_readers(sources: List[str], target: str, vocab_sources: List[vocab.Vocab], vocab_target: vocab.Vocab) -> Tuple[List[SequenceReader], SequenceReader]: """ Create source readers with EOS and target readers with BOS. :param sources: T...
python
{ "resource": "" }
q26276
get_default_bucket_key
train
def get_default_bucket_key(buckets: List[Tuple[int, int]]) -> Tuple[int, int]: """ Returns the default bucket from a list of buckets, i.e. the largest bucket. :param buckets: List of
python
{ "resource": "" }
q26277
get_permutations
train
def get_permutations(bucket_counts: List[int]) -> Tuple[List[mx.nd.NDArray], List[mx.nd.NDArray]]: """ Returns the indices of a random permutation for each bucket and the corresponding inverse permutations that can restore the original order of the data if applied to the permuted data. :param bucket_co...
python
{ "resource": "" }
q26278
get_batch_indices
train
def get_batch_indices(data: ParallelDataSet, bucket_batch_sizes: List[BucketBatchSize]) -> List[Tuple[int, int]]: """ Returns a list of index tuples that index into the bucket and the start index inside a bucket given the batch size for a bucket. These indices are valid for the given d...
python
{ "resource": "" }
q26279
ParallelDataSet.save
train
def save(self, fname: str): """ Saves the dataset to a binary .npy file. """
python
{ "resource": "" }
q26280
ParallelDataSet.load
train
def load(fname: str) -> 'ParallelDataSet': """ Loads a dataset from a binary .npy file. """ data = mx.nd.load(fname) n = len(data) // 3 source = data[:n] target = data[n:2 *
python
{ "resource": "" }
q26281
ParallelDataSet.fill_up
train
def fill_up(self, bucket_batch_sizes: List[BucketBatchSize], seed: int = 42) -> 'ParallelDataSet': """ Returns a new dataset with buckets filled up. :param bucket_batch_sizes: Bucket batch sizes. :param seed: The random seed used for sampling sentences to...
python
{ "resource": "" }
q26282
BatchedRawParallelSampleIter.iter_next
train
def iter_next(self) -> bool: """ True if the iterator can return another batch. """ # Read batch_size lines from the source stream sources_sentences = [[] for x in self.sources_sentences] # type: List[List[str]] target_sentences = [] # type: List[str] num_read ...
python
{ "resource": "" }
q26283
BatchedRawParallelSampleIter.next
train
def next(self) -> mx.io.DataBatch: """ Returns the next batch. """ if
python
{ "resource": "" }
q26284
ParallelSampleIter.reset
train
def reset(self): """ Resets and reshuffles the data. """ self.curr_batch_index = 0 if self.permute: # shuffle batch start indices random.shuffle(self.batch_indices) # restore the data permutation self.data = self.data.permute(self....
python
{ "resource": "" }
q26285
ParallelSampleIter.save_state
train
def save_state(self, fname: str): """ Saves the current state of iterator to a file, so that iteration can be continued. Note that the data is not saved, i.e. the iterator must be initialized with the same parameters as in the first call.
python
{ "resource": "" }
q26286
ParallelSampleIter.load_state
train
def load_state(self, fname: str): """ Loads the state of the iterator from a file. :param fname: File name to load the information from. """ # restore order self.data = self.data.permute(self.inverse_data_permutations) with open(fname, "rb") as fp: ...
python
{ "resource": "" }
q26287
create_checkpoint_decoder
train
def create_checkpoint_decoder(args: argparse.Namespace, exit_stack: ExitStack, train_context: List[mx.Context]) -> Optional[checkpoint_decoder.CheckpointDecoder]: """ Returns a checkpoint decoder or None. :param args: Arguments as returned by argp...
python
{ "resource": "" }
q26288
get_preinit_encoders
train
def get_preinit_encoders(encoders: List[encoder.Encoder]) -> List[Tuple[str, mx.init.Initializer]]: """ Get initializers from encoders. Some encoders might be initialized from pretrained models. :param encoders: List of encoders :return: The list of initializers """ init = [] # type: List[Tupl...
python
{ "resource": "" }
q26289
get_recurrent_encoder
train
def get_recurrent_encoder(config: RecurrentEncoderConfig, prefix: str) -> 'Encoder': """ Returns an encoder stack with a bi-directional RNN, and a variable number of uni-directional forward RNNs. :param config: Configuration for recurrent encoder. :param prefix: Prefix for variable names. :return: ...
python
{ "resource": "" }
q26290
get_convolutional_encoder
train
def get_convolutional_encoder(config: ConvolutionalEncoderConfig, prefix: str) -> 'Encoder': """ Creates a convolutional encoder. :param config: Configuration for convolutional encoder. :param prefix: Prefix for variable names. :return: Encoder instance. """ encoder_seq = EncoderSequence([]...
python
{ "resource": "" }
q26291
get_transformer_encoder
train
def get_transformer_encoder(config: transformer.TransformerConfig, prefix: str) -> 'Encoder': """ Returns a Transformer encoder, consisting of an embedding layer with positional encodings and a TransformerEncoder instance. :param config: Configuration for transformer encoder. :param prefix: Prefix ...
python
{ "resource": "" }
q26292
EncoderSequence.append
train
def append(self, cls, infer_hidden: bool = False, **kwargs) -> Encoder: """ Extends sequence with new Encoder. 'dtype' gets passed into Encoder instance if not present in parameters and supported by specific Encoder type. :param cls: Encoder type. :param infer_hidden: If number ...
python
{ "resource": "" }
q26293
BiDirectionalRNNEncoder._encode
train
def _encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> mx.sym.Symbol: """ Bidirectionally encodes time-major data. """ # (seq_len, batch_size, num_embed) data_reverse = mx.sym.SequenceReverse(data=data, sequence_length=data_length, ...
python
{ "resource": "" }
q26294
BiDirectionalRNNEncoder.get_rnn_cells
train
def get_rnn_cells(self) -> List[mx.rnn.BaseRNNCell]: """ Returns a list of RNNCells used by this encoder. """
python
{ "resource": "" }
q26295
ConvolutionalEncoder.encode
train
def encode(self, data: mx.sym.Symbol, data_length: mx.sym.Symbol, seq_len: int) -> Tuple[mx.sym.Symbol, mx.sym.Symbol, int]: """ Encodes data with a stack of Convolution+GLU blocks given sequence lengths of individual examples and maximum sequence len...
python
{ "resource": "" }
q26296
_instantiate
train
def _instantiate(cls, params): """ Helper to instantiate Attention classes from parameters. Warns in log if parameter is not supported by class constructor. :param cls: Attention class. :param params: configuration parameters. :return: instance of `cls` type. """ sig_params = inspect.si...
python
{ "resource": "" }
q26297
get_attention
train
def get_attention(config: AttentionConfig, max_seq_len: int, prefix: str = C.ATTENTION_PREFIX) -> 'Attention': """ Returns an Attention instance based on attention_type. :param config: Attention configuration. :param max_seq_len: Maximum length
python
{ "resource": "" }
q26298
get_context_and_attention_probs
train
def get_context_and_attention_probs(values: mx.sym.Symbol, length: mx.sym.Symbol, logits: mx.sym.Symbol, dtype: str) -> Tuple[mx.sym.Symbol, mx.sym.Symbol]: """ Returns context vector and attention probab...
python
{ "resource": "" }
q26299
Attention.get_initial_state
train
def get_initial_state(self, source_length: mx.sym.Symbol, source_seq_len: int) -> AttentionState: """ Returns initial attention state. Dynamic source encoding is initialized with zeros. :param source_length: Source length. Shape: (batch_size,). :param source_seq_len: Maximum length of s...
python
{ "resource": "" }