file_path
stringlengths
3
280
file_language
stringclasses
66 values
content
stringlengths
1
1.04M
repo_name
stringlengths
5
92
repo_stars
int64
0
154k
repo_description
stringlengths
0
402
repo_primary_language
stringclasses
108 values
developer_username
stringlengths
1
25
developer_name
stringlengths
0
30
developer_company
stringlengths
0
82
bert/interactive.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Translate raw text with a trained model. Batches data on-the-fly. """ from collections import namedtuple import numpy as np import sys import torch from fairseq import data, options, tasks, tokenizer, utils from fairseq.sequence_generator import SequenceGenerator Batch = namedtuple('Batch', 'srcs tokens lengths') Translation = namedtuple('Translation', 'src_str hypos pos_scores alignments') def buffered_read(buffer_size): buffer = [] for src_str in sys.stdin: buffer.append(src_str.strip()) if len(buffer) >= buffer_size: yield buffer buffer = [] if len(buffer) > 0: yield buffer def make_batches(lines, args, task, max_positions): tokens = [ tokenizer.Tokenizer.tokenize(src_str, task.source_dictionary, add_if_not_exist=False).long() for src_str in lines ] lengths = np.array([t.numel() for t in tokens]) itr = task.get_batch_iterator( dataset=data.LanguagePairDataset(tokens, lengths, task.source_dictionary), max_tokens=args.max_tokens, max_sentences=args.max_sentences, max_positions=max_positions, ).next_epoch_itr(shuffle=False) for batch in itr: yield Batch( srcs=[lines[i] for i in batch['id']], tokens=batch['net_input']['src_tokens'], lengths=batch['net_input']['src_lengths'], ), batch['id'] def main(args): if args.buffer_size < 1: args.buffer_size = 1 if args.max_tokens is None and args.max_sentences is None: args.max_sentences = 1 assert not args.sampling or args.nbest == args.beam, \ '--sampling requires --nbest to be equal to --beam' assert not args.max_sentences or args.max_sentences <= args.buffer_size, \ '--max-sentences/--batch-size cannot be larger than --buffer-size' print(args) use_cuda = torch.cuda.is_available() and not args.cpu # Setup task, e.g., translation task = tasks.setup_task(args) # Load ensemble print('| loading model(s) from {}'.format(args.path)) model_paths = args.path.split(':') models, model_args = utils.load_ensemble_for_inference(model_paths, task, model_arg_overrides=eval(args.model_overrides)) # Set dictionaries tgt_dict = task.target_dictionary # Optimize ensemble for generation for model in models: model.make_generation_fast_( beamable_mm_beam_size=None if args.no_beamable_mm else args.beam, need_attn=args.print_alignment, ) if args.fp16: model.half() # Initialize generator translator = SequenceGenerator( models, tgt_dict, beam_size=args.beam, minlen=args.min_len, stop_early=(not args.no_early_stop), normalize_scores=(not args.unnormalized), len_penalty=args.lenpen, unk_penalty=args.unkpen, sampling=args.sampling, sampling_topk=args.sampling_topk, sampling_temperature=args.sampling_temperature, diverse_beam_groups=args.diverse_beam_groups, diverse_beam_strength=args.diverse_beam_strength, ) if use_cuda: translator.cuda() # Load alignment dictionary for unknown word replacement # (None if no unknown word replacement, empty if no path to align dictionary) align_dict = utils.load_align_dict(args.replace_unk) def make_result(src_str, hypos): result = Translation( src_str='O\t{}'.format(src_str), hypos=[], pos_scores=[], alignments=[], ) # Process top predictions for hypo in hypos[:min(len(hypos), args.nbest)]: hypo_tokens, hypo_str, alignment = utils.post_process_prediction( hypo_tokens=hypo['tokens'].int().cpu(), src_str=src_str, alignment=hypo['alignment'].int().cpu() if hypo['alignment'] is not None else None, align_dict=align_dict, tgt_dict=tgt_dict, remove_bpe=args.remove_bpe, ) result.hypos.append('H\t{}\t{}'.format(hypo['score'], hypo_str)) result.pos_scores.append('P\t{}'.format( ' '.join(map( lambda x: '{:.4f}'.format(x), hypo['positional_scores'].tolist(), )) )) result.alignments.append( 'A\t{}'.format(' '.join(map(lambda x: str(utils.item(x)), alignment))) if args.print_alignment else None ) return result def process_batch(batch): tokens = batch.tokens lengths = batch.lengths if use_cuda: tokens = tokens.cuda() lengths = lengths.cuda() encoder_input = {'src_tokens': tokens, 'src_lengths': lengths} translations = translator.generate( encoder_input, maxlen=int(args.max_len_a * tokens.size(1) + args.max_len_b), ) return [make_result(batch.srcs[i], t) for i, t in enumerate(translations)] max_positions = utils.resolve_max_positions( task.max_positions(), *[model.max_positions() for model in models] ) if args.buffer_size > 1: print('| Sentence buffer size:', args.buffer_size) print('| Type the input sentence and press return:') for inputs in buffered_read(args.buffer_size): indices = [] results = [] for batch, batch_indices in make_batches(inputs, args, task, max_positions): indices.extend(batch_indices) results += process_batch(batch) for i in np.argsort(indices): result = results[i] print(result.src_str) for hypo, pos_scores, align in zip(result.hypos, result.pos_scores, result.alignments): print(hypo) print(pos_scores) if align is not None: print(align) if __name__ == '__main__': parser = options.get_generation_parser(interactive=True) args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/bert/WikiExtractor.py
Python
#!/usr/bin/env python # -*- coding: utf-8 -*- # ============================================================================= # Version: 2.75 (March 4, 2017) # Author: Giuseppe Attardi (attardi@di.unipi.it), University of Pisa # # Contributors: # Antonio Fuschetto (fuschett@aol.com) # Leonardo Souza (lsouza@amtera.com.br) # Juan Manuel Caicedo (juan@cavorite.com) # Humberto Pereira (begini@gmail.com) # Siegfried-A. Gevatter (siegfried@gevatter.com) # Pedro Assis (pedroh2306@gmail.com) # Wim Muskee (wimmuskee@gmail.com) # Radics Geza (radicsge@gmail.com) # orangain (orangain@gmail.com) # Seth Cleveland (scleveland@turnitin.com) # Bren Barn # # ============================================================================= # Copyright (c) 2011-2017. Giuseppe Attardi (attardi@di.unipi.it). # ============================================================================= # This file is part of Tanl. # # Tanl is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License, version 3, # as published by the Free Software Foundation. # # Tanl is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License at <http://www.gnu.org/licenses/> for more details. # # ============================================================================= """Wikipedia Extractor: Extracts and cleans text from a Wikipedia database dump and stores output in a number of files of similar size in a given directory. Each file will contain several documents in the format: <doc id="" revid="" url="" title=""> ... </doc> If the program is invoked with the --json flag, then each file will contain several documents formatted as json ojects, one per line, with the following structure {"id": "", "revid": "", "url":"", "title": "", "text": "..."} Template expansion requires preprocesssng first the whole dump and collecting template definitions. """ from __future__ import unicode_literals, division import argparse import bz2 import codecs import fileinput import html import json import logging import os.path import re # TODO use regex when it will be standard import sys import time from html.entities import name2codepoint from io import StringIO from itertools import zip_longest from multiprocessing import Queue, Process, Value, cpu_count from timeit import default_timer from types import SimpleNamespace from urllib.parse import quote text_type = str # =========================================================================== # Program version version = '2.75' ## PARAMS #################################################################### options = SimpleNamespace( ## # Defined in <siteinfo> # We include as default Template, when loading external template file. knownNamespaces={'Template': 10}, ## # The namespace used for template definitions # It is the name associated with namespace key=10 in the siteinfo header. templateNamespace='', templatePrefix='', ## # The namespace used for module definitions # It is the name associated with namespace key=828 in the siteinfo header. moduleNamespace='', ## # Recognize only these namespaces in links # w: Internal links to the Wikipedia # wiktionary: Wiki dictionary # wikt: shortcut for Wiktionary # acceptedNamespaces=['w', 'wiktionary', 'wikt'], # This is obtained from <siteinfo> urlbase='', ## # Filter disambiguation pages filter_disambig_pages=False, ## # Drop tables from the article keep_tables=False, ## # Whether to preserve links in output keepLinks=False, ## # Whether to preserve section titles keepSections=True, ## # Whether to preserve lists keepLists=False, ## # Whether to output HTML instead of text toHTML=False, ## # Whether to write json instead of the xml-like default output format write_json=False, ## # Whether to expand templates expand_templates=True, ## ## Whether to escape doc content escape_doc=False, ## # Print the wikipedia article revision print_revision=False, ## # Minimum expanded text length required to print document min_text_length=0, # Shared objects holding templates, redirects and cache templates={}, redirects={}, # cache of parser templates # FIXME: sharing this with a Manager slows down. templateCache={}, # Elements to ignore/discard ignored_tag_patterns=[], discardElements=[ 'gallery', 'timeline', 'noinclude', 'pre', 'table', 'tr', 'td', 'th', 'caption', 'div', 'form', 'input', 'select', 'option', 'textarea', 'ul', 'li', 'ol', 'dl', 'dt', 'dd', 'menu', 'dir', 'ref', 'references', 'img', 'imagemap', 'source', 'small', 'sub', 'sup', 'indicator' ], ) ## # Keys for Template and Module namespaces templateKeys = {'10', '828'} ## # Regex for identifying disambig pages filter_disambig_page_pattern = re.compile("{{disambig(uation)?(\|[^}]*)?}}") ## # page filtering logic -- remove templates, undesired xml namespaces, and disambiguation pages def keepPage(ns, page): if ns != '0': # Aritcle return False # remove disambig pages if desired if options.filter_disambig_pages: for line in page: if filter_disambig_page_pattern.match(line): return False return True def get_url(uid): return "%s?curid=%s" % (options.urlbase, uid) # ========================================================================= # # MediaWiki Markup Grammar # https://www.mediawiki.org/wiki/Preprocessor_ABNF # xml-char = %x9 / %xA / %xD / %x20-D7FF / %xE000-FFFD / %x10000-10FFFF # sptab = SP / HTAB # ; everything except ">" (%x3E) # attr-char = %x9 / %xA / %xD / %x20-3D / %x3F-D7FF / %xE000-FFFD / %x10000-10FFFF # literal = *xml-char # title = wikitext-L3 # part-name = wikitext-L3 # part-value = wikitext-L3 # part = ( part-name "=" part-value ) / ( part-value ) # parts = [ title *( "|" part ) ] # tplarg = "{{{" parts "}}}" # template = "{{" parts "}}" # link = "[[" wikitext-L3 "]]" # comment = "<!--" literal "-->" # unclosed-comment = "<!--" literal END # ; the + in the line-eating-comment rule was absent between MW 1.12 and MW 1.22 # line-eating-comment = LF LINE-START *SP +( comment *SP ) LINE-END # attr = *attr-char # nowiki-element = "<nowiki" attr ( "/>" / ( ">" literal ( "</nowiki>" / END ) ) ) # wikitext-L2 = heading / wikitext-L3 / *wikitext-L2 # wikitext-L3 = literal / template / tplarg / link / comment / # line-eating-comment / unclosed-comment / xmlish-element / # *wikitext-L3 # ------------------------------------------------------------------------------ selfClosingTags = ('hr', 'nobr', 'ref', 'references', 'nowiki') placeholder_tags = {'math': 'formula', 'code': 'codice'} def normalizeTitle(title): """Normalize title""" # remove leading/trailing whitespace and underscores title = title.strip(' _') # replace sequences of whitespace and underscore chars with a single space title = re.sub(r'[\s_]+', ' ', title) m = re.match(r'([^:]*):(\s*)(\S(?:.*))', title) if m: prefix = m.group(1) if m.group(2): optionalWhitespace = ' ' else: optionalWhitespace = '' rest = m.group(3) ns = normalizeNamespace(prefix) if ns in options.knownNamespaces: # If the prefix designates a known namespace, then it might be # followed by optional whitespace that should be removed to get # the canonical page name # (e.g., "Category: Births" should become "Category:Births"). title = ns + ":" + ucfirst(rest) else: # No namespace, just capitalize first letter. # If the part before the colon is not a known namespace, then we # must not remove the space after the colon (if any), e.g., # "3001: The_Final_Odyssey" != "3001:The_Final_Odyssey". # However, to get the canonical page name we must contract multiple # spaces into one, because # "3001: The_Final_Odyssey" != "3001: The_Final_Odyssey". title = ucfirst(prefix) + ":" + optionalWhitespace + ucfirst(rest) else: # no namespace, just capitalize first letter title = ucfirst(title) return title def unescape(text): """ Removes HTML or XML character references and entities from a text string. :param text The HTML (or XML) source text. :return The plain text, as a Unicode string, if necessary. """ def fixup(m): text = m.group(0) code = m.group(1) try: if text[1] == "#": # character reference if text[2] == "x": return chr(int(code[1:], 16)) else: return chr(int(code)) else: # named entity return chr(name2codepoint[code]) except: return text # leave as is return re.sub("&#?(\w+);", fixup, text) # Match HTML comments # The buggy template {{Template:T}} has a comment terminating with just "->" comment = re.compile(r'<!--.*?-->', re.DOTALL) # Match <nowiki>...</nowiki> nowiki = re.compile(r'<nowiki>.*?</nowiki>') def ignoreTag(tag): left = re.compile(r'<%s\b.*?>' % tag, re.IGNORECASE | re.DOTALL) # both <ref> and <reference> right = re.compile(r'</\s*%s>' % tag, re.IGNORECASE) options.ignored_tag_patterns.append((left, right)) # Match selfClosing HTML tags selfClosing_tag_patterns = [ re.compile(r'<\s*%s\b[^>]*/\s*>' % tag, re.DOTALL | re.IGNORECASE) for tag in selfClosingTags ] # Match HTML placeholder tags placeholder_tag_patterns = [ (re.compile(r'<\s*%s(\s*| [^>]+?)>.*?<\s*/\s*%s\s*>' % (tag, tag), re.DOTALL | re.IGNORECASE), repl) for tag, repl in placeholder_tags.items() ] # Match preformatted lines preformatted = re.compile(r'^ .*?$') # Match external links (space separates second optional parameter) externalLink = re.compile(r'\[\w+[^ ]*? (.*?)]') externalLinkNoAnchor = re.compile(r'\[\w+[&\]]*\]') # Matches bold/italic bold_italic = re.compile(r"'''''(.*?)'''''") bold = re.compile(r"'''(.*?)'''") italic_quote = re.compile(r"''\"([^\"]*?)\"''") italic = re.compile(r"''(.*?)''") quote_quote = re.compile(r'""([^"]*?)""') # Matches space spaces = re.compile(r' {2,}') # Matches dots dots = re.compile(r'\.{4,}') # ====================================================================== class Template(list): """ A Template is a list of TemplateText or TemplateArgs """ @classmethod def parse(cls, body): tpl = Template() # we must handle nesting, s.a. # {{{1|{{PAGENAME}}} # {{{italics|{{{italic|}}} # {{#if:{{{{{#if:{{{nominee|}}}|nominee|candidate}}|}}}| # start = 0 for s, e in findMatchingBraces(body, 3): tpl.append(TemplateText(body[start:s])) tpl.append(TemplateArg(body[s + 3:e - 3])) start = e tpl.append(TemplateText(body[start:])) # leftover return tpl def subst(self, params, extractor, depth=0): # We perform parameter substitutions recursively. # We also limit the maximum number of iterations to avoid too long or # even endless loops (in case of malformed input). # :see: http://meta.wikimedia.org/wiki/Help:Expansion#Distinction_between_variables.2C_parser_functions.2C_and_templates # # Parameter values are assigned to parameters in two (?) passes. # Therefore a parameter name in a template can depend on the value of # another parameter of the same template, regardless of the order in # which they are specified in the template call, for example, using # Template:ppp containing "{{{{{{p}}}}}}", {{ppp|p=q|q=r}} and even # {{ppp|q=r|p=q}} gives r, but using Template:tvvv containing # "{{{{{{{{{p}}}}}}}}}", {{tvvv|p=q|q=r|r=s}} gives s. # logging.debug('&*ssubst tpl %d %s', extractor.frame.length, '', depth, self) if depth > extractor.maxParameterRecursionLevels: extractor.recursion_exceeded_3_errs += 1 return '' return ''.join([tpl.subst(params, extractor, depth) for tpl in self]) def __str__(self): return ''.join([text_type(x) for x in self]) class TemplateText(text_type): """Fixed text of template""" def subst(self, params, extractor, depth): return self class TemplateArg(object): """ parameter to a template. Has a name and a default value, both of which are Templates. """ def __init__(self, parameter): """ :param parameter: the parts of a tplarg. """ # the parameter name itself might contain templates, e.g.: # appointe{{#if:{{{appointer14|}}}|r|d}}14| # 4|{{{{{subst|}}}CURRENTYEAR}} # any parts in a tplarg after the first (the parameter default) are # ignored, and an equals sign in the first part is treated as plain text. # logging.debug('TemplateArg %s', parameter) parts = splitParts(parameter) self.name = Template.parse(parts[0]) if len(parts) > 1: # This parameter has a default value self.default = Template.parse(parts[1]) else: self.default = None def __str__(self): if self.default: return '{{{%s|%s}}}' % (self.name, self.default) else: return '{{{%s}}}' % self.name def subst(self, params, extractor, depth): """ Substitute value for this argument from dict :param params: Use :param extractor: to evaluate expressions for name and default. Limit substitution to the maximun :param depth:. """ # the parameter name itself might contain templates, e.g.: # appointe{{#if:{{{appointer14|}}}|r|d}}14| paramName = self.name.subst(params, extractor, depth + 1) paramName = extractor.transform(paramName) res = '' if paramName in params: res = params[paramName] # use parameter value specified in template invocation elif self.default: # use the default value defaultValue = self.default.subst(params, extractor, depth + 1) res = extractor.transform(defaultValue) # logging.debug('subst arg %d %s -> %s' % (depth, paramName, res)) return res class Frame(object): def __init__(self, title='', args=[], prev=None): self.title = title self.args = args self.prev = prev self.depth = prev.depth + 1 if prev else 0 def push(self, title, args): return Frame(title, args, self) def pop(self): return self.prev def __str__(self): res = '' prev = self.prev while prev: if res: res += ', ' res += '(%s, %s)' % (prev.title, prev.args) prev = prev.prev return '<Frame [' + res + ']>' # ====================================================================== substWords = 'subst:|safesubst:' class Extractor(object): """ An extraction task on a article. """ def __init__(self, id, revid, title, lines): """ :param id: id of page. :param title: tutle of page. :param lines: a list of lines. """ self.id = id self.revid = revid self.title = title self.text = ''.join(lines) self.magicWords = MagicWords() self.frame = Frame() self.recursion_exceeded_1_errs = 0 # template recursion within expand() self.recursion_exceeded_2_errs = 0 # template recursion within expandTemplate() self.recursion_exceeded_3_errs = 0 # parameter recursion self.template_title_errs = 0 def write_output(self, out, text): """ :param out: a memory file :param text: the text of the page """ url = get_url(self.id) if options.write_json: json_data = { 'id': self.id, 'url': url, 'title': self.title, 'text': "\n".join(text) } if options.print_revision: json_data['revid'] = self.revid # We don't use json.dump(data, out) because we want to be # able to encode the string if the output is sys.stdout out_str = json.dumps(json_data, ensure_ascii=False) if out == sys.stdout: # option -a or -o - out_str = out_str.encode('utf-8') out.write(out_str) out.write('\n') else: for line in text: if out == sys.stdout: # option -a or -o - line = line.encode('utf-8') out.write(line) out.write('\n') def extract(self, out): """ :param out: a memory file. """ logging.info('%s\t%s', self.id, self.title) # https://www.mediawiki.org/wiki/Help:Magic_words colon = self.title.find(':') if colon != -1: ns = self.title[:colon] pagename = self.title[colon + 1:] else: ns = '' # Main pagename = self.title self.magicWords['NAMESPACE'] = ns self.magicWords['NAMESPACENUMBER'] = options.knownNamespaces.get(ns, '0') self.magicWords['PAGENAME'] = pagename self.magicWords['FULLPAGENAME'] = self.title slash = pagename.rfind('/') if slash != -1: self.magicWords['BASEPAGENAME'] = pagename[:slash] self.magicWords['SUBPAGENAME'] = pagename[slash + 1:] else: self.magicWords['BASEPAGENAME'] = pagename self.magicWords['SUBPAGENAME'] = '' slash = pagename.find('/') if slash != -1: self.magicWords['ROOTPAGENAME'] = pagename[:slash] else: self.magicWords['ROOTPAGENAME'] = pagename self.magicWords['CURRENTYEAR'] = time.strftime('%Y') self.magicWords['CURRENTMONTH'] = time.strftime('%m') self.magicWords['CURRENTDAY'] = time.strftime('%d') self.magicWords['CURRENTHOUR'] = time.strftime('%H') self.magicWords['CURRENTTIME'] = time.strftime('%H:%M:%S') text = self.text self.text = '' # save memory # # @see https://doc.wikimedia.org/mediawiki-core/master/php/classParser.html # This does the equivalent of internalParse(): # # $dom = $this->preprocessToDom( $text, $flag ); # $text = $frame->expand( $dom ); # # ############### Process HTML ############### # turn into HTML, except for the content of <syntaxhighlight> res = '' cur = 0 for m in syntaxhighlight.finditer(text): res += unescape(text[cur:m.start()]) + m.group(1) cur = m.end() text = res + unescape(text[cur:]) text = self.transform(text) text = self.wiki2text(text) text = compact(self.clean(text)) if sum(len(line) for line in text) < options.min_text_length: return self.write_output(out, text) errs = (self.template_title_errs, self.recursion_exceeded_1_errs, self.recursion_exceeded_2_errs, self.recursion_exceeded_3_errs) if any(errs): logging.warning("Template errors in article '%s' (%s): title(%d) recursion(%d, %d, %d)", self.title, self.id, *errs) def transform(self, wikitext): """ Transforms wiki markup. @see https://www.mediawiki.org/wiki/Help:Formatting """ # look for matching <nowiki>...</nowiki> res = '' cur = 0 for m in nowiki.finditer(wikitext, cur): res += self.transform1(wikitext[cur:m.start()]) + wikitext[m.start() + 8:m.end() - 9] cur = m.end() # leftover res += self.transform1(wikitext[cur:]) return res def transform1(self, text): """Transform text not containing <nowiki>""" if options.expand_templates: # expand templates # See: http://www.mediawiki.org/wiki/Help:Templates return self.expand(text) else: # Drop transclusions (template, parser functions) return dropNested(text, r'{{', r'}}') def wiki2text(self, text): # # final part of internalParse().) # # $text = $this->doTableStuff( $text ); # $text = preg_replace( '/(^|\n)-----*/', '\\1<hr />', $text ); # $text = $this->doDoubleUnderscore( $text ); # $text = $this->doHeadings( $text ); # $text = $this->replaceInternalLinks( $text ); # $text = $this->doAllQuotes( $text ); # $text = $this->replaceExternalLinks( $text ); # $text = str_replace( self::MARKER_PREFIX . 'NOPARSE', '', $text ); # $text = $this->doMagicLinks( $text ); # $text = $this->formatHeadings( $text, $origText, $isMain ); # Drop tables # first drop residual templates, or else empty parameter |} might look like end of table. if not options.keep_tables: text = dropNested(text, r'{{', r'}}') text = dropNested(text, r'{\|', r'\|}') # Handle bold/italic/quote if options.toHTML: text = bold_italic.sub(r'<b>\1</b>', text) text = bold.sub(r'<b>\1</b>', text) text = italic.sub(r'<i>\1</i>', text) else: text = bold_italic.sub(r'\1', text) text = bold.sub(r'\1', text) text = italic_quote.sub(r'"\1"', text) text = italic.sub(r'"\1"', text) text = quote_quote.sub(r'"\1"', text) # residuals of unbalanced quotes text = text.replace("'''", '').replace("''", '"') # drop MagicWords behavioral switches text = magicWordsRE.sub('', text) # Collect spans spans = [] # Drop HTML comments for m in comment.finditer(text): spans.append((m.start(), m.end())) # Drop self-closing tags for pattern in selfClosing_tag_patterns: for m in pattern.finditer(text): spans.append((m.start(), m.end())) # Drop ignored tags for left, right in options.ignored_tag_patterns: for m in left.finditer(text): spans.append((m.start(), m.end())) for m in right.finditer(text): spans.append((m.start(), m.end())) # Bulk remove all spans text = dropSpans(spans, text) # Replace br with \n text = re.compile(r'(<\s*br\b[^>]*/\s*>)|(<br\b\s*>)', re.DOTALL | re.IGNORECASE).sub('\n', text) # Drop discarded elements for tag in options.discardElements: text = dropNested(text, r'<\s*%s\b[^>]*>' % tag, r'<\s*/\s*%s>' % tag) if not options.toHTML: # Turn into text what is left (&amp;nbsp;) and <syntaxhighlight> text = unescape(text) # replace internal links text = replaceInternalLinks(text) # assert '[[' not in text, "003 " + text # replace external links text = replaceExternalLinks(text) return text def clean(self, text): """ Removes irrelevant parts from :param: text. """ # Expand placeholders for pattern, placeholder in placeholder_tag_patterns: index = 1 for match in pattern.finditer(text): text = text.replace(match.group(), '%s_%d' % (placeholder, index)) index += 1 text = text.replace('<<', '«').replace('>>', '»') ############################################# # Cleanup text text = '\n' + text + '\n' text = text.replace('\t', ' ') text = spaces.sub(' ', text) text = dots.sub('...', text) text = re.sub(' (,:\.\)\]»)', r'\1', text) text = re.sub('(\[\(«) ', r'\1', text) text = text.replace(',,', ',').replace(',.', '.') text = re.sub(r'(^[ \t]+)|([ \t]+$)', '', text, flags=re.MULTILINE) # text = re.sub(r'\\', ' ', text) text = re.sub(r' \*([^\s])', r' \1', text) text = re.sub(r'(\w)\n([a-z])', r'\1 \2', text) text = re.sub(r'^\|.*$', '', text, flags=re.MULTILINE) text = text.strip() if options.keep_tables: # the following regular expressions are used to remove the wikiml chartacters around table strucutures # yet keep the content. The order here is imporant so we remove certain markup like {| and then # then the future html attributes such as 'style'. Finally we drop the remaining '|-' that delimits cells. text = re.sub(r'!(?:\s)?style=\"[a-z]+:(?:\d+)%;\"', r'', text) text = re.sub(r'!(?:\s)?style="[a-z]+:(?:\d+)%;[a-z]+:(?:#)?(?:[0-9a-z]+)?"', r'', text) text = text.replace('|-', '') text = text.replace('|', '') if options.toHTML: text = html.escape(text) return text # ---------------------------------------------------------------------- # Expand templates maxTemplateRecursionLevels = 30 maxParameterRecursionLevels = 10 # check for template beginning reOpen = re.compile('(?<!{){{(?!{)', re.DOTALL) def expand(self, wikitext): """ :param wikitext: the text to be expanded. Templates are frequently nested. Occasionally, parsing mistakes may cause template insertion to enter an infinite loop, for instance when trying to instantiate Template:Country {{country_{{{1}}}|{{{2}}}|{{{2}}}|size={{{size|}}}|name={{{name|}}}}} which is repeatedly trying to insert template 'country_', which is again resolved to Template:Country. The straightforward solution of keeping track of templates that were already inserted for the current article would not work, because the same template may legally be used more than once, with different parameters in different parts of the article. Therefore, we limit the number of iterations of nested template inclusion. """ # Test template expansion at: # https://en.wikipedia.org/wiki/Special:ExpandTemplates # https://it.wikipedia.org/wiki/Speciale:EspandiTemplate res = '' if self.frame.depth >= self.maxTemplateRecursionLevels: self.recursion_exceeded_1_errs += 1 return res # logging.debug('%*s<expand', self.frame.depth, '') cur = 0 # look for matching {{...}} for s, e in findMatchingBraces(wikitext, 2): res += wikitext[cur:s] + self.expandTemplate(wikitext[s + 2:e - 2]) cur = e # leftover res += wikitext[cur:] # logging.debug('%*sexpand> %s', self.frame.depth, '', res) return res def templateParams(self, parameters): """ Build a dictionary with positional or name key to expanded parameters. :param parameters: the parts[1:] of a template, i.e. all except the title. """ templateParams = {} if not parameters: return templateParams # logging.debug('%*s<templateParams: %s', self.frame.length, '', '|'.join(parameters)) # Parameters can be either named or unnamed. In the latter case, their # name is defined by their ordinal position (1, 2, 3, ...). unnamedParameterCounter = 0 # It's legal for unnamed parameters to be skipped, in which case they # will get default values (if available) during actual instantiation. # That is {{template_name|a||c}} means parameter 1 gets # the value 'a', parameter 2 value is not defined, and parameter 3 gets # the value 'c'. This case is correctly handled by function 'split', # and does not require any special handling. for param in parameters: # Spaces before or after a parameter value are normally ignored, # UNLESS the parameter contains a link (to prevent possible gluing # the link to the following text after template substitution) # Parameter values may contain "=" symbols, hence the parameter # name extends up to the first such symbol. # It is legal for a parameter to be specified several times, in # which case the last assignment takes precedence. Example: # "{{t|a|b|c|2=B}}" is equivalent to "{{t|a|B|c}}". # Therefore, we don't check if the parameter has been assigned a # value before, because anyway the last assignment should override # any previous ones. # FIXME: Don't use DOTALL here since parameters may be tags with # attributes, e.g. <div class="templatequotecite"> # Parameters may span several lines, like: # {{Reflist|colwidth=30em|refs= # &lt;ref name=&quot;Goode&quot;&gt;Title&lt;/ref&gt; # The '=' might occurr within an HTML attribute: # "&lt;ref name=value" # but we stop at first. m = re.match(' *([^=]*?) *?=(.*)', param, re.DOTALL) if m: # This is a named parameter. This case also handles parameter # assignments like "2=xxx", where the number of an unnamed # parameter ("2") is specified explicitly - this is handled # transparently. parameterName = m.group(1).strip() parameterValue = m.group(2) if ']]' not in parameterValue: # if the value does not contain a link, trim whitespace parameterValue = parameterValue.strip() templateParams[parameterName] = parameterValue else: # this is an unnamed parameter unnamedParameterCounter += 1 if ']]' not in param: # if the value does not contain a link, trim whitespace param = param.strip() templateParams[str(unnamedParameterCounter)] = param # logging.debug('%*stemplateParams> %s', self.frame.length, '', '|'.join(templateParams.values())) return templateParams def expandTemplate(self, body): """Expands template invocation. :param body: the parts of a template. :see http://meta.wikimedia.org/wiki/Help:Expansion for an explanation of the process. See in particular: Expansion of names and values http://meta.wikimedia.org/wiki/Help:Expansion#Expansion_of_names_and_values For most parser functions all names and values are expanded, regardless of what is relevant for the result. The branching functions (#if, #ifeq, #iferror, #ifexist, #ifexpr, #switch) are exceptions. All names in a template call are expanded, and the titles of the tplargs in the template body, after which it is determined which values must be expanded, and for which tplargs in the template body the first part (default) [sic in the original doc page]. In the case of a tplarg, any parts beyond the first are never expanded. The possible name and the value of the first part is expanded if the title does not match a name in the template call. :see code for braceSubstitution at https://doc.wikimedia.org/mediawiki-core/master/php/html/Parser_8php_source.html#3397: """ # template = "{{" parts "}}" # Templates and tplargs are decomposed in the same way, with pipes as # separator, even though eventually any parts in a tplarg after the first # (the parameter default) are ignored, and an equals sign in the first # part is treated as plain text. # Pipes inside inner templates and tplargs, or inside double rectangular # brackets within the template or tplargs are not taken into account in # this decomposition. # The first part is called title, the other parts are simply called parts. # If a part has one or more equals signs in it, the first equals sign # determines the division into name = value. Equals signs inside inner # templates and tplargs, or inside double rectangular brackets within the # part are not taken into account in this decomposition. Parts without # equals sign are indexed 1, 2, .., given as attribute in the <name> tag. if self.frame.depth >= self.maxTemplateRecursionLevels: self.recursion_exceeded_2_errs += 1 # logging.debug('%*sEXPAND> %s', self.frame.depth, '', body) return '' logging.debug('%*sEXPAND %s', self.frame.depth, '', body) parts = splitParts(body) # title is the portion before the first | title = parts[0].strip() title = self.expand(title) # SUBST # Apply the template tag to parameters without # substituting into them, e.g. # {{subst:t|a{{{p|q}}}b}} gives the wikitext start-a{{{p|q}}}b-end # @see https://www.mediawiki.org/wiki/Manual:Substitution#Partial_substitution subst = False if re.match(substWords, title, re.IGNORECASE): title = re.sub(substWords, '', title, 1, re.IGNORECASE) subst = True if title in self.magicWords.values: ret = self.magicWords[title] logging.debug('%*s<EXPAND %s %s', self.frame.depth, '', title, ret) return ret # Parser functions. # For most parser functions all names and values are expanded, # regardless of what is relevant for the result. The branching # functions (#if, #ifeq, #iferror, #ifexist, #ifexpr, #switch) are # exceptions: for #if, #iferror, #ifexist, #ifexp, only the part that # is applicable is expanded; for #ifeq the first and the applicable # part are expanded; for #switch, expanded are the names up to and # including the match (or all if there is no match), and the value in # the case of a match or if there is no match, the default, if any. # The first argument is everything after the first colon. # It has been evaluated above. colon = title.find(':') if colon > 1: funct = title[:colon] parts[0] = title[colon + 1:].strip() # side-effect (parts[0] not used later) # arguments after first are not evaluated ret = callParserFunction(funct, parts, self) logging.debug('%*s<EXPAND %s %s', self.frame.depth, '', funct, ret) return ret title = fullyQualifiedTemplateTitle(title) if not title: self.template_title_errs += 1 return '' redirected = options.redirects.get(title) if redirected: title = redirected # get the template if title in options.templateCache: template = options.templateCache[title] elif title in options.templates: template = Template.parse(options.templates[title]) # add it to cache options.templateCache[title] = template del options.templates[title] else: # The page being included could not be identified logging.debug('%*s<EXPAND %s %s', self.frame.depth, '', title, '') return '' logging.debug('%*sTEMPLATE %s: %s', self.frame.depth, '', title, template) # tplarg = "{{{" parts "}}}" # parts = [ title *( "|" part ) ] # part = ( part-name "=" part-value ) / ( part-value ) # part-name = wikitext-L3 # part-value = wikitext-L3 # wikitext-L3 = literal / template / tplarg / link / comment / # line-eating-comment / unclosed-comment / # xmlish-element / *wikitext-L3 # A tplarg may contain other parameters as well as templates, e.g.: # {{{text|{{{quote|{{{1|{{error|Error: No text given}}}}}}}}}}} # hence no simple RE like this would work: # '{{{((?:(?!{{{).)*?)}}}' # We must use full CF parsing. # the parameter name itself might be computed, e.g.: # {{{appointe{{#if:{{{appointer14|}}}|r|d}}14|}}} # Because of the multiple uses of double-brace and triple-brace # syntax, expressions can sometimes be ambiguous. # Precedence rules specifed here: # http://www.mediawiki.org/wiki/Preprocessor_ABNF#Ideal_precedence # resolve ambiguities like this: # {{{{ }}}} -> { {{{ }}} } # {{{{{ }}}}} -> {{ {{{ }}} }} # # :see: https://en.wikipedia.org/wiki/Help:Template#Handling_parameters params = parts[1:] # Order of evaluation. # Template parameters are fully evaluated before they are passed to the template. # :see: https://www.mediawiki.org/wiki/Help:Templates#Order_of_evaluation if not subst: # Evaluate parameters, since they may contain templates, including # the symbol "=". # {{#ifexpr: {{{1}}} = 1 }} params = [self.transform(p) for p in params] # build a dict of name-values for the parameter values params = self.templateParams(params) # Perform parameter substitution. # Extend frame before subst, since there may be recursion in default # parameter value, e.g. {{OTRS|celebrative|date=April 2015}} in article # 21637542 in enwiki. self.frame = self.frame.push(title, params) instantiated = template.subst(params, self) value = self.transform(instantiated) self.frame = self.frame.pop() logging.debug('%*s<EXPAND %s %s', self.frame.depth, '', title, value) return value # ---------------------------------------------------------------------- # parameter handling def splitParts(paramsList): """ :param paramsList: the parts of a template or tplarg. Split template parameters at the separator "|". separator "=". Template parameters often contain URLs, internal links, text or even template expressions, since we evaluate templates outside in. This is required for cases like: {{#if: {{{1}}} | {{lc:{{{1}}} | "parameter missing"}} Parameters are separated by "|" symbols. However, we cannot simply split the string on "|" symbols, since these also appear inside templates and internal links, e.g. {{if:| |{{#if:the president| |{{#if:| [[Category:Hatnote templates|A{{PAGENAME}}]] }} }} }} We split parts at the "|" symbols that are not inside any pair {{{...}}}, {{...}}, [[...]], {|...|}. """ # Must consider '[' as normal in expansion of Template:EMedicine2: # #ifeq: ped|article|[http://emedicine.medscape.com/article/180-overview|[http://www.emedicine.com/ped/topic180.htm#{{#if: |section~}} # as part of: # {{#ifeq: ped|article|[http://emedicine.medscape.com/article/180-overview|[http://www.emedicine.com/ped/topic180.htm#{{#if: |section~}}}} ped/180{{#if: |~}}] # should handle both tpl arg like: # 4|{{{{{subst|}}}CURRENTYEAR}} # and tpl parameters like: # ||[[Category:People|{{#if:A|A|{{PAGENAME}}}}]] sep = '|' parameters = [] cur = 0 for s, e in findMatchingBraces(paramsList): par = paramsList[cur:s].split(sep) if par: if parameters: # portion before | belongs to previous parameter parameters[-1] += par[0] if len(par) > 1: # rest are new parameters parameters.extend(par[1:]) else: parameters = par elif not parameters: parameters = [''] # create first param # add span to last previous parameter parameters[-1] += paramsList[s:e] cur = e # leftover par = paramsList[cur:].split(sep) if par: if parameters: # portion before | belongs to previous parameter parameters[-1] += par[0] if len(par) > 1: # rest are new parameters parameters.extend(par[1:]) else: parameters = par # logging.debug('splitParts %s %s\nparams: %s', sep, paramsList, text_type(parameters)) return parameters def findMatchingBraces(text, ldelim=0): """ :param ldelim: number of braces to match. 0 means match [[]], {{}} and {{{}}}. """ # Parsing is done with respect to pairs of double braces {{..}} delimiting # a template, and pairs of triple braces {{{..}}} delimiting a tplarg. # If double opening braces are followed by triple closing braces or # conversely, this is taken as delimiting a template, with one left-over # brace outside it, taken as plain text. For any pattern of braces this # defines a set of templates and tplargs such that any two are either # separate or nested (not overlapping). # Unmatched double rectangular closing brackets can be in a template or # tplarg, but unmatched double rectangular opening brackets cannot. # Unmatched double or triple closing braces inside a pair of # double rectangular brackets are treated as plain text. # Other formulation: in ambiguity between template or tplarg on one hand, # and a link on the other hand, the structure with the rightmost opening # takes precedence, even if this is the opening of a link without any # closing, so not producing an actual link. # In the case of more than three opening braces the last three are assumed # to belong to a tplarg, unless there is no matching triple of closing # braces, in which case the last two opening braces are are assumed to # belong to a template. # We must skip individual { like in: # {{#ifeq: {{padleft:|1|}} | { | | &nbsp;}} # We must resolve ambiguities like this: # {{{{ }}}} -> { {{{ }}} } # {{{{{ }}}}} -> {{ {{{ }}} }} # {{#if:{{{{{#if:{{{nominee|}}}|nominee|candidate}}|}}}|...}} # {{{!}} {{!}}} # Handle: # {{{{{|safesubst:}}}#Invoke:String|replace|{{{1|{{{{{|safesubst:}}}PAGENAME}}}}}|%s+%([^%(]-%)$||plain=false}} # as well as expressions with stray }: # {{{link|{{ucfirst:{{{1}}}}}} interchange}}} if ldelim: # 2-3 reOpen = re.compile('[{]{%d,}' % ldelim) # at least ldelim reNext = re.compile('[{]{2,}|}{2,}') # at least 2 else: reOpen = re.compile('{{2,}|\[{2,}') reNext = re.compile('{{2,}|}{2,}|\[{2,}|]{2,}') # at least 2 cur = 0 while True: m1 = reOpen.search(text, cur) if not m1: return lmatch = m1.end() - m1.start() if m1.group()[0] == '{': stack = [lmatch] # stack of opening braces lengths else: stack = [-lmatch] # negative means [ end = m1.end() while True: m2 = reNext.search(text, end) if not m2: return # unbalanced end = m2.end() brac = m2.group()[0] lmatch = m2.end() - m2.start() if brac == '{': stack.append(lmatch) elif brac == '}': while stack: openCount = stack.pop() # opening span if openCount == 0: # illegal unmatched [[ continue if lmatch >= openCount: lmatch -= openCount if lmatch <= 1: # either close or stray } break else: # put back unmatched stack.append(openCount - lmatch) break if not stack: yield m1.start(), end - lmatch cur = end break elif len(stack) == 1 and 0 < stack[0] < ldelim: # ambiguous {{{{{ }}} }} # yield m1.start() + stack[0], end cur = end break elif brac == '[': # [[ stack.append(-lmatch) else: # ]] while stack and stack[-1] < 0: # matching [[ openCount = -stack.pop() if lmatch >= openCount: lmatch -= openCount if lmatch <= 1: # either close or stray ] break else: # put back unmatched (negative) stack.append(lmatch - openCount) break if not stack: yield m1.start(), end - lmatch cur = end break # unmatched ]] are discarded cur = end def findBalanced(text, openDelim=('[[',), closeDelim=(']]',)): """ Assuming that text contains a properly balanced expression using :param openDelim: as opening delimiters and :param closeDelim: as closing delimiters. :return: an iterator producing pairs (start, end) of start and end positions in text containing a balanced expression. """ openPat = '|'.join([re.escape(x) for x in openDelim]) # pattern for delimiters expected after each opening delimiter afterPat = {o: re.compile(openPat + '|' + c, re.DOTALL) for o, c in zip(openDelim, closeDelim)} stack = [] start = 0 cur = 0 # end = len(text) startSet = False startPat = re.compile(openPat) nextPat = startPat while True: next = nextPat.search(text, cur) if not next: return if not startSet: start = next.start() startSet = True delim = next.group(0) if delim in openDelim: stack.append(delim) nextPat = afterPat[delim] else: opening = stack.pop() # assert opening == openDelim[closeDelim.index(next.group(0))] if stack: nextPat = afterPat[stack[-1]] else: yield start, next.end() nextPat = startPat start = next.end() startSet = False cur = next.end() # ---------------------------------------------------------------------- # Modules # Only minimal support # FIXME: import Lua modules. def if_empty(*rest): """ This implements If_empty from English Wikipedia module: <title>Module:If empty</title> <ns>828</ns> <text>local p = {} function p.main(frame) local args = require('Module:Arguments').getArgs(frame, {wrappers = 'Template:If empty', removeBlanks = false}) -- For backwards compatibility reasons, the first 8 parameters can be unset instead of being blank, -- even though there's really no legitimate use case for this. At some point, this will be removed. local lowestNil = math.huge for i = 8,1,-1 do if args[i] == nil then args[i] = '' lowestNil = i end end for k,v in ipairs(args) do if v ~= '' then if lowestNil &lt; k then -- If any uses of this template depend on the behavior above, add them to a tracking category. -- This is a rather fragile, convoluted, hacky way to do it, but it ensures that this module's output won't be modified -- by it. frame:extensionTag('ref', '[[Category:Instances of Template:If_empty missing arguments]]', {group = 'TrackingCategory'}) frame:extensionTag('references', '', {group = 'TrackingCategory'}) end return v end end end return p </text> """ for arg in rest: if arg: return arg return '' # ---------------------------------------------------------------------- # String module emulation # https://en.wikipedia.org/wiki/Module:String def functionParams(args, vars): """ Build a dictionary of var/value from :param: args. Parameters can be either named or unnamed. In the latter case, their name is taken fron :param: vars. """ params = {} index = 1 for var in vars: value = args.get(var) if value is None: value = args.get(str(index)) # positional argument if value is None: value = '' else: index += 1 params[var] = value return params def string_sub(args): params = functionParams(args, ('s', 'i', 'j')) s = params.get('s', '') i = int(params.get('i', 1) or 1) # or handles case of '' value j = int(params.get('j', -1) or -1) if i > 0: i -= 1 # lua is 1-based if j < 0: j += 1 if j == 0: j = len(s) return s[i:j] def string_sublength(args): params = functionParams(args, ('s', 'i', 'len')) s = params.get('s', '') i = int(params.get('i', 1) or 1) - 1 # lua is 1-based len = int(params.get('len', 1) or 1) return s[i:i + len] def string_len(args): params = functionParams(args, ('s')) s = params.get('s', '') return len(s) def string_find(args): params = functionParams(args, ('source', 'target', 'start', 'plain')) source = params.get('source', '') pattern = params.get('target', '') start = int('0' + params.get('start', 1)) - 1 # lua is 1-based plain = int('0' + params.get('plain', 1)) if source == '' or pattern == '': return 0 if plain: return source.find(pattern, start) + 1 # lua is 1-based else: return (re.compile(pattern).search(source, start) or -1) + 1 def string_pos(args): params = functionParams(args, ('target', 'pos')) target = params.get('target', '') pos = int(params.get('pos', 1) or 1) if pos > 0: pos -= 1 # The first character has an index value of 1 return target[pos] def string_replace(args): params = functionParams(args, ('source', 'pattern', 'replace', 'count', 'plain')) source = params.get('source', '') pattern = params.get('pattern', '') replace = params.get('replace', '') count = int(params.get('count', 0) or 0) plain = int(params.get('plain', 1) or 1) if plain: if count: return source.replace(pattern, replace, count) else: return source.replace(pattern, replace) else: return re.compile(pattern).sub(replace, source, count) def string_rep(args): params = functionParams(args, ('s')) source = params.get('source', '') count = int(params.get('count', '1')) return source * count # ---------------------------------------------------------------------- # Module:Roman # http://en.wikipedia.org/w/index.php?title=Module:Roman # Modulo:Numero_romano # https://it.wikipedia.org/wiki/Modulo:Numero_romano def roman_main(args): """Convert first arg to roman numeral if <= 5000 else :return: second arg.""" num = int(float(args.get('1'))) # Return a message for numbers too big to be expressed in Roman numerals. if 0 > num or num >= 5000: return args.get('2', 'N/A') def toRoman(n, romanNumeralMap): """convert integer to Roman numeral""" result = "" for integer, numeral in romanNumeralMap: while n >= integer: result += numeral n -= integer return result # Find the Roman numerals for numbers 4999 or less. smallRomans = ( (1000, "M"), (900, "CM"), (500, "D"), (400, "CD"), (100, "C"), (90, "XC"), (50, "L"), (40, "XL"), (10, "X"), (9, "IX"), (5, "V"), (4, "IV"), (1, "I") ) return toRoman(num, smallRomans) # ---------------------------------------------------------------------- modules = { 'convert': { 'convert': lambda x, u, *rest: x + ' ' + u, # no conversion }, 'If empty': { 'main': if_empty }, 'String': { 'len': string_len, 'sub': string_sub, 'sublength': string_sublength, 'pos': string_pos, 'find': string_find, 'replace': string_replace, 'rep': string_rep, }, 'Roman': { 'main': roman_main }, 'Numero romano': { 'main': roman_main } } # ---------------------------------------------------------------------- # variables class MagicWords(object): """ One copy in each Extractor. @see https://doc.wikimedia.org/mediawiki-core/master/php/MagicWord_8php_source.html """ names = [ '!', 'currentmonth', 'currentmonth1', 'currentmonthname', 'currentmonthnamegen', 'currentmonthabbrev', 'currentday', 'currentday2', 'currentdayname', 'currentyear', 'currenttime', 'currenthour', 'localmonth', 'localmonth1', 'localmonthname', 'localmonthnamegen', 'localmonthabbrev', 'localday', 'localday2', 'localdayname', 'localyear', 'localtime', 'localhour', 'numberofarticles', 'numberoffiles', 'numberofedits', 'articlepath', 'pageid', 'sitename', 'server', 'servername', 'scriptpath', 'stylepath', 'pagename', 'pagenamee', 'fullpagename', 'fullpagenamee', 'namespace', 'namespacee', 'namespacenumber', 'currentweek', 'currentdow', 'localweek', 'localdow', 'revisionid', 'revisionday', 'revisionday2', 'revisionmonth', 'revisionmonth1', 'revisionyear', 'revisiontimestamp', 'revisionuser', 'revisionsize', 'subpagename', 'subpagenamee', 'talkspace', 'talkspacee', 'subjectspace', 'subjectspacee', 'talkpagename', 'talkpagenamee', 'subjectpagename', 'subjectpagenamee', 'numberofusers', 'numberofactiveusers', 'numberofpages', 'currentversion', 'rootpagename', 'rootpagenamee', 'basepagename', 'basepagenamee', 'currenttimestamp', 'localtimestamp', 'directionmark', 'contentlanguage', 'numberofadmins', 'cascadingsources', ] def __init__(self): self.values = {'!': '|'} def __getitem__(self, name): return self.values.get(name) def __setitem__(self, name, value): self.values[name] = value switches = ( '__NOTOC__', '__FORCETOC__', '__TOC__', '__TOC__', '__NEWSECTIONLINK__', '__NONEWSECTIONLINK__', '__NOGALLERY__', '__HIDDENCAT__', '__NOCONTENTCONVERT__', '__NOCC__', '__NOTITLECONVERT__', '__NOTC__', '__START__', '__END__', '__INDEX__', '__NOINDEX__', '__STATICREDIRECT__', '__DISAMBIG__' ) magicWordsRE = re.compile('|'.join(MagicWords.switches)) # ---------------------------------------------------------------------- # parser functions utilities def ucfirst(string): """:return: a string with just its first character uppercase We can't use title() since it coverts all words. """ if string: return string[0].upper() + string[1:] else: return '' def lcfirst(string): """:return: a string with its first character lowercase""" if string: if len(string) > 1: return string[0].lower() + string[1:] else: return string.lower() else: return '' def fullyQualifiedTemplateTitle(templateTitle): """ Determine the namespace of the page being included through the template mechanism """ if templateTitle.startswith(':'): # Leading colon by itself implies main namespace, so strip this colon return ucfirst(templateTitle[1:]) else: m = re.match('([^:]*)(:.*)', templateTitle) if m: # colon found but not in the first position - check if it # designates a known namespace prefix = normalizeNamespace(m.group(1)) if prefix in options.knownNamespaces: return prefix + ucfirst(m.group(2)) # The title of the page being included is NOT in the main namespace and # lacks any other explicit designation of the namespace - therefore, it # is resolved to the Template namespace (that's the default for the # template inclusion mechanism). # This is a defense against pages whose title only contains UTF-8 chars # that are reduced to an empty string. Right now I can think of one such # case - <C2><A0> which represents the non-breaking space. # In this particular case, this page is a redirect to [[Non-nreaking # space]], but having in the system a redirect page with an empty title # causes numerous problems, so we'll live happier without it. if templateTitle: return options.templatePrefix + ucfirst(templateTitle) else: return '' # caller may log as error def normalizeNamespace(ns): return ucfirst(ns) # ---------------------------------------------------------------------- # Parser functions # see http://www.mediawiki.org/wiki/Help:Extension:ParserFunctions # https://github.com/Wikia/app/blob/dev/extensions/ParserFunctions/ParserFunctions_body.php class Infix: """Infix operators. The calling sequence for the infix is: x |op| y """ def __init__(self, function): self.function = function def __ror__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __or__(self, other): return self.function(other) def __rlshift__(self, other): return Infix(lambda x, self=self, other=other: self.function(other, x)) def __rshift__(self, other): return self.function(other) def __call__(self, value1, value2): return self.function(value1, value2) ROUND = Infix(lambda x, y: round(x, y)) def sharp_expr(extr, expr): """Tries converting a lua expr into a Python expr.""" try: expr = extr.expand(expr) expr = re.sub('(?<![!<>])=', '==', expr) # negative lookbehind expr = re.sub('mod', '%', expr) # no \b here expr = re.sub('\bdiv\b', '/', expr) expr = re.sub('\bround\b', '|ROUND|', expr) return text_type(eval(expr)) except: return '<span class="error">%s</span>' % expr def sharp_if(extr, testValue, valueIfTrue, valueIfFalse=None, *args): # In theory, we should evaluate the first argument here, # but it was evaluated while evaluating part[0] in expandTemplate(). if testValue.strip(): # The {{#if:}} function is an if-then-else construct. # The applied condition is: "The condition string is non-empty". valueIfTrue = extr.expand(valueIfTrue.strip()) # eval if valueIfTrue: return valueIfTrue elif valueIfFalse: return extr.expand(valueIfFalse.strip()) # eval return "" def sharp_ifeq(extr, lvalue, rvalue, valueIfTrue, valueIfFalse=None, *args): rvalue = rvalue.strip() if rvalue: # lvalue is always evaluated if lvalue.strip() == rvalue: # The {{#ifeq:}} function is an if-then-else construct. The # applied condition is "is rvalue equal to lvalue". Note that this # does only string comparison while MediaWiki implementation also # supports numerical comparissons. if valueIfTrue: return extr.expand(valueIfTrue.strip()) else: if valueIfFalse: return extr.expand(valueIfFalse.strip()) return "" def sharp_iferror(extr, test, then='', Else=None, *args): if re.match('<(?:strong|span|p|div)\s(?:[^\s>]*\s+)*?class="(?:[^"\s>]*\s+)*?error(?:\s[^">]*)?"', test): return extr.expand(then.strip()) elif Else is None: return test.strip() else: return extr.expand(Else.strip()) def sharp_switch(extr, primary, *params): # FIXME: we don't support numeric expressions in primary # {{#switch: comparison string # | case1 = result1 # | case2 # | case4 = result2 # | 1 | case5 = result3 # | #default = result4 # }} primary = primary.strip() found = False # for fall through cases default = None rvalue = None lvalue = '' for param in params: # handle cases like: # #default = [http://www.perseus.tufts.edu/hopper/text?doc=Perseus...] pair = param.split('=', 1) lvalue = extr.expand(pair[0].strip()) rvalue = None if len(pair) > 1: # got "=" rvalue = extr.expand(pair[1].strip()) # check for any of multiple values pipe separated if found or primary in [v.strip() for v in lvalue.split('|')]: # Found a match, return now return rvalue elif lvalue == '#default': default = rvalue rvalue = None # avoid defaulting to last case elif lvalue == primary: # If the value matches, set a flag and continue found = True # Default case # Check if the last item had no = sign, thus specifying the default case if rvalue is not None: return lvalue elif default is not None: return default return '' # Extension Scribunto: https://www.mediawiki.org/wiki/Extension:Scribunto def sharp_invoke(module, function, args): functions = modules.get(module) if functions: funct = functions.get(function) if funct: return text_type(funct(args)) return '' parserFunctions = { '#expr': sharp_expr, '#if': sharp_if, '#ifeq': sharp_ifeq, '#iferror': sharp_iferror, '#ifexpr': lambda *args: '', # not supported '#ifexist': lambda extr, title, ifex, ifnex: extr.expand(ifnex), # assuming title is not present '#rel2abs': lambda *args: '', # not supported '#switch': sharp_switch, '#language': lambda *args: '', # not supported '#time': lambda *args: '', # not supported '#timel': lambda *args: '', # not supported '#titleparts': lambda *args: '', # not supported # This function is used in some pages to construct links # http://meta.wikimedia.org/wiki/Help:URL 'urlencode': lambda extr, string, *rest: quote(string.encode('utf-8')), 'lc': lambda extr, string, *rest: string.lower() if string else '', 'lcfirst': lambda extr, string, *rest: lcfirst(string), 'uc': lambda extr, string, *rest: string.upper() if string else '', 'ucfirst': lambda extr, string, *rest: ucfirst(string), 'int': lambda extr, string, *rest: text_type(int(string)), } def callParserFunction(functionName, args, extractor): """ Parser functions have similar syntax as templates, except that the first argument is everything after the first colon. :return: the result of the invocation, None in case of failure. :param: args not yet expanded (see branching functions). https://www.mediawiki.org/wiki/Help:Extension:ParserFunctions """ try: # https://it.wikipedia.org/wiki/Template:Str_endswith has #Invoke functionName = functionName.lower() if functionName == '#invoke': module, fun = args[0].strip(), args[1].strip() logging.debug('%*s#invoke %s %s %s', extractor.frame.depth, '', module, fun, args[2:]) # special handling of frame if len(args) == 2: # find parameters in frame whose title is the one of the original # template invocation templateTitle = fullyQualifiedTemplateTitle(module) if not templateTitle: logging.warn("Template with empty title") params = None frame = extractor.frame while frame: if frame.title == templateTitle: params = frame.args break frame = frame.prev else: params = [extractor.transform(p) for p in args[2:]] # evaluates them params = extractor.templateParams(params) ret = sharp_invoke(module, fun, params) logging.debug('%*s<#invoke %s %s %s', extractor.frame.depth, '', module, fun, ret) return ret if functionName in parserFunctions: # branching functions use the extractor to selectively evaluate args return parserFunctions[functionName](extractor, *args) except: return "" # FIXME: fix errors return "" # ---------------------------------------------------------------------- # Expand using WikiMedia API # import json # def expand(text): # """Expand templates invoking MediaWiki API""" # text = urlib.urlencodew(text.encode('utf-8')) # base = urlbase[:urlbase.rfind('/')] # url = base + "/w/api.php?action=expandtemplates&format=json&text=" + text # exp = json.loads(urllib.urlopen(url)) # return exp['expandtemplates']['*'] # ---------------------------------------------------------------------- # Extract Template definition reNoinclude = re.compile(r'<noinclude>(?:.*?)</noinclude>', re.DOTALL) reIncludeonly = re.compile(r'<includeonly>|</includeonly>', re.DOTALL) def define_template(title, page): """ Adds a template defined in the :param page:. @see https://en.wikipedia.org/wiki/Help:Template#Noinclude.2C_includeonly.2C_and_onlyinclude """ # title = normalizeTitle(title) # sanity check (empty template, e.g. Template:Crude Oil Prices)) if not page: return # check for redirects m = re.match('#REDIRECT.*?\[\[([^\]]*)]]', page[0], re.IGNORECASE) if m: options.redirects[title] = m.group(1) # normalizeTitle(m.group(1)) return text = unescape(''.join(page)) # We're storing template text for future inclusion, therefore, # remove all <noinclude> text and keep all <includeonly> text # (but eliminate <includeonly> tags per se). # However, if <onlyinclude> ... </onlyinclude> parts are present, # then only keep them and discard the rest of the template body. # This is because using <onlyinclude> on a text fragment is # equivalent to enclosing it in <includeonly> tags **AND** # enclosing all the rest of the template body in <noinclude> tags. # remove comments text = comment.sub('', text) # eliminate <noinclude> fragments text = reNoinclude.sub('', text) # eliminate unterminated <noinclude> elements text = re.sub(r'<noinclude\s*>.*$', '', text, flags=re.DOTALL) text = re.sub(r'<noinclude/>', '', text) onlyincludeAccumulator = '' for m in re.finditer('<onlyinclude>(.*?)</onlyinclude>', text, re.DOTALL): onlyincludeAccumulator += m.group(1) if onlyincludeAccumulator: text = onlyincludeAccumulator else: text = reIncludeonly.sub('', text) if text: if title in options.templates: logging.warn('Redefining: %s', title) options.templates[title] = text # ---------------------------------------------------------------------- def dropNested(text, openDelim, closeDelim): """ A matching function for nested expressions, e.g. namespaces and tables. """ openRE = re.compile(openDelim, re.IGNORECASE) closeRE = re.compile(closeDelim, re.IGNORECASE) # partition text in separate blocks { } { } spans = [] # pairs (s, e) for each partition nest = 0 # nesting level start = openRE.search(text, 0) if not start: return text end = closeRE.search(text, start.end()) next = start while end: next = openRE.search(text, next.end()) if not next: # termination while nest: # close all pending nest -= 1 end0 = closeRE.search(text, end.end()) if end0: end = end0 else: break spans.append((start.start(), end.end())) break while end.end() < next.start(): # { } { if nest: nest -= 1 # try closing more last = end.end() end = closeRE.search(text, end.end()) if not end: # unbalanced if spans: span = (spans[0][0], last) else: span = (start.start(), last) spans = [span] break else: spans.append((start.start(), end.end())) # advance start, find next close start = next end = closeRE.search(text, next.end()) break # { } if next != start: # { { } nest += 1 # collect text outside partitions return dropSpans(spans, text) def dropSpans(spans, text): """ Drop from text the blocks identified in :param spans:, possibly nested. """ spans.sort() res = '' offset = 0 for s, e in spans: if offset <= s: # handle nesting if offset < s: res += text[offset:s] offset = e res += text[offset:] return res # ---------------------------------------------------------------------- # WikiLinks # May be nested [[File:..|..[[..]]..|..]], [[Category:...]], etc. # Also: [[Help:IPA for Catalan|[andora]]] def replaceInternalLinks(text): def func(inner): pipe = inner.find('|') if pipe < 0: title = inner label = title else: title = inner[:pipe].rstrip() last = inner.rfind('|', pipe + 1) if last >= 0: pipe = last label = inner[pipe + 1:].strip() return makeInternalLink(title, label) st = [] split1 = text.split('[[') for now1 in split1[:-1]: split2 = now1.split(']]') for now2 in split2[:-1]: while st and st[-1] != '[[': now2 = st.pop() + now2 if st and st[-1] == '[[': st.pop() now2 = func(now2) st.append(now2) st.append(split2[-1]) st.append('[[') split2 = split1[-1].split(']]') for now2 in split2[:-1]: while st and st[-1] != '[[': now2 = st.pop() + now2 if st and st[-1] == '[[': st.pop() now2 = func(now2) st.append(now2) st.append(split2[-1]) return ''.join([s if s != '[[' else ' ' for s in st]) def makeInternalLink(title, label): colon = title.find(':') if colon > 0 and title[:colon] not in options.acceptedNamespaces: return '' if colon == 0: # drop also :File: colon2 = title.find(':', colon + 1) if colon2 > 1 and title[colon + 1:colon2] not in options.acceptedNamespaces: return '' if options.keepLinks: return '<a href="%s">%s</a>' % (quote(title.encode('utf-8')), label) else: return label # ---------------------------------------------------------------------- # External links # from: https://doc.wikimedia.org/mediawiki-core/master/php/DefaultSettings_8php_source.html wgUrlProtocols = [ 'bitcoin:', 'ftp://', 'ftps://', 'geo:', 'git://', 'gopher://', 'http://', 'https://', 'irc://', 'ircs://', 'magnet:', 'mailto:', 'mms://', 'news:', 'nntp://', 'redis://', 'sftp://', 'sip:', 'sips:', 'sms:', 'ssh://', 'svn://', 'tel:', 'telnet://', 'urn:', 'worldwind://', 'xmpp:', '//' ] # from: https://doc.wikimedia.org/mediawiki-core/master/php/Parser_8php_source.html # Constants needed for external link processing # Everything except bracket, space, or control characters # \p{Zs} is unicode 'separator, space' category. It covers the space 0x20 # as well as U+3000 is IDEOGRAPHIC SPACE for bug 19052 EXT_LINK_URL_CLASS = r'[^][<>"\x00-\x20\x7F\s]' ANCHOR_CLASS = r'[^][\x00-\x08\x0a-\x1F]' ExtLinkBracketedRegex = re.compile( '\[(((?i)' + '|'.join(wgUrlProtocols) + ')' + EXT_LINK_URL_CLASS + r'+)' + r'\s*((?:' + ANCHOR_CLASS + r'|\[\[' + ANCHOR_CLASS + r'+\]\])' + r'*?)\]', re.S | re.U) # A simpler alternative: # ExtLinkBracketedRegex = re.compile(r'\[(.*?)\](?!])') EXT_IMAGE_REGEX = re.compile( r"""^(http://|https://)([^][<>"\x00-\x20\x7F\s]+) /([A-Za-z0-9_.,~%\-+&;#*?!=()@\x80-\xFF]+)\.((?i)gif|png|jpg|jpeg)$""", re.X | re.S | re.U) def replaceExternalLinks(text): """ https://www.mediawiki.org/wiki/Help:Links#External_links [URL anchor text] """ s = '' cur = 0 for m in ExtLinkBracketedRegex.finditer(text): s += text[cur:m.start()] cur = m.end() url = m.group(1) label = m.group(3) # # The characters '<' and '>' (which were escaped by # # removeHTMLtags()) should not be included in # # URLs, per RFC 2396. # m2 = re.search('&(lt|gt);', url) # if m2: # link = url[m2.end():] + ' ' + link # url = url[0:m2.end()] # If the link text is an image URL, replace it with an <img> tag # This happened by accident in the original parser, but some people used it extensively m = EXT_IMAGE_REGEX.match(label) if m: label = makeExternalImage(label) # Use the encoded URL # This means that users can paste URLs directly into the text # Funny characters like ö aren't valid in URLs anyway # This was changed in August 2004 s += makeExternalLink(url, label) # + trail return s + text[cur:] def makeExternalLink(url, anchor): """Function applied to wikiLinks""" if options.keepLinks: return '<a href="%s">%s</a>' % (quote(url.encode('utf-8')), anchor) else: return anchor def makeExternalImage(url, alt=''): if options.keepLinks: return '<img src="%s" alt="%s">' % (url, alt) else: return alt # ---------------------------------------------------------------------- # match tail after wikilink tailRE = re.compile('\w+') syntaxhighlight = re.compile('&lt;syntaxhighlight .*?&gt;(.*?)&lt;/syntaxhighlight&gt;', re.DOTALL) # skip level 1, it is page name level section = re.compile(r'(==+)\s*(.*?)\s*\1') listOpen = {'*': '<ul>', '#': '<ol>', ';': '<dl>', ':': '<dl>'} listClose = {'*': '</ul>', '#': '</ol>', ';': '</dl>', ':': '</dl>'} listItem = {'*': '<li>%s</li>', '#': '<li>%s</<li>', ';': '<dt>%s</dt>', ':': '<dd>%s</dd>'} def compact(text): """Deal with headers, lists, empty sections, residuals of tables. :param text: convert to HTML. """ page = [] # list of paragraph headers = {} # Headers for unfilled sections emptySection = False # empty sections are discarded listLevel = [] # nesting of lists listCount = [] # count of each list (it should be always in the same length of listLevel) for line in text.split('\n'): if not line: # collapse empty lines # if there is an opening list, close it if we see an empty line if len(listLevel): page.append(line) if options.toHTML: for c in reversed(listLevel): page.append(listClose[c]) listLevel = [] listCount = [] emptySection = False elif page and page[-1]: page.append('') continue # Handle section titles m = section.match(line) if m: title = m.group(2) lev = len(m.group(1)) # header level if options.toHTML: page.append("<h%d>%s</h%d>" % (lev, title, lev)) if title and title[-1] not in '!?': title += '.' # terminate sentence. headers[lev] = title # drop previous headers for i in list(headers.keys()): if i > lev: del headers[i] emptySection = True listLevel = [] listCount = [] continue # Handle page title elif line.startswith('++'): title = line[2:-2] if title: if title[-1] not in '!?': title += '.' page.append(title) # handle indents elif line[0] == ':': # page.append(line.lstrip(':*#;')) continue # handle lists elif line[0] in '*#;:': i = 0 # c: current level char # n: next level char for c, n in zip_longest(listLevel, line, fillvalue=''): if not n or n not in '*#;:': # shorter or different if c: if options.toHTML: page.append(listClose[c]) listLevel = listLevel[:-1] listCount = listCount[:-1] continue else: break # n != '' if c != n and (not c or (c not in ';:' and n not in ';:')): if c: # close level if options.toHTML: page.append(listClose[c]) listLevel = listLevel[:-1] listCount = listCount[:-1] listLevel += n listCount.append(0) if options.toHTML: page.append(listOpen[n]) i += 1 n = line[i - 1] # last list char line = line[i:].strip() if line: # FIXME: n is '"' if options.keepLists: if options.keepSections: # emit open sections items = sorted(headers.items()) for _, v in items: page.append(v) headers.clear() # use item count for #-lines listCount[i - 1] += 1 bullet = '%d. ' % listCount[i - 1] if n == '#' else '- ' page.append('{0:{1}s}'.format(bullet, len(listLevel)) + line) elif options.toHTML: page.append(listItem[n] % line) elif len(listLevel): if options.toHTML: for c in reversed(listLevel): page.append(listClose[c]) listLevel = [] listCount = [] page.append(line) # Drop residuals of lists elif line[0] in '{|' or line[-1] == '}': continue # Drop irrelevant lines elif (line[0] == '(' and line[-1] == ')') or line.strip('.-') == '': continue elif len(headers): if options.keepSections: items = sorted(headers.items()) for i, v in items: page.append(v) headers.clear() page.append(line) # first line emptySection = False elif not emptySection: # Drop preformatted if line[0] != ' ': # dangerous page.append(line) return page def handle_unicode(entity): numeric_code = int(entity[2:-1]) if numeric_code >= 0x10000: return '' return chr(numeric_code) # ------------------------------------------------------------------------------ # Output class NextFile(object): """ Synchronous generation of next available file name. """ filesPerDir = 100 def __init__(self, path_name): self.path_name = path_name self.dir_index = -1 self.file_index = -1 def __next__(self): self.file_index = (self.file_index + 1) % NextFile.filesPerDir if self.file_index == 0: self.dir_index += 1 dirname = self._dirname() if not os.path.isdir(dirname): os.makedirs(dirname) return self._filepath() next = __next__ def _dirname(self): char1 = self.dir_index % 26 char2 = self.dir_index // 26 % 26 return os.path.join(self.path_name, '%c%c' % (ord('A') + char2, ord('A') + char1)) def _filepath(self): return '%s/wiki_%02d' % (self._dirname(), self.file_index) class OutputSplitter(object): """ File-like object, that splits output to multiple files of a given max size. """ def __init__(self, nextFile, max_file_size=0, compress=True): """ :param nextFile: a NextFile object from which to obtain filenames to use. :param max_file_size: the maximum size of each file. :para compress: whether to write data with bzip compression. """ self.nextFile = nextFile self.compress = compress self.max_file_size = max_file_size self.file = self.open(next(self.nextFile)) def reserve(self, size): if self.file.tell() + size > self.max_file_size: self.close() self.file = self.open(next(self.nextFile)) def write(self, data): self.reserve(len(data)) self.file.write(data) def close(self): self.file.close() def open(self, filename): if self.compress: return bz2.BZ2File(filename + '.bz2', 'w') else: return open(filename, 'wb') # ---------------------------------------------------------------------- # READER tagRE = re.compile(r'(.*?)<(/?\w+)[^>]*?>(?:([^<]*)(<.*?>)?)?') # 1 2 3 4 keyRE = re.compile(r'key="(\d*)"') def load_templates(file, output_file=None): """ Load templates from :param file:. :param output_file: file where to save templates and modules. """ options.templatePrefix = options.templateNamespace + ':' options.modulePrefix = options.moduleNamespace + ':' if output_file: output = codecs.open(output_file, 'wb', 'utf-8') for page_count, page_data in enumerate(pages_from(file)): id, revid, title, ns, page = page_data if not output_file and (not options.templateNamespace or not options.moduleNamespace): # do not know it yet # reconstruct templateNamespace and moduleNamespace from the first title if ns in templateKeys: colon = title.find(':') if colon > 1: if ns == '10': options.templateNamespace = title[:colon] options.templatePrefix = title[:colon + 1] elif ns == '828': options.moduleNamespace = title[:colon] options.modulePrefix = title[:colon + 1] if ns in templateKeys: text = ''.join(page) define_template(title, text) # save templates and modules to file if output_file: output.write('<page>\n') output.write(' <title>%s</title>\n' % title) output.write(' <ns>%s</ns>\n' % ns) output.write(' <id>%s</id>\n' % id) output.write(' <text>') for line in page: output.write(line) output.write(' </text>\n') output.write('</page>\n') if page_count and page_count % 100000 == 0: logging.info("Preprocessed %d pages", page_count) if output_file: output.close() logging.info("Saved %d templates to '%s'", len(options.templates), output_file) def pages_from(input): """ Scans input extracting pages. :return: (id, revid, title, namespace key, page), page is a list of lines. """ # we collect individual lines, since str.join() is significantly faster # than concatenation page = [] id = None ns = '0' last_id = None revid = None inText = False redirect = False title = None for line in input: if not isinstance(line, text_type): line = line.decode('utf-8') if '<' not in line: # faster than doing re.search() if inText: page.append(line) continue m = tagRE.search(line) if not m: continue tag = m.group(2) if tag == 'page': page = [] redirect = False elif tag == 'id' and not id: id = m.group(3) elif tag == 'id' and id: revid = m.group(3) elif tag == 'title': title = m.group(3) elif tag == 'ns': ns = m.group(3) elif tag == 'redirect': redirect = True elif tag == 'text': if m.lastindex == 3 and line[m.start(3) - 2] == '/': # self closing # <text xml:space="preserve" /> continue inText = True line = line[m.start(3):m.end(3)] page.append(line) if m.lastindex == 4: # open-close inText = False elif tag == '/text': if m.group(1): page.append(m.group(1)) inText = False elif inText: page.append(line) elif tag == '/page': if id != last_id and not redirect: yield (id, revid, title, ns, page) last_id = id ns = '0' id = None revid = None title = None page = [] def process_dump(input_file, template_file, out_file, file_size, file_compress, process_count): """ :param input_file: name of the wikipedia dump file; '-' to read from stdin :param template_file: optional file with template definitions. :param out_file: directory where to store extracted data, or '-' for stdout :param file_size: max size of each extracted file, or None for no max (one file) :param file_compress: whether to compress files with bzip. :param process_count: number of extraction processes to spawn. """ if input_file == '-': input = sys.stdin else: input = fileinput.FileInput(input_file, openhook=fileinput.hook_compressed) # collect siteinfo for line in input: # When an input file is .bz2 or .gz, line can be a bytes even in Python 3. if not isinstance(line, text_type): line = line.decode('utf-8') m = tagRE.search(line) if not m: continue tag = m.group(2) if tag == 'base': # discover urlbase from the xml dump file # /mediawiki/siteinfo/base base = m.group(3) options.urlbase = base[:base.rfind("/")] elif tag == 'namespace': mk = keyRE.search(line) if mk: nsid = mk.group(1) else: nsid = '' options.knownNamespaces[m.group(3)] = nsid if re.search('key="10"', line): options.templateNamespace = m.group(3) options.templatePrefix = options.templateNamespace + ':' elif re.search('key="828"', line): options.moduleNamespace = m.group(3) options.modulePrefix = options.moduleNamespace + ':' elif tag == '/siteinfo': break if options.expand_templates: # preprocess template_load_start = default_timer() if template_file: if os.path.exists(template_file): logging.info("Loading template definitions from: %s", template_file) # can't use with here: file = fileinput.FileInput(template_file, openhook=fileinput.hook_compressed) load_templates(file) file.close() else: if input_file == '-': # can't scan then reset stdin; must error w/ suggestion to specify template_file raise ValueError("to use templates with stdin dump, must supply explicit template-file") logging.info("Preprocessing '%s' to collect template definitions: this may take some time.", input_file) load_templates(input, template_file) input.close() input = fileinput.FileInput(input_file, openhook=fileinput.hook_compressed) template_load_elapsed = default_timer() - template_load_start logging.info("Loaded %d templates in %.1fs", len(options.templates), template_load_elapsed) # process pages logging.info("Starting page extraction from %s.", input_file) extract_start = default_timer() # Parallel Map/Reduce: # - pages to be processed are dispatched to workers # - a reduce process collects the results, sort them and print them. process_count = max(1, process_count) maxsize = 10 * process_count # output queue output_queue = Queue(maxsize=maxsize) if out_file == '-': out_file = None worker_count = process_count # load balancing max_spool_length = 10000 spool_length = Value('i', 0, lock=False) # reduce job that sorts and prints output reduce = Process(target=reduce_process, args=(options, output_queue, spool_length, out_file, file_size, file_compress)) reduce.start() # initialize jobs queue jobs_queue = Queue(maxsize=maxsize) # start worker processes logging.info("Using %d extract processes.", worker_count) workers = [] for i in range(worker_count): extractor = Process(target=extract_process, args=(options, i, jobs_queue, output_queue)) extractor.daemon = True # only live while parent process lives extractor.start() workers.append(extractor) # Mapper process page_num = 0 for page_data in pages_from(input): id, revid, title, ns, page = page_data if keepPage(ns, page): # slow down delay = 0 if spool_length.value > max_spool_length: # reduce to 10% while spool_length.value > max_spool_length / 10: time.sleep(10) delay += 10 if delay: logging.info('Delay %ds', delay) job = (id, revid, title, page, page_num) jobs_queue.put(job) # goes to any available extract_process page_num += 1 page = None # free memory input.close() # signal termination for _ in workers: jobs_queue.put(None) # wait for workers to terminate for w in workers: w.join() # signal end of work to reduce process output_queue.put(None) # wait for it to finish reduce.join() extract_duration = default_timer() - extract_start extract_rate = page_num / extract_duration logging.info("Finished %d-process extraction of %d articles in %.1fs (%.1f art/s)", process_count, page_num, extract_duration, extract_rate) # ---------------------------------------------------------------------- # Multiprocess support def extract_process(opts, i, jobs_queue, output_queue): """Pull tuples of raw page content, do CPU/regex-heavy fixup, push finished text :param i: process id. :param jobs_queue: where to get jobs. :param output_queue: where to queue extracted text for output. """ global options options = opts createLogger(options.quiet, options.debug) out = StringIO() # memory buffer while True: job = jobs_queue.get() # job is (id, title, page, page_num) if job: id, revid, title, page, page_num = job try: e = Extractor(*job[:4]) # (id, revid, title, page) page = None # free memory e.extract(out) text = out.getvalue() except: text = '' logging.exception('Processing page: %s %s', id, title) output_queue.put((page_num, text)) out.truncate(0) out.seek(0) else: logging.debug('Quit extractor') break out.close() report_period = 10000 # progress report period def reduce_process(opts, output_queue, spool_length, out_file=None, file_size=0, file_compress=True): """Pull finished article text, write series of files (or stdout) :param opts: global parameters. :param output_queue: text to be output. :param spool_length: spool length. :param out_file: filename where to print. :param file_size: max file size. :param file_compress: whether to compress output. """ global options options = opts createLogger(options.quiet, options.debug) if out_file: nextFile = NextFile(out_file) output = OutputSplitter(nextFile, file_size, file_compress) else: output = sys.stdout.buffer if file_compress: logging.warn("writing to stdout, so no output compression (use an external tool)") interval_start = default_timer() # FIXME: use a heap spool = {} # collected pages next_page = 0 # sequence numbering of page while True: if next_page in spool: output.write(spool.pop(next_page).encode('utf-8')) next_page += 1 # tell mapper our load: spool_length.value = len(spool) # progress report if next_page % report_period == 0: interval_rate = report_period / (default_timer() - interval_start) logging.info("Extracted %d articles (%.1f art/s)", next_page, interval_rate) interval_start = default_timer() else: # mapper puts None to signal finish pair = output_queue.get() if not pair: break page_num, text = pair spool[page_num] = text # tell mapper our load: spool_length.value = len(spool) # FIXME: if an extractor dies, process stalls; the other processes # continue to produce pairs, filling up memory. if len(spool) > 200: logging.debug('Collected %d, waiting: %d, %d', len(spool), next_page, next_page == page_num) if output != sys.stdout: output.close() # ---------------------------------------------------------------------- # Minimum size of output files minFileSize = 200 * 1024 def main(): parser = argparse.ArgumentParser(prog=os.path.basename(sys.argv[0]), formatter_class=argparse.RawDescriptionHelpFormatter, description=__doc__) parser.add_argument("input", help="XML wiki dump file") groupO = parser.add_argument_group('Output') groupO.add_argument("-o", "--output", default="text", help="directory for extracted files (or '-' for dumping to stdout)") groupO.add_argument("-b", "--bytes", default="1M", help="maximum bytes per output file (default %(default)s)", metavar="n[KMG]") groupO.add_argument("-c", "--compress", action="store_true", help="compress output files using bzip") groupO.add_argument("--json", action="store_true", help="write output in json format instead of the default one") groupP = parser.add_argument_group('Processing') groupP.add_argument("--html", action="store_true", help="produce HTML output, subsumes --links") groupP.add_argument("-l", "--links", action="store_true", help="preserve links") groupP.add_argument("-s", "--sections", action="store_true", help="preserve sections") groupP.add_argument("--lists", action="store_true", help="preserve lists") groupP.add_argument("-ns", "--namespaces", default="", metavar="ns1,ns2", help="accepted namespaces in links") groupP.add_argument("--templates", help="use or create file containing templates") groupP.add_argument("--no-templates", action="store_false", help="Do not expand templates") groupP.add_argument("-r", "--revision", action="store_true", default=options.print_revision, help="Include the document revision id (default=%(default)s)") groupP.add_argument("--min_text_length", type=int, default=options.min_text_length, help="Minimum expanded text length required to write document (default=%(default)s)") groupP.add_argument("--filter_disambig_pages", action="store_true", default=options.filter_disambig_pages, help="Remove pages from output that contain disabmiguation markup (default=%(default)s)") groupP.add_argument("-it", "--ignored_tags", default="", metavar="abbr,b,big", help="comma separated list of tags that will be dropped, keeping their content") groupP.add_argument("-de", "--discard_elements", default="", metavar="gallery,timeline,noinclude", help="comma separated list of elements that will be removed from the article text") groupP.add_argument("--keep_tables", action="store_true", default=options.keep_tables, help="Preserve tables in the output article text (default=%(default)s)") default_process_count = max(1, cpu_count() - 1) parser.add_argument("--processes", type=int, default=default_process_count, help="Number of processes to use (default %(default)s)") groupS = parser.add_argument_group('Special') groupS.add_argument("-q", "--quiet", action="store_true", help="suppress reporting progress info") groupS.add_argument("--debug", action="store_true", help="print debug info") groupS.add_argument("-a", "--article", action="store_true", help="analyze a file containing a single article (debug option)") groupS.add_argument("-v", "--version", action="version", version='%(prog)s ' + version, help="print program version") args = parser.parse_args() options.keepLinks = args.links options.keepSections = args.sections options.keepLists = args.lists options.toHTML = args.html options.write_json = args.json options.print_revision = args.revision options.min_text_length = args.min_text_length if args.html: options.keepLinks = True options.expand_templates = args.no_templates options.filter_disambig_pages = args.filter_disambig_pages options.keep_tables = args.keep_tables try: power = 'kmg'.find(args.bytes[-1].lower()) + 1 file_size = int(args.bytes[:-1]) * 1024 ** power if file_size < minFileSize: raise ValueError() except ValueError: logging.error('Insufficient or invalid size: %s', args.bytes) return if args.namespaces: options.acceptedNamespaces = set(args.namespaces.split(',')) # ignoredTags and discardElemets have default values already supplied, if passed in the defaults are overwritten if args.ignored_tags: ignoredTags = set(args.ignored_tags.split(',')) else: ignoredTags = [ 'abbr', 'b', 'big', 'blockquote', 'center', 'cite', 'em', 'font', 'h1', 'h2', 'h3', 'h4', 'hiero', 'i', 'kbd', 'p', 'plaintext', 's', 'span', 'strike', 'strong', 'tt', 'u', 'var', 'poem' ] # 'a' tag is handled separately for tag in ignoredTags: ignoreTag(tag) if args.discard_elements: options.discardElements = set(args.discard_elements.split(',')) FORMAT = '%(levelname)s: %(message)s' logging.basicConfig(format=FORMAT) options.quiet = args.quiet options.debug = args.debug createLogger(options.quiet, options.debug) input_file = args.input if not options.keepLinks: ignoreTag('a') # sharing cache of parser templates is too slow: # manager = Manager() # templateCache = manager.dict() if args.article: if args.templates: if os.path.exists(args.templates): with open(args.templates) as file: load_templates(file) file = fileinput.FileInput(input_file, openhook=fileinput.hook_compressed) for page_data in pages_from(file): id, revid, title, ns, page = page_data Extractor(id, revid, title, page).extract(sys.stdout) file.close() return output_path = args.output if output_path != '-' and not os.path.isdir(output_path): try: os.makedirs(output_path) except: logging.error('Could not create: %s', output_path) return process_dump(input_file, args.templates, output_path, file_size, args.compress, args.processes) def createLogger(quiet, debug): logger = logging.getLogger() if not quiet: logger.setLevel(logging.INFO) if debug: logger.setLevel(logging.DEBUG) if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/bert/concat_short_sentences.py
Python
import sys def score(line1, line2): # the smaller the more likely to be concat s = len(line1) + len(line2) if s > 250: return 9999999 if line1[-1] in ['.', '"', '!', '?']: s += 5 return s def main(): buf = [] for line in sys.stdin: words = line.strip().split() if len(words) == 0: while True: if min([len(sent) for sent in buf]) >= 5: break mi, best = 9999999, None for i in range(len(buf) - 1): s = score(buf[i], buf[i + 1]) if s < mi: mi = s best = i if best is None: break buf[best] = buf[best] + buf[best + 1] buf.pop(best + 1) sys.stdout.write(''.join(' '.join(sent) + '\n' for sent in buf) + '\n') buf = [] else: buf.append(words) if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/bert/filter_and_cleanup_lines.py
Python
import re import string import sys from collections import Counter def is_valid(line): l = len(line) if l > 1000000 or l < 50: return False count = Counter(line) alpha_cnt = sum(count[ch] for ch in string.ascii_letters) if alpha_cnt < 50 or alpha_cnt / l < 0.7: return False if count['/'] / l > 0.05: # filter hyperlinks return False if count['\\'] / l > 0.05: # filter latex math equations return False if count['|'] / l > 0.05 or line[0] == '|': # filter remaining tables return False return True def post_cleanup(line): line = re.sub(r'\\', ' ', line) # remove all backslashes return ' '.join(line.strip().split()) # remove redundant spaces existed = set() pending_tail = string.ascii_letters + string.digits + ',' def write_output(line): global existed if is_valid(line): line = post_cleanup(line) if line not in existed: existed.add(line) sys.stdout.write(line + '\n') def check_concat(line1, line2): global pending_tail if len(line1) == 0 or len(line2) == 0: return False return (line1[-1] in pending_tail) and (line2[0] in string.ascii_lowercase) def main(): buf = [] for line in sys.stdin: line = ' '.join(line.strip().split()) if buf and (not check_concat(buf[-1], line)): write_output(' '.join(buf) + '\n') buf = [] buf.append(line) if buf: write_output(' '.join(buf) + '\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/bert/process_bert.sh
Shell
#!/usr/bin/env bash git clone https://github.com/kevinboone/epub2txt cd epub2txt make cd .. # Crawl your own book_corpus data and put them at book_corpus/ echo 'BookCorpus(epub)' rm book_corpus/data/English/instructors-manual-identifeye-worskhop.epub find book_corpus/data/American book_corpus/data/British book_corpus/data/English -type f -name "*.epub" -print0 | \ xargs -0 epub2txt/epub2txt > book_corpus_epub.txt echo 'BookCorpus(txt)' find book_corpus/data/American book_corpus/data/British book_corpus/data/English -type f -name "*.txt" -print0 | \ xargs -0 cat > book_corpus_txt.txt echo 'Wikipedia' wget -t 0 -c -T 20 https://dumps.wikimedia.org/enwiki/20190220/enwiki-20190220-pages-articles.xml.bz2 python WikiExtractor.py enwiki-20190220-pages-articles.xml.bz2 -b 30G -q -o - > enwiki.txt cat enwiki.txt book_corpus_txt.txt book_corpus_epub.txt | \ python ../common/remove_non_utf8_chars.py | \ python ../common/precleanup_english.py | \ perl ../common/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl en | \ perl ../common/mosesdecoder/scripts/tokenizer/remove-non-printing-char.perl | \ python filter_and_cleanup_lines.py > old_corpus.cleaned.txt python split.py old_corpus.cleaned.txt old_corpus 13088055 cat old_corpus.valid.txt | \ python segment_sentence.py | \ ../common/mosesdecoder/scripts/tokenizer/tokenizer.perl -threads 1 -no-escape -l en | \ gawk '{print tolower($0);}' > old_corpus.valid.tok for i in 0 1 2 3 do cat old_corpus.train.txt.${i} | \ python segment_sentence.py | \ ../common/mosesdecoder/scripts/tokenizer/tokenizer.perl -threads 1 -no-escape -l en | \ gawk '{print tolower($0);}' > old_corpus.train.tok.${i} done rm corpus.train.tok ||: for i in 0 1 2 3; do cat old_corpus.train.tok.${i} >> corpus.train.tok; done cat old_corpus.valid.tok > corpus.valid.tok ../common/fastBPE/fast learnbpe 32640 corpus.train.tok > bpe-code cat corpus.train.tok | \ python concat_short_sentences.py | \ python ../common/length_filter_by_char.py 20 1000000 > corpus.train.tok.tmp ../common/fastBPE/fast applybpe corpus.train.tok.bpe corpus.train.tok.tmp bpe-code rm corpus.train.tok.tmp cat corpus.valid.tok | \ python concat_short_sentences.py | \ python ../common/length_filter_by_char.py 20 1000000 > corpus.valid.tok.tmp ../common/fastBPE/fast applybpe corpus.valid.tok.bpe corpus.valid.tok.tmp bpe-code rm corpus.valid.tok.tmp cd ../.. python preprocess.py --only-source --workers 16 --nwordssrc 32768 \ --trainpref macaron-scripts/bert/corpus.train.tok.bpe \ --validpref macaron-scripts/bert/corpus.valid.tok.bpe \ --destdir data-bin/bert_corpus cp macaron-scripts/bert/bpe-code data-bin/bert_corpus/
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/bert/segment_sentence.py
Python
import re import sys from multiprocessing import Pool import spacy spacy.require_gpu() nlp = None def init(): global nlp nlp = spacy.load('en', disable=['tagger', 'ner', 'textcat']) def segment(line): global nlp return ''.join([str(sent) + '\n' for sent in nlp(line).sents if not re.match(r'^\W+$', str(sent))]) def main(): with Pool(4, initializer=init) as pool: for text in pool.imap(segment, sys.stdin, chunksize=128): sys.stdout.write(text) if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/bert/split.py
Python
import sys def main(): cnt = 0 f_cnt = 0 input_file = sys.argv[1] output_prefix = sys.argv[2] chunk_size = int(sys.argv[3]) f_ov = open(f'{output_prefix}.valid.txt', 'w', encoding='utf-8') f_ot = None with open(input_file, 'r', encoding='utf-8') as f_in: for line in f_in: if cnt % 200 == 199: f_ov.write(line) else: if cnt // chunk_size >= f_cnt: f_ot = open(f'{output_prefix}.train.txt.{f_cnt}', 'w', encoding='utf-8') f_cnt += 1 f_ot.write(line) cnt += 1 f_ov.close() f_ot.close() if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/common/clone-repos.sh
Shell
#!/usr/bin/env bash echo ' - Cloning Moses github repository (for tokenization scripts)...' git clone https://github.com/moses-smt/mosesdecoder.git echo ' - Cloning Subword NMT repository (for BPE pre-processing)...' git clone https://github.com/rsennrich/subword-nmt.git echo ' - Cloning FastBPE repository (for faster BPE pre-processing)...' git clone https://github.com/glample/fastBPE cd fastBPE g++ -std=c++11 -pthread -O3 -march=native fastBPE/main.cc -IfastBPE -o fast
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/common/length_filter_by_char.py
Python
import sys for line in sys.stdin: l = len(line) if int(sys.argv[1]) <= l <= int(sys.argv[2]): sys.stdout.write(line) else: sys.stdout.write('\n')
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/common/length_filter_by_token.py
Python
import sys for line in sys.stdin: l = len(line.strip().split(' ')) if int(sys.argv[1]) <= l <= int(sys.argv[2]): sys.stdout.write(line) else: sys.stdout.write('\n')
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/common/precleanup_english.py
Python
import re import sys def pre_cleanup(line): line = line.replace('\t', ' ') # replace tab with spaces line = ' '.join(line.strip().split()) # remove redundant spaces line = re.sub(r'\.{4,}', '...', line) # remove extra dots line = line.replace('<<', '«').replace('>>', '»') # group << together line = re.sub(' (,:\.\)\]»)', r'\1', line) # remove space before >> line = re.sub('(\[\(«) ', r'\1', line) # remove space after << line = line.replace(',,', ',').replace(',.', '.') # remove redundant punctuations line = re.sub(r' \*([^\s])', r' \1', line) # remove redundant asterisks return ' '.join(line.strip().split()) # remove redundant spaces def main(): for line in sys.stdin: line = pre_cleanup(line) sys.stdout.write(line + '\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/common/remove_non_utf8_chars.py
Python
import io import sys for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8', errors='ignore'): sys.stdout.write(line)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/common/truncate_by_token.py
Python
import sys max_len = int(sys.argv[1]) for line in sys.stdin: lst = line.strip().split(' ') if len(lst) <= max_len: sys.stdout.write(line) else: sys.stdout.write(" ".join(lst[:max_len]) + '\n')
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/align_text.py
Python
import sys import re for line in sys.stdin: re.sub(r" n't\b", "n't", line) re.sub(r" 's\b", "'s", line) sys.stdout.write(line)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/download_glue_data.py
Python
''' Script for downloading all GLUE data. Note: for legal reasons, we are unable to host MRPC. You can either use the version hosted by the SentEval team, which is already tokenized, or you can download the original data from (https://download.microsoft.com/download/D/4/6/D46FF87A-F6B9-4252-AA8B-3604ED519838/MSRParaphraseCorpus.msi) and extract the data from it manually. For Windows users, you can run the .msi file. For Mac and Linux users, consider an external library such as 'cabextract' (see below for an example). You should then rename and place specific files in a folder (see below for an example). mkdir MRPC cabextract MSRParaphraseCorpus.msi -d MRPC cat MRPC/_2DEC3DBE877E4DB192D17C0256E90F1D | tr -d $'\r' > MRPC/msr_paraphrase_train.txt cat MRPC/_D7B391F9EAFF4B1B8BCE8F21B20B1B61 | tr -d $'\r' > MRPC/msr_paraphrase_test.txt rm MRPC/_* rm MSRParaphraseCorpus.msi 1/30/19: It looks like SentEval is no longer hosting their extracted and tokenized MRPC data, so you'll need to download the data from the original source for now. 2/11/19: It looks like SentEval actually *is* hosting the extracted data. Hooray! ''' import os import sys import shutil import argparse import tempfile import urllib.request import zipfile TASKS = ["CoLA", "SST", "MRPC", "QQP", "STS", "MNLI", "SNLI", "QNLI", "RTE", "WNLI", "diagnostic"] TASK2PATH = {"CoLA":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FCoLA.zip?alt=media&token=46d5e637-3411-4188-bc44-5809b5bfb5f4', "SST":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSST-2.zip?alt=media&token=aabc5f6b-e466-44a2-b9b4-cf6337f84ac8', "MRPC":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2Fmrpc_dev_ids.tsv?alt=media&token=ec5c0836-31d5-48f4-b431-7480817f1adc', "QQP":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQQP.zip?alt=media&token=700c6acf-160d-4d89-81d1-de4191d02cb5', "STS":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSTS-B.zip?alt=media&token=bddb94a7-8706-4e0d-a694-1109e12273b5', "MNLI":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FMNLI.zip?alt=media&token=50329ea1-e339-40e2-809c-10c40afff3ce', "SNLI":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FSNLI.zip?alt=media&token=4afcfbb2-ff0c-4b2d-a09a-dbf07926f4df', "QNLI": 'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FQNLIv2.zip?alt=media&token=6fdcf570-0fc5-4631-8456-9505272d1601', "RTE":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FRTE.zip?alt=media&token=5efa7e85-a0bb-4f19-8ea2-9e1840f077fb', "WNLI":'https://firebasestorage.googleapis.com/v0/b/mtl-sentence-representations.appspot.com/o/data%2FWNLI.zip?alt=media&token=068ad0a0-ded7-4bd7-99a5-5e00222e0faf', "diagnostic":'https://storage.googleapis.com/mtl-sentence-representations.appspot.com/tsvsWithoutLabels%2FAX.tsv?GoogleAccessId=firebase-adminsdk-0khhl@mtl-sentence-representations.iam.gserviceaccount.com&Expires=2498860800&Signature=DuQ2CSPt2Yfre0C%2BiISrVYrIFaZH1Lc7hBVZDD4ZyR7fZYOMNOUGpi8QxBmTNOrNPjR3z1cggo7WXFfrgECP6FBJSsURv8Ybrue8Ypt%2FTPxbuJ0Xc2FhDi%2BarnecCBFO77RSbfuz%2Bs95hRrYhTnByqu3U%2FYZPaj3tZt5QdfpH2IUROY8LiBXoXS46LE%2FgOQc%2FKN%2BA9SoscRDYsnxHfG0IjXGwHN%2Bf88q6hOmAxeNPx6moDulUF6XMUAaXCSFU%2BnRO2RDL9CapWxj%2BDl7syNyHhB7987hZ80B%2FwFkQ3MEs8auvt5XW1%2Bd4aCU7ytgM69r8JDCwibfhZxpaa4gd50QXQ%3D%3D'} MRPC_TRAIN = 'https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_train.txt' MRPC_TEST = 'https://dl.fbaipublicfiles.com/senteval/senteval_data/msr_paraphrase_test.txt' def download_and_extract(task, data_dir): print("Downloading and extracting %s..." % task) data_file = "%s.zip" % task urllib.request.urlretrieve(TASK2PATH[task], data_file) with zipfile.ZipFile(data_file) as zip_ref: zip_ref.extractall(data_dir) os.remove(data_file) print("\tCompleted!") def format_mrpc(data_dir, path_to_data): print("Processing MRPC...") mrpc_dir = os.path.join(data_dir, "MRPC") if not os.path.isdir(mrpc_dir): os.mkdir(mrpc_dir) if path_to_data: mrpc_train_file = os.path.join(path_to_data, "msr_paraphrase_train.txt") mrpc_test_file = os.path.join(path_to_data, "msr_paraphrase_test.txt") else: print("Local MRPC data not specified, downloading data from %s" % MRPC_TRAIN) mrpc_train_file = os.path.join(mrpc_dir, "msr_paraphrase_train.txt") mrpc_test_file = os.path.join(mrpc_dir, "msr_paraphrase_test.txt") urllib.request.urlretrieve(MRPC_TRAIN, mrpc_train_file) urllib.request.urlretrieve(MRPC_TEST, mrpc_test_file) assert os.path.isfile(mrpc_train_file), "Train data not found at %s" % mrpc_train_file assert os.path.isfile(mrpc_test_file), "Test data not found at %s" % mrpc_test_file urllib.request.urlretrieve(TASK2PATH["MRPC"], os.path.join(mrpc_dir, "dev_ids.tsv")) dev_ids = [] with open(os.path.join(mrpc_dir, "dev_ids.tsv"), encoding="utf8") as ids_fh: for row in ids_fh: dev_ids.append(row.strip().split('\t')) with open(mrpc_train_file, encoding="utf8") as data_fh, \ open(os.path.join(mrpc_dir, "train.tsv"), 'w', encoding="utf8") as train_fh, \ open(os.path.join(mrpc_dir, "dev.tsv"), 'w', encoding="utf8") as dev_fh: header = data_fh.readline() train_fh.write(header) dev_fh.write(header) for row in data_fh: label, id1, id2, s1, s2 = row.strip().split('\t') if [id1, id2] in dev_ids: dev_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) else: train_fh.write("%s\t%s\t%s\t%s\t%s\n" % (label, id1, id2, s1, s2)) with open(mrpc_test_file, encoding="utf8") as data_fh, \ open(os.path.join(mrpc_dir, "test.tsv"), 'w', encoding="utf8") as test_fh: header = data_fh.readline() test_fh.write("index\t#1 ID\t#2 ID\t#1 String\t#2 String\n") for idx, row in enumerate(data_fh): label, id1, id2, s1, s2 = row.strip().split('\t') test_fh.write("%d\t%s\t%s\t%s\t%s\n" % (idx, id1, id2, s1, s2)) print("\tCompleted!") def download_diagnostic(data_dir): print("Downloading and extracting diagnostic...") if not os.path.isdir(os.path.join(data_dir, "diagnostic")): os.mkdir(os.path.join(data_dir, "diagnostic")) data_file = os.path.join(data_dir, "diagnostic", "diagnostic.tsv") urllib.request.urlretrieve(TASK2PATH["diagnostic"], data_file) print("\tCompleted!") return def get_tasks(task_names): task_names = task_names.split(',') if "all" in task_names: tasks = TASKS else: tasks = [] for task_name in task_names: assert task_name in TASKS, "Task %s not found!" % task_name tasks.append(task_name) return tasks def main(arguments): parser = argparse.ArgumentParser() parser.add_argument('--data_dir', help='directory to save data to', type=str, default='glue_data') parser.add_argument('--tasks', help='tasks to download data for as a comma separated string', type=str, default='all') parser.add_argument('--path_to_mrpc', help='path to directory containing extracted MRPC data, msr_paraphrase_train.txt and msr_paraphrase_text.txt', type=str, default='') args = parser.parse_args(arguments) if not os.path.isdir(args.data_dir): os.mkdir(args.data_dir) tasks = get_tasks(args.tasks) for task in tasks: if task == 'MRPC': format_mrpc(args.data_dir, args.path_to_mrpc) elif task == 'diagnostic': download_diagnostic(args.data_dir) else: download_and_extract(task, args.data_dir) if __name__ == '__main__': sys.exit(main(sys.argv[1:]))
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_cola.py
Python
import argparse import csv import os import torch def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: fo.write(line[3] + "\n") labels.append(int(line[1])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: fo.write(line[3] + "\n") labels.append(int(line[1])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence": continue fo.write(line[1] + "\n") if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_diagnostic.py
Python
import argparse import csv import os _label_to_id = { 'neutral': 0, 'entailment': 1, 'contradiction': 2 } def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "diagnostic.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[1] == "sentence1" and line[2] == "sentence2": continue fo.write(f'{line[1]}\n{line[2]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_mnli.py
Python
import argparse import csv import os import torch _label_to_id = { 'neutral': 0, 'entailment': 1, 'contradiction': 2 } def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[8] == "sentence1" and line[9] == "sentence2" and line[10] == 'label1' and line[11] == 'gold_label': continue assert line[10] == line[11] fo.write(f'{line[8]}\n{line[9]}\n') labels.append(_label_to_id[line[10]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev_matched.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[8] == "sentence1" and line[9] == "sentence2" and line[15] == 'gold_label': continue fo.write(f'{line[8]}\n{line[9]}\n') labels.append(_label_to_id[line[10]]) # with open(os.path.join(args.data, "dev_mismatched.tsv"), "r", encoding="utf-8") as fi: # reader = csv.reader(fi, delimiter="\t", quotechar=None) # for line in reader: # if line[8] == "sentence1" and line[9] == "sentence2" and line[15] == 'gold_label': # continue # fo.write(f'{line[8]}\n{line[9]}\n') # labels.append(_label_to_id[line[10]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test_matched.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[8] == "sentence1" and line[9] == "sentence2": continue fo.write(f'{line[8]}\n{line[9]}\n') # with open(os.path.join(args.data, "test_mismatched.tsv"), "r", encoding="utf-8") as fi: # reader = csv.reader(fi, delimiter="\t", quotechar=None) # for line in reader: # if line[8] == "sentence1" and line[9] == "sentence2": # continue # fo.write(f'{line[8]}\n{line[9]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_mnli_mm.py
Python
import argparse import csv import os import torch _label_to_id = { 'neutral': 0, 'entailment': 1, 'contradiction': 2 } def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[8] == "sentence1" and line[9] == "sentence2" and line[10] == 'label1' and line[11] == 'gold_label': continue assert line[10] == line[11] fo.write(f'{line[8]}\n{line[9]}\n') labels.append(_label_to_id[line[10]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev_mismatched.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[8] == "sentence1" and line[9] == "sentence2" and line[15] == 'gold_label': continue fo.write(f'{line[8]}\n{line[9]}\n') labels.append(_label_to_id[line[10]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test_mismatched.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[8] == "sentence1" and line[9] == "sentence2": continue fo.write(f'{line[8]}\n{line[9]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_mrpc.py
Python
import argparse import csv import os import torch def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8-sig") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[3] == "#1 String" and line[4] == "#2 String" and line[0] == 'Quality': continue fo.write(f'{line[3]}\n{line[4]}\n') labels.append(int(line[0])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8-sig") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[3] == "#1 String" and line[4] == "#2 String" and line[0] == 'Quality': continue fo.write(f'{line[3]}\n{line[4]}\n') labels.append(int(line[0])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8-sig") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[3] == "#1 String" and line[4] == "#2 String": continue fo.write(f'{line[3]}\n{line[4]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_qnli.py
Python
import argparse import csv import os import torch _label_to_id = { 'not_entailment': 0, 'entailment': 1 } def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "question" and line[2] == 'sentence' and line[3] == 'label': continue fo.write(f'{line[1]}\n{line[2]}\n') labels.append(_label_to_id[line[3]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "question" and line[2] == 'sentence' and line[3] == 'label': continue fo.write(f'{line[1]}\n{line[2]}\n') labels.append(_label_to_id[line[3]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "question" and line[2] == 'sentence': continue fo.write(f'{line[1]}\n{line[2]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_qqp.py
Python
import argparse import csv import os import torch def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "id" and line[1] == "qid1" and line[2] == 'qid2' and line[3] == 'question1' and line[4] == 'question2' and line[5] == 'is_duplicate': continue if len(line) != 6: # print(line) continue fo.write(f'{line[3]}\n{line[4]}\n') labels.append(int(line[5])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "id" and line[1] == "qid1" and line[2] == 'qid2' and line[3] == 'question1' and line[4] == 'question2' and line[5] == 'is_duplicate': continue if len(line) != 6: # print(line, 'valid') continue fo.write(f'{line[3]}\n{line[4]}\n') labels.append(int(line[5])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "id" and line[1] == "question1" and line[2] == 'question2': continue if len(line) != 3: # print(line, 'test') continue fo.write(f'{line[1]}\n{line[2]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_rte.py
Python
import argparse import csv import os import torch _label_to_id = { 'not_entailment': 0, 'entailment': 1 } def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence1" and line[2] == 'sentence2' and line[3] == 'label': continue fo.write(f'{line[1]}\n{line[2]}\n') labels.append(_label_to_id[line[3]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence1" and line[2] == 'sentence2' and line[3] == 'label': continue fo.write(f'{line[1]}\n{line[2]}\n') labels.append(_label_to_id[line[3]]) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence1" and line[2] == 'sentence2': continue fo.write(f'{line[1]}\n{line[2]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_sts.py
Python
import argparse import csv import os import torch def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[7] == "sentence1" and line[8] == "sentence2" and line[9] == 'score': continue fo.write(f'{line[7]}\n{line[8]}\n') labels.append(0.5 *(float(line[9]) - 3)) torch.save(torch.FloatTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[7] == "sentence1" and line[8] == "sentence2" and line[9] == 'score': continue fo.write(f'{line[7]}\n{line[8]}\n') labels.append(0.5 * (float(line[9]) - 3)) torch.save(torch.FloatTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[7] == "sentence1" and line[8] == "sentence2": continue fo.write(f'{line[7]}\n{line[8]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/generate_wnli.py
Python
import argparse import csv import os import torch def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence1" and line[2] == 'sentence2' and line[3] == 'label': continue fo.write(f'{line[1]}\n{line[2]}\n') labels.append(int(line[3])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence1" and line[2] == 'sentence2' and line[3] == 'label': continue fo.write(f'{line[1]}\n{line[2]}\n') labels.append(int(line[3])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8") as fi: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence1" and line[2] == 'sentence2': continue fo.write(f'{line[1]}\n{line[2]}\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/process_glue.sh
Shell
#!/usr/bin/env bash BPE_CODE_PATH=$1 DICT_PATH=$2 python download_glue_data.py --data_dir glue --tasks CoLA,SST,MRPC,QQP,STS,MNLI,QNLI,RTE,WNLI,diagnostic python generate_cola.py glue/CoLA --output glue/CoLA python single_sentence.py glue/SST-2 --output glue/SST-2 python generate_mrpc.py glue/MRPC --output glue/MRPC python generate_qqp.py glue/QQP --output glue/QQP python generate_sts.py glue/STS-B --output glue/STS-B python generate_mnli.py glue/MNLI --output glue/MNLI python generate_mnli_mm.py glue/MNLI --output glue/MNLI-mm python generate_qnli.py glue/QNLI --output glue/QNLI python generate_rte.py glue/RTE --output glue/RTE python generate_wnli.py glue/WNLI --output glue/WNLI python generate_diagnostic.py glue/diagnostic --output glue/diagnostic for TASK in CoLA SST-2 MRPC QQP STS-B MNLI MNLI-mm QNLI RTE WNLI do for SPLIT in train valid test do cat glue/${TASK}/${SPLIT}.txt | \ python ../common/remove_non_utf8_chars.py | \ python ../common/precleanup_english.py | \ perl ../common/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl en | \ perl ../common/mosesdecoder/scripts/tokenizer/remove-non-printing-char.perl | \ python align_text.py | \ sed 's/\\/ /g' | \ ../common/mosesdecoder/scripts/tokenizer/tokenizer.perl -threads 8 -no-escape -l en | \ gawk '{print tolower($0);}' > ${SPLIT}.tok.tmp #../common/fastBPE/fast applybpe glue/${TASK}/${SPLIT}.tok.bpe ${SPLIT}.tok.tmp ${BPE_CODE_PATH} ../common/subword-nmt/subword_nmt/apply_bpe.py -c ${BPE_CODE_PATH} < ${SPLIT}.tok.tmp > glue/${TASK}/${SPLIT}.tok.bpe rm ${SPLIT}.tok.tmp done done cat glue/diagnostic/test.txt | \ python ../common/remove_non_utf8_chars.py | \ python ../common/precleanup_english.py | \ perl ../common/mosesdecoder/scripts/tokenizer/normalize-punctuation.perl en | \ perl ../common/mosesdecoder/scripts/tokenizer/remove-non-printing-char.perl | \ python align_text.py | \ sed 's/\\/ /g' | \ ../common/mosesdecoder/scripts/tokenizer/tokenizer.perl -threads 8 -no-escape -l en | \ gawk '{print tolower($0);}' > test.tok.tmp #../common/fastBPE/fast applybpe glue/diagnostic/test.tok.bpe test.tok.tmp ${BPE_CODE_PATH} ../common/subword-nmt/subword_nmt/apply_bpe.py -c ${BPE_CODE_PATH} < test.tok.tmp > glue/diagnostic/test.tok.bpe rm test.tok.tmp cd ../.. for TASK in CoLA SST-2 MRPC QQP STS-B MNLI MNLI-mm QNLI RTE WNLI do python preprocess_bert.py --only-source --workers 8 \ --trainpref macaron-scripts/glue/glue/${TASK}/train.tok.bpe \ --validpref macaron-scripts/glue/glue/${TASK}/valid.tok.bpe \ --testpref macaron-scripts/glue/glue/${TASK}/test.tok.bpe \ --srcdict macaron-scripts/glue/${DICT_PATH} \ --destdir data-bin/glue/${TASK} cp macaron-scripts/glue/glue/${TASK}/train_labels.pt data-bin/glue/${TASK}/ cp macaron-scripts/glue/glue/${TASK}/valid_labels.pt data-bin/glue/${TASK}/ done python preprocess_bert.py --only-source --workers 8 \ --testpref macaron-scripts/glue/glue/diagnostic/test.tok.bpe \ --srcdict macaron-scripts/glue/${DICT_PATH} \ --destdir data-bin/glue/diagnostic
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/process_predictions.py
Python
import argparse import os rte_labels = ['not_entailment', 'entailment'] mnli_labels = ['neutral', 'entailment', 'contradiction'] qnli_labels = ['not_entailment', 'entailment'] def main(): parser = argparse.ArgumentParser() parser.add_argument('input', type=str, help='input path of predictions') parser.add_argument('--output', type=str, help='output path of submissions') args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f'{args.output} is not a directory') with open(os.path.join(args.output, 'CoLA.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_CoLA.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{line.strip()}\n') cnt += 1 with open(os.path.join(args.output, 'MRPC.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_MRPC.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{line.strip()}\n') cnt += 1 with open(os.path.join(args.output, 'STS-B.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_STS-B.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{float(line.strip()) * 2.0 + 3.0}\n') cnt += 1 with open(os.path.join(args.output, 'RTE.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_RTE.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{rte_labels[int(line.strip())]}\n') cnt += 1 with open(os.path.join(args.output, 'MNLI-m.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_MNLI.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{mnli_labels[int(line.strip())]}\n') cnt += 1 with open(os.path.join(args.output, 'MNLI-mm.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_MNLI-mm.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{mnli_labels[int(line.strip())]}\n') cnt += 1 with open(os.path.join(args.output, 'QNLI.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_QNLI.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{qnli_labels[int(line.strip())]}\n') cnt += 1 with open(os.path.join(args.output, 'QQP.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_QQP.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{line.strip()}\n') cnt += 1 with open(os.path.join(args.output, 'SST-2.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_SST-2.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{line.strip()}\n') cnt += 1 with open(os.path.join(args.output, 'AX.tsv'), 'w', encoding='utf-8') as fo, open(os.path.join(args.input, 'prediction_diagnostic.txt'), 'r', encoding='utf-8') as fi: fo.write('index\tprediction\n') cnt = 0 for line in fi: fo.write(f'{cnt}\t{mnli_labels[int(line.strip())]}\n') cnt += 1 with open(os.path.join(args.output, 'WNLI.tsv'), 'w', encoding='utf-8') as fo: fo.write('index\tprediction\n') for i in range(146): fo.write(f'{i}\t0\n') if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/glue/single_sentence.py
Python
import argparse import csv import os import torch def main(): parser = argparse.ArgumentParser() parser.add_argument("data", type=str, help="path of data") parser.add_argument("--output", type=str, required=True, help="path of output") args = parser.parse_args() if not os.path.exists(args.output): os.mkdir(args.output) elif not os.path.isdir(args.output): raise FileExistsError(f"{args.output} is not a directory") labels = [] with open(os.path.join(args.data, "train.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "train.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "sentence" and line[1] == "label": continue fo.write(line[0] + "\n") labels.append(int(line[1])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "train_labels.pt")) labels = [] with open(os.path.join(args.data, "dev.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "valid.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "sentence" and line[1] == "label": continue fo.write(line[0] + "\n") labels.append(int(line[1])) torch.save(torch.LongTensor(labels), os.path.join(args.output, "valid_labels.pt")) with open(os.path.join(args.data, "test.tsv"), "r", encoding="utf-8") as fi, open( os.path.join(args.output, "test.txt"), "w", encoding="utf-8") as fo: reader = csv.reader(fi, delimiter="\t", quotechar=None) for line in reader: if line[0] == "index" and line[1] == "sentence": continue fo.write(line[1] + "\n") if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/test/generate_test_scripts.py
Python
import os import sys import copy import itertools import inspect def task(name, n_sentences, task, criterion, symmetric, n_classes, data_path): return locals() def params(*args): keys = ["seed_list", "n_epoch_list", "batch_sz_list", "lr_list", "weight_decay_list"] assert len(args) == len(keys) values = itertools.product(*args) return [{k: v for k, v in zip(keys, vs)} for vs in values] cola = ( task("cola", 8551, "glue_single", "cross_entropy_classify_binary", "", 1, "CoLA"), params(["100 200 300 400 500 600"], ["3 4 5"], ["16 32"], ["0.00005 0.00003"], ["0.00 0.01"]) ) # 60s / epoch, 3h / search mrpc = ( task("mrpc", 3668, "glue_pair", "cross_entropy_classify_binary", "--symmetric", 1, "MRPC"), params(["100 200 300 400 500 600"], ["3 4 5"], ["16 32"], ["0.00005 0.00003"], ["0.00 0.01"]) ) # 50s / epoch, 3h / search sts = ( task("sts", 5749, "glue_pair", "mean_squared_error", "--symmetric", 1, "STS-B"), params(["100 200 300 400 500 600"], ["3 4 5"], ["16 32"], ["0.00005 0.00003"], ["0.00 0.01"]) ) # 50s / epoch, 4h / search rte = ( task("rte", 2475, "glue_pair", "cross_entropy_classify", "", 2, "RTE"), params(["100 200 300 400 500 600"], ["3 4 5"], ["16 32"], ["0.00005 0.00003"], ["0.00 0.01"]) ) # 60s / epoch, 3h / search mnli = ( task("mnli", 392702, "glue_pair", "cross_entropy_classify", "", 3, "MNLI"), params(["100", "200", "300"], ["3 4 5"], ["16 24"], ["0.00005", "0.00003"], ["0.00", "0.01"]) ) # 5000s / epoch, bs 32 oom mnlimm = ( task("mnlimm", 392702, "glue_pair", "cross_entropy_classify", "", 3, "MNLI-mm"), params(["100", "200", "300"], ["3 4 5"], ["16 24"], ["0.00005", "0.00003"], ["0.00", "0.01"]) ) # 5000s / epoch, bs 32 oom qnli = ( task("qnli", 108436, "glue_pair", "cross_entropy_classify", "", 2, "QNLI-new"), params(["100", "200", "300"], ["3 4 5"], ["16 24"], ["0.00005", "0.00003"], ["0.00", "0.01"]) ) # 1600s / epoch, bs 32 oom qqp = ( task("qqp", 363849, "glue_pair", "cross_entropy_classify_binary", "--symmetric", 1, "QQP"), params(["100", "200", "300"], ["3 4 5"], ["16 24"], ["0.00005", "0.00003"], ["0.00", "0.01"]) ) # 4000s / epoch, bs 32 oom sst = ( task("sst", 67349, "glue_single", "cross_entropy_classify", "", 2, "SST-2"), params(["100", "200", "300", "400", "500", "600"], ["3 4 5"], ["16 32"], ["0.00005 0.00003"], ["0.00 0.01"]) ) # 400s / epoch, 18h / search task_list = [cola, mrpc, sts, rte, mnli, mnlimm, qnli, qqp, sst] bert_model_config = { "bert_model_name": "macaron_pretrained", "bert_model_path": "log/bert/transformer_bert_base_macaron/checkpoint_pretrained.pt", "bert_model_arch": "transformer_classifier_base_macaron", } script_dir = os.path.join("generated/", bert_model_config["bert_model_name"]) env_vars = """ PROBLEM={name} BERT_MODEL_NAME={bert_model_name} TASK={task} BERT_MODEL_PATH={bert_model_path} N_CLASSES={n_classes} ARCH={bert_model_arch} N_SENT={n_sentences} CRITERION={criterion} SYMMETRIC={symmetric} DATA_PATH=data/glue/{data_path} SEED_LIST="{seed_list}" N_EPOCH_LIST="{n_epoch_list}" BATCH_SZ_LIST="{batch_sz_list}" LR_LIST="{lr_list}" WEIGHT_DECAY_LIST="{weight_decay_list}" """ script_template = r""" CODE_PATH=. cd $CODE_PATH export PYTHONPATH=$CODE_PATH:$PYTHONPATH for SEED in $SEED_LIST do for N_EPOCH in $N_EPOCH_LIST do for BATCH_SZ in $BATCH_SZ_LIST do SENT_PER_GPU=$(( BATCH_SZ / 1 )) N_UPDATES=$(( ((N_SENT + BATCH_SZ - 1) / BATCH_SZ) * N_EPOCH )) WARMUP_UPDATES=$(( (N_UPDATES + 5) / 10 )) echo $SENT_PER_GPU $N_UPDATES $WARMUP_UPDATES for LR in $LR_LIST do for WEIGHT_DECAY in $WEIGHT_DECAY_LIST do OUTPUT_PATH=log/bert_downstream/$BERT_MODEL_NAME/$PROBLEM/${N_EPOCH}-${BATCH_SZ}-${LR}-${WEIGHT_DECAY}-$SEED mkdir -p $OUTPUT_PATH python train.py $DATA_PATH --task $TASK --load-bert $BERT_MODEL_PATH --load-type no_out \ --arch $ARCH --n-classes $N_CLASSES \ --optimizer adam --adam-betas '(0.9, 0.999)' --adam-eps 1e-6 --clip-norm 0.0 --weight-decay $WEIGHT_DECAY \ --lr $LR --lr-scheduler linear --warmup-init-lr 1e-07 --warmup-updates $WARMUP_UPDATES --min-lr 1e-09 \ --criterion $CRITERION $SYMMETRIC \ --max-sentences $SENT_PER_GPU --max-update $N_UPDATES --seed $SEED \ --save-dir $OUTPUT_PATH --no-progress-bar --log-interval 100 --no-epoch-checkpoints \ | tee -a $OUTPUT_PATH/train_log.txt done done done done done """ os.makedirs(script_dir, exist_ok=True) os.system('cp {} {}'.format(__file__, script_dir)) for task_dict, params_list in task_list: for i, param_dict in enumerate(params_list): result_dict = {} result_dict.update(task_dict) result_dict.update(bert_model_config) result_dict.update(param_dict) this_env_var = env_vars.format(**result_dict) script = this_env_var + script_template script_name = os.path.join(script_dir, ".".join([task_dict["name"], "%02d" % i, "sh"])) print(script_name) with open(script_name, "w") as f: f.write(script)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/test/test-our-best-setting.sh
Shell
#!/usr/bin/env bash BERT_DIR=log/bert/transformer_bert_base_macaron CKPT=$1 CKPT_ID=$(echo $CKPT | sed 's/checkpoint//g' | sed 's/\.pt//g' | sed 's/^_//g') BERT_PATH=${BERT_DIR}/$CKPT DATA_PATH=glue function run_exp { TASK_NAME=$1 TASK_TYPE=$2 SYMMETRIC_FLAG=$3 TASK_CRITERION=$4 N_CLASSES=$5 N_SENT=$6 WEIGHT_DECAY=$7 N_EPOCH=$8 BATCH_SZ=$9 LR=${10} SEED=${11} # Runs on 1 GPU SENT_PER_GPU=$(( BATCH_SZ / 1 )) N_UPDATES=$(( ((N_SENT + BATCH_SZ - 1) / BATCH_SZ) * N_EPOCH )) WARMUP_UPDATES=$(( (N_UPDATES + 5) / 10 )) mkdir -p ${BERT_DIR}/${CKPT_ID}/${TASK_NAME} python train.py data-bin/${DATA_PATH}/${TASK_NAME} --task ${TASK_TYPE} ${SYMMETRIC_FLAG} \ --arch transformer_classifier_base_macaron --n-classes ${N_CLASSES} --load-bert ${BERT_PATH} \ --optimizer adam --adam-betas '(0.9, 0.999)' --adam-eps 1e-6 --clip-norm 0.0 --weight-decay ${WEIGHT_DECAY} \ --lr ${LR} --lr-scheduler linear --warmup-init-lr 1e-07 --warmup-updates ${WARMUP_UPDATES} --min-lr 1e-09 \ --criterion ${TASK_CRITERION} \ --max-sentences ${SENT_PER_GPU} --max-update ${N_UPDATES} --seed ${SEED} \ --save-dir ${BERT_DIR}/${CKPT_ID}/${TASK_NAME} --no-progress-bar --no-epoch-checkpoints python inference.py data-bin/${DATA_PATH}/${TASK_NAME} --gen-subset test --task ${TASK_TYPE} \ --path ${BERT_DIR}/${CKPT_ID}/${TASK_NAME}/checkpoint_last.pt --output ${BERT_DIR}/${CKPT_ID}/prediction_${TASK_NAME}.txt } echo 'To reproduce our result, please run in 1 GPU' run_exp 'CoLA' 'glue_single' '' 'cross_entropy_classify_binary' 1 8551 0.00 5 32 0.00003 400 run_exp 'MRPC' 'glue_pair' '--symmetric' 'cross_entropy_classify_binary' 1 3668 0.00 4 16 0.00005 500 run_exp 'STS-B' 'glue_pair' '--symmetric' 'mean_squared_error' 1 5749 0.00 5 16 0.00005 500 run_exp 'RTE' 'glue_pair' '' 'cross_entropy_classify' 2 2475 0.00 4 16 0.00005 200 run_exp 'SST-2' 'glue_single' '' 'cross_entropy_classify' 2 67349 0.00 3 24 0.00005 200 run_exp 'MNLI' 'glue_pair' '' 'cross_entropy_classify' 3 392702 0.00 3 24 0.00005 300 run_exp 'MNLI-mm' 'glue_pair' '' 'cross_entropy_classify' 3 392702 0.00 3 16 0.00005 300 run_exp 'QQP' 'glue_pair' '--symmetric' 'cross_entropy_classify_binary' 1 363849 0.00 5 16 0.00005 200 run_exp 'QNLI' 'glue_pair' '' 'cross_entropy_classify' 2 108436 0.01 4 16 0.00003 400 python inference.py data-bin/${DATA_PATH}/diagnostic --gen-subset test --task glue_pair \ --path ${BERT_DIR}/${CKPT_ID}/MNLI/checkpoint_last.pt --output ${BERT_DIR}/${CKPT_ID}/prediction_diagnostic.txt mkdir -p predictions python examples/glue/process_predictions.py predictions --output predictions zip predictions.zip predictions/*.tsv
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/train/train-distributed.sh
Shell
#!/usr/bin/env bash CODE_PATH=. cd $CODE_PATH export PYTHONPATH=$CODE_PATH:$PYTHONPATH model=transformer PROBLEM=bert ARCH=transformer_bert_base_macaron # Because of copyright, we cannot provide our binarized data. # Please process your own training data. DATA_PATH=data-bin/bert_corpus/ OUTPUT_PATH=log/$PROBLEM/ARCH mkdir -p $OUTPUT_PATH # Example usage with 8 * 4 = 32 P40 GPUs. Change the --max-tokens and --update-freq to match your hardware settings. MASTER_HOST="0.0.0.0" # Replace it with your master's IP python distributed_train.py $DATA_PATH \ --distributed-init-method tcp://$MASTER_HOST:23456 \ --distributed-world-size $OMPI_COMM_WORLD_SIZE \ --distributed-rank $OMPI_COMM_WORLD_RANK \ --device-id $OMPI_COMM_WORLD_LOCAL_RANK \ --task bert --seed 1 \ --arch $ARCH --share-all-embeddings \ --optimizer adam --adam-betas '(0.9, 0.999)' --adam-eps 1e-6 --clip-norm 0.0 --weight-decay 0.01 \ --lr 0.0003 --lr-scheduler linear --warmup-updates 1 --min-lr 1e-09 \ --criterion cross_entropy_bert \ --max-tokens 4000 \ --update-freq 1 --max-update 800000 --seed 3 \ --ddp-backend no_c10d \ --save-dir $OUTPUT_PATH --no-progress-bar --log-interval 50 --save-interval-updates 10000 --keep-interval-updates 20 \ | tee -a $OUTPUT_PATH/train_log.txt
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/macaron-scripts/train/train.sh
Shell
#!/usr/bin/env bash CODE_PATH=. cd $CODE_PATH export PYTHONPATH=$CODE_PATH:$PYTHONPATH model=transformer PROBLEM=bert ARCH=transformer_bert_base_macaron # Because of copyright, we cannot provide our binarized data. # Please process your own training data. DATA_PATH=data-bin/bert_corpus/ OUTPUT_PATH=log/$PROBLEM/ARCH mkdir -p $OUTPUT_PATH # Assume training on 4 P40 GPUs. Change the --max-tokens and --update-freq to match your hardware settings. python train.py $DATA_PATH \ --task bert --seed 1 \ --arch $ARCH --share-all-embeddings \ --optimizer adam --adam-betas '(0.9, 0.999)' --adam-eps 1e-6 --clip-norm 0.0 --weight-decay 0.01 \ --lr 0.0003 --lr-scheduler linear --warmup-updates 1 --min-lr 1e-09 \ --criterion cross_entropy_bert \ --max-tokens 6400 --update-freq 5 --max-update 800000 --seed 3 \ --ddp-backend no_c10d \ --save-dir $OUTPUT_PATH --no-progress-bar --log-interval 50 --save-interval-updates 10000 --keep-interval-updates 20 \ | tee -a $OUTPUT_PATH/train_log.txt
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/multiprocessing_train.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os import random import signal import torch from fairseq import distributed_utils, options from train import main as single_process_main def main(args): # Set distributed training parameters for a single node. args.distributed_world_size = torch.cuda.device_count() port = random.randint(10000, 20000) args.distributed_init_method = 'tcp://localhost:{port}'.format(port=port) args.distributed_init_host = 'localhost' args.distributed_port = port + 1 mp = torch.multiprocessing.get_context('spawn') # Create a thread to listen for errors in the child processes. error_queue = mp.SimpleQueue() error_handler = ErrorHandler(error_queue) # Train with multiprocessing. procs = [] for i in range(args.distributed_world_size): args.distributed_rank = i args.device_id = i procs.append(mp.Process(target=run, args=(args, error_queue, ), daemon=True)) procs[i].start() error_handler.add_child(procs[i].pid) for p in procs: p.join() def run(args, error_queue): try: args.distributed_rank = distributed_utils.distributed_init(args) single_process_main(args) except KeyboardInterrupt: pass # killed by parent, do nothing except Exception: # propagate exception to parent process, keeping original traceback import traceback error_queue.put((args.distributed_rank, traceback.format_exc())) class ErrorHandler(object): """A class that listens for exceptions in children processes and propagates the tracebacks to the parent process.""" def __init__(self, error_queue): import signal import threading self.error_queue = error_queue self.children_pids = [] self.error_thread = threading.Thread(target=self.error_listener, daemon=True) self.error_thread.start() signal.signal(signal.SIGUSR1, self.signal_handler) def add_child(self, pid): self.children_pids.append(pid) def error_listener(self): (rank, original_trace) = self.error_queue.get() self.error_queue.put((rank, original_trace)) os.kill(os.getpid(), signal.SIGUSR1) def signal_handler(self, signalnum, stackframe): for pid in self.children_pids: os.kill(pid, signal.SIGINT) # kill children processes (rank, original_trace) = self.error_queue.get() msg = "\n\n-- Tracebacks above this line can probably be ignored --\n\n" msg += original_trace raise Exception(msg) if __name__ == '__main__': parser = options.get_training_parser() args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/preprocess.py
Python
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Data pre-processing: build vocabularies and binarize training data. """ import argparse from collections import Counter from itertools import zip_longest import os import shutil from fairseq.data import indexed_dataset, dictionary from fairseq.tokenizer import Tokenizer, tokenize_line from multiprocessing import Pool, Manager, Process def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='source language') parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET', help='target language') parser.add_argument('--trainpref', metavar='FP', default=None, help='train file prefix') parser.add_argument('--validpref', metavar='FP', default=None, help='comma separated, valid file prefixes') parser.add_argument('--testpref', metavar='FP', default=None, help='comma separated, test file prefixes') parser.add_argument('--destdir', metavar='DIR', default='data-bin', help='destination dir') parser.add_argument('--thresholdtgt', metavar='N', default=0, type=int, help='map words appearing less than threshold times to unknown') parser.add_argument('--thresholdsrc', metavar='N', default=0, type=int, help='map words appearing less than threshold times to unknown') parser.add_argument('--tgtdict', metavar='FP', help='reuse given target dictionary') parser.add_argument('--srcdict', metavar='FP', help='reuse given source dictionary') parser.add_argument('--nwordstgt', metavar='N', default=-1, type=int, help='number of target words to retain') parser.add_argument('--nwordssrc', metavar='N', default=-1, type=int, help='number of source words to retain') parser.add_argument('--alignfile', metavar='ALIGN', default=None, help='an alignment file (optional)') parser.add_argument('--output-format', metavar='FORMAT', default='binary', choices=['binary', 'raw'], help='output format (optional)') parser.add_argument('--joined-dictionary', action='store_true', help='Generate joined dictionary') parser.add_argument('--only-source', action='store_true', help='Only process the source language') parser.add_argument('--padding-factor', metavar='N', default=8, type=int, help='Pad dictionary size to be multiple of N') parser.add_argument('--workers', metavar='N', default=1, type=int, help='number of parallel workers') return parser def main(args): print(args) os.makedirs(args.destdir, exist_ok=True) target = not args.only_source def build_dictionary(filenames): d = dictionary.Dictionary() for filename in filenames: Tokenizer.add_file_to_dictionary(filename, d, tokenize_line, args.workers) return d def train_path(lang): return '{}{}'.format(args.trainpref, ('.' + lang) if lang else '') def file_name(prefix, lang): fname = prefix if lang is not None: fname += f'.{lang}' return fname def dest_path(prefix, lang): return os.path.join(args.destdir, file_name(prefix, lang)) def dict_path(lang): return dest_path('dict', lang) + '.txt' if args.joined_dictionary: assert not args.srcdict, 'cannot combine --srcdict and --joined-dictionary' assert not args.tgtdict, 'cannot combine --tgtdict and --joined-dictionary' src_dict = build_dictionary(set([ train_path(lang) for lang in [args.source_lang, args.target_lang] ])) tgt_dict = src_dict else: if args.srcdict: src_dict = dictionary.Dictionary.load(args.srcdict) else: assert args.trainpref, "--trainpref must be set if --srcdict is not specified" src_dict = build_dictionary([train_path(args.source_lang)]) if target: if args.tgtdict: tgt_dict = dictionary.Dictionary.load(args.tgtdict) else: assert args.trainpref, "--trainpref must be set if --tgtdict is not specified" tgt_dict = build_dictionary([train_path(args.target_lang)]) src_dict.finalize( threshold=args.thresholdsrc, nwords=args.nwordssrc, padding_factor=args.padding_factor, ) src_dict.save(dict_path(args.source_lang)) if target: if not args.joined_dictionary: tgt_dict.finalize( threshold=args.thresholdtgt, nwords=args.nwordstgt, padding_factor=args.padding_factor, ) tgt_dict.save(dict_path(args.target_lang)) def make_binary_dataset(input_prefix, output_prefix, lang, num_workers): dict = dictionary.Dictionary.load(dict_path(lang)) print('| [{}] Dictionary: {} types'.format(lang, len(dict) - 1)) n_seq_tok = [0, 0] replaced = Counter() def merge_result(worker_result): replaced.update(worker_result['replaced']) n_seq_tok[0] += worker_result['nseq'] n_seq_tok[1] += worker_result['ntok'] input_file = '{}{}'.format(input_prefix, ('.' + lang) if lang is not None else '') offsets = Tokenizer.find_offsets(input_file, num_workers) pool = None if num_workers > 1: pool = Pool(processes=num_workers-1) for worker_id in range(1, num_workers): prefix = "{}{}".format(output_prefix, worker_id) pool.apply_async(binarize, (args, input_file, dict, prefix, lang, offsets[worker_id], offsets[worker_id + 1]), callback=merge_result) pool.close() ds = indexed_dataset.IndexedDatasetBuilder(dataset_dest_file(args, output_prefix, lang, 'bin')) merge_result(Tokenizer.binarize(input_file, dict, lambda t: ds.add_item(t), offset=0, end=offsets[1])) if num_workers > 1: pool.join() for worker_id in range(1, num_workers): prefix = "{}{}".format(output_prefix, worker_id) temp_file_path = dataset_dest_prefix(args, prefix, lang) ds.merge_file_(temp_file_path) os.remove(indexed_dataset.data_file_path(temp_file_path)) os.remove(indexed_dataset.index_file_path(temp_file_path)) ds.finalize(dataset_dest_file(args, output_prefix, lang, 'idx')) print('| [{}] {}: {} sents, {} tokens, {:.3}% replaced by {}'.format( lang, input_file, n_seq_tok[0], n_seq_tok[1], 100 * sum(replaced.values()) / n_seq_tok[1], dict.unk_word)) def make_dataset(input_prefix, output_prefix, lang, num_workers=1): if args.output_format == 'binary': make_binary_dataset(input_prefix, output_prefix, lang, num_workers) elif args.output_format == 'raw': # Copy original text file to destination folder output_text_file = dest_path( output_prefix + '.{}-{}'.format(args.source_lang, args.target_lang), lang, ) shutil.copyfile(file_name(input_prefix, lang), output_text_file) def make_all(lang): if args.trainpref: make_dataset(args.trainpref, 'train', lang, num_workers=args.workers) if args.validpref: for k, validpref in enumerate(args.validpref.split(',')): outprefix = 'valid{}'.format(k) if k > 0 else 'valid' make_dataset(validpref, outprefix, lang) if args.testpref: for k, testpref in enumerate(args.testpref.split(',')): outprefix = 'test{}'.format(k) if k > 0 else 'test' make_dataset(testpref, outprefix, lang) make_all(args.source_lang) if target: make_all(args.target_lang) print('| Wrote preprocessed data to {}'.format(args.destdir)) if args.alignfile: assert args.trainpref, "--trainpref must be set if --alignfile is specified" src_file_name = train_path(args.source_lang) tgt_file_name = train_path(args.target_lang) src_dict = dictionary.Dictionary.load(dict_path(args.source_lang)) tgt_dict = dictionary.Dictionary.load(dict_path(args.target_lang)) freq_map = {} with open(args.alignfile, 'r') as align_file: with open(src_file_name, 'r') as src_file: with open(tgt_file_name, 'r') as tgt_file: for a, s, t in zip_longest(align_file, src_file, tgt_file): si = Tokenizer.tokenize(s, src_dict, add_if_not_exist=False) ti = Tokenizer.tokenize(t, tgt_dict, add_if_not_exist=False) ai = list(map(lambda x: tuple(x.split('-')), a.split())) for sai, tai in ai: srcidx = si[int(sai)] tgtidx = ti[int(tai)] if srcidx != src_dict.unk() and tgtidx != tgt_dict.unk(): assert srcidx != src_dict.pad() assert srcidx != src_dict.eos() assert tgtidx != tgt_dict.pad() assert tgtidx != tgt_dict.eos() if srcidx not in freq_map: freq_map[srcidx] = {} if tgtidx not in freq_map[srcidx]: freq_map[srcidx][tgtidx] = 1 else: freq_map[srcidx][tgtidx] += 1 align_dict = {} for srcidx in freq_map.keys(): align_dict[srcidx] = max(freq_map[srcidx], key=freq_map[srcidx].get) with open(os.path.join(args.destdir, 'alignment.{}-{}.txt'.format( args.source_lang, args.target_lang)), 'w') as f: for k, v in align_dict.items(): print('{} {}'.format(src_dict[k], tgt_dict[v]), file=f) def binarize(args, filename, dict, output_prefix, lang, offset, end): ds = indexed_dataset.IndexedDatasetBuilder(dataset_dest_file(args, output_prefix, lang, 'bin')) def consumer(tensor): ds.add_item(tensor) res = Tokenizer.binarize(filename, dict, consumer, offset=offset, end=end) ds.finalize(dataset_dest_file(args, output_prefix, lang, 'idx')) return res def dataset_dest_prefix(args, output_prefix, lang): base = f'{args.destdir}/{output_prefix}' lang_part = f'.{args.source_lang}-{args.target_lang}.{lang}' if lang is not None else '' return f'{base}{lang_part}' def dataset_dest_file(args, output_prefix, lang, extension): base = dataset_dest_prefix(args, output_prefix, lang) return f'{base}.{extension}' if __name__ == '__main__': parser = get_parser() args = parser.parse_args() main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/preprocess_bert.py
Python
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Data pre-processing: build vocabularies and binarize training data. """ import argparse from collections import Counter from itertools import zip_longest import os import shutil from fairseq.data import indexed_dataset, dictionary from fairseq.tokenizer import Tokenizer, tokenize_line from multiprocessing import Pool, Manager, Process def get_parser(): parser = argparse.ArgumentParser() parser.add_argument('-s', '--source-lang', default=None, metavar='SRC', help='source language') parser.add_argument('-t', '--target-lang', default=None, metavar='TARGET', help='target language') parser.add_argument('--trainpref', metavar='FP', default=None, help='train file prefix') parser.add_argument('--validpref', metavar='FP', default=None, help='comma separated, valid file prefixes') parser.add_argument('--testpref', metavar='FP', default=None, help='comma separated, test file prefixes') parser.add_argument('--destdir', metavar='DIR', default='data-bin', help='destination dir') parser.add_argument('--thresholdtgt', metavar='N', default=0, type=int, help='map words appearing less than threshold times to unknown') parser.add_argument('--thresholdsrc', metavar='N', default=0, type=int, help='map words appearing less than threshold times to unknown') parser.add_argument('--tgtdict', metavar='FP', help='reuse given target dictionary') parser.add_argument('--srcdict', metavar='FP', help='reuse given source dictionary') parser.add_argument('--nwordstgt', metavar='N', default=-1, type=int, help='number of target words to retain') parser.add_argument('--nwordssrc', metavar='N', default=-1, type=int, help='number of source words to retain') parser.add_argument('--alignfile', metavar='ALIGN', default=None, help='an alignment file (optional)') parser.add_argument('--output-format', metavar='FORMAT', default='binary', choices=['binary', 'raw'], help='output format (optional)') parser.add_argument('--joined-dictionary', action='store_true', help='Generate joined dictionary') parser.add_argument('--only-source', action='store_true', help='Only process the source language') parser.add_argument('--padding-factor', metavar='N', default=8, type=int, help='Pad dictionary size to be multiple of N') parser.add_argument('--workers', metavar='N', default=1, type=int, help='number of parallel workers') return parser def main(args): print(args) os.makedirs(args.destdir, exist_ok=True) target = not args.only_source def build_dictionary(filenames): d = dictionary.BertDictionary() for filename in filenames: Tokenizer.add_file_to_dictionary(filename, d, tokenize_line, args.workers) return d def train_path(lang): return '{}{}'.format(args.trainpref, ('.' + lang) if lang else '') def file_name(prefix, lang): fname = prefix if lang is not None: fname += f'.{lang}' return fname def dest_path(prefix, lang): return os.path.join(args.destdir, file_name(prefix, lang)) def dict_path(lang): return dest_path('dict', lang) + '.txt' if args.joined_dictionary: assert not args.srcdict, 'cannot combine --srcdict and --joined-dictionary' assert not args.tgtdict, 'cannot combine --tgtdict and --joined-dictionary' src_dict = build_dictionary(set([ train_path(lang) for lang in [args.source_lang, args.target_lang] ])) tgt_dict = src_dict else: if args.srcdict: src_dict = dictionary.BertDictionary.load(args.srcdict) else: assert args.trainpref, "--trainpref must be set if --srcdict is not specified" src_dict = build_dictionary([train_path(args.source_lang)]) if target: if args.tgtdict: tgt_dict = dictionary.BertDictionary.load(args.tgtdict) else: assert args.trainpref, "--trainpref must be set if --tgtdict is not specified" tgt_dict = build_dictionary([train_path(args.target_lang)]) src_dict.finalize( threshold=args.thresholdsrc, nwords=args.nwordssrc, padding_factor=args.padding_factor, ) src_dict.save(dict_path(args.source_lang)) if target: if not args.joined_dictionary: tgt_dict.finalize( threshold=args.thresholdtgt, nwords=args.nwordstgt, padding_factor=args.padding_factor, ) tgt_dict.save(dict_path(args.target_lang)) def make_binary_dataset(input_prefix, output_prefix, lang, num_workers): dict = dictionary.BertDictionary.load(dict_path(lang)) print('| [{}] Dictionary: {} types'.format(lang, len(dict) - 1)) n_seq_tok = [0, 0] replaced = Counter() def merge_result(worker_result): replaced.update(worker_result['replaced']) n_seq_tok[0] += worker_result['nseq'] n_seq_tok[1] += worker_result['ntok'] input_file = '{}{}'.format(input_prefix, ('.' + lang) if lang is not None else '') offsets = Tokenizer.find_offsets(input_file, num_workers) pool = None if num_workers > 1: pool = Pool(processes=num_workers-1) for worker_id in range(1, num_workers): prefix = "{}{}".format(output_prefix, worker_id) pool.apply_async(binarize, (args, input_file, dict, prefix, lang, offsets[worker_id], offsets[worker_id + 1]), callback=merge_result) pool.close() ds = indexed_dataset.IndexedDatasetBuilder(dataset_dest_file(args, output_prefix, lang, 'bin')) merge_result(Tokenizer.binarize(input_file, dict, lambda t: ds.add_item(t), offset=0, end=offsets[1])) if num_workers > 1: pool.join() for worker_id in range(1, num_workers): prefix = "{}{}".format(output_prefix, worker_id) temp_file_path = dataset_dest_prefix(args, prefix, lang) ds.merge_file_(temp_file_path) os.remove(indexed_dataset.data_file_path(temp_file_path)) os.remove(indexed_dataset.index_file_path(temp_file_path)) ds.finalize(dataset_dest_file(args, output_prefix, lang, 'idx')) print('| [{}] {}: {} sents, {} tokens, {:.3}% replaced by {}'.format( lang, input_file, n_seq_tok[0], n_seq_tok[1], 100 * sum(replaced.values()) / n_seq_tok[1], dict.unk_word)) def make_dataset(input_prefix, output_prefix, lang, num_workers=1): if args.output_format == 'binary': make_binary_dataset(input_prefix, output_prefix, lang, num_workers) elif args.output_format == 'raw': # Copy original text file to destination folder output_text_file = dest_path( output_prefix + '.{}-{}'.format(args.source_lang, args.target_lang), lang, ) shutil.copyfile(file_name(input_prefix, lang), output_text_file) def make_all(lang): if args.trainpref: make_dataset(args.trainpref, 'train', lang, num_workers=args.workers) if args.validpref: for k, validpref in enumerate(args.validpref.split(',')): outprefix = 'valid{}'.format(k) if k > 0 else 'valid' make_dataset(validpref, outprefix, lang) if args.testpref: for k, testpref in enumerate(args.testpref.split(',')): outprefix = 'test{}'.format(k) if k > 0 else 'test' make_dataset(testpref, outprefix, lang) make_all(args.source_lang) if target: make_all(args.target_lang) print('| Wrote preprocessed data to {}'.format(args.destdir)) if args.alignfile: assert args.trainpref, "--trainpref must be set if --alignfile is specified" src_file_name = train_path(args.source_lang) tgt_file_name = train_path(args.target_lang) src_dict = dictionary.BertDictionary.load(dict_path(args.source_lang)) tgt_dict = dictionary.BertDictionary.load(dict_path(args.target_lang)) freq_map = {} with open(args.alignfile, 'r') as align_file: with open(src_file_name, 'r') as src_file: with open(tgt_file_name, 'r') as tgt_file: for a, s, t in zip_longest(align_file, src_file, tgt_file): si = Tokenizer.tokenize(s, src_dict, add_if_not_exist=False) ti = Tokenizer.tokenize(t, tgt_dict, add_if_not_exist=False) ai = list(map(lambda x: tuple(x.split('-')), a.split())) for sai, tai in ai: srcidx = si[int(sai)] tgtidx = ti[int(tai)] if srcidx != src_dict.unk() and tgtidx != tgt_dict.unk(): assert srcidx != src_dict.pad() assert srcidx != src_dict.eos() assert tgtidx != tgt_dict.pad() assert tgtidx != tgt_dict.eos() if srcidx not in freq_map: freq_map[srcidx] = {} if tgtidx not in freq_map[srcidx]: freq_map[srcidx][tgtidx] = 1 else: freq_map[srcidx][tgtidx] += 1 align_dict = {} for srcidx in freq_map.keys(): align_dict[srcidx] = max(freq_map[srcidx], key=freq_map[srcidx].get) with open(os.path.join(args.destdir, 'alignment.{}-{}.txt'.format( args.source_lang, args.target_lang)), 'w') as f: for k, v in align_dict.items(): print('{} {}'.format(src_dict[k], tgt_dict[v]), file=f) def binarize(args, filename, dict, output_prefix, lang, offset, end): ds = indexed_dataset.IndexedDatasetBuilder(dataset_dest_file(args, output_prefix, lang, 'bin')) def consumer(tensor): ds.add_item(tensor) res = Tokenizer.binarize(filename, dict, consumer, offset=offset, end=end) ds.finalize(dataset_dest_file(args, output_prefix, lang, 'idx')) return res def dataset_dest_prefix(args, output_prefix, lang): base = f'{args.destdir}/{output_prefix}' lang_part = f'.{args.source_lang}-{args.target_lang}.{lang}' if lang is not None else '' return f'{base}{lang_part}' def dataset_dest_file(args, output_prefix, lang, extension): base = dataset_dest_prefix(args, output_prefix, lang) return f'{base}.{extension}' if __name__ == '__main__': parser = get_parser() args = parser.parse_args() main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/score.py
Python
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ BLEU scoring of generated translations against reference translations. """ import argparse import os import sys from fairseq import bleu, tokenizer from fairseq.data import dictionary def get_parser(): parser = argparse.ArgumentParser(description='Command-line script for BLEU scoring.') parser.add_argument('-s', '--sys', default='-', help='system output') parser.add_argument('-r', '--ref', required=True, help='references') parser.add_argument('-o', '--order', default=4, metavar='N', type=int, help='consider ngrams up to this order') parser.add_argument('--ignore-case', action='store_true', help='case-insensitive scoring') return parser def main(): parser = get_parser() args = parser.parse_args() print(args) assert args.sys == '-' or os.path.exists(args.sys), \ "System output file {} does not exist".format(args.sys) assert os.path.exists(args.ref), \ "Reference file {} does not exist".format(args.ref) dict = dictionary.Dictionary() def readlines(fd): for line in fd.readlines(): if args.ignore_case: yield line.lower() yield line def score(fdsys): with open(args.ref) as fdref: scorer = bleu.Scorer(dict.pad(), dict.eos(), dict.unk()) for sys_tok, ref_tok in zip(readlines(fdsys), readlines(fdref)): sys_tok = tokenizer.Tokenizer.tokenize(sys_tok, dict) ref_tok = tokenizer.Tokenizer.tokenize(ref_tok, dict) scorer.add(ref_tok, sys_tok) print(scorer.result_string(args.order)) if args.sys == '-': score(sys.stdin) else: with open(args.sys, 'r') as f: score(f) if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/scripts/average_checkpoints.py
Python
#!/usr/bin/env python3 import argparse import collections import torch import os import re def average_checkpoints(inputs): """Loads checkpoints from inputs and returns a model with averaged weights. Args: inputs: An iterable of string paths of checkpoints to load from. Returns: A dict of string keys mapping to various values. The 'model' key from the returned dict should correspond to an OrderedDict mapping string parameter names to torch Tensors. """ params_dict = collections.OrderedDict() params_keys = None new_state = None for f in inputs: state = torch.load( f, map_location=( lambda s, _: torch.serialization.default_restore_location(s, 'cpu') ), ) # Copies over the settings from the first checkpoint if new_state is None: new_state = state model_params = state['model'] model_params_keys = list(model_params.keys()) if params_keys is None: params_keys = model_params_keys elif params_keys != model_params_keys: raise KeyError( 'For checkpoint {}, expected list of params: {}, ' 'but found: {}'.format(f, params_keys, model_params_keys) ) for k in params_keys: if k not in params_dict: params_dict[k] = [] p = model_params[k] if isinstance(p, torch.HalfTensor): p = p.float() params_dict[k].append(p) averaged_params = collections.OrderedDict() # v should be a list of torch Tensor. for k, v in params_dict.items(): summed_v = None for x in v: summed_v = summed_v + x if summed_v is not None else x averaged_params[k] = summed_v / len(v) new_state['model'] = averaged_params return new_state def last_n_checkpoints(paths, n, update_based): assert len(paths) == 1 path = paths[0] if update_based: pt_regexp = re.compile(r'checkpoint_\d+_(\d+)\.pt') else: pt_regexp = re.compile(r'checkpoint(\d+)\.pt') files = os.listdir(path) entries = [] for f in files: m = pt_regexp.fullmatch(f) if m is not None: entries.append((int(m.group(1)), m.group(0))) if len(entries) < n: raise Exception('Found {} checkpoint files but need at least {}', len(entries), n) return [os.path.join(path, x[1]) for x in sorted(entries, reverse=True)[:n]] def main(): parser = argparse.ArgumentParser( description='Tool to average the params of input checkpoints to ' 'produce a new checkpoint', ) parser.add_argument( '--inputs', required=True, nargs='+', help='Input checkpoint file paths.', ) parser.add_argument( '--output', required=True, metavar='FILE', help='Write the new checkpoint containing the averaged weights to this ' 'path.', ) num_group = parser.add_mutually_exclusive_group() num_group.add_argument( '--num-epoch-checkpoints', type=int, help='if set, will try to find checkpoints with names checkpoint_xx.pt in the path specified by input, ' 'and average last this many of them.', ) num_group.add_argument( '--num-update-checkpoints', type=int, help='if set, will try to find checkpoints with names checkpoint_ee_xx.pt in the path specified by input, ' 'and average last this many of them.', ) args = parser.parse_args() print(args) num = None is_update_based = False if args.num_update_checkpoints is not None: num = args.num_update_checkpoints is_update_based = True elif args.num_epoch_checkpoints is not None: num = args.num_epoch_checkpoints if num is not None: args.inputs = last_n_checkpoints(args.inputs, num, is_update_based) print('averaging checkpoints: ', args.inputs) new_state = average_checkpoints(args.inputs) torch.save(new_state, args.output) print('Finished writing averaged checkpoint to {}.'.format(args.output)) if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/scripts/build_sym_alignment.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # """ Use this script in order to build symmetric alignments for your translation dataset. This script depends on fast_align and mosesdecoder tools. You will need to build those before running the script. fast_align: github: http://github.com/clab/fast_align instructions: follow the instructions in README.md mosesdecoder: github: http://github.com/moses-smt/mosesdecoder instructions: http://www.statmt.org/moses/?n=Development.GetStarted The script produces the following files under --output_dir: text.joined - concatenation of lines from the source_file and the target_file. align.forward - forward pass of fast_align. align.backward - backward pass of fast_align. aligned.sym_heuristic - symmetrized alignment. """ import argparse import os from itertools import zip_longest def main(): parser = argparse.ArgumentParser(description='symmetric alignment builer') parser.add_argument('--fast_align_dir', help='path to fast_align build directory') parser.add_argument('--mosesdecoder_dir', help='path to mosesdecoder root directory') parser.add_argument('--sym_heuristic', help='heuristic to use for symmetrization', default='grow-diag-final-and') parser.add_argument('--source_file', help='path to a file with sentences ' 'in the source language') parser.add_argument('--target_file', help='path to a file with sentences ' 'in the target language') parser.add_argument('--output_dir', help='output directory') args = parser.parse_args() fast_align_bin = os.path.join(args.fast_align_dir, 'fast_align') symal_bin = os.path.join(args.mosesdecoder_dir, 'bin', 'symal') sym_fast_align_bin = os.path.join( args.mosesdecoder_dir, 'scripts', 'ems', 'support', 'symmetrize-fast-align.perl') # create joined file joined_file = os.path.join(args.output_dir, 'text.joined') with open(args.source_file, 'r') as src, open(args.target_file, 'r') as tgt: with open(joined_file, 'w') as joined: for s, t in zip_longest(src, tgt): print('{} ||| {}'.format(s.strip(), t.strip()), file=joined) bwd_align_file = os.path.join(args.output_dir, 'align.backward') # run forward alignment fwd_align_file = os.path.join(args.output_dir, 'align.forward') fwd_fast_align_cmd = '{FASTALIGN} -i {JOINED} -d -o -v > {FWD}'.format( FASTALIGN=fast_align_bin, JOINED=joined_file, FWD=fwd_align_file) assert os.system(fwd_fast_align_cmd) == 0 # run backward alignment bwd_align_file = os.path.join(args.output_dir, 'align.backward') bwd_fast_align_cmd = '{FASTALIGN} -i {JOINED} -d -o -v -r > {BWD}'.format( FASTALIGN=fast_align_bin, JOINED=joined_file, BWD=bwd_align_file) assert os.system(bwd_fast_align_cmd) == 0 # run symmetrization sym_out_file = os.path.join(args.output_dir, 'aligned') sym_cmd = '{SYMFASTALIGN} {FWD} {BWD} {SRC} {TGT} {OUT} {HEURISTIC} {SYMAL}'.format( SYMFASTALIGN=sym_fast_align_bin, FWD=fwd_align_file, BWD=bwd_align_file, SRC=args.source_file, TGT=args.target_file, OUT=sym_out_file, HEURISTIC=args.sym_heuristic, SYMAL=symal_bin ) assert os.system(sym_cmd) == 0 if __name__ == '__main__': main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/scripts/convert_dictionary.lua
Lua
-- Copyright (c) 2017-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the license found in the LICENSE file in -- the root directory of this source tree. An additional grant of patent rights -- can be found in the PATENTS file in the same directory. -- -- Usage: convert_dictionary.lua <dict.th7> require 'fairseq' require 'torch' require 'paths' if #arg < 1 then print('usage: convert_dictionary.lua <dict.th7>') os.exit(1) end if not paths.filep(arg[1]) then print('error: file does not exit: ' .. arg[1]) os.exit(1) end dict = torch.load(arg[1]) dst = paths.basename(arg[1]):gsub('.th7', '.txt') assert(dst:match('.txt$')) f = io.open(dst, 'w') for idx, symbol in ipairs(dict.index_to_symbol) do if idx > dict.cutoff then break end f:write(symbol) f:write(' ') f:write(dict.index_to_freq[idx]) f:write('\n') end f:close()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/scripts/convert_model.lua
Lua
-- Copyright (c) 2017-present, Facebook, Inc. -- All rights reserved. -- -- This source code is licensed under the license found in the LICENSE file in -- the root directory of this source tree. An additional grant of patent rights -- can be found in the PATENTS file in the same directory. -- -- Usage: convert_model.lua <model_epoch1.th7> require 'torch' local fairseq = require 'fairseq' model = torch.load(arg[1]) function find_weight_norm(container, module) for _, wn in ipairs(container:listModules()) do if torch.type(wn) == 'nn.WeightNorm' and wn.modules[1] == module then return wn end end end function push_state(dict, key, module) if torch.type(module) == 'nn.Linear' then local wn = find_weight_norm(model.module, module) assert(wn) dict[key .. '.weight_v'] = wn.v:float() dict[key .. '.weight_g'] = wn.g:float() elseif torch.type(module) == 'nn.TemporalConvolutionTBC' then local wn = find_weight_norm(model.module, module) assert(wn) local v = wn.v:float():view(wn.viewOut):transpose(2, 3) dict[key .. '.weight_v'] = v dict[key .. '.weight_g'] = wn.g:float():view(module.weight:size(3), 1, 1) else dict[key .. '.weight'] = module.weight:float() end if module.bias then dict[key .. '.bias'] = module.bias:float() end end encoder_dict = {} decoder_dict = {} combined_dict = {} function encoder_state(encoder) luts = encoder:findModules('nn.LookupTable') push_state(encoder_dict, 'embed_tokens', luts[1]) push_state(encoder_dict, 'embed_positions', luts[2]) fcs = encoder:findModules('nn.Linear') assert(#fcs >= 2) local nInputPlane = fcs[1].weight:size(1) push_state(encoder_dict, 'fc1', table.remove(fcs, 1)) push_state(encoder_dict, 'fc2', table.remove(fcs, #fcs)) for i, module in ipairs(encoder:findModules('nn.TemporalConvolutionTBC')) do push_state(encoder_dict, 'convolutions.' .. tostring(i - 1), module) if nInputPlane ~= module.weight:size(3) / 2 then push_state(encoder_dict, 'projections.' .. tostring(i - 1), table.remove(fcs, 1)) end nInputPlane = module.weight:size(3) / 2 end assert(#fcs == 0) end function decoder_state(decoder) luts = decoder:findModules('nn.LookupTable') push_state(decoder_dict, 'embed_tokens', luts[1]) push_state(decoder_dict, 'embed_positions', luts[2]) fcs = decoder:findModules('nn.Linear') local nInputPlane = fcs[1].weight:size(1) push_state(decoder_dict, 'fc1', table.remove(fcs, 1)) push_state(decoder_dict, 'fc2', fcs[#fcs - 1]) push_state(decoder_dict, 'fc3', fcs[#fcs]) table.remove(fcs, #fcs) table.remove(fcs, #fcs) for i, module in ipairs(decoder:findModules('nn.TemporalConvolutionTBC')) do if nInputPlane ~= module.weight:size(3) / 2 then push_state(decoder_dict, 'projections.' .. tostring(i - 1), table.remove(fcs, 1)) end nInputPlane = module.weight:size(3) / 2 local prefix = 'attention.' .. tostring(i - 1) push_state(decoder_dict, prefix .. '.in_projection', table.remove(fcs, 1)) push_state(decoder_dict, prefix .. '.out_projection', table.remove(fcs, 1)) push_state(decoder_dict, 'convolutions.' .. tostring(i - 1), module) end assert(#fcs == 0) end _encoder = model.module.modules[2] _decoder = model.module.modules[3] encoder_state(_encoder) decoder_state(_decoder) for k, v in pairs(encoder_dict) do combined_dict['encoder.' .. k] = v end for k, v in pairs(decoder_dict) do combined_dict['decoder.' .. k] = v end torch.save('state_dict.t7', combined_dict)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/scripts/read_binarized.py
Python
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # import argparse from fairseq.data import dictionary from fairseq.data import IndexedDataset def get_parser(): parser = argparse.ArgumentParser( description='writes text from binarized file to stdout') parser.add_argument('--dict', metavar='FP', required=True, help='dictionary containing known words') parser.add_argument('--input', metavar='FP', required=True, help='binarized file to read') return parser def main(args): dict = dictionary.Dictionary.load(args.dict) ds = IndexedDataset(args.input, fix_lua_indexing=True) for tensor_line in ds: print(dict.string(tensor_line)) if __name__ == '__main__': parser = get_parser() args = parser.parse_args() main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/setup.py
Python
#!/usr/bin/env python3 # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from setuptools import setup, find_packages, Extension import sys if sys.version_info < (3,): sys.exit('Sorry, Python3 is required for fairseq.') with open('README.md') as f: readme = f.read() with open('LICENSE') as f: license = f.read() with open('requirements.txt') as f: reqs = f.read() bleu = Extension( 'fairseq.libbleu', sources=[ 'fairseq/clib/libbleu/libbleu.cpp', 'fairseq/clib/libbleu/module.cpp', ], extra_compile_args=['-std=c++11'], ) setup( name='fairseq', version='0.6.0', description='Facebook AI Research Sequence-to-Sequence Toolkit', long_description=readme, license=license, install_requires=reqs.strip().split('\n'), packages=find_packages(), ext_modules=[bleu], test_suite='tests', )
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_average_checkpoints.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import collections import os import tempfile import unittest import numpy as np import torch from scripts.average_checkpoints import average_checkpoints class TestAverageCheckpoints(unittest.TestCase): def test_average_checkpoints(self): params_0 = collections.OrderedDict( [ ('a', torch.DoubleTensor([100.0])), ('b', torch.FloatTensor([[1.0, 2.0, 3.0], [4.0, 5.0, 6.0]])), ('c', torch.IntTensor([7, 8, 9])), ] ) params_1 = collections.OrderedDict( [ ('a', torch.DoubleTensor([1.0])), ('b', torch.FloatTensor([[1.0, 1.0, 1.0], [1.0, 1.0, 1.0]])), ('c', torch.IntTensor([2, 2, 2])), ] ) params_avg = collections.OrderedDict( [ ('a', torch.DoubleTensor([50.5])), ('b', torch.FloatTensor([[1.0, 1.5, 2.0], [2.5, 3.0, 3.5]])), # We expect truncation for integer division ('c', torch.IntTensor([4, 5, 5])), ] ) fd_0, path_0 = tempfile.mkstemp() fd_1, path_1 = tempfile.mkstemp() torch.save(collections.OrderedDict([('model', params_0)]), path_0) torch.save(collections.OrderedDict([('model', params_1)]), path_1) output = average_checkpoints([path_0, path_1])['model'] os.close(fd_0) os.remove(path_0) os.close(fd_1) os.remove(path_1) for (k_expected, v_expected), (k_out, v_out) in zip( params_avg.items(), output.items()): self.assertEqual( k_expected, k_out, 'Key mismatch - expected {} but found {}. ' '(Expected list of keys: {} vs actual list of keys: {})'.format( k_expected, k_out, params_avg.keys(), output.keys() ) ) np.testing.assert_allclose( v_expected.numpy(), v_out.numpy(), err_msg='Tensor value mismatch for key {}'.format(k_expected) ) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_backtranslation_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import unittest import tests.utils as test_utils import torch from fairseq.data.backtranslation_dataset import BacktranslationDataset class TestBacktranslationDataset(unittest.TestCase): def setUp(self): self.tgt_dict, self.w1, self.w2, self.src_tokens, self.src_lengths, self.model = ( test_utils.sequence_generator_setup() ) backtranslation_args = argparse.Namespace() """ Same as defaults from fairseq/options.py """ backtranslation_args.backtranslation_unkpen = 0 backtranslation_args.backtranslation_sampling = False backtranslation_args.backtranslation_max_len_a = 0 backtranslation_args.backtranslation_max_len_b = 200 backtranslation_args.backtranslation_beam = 2 self.backtranslation_args = backtranslation_args dummy_src_samples = self.src_tokens self.tgt_dataset = test_utils.TestDataset(data=dummy_src_samples) def test_backtranslation_dataset(self): backtranslation_dataset = BacktranslationDataset( args=self.backtranslation_args, tgt_dataset=self.tgt_dataset, tgt_dict=self.tgt_dict, backtranslation_model=self.model, ) dataloader = torch.utils.data.DataLoader( backtranslation_dataset, batch_size=2, collate_fn=backtranslation_dataset.collater, ) backtranslation_batch_result = next(iter(dataloader)) eos, pad, w1, w2 = self.tgt_dict.eos(), self.tgt_dict.pad(), self.w1, self.w2 # Note that we sort by src_lengths and add left padding, so actually # ids will look like: [1, 0] expected_src = torch.LongTensor([[w1, w2, w1, eos], [pad, pad, w1, eos]]) expected_tgt = torch.LongTensor([[w1, w2, eos], [w1, w2, eos]]) generated_src = backtranslation_batch_result["net_input"]["src_tokens"] tgt_tokens = backtranslation_batch_result["target"] self.assertTensorEqual(expected_src, generated_src) self.assertTensorEqual(expected_tgt, tgt_tokens) def assertTensorEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertEqual(t1.ne(t2).long().sum(), 0) if __name__ == "__main__": unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_binaries.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import contextlib from io import StringIO import os import random import sys import tempfile import unittest import torch from fairseq import options import preprocess import train import generate import interactive import eval_lm class TestTranslation(unittest.TestCase): def test_fconv(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fconv') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) train_translation_model(data_dir, 'fconv_iwslt_de_en') generate_main(data_dir) def test_raw(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fconv_raw') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir, ['--output-format', 'raw']) train_translation_model(data_dir, 'fconv_iwslt_de_en', ['--raw-text']) generate_main(data_dir, ['--raw-text']) def test_fp16(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fp16') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) train_translation_model(data_dir, 'fconv_iwslt_de_en', ['--fp16']) generate_main(data_dir) def test_update_freq(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_update_freq') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) train_translation_model(data_dir, 'fconv_iwslt_de_en', ['--update-freq', '3']) generate_main(data_dir) def test_max_positions(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_max_positions') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) with self.assertRaises(Exception) as context: train_translation_model( data_dir, 'fconv_iwslt_de_en', ['--max-target-positions', '5'], ) self.assertTrue( 'skip this example with --skip-invalid-size-inputs-valid-test' \ in str(context.exception) ) train_translation_model( data_dir, 'fconv_iwslt_de_en', ['--max-target-positions', '5', '--skip-invalid-size-inputs-valid-test'], ) with self.assertRaises(Exception) as context: generate_main(data_dir) generate_main(data_dir, ['--skip-invalid-size-inputs-valid-test']) def test_generation(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_sampling') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) train_translation_model(data_dir, 'fconv_iwslt_de_en') generate_main(data_dir, [ '--sampling', '--sampling-temperature', '2', '--beam', '2', '--nbest', '2', ]) generate_main(data_dir, [ '--sampling', '--sampling-topk', '3', '--beam', '2', '--nbest', '2', ]) generate_main(data_dir, ['--prefix-size', '2']) def test_lstm(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_lstm') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) train_translation_model(data_dir, 'lstm_wiseman_iwslt_de_en', [ '--encoder-layers', '2', '--decoder-layers', '2', ]) generate_main(data_dir) def test_lstm_bidirectional(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_lstm_bidirectional') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) train_translation_model(data_dir, 'lstm', [ '--encoder-layers', '2', '--encoder-bidirectional', '--encoder-hidden-size', '256', '--decoder-layers', '2', ]) generate_main(data_dir) def test_transformer(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_transformer') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) train_translation_model(data_dir, 'transformer_iwslt_de_en') generate_main(data_dir) class TestStories(unittest.TestCase): def test_fconv_self_att_wp(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fconv_self_att_wp') as data_dir: create_dummy_data(data_dir) preprocess_translation_data(data_dir) config = [ '--encoder-layers', '[(512, 3)] * 2', '--decoder-layers', '[(512, 3)] * 2', '--decoder-attention', 'True', '--encoder-attention', 'False', '--gated-attention', 'True', '--self-attention', 'True', '--project-input', 'True', ] train_translation_model(data_dir, 'fconv_self_att_wp', config) generate_main(data_dir) # fusion model os.rename(os.path.join(data_dir, 'checkpoint_last.pt'), os.path.join(data_dir, 'pretrained.pt')) config.extend([ '--pretrained', 'True', '--pretrained-checkpoint', os.path.join(data_dir, 'pretrained.pt'), '--save-dir', os.path.join(data_dir, 'fusion_model'), ]) train_translation_model(data_dir, 'fconv_self_att_wp', config) class TestLanguageModeling(unittest.TestCase): def test_fconv_lm(self): with contextlib.redirect_stdout(StringIO()): with tempfile.TemporaryDirectory('test_fconv_lm') as data_dir: create_dummy_data(data_dir) preprocess_lm_data(data_dir) train_language_model(data_dir, 'fconv_lm') eval_lm_main(data_dir) def create_dummy_data(data_dir, num_examples=1000, maxlen=20): def _create_dummy_data(filename): data = torch.rand(num_examples * maxlen) data = 97 + torch.floor(26 * data).int() with open(os.path.join(data_dir, filename), 'w') as h: offset = 0 for _ in range(num_examples): ex_len = random.randint(1, maxlen) ex_str = ' '.join(map(chr, data[offset:offset+ex_len])) print(ex_str, file=h) offset += ex_len _create_dummy_data('train.in') _create_dummy_data('train.out') _create_dummy_data('valid.in') _create_dummy_data('valid.out') _create_dummy_data('test.in') _create_dummy_data('test.out') def preprocess_translation_data(data_dir, extra_flags=None): preprocess_parser = preprocess.get_parser() preprocess_args = preprocess_parser.parse_args( [ '--source-lang', 'in', '--target-lang', 'out', '--trainpref', os.path.join(data_dir, 'train'), '--validpref', os.path.join(data_dir, 'valid'), '--testpref', os.path.join(data_dir, 'test'), '--thresholdtgt', '0', '--thresholdsrc', '0', '--destdir', data_dir, ] + (extra_flags or []), ) preprocess.main(preprocess_args) def train_translation_model(data_dir, arch, extra_flags=None): train_parser = options.get_training_parser() train_args = options.parse_args_and_arch( train_parser, [ '--task', 'translation', data_dir, '--save-dir', data_dir, '--arch', arch, '--optimizer', 'nag', '--lr', '0.05', '--max-tokens', '500', '--max-epoch', '1', '--no-progress-bar', '--distributed-world-size', '1', '--source-lang', 'in', '--target-lang', 'out', ] + (extra_flags or []), ) train.main(train_args) def generate_main(data_dir, extra_flags=None): generate_parser = options.get_generation_parser() generate_args = options.parse_args_and_arch( generate_parser, [ data_dir, '--path', os.path.join(data_dir, 'checkpoint_last.pt'), '--beam', '3', '--batch-size', '64', '--max-len-b', '5', '--gen-subset', 'valid', '--no-progress-bar', '--print-alignment', ] + (extra_flags or []), ) # evaluate model in batch mode generate.main(generate_args) # evaluate model interactively generate_args.buffer_size = 0 generate_args.max_sentences = None orig_stdin = sys.stdin sys.stdin = StringIO('h e l l o\n') interactive.main(generate_args) sys.stdin = orig_stdin def preprocess_lm_data(data_dir): preprocess_parser = preprocess.get_parser() preprocess_args = preprocess_parser.parse_args([ '--only-source', '--trainpref', os.path.join(data_dir, 'train.out'), '--validpref', os.path.join(data_dir, 'valid.out'), '--testpref', os.path.join(data_dir, 'test.out'), '--destdir', data_dir, ]) preprocess.main(preprocess_args) def train_language_model(data_dir, arch): train_parser = options.get_training_parser() train_args = options.parse_args_and_arch( train_parser, [ '--task', 'language_modeling', data_dir, '--arch', arch, '--optimizer', 'nag', '--lr', '1.0', '--criterion', 'adaptive_loss', '--adaptive-softmax-cutoff', '5,10,15', '--decoder-layers', '[(850, 3)] * 2 + [(1024,4)]', '--decoder-embed-dim', '280', '--max-tokens', '500', '--tokens-per-sample', '500', '--save-dir', data_dir, '--max-epoch', '1', '--no-progress-bar', '--distributed-world-size', '1', '--ddp-backend', 'no_c10d', ], ) train.main(train_args) def eval_lm_main(data_dir): eval_lm_parser = options.get_eval_lm_parser() eval_lm_args = options.parse_args_and_arch( eval_lm_parser, [ data_dir, '--path', os.path.join(data_dir, 'checkpoint_last.pt'), '--no-progress-bar', ], ) eval_lm.main(eval_lm_args) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_character_token_embedder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import unittest from fairseq.data import Dictionary from fairseq.modules import CharacterTokenEmbedder class TestCharacterTokenEmbedder(unittest.TestCase): def test_character_token_embedder(self): vocab = Dictionary() vocab.add_symbol('hello') vocab.add_symbol('there') embedder = CharacterTokenEmbedder(vocab, [(2, 16), (4, 32), (8, 64), (16, 2)], 64, 5, 2) test_sents = [['hello', 'unk', 'there'], ['there'], ['hello', 'there']] max_len = max(len(s) for s in test_sents) input = torch.LongTensor(len(test_sents), max_len + 2).fill_(vocab.pad()) for i in range(len(test_sents)): input[i][0] = vocab.eos() for j in range(len(test_sents[i])): input[i][j + 1] = vocab.index(test_sents[i][j]) input[i][j + 2] = vocab.eos() embs = embedder(input) assert embs.size() == (len(test_sents), max_len + 2, 5) self.assertAlmostEqual(embs[0][0], embs[1][0]) self.assertAlmostEqual(embs[0][0], embs[0][-1]) self.assertAlmostEqual(embs[0][1], embs[2][1]) self.assertAlmostEqual(embs[0][3], embs[1][1]) embs.sum().backward() assert embedder.char_embeddings.weight.grad is not None def assertAlmostEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertLess((t1 - t2).abs().max(), 1e-6) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_convtbc.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import unittest from fairseq.modules import ConvTBC import torch.nn as nn class TestConvTBC(unittest.TestCase): def test_convtbc(self): # ksz, in_channels, out_channels conv_tbc = ConvTBC(4, 5, kernel_size=3, padding=1) # out_channels, in_channels, ksz conv1d = nn.Conv1d(4, 5, kernel_size=3, padding=1) conv_tbc.weight.data.copy_(conv1d.weight.data.transpose(0, 2)) conv_tbc.bias.data.copy_(conv1d.bias.data) input_tbc = torch.randn(7, 2, 4, requires_grad=True) input1d = input_tbc.data.transpose(0, 1).transpose(1, 2) input1d.requires_grad = True output_tbc = conv_tbc(input_tbc) output1d = conv1d(input1d) self.assertAlmostEqual(output_tbc.data.transpose(0, 1).transpose(1, 2), output1d.data) grad_tbc = torch.randn(output_tbc.size()) grad1d = grad_tbc.transpose(0, 1).transpose(1, 2).contiguous() output_tbc.backward(grad_tbc) output1d.backward(grad1d) self.assertAlmostEqual(conv_tbc.weight.grad.data.transpose(0, 2), conv1d.weight.grad.data) self.assertAlmostEqual(conv_tbc.bias.grad.data, conv1d.bias.grad.data) self.assertAlmostEqual(input_tbc.grad.data.transpose(0, 1).transpose(1, 2), input1d.grad.data) def assertAlmostEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertLess((t1 - t2).abs().max(), 1e-4) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_dictionary.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import tempfile import unittest import torch from fairseq.data import Dictionary from fairseq.tokenizer import Tokenizer class TestDictionary(unittest.TestCase): def test_finalize(self): txt = [ 'A B C D', 'B C D', 'C D', 'D', ] ref_ids1 = list(map(torch.IntTensor, [ [4, 5, 6, 7, 2], [5, 6, 7, 2], [6, 7, 2], [7, 2], ])) ref_ids2 = list(map(torch.IntTensor, [ [7, 6, 5, 4, 2], [6, 5, 4, 2], [5, 4, 2], [4, 2], ])) # build dictionary d = Dictionary() for line in txt: Tokenizer.tokenize(line, d, add_if_not_exist=True) def get_ids(dictionary): ids = [] for line in txt: ids.append(Tokenizer.tokenize(line, dictionary, add_if_not_exist=False)) return ids def assertMatch(ids, ref_ids): for toks, ref_toks in zip(ids, ref_ids): self.assertEqual(toks.size(), ref_toks.size()) self.assertEqual(0, (toks != ref_toks).sum().item()) ids = get_ids(d) assertMatch(ids, ref_ids1) # check finalized dictionary d.finalize() finalized_ids = get_ids(d) assertMatch(finalized_ids, ref_ids2) # write to disk and reload with tempfile.NamedTemporaryFile(mode='w') as tmp_dict: d.save(tmp_dict.name) d = Dictionary.load(tmp_dict.name) reload_ids = get_ids(d) assertMatch(reload_ids, ref_ids2) assertMatch(finalized_ids, reload_ids) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_iterators.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import unittest from fairseq.data import iterators class TestIterators(unittest.TestCase): def test_counting_iterator(self): x = list(range(10)) itr = iterators.CountingIterator(x) self.assertTrue(itr.has_next()) self.assertEqual(next(itr), 0) self.assertEqual(next(itr), 1) itr.skip(3) self.assertEqual(next(itr), 5) itr.skip(3) self.assertEqual(next(itr), 9) self.assertFalse(itr.has_next()) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_label_smoothing.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import copy import unittest import torch from fairseq.criterions.cross_entropy import CrossEntropyCriterion from fairseq.criterions.label_smoothed_cross_entropy import LabelSmoothedCrossEntropyCriterion import tests.utils as test_utils class TestLabelSmoothing(unittest.TestCase): def setUp(self): # build dictionary self.d = test_utils.dummy_dictionary(3) vocab = len(self.d) self.assertEqual(vocab, 4 + 3) # 4 special + 3 tokens self.assertEqual(self.d.pad(), 1) self.assertEqual(self.d.eos(), 2) self.assertEqual(self.d.unk(), 3) pad, eos, unk, w1, w2, w3 = 1, 2, 3, 4, 5, 6 # noqa: F841 # build dataset self.data = [ # the first batch item has padding {'source': torch.LongTensor([w1, eos]), 'target': torch.LongTensor([w1, eos])}, {'source': torch.LongTensor([w1, eos]), 'target': torch.LongTensor([w1, w1, eos])}, ] self.sample = next(test_utils.dummy_dataloader(self.data)) # build model self.args = argparse.Namespace() self.args.sentence_avg = False self.args.probs = torch.FloatTensor([ # pad eos unk w1 w2 w3 [0.05, 0.05, 0.1, 0.05, 0.3, 0.4, 0.05], [0.05, 0.10, 0.2, 0.05, 0.2, 0.3, 0.10], [0.05, 0.15, 0.3, 0.05, 0.1, 0.2, 0.15], ]).unsqueeze(0).expand(2, 3, 7) # add batch dimension self.task = test_utils.TestTranslationTask.setup_task(self.args, self.d, self.d) self.model = self.task.build_model(self.args) def test_nll_loss(self): self.args.label_smoothing = 0.1 nll_crit = CrossEntropyCriterion(self.args, self.task) smooth_crit = LabelSmoothedCrossEntropyCriterion(self.args, self.task) nll_loss, nll_sample_size, nll_logging_output = nll_crit(self.model, self.sample) smooth_loss, smooth_sample_size, smooth_logging_output = smooth_crit(self.model, self.sample) self.assertLess(abs(nll_loss - nll_logging_output['loss']), 1e-6) self.assertLess(abs(nll_loss - smooth_logging_output['nll_loss']), 1e-6) def test_padding(self): self.args.label_smoothing = 0.1 crit = LabelSmoothedCrossEntropyCriterion(self.args, self.task) loss, _, logging_output = crit(self.model, self.sample) def get_one_no_padding(idx): # create a new sample with just a single batch item so that there's # no padding sample1 = next(test_utils.dummy_dataloader([self.data[idx]])) args1 = copy.copy(self.args) args1.probs = args1.probs[idx, :, :].unsqueeze(0) model1 = self.task.build_model(args1) loss1, _, _ = crit(model1, sample1) return loss1 loss1 = get_one_no_padding(0) loss2 = get_one_no_padding(1) self.assertAlmostEqual(loss, loss1 + loss2) def test_reduction(self): self.args.label_smoothing = 0.1 crit = LabelSmoothedCrossEntropyCriterion(self.args, self.task) loss, _, logging_output = crit(self.model, self.sample, reduce=True) unreduced_loss, _, _ = crit(self.model, self.sample, reduce=False) self.assertAlmostEqual(loss, unreduced_loss.sum()) def test_zero_eps(self): self.args.label_smoothing = 0.0 nll_crit = CrossEntropyCriterion(self.args, self.task) smooth_crit = LabelSmoothedCrossEntropyCriterion(self.args, self.task) nll_loss, nll_sample_size, nll_logging_output = nll_crit(self.model, self.sample) smooth_loss, smooth_sample_size, smooth_logging_output = smooth_crit(self.model, self.sample) self.assertAlmostEqual(nll_loss, smooth_loss) def assertAlmostEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertLess((t1 - t2).abs().max(), 1e-6) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_reproducibility.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import contextlib from io import StringIO import json import os import tempfile import unittest import torch from fairseq import options from . import test_binaries class TestReproducibility(unittest.TestCase): def _test_reproducibility(self, name, extra_flags=None): if extra_flags is None: extra_flags = [] with tempfile.TemporaryDirectory(name) as data_dir: with contextlib.redirect_stdout(StringIO()): test_binaries.create_dummy_data(data_dir) test_binaries.preprocess_translation_data(data_dir) # train epochs 1 and 2 together stdout = StringIO() with contextlib.redirect_stdout(stdout): test_binaries.train_translation_model( data_dir, 'fconv_iwslt_de_en', [ '--dropout', '0.0', '--log-format', 'json', '--log-interval', '1', '--max-epoch', '3', ] + extra_flags, ) stdout = stdout.getvalue() train_log, valid_log = map(json.loads, stdout.split('\n')[-4:-2]) # train epoch 2, resuming from previous checkpoint 1 os.rename( os.path.join(data_dir, 'checkpoint1.pt'), os.path.join(data_dir, 'checkpoint_last.pt'), ) stdout = StringIO() with contextlib.redirect_stdout(stdout): test_binaries.train_translation_model( data_dir, 'fconv_iwslt_de_en', [ '--dropout', '0.0', '--log-format', 'json', '--log-interval', '1', '--max-epoch', '3', ] + extra_flags, ) stdout = stdout.getvalue() train_res_log, valid_res_log = map(json.loads, stdout.split('\n')[-4:-2]) def cast(s): return round(float(s), 3) for k in ['loss', 'ppl', 'num_updates', 'gnorm']: self.assertEqual(cast(train_log[k]), cast(train_res_log[k])) for k in ['valid_loss', 'valid_ppl', 'num_updates', 'best']: self.assertEqual(cast(valid_log[k]), cast(valid_res_log[k])) def test_reproducibility(self): self._test_reproducibility('test_reproducibility') def test_reproducibility_fp16(self): self._test_reproducibility('test_reproducibility_fp16', [ '--fp16', '--fp16-init-scale', '4096', ]) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_sequence_generator.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import unittest import torch from fairseq.sequence_generator import SequenceGenerator import tests.utils as test_utils class TestSequenceGenerator(unittest.TestCase): def setUp(self): self.tgt_dict, self.w1, self.w2, src_tokens, src_lengths, self.model = ( test_utils.sequence_generator_setup() ) self.encoder_input = { 'src_tokens': src_tokens, 'src_lengths': src_lengths, } def test_with_normalization(self): generator = SequenceGenerator([self.model], self.tgt_dict) hypos = generator.generate(self.encoder_input, beam_size=2) eos, w1, w2 = self.tgt_dict.eos(), self.w1, self.w2 # sentence 1, beam 1 self.assertHypoTokens(hypos[0][0], [w1, eos]) self.assertHypoScore(hypos[0][0], [0.9, 1.0]) # sentence 1, beam 2 self.assertHypoTokens(hypos[0][1], [w2, w1, w2, eos]) self.assertHypoScore(hypos[0][1], [0.1, 0.9, 0.9, 1.0]) # sentence 2, beam 1 self.assertHypoTokens(hypos[1][0], [w1, w2, w1, eos]) self.assertHypoScore(hypos[1][0], [0.7, 0.4, 0.4, 1.0]) # sentence 2, beam 2 self.assertHypoTokens(hypos[1][1], [w1, w2, eos]) self.assertHypoScore(hypos[1][1], [0.7, 0.4, 0.6]) def test_without_normalization(self): # Sentence 1: unchanged from the normalized case # Sentence 2: beams swap order generator = SequenceGenerator([self.model], self.tgt_dict, normalize_scores=False) hypos = generator.generate(self.encoder_input, beam_size=2) eos, w1, w2 = self.tgt_dict.eos(), self.w1, self.w2 # sentence 1, beam 1 self.assertHypoTokens(hypos[0][0], [w1, eos]) self.assertHypoScore(hypos[0][0], [0.9, 1.0], normalized=False) # sentence 1, beam 2 self.assertHypoTokens(hypos[0][1], [w2, w1, w2, eos]) self.assertHypoScore(hypos[0][1], [0.1, 0.9, 0.9, 1.0], normalized=False) # sentence 2, beam 1 self.assertHypoTokens(hypos[1][0], [w1, w2, eos]) self.assertHypoScore(hypos[1][0], [0.7, 0.4, 0.6], normalized=False) # sentence 2, beam 2 self.assertHypoTokens(hypos[1][1], [w1, w2, w1, eos]) self.assertHypoScore(hypos[1][1], [0.7, 0.4, 0.4, 1.0], normalized=False) def test_with_lenpen_favoring_short_hypos(self): lenpen = 0.6 generator = SequenceGenerator([self.model], self.tgt_dict, len_penalty=lenpen) hypos = generator.generate(self.encoder_input, beam_size=2) eos, w1, w2 = self.tgt_dict.eos(), self.w1, self.w2 # sentence 1, beam 1 self.assertHypoTokens(hypos[0][0], [w1, eos]) self.assertHypoScore(hypos[0][0], [0.9, 1.0], lenpen=lenpen) # sentence 1, beam 2 self.assertHypoTokens(hypos[0][1], [w2, w1, w2, eos]) self.assertHypoScore(hypos[0][1], [0.1, 0.9, 0.9, 1.0], lenpen=lenpen) # sentence 2, beam 1 self.assertHypoTokens(hypos[1][0], [w1, w2, eos]) self.assertHypoScore(hypos[1][0], [0.7, 0.4, 0.6], lenpen=lenpen) # sentence 2, beam 2 self.assertHypoTokens(hypos[1][1], [w1, w2, w1, eos]) self.assertHypoScore(hypos[1][1], [0.7, 0.4, 0.4, 1.0], lenpen=lenpen) def test_with_lenpen_favoring_long_hypos(self): lenpen = 5.0 generator = SequenceGenerator([self.model], self.tgt_dict, len_penalty=lenpen) hypos = generator.generate(self.encoder_input, beam_size=2) eos, w1, w2 = self.tgt_dict.eos(), self.w1, self.w2 # sentence 1, beam 1 self.assertHypoTokens(hypos[0][0], [w2, w1, w2, eos]) self.assertHypoScore(hypos[0][0], [0.1, 0.9, 0.9, 1.0], lenpen=lenpen) # sentence 1, beam 2 self.assertHypoTokens(hypos[0][1], [w1, eos]) self.assertHypoScore(hypos[0][1], [0.9, 1.0], lenpen=lenpen) # sentence 2, beam 1 self.assertHypoTokens(hypos[1][0], [w1, w2, w1, eos]) self.assertHypoScore(hypos[1][0], [0.7, 0.4, 0.4, 1.0], lenpen=lenpen) # sentence 2, beam 2 self.assertHypoTokens(hypos[1][1], [w1, w2, eos]) self.assertHypoScore(hypos[1][1], [0.7, 0.4, 0.6], lenpen=lenpen) def test_maxlen(self): generator = SequenceGenerator([self.model], self.tgt_dict, maxlen=2) hypos = generator.generate(self.encoder_input, beam_size=2) eos, w1, w2 = self.tgt_dict.eos(), self.w1, self.w2 # sentence 1, beam 1 self.assertHypoTokens(hypos[0][0], [w1, eos]) self.assertHypoScore(hypos[0][0], [0.9, 1.0]) # sentence 1, beam 2 self.assertHypoTokens(hypos[0][1], [w2, w2, eos]) self.assertHypoScore(hypos[0][1], [0.1, 0.1, 0.6]) # sentence 2, beam 1 self.assertHypoTokens(hypos[1][0], [w1, w2, eos]) self.assertHypoScore(hypos[1][0], [0.7, 0.4, 0.6]) # sentence 2, beam 2 self.assertHypoTokens(hypos[1][1], [w2, w2, eos]) self.assertHypoScore(hypos[1][1], [0.3, 0.9, 0.01]) def test_no_stop_early(self): generator = SequenceGenerator([self.model], self.tgt_dict, stop_early=False) hypos = generator.generate(self.encoder_input, beam_size=2) eos, w1, w2 = self.tgt_dict.eos(), self.w1, self.w2 # sentence 1, beam 1 self.assertHypoTokens(hypos[0][0], [w1, eos]) self.assertHypoScore(hypos[0][0], [0.9, 1.0]) # sentence 1, beam 2 self.assertHypoTokens(hypos[0][1], [w2, w1, w2, eos]) self.assertHypoScore(hypos[0][1], [0.1, 0.9, 0.9, 1.0]) # sentence 2, beam 1 self.assertHypoTokens(hypos[1][0], [w2, w2, w2, w2, eos]) self.assertHypoScore(hypos[1][0], [0.3, 0.9, 0.99, 0.4, 1.0]) # sentence 2, beam 2 self.assertHypoTokens(hypos[1][1], [w1, w2, w1, eos]) self.assertHypoScore(hypos[1][1], [0.7, 0.4, 0.4, 1.0]) def assertHypoTokens(self, hypo, tokens): self.assertTensorEqual(hypo['tokens'], torch.LongTensor(tokens)) def assertHypoScore(self, hypo, pos_probs, normalized=True, lenpen=1.): pos_scores = torch.FloatTensor(pos_probs).log() self.assertAlmostEqual(hypo['positional_scores'], pos_scores) self.assertEqual(pos_scores.numel(), hypo['tokens'].numel()) score = pos_scores.sum() if normalized: score /= pos_scores.numel()**lenpen self.assertLess(abs(score - hypo['score']), 1e-6) def assertAlmostEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertLess((t1 - t2).abs().max(), 1e-4) def assertTensorEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertEqual(t1.ne(t2).long().sum(), 0) class TestDiverseBeamSearch(unittest.TestCase): def setUp(self): # construct dummy dictionary d = test_utils.dummy_dictionary(vocab_size=2) self.assertEqual(d.pad(), 1) self.assertEqual(d.eos(), 2) self.assertEqual(d.unk(), 3) self.eos = d.eos() self.w1 = 4 self.w2 = 5 # construct source data self.src_tokens = torch.LongTensor([ [self.w1, self.w2, self.eos], [self.w1, self.w2, self.eos], ]) self.src_lengths = torch.LongTensor([2, 2]) args = argparse.Namespace() unk = 0. args.beam_probs = [ # step 0: torch.FloatTensor([ # eos w1 w2 # sentence 1: [0.0, unk, 0.9, 0.1], # beam 1 [0.0, unk, 0.9, 0.1], # beam 2 # sentence 2: [0.0, unk, 0.7, 0.3], [0.0, unk, 0.7, 0.3], ]), # step 1: torch.FloatTensor([ # eos w1 w2 # sentence 1: [0.0, unk, 0.6, 0.4], [0.0, unk, 0.6, 0.4], # sentence 2: [0.25, unk, 0.35, 0.4], [0.25, unk, 0.35, 0.4], ]), # step 2: torch.FloatTensor([ # eos w1 w2 # sentence 1: [1.0, unk, 0.0, 0.0], [1.0, unk, 0.0, 0.0], # sentence 2: [0.9, unk, 0.1, 0.0], [0.9, unk, 0.1, 0.0], ]), ] task = test_utils.TestTranslationTask.setup_task(args, d, d) self.model = task.build_model(args) self.tgt_dict = task.target_dictionary def test_diverse_beam_search(self): generator = SequenceGenerator( [self.model], self.tgt_dict, beam_size=2, diverse_beam_groups=2, diverse_beam_strength=0., ) encoder_input = {'src_tokens': self.src_tokens, 'src_lengths': self.src_lengths} hypos = generator.generate(encoder_input) eos, w1, w2 = self.eos, self.w1, self.w2 # sentence 1, beam 1 self.assertHypoTokens(hypos[0][0], [w1, w1, eos]) self.assertHypoScore(hypos[0][0], [0.9, 0.6, 1.0]) # sentence 1, beam 2 self.assertHypoTokens(hypos[0][1], [w1, w1, eos]) self.assertHypoScore(hypos[0][1], [0.9, 0.6, 1.0]) # sentence 2, beam 1 self.assertHypoTokens(hypos[1][0], [w1, w2, eos]) self.assertHypoScore(hypos[1][0], [0.7, 0.4, 0.9]) # sentence 2, beam 2 self.assertHypoTokens(hypos[1][1], [w1, w2, eos]) self.assertHypoScore(hypos[1][1], [0.7, 0.4, 0.9]) def assertHypoTokens(self, hypo, tokens): self.assertTensorEqual(hypo['tokens'], torch.LongTensor(tokens)) def assertHypoScore(self, hypo, pos_probs, normalized=True, lenpen=1.): pos_scores = torch.FloatTensor(pos_probs).log() self.assertAlmostEqual(hypo['positional_scores'], pos_scores) self.assertEqual(pos_scores.numel(), hypo['tokens'].numel()) score = pos_scores.sum() if normalized: score /= pos_scores.numel()**lenpen self.assertLess(abs(score - hypo['score']), 1e-6) def assertAlmostEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertLess((t1 - t2).abs().max(), 1e-4) def assertTensorEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertEqual(t1.ne(t2).long().sum(), 0) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_sequence_scorer.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import unittest import torch from fairseq.sequence_scorer import SequenceScorer import tests.utils as test_utils class TestSequenceScorer(unittest.TestCase): def test_sequence_scorer(self): # construct dummy dictionary d = test_utils.dummy_dictionary(vocab_size=2) self.assertEqual(d.pad(), 1) self.assertEqual(d.eos(), 2) self.assertEqual(d.unk(), 3) eos = d.eos() w1 = 4 w2 = 5 # construct dataloader data = [ { 'source': torch.LongTensor([w1, w2, eos]), 'target': torch.LongTensor([w1, w2, w1, eos]), }, { 'source': torch.LongTensor([w2, eos]), 'target': torch.LongTensor([w2, w1, eos]), }, { 'source': torch.LongTensor([w2, eos]), 'target': torch.LongTensor([w2, eos]), }, ] data_itr = test_utils.dummy_dataloader(data) # specify expected output probabilities args = argparse.Namespace() unk = 0. args.beam_probs = [ # step 0: torch.FloatTensor([ # eos w1 w2 [0.0, unk, 0.6, 0.4], # sentence 1 [0.0, unk, 0.4, 0.6], # sentence 2 [0.0, unk, 0.7, 0.3], # sentence 3 ]), # step 1: torch.FloatTensor([ # eos w1 w2 [0.0, unk, 0.2, 0.7], # sentence 1 [0.0, unk, 0.8, 0.2], # sentence 2 [0.7, unk, 0.1, 0.2], # sentence 3 ]), # step 2: torch.FloatTensor([ # eos w1 w2 [0.10, unk, 0.50, 0.4], # sentence 1 [0.15, unk, 0.15, 0.7], # sentence 2 [0.00, unk, 0.00, 0.0], # sentence 3 ]), # step 3: torch.FloatTensor([ # eos w1 w2 [0.9, unk, 0.05, 0.05], # sentence 1 [0.0, unk, 0.00, 0.0], # sentence 2 [0.0, unk, 0.00, 0.0], # sentence 3 ]), ] expected_scores = [ [0.6, 0.7, 0.5, 0.9], # sentence 1 [0.6, 0.8, 0.15], # sentence 2 [0.3, 0.7], # sentence 3 ] task = test_utils.TestTranslationTask.setup_task(args, d, d) model = task.build_model(args) scorer = SequenceScorer([model], task.target_dictionary) for id, _src, _ref, hypos in scorer.score_batched_itr(data_itr): self.assertHypoTokens(hypos[0], data[id]['target']) self.assertHypoScore(hypos[0], expected_scores[id]) def assertHypoTokens(self, hypo, tokens): self.assertTensorEqual(hypo['tokens'], torch.LongTensor(tokens)) def assertHypoScore(self, hypo, pos_probs, normalized=True, lenpen=1.): pos_scores = torch.FloatTensor(pos_probs).log() self.assertAlmostEqual(hypo['positional_scores'], pos_scores) self.assertEqual(pos_scores.numel(), hypo['tokens'].numel()) score = pos_scores.sum() if normalized: score /= pos_scores.numel()**lenpen self.assertLess(abs(score - hypo['score']), 1e-6) def assertAlmostEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertLess((t1 - t2).abs().max(), 1e-4) def assertTensorEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertEqual(t1.ne(t2).long().sum(), 0) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_train.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import contextlib from io import StringIO import unittest from unittest.mock import MagicMock, patch import torch from fairseq import data import train def mock_trainer(epoch, num_updates, iterations_in_epoch): trainer = MagicMock() trainer.load_checkpoint.return_value = { 'train_iterator': { 'epoch': epoch, 'iterations_in_epoch': iterations_in_epoch, 'shuffle': False, }, } trainer.get_num_updates.return_value = num_updates return trainer def mock_dict(): d = MagicMock() d.pad.return_value = 1 d.eos.return_value = 2 d.unk.return_value = 3 return d def get_trainer_and_epoch_itr(epoch, epoch_size, num_updates, iterations_in_epoch): tokens = torch.LongTensor(list(range(epoch_size))) tokens_ds = data.TokenBlockDataset(tokens, sizes=[len(tokens)], block_size=1, pad=0, eos=1, include_targets=False) trainer = mock_trainer(epoch, num_updates, iterations_in_epoch) dataset = data.LanguagePairDataset(tokens_ds, tokens_ds.sizes, mock_dict(), shuffle=False) epoch_itr = data.EpochBatchIterator( dataset=dataset, collate_fn=dataset.collater, batch_sampler=[[i] for i in range(epoch_size)], ) return trainer, epoch_itr class TestLoadCheckpoint(unittest.TestCase): def setUp(self): self.args_mock = MagicMock() self.args_mock.optimizer_overrides = '{}' self.patches = { 'os.makedirs': MagicMock(), 'os.path.join': MagicMock(), 'os.path.isfile': MagicMock(return_value=True), } self.applied_patches = [patch(p, d) for p, d in self.patches.items()] [p.start() for p in self.applied_patches] def test_load_partial_checkpoint(self): with contextlib.redirect_stdout(StringIO()): trainer, epoch_itr = get_trainer_and_epoch_itr(2, 150, 200, 50) train.load_checkpoint(self.args_mock, trainer, epoch_itr) self.assertEqual(epoch_itr.epoch, 2) self.assertEqual(epoch_itr.iterations_in_epoch, 50) itr = epoch_itr.next_epoch_itr(shuffle=False) self.assertEqual(epoch_itr.epoch, 2) self.assertEqual(epoch_itr.iterations_in_epoch, 50) self.assertEqual(next(itr)['net_input']['src_tokens'][0].item(), 50) self.assertEqual(epoch_itr.iterations_in_epoch, 51) def test_load_full_checkpoint(self): with contextlib.redirect_stdout(StringIO()): trainer, epoch_itr = get_trainer_and_epoch_itr(2, 150, 300, 150) train.load_checkpoint(self.args_mock, trainer, epoch_itr) itr = epoch_itr.next_epoch_itr(shuffle=False) self.assertEqual(epoch_itr.epoch, 3) self.assertEqual(epoch_itr.iterations_in_epoch, 0) self.assertEqual(next(itr)['net_input']['src_tokens'][0].item(), 0) def test_load_no_checkpoint(self): with contextlib.redirect_stdout(StringIO()): trainer, epoch_itr = get_trainer_and_epoch_itr(0, 150, 0, 0) self.patches['os.path.isfile'].return_value = False train.load_checkpoint(self.args_mock, trainer, epoch_itr) itr = epoch_itr.next_epoch_itr(shuffle=False) self.assertEqual(epoch_itr.epoch, 1) self.assertEqual(epoch_itr.iterations_in_epoch, 0) self.assertEqual(next(itr)['net_input']['src_tokens'][0].item(), 0) def tearDown(self): patch.stopall() if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/test_utils.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import unittest import torch from fairseq import utils class TestUtils(unittest.TestCase): def test_convert_padding_direction(self): pad = 1 left_pad = torch.LongTensor([ [2, 3, 4, 5, 6], [1, 7, 8, 9, 10], [1, 1, 1, 11, 12], ]) right_pad = torch.LongTensor([ [2, 3, 4, 5, 6], [7, 8, 9, 10, 1], [11, 12, 1, 1, 1], ]) self.assertAlmostEqual( right_pad, utils.convert_padding_direction( left_pad, pad, left_to_right=True, ), ) self.assertAlmostEqual( left_pad, utils.convert_padding_direction( right_pad, pad, right_to_left=True, ), ) def test_make_positions(self): pad = 1 left_pad_input = torch.LongTensor([ [9, 9, 9, 9, 9], [1, 9, 9, 9, 9], [1, 1, 1, 9, 9], ]) left_pad_output = torch.LongTensor([ [2, 3, 4, 5, 6], [1, 2, 3, 4, 5], [1, 1, 1, 2, 3], ]) right_pad_input = torch.LongTensor([ [9, 9, 9, 9, 9], [9, 9, 9, 9, 1], [9, 9, 1, 1, 1], ]) right_pad_output = torch.LongTensor([ [2, 3, 4, 5, 6], [2, 3, 4, 5, 1], [2, 3, 1, 1, 1], ]) self.assertAlmostEqual( left_pad_output, utils.make_positions(left_pad_input, pad, left_pad=True), ) self.assertAlmostEqual( right_pad_output, utils.make_positions(right_pad_input, pad, left_pad=False), ) def assertAlmostEqual(self, t1, t2): self.assertEqual(t1.size(), t2.size(), "size mismatch") self.assertLess(utils.item((t1 - t2).abs().max()), 1e-4) if __name__ == '__main__': unittest.main()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/tests/utils.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import torch from fairseq import utils from fairseq.data import Dictionary from fairseq.data.language_pair_dataset import collate from fairseq.models import ( FairseqEncoder, FairseqIncrementalDecoder, FairseqModel, ) from fairseq.tasks import FairseqTask def dummy_dictionary(vocab_size, prefix='token_'): d = Dictionary() for i in range(vocab_size): token = prefix + str(i) d.add_symbol(token) d.finalize(padding_factor=1) # don't add extra padding symbols return d def dummy_dataloader( samples, padding_idx=1, eos_idx=2, batch_size=None, ): if batch_size is None: batch_size = len(samples) # add any missing data to samples for i, sample in enumerate(samples): if 'id' not in sample: sample['id'] = i # create dataloader dataset = TestDataset(samples) dataloader = torch.utils.data.DataLoader( dataset, batch_size=batch_size, collate_fn=(lambda samples: collate(samples, padding_idx, eos_idx)), ) return iter(dataloader) def sequence_generator_setup(): # construct dummy dictionary d = dummy_dictionary(vocab_size=2) eos = d.eos() w1 = 4 w2 = 5 # construct source data src_tokens = torch.LongTensor([[w1, w2, eos], [w1, w2, eos]]) src_lengths = torch.LongTensor([2, 2]) args = argparse.Namespace() unk = 0. args.beam_probs = [ # step 0: torch.FloatTensor([ # eos w1 w2 # sentence 1: [0.0, unk, 0.9, 0.1], # beam 1 [0.0, unk, 0.9, 0.1], # beam 2 # sentence 2: [0.0, unk, 0.7, 0.3], [0.0, unk, 0.7, 0.3], ]), # step 1: torch.FloatTensor([ # eos w1 w2 prefix # sentence 1: [1.0, unk, 0.0, 0.0], # w1: 0.9 (emit: w1 <eos>: 0.9*1.0) [0.0, unk, 0.9, 0.1], # w2: 0.1 # sentence 2: [0.25, unk, 0.35, 0.4], # w1: 0.7 (don't emit: w1 <eos>: 0.7*0.25) [0.00, unk, 0.10, 0.9], # w2: 0.3 ]), # step 2: torch.FloatTensor([ # eos w1 w2 prefix # sentence 1: [0.0, unk, 0.1, 0.9], # w2 w1: 0.1*0.9 [0.6, unk, 0.2, 0.2], # w2 w2: 0.1*0.1 (emit: w2 w2 <eos>: 0.1*0.1*0.6) # sentence 2: [0.60, unk, 0.4, 0.00], # w1 w2: 0.7*0.4 (emit: w1 w2 <eos>: 0.7*0.4*0.6) [0.01, unk, 0.0, 0.99], # w2 w2: 0.3*0.9 ]), # step 3: torch.FloatTensor([ # eos w1 w2 prefix # sentence 1: [1.0, unk, 0.0, 0.0], # w2 w1 w2: 0.1*0.9*0.9 (emit: w2 w1 w2 <eos>: 0.1*0.9*0.9*1.0) [1.0, unk, 0.0, 0.0], # w2 w1 w1: 0.1*0.9*0.1 (emit: w2 w1 w1 <eos>: 0.1*0.9*0.1*1.0) # sentence 2: [0.1, unk, 0.5, 0.4], # w2 w2 w2: 0.3*0.9*0.99 (emit: w2 w2 w2 <eos>: 0.3*0.9*0.99*0.1) [1.0, unk, 0.0, 0.0], # w1 w2 w1: 0.7*0.4*0.4 (emit: w1 w2 w1 <eos>: 0.7*0.4*0.4*1.0) ]), ] task = TestTranslationTask.setup_task(args, d, d) model = task.build_model(args) tgt_dict = task.target_dictionary return tgt_dict, w1, w2, src_tokens, src_lengths, model class TestDataset(torch.utils.data.Dataset): def __init__(self, data): super().__init__() self.data = data def __getitem__(self, index): return self.data[index] def __len__(self): return len(self.data) class TestTranslationTask(FairseqTask): def __init__(self, args, src_dict, tgt_dict, model): super().__init__(args) self.src_dict = src_dict self.tgt_dict = tgt_dict self.model = model @classmethod def setup_task(cls, args, src_dict=None, tgt_dict=None, model=None): return cls(args, src_dict, tgt_dict, model) def build_model(self, args): return TestModel.build_model(args, self) @property def source_dictionary(self): return self.src_dict @property def target_dictionary(self): return self.tgt_dict class TestModel(FairseqModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) @classmethod def build_model(cls, args, task): encoder = TestEncoder(args, task.source_dictionary) decoder = TestIncrementalDecoder(args, task.target_dictionary) return cls(encoder, decoder) class TestEncoder(FairseqEncoder): def __init__(self, args, dictionary): super().__init__(dictionary) self.args = args def forward(self, src_tokens, src_lengths): return src_tokens def reorder_encoder_out(self, encoder_out, new_order): return encoder_out.index_select(0, new_order) class TestIncrementalDecoder(FairseqIncrementalDecoder): def __init__(self, args, dictionary): super().__init__(dictionary) assert hasattr(args, 'beam_probs') or hasattr(args, 'probs') args.max_decoder_positions = getattr(args, 'max_decoder_positions', 100) self.args = args def forward(self, prev_output_tokens, encoder_out, incremental_state=None): if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] bbsz = prev_output_tokens.size(0) vocab = len(self.dictionary) src_len = encoder_out.size(1) tgt_len = prev_output_tokens.size(1) # determine number of steps if incremental_state is not None: # cache step number step = utils.get_incremental_state(self, incremental_state, 'step') if step is None: step = 0 utils.set_incremental_state(self, incremental_state, 'step', step + 1) steps = [step] else: steps = list(range(tgt_len)) # define output in terms of raw probs if hasattr(self.args, 'probs'): assert self.args.probs.dim() == 3, \ 'expected probs to have size bsz*steps*vocab' probs = self.args.probs.index_select(1, torch.LongTensor(steps)) else: probs = torch.FloatTensor(bbsz, len(steps), vocab).zero_() for i, step in enumerate(steps): # args.beam_probs gives the probability for every vocab element, # starting with eos, then unknown, and then the rest of the vocab if step < len(self.args.beam_probs): probs[:, i, self.dictionary.eos():] = self.args.beam_probs[step] else: probs[:, i, self.dictionary.eos()] = 1.0 # random attention attn = torch.rand(bbsz, tgt_len, src_len) return probs, attn def get_normalized_probs(self, net_output, log_probs, _): # the decoder returns probabilities directly probs = net_output[0] if log_probs: return probs.log() else: return probs def max_positions(self): return self.args.max_decoder_positions
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
bert/train.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Train a new model on one or across multiple GPUs. """ import collections import itertools import os import math import torch import numpy as np import scipy.stats from fairseq import distributed_utils, options, progress_bar, tasks, utils from fairseq.data import iterators from fairseq.trainer import Trainer from fairseq.meters import AverageMeter, StopwatchMeter def main(args): if args.max_tokens is None: args.max_tokens = 10240 print(args) if not torch.cuda.is_available(): raise NotImplementedError('Training on CPU is not supported') torch.cuda.set_device(args.device_id) torch.manual_seed(args.seed) # Setup task, e.g., translation, language modeling, etc. task = tasks.setup_task(args) # Load dataset splits load_dataset_splits(task, ['train', 'valid']) # Build model and criterion model = task.build_model(args) criterion = task.build_criterion(args) print('| model {}, criterion {}'.format(args.arch, criterion.__class__.__name__)) print('| num. model params: {}'.format(sum(p.numel() for p in model.parameters()))) # Make a dummy batch to (i) warm the caching allocator and (ii) as a # placeholder DistributedDataParallel when there's an uneven number of # batches per worker. max_positions = utils.resolve_max_positions( task.max_positions(), model.max_positions(), ) dummy_batch = task.dataset('train').get_dummy_batch(args.max_tokens, max_positions) # Build trainer trainer = Trainer(args, task, model, criterion, dummy_batch) print('| training on {} GPUs'.format(args.distributed_world_size)) print('| max tokens per GPU = {} and max sentences per GPU = {}'.format( args.max_tokens, args.max_sentences, )) # Initialize dataloader epoch_itr = task.get_batch_iterator( dataset=task.dataset(args.train_subset), max_tokens=args.max_tokens, max_sentences=args.max_sentences, max_positions=max_positions, ignore_invalid_inputs=True, required_batch_size_multiple=8, seed=args.seed, num_shards=args.distributed_world_size, shard_id=args.distributed_rank, ) # Load bert model if one is available if hasattr(args, 'load_bert') and args.load_bert: print('| load bert model from {}'.format(args.load_bert)) load_bert_model(args, trainer) # Load the latest checkpoint if one is available if not load_checkpoint(args, trainer, epoch_itr): trainer.dummy_train_step([dummy_batch]) # Train until the learning rate gets too small max_epoch = args.max_epoch or math.inf max_update = args.max_update or math.inf lr = trainer.get_lr() train_meter = StopwatchMeter() train_meter.start() valid_subsets = args.valid_subset.split(',') valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets) while lr > args.min_lr and epoch_itr.epoch < max_epoch and trainer.get_num_updates() < max_update: # train for one epoch if epoch_itr.epoch > 0: epoch_itr_state = epoch_itr.state_dict() epoch_itr = task.get_batch_iterator( dataset=task.dataset(args.train_subset), max_tokens=args.max_tokens, max_sentences=args.max_sentences, max_positions=max_positions, ignore_invalid_inputs=True, required_batch_size_multiple=8, seed=args.seed + epoch_itr.epoch, num_shards=args.distributed_world_size, shard_id=args.distributed_rank, ) epoch_itr.load_state_dict(epoch_itr_state) train(args, trainer, task, epoch_itr) if epoch_itr.epoch % args.validate_interval == 0: valid_losses = validate(args, trainer, task, epoch_itr, valid_subsets) # only use first validation loss to update the learning rate lr = trainer.lr_step(epoch_itr.epoch, valid_losses[0]) # save checkpoint if epoch_itr.epoch % args.save_interval == 0: save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) train_meter.stop() print('| done training in {:.1f} seconds'.format(train_meter.sum)) def train(args, trainer, task, epoch_itr): """Train the model for one epoch.""" # Update parameters every N batches if epoch_itr.epoch <= len(args.update_freq): update_freq = args.update_freq[epoch_itr.epoch - 1] else: update_freq = args.update_freq[-1] # Initialize data iterator itr = epoch_itr.next_epoch_itr() itr = iterators.GroupedIterator(itr, update_freq) progress = progress_bar.build_progress_bar( args, itr, epoch_itr.epoch, no_progress_bar='simple', ) extra_meters = collections.defaultdict(lambda: AverageMeter()) first_valid = args.valid_subset.split(',')[0] max_update = args.max_update or math.inf num_batches = len(epoch_itr) for i, samples in enumerate(progress, start=epoch_itr.iterations_in_epoch): log_output = trainer.train_step(samples) if log_output is None: continue # log mid-epoch stats stats = get_training_stats(trainer) for k, v in log_output.items(): if k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size', 'x', 'y', 'tp', 'tn', 'fp', 'fn']: continue # these are already logged above if 'loss' in k: extra_meters[k].update(v, log_output['sample_size']) else: extra_meters[k].update(v) stats[k] = extra_meters[k].avg progress.log(stats) # ignore the first mini-batch in words-per-second calculation if i == 0: trainer.get_meter('wps').reset() num_updates = trainer.get_num_updates() if args.save_interval_updates > 0 and num_updates % args.save_interval_updates == 0 and num_updates > 0: valid_losses = validate(args, trainer, task, epoch_itr, [first_valid]) save_checkpoint(args, trainer, epoch_itr, valid_losses[0]) if num_updates >= max_update: break # log end-of-epoch stats stats = get_training_stats(trainer) for k, meter in extra_meters.items(): stats[k] = meter.avg progress.print(stats) # reset training meters for k in [ 'train_loss', 'train_nll_loss', 'wps', 'ups', 'wpb', 'bsz', 'gnorm', 'clip', ]: meter = trainer.get_meter(k) if meter is not None: meter.reset() def get_training_stats(trainer): stats = collections.OrderedDict() stats['loss'] = '{:.3f}'.format(trainer.get_meter('train_loss').avg) if trainer.get_meter('train_nll_loss').count > 0: nll_loss = trainer.get_meter('train_nll_loss').avg stats['nll_loss'] = '{:.3f}'.format(nll_loss) else: nll_loss = trainer.get_meter('train_loss').avg stats['ppl'] = get_perplexity(nll_loss) stats['wps'] = round(trainer.get_meter('wps').avg) stats['ups'] = '{:.1f}'.format(trainer.get_meter('ups').avg) stats['wpb'] = round(trainer.get_meter('wpb').avg) stats['bsz'] = round(trainer.get_meter('bsz').avg) stats['num_updates'] = trainer.get_num_updates() stats['lr'] = trainer.get_lr() stats['gnorm'] = '{:.3f}'.format(trainer.get_meter('gnorm').avg) stats['clip'] = '{:.0%}'.format(trainer.get_meter('clip').avg) stats['oom'] = trainer.get_meter('oom').avg if trainer.get_meter('loss_scale') is not None: stats['loss_scale'] = '{:.3f}'.format(trainer.get_meter('loss_scale').avg) stats['wall'] = round(trainer.get_meter('wall').elapsed_time) stats['train_wall'] = round(trainer.get_meter('train_wall').sum) return stats def validate(args, trainer, task, epoch_itr, subsets): """Evaluate the model on the validation set(s) and return the losses.""" valid_losses = [] for subset in subsets: # Initialize data iterator itr = task.get_batch_iterator( dataset=task.dataset(subset), max_tokens=args.max_tokens, max_sentences=args.max_sentences_valid, max_positions=utils.resolve_max_positions( task.max_positions(), trainer.get_model().max_positions(), ), ignore_invalid_inputs=args.skip_invalid_size_inputs_valid_test, required_batch_size_multiple=8, seed=args.seed, num_shards=args.distributed_world_size, shard_id=args.distributed_rank, ).next_epoch_itr(shuffle=False) progress = progress_bar.build_progress_bar( args, itr, epoch_itr.epoch, prefix='valid on \'{}\' subset'.format(subset), no_progress_bar='simple' ) # reset validation loss meters for k in ['valid_loss', 'valid_nll_loss']: meter = trainer.get_meter(k) if meter is not None: meter.reset() extra_meters = collections.defaultdict(lambda: AverageMeter()) for sample in progress: log_output = trainer.valid_step(sample) for k, v in log_output.items(): if k in ['loss', 'nll_loss', 'ntokens', 'nsentences', 'sample_size', 'x', 'y', 'tp', 'tn', 'fp', 'fn']: continue extra_meters[k].update(v) # log validation stats stats = get_valid_stats(trainer) for k, meter in extra_meters.items(): stats[k] = meter.avg progress.print(stats) valid_losses.append(stats['valid_loss']) return valid_losses def get_valid_stats(trainer): stats = collections.OrderedDict() stats['valid_loss'] = trainer.get_meter('valid_loss').avg if trainer.get_meter('valid_nll_loss').count > 0: nll_loss = trainer.get_meter('valid_nll_loss').avg stats['valid_nll_loss'] = nll_loss else: nll_loss = trainer.get_meter('valid_loss').avg stats['valid_ppl'] = get_perplexity(nll_loss) stats['num_updates'] = trainer.get_num_updates() if hasattr(save_checkpoint, 'best'): stats['best'] = min(save_checkpoint.best, stats['valid_loss']) if trainer.cache['valid_x'] and trainer.cache['valid_y']: x = np.concatenate(trainer.cache['valid_x']) y = np.concatenate(trainer.cache['valid_y']) stats['pearson'] = scipy.stats.pearsonr(x, y)[0] stats['spearman'] = scipy.stats.spearmanr(x, y)[0] stats['acc'] = 0.5 * (stats['pearson'] + stats['spearman']) trainer.cache['valid_x'], trainer.cache['valid_y'] = [], [] if trainer.cache['valid_tp'] and trainer.cache['valid_tn'] and trainer.cache['valid_fp'] and trainer.cache['valid_fn']: tp = sum(trainer.cache['valid_tp']) tn = sum(trainer.cache['valid_tn']) fp = sum(trainer.cache['valid_fp']) fn = sum(trainer.cache['valid_fn']) tmp = 2 * tp + fp + fn stats['f1'] = (2 * tp) / tmp if tmp else 0 tmp = (tp + fp) * (tp + fn) * (tn + fp) * (tn + fn) stats['mcc'] = (tp * tn - fp * fn) / (tmp ** 0.5) if tmp else 0 trainer.cache['valid_tp'], trainer.cache['valid_tn'], trainer.cache['valid_fp'], trainer.cache['valid_fn'] = [], [], [], [] return stats def get_perplexity(loss): try: return '{:.2f}'.format(math.exp(loss)) except OverflowError: return float('inf') def save_checkpoint(args, trainer, epoch_itr, val_loss): if args.no_save or not distributed_utils.is_master(args): return epoch = epoch_itr.epoch end_of_epoch = epoch_itr.end_of_epoch() updates = trainer.get_num_updates() checkpoint_conds = collections.OrderedDict() checkpoint_conds['checkpoint{}.pt'.format(epoch)] = ( end_of_epoch and not args.no_epoch_checkpoints and epoch % args.save_interval == 0 ) checkpoint_conds['checkpoint_{}_{}.pt'.format(epoch, updates)] = ( not end_of_epoch and args.save_interval_updates > 0 and updates % args.save_interval_updates == 0 ) checkpoint_conds['checkpoint_best.pt'] = ( val_loss is not None and (not hasattr(save_checkpoint, 'best') or val_loss < save_checkpoint.best) ) checkpoint_conds['checkpoint_last.pt'] = True # keep this last so that it's a symlink prev_best = getattr(save_checkpoint, 'best', val_loss) if val_loss is not None: save_checkpoint.best = min(val_loss, prev_best) extra_state = { 'best': save_checkpoint.best, 'train_iterator': epoch_itr.state_dict(), 'val_loss': val_loss, } checkpoints = [os.path.join(args.save_dir, fn) for fn, cond in checkpoint_conds.items() if cond] if len(checkpoints) > 0: for cp in checkpoints: trainer.save_checkpoint(cp, extra_state) if not end_of_epoch and args.keep_interval_updates > 0: # remove old checkpoints; checkpoints are sorted in descending order checkpoints = utils.checkpoint_paths(args.save_dir, pattern=r'checkpoint_\d+_(\d+)\.pt') for old_chk in checkpoints[args.keep_interval_updates:]: os.remove(old_chk) def load_checkpoint(args, trainer, epoch_itr): """Load a checkpoint and replay dataloader to match.""" os.makedirs(args.save_dir, exist_ok=True) checkpoint_path = os.path.join(args.save_dir, args.restore_file) if os.path.isfile(checkpoint_path): extra_state = trainer.load_checkpoint(checkpoint_path, args.reset_optimizer, args.reset_lr_scheduler, eval(args.optimizer_overrides)) if extra_state is not None: # replay train iterator to match checkpoint epoch_itr.load_state_dict(extra_state['train_iterator']) print('| loaded checkpoint {} (epoch {} @ {} updates)'.format( checkpoint_path, epoch_itr.epoch, trainer.get_num_updates())) trainer.lr_step(epoch_itr.epoch) trainer.lr_step_update(trainer.get_num_updates()) if 'best' in extra_state: save_checkpoint.best = extra_state['best'] return True return False def load_bert_model(args, trainer): extra_state, _, _ = utils.load_bert_state(args.load_bert, trainer.get_model(), args) def load_dataset_splits(task, splits): for split in splits: if split == 'train': task.load_dataset(split, combine=True) else: for k in itertools.count(): split_k = split + (str(k) if k > 0 else '') try: task.load_dataset(split_k, combine=False) except FileNotFoundError as e: if k > 0: break raise e if __name__ == '__main__': parser = options.get_training_parser() args = options.parse_args_and_arch(parser) if args.distributed_port > 0 or args.distributed_init_method is not None: from distributed_train import main as distributed_main distributed_main(args) elif args.distributed_world_size > 1: from multiprocessing_train import main as multiprocessing_main multiprocessing_main(args) else: main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/distributed_train.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os import socket import subprocess from train import main as single_process_main from fairseq import distributed_utils, options def main(args): if args.distributed_init_method is None and args.distributed_port > 0: # We can determine the init method automatically for Slurm. node_list = os.environ.get('SLURM_JOB_NODELIST') if node_list is not None: try: hostnames = subprocess.check_output(['scontrol', 'show', 'hostnames', node_list]) args.distributed_init_method = 'tcp://{host}:{port}'.format( host=hostnames.split()[0].decode('utf-8'), port=args.distributed_port) args.distributed_rank = int(os.environ.get('SLURM_PROCID')) args.device_id = int(os.environ.get('SLURM_LOCALID')) except subprocess.CalledProcessError as e: # scontrol failed raise e except FileNotFoundError as e: # Slurm is not installed pass if args.distributed_init_method is None and args.distributed_port is None: raise ValueError('--distributed-init-method or --distributed-port ' 'must be specified for distributed training') args.distributed_rank = distributed_utils.distributed_init(args) print('| initialized host {} as rank {}'.format(socket.gethostname(), args.distributed_rank)) single_process_main(args) if __name__ == '__main__': parser = options.get_training_parser() args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/eval_lm.py
Python
#!/usr/bin/env python3 -u # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. """ Evaluate the perplexity of a trained language model. """ import numpy as np import torch from fairseq import data, options, progress_bar, tasks, utils from fairseq.meters import StopwatchMeter, TimeMeter from fairseq.sequence_scorer import SequenceScorer class WordStat(object): def __init__(self, word, is_bpe): self.word = word self.is_bpe = is_bpe self.log_prob = 0 self.count = 0 def add(self, log_prob): self.log_prob += log_prob self.count += 1 def __str__(self): return '{}\t{}\t{}\t{}'.format(self.word, self.count, self.log_prob / self.count, self.is_bpe) def main(parsed_args): assert parsed_args.path is not None, '--path required for evaluation!' print(parsed_args) use_cuda = torch.cuda.is_available() and not parsed_args.cpu task = tasks.setup_task(parsed_args) # Load ensemble print('| loading model(s) from {}'.format(parsed_args.path)) models, args = utils.load_ensemble_for_inference(parsed_args.path.split(':'), task) args.__dict__.update(parsed_args.__dict__) print(args) task.args = args # Load dataset splits task.load_dataset(args.gen_subset) print('| {} {} {} examples'.format(args.data, args.gen_subset, len(task.dataset(args.gen_subset)))) # Optimize ensemble for generation and set the source and dest dicts on the model (required by scorer) for model in models: model.make_generation_fast_() if args.fp16: model.half() assert len(models) > 0 itr = task.get_batch_iterator( dataset=task.dataset(args.gen_subset), max_tokens=args.max_tokens or 36000, max_sentences=args.max_sentences, max_positions=utils.resolve_max_positions(*[ model.max_positions() for model in models ]), num_shards=args.num_shards, shard_id=args.shard_id, ignore_invalid_inputs=True, ).next_epoch_itr(shuffle=False) gen_timer = StopwatchMeter() scorer = SequenceScorer(models, task.target_dictionary) if use_cuda: scorer.cuda() score_sum = 0. count = 0 if args.remove_bpe is not None: bpe_cont = args.remove_bpe.rstrip() bpe_toks = set(i for i in range(len(task.dictionary)) if task.dictionary[i].endswith(bpe_cont)) bpe_len = len(bpe_cont) else: bpe_toks = None bpe_len = 0 word_stats = dict() with progress_bar.build_progress_bar(args, itr) as t: results = scorer.score_batched_itr(t, cuda=use_cuda, timer=gen_timer) wps_meter = TimeMeter() for _, src_tokens, __, hypos in results: for hypo in hypos: pos_scores = hypo['positional_scores'] skipped_toks = 0 if bpe_toks is not None: for i in range(len(hypo['tokens']) - 1): if hypo['tokens'][i].item() in bpe_toks: skipped_toks += 1 pos_scores[i + 1] += pos_scores[i] pos_scores[i] = 0 inf_scores = pos_scores.eq(float('inf')) | pos_scores.eq(float('-inf')) if inf_scores.any(): print('| Skipping tokens with inf scores:', task.target_dictionary.string(hypo['tokens'][inf_scores.nonzero()])) pos_scores = pos_scores[(~inf_scores).nonzero()] score_sum += utils.item(pos_scores.sum()) count += pos_scores.numel() - skipped_toks if args.output_word_probs or args.output_word_stats: w = '' word_prob = [] is_bpe = False for i in range(len(hypo['tokens'])): w_ind = hypo['tokens'][i].item() w += task.dictionary[w_ind] if bpe_toks is not None and w_ind in bpe_toks: w = w[:-bpe_len] is_bpe = True else: word_prob.append((w, pos_scores[i].item())) word_stats.setdefault(w, WordStat(w, is_bpe)).add(pos_scores[i].item()) is_bpe = False w = '' if args.output_word_probs: print('\t'.join('{} [{:2f}]'.format(x[0], x[1]) for x in word_prob)) wps_meter.update(src_tokens.size(0)) t.log({'wps': round(wps_meter.avg)}) avg_nll_loss = -score_sum / count print('| Evaluated {} tokens in {:.1f}s ({:.2f} tokens/s)'.format(gen_timer.n, gen_timer.sum, 1. / gen_timer.avg)) print('| Loss: {:.4f}, Perplexity: {:.2f}'.format(avg_nll_loss, np.exp(avg_nll_loss))) if args.output_word_stats: for ws in sorted(word_stats.values(), key=lambda x: x.count, reverse=True): print(ws) if __name__ == '__main__': parser = options.get_eval_lm_parser() args = options.parse_args_and_arch(parser) main(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .multiprocessing_pdb import pdb __all__ = ['pdb'] import fairseq.criterions import fairseq.models import fairseq.modules import fairseq.optim import fairseq.optim.lr_scheduler import fairseq.tasks
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/bleu.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import ctypes import math import torch try: from fairseq import libbleu except ImportError as e: import sys sys.stderr.write('ERROR: missing libbleu.so. run `python setup.py install`\n') raise e C = ctypes.cdll.LoadLibrary(libbleu.__file__) class BleuStat(ctypes.Structure): _fields_ = [ ('reflen', ctypes.c_size_t), ('predlen', ctypes.c_size_t), ('match1', ctypes.c_size_t), ('count1', ctypes.c_size_t), ('match2', ctypes.c_size_t), ('count2', ctypes.c_size_t), ('match3', ctypes.c_size_t), ('count3', ctypes.c_size_t), ('match4', ctypes.c_size_t), ('count4', ctypes.c_size_t), ] class Scorer(object): def __init__(self, pad, eos, unk): self.stat = BleuStat() self.pad = pad self.eos = eos self.unk = unk self.reset() def reset(self, one_init=False): if one_init: C.bleu_one_init(ctypes.byref(self.stat)) else: C.bleu_zero_init(ctypes.byref(self.stat)) def add(self, ref, pred): if not isinstance(ref, torch.IntTensor): raise TypeError('ref must be a torch.IntTensor (got {})' .format(type(ref))) if not isinstance(pred, torch.IntTensor): raise TypeError('pred must be a torch.IntTensor(got {})' .format(type(pred))) # don't match unknown words rref = ref.clone() assert not rref.lt(0).any() rref[rref.eq(self.unk)] = -999 rref = rref.contiguous().view(-1) pred = pred.contiguous().view(-1) C.bleu_add( ctypes.byref(self.stat), ctypes.c_size_t(rref.size(0)), ctypes.c_void_p(rref.data_ptr()), ctypes.c_size_t(pred.size(0)), ctypes.c_void_p(pred.data_ptr()), ctypes.c_int(self.pad), ctypes.c_int(self.eos)) def score(self, order=4): psum = sum(math.log(p) if p > 0 else float('-Inf') for p in self.precision()[:order]) return self.brevity() * math.exp(psum / order) * 100 def precision(self): def ratio(a, b): return a / b if b > 0 else 0 return [ ratio(self.stat.match1, self.stat.count1), ratio(self.stat.match2, self.stat.count2), ratio(self.stat.match3, self.stat.count3), ratio(self.stat.match4, self.stat.count4), ] def brevity(self): r = self.stat.reflen / self.stat.predlen return min(1, math.exp(1 - r)) def result_string(self, order=4): assert order <= 4, "BLEU scores for order > 4 aren't supported" fmt = 'BLEU{} = {:2.2f}, {:2.1f}' for _ in range(1, order): fmt += '/{:2.1f}' fmt += ' (BP={:.3f}, ratio={:.3f}, syslen={}, reflen={})' bleup = [p * 100 for p in self.precision()[:order]] return fmt.format(order, self.score(order=order), *bleup, self.brevity(), self.stat.predlen/self.stat.reflen, self.stat.predlen, self.stat.reflen)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/clib/libbleu/libbleu.cpp
C++
/** * Copyright 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. */ #include <map> #include <array> #include <cstring> #include <cstdio> typedef struct { size_t reflen; size_t predlen; size_t match1; size_t count1; size_t match2; size_t count2; size_t match3; size_t count3; size_t match4; size_t count4; } bleu_stat; // left trim (remove pad) void bleu_ltrim(size_t* len, int** sent, int pad) { size_t start = 0; while(start < *len) { if (*(*sent + start) != pad) { break; } start++; } *sent += start; *len -= start; } // right trim remove (eos) void bleu_rtrim(size_t* len, int** sent, int pad, int eos) { size_t end = *len - 1; while (end > 0) { if (*(*sent + end) != eos && *(*sent + end) != pad) { break; } end--; } *len = end + 1; } // left and right trim void bleu_trim(size_t* len, int** sent, int pad, int eos) { bleu_ltrim(len, sent, pad); bleu_rtrim(len, sent, pad, eos); } size_t bleu_hash(int len, int* data) { size_t h = 14695981039346656037ul; size_t prime = 0x100000001b3; char* b = (char*) data; size_t blen = sizeof(int) * len; while (blen-- > 0) { h ^= *b++; h *= prime; } return h; } void bleu_addngram( size_t *ntotal, size_t *nmatch, size_t n, size_t reflen, int* ref, size_t predlen, int* pred) { if (predlen < n) { return; } predlen = predlen - n + 1; (*ntotal) += predlen; if (reflen < n) { return; } reflen = reflen - n + 1; std::map<size_t, size_t> count; while (predlen > 0) { size_t w = bleu_hash(n, pred++); count[w]++; predlen--; } while (reflen > 0) { size_t w = bleu_hash(n, ref++); if (count[w] > 0) { (*nmatch)++; count[w] -=1; } reflen--; } } extern "C" { void bleu_zero_init(bleu_stat* stat) { std::memset(stat, 0, sizeof(bleu_stat)); } void bleu_one_init(bleu_stat* stat) { bleu_zero_init(stat); stat->count1 = 0; stat->count2 = 1; stat->count3 = 1; stat->count4 = 1; stat->match1 = 0; stat->match2 = 1; stat->match3 = 1; stat->match4 = 1; } void bleu_add( bleu_stat* stat, size_t reflen, int* ref, size_t predlen, int* pred, int pad, int eos) { bleu_trim(&reflen, &ref, pad, eos); bleu_trim(&predlen, &pred, pad, eos); stat->reflen += reflen; stat->predlen += predlen; bleu_addngram(&stat->count1, &stat->match1, 1, reflen, ref, predlen, pred); bleu_addngram(&stat->count2, &stat->match2, 2, reflen, ref, predlen, pred); bleu_addngram(&stat->count3, &stat->match3, 3, reflen, ref, predlen, pred); bleu_addngram(&stat->count4, &stat->match4, 4, reflen, ref, predlen, pred); } }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/clib/libbleu/module.cpp
C++
/** * Copyright 2017-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the license found in the * LICENSE file in the root directory of this source tree. */ #include <Python.h> static PyMethodDef method_def[] = { {NULL, NULL, 0, NULL} }; static struct PyModuleDef module_def = { PyModuleDef_HEAD_INIT, "libbleu", /* name of module */ NULL, /* module documentation, may be NULL */ -1, /* size of per-interpreter state of the module, or -1 if the module keeps state in global variables. */ method_def }; #if PY_MAJOR_VERSION == 2 PyMODINIT_FUNC init_libbleu() #else PyMODINIT_FUNC PyInit_libbleu() #endif { PyObject *m = PyModule_Create(&module_def); if (!m) { return NULL; } return m; }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/criterions/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import importlib import os from .fairseq_criterion import FairseqCriterion CRITERION_REGISTRY = {} CRITERION_CLASS_NAMES = set() def build_criterion(args, task): return CRITERION_REGISTRY[args.criterion](args, task) def register_criterion(name): """Decorator to register a new criterion.""" def register_criterion_cls(cls): if name in CRITERION_REGISTRY: raise ValueError('Cannot register duplicate criterion ({})'.format(name)) if not issubclass(cls, FairseqCriterion): raise ValueError('Criterion ({}: {}) must extend FairseqCriterion'.format(name, cls.__name__)) if cls.__name__ in CRITERION_CLASS_NAMES: # We use the criterion class name as a unique identifier in # checkpoints, so all criterions must have unique class names. raise ValueError('Cannot register criterion with duplicate class name ({})'.format(cls.__name__)) CRITERION_REGISTRY[name] = cls CRITERION_CLASS_NAMES.add(cls.__name__) return cls return register_criterion_cls # automatically import any Python files in the criterions/ directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith('.py') and not file.startswith('_'): module = file[:file.find('.py')] importlib.import_module('fairseq.criterions.' + module)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/criterions/adaptive_loss.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch.nn.functional as F from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('adaptive_loss') class AdaptiveLoss(FairseqCriterion): """This is an implementation of the loss function accompanying the adaptive softmax approximation for graphical processing units (GPU), described in the paper "Efficient softmax approximation for GPUs" (http://arxiv.org/abs/1609.04309).""" def __init__(self, args, task): super().__init__(args, task) if args.ddp_backend == 'c10d': raise Exception( 'AdaptiveLoss is not compatible with the c10d ' 'version of DistributedDataParallel. Please use ' '`--ddp-backend=no_c10d` instead.' ) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ assert hasattr(model.decoder, 'adaptive_softmax') and model.decoder.adaptive_softmax is not None adaptive_softmax = model.decoder.adaptive_softmax net_output = model(**sample['net_input']) orig_target = model.get_targets(sample, net_output) nsentences = orig_target.size(0) orig_target = orig_target.view(-1) bsz = orig_target.size(0) logits, target = adaptive_softmax(net_output[0], orig_target) assert len(target) == len(logits) loss = net_output[0].new(1 if reduce else bsz).zero_() for i in range(len(target)): if target[i] is not None: assert (target[i].min() >= 0 and target[i].max() <= logits[i].size(1)) loss += F.cross_entropy(logits[i], target[i], size_average=False, ignore_index=self.padding_idx, reduce=reduce) orig = utils.strip_pad(orig_target, self.padding_idx) ntokens = orig.numel() sample_size = sample['target'].size(0) if self.args.sentence_avg else ntokens logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) agg_output = { 'loss': loss_sum / sample_size / math.log(2), 'nll_loss': loss_sum / sample_size / math.log(2), 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } if sample_size != ntokens: agg_output['nll_loss'] = loss_sum / ntokens / math.log(2) return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/criterions/cross_entropy.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch.nn.functional as F from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('cross_entropy') class CrossEntropyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ net_output = model(**sample['net_input']) lprobs = model.get_normalized_probs(net_output, log_probs=True) lprobs = lprobs.view(-1, lprobs.size(-1)) target = model.get_targets(sample, net_output).view(-1) loss = F.nll_loss(lprobs, target, size_average=False, ignore_index=self.padding_idx, reduce=reduce) sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens'] logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'ntokens': sample['ntokens'], 'nsentences': sample['target'].size(0), 'sample_size': sample_size, } return loss, sample_size, logging_output @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" loss_sum = sum(log.get('loss', 0) for log in logging_outputs) ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) agg_output = { 'loss': loss_sum / sample_size / math.log(2), 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, } if sample_size != ntokens: agg_output['nll_loss'] = loss_sum / ntokens / math.log(2) return agg_output
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/criterions/fairseq_criterion.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from torch.nn.modules.loss import _Loss class FairseqCriterion(_Loss): def __init__(self, args, task): super().__init__() self.args = args self.padding_idx = task.target_dictionary.pad() @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" pass def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ raise NotImplementedError @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" raise NotImplementedError @staticmethod def grad_denom(sample_sizes): """Compute the gradient denominator for a set of sample sizes.""" return sum(sample_sizes)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/criterions/label_smoothed_cross_entropy.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math from fairseq import utils from . import FairseqCriterion, register_criterion @register_criterion('label_smoothed_cross_entropy') class LabelSmoothedCrossEntropyCriterion(FairseqCriterion): def __init__(self, args, task): super().__init__(args, task) self.eps = args.label_smoothing @staticmethod def add_args(parser): """Add criterion-specific arguments to the parser.""" parser.add_argument('--label-smoothing', default=0., type=float, metavar='D', help='epsilon for label smoothing, 0 means no label smoothing') def forward(self, model, sample, reduce=True): """Compute the loss for the given sample. Returns a tuple with three elements: 1) the loss 2) the sample size, which is used as the denominator for the gradient 3) logging outputs to display while training """ net_output = model(**sample['net_input']) loss, nll_loss = self.compute_loss(model, net_output, sample, reduce=reduce) sample_size = sample['target'].size(0) if self.args.sentence_avg else sample['ntokens'] logging_output = { 'loss': utils.item(loss.data) if reduce else loss.data, 'nll_loss': utils.item(nll_loss.data) if reduce else nll_loss.data, 'ntokens': sample['ntokens'], 'nsentences': sample['target'].size(0), 'sample_size': sample_size, } return loss, sample_size, logging_output def compute_loss(self, model, net_output, sample, reduce=True): lprobs = model.get_normalized_probs(net_output, log_probs=True) lprobs = lprobs.view(-1, lprobs.size(-1)) target = model.get_targets(sample, net_output).view(-1, 1) non_pad_mask = target.ne(self.padding_idx) nll_loss = -lprobs.gather(dim=-1, index=target)[non_pad_mask] smooth_loss = -lprobs.sum(dim=-1, keepdim=True)[non_pad_mask] if reduce: nll_loss = nll_loss.sum() smooth_loss = smooth_loss.sum() eps_i = self.eps / lprobs.size(-1) loss = (1. - self.eps) * nll_loss + eps_i * smooth_loss return loss, nll_loss @staticmethod def aggregate_logging_outputs(logging_outputs): """Aggregate logging outputs from data parallel training.""" ntokens = sum(log.get('ntokens', 0) for log in logging_outputs) nsentences = sum(log.get('nsentences', 0) for log in logging_outputs) sample_size = sum(log.get('sample_size', 0) for log in logging_outputs) return { 'loss': sum(log.get('loss', 0) for log in logging_outputs) / sample_size / math.log(2), 'nll_loss': sum(log.get('nll_loss', 0) for log in logging_outputs) / ntokens / math.log(2), 'ntokens': ntokens, 'nsentences': nsentences, 'sample_size': sample_size, }
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .dictionary import Dictionary, TruncatedDictionary from .fairseq_dataset import FairseqDataset from .indexed_dataset import IndexedDataset, IndexedInMemoryDataset, IndexedRawTextDataset from .language_pair_dataset import LanguagePairDataset from .monolingual_dataset import MonolingualDataset from .token_block_dataset import TokenBlockDataset from .iterators import ( CountingIterator, EpochBatchIterator, GroupedIterator, ShardedIterator, ) __all__ = [ 'CountingIterator', 'Dictionary', 'EpochBatchIterator', 'FairseqDataset', 'GroupedIterator', 'IndexedDataset', 'IndexedInMemoryDataset', 'IndexedRawTextDataset', 'LanguagePairDataset', 'MonolingualDataset', 'ShardedIterator', 'TokenBlockDataset', ]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/backtranslation_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from fairseq import sequence_generator from . import FairseqDataset, language_pair_dataset class BacktranslationDataset(FairseqDataset): def __init__(self, args, tgt_dataset, tgt_dict, backtranslation_model): """ Sets up a backtranslation dataset which takes a tgt batch, generates a src using a tgt-src backtranslation_model, and returns the corresponding {generated src, input tgt} batch Args: args: generation args for the backtranslation SequenceGenerator' Note that there is no equivalent argparse code for these args anywhere in our top level train scripts yet. Integration is still in progress. You can still, however, test out this dataset functionality with the appropriate args as in the corresponding unittest: test_backtranslation_dataset. tgt_dataset: dataset which will be used to build self.tgt_dataset -- a LanguagePairDataset with tgt dataset as the source dataset and None as the target dataset. We use language_pair_dataset here to encapsulate the tgt_dataset so we can re-use the LanguagePairDataset collater to format the batches in the structure that SequenceGenerator expects. tgt_dict: tgt dictionary (typically a joint src/tgt BPE dictionary) backtranslation_model: tgt-src model to use in the SequenceGenerator to generate backtranslations from tgt batches """ self.tgt_dataset = language_pair_dataset.LanguagePairDataset( src=tgt_dataset, src_sizes=None, src_dict=tgt_dict, tgt=None, tgt_sizes=None, tgt_dict=None, ) self.backtranslation_generator = sequence_generator.SequenceGenerator( [backtranslation_model], tgt_dict, unk_penalty=args.backtranslation_unkpen, sampling=args.backtranslation_sampling, beam_size=args.backtranslation_beam, ) self.backtranslation_max_len_a = args.backtranslation_max_len_a self.backtranslation_max_len_b = args.backtranslation_max_len_b self.backtranslation_beam = args.backtranslation_beam def __getitem__(self, index): """ Returns a single sample. Multiple samples are fed to the collater to create a backtranslation batch. Note you should always use collate_fn BacktranslationDataset.collater() below if given the option to specify which collate_fn to use (e.g. in a dataloader which uses this BacktranslationDataset -- see corresponding unittest for an example). """ return self.tgt_dataset[index] def __len__(self): """ The length of the backtranslation dataset is the length of tgt. """ return len(self.tgt_dataset) def collater(self, samples): """ Using the samples from the tgt dataset, load a collated tgt sample to feed to the backtranslation model. Then take the generated translation with best score as the source and the orignal net input as the target. """ collated_tgt_only_sample = self.tgt_dataset.collater(samples) backtranslation_hypos = self._generate_hypotheses(collated_tgt_only_sample) # Go through each tgt sentence in batch and its corresponding best # generated hypothesis and create a backtranslation data pair # {id: id, source: generated backtranslation, target: original tgt} generated_samples = [] for input_sample, hypos in zip(samples, backtranslation_hypos): generated_samples.append( { "id": input_sample["id"], "source": hypos[0]["tokens"], # first hypo is best hypo "target": input_sample["source"], } ) return language_pair_dataset.collate( samples=generated_samples, pad_idx=self.tgt_dataset.src_dict.pad(), eos_idx=self.tgt_dataset.src_dict.eos(), ) def get_dummy_batch(self, num_tokens, max_positions): """ Just use the tgt dataset get_dummy_batch """ self.tgt_dataset.get_dummy_batch(num_tokens, max_positions) def num_tokens(self, index): """ Just use the tgt dataset num_tokens """ self.tgt_dataset.num_tokens(index) def ordered_indices(self): """ Just use the tgt dataset ordered_indices """ self.tgt_dataset.ordered_indices def valid_size(self, index, max_positions): """ Just use the tgt dataset size """ self.tgt_dataset.valid_size(index, max_positions) def _generate_hypotheses(self, sample): """ Generates hypotheses from a LanguagePairDataset collated / batched sample. Note in this case, sample["target"] is None, and sample["net_input"]["src_tokens"] is really in tgt language. """ self.backtranslation_generator.cuda() input = sample["net_input"] srclen = input["src_tokens"].size(1) hypos = self.backtranslation_generator.generate( input, maxlen=int( self.backtranslation_max_len_a * srclen + self.backtranslation_max_len_b ), ) return hypos
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/data_utils.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import contextlib import os import numpy as np def infer_language_pair(path): """Infer language pair from filename: <split>.<lang1>-<lang2>.(...).idx""" src, dst = None, None for filename in os.listdir(path): parts = filename.split('.') if len(parts) >= 3 and len(parts[1].split('-')) == 2: return parts[1].split('-') return src, dst def collate_tokens(values, pad_idx, eos_idx, left_pad, move_eos_to_beginning=False): """Convert a list of 1d tensors into a padded 2d tensor.""" size = max(v.size(0) for v in values) res = values[0].new(len(values), size).fill_(pad_idx) def copy_tensor(src, dst): assert dst.numel() == src.numel() if move_eos_to_beginning: assert src[-1] == eos_idx dst[0] = eos_idx dst[1:] = src[:-1] else: dst.copy_(src) for i, v in enumerate(values): copy_tensor(v, res[i][size - len(v):] if left_pad else res[i][:len(v)]) return res @contextlib.contextmanager def numpy_seed(seed): """Context manager which seeds the NumPy PRNG with the specified seed and restores the state afterward""" if seed is None: yield return state = np.random.get_state() np.random.seed(seed) try: yield finally: np.random.set_state(state) def collect_filtered(function, iterable, filtered): """ Similar to :func:`filter` but collects filtered elements in ``filtered``. Args: function (callable): function that returns ``False`` for elements that should be filtered iterable (iterable): iterable to filter filtered (list): list to store filtered elements """ for el in iterable: if function(el): yield el else: filtered.append(el) def filter_by_size(indices, size_fn, max_positions, raise_exception=False): """ Filter indices based on their size. Args: indices (List[int]): ordered list of dataset indices size_fn (callable): function that returns the size of a given index max_positions (tuple): filter elements larger than this size. Comparisons are done component-wise. raise_exception (bool, optional): if ``True``, raise an exception if any elements are filtered. Default: ``False`` """ def check_size(idx): if isinstance(max_positions, float) or isinstance(max_positions, int): return size_fn(idx) <= max_positions else: return all(a is None or b is None or a <= b for a, b in zip(size_fn(idx), max_positions)) ignored = [] itr = collect_filtered(check_size, indices, ignored) for idx in itr: if len(ignored) > 0 and raise_exception: raise Exception(( 'Size of sample #{} is invalid (={}) since max_positions={}, ' 'skip this example with --skip-invalid-size-inputs-valid-test' ).format(idx, size_fn(idx), max_positions)) yield idx if len(ignored) > 0: print(( '| WARNING: {} samples have invalid sizes and will be skipped, ' 'max_positions={}, first few sample ids={}' ).format(len(ignored), max_positions, ignored[:10])) def batch_by_size( indices, num_tokens_fn, max_tokens=None, max_sentences=None, required_batch_size_multiple=1, ): """ Yield mini-batches of indices bucketed by size. Batches may contain sequences of different lengths. Args: indices (List[int]): ordered list of dataset indices num_tokens_fn (callable): function that returns the number of tokens at a given index max_tokens (int, optional): max number of tokens in each batch. Default: ``None`` max_sentences (int, optional): max number of sentences in each batch. Default: ``None`` required_batch_size_multiple (int, optional): require batch size to be a multiple of N. Default: ``1`` """ max_tokens = max_tokens if max_tokens is not None else float('Inf') max_sentences = max_sentences if max_sentences is not None else float('Inf') bsz_mult = required_batch_size_multiple batch = [] def is_batch_full(num_tokens): if len(batch) == 0: return False if len(batch) == max_sentences: return True if num_tokens > max_tokens: return True return False sample_len = 0 sample_lens = [] ignored = [] for idx in indices: sample_lens.append(num_tokens_fn(idx)) sample_len = max(sample_len, sample_lens[-1]) num_tokens = (len(batch) + 1) * sample_len if is_batch_full(num_tokens): mod_len = max( bsz_mult * (len(batch) // bsz_mult), len(batch) % bsz_mult, ) yield batch[:mod_len] batch = batch[mod_len:] sample_lens = sample_lens[mod_len:] sample_len = max(sample_lens) if len(sample_lens) > 0 else 0 batch.append(idx) if len(batch) > 0: yield batch
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/dictionary.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from collections import Counter import os import torch class Dictionary(object): """A mapping from symbols to consecutive integers""" def __init__(self, pad='<pad>', eos='</s>', unk='<unk>'): self.unk_word, self.pad_word, self.eos_word = unk, pad, eos self.symbols = [] self.count = [] self.indices = {} # dictionary indexing starts at 1 for consistency with Lua self.add_symbol('<Lua heritage>') self.pad_index = self.add_symbol(pad) self.eos_index = self.add_symbol(eos) self.unk_index = self.add_symbol(unk) self.nspecial = len(self.symbols) def __eq__(self, other): return self.indices == other.indices def __getitem__(self, idx): if idx < len(self.symbols): return self.symbols[idx] return self.unk_word def __len__(self): """Returns the number of symbols in the dictionary""" return len(self.symbols) def index(self, sym): """Returns the index of the specified symbol""" if sym in self.indices: return self.indices[sym] return self.unk_index def string(self, tensor, bpe_symbol=None, escape_unk=False): """Helper for converting a tensor of token indices to a string. Can optionally remove BPE symbols or escape <unk> words. """ if torch.is_tensor(tensor) and tensor.dim() == 2: return '\n'.join(self.string(t) for t in tensor) def token_string(i): if i == self.unk(): return self.unk_string(escape_unk) else: return self[i] sent = ' '.join(token_string(i) for i in tensor if i != self.eos()) if bpe_symbol is not None: sent = (sent + ' ').replace(bpe_symbol, '').rstrip() return sent def unk_string(self, escape=False): """Return unknown string, optionally escaped as: <<unk>>""" if escape: return '<{}>'.format(self.unk_word) else: return self.unk_word def add_symbol(self, word, n=1): """Adds a word to the dictionary""" if word in self.indices: idx = self.indices[word] self.count[idx] = self.count[idx] + n return idx else: idx = len(self.symbols) self.indices[word] = idx self.symbols.append(word) self.count.append(n) return idx def update(self, new_dict): """Updates counts from new dictionary.""" for word in new_dict.symbols: idx2 = new_dict.indices[word] if word in self.indices: idx = self.indices[word] self.count[idx] = self.count[idx] + new_dict.count[idx2] else: idx = len(self.symbols) self.indices[word] = idx self.symbols.append(word) self.count.append(new_dict.count[idx2]) def finalize(self, threshold=-1, nwords=-1, padding_factor=8): """Sort symbols by frequency in descending order, ignoring special ones. Args: - threshold defines the minimum word count - nwords defines the total number of words in the final dictionary, including special symbols - padding_factor can be used to pad the dictionary size to be a multiple of 8, which is important on some hardware (e.g., Nvidia Tensor Cores). """ if nwords <= 0: nwords = len(self) new_indices = dict(zip(self.symbols[:self.nspecial], range(self.nspecial))) new_symbols = self.symbols[:self.nspecial] new_count = self.count[:self.nspecial] c = Counter(dict(zip(self.symbols[self.nspecial:], self.count[self.nspecial:]))) for symbol, count in c.most_common(nwords - self.nspecial): if count >= threshold: new_indices[symbol] = len(new_symbols) new_symbols.append(symbol) new_count.append(count) else: break threshold_nwords = len(new_symbols) if padding_factor > 1: i = 0 while threshold_nwords % padding_factor != 0: symbol = 'madeupword{:04d}'.format(i) new_indices[symbol] = len(new_symbols) new_symbols.append(symbol) new_count.append(0) i += 1 threshold_nwords += 1 assert len(new_symbols) % padding_factor == 0 assert len(new_symbols) == len(new_indices) self.count = list(new_count) self.symbols = list(new_symbols) self.indices = new_indices def pad(self): """Helper to get index of pad symbol""" return self.pad_index def eos(self): """Helper to get index of end-of-sentence symbol""" return self.eos_index def unk(self): """Helper to get index of unk symbol""" return self.unk_index @classmethod def load(cls, f, ignore_utf_errors=False): """Loads the dictionary from a text file with the format: ``` <symbol0> <count0> <symbol1> <count1> ... ``` """ if isinstance(f, str): try: if not ignore_utf_errors: with open(f, 'r', encoding='utf-8') as fd: return cls.load(fd) else: with open(f, 'r', encoding='utf-8', errors='ignore') as fd: return cls.load(fd) except FileNotFoundError as fnfe: raise fnfe except Exception: raise Exception("Incorrect encoding detected in {}, please " "rebuild the dataset".format(f)) d = cls() for line in f.readlines(): idx = line.rfind(' ') word = line[:idx] count = int(line[idx+1:]) d.indices[word] = len(d.symbols) d.symbols.append(word) d.count.append(count) return d def save(self, f): """Stores dictionary into a text file""" if isinstance(f, str): os.makedirs(os.path.dirname(f), exist_ok=True) with open(f, 'w', encoding='utf-8') as fd: return self.save(fd) for symbol, count in zip(self.symbols[self.nspecial:], self.count[self.nspecial:]): print('{} {}'.format(symbol, count), file=f) def dummy_sentence(self, length): t = torch.Tensor(length).uniform_(self.nspecial + 1, len(self)).long() t[-1] = self.eos() return t class TruncatedDictionary(object): def __init__(self, wrapped_dict, length): self.__class__ = type(wrapped_dict.__class__.__name__, (self.__class__, wrapped_dict.__class__), {}) self.__dict__ = wrapped_dict.__dict__ self.wrapped_dict = wrapped_dict self.length = min(len(self.wrapped_dict), length) def __len__(self): return self.length def __getitem__(self, i): if i < self.length: return self.wrapped_dict[i] return self.wrapped_dict.unk()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/fairseq_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.utils.data from fairseq.data import data_utils class FairseqDataset(torch.utils.data.Dataset): """A dataset that provides helpers for batching.""" def __getitem__(self, index): raise NotImplementedError def __len__(self): raise NotImplementedError def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[int]): sample indices to collate Returns: dict: a mini-batch suitable for forwarding with a Model """ raise NotImplementedError def get_dummy_batch(self, num_tokens, max_positions): """Return a dummy batch with a given number of tokens.""" raise NotImplementedError def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" raise NotImplementedError def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" raise NotImplementedError def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" raise NotImplementedError
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/indexed_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import os import struct import numpy as np import torch from fairseq.tokenizer import Tokenizer def read_longs(f, n): a = np.empty(n, dtype=np.int64) f.readinto(a) return a def write_longs(f, a): f.write(np.array(a, dtype=np.int64)) dtypes = { 1: np.uint8, 2: np.int8, 3: np.int16, 4: np.int32, 5: np.int64, 6: np.float, 7: np.double, } def code(dtype): for k in dtypes.keys(): if dtypes[k] == dtype: return k def index_file_path(prefix_path): return prefix_path + '.idx' def data_file_path(prefix_path): return prefix_path + '.bin' class IndexedDataset(torch.utils.data.Dataset): """Loader for TorchNet IndexedDataset""" def __init__(self, path, fix_lua_indexing=False, read_data=True): super().__init__() self.fix_lua_indexing = fix_lua_indexing self.read_index(path) self.data_file = None if read_data: self.read_data(path) def read_index(self, path): with open(index_file_path(path), 'rb') as f: magic = f.read(8) assert magic == b'TNTIDX\x00\x00' version = f.read(8) assert struct.unpack('<Q', version) == (1,) code, self.element_size = struct.unpack('<QQ', f.read(16)) self.dtype = dtypes[code] self.size, self.s = struct.unpack('<QQ', f.read(16)) self.dim_offsets = read_longs(f, self.size + 1) self.data_offsets = read_longs(f, self.size + 1) self.sizes = read_longs(f, self.s) def read_data(self, path): self.data_file = open(data_file_path(path), 'rb', buffering=0) def check_index(self, i): if i < 0 or i >= self.size: raise IndexError('index out of range') def __del__(self): if self.data_file: self.data_file.close() def __getitem__(self, i): self.check_index(i) tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]] a = np.empty(tensor_size, dtype=self.dtype) self.data_file.seek(self.data_offsets[i] * self.element_size) self.data_file.readinto(a) item = torch.from_numpy(a).long() if self.fix_lua_indexing: item -= 1 # subtract 1 for 0-based indexing return item def __len__(self): return self.size @staticmethod def exists(path): return ( os.path.exists(index_file_path(path)) and os.path.exists(data_file_path(path)) ) class IndexedInMemoryDataset(IndexedDataset): """Loader for TorchNet IndexedDataset, keeps all the data in memory""" def read_data(self, path): self.data_file = open(data_file_path(path), 'rb') self.buffer = np.empty(self.data_offsets[-1], dtype=self.dtype) self.data_file.readinto(self.buffer) self.data_file.close() if self.fix_lua_indexing: self.buffer -= 1 # subtract 1 for 0-based indexing def __del__(self): pass def __getitem__(self, i): self.check_index(i) tensor_size = self.sizes[self.dim_offsets[i]:self.dim_offsets[i + 1]] a = np.empty(tensor_size, dtype=self.dtype) np.copyto(a, self.buffer[self.data_offsets[i]:self.data_offsets[i + 1]]) return torch.from_numpy(a).long() class IndexedRawTextDataset(IndexedDataset): """Takes a text file as input and binarizes it in memory at instantiation. Original lines are also kept in memory""" def __init__(self, path, dictionary, append_eos=True, reverse_order=False): self.tokens_list = [] self.lines = [] self.sizes = [] self.append_eos = append_eos self.reverse_order = reverse_order self.read_data(path, dictionary) self.size = len(self.tokens_list) def read_data(self, path, dictionary): with open(path, 'r') as f: for line in f: self.lines.append(line.strip('\n')) tokens = Tokenizer.tokenize( line, dictionary, add_if_not_exist=False, append_eos=self.append_eos, reverse_order=self.reverse_order, ).long() self.tokens_list.append(tokens) self.sizes.append(len(tokens)) self.sizes = np.array(self.sizes) def __getitem__(self, i): self.check_index(i) return self.tokens_list[i] def get_original_text(self, i): self.check_index(i) return self.lines[i] def __del__(self): pass def __len__(self): return self.size @staticmethod def exists(path): return os.path.exists(path) class IndexedDatasetBuilder(object): element_sizes = { np.uint8: 1, np.int8: 1, np.int16: 2, np.int32: 4, np.int64: 8, np.float: 4, np.double: 8 } def __init__(self, out_file, dtype=np.int32): self.out_file = open(out_file, 'wb') self.dtype = dtype self.data_offsets = [0] self.dim_offsets = [0] self.sizes = [] self.element_size = self.element_sizes[self.dtype] def add_item(self, tensor): # +1 for Lua compatibility bytes = self.out_file.write(np.array(tensor.numpy() + 1, dtype=self.dtype)) self.data_offsets.append(self.data_offsets[-1] + bytes / self.element_size) for s in tensor.size(): self.sizes.append(s) self.dim_offsets.append(self.dim_offsets[-1] + len(tensor.size())) def merge_file_(self, another_file): index = IndexedDataset(another_file, read_data=False) assert index.dtype == self.dtype begin = self.data_offsets[-1] for offset in index.data_offsets[1:]: self.data_offsets.append(begin + offset) self.sizes.extend(index.sizes) begin = self.dim_offsets[-1] for dim_offset in index.dim_offsets[1:]: self.dim_offsets.append(begin + dim_offset) with open(data_file_path(another_file), 'rb') as f: while True: data = f.read(1024) if data: self.out_file.write(data) else: break def finalize(self, index_file): self.out_file.close() index = open(index_file, 'wb') index.write(b'TNTIDX\x00\x00') index.write(struct.pack('<Q', 1)) index.write(struct.pack('<QQ', code(self.dtype), self.element_size)) index.write(struct.pack('<QQ', len(self.data_offsets) - 1, len(self.sizes))) write_longs(index, self.dim_offsets) write_longs(index, self.data_offsets) write_longs(index, self.sizes) index.close()
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/iterators.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import itertools import math import numpy as np import torch from . import data_utils class CountingIterator(object): """Wrapper around an iterable that maintains the iteration count. Args: iterable (iterable): iterable to wrap Attributes: count (int): number of elements consumed from this iterator """ def __init__(self, iterable): self.iterable = iterable self.count = 0 self.itr = iter(self) def __len__(self): return len(self.iterable) def __iter__(self): for x in self.iterable: self.count += 1 yield x def __next__(self): return next(self.itr) def has_next(self): """Whether the iterator has been exhausted.""" return self.count < len(self) def skip(self, num_to_skip): """Fast-forward the iterator by skipping *num_to_skip* elements.""" next(itertools.islice(self.itr, num_to_skip, num_to_skip), None) return self class EpochBatchIterator(object): """A multi-epoch iterator over a :class:`torch.utils.data.Dataset`. Compared to :class:`torch.utils.data.DataLoader`, this iterator: - can be reused across multiple epochs with the :func:`next_epoch_itr` method (optionally shuffled between epochs) - can be serialized/deserialized with the :func:`state_dict` and :func:`load_state_dict` methods - supports sharding with the *num_shards* and *shard_id* arguments Args: dataset (~torch.utils.data.Dataset): dataset from which to load the data collate_fn (callable): merges a list of samples to form a mini-batch batch_sampler (~torch.utils.data.Sampler): an iterator over batches of indices seed (int, optional): seed for random number generator for reproducibility. Default: ``1`` num_shards (int, optional): shard the data iterator into N shards. Default: ``1`` shard_id (int, optional): which shard of the data iterator to return. Default: ``0`` """ def __init__(self, dataset, collate_fn, batch_sampler, seed=1, num_shards=1, shard_id=0): assert isinstance(dataset, torch.utils.data.Dataset) self.dataset = dataset self.collate_fn = collate_fn self.frozen_batches = tuple(batch_sampler) self.seed = seed self.num_shards = num_shards self.shard_id = shard_id self.epoch = 0 self._cur_epoch_itr = None self._next_epoch_itr = None def __len__(self): return len(self.frozen_batches) def next_epoch_itr(self, shuffle=True): """Return a new iterator over the dataset. Args: shuffle (bool, optional): shuffle batches before returning the iterator. Default: ``True`` """ if self._next_epoch_itr is not None: self._cur_epoch_itr = self._next_epoch_itr self._next_epoch_itr = None else: self.epoch += 1 self._cur_epoch_itr = self._get_iterator_for_epoch(self.epoch, shuffle) return self._cur_epoch_itr def end_of_epoch(self): """Returns whether the most recent epoch iterator has been exhausted""" return not self._cur_epoch_itr.has_next() @property def iterations_in_epoch(self): """The number of consumed batches in the current epoch.""" if self._cur_epoch_itr is not None: return self._cur_epoch_itr.count elif self._next_epoch_itr is not None: return self._next_epoch_itr.count return 0 def state_dict(self): """Returns a dictionary containing a whole state of the iterator.""" return { 'epoch': self.epoch, 'iterations_in_epoch': self.iterations_in_epoch, } def load_state_dict(self, state_dict): """Copies the state of the iterator from the given *state_dict*.""" self.epoch = state_dict['epoch'] itr_pos = state_dict.get('iterations_in_epoch', 0) if itr_pos > 0: # fast-forward epoch iterator itr = self._get_iterator_for_epoch(self.epoch, state_dict.get('shuffle', True)) if itr_pos < len(itr): self._next_epoch_itr = itr.skip(itr_pos) def _get_iterator_for_epoch(self, epoch, shuffle): if shuffle: # set seed based on the seed and epoch number so that we get # reproducible results when resuming from checkpoints with data_utils.numpy_seed(self.seed + epoch): batches = list(self.frozen_batches) # copy np.random.shuffle(batches) else: batches = self.frozen_batches return CountingIterator(torch.utils.data.DataLoader( self.dataset, collate_fn=self.collate_fn, batch_sampler=ShardedIterator(batches, self.num_shards, self.shard_id, fill_value=[]), )) class GroupedIterator(object): """Wrapper around an iterable that returns groups (chunks) of items. Args: iterable (iterable): iterable to wrap chunk_size (int): size of each chunk """ def __init__(self, iterable, chunk_size): self._len = int(math.ceil(len(iterable) / float(chunk_size))) self.itr = iter(iterable) self.chunk_size = chunk_size def __len__(self): return self._len def __iter__(self): return self def __next__(self): chunk = [] try: for _ in range(self.chunk_size): chunk.append(next(self.itr)) except StopIteration as e: if len(chunk) == 0: raise e return chunk class ShardedIterator(object): """A sharded wrapper around an iterable, padded to length. Args: iterable (iterable): iterable to wrap num_shards (int): number of shards to split the iterable into shard_id (int): which shard to iterator over fill_value (Any, optional): padding value when the iterable doesn't evenly divide *num_shards*. Default: ``None`` """ def __init__(self, iterable, num_shards, shard_id, fill_value=None): if shard_id < 0 or shard_id >= num_shards: raise ValueError('shard_id must be between 0 and num_shards') self._sharded_len = len(iterable) // num_shards if len(iterable) % num_shards > 0: self._sharded_len += 1 self.itr = itertools.zip_longest( range(self._sharded_len), itertools.islice(iterable, shard_id, len(iterable), num_shards), fillvalue=fill_value, ) def __len__(self): return self._sharded_len def __iter__(self): return self def __next__(self): return next(self.itr)[1]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/language_pair_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch from fairseq import utils from . import data_utils, FairseqDataset def collate( samples, pad_idx, eos_idx, left_pad_source=True, left_pad_target=False, input_feeding=True, ): if len(samples) == 0: return {} def merge(key, left_pad, move_eos_to_beginning=False): return data_utils.collate_tokens( [s[key] for s in samples], pad_idx, eos_idx, left_pad, move_eos_to_beginning, ) id = torch.LongTensor([s['id'] for s in samples]) src_tokens = merge('source', left_pad=left_pad_source) # sort by descending source length src_lengths = torch.LongTensor([s['source'].numel() for s in samples]) src_lengths, sort_order = src_lengths.sort(descending=True) id = id.index_select(0, sort_order) src_tokens = src_tokens.index_select(0, sort_order) prev_output_tokens = None target = None if samples[0].get('target', None) is not None: target = merge('target', left_pad=left_pad_target) target = target.index_select(0, sort_order) ntokens = sum(len(s['target']) for s in samples) if input_feeding: # we create a shifted version of targets for feeding the # previous output token(s) into the next decoder step prev_output_tokens = merge( 'target', left_pad=left_pad_target, move_eos_to_beginning=True, ) prev_output_tokens = prev_output_tokens.index_select(0, sort_order) else: ntokens = sum(len(s['source']) for s in samples) batch = { 'id': id, 'ntokens': ntokens, 'net_input': { 'src_tokens': src_tokens, 'src_lengths': src_lengths, }, 'target': target, 'nsentences': samples[0]['source'].size(0), } if prev_output_tokens is not None: batch['net_input']['prev_output_tokens'] = prev_output_tokens return batch class LanguagePairDataset(FairseqDataset): """ A pair of torch.utils.data.Datasets. Args: src (torch.utils.data.Dataset): source dataset to wrap src_sizes (List[int]): source sentence lengths src_dict (~fairseq.data.Dictionary): source vocabulary tgt (torch.utils.data.Dataset, optional): target dataset to wrap tgt_sizes (List[int], optional): target sentence lengths tgt_dict (~fairseq.data.Dictionary, optional): target vocabulary left_pad_source (bool, optional): pad source tensors on the left side. Default: ``True`` left_pad_target (bool, optional): pad target tensors on the left side. Default: ``False`` max_source_positions (int, optional): max number of tokens in the source sentence. Default: ``1024`` max_target_positions (int, optional): max number of tokens in the target sentence. Default: ``1024`` shuffle (bool, optional): shuffle dataset elements before batching. Default: ``True`` input_feeding (bool, optional): create a shifted version of the targets to be passed into the model for input feeding/teacher forcing. Default: ``True`` """ def __init__( self, src, src_sizes, src_dict, tgt=None, tgt_sizes=None, tgt_dict=None, left_pad_source=True, left_pad_target=False, max_source_positions=1024, max_target_positions=1024, shuffle=True, input_feeding=True, ): if tgt_dict is not None: assert src_dict.pad() == tgt_dict.pad() assert src_dict.eos() == tgt_dict.eos() assert src_dict.unk() == tgt_dict.unk() self.src = src self.tgt = tgt self.src_sizes = np.array(src_sizes) self.tgt_sizes = np.array(tgt_sizes) if tgt_sizes is not None else None self.src_dict = src_dict self.tgt_dict = tgt_dict self.left_pad_source = left_pad_source self.left_pad_target = left_pad_target self.max_source_positions = max_source_positions self.max_target_positions = max_target_positions self.shuffle = shuffle self.input_feeding = input_feeding def __getitem__(self, index): return { 'id': index, 'source': self.src[index], 'target': self.tgt[index] if self.tgt is not None else None, } def __len__(self): return len(self.src) def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in the source sentence of shape `(bsz, src_len)`. Padding will appear on the left if *left_pad_source* is ``True``. - `src_lengths` (LongTensor): 1D Tensor of the unpadded lengths of each source sentence of shape `(bsz)` - `prev_output_tokens` (LongTensor): a padded 2D Tensor of tokens in the target sentence, shifted right by one position for input feeding/teacher forcing, of shape `(bsz, tgt_len)`. This key will not be present if *input_feeding* is ``False``. Padding will appear on the left if *left_pad_target* is ``True``. - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the left if *left_pad_target* is ``True``. """ return collate( samples, pad_idx=self.src_dict.pad(), eos_idx=self.src_dict.eos(), left_pad_source=self.left_pad_source, left_pad_target=self.left_pad_target, input_feeding=self.input_feeding, ) def get_dummy_batch(self, num_tokens, max_positions, src_len=128, tgt_len=128): """Return a dummy batch with a given number of tokens.""" src_len, tgt_len = utils.resolve_max_positions( (src_len, tgt_len), max_positions, (self.max_source_positions, self.max_target_positions), ) bsz = num_tokens // max(src_len, tgt_len) return self.collater([ { 'id': i, 'source': self.src_dict.dummy_sentence(src_len), 'target': self.tgt_dict.dummy_sentence(tgt_len) if self.tgt_dict is not None else None, } for i in range(bsz) ]) def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return max(self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0) def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return (self.src_sizes[index], self.tgt_sizes[index] if self.tgt_sizes is not None else 0) def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" if self.shuffle: indices = np.random.permutation(len(self)) else: indices = np.arange(len(self)) if self.tgt_sizes is not None: indices = indices[np.argsort(self.tgt_sizes[indices], kind='mergesort')] return indices[np.argsort(self.src_sizes[indices], kind='mergesort')]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/monolingual_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch from . import data_utils, FairseqDataset from typing import List def collate(samples, pad_idx, eos_idx): if len(samples) == 0: return {} def merge(key, is_list=False): if is_list: res = [] for i in range(len(samples[0][key])): res.append(data_utils.collate_tokens( [s[key][i] for s in samples], pad_idx, eos_idx, left_pad=False, )) return res else: return data_utils.collate_tokens( [s[key] for s in samples], pad_idx, eos_idx, left_pad=False, ) is_target_list = isinstance(samples[0]['target'], list) return { 'id': torch.LongTensor([s['id'] for s in samples]), 'ntokens': sum(len(s['source']) for s in samples), 'net_input': { 'src_tokens': merge('source'), 'src_lengths': torch.LongTensor([ s['source'].numel() for s in samples ]), }, 'target': merge('target', is_target_list), 'nsentences': samples[0]['source'].size(0), } class MonolingualDataset(FairseqDataset): """ A wrapper around torch.utils.data.Dataset for monolingual data. Args: dataset (torch.utils.data.Dataset): dataset to wrap sizes (List[int]): sentence lengths vocab (~fairseq.data.Dictionary): vocabulary shuffle (bool, optional): shuffle the elements before batching. Default: ``True`` """ def __init__(self, dataset, sizes, src_vocab, tgt_vocab, add_eos_for_other_targets, shuffle, targets=None): self.dataset = dataset self.sizes = np.array(sizes) self.vocab = src_vocab self.tgt_vocab = tgt_vocab self.add_eos_for_other_targets = add_eos_for_other_targets self.shuffle = shuffle assert targets is None or all( t in {'self', 'future', 'past'} for t in targets), "targets must be none or one of 'self', 'future', 'past'" if targets is not None and len(targets) == 0: targets = None self.targets = targets def __getitem__(self, index): source, future_target, past_target = self.dataset[index] source, target = self._make_source_target(source, future_target, past_target) return {'id': index, 'source': source, 'target': target} def __len__(self): return len(self.dataset) def _make_source_target(self, source, future_target, past_target): if self.targets is not None: target = [] if self.add_eos_for_other_targets and (('self' in self.targets) or ('past' in self.targets)) \ and source[-1] != self.vocab.eos(): # append eos at the end of source source = torch.cat([source, source.new([self.vocab.eos()])]) if 'future' in self.targets: future_target = torch.cat([future_target, future_target.new([self.vocab.pad()])]) if 'past' in self.targets: # first token is before the start of sentence which is only used in "none" break mode when # add_eos_for_other_targets is False past_target = torch.cat([past_target.new([self.vocab.pad()]), past_target[1:], source[-2, None]]) for t in self.targets: if t == 'self': target.append(source) elif t == 'future': target.append(future_target) elif t == 'past': target.append(past_target) else: raise Exception('invalid target ' + t) if len(target) == 1: target = target[0] else: target = future_target return source, self._filter_vocab(target) def _filter_vocab(self, target): if len(self.tgt_vocab) != len(self.vocab): def _filter(target): mask = target.ge(len(self.tgt_vocab)) if mask.any(): target[mask] = self.tgt_vocab.unk() return target if isinstance(target, list): return [_filter(t) for t in target] return _filter(target) return target def collater(self, samples): """Merge a list of samples to form a mini-batch. Args: samples (List[dict]): samples to collate Returns: dict: a mini-batch with the following keys: - `id` (LongTensor): example IDs in the original input order - `ntokens` (int): total number of tokens in the batch - `net_input` (dict): the input to the Model, containing keys: - `src_tokens` (LongTensor): a padded 2D Tensor of tokens in the source sentence of shape `(bsz, src_len)`. Padding will appear on the right. - `target` (LongTensor): a padded 2D Tensor of tokens in the target sentence of shape `(bsz, tgt_len)`. Padding will appear on the right. """ return collate(samples, self.vocab.pad(), self.vocab.eos()) def get_dummy_batch(self, num_tokens, max_positions, tgt_len=128): """Return a dummy batch with a given number of tokens.""" if isinstance(max_positions, float) or isinstance(max_positions, int): tgt_len = min(tgt_len, max_positions) bsz = num_tokens // tgt_len target = self.vocab.dummy_sentence(tgt_len + 2) source, past_target, future_target = target[1:-1], target[2:], target[:-2] source, target = self._make_source_target(source, past_target, future_target) return self.collater([ {'id': i, 'source': source, 'target': target} for i in range(bsz) ]) def num_tokens(self, index): """Return the number of tokens in a sample. This value is used to enforce ``--max-tokens`` during batching.""" return self.sizes[index] def size(self, index): """Return an example's size as a float or tuple. This value is used when filtering a dataset with ``--max-positions``.""" return self.sizes[index] def ordered_indices(self): """Return an ordered list of indices. Batches will be constructed based on this order.""" if self.shuffle: order = [np.random.permutation(len(self))] else: order = [np.arange(len(self))] order.append(np.flip(self.sizes, 0)) return np.lexsort(order)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/data/token_block_dataset.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import numpy as np import torch class TokenBlockDataset(torch.utils.data.Dataset): """Break a 1d tensor of tokens into blocks. The blocks are fetched from the original tensor so no additional memory is allocated. Args: tokens: 1d tensor of tokens to break into blocks sizes: sentence lengths (required for 'complete' and 'eos') block_size: maximum block size (ignored in 'eos' break mode) break_mode: Mode used for breaking tokens. Values can be one of: - 'none': break tokens into equally sized blocks (up to block_size) - 'complete': break tokens into blocks (up to block_size) such that blocks contains complete sentences, although block_size may be exceeded if some sentences exceed block_size - 'eos': each block contains one sentence (block_size is ignored) include_targets: return next tokens as targets """ def __init__(self, tokens, sizes, block_size, pad, eos, break_mode=None, include_targets=False): super().__init__() self.tokens = tokens self.total_size = len(tokens) self.pad = pad self.eos = eos self.include_targets = include_targets self.slice_indices = [] if break_mode is None or break_mode == 'none': length = math.ceil(len(tokens) / block_size) def block_at(i): start = i * block_size end = min(start + block_size, len(tokens)) return (start, end) self.slice_indices = [block_at(i) for i in range(length)] elif break_mode == 'complete': assert sizes is not None and sum(sizes) == len(tokens), '{} != {}'.format(sum(sizes), len(tokens)) tok_idx = 0 sz_idx = 0 curr_size = 0 while sz_idx < len(sizes): if curr_size + sizes[sz_idx] <= block_size or curr_size == 0: curr_size += sizes[sz_idx] sz_idx += 1 else: self.slice_indices.append((tok_idx, tok_idx + curr_size)) tok_idx += curr_size curr_size = 0 if curr_size > 0: self.slice_indices.append((tok_idx, tok_idx + curr_size)) elif break_mode == 'eos': assert sizes is not None and sum(sizes) == len(tokens), '{} != {}'.format(sum(sizes), len(tokens)) curr = 0 for sz in sizes: # skip samples with just 1 example (which would be just the eos token) if sz > 1: self.slice_indices.append((curr, curr + sz)) curr += sz else: raise ValueError('Invalid break_mode: ' + break_mode) self.sizes = np.array([e - s for s, e in self.slice_indices]) def __getitem__(self, index): s, e = self.slice_indices[index] item = torch.LongTensor(self.tokens[s:e]) if self.include_targets: # target is the sentence, for source, rotate item one token to the left (would start with eos) # past target is rotated to the left by 2 (padded if its first) if s == 0: source = np.concatenate([[self.eos], self.tokens[0:e - 1]]) past_target = np.concatenate([[self.pad, self.eos], self.tokens[0:e - 2]]) else: source = self.tokens[s - 1:e - 1] if s == 1: past_target = np.concatenate([[self.eos], self.tokens[0:e - 2]]) else: past_target = self.tokens[s - 2:e - 2] return torch.LongTensor(source), item, torch.LongTensor(past_target) return item def __len__(self): return len(self.slice_indices)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/distributed_utils.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from collections import namedtuple import pickle import torch from torch import nn from fairseq import utils def is_master(args): return args.distributed_rank == 0 _use_c10d = [True] C10dStatus = namedtuple('C10dStatus', ['has_c10d', 'is_default']) if hasattr(nn.parallel, 'deprecated'): c10d_status = C10dStatus(has_c10d=True, is_default=True) elif hasattr(nn.parallel, '_DistributedDataParallelC10d'): c10d_status = C10dStatus(has_c10d=True, is_default=False) else: c10d_status = C10dStatus(has_c10d=False, is_default=False) if c10d_status.is_default: import torch.distributed as dist_c10d import torch.distributed.deprecated as dist_no_c10d elif c10d_status.has_c10d: import torch.distributed.c10d as dist_c10d import torch.distributed as dist_no_c10d else: import torch.distributed as dist_no_c10d def distributed_init(args): if args.distributed_world_size == 1: raise ValueError('Cannot initialize distributed with distributed_world_size=1') if args.ddp_backend == 'no_c10d': _use_c10d[0] = False print('| distributed init (rank {}): {}'.format( args.distributed_rank, args.distributed_init_method), flush=True) if _use_c10d[0]: init_fn = dist_c10d.init_process_group else: init_fn = dist_no_c10d.init_process_group init_fn( backend=args.distributed_backend, init_method=args.distributed_init_method, world_size=args.distributed_world_size, rank=args.distributed_rank, ) if not is_master(args): suppress_output() return args.distributed_rank def suppress_output(): """Suppress printing on the current device. Force printing with `force=True`.""" import builtins as __builtin__ builtin_print = __builtin__.print def print(*args, **kwargs): if 'force' in kwargs: force = kwargs.pop('force') if force: builtin_print(*args, **kwargs) __builtin__.print = print def get_rank(): if _use_c10d[0]: return dist_c10d.get_rank() else: return dist_no_c10d.get_rank() def get_world_size(): if _use_c10d[0]: return dist_c10d.get_world_size() else: return dist_no_c10d.get_world_size() def get_default_group(): if _use_c10d[0]: return dist_c10d.group.WORLD else: return dist_no_c10d.group.WORLD def all_reduce(tensor, group=None): if group is None: group = get_default_group() if _use_c10d[0]: return dist_c10d.all_reduce(tensor, group=group) else: return dist_no_c10d.all_reduce(tensor, group=group) def all_gather_list(data, group=None, max_size=16384): """Gathers arbitrary data from all nodes into a list. Similar to :func:`~torch.distributed.all_gather` but for arbitrary Python data. Note that *data* must be picklable. Args: data (Any): data from the local worker to be gathered on other workers group (optional): group of the collective max_size (int, optional): maximum size of the data to be gathered across workers """ rank = get_rank() world_size = get_world_size() buffer_size = max_size * world_size if not hasattr(all_gather_list, '_buffer') or \ all_gather_list._buffer.numel() < buffer_size: all_gather_list._buffer = torch.cuda.ByteTensor(buffer_size) buffer = all_gather_list._buffer buffer.zero_() enc = pickle.dumps(data) enc_size = len(enc) if enc_size + 2 > max_size: raise ValueError('encoded data exceeds max_size: {}'.format(enc_size + 2)) assert max_size < 255*256 buffer_rank = buffer[rank * max_size : (rank + 1) * max_size] buffer_rank[0] = enc_size // 255 # this encoding works for max_size < 65k buffer_rank[1] = enc_size % 255 buffer_rank[2:enc_size+2] = torch.ByteTensor(list(enc)) all_reduce(buffer, group=group) result = [] for i in range(world_size): out_buffer = buffer[i * max_size : (i + 1) * max_size] size = (255 * utils.item(out_buffer[0])) + utils.item(out_buffer[1]) if size > 0: result.append( pickle.loads(bytes(out_buffer[2:size+2].tolist())) ) return result
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/meters.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import time class AverageMeter(object): """Computes and stores the average and current value""" def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val = val self.sum += val * n self.count += n self.avg = self.sum / self.count class TimeMeter(object): """Computes the average occurrence of some event per second""" def __init__(self, init=0): self.reset(init) def reset(self, init=0): self.init = init self.start = time.time() self.n = 0 def update(self, val=1): self.n += val @property def avg(self): return self.n / self.elapsed_time @property def elapsed_time(self): return self.init + (time.time() - self.start) class StopwatchMeter(object): """Computes the sum/avg duration of some event in seconds""" def __init__(self): self.reset() def start(self): self.start_time = time.time() def stop(self, n=1): if self.start_time is not None: delta = time.time() - self.start_time self.sum += delta self.n += n self.start_time = None def reset(self): self.sum = 0 self.n = 0 self.start_time = None @property def avg(self): return self.sum / self.n
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import argparse import importlib import os from .fairseq_decoder import FairseqDecoder # noqa: F401 from .fairseq_encoder import FairseqEncoder # noqa: F401 from .fairseq_incremental_decoder import FairseqIncrementalDecoder # noqa: F401 from .fairseq_model import BaseFairseqModel, FairseqModel, FairseqLanguageModel # noqa: F401 from .composite_encoder import CompositeEncoder # noqa: F401 from .distributed_fairseq_model import DistributedFairseqModel # noqa: F401 MODEL_REGISTRY = {} ARCH_MODEL_REGISTRY = {} ARCH_MODEL_INV_REGISTRY = {} ARCH_CONFIG_REGISTRY = {} def build_model(args, task): return ARCH_MODEL_REGISTRY[args.arch].build_model(args, task) def register_model(name): """ New model types can be added to fairseq with the :func:`register_model` function decorator. For example:: @register_model('lstm') class LSTM(FairseqModel): (...) .. note:: All models must implement the :class:`BaseFairseqModel` interface. Typically you will extend :class:`FairseqModel` for sequence-to-sequence tasks or :class:`FairseqLanguageModel` for language modeling tasks. Args: name (str): the name of the model """ def register_model_cls(cls): if name in MODEL_REGISTRY: raise ValueError('Cannot register duplicate model ({})'.format(name)) if not issubclass(cls, BaseFairseqModel): raise ValueError('Model ({}: {}) must extend BaseFairseqModel'.format(name, cls.__name__)) MODEL_REGISTRY[name] = cls return cls return register_model_cls def register_model_architecture(model_name, arch_name): """ New model architectures can be added to fairseq with the :func:`register_model_architecture` function decorator. After registration, model architectures can be selected with the ``--arch`` command-line argument. For example:: @register_model_architecture('lstm', 'lstm_luong_wmt_en_de') def lstm_luong_wmt_en_de(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1000) (...) The decorated function should take a single argument *args*, which is a :class:`argparse.Namespace` of arguments parsed from the command-line. The decorated function should modify these arguments in-place to match the desired architecture. Args: model_name (str): the name of the Model (Model must already be registered) arch_name (str): the name of the model architecture (``--arch``) """ def register_model_arch_fn(fn): if model_name not in MODEL_REGISTRY: raise ValueError('Cannot register model architecture for unknown model type ({})'.format(model_name)) if arch_name in ARCH_MODEL_REGISTRY: raise ValueError('Cannot register duplicate model architecture ({})'.format(arch_name)) if not callable(fn): raise ValueError('Model architecture must be callable ({})'.format(arch_name)) ARCH_MODEL_REGISTRY[arch_name] = MODEL_REGISTRY[model_name] ARCH_MODEL_INV_REGISTRY.setdefault(model_name, []).append(arch_name) ARCH_CONFIG_REGISTRY[arch_name] = fn return fn return register_model_arch_fn # automatically import any Python files in the models/ directory for file in os.listdir(os.path.dirname(__file__)): if file.endswith('.py') and not file.startswith('_'): model_name = file[:file.find('.py')] module = importlib.import_module('fairseq.models.' + model_name) # extra `model_parser` for sphinx if model_name in MODEL_REGISTRY: parser = argparse.ArgumentParser(add_help=False) group_archs = parser.add_argument_group('Named architectures') group_archs.add_argument('--arch', choices=ARCH_MODEL_INV_REGISTRY[model_name]) group_args = parser.add_argument_group('Additional command-line arguments') MODEL_REGISTRY[model_name].add_args(group_args) globals()[model_name + '_parser'] = parser
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/composite_encoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqEncoder class CompositeEncoder(FairseqEncoder): """ A wrapper around a dictionary of :class:`FairseqEncoder` objects. We run forward on each encoder and return a dictionary of outputs. The first encoder's dictionary is used for initialization. Args: encoders (dict): a dictionary of :class:`FairseqEncoder` objects. """ def __init__(self, encoders): super().__init__(next(iter(encoders.values())).dictionary) self.encoders = encoders for key in self.encoders: self.add_module(key, self.encoders[key]) def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: the outputs from each Encoder """ encoder_out = {} for key in self.encoders: encoder_out[key] = self.encoders[key](src_tokens, src_lengths) return encoder_out def reorder_encoder_out(self, encoder_out, new_order): """Reorder encoder output according to new_order.""" for key in self.encoders: encoder_out[key] = self.encoders[key].reorder_encoder_out(encoder_out[key], new_order) return encoder_out def max_positions(self): return min([self.encoders[key].max_positions() for key in self.encoders]) def upgrade_state_dict(self, state_dict): for key in self.encoders: self.encoders[key].upgrade_state_dict(state_dict) return state_dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/distributed_fairseq_model.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from torch.nn import parallel from fairseq.distributed_utils import c10d_status from . import BaseFairseqModel class DistributedFairseqModel(BaseFairseqModel): """ A wrapper around a :class:`BaseFairseqModel` instance that adds support for distributed training. Anytime a method or attribute is called on this class we first try to forward it to the underlying DistributedDataParallel instance, otherwise we forward it to the original :class:`BaseFairseqModel` instance. Args: args (argparse.Namespace): fairseq args model (BaseFairseqModel): model to wrap """ def __init__(self, args, model): super().__init__() assert isinstance(model, BaseFairseqModel) if args.ddp_backend == 'c10d': if c10d_status.is_default: ddp_class = parallel.DistributedDataParallel elif c10d_status.has_c10d: ddp_class = parallel._DistributedDataParallelC10d else: raise Exception( 'Can\'t find c10d version of DistributedDataParallel. ' 'Please update PyTorch.' ) self.ddp_model = ddp_class( module=model, device_ids=[args.device_id], output_device=args.device_id, broadcast_buffers=False, bucket_cap_mb=args.bucket_cap_mb, ) elif args.ddp_backend == 'no_c10d': if c10d_status.is_default: ddp_class = parallel.deprecated.DistributedDataParallel else: ddp_class = parallel.DistributedDataParallel self.ddp_model = ddp_class( module=model, device_ids=[args.device_id], output_device=args.device_id, broadcast_buffers=False, ) else: raise ValueError('Unknown --ddp-backend: ' + args.ddp_backend) def __call__(self, *args, **kwargs): return self.ddp_model(*args, **kwargs) def forward(self, *args, **kwargs): return self.ddp_model.forward(*args, **kwargs) def __getattr__(self, name): try: return super().__getattr__(name) except AttributeError: pass try: return self.ddp_model.__getattr__(name) except AttributeError: pass return self.ddp_model.module.__getattr__(name)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/fairseq_decoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn as nn import torch.nn.functional as F class FairseqDecoder(nn.Module): """Base class for decoders.""" def __init__(self, dictionary): super().__init__() self.dictionary = dictionary def forward(self, prev_output_tokens, encoder_out): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention Returns: tuple: - the last decoder layer's output of shape `(batch, tgt_len, vocab)` - the last decoder layer's attention weights of shape `(batch, tgt_len, src_len)` """ raise NotImplementedError def get_normalized_probs(self, net_output, log_probs, sample): """Get normalized probabilities (or log probs) from a net's output.""" if hasattr(self, 'adaptive_softmax') and self.adaptive_softmax is not None: assert sample is not None and 'target' in sample out = self.adaptive_softmax.get_log_prob(net_output[0], sample['target']) return out.exp_() if not log_probs else out logits = net_output[0].float() if log_probs: return F.log_softmax(logits, dim=-1) else: return F.softmax(logits, dim=-1) def max_positions(self): """Maximum input length supported by the decoder.""" return 1e6 # an arbitrary large number def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" return state_dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/fairseq_encoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn as nn class FairseqEncoder(nn.Module): """Base class for encoders.""" def __init__(self, dictionary): super().__init__() self.dictionary = dictionary def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): lengths of each source sentence of shape `(batch)` """ raise NotImplementedError def reorder_encoder_out(self, encoder_out, new_order): """ Reorder encoder output according to `new_order`. Args: encoder_out: output from the ``forward()`` method new_order (LongTensor): desired order Returns: `encoder_out` rearranged according to `new_order` """ raise NotImplementedError def max_positions(self): """Maximum input length supported by the encoder.""" return 1e6 # an arbitrary large number def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" return state_dict
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/fairseq_incremental_decoder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from . import FairseqDecoder class FairseqIncrementalDecoder(FairseqDecoder): """Base class for incremental decoders. Incremental decoding is a special mode at inference time where the Model only receives a single timestep of input corresponding to the immediately previous output token (for input feeding) and must produce the next output *incrementally*. Thus the model must cache any long-term state that is needed about the sequence, e.g., hidden states, convolutional states, etc. Compared to the standard :class:`FairseqDecoder` interface, the incremental decoder interface allows :func:`forward` functions to take an extra keyword argument (*incremental_state*) that can be used to cache state across time-steps. The :class:`FairseqIncrementalDecoder` interface also defines the :func:`reorder_incremental_state` method, which is used during beam search to select and reorder the incremental state based on the selection of beams. """ def __init__(self, dictionary): super().__init__(dictionary) def forward(self, prev_output_tokens, encoder_out, incremental_state=None): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention incremental_state (dict): dictionary used for storing state during :ref:`Incremental decoding` Returns: tuple: - the last decoder layer's output of shape `(batch, tgt_len, vocab)` - the last decoder layer's attention weights of shape `(batch, tgt_len, src_len)` """ raise NotImplementedError def reorder_incremental_state(self, incremental_state, new_order): """Reorder incremental state. This should be called when the order of the input has changed from the previous time step. A typical use case is beam search, where the input order changes between time steps based on the selection of beams. """ def apply_reorder_incremental_state(module): if module != self and hasattr(module, 'reorder_incremental_state'): module.reorder_incremental_state( incremental_state, new_order, ) self.apply(apply_reorder_incremental_state) def set_beam_size(self, beam_size): """Sets the beam size in the decoder and all children.""" if getattr(self, '_beam_size', -1) != beam_size: def apply_set_beam_size(module): if module != self and hasattr(module, 'set_beam_size'): module.set_beam_size(beam_size) self.apply(apply_set_beam_size) self._beam_size = beam_size
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/fairseq_model.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn as nn import torch.nn.functional as F from . import FairseqDecoder, FairseqEncoder class BaseFairseqModel(nn.Module): """Base class for fairseq models.""" def __init__(self): super().__init__() self._is_generation_fast = False @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" pass @classmethod def build_model(cls, args, task): """Build a new model instance.""" raise NotImplementedError def get_targets(self, sample, net_output): """Get targets from either the sample or the net's output.""" return sample['target'] def get_normalized_probs(self, net_output, log_probs, sample=None): """Get normalized probabilities (or log probs) from a net's output.""" if hasattr(self, 'decoder'): return self.decoder.get_normalized_probs(net_output, log_probs, sample) elif torch.is_tensor(net_output): logits = net_output.float() if log_probs: return F.log_softmax(logits, dim=-1) else: return F.softmax(logits, dim=-1) raise NotImplementedError def max_positions(self): """Maximum length supported by the model.""" return None def max_decoder_positions(self): """Maximum length supported by the decoder.""" return self.decoder.max_positions() def load_state_dict(self, state_dict, strict=True): """Copies parameters and buffers from *state_dict* into this module and its descendants. Overrides the method in :class:`nn.Module`. Compared with that method this additionally "upgrades" *state_dicts* from old checkpoints. """ self.upgrade_state_dict(state_dict) super().load_state_dict(state_dict, strict) def upgrade_state_dict(self, state_dict): """Upgrade old state dicts to work with newer code.""" self.upgrade_state_dict_named(state_dict, '') def upgrade_state_dict_named(self, state_dict, name): assert state_dict is not None def do_upgrade(m, prefix): if len(prefix) > 0: prefix += '.' for n, c in m.named_children(): name = prefix + n if hasattr(c, 'upgrade_state_dict_named'): c.upgrade_state_dict_named(state_dict, name) elif hasattr(c, 'upgrade_state_dict'): c.upgrade_state_dict(state_dict) do_upgrade(c, name) do_upgrade(self, name) def make_generation_fast_(self, **kwargs): """Optimize model for faster generation.""" if self._is_generation_fast: return # only apply once self._is_generation_fast = True # remove weight norm from all modules in the network def apply_remove_weight_norm(module): try: nn.utils.remove_weight_norm(module) except ValueError: # this module didn't have weight norm return self.apply(apply_remove_weight_norm) def apply_make_generation_fast_(module): if module != self and hasattr(module, 'make_generation_fast_'): module.make_generation_fast_(**kwargs) self.apply(apply_make_generation_fast_) def train(mode): if mode: raise RuntimeError('cannot train after make_generation_fast') # this model should no longer be used for training self.eval() self.train = train def prepare_for_onnx_export_(self, **kwargs): """Make model exportable via ONNX trace.""" def apply_prepare_for_onnx_export_(module): if module != self and hasattr(module, 'prepare_for_onnx_export_'): module.prepare_for_onnx_export_(**kwargs) self.apply(apply_prepare_for_onnx_export_) class FairseqModel(BaseFairseqModel): """Base class for encoder-decoder models. Args: encoder (FairseqEncoder): the encoder decoder (FairseqDecoder): the decoder """ def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder self.decoder = decoder assert isinstance(self.encoder, FairseqEncoder) assert isinstance(self.decoder, FairseqDecoder) def forward(self, src_tokens, src_lengths, prev_output_tokens): """ Run the forward pass for an encoder-decoder model. First feed a batch of source tokens through the encoder. Then, feed the encoder output and previous decoder outputs (i.e., input feeding/teacher forcing) to the decoder to produce the next outputs:: encoder_out = self.encoder(src_tokens, src_lengths) return self.decoder(prev_output_tokens, encoder_out) Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): source sentence lengths of shape `(batch)` prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing Returns: the decoder's output, typically of shape `(batch, tgt_len, vocab)` """ encoder_out = self.encoder(src_tokens, src_lengths) decoder_out = self.decoder(prev_output_tokens, encoder_out) return decoder_out def max_positions(self): """Maximum length supported by the model.""" return (self.encoder.max_positions(), self.decoder.max_positions()) class FairseqLanguageModel(BaseFairseqModel): """Base class for decoder-only models. Args: decoder (FairseqDecoder): the decoder """ def __init__(self, decoder): super().__init__() self.decoder = decoder assert isinstance(self.decoder, FairseqDecoder) def forward(self, src_tokens, src_lengths): """ Run the forward pass for a decoder-only model. Feeds a batch of tokens through the decoder to predict the next tokens. Args: src_tokens (LongTensor): tokens on which to condition the decoder, of shape `(batch, tgt_len)` src_lengths (LongTensor): source sentence lengths of shape `(batch)` Returns: the decoder's output, typically of shape `(batch, seq_len, vocab)` """ return self.decoder(src_tokens) def max_positions(self): """Maximum length supported by the model.""" return self.decoder.max_positions() @property def supported_targets(self): return {'future'}
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/fconv.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options, utils from fairseq.modules import ( AdaptiveSoftmax, BeamableMM, GradMultiply, LearnedPositionalEmbedding, LinearizedConvolution, ) from . import ( FairseqEncoder, FairseqIncrementalDecoder, FairseqModel, FairseqLanguageModel, register_model, register_model_architecture, ) @register_model('fconv') class FConvModel(FairseqModel): """ A fully convolutional model, i.e. a convolutional encoder and a convolutional decoder, as described in `"Convolutional Sequence to Sequence Learning" (Gehring et al., 2017) <https://arxiv.org/abs/1705.03122>`_. Args: encoder (FConvEncoder): the encoder decoder (FConvDecoder): the decoder The Convolutional model provides the following named architectures and command-line arguments: .. argparse:: :ref: fairseq.models.fconv_parser :prog: """ def __init__(self, encoder, decoder): super().__init__(encoder, decoder) self.encoder.num_attention_layers = sum(layer is not None for layer in decoder.attention) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-layers', type=str, metavar='EXPR', help='encoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-embed-path', type=str, metavar='STR', help='path to pre-trained decoder embedding') parser.add_argument('--decoder-layers', type=str, metavar='EXPR', help='decoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--decoder-attention', type=str, metavar='EXPR', help='decoder attention [True, ...]') parser.add_argument('--share-input-output-embed', action='store_true', help='share input and output embeddings (requires' ' --decoder-out-embed-dim and --decoder-embed-dim' ' to be equal)') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure that all args are properly defaulted (in case there are any new ones) base_architecture(args) encoder_embed_dict = None if args.encoder_embed_path: encoder_embed_dict = utils.parse_embedding(args.encoder_embed_path) utils.print_embed_overlap(encoder_embed_dict, task.source_dictionary) decoder_embed_dict = None if args.decoder_embed_path: decoder_embed_dict = utils.parse_embedding(args.decoder_embed_path) utils.print_embed_overlap(decoder_embed_dict, task.target_dictionary) encoder = FConvEncoder( dictionary=task.source_dictionary, embed_dim=args.encoder_embed_dim, embed_dict=encoder_embed_dict, convolutions=eval(args.encoder_layers), dropout=args.dropout, max_positions=args.max_source_positions, ) decoder = FConvDecoder( dictionary=task.target_dictionary, embed_dim=args.decoder_embed_dim, embed_dict=decoder_embed_dict, convolutions=eval(args.decoder_layers), out_embed_dim=args.decoder_out_embed_dim, attention=eval(args.decoder_attention), dropout=args.dropout, max_positions=args.max_target_positions, share_embed=args.share_input_output_embed, ) return FConvModel(encoder, decoder) @register_model('fconv_lm') class FConvLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-layers', type=str, metavar='EXPR', help='decoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion') parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') parser.add_argument('--decoder-attention', type=str, metavar='EXPR', help='decoder attention [True, ...]') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_lm_architecture(args) if hasattr(args, 'max_target_positions'): args.tokens_per_sample = args.max_target_positions decoder = FConvDecoder( dictionary=task.target_dictionary, embed_dim=args.decoder_embed_dim, convolutions=eval(args.decoder_layers), out_embed_dim=args.decoder_embed_dim, attention=eval(args.decoder_attention), dropout=args.dropout, max_positions=args.tokens_per_sample, share_embed=False, positional_embeddings=False, adaptive_softmax_cutoff=( options.eval_str_list(args.adaptive_softmax_cutoff, type=int) if args.criterion == 'adaptive_loss' else None ), adaptive_softmax_dropout=args.adaptive_softmax_dropout, ) return FConvLanguageModel(decoder) class FConvEncoder(FairseqEncoder): """ Convolutional encoder consisting of `len(convolutions)` layers. Args: dictionary (~fairseq.data.Dictionary): encoding dictionary embed_dim (int, optional): embedding dimension embed_dict (str, optional): filename from which to load pre-trained embeddings max_positions (int, optional): maximum supported input sequence length convolutions (list, optional): the convolutional layer structure. Each list item `i` corresponds to convolutional layer `i`. Layers are given as ``(out_channels, kernel_width, [residual])``. Residual connections are added between layers when ``residual=1`` (which is the default behavior). dropout (float, optional): dropout to be applied before each conv layer normalization_constant (float, optional): multiplies the result of the residual block by sqrt(value) left_pad (bool, optional): whether the input is left-padded. Default: ``True`` """ def __init__( self, dictionary, embed_dim=512, embed_dict=None, max_positions=1024, convolutions=((512, 3),) * 20, dropout=0.1, left_pad=True, ): super().__init__(dictionary) self.dropout = dropout self.left_pad = left_pad self.num_attention_layers = None num_embeddings = len(dictionary) self.padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) if embed_dict: self.embed_tokens = utils.load_embedding(embed_dict, self.dictionary, self.embed_tokens) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, self.padding_idx, left_pad=self.left_pad, ) convolutions = extend_conv_spec(convolutions) in_channels = convolutions[0][0] self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.residuals = [] layer_in_channels = [in_channels] for i, (out_channels, kernel_size, residual) in enumerate(convolutions): if residual == 0: residual_dim = out_channels else: residual_dim = layer_in_channels[-residual] self.projections.append(Linear(residual_dim, out_channels) if residual_dim != out_channels else None) if kernel_size % 2 == 1: padding = kernel_size // 2 else: padding = 0 self.convolutions.append( ConvTBC(in_channels, out_channels * 2, kernel_size, dropout=dropout, padding=padding) ) self.residuals.append(residual) in_channels = out_channels layer_in_channels.append(out_channels) self.fc2 = Linear(in_channels, embed_dim) def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: - **encoder_out** (tuple): a tuple with two elements, where the first element is the last encoder layer's output and the second element is the same quantity summed with the input embedding (used for attention). The shape of both tensors is `(batch, src_len, embed_dim)`. - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)` """ # embed tokens and positions x = self.embed_tokens(src_tokens) + self.embed_positions(src_tokens) x = F.dropout(x, p=self.dropout, training=self.training) input_embedding = x # project to size of convolution x = self.fc1(x) # used to mask padding in input encoder_padding_mask = src_tokens.eq(self.padding_idx).t() # -> T x B if not encoder_padding_mask.any(): encoder_padding_mask = None # B x T x C -> T x B x C x = x.transpose(0, 1) residuals = [x] # temporal convolutions for proj, conv, res_layer in zip(self.projections, self.convolutions, self.residuals): if res_layer > 0: residual = residuals[-res_layer] residual = residual if proj is None else proj(residual) else: residual = None if encoder_padding_mask is not None: x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0) x = F.dropout(x, p=self.dropout, training=self.training) if conv.kernel_size[0] % 2 == 1: # padding is implicit in the conv x = conv(x) else: padding_l = (conv.kernel_size[0] - 1) // 2 padding_r = conv.kernel_size[0] // 2 x = F.pad(x, (0, 0, 0, 0, padding_l, padding_r)) x = conv(x) x = F.glu(x, dim=2) if residual is not None: x = (x + residual) * math.sqrt(0.5) residuals.append(x) # T x B x C -> B x T x C x = x.transpose(1, 0) # project back to size of embedding x = self.fc2(x) if encoder_padding_mask is not None: encoder_padding_mask = encoder_padding_mask.t() # -> B x T x = x.masked_fill(encoder_padding_mask.unsqueeze(-1), 0) # scale gradients (this only affects backward, not forward) x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers)) # add output to input embedding for attention y = (x + input_embedding) * math.sqrt(0.5) return { 'encoder_out': (x, y), 'encoder_padding_mask': encoder_padding_mask, # B x T } def reorder_encoder_out(self, encoder_out, new_order): if encoder_out['encoder_out'] is not None: encoder_out['encoder_out'] = ( encoder_out['encoder_out'][0].index_select(0, new_order), encoder_out['encoder_out'][1].index_select(0, new_order), ) if encoder_out['encoder_padding_mask'] is not None: encoder_out['encoder_padding_mask'] = \ encoder_out['encoder_padding_mask'].index_select(0, new_order) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" return self.embed_positions.max_positions() class AttentionLayer(nn.Module): def __init__(self, conv_channels, embed_dim, bmm=None): super().__init__() # projects from output of convolution to embedding dimension self.in_projection = Linear(conv_channels, embed_dim) # projects from embedding dimension to convolution size self.out_projection = Linear(embed_dim, conv_channels) self.bmm = bmm if bmm is not None else torch.bmm def forward(self, x, target_embedding, encoder_out, encoder_padding_mask): residual = x # attention x = (self.in_projection(x) + target_embedding) * math.sqrt(0.5) x = self.bmm(x, encoder_out[0]) # don't attend over padding if encoder_padding_mask is not None: x = x.float().masked_fill( encoder_padding_mask.unsqueeze(1), float('-inf') ).type_as(x) # FP16 support: cast to float and back # softmax over last dim sz = x.size() x = F.softmax(x.view(sz[0] * sz[1], sz[2]), dim=1) x = x.view(sz) attn_scores = x x = self.bmm(x, encoder_out[1]) # scale attention output (respecting potentially different lengths) s = encoder_out[1].size(1) if encoder_padding_mask is None: x = x * (s * math.sqrt(1.0 / s)) else: s = s - encoder_padding_mask.type_as(x).sum(dim=1, keepdim=True) # exclude padding s = s.unsqueeze(-1) x = x * (s * s.rsqrt()) # project back x = (self.out_projection(x) + residual) * math.sqrt(0.5) return x, attn_scores def make_generation_fast_(self, beamable_mm_beam_size=None, **kwargs): """Replace torch.bmm with BeamableMM.""" if beamable_mm_beam_size is not None: del self.bmm self.add_module('bmm', BeamableMM(beamable_mm_beam_size)) class FConvDecoder(FairseqIncrementalDecoder): """Convolutional decoder""" def __init__( self, dictionary, embed_dim=512, embed_dict=None, out_embed_dim=256, max_positions=1024, convolutions=((512, 3),) * 20, attention=True, dropout=0.1, share_embed=False, positional_embeddings=True, adaptive_softmax_cutoff=None, adaptive_softmax_dropout=0, left_pad=False, ): super().__init__(dictionary) self.register_buffer('version', torch.Tensor([2])) self.dropout = dropout self.left_pad = left_pad self.need_attn = True convolutions = extend_conv_spec(convolutions) in_channels = convolutions[0][0] if isinstance(attention, bool): # expand True into [True, True, ...] and do the same with False attention = [attention] * len(convolutions) if not isinstance(attention, list) or len(attention) != len(convolutions): raise ValueError('Attention is expected to be a list of booleans of ' 'length equal to the number of layers.') num_embeddings = len(dictionary) padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) if embed_dict: self.embed_tokens = utils.load_embedding(embed_dict, self.dictionary, self.embed_tokens) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, padding_idx, left_pad=self.left_pad, ) if positional_embeddings else None self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.attention = nn.ModuleList() self.residuals = [] layer_in_channels = [in_channels] for i, (out_channels, kernel_size, residual) in enumerate(convolutions): if residual == 0: residual_dim = out_channels else: residual_dim = layer_in_channels[-residual] self.projections.append(Linear(residual_dim, out_channels) if residual_dim != out_channels else None) self.convolutions.append( LinearizedConv1d(in_channels, out_channels * 2, kernel_size, padding=(kernel_size - 1), dropout=dropout) ) self.attention.append(AttentionLayer(out_channels, embed_dim) if attention[i] else None) self.residuals.append(residual) in_channels = out_channels layer_in_channels.append(out_channels) self.adaptive_softmax = None self.fc2 = self.fc3 = None if adaptive_softmax_cutoff is not None: assert not share_embed self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, in_channels, adaptive_softmax_cutoff, dropout=adaptive_softmax_dropout) else: self.fc2 = Linear(in_channels, out_embed_dim) if share_embed: assert out_embed_dim == embed_dim, \ "Shared embed weights implies same dimensions " \ " out_embed_dim={} vs embed_dim={}".format(out_embed_dim, embed_dim) self.fc3 = nn.Linear(out_embed_dim, num_embeddings) self.fc3.weight = self.embed_tokens.weight else: self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout) def forward(self, prev_output_tokens, encoder_out_dict=None, incremental_state=None): if encoder_out_dict is not None: encoder_out = encoder_out_dict['encoder_out'] encoder_padding_mask = encoder_out_dict['encoder_padding_mask'] # split and transpose encoder outputs encoder_a, encoder_b = self._split_encoder_out(encoder_out, incremental_state) if self.embed_positions is not None: pos_embed = self.embed_positions(prev_output_tokens, incremental_state) else: pos_embed = 0 if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] x = self._embed_tokens(prev_output_tokens, incremental_state) # embed tokens and combine with positional embeddings x += pos_embed x = F.dropout(x, p=self.dropout, training=self.training) target_embedding = x # project to size of convolution x = self.fc1(x) # B x T x C -> T x B x C x = self._transpose_if_training(x, incremental_state) # temporal convolutions avg_attn_scores = None num_attn_layers = len(self.attention) residuals = [x] for proj, conv, attention, res_layer in zip(self.projections, self.convolutions, self.attention, self.residuals): if res_layer > 0: residual = residuals[-res_layer] residual = residual if proj is None else proj(residual) else: residual = None x = F.dropout(x, p=self.dropout, training=self.training) x = conv(x, incremental_state) x = F.glu(x, dim=2) # attention if attention is not None: x = self._transpose_if_training(x, incremental_state) x, attn_scores = attention(x, target_embedding, (encoder_a, encoder_b), encoder_padding_mask) if not self.training and self.need_attn: attn_scores = attn_scores / num_attn_layers if avg_attn_scores is None: avg_attn_scores = attn_scores else: avg_attn_scores.add_(attn_scores) x = self._transpose_if_training(x, incremental_state) # residual if residual is not None: x = (x + residual) * math.sqrt(0.5) residuals.append(x) # T x B x C -> B x T x C x = self._transpose_if_training(x, incremental_state) # project back to size of vocabulary if not using adaptive softmax if self.fc2 is not None and self.fc3 is not None: x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = self.fc3(x) return x, avg_attn_scores def reorder_incremental_state(self, incremental_state, new_order): super().reorder_incremental_state(incremental_state, new_order) encoder_out = utils.get_incremental_state(self, incremental_state, 'encoder_out') if encoder_out is not None: encoder_out = tuple(eo.index_select(0, new_order) for eo in encoder_out) utils.set_incremental_state(self, incremental_state, 'encoder_out', encoder_out) def max_positions(self): """Maximum output length supported by the decoder.""" return self.embed_positions.max_positions() if self.embed_positions is not None else float('inf') def upgrade_state_dict(self, state_dict): if utils.item(state_dict.get('decoder.version', torch.Tensor([1]))[0]) < 2: # old models use incorrect weight norm dimension for i, conv in enumerate(self.convolutions): # reconfigure weight norm nn.utils.remove_weight_norm(conv) self.convolutions[i] = nn.utils.weight_norm(conv, dim=0) state_dict['decoder.version'] = torch.Tensor([1]) return state_dict def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def _embed_tokens(self, tokens, incremental_state): if incremental_state is not None: # keep only the last token for incremental forward pass tokens = tokens[:, -1:] return self.embed_tokens(tokens) def _split_encoder_out(self, encoder_out, incremental_state): """Split and transpose encoder outputs. This is cached when doing incremental inference. """ cached_result = utils.get_incremental_state(self, incremental_state, 'encoder_out') if cached_result is not None: return cached_result # transpose only once to speed up attention layers encoder_a, encoder_b = encoder_out encoder_a = encoder_a.transpose(1, 2).contiguous() result = (encoder_a, encoder_b) if incremental_state is not None: utils.set_incremental_state(self, incremental_state, 'encoder_out', result) return result def _transpose_if_training(self, x, incremental_state): if incremental_state is None: x = x.transpose(0, 1) return x def extend_conv_spec(convolutions): """ Extends convolutional spec that is a list of tuples of 2 or 3 parameters (kernel size, dim size and optionally how many layers behind to look for residual) to default the residual propagation param if it is not specified """ extended = [] for spec in convolutions: if len(spec) == 3: extended.append(spec) elif len(spec) == 2: extended.append(spec + (1,)) else: raise Exception('invalid number of parameters in convolution spec ' + str(spec) + '. expected 2 or 3') return tuple(extended) def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) nn.init.normal_(m.weight, 0, 0.1) nn.init.constant_(m.weight[padding_idx], 0) return m def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad): m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad) nn.init.normal_(m.weight, 0, 0.1) nn.init.constant_(m.weight[padding_idx], 0) return m def Linear(in_features, out_features, dropout=0): """Weight-normalized Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features) nn.init.normal_(m.weight, mean=0, std=math.sqrt((1 - dropout) / in_features)) nn.init.constant_(m.bias, 0) return nn.utils.weight_norm(m) def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer optimized for decoding""" m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) nn.init.normal_(m.weight, mean=0, std=std) nn.init.constant_(m.bias, 0) return nn.utils.weight_norm(m, dim=2) def ConvTBC(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer""" from fairseq.modules import ConvTBC m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) nn.init.normal_(m.weight, mean=0, std=std) nn.init.constant_(m.bias, 0) return nn.utils.weight_norm(m, dim=2) @register_model_architecture('fconv_lm', 'fconv_lm') def base_lm_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 128) args.decoder_layers = getattr(args, 'decoder_layers', '[(1268, 4)] * 13') args.decoder_attention = getattr(args, 'decoder_attention', 'False') args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) @register_model_architecture('fconv_lm', 'fconv_lm_dauphin_wikitext103') def fconv_lm_dauphin_wikitext103(args): layers = '[(850, 6)] * 3' layers += ' + [(850, 1)] * 1' layers += ' + [(850, 5)] * 4' layers += ' + [(850, 1)] * 1' layers += ' + [(850, 4)] * 3' layers += ' + [(1024, 4)] * 1' layers += ' + [(2048, 4)] * 1' args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 280) args.decoder_layers = getattr(args, 'decoder_layers', layers) args.decoder_attention = getattr(args, 'decoder_attention', 'False') args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', '10000,20000,200000') base_lm_architecture(args) @register_model_architecture('fconv_lm', 'fconv_lm_dauphin_gbw') def fconv_lm_dauphin_gbw(args): layers = '[(512, 5)]' layers += ' + [(128, 1, 0), (128, 5, 0), (512, 1, 3)] * 3' layers += ' + [(512, 1, 0), (512, 5, 0), (1024, 1, 3)] * 3' layers += ' + [(1024, 1, 0), (1024, 5, 0), (2048, 1, 3)] * 6' layers += ' + [(1024, 1, 0), (1024, 5, 0), (4096, 1, 3)]' args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 128) args.decoder_layers = getattr(args, 'decoder_layers', layers) args.decoder_attention = getattr(args, 'decoder_attention', 'False') args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', '10000,50000,200000') base_lm_architecture(args) @register_model_architecture('fconv', 'fconv') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 20') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 3)] * 20') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.decoder_attention = getattr(args, 'decoder_attention', 'True') args.share_input_output_embed = getattr(args, 'share_input_output_embed', False) @register_model_architecture('fconv', 'fconv_iwslt_de_en') def fconv_iwslt_de_en(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256) args.encoder_layers = getattr(args, 'encoder_layers', '[(256, 3)] * 4') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256) args.decoder_layers = getattr(args, 'decoder_layers', '[(256, 3)] * 3') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) base_architecture(args) @register_model_architecture('fconv', 'fconv_wmt_en_ro') def fconv_wmt_en_ro(args): args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) base_architecture(args) @register_model_architecture('fconv', 'fconv_wmt_en_de') def fconv_wmt_en_de(args): convs = '[(512, 3)] * 9' # first 9 layers have 512 units convs += ' + [(1024, 3)] * 4' # next 4 layers have 1024 units convs += ' + [(2048, 1)] * 2' # final 2 layers use 1x1 convolutions args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_layers = getattr(args, 'encoder_layers', convs) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768) args.decoder_layers = getattr(args, 'decoder_layers', convs) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) base_architecture(args) @register_model_architecture('fconv', 'fconv_wmt_en_fr') def fconv_wmt_en_fr(args): convs = '[(512, 3)] * 6' # first 6 layers have 512 units convs += ' + [(768, 3)] * 4' # next 4 layers have 768 units convs += ' + [(1024, 3)] * 3' # next 3 layers have 1024 units convs += ' + [(2048, 1)] * 1' # next 1 layer uses 1x1 convolutions convs += ' + [(4096, 1)] * 1' # final 1 layer uses 1x1 convolutions args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 768) args.encoder_layers = getattr(args, 'encoder_layers', convs) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 768) args.decoder_layers = getattr(args, 'decoder_layers', convs) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) base_architecture(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/fconv_self_att.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq.modules import ( DownsampledMultiHeadAttention, GradMultiply, LearnedPositionalEmbedding, LinearizedConvolution, ) from fairseq import utils from . import ( FairseqEncoder, CompositeEncoder, FairseqDecoder, FairseqModel, register_model, register_model_architecture, ) @register_model('fconv_self_att') class FConvModelSelfAtt(FairseqModel): def __init__(self, encoder, decoder, pretrained_encoder=None): super().__init__(encoder, decoder) self.encoder.num_attention_layers = sum(layer is not None for layer in decoder.attention) self.pretrained_encoder = pretrained_encoder if self.pretrained_encoder is None: encoders = {'encoder': encoder} else: encoders = {'encoder': encoder, 'pretrained': self.pretrained_encoder} # for fusion model, CompositeEncoder contains both pretrained and training encoders # these are forwarded and then combined in the decoder self.encoder = CompositeEncoder(encoders) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-layers', type=str, metavar='EXPR', help='encoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-layers', type=str, metavar='EXPR', help='decoder layers [(dim, kernel_size), ...]') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--decoder-attention', type=str, metavar='EXPR', help='decoder attention [True, ...]') parser.add_argument('--self-attention', type=str, metavar='EXPR', help='decoder self-attention layers, ex: [True] + [False]*5') parser.add_argument('--multihead-attention-nheads', type=int, help='Number of heads to use in attention') parser.add_argument('--multihead-self-attention-nheads', type=int, help='Number of heads to use in self-attention') parser.add_argument('--encoder-attention', type=str, metavar='EXPR', help='encoder attention [True, ...]') parser.add_argument('--encoder-attention-nheads', type=int, help='Number of heads to use in encoder attention') parser.add_argument('--project-input', type=str, metavar='EXPR', help='Use projections in self-attention [True, ...]') parser.add_argument('--gated-attention', type=str, metavar='EXPR', help='Use GLU layers in self-attention projections [True, ...]') parser.add_argument('--downsample', type=str, metavar='EXPR', help='Use downsampling in self-attention [True, ...]') parser.add_argument('--pretrained-checkpoint', metavar='DIR', help='path to load checkpoint from pretrained model') parser.add_argument('--pretrained', type=str, metavar='EXPR', help='use pretrained model when training [True, ...]') @classmethod def build_model(cls, args, task): trained_encoder, trained_decoder = None, None pretrained = eval(args.pretrained) if pretrained: print("| loading pretrained model") trained_model = utils.load_ensemble_for_inference( # not actually for inference, but loads pretrained model parameters filenames=[args.pretrained_checkpoint], task=task, )[0][0] trained_decoder = list(trained_model.children())[1] trained_encoder = list(trained_model.children())[0] # freeze pretrained model for param in trained_decoder.parameters(): param.requires_grad = False for param in trained_encoder.parameters(): param.requires_grad = False """Build a new model instance.""" encoder = FConvEncoder( task.source_dictionary, embed_dim=args.encoder_embed_dim, convolutions=eval(args.encoder_layers), dropout=args.dropout, max_positions=args.max_source_positions, attention=eval(args.encoder_attention), attention_nheads=args.encoder_attention_nheads ) decoder = FConvDecoder( task.target_dictionary, embed_dim=args.decoder_embed_dim, convolutions=eval(args.decoder_layers), out_embed_dim=args.decoder_out_embed_dim, attention=eval(args.decoder_attention), dropout=args.dropout, max_positions=args.max_target_positions, selfattention=eval(args.self_attention), attention_nheads=args.multihead_attention_nheads, selfattention_nheads=args.multihead_self_attention_nheads, project_input=eval(args.project_input), gated_attention=eval(args.gated_attention), downsample=eval(args.downsample), pretrained=pretrained, trained_decoder=trained_decoder ) model = FConvModelSelfAtt(encoder, decoder, trained_encoder) return model @property def pretrained(self): return self.pretrained_encoder is not None class FConvEncoder(FairseqEncoder): """Convolutional encoder""" def __init__( self, dictionary, embed_dim=512, max_positions=1024, convolutions=((512, 3),) * 20, dropout=0.1, attention=False, attention_nheads=1, left_pad=True, ): super().__init__(dictionary) self.dropout = dropout self.num_attention_layers = None self.left_pad = left_pad num_embeddings = len(dictionary) self.padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, self.padding_idx, left_pad=self.left_pad, ) def expand_bool_array(val): if isinstance(val, bool): # expand True into [True, True, ...] and do the same with False return [val] * len(convolutions) return val attention = expand_bool_array(attention) in_channels = convolutions[0][0] self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.attention = nn.ModuleList() self.attproj = nn.ModuleList() for i, (out_channels, kernel_size) in enumerate(convolutions): self.projections.append( Linear(in_channels, out_channels) if in_channels != out_channels else None ) self.convolutions.append( ConvTBC(in_channels, out_channels * 2, kernel_size, dropout=dropout) ) self.attention.append( SelfAttention(out_channels, embed_dim, attention_nheads) if attention[i] else None ) in_channels = out_channels self.fc2 = Linear(in_channels, embed_dim) def forward(self, src_tokens, src_lengths): # embed tokens and positions x = self.embed_tokens(src_tokens) + self.embed_positions(src_tokens) x = F.dropout(x, p=self.dropout, training=self.training) input_embedding = x.transpose(0, 1) # project to size of convolution x = self.fc1(x) # B x T x C -> T x B x C x = x.transpose(0, 1) # temporal convolutions for proj, conv, attention in zip(self.projections, self.convolutions, self.attention): residual = x if proj is None else proj(x) x = F.dropout(x, p=self.dropout, training=self.training) padding_l = (conv.kernel_size[0] - 1) // 2 padding_r = conv.kernel_size[0] // 2 x = F.pad(x, (0, 0, 0, 0, padding_l, padding_r)) x = conv(x) x = F.glu(x, dim=2) if attention is not None: x = attention(x) x = (x + residual) * math.sqrt(0.5) # T x B x C -> B x T x C x = x.transpose(1, 0) # project back to size of embedding x = self.fc2(x) # scale gradients (this only affects backward, not forward) x = GradMultiply.apply(x, 1.0 / (2.0 * self.num_attention_layers)) # add output to input embedding for attention y = (x + input_embedding.transpose(0, 1)) * math.sqrt(0.5) return { 'encoder_out': (x, y), } def reorder_encoder_out(self, encoder_out, new_order): encoder_out['encoder_out'] = tuple( eo.index_select(0, new_order) for eo in encoder_out['encoder_out'] ) if 'pretrained' in encoder_out: encoder_out['pretrained']['encoder_out'] = tuple( eo.index_select(0, new_order) for eo in encoder_out['pretrained']['encoder_out'] ) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" return self.embed_positions.max_positions() class FConvDecoder(FairseqDecoder): """Convolutional decoder""" def __init__( self, dictionary, embed_dim=512, out_embed_dim=256, max_positions=1024, convolutions=((512, 3),) * 8, attention=True, dropout=0.1, selfattention=False, attention_nheads=1, selfattention_nheads=1, project_input=False, gated_attention=False, downsample=False, pretrained=False, trained_decoder=None, left_pad=False, ): super().__init__(dictionary) self.register_buffer('version', torch.Tensor([2])) self.pretrained = pretrained self.pretrained_decoder = trained_decoder self.dropout = dropout self.left_pad = left_pad self.need_attn = True in_channels = convolutions[0][0] def expand_bool_array(val): if isinstance(val, bool): # expand True into [True, True, ...] and do the same with False return [val] * len(convolutions) return val attention = expand_bool_array(attention) selfattention = expand_bool_array(selfattention) if not isinstance(attention, list) or len(attention) != len(convolutions): raise ValueError('Attention is expected to be a list of booleans of ' 'length equal to the number of layers.') num_embeddings = len(dictionary) padding_idx = dictionary.pad() self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) self.embed_positions = PositionalEmbedding( max_positions, embed_dim, padding_idx, left_pad=self.left_pad, ) self.fc1 = Linear(embed_dim, in_channels, dropout=dropout) self.projections = nn.ModuleList() self.convolutions = nn.ModuleList() self.attention = nn.ModuleList() self.selfattention = nn.ModuleList() self.attproj = nn.ModuleList() for i, (out_channels, kernel_size) in enumerate(convolutions): self.projections.append( Linear(in_channels, out_channels) if in_channels != out_channels else None ) self.convolutions.append( LinearizedConv1d( in_channels, out_channels * 2, kernel_size, padding=(kernel_size - 1), dropout=dropout, ) ) self.attention.append( DownsampledMultiHeadAttention( out_channels, embed_dim, attention_nheads, project_input=project_input, gated=False, downsample=False, ) if attention[i] else None ) self.attproj.append( Linear(out_channels, embed_dim, dropout=dropout) if attention[i] else None ) self.selfattention.append( SelfAttention( out_channels, embed_dim, selfattention_nheads, project_input=project_input, gated=gated_attention, downsample=downsample, ) if selfattention[i] else None ) in_channels = out_channels self.fc2 = Linear(in_channels, out_embed_dim) self.fc3 = Linear(out_embed_dim, num_embeddings, dropout=dropout) # model fusion if self.pretrained: # independent gates are learned from the concatenated input self.gate1 = nn.Sequential(Linear(out_embed_dim*2, out_embed_dim), nn.Sigmoid()) self.gate2 = nn.Sequential(Linear(out_embed_dim*2, out_embed_dim), nn.Sigmoid()) # pretrained and trained models are joined self.joining = nn.Sequential( Linear(out_embed_dim*2, out_embed_dim*2), nn.LayerNorm(out_embed_dim*2), nn.GLU(), Linear(out_embed_dim, out_embed_dim*2), nn.LayerNorm(out_embed_dim*2), nn.GLU(), Linear(out_embed_dim, out_embed_dim), nn.LayerNorm(out_embed_dim) ) # pretrained model contains an output layer that is nhid -> vocab size # but the models are combined in their hidden state # the hook stores the output of the pretrained model forward self.pretrained_outputs = {} def save_output(): def hook(a, b, output): self.pretrained_outputs["out"] = output return hook self.pretrained_decoder.fc2.register_forward_hook(save_output()) def forward(self, prev_output_tokens, encoder_out_dict): encoder_out = encoder_out_dict['encoder']['encoder_out'] trained_encoder_out = encoder_out_dict['pretrained'] if self.pretrained else None encoder_a, encoder_b = self._split_encoder_out(encoder_out) # embed positions positions = self.embed_positions(prev_output_tokens) # embed tokens and positions x = self.embed_tokens(prev_output_tokens) + positions x = F.dropout(x, p=self.dropout, training=self.training) target_embedding = x.transpose(0, 1) # project to size of convolution x = self.fc1(x) # B x T x C -> T x B x C x = x.transpose(0, 1) # temporal convolutions avg_attn_scores = None for proj, conv, attention, selfattention, attproj in zip( self.projections, self.convolutions, self.attention, self.selfattention, self.attproj ): residual = x if proj is None else proj(x) x = F.dropout(x, p=self.dropout, training=self.training) x = conv(x) x = F.glu(x, dim=2) # attention if attention is not None: r = x x, attn_scores = attention(attproj(x) + target_embedding, encoder_a, encoder_b) x = x + r if not self.training and self.need_attn: if avg_attn_scores is None: avg_attn_scores = attn_scores else: avg_attn_scores.add_(attn_scores) if selfattention is not None: x = selfattention(x) x = (x + residual) * math.sqrt(0.5) # T x B x C -> B x T x C x = x.transpose(0, 1) # project back to size of vocabulary x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) if not self.pretrained: x = self.fc3(x) # fusion gating if self.pretrained: trained_x, _ = self.pretrained_decoder.forward(prev_output_tokens, trained_encoder_out) y = torch.cat([x, self.pretrained_outputs["out"]], dim=-1) gate1 = self.gate1(y) gate2 = self.gate2(y) gated_x1 = gate1 * x gated_x2 = gate2 * self.pretrained_outputs["out"] fusion = torch.cat([gated_x1, gated_x2], dim=-1) fusion = self.joining(fusion) fusion_output = self.fc3(fusion) return fusion_output, avg_attn_scores else: return x, avg_attn_scores def max_positions(self): """Maximum output length supported by the decoder.""" return self.embed_positions.max_positions() def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def _split_encoder_out(self, encoder_out): """Split and transpose encoder outputs.""" # transpose only once to speed up attention layers encoder_a, encoder_b = encoder_out encoder_a = encoder_a.transpose(0, 1).contiguous() encoder_b = encoder_b.transpose(0, 1).contiguous() result = (encoder_a, encoder_b) return result class SelfAttention(nn.Module): def __init__(self, out_channels, embed_dim, num_heads, project_input=False, gated=False, downsample=False): super().__init__() self.attention = DownsampledMultiHeadAttention( out_channels, embed_dim, num_heads, dropout=0, bias=True, project_input=project_input, gated=gated, downsample=downsample, ) self.in_proj_q = Linear(out_channels, embed_dim) self.in_proj_k = Linear(out_channels, embed_dim) self.in_proj_v = Linear(out_channels, embed_dim) self.ln = nn.LayerNorm(out_channels) def forward(self, x): residual = x query = self.in_proj_q(x) key = self.in_proj_k(x) value = self.in_proj_v(x) x, _ = self.attention(query, key, value, mask_future_timesteps=True, use_scalar_bias=True) return self.ln(x + residual) def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) m.weight.data.normal_(0, 0.1) return m def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad): m = LearnedPositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad) m.weight.data.normal_(0, 0.1) return m def Linear(in_features, out_features, dropout=0.): """Weight-normalized Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features) m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features)) m.bias.data.zero_() return m def LinearizedConv1d(in_channels, out_channels, kernel_size, dropout=0., **kwargs): """Weight-normalized Conv1d layer optimized for decoding""" m = LinearizedConvolution(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) m.weight.data.normal_(mean=0, std=std) m.bias.data.zero_() return m def ConvTBC(in_channels, out_channels, kernel_size, dropout=0, **kwargs): """Weight-normalized Conv1d layer""" from fairseq.modules import ConvTBC m = ConvTBC(in_channels, out_channels, kernel_size, **kwargs) std = math.sqrt((4 * (1.0 - dropout)) / (m.kernel_size[0] * in_channels)) m.weight.data.normal_(mean=0, std=std) m.bias.data.zero_() return m @register_model_architecture('fconv_self_att', 'fconv_self_att') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_layers = getattr(args, 'encoder_layers', '[(512, 3)] * 3') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 3)] * 8') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.decoder_attention = getattr(args, 'decoder_attention', 'True') args.self_attention = getattr(args, 'self_attention', 'False') args.encoder_attention = getattr(args, 'encoder_attention', 'False') args.multihead_attention_nheads = getattr(args, 'multihead_attention_nheads', 1) args.multihead_self_attention_nheads = getattr(args, 'multihead_self_attention_nheads', 1) args.encoder_attention_nheads = getattr(args, 'encoder_attention_nheads', 1) args.project_input = getattr(args, 'project_input', 'False') args.gated_attention = getattr(args, 'gated_attention', 'False') args.downsample = getattr(args, 'downsample', 'False') args.pretrained_checkpoint = getattr(args, 'pretrained_checkpoint', '') args.pretrained = getattr(args, 'pretrained', 'False') @register_model_architecture('fconv_self_att', 'fconv_self_att_wp') def fconv_self_att_wp(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256) args.encoder_layers = getattr(args, 'encoder_layers', '[(128, 3)] * 2 + [(512,3)] * 1') args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256) args.decoder_layers = getattr(args, 'decoder_layers', '[(512, 4)] * 4 + [(768, 4)] * 2 + [(1024, 4)] * 1') args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.self_attention = getattr(args, 'self_attention', 'True') args.multihead_self_attention_nheads = getattr(args, 'multihead_self_attention_nheads', 4) args.project_input = getattr(args, 'project_input', 'True') args.gated_attention = getattr(args, 'gated_attention', 'True') args.downsample = getattr(args, 'downsample', 'True') base_architecture(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/lstm.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options, utils from fairseq.modules import AdaptiveSoftmax from . import ( FairseqEncoder, FairseqIncrementalDecoder, FairseqModel, register_model, register_model_architecture, ) @register_model('lstm') class LSTMModel(FairseqModel): def __init__(self, encoder, decoder): super().__init__(encoder, decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-hidden-size', type=int, metavar='N', help='encoder hidden size') parser.add_argument('--encoder-layers', type=int, metavar='N', help='number of encoder layers') parser.add_argument('--encoder-bidirectional', action='store_true', help='make all layers of encoder bidirectional') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-embed-path', type=str, metavar='STR', help='path to pre-trained decoder embedding') parser.add_argument('--decoder-hidden-size', type=int, metavar='N', help='decoder hidden size') parser.add_argument('--decoder-layers', type=int, metavar='N', help='number of decoder layers') parser.add_argument('--decoder-out-embed-dim', type=int, metavar='N', help='decoder output embedding dimension') parser.add_argument('--decoder-attention', type=str, metavar='BOOL', help='decoder attention') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion') # Granular dropout settings (if not specified these default to --dropout) parser.add_argument('--encoder-dropout-in', type=float, metavar='D', help='dropout probability for encoder input embedding') parser.add_argument('--encoder-dropout-out', type=float, metavar='D', help='dropout probability for encoder output') parser.add_argument('--decoder-dropout-in', type=float, metavar='D', help='dropout probability for decoder input embedding') parser.add_argument('--decoder-dropout-out', type=float, metavar='D', help='dropout probability for decoder output') parser.add_argument('--share-decoder-input-output-embed', default=False, action='store_true', help='share decoder input and output embeddings') parser.add_argument('--share-all-embeddings', default=False, action='store_true', help='share encoder, decoder and output embeddings' ' (requires shared dictionary and embed dim)') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure that all args are properly defaulted (in case there are any new ones) base_architecture(args) def load_pretrained_embedding_from_file(embed_path, dictionary, embed_dim): num_embeddings = len(dictionary) padding_idx = dictionary.pad() embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) embed_dict = utils.parse_embedding(embed_path) utils.print_embed_overlap(embed_dict, dictionary) return utils.load_embedding(embed_dict, dictionary, embed_tokens) if args.encoder_embed_path: pretrained_encoder_embed = load_pretrained_embedding_from_file( args.encoder_embed_path, task.source_dictionary, args.encoder_embed_dim) else: num_embeddings = len(task.source_dictionary) pretrained_encoder_embed = Embedding( num_embeddings, args.encoder_embed_dim, task.source_dictionary.pad() ) if args.share_all_embeddings: # double check all parameters combinations are valid if task.source_dictionary != task.target_dictionary: raise RuntimeError('--share-all-embeddings requires a joint dictionary') if args.decoder_embed_path and ( args.decoder_embed_path != args.encoder_embed_path): raise RuntimeError( '--share-all-embed not compatible with --decoder-embed-path' ) if args.encoder_embed_dim != args.decoder_embed_dim: raise RuntimeError( '--share-all-embeddings requires --encoder-embed-dim to ' 'match --decoder-embed-dim' ) pretrained_decoder_embed = pretrained_encoder_embed args.share_decoder_input_output_embed = True else: # separate decoder input embeddings pretrained_decoder_embed = None if args.decoder_embed_path: pretrained_decoder_embed = load_pretrained_embedding_from_file( args.decoder_embed_path, task.target_dictionary, args.decoder_embed_dim ) # one last double check of parameter combinations if args.share_decoder_input_output_embed and ( args.decoder_embed_dim != args.decoder_out_embed_dim): raise RuntimeError( '--share-decoder-input-output-embeddings requires ' '--decoder-embed-dim to match --decoder-out-embed-dim' ) encoder = LSTMEncoder( dictionary=task.source_dictionary, embed_dim=args.encoder_embed_dim, hidden_size=args.encoder_hidden_size, num_layers=args.encoder_layers, dropout_in=args.encoder_dropout_in, dropout_out=args.encoder_dropout_out, bidirectional=args.encoder_bidirectional, pretrained_embed=pretrained_encoder_embed, ) decoder = LSTMDecoder( dictionary=task.target_dictionary, embed_dim=args.decoder_embed_dim, hidden_size=args.decoder_hidden_size, out_embed_dim=args.decoder_out_embed_dim, num_layers=args.decoder_layers, dropout_in=args.decoder_dropout_in, dropout_out=args.decoder_dropout_out, attention=options.eval_bool(args.decoder_attention), encoder_embed_dim=args.encoder_embed_dim, encoder_output_units=encoder.output_units, pretrained_embed=pretrained_decoder_embed, share_input_output_embed=args.share_decoder_input_output_embed, adaptive_softmax_cutoff=( options.eval_str_list(args.adaptive_softmax_cutoff, type=int) if args.criterion == 'adaptive_loss' else None ), ) return cls(encoder, decoder) class LSTMEncoder(FairseqEncoder): """LSTM encoder.""" def __init__( self, dictionary, embed_dim=512, hidden_size=512, num_layers=1, dropout_in=0.1, dropout_out=0.1, bidirectional=False, left_pad=True, pretrained_embed=None, padding_value=0., ): super().__init__(dictionary) self.num_layers = num_layers self.dropout_in = dropout_in self.dropout_out = dropout_out self.bidirectional = bidirectional self.hidden_size = hidden_size num_embeddings = len(dictionary) self.padding_idx = dictionary.pad() if pretrained_embed is None: self.embed_tokens = Embedding(num_embeddings, embed_dim, self.padding_idx) else: self.embed_tokens = pretrained_embed self.lstm = LSTM( input_size=embed_dim, hidden_size=hidden_size, num_layers=num_layers, dropout=self.dropout_out if num_layers > 1 else 0., bidirectional=bidirectional, ) self.left_pad = left_pad self.padding_value = padding_value self.output_units = hidden_size if bidirectional: self.output_units *= 2 def forward(self, src_tokens, src_lengths): if self.left_pad: # convert left-padding to right-padding src_tokens = utils.convert_padding_direction( src_tokens, self.padding_idx, left_to_right=True, ) bsz, seqlen = src_tokens.size() # embed tokens x = self.embed_tokens(src_tokens) x = F.dropout(x, p=self.dropout_in, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) # pack embedded source tokens into a PackedSequence packed_x = nn.utils.rnn.pack_padded_sequence(x, src_lengths.data.tolist()) # apply LSTM if self.bidirectional: state_size = 2 * self.num_layers, bsz, self.hidden_size else: state_size = self.num_layers, bsz, self.hidden_size h0 = x.data.new(*state_size).zero_() c0 = x.data.new(*state_size).zero_() packed_outs, (final_hiddens, final_cells) = self.lstm(packed_x, (h0, c0)) # unpack outputs and apply dropout x, _ = nn.utils.rnn.pad_packed_sequence(packed_outs, padding_value=self.padding_value) x = F.dropout(x, p=self.dropout_out, training=self.training) assert list(x.size()) == [seqlen, bsz, self.output_units] if self.bidirectional: def combine_bidir(outs): return outs.view(self.num_layers, 2, bsz, -1).transpose(1, 2).contiguous().view(self.num_layers, bsz, -1) final_hiddens = combine_bidir(final_hiddens) final_cells = combine_bidir(final_cells) encoder_padding_mask = src_tokens.eq(self.padding_idx).t() return { 'encoder_out': (x, final_hiddens, final_cells), 'encoder_padding_mask': encoder_padding_mask if encoder_padding_mask.any() else None } def reorder_encoder_out(self, encoder_out, new_order): encoder_out['encoder_out'] = tuple( eo.index_select(1, new_order) for eo in encoder_out['encoder_out'] ) if encoder_out['encoder_padding_mask'] is not None: encoder_out['encoder_padding_mask'] = \ encoder_out['encoder_padding_mask'].index_select(1, new_order) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" return int(1e5) # an arbitrary large number class AttentionLayer(nn.Module): def __init__(self, input_embed_dim, output_embed_dim): super().__init__() self.input_proj = Linear(input_embed_dim, output_embed_dim, bias=False) self.output_proj = Linear(input_embed_dim + output_embed_dim, output_embed_dim, bias=False) def forward(self, input, source_hids, encoder_padding_mask): # input: bsz x input_embed_dim # source_hids: srclen x bsz x output_embed_dim # x: bsz x output_embed_dim x = self.input_proj(input) # compute attention attn_scores = (source_hids * x.unsqueeze(0)).sum(dim=2) # don't attend over padding if encoder_padding_mask is not None: attn_scores = attn_scores.float().masked_fill_( encoder_padding_mask, float('-inf') ).type_as(attn_scores) # FP16 support: cast to float and back attn_scores = F.softmax(attn_scores, dim=0) # srclen x bsz # sum weighted sources x = (attn_scores.unsqueeze(2) * source_hids).sum(dim=0) x = F.tanh(self.output_proj(torch.cat((x, input), dim=1))) return x, attn_scores class LSTMDecoder(FairseqIncrementalDecoder): """LSTM decoder.""" def __init__( self, dictionary, embed_dim=512, hidden_size=512, out_embed_dim=512, num_layers=1, dropout_in=0.1, dropout_out=0.1, attention=True, encoder_embed_dim=512, encoder_output_units=512, pretrained_embed=None, share_input_output_embed=False, adaptive_softmax_cutoff=None, ): super().__init__(dictionary) self.dropout_in = dropout_in self.dropout_out = dropout_out self.hidden_size = hidden_size self.share_input_output_embed = share_input_output_embed self.need_attn = True self.adaptive_softmax = None num_embeddings = len(dictionary) padding_idx = dictionary.pad() if pretrained_embed is None: self.embed_tokens = Embedding(num_embeddings, embed_dim, padding_idx) else: self.embed_tokens = pretrained_embed self.encoder_output_units = encoder_output_units assert encoder_output_units == hidden_size, \ 'encoder_output_units ({}) != hidden_size ({})'.format(encoder_output_units, hidden_size) # TODO another Linear layer if not equal self.layers = nn.ModuleList([ LSTMCell( input_size=encoder_output_units + embed_dim if layer == 0 else hidden_size, hidden_size=hidden_size, ) for layer in range(num_layers) ]) self.attention = AttentionLayer(encoder_output_units, hidden_size) if attention else None if hidden_size != out_embed_dim: self.additional_fc = Linear(hidden_size, out_embed_dim) if adaptive_softmax_cutoff is not None: # setting adaptive_softmax dropout to dropout_out for now but can be redefined self.adaptive_softmax = AdaptiveSoftmax(num_embeddings, embed_dim, adaptive_softmax_cutoff, dropout=dropout_out) elif not self.share_input_output_embed: self.fc_out = Linear(out_embed_dim, num_embeddings, dropout=dropout_out) def forward(self, prev_output_tokens, encoder_out_dict, incremental_state=None): encoder_out = encoder_out_dict['encoder_out'] encoder_padding_mask = encoder_out_dict['encoder_padding_mask'] if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] bsz, seqlen = prev_output_tokens.size() # get outputs from encoder encoder_outs, _, _ = encoder_out[:3] srclen = encoder_outs.size(0) # embed tokens x = self.embed_tokens(prev_output_tokens) x = F.dropout(x, p=self.dropout_in, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) # initialize previous states (or get from cache during incremental generation) cached_state = utils.get_incremental_state(self, incremental_state, 'cached_state') if cached_state is not None: prev_hiddens, prev_cells, input_feed = cached_state else: _, encoder_hiddens, encoder_cells = encoder_out[:3] num_layers = len(self.layers) prev_hiddens = [encoder_hiddens[i] for i in range(num_layers)] prev_cells = [encoder_cells[i] for i in range(num_layers)] input_feed = x.data.new(bsz, self.encoder_output_units).zero_() attn_scores = x.data.new(srclen, seqlen, bsz).zero_() outs = [] for j in range(seqlen): # input feeding: concatenate context vector from previous time step input = torch.cat((x[j, :, :], input_feed), dim=1) for i, rnn in enumerate(self.layers): # recurrent cell hidden, cell = rnn(input, (prev_hiddens[i], prev_cells[i])) # hidden state becomes the input to the next layer input = F.dropout(hidden, p=self.dropout_out, training=self.training) # save state for next time step prev_hiddens[i] = hidden prev_cells[i] = cell # apply attention using the last layer's hidden state if self.attention is not None: out, attn_scores[:, j, :] = self.attention(hidden, encoder_outs, encoder_padding_mask) else: out = hidden out = F.dropout(out, p=self.dropout_out, training=self.training) # input feeding input_feed = out # save final output outs.append(out) # cache previous states (no-op except during incremental generation) utils.set_incremental_state( self, incremental_state, 'cached_state', (prev_hiddens, prev_cells, input_feed)) # collect outputs across time steps x = torch.cat(outs, dim=0).view(seqlen, bsz, self.hidden_size) # T x B x C -> B x T x C x = x.transpose(1, 0) # srclen x tgtlen x bsz -> bsz x tgtlen x srclen if not self.training and self.need_attn: attn_scores = attn_scores.transpose(0, 2) else: attn_scores = None # project back to size of vocabulary if self.adaptive_softmax is None: if hasattr(self, 'additional_fc'): x = self.additional_fc(x) x = F.dropout(x, p=self.dropout_out, training=self.training) if self.share_input_output_embed: x = F.linear(x, self.embed_tokens.weight) else: x = self.fc_out(x) return x, attn_scores def reorder_incremental_state(self, incremental_state, new_order): super().reorder_incremental_state(incremental_state, new_order) cached_state = utils.get_incremental_state(self, incremental_state, 'cached_state') if cached_state is None: return def reorder_state(state): if isinstance(state, list): return [reorder_state(state_i) for state_i in state] return state.index_select(0, new_order) new_state = tuple(map(reorder_state, cached_state)) utils.set_incremental_state(self, incremental_state, 'cached_state', new_state) def max_positions(self): """Maximum output length supported by the decoder.""" return int(1e5) # an arbitrary large number def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) nn.init.uniform_(m.weight, -0.1, 0.1) nn.init.constant_(m.weight[padding_idx], 0) return m def LSTM(input_size, hidden_size, **kwargs): m = nn.LSTM(input_size, hidden_size, **kwargs) for name, param in m.named_parameters(): if 'weight' in name or 'bias' in name: param.data.uniform_(-0.1, 0.1) return m def LSTMCell(input_size, hidden_size, **kwargs): m = nn.LSTMCell(input_size, hidden_size, **kwargs) for name, param in m.named_parameters(): if 'weight' in name or 'bias' in name: param.data.uniform_(-0.1, 0.1) return m def Linear(in_features, out_features, bias=True, dropout=0): """Linear layer (input: N x T x C)""" m = nn.Linear(in_features, out_features, bias=bias) m.weight.data.uniform_(-0.1, 0.1) if bias: m.bias.data.uniform_(-0.1, 0.1) return m @register_model_architecture('lstm', 'lstm') def base_architecture(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_hidden_size = getattr(args, 'encoder_hidden_size', args.encoder_embed_dim) args.encoder_layers = getattr(args, 'encoder_layers', 1) args.encoder_bidirectional = getattr(args, 'encoder_bidirectional', False) args.encoder_dropout_in = getattr(args, 'encoder_dropout_in', args.dropout) args.encoder_dropout_out = getattr(args, 'encoder_dropout_out', args.dropout) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_hidden_size = getattr(args, 'decoder_hidden_size', args.decoder_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 1) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 512) args.decoder_attention = getattr(args, 'decoder_attention', '1') args.decoder_dropout_in = getattr(args, 'decoder_dropout_in', args.dropout) args.decoder_dropout_out = getattr(args, 'decoder_dropout_out', args.dropout) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', False) args.share_all_embeddings = getattr(args, 'share_all_embeddings', False) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', '10000,50000,200000') @register_model_architecture('lstm', 'lstm_wiseman_iwslt_de_en') def lstm_wiseman_iwslt_de_en(args): args.dropout = getattr(args, 'dropout', 0.1) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 256) args.encoder_dropout_in = getattr(args, 'encoder_dropout_in', 0) args.encoder_dropout_out = getattr(args, 'encoder_dropout_out', 0) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 256) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 256) args.decoder_dropout_in = getattr(args, 'decoder_dropout_in', 0) args.decoder_dropout_out = getattr(args, 'decoder_dropout_out', args.dropout) base_architecture(args) @register_model_architecture('lstm', 'lstm_luong_wmt_en_de') def lstm_luong_wmt_en_de(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1000) args.encoder_layers = getattr(args, 'encoder_layers', 4) args.encoder_dropout_out = getattr(args, 'encoder_dropout_out', 0) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1000) args.decoder_layers = getattr(args, 'decoder_layers', 4) args.decoder_out_embed_dim = getattr(args, 'decoder_out_embed_dim', 1000) args.decoder_dropout_out = getattr(args, 'decoder_dropout_out', 0) base_architecture(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/models/transformer.py
Python
# Modified by Zhuohan Li in May 2019 for macaron-net # # Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq import options from fairseq import utils from fairseq.modules import ( AdaptiveSoftmax, CharacterTokenEmbedder, LearnedPositionalEmbedding, MultiheadAttention, SinusoidalPositionalEmbedding ) from . import ( FairseqIncrementalDecoder, FairseqEncoder, FairseqLanguageModel, FairseqModel, register_model, register_model_architecture, ) @register_model('transformer') class TransformerModel(FairseqModel): """ Transformer model from `"Attention Is All You Need" (Vaswani, et al, 2017) <https://arxiv.org/abs/1706.03762>`_. Args: encoder (TransformerEncoder): the encoder decoder (TransformerDecoder): the decoder The Transformer model provides the following named architectures and command-line arguments: .. argparse:: :ref: fairseq.models.transformer_parser :prog: """ def __init__(self, encoder, decoder): super().__init__(encoder, decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--encoder-embed-path', type=str, metavar='STR', help='path to pre-trained encoder embedding') parser.add_argument('--encoder-embed-dim', type=int, metavar='N', help='encoder embedding dimension') parser.add_argument('--encoder-ffn-embed-dim', type=int, metavar='N', help='encoder embedding dimension for FFN') parser.add_argument('--encoder-layers', type=int, metavar='N', help='num encoder layers') parser.add_argument('--encoder-attention-heads', type=int, metavar='N', help='num encoder attention heads') parser.add_argument('--encoder-normalize-before', action='store_true', help='apply layernorm before each encoder block') parser.add_argument('--encoder-learned-pos', action='store_true', help='use learned positional embeddings in the encoder') parser.add_argument('--decoder-embed-path', type=str, metavar='STR', help='path to pre-trained decoder embedding') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N', help='decoder embedding dimension for FFN') parser.add_argument('--decoder-layers', type=int, metavar='N', help='num decoder layers') parser.add_argument('--decoder-attention-heads', type=int, metavar='N', help='num decoder attention heads') parser.add_argument('--decoder-learned-pos', action='store_true', help='use learned positional embeddings in the decoder') parser.add_argument('--decoder-normalize-before', action='store_true', help='apply layernorm before each decoder block') parser.add_argument('--share-decoder-input-output-embed', action='store_true', help='share decoder input and output embeddings') parser.add_argument('--share-all-embeddings', action='store_true', help='share encoder, decoder and output embeddings' ' (requires shared dictionary and embed dim)') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion'), parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') parser.add_argument('--macaron', action='store_true', help='use the macaron network') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_architecture(args) if not hasattr(args, 'max_source_positions'): args.max_source_positions = 1024 if not hasattr(args, 'max_target_positions'): args.max_target_positions = 1024 src_dict, tgt_dict = task.source_dictionary, task.target_dictionary def build_embedding(dictionary, embed_dim, path=None): num_embeddings = len(dictionary) padding_idx = dictionary.pad() emb = Embedding(num_embeddings, embed_dim, padding_idx) # if provided, load from preloaded dictionaries if path: embed_dict = utils.parse_embedding(path) utils.load_embedding(embed_dict, dictionary, emb) return emb if args.share_all_embeddings: if src_dict != tgt_dict: raise RuntimeError('--share-all-embeddings requires a joined dictionary') if args.encoder_embed_dim != args.decoder_embed_dim: raise RuntimeError( '--share-all-embeddings requires --encoder-embed-dim to match --decoder-embed-dim') if args.decoder_embed_path and ( args.decoder_embed_path != args.encoder_embed_path): raise RuntimeError('--share-all-embeddings not compatible with --decoder-embed-path') encoder_embed_tokens = build_embedding( src_dict, args.encoder_embed_dim, args.encoder_embed_path ) decoder_embed_tokens = encoder_embed_tokens args.share_decoder_input_output_embed = True else: encoder_embed_tokens = build_embedding( src_dict, args.encoder_embed_dim, args.encoder_embed_path ) decoder_embed_tokens = build_embedding( tgt_dict, args.decoder_embed_dim, args.decoder_embed_path ) encoder = TransformerEncoder(args, src_dict, encoder_embed_tokens) decoder = TransformerDecoder(args, tgt_dict, decoder_embed_tokens) return TransformerModel(encoder, decoder) @register_model('transformer_lm') class TransformerLanguageModel(FairseqLanguageModel): def __init__(self, decoder): super().__init__(decoder) @staticmethod def add_args(parser): """Add model-specific arguments to the parser.""" parser.add_argument('--dropout', default=0.1, type=float, metavar='D', help='dropout probability') parser.add_argument('--attention-dropout', default=0., type=float, metavar='D', help='dropout probability for attention weights') parser.add_argument('--relu-dropout', default=0., type=float, metavar='D', help='dropout probability after ReLU in FFN') parser.add_argument('--decoder-embed-dim', type=int, metavar='N', help='decoder embedding dimension') parser.add_argument('--decoder-output-dim', type=int, metavar='N', help='decoder output dimension') parser.add_argument('--decoder-input-dim', type=int, metavar='N', help='decoder input dimension') parser.add_argument('--decoder-ffn-embed-dim', type=int, metavar='N', help='decoder embedding dimension for FFN') parser.add_argument('--decoder-layers', type=int, metavar='N', help='num decoder layers') parser.add_argument('--decoder-attention-heads', type=int, metavar='N', help='num decoder attention heads') parser.add_argument('--decoder-normalize-before', default=False, action='store_true', help='apply layernorm before each decoder block') parser.add_argument('--adaptive-softmax-cutoff', metavar='EXPR', help='comma separated list of adaptive softmax cutoff points. ' 'Must be used with adaptive_loss criterion') parser.add_argument('--adaptive-softmax-dropout', type=float, metavar='D', help='sets adaptive softmax dropout for the tail projections') parser.add_argument('--no-token-positional-embeddings', default=False, action='store_true', help='if set, disables positional embeddings (outside self attention)') parser.add_argument('--share-decoder-input-output-embed', default=False, action='store_true', help='share decoder input and output embeddings') parser.add_argument('--character-embeddings', default=False, action='store_true', help='if set, uses character embedding convolutions to produce token embeddings') parser.add_argument('--character-filters', type=str, metavar='LIST', default='[(1, 64), (2, 128), (3, 192), (4, 256), (5, 256), (6, 256), (7, 256)]', help='size of character embeddings') parser.add_argument('--character-embedding-dim', type=int, metavar='N', default=4, help='size of character embeddings') parser.add_argument('--char-embedder-highway-layers', type=int, metavar='N', default=2, help='number of highway layers for character token embeddder') @classmethod def build_model(cls, args, task): """Build a new model instance.""" # make sure all arguments are present in older models base_lm_architecture(args) if not hasattr(args, 'max_source_positions'): args.max_source_positions = args.tokens_per_sample if not hasattr(args, 'max_target_positions'): args.max_target_positions = args.tokens_per_sample if args.character_embeddings: embed_tokens = CharacterTokenEmbedder(task.dictionary, eval(args.character_filters), args.character_embedding_dim, args.decoder_embed_dim, args.char_embedder_highway_layers, ) else: embed_tokens = Embedding(len(task.dictionary), args.decoder_input_dim, task.dictionary.pad()) decoder = TransformerDecoder(args, task.output_dictionary, embed_tokens, no_encoder_attn=True, final_norm=False) return TransformerLanguageModel(decoder) class TransformerEncoder(FairseqEncoder): """ Transformer encoder consisting of *args.encoder_layers* layers. Each layer is a :class:`TransformerEncoderLayer`. Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): encoding dictionary embed_tokens (torch.nn.Embedding): input embedding left_pad (bool, optional): whether the input is left-padded. Default: ``True`` """ def __init__(self, args, dictionary, embed_tokens, left_pad=True): super().__init__(dictionary) self.dropout = args.dropout embed_dim = embed_tokens.embedding_dim self.padding_idx = embed_tokens.padding_idx self.max_source_positions = args.max_source_positions self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim) self.embed_positions = PositionalEmbedding( args.max_source_positions, embed_dim, self.padding_idx, left_pad=left_pad, learned=args.encoder_learned_pos, ) if not args.no_token_positional_embeddings else None self.layers = nn.ModuleList([]) self.layers.extend([ TransformerEncoderLayer(args) for i in range(args.encoder_layers) ]) self.register_buffer('version', torch.Tensor([2])) self.normalize = args.encoder_normalize_before if self.normalize: self.layer_norm = LayerNorm(embed_dim) def forward(self, src_tokens, src_lengths): """ Args: src_tokens (LongTensor): tokens in the source language of shape `(batch, src_len)` src_lengths (torch.LongTensor): lengths of each source sentence of shape `(batch)` Returns: dict: - **encoder_out** (Tensor): the last encoder layer's output of shape `(src_len, batch, embed_dim)` - **encoder_padding_mask** (ByteTensor): the positions of padding elements of shape `(batch, src_len)` """ # embed tokens and positions x = self.embed_scale * self.embed_tokens(src_tokens) if self.embed_positions is not None: x += self.embed_positions(src_tokens) x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) # compute padding mask encoder_padding_mask = src_tokens.eq(self.padding_idx) if not encoder_padding_mask.any(): encoder_padding_mask = None # encoder layers for layer in self.layers: x = layer(x, encoder_padding_mask) if self.normalize: x = self.layer_norm(x) return { 'encoder_out': x, # T x B x C 'encoder_padding_mask': encoder_padding_mask, # B x T } def reorder_encoder_out(self, encoder_out, new_order): """ Reorder encoder output according to *new_order*. Args: encoder_out: output from the ``forward()`` method new_order (LongTensor): desired order Returns: *encoder_out* rearranged according to *new_order* """ if encoder_out['encoder_out'] is not None: encoder_out['encoder_out'] = \ encoder_out['encoder_out'].index_select(1, new_order) if encoder_out['encoder_padding_mask'] is not None: encoder_out['encoder_padding_mask'] = \ encoder_out['encoder_padding_mask'].index_select(0, new_order) return encoder_out def max_positions(self): """Maximum input length supported by the encoder.""" if self.embed_positions is None: return self.max_source_positions return min(self.max_source_positions, self.embed_positions.max_positions()) def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): if 'encoder.embed_positions.weights' in state_dict: del state_dict['encoder.embed_positions.weights'] state_dict['encoder.embed_positions._float_tensor'] = torch.FloatTensor(1) if utils.item(state_dict.get('encoder.version', torch.Tensor([1]))[0]) < 2: # earlier checkpoints did not normalize after the stack of layers self.layer_norm = None self.normalize = False state_dict['encoder.version'] = torch.Tensor([1]) return state_dict class TransformerDecoder(FairseqIncrementalDecoder): """ Transformer decoder consisting of *args.decoder_layers* layers. Each layer is a :class:`TransformerDecoderLayer`. Args: args (argparse.Namespace): parsed command-line arguments dictionary (~fairseq.data.Dictionary): decoding dictionary embed_tokens (torch.nn.Embedding): output embedding no_encoder_attn (bool, optional): whether to attend to encoder outputs. Default: ``False`` left_pad (bool, optional): whether the input is left-padded. Default: ``False`` """ def __init__(self, args, dictionary, embed_tokens, no_encoder_attn=False, left_pad=False, final_norm=True): super().__init__(dictionary) self.dropout = args.dropout self.share_input_output_embed = args.share_decoder_input_output_embed input_embed_dim = embed_tokens.embedding_dim embed_dim = args.decoder_embed_dim output_embed_dim = args.decoder_output_dim padding_idx = embed_tokens.padding_idx self.max_target_positions = args.max_target_positions self.embed_tokens = embed_tokens self.embed_scale = math.sqrt(embed_dim) # todo: try with input_embed_dim self.project_in_dim = Linear(input_embed_dim, embed_dim, bias=False, uniform=False) if embed_dim != input_embed_dim else None self.embed_positions = PositionalEmbedding( args.max_target_positions, embed_dim, padding_idx, left_pad=left_pad, learned=args.decoder_learned_pos, ) if not args.no_token_positional_embeddings else None self.layers = nn.ModuleList([]) self.layers.extend([ TransformerDecoderLayer(args, no_encoder_attn) for _ in range(args.decoder_layers) ]) self.adaptive_softmax = None self.project_out_dim = Linear(embed_dim, output_embed_dim, bias=False, uniform=False) if embed_dim != output_embed_dim else None if args.adaptive_softmax_cutoff is not None: self.adaptive_softmax = AdaptiveSoftmax( len(dictionary), output_embed_dim, options.eval_str_list(args.adaptive_softmax_cutoff, type=int), dropout=args.adaptive_softmax_dropout, ) elif not self.share_input_output_embed: self.embed_out = nn.Parameter(torch.Tensor(len(dictionary), output_embed_dim)) nn.init.normal_(self.embed_out, mean=0, std=output_embed_dim ** -0.5) self.register_buffer('version', torch.Tensor([2])) self.normalize = args.decoder_normalize_before and final_norm if self.normalize: self.layer_norm = LayerNorm(embed_dim) def forward(self, prev_output_tokens, encoder_out=None, incremental_state=None): """ Args: prev_output_tokens (LongTensor): previous decoder outputs of shape `(batch, tgt_len)`, for input feeding/teacher forcing encoder_out (Tensor, optional): output from the encoder, used for encoder-side attention incremental_state (dict): dictionary used for storing state during :ref:`Incremental decoding` Returns: tuple: - the last decoder layer's output of shape `(batch, tgt_len, vocab)` - the last decoder layer's attention weights of shape `(batch, tgt_len, src_len)` """ # embed positions positions = self.embed_positions( prev_output_tokens, incremental_state=incremental_state, ) if self.embed_positions is not None else None if incremental_state is not None: prev_output_tokens = prev_output_tokens[:, -1:] if positions is not None: positions = positions[:, -1:] # embed tokens and positions x = self.embed_scale * self.embed_tokens(prev_output_tokens) if self.project_in_dim is not None: x = self.project_in_dim(x) if positions is not None: x += positions x = F.dropout(x, p=self.dropout, training=self.training) # B x T x C -> T x B x C x = x.transpose(0, 1) attn = None inner_states = [x] # decoder layers for layer in self.layers: x, attn = layer( x, encoder_out['encoder_out'] if encoder_out is not None else None, encoder_out['encoder_padding_mask'] if encoder_out is not None else None, incremental_state, self_attn_mask=self.buffered_future_mask(x) if incremental_state is None else None, ) inner_states.append(x) if self.normalize: x = self.layer_norm(x) # T x B x C -> B x T x C x = x.transpose(0, 1) if self.project_out_dim is not None: x = self.project_out_dim(x) if self.adaptive_softmax is None: # project back to size of vocabulary if self.share_input_output_embed: x = F.linear(x, self.embed_tokens.weight) else: x = F.linear(x, self.embed_out) return x, {'attn': attn, 'inner_states': inner_states} def max_positions(self): """Maximum output length supported by the decoder.""" if self.embed_positions is None: return self.max_target_positions return min(self.max_target_positions, self.embed_positions.max_positions()) def buffered_future_mask(self, tensor): dim = tensor.size(0) if not hasattr(self, '_future_mask') or self._future_mask is None or self._future_mask.device != tensor.device: self._future_mask = torch.triu(utils.fill_with_neg_inf(tensor.new(dim, dim)), 1) if self._future_mask.size(0) < dim: self._future_mask = torch.triu(utils.fill_with_neg_inf(self._future_mask.resize_(dim, dim)), 1) return self._future_mask[:dim, :dim] def upgrade_state_dict(self, state_dict): """Upgrade a (possibly old) state dict for new versions of fairseq.""" if isinstance(self.embed_positions, SinusoidalPositionalEmbedding): if 'decoder.embed_positions.weights' in state_dict: del state_dict['decoder.embed_positions.weights'] state_dict['decoder.embed_positions._float_tensor'] = torch.FloatTensor(1) for i in range(len(self.layers)): # update layer norms layer_norm_map = { '0': 'self_attn_layer_norm', '1': 'encoder_attn_layer_norm', '2': 'final_layer_norm' } for old, new in layer_norm_map.items(): for m in ('weight', 'bias'): k = 'decoder.layers.{}.layer_norms.{}.{}'.format(i, old, m) if k in state_dict: state_dict['decoder.layers.{}.{}.{}'.format(i, new, m)] = state_dict[k] del state_dict[k] if utils.item(state_dict.get('decoder.version', torch.Tensor([1]))[0]) < 2: # earlier checkpoints did not normalize after the stack of layers self.layer_norm = None self.normalize = False state_dict['decoder.version'] = torch.Tensor([1]) return state_dict class TransformerEncoderLayer(nn.Module): """Encoder layer block. In the original paper each operation (multi-head attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.encoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments """ def __init__(self, args): super().__init__() self.embed_dim = args.encoder_embed_dim self.self_attn = MultiheadAttention( self.embed_dim, args.encoder_attention_heads, dropout=args.attention_dropout, ) self.dropout = args.dropout self.relu_dropout = args.relu_dropout self.normalize_before = args.encoder_normalize_before self.fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim) self.fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim) n_layernorm = 2 self.fc_factor = 1.0 self.macaron = getattr(args, "macaron", False) if self.macaron: self.macaron_fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim) self.macaron_fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim) self.fc_factor = 0.5 n_layernorm += 1 self.layer_norms = nn.ModuleList([LayerNorm(self.embed_dim) for i in range(n_layernorm)]) def forward(self, x, encoder_padding_mask): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. Returns: encoded output of shape `(batch, src_len, embed_dim)` """ if self.macaron: residual = x x = self.maybe_layer_norm(2, x, before=True) x = F.relu(self.macaron_fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.macaron_fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(2, x, after=True) residual = x x = self.maybe_layer_norm(0, x, before=True) x, _ = self.self_attn(query=x, key=x, value=x, key_padding_mask=encoder_padding_mask) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(0, x, after=True) residual = x x = self.maybe_layer_norm(1, x, before=True) x = F.relu(self.fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(1, x, after=True) return x def maybe_layer_norm(self, i, x, before=False, after=False): assert before ^ after if after ^ self.normalize_before: return self.layer_norms[i](x) else: return x class TransformerDecoderLayer(nn.Module): """Decoder layer block. In the original paper each operation (multi-head attention, encoder attention or FFN) is postprocessed with: `dropout -> add residual -> layernorm`. In the tensor2tensor code they suggest that learning is more robust when preprocessing each layer with layernorm and postprocessing with: `dropout -> add residual`. We default to the approach in the paper, but the tensor2tensor approach can be enabled by setting *args.decoder_normalize_before* to ``True``. Args: args (argparse.Namespace): parsed command-line arguments no_encoder_attn (bool, optional): whether to attend to encoder outputs. Default: ``False`` """ def __init__(self, args, no_encoder_attn=False): super().__init__() self.embed_dim = args.decoder_embed_dim self.self_attn = MultiheadAttention( self.embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, ) self.dropout = args.dropout self.relu_dropout = args.relu_dropout self.normalize_before = args.decoder_normalize_before self.self_attn_layer_norm = LayerNorm(self.embed_dim) if no_encoder_attn: self.encoder_attn = None self.encoder_attn_layer_norm = None else: self.encoder_attn = MultiheadAttention( self.embed_dim, args.decoder_attention_heads, dropout=args.attention_dropout, ) self.encoder_attn_layer_norm = LayerNorm(self.embed_dim) self.fc1 = Linear(self.embed_dim, args.decoder_ffn_embed_dim) self.fc2 = Linear(args.decoder_ffn_embed_dim, self.embed_dim) self.fc_factor = 1.0 self.macaron = getattr(args, "macaron", False) if self.macaron: self.macaron_fc1 = Linear(self.embed_dim, args.encoder_ffn_embed_dim) self.macaron_fc2 = Linear(args.encoder_ffn_embed_dim, self.embed_dim) self.macaron_layer_norm = LayerNorm(self.embed_dim) self.fc_factor = 0.5 self.final_layer_norm = LayerNorm(self.embed_dim) self.need_attn = True self.onnx_trace = False def prepare_for_onnx_export_(self): self.onnx_trace = True def forward(self, x, encoder_out, encoder_padding_mask, incremental_state, prev_self_attn_state=None, prev_attn_state=None, self_attn_mask=None, self_attn_padding_mask=None): """ Args: x (Tensor): input to the layer of shape `(seq_len, batch, embed_dim)` encoder_padding_mask (ByteTensor): binary ByteTensor of shape `(batch, src_len)` where padding elements are indicated by ``1``. Returns: encoded output of shape `(batch, src_len, embed_dim)` """ if self.macaron: residual = x x = self.maybe_layer_norm(self.macaron_layer_norm, x, before=True) x = F.relu(self.macaron_fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.macaron_fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(self.macaron_layer_norm, x, after=True) residual = x x = self.maybe_layer_norm(self.self_attn_layer_norm, x, before=True) if prev_self_attn_state is not None: if incremental_state is None: incremental_state = {} prev_key, prev_value = prev_self_attn_state saved_state = {"prev_key": prev_key, "prev_value": prev_value} self.self_attn._set_input_buffer(incremental_state, saved_state) x, _ = self.self_attn( query=x, key=x, value=x, key_padding_mask=self_attn_padding_mask, incremental_state=incremental_state, need_weights=False, attn_mask=self_attn_mask, ) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(self.self_attn_layer_norm, x, after=True) attn = None if self.encoder_attn is not None: residual = x x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, before=True) if prev_attn_state is not None: if incremental_state is None: incremental_state = {} prev_key, prev_value = prev_attn_state saved_state = {"prev_key": prev_key, "prev_value": prev_value} self.encoder_attn._set_input_buffer(incremental_state, saved_state) x, attn = self.encoder_attn( query=x, key=encoder_out, value=encoder_out, key_padding_mask=encoder_padding_mask, incremental_state=incremental_state, static_kv=True, need_weights=(not self.training and self.need_attn), ) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + x x = self.maybe_layer_norm(self.encoder_attn_layer_norm, x, after=True) residual = x x = self.maybe_layer_norm(self.final_layer_norm, x, before=True) x = F.relu(self.fc1(x)) x = F.dropout(x, p=self.relu_dropout, training=self.training) x = self.fc2(x) x = F.dropout(x, p=self.dropout, training=self.training) x = residual + self.fc_factor * x x = self.maybe_layer_norm(self.final_layer_norm, x, after=True) if self.onnx_trace: saved_state = self.self_attn._get_input_buffer(incremental_state) self_attn_state = saved_state["prev_key"], saved_state["prev_value"] return x, attn, self_attn_state return x, attn def maybe_layer_norm(self, layer_norm, x, before=False, after=False): assert before ^ after if after ^ self.normalize_before: return layer_norm(x) else: return x def make_generation_fast_(self, need_attn=False, **kwargs): self.need_attn = need_attn def Embedding(num_embeddings, embedding_dim, padding_idx): m = nn.Embedding(num_embeddings, embedding_dim, padding_idx=padding_idx) nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5) nn.init.constant_(m.weight[padding_idx], 0) return m def LayerNorm(embedding_dim): m = nn.LayerNorm(embedding_dim) return m def Linear(in_features, out_features, bias=True, uniform=True): m = nn.Linear(in_features, out_features, bias) if uniform: nn.init.xavier_uniform_(m.weight) else: nn.init.xavier_normal_(m.weight) if bias: nn.init.constant_(m.bias, 0.) return m def PositionalEmbedding(num_embeddings, embedding_dim, padding_idx, left_pad, learned=False): if learned: m = LearnedPositionalEmbedding(num_embeddings + padding_idx + 1, embedding_dim, padding_idx, left_pad) nn.init.normal_(m.weight, mean=0, std=embedding_dim ** -0.5) nn.init.constant_(m.weight[padding_idx], 0) else: m = SinusoidalPositionalEmbedding(embedding_dim, padding_idx, left_pad, num_embeddings + padding_idx + 1) return m @register_model_architecture('transformer_lm', 'transformer_lm') def base_lm_architecture(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 2048) args.decoder_layers = getattr(args, 'decoder_layers', 6) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False) args.character_embeddings = getattr(args, 'character_embeddings', False) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) # The model training is not stable without this args.decoder_normalize_before = True @register_model_architecture('transformer_lm', 'transformer_lm_big') def transformer_lm_big(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) base_lm_architecture(args) @register_model_architecture('transformer_lm', 'transformer_lm_wiki103') def transformer_lm_wiki103(args): args.dropout = getattr(args, 'dropout', 0.3) transformer_lm_big(args) @register_model_architecture('transformer_lm', 'transformer_lm_gbw') def transformer_lm_gbw(args): args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.dropout = getattr(args, 'dropout', 0.1) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) transformer_lm_big(args) @register_model_architecture('transformer', 'transformer') def base_architecture(args): args.encoder_embed_path = getattr(args, 'encoder_embed_path', None) args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 8) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.encoder_learned_pos = getattr(args, 'encoder_learned_pos', False) args.decoder_embed_path = getattr(args, 'decoder_embed_path', None) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', args.encoder_embed_dim) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', args.encoder_ffn_embed_dim) args.decoder_layers = getattr(args, 'decoder_layers', 6) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 8) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', False) args.decoder_learned_pos = getattr(args, 'decoder_learned_pos', False) args.attention_dropout = getattr(args, 'attention_dropout', 0.) args.relu_dropout = getattr(args, 'relu_dropout', 0.) args.dropout = getattr(args, 'dropout', 0.1) args.adaptive_softmax_cutoff = getattr(args, 'adaptive_softmax_cutoff', None) args.adaptive_softmax_dropout = getattr(args, 'adaptive_softmax_dropout', 0) args.share_decoder_input_output_embed = getattr(args, 'share_decoder_input_output_embed', False) args.share_all_embeddings = getattr(args, 'share_all_embeddings', False) args.no_token_positional_embeddings = getattr(args, 'no_token_positional_embeddings', False) args.decoder_output_dim = getattr(args, 'decoder_output_dim', args.decoder_embed_dim) args.decoder_input_dim = getattr(args, 'decoder_input_dim', args.decoder_embed_dim) @register_model_architecture('transformer', 'transformer_iwslt_de_en') def transformer_iwslt_de_en(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 512) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1024) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 4) args.encoder_layers = getattr(args, 'encoder_layers', 6) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 1024) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 4) args.decoder_layers = getattr(args, 'decoder_layers', 6) base_architecture(args) @register_model_architecture('transformer', 'transformer_iwslt_de_en_macaron') def transformer_iwslt_de_en_macaron(args): args.macaron = getattr(args, 'macaron', True) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 512) transformer_iwslt_de_en(args) @register_model_architecture('transformer', 'transformer_iwslt_de_en_v2') def transformer_iwslt_de_en_v2(args): args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.1) transformer_iwslt_de_en(args) @register_model_architecture('transformer', 'transformer_iwslt_de_en_macaron_v2') def transformer_iwslt_de_en_macaron_v2(args): args.macaron = getattr(args, 'macaron', True) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 512) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 512) transformer_iwslt_de_en_v2(args) @register_model_architecture('transformer', 'transformer_wmt_en_de') def transformer_wmt_en_de(args): base_architecture(args) @register_model_architecture('transformer', 'transformer_wmt_en_de_macaron') def transformer_wmt_en_de_macaron(args): args.macaron = getattr(args, 'macaron', "new") args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 1024) base_architecture(args) @register_model_architecture('transformer', 'transformer_wmt_en_de_v2') def transformer_wmt_en_de_v2(args): args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.1) base_architecture(args) @register_model_architecture('transformer', 'transformer_wmt_en_de_macaron_v2') def transformer_wmt_en_de_macaron_v2(args): args.macaron = getattr(args, 'macaron', "new") args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 1024) transformer_wmt_en_de_v2(args) # parameters used in the "Attention Is All You Need" paper (Vaswani, et al, 2017) @register_model_architecture('transformer', 'transformer_vaswani_wmt_en_de_big') def transformer_vaswani_wmt_en_de_big(args): args.encoder_embed_dim = getattr(args, 'encoder_embed_dim', 1024) args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 4096) args.encoder_attention_heads = getattr(args, 'encoder_attention_heads', 16) args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', False) args.decoder_embed_dim = getattr(args, 'decoder_embed_dim', 1024) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 4096) args.decoder_attention_heads = getattr(args, 'decoder_attention_heads', 16) args.dropout = getattr(args, 'dropout', 0.3) base_architecture(args) @register_model_architecture('transformer', 'transformer_vaswani_wmt_en_fr_big') def transformer_vaswani_wmt_en_fr_big(args): args.dropout = getattr(args, 'dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) @register_model_architecture('transformer', 'transformer_wmt_en_de_big') def transformer_wmt_en_de_big(args): args.attention_dropout = getattr(args, 'attention_dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) # default parameters used in tensor2tensor implementation @register_model_architecture('transformer', 'transformer_wmt_en_de_big_t2t') def transformer_wmt_en_de_big_t2t(args): args.encoder_normalize_before = getattr(args, 'encoder_normalize_before', True) args.decoder_normalize_before = getattr(args, 'decoder_normalize_before', True) args.attention_dropout = getattr(args, 'attention_dropout', 0.1) args.relu_dropout = getattr(args, 'relu_dropout', 0.1) transformer_vaswani_wmt_en_de_big(args) # default parameters used in tensor2tensor implementation @register_model_architecture('transformer', 'transformer_wmt_en_de_big_t2t_macaron') def transformer_wmt_en_de_big_t2t_macaron(args): args.macaron = getattr(args, 'macaron', "new") args.encoder_ffn_embed_dim = getattr(args, 'encoder_ffn_embed_dim', 2048) args.decoder_ffn_embed_dim = getattr(args, 'decoder_ffn_embed_dim', 2048) transformer_wmt_en_de_big_t2t(args)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/__init__.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. from .adaptive_softmax import AdaptiveSoftmax from .beamable_mm import BeamableMM from .character_token_embedder import CharacterTokenEmbedder from .conv_tbc import ConvTBC from .downsampled_multihead_attention import DownsampledMultiHeadAttention from .grad_multiply import GradMultiply from .highway import Highway from .learned_positional_embedding import LearnedPositionalEmbedding from .linearized_convolution import LinearizedConvolution from .multihead_attention import MultiheadAttention from .scalar_bias import ScalarBias from .sinusoidal_positional_embedding import SinusoidalPositionalEmbedding __all__ = [ 'AdaptiveSoftmax', 'BeamableMM', 'CharacterTokenEmbedder', 'ConvTBC', 'DownsampledMultiHeadAttention', 'GradMultiply', 'Highway', 'LearnedPositionalEmbedding', 'LinearizedConvolution', 'MultiheadAttention', 'ScalarBias', 'SinusoidalPositionalEmbedding', ]
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/adaptive_softmax.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn.functional as F from torch import nn class AdaptiveSoftmax(nn.Module): """ This is an implementation of the efficient softmax approximation for graphical processing units (GPU), described in the paper "Efficient softmax approximation for GPUs" (http://arxiv.org/abs/1609.04309). """ def __init__(self, vocab_size, input_dim, cutoff, dropout): super().__init__() if vocab_size > cutoff[-1]: cutoff = cutoff + [vocab_size] else: assert vocab_size == cutoff[ -1], 'cannot specify cutoff larger than vocab size' output_dim = cutoff[0] + len(cutoff) - 1 self.vocab_size = vocab_size self.cutoff = cutoff self.dropout = dropout self.input_dim = input_dim self.lsm = nn.LogSoftmax(dim=1) self.head = nn.Linear(input_dim, output_dim, bias=False) self._make_tail(True) def init_weights(m): if hasattr(m, 'weight'): nn.init.xavier_uniform_(m.weight) self.apply(init_weights) self.register_buffer('version', torch.LongTensor([1])) # versions prior to 1 had a bug that offset indices on the head by 1 self.buggy_offset = 0 def _make_tail(self, fix_exponent): extra_denom = 1 if fix_exponent else 0 self.tail = nn.ModuleList() for i in range(len(self.cutoff) - 1): self.tail.append( nn.Sequential( nn.Linear(self.input_dim, self.input_dim // 4 ** (i + extra_denom), bias=False), nn.Dropout(self.dropout), nn.Linear(self.input_dim // 4 ** (i + extra_denom), self.cutoff[i + 1] - self.cutoff[i], bias=False) ) ) def upgrade_state_dict_named(self, state_dict, name): version_name = name + '.version' if version_name not in state_dict: self.buggy_offset = 1 self._make_tail(False) state_dict[version_name] = torch.LongTensor([1]) def adapt_target(self, target): """ In order to be efficient, the AdaptiveSoftMax does not compute the scores for all the word of the vocabulary for all the examples. It is thus necessary to call the method adapt_target of the AdaptiveSoftMax layer inside each forward pass. """ target = target.view(-1) new_target = [target.clone()] target_idxs = [] for i in range(len(self.cutoff) - 1): mask = target.ge(self.cutoff[i]).mul(target.lt(self.cutoff[i + 1])) new_target[0][mask] = self.cutoff[0] + i - self.buggy_offset if mask.any(): target_idxs.append(mask.nonzero().squeeze(1)) new_target.append(target[mask].add(-self.cutoff[i])) else: target_idxs.append(None) new_target.append(None) return new_target, target_idxs def forward(self, input, target): """ Args: input: (b x t x d) target: (b x t) Returns: 2 lists: output for each cutoff section and new targets by cut off """ input = input.contiguous().view(-1, input.size(-1)) input = F.dropout(input, p=self.dropout, training=self.training) new_target, target_idxs = self.adapt_target(target) output = [self.head(input)] for i in range(len(target_idxs)): if target_idxs[i] is not None: output.append(self.tail[i](input.index_select(0, target_idxs[i]))) else: output.append(None) return output, new_target def get_log_prob(self, input, target): """ Computes the log probabilities for all the words of the vocabulary, given a 2D tensor of hidden vectors. """ bsz, length, dim = input.size() input = input.contiguous().view(-1, dim) if target is not None: _, target_idxs = self.adapt_target(target) else: target_idxs = None head_y = self.head(input) log_probs = head_y.new_zeros(input.size(0), self.vocab_size) head_sz = self.cutoff[0] + len(self.tail) log_probs[:, :head_sz] = self.lsm(head_y) tail_priors = log_probs[:, self.cutoff[0] - self.buggy_offset: head_sz - self.buggy_offset].clone() for i in range(len(self.tail)): start = self.cutoff[i] end = self.cutoff[i + 1] if target_idxs is None: tail_out = log_probs[:, start:end] tail_out.copy_(self.tail[i](input)) log_probs[:, start:end] = self.lsm(tail_out).add_(tail_priors[:, i, None]) elif target_idxs[i] is not None: idxs = target_idxs[i] tail_out = log_probs[idxs, start:end] tail_out.copy_(self.tail[i](input[idxs])) log_probs[idxs, start:end] = self.lsm(tail_out).add_(tail_priors[idxs, i, None]) log_probs = log_probs.view(bsz, length, -1) return log_probs
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/beamable_mm.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn as nn class BeamableMM(nn.Module): """This module provides an optimized MM for beam decoding with attention. It leverage the fact that the source-side of the input is replicated beam times and the target-side of the input is of width one. This layer speeds up inference by replacing the inputs {(bsz x 1 x nhu), (bsz x sz2 x nhu)} with smaller inputs {(bsz/beam x beam x nhu), (bsz/beam x sz2 x nhu)}. """ def __init__(self, beam_size=None): super(BeamableMM, self).__init__() self.beam_size = beam_size def forward(self, input1, input2): if ( not self.training and # test mode self.beam_size is not None and # beam size is set input1.dim() == 3 and # only support batched input input1.size(1) == 1 # single time step update ): bsz, beam = input1.size(0), self.beam_size # bsz x 1 x nhu --> bsz/beam x beam x nhu input1 = input1[:, 0, :].unfold(0, beam, beam).transpose(2, 1) # bsz x sz2 x nhu --> bsz/beam x sz2 x nhu input2 = input2.unfold(0, beam, beam)[:, :, :, 0] # use non batched operation if bsz = beam if input1.size(0) == 1: output = torch.mm(input1[0, :, :], input2[0, :, :]) else: output = input1.bmm(input2) return output.view(bsz, 1, -1) else: return input1.bmm(input2) def set_beam_size(self, beam_size): self.beam_size = beam_size
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/character_token_embedder.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import numpy as np import torch import torch.nn.functional as F from torch import nn from torch.nn.utils.rnn import pad_sequence from typing import List, Tuple from .highway import Highway from fairseq.data import Dictionary class CharacterTokenEmbedder(torch.nn.Module): def __init__( self, vocab: Dictionary, filters: List[Tuple[int, int]], char_embed_dim: int, word_embed_dim: int, highway_layers: int, max_char_len: int = 50, ): super(CharacterTokenEmbedder, self).__init__() self.embedding_dim = word_embed_dim self.char_embeddings = nn.Embedding(257, char_embed_dim, padding_idx=0) self.symbol_embeddings = nn.Parameter(torch.FloatTensor(2, word_embed_dim)) self.eos_idx, self.unk_idx = 0, 1 self.convolutions = nn.ModuleList() for width, out_c in filters: self.convolutions.append( nn.Conv1d(char_embed_dim, out_c, kernel_size=width) ) final_dim = sum(f[1] for f in filters) self.highway = Highway(final_dim, highway_layers) self.projection = nn.Linear(final_dim, word_embed_dim) self.set_vocab(vocab, max_char_len) self.reset_parameters() def set_vocab(self, vocab, max_char_len): word_to_char = torch.LongTensor(len(vocab), max_char_len) truncated = 0 for i in range(len(vocab)): if i < vocab.nspecial: char_idxs = [0] * max_char_len else: chars = vocab[i].encode() # +1 for padding char_idxs = [c + 1 for c in chars] + [0] * (max_char_len - len(chars)) if len(char_idxs) > max_char_len: truncated += 1 char_idxs = char_idxs[:max_char_len] word_to_char[i] = torch.LongTensor(char_idxs) if truncated > 0: print('Truncated {} words longer than {} characters'.format(truncated, max_char_len)) self.vocab = vocab self.word_to_char = word_to_char @property def padding_idx(self): return self.vocab.pad() def reset_parameters(self): nn.init.xavier_normal_(self.char_embeddings.weight) nn.init.xavier_normal_(self.symbol_embeddings) nn.init.xavier_normal_(self.projection.weight) nn.init.constant_(self.char_embeddings.weight[self.char_embeddings.padding_idx], 0.) nn.init.constant_(self.projection.bias, 0.) def forward( self, words: torch.Tensor, ): self.word_to_char = self.word_to_char.type_as(words) flat_words = words.view(-1) word_embs = self._convolve(self.word_to_char[flat_words]) pads = flat_words.eq(self.vocab.pad()) if pads.any(): word_embs[pads] = 0 eos = flat_words.eq(self.vocab.eos()) if eos.any(): word_embs[eos] = self.symbol_embeddings[self.eos_idx] unk = flat_words.eq(self.vocab.unk()) if unk.any(): word_embs[unk] = self.symbol_embeddings[self.unk_idx] return word_embs.view(words.size() + (-1,)) def _convolve( self, char_idxs: torch.Tensor, ): char_embs = self.char_embeddings(char_idxs) char_embs = char_embs.transpose(1, 2) # BTC -> BCT conv_result = [] for i, conv in enumerate(self.convolutions): x = conv(char_embs) x, _ = torch.max(x, -1) x = F.relu(x) conv_result.append(x) conv_result = torch.cat(conv_result, dim=-1) conv_result = self.highway(conv_result) return self.projection(conv_result)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/conv_tbc.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch from torch.nn.modules.utils import _single class ConvTBC(torch.nn.Module): """1D convolution over an input of shape (time x batch x channel) The implementation uses gemm to perform the convolution. This implementation is faster than cuDNN for small kernel sizes. """ def __init__(self, in_channels, out_channels, kernel_size, padding=0): super(ConvTBC, self).__init__() self.in_channels = in_channels self.out_channels = out_channels self.kernel_size = _single(kernel_size) self.padding = _single(padding) self.weight = torch.nn.Parameter(torch.Tensor( self.kernel_size[0], in_channels, out_channels)) self.bias = torch.nn.Parameter(torch.Tensor(out_channels)) def forward(self, input): return torch.conv_tbc(input.contiguous(), self.weight, self.bias, self.padding[0]) def __repr__(self): s = ('{name}({in_channels}, {out_channels}, kernel_size={kernel_size}' ', padding={padding}') if self.bias is None: s += ', bias=False' s += ')' return s.format(name=self.__class__.__name__, **self.__dict__)
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/downsampled_multihead_attention.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. # import math import torch import torch.nn as nn import torch.nn.functional as F from fairseq.modules.scalar_bias import scalar_bias class SingleHeadAttention(nn.Module): """ Single-head attention that supports Gating and Downsampling """ def __init__( self, out_channels, embed_dim, head_dim, head_index, dropout=0., bias=True, project_input=True, gated=False, downsample=False, num_heads=1, ): super().__init__() self.embed_dim = embed_dim self.dropout = dropout self.head_index = head_index self.head_dim = head_dim self.project_input = project_input self.gated = gated self.downsample = downsample self.num_heads = num_heads self.projection = None k_layers = [] v_layers = [] if self.downsample: k_layers.append(Downsample(self.head_index)) v_layers.append(Downsample(self.head_index)) out_proj_size = self.head_dim else: out_proj_size = self.head_dim * self.num_heads if self.gated: k_layers.append(GatedLinear(self.embed_dim, out_proj_size, bias=bias)) self.in_proj_q = GatedLinear(self.embed_dim, out_proj_size, bias=bias) v_layers.append(GatedLinear(self.embed_dim, out_proj_size, bias=bias)) else: k_layers.append(Linear(self.embed_dim, out_proj_size, bias=bias)) self.in_proj_q = Linear(self.embed_dim, out_proj_size, bias=bias) v_layers.append(Linear(self.embed_dim, out_proj_size, bias=bias)) self.in_proj_k = nn.Sequential(*k_layers) self.in_proj_v = nn.Sequential(*v_layers) if self.downsample: self.out_proj = Linear(out_proj_size, self.head_dim, bias=bias) else: self.out_proj = Linear(out_proj_size, out_channels, bias=bias) self.scaling = self.head_dim**-0.5 def forward( self, query, key, value, mask_future_timesteps=False, key_padding_mask=None, use_scalar_bias=False, ): """Input shape: Time x Batch x Channel Self-attention can be implemented by passing in the same arguments for query, key and value. Future timesteps can be masked with the `mask_future_timesteps` argument. Padding elements can be excluded from the key by passing a binary ByteTensor (`key_padding_mask`) with shape: batch x src_len, where padding elements are indicated by 1s. """ src_len, bsz, out_channels = key.size() tgt_len = query.size(0) assert list(query.size()) == [tgt_len, bsz, out_channels] assert key.size() == value.size() if key_padding_mask is not None: assert key_padding_mask.size(0) == bsz assert key_padding_mask.size(1) == src_len if self.downsample: size = bsz else: size = bsz * self.num_heads k = key v = value q = query if self.project_input: q = self.in_proj_q(q) k = self.in_proj_k(k) v = self.in_proj_v(v) src_len = k.size()[0] q *= self.scaling if not self.downsample: q = q.view(tgt_len, size, self.head_dim) k = k.view(src_len, size, self.head_dim) v = v.view(src_len, size, self.head_dim) q = q.transpose(0, 1) k = k.transpose(0, 1) v = v.transpose(0, 1) attn_weights = torch.bmm(q, k.transpose(1, 2)) if mask_future_timesteps: assert query.size() == key.size(), \ 'mask_future_timesteps only applies to self-attention' attn_weights *= torch.tril( attn_weights.data.new([1]).expand(tgt_len, tgt_len).clone(), diagonal=-1, )[:, ::self.head_index + 1 if self.downsample else 1].unsqueeze(0) attn_weights += torch.triu( attn_weights.data.new([-math.inf]).expand(tgt_len, tgt_len).clone(), diagonal=0 )[:, ::self.head_index + 1 if self.downsample else 1].unsqueeze(0) tgt_size = tgt_len if use_scalar_bias: attn_weights = scalar_bias(attn_weights, 2) v = scalar_bias(v, 1) tgt_size += 1 if key_padding_mask is not None: # don't attend to padding symbols if key_padding_mask.max() > 0: if self.downsample: attn_weights = attn_weights.view(bsz, 1, tgt_len, src_len) else: attn_weights = attn_weights.view(size, self.num_heads, tgt_len, src_len) attn_weights = attn_weights.masked_fill( key_padding_mask.unsqueeze(1).unsqueeze(2), -math.inf, ) attn_weights = attn_weights.view(size, tgt_len, src_len) attn_weights = F.softmax(attn_weights, dim=-1) attn_weights = F.dropout(attn_weights, p=self.dropout, training=self.training) attn = torch.bmm(attn_weights, v) if self.downsample: attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, self.head_dim) else: attn = attn.transpose(0, 1).contiguous().view(tgt_len, bsz, self.embed_dim) attn = self.out_proj(attn) return attn, attn_weights class DownsampledMultiHeadAttention(nn.ModuleList): """ Multi-headed attention with Gating and Downsampling """ def __init__( self, out_channels, embed_dim, num_heads, dropout=0., bias=True, project_input=True, gated=False, downsample=False, ): self.embed_dim = embed_dim self.num_heads = num_heads self.dropout = dropout self.head_dim = embed_dim // num_heads self.downsample = downsample self.gated = gated self.project_input = project_input assert self.head_dim * num_heads == embed_dim if self.downsample: attention_heads = [] for index in range(self.num_heads): attention_heads.append( SingleHeadAttention( out_channels, self.embed_dim, self.head_dim, index, self.dropout, bias, self.project_input, self.gated, self.downsample, self.num_heads, ) ) super().__init__(modules=attention_heads) self.out_proj = Linear(embed_dim, out_channels, bias=bias) else: # either we have a list of attention heads, or just one attention head # if not being downsampled, we can do the heads with one linear layer instead of separate ones super().__init__() self.attention_module = SingleHeadAttention( out_channels, self.embed_dim, self.head_dim, 1, self.dropout, bias, self.project_input, self.gated, self.downsample, self.num_heads, ) def forward( self, query, key, value, mask_future_timesteps=False, key_padding_mask=None, use_scalar_bias=False, ): src_len, bsz, embed_dim = key.size() tgt_len = query.size(0) assert embed_dim == self.embed_dim assert list(query.size()) == [tgt_len, bsz, embed_dim] assert key.size() == value.size() tgt_size = tgt_len if use_scalar_bias: tgt_size += 1 attn = [] attn_weights = [] if self.downsample: for attention_head_number in range(self.num_heads): # call the forward of each attention head _attn, _attn_weight = self[attention_head_number]( query, key, value, mask_future_timesteps, key_padding_mask, use_scalar_bias, ) attn.append(_attn) attn_weights.append(_attn_weight) full_attn = torch.cat(attn, dim=2) full_attn = self.out_proj(full_attn) return full_attn, attn_weights[0].clone() else: _attn, _attn_weight = self.attention_module( query, key, value, mask_future_timesteps, key_padding_mask, use_scalar_bias, ) attn.append(_attn) attn_weights.append(_attn_weight) full_attn = torch.cat(attn, dim=2) full_attn_weights = torch.cat(attn_weights) full_attn_weights = full_attn_weights.view(bsz, self.num_heads, tgt_size, src_len) full_attn_weights = full_attn_weights.sum(dim=1) / self.num_heads return full_attn, full_attn_weights class Downsample(nn.Module): """ Selects every nth element, where n is the index """ def __init__(self, index): super().__init__() self.index = index def forward(self, x): return x[::self.index+1] def Linear(in_features, out_features, dropout=0., bias=True): """Weight-normalized Linear layer (input: B x T x C)""" m = nn.Linear(in_features, out_features, bias=bias) m.weight.data.normal_(mean=0, std=math.sqrt((1 - dropout) / in_features)) m.bias.data.zero_() return nn.utils.weight_norm(m) def GatedLinear(in_features, out_features, dropout=0., bias=True): """Weight-normalized Linear layer (input: B x T x C) with interspersed GLU units""" return nn.Sequential( Linear(in_features, out_features*4, dropout, bias), nn.GLU(), Linear(out_features*2, out_features*2, dropout, bias), nn.GLU(), Linear(out_features, out_features, dropout, bias) )
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/grad_multiply.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch class GradMultiply(torch.autograd.Function): @staticmethod def forward(ctx, x, scale): ctx.scale = scale res = x.new(x) return res @staticmethod def backward(ctx, grad): return grad * ctx.scale, None
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/highway.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch import torch.nn.functional as F from torch import nn class Highway(torch.nn.Module): """ A `Highway layer <https://arxiv.org/abs/1505.00387>`_. Adopted from the AllenNLP implementation. """ def __init__( self, input_dim: int, num_layers: int = 1 ): super(Highway, self).__init__() self.input_dim = input_dim self.layers = nn.ModuleList([nn.Linear(input_dim, input_dim * 2) for _ in range(num_layers)]) self.activation = nn.ReLU() self.reset_parameters() def reset_parameters(self): for layer in self.layers: # As per comment in AllenNLP: # We should bias the highway layer to just carry its input forward. We do that by # setting the bias on `B(x)` to be positive, because that means `g` will be biased to # be high, so we will carry the input forward. The bias on `B(x)` is the second half # of the bias vector in each Linear layer. nn.init.constant_(layer.bias[self.input_dim:], 1) nn.init.constant_(layer.bias[:self.input_dim], 0) nn.init.xavier_normal_(layer.weight) def forward( self, x: torch.Tensor ): for layer in self.layers: projection = layer(x) proj_x, gate = projection.chunk(2, dim=-1) proj_x = self.activation(proj_x) gate = F.sigmoid(gate) x = gate * x + (1 - gate) * proj_x return x
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta
translation/fairseq/modules/learned_positional_embedding.py
Python
# Copyright (c) 2017-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the license found in the LICENSE file in # the root directory of this source tree. An additional grant of patent rights # can be found in the PATENTS file in the same directory. import torch.nn as nn from fairseq import utils class LearnedPositionalEmbedding(nn.Embedding): """This module learns positional embeddings up to a fixed maximum size. Padding symbols are ignored, but it is necessary to specify whether padding is added on the left side (left_pad=True) or right side (left_pad=False). """ def __init__(self, num_embeddings, embedding_dim, padding_idx, left_pad): super().__init__(num_embeddings, embedding_dim, padding_idx) self.left_pad = left_pad def forward(self, input, incremental_state=None): """Input is expected to be of size [bsz x seqlen].""" if incremental_state is not None: # positions is the same for every token when decoding a single step positions = input.data.new(1, 1).fill_(self.padding_idx + input.size(1)) else: positions = utils.make_positions(input.data, self.padding_idx, self.left_pad) return super().forward(positions) def max_positions(self): """Maximum number of supported positions.""" return self.num_embeddings - self.padding_idx - 1
zhuohan123/macaron-net
147
Codes for "Understanding and Improving Transformer From a Multi-Particle Dynamic System Point of View"
Python
zhuohan123
Zhuohan Li
vLLM / Meta