Ejemplo n.º 1
0
    def __init__(self, model_file, vocabulary_path="model/"):
        opt, state_dict, vocab = interactive.load_model_file(model_file)

        data_loader, text_encoder = interactive.load_data(
            "conceptnet", opt, vocab, vocabulary_path)

        self.opt = opt
        self.data_loader = data_loader
        self.text_encoder = text_encoder

        n_ctx = data_loader.max_e1 + data_loader.max_e2 + data_loader.max_r
        n_vocab = len(text_encoder.encoder) + n_ctx

        model = interactive.make_model(opt, n_vocab, n_ctx, state_dict)

        self.model = model
Ejemplo n.º 2
0
    def __init__(self, model_file, vocabulary_path="model/"):
        opt, state_dict, vocab = interactive.load_model_file(model_file)
        # print(opt)
        data_loader, text_encoder = interactive.load_data(
            "atomic", opt, vocab, vocabulary_path)

        self.opt = opt
        self.data_loader = data_loader
        self.text_encoder = text_encoder

        n_ctx = data_loader.max_event + data_loader.max_effect
        n_vocab = len(text_encoder.encoder) + n_ctx

        model = interactive.make_model(opt, n_vocab, n_ctx, state_dict)

        self.model = model
Ejemplo n.º 3
0
import torch
from comet.interactive import functions as interactive
import comet.train.atomic_train as train
from comet.train.opt import OpenAIAdam
import comet.data.config as cfg

num_calibration_batches = 10

opt, state_dict = interactive.load_model_file("models/6.25e-05_adam_64_20500.pickle")

data_loader, text_encoder = interactive.load_data("atomic", opt)

n_ctx = data_loader.max_event + data_loader.max_effect
n_vocab = len(text_encoder.encoder) + n_ctx
model = interactive.make_model(opt, n_vocab, n_ctx, state_dict).to('cpu')
model.eval()


# Specify quantization configuration
# Start with simple min/max range estimation and per-tensor quantization of weights
model.qconfig = torch.quantization.default_qconfig
print(model.qconfig)
torch.quantization.prepare(model, inplace=True)

# Calibrate first
print('Post Training Quantization Prepare: Inserting Observers')
config_file = "config/atomic/config_{}.json".format(0)
config = cfg.read_config(cfg.load_config(config_file))
opt, meta = cfg.get_parameters(config)

