model.py
Browse files
model.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import typing as t
|
| 3 |
+
|
| 4 |
+
import torch
|
| 5 |
+
import transformers
|
| 6 |
+
|
| 7 |
+
logger = logging.getLogger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def build_model_and_tokenizer_for(
|
| 11 |
+
model_name: str
|
| 12 |
+
) -> t.Tuple[transformers.AutoModelForCausalLM, transformers.AutoTokenizer]:
|
| 13 |
+
'''Sets up the model and accompanying objects.'''
|
| 14 |
+
logger.info(f"Loading tokenizer for {model_name}")
|
| 15 |
+
tokenizer = transformers.AutoTokenizer.from_pretrained(model_name)
|
| 16 |
+
|
| 17 |
+
# NOTE(11b): non-OPT models support passing this in at inference time, might
|
| 18 |
+
# be worth refactoring for a debug version so we're able to experiment on
|
| 19 |
+
# the fly
|
| 20 |
+
bad_words_ids = [
|
| 21 |
+
tokenizer(bad_word, add_special_tokens=False).input_ids
|
| 22 |
+
for bad_word in _build_bad_words_list_for(model_name)
|
| 23 |
+
]
|
| 24 |
+
|
| 25 |
+
logger.info(f"Loading the {model_name} model")
|
| 26 |
+
model = transformers.AutoModelForCausalLM.from_pretrained(
|
| 27 |
+
model_name, bad_words_ids=bad_words_ids)
|
| 28 |
+
model.eval().half().to("cuda")
|
| 29 |
+
|
| 30 |
+
logger.info("Model and tokenizer are ready")
|
| 31 |
+
return model, tokenizer
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def run_raw_inference(model: transformers.AutoModelForCausalLM,
|
| 35 |
+
tokenizer: transformers.AutoTokenizer, prompt: str,
|
| 36 |
+
user_message: str, **kwargs: t.Any) -> str:
|
| 37 |
+
'''
|
| 38 |
+
Runs inference on the model, and attempts to returns only the newly
|
| 39 |
+
generated text.
|
| 40 |
+
|
| 41 |
+
:param model: Model to perform inference with.
|
| 42 |
+
:param tokenizer: Tokenizer to tokenize input with.
|
| 43 |
+
:param prompt: Input to feed to the model.
|
| 44 |
+
:param user_message: The user's raw message, exactly as appended to the end
|
| 45 |
+
of `prompt`. Used for trimming the original input from the model output.
|
| 46 |
+
:return: Decoded model generation.
|
| 47 |
+
'''
|
| 48 |
+
tokenized_items = tokenizer(prompt, return_tensors="pt").to("cuda")
|
| 49 |
+
|
| 50 |
+
# Atrocious code to stop generation when the model outputs "\nYou: " in
|
| 51 |
+
# freshly generated text. Feel free to send in a PR if you know of a
|
| 52 |
+
# cleaner way to do this.
|
| 53 |
+
stopping_criteria_list = transformers.StoppingCriteriaList([
|
| 54 |
+
_SentinelTokenStoppingCriteria(
|
| 55 |
+
sentinel_token_ids=tokenizer(
|
| 56 |
+
"\nYou:",
|
| 57 |
+
add_special_tokens=False,
|
| 58 |
+
return_tensors="pt",
|
| 59 |
+
).input_ids.to("cuda"),
|
| 60 |
+
starting_idx=tokenized_items.input_ids.shape[-1])
|
| 61 |
+
])
|
| 62 |
+
|
| 63 |
+
logits = model.generate(stopping_criteria=stopping_criteria_list,
|
| 64 |
+
**tokenized_items,
|
| 65 |
+
**kwargs)
|
| 66 |
+
output = tokenizer.decode(logits[0], skip_special_tokens=True)
|
| 67 |
+
|
| 68 |
+
logger.debug("Before trimming, model output was: `%s`", output)
|
| 69 |
+
|
| 70 |
+
# Trim out the input prompt from the generated output.
|
| 71 |
+
if (idx := prompt.rfind(user_message)) != -1:
|
| 72 |
+
trimmed_output = output[idx + len(user_message) - 1:].strip()
|
| 73 |
+
logger.debug("After trimming, it became: `%s`", trimmed_output)
|
| 74 |
+
|
| 75 |
+
return trimmed_output
|
| 76 |
+
else:
|
| 77 |
+
raise Exception(
|
| 78 |
+
"Couldn't find user message in the model's output. What?")
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _build_bad_words_list_for(_model_name: str) -> t.List[str]:
|
| 82 |
+
'''Builds a list of bad words for the given model.'''
|
| 83 |
+
|
| 84 |
+
# NOTE(11b): This was implemented as a function because each model size
|
| 85 |
+
# seems to have it quirks at the moment, but this is a rushed implementation
|
| 86 |
+
# so I'm not handling that, hence the dumb return here.
|
| 87 |
+
return ["Persona:", "Scenario:", "<START>"]
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
class _SentinelTokenStoppingCriteria(transformers.StoppingCriteria):
|
| 91 |
+
|
| 92 |
+
def __init__(self, sentinel_token_ids: torch.LongTensor,
|
| 93 |
+
starting_idx: int):
|
| 94 |
+
transformers.StoppingCriteria.__init__(self)
|
| 95 |
+
self.sentinel_token_ids = sentinel_token_ids
|
| 96 |
+
self.starting_idx = starting_idx
|
| 97 |
+
|
| 98 |
+
def __call__(self, input_ids: torch.LongTensor,
|
| 99 |
+
_scores: torch.FloatTensor) -> bool:
|
| 100 |
+
for sample in input_ids:
|
| 101 |
+
trimmed_sample = sample[self.starting_idx:]
|
| 102 |
+
# Can't unfold, output is still too tiny. Skip.
|
| 103 |
+
if trimmed_sample.shape[-1] < self.sentinel_token_ids.shape[-1]:
|
| 104 |
+
continue
|
| 105 |
+
|
| 106 |
+
for window in trimmed_sample.unfold(
|
| 107 |
+
0, self.sentinel_token_ids.shape[-1], 1):
|
| 108 |
+
if torch.all(torch.eq(self.sentinel_token_ids, window)):
|
| 109 |
+
return True
|
| 110 |
+
return False
|