INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Adds the specified response headers while keeping existing ones in - tact
def add_response_headers(self, headers, **overrides): """Adds the specified response headers while keeping existing ones in-tact""" response_headers = self.route.get('response_headers', {}).copy() response_headers.update(headers) return self.where(response_headers=response_headers, **ove...
Convenience method for quickly adding cache header to route
def cache(self, private=False, max_age=31536000, s_maxage=None, no_cache=False, no_store=False, must_revalidate=False, **overrides): """Convenience method for quickly adding cache header to route""" parts = ('private' if private else 'public', 'max-age={0}'.format(max_age), ...
Convenience method for quickly allowing other resources to access this one
def allow_origins(self, *origins, methods=None, max_age=None, credentials=None, headers=None, **overrides): """Convenience method for quickly allowing other resources to access this one""" response_headers = {} if origins: @hug.response_middleware() def process_data(reque...
Sets the acceptable HTTP method to a GET
def get(self, urls=None, **overrides): """Sets the acceptable HTTP method to a GET""" if urls is not None: overrides['urls'] = urls return self.where(accept='GET', **overrides)
Sets the acceptable HTTP method to DELETE
def delete(self, urls=None, **overrides): """Sets the acceptable HTTP method to DELETE""" if urls is not None: overrides['urls'] = urls return self.where(accept='DELETE', **overrides)
Sets the acceptable HTTP method to POST
def post(self, urls=None, **overrides): """Sets the acceptable HTTP method to POST""" if urls is not None: overrides['urls'] = urls return self.where(accept='POST', **overrides)
Sets the acceptable HTTP method to PUT
def put(self, urls=None, **overrides): """Sets the acceptable HTTP method to PUT""" if urls is not None: overrides['urls'] = urls return self.where(accept='PUT', **overrides)
Sets the acceptable HTTP method to TRACE
def trace(self, urls=None, **overrides): """Sets the acceptable HTTP method to TRACE""" if urls is not None: overrides['urls'] = urls return self.where(accept='TRACE', **overrides)
Sets the acceptable HTTP method to PATCH
def patch(self, urls=None, **overrides): """Sets the acceptable HTTP method to PATCH""" if urls is not None: overrides['urls'] = urls return self.where(accept='PATCH', **overrides)
Sets the acceptable HTTP method to OPTIONS
def options(self, urls=None, **overrides): """Sets the acceptable HTTP method to OPTIONS""" if urls is not None: overrides['urls'] = urls return self.where(accept='OPTIONS', **overrides)
Sets the acceptable HTTP method to HEAD
def head(self, urls=None, **overrides): """Sets the acceptable HTTP method to HEAD""" if urls is not None: overrides['urls'] = urls return self.where(accept='HEAD', **overrides)
Sets the acceptable HTTP method to CONNECT
def connect(self, urls=None, **overrides): """Sets the acceptable HTTP method to CONNECT""" if urls is not None: overrides['urls'] = urls return self.where(accept='CONNECT', **overrides)
Creates routes from a class where the class method names should line up to HTTP METHOD types
def http_methods(self, urls=None, **route_data): """Creates routes from a class, where the class method names should line up to HTTP METHOD types""" def decorator(class_definition): instance = class_definition if isinstance(class_definition, type): instance = clas...
Registers a method on an Object as a CLI route
def cli(self, method): """Registers a method on an Object as a CLI route""" routes = getattr(method, '_hug_cli_routes', []) routes.append(self.route) method._hug_cli_routes = routes return method
Starts the process of building a new HTTP route linked to this API instance
def http(self, *args, **kwargs): """Starts the process of building a new HTTP route linked to this API instance""" kwargs['api'] = self.api return http(*args, **kwargs)
Defines the handler that should handle not found requests against this API
def not_found(self, *args, **kwargs): """Defines the handler that should handle not found requests against this API""" kwargs['api'] = self.api return not_found(*args, **kwargs)
Define the routes to static files the API should expose
def static(self, *args, **kwargs): """Define the routes to static files the API should expose""" kwargs['api'] = self.api return static(*args, **kwargs)
Define URL prefixes/ handler matches where everything under the URL prefix should be handled
def sink(self, *args, **kwargs): """Define URL prefixes/handler matches where everything under the URL prefix should be handled""" kwargs['api'] = self.api return sink(*args, **kwargs)
Defines how this API should handle the provided exceptions
def exception(self, *args, **kwargs): """Defines how this API should handle the provided exceptions""" kwargs['api'] = self.api return exception(*args, **kwargs)
Defines a CLI function that should be routed by this API
def cli(self, *args, **kwargs): """Defines a CLI function that should be routed by this API""" kwargs['api'] = self.api return cli(*args, **kwargs)
Registers a class based router to this API
def object(self, *args, **kwargs): """Registers a class based router to this API""" kwargs['api'] = self.api return Object(*args, **kwargs)
Returns a generator of all URLs attached to this API
def urls(self): """Returns a generator of all URLs attached to this API""" for base_url, mapping in self.routes.items(): for url, _ in mapping.items(): yield base_url + url
Returns all registered handlers attached to this API
def handlers(self): """Returns all registered handlers attached to this API""" used = [] for base_url, mapping in self.routes.items(): for url, methods in mapping.items(): for method, versions in methods.items(): for version, handler in versions.it...
Returns the set input_format handler for the given content_type
def input_format(self, content_type): """Returns the set input_format handler for the given content_type""" return getattr(self, '_input_format', {}).get(content_type, hug.defaults.input_format.get(content_type, None))
Sets an input format handler for this Hug API given the specified content_type
def set_input_format(self, content_type, handler): """Sets an input format handler for this Hug API, given the specified content_type""" if getattr(self, '_input_format', None) is None: self._input_format = {} self._input_format[content_type] = handler
Adds a middleware object used to process all incoming requests against the API
def add_middleware(self, middleware): """Adds a middleware object used to process all incoming requests against the API""" if self.middleware is None: self._middleware = [] self.middleware.append(middleware)
Adds a error handler to the hug api
def add_exception_handler(self, exception_type, error_handler, versions=(None, )): """Adds a error handler to the hug api""" versions = (versions, ) if not isinstance(versions, (tuple, list)) else versions if not hasattr(self, '_exception_handlers'): self._exception_handlers = {} ...
Adds handlers from a different Hug API to this one - to create a single API
def extend(self, http_api, route="", base_url="", **kwargs): """Adds handlers from a different Hug API to this one - to create a single API""" self.versions.update(http_api.versions) base_url = base_url or self.base_url for router_base_url, routes in http_api.routes.items(): ...
Sets the not_found handler for the specified version of the api
def set_not_found_handler(self, handler, version=None): """Sets the not_found handler for the specified version of the api""" if not self.not_found_handlers: self._not_found_handlers = {} self.not_found_handlers[version] = handler
Generates and returns documentation for this API endpoint
def documentation(self, base_url=None, api_version=None, prefix=""): """Generates and returns documentation for this API endpoint""" documentation = OrderedDict() base_url = self.base_url if base_url is None else base_url overview = self.api.doc if overview: documenta...
Runs the basic hug development server against this API
def serve(self, host='', port=8000, no_documentation=False, display_intro=True): """Runs the basic hug development server against this API""" if no_documentation: api = self.server(None) else: api = self.server() if display_intro: print(INTRO) ...
Determines the appropriate version given the set api_version the request header and URL query params
def determine_version(self, request, api_version=None): """Determines the appropriate version given the set api_version, the request header, and URL query params""" if api_version is False: api_version = None for version in self.versions: if version and "v{0}".for...
Returns a smart 404 page that contains documentation for the written API
def documentation_404(self, base_url=None): """Returns a smart 404 page that contains documentation for the written API""" base_url = self.base_url if base_url is None else base_url def handle_404(request, response, *args, **kwargs): url_prefix = request.forwarded_uri[:-1] ...
Intelligently routes a request to the correct handler based on the version being requested
def version_router(self, request, response, api_version=None, versions={}, not_found=None, **kwargs): """Intelligently routes a request to the correct handler based on the version being requested""" request_version = self.determine_version(request, api_version) if request_version: re...
Returns a WSGI compatible API server for the given Hug API module
def server(self, default_not_found=True, base_url=None): """Returns a WSGI compatible API server for the given Hug API module""" falcon_api = falcon.API(middleware=self.middleware) default_not_found = self.documentation_404() if default_not_found is True else None base_url = self.base_ur...
Extends this CLI api with the commands present in the provided cli_api object
def extend(self, cli_api, command_prefix="", sub_command="", **kwargs): """Extends this CLI api with the commands present in the provided cli_api object""" if sub_command and command_prefix: raise ValueError('It is not currently supported to provide both a command_prefix and sub_command') ...
Returns all directives applicable to this Hug API
def directives(self): """Returns all directives applicable to this Hug API""" directive_sources = chain(hug.defaults.directives.items(), getattr(self, '_directives', {}).items()) return {'hug_' + directive_name: directive for directive_name, directive in directive_sources}
Returns the loaded directive with the specified name or default if passed name is not present
def directive(self, name, default=None): """Returns the loaded directive with the specified name, or default if passed name is not present""" return getattr(self, '_directives', {}).get(name, hug.defaults.directives.get(name, default))
Returns all registered handlers attached to this API
def handlers(self): """Returns all registered handlers attached to this API""" if getattr(self, '_http'): yield from self.http.handlers() if getattr(self, '_cli'): yield from self.cli.handlers()
Adds handlers from a different Hug API to this one - to create a single API
def extend(self, api, route="", base_url="", http=True, cli=True, **kwargs): """Adds handlers from a different Hug API to this one - to create a single API""" api = API(api) if http and hasattr(api, '_http'): self.http.extend(api.http, route, base_url, **kwargs) if cli and ...
Adds a startup handler to the hug api
def add_startup_handler(self, handler): """Adds a startup handler to the hug api""" if not self.startup_handlers: self._startup_handlers = [] self.startup_handlers.append(handler)
Marks the API as started and runs all startup handlers
def _ensure_started(self): """Marks the API as started and runs all startup handlers""" if not self.started: async_handlers = [startup_handler for startup_handler in self.startup_handlers if introspect.is_coroutine(startup_handler)] if async_handlers...
Helper for WeightDrop.
def _weight_drop(module, weights, dropout): """ Helper for `WeightDrop`. """ for name_w in weights: w = getattr(module, name_w) del module._parameters[name_w] module.register_parameter(name_w + '_raw', Parameter(w)) original_module_forward = module.forward def forward(...
Load the IMDB dataset ( Large Movie Review Dataset v1. 0 ).
def imdb_dataset(directory='data/', train=False, test=False, train_directory='train', test_directory='test', extracted_name='aclImdb', check_files=['aclImdb/README'], url='http://ai.stanford.edu/~amaas...
Load the Text REtrieval Conference ( TREC ) Question Classification dataset.
def trec_dataset(directory='data/trec/', train=False, test=False, train_filename='train_5500.label', test_filename='TREC_10.label', check_files=['train_5500.label'], urls=[ 'http://cogcomp.org/Data...
Load the Stanford Natural Language Inference ( SNLI ) dataset.
def snli_dataset(directory='data/', train=False, dev=False, test=False, train_filename='snli_1.0_train.jsonl', dev_filename='snli_1.0_dev.jsonl', test_filename='snli_1.0_test.jsonl', extracted_name='sn...
Args: query (: class: torch. FloatTensor [ batch size output length dimensions ] ): Sequence of queries to query the context. context (: class: torch. FloatTensor [ batch size query length dimensions ] ): Data overwhich to apply the attention mechanism.
def forward(self, query, context): """ Args: query (:class:`torch.FloatTensor` [batch size, output length, dimensions]): Sequence of queries to query the context. context (:class:`torch.FloatTensor` [batch size, query length, dimensions]): Data ove...
Load the International Workshop on Spoken Language Translation ( IWSLT ) 2017 translation dataset.
def iwslt_dataset( directory='data/iwslt/', train=False, dev=False, test=False, language_extensions=['en', 'de'], train_filename='{source}-{target}/train.{source}-{target}.{lang}', dev_filename='{source}-{target}/IWSLT16.TED.tst2013.{source}-{target}.{lang}', ...
Encodes an object.
def encode(self, object_): """ Encodes an object. Args: object_ (object): Object to encode. Returns: object: Encoding of the object. """ if self.enforce_reversible: self.enforce_reversible = False if self.decode(self.encode(object...
Args: batch ( list ): Batch of objects to encode. * args: Arguments passed to encode. ** kwargs: Keyword arguments passed to encode.
def batch_encode(self, iterator, *args, **kwargs): """ Args: batch (list): Batch of objects to encode. *args: Arguments passed to ``encode``. **kwargs: Keyword arguments passed to ``encode``. Returns: list: Batch of encoded objects. """ ...
Decodes an object.
def decode(self, encoded): """ Decodes an object. Args: object_ (object): Encoded object. Returns: object: Object decoded. """ if self.enforce_reversible: self.enforce_reversible = False if self.encode(self.decode(encoded)) != enc...
Args: iterator ( list ): Batch of encoded objects. * args: Arguments passed to decode. ** kwargs: Keyword arguments passed to decode.
def batch_decode(self, iterator, *args, **kwargs): """ Args: iterator (list): Batch of encoded objects. *args: Arguments passed to ``decode``. **kwargs: Keyword arguments passed to ``decode``. Returns: list: Batch of decoded objects. """ ...
Args: tokens (: class: torch. FloatTensor [ batch_size num_tokens input_dim ] ): Sequence matrix to encode. mask (: class: torch. FloatTensor ): Broadcastable matrix to tokens used as a mask. Returns: (: class: torch. FloatTensor [ batch_size output_dim ] ): Encoding of sequence.
def forward(self, tokens, mask=None): """ Args: tokens (:class:`torch.FloatTensor` [batch_size, num_tokens, input_dim]): Sequence matrix to encode. mask (:class:`torch.FloatTensor`): Broadcastable matrix to `tokens` used as a mask. Returns: (:c...
Inverse of _escape_token (). Args: escaped_token: a unicode string Returns: token: a unicode string
def _unescape_token(escaped_token): """ Inverse of _escape_token(). Args: escaped_token: a unicode string Returns: token: a unicode string """ def match(m): if m.group(1) is None: return u"_" if m.group(0) == u"\\u" else u"\\" try: return six...
Converts a list of tokens to a list of subtoken.
def _tokens_to_subtoken(self, tokens): """ Converts a list of tokens to a list of subtoken. Args: tokens: a list of strings. Returns: a list of integers in the range [0, vocab_size) """ ret = [] for token in tokens: ret.extend( ...
Converts a list of subtoken to a list of tokens.
def _subtoken_to_tokens(self, subtokens): """ Converts a list of subtoken to a list of tokens. Args: subtokens: a list of integers in the range [0, vocab_size) Returns: a list of strings. """ concatenated = "".join(subtokens) split = concatenated.spl...
Converts an escaped token string to a list of subtoken strings.
def _escaped_token_to_subtoken_strings(self, escaped_token): """ Converts an escaped token string to a list of subtoken strings. Args: escaped_token: An escaped token as a unicode string. Returns: A list of subtokens as unicode strings. """ # NOTE: This algor...
Builds a SubwordTextTokenizer that has vocab_size near target_size.
def build_to_target_size_from_token_counts(cls, target_size, token_counts, min_val, max_val, ...
Train a SubwordTextTokenizer based on a dictionary of word counts.
def build_from_token_counts(self, token_counts, min_count, num_iterations=4): """Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_...
Initialize token information from a list of subtoken strings.
def _init_subtokens_from_list(self, subtoken_strings): """Initialize token information from a list of subtoken strings.""" # we remember the maximum length of any subtoken to avoid having to # check arbitrarily long strings. self._all_subtoken_strings = set([s for s in subtoken_strings i...
Initialize alphabet from an iterable of token or subtoken strings.
def _init_alphabet_from_tokens(self, tokens): """Initialize alphabet from an iterable of token or subtoken strings.""" # Include all characters from all tokens in the alphabet to guarantee that # any token can be encoded. Additionally, include all escaping # characters. self._alp...
Get the BLEU score using the moses multi - bleu. perl script.
def get_moses_multi_bleu(hypotheses, references, lowercase=False): """Get the BLEU score using the moses `multi-bleu.perl` script. **Script:** https://raw.githubusercontent.com/moses-smt/mosesdecoder/master/scripts/generic/multi-bleu.perl Args: hypotheses (list of str): List of predicted values ...
Load the Universal Dependencies - English Dependency Treebank dataset.
def ud_pos_dataset(directory='data/', train=False, dev=False, test=False, train_filename='en-ud-tag.v2.train.txt', dev_filename='en-ud-tag.v2.dev.txt', test_filename='en-ud-tag.v2.test.txt', ...
helper function for python 2 and 3 to call os. makedirs () avoiding an error if the directory to be created already exists
def makedirs(name): """helper function for python 2 and 3 to call os.makedirs() avoiding an error if the directory to be created already exists""" import os, errno try: os.makedirs(name) except OSError as ex: if ex.errno == errno.EEXIST and os.path.isdir(name): # ign...
list of tensors to a batch tensors
def collate_fn(batch, train=True): """ list of tensors to a batch tensors """ premise_batch, _ = pad_batch([row['premise'] for row in batch]) hypothesis_batch, _ = pad_batch([row['hypothesis'] for row in batch]) label_batch = torch.stack([row['label'] for row in batch]) # PyTorch RNN requires batch...
Load the Stanford Sentiment Treebank dataset.
def smt_dataset(directory='data/', train=False, dev=False, test=False, train_filename='train.txt', dev_filename='dev.txt', test_filename='test.txt', extracted_name='trees', check_files=['trees...
Load the SimpleQuestions dataset.
def simple_qa_dataset( directory='data/', train=False, dev=False, test=False, extracted_name='SimpleQuestions_v2', train_filename='annotated_fb_data_train.txt', dev_filename='annotated_fb_data_valid.txt', test_filename='annotated_fb_data_test.txt', ...
Args: x (: class: torch. FloatTensor [ batch size sequence length rnn hidden size ] ): Input to apply dropout too.
def forward(self, x): """ Args: x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to apply dropout too. """ if not self.training or not self.p: return x x = x.clone() mask = x.new_empty(1, x.size(1...
Pad a tensor to length with padding_index.
def pad_tensor(tensor, length, padding_index=DEFAULT_PADDING_INDEX): """ Pad a ``tensor`` to ``length`` with ``padding_index``. Args: tensor (torch.Tensor [n, ...]): Tensor to pad. length (int): Pad the ``tensor`` up to ``length``. padding_index (int, optional): Index to pad tensor with...
Pad a: class: list of tensors ( batch ) with padding_index.
def stack_and_pad_tensors(batch, padding_index=DEFAULT_PADDING_INDEX, dim=0): """ Pad a :class:`list` of ``tensors`` (``batch``) with ``padding_index``. Args: batch (:class:`list` of :class:`torch.Tensor`): Batch of tensors to pad. padding_index (int, optional): Index to pad tensors with. ...
Args: iterator ( iterator ): Batch of text to encode. * args: Arguments passed onto Encoder. __init__. dim ( int optional ): Dimension along which to concatenate tensors. ** kwargs: Keyword arguments passed onto Encoder. __init__.
def batch_encode(self, iterator, *args, dim=0, **kwargs): """ Args: iterator (iterator): Batch of text to encode. *args: Arguments passed onto ``Encoder.__init__``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword argume...
Args: batch ( list of: class: torch. Tensor ): Batch of encoded sequences. lengths ( list of int ): Original lengths of sequences. dim ( int optional ): Dimension along which to split tensors. * args: Arguments passed to decode. ** kwargs: Key word arguments passed to decode.
def batch_decode(self, tensor, lengths, dim=0, *args, **kwargs): """ Args: batch (list of :class:`torch.Tensor`): Batch of encoded sequences. lengths (list of int): Original lengths of sequences. dim (int, optional): Dimension along which to split tensors. ...
Encodes a sequence.
def encode(self, sequence): """ Encodes a ``sequence``. Args: sequence (str): String ``sequence`` to encode. Returns: torch.Tensor: Encoding of the ``sequence``. """ sequence = super().encode(sequence) sequence = self.tokenize(sequence) v...
Decodes a tensor into a sequence.
def decode(self, encoded): """ Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``. """ encoded = super().decode(encoded) tokens = [self.itos[index] for index in encode...
reporthook to use with urllib. request that prints the process of the download.
def _reporthook(t): """ ``reporthook`` to use with ``urllib.request`` that prints the process of the download. Uses ``tqdm`` for progress bar. **Reference:** https://github.com/tqdm/tqdm Args: t (tqdm.tqdm) Progress bar. Example: >>> with tqdm(unit='B', unit_scale=True, minit...
Download filename from google drive unless it s already in directory.
def _download_file_from_drive(filename, url): # pragma: no cover """ Download filename from google drive unless it's already in directory. Args: filename (str): Name of the file to download to (do nothing if it already exists). url (str): URL to download from. """ confirm_token = None ...
Extract a compressed file to directory.
def _maybe_extract(compressed_filename, directory, extension=None): """ Extract a compressed file to ``directory``. Args: compressed_filename (str): Compressed file. directory (str): Extract to directory. extension (str, optional): Extension of the file; Otherwise, attempts to extract e...
Return a filename from a URL
def _get_filename_from_url(url): """ Return a filename from a URL Args: url (str): URL to extract filename from Returns: (str): Filename in URL """ parse = urlparse(url) return os.path.basename(parse.path)
Download the file at url to directory. Extract to directory if tar or zip.
def download_file_maybe_extract(url, directory, filename=None, extension=None, check_files=[]): """ Download the file at ``url`` to ``directory``. Extract to ``directory`` if tar or zip. Args: url (str): Url of file. directory (str): Directory to download to. filename (str, optional): N...
Download the files at urls to directory. Extract to directory if tar or zip.
def download_files_maybe_extract(urls, directory, check_files=[]): """ Download the files at ``urls`` to ``directory``. Extract to ``directory`` if tar or zip. Args: urls (str): Url of files. directory (str): Directory to download to. check_files (list of str): Check if these files exis...
Get the accuracy top - k accuracy between two tensors.
def get_accuracy(targets, outputs, k=1, ignore_index=None): """ Get the accuracy top-k accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
Get the accuracy token accuracy between two tensors.
def get_token_accuracy(targets, outputs, ignore_index=None): """ Get the accuracy token accuracy between two tensors. Args: targets (1 - 2D :class:`torch.Tensor`): Target or true vector against which to measure saccuracy outputs (1 - 3D :class:`torch.Tensor`): Prediction or output vector ...
Get all tensors associated with object_
def get_tensors(object_): """ Get all tensors associated with ``object_`` Args: object_ (any): Any object to look for tensors. Returns: (list of torch.tensor): List of tensors that are associated with ``object_``. """ if torch.is_tensor(object_): return [object_] elif i...
Given a batch sampler or sampler returns examples instead of indices
def sampler_to_iterator(dataset, sampler): """ Given a batch sampler or sampler returns examples instead of indices Args: dataset (torch.utils.data.Dataset): Dataset to sample from. sampler (torch.utils.data.sampler.Sampler): Sampler over the dataset. Returns: generator over datase...
Deterministic shuffle and split algorithm.
def resplit_datasets(dataset, other_dataset, random_seed=None, split=None): """Deterministic shuffle and split algorithm. Given the same two datasets and the same ``random_seed``, the split happens the same exact way every call. Args: dataset (lib.datasets.Dataset): First dataset. othe...
Compute torch. equal with the optional mask parameter.
def torch_equals_ignore_index(tensor, tensor_other, ignore_index=None): """ Compute ``torch.equal`` with the optional mask parameter. Args: ignore_index (int, optional): Specifies a ``tensor`` index that is ignored. Returns: (bool) Returns ``True`` if target and prediction are equal. ...
Given a list of lengths create a batch mask.
def lengths_to_mask(*lengths, **kwargs): """ Given a list of lengths, create a batch mask. Example: >>> lengths_to_mask([1, 2, 3]) tensor([[1, 0, 0], [1, 1, 0], [1, 1, 1]], dtype=torch.uint8) >>> lengths_to_mask([1, 2, 2], [1, 2, 2]) tensor([[[1, ...
Collate a list of type k ( dict namedtuple list etc. ) with tensors.
def collate_tensors(batch, stack_tensors=torch.stack): """ Collate a list of type ``k`` (dict, namedtuple, list, etc.) with tensors. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: batch (list of k): List of rows of type ``k``. s...
Apply torch. Tensor. to to tensors in a generic data structure.
def tensors_to(tensors, *args, **kwargs): """ Apply ``torch.Tensor.to`` to tensors in a generic data structure. Inspired by: https://github.com/pytorch/pytorch/blob/master/torch/utils/data/_utils/collate.py#L31 Args: tensors (tensor, dict, list, namedtuple or tuple): Data structure with tensor...
Load the Zero dataset.
def zero_dataset(train=False, dev=False, test=False, train_rows=256, dev_rows=64, test_rows=64): """ Load the Zero dataset. The Zero dataset is a simple task of predicting zero from zero. This dataset is useful for integration testing. The extreme simplicity of the dataset allows for models to learn th...
Decodes a tensor into a sequence.
def decode(self, encoded): """ Decodes a tensor into a sequence. Args: encoded (torch.Tensor): Encoded sequence. Returns: str: Sequence decoded from ``encoded``. """ encoded = super().decode(encoded) return self.tokenizer.decode([self.itos[index]...
Encodes a label.
def encode(self, label): """ Encodes a ``label``. Args: label (object): Label to encode. Returns: torch.Tensor: Encoding of the label. """ label = super().encode(label) return torch.tensor(self.stoi.get(label, self.unknown_index))
Args: iterator ( iterator ): Batch of labels to encode. * args: Arguments passed to Encoder. batch_encode. dim ( int optional ): Dimension along which to concatenate tensors. ** kwargs: Keyword arguments passed to Encoder. batch_encode.
def batch_encode(self, iterator, *args, dim=0, **kwargs): """ Args: iterator (iterator): Batch of labels to encode. *args: Arguments passed to ``Encoder.batch_encode``. dim (int, optional): Dimension along which to concatenate tensors. **kwargs: Keyword ar...
Decodes encoded label.
def decode(self, encoded): """ Decodes ``encoded`` label. Args: encoded (torch.Tensor): Encoded label. Returns: object: Label decoded from ``encoded``. """ encoded = super().decode(encoded) if encoded.numel() > 1: raise ValueError( ...
Args: tensor ( torch. Tensor ): Batch of tensors. * args: Arguments passed to Encoder. batch_decode. dim ( int optional ): Dimension along which to split tensors. ** kwargs: Keyword arguments passed to Encoder. batch_decode.
def batch_decode(self, tensor, *args, dim=0, **kwargs): """ Args: tensor (torch.Tensor): Batch of tensors. *args: Arguments passed to ``Encoder.batch_decode``. dim (int, optional): Dimension along which to split tensors. **kwargs: Keyword arguments passed ...
Load the Count dataset.
def count_dataset(train=False, dev=False, test=False, train_rows=10000, dev_rows=1000, test_rows=1000, seq_max_length=10): """ Load the Count dataset. The Count dataset is a simple task of counting t...
Load the WMT 2016 machine translation dataset.
def multi30k_dataset(directory='data/multi30k/', train=False, dev=False, test=False, train_filename='train', dev_filename='val', test_filename='test', check_files=['train.de...
Load the Penn Treebank dataset.
def penn_treebank_dataset( directory='data/penn-treebank', train=False, dev=False, test=False, train_filename='ptb.train.txt', dev_filename='ptb.valid.txt', test_filename='ptb.test.txt', check_files=['ptb.train.txt'], urls=[ 'https://ra...
Wraps hidden states in new Tensors to detach them from their history.
def repackage_hidden(h): """Wraps hidden states in new Tensors, to detach them from their history.""" if isinstance(h, torch.Tensor): return h.detach() else: return tuple(repackage_hidden(v) for v in h)
Parses the given vyper source code and returns a list of python AST objects for all statements in the source. Performs pre - processing of source code before parsing as well as post - processing of the resulting AST.
def parse_to_ast(source_code: str) -> List[ast.stmt]: """ Parses the given vyper source code and returns a list of python AST objects for all statements in the source. Performs pre-processing of source code before parsing as well as post-processing of the resulting AST. :param source_code: The vyp...