File size: 13,532 Bytes
64772a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
from dataclasses import asdict, dataclass
from enum import Enum
from typing import (
    Any,
    Dict,
    List,
    Mapping,
    Optional,
    Sequence,
    Tuple,
)
from aleph_alpha_client.prompt import Prompt


@dataclass(frozen=True)
class EmbeddingRequest:
    """
    Embeds a text and returns vectors that can be used for downstream tasks (e.g. semantic similarity) and models (e.g. classifiers).

    Parameters:
        prompt
            The text and/or image(s) to be embedded.

        layers
            A list of layer indices from which to return embeddings.

            * Index 0 corresponds to the word embeddings used as input to the first transformer layer
            * Index 1 corresponds to the hidden state as output by the first transformer layer, index 2 to the output of the second layer etc.
            * Index -1 corresponds to the last transformer layer (not the language modelling head), index -2 to the second last layer etc.

        pooling
            Pooling operation to use.
            Pooling operations include:

            * mean: aggregate token embeddings across the sequence dimension using an average
            * max: aggregate token embeddings across the sequence dimension using a maximum
            * last_token: just use the last token
            * abs_max: aggregate token embeddings across the sequence dimension using a maximum of absolute values

        type
            Type of the embedding (e.g. symmetric or asymmetric)

        tokens
            Flag indicating whether the tokenized prompt is to be returned (True) or not (False)

        normalize
            Return normalized embeddings. This can be used to save on additional compute when applying a cosine similarity metric.

            Note that at the moment this parameter does not yet have any effect. This will change as soon as the
            corresponding feature is available in the backend

        contextual_control_threshold (float, default None)
            If set to None, attention control parameters only apply to those tokens that have
            explicitly been set in the request.
            If set to a non-None value, we apply the control parameters to similar tokens as well.
            Controls that have been applied to one token will then be applied to all other tokens
            that have at least the similarity score defined by this parameter.
            The similarity score is the cosine similarity of token embeddings.

        control_log_additive (bool, default True)
            True: apply control by adding the log(control_factor) to attention scores.
            False: apply control by (attention_scores - - attention_scores.min(-1)) * control_factor

    Examples:
        >>> prompt = Prompt.from_text("This is an example.")
        >>> EmbeddingRequest(prompt=prompt, layers=[-1], pooling=["mean"])
    """

    prompt: Prompt
    layers: List[int]
    pooling: List[str]
    type: Optional[str] = None
    tokens: bool = False
    normalize: bool = False
    contextual_control_threshold: Optional[float] = None
    control_log_additive: Optional[bool] = True

    def to_json(self) -> Mapping[str, Any]:
        return {
            **self._asdict(),
            "prompt": self.prompt.to_json(),
        }

    def _asdict(self) -> Mapping[str, Any]:
        return asdict(self)


@dataclass(frozen=True)
class EmbeddingResponse:
    model_version: str
    num_tokens_prompt_total: int
    embeddings: Optional[Dict[Tuple[str, str], List[float]]]
    tokens: Optional[List[str]]
    message: Optional[str] = None

    @staticmethod
    def from_json(json: Dict[str, Any]) -> "EmbeddingResponse":
        return EmbeddingResponse(
            model_version=json["model_version"],
            embeddings={
                (layer, pooling): embedding
                for layer, pooling_dict in json["embeddings"].items()
                for pooling, embedding in pooling_dict.items()
            },
            tokens=json.get("tokens"),
            message=json.get("message"),
            num_tokens_prompt_total=json["num_tokens_prompt_total"],
        )


class SemanticRepresentation(Enum):
    """
    Available types of semantic representations that prompts can be embedded with.

    Symmetric:
        `Symmetric` is useful for comparing prompts to each other, in use cases such as clustering, classification, similarity, etc. `Symmetric` embeddings should be compared with other `Symmetric` embeddings.
    Document:
        `Document` and `Query` are used together in use cases such as search where you want to compare shorter queries against larger documents.

        `Document` embeddings are optimized for larger pieces of text to compare queries against.
    Query:
        `Document` and `Query` are used together in use cases such as search where you want to compare shorter queries against larger documents.

        `Query` embeddings are optimized for shorter texts, such as questions or keywords.
    """

    Symmetric = "symmetric"
    Document = "document"
    Query = "query"


@dataclass(frozen=True)
class SemanticEmbeddingRequest:
    """
    Embeds a text and returns vectors that can be used for downstream tasks (e.g. semantic similarity) and models (e.g. classifiers).

    Parameters:
        prompt
            The text and/or image(s) to be embedded.
        representation
            Semantic representation to embed the prompt with.
        compress_to_size
            Options available: 128

            The default behavior is to return the full embedding, but you can optionally request an embedding compressed to a smaller set of dimensions.

            Full embedding sizes for supported models:
              - luminous-base: 5120

            The 128 size is expected to have a small drop in accuracy performance (4-6%), with the benefit of being much smaller, which makes comparing these embeddings much faster for use cases where speed is critical.

            The 128 size can also perform better if you are embedding really short texts or documents.

        normalize
            Return normalized embeddings. This can be used to save on additional compute when applying a cosine similarity metric.

            Note that at the moment this parameter does not yet have any effect. This will change as soon as the
            corresponding feature is available in the backend

        contextual_control_threshold (float, default None)
            If set to None, attention control parameters only apply to those tokens that have
            explicitly been set in the request.
            If set to a non-None value, we apply the control parameters to similar tokens as well.
            Controls that have been applied to one token will then be applied to all other tokens
            that have at least the similarity score defined by this parameter.
            The similarity score is the cosine similarity of token embeddings.

        control_log_additive (bool, default True)
            True: apply control by adding the log(control_factor) to attention scores.
            False: apply control by (attention_scores - - attention_scores.min(-1)) * control_factor

    Examples
        >>> texts = [
                "deep learning",
                "artificial intelligence",
                "deep diving",
                "artificial snow",
            ]
        >>> # Texts to compare
        >>> embeddings = []
        >>> for text in texts:
                request = SemanticEmbeddingRequest(prompt=Prompt.from_text(text), representation=SemanticRepresentation.Symmetric)
                result = model.semantic_embed(request)
                embeddings.append(result.embedding)
    """

    prompt: Prompt
    representation: SemanticRepresentation
    compress_to_size: Optional[int] = None
    normalize: bool = False
    contextual_control_threshold: Optional[float] = None
    control_log_additive: Optional[bool] = True

    def to_json(self) -> Mapping[str, Any]:
        return {
            **self._asdict(),
            "representation": self.representation.value,
            "prompt": self.prompt.to_json(),
        }

    def _asdict(self) -> Mapping[str, Any]:
        return asdict(self)


