/
tensor-user-guide.html
440 lines (388 loc) · 18.6 KB
/
tensor-user-guide.html
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
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
---
# Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
title: "Tensor Guide"
redirect_from:
- /documentation/tensor-user-guide.html
---
<p>
Vespa provides a <em>tensor</em> data model and computation engine to support advanced computations over data.
This guide explains the tensor support in Vespa. See also the <a href="reference/tensor.html">tensor reference</a>,
and our <a href="https://dl.acm.org/doi/10.1145/3459104.3459152">published paper</a>
(<a href="a_tensor_formalism_for_computer_science.pdf">pdf</a>).
</p>
<h2 id="tensor-concepts">Tensor concepts</h2>
<p>
A tensor in Vespa is a data structure which generalizes scalars, vectors and matrices to any number of dimensions:
</p>
<ul>
<li>A scalar is a tensor of rank 0</li>
<li>A vector is a tensor of rank 1</li>
<li>A matrix is a tensor of rank 2</li>
<li>...</li>
</ul>
<p>
Tensors consist of a set of scalar valued <i>cells</i>, with each cell having a unique <i>address</i>.
A cell's address is specified by its index or label in all the dimensions of that tensor.
The number of dimensions in a tensor is the <em>rank</em> of the tensor.
Each dimension can be either <em>mapped</em> or <em>indexed</em>.
Mapped dimensions are sparse and allow any label (string identifier) designating their address,
while indexed dimensions use dense numeric indices starting at 0.
</p>
<p>
Example: Using <a href="reference/tensor.html#tensor-literal-form">literal form</a>, the tensor:
</p>
<pre>
{
{user:bob, movie:"Heat"}:0.1,
{user:alice, movie:"Frozen"}:0.9,
{user:carol, movie:"Top Gun"}:0.3,
}
</pre>
<p>
has two dimensions named <code>user</code> and <code>movie</code>, and has three cells with defined values:
</p>
<img src="/assets/img/tensor-mapped.png" alt="Tensor graphical representation" />
<p>
A tensor has a <i>type</i>, which consists of a set of dimension names, dimension types, and
a <a href="reference/tensor.html#tensor-type-spec">tensor cell value type</a>.
The dimension name can be anything.
This defines a 2-dimensional mapped tensor (sparse 2D matrix) of floats as illustrated above:
<pre>
tensor<float>(user{},movie{})
</pre>
This is a 2-dimensional indexed tensor (a 2D 1280x720 matrix). For example, used to represent an image:
<pre>
tensor<int8>(x[1280],y[720])
</pre>
This is a 3-dimensional indexed tensor. For example, used to represent spatial data:
<pre>
tensor<float>(x[256], y[256], z[128])
</pre>
This is a <i>mixed</i> tensor combining a <i>mapped</i> dimension and an <i>indexed</i> dimension. For example, used
to represent word2vec:
<pre>
tensor<bfloat16>(word_id{},vec[300])
</pre>
Another mixed tensor used to represent paragraph <a href="embedding.html">embeddings</a>
used to power <a href="https://blog.vespa.ai/semantic-search-with-multi-vector-indexing/">multi-vector indexing</a>.
<pre>
tensor<float>(paragraph{},embedding[768])
</pre>
<p>Vespa uses the tensor type information to optimize tensor expression execution plans at configuration time.</p>
<h2 id="tensor-document-fields">Tensor document fields</h2>
<p>Document fields in <a href="schemas.html">schemas</a> can be of any tensor type:
<pre>
schema product {
document product {
field title type string {
indexing: summary | index
}
field price type int {
indexing: summary | attribute
}
field popularity type float {
indexing: summary | attribute
}
field sales_score type tensor<float>(category{}) {
indexing: summary | attribute
}
field embedding type tensor<float>(x[4]) {
indexing: summary | attribute | index
attribute {
distance-metric: dotproduct
}
}
}
}
</pre>
<p>The above schema exemplifies a <em>product</em> with two tensor fields.
The <code>sales_score</code> tensor field represents
how popular a product is per unique <em>category</em>. This information could be used when
<a href="ranking.html">ranking</a> products for a user query. The <code>embedding</code>
tensor field represents an embedding vector representation of the product.
</p>
<ul>
<li><b>sales_score</b> is a <em>mapped</em> tensor with a single mapped dimension <code>category</code>.
Mapped dimensions are sparse and allow any label (string identifier) designating their address.</li>
<li><b>embedding</b> is an <em>indexed</em> tensor. Indexed dimensions use dense numeric indices starting at 0.</li>
</ul>
<p>To perform computations over a document tensor field in <a href="ranking.html">ranking</a>,
the field must be defined with <a href="attributes.html">attribute</a>.
<p>Tensors with the following types can be indexed with <a href="approximate-nn-hnsw.html">HNSW</a> and searched
efficiently using the <a href="reference/query-language-reference.html#nearestneighbor">nearestNeighbor</a> query operator:</p>
<ul>
<li>One indexed dimension - single vector per tensor field</li>
<li>One mapped and one indexed dimension - multiple vectors per tensor field</li>
</ul>
<p>See <a href="nearest-neighbor-search.html">nearest neighbor search</a> and
<a href="approximate-nn-hnsw.html">approximate nearest neighbor search</a>.</p>
<p>
<h2 id="feeding-tensors">Feeding tensors</h2>
<p>An example <em>product</em> document in Vespa JSON format.
This example uses the product category string as the mapped label key.
The <em>embedding</em> tensor stores and indexes (<a href="approximate-nn-hnsw.html">HNSW</a>) a
dense <a href="embedding.html">embedding</a>.</p>
<pre>{% highlight json %}
{
"put": "id:shopping:product::B0BFW5SXX2",
"fields": {
"title": "Keyboard Case for iPad Pro 12.9 inch",
"price": 29,
"popularity": 0.8,
"sales_score": {
"Tablet Keyboard Cases": 8.0,
"Keyboards": 2.0,
"Personal Computers": 0.1
},
"embedding": [
1,
2,
3,
4
]
}
}{% endhighlight %}</pre>
<p>The above JSON feed format example uses short value form.
Tensor fields can be represented using different
<a href="reference/document-json-format.html#tensor">JSON format</a> verbosity.
You can use <a href="partial-updates.html">partial updates</a> of tensor fields with
<a href="reference/document-json-format.html#tensor-add">add</a>,
<a href="reference/document-json-format.html#tensor-remove">remove</a> and
<a href="reference/document-json-format.html#tensor-modify">modify</a> tensor cells, or
<a href="reference/document-json-format.html#tensor-field">assign</a> a completely new tensor value.
From <a href="jdisc/container-components.html">container components</a> you can create and modify tensor values using the
<a href="https://javadoc.io/doc/com.yahoo.vespa/vespajlib/latest/com/yahoo/tensor/Tensor.html">tensor Java API</a>.
</p>
<p>
One can imagine that the per category sales scores are re-calculated outside of Vespa and updated in Vespa regularly
using <a href="partial-updates.html">partial updates</a>, avoiding re-feed or re-index other fields.
</p>
<h2 id="querying-with-tensors">Querying with tensors</h2>
<p>Query input tensors <b>must</b> be defined in the schema <a href="ranking.html">rank-profile</a> using
<a href="reference/schema-reference.html#inputs">inputs</a>:</p>
<pre>
rank-profile product_ranking inherits default {
inputs {
query(q_category) tensor<float>(category{})
query(q_embedding) tensor<float>(x[4])
}
.....
}
</pre>
<p>The above defines two query input tensors that we can reference in <a href="ranking.html">ranking</a> expressions.
With the tensor query name and tensor type defined, you can:</p>
<ul>
<li>Add it to the query in a <a href="searcher-development.html">Searcher</a> using the
<a href="https://javadoc.io/doc/com.yahoo.vespa/vespajlib/latest/com/yahoo/tensor/Tensor.html">Tensor class</a>
and setting it by <code>Query.getRanking().getFeatures.put("query(q_embedding)", myTensorInstance)</code>, or
<li>Pass it in the request, using an HTTP parameter like <code>input.query(q_embedding)</code> and
passing a tensor <a href="reference/tensor.html#tensor-literal-form">value</a>.
</ul>
<p>An example query request using <a href="vespa-cli.html#queries">Vespa CLI query request</a>:
<pre>{% highlight shell %}
vespa query 'yql=select * from product where {targetHits:1}nearestNeighbor(embedding,q_embedding)' \
'input.query(q_embedding)=[1,2,3,4]' \
'input.query(q_category)={"Tablet Keyboard Cases":0.8, "Keyboards":0.3}' \
'ranking=product_ranking' {% endhighlight %}</pre>
<p>
This query request example assumes that the user query has been mapped (classified) to be related to the
<em>Tablet Keyboard Cases</em> and <em>Keyboards</em> categories. Similarly, the user query has been mapped to
a dense vector representation (<code>query(q_embedding</code>) and is used as
input to the <a href="reference/query-language-reference.html#nearestneighbor">nearestNeighbor</a>
query operator, expressed with the <a href="query-language.html">YQL query language</a>.
</p>
<p>
The Vespa CLI uses HTTP GET and you can use the <em>-v</em> flag to see the curl GET equivalent. For
<a href="query-api.html#using-post">POST</a> query requests using JSON, the equivalent JSON is:</p>
<pre>{% highlight json %}
{
"yql": "select * from product where {targetHits:1}nearestNeighbor(embedding,q_embedding)",
"input": {
"query(q_embedding)": [
1,
2,
3,
4
],
"query(q_category)": {
"Tablet Keyboard Cases": 0.8,
"Keyboards":0.3
}
},
"ranking": "product_ranking"
}{% endhighlight %}</pre>
<p>If the input query tensor used for the <a href="reference/query-language-reference.html#nearestneighbor">nearestNeighbor</a>
operator is not defined in the schema rank-profile, the request will fail:</p>
<pre>
"Expected 'query(q_embedding)' to be a tensor, but it is the string '[1,2,3,4]'"
</pre>
<h2 id="ranking-with-tensors">Ranking with tensors</h2>
<p>
Tensors can be used in making inference computations over documents that are matched by a query.
These computations are expressed with <a href="reference/ranking-expressions.html">ranking expressions</a> in
schema <a href="reference/schema-reference.html#rank-profile">rank profiles</a>. We can use this support
to rank products by both the dense embedding dot product similarity and the category sales score.
</p>
<pre>
rank-profile product_ranking inherits default {
inputs {
query(q_category) tensor<float>(category{})
query(q_embedding) tensor<float>(x[4])
}
function p_sales_score() {
expression: sum(query(q_category) * attribute(sales_score))
}
function p_embedding_score() {
expression: closeness(field, embedding)
}
first-phase {
expression: p_sales_score() + p_embedding_score()
}
match-features: p_sales_score() p_embedding_score()
}
</pre>
<p>The above profile uses a combination of two dot product calculations in the <a href="phased-ranking.html">first phase</a> expression.
The <code>first-phase</code> expression is invoked for all documents that are <b>retrieved</b>
by the <a href="query-language.html">YQL query language</a>.</p>
<ul>
<li>
The <em>p_sales_score</em> function calculates the sparse tensor dotproduct between the <em>query(q_category)</em> and <em>attribute(sales_score)</em> tensor.
</li>
<li>
The <em>p_embedding_score</em> calculates the dense tensor dotproduct between the <em>query(q_embedding)</em> and <em>attribute(embedding)</em> tensors.
The function uses the <a href="reference/rank-features.html#closeness(dimension,name)">closeness(dimension,name)</a> <a href="reference/rank-features.html">rank-feature</a>
which is calculated by the <a href="reference/query-language-reference.html#nearestneighbor">nearestNeighbor</a> query operator. Alternatively, if we don't
use the <em>nearestNeighbor</em> operator in the query request, we could use sparse tensor dotproduct:
<pre>
function p_embedding_score() {
expression: sum(query(q_embedding) * attribute(embedding))
}</pre>
</li>
</ul>
<p>
The full list of tensor functions are listed in the
<a href="reference/ranking-expressions.html#tensor-functions">ranking expression reference</a>.
Using <a href="reference/schema-reference.html#match-features">match-features</a>, developers
can debug, or log function outputs in the search result.</p>
<pre>
"matchfeatures": {
"p_embedding_score": 30.0,
"p_sales_score": 8.0,
},
"documentid": "id:shopping:product::B0BFW5SXX2",
"title": "Keyboard Case for iPad Pro 12.9 inch"
</pre>
<h2 id="creating-tensors-from-document-fields">Creating tensors from document fields</h2>
<p>If you need to make tensor computations from non-tensor single-valued attributes, arrays or weighted sets,
you can convert them in a ranking expression:</p>
<ul>
<li>Creating an <i>indexed</i> tensor where the <i>values</i> are lifted from single-value
attributes (price and popularity) using the tensor generate function:
<pre>
function to_indexed_tensor() {
expression: tensor(x[2]):[attribute(price),attribute(popularity)]
}
</pre>
</li>
<li>Creating a <i>mapped</i> tensor where the <i>values</i> are lifted from single-value
attributes using the tensor generate function:
<pre>
function to_mapped_tensor() {
expression: tensor(x{}):{key1:attribute(price),key2:attribute(popularity)}
}
</pre>
</li>
<li>Creating a <i>mapped</i> tensor where the <i>label(s)</i> are lifted from a string array or
single-value attribute can be done with the
<a href="reference/rank-features.html#document-features">document feature.</a> <code>tensorFromLabels</code>.
</li>
<li>Creating a mapped tensor where the labels <i>and</i> values are lifted from a string array can be done with the
<a href="reference/rank-features.html#document-features">document feature.</a> <code>tensorFromWeightedSet</code>.
</li>
</ul>
<p>
Converting non-tensor fields to tensors at query runtime has a performance penalty that is linear with the number of elements
in the array/weightedset. Prefer using native tensor fields instead. The benefit of converting non-tensor fields
is that non-tensor fields like <code>int, float, weightedset</code> can be efficiently queried. Only specific tensor
types can be searched efficiently using the <a href="reference/query-language-reference.html#nearestneighbor">nearestNeighbor</a>
query operator.
</p>
<h2 id="constant-tensors">Constant tensors</h2>
<p>In addition to document tensors and query tensors,
<a href="reference/schema-reference.html#constant">constant tensors</a>
can be put in the <a href="reference/application-packages-reference.html">application package</a>.
This is useful for adding machine learned models. Example:
</p>
<pre>
constants {
my_tensor_constant tensor<float>(x[4]): file: constants/constant_tensor_file.json
}
</pre>
<p>
This defines a new tensor with the type as defined and the
contents distributed with the application package in the file
<em>constants/constant_tensor_file.json</em>. The format of this file is the
<a href="reference/constant-tensor-json-format.html">constant tensor JSON format</a>:
</p>
<pre>{% highlight json %}
{
"type": "tensor<float>(x[4])",
"values": [
0,
0,
0,
1.0
]
}{% endhighlight%}</pre>
<p>
To use this constant tensor in a ranking expression, encapsulate the constant name with <code>constant(...)</code>:
<pre>
rank-profile use_constant_tensor inherits product_ranking {
constants {
my_tensor_constant tensor<float>(x[4]): file: constants/constant_tensor_file.json
}
first-phase {
expression: sum(query(q_embedding) * attribute(embedding) * constant(my_tensor_constant))
}
}</pre>
<p>
Note that the rank profile <code>inherit</code> the inputs we defined in the <code>product_ranking</code> profile.
With the example data used, the first-phase expression returns the 16.0 since:
</p>
<pre>
"embedding": [
1.0,
2.0,
3.0,
4.0
],
"query(q_embedding)": [
1.0,
2.0,
3.0,
4.0
],
"constant(my_tensor_constant)": [
0.0,
0.0,
0.0,
1.0
]
</pre>
<h2 id="tensors-with-strings">Tensors with strings</h2>
<p>Tensors in Vespa cannot have strings as values, since the mathematical tensor functions
would be undefined for such "tensors". However, you can still represent sets of strings in tensors
by using the strings as keys in a mapped tensor dimensions, using e.g 1.0 as values.
This allows you to perform set operations on strings and similar without making those tensors
incompatible with other tensors and with normal tensor operations.</p>
<h2 id="further-reading">Further reading</h2>
<p>See also:</p>
<ul>
<li><a href="https://blog.vespa.ai/computing-with-tensors/">Blog post: Computing with tensors in Vespa</a>.</li>
<li><a href="onnx.html">Using ONNX models</a> to use machine-learned models taking tensor input in Vespa.</li>
<li>Some <a href="tensor-examples.html">practical tensor computation examples</a>.</li>
<li>The <a href="https://docs.vespa.ai/playground/#N4KABGBEBmkFxgNrgmUrWQPYAd5QGNIAaFDSPBdDTAF30gAkBTAJ2bAE8sBXMAgIYA7MDgA2AzmAGteQgCbSFYZgA8cbAJYBbZkNpgA7ptoALMLT0BnLKytLFloTdYr17K1c1ZnAOjAs7GCa9gJgVqa2BgA6QmoC2uLMxFy8-MJg0JrK2rYc2dC22gK03iIlYLGIZhxOLmA8VmxgAOY8mvLMALoAFKa0tDhWcAD0I-JYBFa+AG7MVjgCvgKaI3ojdbYAtI1sW20dzL792mIAlJBkqAC+V9ekGNTkuAxEDzQU+E8f9AiQAIIWay2YKhMDyEphKy0Vg8Ai0HhBMwVELSVp6NgCMSaABeJTKYCw0HCggkdhSc3htlCORKrE0BHm-liABVgXYwKYBHM0UIeNoAEbNIngnTWMr2ZEGQQiIUqEymZqdZwcEELGRNQmuMIELCC7L4ny+WL-ETxRJiVXEqGLOy1dlwS40MC3DD3K7fCDYShQZgkK5en2ezBCBjqu0AfU2rH9zq9fr+0Z6qmA1zOcGAAjgAEZiAK4AAma5Omium7vCDB72vWMfIMBugMQHKzXRowKiyGLCi3TOCUpTS+I5o4owzSqR0NssQd2PBvVv5+iuYetxqChv4t5hR9m152QBNQJOqRAFrrETiIADMXXTiEQuYLxBvxEQABZiABWYgANi6XRLN07mXKsXj+N551XONIF+KA2Wcal0hELkeQFLAzHCW1NWERQtx7cUfCsFIPB4MRSiEFpgnKMBtHHZhHHZfxAg4YwMJqMAAANoDELASg42IIVoMJaE4DRJ2dacXRA+cwN9PcVy+BsvQ3KBaNUeidwQmNl3IQ8YPZAAebjeNoAA+ZNUwva9bwzLMH2IJ8X3zd8v1-LpiynYCPRkn1IAg-coP3WDIHglx7BQjgoWYAwRVwTFSkI6QxB44wKMyEEwnkTQ5jtcJosJYldUSHghISoR-AAMRBbJoWERkUjCDiACssGyDjxNLLy533WSD3kwNFLXSAVMgfrMD0lrsh6cMmk0lwUjUjToxSaAegEPMzjWgAqAUzguTy3WknrfP8utBug4KWVMVFUWYABHdoZixPQDFoLAOqAw7vOOhgl0g879xGsb4zDLDtzbLaaLo+Q5tsQCbi61BQJOsbPioJSjwYKrXFyIJzSSIi8o4RAJimWZ5kWZZVnWaMtnxy1phOMRen6QZhjGUnpjmdUqbWIQNnZOnVASAnjloU59oku4UC6EBriAA">tensor playground</a>
which allows you to create and compute with Vespa tensors in your browser.</li>
<li>The <a href="https://javadoc.io/doc/com.yahoo.vespa/vespajlib/latest/com/yahoo/tensor/Tensor.html">Tensor Java API</a>.</li>
<li><a href="performance/feature-tuning.html#tensor-ranking">Tensor ranking performance</a>.</li>
</ul>