Ejemplo n.º 1
0
def bertForNextSentencePrediction(*args, **kwargs):
    """
    BERT model with next sentence prediction head.
    This module comprises the BERT model followed by the next sentence
    classification head.

    Example:
        # Load the tokenizer
        >>> import torch
        >>> tokenizer = torch.hub.load('huggingface/pytorch-pretrained-BERT', 'bertTokenizer', 'bert-base-cased', do_basic_tokenize=False)
        #  Prepare tokenized input
        >>> text = "[CLS] Who was Jim Henson ? [SEP] Jim Henson was a puppeteer [SEP]"
        >>> tokenized_text = tokenizer.tokenize(text)
        >>> indexed_tokens = tokenizer.convert_tokens_to_ids(tokenized_text)
        >>> segments_ids = [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1]
        >>> tokens_tensor = torch.tensor([indexed_tokens])
        >>> segments_tensors = torch.tensor([segments_ids])
        # Load bertForNextSentencePrediction
        >>> model = torch.hub.load('huggingface/pytorch-pretrained-BERT', 'bertForNextSentencePrediction', 'bert-base-cased')
        >>> model.eval()
        # Predict the next sentence classification logits
        >>> with torch.no_grad():
                next_sent_classif_logits = model(tokens_tensor, segments_tensors)
    """
    model = BertForNextSentencePrediction.from_pretrained(*args, **kwargs)
    return model
def bertForNextSentencePrediction(*args, **kwargs):
    """
    BERT model with next sentence prediction head.
    This module comprises the BERT model followed by the next sentence
    classification head.
    """
    model = BertForNextSentencePrediction.from_pretrained(*args, **kwargs)
    return model
Ejemplo n.º 3
0
def test_BertForNextSentencePrediction():
    input_ids = torch.LongTensor([[31, 51, 99], [15, 5, 0]])
    input_mask = torch.LongTensor([[1, 1, 1], [1, 1, 0]])
    token_type_ids = torch.LongTensor([[0, 0, 1], [0, 1, 0]])
    config = BertConfig(vocab_size_or_config_json_file=32000,
                        hidden_size=768,
                        num_hidden_layers=12,
                        num_attention_heads=12,
                        intermediate_size=3072)
    model = BertForNextSentencePrediction(config)
    print(model(input_ids, token_type_ids, input_mask))
Ejemplo n.º 4
0
 def __init__(
     self
     , question_file
     , answer_file
     , sample_n
     , random_state
     , bert_cache
     , logger
     , device
     , max_seq_length
     , batch_size
 ):
     # initializes some vars
     self.question_file = question_file
     self.answer_file = answer_file
     self.sample_n = sample_n
     self.random_state = random_state
     self.bert_cache = bert_cache
     self.logger = logger
     self.device = device
     self.max_seq_length = max_seq_length
     self.batch_size = batch_size
     
     # gets the pre-trained tokenizer
     self.tokenizer = BertTokenizer.from_pretrained(
         "bert-base-uncased"
         , do_lower_case = True
         , cache_dir = self.bert_cache
     )
     
     # gets the pre-trained model
     self.model = BertForNextSentencePrediction.from_pretrained(
         "bert-base-uncased"
         , cache_dir = self.bert_cache
     ).to(self.device)
     
     # instantiates the helper class
     self.ceshiner = Ceshiner()
Ejemplo n.º 5
0
        if label == pred_label:
            correct += 1
    print(
        f'Accuracy: {correct}/{len(labels)} = {correct/len(labels)*100:.2f}%')


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='CSQA using BERT NSP model')
    parser.add_argument('--input', help='input dataset')
    parser.add_argument('--bert-vocab', help='bert vocab file')
    parser.add_argument('--bert-model', help='pretrained bert model')
    parser.add_argument('--batch-size',
                        type=int,
                        default=8,
                        help='batch size for BERT')
    parser.add_argument('--gpu-id', '-g', type=int, default=0, help='GPU ID')

    args = parser.parse_args()

    print('Initialize BERT model...')

    TOKENIZER = WordTokenizer(word_splitter=BertBasicWordSplitter())
    WORD_INDEXER = PretrainedBertIndexer(pretrained_model=args.bert_vocab)
    VOCAB = Vocabulary()
    GPU_ID = args.gpu_id
    BERT_NEXT_SENTENCE = BertForNextSentencePrediction.from_pretrained(
        args.bert_model).to(torch.device(f"cuda:{GPU_ID}"))
    BERT_NEXT_SENTENCE.eval()

    main()
