def test_cnn_summarization_same_as_fairseq(self):
        model = FlaxBartForConditionalGeneration.from_pretrained("facebook/bart-large-cnn")
        tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")

        FRANCE_ARTICLE = ' Marseille, France (CNN)The French prosecutor leading an investigation into the crash of Germanwings Flight 9525 insisted Wednesday that he was not aware of any video footage from on board the plane. Marseille prosecutor Brice Robin told CNN that "so far no videos were used in the crash investigation." He added, "A person who has such a video needs to immediately give it to the investigators." Robin\'s comments follow claims by two magazines, German daily Bild and French Paris Match, of a cell phone video showing the harrowing final seconds from on board Germanwings Flight 9525 as it crashed into the French Alps. All 150 on board were killed. Paris Match and Bild reported that the video was recovered from a phone at the wreckage site. The two publications described the supposed video, but did not post it on their websites. The publications said that they watched the video, which was found by a source close to the investigation. "One can hear cries of \'My God\' in several languages," Paris Match reported. "Metallic banging can also be heard more than three times, perhaps of the pilot trying to open the cockpit door with a heavy object.  Towards the end, after a heavy shake, stronger than the others, the screaming intensifies. Then nothing." "It is a very disturbing scene," said Julian Reichelt, editor-in-chief of Bild online. An official with France\'s accident investigation agency, the BEA, said the agency is not aware of any such video. Lt. Col. Jean-Marc Menichini, a French Gendarmerie spokesman in charge of communications on rescue efforts around the Germanwings crash site, told CNN that the reports were "completely wrong" and "unwarranted." Cell phones have been collected at the site, he said, but that they "hadn\'t been exploited yet." Menichini said he believed the cell phones would need to be sent to the Criminal Research Institute in Rosny sous-Bois, near Paris, in order to be analyzed by specialized technicians working hand-in-hand with investigators. But none of the cell phones found so far have been sent to the institute, Menichini said. Asked whether staff involved in the search could have leaked a memory card to the media, Menichini answered with a categorical "no." Reichelt told "Erin Burnett: Outfront" that he had watched the video and stood by the report, saying Bild and Paris Match are "very confident" that the clip is real. He noted that investigators only revealed they\'d recovered cell phones from the crash site after Bild and Paris Match published their reports. "That is something we did not know before. ... Overall we can say many things of the investigation weren\'t revealed by the investigation at the beginning," he said. What was mental state of Germanwings co-pilot? German airline Lufthansa confirmed Tuesday that co-pilot Andreas Lubitz had battled depression years before he took the controls of Germanwings Flight 9525, which he\'s accused of deliberately crashing last week in the French Alps. Lubitz told his Lufthansa flight training school in 2009 that he had a "previous episode of severe depression," the airline said Tuesday. Email correspondence between Lubitz and the school discovered in an internal investigation, Lufthansa said, included medical documents he submitted in connection with resuming his flight training. The announcement indicates that Lufthansa, the parent company of Germanwings, knew of Lubitz\'s battle with depression, allowed him to continue training and ultimately put him in the cockpit. Lufthansa, whose CEO Carsten Spohr previously said Lubitz was 100% fit to fly, described its statement Tuesday as a "swift and seamless clarification" and said it was sharing the information and documents -- including training and medical records -- with public prosecutors. Spohr traveled to the crash site Wednesday, where recovery teams have been working for the past week to recover human remains and plane debris scattered across a steep mountainside. He saw the crisis center set up in Seyne-les-Alpes, laid a wreath in the village of Le Vernet, closer to the crash site, where grieving families have left flowers at a simple stone memorial. Menichini told CNN late Tuesday that no visible human remains were left at the site but recovery teams would keep searching. French President Francois Hollande, speaking Tuesday, said that it should be possible to identify all the victims using DNA analysis by the end of the week, sooner than authorities had previously suggested. In the meantime, the recovery of the victims\' personal belongings will start Wednesday, Menichini said. Among those personal belongings could be more cell phones belonging to the 144 passengers and six crew on board. Check out the latest from our correspondents . The details about Lubitz\'s correspondence with the flight school during his training were among several developments as investigators continued to delve into what caused the crash and Lubitz\'s possible motive for downing the jet. A Lufthansa spokesperson told CNN on Tuesday that Lubitz had a valid medical certificate, had passed all his examinations and "held all the licenses required." Earlier, a spokesman for the prosecutor\'s office in Dusseldorf, Christoph Kumpa, said medical records reveal Lubitz suffered from suicidal tendencies at some point before his aviation career and underwent psychotherapy before he got his pilot\'s license. Kumpa emphasized there\'s no evidence suggesting Lubitz was suicidal or acting aggressively before the crash. Investigators are looking into whether Lubitz feared his medical condition would cause him to lose his pilot\'s license, a European government official briefed on the investigation told CNN on Tuesday. While flying was "a big part of his life," the source said, it\'s only one theory being considered. Another source, a law enforcement official briefed on the investigation, also told CNN that authorities believe the primary motive for Lubitz to bring down the plane was that he feared he would not be allowed to fly because of his medical problems. Lubitz\'s girlfriend told investigators he had seen an eye doctor and a neuropsychologist, both of whom deemed him unfit to work recently and concluded he had psychological issues, the European government official said. But no matter what details emerge about his previous mental health struggles, there\'s more to the story, said Brian Russell, a forensic psychologist. "Psychology can explain why somebody would turn rage inward on themselves about the fact that maybe they weren\'t going to keep doing their job and they\'re upset about that and so they\'re suicidal," he said. "But there is no mental illness that explains why somebody then feels entitled to also take that rage and turn it outward on 149 other people who had nothing to do with the person\'s problems." Germanwings crash compensation: What we know . Who was the captain of Germanwings Flight 9525? CNN\'s Margot Haddad reported from Marseille and Pamela Brown from Dusseldorf, while Laura Smith-Spark wrote from London. CNN\'s Frederik Pleitgen, Pamela Boykoff, Antonia Mortensen, Sandrine Amiel and Anna-Maja Rappard contributed to this report.'  # @noq

        SHORTER_ARTICLE = ' (CNN)The Palestinian Authority officially became the 123rd member of the International Criminal Court on Wednesday, a step that gives the court jurisdiction over alleged crimes in Palestinian territories. The formal accession was marked with a ceremony at The Hague, in the Netherlands, where the court is based. The Palestinians signed the ICC\'s founding Rome Statute in January, when they also accepted its jurisdiction over alleged crimes committed "in the occupied Palestinian territory, including East Jerusalem, since June 13, 2014." Later that month, the ICC opened a preliminary examination into the situation in Palestinian territories, paving the way for possible war crimes investigations against Israelis. As members of the court, Palestinians may be subject to counter-charges as well. Israel and the United States, neither of which is an ICC member, opposed the Palestinians\' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki, speaking at Wednesday\'s ceremony, said it was a move toward greater justice. "As Palestine formally becomes a State Party to the Rome Statute today, the world is also a step closer to ending a long era of impunity and injustice," he said, according to an ICC news release. "Indeed, today brings us closer to our shared goals of justice and peace." Judge Kuniko Ozaki, a vice president of the ICC, said acceding to the treaty was just the first step for the Palestinians. "As the Rome Statute today enters into force for the State of Palestine, Palestine acquires all the rights as well as responsibilities that come with being a State Party to the Statute. These are substantive commitments, which cannot be taken lightly," she said. Rights group Human Rights Watch welcomed the development. "Governments seeking to penalize Palestine for joining the ICC should immediately end their pressure, and countries that support universal acceptance of the court\'s treaty should speak out to welcome its membership," said Balkees Jarrah, international justice counsel for the group. "What\'s objectionable is the attempts to undermine international justice, not Palestine\'s decision to join a treaty to which over 100 countries around the world are members." In January, when the preliminary ICC examination was opened, Israeli Prime Minister Benjamin Netanyahu described it as an outrage, saying the court was overstepping its boundaries. The United States also said it "strongly" disagreed with the court\'s decision. "As we have said repeatedly, we do not believe that Palestine is a state and therefore we do not believe that it is eligible to join the ICC," the State Department said in a statement. It urged the warring sides to resolve their differences through direct negotiations. "We will continue to oppose actions against Israel at the ICC as counterproductive to the cause of peace," it said. But the ICC begs to differ with the definition of a state for its purposes and refers to the territories as "Palestine." While a preliminary examination is not a formal investigation, it allows the court to review evidence and determine whether to investigate suspects on both sides. Prosecutor Fatou Bensouda said her office would "conduct its analysis in full independence and impartiality." The war between Israel and Hamas militants in Gaza last summer left more than 2,000 people dead. The inquiry will include alleged war crimes committed since June. The International Criminal Court was set up in 2002 to prosecute genocide, crimes against humanity and war crimes. CNN\'s Vasco Cotovio, Kareem Khadder and Faith Karimi contributed to this report.'

        # The below article tests that we don't add any hypotheses outside of the top n_beams
        IRAN_ARTICLE = " (CNN)The United States and its negotiating partners reached a very strong framework agreement with Iran in Lausanne, Switzerland, on Thursday that limits Iran's nuclear program in such a way as to effectively block it from building a nuclear weapon. Expect pushback anyway, if the recent past is any harbinger. Just last month, in an attempt to head off such an agreement, House Speaker John Boehner invited Israeli Prime Minister Benjamin Netanyahu to preemptively blast it before Congress, and 47 senators sent a letter to the Iranian leadership warning them away from a deal. The debate that has already begun since the announcement of the new framework will likely result in more heat than light. It will not be helped by the gathering swirl of dubious assumptions and doubtful assertions. Let us address some of these: . The most misleading assertion, despite universal rejection by experts, is that the negotiations' objective at the outset was the total elimination of any nuclear program in Iran. That is the position of Netanyahu and his acolytes in the U.S. Congress. But that is not and never was the objective. If it had been, there would have been no Iranian team at the negotiating table. Rather, the objective has always been to structure an agreement or series of agreements so that Iran could not covertly develop a nuclear arsenal before the United States and its allies could respond. The new framework has exceeded expectations in achieving that goal. It would reduce Iran's low-enriched uranium stockpile, cut by two-thirds its number of installed centrifuges and implement a rigorous inspection regime. Another dubious assumption of opponents is that the Iranian nuclear program is a covert weapons program. Despite sharp accusations by some in the United States and its allies, Iran denies having such a program, and U.S. intelligence contends that Iran has not yet made the decision to build a nuclear weapon. Iran's continued cooperation with International Atomic Energy Agency inspections is further evidence on this point, and we'll know even more about Iran's program in the coming months and years because of the deal. In fact, the inspections provisions that are part of this agreement are designed to protect against any covert action by the Iranians. What's more, the rhetoric of some members of Congress has implied that the negotiations have been between only the United States and Iran (i.e., the 47 senators' letter warning that a deal might be killed by Congress or a future president). This of course is not the case. The talks were between Iran and the five permanent members of the U.N. Security Council (United States, United Kingdom, France, China and Russia) plus Germany, dubbed the P5+1. While the United States has played a leading role in the effort, it negotiated the terms alongside its partners. If the agreement reached by the P5+1 is rejected by Congress, it could result in an unraveling of the sanctions on Iran and threaten NATO cohesion in other areas. Another questionable assertion is that this agreement contains a sunset clause, after which Iran will be free to do as it pleases. Again, this is not the case. Some of the restrictions on Iran's nuclear activities, such as uranium enrichment, will be eased or eliminated over time, as long as 15 years. But most importantly, the framework agreement includes Iran's ratification of the Additional Protocol, which allows IAEA inspectors expanded access to nuclear sites both declared and nondeclared. This provision will be permanent. It does not sunset. Thus, going forward, if Iran decides to enrich uranium to weapons-grade levels, monitors will be able to detect such a move in a matter of days and alert the U.N. Security Council. Many in Congress have said that the agreement should be a formal treaty requiring the Senate to \"advise and consent.\" But the issue is not suited for a treaty. Treaties impose equivalent obligations on all signatories. For example, the New START treaty limits Russia and the United States to 1,550 deployed strategic warheads. But any agreement with Iran will not be so balanced.  The restrictions and obligations in the final framework agreement will be imposed almost exclusively on Iran. The P5+1 are obligated only to ease and eventually remove most but not all economic sanctions, which were imposed as leverage to gain this final deal. Finally some insist that any agreement must address Iranian missile programs, human rights violations or support for Hamas or Hezbollah.  As important as these issues are, and they must indeed be addressed, they are unrelated to the most important aim of a nuclear deal: preventing a nuclear Iran.  To include them in the negotiations would be a poison pill. This agreement should be judged on its merits and on how it affects the security of our negotiating partners and allies, including Israel. Those judgments should be fact-based, not based on questionable assertions or dubious assumptions."

        ARTICLE_SUBWAY = ' New York (CNN)When Liana Barrientos was 23 years old, she got married in Westchester County, New York. A year later, she got married again in Westchester County, but to a different man and without divorcing her first husband.  Only 18 days after that marriage, she got hitched yet again. Then, Barrientos declared "I do" five more times, sometimes only within two weeks of each other. In 2010, she married once more, this time in the Bronx. In an application for a marriage license, she stated it was her "first and only" marriage. Barrientos, now 39, is facing two criminal counts of "offering a false instrument for filing in the first degree," referring to her false statements on the 2010 marriage license application, according to court documents. Prosecutors said the marriages were part of an immigration scam. On Friday, she pleaded not guilty at State Supreme Court in the Bronx, according to her attorney, Christopher Wright, who declined to comment further. After leaving court, Barrientos was arrested and charged with theft of service and criminal trespass for allegedly sneaking into the New York subway through an emergency exit, said Detective Annette Markowski, a police spokeswoman. In total, Barrientos has been married 10 times, with nine of her marriages occurring between 1999 and 2002.  All occurred either in Westchester County, Long Island, New Jersey or the Bronx. She is believed to still be married to four men, and at one time, she was married to eight men at once, prosecutors say. Prosecutors said the immigration scam involved some of her husbands, who filed for permanent residence status shortly after the marriages.  Any divorces happened only after such filings were approved. It was unclear whether any of the men will be prosecuted. The case was referred to the Bronx District Attorney\'s Office by Immigration and Customs Enforcement and the Department of Homeland Security\'s Investigation Division. Seven of the men are from so-called "red-flagged" countries, including Egypt, Turkey, Georgia, Pakistan and Mali. Her eighth husband, Rashid Rajput, was deported in 2006 to his native Pakistan after an investigation by the Joint Terrorism Task Force. If convicted, Barrientos faces up to four years in prison.  Her next court appearance is scheduled for May 18.'

        dct = tokenizer.batch_encode_plus(
            [FRANCE_ARTICLE, SHORTER_ARTICLE, IRAN_ARTICLE, ARTICLE_SUBWAY],
            max_length=1024,
            padding="max_length",
            truncation_strategy="only_first",
            truncation=True,
            return_tensors="jax",
        )

        self.assertEqual(1024, dct["input_ids"].shape[1])
        hypotheses_batch = model.generate(
            input_ids=dct["input_ids"],
            attention_mask=dct["attention_mask"],
            num_beams=2,
        ).sequences
        assert (hypotheses_batch[:, 1] == 0).all().item()

        EXPECTED = [
            "A French prosecutor says he is not aware of any video footage from on board the plane. Two German magazines claim to have found a cell phone video showing the crash. The publications say they watched the video, which was found by a source close to the investigation. All 150 on board the Germanwings flight were killed.",
            "Palestinian Authority becomes 123rd member of the International Criminal Court. The move gives the court jurisdiction over alleged crimes in Palestinian territories. Israel and the United States opposed the Palestinians' efforts to join the body. But Palestinian Foreign Minister Riad al-Malki said it was a move toward greater justice.",
            "U.S. and its negotiating partners reached a strong framework agreement with Iran. Peter Bergen: The debate that has already begun will likely result in more heat than light. Bergen: The most misleading assertion is that the negotiations' objective at the outset was the total elimination of any nuclear program.",
            "Liana Barrientos, 39, has been married 10 times, sometimes within two weeks of each other. Prosecutors say the marriages were part of an immigration scam. She pleaded not guilty at State Supreme Court in the Bronx on Friday. If convicted, Barrientos faces up to four years in prison.",
        ]

        generated_summaries = tokenizer.batch_decode(
            hypotheses_batch.tolist(), clean_up_tokenization_spaces=True, skip_special_tokens=True
        )
        assert generated_summaries == EXPECTED
    def test_rag_token_inference(self):
        rag_config = self.get_rag_config()
        rag_decoder_tokenizer = BartTokenizer.from_pretrained(
            "facebook/bart-large-cnn")
        rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
            "facebook/dpr-question_encoder-single-nq-base")
        rag_retriever = RagRetriever(
            rag_config,
            question_encoder_tokenizer=rag_question_encoder_tokenizer,
            generator_tokenizer=rag_decoder_tokenizer,
        )

        rag_token = self.token_model
        rag_token.set_retriever(rag_retriever)

        input_ids = rag_question_encoder_tokenizer(
            "who sings does he love me with reba",
            return_tensors="pt").input_ids
        decoder_input_ids = rag_decoder_tokenizer(
            "Linda Davis", return_tensors="pt").input_ids

        input_ids = input_ids.to(torch_device)
        decoder_input_ids = decoder_input_ids.to(torch_device)

        with torch.no_grad():
            output = rag_token(
                input_ids,
                labels=decoder_input_ids,
            )

        expected_shape = torch.Size([5, 5, 50264])
        self.assertEqual(output.logits.shape, expected_shape)

        expected_doc_scores = torch.tensor(
            [[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]]).to(torch_device)
        _assert_tensors_equal(expected_doc_scores,
                              output.doc_scores,
                              atol=TOLERANCE)

        expected_loss = torch.tensor([36.3557]).to(torch_device)
        _assert_tensors_equal(expected_loss, output.loss, atol=TOLERANCE)