@dataclass(frozen=True)
class BatchSemanticEmbeddingRequest:
    """
    Embeds multiple multi-modal prompts and returns their embeddings in the same order as they were supplied.

    Parameters:
        prompts
            A list of texts and/or images to be embedded.
        representation
            Semantic representation to embed the prompt with.
        compress_to_size
            Options available: 128

            The default behavior is to return the full embedding, but you can optionally request an embedding compressed to a smaller set of dimensions.

            Full embedding sizes for supported models:
              - luminous-base: 5120

            The 128 size is expected to have a small drop in accuracy performance (4-6%), with the benefit of being much smaller, which makes comparing these embeddings much faster for use cases where speed is critical.

            The 128 size can also perform better if you are embedding really short texts or documents.

        normalize
            Return normalized embeddings. This can be used to save on additional compute when applying a cosine similarity metric.

            Note that at the moment this parameter does not yet have any effect. This will change as soon as the
            corresponding feature is available in the backend

        contextual_control_threshold (float, default None)
            If set to None, attention control parameters only apply to those tokens that have
            explicitly been set in the request.
            If set to a non-None value, we apply the control parameters to similar tokens as well.
            Controls that have been applied to one token will then be applied to all other tokens
            that have at least the similarity score defined by this parameter.
            The similarity score is the cosine similarity of token embeddings.

        control_log_additive (bool, default True)
            True: apply control by adding the log(control_factor) to attention scores.
            False: apply control by (attention_scores - - attention_scores.min(-1)) * control_factor

    Examples
        >>> texts = [
                "deep learning",
                "artificial intelligence",
                "deep diving",
                "artificial snow",
            ]
        >>> # Texts to compare
        >>> request = BatchSemanticEmbeddingRequest(prompts=[Prompt.from_text(text) for text in texts], representation=SemanticRepresentation.Symmetric)
            result = model.batch_semantic_embed(request)
    """

    prompts: Sequence[Prompt]
    representation: SemanticRepresentation
    compress_to_size: Optional[int] = None
    normalize: bool = False
    contextual_control_threshold: Optional[float] = None
    control_log_additive: Optional[bool] = True

    def to_json(self) -> Mapping[str, Any]:
        return {
            **self._asdict(),
            "representation": self.representation.value,
            "prompts": [prompt.to_json() for prompt in self.prompts],
        }

    def _asdict(self) -> Mapping[str, Any]:
        return asdict(self)


EmbeddingVector = List[float]


@dataclass(frozen=True)
class SemanticEmbeddingResponse:
    """
    Response of a semantic embedding request

    Parameters:
        model_version
            Model name and version (if any) of the used model for inference
        embedding
            A list of floats that can be used to compare against other embeddings.
        message
            This field is no longer used.
    """

    model_version: str
    embedding: EmbeddingVector
    num_tokens_prompt_total: int
    message: Optional[str] = None

    @staticmethod
    def from_json(json: Dict[str, Any]) -> "SemanticEmbeddingResponse":
        return SemanticEmbeddingResponse(
            model_version=json["model_version"],
            embedding=json["embedding"],
            message=json.get("message"),
            num_tokens_prompt_total=json["num_tokens_prompt_total"],
        )


@dataclass(frozen=True)
class BatchSemanticEmbeddingResponse:
    """
    Response of a batch semantic embedding request

    Parameters:
        model_version
            Model name and version (if any) of the used model for inference
        embeddings
            A list of embeddings.
    """

    model_version: str
    embeddings: Sequence[EmbeddingVector]
    num_tokens_prompt_total: int

    @staticmethod
    def from_json(json: Dict[str, Any]) -> "BatchSemanticEmbeddingResponse":
        return BatchSemanticEmbeddingResponse(
            model_version=json["model_version"],
            embeddings=json["embeddings"],
            num_tokens_prompt_total=json["num_tokens_prompt_total"],
        )

    def to_json(self) -> Mapping[str, Any]:
        return {
            **asdict(self),
            "embeddings": [embedding for embedding in self.embeddings],
        }

    @staticmethod
    def _from_model_version_and_embeddings(
        model_version: str,
        embeddings: Sequence[EmbeddingVector],
        num_tokens_prompt_total: int,
    ) -> "BatchSemanticEmbeddingResponse":
        return BatchSemanticEmbeddingResponse(
            model_version=model_version,
            embeddings=embeddings,
            num_tokens_prompt_total=num_tokens_prompt_total,
        )