outlines

Форк
0
/
dating_profile.py 
176 строк · 7.8 Кб
1
from dataclasses import dataclass
2
from enum import Enum
3

4
import torch
5
import transformers
6
from pydantic import BaseModel, conlist
7

8
import outlines
9
from outlines import models
10

11

12
class QuestionChoice(str, Enum):
13
    A = "The key to my heart is"
14
    B = "The first item on my bucket list is"
15
    C = "Perks of dating me"
16
    D = "Message me if you also love"
17
    E = "People would describe me as"
18
    F = "I can beat you in a game of"
19

20

21
@dataclass
22
class QuestionAnswer:
23
    question: QuestionChoice
24
    answer: str
25

26

27
class DatingProfile(BaseModel):
28
    # It is possible put length constraints on these strings using constr- however, this appears to dramatically increase the generation time
29
    # This may be resolved in the future with this PR: https://github.com/outlines-dev/outlines/pull/272
30
    bio: str
31
    job: str
32
    # Ignore mypy checks here because it still doesn't support conlist or constr: https://github.com/pydantic/pydantic/issues/975
33
    interests: conlist(str, min_length=1, max_length=5)  # type: ignore
34
    qna1: QuestionAnswer
35
    qna2: QuestionAnswer
36

37

38
@dataclass
39
class Example:
40
    description: str
41
    profile: DatingProfile
42

43

44
@outlines.prompt
45
def dating_profile_prompt(description: str, examples: list[Example]):
46
    """
47
    You are a world-renowned matchmaker who understands the modern dating market. Your job is to generate dating app profiles for male clients interested in women based on a provided description. The profiles should be authentic, show off their strengths, and maximize their likelihood of getting matches on dating apps.
48
    Here are some examples of past clients that you have successfully created profiles for:
49
    {% for example in examples %}
50
    Description:
51
    {{ example.description }}
52
    Profile:
53
    {{ example.profile }}
54
    {% endfor %}
55
    Here is the new client who you need to create a profile for:
56
    Description: {{ description }}
57
    Profile:
58
    """
59

60

61
samples: list[Example] = [
62
    Example(
63
        description="I'm an author and former professional soccer player living in Seattle who publishes popular fiction books. A typical day for me starts by hanging out with my cat, drinking a coffee, and reading as much as I can in a few hours. Then, I'll prepare a quick smoothie before starting to write for a few hours, take a break with soccer or running a few miles, and finally meet friends for dinner at a new, hip restaurant in the evening. Sometimes we go axe-throwing afterwards, or play poker, or watch a comedy show, or visit a dive bar. On my vacations, I travel extensively to countries South America, Europe, and Asia, with the goal of visiting them all!",
64
        profile=DatingProfile(
65
            bio="Adventurer, dreamer, author, and soccer enthusiast. Life’s too short to waste time so I make the most of each day by exploring new places and playing with my friends on the pitch. What’s your favorite way to get out and have fun?",
66
            job="Famous Soccer Player -> Famous Author",
67
            interests=["Soccer", "Travel", "Friends", "Books", "Fluffy Animals"],
68
            qna1=QuestionAnswer(
69
                question=QuestionChoice.B, answer="swim in all seven oceans!"
70
            ),
71
            qna2=QuestionAnswer(
72
                question=QuestionChoice.E,
73
                answer="fun-loving, adventurous, and a little bit crazy",
74
            ),
75
        ),
76
    ),
77
    Example(
78
        description="I run my company and build houses for a living. I'm a big fan of the outdoors and love to go hiking, camping, and fishing. I don't like video games, but do like to watch movies. My love language is home-cooked food, and I'm looking for someone who isn't afraid to get their hands dirty.",
79
        profile=DatingProfile(
80
            bio="If you're looking for a Montana man who loves to get outdoors and hunt, and who's in-tune with his masculinity then I'm your guy!",
81
            job="House Construction Manager / Entrepreneur",
82
            interests=["Hunting", "Hiking", "The outdoors", "Home-cooked food"],
83
            qna1=QuestionAnswer(question=QuestionChoice.A, answer="food made at home"),
84
            qna2=QuestionAnswer(
85
                question=QuestionChoice.C,
86
                answer="having a man in your life who can fix anything",
87
            ),
88
        ),
89
    ),
90
    Example(
91
        description="I run my own Youtube channel with 10M subscribers. I love working with kids, and my audience skews pretty young too. In my free time, I play Fortnite and Roblox. I'm looking for someone who is also a gamer and likes to have fun. I'm learning Japanese in my free time as well as how to cook.",
92
        profile=DatingProfile(
93
            bio="Easy on the eyes (find me on Youtube!) and great with kids. What more do you need?",
94
            job="Youtuber 10M+ subscribers",
95
            interests=["Kids", "Gaming", "Japanese"],
96
            qna1=QuestionAnswer(question=QuestionChoice.D, answer="anime and gaming!"),
97
            qna2=QuestionAnswer(question=QuestionChoice.F, answer="Fortnite, gg ez"),
98
        ),
99
    ),
100
]
101