async def upload_pretrained_model_to_classifier(category: str):  # , pretrained_model: str):
    print("\n@ PUT upload_pretrained_2_classifier resourse.")
    print("loading local pretrained model...")

    pretrained_model = BartForSequenceClassification.from_pretrained(
        pretrained_model_name_or_path="C:/Users/lavml/Documents/SoSe20/nlp/BERT/restapi/results/fine-tuning/",
        local_files_only=True)
    tokenizer = BartTokenizer.from_pretrained('results/fine-tuning/', vocab_file="results/fine-tuning/vocab.json",
                                              merges_file="results/fine-tuning/merges.txt")

    classifier = pipeline('zero-shot-classification', model=pretrained_model, tokenizer=tokenizer)  # , device=0)

    # add it to the db

    new_id = 1 if len(db) == 0 else db[-1]['cl_id'] + 1
    db.append(
        {'cl_id': new_id, 'model': classifier, 'category': category, 'data': [], 'description': 'fine-tuned model'})

    return {'data': None,
            'message': f"Fine-tuned Model apended to the database under the id: {new_id}. Try the new resource here "
                       f"--> http://127.0.0.1:8000/api/zero-shot/{new_id}"}
示例#4
0
    def __init__(self, device):
        super().__init__()

        self._device = device

        # we shard the model into multiple gpus if possible
        self._device_encoder1 = self._device_encoder2 = None
        self._device_decoder1 = self._device_decoder2 = None

        self._interface = BartForConditionalGeneration.from_pretrained(
            'sshleifer/distilbart-cnn-6-6')
        self._tokenizer = BartTokenizer.from_pretrained(
            'sshleifer/distilbart-cnn-6-6')

        self._label_output_layer = nn.Linear(HIDDEN_SIZE, LABEL_NUM)

        # initialize the label output layer
        self._label_output_layer.weight.data.normal_(mean=0.0, std=0.02)

        self.pad_label_index = -100
        self._mode = None
