project_name
stringlengths
6
104
file_name
stringlengths
4
89
full_name
stringlengths
1
102
func_name
stringlengths
1
85
docstring
stringlengths
13
836
docstring_tokens
listlengths
4
122
code
stringlengths
23
39.7k
code_tokens
stringlengths
29
44.6k
url
int64
3
986k
asyml/texar-pytorch
attention_mechanism.py
AttentionMechanism.query_layer
query_layer
The layer used to transform the attention query.
[ "The", "layer", "used", "to", "transform", "the", "attention", "query." ]
def query_layer(self) -> Optional[nn.Module]: return self._query_layer
['def', 'query_layer(self)', '->', 'Optional[nn.Module]:', 'return', 'self._query_layer']
924,964
asyml/texar-pytorch
attention_mechanism.py
AttentionMechanism.encoder_output_size
encoder_output_size
Dimension of the encoder output.
[ "Dimension", "of", "the", "encoder", "output." ]
def encoder_output_size(self) -> int: return self._encoder_output_size
['def', 'encoder_output_size(self)', '->', 'int:', 'return', 'self._encoder_output_size']
924,966
asyml/texar-pytorch
attention_mechanism_utils.py
maybe_mask_score
maybe_mask_score
Mask the attention score based on the masks.
[ "Mask", "the", "attention", "score", "based", "on", "the", "masks." ]
def maybe_mask_score(score: torch.Tensor, score_mask_value: torch.Tensor, memory_sequence_length: Optional[torch.LongTensor]) -> torch.Tensor: if memory_sequence_length is None: return score for memory_sequence_length_value in memory_sequence_length: if memory_sequence_length_value <= 0: ...
['def', 'maybe_mask_score(score:', 'torch.Tensor,', 'score_mask_value:', 'torch.Tensor,', 'memory_sequence_length:', 'Optional[torch.LongTensor])', '->', 'torch.Tensor:', 'if', 'memory_sequence_length', 'is', 'None:', 'return', 'score', 'for', 'memory_sequence_length_value', 'in', 'memory_sequence_length:', 'if', 'memo...
924,972
asyml/texar-pytorch
cell_wrappers.py
RNNCellBase.input_size
input_size
The number of expected features in the input.
[ "The", "number", "of", "expected", "features", "in", "the", "input." ]
def input_size(self) -> int: return self._cell.input_size
['def', 'input_size(self)', '->', 'int:', 'return', 'self._cell.input_size']
924,977
asyml/texar-pytorch
cell_wrappers.py
LSTMCell.zero_state
zero_state
Returns the zero state for LSTMs as (h, c).
[ "Returns", "the", "zero", "state", "for", "LSTMs", "as", "(h,", "c)." ]
def zero_state(self, batch_size: int) -> LSTMState: state = self._param.new_zeros(batch_size, self.hidden_size, requires_grad=False) return (state, state)
['def', 'zero_state(self,', 'batch_size:', 'int)', '->', 'LSTMState:', 'state', '=', 'self._param.new_zeros(batch_size,', 'self.hidden_size,', 'requires_grad=False)', 'return', '(state,', 'state)']
924,982
asyml/texar-pytorch
layers.py
MergeLayer.forward
forward
Feed input to every containing layer and merge the outputs.
[ "Feed", "input", "to", "every", "containing", "layer", "and", "merge", "the", "outputs." ]
def forward(self, input: torch.Tensor) -> torch.Tensor: layer_outputs: List[torch.Tensor] if self._layers is None: layer_outputs = input if not isinstance(layer_outputs, (list, tuple)): layer_outputs = [layer_outputs] else: layer_outputs = [] for layer in self._la...
['def', 'forward(self,', 'input:', 'torch.Tensor)', '->', 'torch.Tensor:', 'layer_outputs:', 'List[torch.Tensor]', 'if', 'self._layers', 'is', 'None:', 'layer_outputs', '=', 'input', 'if', 'not', 'isinstance(layer_outputs,', '(list,', 'tuple)):', 'layer_outputs', '=', '[layer_outputs]', 'else:', 'layer_outputs', '=', '...
924,996
asyml/texar-pytorch
optimization.py
get_scheduler
get_scheduler
Creates a scheduler instance.
[ "Creates", "a", "scheduler", "instance." ]
def get_scheduler(optimizer: Optimizer, hparams: Optional[Union[HParams, Dict[str, Any]]]=None) -> Optional[_LRScheduler]: if hparams is None or isinstance(hparams, dict): hparams = HParams(hparams, default_optimization_hparams()) hparams_scheduler = hparams['learning_rate_decay'] scheduler_type = h...
['def', 'get_scheduler(optimizer:', 'Optimizer,', 'hparams:', 'Optional[Union[HParams,', 'Dict[str,', 'Any]]]=None)', '->', 'Optional[_LRScheduler]:', 'if', 'hparams', 'is', 'None', 'or', 'isinstance(hparams,', 'dict):', 'hparams', '=', 'HParams(hparams,', 'default_optimization_hparams())', 'hparams_scheduler', '=', "h...
924,999
asyml/texar-pytorch
optimization.py
get_grad_clip_fn
get_grad_clip_fn
Create a gradient clipping function.
[ "Create", "a", "gradient", "clipping", "function." ]
def get_grad_clip_fn(hparams: Optional[Union[HParams, Dict[str, Any]]]=None) -> Optional[Callable[[torch.Tensor], Optional[torch.Tensor]]]: if hparams is None or isinstance(hparams, dict): hparams = HParams(hparams, default_optimization_hparams()) hparams_grad_clip = hparams['gradient_clip'] grad_cl...
['def', 'get_grad_clip_fn(hparams:', 'Optional[Union[HParams,', 'Dict[str,', 'Any]]]=None)', '->', 'Optional[Callable[[torch.Tensor],', 'Optional[torch.Tensor]]]:', 'if', 'hparams', 'is', 'None', 'or', 'isinstance(hparams,', 'dict):', 'hparams', '=', 'HParams(hparams,', 'default_optimization_hparams())', 'hparams_grad_...
925,000
asyml/texar-pytorch
regularizers.py
l1
l1
Construct an L1 regularizer.
[ "Construct", "an", "L1", "regularizer." ]
def l1(l: Union[int, float]=0.01) -> Regularizer: return L1L2(l1=l)
['def', 'l1(l:', 'Union[int,', 'float]=0.01)', '->', 'Regularizer:', 'return', 'L1L2(l1=l)']
925,003
asyml/texar-pytorch
regularizers.py
l1_l2
l1_l2
Construct a regularizer with both L1 and L2 components.
[ "Construct", "a", "regularizer", "with", "both", "L1", "and", "L2", "components." ]
def l1_l2(l1: Union[int, float]=0.01, l2: Union[int, float]=0.01) -> Regularizer: return L1L2(l1=l1, l2=l2)
['def', 'l1_l2(l1:', 'Union[int,', 'float]=0.01,', 'l2:', 'Union[int,', 'float]=0.01)', '->', 'Regularizer:', 'return', 'L1L2(l1=l1,', 'l2=l2)']
925,005
asyml/texar-pytorch
regularizers.py
Regularizer.get_config
get_config
Return a Dict with configurations for the current regularizer instance.
[ "Return", "a", "Dict", "with", "configurations", "for", "the", "current", "regularizer", "instance." ]
def get_config(self) -> Dict[str, float]: raise NotImplementedError
['def', 'get_config(self)', '->', 'Dict[str,', 'float]:', 'raise', 'NotImplementedError']
925,007
asyml/texar-pytorch
vocabulary.py
Vocab.id_to_token_map_py
id_to_token_map_py
The dictionary instance that maps from token index to the string form.
[ "The", "dictionary", "instance", "that", "maps", "from", "token", "index", "to", "the", "string", "form." ]
def id_to_token_map_py(self) -> Dict[int, str]: return self._id_to_token_map_py
['def', 'id_to_token_map_py(self)', '->', 'Dict[int,', 'str]:', 'return', 'self._id_to_token_map_py']
925,021
asyml/texar-pytorch
vocabulary.py
Vocab.token_to_id_map_py
token_to_id_map_py
The dictionary instance that maps from token string to the index.
[ "The", "dictionary", "instance", "that", "maps", "from", "token", "string", "to", "the", "index." ]
def token_to_id_map_py(self) -> Dict[str, int]: return self._token_to_id_map_py
['def', 'token_to_id_map_py(self)', '->', 'Dict[str,', 'int]:', 'return', 'self._token_to_id_map_py']
925,022
asyml/texar-pytorch
dataset_utils.py
padded_batch
padded_batch
Pad a batch of integer lists (or numpy arrays) to the same length, and stack them together.
[ "Pad", "a", "batch", "of", "integer", "lists", "(or", "numpy", "arrays)", "to", "the", "same", "length,", "and", "stack", "them", "together." ]
def padded_batch(examples: Union[List[np.ndarray], List[List[int]]], pad_length: Optional[int]=None, pad_value: int=0) -> Tuple[np.ndarray, List[int]]: lengths = [len(sent) for sent in examples] pad_length = pad_length or max(lengths) padded = np.full((len(examples), pad_length), pad_value, dtype=np.int64) ...
['def', 'padded_batch(examples:', 'Union[List[np.ndarray],', 'List[List[int]]],', 'pad_length:', 'Optional[int]=None,', 'pad_value:', 'int=0)', '->', 'Tuple[np.ndarray,', 'List[int]]:', 'lengths', '=', '[len(sent)', 'for', 'sent', 'in', 'examples]', 'pad_length', '=', 'pad_length', 'or', 'max(lengths)', 'padded', '=', ...
925,032
asyml/texar-pytorch
data_iterators.py
TrainTestDataIterator.switch_to_train_data
switch_to_train_data
Switch to training data.
[ "Switch", "to", "training", "data." ]
def switch_to_train_data(self) -> None: if self._train_name not in self._datasets: raise ValueError('Training data not provided.') self.switch_to_dataset(self._train_name)
['def', 'switch_to_train_data(self)', '->', 'None:', 'if', 'self._train_name', 'not', 'in', 'self._datasets:', 'raise', "ValueError('Training", 'data', 'not', "provided.')", 'self.switch_to_dataset(self._train_name)']
925,041
asyml/texar-pytorch
data_iterators.py
TrainTestDataIterator.switch_to_val_data
switch_to_val_data
Switch to validation data.
[ "Switch", "to", "validation", "data." ]
def switch_to_val_data(self) -> None: if self._val_name not in self._datasets: raise ValueError('Validation data not provided.') self.switch_to_dataset(self._val_name)
['def', 'switch_to_val_data(self)', '->', 'None:', 'if', 'self._val_name', 'not', 'in', 'self._datasets:', 'raise', "ValueError('Validation", 'data', 'not', "provided.')", 'self.switch_to_dataset(self._val_name)']
925,042
asyml/texar-pytorch
data_iterators.py
TrainTestDataIterator.switch_to_test_data
switch_to_test_data
Switch to test data.
[ "Switch", "to", "test", "data." ]
def switch_to_test_data(self) -> None: if self._test_name not in self._datasets: raise ValueError('Test data not provided.') self.switch_to_dataset(self._test_name)
['def', 'switch_to_test_data(self)', '->', 'None:', 'if', 'self._test_name', 'not', 'in', 'self._datasets:', 'raise', "ValueError('Test", 'data', 'not', "provided.')", 'self.switch_to_dataset(self._test_name)']
925,043
asyml/texar-pytorch
data_iterators.py
TrainTestDataIterator.get_train_iterator
get_train_iterator
Obtain an iterator over training data.
[ "Obtain", "an", "iterator", "over", "training", "data." ]
def get_train_iterator(self) -> Iterable[Batch]: if self._train_name not in self._datasets: raise ValueError('Training data not provided.') return self.get_iterator(self._train_name)
['def', 'get_train_iterator(self)', '->', 'Iterable[Batch]:', 'if', 'self._train_name', 'not', 'in', 'self._datasets:', 'raise', "ValueError('Training", 'data', 'not', "provided.')", 'return', 'self.get_iterator(self._train_name)']
925,044
asyml/texar-pytorch
data_iterators.py
TrainTestDataIterator.get_test_iterator
get_test_iterator
Obtain an iterator over test data.
[ "Obtain", "an", "iterator", "over", "test", "data." ]
def get_test_iterator(self) -> Iterable[Batch]: if self._test_name not in self._datasets: raise ValueError('Test data not provided.') return self.get_iterator(self._test_name)
['def', 'get_test_iterator(self)', '->', 'Iterable[Batch]:', 'if', 'self._test_name', 'not', 'in', 'self._datasets:', 'raise', "ValueError('Test", 'data', 'not', "provided.')", 'return', 'self.get_iterator(self._test_name)']
925,046
asyml/texar-pytorch
multi_aligned_data.py
MultiAlignedData.make_vocab
make_vocab
Makes a list of vocabs based on the hyperparameters.
[ "Makes", "a", "list", "of", "vocabs", "based", "on", "the", "hyperparameters." ]
def make_vocab(hparams: List[HParams]) -> List[Optional[Vocab]]: vocabs: List[Optional[Vocab]] = [] for (i, hparams_i) in enumerate(hparams): if not _is_text_data(hparams_i.data_type): vocabs.append(None) continue proc_share = hparams_i.processing_share_with if pr...
['def', 'make_vocab(hparams:', 'List[HParams])', '->', 'List[Optional[Vocab]]:', 'vocabs:', 'List[Optional[Vocab]]', '=', '[]', 'for', '(i,', 'hparams_i)', 'in', 'enumerate(hparams):', 'if', 'not', '_is_text_data(hparams_i.data_type):', 'vocabs.append(None)', 'continue', 'proc_share', '=', 'hparams_i.processing_share_w...
925,054
asyml/texar-pytorch
tokenizer_base.py
TokenizerBase.encode_text
encode_text
Adds special tokens to a sequence or sequence pair and computes other information such as segment ids, input mask, and sequence length for specific tasks.
[ "Adds", "special", "tokens", "to", "a", "sequence", "or", "sequence", "pair", "and", "computes", "other", "information", "such", "as", "segment", "ids,", "input", "mask,", "and", "sequence", "length", "for", "specific", "tasks." ]
def encode_text(self, text_a: str, text_b: Optional[str]=None, max_seq_length: Optional[int]=None): raise NotImplementedError
['def', 'encode_text(self,', 'text_a:', 'str,', 'text_b:', 'Optional[str]=None,', 'max_seq_length:', 'Optional[int]=None):', 'raise', 'NotImplementedError']
925,111
asyml/texar-pytorch
mle_losses.py
binary_sigmoid_cross_entropy_with_clas
binary_sigmoid_cross_entropy_with_clas
Computes sigmoid cross entropy of binary classifier.
[ "Computes", "sigmoid", "cross", "entropy", "of", "binary", "classifier." ]
def binary_sigmoid_cross_entropy_with_clas(clas_fn: Callable[[torch.Tensor], MaybeTuple[torch.Tensor]], pos_inputs: Optional[torch.Tensor]=None, neg_inputs: Optional[torch.Tensor]=None, average_across_batch: bool=True, average_across_classes: bool=True, sum_over_batch: bool=False, sum_over_classes: bool=False, return_p...
['def', 'binary_sigmoid_cross_entropy_with_clas(clas_fn:', 'Callable[[torch.Tensor],', 'MaybeTuple[torch.Tensor]],', 'pos_inputs:', 'Optional[torch.Tensor]=None,', 'neg_inputs:', 'Optional[torch.Tensor]=None,', 'average_across_batch:', 'bool=True,', 'average_across_classes:', 'bool=True,', 'sum_over_batch:', 'bool=Fals...
925,139
asyml/texar-pytorch
xlnet_classifier.py
XLNetClassifier.forward
forward
Feeds the inputs through the network and makes classification.
[ "Feeds", "the", "inputs", "through", "the", "network", "and", "makes", "classification." ]
def forward(self, inputs: Union[torch.Tensor, torch.LongTensor], segment_ids: Optional[torch.LongTensor]=None, input_mask: Optional[torch.Tensor]=None) -> Tuple[torch.Tensor, torch.LongTensor]: (output, _) = self._encoder(inputs=inputs, segment_ids=segment_ids, input_mask=input_mask) strategy = self._hparams.cl...
['def', 'forward(self,', 'inputs:', 'Union[torch.Tensor,', 'torch.LongTensor],', 'segment_ids:', 'Optional[torch.LongTensor]=None,', 'input_mask:', 'Optional[torch.Tensor]=None)', '->', 'Tuple[torch.Tensor,', 'torch.LongTensor]:', '(output,', '_)', '=', 'self._encoder(inputs=inputs,', 'segment_ids=segment_ids,', 'input...
925,160
asyml/texar-pytorch
connectors.py
ConstantConnector.forward
forward
Creates output tensor(s) that has the given value.
[ "Creates", "output", "tensor(s)", "that", "has", "the", "given", "value." ]
def forward(self, batch_size: Union[int, torch.Tensor]) -> Any: def full_tensor(x): if isinstance(x, torch.Size): return torch.full((batch_size,) + x, self.value) else: return torch.full((batch_size, x), self.value) output = utils.map_structure(full_tensor, self._output_...
['def', 'forward(self,', 'batch_size:', 'Union[int,', 'torch.Tensor])', '->', 'Any:', 'def', 'full_tensor(x):', 'if', 'isinstance(x,', 'torch.Size):', 'return', 'torch.full((batch_size,)', '+', 'x,', 'self.value)', 'else:', 'return', 'torch.full((batch_size,', 'x),', 'self.value)', 'output', '=', 'utils.map_structure(f...
925,163
asyml/texar-pytorch
decoder_base.py
DecoderBase.embed_tokens
embed_tokens
Convert tokens along with positions to embeddings.
[ "Convert", "tokens", "along", "with", "positions", "to", "embeddings." ]
def embed_tokens(self, tokens: torch.LongTensor, positions: torch.LongTensor) -> torch.Tensor: if self._token_embedder is not None: return self._token_embedder(tokens) assert self._token_pos_embedder is not None return self._token_pos_embedder(tokens, positions)
['def', 'embed_tokens(self,', 'tokens:', 'torch.LongTensor,', 'positions:', 'torch.LongTensor)', '->', 'torch.Tensor:', 'if', 'self._token_embedder', 'is', 'not', 'None:', 'return', 'self._token_embedder(tokens)', 'assert', 'self._token_pos_embedder', 'is', 'not', 'None', 'return', 'self._token_pos_embedder(tokens,', '...
925,173
asyml/texar-pytorch
decoder_base.py
DecoderBase.set_default_train_helper
set_default_train_helper
Set the default helper used in training mode.
[ "Set", "the", "default", "helper", "used", "in", "training", "mode." ]
def set_default_train_helper(self, helper: Helper): self._train_helper = helper
['def', 'set_default_train_helper(self,', 'helper:', 'Helper):', 'self._train_helper', '=', 'helper']
925,174
asyml/texar-pytorch
decoder_base.py
DecoderBase.set_default_infer_helper
set_default_infer_helper
Set the default helper used in eval (inference) mode.
[ "Set", "the", "default", "helper", "used", "in", "eval", "(inference)", "mode." ]
def set_default_infer_helper(self, helper: Helper): self._infer_helper = helper
['def', 'set_default_infer_helper(self,', 'helper:', 'Helper):', 'self._infer_helper', '=', 'helper']
925,175
asyml/texar-pytorch
decoder_helpers.py
Helper.initialize
initialize
Initialize the current batch.
[ "Initialize", "the", "current", "batch." ]
def initialize(self, embedding_fn: EmbeddingFn, inputs: Optional[torch.Tensor], sequence_length: Optional[torch.LongTensor]) -> HelperInitTuple: raise NotImplementedError
['def', 'initialize(self,', 'embedding_fn:', 'EmbeddingFn,', 'inputs:', 'Optional[torch.Tensor],', 'sequence_length:', 'Optional[torch.LongTensor])', '->', 'HelperInitTuple:', 'raise', 'NotImplementedError']
925,184
asyml/texar-pytorch
decoder_helpers.py
Helper.next_inputs
next_inputs
Returns ``(finished, next_inputs, next_state)``.
[ "Returns", "``(finished,", "next_inputs,", "next_state)``." ]
def next_inputs(self, embedding_fn: EmbeddingFn, time: int, outputs: torch.Tensor, sample_ids: IDType) -> NextInputTuple: raise NotImplementedError
['def', 'next_inputs(self,', 'embedding_fn:', 'EmbeddingFn,', 'time:', 'int,', 'outputs:', 'torch.Tensor,', 'sample_ids:', 'IDType)', '->', 'NextInputTuple:', 'raise', 'NotImplementedError']
925,185
asyml/texar-pytorch
embedders.py
WordEmbedder.embedding
embedding
The embedding tensor, of shape ``[vocab_size] + dim``.
[ "The", "embedding", "tensor,", "of", "shape", "``[vocab_size]", "+", "dim``." ]
def embedding(self) -> torch.Tensor: return self._embedding
['def', 'embedding(self)', '->', 'torch.Tensor:', 'return', 'self._embedding']
925,202
asyml/texar-pytorch
embedder_base.py
EmbeddingDropout.forward
forward
Apply dropout on the tensor.
[ "Apply", "dropout", "on", "the", "tensor." ]
def forward(self, input_tensor: torch.Tensor, noise_shape: Optional[torch.Size]=None) -> torch.Tensor: if not self.training or self._rate == 0.0: return input_tensor if noise_shape is None: noise_shape = input_tensor.size() keep_rate = 1 - self._rate mask = input_tensor.new_full(noise_sh...
['def', 'forward(self,', 'input_tensor:', 'torch.Tensor,', 'noise_shape:', 'Optional[torch.Size]=None)', '->', 'torch.Tensor:', 'if', 'not', 'self.training', 'or', 'self._rate', '==', '0.0:', 'return', 'input_tensor', 'if', 'noise_shape', 'is', 'None:', 'noise_shape', '=', 'input_tensor.size()', 'keep_rate', '=', '1', ...
925,207
asyml/texar-pytorch
bert_encoder.py
BERTEncoder.output_size
output_size
The feature size of :meth:`forward` output :attr:`pooled_output`.
[ "The", "feature", "size", "of", ":meth:`forward`", "output", ":attr:`pooled_output`." ]
def output_size(self): return self._hparams.hidden_size
['def', 'output_size(self):', 'return', 'self._hparams.hidden_size']
925,218
asyml/texar-pytorch
gpt2_encoder.py
GPT2Encoder.output_size
output_size
The feature size of :meth:`forward` output.
[ "The", "feature", "size", "of", ":meth:`forward`", "output." ]
def output_size(self): return self._hparams.encoder.dim
['def', 'output_size(self):', 'return', 'self._hparams.encoder.dim']
925,221
asyml/texar-pytorch
t5_encoder.py
T5Encoder.initialize_blocks
initialize_blocks
Helper function to initialize blocks.
[ "Helper", "function", "to", "initialize", "blocks." ]
def initialize_blocks(self): for i in range(self._hparams.num_blocks): mh_attn = MultiheadRPRAttention(self._input_size, self._hparams.multihead_attention, stores_relative_position=bool(i == 0)) self.self_attns.append(mh_attn) self.self_attn_layer_norm.append(T5LayerNorm(self._input_size, ep...
['def', 'initialize_blocks(self):', 'for', 'i', 'in', 'range(self._hparams.num_blocks):', 'mh_attn', '=', 'MultiheadRPRAttention(self._input_size,', 'self._hparams.multihead_attention,', 'stores_relative_position=bool(i', '==', '0))', 'self.self_attns.append(mh_attn)', 'self.self_attn_layer_norm.append(T5LayerNorm(self...
925,235
asyml/texar-pytorch
t5_encoder_decoder.py
T5EncoderDecoder.forward
forward
Performs encoding and decoding.
[ "Performs", "encoding", "and", "decoding." ]
def forward(self, inputs: Union[torch.Tensor, torch.LongTensor], sequence_length: Optional[torch.LongTensor]=None): if inputs.dim() == 2: word_embeds = self.word_embedder(ids=inputs) elif inputs.dim() == 3: word_embeds = self.word_embedder(soft_ids=inputs) else: raise ValueError("'in...
['def', 'forward(self,', 'inputs:', 'Union[torch.Tensor,', 'torch.LongTensor],', 'sequence_length:', 'Optional[torch.LongTensor]=None):', 'if', 'inputs.dim()', '==', '2:', 'word_embeds', '=', 'self.word_embedder(ids=inputs)', 'elif', 'inputs.dim()', '==', '3:', 'word_embeds', '=', 'self.word_embedder(soft_ids=inputs)',...
925,242
asyml/texar-pytorch
t5_encoder_decoder.py
T5EncoderDecoder.output_size
output_size
The feature size of :meth:`forward` output of the encoder.
[ "The", "feature", "size", "of", ":meth:`forward`", "output", "of", "the", "encoder." ]
def output_size(self): return self._hparams.hidden_size
['def', 'output_size(self):', 'return', 'self._hparams.hidden_size']
925,243
asyml/texar-pytorch
conv_networks.py
Conv1DNetwork.forward
forward
Feeds forward inputs through the network layers and returns outputs.
[ "Feeds", "forward", "inputs", "through", "the", "network", "layers", "and", "returns", "outputs." ]
def forward(self, input: torch.Tensor, sequence_length: Optional[Union[torch.LongTensor, List[int]]]=None, dtype: Optional[torch.dtype]=None, data_format: Optional[str]=None) -> torch.Tensor: if input.dim() != 3: raise ValueError("'input' should be a 3D tensor.") if data_format is None: data_for...
['def', 'forward(self,', 'input:', 'torch.Tensor,', 'sequence_length:', 'Optional[Union[torch.LongTensor,', 'List[int]]]=None,', 'dtype:', 'Optional[torch.dtype]=None,', 'data_format:', 'Optional[str]=None)', '->', 'torch.Tensor:', 'if', 'input.dim()', '!=', '3:', 'raise', 'ValueError("\'input\'', 'should', 'be', 'a', ...
925,244
asyml/texar-pytorch
network_base.py
FeedForwardNetworkBase.append_layer
append_layer
Appends a layer to the end of the network.
[ "Appends", "a", "layer", "to", "the", "end", "of", "the", "network." ]
def append_layer(self, layer: Union[nn.Module, HParams, Dict[str, Any]]): layer_ = layer if not isinstance(layer_, nn.Module): layer_ = get_layer(hparams=layer_) self._layers.append(layer_) layer_name = uniquify_str(layer_.__class__.__name__, self._layer_names) self._layer_names.append(layer...
['def', 'append_layer(self,', 'layer:', 'Union[nn.Module,', 'HParams,', 'Dict[str,', 'Any]]):', 'layer_', '=', 'layer', 'if', 'not', 'isinstance(layer_,', 'nn.Module):', 'layer_', '=', 'get_layer(hparams=layer_)', 'self._layers.append(layer_)', 'layer_name', '=', 'uniquify_str(layer_.__class__.__name__,', 'self._layer_...
925,250
asyml/texar-pytorch
pretrained_base.py
PretrainedMixin.load_pretrained_config
load_pretrained_config
Load paths and configurations of the pre-trained model.
[ "Load", "paths", "and", "configurations", "of", "the", "pre-trained", "model." ]
def load_pretrained_config(self, pretrained_model_name: Optional[str]=None, cache_dir: Optional[str]=None, hparams=None): if not hasattr(self, '_hparams'): self._hparams = HParams(hparams, self.default_hparams()) elif hparams is not None: raise ValueError('`self._hparams` is already assigned, bu...
['def', 'load_pretrained_config(self,', 'pretrained_model_name:', 'Optional[str]=None,', 'cache_dir:', 'Optional[str]=None,', 'hparams=None):', 'if', 'not', 'hasattr(self,', "'_hparams'):", 'self._hparams', '=', 'HParams(hparams,', 'self.default_hparams())', 'elif', 'hparams', 'is', 'not', 'None:', 'raise', "ValueError...
925,257
asyml/texar-pytorch
t5_utils.py
read_t5_gin_config_file
read_t5_gin_config_file
Simple helper function to read a gin file and get hyperparameters for T5.
[ "Simple", "helper", "function", "to", "read", "a", "gin", "file", "and", "get", "hyperparameters", "for", "T5." ]
def read_t5_gin_config_file(config_file_path: str) -> Dict: config = {} with open(config_file_path, 'r') as gin_file: for line in gin_file: if line.startswith(IMPORTANT_PARAMS): assignment = line.strip().split() assert len(assignment) == 3 (arg...
['def', 'read_t5_gin_config_file(config_file_path:', 'str)', '->', 'Dict:', 'config', '=', '{}', 'with', 'open(config_file_path,', "'r')", 'as', 'gin_file:', 'for', 'line', 'in', 'gin_file:', 'if', 'line.startswith(IMPORTANT_PARAMS):', 'assignment', '=', 'line.strip().split()', 'assert', 'len(assignment)', '==', '3', '...
925,261
asyml/texar-pytorch
executor.py
make_deterministic
make_deterministic
Make experiment deterministic by using specific random seeds across all frameworks and (optionally) use deterministic algorithms.
[ "Make", "experiment", "deterministic", "by", "using", "specific", "random", "seeds", "across", "all", "frameworks", "and", "(optionally)", "use", "deterministic", "algorithms." ]
def make_deterministic(seed: int=19260817, cudnn_deterministic: bool=False): random.seed(seed) np.random.seed(seed) torch.manual_seed(seed) torch.cuda.manual_seed_all(seed) if cudnn_deterministic: torch.backends.cudnn.deterministic = True torch.backends.cudnn.benchmark = False
['def', 'make_deterministic(seed:', 'int=19260817,', 'cudnn_deterministic:', 'bool=False):', 'random.seed(seed)', 'np.random.seed(seed)', 'torch.manual_seed(seed)', 'torch.cuda.manual_seed_all(seed)', 'if', 'cudnn_deterministic:', 'torch.backends.cudnn.deterministic', '=', 'True', 'torch.backends.cudnn.benchmark', '=',...
925,271
asyml/texar-pytorch
executor.py
Executor.save
save
Save a snapshot of the current state to a checkpoint file.
[ "Save", "a", "snapshot", "of", "the", "current", "state", "to", "a", "checkpoint", "file." ]
def save(self, path: Optional[str]=None, save_training_state: Optional[bool]=None): if path is not None: ckpt_dir = Path(path) elif self.checkpoint_dir is not None: ckpt_dir = self.checkpoint_dir else: raise ValueError('`path` must be specified when `checkpoint_dir` is `None`') i...
['def', 'save(self,', 'path:', 'Optional[str]=None,', 'save_training_state:', 'Optional[bool]=None):', 'if', 'path', 'is', 'not', 'None:', 'ckpt_dir', '=', 'Path(path)', 'elif', 'self.checkpoint_dir', 'is', 'not', 'None:', 'ckpt_dir', '=', 'self.checkpoint_dir', 'else:', 'raise', "ValueError('`path`", 'must', 'be', 'sp...
925,275
asyml/texar-pytorch
executor.py
Executor.train
train
Start the training loop.
[ "Start", "the", "training", "loop." ]
def train(self): opened_files = self._open_files() if self._directory_exists: self.write_log(f"Specified checkpoint directory '{self.checkpoint_dir}' exists, previous checkpoints might be erased", mode='warning') if len(self._stop_training_conditions) == 0: self.write_log('`stop_training_on`...
['def', 'train(self):', 'opened_files', '=', 'self._open_files()', 'if', 'self._directory_exists:', 'self.write_log(f"Specified', 'checkpoint', 'directory', "'{self.checkpoint_dir}'", 'exists,', 'previous', 'checkpoints', 'might', 'be', 'erased",', "mode='warning')", 'if', 'len(self._stop_training_conditions)', '==', '...
925,279
asyml/texar-pytorch
executor.py
Executor.test
test
Start the test loop.
[ "Start", "the", "test", "loop." ]
def test(self, dataset: OptionalDict[DatasetBase]=None): opened_files = self._open_files() if dataset is None and self.test_data is None: raise ValueError('No testing dataset is specified') if len(self.test_metrics) == 0: raise ValueError('No testing metric is specified. Validation metrics a...
['def', 'test(self,', 'dataset:', 'OptionalDict[DatasetBase]=None):', 'opened_files', '=', 'self._open_files()', 'if', 'dataset', 'is', 'None', 'and', 'self.test_data', 'is', 'None:', 'raise', "ValueError('No", 'testing', 'dataset', 'is', "specified')", 'if', 'len(self.test_metrics)', '==', '0:', 'raise', "ValueError('...
925,280
asyml/texar-pytorch
base_metric.py
Metric.reset
reset
Reset the internal state of the metric, and erase all previously added data points.
[ "Reset", "the", "internal", "state", "of", "the", "metric,", "and", "erase", "all", "previously", "added", "data", "points." ]
def reset(self) -> None: raise NotImplementedError
['def', 'reset(self)', '->', 'None:', 'raise', 'NotImplementedError']
925,285
asyml/texar-pytorch
average_recorder.py
_SingleAverageRecorder.add
add
Appends a new record.
[ "Appends", "a", "new", "record." ]
def add(self, record: Scalar, weight: Optional[Scalar]=None): w = weight if weight is not None else 1 self._w_sum += w self._sum += record * w if self._size is not None: if len(self._q) == self._size: w_pop = self._w.popleft() self._sum -= self._q.popleft() * w_pop ...
['def', 'add(self,', 'record:', 'Scalar,', 'weight:', 'Optional[Scalar]=None):', 'w', '=', 'weight', 'if', 'weight', 'is', 'not', 'None', 'else', '1', 'self._w_sum', '+=', 'w', 'self._sum', '+=', 'record', '*', 'w', 'if', 'self._size', 'is', 'not', 'None:', 'if', 'len(self._q)', '==', 'self._size:', 'w_pop', '=', 'self...
925,291
asyml/texar-pytorch
dtypes.py
get_numpy_dtype
get_numpy_dtype
Returns equivalent NumPy dtype.
[ "Returns", "equivalent", "NumPy", "dtype." ]
def get_numpy_dtype(dtype: Union[str, type]): for (np_dtype, valid_values) in DTYPE_MAP.items(): if dtype in valid_values: return np_dtype raise ValueError(f'Unsupported conversion from type {dtype!s} to NumPy dtype')
['def', 'get_numpy_dtype(dtype:', 'Union[str,', 'type]):', 'for', '(np_dtype,', 'valid_values)', 'in', 'DTYPE_MAP.items():', 'if', 'dtype', 'in', 'valid_values:', 'return', 'np_dtype', 'raise', "ValueError(f'Unsupported", 'conversion', 'from', 'type', '{dtype!s}', 'to', 'NumPy', "dtype')"]
925,301
asyml/texar-pytorch
dtypes.py
get_supported_scalar_types
get_supported_scalar_types
Returns a list of scalar types supported.
[ "Returns", "a", "list", "of", "scalar", "types", "supported." ]
def get_supported_scalar_types(): types = [] for (key, value) in DTYPE_MAP.items(): if key not in {np.str_, np.bytes_}: types.extend(value) return types
['def', 'get_supported_scalar_types():', 'types', '=', '[]', 'for', '(key,', 'value)', 'in', 'DTYPE_MAP.items():', 'if', 'key', 'not', 'in', '{np.str_,', 'np.bytes_}:', 'types.extend(value)', 'return', 'types']
925,304
asyml/texar-pytorch
dtypes.py
compat_as_text
compat_as_text
Converts strings into ``unicode`` (Python 2) or ``str`` (Python 3).
[ "Converts", "strings", "into", "``unicode``", "(Python", "2)", "or", "``str``", "(Python", "3)." ]
def compat_as_text(str_): def _recur_convert(s): if isinstance(s, (list, tuple, np.ndarray)): s_ = [_recur_convert(si) for si in s] return _maybe_list_to_array(s_, s) else: try: return _as_text(s) except TypeError: retu...
['def', 'compat_as_text(str_):', 'def', '_recur_convert(s):', 'if', 'isinstance(s,', '(list,', 'tuple,', 'np.ndarray)):', 's_', '=', '[_recur_convert(si)', 'for', 'si', 'in', 's]', 'return', '_maybe_list_to_array(s_,', 's)', 'else:', 'try:', 'return', '_as_text(s)', 'except', 'TypeError:', 'return', '_as_text(str(s))',...
925,306
asyml/texar-pytorch
utils.py
map_structure
map_structure
Map a function over all elements in a (possibly nested) collection.
[ "Map", "a", "function", "over", "all", "elements", "in", "a", "(possibly", "nested)", "collection." ]
def map_structure(fn: Callable[[T], R], obj: Collection[T]) -> Collection[R]: if hasattr(obj, '--no-map--'): return fn(obj) if isinstance(obj, list): return [map_structure(fn, x) for x in obj] if isinstance(obj, tuple): if isinstance(obj, torch.Size): return fn(obj) ...
['def', 'map_structure(fn:', 'Callable[[T],', 'R],', 'obj:', 'Collection[T])', '->', 'Collection[R]:', 'if', 'hasattr(obj,', "'--no-map--'):", 'return', 'fn(obj)', 'if', 'isinstance(obj,', 'list):', 'return', '[map_structure(fn,', 'x)', 'for', 'x', 'in', 'obj]', 'if', 'isinstance(obj,', 'tuple):', 'if', 'isinstance(obj...
925,323
asyml/texar-pytorch
utils.py
get_first_in_structure
get_first_in_structure
Return the first not-`None` element within a (possibly nested) collection.
[ "Return", "the", "first", "not-`None`", "element", "within", "a", "(possibly", "nested)", "collection." ]
def get_first_in_structure(obj: Collection[T]) -> Optional[T]: item = None def _get_first(x): nonlocal item if item is None: item = x map_structure(_get_first, obj) return item
['def', 'get_first_in_structure(obj:', 'Collection[T])', '->', 'Optional[T]:', 'item', '=', 'None', 'def', '_get_first(x):', 'nonlocal', 'item', 'if', 'item', 'is', 'None:', 'item', '=', 'x', 'map_structure(_get_first,', 'obj)', 'return', 'item']
925,325
asyml/texar-pytorch
utils.py
sum_tensors
sum_tensors
Sum a list of tensors with possible `None` values.
[ "Sum", "a", "list", "of", "tensors", "with", "possible", "`None`", "values." ]
def sum_tensors(xs: List[Optional[torch.Tensor]]) -> Optional[torch.Tensor]: idx = next((idx for (idx, tensor) in enumerate(xs) if tensor is not None), -1) if idx == -1: return None ret = xs[idx] for tensor in xs[idx + 1:]: if tensor is not None: ret = ret + tensor return...
['def', 'sum_tensors(xs:', 'List[Optional[torch.Tensor]])', '->', 'Optional[torch.Tensor]:', 'idx', '=', 'next((idx', 'for', '(idx,', 'tensor)', 'in', 'enumerate(xs)', 'if', 'tensor', 'is', 'not', 'None),', '-1)', 'if', 'idx', '==', '-1:', 'return', 'None', 'ret', '=', 'xs[idx]', 'for', 'tensor', 'in', 'xs[idx', '+', '...
925,352
crisbodnar/text-to-image
model.py
inception_net
inception_net
Build Inception v3 model architecture.
[ "Build", "Inception", "v3", "model", "architecture." ]
def inception_net(images, num_classes, for_training=False, reuse=False): with slim.arg_scope(inception.inception_v3_arg_scope()): (logits, endpoints) = inception.inception_v3(images, dropout_keep_prob=0.8, num_classes=num_classes, is_training=for_training, reuse=reuse, scope='InceptionV3') return (logit...
['def', 'inception_net(images,', 'num_classes,', 'for_training=False,', 'reuse=False):', 'with', 'slim.arg_scope(inception.inception_v3_arg_scope()):', '(logits,', 'endpoints)', '=', 'inception.inception_v3(images,', 'dropout_keep_prob=0.8,', 'num_classes=num_classes,', 'is_training=for_training,', 'reuse=reuse,', "sco...
925,485
crisbodnar/text-to-image
visualize.py
save_cap_batch
save_cap_batch
Creates a super image of generated images with the caption of the images written on a top blank row.
[ "Creates", "a", "super", "image", "of", "generated", "images", "with", "the", "caption", "of", "the", "images", "written", "on", "a", "top", "blank", "row." ]
def save_cap_batch(img_batch, caption, path, rows=None, split=50): img_shape = img_batch[0].shape font_size = img_shape[0] // 3 - 2 super_img = prepare_img_for_captioning(img_batch, bottom=False, rows=rows) caption = preporcess_caption(caption) super_img = Image.fromarray(write_caption(super_img, ca...
['def', 'save_cap_batch(img_batch,', 'caption,', 'path,', 'rows=None,', 'split=50):', 'img_shape', '=', 'img_batch[0].shape', 'font_size', '=', 'img_shape[0]', '//', '3', '-', '2', 'super_img', '=', 'prepare_img_for_captioning(img_batch,', 'bottom=False,', 'rows=rows)', 'caption', '=', 'preporcess_caption(caption)', 's...
925,502
crisbodnar/text-to-image
visualize.py
save_interp_cap_batch
save_interp_cap_batch
Creates a super image of interpolated captions.
[ "Creates", "a", "super", "image", "of", "interpolated", "captions." ]
def save_interp_cap_batch(img_batch, cap1, cap2, path, rows=None): img_shape = img_batch[0].shape font_size = img_shape[0] // 3 - 2 super_img = prepare_img_for_captioning(img_batch, bottom=True, rows=rows) cap1 = preporcess_caption(cap1) cap2 = preporcess_caption(cap2) super_img = write_caption(...
['def', 'save_interp_cap_batch(img_batch,', 'cap1,', 'cap2,', 'path,', 'rows=None):', 'img_shape', '=', 'img_batch[0].shape', 'font_size', '=', 'img_shape[0]', '//', '3', '-', '2', 'super_img', '=', 'prepare_img_for_captioning(img_batch,', 'bottom=True,', 'rows=rows)', 'cap1', '=', 'preporcess_caption(cap1)', 'cap2', '...
925,503
google-research/text-to-text-transfer-transformer
glue_utils.py
get_glue_text_preprocessor
get_glue_text_preprocessor
Return the glue preprocessor.
[ "Return", "the", "glue", "preprocessor." ]
def get_glue_text_preprocessor(builder_config): if builder_config.name == 'stsb': return preprocessors.stsb elif builder_config.name == 'wsc.fixed': return preprocessors.wsc elif builder_config.name == 'record': return preprocessors.record else: if 'mnli' in builder_confi...
['def', 'get_glue_text_preprocessor(builder_config):', 'if', 'builder_config.name', '==', "'stsb':", 'return', 'preprocessors.stsb', 'elif', 'builder_config.name', '==', "'wsc.fixed':", 'return', 'preprocessors.wsc', 'elif', 'builder_config.name', '==', "'record':", 'return', 'preprocessors.record', 'else:', 'if', "'mn...
925,532
google-research/text-to-text-transfer-transformer
postprocessors.py
multirc
multirc
Returns dict containing the class with the question index for grouping.
[ "Returns", "dict", "containing", "the", "class", "with", "the", "question", "index", "for", "grouping." ]
def multirc(string_label, example=None, is_target=False): res = {'value': string_label_to_class_id(string_label, example=example, label_classes=('False', 'True'))} if is_target: res['group'] = example['idx/question'] return res
['def', 'multirc(string_label,', 'example=None,', 'is_target=False):', 'res', '=', "{'value':", 'string_label_to_class_id(string_label,', 'example=example,', "label_classes=('False',", "'True'))}", 'if', 'is_target:', "res['group']", '=', "example['idx/question']", 'return', 'res']
925,535
google-research/text-to-text-transfer-transformer
postprocessors.py
record
record
Returns dict with answer, or all answers + grouping key for a target.
[ "Returns", "dict", "with", "answer,", "or", "all", "answers", "+", "grouping", "key", "for", "a", "target." ]
def record(answer, example=None, is_target=False): if is_target: return {'value': [tf.compat.as_text(a) for a in example['answers']], 'group': (example['idx/passage'], example['idx/query'])} return {'value': answer}
['def', 'record(answer,', 'example=None,', 'is_target=False):', 'if', 'is_target:', 'return', "{'value':", '[tf.compat.as_text(a)', 'for', 'a', 'in', "example['answers']],", "'group':", "(example['idx/passage'],", "example['idx/query'])}", 'return', "{'value':", 'answer}']
925,536
google-research/text-to-text-transfer-transformer
postprocessors.py
qa
qa
Returns answer, or all answers if the full example is provided.
[ "Returns", "answer,", "or", "all", "answers", "if", "the", "full", "example", "is", "provided." ]
def qa(answer, example=None, is_target=False): if is_target: return [tf.compat.as_text(a) for a in example['answers']] return answer
['def', 'qa(answer,', 'example=None,', 'is_target=False):', 'if', 'is_target:', 'return', '[tf.compat.as_text(a)', 'for', 'a', 'in', "example['answers']]", 'return', 'answer']
925,537
google-research/text-to-text-transfer-transformer
postprocessors.py
span_qa
span_qa
Returns answer, or a dict with answers and context if the example is provided.
[ "Returns", "answer,", "or", "a", "dict", "with", "answers", "and", "context", "if", "the", "example", "is", "provided." ]
def span_qa(answer, example=None, is_target=False): if is_target: return {'answers': [tf.compat.as_text(a) for a in example['answers']], 'context': tf.compat.as_text(example['context'])} return answer
['def', 'span_qa(answer,', 'example=None,', 'is_target=False):', 'if', 'is_target:', 'return', "{'answers':", '[tf.compat.as_text(a)', 'for', 'a', 'in', "example['answers']],", "'context':", "tf.compat.as_text(example['context'])}", 'return', 'answer']
925,538
google-research/text-to-text-transfer-transformer
postprocessors.py
wsc_simple
wsc_simple
Sees whether we predicted the referent or not.
[ "Sees", "whether", "we", "predicted", "the", "referent", "or", "not." ]
def wsc_simple(prediction, example=None, is_target=False): if is_target: return example['label'] determiners = {'a', 'an', 'few', 'her', 'his', 'each', 'every', 'many', 'much', 'my', 'our', 'some', 'that', 'the', 'their', 'these', 'this', 'those', 'which', 'whose', 'your'} def clean(s): s =...
['def', 'wsc_simple(prediction,', 'example=None,', 'is_target=False):', 'if', 'is_target:', 'return', "example['label']", 'determiners', '=', "{'a',", "'an',", "'few',", "'her',", "'his',", "'each',", "'every',", "'many',", "'much',", "'my',", "'our',", "'some',", "'that',", "'the',", "'their',", "'these',", "'this',",...
925,539
google-research/text-to-text-transfer-transformer
preprocessors.py
split_text_to_words
split_text_to_words
Split text to words and filter out examples with too few words.
[ "Split", "text", "to", "words", "and", "filter", "out", "examples", "with", "too", "few", "words." ]
def split_text_to_words(dataset, text_key='text', min_num_words=2): def split(x): res = dict(x) res['words'] = tf.strings.split([x[text_key]]).values return res dataset = dataset.map(split, num_parallel_calls=AUTOTUNE) return dataset.filter(lambda x: tf.size(x['words']) >= min_num_w...
['def', 'split_text_to_words(dataset,', "text_key='text',", 'min_num_words=2):', 'def', 'split(x):', 'res', '=', 'dict(x)', "res['words']", '=', 'tf.strings.split([x[text_key]]).values', 'return', 'res', 'dataset', '=', 'dataset.map(split,', 'num_parallel_calls=AUTOTUNE)', 'return', 'dataset.filter(lambda', 'x:', "tf.s...
925,548
google-research/text-to-text-transfer-transformer
preprocessors.py
full_lm
full_lm
Full language modeling objective with EOS only at document boundaries.
[ "Full", "language", "modeling", "objective", "with", "EOS", "only", "at", "document", "boundaries." ]
def full_lm(dataset, sequence_length, output_features): ds = dataset ds = select_random_chunk(ds, output_features=output_features, feature_key='targets', max_length=65536) ds = seqio.preprocessors.append_eos(ds, output_features) ds = reduce_concat_tokens(ds, feature_key='targets', batch_size=128) ds...
['def', 'full_lm(dataset,', 'sequence_length,', 'output_features):', 'ds', '=', 'dataset', 'ds', '=', 'select_random_chunk(ds,', 'output_features=output_features,', "feature_key='targets',", 'max_length=65536)', 'ds', '=', 'seqio.preprocessors.append_eos(ds,', 'output_features)', 'ds', '=', 'reduce_concat_tokens(ds,', ...
925,563
google-research/text-to-text-transfer-transformer
preprocessors.py
select_random_chunk
select_random_chunk
SeqIO wrapper for single_example_select_random_chunk().
[ "SeqIO", "wrapper", "for", "single_example_select_random_chunk()." ]
def select_random_chunk(dataset: tf.data.Dataset, output_features: Mapping[str, seqio.Feature], max_length: Optional[int]=None, feature_key: str='targets', additional_feature_keys: Optional[Sequence[str]]=None, passthrough_feature_keys: Optional[Sequence[str]]=None, sequence_length: Optional[Mapping[str, int]]=None, un...
['def', 'select_random_chunk(dataset:', 'tf.data.Dataset,', 'output_features:', 'Mapping[str,', 'seqio.Feature],', 'max_length:', 'Optional[int]=None,', 'feature_key:', "str='targets',", 'additional_feature_keys:', 'Optional[Sequence[str]]=None,', 'passthrough_feature_keys:', 'Optional[Sequence[str]]=None,', 'sequence_...
925,565
google-research/text-to-text-transfer-transformer
preprocessors.py
trim_tokens_at_front
trim_tokens_at_front
Token-preprocessor to trim sequence at the beginning.
[ "Token-preprocessor", "to", "trim", "sequence", "at", "the", "beginning." ]
def trim_tokens_at_front(x, sequence_length, keys_to_trim=None, **unused_kwargs): for key in keys_to_trim or sequence_length.keys(): if key in x: x[key] = x[key][-(sequence_length[key] - 1):] return x
['def', 'trim_tokens_at_front(x,', 'sequence_length,', 'keys_to_trim=None,', '**unused_kwargs):', 'for', 'key', 'in', 'keys_to_trim', 'or', 'sequence_length.keys():', 'if', 'key', 'in', 'x:', 'x[key]', '=', 'x[key][-(sequence_length[key]', '-', '1):]', 'return', 'x']
925,567
google-research/text-to-text-transfer-transformer
preprocessors.py
filter_by_string_length
filter_by_string_length
Filter examples by string length.
[ "Filter", "examples", "by", "string", "length." ]
def filter_by_string_length(dataset, feature_key='targets', min_length=1, max_length=1000000, **unused_kwargs): def my_fn(x): l = tf.strings.length(x[feature_key]) return tf.logical_and(tf.greater_equal(l, min_length), tf.less_equal(l, max_length)) return dataset.filter(my_fn)
['def', 'filter_by_string_length(dataset,', "feature_key='targets',", 'min_length=1,', 'max_length=1000000,', '**unused_kwargs):', 'def', 'my_fn(x):', 'l', '=', 'tf.strings.length(x[feature_key])', 'return', 'tf.logical_and(tf.greater_equal(l,', 'min_length),', 'tf.less_equal(l,', 'max_length))', 'return', 'dataset.fil...
925,572
google-research/text-to-text-transfer-transformer
preprocessors.py
random_spans_targets_length
random_spans_targets_length
Helper for gin-configuring the targets sequence length.
[ "Helper", "for", "gin-configuring", "the", "targets", "sequence", "length." ]
def random_spans_targets_length(): return random_spans_helper()[1]
['def', 'random_spans_targets_length():', 'return', 'random_spans_helper()[1]']
925,575
google-research/text-to-text-transfer-transformer
preprocessors.py
denoise
denoise
SeqIO wrapper for single_example_denoise().
[ "SeqIO", "wrapper", "for", "single_example_denoise()." ]
def denoise(dataset, output_features, noise_density=gin.REQUIRED, noise_mask_fn=gin.REQUIRED, inputs_fn=gin.REQUIRED, targets_fn=None, passthrough_feature_keys: Optional[Sequence[str]]=None, input_feature_key='inputs', **unused_kwargs): @seqio.map_over_dataset(num_seeds=1) def my_fn(features, seed): re...
['def', 'denoise(dataset,', 'output_features,', 'noise_density=gin.REQUIRED,', 'noise_mask_fn=gin.REQUIRED,', 'inputs_fn=gin.REQUIRED,', 'targets_fn=None,', 'passthrough_feature_keys:', 'Optional[Sequence[str]]=None,', "input_feature_key='inputs',", '**unused_kwargs):', '@seqio.map_over_dataset(num_seeds=1)', 'def', 'm...
925,576
google-research/text-to-text-transfer-transformer
preprocessors.py
noise_token_to_sentinel
noise_token_to_sentinel
Replace each noise token with the given sentinel.
[ "Replace", "each", "noise", "token", "with", "the", "given", "sentinel." ]
def noise_token_to_sentinel(tokens, noise_mask, vocabulary, seeds): del seeds return tf.where(noise_mask, tf.cast(sentinel_id(vocabulary), tokens.dtype), tokens)
['def', 'noise_token_to_sentinel(tokens,', 'noise_mask,', 'vocabulary,', 'seeds):', 'del', 'seeds', 'return', 'tf.where(noise_mask,', 'tf.cast(sentinel_id(vocabulary),', 'tokens.dtype),', 'tokens)']
925,582
google-research/text-to-text-transfer-transformer
preprocessors.py
permute_noise_tokens
permute_noise_tokens
Permute the noise tokens, keeping the non-noise tokens where they are.
[ "Permute", "the", "noise", "tokens,", "keeping", "the", "non-noise", "tokens", "where", "they", "are." ]
def permute_noise_tokens(tokens, noise_mask, vocabulary, seeds): del vocabulary masked_only = tf.boolean_mask(tokens, noise_mask) permuted = seqio.stateless_shuffle(masked_only, seeds[0]) permuted = tf.pad(permuted, [[0, 1]]) indices = tf.cumsum(tf.cast(noise_mask, tf.int32), exclusive=True) ret...
['def', 'permute_noise_tokens(tokens,', 'noise_mask,', 'vocabulary,', 'seeds):', 'del', 'vocabulary', 'masked_only', '=', 'tf.boolean_mask(tokens,', 'noise_mask)', 'permuted', '=', 'seqio.stateless_shuffle(masked_only,', 'seeds[0])', 'permuted', '=', 'tf.pad(permuted,', '[[0,', '1]])', 'indices', '=', 'tf.cumsum(tf.cas...
925,587
google-research/text-to-text-transfer-transformer
preprocessors.py
noise_token_to_gathered_token
noise_token_to_gathered_token
Replace each noise token with a random token from the sequence.
[ "Replace", "each", "noise", "token", "with", "a", "random", "token", "from", "the", "sequence." ]
def noise_token_to_gathered_token(tokens, noise_mask, vocabulary, seeds): del vocabulary indices = tf.random.stateless_uniform(shape=tf.shape(tokens), maxval=tf.size(tokens), dtype=tf.int32, seed=seeds[0]) return tf.where(noise_mask, tf.gather(tokens, indices), tokens)
['def', 'noise_token_to_gathered_token(tokens,', 'noise_mask,', 'vocabulary,', 'seeds):', 'del', 'vocabulary', 'indices', '=', 'tf.random.stateless_uniform(shape=tf.shape(tokens),', 'maxval=tf.size(tokens),', 'dtype=tf.int32,', 'seed=seeds[0])', 'return', 'tf.where(noise_mask,', 'tf.gather(tokens,', 'indices),', 'token...
925,588
google-research/text-to-text-transfer-transformer
preprocessors.py
noise_token_to_random_token
noise_token_to_random_token
Replace each noise token with a random token from the vocabulary.
[ "Replace", "each", "noise", "token", "with", "a", "random", "token", "from", "the", "vocabulary." ]
def noise_token_to_random_token(tokens, noise_mask, vocabulary, seeds, num_reserved_tokens=3): return tf.where(noise_mask, tf.random.stateless_uniform(tf.shape(tokens), minval=num_reserved_tokens, maxval=vocabulary.vocab_size, dtype=tokens.dtype, seed=seeds[0]), tokens)
['def', 'noise_token_to_random_token(tokens,', 'noise_mask,', 'vocabulary,', 'seeds,', 'num_reserved_tokens=3):', 'return', 'tf.where(noise_mask,', 'tf.random.stateless_uniform(tf.shape(tokens),', 'minval=num_reserved_tokens,', 'maxval=vocabulary.vocab_size,', 'dtype=tokens.dtype,', 'seed=seeds[0]),', 'tokens)']
925,589
google-research/text-to-text-transfer-transformer
preprocessors.py
targets_for_prefix_lm_objective
targets_for_prefix_lm_objective
Prepares targets to be used for prefix LM objective.
[ "Prepares", "targets", "to", "be", "used", "for", "prefix", "LM", "objective." ]
def targets_for_prefix_lm_objective(dataset, sequence_length, output_features): dataset = select_random_chunk(dataset, output_features, max_length=65536, feature_key='targets') dataset = seqio.preprocessors.append_eos(dataset, output_features) dataset = reduce_concat_tokens(dataset, batch_size=128) data...
['def', 'targets_for_prefix_lm_objective(dataset,', 'sequence_length,', 'output_features):', 'dataset', '=', 'select_random_chunk(dataset,', 'output_features,', 'max_length=65536,', "feature_key='targets')", 'dataset', '=', 'seqio.preprocessors.append_eos(dataset,', 'output_features)', 'dataset', '=', 'reduce_concat_to...
925,592
google-research/text-to-text-transfer-transformer
preprocessors.py
pack_prefix_lm_encoder_decoder
pack_prefix_lm_encoder_decoder
Pack two examples into one with the prefix LM objective.
[ "Pack", "two", "examples", "into", "one", "with", "the", "prefix", "LM", "objective." ]
def pack_prefix_lm_encoder_decoder(ds, sequence_length, pad_id=0): packed_length = next(iter(sequence_length.values())) assert packed_length % 2 == 0 assert all((l == packed_length for l in sequence_length.values())) @seqio.utils.map_over_dataset(num_seeds=1) def pack_examples(example_pair, seed): ...
['def', 'pack_prefix_lm_encoder_decoder(ds,', 'sequence_length,', 'pad_id=0):', 'packed_length', '=', 'next(iter(sequence_length.values()))', 'assert', 'packed_length', '%', '2', '==', '0', 'assert', 'all((l', '==', 'packed_length', 'for', 'l', 'in', 'sequence_length.values()))', '@seqio.utils.map_over_dataset(num_seed...
925,593
google-research/text-to-text-transfer-transformer
preprocessors.py
pack_prefix_lm_decoder_only
pack_prefix_lm_decoder_only
Randomly split the tokens for the prefix LM objective.
[ "Randomly", "split", "the", "tokens", "for", "the", "prefix", "LM", "objective." ]
def pack_prefix_lm_decoder_only(ds, sequence_length, loss_on_targets_only=True, pad_id=0): packed_length = next(iter(sequence_length.values())) assert packed_length % 2 == 0 assert all((l == packed_length for l in sequence_length.values())) @seqio.utils.map_over_dataset(num_seeds=1) def pack_exampl...
['def', 'pack_prefix_lm_decoder_only(ds,', 'sequence_length,', 'loss_on_targets_only=True,', 'pad_id=0):', 'packed_length', '=', 'next(iter(sequence_length.values()))', 'assert', 'packed_length', '%', '2', '==', '0', 'assert', 'all((l', '==', 'packed_length', 'for', 'l', 'in', 'sequence_length.values()))', '@seqio.util...
925,594
google-research/text-to-text-transfer-transformer
preprocessors_test.py
PreprocessorsTest.test_random_spans_noise_mask_with_roll
test_random_spans_noise_mask_with_roll
Test random_spans_noise_mask with roll on a fixed sample+seed.
[ "Test", "random_spans_noise_mask", "with", "roll", "on", "a", "fixed", "sample+seed." ]
def test_random_spans_noise_mask_with_roll(self): noise_mask_values = [] for random_roll in (False, True): noise_mask = prep.random_spans_noise_mask(length=32, noise_density=0.25, seeds=[(1, 2), (3, 4)], mean_noise_span_length=3, random_roll=random_roll) noise_mask_values += [self.evaluate(tf.ca...
['def', 'test_random_spans_noise_mask_with_roll(self):', 'noise_mask_values', '=', '[]', 'for', 'random_roll', 'in', '(False,', 'True):', 'noise_mask', '=', 'prep.random_spans_noise_mask(length=32,', 'noise_density=0.25,', 'seeds=[(1,', '2),', '(3,', '4)],', 'mean_noise_span_length=3,', 'random_roll=random_roll)', 'noi...
925,595
google-research/text-to-text-transfer-transformer
preprocessors_test.py
PreprocessorsTest.test_random_spans_noise_mask_with_roll_avg
test_random_spans_noise_mask_with_roll_avg
Test that the empirical mask density is close to the desired density.
[ "Test", "that", "the", "empirical", "mask", "density", "is", "close", "to", "the", "desired", "density." ]
def test_random_spans_noise_mask_with_roll_avg(self): noise_density = 0.15 total_masked = 0 total_lengths = 0 for i in range(50): span_len = 3 length = 16 + i % span_len noise_mask = prep.random_spans_noise_mask(length=length, noise_density=noise_density, seeds=[(1 + i, 2), (3 + ...
['def', 'test_random_spans_noise_mask_with_roll_avg(self):', 'noise_density', '=', '0.15', 'total_masked', '=', '0', 'total_lengths', '=', '0', 'for', 'i', 'in', 'range(50):', 'span_len', '=', '3', 'length', '=', '16', '+', 'i', '%', 'span_len', 'noise_mask', '=', 'prep.random_spans_noise_mask(length=length,', 'noise_d...
925,596
google-research/text-to-text-transfer-transformer
eval_utils.py
log_csv
log_csv
Log scores to be copy/pasted into a spreadsheet.
[ "Log", "scores", "to", "be", "copy/pasted", "into", "a", "spreadsheet." ]
def log_csv(df, metric_names=None, output_file=None): logging.info(','.join(df.columns)) (metric_max, metric_max_step) = metric_group_max(df, metric_names) max_row = 'max,' + ','.join(('{:.3f}'.format(m) for m in metric_max)) logging.info(max_row) idx_row = 'step,' + ','.join(('{:d}'.format(i) for i...
['def', 'log_csv(df,', 'metric_names=None,', 'output_file=None):', "logging.info(','.join(df.columns))", '(metric_max,', 'metric_max_step)', '=', 'metric_group_max(df,', 'metric_names)', 'max_row', '=', "'max,'", '+', "','.join(('{:.3f}'.format(m)", 'for', 'm', 'in', 'metric_max))', 'logging.info(max_row)', 'idx_row', ...
925,605
google-research/text-to-text-transfer-transformer
metrics.py
rouge
rouge
Computes rouge score nondeterministically using the bootstrap.
[ "Computes", "rouge", "score", "nondeterministically", "using", "the", "bootstrap." ]
def rouge(targets, predictions, score_keys=('rouge1', 'rouge2', 'rougeLsum'), **kwargs): scorer = rouge_scorer.RougeScorer(rouge_types=score_keys, **kwargs) aggregator = scoring.BootstrapAggregator() for (prediction, target) in zip(predictions, targets): target = _prepare_summary_rouge(target) ...
['def', 'rouge(targets,', 'predictions,', "score_keys=('rouge1',", "'rouge2',", "'rougeLsum'),", '**kwargs):', 'scorer', '=', 'rouge_scorer.RougeScorer(rouge_types=score_keys,', '**kwargs)', 'aggregator', '=', 'scoring.BootstrapAggregator()', 'for', '(prediction,', 'target)', 'in', 'zip(predictions,', 'targets):', 'tar...
925,606
google-research/text-to-text-transfer-transformer
metrics.py
rouge_mean
rouge_mean
Computes rouge score deterministically (no bootstrap).
[ "Computes", "rouge", "score", "deterministically", "(no", "bootstrap)." ]
def rouge_mean(targets, predictions, score_keys=('rouge1', 'rouge2', 'rougeLsum'), **kwargs): scorer = rouge_scorer.RougeScorer(rouge_types=score_keys, **kwargs) count = 0 sum_scores = collections.defaultdict(float) for (prediction, target) in zip(predictions, targets): target = _prepare_summary...
['def', 'rouge_mean(targets,', 'predictions,', "score_keys=('rouge1',", "'rouge2',", "'rougeLsum'),", '**kwargs):', 'scorer', '=', 'rouge_scorer.RougeScorer(rouge_types=score_keys,', '**kwargs)', 'count', '=', '0', 'sum_scores', '=', 'collections.defaultdict(float)', 'for', '(prediction,', 'target)', 'in', 'zip(predict...
925,607
google-research/text-to-text-transfer-transformer
metrics.py
trivia_qa
trivia_qa
Computes TriviaQA metrics, maximizing over answers per question.
[ "Computes", "TriviaQA", "metrics,", "maximizing", "over", "answers", "per", "question." ]
def trivia_qa(targets, predictions): targets = [[qa_utils.normalize_trivia_qa(t) for t in u] for u in targets] predictions = [qa_utils.normalize_trivia_qa(p) for p in predictions] return qa_utils.qa_metrics(targets, predictions)
['def', 'trivia_qa(targets,', 'predictions):', 'targets', '=', '[[qa_utils.normalize_trivia_qa(t)', 'for', 't', 'in', 'u]', 'for', 'u', 'in', 'targets]', 'predictions', '=', '[qa_utils.normalize_trivia_qa(p)', 'for', 'p', 'in', 'predictions]', 'return', 'qa_utils.qa_metrics(targets,', 'predictions)']
925,610
google-research/text-to-text-transfer-transformer
metrics.py
all_match
all_match
Computes whether all targets match all predictions exactly.
[ "Computes", "whether", "all", "targets", "match", "all", "predictions", "exactly." ]
def all_match(targets, predictions): return {'exact_match': 100 * float(np.array_equal(targets, predictions))}
['def', 'all_match(targets,', 'predictions):', 'return', "{'exact_match':", '100', '*', 'float(np.array_equal(targets,', 'predictions))}']
925,613
google-research/text-to-text-transfer-transformer
metrics.py
edit_distance
edit_distance
Word-level edit distance between targets and predictions.
[ "Word-level", "edit", "distance", "between", "targets", "and", "predictions." ]
def edit_distance(targets, predictions, lower=True): edit_distances = [] for (pred, target) in zip(predictions, targets): if lower: pred = pred.lower() target = target.lower() pred = re.split('[^\\w]', pred) target = re.split('[^\\w]', target) edit_distanc...
['def', 'edit_distance(targets,', 'predictions,', 'lower=True):', 'edit_distances', '=', '[]', 'for', '(pred,', 'target)', 'in', 'zip(predictions,', 'targets):', 'if', 'lower:', 'pred', '=', 'pred.lower()', 'target', '=', 'target.lower()', 'pred', '=', "re.split('[^\\\\w]',", 'pred)', 'target', '=', "re.split('[^\\\\w]...
925,623
google-research/text-to-text-transfer-transformer
metrics.py
ShardedSquad.merge
merge
Returns `Squad` that is the accumulation of `self` and `other`.
[ "Returns", "`Squad`", "that", "is", "the", "accumulation", "of", "`self`", "and", "`other`." ]
def merge(self, other: 'ShardedSquad') -> 'ShardedSquad': count = self.count + other.count f1 = (self.f1 * self.count + other.f1 * other.count) / count em = (self.em * self.count + other.em * other.count) / count return type(self)(f1=f1, em=em, count=count)
['def', 'merge(self,', 'other:', "'ShardedSquad')", '->', "'ShardedSquad':", 'count', '=', 'self.count', '+', 'other.count', 'f1', '=', '(self.f1', '*', 'self.count', '+', 'other.f1', '*', 'other.count)', '/', 'count', 'em', '=', '(self.em', '*', 'self.count', '+', 'other.em', '*', 'other.count)', '/', 'count', 'return...
925,624
google-research/text-to-text-transfer-transformer
hf_model.py
tokens_to_batches
tokens_to_batches
Convert a dataset of token sequences to batches of padded/masked examples.
[ "Convert", "a", "dataset", "of", "token", "sequences", "to", "batches", "of", "padded/masked", "examples." ]
def tokens_to_batches(dataset, sequence_length, batch_size, output_features, mixture_or_task=None): if mixture_or_task: eos_keys = set((k for (k, f) in mixture_or_task.output_features.items() if f.add_eos)) else: eos_keys = True dataset = transformer_dataset.pack_or_pad(dataset, sequence_len...
['def', 'tokens_to_batches(dataset,', 'sequence_length,', 'batch_size,', 'output_features,', 'mixture_or_task=None):', 'if', 'mixture_or_task:', 'eos_keys', '=', 'set((k', 'for', '(k,', 'f)', 'in', 'mixture_or_task.output_features.items()', 'if', 'f.add_eos))', 'else:', 'eos_keys', '=', 'True', 'dataset', '=', 'transfo...
925,628
google-research/text-to-text-transfer-transformer
hf_model.py
HfPyTorchModel.save_checkpoint
save_checkpoint
Save the current model parameters to the `model_dir`.
[ "Save", "the", "current", "model", "parameters", "to", "the", "`model_dir`." ]
def save_checkpoint(self, step): path = os.path.join(self._model_dir, CHECKPOINT_FILE_FORMAT.format(step)) torch.save(self._model.state_dict(), path)
['def', 'save_checkpoint(self,', 'step):', 'path', '=', 'os.path.join(self._model_dir,', 'CHECKPOINT_FILE_FORMAT.format(step))', 'torch.save(self._model.state_dict(),', 'path)']
925,629
google-research/text-to-text-transfer-transformer
hf_model.py
HfPyTorchModel.load_checkpoint
load_checkpoint
Load the model parameters from a checkpoint at a given step.
[ "Load", "the", "model", "parameters", "from", "a", "checkpoint", "at", "a", "given", "step." ]
def load_checkpoint(self, step, model_dir=None): model_dir = model_dir or self._model_dir path = os.path.join(model_dir, CHECKPOINT_FILE_FORMAT.format(step)) logging.info('Loading from %s', path) self._model.load_state_dict(torch.load(path)) self._step = step
['def', 'load_checkpoint(self,', 'step,', 'model_dir=None):', 'model_dir', '=', 'model_dir', 'or', 'self._model_dir', 'path', '=', 'os.path.join(model_dir,', 'CHECKPOINT_FILE_FORMAT.format(step))', "logging.info('Loading", 'from', "%s',", 'path)', 'self._model.load_state_dict(torch.load(path))', 'self._step', '=', 'ste...
925,630
google-research/text-to-text-transfer-transformer
hf_model.py
HfPyTorchModel.get_all_checkpoint_steps
get_all_checkpoint_steps
Retrieve the steps corresponding to all checkpoints in `model_dir`.
[ "Retrieve", "the", "steps", "corresponding", "to", "all", "checkpoints", "in", "`model_dir`." ]
def get_all_checkpoint_steps(self, model_dir=None): model_dir = model_dir or self._model_dir checkpoint_files = tf.io.gfile.glob(os.path.join(model_dir, CHECKPOINT_FILE_FORMAT.format('*'))) if not checkpoint_files: return step_regex = re.compile('.*' + CHECKPOINT_FILE_FORMAT.format('(\\d+)')) ...
['def', 'get_all_checkpoint_steps(self,', 'model_dir=None):', 'model_dir', '=', 'model_dir', 'or', 'self._model_dir', 'checkpoint_files', '=', 'tf.io.gfile.glob(os.path.join(model_dir,', "CHECKPOINT_FILE_FORMAT.format('*')))", 'if', 'not', 'checkpoint_files:', 'return', 'step_regex', '=', "re.compile('.*'", '+', "CHECK...
925,631
google-research/text-to-text-transfer-transformer
mtf_model.py
MtfModel.eval
eval
Evaluate the model on the given Mixture or Task.
[ "Evaluate", "the", "model", "on", "the", "given", "Mixture", "or", "Task." ]
def eval(self, mixture_or_task_name, checkpoint_steps=None, summary_dir=None, split='validation', eval_with_score=False, compute_sequence_length=True): _parse_operative_config(self._model_dir) summary_dir = summary_dir or os.path.join(self._model_dir, '{}_eval'.format(split)) checkpoint_steps = utils.get_ch...
['def', 'eval(self,', 'mixture_or_task_name,', 'checkpoint_steps=None,', 'summary_dir=None,', "split='validation',", 'eval_with_score=False,', 'compute_sequence_length=True):', '_parse_operative_config(self._model_dir)', 'summary_dir', '=', 'summary_dir', 'or', 'os.path.join(self._model_dir,', "'{}_eval'.format(split))...
925,644
google-research/text-to-text-transfer-transformer
mtf_model.py
MtfModel.predict
predict
Predicts targets from the given inputs.
[ "Predicts", "targets", "from", "the", "given", "inputs." ]
def predict(self, input_file, output_file, checkpoint_steps=-1, beam_size=1, temperature=1.0, keep_top_k=-1, vocabulary=None): if checkpoint_steps == -1: checkpoint_steps = utils.get_latest_checkpoint_from_dir(self._model_dir) _parse_operative_config(self._model_dir) with gin.unlock_config(): ...
['def', 'predict(self,', 'input_file,', 'output_file,', 'checkpoint_steps=-1,', 'beam_size=1,', 'temperature=1.0,', 'keep_top_k=-1,', 'vocabulary=None):', 'if', 'checkpoint_steps', '==', '-1:', 'checkpoint_steps', '=', 'utils.get_latest_checkpoint_from_dir(self._model_dir)', '_parse_operative_config(self._model_dir)', ...
925,646
google-research/text-to-text-transfer-transformer
mtf_model.py
MtfModel.export
export
Exports a TensorFlow SavedModel.
[ "Exports", "a", "TensorFlow", "SavedModel." ]
def export(self, export_dir=None, checkpoint_step=-1, beam_size=1, temperature=1.0, keep_top_k=-1, vocabulary=None, eval_with_score=False): if checkpoint_step == -1: checkpoint_step = utils.get_latest_checkpoint_from_dir(self._model_dir) _parse_operative_config(self._model_dir) with gin.unlock_confi...
['def', 'export(self,', 'export_dir=None,', 'checkpoint_step=-1,', 'beam_size=1,', 'temperature=1.0,', 'keep_top_k=-1,', 'vocabulary=None,', 'eval_with_score=False):', 'if', 'checkpoint_step', '==', '-1:', 'checkpoint_step', '=', 'utils.get_latest_checkpoint_from_dir(self._model_dir)', '_parse_operative_config(self._mo...
925,648
google-research/text-to-text-transfer-transformer
utils.py
filter_features
filter_features
Filters example features, keeping only valid model features.
[ "Filters", "example", "features,", "keeping", "only", "valid", "model", "features." ]
def filter_features(ex): return {k: v for (k, v) in ex.items() if k in _MODEL_FEATURES}
['def', 'filter_features(ex):', 'return', '{k:', 'v', 'for', '(k,', 'v)', 'in', 'ex.items()', 'if', 'k', 'in', '_MODEL_FEATURES}']
925,649
google-research/text-to-text-transfer-transformer
utils.py
write_lines_to_file
write_lines_to_file
Write each line to filename, replacing the file if it exists.
[ "Write", "each", "line", "to", "filename,", "replacing", "the", "file", "if", "it", "exists." ]
def write_lines_to_file(lines, filename): if tf.io.gfile.exists(filename): tf.io.gfile.remove(filename) with tf.io.gfile.GFile(filename, 'w') as output_file: output_file.write('\n'.join([str(l) for l in lines]))
['def', 'write_lines_to_file(lines,', 'filename):', 'if', 'tf.io.gfile.exists(filename):', 'tf.io.gfile.remove(filename)', 'with', 'tf.io.gfile.GFile(filename,', "'w')", 'as', 'output_file:', "output_file.write('\\n'.join([str(l)", 'for', 'l', 'in', 'lines]))']
925,650
google-research/text-to-text-transfer-transformer
utils.py
get_vocabulary
get_vocabulary
Return vocabulary from the mixture or task.
[ "Return", "vocabulary", "from", "the", "mixture", "or", "task." ]
def get_vocabulary(mixture_or_task_name=None): if not mixture_or_task_name: try: mixture_or_task_name = gin.query_parameter('%MIXTURE_NAME') except ValueError: logging.warning('Could not extract mixture/task name from gin config.') if mixture_or_task_name: provide...
['def', 'get_vocabulary(mixture_or_task_name=None):', 'if', 'not', 'mixture_or_task_name:', 'try:', 'mixture_or_task_name', '=', "gin.query_parameter('%MIXTURE_NAME')", 'except', 'ValueError:', "logging.warning('Could", 'not', 'extract', 'mixture/task', 'name', 'from', 'gin', "config.')", 'if', 'mixture_or_task_name:',...
925,653
google-research/text-to-text-transfer-transformer
utils.py
get_targets_and_examples
get_targets_and_examples
Get targets, cached datasets, and maximum sequence lengths per feature.
[ "Get", "targets,", "cached", "datasets,", "and", "maximum", "sequence", "lengths", "per", "feature." ]
def get_targets_and_examples(tasks: Sequence[seqio.Task], dataset_fn: Callable[[seqio.Task], tf.data.Dataset], sequence_dims: Mapping[str, int], num_examples: Optional[int]=None, use_memory_cache: bool=True, target_field_name: str='targets') -> Tuple[Mapping[str, Any], Mapping[str, tf.data.Dataset], Mapping[str, int]]:...
['def', 'get_targets_and_examples(tasks:', 'Sequence[seqio.Task],', 'dataset_fn:', 'Callable[[seqio.Task],', 'tf.data.Dataset],', 'sequence_dims:', 'Mapping[str,', 'int],', 'num_examples:', 'Optional[int]=None,', 'use_memory_cache:', 'bool=True,', 'target_field_name:', "str='targets')", '->', 'Tuple[Mapping[str,', 'Any...
925,656
google-research/text-to-text-transfer-transformer
dump_task.py
sequence_length
sequence_length
Sequence length used when tokenizing.
[ "Sequence", "length", "used", "when", "tokenizing." ]
def sequence_length(value=512): if isinstance(value, int): return {'inputs': value, 'targets': value} else: return value
['def', 'sequence_length(value=512):', 'if', 'isinstance(value,', 'int):', 'return', "{'inputs':", 'value,', "'targets':", 'value}', 'else:', 'return', 'value']
925,658
airaria/TextBrewer
modeling_gpt2.py
GPT2Config.from_json_file
from_json_file
Constructs a `GPT2Config` from a json file of parameters.
[ "Constructs", "a", "`GPT2Config`", "from", "a", "json", "file", "of", "parameters." ]
def from_json_file(cls, json_file): with open(json_file, 'r', encoding='utf-8') as reader: text = reader.read() return cls.from_dict(json.loads(text))
['def', 'from_json_file(cls,', 'json_file):', 'with', 'open(json_file,', "'r',", "encoding='utf-8')", 'as', 'reader:', 'text', '=', 'reader.read()', 'return', 'cls.from_dict(json.loads(text))']
925,767
airaria/TextBrewer
modeling_transfo_xl.py
TransfoXLConfig.from_dict
from_dict
Constructs a `TransfoXLConfig` from a Python dictionary of parameters.
[ "Constructs", "a", "`TransfoXLConfig`", "from", "a", "Python", "dictionary", "of", "parameters." ]
def from_dict(cls, json_object): config = TransfoXLConfig(vocab_size_or_config_json_file=-1) for (key, value) in json_object.items(): config.__dict__[key] = value return config
['def', 'from_dict(cls,', 'json_object):', 'config', '=', 'TransfoXLConfig(vocab_size_or_config_json_file=-1)', 'for', '(key,', 'value)', 'in', 'json_object.items():', 'config.__dict__[key]', '=', 'value', 'return', 'config']
925,784
airaria/TextBrewer
modeling_transfo_xl.py
TransfoXLConfig.from_json_file
from_json_file
Constructs a `TransfoXLConfig` from a json file of parameters.
[ "Constructs", "a", "`TransfoXLConfig`", "from", "a", "json", "file", "of", "parameters." ]
def from_json_file(cls, json_file): with open(json_file, 'r', encoding='utf-8') as reader: text = reader.read() return cls.from_dict(json.loads(text))
['def', 'from_json_file(cls,', 'json_file):', 'with', 'open(json_file,', "'r',", "encoding='utf-8')", 'as', 'reader:', 'text', '=', 'reader.read()', 'return', 'cls.from_dict(json.loads(text))']
925,785
airaria/TextBrewer
tokenization_gpt2.py
GPT2Tokenizer.convert_ids_to_tokens
convert_ids_to_tokens
Converts a sequence of ids in BPE tokens using the vocab.
[ "Converts", "a", "sequence", "of", "ids", "in", "BPE", "tokens", "using", "the", "vocab." ]
def convert_ids_to_tokens(self, ids, skip_special_tokens=False): tokens = [] for i in ids: if i in self.special_tokens_decoder: if not skip_special_tokens: tokens.append(self.special_tokens_decoder[i]) else: tokens.append(self.decoder[i]) return tokens
['def', 'convert_ids_to_tokens(self,', 'ids,', 'skip_special_tokens=False):', 'tokens', '=', '[]', 'for', 'i', 'in', 'ids:', 'if', 'i', 'in', 'self.special_tokens_decoder:', 'if', 'not', 'skip_special_tokens:', 'tokens.append(self.special_tokens_decoder[i])', 'else:', 'tokens.append(self.decoder[i])', 'return', 'tokens...
925,820