# Calibrate with the training set
def main():
    parser = argparse.ArgumentParser()

    ## Required parameters
    parser.add_argument("--train_data_file",
                        default=None,
                        type=str,
                        required=True,
                        help="The input training data file (a text file).")
    parser.add_argument(
        "--output_dir",
        default=None,
        type=str,
        required=True,
        help=
        "The output directory where the model predictions and checkpoints will be written."
    )

    parser.add_argument("--eval_output_dir",
                        default=None,
                        type=str,
                        required=False,
                        help="Directory to write results to")
    parser.add_argument("--tb_dir",
                        default=None,
                        type=str,
                        required=False,
                        help="Directory to write tensorboard to")

    ## Other parameters
    parser.add_argument(
        "--task",
        default=None,
        type=str,
        help="The task to finetune the LM on. Currently supports None / anli")
    parser.add_argument("--include_comet",
                        default=False,
                        type=bool,
                        help="To include comet predictions or not")
    parser.add_argument("--comet_model_path",
                        default="comet-model/atomic_pretrained_model.th",
                        type=str,
                        help="Comet model path")
    parser.add_argument("--comet_vocab_path",
                        default="comet-vocab/",
                        type=str,
                        help="Comet model path")
    parser.add_argument("--comet_as_text",
                        default=False,
                        type=bool,
                        help="Comet feature encoded using text")
    parser.add_argument("--conditional_lm",
                        default=False,
                        type=bool,
                        help="Comet feature encoded using text")
    parser.add_argument(
        "--restrict_comet",
        default=False,
        type=bool,
        help="Restrict comet features to only o1's effect and o2's causes")
    parser.add_argument("--sotw",
                        default=False,
                        type=bool,
                        help="Use the state of the world model.")
    parser.add_argument(
        "--no_cache",
        default=False,
        type=bool,
        help="Restrict comet features to only o1's effect and o2's causes")

    parser.add_argument(
        "--eval_data_file",
        default=None,
        type=str,
        help=
        "An optional input evaluation data file to evaluate the perplexity on (a text file)."
    )

    parser.add_argument("--model_type",
                        default="bert",
                        type=str,
                        help="The model architecture to be fine-tuned.")
    parser.add_argument(
        "--model_name_or_path",
        default="bert-base-cased",
        type=str,
        help="The model checkpoint for weights initialization.")

    parser.add_argument(
        "--mlm",
        action='store_true',
        help=
        "Train with masked-language modeling loss instead of language modeling."
    )
    parser.add_argument(
        "--mlm_probability",
        type=float,
        default=0.15,
        help="Ratio of tokens to mask for masked language modeling loss")

    parser.add_argument(
        "--config_name",
        default="",
        type=str,
        help=
        "Optional pretrained config name or path if not the same as model_name_or_path"
    )
    parser.add_argument(
        "--tokenizer_name",
        default="",
        type=str,
        help=
        "Optional pretrained tokenizer name or path if not the same as model_name_or_path"
    )
    parser.add_argument(
        "--cache_dir",
        default="",
        type=str,
        help=
        "Optional directory to store the pre-trained models downloaded from s3 (instread of the default one)"
    )
    parser.add_argument(
        "--block_size",
        default=-1,
        type=int,
        help="Optional input sequence length after tokenization."
        "The training dataset will be truncated in block of this size for training."
        "Default to the model max input length for single sentence inputs (take into account special tokens)."
    )
    parser.add_argument("--do_train",
                        action='store_true',
                        help="Whether to run training.")
    parser.add_argument("--do_eval",
                        action='store_true',
                        help="Whether to run eval on the dev set.")
    parser.add_argument(
        "--evaluate_during_training",
        action='store_true',
        help="Run evaluation during training at each logging step.")
    parser.add_argument(
        "--do_lower_case",
        action='store_true',
        help="Set this flag if you are using an uncased model.")

    parser.add_argument("--per_gpu_train_batch_size",
                        default=4,
                        type=int,
                        help="Batch size per GPU/CPU for training.")
    parser.add_argument("--per_gpu_eval_batch_size",
                        default=4,
                        type=int,
                        help="Batch size per GPU/CPU for evaluation.")
    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("--learning_rate",
                        default=5e-5,
                        type=float,
                        help="The initial learning rate for Adam.")
    parser.add_argument("--weight_decay",
                        default=0.0,
                        type=float,
                        help="Weight deay if we apply some.")
    parser.add_argument("--adam_epsilon",
                        default=1e-8,
                        type=float,
                        help="Epsilon for Adam optimizer.")
    parser.add_argument("--max_grad_norm",
                        default=1.0,
                        type=float,
                        help="Max gradient norm.")
    parser.add_argument("--num_train_epochs",
                        default=1.0,
                        type=float,
                        help="Total number of training epochs to perform.")
    parser.add_argument(
        "--max_steps",
        default=-1,
        type=int,
        help=
        "If > 0: set total number of training steps to perform. Override num_train_epochs."
    )
    parser.add_argument("--warmup_steps",
                        default=0,
                        type=int,
                        help="Linear warmup over warmup_steps.")

    parser.add_argument('--logging_steps',
                        type=int,
                        default=50,
                        help="Log every X updates steps.")
    parser.add_argument('--save_steps',
                        type=int,
                        default=50,
                        help="Save checkpoint every X updates steps.")
    parser.add_argument(
        "--eval_all_checkpoints",
        action='store_true',
        help=
        "Evaluate all checkpoints starting with the same prefix as model_name_or_path ending and ending with step number"
    )
    parser.add_argument("--no_cuda",
                        action='store_true',
                        help="Avoid using CUDA when available")
    parser.add_argument('--overwrite_output_dir',
                        action='store_true',
                        help="Overwrite the content of the output directory")
    parser.add_argument(
        '--overwrite_cache',
        action='store_true',
        help="Overwrite the cached training and evaluation sets")
    parser.add_argument('--seed',
                        type=int,
                        default=42,
                        help="random seed for initialization")

    parser.add_argument(
        '--fp16',
        action='store_true',
        help=
        "Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"
    )
    parser.add_argument(
        '--fp16_opt_level',
        type=str,
        default='O1',
        help=
        "For fp16: Apex AMP optimization level selected in ['O0', 'O1', 'O2', and 'O3']."
        "See details at https://nvidia.github.io/apex/amp.html")
    parser.add_argument("--local_rank",
                        type=int,
                        default=-1,
                        help="For distributed training: local_rank")
    parser.add_argument('--server_ip',
                        type=str,
                        default='',
                        help="For distant debugging.")
    parser.add_argument('--server_port',
                        type=str,
                        default='',
                        help="For distant debugging.")
    args = parser.parse_args()

    if args.eval_output_dir is None:
        args.eval_output_dir = args.output_dir
    if args.tb_dir is None:
        args.tb_dir = args.output_dir

    if args.model_type in ["bert", "roberta"] and not args.mlm:
        raise ValueError(
            "BERT and RoBERTa do not have LM heads but masked LM heads. They must be run using the --mlm "
            "flag (masked language modeling).")
    if args.eval_data_file is None and args.do_eval:
        raise ValueError(
            "Cannot do evaluation without an evaluation data file. Either supply a file to --eval_data_file "
            "or remove the --do_eval argument.")

    if os.path.exists(args.output_dir) and os.listdir(
            args.output_dir
    ) and args.do_train and not args.overwrite_output_dir:
        raise ValueError(
            "Output directory ({}) already exists and is not empty. Use --overwrite_output_dir to overcome."
            .format(args.output_dir))

    # Setup distant debugging if needed
    if args.server_ip and args.server_port:
        # Distant debugging - see https://code.visualstudio.com/docs/python/debugging#_attach-to-a-local-script
        import ptvsd
        print("Waiting for debugger attach")
        ptvsd.enable_attach(address=(args.server_ip, args.server_port),
                            redirect_output=True)
        ptvsd.wait_for_attach()

    # Setup CUDA, GPU & distributed training
    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")
        args.n_gpu = torch.cuda.device_count()
    else:  # Initializes the distributed backend which will take care of sychronizing nodes/GPUs
        torch.cuda.set_device(args.local_rank)
        device = torch.device("cuda", args.local_rank)
        torch.distributed.init_process_group(backend='nccl')
        args.n_gpu = 1
    args.device = device

    # Setup logging
    logging.basicConfig(
        format='%(asctime)s - %(levelname)s - %(name)s -   %(message)s',
        datefmt='%m/%d/%Y %H:%M:%S',
        level=logging.INFO if args.local_rank in [-1, 0] else logging.WARN)
    logger.warning(
        "Process rank: %s, device: %s, n_gpu: %s, distributed training: %s, 16-bits training: %s",
        args.local_rank, device, args.n_gpu, bool(args.local_rank != -1),
        args.fp16)

    # Set seed
    set_seed(args)

    # Load pretrained model and tokenizer
    if args.local_rank not in [-1, 0]:
        torch.distributed.barrier(
        )  # Barrier to make sure only the first process in distributed training download model & vocab

    config_class, model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
    config = config_class.from_pretrained(
        args.config_name if args.config_name else args.model_name_or_path)
    tokenizer = tokenizer_class.from_pretrained(
        args.tokenizer_name
        if args.tokenizer_name else args.model_name_or_path,
        do_lower_case=args.do_lower_case)
    if args.block_size <= 0:
        args.block_size = tokenizer.max_len_single_sentence  # Our input block size will be the max possible for the model
    args.block_size = min(args.block_size, tokenizer.max_len_single_sentence)
    model = model_class.from_pretrained(
        args.model_name_or_path,
        from_tf=bool('.ckpt' in args.model_name_or_path),
        config=config)
    model.resize_token_embeddings(len(tokenizer))
    model.to(args.device)

    comet_text_encoder = None
    comet_data_loader = None
    comet_model = None
    if args.include_comet and not args.comet_as_text:
        opt, state_dict, vocab = comet_interactive.load_model_file(
            args.comet_model_path)
        # print(opt)
        comet_data_loader, comet_text_encoder = \
            comet_interactive.load_data("atomic", opt, vocab, args.comet_vocab_path)

        n_ctx = comet_data_loader.max_event + comet_data_loader.max_effect
        n_vocab = len(comet_text_encoder.encoder) + n_ctx
        if not torch.cuda.is_available():
            comet_interactive.set_compute_mode("cpu")
        comet_model = comet_interactive.make_model(opt, n_vocab, n_ctx,
                                                   state_dict)
        comet_model.train()
        model.set_comet_model(comet_model)
        model.set_comet_encoder(comet_text_encoder)

    if args.local_rank == 0:
        torch.distributed.barrier(
        )  # End of barrier to make sure only the first process in distributed training download model & vocab

    logger.info("Training/evaluation parameters %s", args)

    # Training
    if args.do_train:
        if args.local_rank not in [-1, 0]:
            torch.distributed.barrier(
            )  # Barrier to make sure only the first process in distributed training process the dataset, and the others will use the cache

        if args.task is None:
            train_dataset = load_and_cache_examples(args,
                                                    tokenizer,
                                                    evaluate=False)
        elif args.task == "anli":
            train_dataset = load_and_cache_anli_examples(
                args,
                tokenizer,
                evaluate=False,
                include_comet=args.include_comet,
                comet_text_encoder=comet_text_encoder,
                comet_data_loader=comet_data_loader,
                sotw=args.sotw)
        else:
            raise Exception("Task Unsopported")

        if args.local_rank == 0:
            torch.distributed.barrier()

        global_step, tr_loss = train(args, train_dataset, model, tokenizer,
                                     comet_text_encoder, comet_data_loader)
        logger.info(" global_step = %s, average loss = %s", global_step,
                    tr_loss)

    # Saving best-practices: if you use save_pretrained for the model and tokenizer, you can reload them using from_pretrained()
    if args.do_train and (args.local_rank == -1
                          or torch.distributed.get_rank() == 0):
        # Create output directory if needed
        if not os.path.exists(args.output_dir) and args.local_rank in [-1, 0]:
            os.makedirs(args.output_dir)

        logger.info("Saving model checkpoint to %s", args.output_dir)
        # Save a trained model, configuration and tokenizer using `save_pretrained()`.
        # They can then be reloaded using `from_pretrained()`
        model_to_save = model.module if hasattr(
            model,
            'module') else model  # Take care of distributed/parallel training
        model_to_save.save_pretrained(args.output_dir)
        tokenizer.save_pretrained(args.output_dir)

        # Good practice: save your training arguments together with the trained model
        torch.save(args, os.path.join(args.output_dir, 'training_args.bin'))

        # Load a trained model and vocabulary that you have fine-tuned
        model = model_class.from_pretrained(args.output_dir)
        tokenizer = tokenizer_class.from_pretrained(
            args.output_dir, do_lower_case=args.do_lower_case)
        model.to(args.device)

    # Evaluation
    results = {}
    if args.do_eval and args.local_rank in [-1, 0]:
        checkpoints = [args.output_dir]
        if args.eval_all_checkpoints:
            checkpoints = list(
                os.path.dirname(c) for c in sorted(
                    glob.glob(args.output_dir + '/**/' + WEIGHTS_NAME,
                              recursive=True)))
            logging.getLogger("pytorch_transformers.modeling_utils").setLevel(
                logging.WARN)  # Reduce logging
        logger.info("Evaluate the following checkpoints: %s", checkpoints)
        comet_model = None
        comet_text_encoder = None
        if args.include_comet and not args.comet_as_text:
            logging.info("Setting comet model")

            opt, state_dict, vocab = interactive.load_model_file(
                args.comet_model_path)
            # print(opt)
            comet_data_loader, comet_text_encoder = \
                interactive.load_data("atomic", opt, vocab, args.comet_vocab_path)

            n_ctx = comet_data_loader.max_event + comet_data_loader.max_effect
            n_vocab = len(comet_text_encoder.encoder) + n_ctx
            if not torch.cuda.is_available():
                interactive.set_compute_mode("cpu")
            comet_model = interactive.make_model(opt, n_vocab, n_ctx,
                                                 state_dict)

        for checkpoint in checkpoints:
            global_step = checkpoint.split(
                '-')[-1] if len(checkpoints) > 1 else ""
            model = model_class.from_pretrained(checkpoint)
            model.set_comet_model(comet_model)
            model.set_comet_encoder(comet_text_encoder)
            model.to(args.device)
            result = evaluate(args,
                              model,
                              tokenizer,
                              evaluate=False,
                              comet_text_encoder=comet_text_encoder,
                              comet_data_loader=comet_data_loader,
                              prefix=global_step)
            result = dict(
                (k + '_{}'.format(global_step), v) for k, v in result.items())
            results.update(result)

    return results
