Views
No views yet
1import torch
2from transformers import AutoTokenizer, AutoModelForCausalLM
3from tqdm import tqdm
4
5device = "cuda" if torch.cuda.is_available() else "cpu"
6
7model_id = "danlou/persona-generator-llama-2-7b-qlora-merged"
8tokenizer = AutoTokenizer.from_pretrained(model_id)
9model = AutoModelForCausalLM.from_pretrained(model_id, device_map="auto", torch_dtype=torch.float16)
10
11
12def chunks(lst, n):
13 """Yield successive n-sized chunks from lst."""
14 for i in range(0, len(lst), n):
15 yield lst[i:i + n]
16
17
18def parse_outputs(output_text):
19
20 try:
21 output_lns = output_text.split('\n')
22 assert len(output_lns) == 2
23 assert len(output_lns[0].split(',')) == 2
24 assert len(output_lns[1]) > 16
25
26 name, age = [s.strip() for s in output_lns[0].split(',')]
27 desc = output_lns[1].strip()
28
29 except AssertionError:
30 raise Exception('Malformed output.')
31
32 try:
33 age = int(age)
34 except ValueError:
35 raise Exception('Malformed output (age).')
36
37 return {'name': name, 'age': age, 'description': desc}
38
39
40
41def generate_personas(product, n=1, batch_size=32, parse=True):
42
43 prompt = f"### Instruction:\nDescribe the ideal persona for this product:\n{product}\n\n### Response:\n"
44 input_ids = tokenizer(prompt, return_tensors="pt").input_ids.to(device)
45
46 personas = []
47 with tqdm(total=n) as pbar:
48 for batch in chunks(range(n), batch_size):
49 outputs = model.generate(input_ids,
50 do_sample=True,
51 num_beams=1,
52 num_return_sequences=len(batch),
53 max_length=512,
54 min_length=32,
55 temperature=0.9)
56
57 for output_ids in outputs:
58 output_decoded = tokenizer.decode(output_ids, skip_special_tokens=True)
59 output_decoded = output_decoded[len(prompt):].strip()
60
61 try:
62 if parse:
63 personas.append(parse_outputs(output_decoded))
64 else:
65 personas.append(output_decoded)
66 except Exception as e:
67 print(e)
68 continue
69
70 pbar.update(len(batch))
71
72 return personas
73
74
75product = "Koonie 10000mAh Rechargeable Desk Fan, 8-Inch Battery Operated Clip on Fan, USB Fan, 4 Speeds, Strong Airflow, Sturdy Clamp for Golf Cart Office Desk Outdoor Travel Camping Tent Gym Treadmill, Black (USB Gadgets > USB Fans)"
76personas = generate_personas(product, n=3)
77
78for e in personas:
79 print(e)
80
81# Persona 1 - The yoga instructor
82# {'name': 'Sarah', 'age': 28, 'description': 'Yoga instructor who is passionate about health and fitness. She works from a home studio where she also practices yoga and meditation. Sarah values products that are eco-friendly and sustainable. She loves products that are versatile and can be used for different purposes. Sarah is looking for a product that is durable and can withstand frequent use. She values products that are stylish and aesthetically pleasing.'}
83# Persona 2 - The golf enthusiast
84#{'name': 'Sophia', 'age': 60, 'description': "Golf enthusiast. Sophia spends most of her weekends on the golf course, and she needs a fan that she can carry around in her golf cart. She needs a fan that's lightweight, easy to clip on, and has a long battery life. She also wants a fan that's affordable, especially since she plays at different courses."}
85# Persona 3 - The truck driver
86# {'name': 'Mike', 'age': 32, 'description': "Truck driver who spends most of his day on the road. The cab of his truck can get hot and stuffy, and Mike needs a fan that can keep him comfortable and alert while he's driving. He needs a fan that's easy to install and adjust, so he can keep it on his dashboard and direct the airflow where he needs it most."}