Of course! Here's an example adopted (albeit modified) from the transformers examples repo
# coding=utf-8
# Copyright 2018 Google AI, Google Brain and Carnegie Mellon University Authors and the HuggingFace Inc. team.
# Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
import logging
from typing import Tuple
import numpy as np
import torch
from transformers import *
from transformers.modeling_outputs import *
# Main code which runs the model
def run_model(input, args):
# We encode the prompt
encoded_prompt = tokenizer.encode(input, add_special_tokens=False, return_tensors="pt").to(args.device)
if encoded_prompt.size()[-1] == 0:
input_ids = None
else:
input_ids = encoded_prompt
# Then generate encoded output(s)
output_sequences = model.generate(
input_ids=input_ids,
max_length=args.length + len(encoded_prompt[0]),
temperature=args.temperature,
top_k=args.k,
top_p=args.p,
repetition_penalty=args.repetition_penalty,
do_sample=True,
num_return_sequences=args.num_return_sequences,
)
# Remove the batch dimension when returning multiple sequences
if len(output_sequences.shape) > 2:
output_sequences.squeeze_()
# Then decode and return those outputs
for output_sequence in output_sequences:
output_sequence = output_sequence.tolist()
text = tokenizer.decode(output_sequence, clean_up_tokenization_spaces=True)
# Remove all text after the stop token
text = text[: text.find(args.stop_token) if args.stop_token else None]
yield text
# Load a pretrained the model
def init_model(model_name_or_path, args):
# We must setup CUDA etc.
args.device = torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu")
args.n_gpu = 0 if args.no_cuda else torch.cuda.device_count()
logger.warning(f"device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fp16}")
# Allow a predefined seed for consistent generation
np.random.seed(args.seed)
torch.manual_seed(args.seed)
if args.n_gpu > 0:
torch.cuda.manual_seed_all(args.seed)
# Here we are using the GPT2 model.
# There are others, but do note some of them require additional setup, input, and output processing
model = transformers.GPT2LMHeadModel.from_pretrained(model_name_or_path)
model.to(args.device)
if args.fp16:
model.half()
# We must use the corresponding tokenizer to encode / decode as well
tokenizer = transformers.GPT2Tokenizer.from_pretrained(model_name_or_path)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# Make sure that we have the proper length (see adjust_length_to_model)
args.length = adjust_length_to_model(args.length, max_sequence_length=model.config.max_position_embeddings)
return model, tokenizer
def adjust_length_to_model(length, max_sequence_length):
if length < 0 and max_sequence_length > 0:
length = max_sequence_length
elif 0 < max_sequence_length < length:
length = max_sequence_length # No generation bigger than model size
elif length < 0:
length = 10000 # avoid infinite loop
return length
# This is general Python best practice
def setup_logger():
logging.basicConfig(
format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
datefmt="%m/%d/%Y %H:%M:%S",
level=logging.INFO,
)
global logger = logging.getLogger(__name__)
# Use the model from CLI, if this python file is run directly
def main():
parser = argparse.ArgumentParser()
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(MODEL_CLASSES.keys()),
)
parser.add_argument("--prompt", type=str, default="")
parser.add_argument("--length", type=int, default=20)
parser.add_argument("--stop_token", type=str, default=None, help="Token at which text generation is stopped")
parser.add_argument(
"--temperature",
type=float,
default=1.0,
help="temperature of 1.0 has no effect, lower tend toward greedy sampling",
)
parser.add_argument(
"--repetition_penalty", type=float, default=1.0, help="primarily useful for CTRL model; in that case, use 1.2"
)
parser.add_argument("--k", type=int, default=0)
parser.add_argument("--p", type=float, default=0.9)
parser.add_argument("--prefix", type=str, default="", help="Text added prior to input.")
parser.add_argument("--seed", type=int, default=42, help="random seed for initialization")
parser.add_argument("--no_cuda", action="store_true", help="Avoid using CUDA when available")
parser.add_argument("--num_return_sequences", type=int, default=1, help="The number of samples to generate.")
parser.add_argument(
"--fp16",
action="store_true",
help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit",
)
args = parser.parse_args()
model, tokenizer = init_model(args.model_name_or_path)
logger.info(args)
prompt_text = args.prompt if args.prompt else input("Model prompt >>> ")
for generated_idx, text in enumerate(run_model(args.prefix + prompt_text, args)):
print(f"=== GENERATED SEQUENCE {generated_idx + 1} TEXT ===")
print(text)
setup_logger()
if __name__ == "__main__":
main()
For more info, see https://huggingface.co/docs/transformers/index