示例#5
0
    def __init__(self, model_name='facebook/bart-large-cnn', device=None):
        """
        ```
        interface to BART-based text summarization using transformers library

        Args:
          model_name(str): name of BART model for summarization
          device(str): device to use (e.g., 'cuda', 'cpu')
        ```
        """
        if 'bart' not in model_name:
            raise ValueError('TransformerSummarizer currently only accepts BART models')
        try:
            import torch
        except ImportError:
            raise Exception('TransformerSummarizer requires PyTorch to be installed.')
        self.torch_device = device
        if self.torch_device is None: self.torch_device = 'cuda' if torch.cuda.is_available() else 'cpu'
        from transformers import BartTokenizer, BartForConditionalGeneration
        self.tokenizer = BartTokenizer.from_pretrained(model_name)
        self.model = BartForConditionalGeneration.from_pretrained(model_name).to(self.torch_device)
示例#6
0
def summarization(TEXT):
    now_time = time.time()
    model = BartForConditionalGeneration.from_pretrained(
        'sshleifer/distilbart-cnn-12-6')
    tokenizer = BartTokenizer.from_pretrained('sshleifer/distilbart-cnn-12-6')
    inputs = tokenizer([TEXT], max_length=len(TEXT), return_tensors='pt')

    summary_ids = model.generate(inputs['input_ids'],
                                 num_beams=3,
                                 max_length=100,
                                 early_stopping=True)
    print(f'Process_time : {time.time() - now_time}')
    print(f'**Original Text** \n {TEXT}')
    print('-' * 100)
    print(f'**Summarization Text**')
    for g in summary_ids:
        print(
            tokenizer.decode(g,
                             skip_special_tokens=True,
                             clean_up_tokenization_spaces=False))
    return