Ejemplo n.º 6
0
def main():
    parser = argparse.ArgumentParser()

    # Required parameters
    parser.add_argument(
        "--data_dir",
        default="../data/bert",
        type=str,
        required=False,
        help=
        "The input data dir. Should contain the .tsv files (or other data files) for the task."
    )
    parser.add_argument(
        "--bert_model",
        default='bert-base-uncased',
        type=str,
        required=False,
        help="Bert pre-trained model selected in the list: bert-base-uncased, "
        "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese."
    )
    parser.add_argument("--task_name",
                        default='MRPC',
                        type=str,
                        required=False,
                        help="The name of the task to train.")
    parser.add_argument(
        "--output_dir",
        default="../data/bert/output",
        type=str,
        required=False,
        help="The output directory where the model checkpoints will be written."
    )

    # Other parameters
    parser.add_argument(
        "--max_seq_length",
        default=192,
        type=int,
        help=
        "The maximum total input sequence length after WordPiece tokenization. \n"
        "Sequences longer than this will be truncated, and sequences shorter \n"
        "than this will be padded.")
    parser.add_argument("--do_train",
                        default=True,
                        action='store_true',
                        help="Whether to run training.")
    parser.add_argument("--do_eval",
                        default=False,
                        action='store_true',
                        help="Whether to run eval on the dev set.")
    parser.add_argument(
        "--do_lower_case",
        default=True,
        action='store_true',
        help="Set this flag if you are using an uncased model.")
    parser.add_argument("--train_batch_size",
                        default=128,
                        type=int,
                        help="Total batch size for training.")
    parser.add_argument("--eval_batch_size",
                        default=128,
                        type=int,
                        help="Total batch size for eval.")
    parser.add_argument("--learning_rate",
                        default=5e-5,
                        type=float,
                        help="The initial learning rate for Adam.")
    parser.add_argument("--num_train_epochs",
                        default=2.0,
                        type=float,
                        help="Total number of training epochs to perform.")
    parser.add_argument(
        "--warmup_proportion",
        default=0.1,
        type=float,
        help=
        "Proportion of training to perform linear learning rate warmup for. "
        "E.g., 0.1 = 10%% of training.")
    parser.add_argument("--no_cuda",
                        default=False,
                        action='store_true',
                        help="Whether not to use CUDA when available")
    parser.add_argument("--local_rank",
                        type=int,
                        default=-1,
                        help="local_rank for distributed training on gpus")
    parser.add_argument('--seed',
                        type=int,
                        default=42,
                        help="random seed for initialization")
    parser.add_argument(
        '--gradient_accumulation_steps',
        type=int,
        default=1,
        help=
        "Number of updates steps to accumulate before performing a backward/update pass."
    )
    parser.add_argument(
        '--optimize_on_cpu',
        default=False,
        action='store_true',
        help=
        "Whether to perform optimization and keep the optimizer averages on CPU"
    )
    parser.add_argument(
        '--fp16',
        default=False,
        action='store_true',
        help="Whether to use 16-bit float precision instead of 32-bit")
    parser.add_argument(
        '--loss_scale',
        type=float,
        default=128,
        help=
        'Loss scaling, positive power of 2 values can improve fp16 convergence.'
    )

    args = parser.parse_args()

    processors = {"mrpc": MrpcProcessor}

    if args.local_rank == -1 or args.no_cuda:
        device = torch.device("cuda" if torch.cuda.is_available()
                              and not args.no_cuda else "cpu")
        n_gpu = torch.cuda.device_count()
    else:
        device = torch.device("cuda", args.local_rank)
        n_gpu = 1
        # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
        torch.distributed.init_process_group(backend='nccl')
        if args.fp16:
            logger.info(
                "16-bits training currently not supported in distributed training"
            )
            args.fp16 = False  # (see https://github.com/pytorch/pytorch/pull/13496)
    logger.info("device %s n_gpu %d distributed training %r", device, n_gpu,
                bool(args.local_rank != -1))

    if args.gradient_accumulation_steps < 1:
        raise ValueError(
            "Invalid gradient_accumulation_steps parameter: {}, should be >= 1"
            .format(args.gradient_accumulation_steps))

    args.train_batch_size = int(args.train_batch_size /
                                args.gradient_accumulation_steps)

    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed)

    if not args.do_train and not args.do_eval:
        raise ValueError(
            "At least one of `do_train` or `do_eval` must be True.")

    # if os.path.exists(args.output_dir) and os.listdir(args.output_dir):
    #     raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
    os.makedirs(args.output_dir, exist_ok=True)

    task_name = args.task_name.lower()

    if task_name not in processors:
        raise ValueError("Task not found: %s" % (task_name))

    processor = processors[task_name]()
    label_list = processor.get_labels()

    tokenizer = BertTokenizer.from_pretrained(args.bert_model,
                                              do_lower_case=args.do_lower_case)

    train_examples = None
    num_train_steps = None
    if args.do_train:
        train_examples = processor.get_train_examples(args.data_dir)
        num_train_steps = int(
            len(train_examples) / args.train_batch_size /
            args.gradient_accumulation_steps * args.num_train_epochs)

    # Prepare model
    model = BertForNextSentencePrediction.from_pretrained(args.bert_model)
    # model = BertForNextSentencePrediction.from_pretrained(args.bert_model,
    #                                                       cache_dir=PYTORCH_PRETRAINED_BERT_CACHE / 'distributed_{}'.format(args.local_rank))
    if args.fp16:
        model.half()
    model.to(device)
    if args.local_rank != -1:
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[args.local_rank], output_device=args.local_rank)
    elif n_gpu > 1:
        model = torch.nn.DataParallel(model)

    # Prepare optimizer
    if args.fp16:
        param_optimizer = [
            (n, param.clone().detach().to('cpu').float().requires_grad_())
            for n, param in model.named_parameters()
        ]
    elif args.optimize_on_cpu:
        param_optimizer = [(n,
                            param.clone().detach().to('cpu').requires_grad_())
                           for n, param in model.named_parameters()]
    else:
        param_optimizer = list(model.named_parameters())
    no_decay = ['bias', 'gamma', 'beta']
    optimizer_grouped_parameters = [{
        'params':
        [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
        'weight_decay_rate':
        0.01
    }, {
        'params':
        [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
        'weight_decay_rate':
        0.0
    }]
    t_total = num_train_steps
    if args.local_rank != -1:
        t_total = t_total // torch.distributed.get_world_size()
    optimizer = BertAdam(optimizer_grouped_parameters,
                         lr=args.learning_rate,
                         warmup=args.warmup_proportion,
                         t_total=t_total)

    global_step = 0
    if args.do_train:
        train_features = convert_examples_to_features(train_examples,
                                                      label_list,
                                                      args.max_seq_length,
                                                      tokenizer)
        logger.info("***** Running training *****")
        logger.info("  Num examples = %d", len(train_examples))
        logger.info("  Batch size = %d", args.train_batch_size)
        logger.info("  Num steps = %d", num_train_steps)
        all_input_ids = torch.tensor([f.input_ids for f in train_features],
                                     dtype=torch.long)
        all_input_mask = torch.tensor([f.input_mask for f in train_features],
                                      dtype=torch.long)
        all_segment_ids = torch.tensor([f.segment_ids for f in train_features],
                                       dtype=torch.long)
        all_label_ids = torch.tensor([f.label_id for f in train_features],
                                     dtype=torch.long)
        train_data = TensorDataset(all_input_ids, all_input_mask,
                                   all_segment_ids, all_label_ids)
        if args.local_rank == -1:
            train_sampler = RandomSampler(train_data)
        else:
            train_sampler = DistributedSampler(train_data)
        train_dataloader = DataLoader(train_data,
                                      sampler=train_sampler,
                                      batch_size=args.train_batch_size)

        for epoch in trange(int(args.num_train_epochs), desc="Epoch"):
            model.train()
            tr_loss = 0
            nb_tr_examples, nb_tr_steps = 0, 0
            for step, batch in enumerate(
                    tqdm(train_dataloader, desc="Iteration")):
                batch = tuple(t.to(device) for t in batch)
                input_ids, input_mask, segment_ids, label_ids = batch
                loss = model(input_ids, segment_ids, input_mask, label_ids)
                if n_gpu > 1:
                    loss = loss.mean()  # mean() to average on multi-gpu.
                if args.fp16 and args.loss_scale != 1.0:
                    # rescale loss for fp16 training
                    # see https://docs.nvidia.com/deeplearning/sdk/mixed-precision-training/index.html
                    loss = loss * args.loss_scale
                if args.gradient_accumulation_steps > 1:
                    loss = loss / args.gradient_accumulation_steps
                loss.backward()
                tr_loss += loss.item()
                nb_tr_examples += input_ids.size(0)
                nb_tr_steps += 1
                if (step + 1) % args.gradient_accumulation_steps == 0:
                    if args.fp16 or args.optimize_on_cpu:
                        if args.fp16 and args.loss_scale != 1.0:
                            # scale down gradients for fp16 training
                            for param in model.parameters():
                                if param.grad is not None:
                                    param.grad.data = param.grad.data / args.loss_scale
                        is_nan = set_optimizer_params_grad(
                            param_optimizer,
                            model.named_parameters(),
                            test_nan=True)
                        if is_nan:
                            logger.info(
                                "FP16 TRAINING: Nan in gradients, reducing loss scaling"
                            )
                            args.loss_scale = args.loss_scale / 2
                            model.zero_grad()
                            continue
                        optimizer.step()
                        copy_optimizer_params_to_model(
                            model.named_parameters(), param_optimizer)
                    else:
                        optimizer.step()
                    model.zero_grad()
                    global_step += 1
            model.eval()
            torch.save(model.state_dict(),
                       "../data/models/base-uncased-192-2of9-ep%s.pt" % epoch)

    if args.do_eval and (args.local_rank == -1
                         or torch.distributed.get_rank() == 0):
        eval_examples = processor.get_dev_examples(args.data_dir)
        eval_features = convert_examples_to_features(eval_examples, label_list,
                                                     args.max_seq_length,
                                                     tokenizer)
        logger.info("***** Running evaluation *****")
        logger.info("  Num examples = %d", len(eval_examples))
        logger.info("  Batch size = %d", args.eval_batch_size)
        all_input_ids = torch.tensor([f.input_ids for f in eval_features],
                                     dtype=torch.long)
        all_input_mask = torch.tensor([f.input_mask for f in eval_features],
                                      dtype=torch.long)
        all_segment_ids = torch.tensor([f.segment_ids for f in eval_features],
                                       dtype=torch.long)
        all_label_ids = torch.tensor([f.label_id for f in eval_features],
                                     dtype=torch.long)
        eval_data = TensorDataset(all_input_ids, all_input_mask,
                                  all_segment_ids, all_label_ids)
        # Run prediction for full data
        eval_sampler = SequentialSampler(eval_data)
        eval_dataloader = DataLoader(eval_data,
                                     sampler=eval_sampler,
                                     batch_size=args.eval_batch_size)

        model.eval()
        eval_loss, eval_accuracy = 0, 0
        nb_eval_steps, nb_eval_examples = 0, 0
        for input_ids, input_mask, segment_ids, label_ids in eval_dataloader:
            input_ids = input_ids.to(device)
            input_mask = input_mask.to(device)
            segment_ids = segment_ids.to(device)
            label_ids = label_ids.to(device)

            with torch.no_grad():
                tmp_eval_loss = model(input_ids, segment_ids, input_mask,
                                      label_ids)
                logits = model(input_ids, segment_ids, input_mask)

            logits = logits.detach().cpu().numpy()
            label_ids = label_ids.to('cpu').numpy()
            tmp_eval_accuracy = accuracy(logits, label_ids)

            eval_loss += tmp_eval_loss.mean().item()
            eval_accuracy += tmp_eval_accuracy

            nb_eval_examples += input_ids.size(0)
            nb_eval_steps += 1

        eval_loss = eval_loss / nb_eval_steps
        eval_accuracy = eval_accuracy / nb_eval_examples

        result = {
            'eval_loss': eval_loss,
            'eval_accuracy': eval_accuracy,
            'global_step': global_step,
            'loss': tr_loss / nb_tr_steps
        }

        output_eval_file = os.path.join(args.output_dir, "eval_results.txt")
        with open(output_eval_file, "w", encoding='utf-8') as writer:
            logger.info("***** Eval results *****")
            for key in sorted(result.keys()):
                logger.info("  %s = %s", key, str(result[key]))
                writer.write("%s = %s\n" % (key, str(result[key])))
Ejemplo n.º 7
0
from pytorch_pretrained_bert.modeling import BertConfig, BertForNextSentencePrediction

# from next_sentence.processing import create_features, read_file, MAX_LENGTH
from utils.utils import features_translation, tokenizer

SOURCE_PATH = '/home/gump/Software/pycharm-2018.1.6/projects/bert-for-classificaion/' \
              'next_sentence/data/'
CONFIG_FILE = SOURCE_PATH+'model/model_2.2.2/config_4.json'
MODEL_FILE = SOURCE_PATH+'model/model_2.2.2/model_4.bin'
TEST_FILE = '/home/gump/Software/pycharm-2018.1.6/projects/bert-for-classificaion/' \
            'next_sentence/data/chat_bot_2.2.0.csv'

MAX_LENGTH = 30
# load model
config = BertConfig(CONFIG_FILE)
model = BertForNextSentencePrediction(config)
model.load_state_dict(torch.load(MODEL_FILE))
if torch.cuda.is_available():
    model.cuda()
model.eval()

# load data
tokenizer = tokenizer()


def predict(text_a, text_b):
    token_a = tokenizer.tokenize(text_a)
    token_b = tokenizer.tokenize(text_b)

    token_text = ['[CLS]'] + token_a + ['[SEP]'] + token_b + ['[SEP]']
    tokens_ids = tokenizer.convert_tokens_to_ids(token_text)
Ejemplo n.º 8
0
def main():
    parser = argparse.ArgumentParser()

    # Required parameters
    parser.add_argument(
        "--data_dir",
        default="../data/bert",
        type=str,
        required=False,
        help=
        "The input data dir. Should contain the _p.tsv files (or other data files) for the task."
    )
    parser.add_argument(
        "--bert_model",
        default='bert-base-uncased',
        type=str,
        required=False,
        help="Bert pre-trained model selected in the list: bert-base-uncased, "
        "bert-large-uncased, bert-base-cased, bert-base-multilingual, bert-base-chinese."
    )
    parser.add_argument("--task_name",
                        default='MRPC',
                        type=str,
                        required=False,
                        help="The name of the task to train.")
    parser.add_argument(
        "--output_dir",
        default="../data/bert/output",
        type=str,
        required=False,
        help="The output directory where the model checkpoints will be written."
    )

    # Other parameters
    parser.add_argument(
        "--max_seq_length",
        default=192,
        type=int,
        help=
        "The maximum total input sequence length after WordPiece tokenization. \n"
        "Sequences longer than this will be truncated, and sequences shorter \n"
        "than this will be padded.")
    parser.add_argument("--do_train",
                        default=False,
                        action='store_true',
                        help="Whether to run training.")
    parser.add_argument("--do_eval",
                        default=False,
                        action='store_true',
                        help="Whether to run eval on the dev set.")
    parser.add_argument("--do_predict",
                        default=True,
                        action='store_true',
                        help="Whether to run eval on the dev set.")
    parser.add_argument(
        "--do_lower_case",
        default=True,
        action='store_true',
        help="Set this flag if you are using an uncased model.")
    parser.add_argument("--train_batch_size",
                        default=128,
                        type=int,
                        help="Total batch size for training.")
    parser.add_argument("--eval_batch_size",
                        default=128,
                        type=int,
                        help="Total batch size for eval.")
    parser.add_argument("--learning_rate",
                        default=5e-5,
                        type=float,
                        help="The initial learning rate for Adam.")
    parser.add_argument("--num_train_epochs",
                        default=3.0,
                        type=float,
                        help="Total number of training epochs to perform.")
    parser.add_argument(
        "--warmup_proportion",
        default=0.1,
        type=float,
        help=
        "Proportion of training to perform linear learning rate warmup for. "
        "E.g., 0.1 = 10%% of training.")
    parser.add_argument("--no_cuda",
                        default=False,
                        action='store_true',
                        help="Whether not to use CUDA when available")
    parser.add_argument("--local_rank",
                        type=int,
                        default=-1,
                        help="local_rank for distributed training on gpus")
    parser.add_argument('--seed',
                        type=int,
                        default=42,
                        help="random seed for initialization")
    parser.add_argument(
        '--gradient_accumulation_steps',
        type=int,
        default=1,
        help=
        "Number of updates steps to accumulate before performing a backward/update pass."
    )
    parser.add_argument(
        '--optimize_on_cpu',
        default=False,
        action='store_true',
        help=
        "Whether to perform optimization and keep the optimizer averages on CPU"
    )
    parser.add_argument(
        '--fp16',
        default=False,
        action='store_true',
        help="Whether to use 16-bit float precision instead of 32-bit")
    parser.add_argument(
        '--loss_scale',
        type=float,
        default=128,
        help=
        'Loss scaling, positive power of 2 values can improve fp16 convergence.'
    )
    parser.add_argument('--load_model_path',
                        default='../data/models/base-uncased-192-2of9-ep1.pt',
                        help='Load model for prediction')

    args = parser.parse_args()

    processors = {"mrpc": MrpcProcessor}

    if args.local_rank == -1 or args.no_cuda:
        device = torch.device("cuda" if torch.cuda.is_available()
                              and not args.no_cuda else "cpu")
        n_gpu = torch.cuda.device_count()
    else:
        device = torch.device("cuda", args.local_rank)
        n_gpu = 1
        # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
        torch.distributed.init_process_group(backend='nccl')
        if args.fp16:
            logger.info(
                "16-bits training currently not supported in distributed training"
            )
            args.fp16 = False  # (see https://github.com/pytorch/pytorch/pull/13496)
    logger.info("device %s n_gpu %d distributed training %r", device, n_gpu,
                bool(args.local_rank != -1))

    if args.gradient_accumulation_steps < 1:
        raise ValueError(
            "Invalid gradient_accumulation_steps parameter: {}, should be >= 1"
            .format(args.gradient_accumulation_steps))

    args.train_batch_size = int(args.train_batch_size /
                                args.gradient_accumulation_steps)

    random.seed(args.seed)
    np.random.seed(args.seed)
    torch.manual_seed(args.seed)
    if n_gpu > 0:
        torch.cuda.manual_seed_all(args.seed)

    if not args.do_train and not args.do_eval and not args.do_predict:
        raise ValueError(
            "At least one of `do_train` or `do_eval` or `do_predict` must be True."
        )

    # if os.path.exists(args.output_dir) and os.listdir(args.output_dir):
    #     raise ValueError("Output directory ({}) already exists and is not empty.".format(args.output_dir))
    os.makedirs(args.output_dir, exist_ok=True)

    task_name = args.task_name.lower()

    if task_name not in processors:
        raise ValueError("Task not found: %s" % (task_name))

    processor = processors[task_name]()
    label_list = processor.get_labels()

    tokenizer = BertTokenizer.from_pretrained(args.bert_model,
                                              do_lower_case=args.do_lower_case)

    train_examples = None
    num_train_steps = None
    if args.do_train:
        train_examples = processor.get_train_examples(args.data_dir)
        num_train_steps = int(
            len(train_examples) / args.train_batch_size /
            args.gradient_accumulation_steps * args.num_train_epochs)

    # Prepare model
    model = BertForNextSentencePrediction.from_pretrained(args.bert_model)
    # model = BertForNextSentencePrediction.from_pretrained(args.bert_model,
    #                                                       cache_dir=PYTORCH_PRETRAINED_BERT_CACHE / 'distributed_{}'.format(args.local_rank))

    if args.fp16:
        model.half()
    model.to(device)
    if args.local_rank != -1:
        model = torch.nn.parallel.DistributedDataParallel(
            model, device_ids=[args.local_rank], output_device=args.local_rank)
    elif n_gpu > 1:
        model = torch.nn.DataParallel(model)

    print('model loading')
    model.load_state_dict(torch.load(args.load_model_path))
    print('model loaded')

    # Prepare optimizer
    if args.fp16:
        param_optimizer = [
            (n, param.clone().detach().to('cpu').float().requires_grad_())
            for n, param in model.named_parameters()
        ]
    elif args.optimize_on_cpu:
        param_optimizer = [(n,
                            param.clone().detach().to('cpu').requires_grad_())
                           for n, param in model.named_parameters()]
    else:
        param_optimizer = list(model.named_parameters())
    no_decay = ['bias', 'gamma', 'beta']
    optimizer_grouped_parameters = [{
        'params':
        [p for n, p in param_optimizer if not any(nd in n for nd in no_decay)],
        'weight_decay_rate':
        0.01
    }, {
        'params':
        [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
        'weight_decay_rate':
        0.0
    }]
    t_total = num_train_steps
    if args.local_rank != -1:
        t_total = t_total // torch.distributed.get_world_size()
    optimizer = BertAdam(optimizer_grouped_parameters,
                         lr=args.learning_rate,
                         warmup=args.warmup_proportion,
                         t_total=t_total)

    global_step = 0

    if args.do_predict and (args.local_rank == -1
                            or torch.distributed.get_rank() == 0):

        eval_examples = processor.get_test_examples(args.data_dir)
        eval_features = convert_examples_to_features(eval_examples, label_list,
                                                     args.max_seq_length,
                                                     tokenizer)
        logger.info("***** Running evaluation *****")
        logger.info("  Num examples = %d", len(eval_examples))
        logger.info("  Batch size = %d", args.eval_batch_size)
        all_input_ids = torch.tensor([f.input_ids for f in eval_features],
                                     dtype=torch.long)
        all_input_mask = torch.tensor([f.input_mask for f in eval_features],
                                      dtype=torch.long)
        all_segment_ids = torch.tensor([f.segment_ids for f in eval_features],
                                       dtype=torch.long)
        all_label_ids = torch.tensor([f.label_id for f in eval_features],
                                     dtype=torch.long)
        eval_data = TensorDataset(all_input_ids, all_input_mask,
                                  all_segment_ids, all_label_ids)
        # Run prediction for full data
        eval_sampler = SequentialSampler(eval_data)
        eval_dataloader = DataLoader(eval_data,
                                     sampler=eval_sampler,
                                     batch_size=args.eval_batch_size)

        model.eval()
        count = 0
        predictions = [0]
        for input_ids, input_mask, segment_ids, label_ids in eval_dataloader:
            input_ids = input_ids.to(device)
            input_mask = input_mask.to(device)
            segment_ids = segment_ids.to(device)
            label_ids = label_ids.to(device)

            with torch.no_grad():
                tmp_eval_loss = model(input_ids, segment_ids, input_mask,
                                      label_ids)
                logits = model(input_ids, segment_ids, input_mask)

            logits = logits.detach().cpu().numpy()  #predicted label
            logits = logits[:, 1]
            predictions.extend(logits)
            count += args.eval_batch_size
            print(count / len(eval_examples) * 100)

        data = pd.read_csv('../data/bert/eval2_unlabelled_p.tsv',
                           sep='\t',
                           header=None)
        data[len(data.columns)] = predictions
        data.to_csv('../data/pre-answer.tsv',
                    sep='\t',
                    header=False,
                    index=False)

        # Converting to submission format
        data = pd.read_csv('../data/pre-answer.tsv',
                           sep='\t',
                           names=[
                               'query_id', 'query_text', 'passage_text',
                               'passage_id', 'cs'
                           ])
        uniq, index = np.unique(data['query_id'], return_index=True)
        query_id = uniq[index.argsort()]
        scores = data['cs'].values.reshape(-1, 10)
        print(scores.shape)
        answer = np.column_stack((query_id, scores))
        answer = pd.DataFrame(answer)
        answer.iloc[:, 0] = answer.iloc[:, 0].astype('int')
        answer.to_csv('../data/answer.tsv', sep='\t', header=None, index=False)
Ejemplo n.º 9
0
def main():
    parser = argparse.ArgumentParser()

    #files arguments
    parser.add_argument("-model_name",
                        default="classifacation_2",
                        help="Name of the model. To be used in filename")
    parser.add_argument("-model_group",
                        default="baseline",
                        help="dir to put model in")
    parser.add_argument("-old_model_name",
                        default=None,
                        help="filename of model to be loaded")
    parser.add_argument("-model_version",
                        default=0,
                        help="version to be added to the models filename")
    parser.add_argument("-bert_model",
                        default="bert-base-uncased",
                        help="Bert pre-trained model")
    parser.add_argument("-train",
                        default=True,
                        help="true if you want to train the model")
    parser.add_argument("-val",
                        default=True,
                        help="true if you want to evaluate the model")
    parser.add_argument("-train_batch_size",
                        default=65,
                        help="batch size for training dataset")
    parser.add_argument("-val_batch_size",
                        default=10,
                        help="batch size for validation dataset")
    parser.add_argument("-max_len",
                        default=60,
                        help="max length for input sequence")
    parser.add_argument("-learning_rate",
                        default=0.00005,
                        help="learning weight for optimization")
    parser.add_argument("-gradient_accumulation_steps", default=1, help="")
    parser.add_argument("-num_epochs",
                        default=2,
                        help="number of epochs for training, and validation")
    parser.add_argument("-num_outpout_checkpoints_train",
                        default=-2,
                        help="determines how many times the loss is outputed "
                        "during training")
    parser.add_argument("-num_outpout_checkpoints_val",
                        default=1,
                        help="determines how many times metrics are outputed "
                        "during training")
    parser.add_argument(
        "-warmup_proportion",
        default=0.1,
        help="Proportion of training to perform linear learning"
        " rate warmup for.")

    args = parser.parse_args()
    args.project_file = os.getcwd()
    args.dataset_path = "{}/data/".format(args.project_file)
    args.output_dir = '{}/classification/{}/{}_{}/'.format(
        args.project_file, args.model_group, args.model_name,
        args.model_version)

    os.makedirs(args.output_dir, exist_ok=True)

    # check_files(file)

    use_old_model = args.old_model_name is not None
    if use_old_model:
        args.old_model_filename = '{}/classification/{}/{}' \
        '/'.format(args.project_file,
            args.model_group, args.old_model_name)

        args = load_args("{}args.json".format(args.old_model_filename), args)

    model = cuda(BertForNextSentencePrediction.from_pretrained(
        args.bert_model))

    phases = []
    data_loaders = []

    #loads features from file that is created in make_features.py
    #it takes a long time to create features which is why there is a seperate
    #file
    args.features_path = "{}/classification/features/max_{}/".format(
        args.project_file, args.max_len)

    if not os.path.exists(args.features_path):
        raise ValueError(
            "you must create features with classification/make_features.py "
            "prior to running this model.\n need file: {}".format(
                args.features_path))

    #get train features, and make optimizer
    if args.train:
        train_features = load_features("{}train.pkl".format(
            args.features_path))
        dataloader_train = make_dataloader(train_features,
                                           args.train_batch_size)
        data_loaders.append(dataloader_train)
        phases.append('train')

        num_train_steps = int(
            len(train_features) / args.train_batch_size /
            args.gradient_accumulation_steps * args.num_epochs)

        if args.num_outpout_checkpoints_train < 0:
            args.num_outpout_checkpoints_train = len(train_features) /  \
            args.train_batch_size  / (args.num_outpout_checkpoints_train * -1)

        param_optimizer = list(model.named_parameters())
        no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
        optimizer_grouped_parameters = [{
            'params': [
                p for n, p in param_optimizer
                if not any(nd in n for nd in no_decay)
            ],
            'weight_decay':
            0.01
        }, {
            'params':
            [p for n, p in param_optimizer if any(nd in n for nd in no_decay)],
            'weight_decay':
            0.0
        }]
        t_total = num_train_steps

        optimizer = BertAdam(optimizer_grouped_parameters,
                             lr=args.learning_rate,
                             warmup=args.warmup_proportion,
                             t_total=t_total)

        args.train_len = len(train_features)
    else:
        optimizer = None

    # get val examples
    if args.val:
        val_features = load_features("{}val.pkl".format(args.features_path))
        dataloader_val = make_dataloader(val_features, args.val_batch_size)
        data_loaders.append(dataloader_val)
        phases.append('val')

        args.val_len = len(val_features)

    #outoput args
    string = ""
    for k, v in vars(args).items():
        string += "{}: {}\n".format(k, v)
    print(string)
    output = string + '\n'

    #load checkpoint
    if use_old_model:
        model, optimizer = load_checkpoint(
            "{}model".format(args.old_model_filename), model, optimizer)

        #output results from last model
        results = load_results("{}metrics.json".format(
            args.old_model_filename))
        string = "\n--loaded model--\ntrain loss: {}\nval loss: {}\n" \
            "num_epoch: {}\n".format(results[
            "average_train_epoch_losses"][-1], results["val_loss"][-1],
            results["epoch"])
        output += string
        print(string)

    outfile = open("{}output".format(args.output_dir), 'w')
    outfile.write(output)
    outfile.close()

    with open("{}args.json".format(args.output_dir), 'w') as fp:
        json.dump(vars(args), fp, indent=4, sort_keys=True)

    best_model = model
    best_optimizer = optimizer

    metrics = {
        "accuracy": [],
        "precision": [],
        "recall": [],
        "f1": [],
        "lowest_loss": 100,
        "average_train_epoch_losses": [],
        "train_epoch_losses": [],
        "val_loss": [],
        "best_epoch": 0
    }

    highest_acc = 0

    for epoch in range(0, args.num_epochs):
        start = time.clock()
        string = 'Epoch: {}\n'.format(epoch)
        print(string, end='')
        output = output + '\n' + string
        metrics["epoch"] = epoch

        #if epoch == 6:
        #    model.unfreeze_embeddings()
        #    parameters = list(model.parameters())
        #    optimizer = torch.optim.Adam(
        #        parameters, amsgrad=True, weight_decay=weight_decay)

        #use when you validate before training, and what to validate on last epoch
        #if epoch == params["nb_epochs"] -1 and params["val"] and params["train"]:
        #    phases.append('val')
        #    data_loaders.append(dataloader_val)

        for phase, data_loader in zip(phases, data_loaders):
            if phase == 'train':
                model.train()
                intervals = args.num_outpout_checkpoints_train
                string = '--Train-- \n'
            else:
                model.eval()
                intervals = args.num_outpout_checkpoints_val
                string = '--Validation-- \n'

            print(string, end='')
            output = output + '\n' + string

            epoch_loss = []
            epoch_accuracy = []
            epoch_precision = []
            epoch_recall = []
            epoch_f1 = []
            j = 1

            for i, batch in enumerate(tqdm(data_loader, desc="batch")):
                batch = tuple(variable(t) for t in batch)
                input_ids, input_mask, segment_ids, label_ids = batch

                loss = model(input_ids, segment_ids, input_mask, label_ids)
                if phase == 'val':
                    outputs = model(input_ids, segment_ids, input_mask)

                epoch_loss.append(float(loss))
                average_epoch_loss = np.mean(epoch_loss)

                if phase == 'train':
                    loss.backward()
                    #torch.nn.utils.clip_grad_norm_(parameters,
                    #    params["max_grad_norm"])
                    optimizer.step()
                    if (len(data_loader) / intervals) * j <= i + 1:
                        #if len(data_loader) == i + 1:
                        string = ('Example {:03d} | {} loss: {:.3f}'.format(
                            i, phase, average_epoch_loss))
                        #print(string, end='\n')
                        output = output + string + '\n'
                        outfile = open("{}output".format(args.output_dir), 'w')
                        outfile.write(output)
                        outfile.close()
                        j += 1
                    optimizer.zero_grad()

                else:
                    # get result metrics
                    targets = label_ids.cpu().numpy()
                    predicted = torch.argmax(outputs.view(-1, 2),
                                             -1).cpu().numpy()
                    accuracy, precision, recall, f1 = classifier_accuracy(
                        targets, predicted)
                    #print('{},{},{},{}'.format(accuracy, precision, recall,
                    # f1))
                    epoch_accuracy.append(accuracy)
                    epoch_precision.append(precision)
                    epoch_recall.append(recall)
                    epoch_f1.append(f1)
                    if (len(data_loader) / intervals) * j <= i + 1:
                        # if len(data_loader) == i + 1:
                        string = ('Example {:03d} | {} loss: {:.3f}'.format(
                            i, phase, average_epoch_loss))
                        # print(string, end='\n')
                        output = output + string + '\n'
                        average_epoch_accuracy = np.mean(epoch_accuracy)
                        average_epoch_precision = np.mean(epoch_precision)
                        average_epoch_recall = np.mean(epoch_recall)
                        average_epoch_f1 = np.mean(epoch_f1)
                        string = "Accuracy: {:.3f}\nPrecision: {:.3f}\n" \
                        "Recall: {:.3f}\nF1: {:.3f}\n".format(
                            average_epoch_accuracy, average_epoch_precision,
                            average_epoch_recall, average_epoch_f1)
                        output = output + string + '\n'
                        outfile = open("{}output".format(args.output_dir), 'w')
                        outfile.write(output)
                        outfile.close()
                        j += 1

            # print random sentence
            if phase == 'val':
                time_taken = time.clock() - start

                metrics["val_loss"].append(average_epoch_loss)
                string = ' {} loss: {:.3f} | time: {:.3f}'.format(
                    phase, average_epoch_loss, time_taken)
                string += ' | lowest loss: {:.3f} highest accuracy:' \
                    ' {:.3f}'.format(metrics["lowest_loss"], highest_acc)
                #print(string, end='\n')
                output = output + '\n' + string + '\n'

                average_epoch_accuracy = np.mean(epoch_accuracy)
                average_epoch_precision = np.mean(epoch_precision)
                average_epoch_recall = np.mean(epoch_recall)
                average_epoch_f1 = np.mean(epoch_f1)
                metrics["accuracy"].append(average_epoch_accuracy),
                metrics["precision"].append(average_epoch_precision)
                metrics["recall"].append(average_epoch_recall)
                metrics["f1"].append(average_epoch_f1)

                if average_epoch_loss < metrics["lowest_loss"]:
                    best_model = model
                    best_optimizer = optimizer
                    metrics["best_epoch"] = epoch
                    metrics["lowest_loss"] = average_epoch_loss

                save_checkpoint("{}model".format(args.output_dir), best_model,
                                best_optimizer, epoch, model, optimizer)

                with open("{}metrics.json".format(args.output_dir), 'w') as fp:
                    json.dump(metrics, fp, indent=4, sort_keys=True)

                string = "Accuracy: {:.3f}\nPrecision: {:.3f}\nRecall:" \
                         " {:.3f}\nF1: {:.3f}\n".format(
                    average_epoch_accuracy, average_epoch_precision,
                    average_epoch_recall, average_epoch_f1)
                # print(string, end='\n')
                output = output + string + '\n'
                """
                random_idx = np.random.randint(len(dataset_val))
                sentence_1, sentence_2, labels = dataset_val[random_idx]
                batch = tuple(variable(t) for t in batch)
                input_ids, input_mask, segment_ids, label_ids = batch

                outputs_var = model(sentence_1_var.unsqueeze(0),
                                    sentence_2_var.unsqueeze(0)) # unsqueeze
                #  to get the batch dimension
                outputs = outputs_var.squeeze(0).data.cpu().numpy()

                string = '> {}\n'.format(get_sentence_from_indices(
                    sentence_1, dataset_val.vocab, PairsDataset.EOS_TOKEN))

                string = string + u'> {}\n'.format(get_sentence_from_indices(
                    sentence_2, dataset_val.vocab, PairsDataset.EOS_TOKEN))

                string = string + u'target:{}|  P false:{:.3f}, P true:' \
                    u' {:.3f}'.format(targets, float(outputs[0]), float(outputs[1]))
                print(string, end='\n\n')
                output = output + string + '\n' + '\n'
                """
            else:
                metrics["average_train_epoch_losses"].append(
                    average_epoch_loss)
                metrics["train_epoch_losses"].append(epoch_loss)

            outfile = open("{}output".format(args.output_dir), 'w')
            outfile.write(output)
            outfile.close()
Ejemplo n.º 10
0
val_features = create_features(getattr(args, 'val_file'))
val_features_data = features_translation(val_features)

logging.info('create batch data')
train_data = DataLoader(train_features_data,
                        batch_size=getattr(args, 'batch_size'),
                        shuffle=True,
                        drop_last=True)
val_data = DataLoader(val_features_data,
                      batch_size=getattr(args, 'batch_size'),
                      shuffle=True,
                      drop_last=True)

# load model
logging.info('create model')
model = BertForNextSentencePrediction.from_pretrained(BERT_PRETRAINED_PATH,
                                                      cache_dir='data/cache')
if args.fp16:
    model.half()
if torch.cuda.is_available():
    model.cuda()

# optimizer
parameters = list(model.named_parameters())
# parameters = [n for n in parameters if 'pooler' not in n[0]]
no_decay = ['bias', 'LayerNorm.bias', 'LayerNorm.weight']
optimizer_grouped_parameters = [{
    'params':
    [p for n, p in parameters if not any(nd in n for nd in no_decay)],
    'weight_decay':
    0.01
}, {