File size: 6,199 Bytes
64c529c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
834e995
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# Adapted from TinyStyler (https://github.com/zacharyhorvitz/TinyStyler).
#
# MIT License
#
# Copyright (c) the TinyStyler authors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

"""

Utilities for loading style models and extracting style embeddings from texts

"""

import torch
from transformers import AutoModel, AutoTokenizer

style_model, style_tokenizer = None, None

def get_text_style_embedding(texts):
    global style_model, style_tokenizer
    if style_model is None:
        style_model, style_tokenizer, _ = load_style_model()
        style_model.eval()
        style_model.to('cuda')

    style_embeds = text_to_style(
        model=style_model,
        tokenizer=style_tokenizer,
        texts=texts,
        device='cuda',
        model_type='style',
    )
    return torch.stack(style_embeds).detach().cpu()

def load_style_model(model_name='AnnaWegmann/Style-Embedding'):
    """
    Load model, tokenizer, word embeddings

    Adapted from: https://github.com/zacharyhorvitz/ParaGuide

    Supports
    - Wegmann Style Embeddings https://huggingface.co/AnnaWegmann/Style-Embedding
    - StyleDistance Embeddings https://huggingface.co/StyleDistance/styledistance
    """
    tokenizer = AutoTokenizer.from_pretrained(model_name)
    model = AutoModel.from_pretrained(model_name)
    word_embeds = get_word_embeddings(model)
    return model, tokenizer, word_embeds



def mean_pooling(model_output, attention_mask):
    """
    Mean pool over non mask tokens.

    From https://huggingface.co/AnnaWegmann/Style-Embedding

    """

    token_embeddings = model_output[
        0
    ]  # First element of model_output contains all token embeddings
    input_mask_expanded = (
        attention_mask.unsqueeze(-1).expand(token_embeddings.size()).float()
    )
    return torch.sum(token_embeddings * input_mask_expanded, 1) / torch.clamp(
        input_mask_expanded.sum(1), min=1e-9
    )


def text_to_style(
    *, model, tokenizer, texts, device, model_type='style', max_length=512
):
    """

    Applies get_style_embedding() to a list of texts

    Args:
        model (torch.nn.Module): PyTorch model
        tokenizer (transformers.Tokenizer): tokenizer
        texts (List[str]): list of texts
        device (str): device
        model_type (str): model type (currently only 'style' is supported)
        max_length (int): max length of input text

    Returns:
        List[torch.Tensor]: style embeddings

    """

    inputs = tokenizer(
        texts, return_tensors='pt', padding=True, truncation=True, max_length=max_length
    )
    inputs = {k: v.to(device) for k, v in inputs.items()}
    embeds = get_style_embedding(
        model=model,
        input_tokens=inputs['input_ids'],
        attention_mask=inputs['attention_mask'],
        model_type=model_type,
    )

    embeds = [x for x in embeds]
    return embeds



def get_style_embedding(
    *,
    model,
    inputs_embeds=None,
    input_tokens=None,
    attention_mask=None,
    model_type='style',
):
    """

    Get style embeddings from a model


    Adapted from: https://github.com/zacharyhorvitz/ParaGuide

    Args:
        model (torch.nn.Module): PyTorch model
        inputs_embeds (torch.Tensor): input token embeddings **optional**
        input_tokens (torch.Tensor): input tokens **optional**
        attention_mask (torch.Tensor): attention mask **optional**
        model_type (str): model type (currently only 'style' is supported)

    Returns:

        torch.Tensor: style embeddings  (batch_size, style embed_dim)

    """

    if inputs_embeds is not None and input_tokens is not None:
        raise ValueError('inputs_embeds and input_tokens cannot be both not None')

    if model_type != 'style':
        raise ValueError(
            f'Unknown model type {model_type}, only model type currently supported'
        )

    if inputs_embeds is not None:
        if attention_mask is None:
            attention_mask = torch.ones(*inputs_embeds.shape[:-1]).to(
                inputs_embeds.device
            )  # this may be why I have issues when i insert padding tokens
        attention_mask = attention_mask.to(inputs_embeds.device)
        return mean_pooling(
            model(inputs_embeds=inputs_embeds, attention_mask=attention_mask),
            attention_mask=attention_mask,
        )

    else:
        if attention_mask is None:
            attention_mask = torch.ones(*input_tokens.shape).to(input_tokens.device)
        attention_mask = attention_mask.to(input_tokens.device)
        return mean_pooling(
            model(input_tokens, attention_mask=attention_mask),
            attention_mask=attention_mask,
        )


def get_word_embeddings(model):
    """

    returns the word embeddings from a PyTorch model
    model.get_input_embeddings() also works for most Hugging Face models

    Args:
        model (torch.nn.Module): PyTorch model

    Returns:
        torch.Tensor: word embeddings

    """
    state_dict = model.state_dict()
    params = []
    for key in state_dict:
        if 'word_embeddings' in key:
            params.append((key, state_dict[key]))
    assert len(params) == 1, f'Found {params}'
    return params[0][1]