def multi_news_builder(args):
    save_path = args.data_path + args.data_name + '/' + args.mode + 'loader' + str(
        args.percentage) + '.pt'
    if args.minor_data:
        save_path = args.data_path + args.data_name + '/minor_data' + '/' + args.mode + 'loader' + str(
            args.percentage) + '.pt'
    multi_news_reader = MultiNewsReader(args)
    tokenizer = BartTokenizer.from_pretrained('facebook/bart-base')

    train_set = MultiNewsDataset(tokenizer, multi_news_reader, 'train', args)
    if args.mode == 'train':
        train_loader = DataLoader(dataset=train_set,
                                  batch_size=args.batch_size,
                                  shuffle=True,
                                  collate_fn=train_set.collate_fn)
    else:
        train_loader = DataLoader(dataset=train_set,
                                  batch_size=args.batch_size,
                                  shuffle=False,
                                  collate_fn=train_set.collate_fn)
    save(train_loader, save_path)
示例#8
0
    def test_rag_token_generate_beam(self):
        rag_config = self.get_rag_config()
        rag_decoder_tokenizer = BartTokenizer.from_pretrained(
            "facebook/bart-large-cnn")
        rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
            "facebook/dpr-question_encoder-single-nq-base")
        rag_retriever = RagRetriever(
            rag_config,
            question_encoder_tokenizer=rag_question_encoder_tokenizer,
            generator_tokenizer=rag_decoder_tokenizer,
        )

        rag_token = self.token_model
        rag_token.set_retriever(rag_retriever)

        input_ids = rag_question_encoder_tokenizer(
            "who sings does he love me with reba",
            return_tensors="pt").input_ids

        input_ids = input_ids.to(torch_device)

        output_ids = rag_token.generate(
            input_ids,
            decoder_start_token_id=rag_token.generator.config.
            decoder_start_token_id,
            num_beams=2,
            num_return_sequences=2,
        )
        # sequence generate test
        output_text_1 = rag_decoder_tokenizer.decode(output_ids[0],
                                                     skip_special_tokens=True)
        output_text_2 = rag_decoder_tokenizer.decode(output_ids[1],
                                                     skip_special_tokens=True)

        # Expected outputs as given by model at integration time.
        EXPECTED_OUTPUT_TEXT_1 = "\"She's My Kind of Girl"
        EXPECTED_OUTPUT_TEXT_2 = "\"She's My Kind of Love"

        self.assertEqual(output_text_1, EXPECTED_OUTPUT_TEXT_1)
        self.assertEqual(output_text_2, EXPECTED_OUTPUT_TEXT_2)
def convert_bart_checkpoint(checkpoint_path, pytorch_dump_folder_path):
    """
    Copy/paste/tweak model's weights to our BERT structure.
    """
    b2 = torch.hub.load("pytorch/fairseq", checkpoint_path)
    b2.eval()  # disable dropout
    b2.model.upgrade_state_dict(b2.model.state_dict())
    config = BartConfig()
    tokens = b2.encode(SAMPLE_TEXT).unsqueeze(0)
    tokens2 = BartTokenizer.from_pretrained("bart-large").encode(
        SAMPLE_TEXT).unsqueeze(0)
    assert torch.eq(tokens, tokens2).all()

    # assert their_output.size() == (1, 11, 1024)

    if checkpoint_path == "bart.large":
        state_dict = b2.model.state_dict()
        state_dict["shared.weight"] = state_dict["decoder.embed_tokens.weight"]
        model = BartModel(config)
        their_output = b2.extract_features(tokens)

    else:  # MNLI Case
        state_dict = b2.state_dict()
        state_dict["model.shared.weight"] = state_dict[
            "model.decoder.embed_tokens.weight"]
        for src, dest in rename_keys:
            rename_key(state_dict, src, dest)
        state_dict.pop("_float_tensor", None)
        model = BartForSequenceClassification(config)
        their_output = b2.predict("mnli", tokens, return_logits=True)
    for k in IGNORE_KEYS:
        state_dict.pop(k, None)
    model.load_state_dict(state_dict)
    model.eval()
    our_outputs = model.forward(tokens)[0]

    assert their_output.shape == our_outputs.shape
    assert (their_output == our_outputs).all().item()
    Path(pytorch_dump_folder_path).mkdir(exist_ok=True)
    model.save_pretrained(pytorch_dump_folder_path)
