repo
stringclasses
85 values
path
stringlengths
8
121
func_name
stringlengths
1
82
original_string
stringlengths
112
65.5k
language
stringclasses
1 value
code
stringlengths
112
65.5k
code_tokens
listlengths
20
4.09k
docstring
stringlengths
3
46.3k
docstring_tokens
listlengths
1
564
sha
stringclasses
85 values
url
stringlengths
93
218
partition
stringclasses
1 value
mozilla/DeepSpeech
examples/mic_vad_streaming/mic_vad_streaming.py
VADAudio.vad_collector
def vad_collector(self, padding_ms=300, ratio=0.75, frames=None): """Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being...
python
def vad_collector(self, padding_ms=300, ratio=0.75, frames=None): """Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being...
[ "def", "vad_collector", "(", "self", ",", "padding_ms", "=", "300", ",", "ratio", "=", "0.75", ",", "frames", "=", "None", ")", ":", "if", "frames", "is", "None", ":", "frames", "=", "self", ".", "frame_generator", "(", ")", "num_padding_frames", "=", ...
Generator that yields series of consecutive audio frames comprising each utterence, separated by yielding a single None. Determines voice activity by ratio of frames in padding_ms. Uses a buffer to include padding_ms prior to being triggered. Example: (frame, ..., frame, None, frame, ..., frame,...
[ "Generator", "that", "yields", "series", "of", "consecutive", "audio", "frames", "comprising", "each", "utterence", "separated", "by", "yielding", "a", "single", "None", ".", "Determines", "voice", "activity", "by", "ratio", "of", "frames", "in", "padding_ms", "...
f64aa73e7fbe9dde40d4fcf23b42ab304747d152
https://github.com/mozilla/DeepSpeech/blob/f64aa73e7fbe9dde40d4fcf23b42ab304747d152/examples/mic_vad_streaming/mic_vad_streaming.py#L112-L142
train
fxsjy/jieba
jieba/posseg/__init__.py
cut
def cut(sentence, HMM=True): """ Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported. """ global dt if jieba.pool is None: for w in dt.cut(sentence, HMM=HMM): yield w else: ...
python
def cut(sentence, HMM=True): """ Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported. """ global dt if jieba.pool is None: for w in dt.cut(sentence, HMM=HMM): yield w else: ...
[ "def", "cut", "(", "sentence", ",", "HMM", "=", "True", ")", ":", "global", "dt", "if", "jieba", ".", "pool", "is", "None", ":", "for", "w", "in", "dt", ".", "cut", "(", "sentence", ",", "HMM", "=", "HMM", ")", ":", "yield", "w", "else", ":", ...
Global `cut` function that supports parallel processing. Note that this only works using dt, custom POSTokenizer instances are not supported.
[ "Global", "cut", "function", "that", "supports", "parallel", "processing", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/posseg/__init__.py#L272-L291
train
fxsjy/jieba
jieba/__init__.py
enable_parallel
def enable_parallel(processnum=None): """ Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported. """ global pool, dt, cut, cut_for_search from multiprocessing import cpu_count ...
python
def enable_parallel(processnum=None): """ Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported. """ global pool, dt, cut, cut_for_search from multiprocessing import cpu_count ...
[ "def", "enable_parallel", "(", "processnum", "=", "None", ")", ":", "global", "pool", ",", "dt", ",", "cut", ",", "cut_for_search", "from", "multiprocessing", "import", "cpu_count", "if", "os", ".", "name", "==", "'nt'", ":", "raise", "NotImplementedError", ...
Change the module's `cut` and `cut_for_search` functions to the parallel version. Note that this only works using dt, custom Tokenizer instances are not supported.
[ "Change", "the", "module", "s", "cut", "and", "cut_for_search", "functions", "to", "the", "parallel", "version", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L569-L589
train
fxsjy/jieba
jieba/__init__.py
Tokenizer.cut
def cut(self, sentence, cut_all=False, HMM=True): ''' The main function that segments an entire sentence that contains Chinese characters into separated words. Parameter: - sentence: The str(unicode) to be segmented. - cut_all: Model type. True for full pattern, ...
python
def cut(self, sentence, cut_all=False, HMM=True): ''' The main function that segments an entire sentence that contains Chinese characters into separated words. Parameter: - sentence: The str(unicode) to be segmented. - cut_all: Model type. True for full pattern, ...
[ "def", "cut", "(", "self", ",", "sentence", ",", "cut_all", "=", "False", ",", "HMM", "=", "True", ")", ":", "sentence", "=", "strdecode", "(", "sentence", ")", "if", "cut_all", ":", "re_han", "=", "re_han_cut_all", "re_skip", "=", "re_skip_cut_all", "el...
The main function that segments an entire sentence that contains Chinese characters into separated words. Parameter: - sentence: The str(unicode) to be segmented. - cut_all: Model type. True for full pattern, False for accurate pattern. - HMM: Whether to use the Hidd...
[ "The", "main", "function", "that", "segments", "an", "entire", "sentence", "that", "contains", "Chinese", "characters", "into", "separated", "words", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L275-L315
train
fxsjy/jieba
jieba/__init__.py
Tokenizer.cut_for_search
def cut_for_search(self, sentence, HMM=True): """ Finer segmentation for search engines. """ words = self.cut(sentence, HMM=HMM) for w in words: if len(w) > 2: for i in xrange(len(w) - 1): gram2 = w[i:i + 2] if s...
python
def cut_for_search(self, sentence, HMM=True): """ Finer segmentation for search engines. """ words = self.cut(sentence, HMM=HMM) for w in words: if len(w) > 2: for i in xrange(len(w) - 1): gram2 = w[i:i + 2] if s...
[ "def", "cut_for_search", "(", "self", ",", "sentence", ",", "HMM", "=", "True", ")", ":", "words", "=", "self", ".", "cut", "(", "sentence", ",", "HMM", "=", "HMM", ")", "for", "w", "in", "words", ":", "if", "len", "(", "w", ")", ">", "2", ":",...
Finer segmentation for search engines.
[ "Finer", "segmentation", "for", "search", "engines", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L317-L333
train
fxsjy/jieba
jieba/__init__.py
Tokenizer.load_userdict
def load_userdict(self, f): ''' Load personalized dict to improve detect rate. Parameter: - f : A plain text file contains words and their ocurrences. Can be a file-like object, or the path of the dictionary file, whose encoding must be utf-8. ...
python
def load_userdict(self, f): ''' Load personalized dict to improve detect rate. Parameter: - f : A plain text file contains words and their ocurrences. Can be a file-like object, or the path of the dictionary file, whose encoding must be utf-8. ...
[ "def", "load_userdict", "(", "self", ",", "f", ")", ":", "self", ".", "check_initialized", "(", ")", "if", "isinstance", "(", "f", ",", "string_types", ")", ":", "f_name", "=", "f", "f", "=", "open", "(", "f", ",", "'rb'", ")", "else", ":", "f_name...
Load personalized dict to improve detect rate. Parameter: - f : A plain text file contains words and their ocurrences. Can be a file-like object, or the path of the dictionary file, whose encoding must be utf-8. Structure of dict file: word1 freq...
[ "Load", "personalized", "dict", "to", "improve", "detect", "rate", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L359-L395
train
fxsjy/jieba
jieba/__init__.py
Tokenizer.add_word
def add_word(self, word, freq=None, tag=None): """ Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out. """ self.check_initialized() word = strdecode(word) freq = int(freq) if ...
python
def add_word(self, word, freq=None, tag=None): """ Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out. """ self.check_initialized() word = strdecode(word) freq = int(freq) if ...
[ "def", "add_word", "(", "self", ",", "word", ",", "freq", "=", "None", ",", "tag", "=", "None", ")", ":", "self", ".", "check_initialized", "(", ")", "word", "=", "strdecode", "(", "word", ")", "freq", "=", "int", "(", "freq", ")", "if", "freq", ...
Add a word to dictionary. freq and tag can be omitted, freq defaults to be a calculated value that ensures the word can be cut out.
[ "Add", "a", "word", "to", "dictionary", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L397-L416
train
fxsjy/jieba
jieba/__init__.py
Tokenizer.suggest_freq
def suggest_freq(self, segment, tune=False): """ Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole,...
python
def suggest_freq(self, segment, tune=False): """ Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole,...
[ "def", "suggest_freq", "(", "self", ",", "segment", ",", "tune", "=", "False", ")", ":", "self", ".", "check_initialized", "(", ")", "ftotal", "=", "float", "(", "self", ".", "total", ")", "freq", "=", "1", "if", "isinstance", "(", "segment", ",", "s...
Suggest word frequency to force the characters in a word to be joined or splitted. Parameter: - segment : The segments that the word is expected to be cut into, If the word should be treated as a whole, use a str. - tune : If True, tune the word frequency...
[ "Suggest", "word", "frequency", "to", "force", "the", "characters", "in", "a", "word", "to", "be", "joined", "or", "splitted", "." ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L424-L453
train
fxsjy/jieba
jieba/__init__.py
Tokenizer.tokenize
def tokenize(self, unicode_sentence, mode="default", HMM=True): """ Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: ...
python
def tokenize(self, unicode_sentence, mode="default", HMM=True): """ Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: ...
[ "def", "tokenize", "(", "self", ",", "unicode_sentence", ",", "mode", "=", "\"default\"", ",", "HMM", "=", "True", ")", ":", "if", "not", "isinstance", "(", "unicode_sentence", ",", "text_type", ")", ":", "raise", "ValueError", "(", "\"jieba: the input paramet...
Tokenize a sentence and yields tuples of (word, start, end) Parameter: - sentence: the str(unicode) to be segmented. - mode: "default" or "search", "search" is for finer segmentation. - HMM: whether to use the Hidden Markov Model.
[ "Tokenize", "a", "sentence", "and", "yields", "tuples", "of", "(", "word", "start", "end", ")" ]
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/__init__.py#L455-L486
train
fxsjy/jieba
jieba/analyse/textrank.py
TextRank.textrank
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
python
def textrank(self, sentence, topK=20, withWeight=False, allowPOS=('ns', 'n', 'vn', 'v'), withFlag=False): """ Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, re...
[ "def", "textrank", "(", "self", ",", "sentence", ",", "topK", "=", "20", ",", "withWeight", "=", "False", ",", "allowPOS", "=", "(", "'ns'", ",", "'n'", ",", "'vn'", ",", "'v'", ")", ",", "withFlag", "=", "False", ")", ":", "self", ".", "pos_filt",...
Extract keywords from sentence using TextRank algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed...
[ "Extract", "keywords", "from", "sentence", "using", "TextRank", "algorithm", ".", "Parameter", ":", "-", "topK", ":", "return", "how", "many", "top", "keywords", ".", "None", "for", "all", "possible", "words", ".", "-", "withWeight", ":", "if", "True", "re...
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/analyse/textrank.py#L69-L108
train
fxsjy/jieba
jieba/analyse/tfidf.py
TFIDF.extract_tags
def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False): """ Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (wo...
python
def extract_tags(self, sentence, topK=20, withWeight=False, allowPOS=(), withFlag=False): """ Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (wo...
[ "def", "extract_tags", "(", "self", ",", "sentence", ",", "topK", "=", "20", ",", "withWeight", "=", "False", ",", "allowPOS", "=", "(", ")", ",", "withFlag", "=", "False", ")", ":", "if", "allowPOS", ":", "allowPOS", "=", "frozenset", "(", "allowPOS",...
Extract keywords from sentence using TF-IDF algorithm. Parameter: - topK: return how many top keywords. `None` for all possible words. - withWeight: if True, return a list of (word, weight); if False, return a list of words. - allowPOS: the allowed P...
[ "Extract", "keywords", "from", "sentence", "using", "TF", "-", "IDF", "algorithm", ".", "Parameter", ":", "-", "topK", ":", "return", "how", "many", "top", "keywords", ".", "None", "for", "all", "possible", "words", ".", "-", "withWeight", ":", "if", "Tr...
8212b6c5725d08311952a3a08e5509eeaee33eb7
https://github.com/fxsjy/jieba/blob/8212b6c5725d08311952a3a08e5509eeaee33eb7/jieba/analyse/tfidf.py#L75-L116
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cleaner_en_xx.py
paracrawl_v3_pairs
def paracrawl_v3_pairs(paracrawl_file): """Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in t...
python
def paracrawl_v3_pairs(paracrawl_file): """Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in t...
[ "def", "paracrawl_v3_pairs", "(", "paracrawl_file", ")", ":", "raw_sentences", "=", "_raw_sentences", "(", "paracrawl_file", ")", "for", "s_en", "in", "raw_sentences", ":", "try", ":", "s_xx", "=", "next", "(", "raw_sentences", ")", "if", "s_en", "and", "s_xx"...
Generates raw (English, other) pairs from a ParaCrawl V3.0 data file. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: Pairs of (sentence_en, sentence_xx), as Unicode strings. Raises: StopIteration: If the file ends while this method is in the middle of creating a translation p...
[ "Generates", "raw", "(", "English", "other", ")", "pairs", "from", "a", "ParaCrawl", "V3", ".", "0", "data", "file", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cleaner_en_xx.py#L66-L86
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cleaner_en_xx.py
_raw_sentences
def _raw_sentences(paracrawl_file): """Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the Pa...
python
def _raw_sentences(paracrawl_file): """Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the Pa...
[ "def", "_raw_sentences", "(", "paracrawl_file", ")", ":", "for", "line_utf8", "in", "paracrawl_file", ":", "line_uni", "=", "line_utf8", ".", "decode", "(", "'UTF-8'", ")", "text_match", "=", "re", ".", "match", "(", "r' +<seg>(.*)</seg>$'", ",", "line_uni", "...
Generates Unicode strings, one for each <seg> in a ParaCrawl data file. Also decodes some of the most common HTML entities found in ParaCrawl data. Args: paracrawl_file: A ParaCrawl V3.0 en-.. data file. Yields: One Unicode string for each <seg> element in the ParaCrawl data file.
[ "Generates", "Unicode", "strings", "one", "for", "each", "<seg", ">", "in", "a", "ParaCrawl", "data", "file", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cleaner_en_xx.py#L89-L110
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/cleaner_en_xx.py
clean_en_xx_pairs
def clean_en_xx_pairs(en_xx_pairs): """Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sen...
python
def clean_en_xx_pairs(en_xx_pairs): """Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sen...
[ "def", "clean_en_xx_pairs", "(", "en_xx_pairs", ")", ":", "for", "s1", ",", "s2", "in", "en_xx_pairs", ":", "if", "_regex_filter", "(", "s1", ")", ":", "continue", "s1_list", ",", "s2_list", "=", "_split_sentences", "(", "s1", ",", "s2", ")", "if", "len"...
Generates a cleaned-up stream of (English, other) translation pairs. Cleaning includes both filtering and simplistic sentence splitting, with minimal assumptions on the non-English pair member: (1) All filtering is done based on the English member of the pair, and (2) sentence splitting assumes only that sente...
[ "Generates", "a", "cleaned", "-", "up", "stream", "of", "(", "English", "other", ")", "translation", "pairs", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/cleaner_en_xx.py#L113-L142
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
_get_case_file_paths
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95): """Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for tra...
python
def _get_case_file_paths(tmp_dir, case, training_fraction=0.95): """Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for tra...
[ "def", "_get_case_file_paths", "(", "tmp_dir", ",", "case", ",", "training_fraction", "=", "0.95", ")", ":", "paths", "=", "tf", ".", "gfile", ".", "Glob", "(", "\"%s/*.jpg\"", "%", "tmp_dir", ")", "if", "not", "paths", ":", "raise", "ValueError", "(", "...
Obtain a list of image paths corresponding to training or eval case. Args: tmp_dir: str, the root path to which raw images were written, at the top level having meta/ and raw/ subdirs. case: bool, whether obtaining file paths for training (true) or eval (false). training_fraction: float, the ...
[ "Obtain", "a", "list", "of", "image", "paths", "corresponding", "to", "training", "or", "eval", "case", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L81-L121
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
maybe_download_image_dataset
def maybe_download_image_dataset(image_ids, target_dir): """Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images. """ tf.gfile.MakeDirs(target_dir) num_images = len(image_ids) for...
python
def maybe_download_image_dataset(image_ids, target_dir): """Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images. """ tf.gfile.MakeDirs(target_dir) num_images = len(image_ids) for...
[ "def", "maybe_download_image_dataset", "(", "image_ids", ",", "target_dir", ")", ":", "tf", ".", "gfile", ".", "MakeDirs", "(", "target_dir", ")", "num_images", "=", "len", "(", "image_ids", ")", "for", "i", ",", "image_id", "in", "enumerate", "(", "image_id...
Download a set of images from api.brain-map.org to `target_dir`. Args: image_ids: list, a list of image ids. target_dir: str, a directory to which to download the images.
[ "Download", "a", "set", "of", "images", "from", "api", ".", "brain", "-", "map", ".", "org", "to", "target_dir", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L124-L163
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
random_square_mask
def random_square_mask(shape, fraction): """Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask. """ mask =...
python
def random_square_mask(shape, fraction): """Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask. """ mask =...
[ "def", "random_square_mask", "(", "shape", ",", "fraction", ")", ":", "mask", "=", "np", ".", "ones", "(", "shape", ")", "patch_area", "=", "shape", "[", "0", "]", "*", "shape", "[", "1", "]", "*", "fraction", "patch_dim", "=", "np", ".", "int", "(...
Create a numpy array with specified shape and masked fraction. Args: shape: tuple, shape of the mask to create. fraction: float, fraction of the mask area to populate with `mask_scalar`. Returns: numpy.array: A numpy array storing the mask.
[ "Create", "a", "numpy", "array", "with", "specified", "shape", "and", "masked", "fraction", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L166-L189
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/allen_brain.py
_generator
def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE, training_fraction=0.95): """Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training...
python
def _generator(tmp_dir, training, size=_BASE_EXAMPLE_IMAGE_SIZE, training_fraction=0.95): """Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training...
[ "def", "_generator", "(", "tmp_dir", ",", "training", ",", "size", "=", "_BASE_EXAMPLE_IMAGE_SIZE", ",", "training_fraction", "=", "0.95", ")", ":", "maybe_download_image_dataset", "(", "_IMAGE_IDS", ",", "tmp_dir", ")", "image_files", "=", "_get_case_file_paths", "...
Base problem example generator for Allen Brain Atlas problems. Args: tmp_dir: str, a directory where raw example input data has been stored. training: bool, whether the mode of operation is training (or, alternatively, evaluation), determining whether examples in tmp_dir prefixed with train or d...
[ "Base", "problem", "example", "generator", "for", "Allen", "Brain", "Atlas", "problems", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/allen_brain.py#L192-L260
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_moe.py
transformer_moe_base
def transformer_moe_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2001 hparams.max_input_seq_length = 2000 hparams.max_target_seq_length = 2000 hparams.dropout = 0.0 ...
python
def transformer_moe_base(): """Set of hyperparameters.""" hparams = common_hparams.basic_params1() hparams.norm_type = "layer" hparams.hidden_size = 512 hparams.batch_size = 4096 hparams.max_length = 2001 hparams.max_input_seq_length = 2000 hparams.max_target_seq_length = 2000 hparams.dropout = 0.0 ...
[ "def", "transformer_moe_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "norm_type", "=", "\"layer\"", "hparams", ".", "hidden_size", "=", "512", "hparams", ".", "batch_size", "=", "4096", "hparams", ".",...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L267-L311
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_moe.py
transformer_moe_8k
def transformer_moe_8k(): """Hyper parameters specifics for long sequence generation.""" hparams = transformer_moe_base() hparams.batch_size = 8192 hparams.max_length = 0 # max_length == batch_size hparams.eval_drop_long_sequences = True hparams.min_length_bucket = 256 # Avoid cyclic problems for big bat...
python
def transformer_moe_8k(): """Hyper parameters specifics for long sequence generation.""" hparams = transformer_moe_base() hparams.batch_size = 8192 hparams.max_length = 0 # max_length == batch_size hparams.eval_drop_long_sequences = True hparams.min_length_bucket = 256 # Avoid cyclic problems for big bat...
[ "def", "transformer_moe_8k", "(", ")", ":", "hparams", "=", "transformer_moe_base", "(", ")", "hparams", ".", "batch_size", "=", "8192", "hparams", ".", "max_length", "=", "0", "# max_length == batch_size", "hparams", ".", "eval_drop_long_sequences", "=", "True", ...
Hyper parameters specifics for long sequence generation.
[ "Hyper", "parameters", "specifics", "for", "long", "sequence", "generation", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L315-L327
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_moe.py
transformer_moe_2k
def transformer_moe_2k(): """Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: *...
python
def transformer_moe_2k(): """Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: *...
[ "def", "transformer_moe_2k", "(", ")", ":", "hparams", "=", "transformer_moe_8k", "(", ")", "hparams", ".", "batch_size", "=", "2048", "hparams", ".", "default_ff", "=", "\"sep\"", "# hparams.layer_types contains the network architecture:", "encoder_archi", "=", "\"a/a/...
Base transformers model with moe. Will have the following architecture: * No encoder. * Layer 0: a - sep (self-attention - unmasked separable convolutions) * Layer 1: a - sep * Layer 2: a - sep * Layer 3: a - sep * Layer 4: a - sep * Decoder architecture: * Layer 0: a - a - sepm (self-a...
[ "Base", "transformers", "model", "with", "moe", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L365-L395
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_moe.py
transformer_moe_prepend_8k
def transformer_moe_prepend_8k(): """Model which formulate a seq2seq problem as language modeling.""" hparams = transformer_moe_8k() hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.eval_drop_long_sequences = False hparams.max_input_seq_length = 7500 hparams.default_ff = "sepm" hparams.lay...
python
def transformer_moe_prepend_8k(): """Model which formulate a seq2seq problem as language modeling.""" hparams = transformer_moe_8k() hparams.prepend_mode = "prepend_inputs_masked_attention" hparams.eval_drop_long_sequences = False hparams.max_input_seq_length = 7500 hparams.default_ff = "sepm" hparams.lay...
[ "def", "transformer_moe_prepend_8k", "(", ")", ":", "hparams", "=", "transformer_moe_8k", "(", ")", "hparams", ".", "prepend_mode", "=", "\"prepend_inputs_masked_attention\"", "hparams", ".", "eval_drop_long_sequences", "=", "False", "hparams", ".", "max_input_seq_length"...
Model which formulate a seq2seq problem as language modeling.
[ "Model", "which", "formulate", "a", "seq2seq", "problem", "as", "language", "modeling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_moe.py#L409-L418
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
f
def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1, training=True, bottleneck=True, padding='SAME'): """Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the thi...
python
def f(x, depth1, depth2, dim='2d', first_batch_norm=True, stride=1, training=True, bottleneck=True, padding='SAME'): """Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the thi...
[ "def", "f", "(", "x", ",", "depth1", ",", "depth2", ",", "dim", "=", "'2d'", ",", "first_batch_norm", "=", "True", ",", "stride", "=", "1", ",", "training", "=", "True", ",", "bottleneck", "=", "True", ",", "padding", "=", "'SAME'", ")", ":", "conv...
Applies residual function for RevNet. Args: x: input tensor depth1: Number of output channels for the first and second conv layers. depth2: Number of output channels for the third conv layer. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. first_batch_norm: Whether to keep the first batch norm...
[ "Applies", "residual", "function", "for", "RevNet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L72-L122
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
downsample_bottleneck
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What...
python
def downsample_bottleneck(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What...
[ "def", "downsample_bottleneck", "(", "x", ",", "output_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "1", ",", "scope", "=", "'h'", ")", ":", "conv", "=", "CONFIG", "[", "dim", "]", "[", "'conv'", "]", "with", "tf", ".", "variable_scope", "...
Downsamples 'x' by `stride` using a 1x1 convolution filter. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use. Usually 1 or 2. scope: Optional variable scope. Returns: ...
[ "Downsamples", "x", "by", "stride", "using", "a", "1x1", "convolution", "filter", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L125-L144
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
downsample_residual
def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using average pooling. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to ...
python
def downsample_residual(x, output_channels, dim='2d', stride=1, scope='h'): """Downsamples 'x' by `stride` using average pooling. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to ...
[ "def", "downsample_residual", "(", "x", ",", "output_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "1", ",", "scope", "=", "'h'", ")", ":", "with", "tf", ".", "variable_scope", "(", "scope", ")", ":", "if", "stride", ">", "1", ":", "avg_poo...
Downsamples 'x' by `stride` using average pooling. Args: x: input tensor of size [N, H, W, C] output_channels: Desired number of output channels. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: What stride to use. Usually 1 or 2. scope: Optional variable scope. Returns: A downsa...
[ "Downsamples", "x", "by", "stride", "using", "average", "pooling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L147-L175
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
init
def init(images, num_channels, dim='2d', stride=2, kernel_size=7, maxpool=True, training=True, scope='init'): """Standard ResNet initial block used as first RevNet block. Args: images: [N, H, W, 3] tensor of input images to the model. num_channels: Output depth of convolutional layer in initial bl...
python
def init(images, num_channels, dim='2d', stride=2, kernel_size=7, maxpool=True, training=True, scope='init'): """Standard ResNet initial block used as first RevNet block. Args: images: [N, H, W, 3] tensor of input images to the model. num_channels: Output depth of convolutional layer in initial bl...
[ "def", "init", "(", "images", ",", "num_channels", ",", "dim", "=", "'2d'", ",", "stride", "=", "2", ",", "kernel_size", "=", "7", ",", "maxpool", "=", "True", ",", "training", "=", "True", ",", "scope", "=", "'init'", ")", ":", "conv", "=", "CONFI...
Standard ResNet initial block used as first RevNet block. Args: images: [N, H, W, 3] tensor of input images to the model. num_channels: Output depth of convolutional layer in initial block. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. stride: stride for the convolution and pool layer. kerne...
[ "Standard", "ResNet", "initial", "block", "used", "as", "first", "RevNet", "block", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L178-L205
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
unit
def unit(x1, x2, block_num, depth, num_layers, dim='2d', bottleneck=True, first_batch_norm=True, stride=1, training=True): """Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. ...
python
def unit(x1, x2, block_num, depth, num_layers, dim='2d', bottleneck=True, first_batch_norm=True, stride=1, training=True): """Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. ...
[ "def", "unit", "(", "x1", ",", "x2", ",", "block_num", ",", "depth", ",", "num_layers", ",", "dim", "=", "'2d'", ",", "bottleneck", "=", "True", ",", "first_batch_norm", "=", "True", ",", "stride", "=", "1", ",", "training", "=", "True", ")", ":", ...
Implements bottleneck RevNet unit from authors' RevNet architecture. Args: x1: [N, H, W, C] tensor of network activations. x2: [N, H, W, C] tensor of network activations. block_num: integer ID of block depth: First depth in bottleneck residual unit. num_layers: Number of layers in the RevNet bloc...
[ "Implements", "bottleneck", "RevNet", "unit", "from", "authors", "RevNet", "architecture", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L208-L258
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
final_block
def final_block(x1, x2, dim='2d', training=True, scope='final_block'): """Converts activations from last RevNet block to pre-logits. Args: x1: [NxHxWxC] tensor of network activations. x2: [NxHxWxC] tensor of network activations. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. training: True for ...
python
def final_block(x1, x2, dim='2d', training=True, scope='final_block'): """Converts activations from last RevNet block to pre-logits. Args: x1: [NxHxWxC] tensor of network activations. x2: [NxHxWxC] tensor of network activations. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. training: True for ...
[ "def", "final_block", "(", "x1", ",", "x2", ",", "dim", "=", "'2d'", ",", "training", "=", "True", ",", "scope", "=", "'final_block'", ")", ":", "# Final batch norm and relu", "with", "tf", ".", "variable_scope", "(", "scope", ")", ":", "y", "=", "tf", ...
Converts activations from last RevNet block to pre-logits. Args: x1: [NxHxWxC] tensor of network activations. x2: [NxHxWxC] tensor of network activations. dim: '2d' if 2-dimensional, '3d' if 3-dimensional. training: True for train phase, False for eval phase. scope: Optional variable scope for th...
[ "Converts", "activations", "from", "last", "RevNet", "block", "to", "pre", "-", "logits", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L261-L285
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet
def revnet(inputs, hparams, reuse=None): """Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() o...
python
def revnet(inputs, hparams, reuse=None): """Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() o...
[ "def", "revnet", "(", "inputs", ",", "hparams", ",", "reuse", "=", "None", ")", ":", "training", "=", "hparams", ".", "mode", "==", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "with", "tf", ".", "variable_scope", "(", "'RevNet'", ",", "reuse...
Uses Tensor2Tensor memory optimized RevNet block to build a RevNet. Args: inputs: [NxHxWx3] tensor of input images to the model. hparams: HParams object that contains the following parameters, in addition to the parameters contained in the basic_params1() object in the common_hparams module: ...
[ "Uses", "Tensor2Tensor", "memory", "optimized", "RevNet", "block", "to", "build", "a", "RevNet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L288-L335
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet_base
def revnet_base(): """Default hparams for Revnet.""" hparams = common_hparams.basic_params1() hparams.add_hparam('num_channels', [64, 128, 256, 416]) hparams.add_hparam('num_layers_per_block', [1, 1, 10, 1]) hparams.add_hparam('bottleneck', True) hparams.add_hparam('first_batch_norm', [False, True, True, Tr...
python
def revnet_base(): """Default hparams for Revnet.""" hparams = common_hparams.basic_params1() hparams.add_hparam('num_channels', [64, 128, 256, 416]) hparams.add_hparam('num_layers_per_block', [1, 1, 10, 1]) hparams.add_hparam('bottleneck', True) hparams.add_hparam('first_batch_norm', [False, True, True, Tr...
[ "def", "revnet_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "add_hparam", "(", "'num_channels'", ",", "[", "64", ",", "128", ",", "256", ",", "416", "]", ")", "hparams", ".", "add_hparam", "(", ...
Default hparams for Revnet.
[ "Default", "hparams", "for", "Revnet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L345-L378
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet_cifar_base
def revnet_cifar_base(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_base() hparams.num_channels_init_block = 32 hparams.first_batch_norm = [False, True, True] hparams.init_stride = 1 hparams.init_kernel_size = 3 hparams.init_maxpool = False hparams.strides = [1, 2, 2] hparams.batch_si...
python
def revnet_cifar_base(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_base() hparams.num_channels_init_block = 32 hparams.first_batch_norm = [False, True, True] hparams.init_stride = 1 hparams.init_kernel_size = 3 hparams.init_maxpool = False hparams.strides = [1, 2, 2] hparams.batch_si...
[ "def", "revnet_cifar_base", "(", ")", ":", "hparams", "=", "revnet_base", "(", ")", "hparams", ".", "num_channels_init_block", "=", "32", "hparams", ".", "first_batch_norm", "=", "[", "False", ",", "True", ",", "True", "]", "hparams", ".", "init_stride", "="...
Tiny hparams suitable for CIFAR/etc.
[ "Tiny", "hparams", "suitable", "for", "CIFAR", "/", "etc", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L386-L400
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet_110_cifar
def revnet_110_cifar(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_cifar_base() hparams.bottleneck = False hparams.num_channels = [16, 32, 64] hparams.num_layers_per_block = [8, 8, 8] return hparams
python
def revnet_110_cifar(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_cifar_base() hparams.bottleneck = False hparams.num_channels = [16, 32, 64] hparams.num_layers_per_block = [8, 8, 8] return hparams
[ "def", "revnet_110_cifar", "(", ")", ":", "hparams", "=", "revnet_cifar_base", "(", ")", "hparams", ".", "bottleneck", "=", "False", "hparams", ".", "num_channels", "=", "[", "16", ",", "32", ",", "64", "]", "hparams", ".", "num_layers_per_block", "=", "["...
Tiny hparams suitable for CIFAR/etc.
[ "Tiny", "hparams", "suitable", "for", "CIFAR", "/", "etc", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L415-L421
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet_164_cifar
def revnet_164_cifar(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_cifar_base() hparams.bottleneck = True hparams.num_channels = [16, 32, 64] hparams.num_layers_per_block = [8, 8, 8] return hparams
python
def revnet_164_cifar(): """Tiny hparams suitable for CIFAR/etc.""" hparams = revnet_cifar_base() hparams.bottleneck = True hparams.num_channels = [16, 32, 64] hparams.num_layers_per_block = [8, 8, 8] return hparams
[ "def", "revnet_164_cifar", "(", ")", ":", "hparams", "=", "revnet_cifar_base", "(", ")", "hparams", ".", "bottleneck", "=", "True", "hparams", ".", "num_channels", "=", "[", "16", ",", "32", ",", "64", "]", "hparams", ".", "num_layers_per_block", "=", "[",...
Tiny hparams suitable for CIFAR/etc.
[ "Tiny", "hparams", "suitable", "for", "CIFAR", "/", "etc", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L425-L431
train
tensorflow/tensor2tensor
tensor2tensor/models/revnet.py
revnet_range
def revnet_range(rhp): """Hyperparameters for tuning revnet.""" rhp.set_float('learning_rate', 0.05, 0.2, scale=rhp.LOG_SCALE) rhp.set_float('weight_decay', 1e-5, 1e-3, scale=rhp.LOG_SCALE) rhp.set_discrete('num_channels_init_block', [64, 128]) return rhp
python
def revnet_range(rhp): """Hyperparameters for tuning revnet.""" rhp.set_float('learning_rate', 0.05, 0.2, scale=rhp.LOG_SCALE) rhp.set_float('weight_decay', 1e-5, 1e-3, scale=rhp.LOG_SCALE) rhp.set_discrete('num_channels_init_block', [64, 128]) return rhp
[ "def", "revnet_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "'learning_rate'", ",", "0.05", ",", "0.2", ",", "scale", "=", "rhp", ".", "LOG_SCALE", ")", "rhp", ".", "set_float", "(", "'weight_decay'", ",", "1e-5", ",", "1e-3", ",", "scal...
Hyperparameters for tuning revnet.
[ "Hyperparameters", "for", "tuning", "revnet", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/revnet.py#L435-L440
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_basic_deterministic
def next_frame_basic_deterministic(): """Basic 2-frame conv model.""" hparams = base.next_frame_base() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 hparams.hidden_size = 64 hparams.batch_size = 4 hparams.num_hidden_layers = 2 hparams.optimizer = "Adafactor" hparams.learning_r...
python
def next_frame_basic_deterministic(): """Basic 2-frame conv model.""" hparams = base.next_frame_base() hparams.video_num_input_frames = 4 hparams.video_num_target_frames = 1 hparams.hidden_size = 64 hparams.batch_size = 4 hparams.num_hidden_layers = 2 hparams.optimizer = "Adafactor" hparams.learning_r...
[ "def", "next_frame_basic_deterministic", "(", ")", ":", "hparams", "=", "base", ".", "next_frame_base", "(", ")", "hparams", ".", "video_num_input_frames", "=", "4", "hparams", ".", "video_num_target_frames", "=", "1", "hparams", ".", "hidden_size", "=", "64", "...
Basic 2-frame conv model.
[ "Basic", "2", "-", "frame", "conv", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L27-L56
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_pixel_noise
def next_frame_pixel_noise(): """Basic 2-frame conv model with pixel noise.""" hparams = next_frame_basic_deterministic() hparams.add_hparam("video_modality_input_noise", 0.05) hparams.bottom["inputs"] = modalities.video_pixel_noise_bottom hparams.top["inputs"] = modalities.video_top return hparams
python
def next_frame_pixel_noise(): """Basic 2-frame conv model with pixel noise.""" hparams = next_frame_basic_deterministic() hparams.add_hparam("video_modality_input_noise", 0.05) hparams.bottom["inputs"] = modalities.video_pixel_noise_bottom hparams.top["inputs"] = modalities.video_top return hparams
[ "def", "next_frame_pixel_noise", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "add_hparam", "(", "\"video_modality_input_noise\"", ",", "0.05", ")", "hparams", ".", "bottom", "[", "\"inputs\"", "]", "=", "modalities", ...
Basic 2-frame conv model with pixel noise.
[ "Basic", "2", "-", "frame", "conv", "model", "with", "pixel", "noise", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L60-L66
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_sampling
def next_frame_sampling(): """Basic conv model with scheduled sampling.""" hparams = next_frame_basic_deterministic() hparams.scheduled_sampling_mode = "prob_inverse_exp" hparams.scheduled_sampling_max_prob = 1.0 hparams.scheduled_sampling_decay_steps = 10000 return hparams
python
def next_frame_sampling(): """Basic conv model with scheduled sampling.""" hparams = next_frame_basic_deterministic() hparams.scheduled_sampling_mode = "prob_inverse_exp" hparams.scheduled_sampling_max_prob = 1.0 hparams.scheduled_sampling_decay_steps = 10000 return hparams
[ "def", "next_frame_sampling", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "scheduled_sampling_mode", "=", "\"prob_inverse_exp\"", "hparams", ".", "scheduled_sampling_max_prob", "=", "1.0", "hparams", ".", "scheduled_sampling_...
Basic conv model with scheduled sampling.
[ "Basic", "conv", "model", "with", "scheduled", "sampling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L79-L85
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_ae
def next_frame_ae(): """Conv autoencoder.""" hparams = next_frame_basic_deterministic() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.hidden_size = 256 hparams.batch_size = 8 hparams.num_hidden_layers = 4 hparams.num_compress_steps = 4 ...
python
def next_frame_ae(): """Conv autoencoder.""" hparams = next_frame_basic_deterministic() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.hidden_size = 256 hparams.batch_size = 8 hparams.num_hidden_layers = 4 hparams.num_compress_steps = 4 ...
[ "def", "next_frame_ae", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "bottom", "[", "\"inputs\"", "]", "=", "modalities", ".", "video_bitwise_bottom", "hparams", ".", "top", "[", "\"inputs\"", "]", "=", "modalities",...
Conv autoencoder.
[ "Conv", "autoencoder", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L96-L106
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_ae_tiny
def next_frame_ae_tiny(): """Conv autoencoder, tiny set for testing.""" hparams = next_frame_tiny() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.batch_size = 8 hparams.dropout = 0.4 return hparams
python
def next_frame_ae_tiny(): """Conv autoencoder, tiny set for testing.""" hparams = next_frame_tiny() hparams.bottom["inputs"] = modalities.video_bitwise_bottom hparams.top["inputs"] = modalities.video_top hparams.batch_size = 8 hparams.dropout = 0.4 return hparams
[ "def", "next_frame_ae_tiny", "(", ")", ":", "hparams", "=", "next_frame_tiny", "(", ")", "hparams", ".", "bottom", "[", "\"inputs\"", "]", "=", "modalities", ".", "video_bitwise_bottom", "hparams", ".", "top", "[", "\"inputs\"", "]", "=", "modalities", ".", ...
Conv autoencoder, tiny set for testing.
[ "Conv", "autoencoder", "tiny", "set", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L110-L117
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_tiny
def next_frame_tiny(): """Tiny for testing.""" hparams = next_frame_basic_deterministic() hparams.hidden_size = 32 hparams.num_hidden_layers = 1 hparams.num_compress_steps = 2 hparams.filter_double_steps = 1 return hparams
python
def next_frame_tiny(): """Tiny for testing.""" hparams = next_frame_basic_deterministic() hparams.hidden_size = 32 hparams.num_hidden_layers = 1 hparams.num_compress_steps = 2 hparams.filter_double_steps = 1 return hparams
[ "def", "next_frame_tiny", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "hidden_size", "=", "32", "hparams", ".", "num_hidden_layers", "=", "1", "hparams", ".", "num_compress_steps", "=", "2", "hparams", ".", "filter_...
Tiny for testing.
[ "Tiny", "for", "testing", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L129-L136
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_l1
def next_frame_l1(): """Basic conv model with L1 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l1_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
python
def next_frame_l1(): """Basic conv model with L1 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l1_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
[ "def", "next_frame_l1", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "loss", "[", "\"targets\"", "]", "=", "modalities", ".", "video_l1_loss", "hparams", ".", "top", "[", "\"targets\"", "]", "=", "modalities", ".",...
Basic conv model with L1 modality.
[ "Basic", "conv", "model", "with", "L1", "modality", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L140-L146
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_l2
def next_frame_l2(): """Basic conv model with L2 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l2_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
python
def next_frame_l2(): """Basic conv model with L2 modality.""" hparams = next_frame_basic_deterministic() hparams.loss["targets"] = modalities.video_l2_loss hparams.top["targets"] = modalities.video_l1_top hparams.video_modality_loss_cutoff = 2.4 return hparams
[ "def", "next_frame_l2", "(", ")", ":", "hparams", "=", "next_frame_basic_deterministic", "(", ")", "hparams", ".", "loss", "[", "\"targets\"", "]", "=", "modalities", ".", "video_l2_loss", "hparams", ".", "top", "[", "\"targets\"", "]", "=", "modalities", ".",...
Basic conv model with L2 modality.
[ "Basic", "conv", "model", "with", "L2", "modality", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L150-L156
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_base_range
def next_frame_base_range(rhp): """Basic tuning grid.""" rhp.set_float("dropout", 0.2, 0.6) rhp.set_discrete("hidden_size", [64, 128, 256]) rhp.set_int("num_compress_steps", 5, 8) rhp.set_discrete("batch_size", [4, 8, 16, 32]) rhp.set_int("num_hidden_layers", 1, 3) rhp.set_int("filter_double_steps", 1, 6)...
python
def next_frame_base_range(rhp): """Basic tuning grid.""" rhp.set_float("dropout", 0.2, 0.6) rhp.set_discrete("hidden_size", [64, 128, 256]) rhp.set_int("num_compress_steps", 5, 8) rhp.set_discrete("batch_size", [4, 8, 16, 32]) rhp.set_int("num_hidden_layers", 1, 3) rhp.set_int("filter_double_steps", 1, 6)...
[ "def", "next_frame_base_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.2", ",", "0.6", ")", "rhp", ".", "set_discrete", "(", "\"hidden_size\"", ",", "[", "64", ",", "128", ",", "256", "]", ")", "rhp", ".", "set_int",...
Basic tuning grid.
[ "Basic", "tuning", "grid", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L160-L170
train
tensorflow/tensor2tensor
tensor2tensor/models/video/basic_deterministic_params.py
next_frame_ae_range
def next_frame_ae_range(rhp): """Autoencoder world model tuning grid.""" rhp.set_float("dropout", 0.3, 0.5) rhp.set_int("num_compress_steps", 1, 3) rhp.set_int("num_hidden_layers", 2, 6) rhp.set_float("learning_rate_constant", 1., 2.) rhp.set_float("initializer_gain", 0.8, 1.5) rhp.set_int("filter_double_...
python
def next_frame_ae_range(rhp): """Autoencoder world model tuning grid.""" rhp.set_float("dropout", 0.3, 0.5) rhp.set_int("num_compress_steps", 1, 3) rhp.set_int("num_hidden_layers", 2, 6) rhp.set_float("learning_rate_constant", 1., 2.) rhp.set_float("initializer_gain", 0.8, 1.5) rhp.set_int("filter_double_...
[ "def", "next_frame_ae_range", "(", "rhp", ")", ":", "rhp", ".", "set_float", "(", "\"dropout\"", ",", "0.3", ",", "0.5", ")", "rhp", ".", "set_int", "(", "\"num_compress_steps\"", ",", "1", ",", "3", ")", "rhp", ".", "set_int", "(", "\"num_hidden_layers\""...
Autoencoder world model tuning grid.
[ "Autoencoder", "world", "model", "tuning", "grid", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/basic_deterministic_params.py#L194-L201
train
tensorflow/tensor2tensor
tensor2tensor/models/research/multiquery_paper.py
mqp_lm1b_base
def mqp_lm1b_base(): """Series of architectures for language modeling.""" hparams = mtf_transformer2.mtf_unitransformer_base() hparams.d_model = 1024 hparams.max_length = 256 hparams.batch_size = 256 # Parameters for my_layer_stack() hparams.num_hidden_layers = 6 hparams.d_ff = 8192 hparams.d_kv = 128...
python
def mqp_lm1b_base(): """Series of architectures for language modeling.""" hparams = mtf_transformer2.mtf_unitransformer_base() hparams.d_model = 1024 hparams.max_length = 256 hparams.batch_size = 256 # Parameters for my_layer_stack() hparams.num_hidden_layers = 6 hparams.d_ff = 8192 hparams.d_kv = 128...
[ "def", "mqp_lm1b_base", "(", ")", ":", "hparams", "=", "mtf_transformer2", ".", "mtf_unitransformer_base", "(", ")", "hparams", ".", "d_model", "=", "1024", "hparams", ".", "max_length", "=", "256", "hparams", ".", "batch_size", "=", "256", "# Parameters for my_...
Series of architectures for language modeling.
[ "Series", "of", "architectures", "for", "language", "modeling", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/multiquery_paper.py#L154-L168
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_free.py
initialize_env_specs
def initialize_env_specs(hparams, env_problem_name): """Initializes env_specs using the appropriate env.""" if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval...
python
def initialize_env_specs(hparams, env_problem_name): """Initializes env_specs using the appropriate env.""" if env_problem_name: env = registry.env_problem(env_problem_name, batch_size=hparams.batch_size) else: env = rl_utils.setup_env(hparams, hparams.batch_size, hparams.eval...
[ "def", "initialize_env_specs", "(", "hparams", ",", "env_problem_name", ")", ":", "if", "env_problem_name", ":", "env", "=", "registry", ".", "env_problem", "(", "env_problem_name", ",", "batch_size", "=", "hparams", ".", "batch_size", ")", "else", ":", "env", ...
Initializes env_specs using the appropriate env.
[ "Initializes", "env_specs", "using", "the", "appropriate", "env", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_free.py#L68-L79
train
tensorflow/tensor2tensor
tensor2tensor/rl/trainer_model_free.py
train
def train(hparams, output_dir, env_problem_name, report_fn=None): """Train.""" env_fn = initialize_env_specs(hparams, env_problem_name) tf.logging.vlog(1, "HParams in trainer_model_free.train : %s", misc_utils.pprint_hparams(hparams)) tf.logging.vlog(1, "Using hparams.base_algo: %s", hparams....
python
def train(hparams, output_dir, env_problem_name, report_fn=None): """Train.""" env_fn = initialize_env_specs(hparams, env_problem_name) tf.logging.vlog(1, "HParams in trainer_model_free.train : %s", misc_utils.pprint_hparams(hparams)) tf.logging.vlog(1, "Using hparams.base_algo: %s", hparams....
[ "def", "train", "(", "hparams", ",", "output_dir", ",", "env_problem_name", ",", "report_fn", "=", "None", ")", ":", "env_fn", "=", "initialize_env_specs", "(", "hparams", ",", "env_problem_name", ")", "tf", ".", "logging", ".", "vlog", "(", "1", ",", "\"H...
Train.
[ "Train", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/trainer_model_free.py#L85-L153
train
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
learning_rate_factor
def learning_rate_factor(name, step_num, hparams): """Compute the designated learning rate factor from hparams.""" if name == "constant": tf.logging.info("Base learning rate: %f", hparams.learning_rate_constant) return hparams.learning_rate_constant elif name == "linear_warmup": return tf.minimum(1.0,...
python
def learning_rate_factor(name, step_num, hparams): """Compute the designated learning rate factor from hparams.""" if name == "constant": tf.logging.info("Base learning rate: %f", hparams.learning_rate_constant) return hparams.learning_rate_constant elif name == "linear_warmup": return tf.minimum(1.0,...
[ "def", "learning_rate_factor", "(", "name", ",", "step_num", ",", "hparams", ")", ":", "if", "name", "==", "\"constant\"", ":", "tf", ".", "logging", ".", "info", "(", "\"Base learning rate: %f\"", ",", "hparams", ".", "learning_rate_constant", ")", "return", ...
Compute the designated learning rate factor from hparams.
[ "Compute", "the", "designated", "learning", "rate", "factor", "from", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L26-L69
train
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
learning_rate_schedule
def learning_rate_schedule(hparams): """Learning rate schedule based on hparams.""" mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True) mlperf_log.transformer_print( key=mlperf_log.OPT_LR_WARMUP_STEPS, value=hparams.learning_rate_warmup_steps) step_num = _global_step(hparams) schedu...
python
def learning_rate_schedule(hparams): """Learning rate schedule based on hparams.""" mlperf_log.transformer_print(key=mlperf_log.OPT_LR, deferred=True) mlperf_log.transformer_print( key=mlperf_log.OPT_LR_WARMUP_STEPS, value=hparams.learning_rate_warmup_steps) step_num = _global_step(hparams) schedu...
[ "def", "learning_rate_schedule", "(", "hparams", ")", ":", "mlperf_log", ".", "transformer_print", "(", "key", "=", "mlperf_log", ".", "OPT_LR", ",", "deferred", "=", "True", ")", "mlperf_log", ".", "transformer_print", "(", "key", "=", "mlperf_log", ".", "OPT...
Learning rate schedule based on hparams.
[ "Learning", "rate", "schedule", "based", "on", "hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L72-L85
train
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
legacy_learning_rate_schedule
def legacy_learning_rate_schedule(hparams): """Backwards-compatible learning-rate schedule.""" step_num = _global_step(hparams) warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps) if hparams.learning_rate_decay_scheme == "noam": ret = 5000.0 * hparams.hidden_size**-0.5 * tf.minimum( (step...
python
def legacy_learning_rate_schedule(hparams): """Backwards-compatible learning-rate schedule.""" step_num = _global_step(hparams) warmup_steps = tf.to_float(hparams.learning_rate_warmup_steps) if hparams.learning_rate_decay_scheme == "noam": ret = 5000.0 * hparams.hidden_size**-0.5 * tf.minimum( (step...
[ "def", "legacy_learning_rate_schedule", "(", "hparams", ")", ":", "step_num", "=", "_global_step", "(", "hparams", ")", "warmup_steps", "=", "tf", ".", "to_float", "(", "hparams", ".", "learning_rate_warmup_steps", ")", "if", "hparams", ".", "learning_rate_decay_sch...
Backwards-compatible learning-rate schedule.
[ "Backwards", "-", "compatible", "learning", "-", "rate", "schedule", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L88-L102
train
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_global_step
def _global_step(hparams): """Adjust global step if a multi-step optimizer is used.""" step = tf.to_float(tf.train.get_or_create_global_step()) multiplier = hparams.optimizer_multistep_accumulate_steps if not multiplier: return step tf.logging.info("Dividing global step by %d for multi-step optimizer." ...
python
def _global_step(hparams): """Adjust global step if a multi-step optimizer is used.""" step = tf.to_float(tf.train.get_or_create_global_step()) multiplier = hparams.optimizer_multistep_accumulate_steps if not multiplier: return step tf.logging.info("Dividing global step by %d for multi-step optimizer." ...
[ "def", "_global_step", "(", "hparams", ")", ":", "step", "=", "tf", ".", "to_float", "(", "tf", ".", "train", ".", "get_or_create_global_step", "(", ")", ")", "multiplier", "=", "hparams", ".", "optimizer_multistep_accumulate_steps", "if", "not", "multiplier", ...
Adjust global step if a multi-step optimizer is used.
[ "Adjust", "global", "step", "if", "a", "multi", "-", "step", "optimizer", "is", "used", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L105-L114
train
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_piecewise_learning_rate
def _piecewise_learning_rate(step, boundaries, values): """Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value fo...
python
def _piecewise_learning_rate(step, boundaries, values): """Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value fo...
[ "def", "_piecewise_learning_rate", "(", "step", ",", "boundaries", ",", "values", ")", ":", "values", "=", "[", "1.0", "]", "+", "values", "boundaries", "=", "[", "float", "(", "x", ")", "for", "x", "in", "boundaries", "]", "return", "tf", ".", "train"...
Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value for the learning rate.
[ "Scale", "learning", "rate", "according", "to", "the", "given", "schedule", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L122-L138
train
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_learning_rate_decay
def _learning_rate_decay(hparams, warmup_steps=0): """Learning rate decay multiplier.""" scheme = hparams.learning_rate_decay_scheme warmup_steps = tf.to_float(warmup_steps) global_step = _global_step(hparams) if not scheme or scheme == "none": return tf.constant(1.) tf.logging.info("Applying learning...
python
def _learning_rate_decay(hparams, warmup_steps=0): """Learning rate decay multiplier.""" scheme = hparams.learning_rate_decay_scheme warmup_steps = tf.to_float(warmup_steps) global_step = _global_step(hparams) if not scheme or scheme == "none": return tf.constant(1.) tf.logging.info("Applying learning...
[ "def", "_learning_rate_decay", "(", "hparams", ",", "warmup_steps", "=", "0", ")", ":", "scheme", "=", "hparams", ".", "learning_rate_decay_scheme", "warmup_steps", "=", "tf", ".", "to_float", "(", "warmup_steps", ")", "global_step", "=", "_global_step", "(", "h...
Learning rate decay multiplier.
[ "Learning", "rate", "decay", "multiplier", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L141-L183
train
tensorflow/tensor2tensor
tensor2tensor/utils/learning_rate.py
_learning_rate_warmup
def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None): """Learning rate warmup multiplier.""" if not warmup_steps: return tf.constant(1.) tf.logging.info("Applying %s learning rate warmup for %d steps", warmup_schedule, warmup_steps) warmup_steps = tf.to_float(warm...
python
def _learning_rate_warmup(warmup_steps, warmup_schedule="exp", hparams=None): """Learning rate warmup multiplier.""" if not warmup_steps: return tf.constant(1.) tf.logging.info("Applying %s learning rate warmup for %d steps", warmup_schedule, warmup_steps) warmup_steps = tf.to_float(warm...
[ "def", "_learning_rate_warmup", "(", "warmup_steps", ",", "warmup_schedule", "=", "\"exp\"", ",", "hparams", "=", "None", ")", ":", "if", "not", "warmup_steps", ":", "return", "tf", ".", "constant", "(", "1.", ")", "tf", ".", "logging", ".", "info", "(", ...
Learning rate warmup multiplier.
[ "Learning", "rate", "warmup", "multiplier", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/utils/learning_rate.py#L186-L202
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
is_in_expr
def is_in_expr(expr, find): """Returns True if `find` is a subtree of `expr`.""" return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find))
python
def is_in_expr(expr, find): """Returns True if `find` is a subtree of `expr`.""" return expr == find or (isinstance(expr, ExprNode) and expr.is_in(find))
[ "def", "is_in_expr", "(", "expr", ",", "find", ")", ":", "return", "expr", "==", "find", "or", "(", "isinstance", "(", "expr", ",", "ExprNode", ")", "and", "expr", ".", "is_in", "(", "find", ")", ")" ]
Returns True if `find` is a subtree of `expr`.
[ "Returns", "True", "if", "find", "is", "a", "subtree", "of", "expr", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L90-L92
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
random_expr_with_required_var
def random_expr_with_required_var(depth, required_var, optional_list, ops): """Generate a random expression tree with a required variable. The required variable appears exactly once in the expression. Args: depth: At least one leaf will be this many levels down from the top. required_var: A char. This c...
python
def random_expr_with_required_var(depth, required_var, optional_list, ops): """Generate a random expression tree with a required variable. The required variable appears exactly once in the expression. Args: depth: At least one leaf will be this many levels down from the top. required_var: A char. This c...
[ "def", "random_expr_with_required_var", "(", "depth", ",", "required_var", ",", "optional_list", ",", "ops", ")", ":", "if", "not", "depth", ":", "if", "required_var", ":", "return", "required_var", "return", "str", "(", "optional_list", "[", "random", ".", "r...
Generate a random expression tree with a required variable. The required variable appears exactly once in the expression. Args: depth: At least one leaf will be this many levels down from the top. required_var: A char. This char is guaranteed to be placed exactly once at a leaf somewhere in the tr...
[ "Generate", "a", "random", "expression", "tree", "with", "a", "required", "variable", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L95-L129
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
random_expr
def random_expr(depth, vlist, ops): """Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is t...
python
def random_expr(depth, vlist, ops): """Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is t...
[ "def", "random_expr", "(", "depth", ",", "vlist", ",", "ops", ")", ":", "if", "not", "depth", ":", "return", "str", "(", "vlist", "[", "random", ".", "randrange", "(", "len", "(", "vlist", ")", ")", "]", ")", "max_depth_side", "=", "random", ".", "...
Generate a random expression tree. Args: depth: At least one leaf will be this many levels down from the top. vlist: A list of chars. These chars are randomly selected as leaf values. ops: A list of ExprOp instances. Returns: An ExprNode instance which is the root of the generated expression tree.
[ "Generate", "a", "random", "expression", "tree", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L132-L155
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
algebra_inverse_solve
def algebra_inverse_solve(left, right, var, solve_ops): """Solves for the value of the given var in an expression. Args: left: The root of the ExprNode tree on the left side of the equals sign. right: The root of the ExprNode tree on the right side of the equals sign. var: A char. The variable to solve...
python
def algebra_inverse_solve(left, right, var, solve_ops): """Solves for the value of the given var in an expression. Args: left: The root of the ExprNode tree on the left side of the equals sign. right: The root of the ExprNode tree on the right side of the equals sign. var: A char. The variable to solve...
[ "def", "algebra_inverse_solve", "(", "left", ",", "right", ",", "var", ",", "solve_ops", ")", ":", "is_in_left", "=", "is_in_expr", "(", "left", ",", "var", ")", "is_in_right", "=", "is_in_expr", "(", "right", ",", "var", ")", "if", "is_in_left", "==", "...
Solves for the value of the given var in an expression. Args: left: The root of the ExprNode tree on the left side of the equals sign. right: The root of the ExprNode tree on the right side of the equals sign. var: A char. The variable to solve for. solve_ops: A dictionary with the following properti...
[ "Solves", "for", "the", "value", "of", "the", "given", "var", "in", "an", "expression", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L158-L211
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
format_sympy_expr
def format_sympy_expr(sympy_expr, functions=None): """Convert sympy expression into a string which can be encoded. Args: sympy_expr: Any sympy expression tree or string. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to singl...
python
def format_sympy_expr(sympy_expr, functions=None): """Convert sympy expression into a string which can be encoded. Args: sympy_expr: Any sympy expression tree or string. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to singl...
[ "def", "format_sympy_expr", "(", "sympy_expr", ",", "functions", "=", "None", ")", ":", "if", "functions", "is", "None", ":", "functions", "=", "{", "}", "str_expr", "=", "str", "(", "sympy_expr", ")", "result", "=", "str_expr", ".", "replace", "(", "\" ...
Convert sympy expression into a string which can be encoded. Args: sympy_expr: Any sympy expression tree or string. functions: Defines special functions. A dict mapping human readable string names, like "log", "exp", "sin", "cos", etc., to single chars. Each function gets a unique token, like...
[ "Convert", "sympy", "expression", "into", "a", "string", "which", "can", "be", "encoded", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L214-L233
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
generate_algebra_inverse_sample
def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth, max_depth): """Randomly generate an algebra inverse dataset sample. Given an input equation and variable, produce the expression equal to the variable. Args: vlist: Variable list. List of chars that c...
python
def generate_algebra_inverse_sample(vlist, ops, solve_ops, min_depth, max_depth): """Randomly generate an algebra inverse dataset sample. Given an input equation and variable, produce the expression equal to the variable. Args: vlist: Variable list. List of chars that c...
[ "def", "generate_algebra_inverse_sample", "(", "vlist", ",", "ops", ",", "solve_ops", ",", "min_depth", ",", "max_depth", ")", ":", "side", "=", "random", ".", "randrange", "(", "2", ")", "left_depth", "=", "random", ".", "randrange", "(", "min_depth", "if",...
Randomly generate an algebra inverse dataset sample. Given an input equation and variable, produce the expression equal to the variable. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. solve_ops: S...
[ "Randomly", "generate", "an", "algebra", "inverse", "dataset", "sample", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L236-L274
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
generate_algebra_simplify_sample
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The ...
python
def generate_algebra_simplify_sample(vlist, ops, min_depth, max_depth): """Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The ...
[ "def", "generate_algebra_simplify_sample", "(", "vlist", ",", "ops", ",", "min_depth", ",", "max_depth", ")", ":", "depth", "=", "random", ".", "randrange", "(", "min_depth", ",", "max_depth", "+", "1", ")", "expr", "=", "random_expr", "(", "depth", ",", "...
Randomly generate an algebra simplify dataset sample. Given an input expression, produce the simplified expression. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will no...
[ "Randomly", "generate", "an", "algebra", "simplify", "dataset", "sample", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L277-L299
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
generate_calculus_integrate_sample
def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth, functions): """Randomly generate a symbolic integral dataset sample. Given an input expression, produce the indefinite integral. Args: vlist: Variable list. List of chars that can be used in the e...
python
def generate_calculus_integrate_sample(vlist, ops, min_depth, max_depth, functions): """Randomly generate a symbolic integral dataset sample. Given an input expression, produce the indefinite integral. Args: vlist: Variable list. List of chars that can be used in the e...
[ "def", "generate_calculus_integrate_sample", "(", "vlist", ",", "ops", ",", "min_depth", ",", "max_depth", ",", "functions", ")", ":", "var_index", "=", "random", ".", "randrange", "(", "len", "(", "vlist", ")", ")", "var", "=", "vlist", "[", "var_index", ...
Randomly generate a symbolic integral dataset sample. Given an input expression, produce the indefinite integral. Args: vlist: Variable list. List of chars that can be used in the expression. ops: List of ExprOp instances. The allowed operators for the expression. min_depth: Expression trees will not ...
[ "Randomly", "generate", "a", "symbolic", "integral", "dataset", "sample", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L302-L335
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
math_dataset_init
def math_dataset_init(alphabet_size=26, digits=None, functions=None): """Initializes required objects to generate symbolic math datasets. Produces token set, ExprOp instances, solve_op dictionary, encoders, and decoders needed to generate the algebra inverse dataset. Args: alphabet_size: How many possible...
python
def math_dataset_init(alphabet_size=26, digits=None, functions=None): """Initializes required objects to generate symbolic math datasets. Produces token set, ExprOp instances, solve_op dictionary, encoders, and decoders needed to generate the algebra inverse dataset. Args: alphabet_size: How many possible...
[ "def", "math_dataset_init", "(", "alphabet_size", "=", "26", ",", "digits", "=", "None", ",", "functions", "=", "None", ")", ":", "ops_list", "=", "[", "\"+\"", ",", "\"-\"", ",", "\"*\"", ",", "\"/\"", "]", "ops", "=", "{", "\"+\"", ":", "ExprOp", "...
Initializes required objects to generate symbolic math datasets. Produces token set, ExprOp instances, solve_op dictionary, encoders, and decoders needed to generate the algebra inverse dataset. Args: alphabet_size: How many possible variables there are. Max 52. digits: How many numerical digits to enco...
[ "Initializes", "required", "objects", "to", "generate", "symbolic", "math", "datasets", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L358-L436
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
algebra_inverse
def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra inverse dataset. Each sample is a symbolic math equation involving unknown variables. The task is to solve for the given variable. The target is the resulting expression. Args: a...
python
def algebra_inverse(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra inverse dataset. Each sample is a symbolic math equation involving unknown variables. The task is to solve for the given variable. The target is the resulting expression. Args: a...
[ "def", "algebra_inverse", "(", "alphabet_size", "=", "26", ",", "min_depth", "=", "0", ",", "max_depth", "=", "2", ",", "nbr_cases", "=", "10000", ")", ":", "if", "max_depth", "<", "min_depth", ":", "raise", "ValueError", "(", "\"max_depth must be greater than...
Generate the algebra inverse dataset. Each sample is a symbolic math equation involving unknown variables. The task is to solve for the given variable. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 52. min_depth: Minimum depth of the expression...
[ "Generate", "the", "algebra", "inverse", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L439-L477
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
algebra_simplify
def algebra_simplify(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra simplify dataset. Each sample is a symbolic math expression involving unknown variables. The task is to simplify the expression. The target is ...
python
def algebra_simplify(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the algebra simplify dataset. Each sample is a symbolic math expression involving unknown variables. The task is to simplify the expression. The target is ...
[ "def", "algebra_simplify", "(", "alphabet_size", "=", "26", ",", "min_depth", "=", "0", ",", "max_depth", "=", "2", ",", "nbr_cases", "=", "10000", ")", ":", "if", "max_depth", "<", "min_depth", ":", "raise", "ValueError", "(", "\"max_depth must be greater tha...
Generate the algebra simplify dataset. Each sample is a symbolic math expression involving unknown variables. The task is to simplify the expression. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 52. min_depth: Minimum depth of the expression tre...
[ "Generate", "the", "algebra", "simplify", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L480-L517
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
calculus_integrate
def calculus_integrate(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the calculus integrate dataset. Each sample is a symbolic math expression involving unknown variables. The task is to take the indefinite integral ...
python
def calculus_integrate(alphabet_size=26, min_depth=0, max_depth=2, nbr_cases=10000): """Generate the calculus integrate dataset. Each sample is a symbolic math expression involving unknown variables. The task is to take the indefinite integral ...
[ "def", "calculus_integrate", "(", "alphabet_size", "=", "26", ",", "min_depth", "=", "0", ",", "max_depth", "=", "2", ",", "nbr_cases", "=", "10000", ")", ":", "if", "max_depth", "<", "min_depth", ":", "raise", "ValueError", "(", "\"max_depth must be greater t...
Generate the calculus integrate dataset. Each sample is a symbolic math expression involving unknown variables. The task is to take the indefinite integral of the expression. The target is the resulting expression. Args: alphabet_size: How many possible variables there are. Max 26. min_depth: Minimum ...
[ "Generate", "the", "calculus", "integrate", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L520-L573
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/algorithmic_math.py
ExprNode.is_in
def is_in(self, expr): """Returns True if `expr` is a subtree.""" if expr == self: return True is_in_left = is_in_expr(self.left, expr) is_in_right = is_in_expr(self.right, expr) return is_in_left or is_in_right
python
def is_in(self, expr): """Returns True if `expr` is a subtree.""" if expr == self: return True is_in_left = is_in_expr(self.left, expr) is_in_right = is_in_expr(self.right, expr) return is_in_left or is_in_right
[ "def", "is_in", "(", "self", ",", "expr", ")", ":", "if", "expr", "==", "self", ":", "return", "True", "is_in_left", "=", "is_in_expr", "(", "self", ".", "left", ",", "expr", ")", "is_in_right", "=", "is_in_expr", "(", "self", ".", "right", ",", "exp...
Returns True if `expr` is a subtree.
[ "Returns", "True", "if", "expr", "is", "a", "subtree", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/algorithmic_math.py#L81-L87
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
preprocess_example_common
def preprocess_example_common(example, mode, hparams): """Preprocessing steps common to all models.""" if "inputs" in example and hparams.max_input_seq_length > 0: example["inputs"] = example["inputs"][:hparams.max_input_seq_length] if hparams.prepend_mode != "none": if mode == tf.estimator.ModeKeys.PREDI...
python
def preprocess_example_common(example, mode, hparams): """Preprocessing steps common to all models.""" if "inputs" in example and hparams.max_input_seq_length > 0: example["inputs"] = example["inputs"][:hparams.max_input_seq_length] if hparams.prepend_mode != "none": if mode == tf.estimator.ModeKeys.PREDI...
[ "def", "preprocess_example_common", "(", "example", ",", "mode", ",", "hparams", ")", ":", "if", "\"inputs\"", "in", "example", "and", "hparams", ".", "max_input_seq_length", ">", "0", ":", "example", "[", "\"inputs\"", "]", "=", "example", "[", "\"inputs\"", ...
Preprocessing steps common to all models.
[ "Preprocessing", "steps", "common", "to", "all", "models", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L142-L162
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
_copy_problem_hparams
def _copy_problem_hparams(p_hparams): """Use input modality, vocab, and space id for target.""" p = p_hparams # Duplicate input modality. p.modality["targets"] = p.modality["inputs"] # Duplicate input vocab size. p.vocab_size["targets"] = p.vocab_size["inputs"] # Duplicate input vocabulary. p.vocabulary...
python
def _copy_problem_hparams(p_hparams): """Use input modality, vocab, and space id for target.""" p = p_hparams # Duplicate input modality. p.modality["targets"] = p.modality["inputs"] # Duplicate input vocab size. p.vocab_size["targets"] = p.vocab_size["inputs"] # Duplicate input vocabulary. p.vocabulary...
[ "def", "_copy_problem_hparams", "(", "p_hparams", ")", ":", "p", "=", "p_hparams", "# Duplicate input modality.", "p", ".", "modality", "[", "\"targets\"", "]", "=", "p", ".", "modality", "[", "\"inputs\"", "]", "# Duplicate input vocab size.", "p", ".", "vocab_si...
Use input modality, vocab, and space id for target.
[ "Use", "input", "modality", "vocab", "and", "space", "id", "for", "target", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L947-L959
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
_reverse_problem_hparams
def _reverse_problem_hparams(p_hparams): """Swap input/output modalities, vocab, and space ids.""" p = p_hparams # Swap modalities. # TODO(trandustin): Note this assumes target modalities have feature name # 'target', and each intended feature to swap has feature name 'input'. # In the future, remove need ...
python
def _reverse_problem_hparams(p_hparams): """Swap input/output modalities, vocab, and space ids.""" p = p_hparams # Swap modalities. # TODO(trandustin): Note this assumes target modalities have feature name # 'target', and each intended feature to swap has feature name 'input'. # In the future, remove need ...
[ "def", "_reverse_problem_hparams", "(", "p_hparams", ")", ":", "p", "=", "p_hparams", "# Swap modalities.", "# TODO(trandustin): Note this assumes target modalities have feature name", "# 'target', and each intended feature to swap has feature name 'input'.", "# In the future, remove need fo...
Swap input/output modalities, vocab, and space ids.
[ "Swap", "input", "/", "output", "modalities", "vocab", "and", "space", "ids", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L962-L1014
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
_default_hparams
def _default_hparams(): """A set of basic model hyperparameters.""" return hparam.HParams( # Use this parameter to get comparable perplexity numbers with different # tokenizations. This value should be set to the ratio of the number of # tokens in the test set according to the tokenization used t...
python
def _default_hparams(): """A set of basic model hyperparameters.""" return hparam.HParams( # Use this parameter to get comparable perplexity numbers with different # tokenizations. This value should be set to the ratio of the number of # tokens in the test set according to the tokenization used t...
[ "def", "_default_hparams", "(", ")", ":", "return", "hparam", ".", "HParams", "(", "# Use this parameter to get comparable perplexity numbers with different", "# tokenizations. This value should be set to the ratio of the number of", "# tokens in the test set according to the tokenization u...
A set of basic model hyperparameters.
[ "A", "set", "of", "basic", "model", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L1017-L1050
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.tpu_batch_size_per_shard
def tpu_batch_size_per_shard(self, model_hparams): """Batch size in examples per TPU core. Args: model_hparams: model hyperparameters Returns: an integer """ if self.batch_size_means_tokens and not model_hparams.use_fixed_batch_size: return model_hparams.batch_size // self.max_len...
python
def tpu_batch_size_per_shard(self, model_hparams): """Batch size in examples per TPU core. Args: model_hparams: model hyperparameters Returns: an integer """ if self.batch_size_means_tokens and not model_hparams.use_fixed_batch_size: return model_hparams.batch_size // self.max_len...
[ "def", "tpu_batch_size_per_shard", "(", "self", ",", "model_hparams", ")", ":", "if", "self", ".", "batch_size_means_tokens", "and", "not", "model_hparams", ".", "use_fixed_batch_size", ":", "return", "model_hparams", ".", "batch_size", "//", "self", ".", "max_lengt...
Batch size in examples per TPU core. Args: model_hparams: model hyperparameters Returns: an integer
[ "Batch", "size", "in", "examples", "per", "TPU", "core", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L272-L283
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.preprocess
def preprocess(self, dataset, mode, hparams, interleave=True): """Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preproc...
python
def preprocess(self, dataset, mode, hparams, interleave=True): """Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preproc...
[ "def", "preprocess", "(", "self", ",", "dataset", ",", "mode", ",", "hparams", ",", "interleave", "=", "True", ")", ":", "def", "_preprocess", "(", "example", ")", ":", "examples", "=", "self", ".", "preprocess_example", "(", "example", ",", "mode", ",",...
Runtime preprocessing on the whole dataset. Return a tf.data.Datset -- the preprocessed version of the given one. By default this function calls preprocess_example. Args: dataset: the Dataset of already decoded but not yet preprocessed features. mode: tf.estimator.ModeKeys hparams: HPara...
[ "Runtime", "preprocessing", "on", "the", "whole", "dataset", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L395-L425
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.filepattern
def filepattern(self, data_dir, mode, shard=None): """Get filepattern for data files for mode. Matches mode to a suffix. * DatasetSplit.TRAIN: train * DatasetSplit.EVAL: dev * DatasetSplit.TEST: test * tf.estimator.ModeKeys.PREDICT: dev Args: data_dir: str, data directory. mode...
python
def filepattern(self, data_dir, mode, shard=None): """Get filepattern for data files for mode. Matches mode to a suffix. * DatasetSplit.TRAIN: train * DatasetSplit.EVAL: dev * DatasetSplit.TEST: test * tf.estimator.ModeKeys.PREDICT: dev Args: data_dir: str, data directory. mode...
[ "def", "filepattern", "(", "self", ",", "data_dir", ",", "mode", ",", "shard", "=", "None", ")", ":", "path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "self", ".", "dataset_filename", "(", ")", ")", "shard_str", "=", "\"-%05d\"", "%...
Get filepattern for data files for mode. Matches mode to a suffix. * DatasetSplit.TRAIN: train * DatasetSplit.EVAL: dev * DatasetSplit.TEST: test * tf.estimator.ModeKeys.PREDICT: dev Args: data_dir: str, data directory. mode: DatasetSplit shard: int, if provided, will only re...
[ "Get", "filepattern", "for", "data", "files", "for", "mode", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L458-L485
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.get_hparams
def get_hparams(self, model_hparams=None): """Returns problem_hparams.""" if self._hparams is not None: return self._hparams if model_hparams is None: model_hparams = default_model_hparams() if self._encoders is None: data_dir = (model_hparams and hasattr(model_hparams, "data_dir") a...
python
def get_hparams(self, model_hparams=None): """Returns problem_hparams.""" if self._hparams is not None: return self._hparams if model_hparams is None: model_hparams = default_model_hparams() if self._encoders is None: data_dir = (model_hparams and hasattr(model_hparams, "data_dir") a...
[ "def", "get_hparams", "(", "self", ",", "model_hparams", "=", "None", ")", ":", "if", "self", ".", "_hparams", "is", "not", "None", ":", "return", "self", ".", "_hparams", "if", "model_hparams", "is", "None", ":", "model_hparams", "=", "default_model_hparams...
Returns problem_hparams.
[ "Returns", "problem_hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L513-L542
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.maybe_reverse_features
def maybe_reverse_features(self, feature_map): """Reverse features between inputs and targets if the problem is '_rev'.""" if not self._was_reversed: return inputs = feature_map.pop("inputs", None) targets = feature_map.pop("targets", None) inputs_seg = feature_map.pop("inputs_segmentation", N...
python
def maybe_reverse_features(self, feature_map): """Reverse features between inputs and targets if the problem is '_rev'.""" if not self._was_reversed: return inputs = feature_map.pop("inputs", None) targets = feature_map.pop("targets", None) inputs_seg = feature_map.pop("inputs_segmentation", N...
[ "def", "maybe_reverse_features", "(", "self", ",", "feature_map", ")", ":", "if", "not", "self", ".", "_was_reversed", ":", "return", "inputs", "=", "feature_map", ".", "pop", "(", "\"inputs\"", ",", "None", ")", "targets", "=", "feature_map", ".", "pop", ...
Reverse features between inputs and targets if the problem is '_rev'.
[ "Reverse", "features", "between", "inputs", "and", "targets", "if", "the", "problem", "is", "_rev", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L544-L565
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.dataset
def dataset(self, mode, data_dir=None, num_threads=None, output_buffer_size=None, shuffle_files=None, hparams=None, preprocess=True, dataset_split=None, shard=None, partition_id=0,...
python
def dataset(self, mode, data_dir=None, num_threads=None, output_buffer_size=None, shuffle_files=None, hparams=None, preprocess=True, dataset_split=None, shard=None, partition_id=0,...
[ "def", "dataset", "(", "self", ",", "mode", ",", "data_dir", "=", "None", ",", "num_threads", "=", "None", ",", "output_buffer_size", "=", "None", ",", "shuffle_files", "=", "None", ",", "hparams", "=", "None", ",", "preprocess", "=", "True", ",", "datas...
Build a Dataset for this problem. Args: mode: tf.estimator.ModeKeys; determines which files to read from. data_dir: directory that contains data files. num_threads: int, number of threads to use for decode and preprocess Dataset.map calls. output_buffer_size: int, how many elements ...
[ "Build", "a", "Dataset", "for", "this", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L583-L698
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.decode_example
def decode_example(self, serialized_example): """Return a dict of Tensors from a serialized tensorflow.Example.""" data_fields, data_items_to_decoders = self.example_reading_spec() # Necessary to rejoin examples in the correct order with the Cloud ML Engine # batch prediction API. data_fields["batch...
python
def decode_example(self, serialized_example): """Return a dict of Tensors from a serialized tensorflow.Example.""" data_fields, data_items_to_decoders = self.example_reading_spec() # Necessary to rejoin examples in the correct order with the Cloud ML Engine # batch prediction API. data_fields["batch...
[ "def", "decode_example", "(", "self", ",", "serialized_example", ")", ":", "data_fields", ",", "data_items_to_decoders", "=", "self", ".", "example_reading_spec", "(", ")", "# Necessary to rejoin examples in the correct order with the Cloud ML Engine", "# batch prediction API.", ...
Return a dict of Tensors from a serialized tensorflow.Example.
[ "Return", "a", "dict", "of", "Tensors", "from", "a", "serialized", "tensorflow", ".", "Example", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L700-L717
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.feature_info
def feature_info(self): """Retrieve dict<feature name, FeatureInfo>. Must first call Problem.get_hparams or Problem.dataset to have the problem's internal hparams already constructed. Returns: dict<feature name, FeatureInfo> """ if self._feature_info is not None: return self._featu...
python
def feature_info(self): """Retrieve dict<feature name, FeatureInfo>. Must first call Problem.get_hparams or Problem.dataset to have the problem's internal hparams already constructed. Returns: dict<feature name, FeatureInfo> """ if self._feature_info is not None: return self._featu...
[ "def", "feature_info", "(", "self", ")", ":", "if", "self", ".", "_feature_info", "is", "not", "None", ":", "return", "self", ".", "_feature_info", "assert", "self", ".", "_hparams", "is", "not", "None", "hp", "=", "self", ".", "get_hparams", "(", ")", ...
Retrieve dict<feature name, FeatureInfo>. Must first call Problem.get_hparams or Problem.dataset to have the problem's internal hparams already constructed. Returns: dict<feature name, FeatureInfo>
[ "Retrieve", "dict<feature", "name", "FeatureInfo", ">", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L735-L769
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.make_estimator_input_fn
def make_estimator_input_fn(self, mode, hparams, data_dir=None, force_repeat=False, prevent_repeat=False, dataset_kwargs=None): """Retur...
python
def make_estimator_input_fn(self, mode, hparams, data_dir=None, force_repeat=False, prevent_repeat=False, dataset_kwargs=None): """Retur...
[ "def", "make_estimator_input_fn", "(", "self", ",", "mode", ",", "hparams", ",", "data_dir", "=", "None", ",", "force_repeat", "=", "False", ",", "prevent_repeat", "=", "False", ",", "dataset_kwargs", "=", "None", ")", ":", "def", "estimator_input_fn", "(", ...
Return input_fn wrapped for Estimator.
[ "Return", "input_fn", "wrapped", "for", "Estimator", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L771-L791
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem._dataset_partition
def _dataset_partition(self, mode, config, params): """Which part of the training data to read. If there are multiple parallel calls to input_fn (multiple TPU hosts), then we want each one to read from a separate partition of the training data. Args: mode: tf.estimator.ModeKeys config:...
python
def _dataset_partition(self, mode, config, params): """Which part of the training data to read. If there are multiple parallel calls to input_fn (multiple TPU hosts), then we want each one to read from a separate partition of the training data. Args: mode: tf.estimator.ModeKeys config:...
[ "def", "_dataset_partition", "(", "self", ",", "mode", ",", "config", ",", "params", ")", ":", "if", "mode", "!=", "tf", ".", "estimator", ".", "ModeKeys", ".", "TRAIN", "or", "not", "hasattr", "(", "config", ",", "\"tpu_config\"", ")", ":", "# Reset in ...
Which part of the training data to read. If there are multiple parallel calls to input_fn (multiple TPU hosts), then we want each one to read from a separate partition of the training data. Args: mode: tf.estimator.ModeKeys config: RunConfig params: A dict that contains parameters. ...
[ "Which", "part", "of", "the", "training", "data", "to", "read", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L793-L828
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.input_fn
def input_fn(self, mode, hparams, data_dir=None, params=None, config=None, force_repeat=False, prevent_repeat=False, dataset_kwargs=None): """Builds input pipeline for problem. Args: mo...
python
def input_fn(self, mode, hparams, data_dir=None, params=None, config=None, force_repeat=False, prevent_repeat=False, dataset_kwargs=None): """Builds input pipeline for problem. Args: mo...
[ "def", "input_fn", "(", "self", ",", "mode", ",", "hparams", ",", "data_dir", "=", "None", ",", "params", "=", "None", ",", "config", "=", "None", ",", "force_repeat", "=", "False", ",", "prevent_repeat", "=", "False", ",", "dataset_kwargs", "=", "None",...
Builds input pipeline for problem. Args: mode: tf.estimator.ModeKeys hparams: HParams, model hparams data_dir: str, data directory; if None, will use hparams.data_dir params: dict, may include "batch_size" config: RunConfig; should have the data_parallelism attribute if not using ...
[ "Builds", "input", "pipeline", "for", "problem", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L830-L886
train
tensorflow/tensor2tensor
tensor2tensor/data_generators/problem.py
Problem.serving_input_fn
def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False): """Input fn for serving export, starting from serialized example.""" mode = tf.estimator.ModeKeys.PREDICT serialized_example = tf.placeholder( dtype=tf.string, shape=[None], name="serialized_example") dataset = tf.data.Data...
python
def serving_input_fn(self, hparams, decode_hparams=None, use_tpu=False): """Input fn for serving export, starting from serialized example.""" mode = tf.estimator.ModeKeys.PREDICT serialized_example = tf.placeholder( dtype=tf.string, shape=[None], name="serialized_example") dataset = tf.data.Data...
[ "def", "serving_input_fn", "(", "self", ",", "hparams", ",", "decode_hparams", "=", "None", ",", "use_tpu", "=", "False", ")", ":", "mode", "=", "tf", ".", "estimator", ".", "ModeKeys", ".", "PREDICT", "serialized_example", "=", "tf", ".", "placeholder", "...
Input fn for serving export, starting from serialized example.
[ "Input", "fn", "for", "serving", "export", "starting", "from", "serialized", "example", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/data_generators/problem.py#L899-L930
train
tensorflow/tensor2tensor
tensor2tensor/serving/export.py
_get_hparams_path
def _get_hparams_path(): """Get hyper-parameters file path.""" hparams_path = None if FLAGS.output_dir: hparams_path = os.path.join(FLAGS.output_dir, "hparams.json") else: tf.logging.warning( "--output_dir not specified. Hyper-parameters will be infered from" "--hparams_set and --hparams...
python
def _get_hparams_path(): """Get hyper-parameters file path.""" hparams_path = None if FLAGS.output_dir: hparams_path = os.path.join(FLAGS.output_dir, "hparams.json") else: tf.logging.warning( "--output_dir not specified. Hyper-parameters will be infered from" "--hparams_set and --hparams...
[ "def", "_get_hparams_path", "(", ")", ":", "hparams_path", "=", "None", "if", "FLAGS", ".", "output_dir", ":", "hparams_path", "=", "os", ".", "path", ".", "join", "(", "FLAGS", ".", "output_dir", ",", "\"hparams.json\"", ")", "else", ":", "tf", ".", "lo...
Get hyper-parameters file path.
[ "Get", "hyper", "-", "parameters", "file", "path", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/export.py#L47-L57
train
tensorflow/tensor2tensor
tensor2tensor/serving/export.py
export_module_spec_with_checkpoint
def export_module_spec_with_checkpoint(module_spec, checkpoint_path, export_path, scope_prefix=""): """Exports given checkpoint as tfhub module with given spec.""" # The main requirement is that it ...
python
def export_module_spec_with_checkpoint(module_spec, checkpoint_path, export_path, scope_prefix=""): """Exports given checkpoint as tfhub module with given spec.""" # The main requirement is that it ...
[ "def", "export_module_spec_with_checkpoint", "(", "module_spec", ",", "checkpoint_path", ",", "export_path", ",", "scope_prefix", "=", "\"\"", ")", ":", "# The main requirement is that it is possible to know how to map from", "# module variable name to checkpoint variable name.", "# ...
Exports given checkpoint as tfhub module with given spec.
[ "Exports", "given", "checkpoint", "as", "tfhub", "module", "with", "given", "spec", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/export.py#L80-L100
train
tensorflow/tensor2tensor
tensor2tensor/serving/export.py
export_as_tfhub_module
def export_as_tfhub_module(model_name, hparams, decode_hparams, problem, checkpoint_path, export_dir): """Exports the last checkpoint from the directory as tfhub module. It creates...
python
def export_as_tfhub_module(model_name, hparams, decode_hparams, problem, checkpoint_path, export_dir): """Exports the last checkpoint from the directory as tfhub module. It creates...
[ "def", "export_as_tfhub_module", "(", "model_name", ",", "hparams", ",", "decode_hparams", ",", "problem", ",", "checkpoint_path", ",", "export_dir", ")", ":", "def", "hub_module_fn", "(", ")", ":", "\"\"\"Creates the TF graph for the hub module.\"\"\"", "model_fn", "="...
Exports the last checkpoint from the directory as tfhub module. It creates the Module spec and signature (based on T2T problem information), which is later used to create and export the hub module. Module will be saved inside the ckpt_dir. Args: model_name: name of the model to be exported. hparams: T...
[ "Exports", "the", "last", "checkpoint", "from", "the", "directory", "as", "tfhub", "module", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/serving/export.py#L103-L154
train
tensorflow/tensor2tensor
tensor2tensor/visualization/visualization.py
build_model
def build_model(hparams_set, model_name, data_dir, problem_name, beam_size=1): """Build the graph required to fetch the attention weights. Args: hparams_set: HParams set to build the model with. model_name: Name of model. data_dir: Path to directory containing training data. problem_name: Name of p...
python
def build_model(hparams_set, model_name, data_dir, problem_name, beam_size=1): """Build the graph required to fetch the attention weights. Args: hparams_set: HParams set to build the model with. model_name: Name of model. data_dir: Path to directory containing training data. problem_name: Name of p...
[ "def", "build_model", "(", "hparams_set", ",", "model_name", ",", "data_dir", ",", "problem_name", ",", "beam_size", "=", "1", ")", ":", "hparams", "=", "trainer_lib", ".", "create_hparams", "(", "hparams_set", ",", "data_dir", "=", "data_dir", ",", "problem_n...
Build the graph required to fetch the attention weights. Args: hparams_set: HParams set to build the model with. model_name: Name of model. data_dir: Path to directory containing training data. problem_name: Name of problem. beam_size: (Optional) Number of beams to use when decoding a translation...
[ "Build", "the", "graph", "required", "to", "fetch", "the", "attention", "weights", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/visualization.py#L113-L156
train
tensorflow/tensor2tensor
tensor2tensor/visualization/visualization.py
get_att_mats
def get_att_mats(translate_model): """Get's the tensors representing the attentions from a build model. The attentions are stored in a dict on the Transformer object while building the graph. Args: translate_model: Transformer object to fetch the attention weights from. Returns: Tuple of attention ma...
python
def get_att_mats(translate_model): """Get's the tensors representing the attentions from a build model. The attentions are stored in a dict on the Transformer object while building the graph. Args: translate_model: Transformer object to fetch the attention weights from. Returns: Tuple of attention ma...
[ "def", "get_att_mats", "(", "translate_model", ")", ":", "enc_atts", "=", "[", "]", "dec_atts", "=", "[", "]", "encdec_atts", "=", "[", "]", "prefix", "=", "\"transformer/body/\"", "postfix_self_attention", "=", "\"/multihead_attention/dot_product_attention\"", "if", ...
Get's the tensors representing the attentions from a build model. The attentions are stored in a dict on the Transformer object while building the graph. Args: translate_model: Transformer object to fetch the attention weights from. Returns: Tuple of attention matrices; ( enc_atts: Encoder self a...
[ "Get", "s", "the", "tensors", "representing", "the", "attentions", "from", "a", "build", "model", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/visualization.py#L159-L205
train
tensorflow/tensor2tensor
tensor2tensor/visualization/visualization.py
AttentionVisualizer.encode
def encode(self, input_str): """Input str to features dict, ready for inference.""" inputs = self.encoders["inputs"].encode(input_str) + [EOS_ID] batch_inputs = np.reshape(inputs, [1, -1, 1, 1]) # Make it 3D. return batch_inputs
python
def encode(self, input_str): """Input str to features dict, ready for inference.""" inputs = self.encoders["inputs"].encode(input_str) + [EOS_ID] batch_inputs = np.reshape(inputs, [1, -1, 1, 1]) # Make it 3D. return batch_inputs
[ "def", "encode", "(", "self", ",", "input_str", ")", ":", "inputs", "=", "self", ".", "encoders", "[", "\"inputs\"", "]", ".", "encode", "(", "input_str", ")", "+", "[", "EOS_ID", "]", "batch_inputs", "=", "np", ".", "reshape", "(", "inputs", ",", "[...
Input str to features dict, ready for inference.
[ "Input", "str", "to", "features", "dict", "ready", "for", "inference", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/visualization.py#L52-L56
train
tensorflow/tensor2tensor
tensor2tensor/visualization/visualization.py
AttentionVisualizer.decode
def decode(self, integers): """List of ints to str.""" integers = list(np.squeeze(integers)) return self.encoders["inputs"].decode(integers)
python
def decode(self, integers): """List of ints to str.""" integers = list(np.squeeze(integers)) return self.encoders["inputs"].decode(integers)
[ "def", "decode", "(", "self", ",", "integers", ")", ":", "integers", "=", "list", "(", "np", ".", "squeeze", "(", "integers", ")", ")", "return", "self", ".", "encoders", "[", "\"inputs\"", "]", ".", "decode", "(", "integers", ")" ]
List of ints to str.
[ "List", "of", "ints", "to", "str", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/visualization.py#L58-L61
train
tensorflow/tensor2tensor
tensor2tensor/visualization/visualization.py
AttentionVisualizer.decode_list
def decode_list(self, integers): """List of ints to list of str.""" integers = list(np.squeeze(integers)) return self.encoders["inputs"].decode_list(integers)
python
def decode_list(self, integers): """List of ints to list of str.""" integers = list(np.squeeze(integers)) return self.encoders["inputs"].decode_list(integers)
[ "def", "decode_list", "(", "self", ",", "integers", ")", ":", "integers", "=", "list", "(", "np", ".", "squeeze", "(", "integers", ")", ")", "return", "self", ".", "encoders", "[", "\"inputs\"", "]", ".", "decode_list", "(", "integers", ")" ]
List of ints to list of str.
[ "List", "of", "ints", "to", "list", "of", "str", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/visualization.py#L63-L66
train
tensorflow/tensor2tensor
tensor2tensor/visualization/visualization.py
AttentionVisualizer.get_vis_data_from_string
def get_vis_data_from_string(self, sess, input_string): """Constructs the data needed for visualizing attentions. Args: sess: A tf.Session object. input_string: The input sentence to be translated and visualized. Returns: Tuple of ( output_string: The translated sentence. ...
python
def get_vis_data_from_string(self, sess, input_string): """Constructs the data needed for visualizing attentions. Args: sess: A tf.Session object. input_string: The input sentence to be translated and visualized. Returns: Tuple of ( output_string: The translated sentence. ...
[ "def", "get_vis_data_from_string", "(", "self", ",", "sess", ",", "input_string", ")", ":", "encoded_inputs", "=", "self", ".", "encode", "(", "input_string", ")", "# Run inference graph to get the translation.", "out", "=", "sess", ".", "run", "(", "self", ".", ...
Constructs the data needed for visualizing attentions. Args: sess: A tf.Session object. input_string: The input sentence to be translated and visualized. Returns: Tuple of ( output_string: The translated sentence. input_list: Tokenized input sentence. output_lis...
[ "Constructs", "the", "data", "needed", "for", "visualizing", "attentions", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/visualization/visualization.py#L68-L110
train
tensorflow/tensor2tensor
tensor2tensor/models/research/glow.py
glow_hparams
def glow_hparams(): """Glow Hparams.""" hparams = common_hparams.basic_params1() hparams.clip_grad_norm = None hparams.weight_decay = 0.0 hparams.learning_rate_constant = 3e-4 hparams.batch_size = 32 # can be prev_level, prev_step or normal. # see: glow_ops.merge_level_and_latent_dist hparams.add_hpar...
python
def glow_hparams(): """Glow Hparams.""" hparams = common_hparams.basic_params1() hparams.clip_grad_norm = None hparams.weight_decay = 0.0 hparams.learning_rate_constant = 3e-4 hparams.batch_size = 32 # can be prev_level, prev_step or normal. # see: glow_ops.merge_level_and_latent_dist hparams.add_hpar...
[ "def", "glow_hparams", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "hparams", ".", "clip_grad_norm", "=", "None", "hparams", ".", "weight_decay", "=", "0.0", "hparams", ".", "learning_rate_constant", "=", "3e-4", "hparams", ...
Glow Hparams.
[ "Glow", "Hparams", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/glow.py#L39-L65
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_aux.py
shift_and_pad
def shift_and_pad(tensor, shift, axis=0): """Shifts and pads with zero along an axis. Example: shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2] shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0] Args: tensor: Tensor; to be shifted and padded. shift: int; number of positions to shift by. axis: ...
python
def shift_and_pad(tensor, shift, axis=0): """Shifts and pads with zero along an axis. Example: shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2] shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0] Args: tensor: Tensor; to be shifted and padded. shift: int; number of positions to shift by. axis: ...
[ "def", "shift_and_pad", "(", "tensor", ",", "shift", ",", "axis", "=", "0", ")", ":", "shape", "=", "tensor", ".", "shape", "rank", "=", "len", "(", "shape", ")", "assert", "0", "<=", "abs", "(", "axis", ")", "<", "rank", "length", "=", "int", "(...
Shifts and pads with zero along an axis. Example: shift_and_pad([1, 2, 3, 4], 2) --> [0, 0, 1, 2] shift_and_pad([1, 2, 3, 4], -2) --> [3, 4, 0, 0] Args: tensor: Tensor; to be shifted and padded. shift: int; number of positions to shift by. axis: int; along which axis to shift and pad. Retu...
[ "Shifts", "and", "pads", "with", "zero", "along", "an", "axis", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_aux.py#L29-L64
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_aux.py
transformer_aux_base
def transformer_aux_base(): """Set of hyperparameters.""" hparams = transformer.transformer_base() hparams.shared_embedding_and_softmax_weights = False hparams.add_hparam("shift_values", "1,2,3,4") return hparams
python
def transformer_aux_base(): """Set of hyperparameters.""" hparams = transformer.transformer_base() hparams.shared_embedding_and_softmax_weights = False hparams.add_hparam("shift_values", "1,2,3,4") return hparams
[ "def", "transformer_aux_base", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_base", "(", ")", "hparams", ".", "shared_embedding_and_softmax_weights", "=", "False", "hparams", ".", "add_hparam", "(", "\"shift_values\"", ",", "\"1,2,3,4\"", ")", "ret...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_aux.py#L161-L166
train
tensorflow/tensor2tensor
tensor2tensor/models/research/transformer_aux.py
transformer_aux_tiny
def transformer_aux_tiny(): """Set of hyperparameters.""" hparams = transformer.transformer_tiny() hparams.shared_embedding_and_softmax_weights = False hparams.add_hparam("shift_values", "1,2") return hparams
python
def transformer_aux_tiny(): """Set of hyperparameters.""" hparams = transformer.transformer_tiny() hparams.shared_embedding_and_softmax_weights = False hparams.add_hparam("shift_values", "1,2") return hparams
[ "def", "transformer_aux_tiny", "(", ")", ":", "hparams", "=", "transformer", ".", "transformer_tiny", "(", ")", "hparams", ".", "shared_embedding_and_softmax_weights", "=", "False", "hparams", ".", "add_hparam", "(", "\"shift_values\"", ",", "\"1,2\"", ")", "return"...
Set of hyperparameters.
[ "Set", "of", "hyperparameters", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/research/transformer_aux.py#L170-L175
train
tensorflow/tensor2tensor
tensor2tensor/models/video/base.py
pixels_from_softmax
def pixels_from_softmax(frame_logits, pure_sampling=False, temperature=1.0, gumbel_noise_factor=0.2): """Given frame_logits from a per-pixel softmax, generate colors.""" # If we're purely sampling, just sample each pixel. if pure_sampling or temperature == 0.0: return common_layers.sam...
python
def pixels_from_softmax(frame_logits, pure_sampling=False, temperature=1.0, gumbel_noise_factor=0.2): """Given frame_logits from a per-pixel softmax, generate colors.""" # If we're purely sampling, just sample each pixel. if pure_sampling or temperature == 0.0: return common_layers.sam...
[ "def", "pixels_from_softmax", "(", "frame_logits", ",", "pure_sampling", "=", "False", ",", "temperature", "=", "1.0", ",", "gumbel_noise_factor", "=", "0.2", ")", ":", "# If we're purely sampling, just sample each pixel.", "if", "pure_sampling", "or", "temperature", "=...
Given frame_logits from a per-pixel softmax, generate colors.
[ "Given", "frame_logits", "from", "a", "per", "-", "pixel", "softmax", "generate", "colors", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/base.py#L40-L59
train
tensorflow/tensor2tensor
tensor2tensor/models/video/base.py
next_frame_base
def next_frame_base(): """Common HParams for next_frame models.""" hparams = common_hparams.basic_params1() # Loss cutoff. hparams.add_hparam("video_modality_loss_cutoff", 0.01) # Additional resizing the frames before feeding them to model. hparams.add_hparam("preprocess_resize_frames", None) # How many d...
python
def next_frame_base(): """Common HParams for next_frame models.""" hparams = common_hparams.basic_params1() # Loss cutoff. hparams.add_hparam("video_modality_loss_cutoff", 0.01) # Additional resizing the frames before feeding them to model. hparams.add_hparam("preprocess_resize_frames", None) # How many d...
[ "def", "next_frame_base", "(", ")", ":", "hparams", "=", "common_hparams", ".", "basic_params1", "(", ")", "# Loss cutoff.", "hparams", ".", "add_hparam", "(", "\"video_modality_loss_cutoff\"", ",", "0.01", ")", "# Additional resizing the frames before feeding them to model...
Common HParams for next_frame models.
[ "Common", "HParams", "for", "next_frame", "models", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/models/video/base.py#L679-L704
train
tensorflow/tensor2tensor
tensor2tensor/rl/gym_utils.py
remove_time_limit_wrapper
def remove_time_limit_wrapper(env): """Removes top level TimeLimit Wrapper. Removes TimeLimit Wrapper from top level if exists, throws error if any other TimeLimit Wrapper is present in stack. Args: env: environment Returns: the env with removed time limit wrapper. """ if isinstance(env, gym.wr...
python
def remove_time_limit_wrapper(env): """Removes top level TimeLimit Wrapper. Removes TimeLimit Wrapper from top level if exists, throws error if any other TimeLimit Wrapper is present in stack. Args: env: environment Returns: the env with removed time limit wrapper. """ if isinstance(env, gym.wr...
[ "def", "remove_time_limit_wrapper", "(", "env", ")", ":", "if", "isinstance", "(", "env", ",", "gym", ".", "wrappers", ".", "TimeLimit", ")", ":", "env", "=", "env", ".", "env", "env_", "=", "env", "while", "isinstance", "(", "env_", ",", "gym", ".", ...
Removes top level TimeLimit Wrapper. Removes TimeLimit Wrapper from top level if exists, throws error if any other TimeLimit Wrapper is present in stack. Args: env: environment Returns: the env with removed time limit wrapper.
[ "Removes", "top", "level", "TimeLimit", "Wrapper", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/gym_utils.py#L129-L148
train
tensorflow/tensor2tensor
tensor2tensor/rl/gym_utils.py
gym_env_wrapper
def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env, rendered_env_resize_to, sticky_actions): """Wraps a gym environment. see make_gym_env for details.""" # rl_env_max_episode_steps is None or int. assert ((not rl_env_max_episode_steps) or isinstance(rl_env_m...
python
def gym_env_wrapper(env, rl_env_max_episode_steps, maxskip_env, rendered_env, rendered_env_resize_to, sticky_actions): """Wraps a gym environment. see make_gym_env for details.""" # rl_env_max_episode_steps is None or int. assert ((not rl_env_max_episode_steps) or isinstance(rl_env_m...
[ "def", "gym_env_wrapper", "(", "env", ",", "rl_env_max_episode_steps", ",", "maxskip_env", ",", "rendered_env", ",", "rendered_env_resize_to", ",", "sticky_actions", ")", ":", "# rl_env_max_episode_steps is None or int.", "assert", "(", "(", "not", "rl_env_max_episode_steps...
Wraps a gym environment. see make_gym_env for details.
[ "Wraps", "a", "gym", "environment", ".", "see", "make_gym_env", "for", "details", "." ]
272500b6efe353aeb638d2745ed56e519462ca31
https://github.com/tensorflow/tensor2tensor/blob/272500b6efe353aeb638d2745ed56e519462ca31/tensor2tensor/rl/gym_utils.py#L151-L176
train