forked from Saibo-creator/transformers-CFG
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgenerate_emoji.py
53 lines (40 loc) · 1.79 KB
/
generate_emoji.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import cProfile
import pstats
import io
from transformers import AutoModelForCausalLM, AutoTokenizer
from transformers_cfg.grammar_utils import IncrementalGrammarConstraint
from transformers_cfg.generation.logits_process import GrammarConstrainedLogitsProcessor
import logging
logging.basicConfig(level=logging.DEBUG)
def main():
# Load model and tokenizer
tokenizer = AutoTokenizer.from_pretrained("gpt2") # JackFram/llama-68m"
tokenizer.pad_token = tokenizer.eos_token
model = AutoModelForCausalLM.from_pretrained("gpt2") # Load model to defined device
# Load grammar
with open("examples/grammars/emoji.ebnf", "r") as file:
grammar_str = file.read()
grammar = IncrementalGrammarConstraint(grammar_str, "root", tokenizer, unicode=True)
grammar_processor = GrammarConstrainedLogitsProcessor(grammar)
# Generate
prefix1 = "Describe your feeling with emoji: "
prefix2 = "Write a poem with emoji: "
input_ids = tokenizer(
[prefix1, prefix2], add_special_tokens=False, return_tensors="pt", padding=True
)["input_ids"]
output = model.generate(
input_ids,
do_sample=False,
max_new_tokens=100,
logits_processor=[grammar_processor],
repetition_penalty=1.1,
num_return_sequences=1,
)
# decode output
generations = tokenizer.batch_decode(output, skip_special_tokens=True)
print(generations)
"""
['Describe your feeling with emoji: 🙌🙂😍😯😅🙏🙇🙈🙊🙋🙃🙆🙅🙄🙁🙂🙀🙉🙎🙊🙋🙃🙆🙅🙄🙁🙂🙀🙉🙎🙊🙋🙃🙆', 'Write a poem with emoji: 🙏😍🙏🙏🙌🙏🙏🙏🙏😁😅🙏🙏🙏🙏🙏🙏🙇🙏🙏🙏🙏🙏🙏🙏🙏🙏🙋🙏🙏🙏🙏🙏🙏']
"""
if __name__ == "__main__":
main()