示例#10
0
    def __init__(self, rouge_metrics=None, lang="english"):
        if rouge_metrics is None:
            rouge_metrics = ['rouge1', 'rougeL', 'rougeLsum']
            warnings.warn(
                f"Rouge metrics not defined, using default metrics {rouge_metrics}."
            )

        self.LANGUAGE = lang
        stemmer = Stemmer(self.LANGUAGE)

        # single-doc LexRank
        self.lr_sum = LexRankSummarizer(stemmer)
        self.lr_sum.stop_words = get_stop_words(self.LANGUAGE)

        # single-doc LSA
        self.lsa_sum = LsaSummarizer(stemmer)
        self.lsa_sum.stop_words = get_stop_words(self.LANGUAGE)

        # single-doc TextRank
        self.tr_sum = TextRankSummarizer(stemmer)
        self.tr_sum.stop_words = get_stop_words(self.LANGUAGE)

        # single-doc T5
        self.t5_sum_model = T5ForConditionalGeneration.from_pretrained(
            't5-base')
        self.t5_sum_tokenizer = T5Tokenizer.from_pretrained('t5-base')

        # single-doc BART
        self.bart_tokenizer = BartTokenizer.from_pretrained(
            'facebook/bart-large-cnn')
        # self.bart_sum_model = pipeline('summarization', model='facebook/bart-large-cnn',
        #                                tokenizer='facebook/bart-large-cnn')
        self.bart_sum_model = BartForConditionalGeneration.from_pretrained(
            'facebook/bart-large-cnn')

        # SCORES
        # what is stemming? - https://en.wikipedia.org/wiki/Stemming
        # Stemming is the process of reducing words to their root form.
        # For example: contesting -> contest ; contestant -> contest
        self.scorer = rouge_scorer.RougeScorer(rouge_metrics, use_stemmer=True)
示例#11
0
    def test_rag_sequence_generate_beam(self):
        rag_config = self.get_rag_config()
        rag_decoder_tokenizer = BartTokenizer.from_pretrained(
            "facebook/bart-large-cnn")
        rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
            "facebook/dpr-question_encoder-single-nq-base")
        rag_retriever = RagRetriever(
            rag_config,
            question_encoder_tokenizer=rag_question_encoder_tokenizer,
            generator_tokenizer=rag_decoder_tokenizer,
        )

        rag_token = self.sequence_model
        rag_token.set_retriever(rag_retriever)

        input_ids = rag_question_encoder_tokenizer(
            "who sings does he love me with reba",
            return_tensors="pt").input_ids

        input_ids = input_ids.to(torch_device)

        output_ids = rag_token.generate(
            input_ids,
            decoder_start_token_id=rag_token.generator.config.
            decoder_start_token_id,
            num_beams=2,
            num_return_sequences=2,
        )
        # sequence generate test
        output_text_1 = rag_decoder_tokenizer.decode(output_ids[0],
                                                     skip_special_tokens=True)
        output_text_2 = rag_decoder_tokenizer.decode(output_ids[1],
                                                     skip_special_tokens=True)

        # Expected outputs as given by model at integration time.
        EXPECTED_OUTPUT_TEXT_1 = """\"She's My Kind of Girl\" was released through Epic Records in Japan in March 1972, giving the duo a Top 10 hit. Two more singles were released in Japan, \"En Carousel\" and \"Love Has Its Ways\" Ulvaeus and Andersson persevered with their songwriting and experimented with new sounds and vocal arrangements."""
        EXPECTED_OUTPUT_TEXT_2 = """In September 2018, Björn Ulvaeus revealed that the two new songs, \"I Still Have Faith In You\" and \"Don't Shut Me Down\", would be released no earlier than March 2019. The two new tracks will feature in a TV special set to air later in the year."""

        self.assertEqual(output_text_1, EXPECTED_OUTPUT_TEXT_1)
        self.assertEqual(output_text_2, EXPECTED_OUTPUT_TEXT_2)
示例#12
0
	def __init__(self, summarizer, batch_size=1):
		"""
		:param summarizer: SummarizerModel value
		:param batch_size : [int] batch size for summarizer input (for T5 and BART)
		"""
		super().__init__()
		self.summarizer = summarizer
		self.batch_size = batch_size

		print("Loading model : ", str(summarizer))
		if self.summarizer == SummarizerModel.BERT_SUM:
			self.model = Summarizer()

		if self.summarizer == SummarizerModel.T5:
			self.tokenizer = T5Tokenizer.from_pretrained('t5-small')
			self.model = T5ForConditionalGeneration.from_pretrained('t5-small')
			self.model.eval()
			if torch.cuda.is_available():
				self.model.cuda()
			self.decoding_strategy = T5_DECODING_STRAT
			print("Use for decoding strategy :", self.decoding_strategy)

		if self.summarizer == SummarizerModel.BART:
			self.tokenizer = BartTokenizer.from_pretrained('bart-large-cnn')
			self.model = BartForConditionalGeneration.from_pretrained('bart-large-cnn')
			self.model.eval()
			if torch.cuda.is_available():
				self.model.cuda()

			self.decoding_strategy = BART_DECODING_STRAT
			print("Use for decoding strategy :", self.decoding_strategy)

		if self.summarizer == SummarizerModel.PYSUM:
			self.model = AutoAbstractor()
			self.model.tokenizable_doc = SimpleTokenizer()
			self.model.delimiter_list = ['.', '\n']
			self.doc_filtering = TopNRankAbstractor()

		if self.summarizer == SummarizerModel.KW:
			self.model = keywords