102

103
# Below requires ~13GB of GPU memory
104
# https://huggingface.co/mosaicml/mpt-7b-8k-instruct
105
# Motivation: Reasonably large model that fits on a single GPU and has been fine-tuned for a larger context window
106
config = transformers.AutoConfig.from_pretrained(
107
    "mosaicml/mpt-7b-8k-instruct", trust_remote_code=True
108
)
109
config.init_device = "meta"
110
model = models.transformers(
111
    model_name="mosaicml/mpt-7b-8k-instruct",
112
    device="cuda",
113
    model_kwargs={
114
        "config": config,
115
        "trust_remote_code": True,
116
        "torch_dtype": torch.bfloat16,
117
        "device_map": {"": 0},
118
    },
119
)
120

121
new_description = "I'm a laid-back lawyer who spends a lot of his free-time gaming. I work in a corporate office, but ended up here after the start-up I cofounded got acquired, so still play ping pong with my cool coworkers every day. I have a bar at home where I make cocktails, which is great for entertaining friends. I secretly like to wear suits and get a new one tailored every few months. I also like weddings because I get to wear those suits, and it's a good excuse for a date. I watch the latest series because I'm paying, with my hard-earned money, for every streaming service."
122

123
prompt = dating_profile_prompt(description=new_description, examples=samples)
124
profile = outlines.generate.json(model, DatingProfile)(prompt)  # type: ignore
125
print(profile)
126

127
# Sample generated profiles
128
"""
129
{
130
    "bio": "I'm an ambitious lawyer with a casual and fashionable style. I love games and sports, but my true passion is preparing refreshing cocktails at home and dressing to the nines at weddings. I'm currently looking for a woman to show a good time to and get a kiss on the opulent suit I just had made. Send resumà € to this inbox.",
131
    "job": "Lawyer",
132
    "interests":
133
    [
134
        "Stylish guys",
135
        "Gaming",
136
        "Ping pong",
137
        "Cocktails",
138
        "Weddings"
139
    ],
140
    "qna1":
141
    {
142
        "question": "The first item on my bucket list is",
143
        "answer": "be married and have a family."
144
    },
145
    "qna2":
146
    {
147
        "question": "People would describe me as",
148
        "answer": "charming, stylish, and funny."
149
    }
150
}
151
"""
152

153
"""
154
{
155
    "bio": "I’m a sexy lawyer with time on my hands. I love to game and play ping pong, but the real reason you should swipe to the right is because I look great in a suit. Who doesn’t love a man in a suit? Just saying. Send me a message if you think it’s time to take your dating life to the next level.",
156
    "job": "Lawyer",
157
    "interests":
158
    [
159
        "Gaming",
160
        "Ping Pong",
161
        "Tailored Suits",
162
        "Weddings",
163
        "Streaming Services"
164
    ],
165
    "qna1":
166
    {
167
        "question": "The first item on my bucket list is",
168
        "answer": "simulate space but stay alive for as long as possible"
169
    },
170
    "qna2":
171
    {
172
        "question": "People would describe me as",
173
        "answer": "easy-going, a little nerdy but with a mature essence"
174
    }
175
}
176
"""
177

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.