Ejemplo n.º 5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("--model_type",
                        default=None,
                        type=str,
                        required=True,
                        help="Model type selected in the list: " +
                        ", ".join(MODEL_CLASSES.keys()))
    parser.add_argument(
        "--model_name_or_path",
        default=None,
        type=str,
        required=True,
        help="Path to pre-trained model or shortcut name selected in the list: "
        + ", ".join(ALL_MODELS))
    parser.add_argument("--input-file",
                        type=str,
                        default=None,
                        help="File to load instance prompts from")
    parser.add_argument(
        "--task",
        type=str,
        default=None,
        help=
        "Which task for file input. If None, prompt is read as raw text 1 prompt per line in input-file"
    )
    parser.add_argument("--output-file",
                        type=str,
                        default=None,
                        help="File to load instance prompts from")
    parser.add_argument("--prompt", type=str, default="")
    parser.add_argument("--padding_text", type=str, default="")
    parser.add_argument("--length", type=int, default=20)
    parser.add_argument("--temperature", type=float, default=1.0)
    parser.add_argument("--top_k", type=int, default=0)
    parser.add_argument("--top_p", type=float, default=0.9)
    parser.add_argument("--no_cuda",
                        action='store_true',
                        help="Avoid using CUDA when available")
    parser.add_argument('--seed',
                        type=int,
                        default=42,
                        help="random seed for initialization")

    parser.add_argument("--include_comet",
                        default=False,
                        type=bool,
                        help="To include comet predictions or not")
    parser.add_argument("--comet_model_path",
                        default="comet-model/atomic_pretrained_model.th",
                        type=str,
                        help="Comet model path")
    parser.add_argument("--comet_vocab_path",
                        default="comet-vocab/",
                        type=str,
                        help="Comet model path")
    parser.add_argument("--comet_as_text",
                        default=False,
                        type=bool,
                        help="Comet feature encoded using text")
    parser.add_argument(
        "--restrict_comet",
        default=False,
        type=bool,
        help="Restrict comet features to only o1's effect and o2's causes")
    parser.add_argument("--num_samples",
                        default=1,
                        type=int,
                        help="No. of samples to obtain.")

    args = parser.parse_args()

    args.device = torch.device(
        "cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
    args.n_gpu = torch.cuda.device_count()

    set_seed(args)

    args.model_type = args.model_type.lower()
    model_class, tokenizer_class = MODEL_CLASSES[args.model_type]
    tokenizer = tokenizer_class.from_pretrained(args.model_name_or_path)
    model = model_class.from_pretrained(args.model_name_or_path)
    model.to(args.device)

    comet_text_encoder = None
    if args.include_comet and not args.comet_as_text:
        logging.info("Setting comet model")
        opt, state_dict, vocab = comet_interactive.load_model_file(
            args.comet_model_path)
        # print(opt)
        comet_data_loader, comet_text_encoder = \
            comet_interactive.load_data("atomic", opt, vocab, args.comet_vocab_path)

        n_ctx = comet_data_loader.max_event + comet_data_loader.max_effect
        n_vocab = len(comet_text_encoder.encoder) + n_ctx
        if not torch.cuda.is_available():
            comet_interactive.set_compute_mode("cpu")
        comet_model = comet_interactive.make_model(opt, n_vocab, n_ctx,
                                                   state_dict)
        model.set_comet_model(comet_model)
        model.set_comet_encoder(comet_text_encoder)

    model.eval()

    if args.length < 0 and model.config.max_position_embeddings > 0:
        args.length = model.config.max_position_embeddings
    elif 0 < model.config.max_position_embeddings < args.length:
        args.length = model.config.max_position_embeddings  # No generation bigger than model size
    elif args.length < 0:
        args.length = MAX_LENGTH  # avoid infinite loop

    print(args)

    def _prompt_to_gen(txt, comet_event_inputs, comet_attention_masks):
        if args.model_type in ["transfo-xl", "xlnet"]:
            # Models with memory likes to have a long prompt for short inputs.
            txt = (args.padding_text
                   if args.padding_text else PADDING_TEXT) + txt
        context_tokens = tokenizer.encode(txt)
        out = sample_sequence(model=model,
                              context=context_tokens,
                              length=args.length,
                              temperature=args.temperature,
                              top_k=args.top_k,
                              top_p=args.top_p,
                              device=args.device,
                              is_xlnet=bool(args.model_type == "xlnet"),
                              comet_input=comet_event_inputs,
                              comet_mask=comet_attention_masks,
                              num_samples=args.num_samples)
        out = out[0, len(context_tokens):].tolist()
        text = tokenizer.decode(out, clean_up_tokenization_spaces=True)
        return text

    if args.input_file is None:
        while True:
            raw_text = args.prompt if args.prompt else input(
                "Model prompt >>> ")
            text = _prompt_to_gen(raw_text)
            print(text)
            if args.prompt:
                break
    else:
        if args.task is None:
            lines = read_lines(args.input_file)
            generations = []
            for l in lines:
                generations.append(_prompt_to_gen(l))
            write_items(generations, args.output_file)
        elif args.task == "anli":
            records = read_jsonl_lines(args.input_file)
            idx = 0
            for record in tqdm.tqdm(records):
                input_text_tokens = None
                comet_event_inputs = None
                comet_attention_masks = None

                if args.model_type == "gpt2_for_anli_comet":
                    input_text_tokens, comet_event_inputs, comet_attention_masks = \
                        record_to_text_tokens_with_comet_pred(
                            tokenizer=tokenizer,
                            record=record,
                            is_eval=True,
                            comet_as_text=args.comet_as_text,
                            include_comet=args.include_comet,
                            comet_text_encoder=comet_text_encoder,
                            restrict_comet=args.restrict_comet
                        )
                elif args.model_type == "gpt2_for_anli":
                    input_text_tokens = anli_record_to_gpt_prompt(
                        tokenizer=tokenizer, record=record, is_eval=True)

                input_text = " ".join(input_text_tokens)
                gen = _prompt_to_gen(input_text, comet_event_inputs,
                                     comet_attention_masks)
                if args.model_type == "gpt2_for_anli":
                    period_idx = gen.find(".")
                    if period_idx != -1:
                        gen = gen[:period_idx]

                if 'generations' not in record:
                    record['generations'] = {}
                record['generations'][args.model_type] = [gen]

                if idx < 5:
                    print("Input context format: {}".format(input_text_tokens))
                    if comet_event_inputs is not None:
                        print("Comet event input format: {}".format(
                            comet_event_inputs))
                        print("Comet mask: {}".format(comet_attention_masks))
                idx += 1
            write_items([json.dumps(r) for r in records], args.output_file)