示例#13
0
 def load(self, k):
     while self.m.get(k, None) == -1:
         time.sleep(1)  # loading, wit till ready
     if self.m.get(k, None) is not None:
         return self.m[k]  # it's already loaded
     self.m[k] = -1  # tell others it's loading, wait
     m = None
     if k == 'sentence-encode':
         m = SentenceTransformer('roberta-base-nli-stsb-mean-tokens')
     elif k == 'sentiment-analysis':
         tokenizer = AutoTokenizer.from_pretrained(
             "mrm8488/t5-base-finetuned-emotion")
         model = AutoModelWithLMHead.from_pretrained(
             "mrm8488/t5-base-finetuned-emotion").to("cuda")
         # TODO we sure it's not ForSequenceClassification? https://huggingface.co/mrm8488/t5-base-finetuned-emotion
         m = (tokenizer, model, 512)
     elif k == 'summarization':
         # Not using pipelines because can't handle >max_tokens
         # https://github.com/huggingface/transformers/issues/4501
         # https://github.com/huggingface/transformers/issues/4224
         max_tokens = 1024  # 4096
         tokenizer = BartTokenizer.from_pretrained(
             'facebook/bart-large-cnn')
         model = BartForConditionalGeneration.from_pretrained(
             'facebook/bart-large-cnn').to("cuda")
         # model = EncoderDecoderModel.from_pretrained("patrickvonplaten/longformer2roberta-cnn_dailymail-fp16").to("cuda")
         # tokenizer = AutoTokenizer.from_pretrained("allenai/longformer-base-4096")
         m = (tokenizer, model, max_tokens)
     elif k == 'question-answering':
         tokenizer = LongformerTokenizer.from_pretrained(
             "allenai/longformer-large-4096-finetuned-triviaqa")
         model = LongformerForQuestionAnswering.from_pretrained(
             "allenai/longformer-large-4096-finetuned-triviaqa",
             return_dict=True).to("cuda")
         # tokenizer = AutoTokenizer.from_pretrained("mrm8488/longformer-base-4096-finetuned-squadv2")
         # model = AutoModelForQuestionAnswering.from_pretrained("mrm8488/longformer-base-4096-finetuned-squadv2", return_dict=True).to("cuda")
         m = (tokenizer, model, 4096)
     self.m[k] = m
     return m
示例#14
0
def generate_summaries(examples: list,
                       out_file: str,
                       model_name: str,
                       batch_size: int = 8,
                       device: str = DEFAULT_DEVICE):
    fout = Path(out_file).open("w")
    model = BartForConditionalGeneration.from_pretrained(model_name).to(device)
    tokenizer = BartTokenizer.from_pretrained("bart-large")

    max_length = 140
    min_length = 55

    for batch in tqdm(list(chunks(examples, batch_size))):
        dct = tokenizer.batch_encode_plus(batch,
                                          max_length=1024,
                                          return_tensors="pt",
                                          pad_to_max_length=True)
        summaries = model.generate(
            input_ids=dct["input_ids"].to(device),
            attention_mask=dct["attention_mask"].to(device),
            num_beams=4,
            length_penalty=2.0,
            max_length=max_length +
            2,  # +2 from original because we start at step=1 and stop before max_length
            min_length=min_length +
            1,  # +1 from original because we start at step=1
            no_repeat_ngram_size=3,
            early_stopping=True,
            decoder_start_token_id=model.config.eos_token_id,
        )
        dec = [
            tokenizer.decode(g,
                             skip_special_tokens=True,
                             clean_up_tokenization_spaces=False)
            for g in summaries
        ]
        for hypothesis in dec:
            fout.write(hypothesis + "\n")
            fout.flush()
示例#15
0
    def __init__(self, checkpoint):
        self.tokenizer = BartTokenizer.from_pretrained("bart-large")

        def convert_to_single_gpu(state_dict):
            def _convert(key):
                if key.startswith('module.'):
                    return key[7:]
                return key

            return {_convert(key): value for key, value in state_dict.items()}

        file_name, headers = urllib.request.urlretrieve(checkpoint)

        self.model = MyBart.from_pretrained("bart-large",
                                            state_dict=convert_to_single_gpu(
                                                torch.load(file_name)))
        # self.model.to(torch.device("cuda"))
        self.model.eval()

        self.num_beams = 4
        self.max_input_length = 512
        self.max_output_length = 100
示例#16
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('--user_input', action="store_true")
    args = parser.parse_args()

    print("initializing bart tokenizer...")
    tokenizer = BartTokenizer.from_pretrained("facebook/bart-base")

    print("creating lightseq model...")
    ls_model = lightseq.Transformer("lightseq_bart_base.pb", 128)
    print("creating huggingface model...")
    hf_model = BartForConditionalGeneration.from_pretrained(
        "facebook/bart-base")
    hf_model.to('cuda:0')

    sentences = [
        "I love that girl, but <mask> does not <mask> me.",
        "She is so <mask> that I can not help glance at <mask>.",
        "Nothing's gonna <mask> my love for you.",
        "Drop everything now. Meet me in the pouring <mask>. Kiss me on the sidewalk."
    ]

    print("====================START warmup====================")
    warmup(tokenizer, ls_model, hf_model, sentences)
    print("====================END warmup====================")

    while True:
        if args.user_input:
            sentences = [input("input the masked sentence:\n")]

        print("tokenizing the sentences...")
        inputs = tokenizer(sentences, return_tensors="pt", padding=True)
        inputs_id = inputs["input_ids"]

        ls_generate(ls_model, tokenizer, inputs_id)
        hf_generate(hf_model, tokenizer, inputs_id)

        if not args.user_input:
            break
示例#17
0
    def __init__(self, model_name='facebook/bart-large-mnli', device=None):
        """
        interface to BART-based text summarization using transformers library

        Args:
          model_name(str): name of BART model
          device(str): device to use (e.g., 'cuda', 'cpu')
        """
        if 'mnli' not in model_name:
            raise ValueError('ZeroShotClasifier requires an MNLI model')
        try:
            import torch
        except ImportError:
            raise Exception(
                'ZeroShotClassifier requires PyTorch to be installed.')
        self.torch_device = device
        if self.torch_device is None:
            self.torch_device = 'cuda' if torch.cuda.is_available() else 'cpu'
        from transformers import BartForSequenceClassification, BartTokenizer
        self.tokenizer = BartTokenizer.from_pretrained(model_name)
        self.model = BartForSequenceClassification.from_pretrained(
            model_name).to(self.torch_device)
 def __init__(self, conf=None):
     super().__init__()
     # save conf, accessible in self.hparams.conf
     self.save_hyperparameters()
     # pretrained models
     self.sentence_classifier = BertClf.load_from_checkpoint(
         checkpoint_path=os.path.join(
             os.path.split(hydra.utils.get_original_cwd())[0], 'outputs',
             conf.model.classifier_path))
     self.question_generator = BartQG.load_from_checkpoint(
         checkpoint_path=os.path.join(
             os.path.split(hydra.utils.get_original_cwd())[0], 'outputs',
             conf.model.generator_path))
     # tokenizers
     self.bert_tokenizer = BertTokenizer.from_pretrained(
         'bert-base-uncased')
     self.bart_tokenizer = BartTokenizer.from_pretrained(
         'facebook/bart-base')
     # classification threshold
     self.threshold = 0.947
     # loss
     self.loss = torch.nn.CrossEntropyLoss(
         ignore_index=self.bart_tokenizer.pad_token_id)
示例#19
0
    def summarise_with_BART(self, text_block):
        """
        Summarisation as conditional language generation.

        See https://huggingface.co for further info on
        using BART models with Hugging Face.

        Args:
            text_block (str): scraped article 
        Returns:
            summary (str): article summary 
        """
        from transformers import BartTokenizer, BartForConditionalGeneration

        tokenizer = BartTokenizer.from_pretrained(NLP.MODELS[0])
        model = BartForConditionalGeneration.from_pretrained(NLP.MODELS[0])

        inputs = tokenizer([text_block], padding=True, truncation=True, max_length=512,return_tensors="pt") # change max_length for shorter summaries
        outputs = model.generate(inputs['input_ids'], num_beams=4, max_length=150, early_stopping=True)

        summary = [tokenizer.decode(output, skip_special_tokens=True, clean_up_tokenization_spaces=False) for output in outputs]

        return summary
 def __init__(self, conf):
     super().__init__()
     # configuration
     self.conf = conf
     # dataset
     self.dataset = None
     # dataset paths
     if len(conf.dataset.preprocessing.path) > 0:
         self.dataset_path = os.path.join(
             os.path.split(hydra.utils.get_original_cwd())[0], 'datasets',
             conf.dataset.preprocessing.path)
     else:
         self.dataset_path = os.path.join(
             os.path.split(hydra.utils.get_original_cwd())[0], 'datasets',
             conf.dataset.name) + ('combined' if self.conf.dataset.
                                   preprocessing.combine else '')
     self.dataset_setup_path = self.dataset_path + '_' + conf.model.name + (
         '_context' if self.conf.dataset.setup.context else '')
     # tokenizers
     self.bert_tokenizer = BertTokenizer.from_pretrained(
         'bert-base-uncased')
     self.bart_tokenizer = BartTokenizer.from_pretrained(
         'facebook/bart-base')
示例#21
0
    def test_bart_summarization_dataset(self):
        tmp_dir = Path(tempfile.gettempdir())
        articles = [" Sam ate lunch today", "Sams lunch ingredients"]
        summaries = ["A very interesting story about what I ate for lunch.", "Avocado, celery, turkey, coffee"]
        _dump_articles((tmp_dir / "train.source"), articles)
        _dump_articles((tmp_dir / "train.target"), summaries)
        tokenizer = BartTokenizer.from_pretrained("bart-large")
        max_len_source = max(len(tokenizer.encode(a)) for a in articles)
        max_len_target = max(len(tokenizer.encode(a)) for a in summaries)
        trunc_target = 4
        train_dataset = SummarizationDataset(
            tokenizer, data_dir=tmp_dir, type_path="train", max_source_length=20, max_target_length=trunc_target,
        )
        dataloader = DataLoader(train_dataset, batch_size=2, collate_fn=train_dataset.collate_fn)
        for batch in dataloader:
            self.assertEqual(batch["source_mask"].shape, batch["source_ids"].shape)
            # show that articles were trimmed.
            self.assertEqual(batch["source_ids"].shape[1], max_len_source)
            self.assertGreater(20, batch["source_ids"].shape[1])  # trimmed significantly

            # show that targets were truncated
            self.assertEqual(batch["target_ids"].shape[1], trunc_target)  # Truncated
            self.assertGreater(max_len_target, trunc_target)  # Truncated
示例#22
0
def run_interaction(model_name: str, device: str = DEFAULT_DEVICE):

    assert model_name.endswith(".ckpt")
    model = SummarizationTrainer.load_from_checkpoint(model_name).model.to(
        device)
    tokenizer = BartTokenizer.from_pretrained("bart-large")
    SEP = tokenizer.special_tokens_map["sep_token"]

    max_length = 140
    min_length = 10

    from whoosh.qparser import QueryParser

    ix = index.open_dir(INDEX_DIR)
    qp = QueryParser("story", schema=ix.schema)

    with ix.searcher() as s:
        while True:
            utt = input(": ")
            or_searche = " OR ".join(utt.split(" "))
            q = qp.parse(or_searche)
            results = s.search(q, limit=1)
            if len(results) > 0:
                background = results[0]["story"]
                answer = generate_answer(
                    SEP,
                    background,
                    device,
                    max_length,
                    min_length,
                    model,
                    tokenizer,
                    utt,
                )
            else:
                answer = "Whaat?"
            print(answer)
示例#23
0
    def test_rag_token_inference_nq_checkpoint(self):
        rag_config = self.get_rag_config()
        rag_decoder_tokenizer = BartTokenizer.from_pretrained("facebook/bart-large-cnn")
        rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
            "facebook/dpr-question_encoder-single-nq-base"
        )
        rag_retriever = RagRetriever(
            rag_config,
            question_encoder_tokenizer=rag_question_encoder_tokenizer,
            generator_tokenizer=rag_decoder_tokenizer,
        )

        rag_token = self.token_model_nq_checkpoint(retriever=rag_retriever)

        # check that outputs after saving and loading are equal
        with tempfile.TemporaryDirectory() as tmpdirname:
            rag_token.save_pretrained(tmpdirname)
            rag_token = TFRagTokenForGeneration.from_pretrained(tmpdirname, retriever=rag_retriever)

        input_ids = rag_question_encoder_tokenizer(
            "who sings does he love me with reba", return_tensors="tf"
        ).input_ids
        decoder_input_ids = rag_decoder_tokenizer("Linda Davis", return_tensors="tf").input_ids

        output = rag_token(
            input_ids,
            labels=decoder_input_ids,
        )

        expected_shape = tf.TensorShape([5, 5, 50265])
        self.assertEqual(output.logits.shape, expected_shape)

        expected_doc_scores = tf.convert_to_tensor([[62.9402, 62.7107, 62.2382, 62.1194, 61.8578]])
        expected_loss = tf.convert_to_tensor([32.521812])

        tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3)
        tf.debugging.assert_near(output.doc_scores, expected_doc_scores, atol=1e-3)
    def test_rag_sequence_inference(self):
        rag_config = self.get_rag_config()
        rag_decoder_tokenizer = BartTokenizer.from_pretrained(
            "facebook/bart-large-cnn")
        rag_question_encoder_tokenizer = DPRQuestionEncoderTokenizer.from_pretrained(
            "facebook/dpr-question_encoder-single-nq-base")
        rag_retriever = RagRetriever(
            rag_config,
            question_encoder_tokenizer=rag_question_encoder_tokenizer,
            generator_tokenizer=rag_decoder_tokenizer,
        )

        rag_sequence = self.sequence_model
        rag_sequence.set_retriever(rag_retriever)

        input_ids = rag_question_encoder_tokenizer(
            "who sings does he love me with reba",
            return_tensors="tf").input_ids
        decoder_input_ids = rag_decoder_tokenizer(
            "Linda Davis", return_tensors="tf").input_ids

        output = rag_sequence(
            input_ids,
            labels=decoder_input_ids,
        )

        expected_shape = tf.TensorShape([5, 5, 50264])
        self.assertEqual(output.logits.shape, expected_shape)

        expected_doc_scores = tf.convert_to_tensor(
            [[75.0286, 74.4998, 74.0804, 74.0306, 73.9504]])
        expected_loss = tf.convert_to_tensor([36.7368])

        tf.debugging.assert_near(output.loss, expected_loss, atol=1e-3)
        tf.debugging.assert_near(output.doc_scores,
                                 expected_doc_scores,
                                 atol=1e-3)
示例#25
0
def run(args):
    # initialize pretrained model and tokenizer from files
    model_state_dict = torch.load(args.model_file)
    model = load_model(args.model, model_state_dict)
    tokenizer = BartTokenizer.from_pretrained(args.model)

    # load predict file data
    dataset = QADataset(args.predict_file)
    loader = dataset.loader(batch_size=args.predict_batch_size)

    # run interactive mode
    if args.interactive:
        interactive(args, model, tokenizer)

    # run and print model predictions from file
    else:
        correct_answers = 0
        total_answers = 0
        dataset_total_answers = len(loader) * args.predict_batch_size
        for questions, answers in loader:
            model_predictions = [
                normalize_answer(p)
                for p in predict(args, model, tokenizer, questions)
            ]
            norm_answers = [normalize_answer(a) for a in answers]
            for i in range(args.predict_batch_size):
                print(f"Question {total_answers + 1}/{dataset_total_answers}")
                print(
                    f"Q: {questions[i]}\nA: {norm_answers[i]}\nP: {model_predictions[i]}\n{'-' * 30}"
                )
                if norm_answers[i] == model_predictions[
                        i]:  # exact match score
                    correct_answers += 1
                total_answers += 1
        acc = correct_answers / total_answers
        log_path = log_to_file(args, acc)
        print(f"Inference is done. results are logged to: {log_path}")
示例#26
0
def train_newsela(data_dir):

    tokenizer = BartTokenizer.from_pretrained('facebook/bart-large-xsum')
    loss_func = nn.BCELoss(reduction='mean')
    model = LogR(tokenizer.vocab_size).to('cuda')
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-2)

    for i in range(5):
        print('beginning epoch ' + str(i + 1))

        #first train on train split
        for batch in dataloader(data_dir, batch_size=16):

            X, y = construct_dataset(batch, tokenizer)
            X = torch.from_numpy(X).float().to('cuda')
            y = torch.from_numpy(y).float().to('cuda')

            optimizer.zero_grad()
            outputs = model(X)
            loss = loss_func(outputs, y)
            loss.backward()
            optimizer.step()

    return model
def run_one_fig(spec, args, num_samples=300):
    print(f"--{spec}--")
    CUR_DIR = os.path.join(args.prob_meta_dir, spec)
    args.cur_dir = CUR_DIR
    files = os.listdir(CUR_DIR)
    random.shuffle(files)
    files = files[:num_samples]

    BOS_TOKEN = 0
    print(args.spec_name)
    if 'pegasus' in args.model_name:
        from transformers import PegasusTokenizer

        bpe_tokenizer = PegasusTokenizer.from_pretrained(args.model_name)
        EOS_TOK_IDs = [106, bpe_tokenizer.eos_token_id, 2]  # <n>
    elif 'gpt' in args.model_name:
        from transformers import GPT2Tokenizer

        bpe_tokenizer = GPT2Tokenizer.from_pretrained('gpt2')
        EOS_TOK_IDs = [bpe_tokenizer.eos_token_id]
    elif 'bart' in args.model_name:
        from transformers import BartTokenizer

        bpe_tokenizer = BartTokenizer.from_pretrained(args.model_name)
        EOS_TOK_IDs = [bpe_tokenizer.eos_token_id]
    else:
        raise NotImplementedError
    # process_data_single(args, files[0], eos_token_ids=EOS_TOK_IDs)
    len_samples = len(files)
    cpu_cnt = multiprocessing.cpu_count()
    with multiprocessing.Pool(processes=cpu_cnt) as pool:
        results = pool.starmap(process_data_single, zip([args] * len_samples, files, [EOS_TOK_IDs] * len_samples))
    output = list(itertools.chain.from_iterable(results))
    print(f"Samples: {len(output)}")
    output = proceed_data(10, output)
    return output
示例#28
0
    def test_xsum_summarization_same_as_fairseq(self):
        model = BartForConditionalGeneration.from_pretrained("facebook/bart-large-xsum").to(torch_device)
        self.assertFalse(model.config.is_valid_mbart())
        tok = BartTokenizer.from_pretrained("facebook/bart-large")

        EXPECTED_SUMMARY = "California's largest power company has begun shutting off electricity to thousands of customers in the state."
        dct = tok.batch_encode_plus(
            [PGE_ARTICLE], max_length=1024, padding="max_length", truncation=True, return_tensors="pt",
        ).to(torch_device)

        hypotheses_batch = model.generate(
            input_ids=dct["input_ids"],
            attention_mask=dct["attention_mask"],
            num_beams=2,
            max_length=62,
            min_length=11,
            length_penalty=1.0,
            no_repeat_ngram_size=3,
            early_stopping=True,
            decoder_start_token_id=model.config.eos_token_id,
        )

        decoded = tok.batch_decode(hypotheses_batch, skip_special_tokens=True,)
        self.assertEqual(EXPECTED_SUMMARY, decoded[0])
if __name__ == '__main__':
    args = parse_args()
    device_ = args.device

    if device_ > -1:
        device = f'cuda:{device_}'
    else:
        device = 'cpu'

    model = BartSystem.load_from_checkpoint(str(
        args.model_checkpoint.absolute()),
                                            map_location='cuda:0')
    model.model.to(device)

    tokenizer = BartTokenizer.from_pretrained('bart-large-cnn')

    spacy_nlp = spacy.load("en_core_web_sm")

    # read input data
    set_ = args.set
    input_file = (args.data_folder / set_).with_suffix('.json')

    with open(input_file) as f:
        samples = json.load(f)

    batch_size = 128

    for batch in tqdm.tqdm(batches(samples, batch_size),
                           total=len(samples) // batch_size + 1):
        process_batch(batch, model, spacy_nlp)
 def default_tokenizer(self):
     return BartTokenizer.from_pretrained("facebook/bart-large")