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
|
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#pragma once
#include <vespa/vespalib/stllike/string.h>
#include <vespa/vespalib/util/approx.h>
#include <memory>
#include <map>
namespace vespalib::slime {
struct Cursor;
struct Inspector;
}
namespace vespalib::eval {
struct Value;
/**
* An implementation-independent specification of the type and
* contents of a tensor.
**/
class TensorSpec
{
public:
struct Label {
size_t index;
vespalib::string name;
static constexpr size_t npos = -1;
Label(size_t index_in) : index(index_in), name() {}
Label(const vespalib::string &name_in) : index(npos), name(name_in) {}
Label(const char *name_in) : index(npos), name(name_in) {}
bool is_mapped() const { return (index == npos); }
bool is_indexed() const { return (index != npos); }
bool operator==(const Label &rhs) const noexcept {
return ((index == rhs.index) &&
(name == rhs.name));
}
bool operator<(const Label &rhs) const noexcept {
if (index != rhs.index) {
return (index < rhs.index);
}
return (name < rhs.name);
}
};
struct Value {
double value;
Value(double value_in) : value(value_in) {}
operator double() const { return value; }
static bool both_nan(double a, double b) {
return (std::isnan(a) && std::isnan(b));
}
bool operator==(const Value &rhs) const {
return (both_nan(value, rhs.value) || approx_equal(value, rhs.value));
}
};
using Address = std::map<vespalib::string,Label>;
using Cells = std::map<Address,Value>;
private:
vespalib::string _type;
Cells _cells;
public:
TensorSpec(const vespalib::string &type_spec);
TensorSpec(const TensorSpec &);
TensorSpec & operator = (const TensorSpec &);
~TensorSpec();
double as_double() const;
TensorSpec &add(Address address, double value);
const vespalib::string &type() const { return _type; }
const Cells &cells() const { return _cells; }
vespalib::string to_string() const;
TensorSpec normalize() const;
void to_slime(slime::Cursor &tensor) const;
vespalib::string to_expr() const;
static TensorSpec from_slime(const slime::Inspector &tensor);
static TensorSpec from_value(const eval::Value &value);
static TensorSpec from_expr(const vespalib::string &expr);
static vespalib::string diff(const TensorSpec &lhs, const vespalib::string &lhs_desc,
const TensorSpec &rhs, const vespalib::string &rhs_desc);
};
bool operator==(const TensorSpec &lhs, const TensorSpec &rhs);
std::ostream &operator<<(std::ostream &out, const TensorSpec &tensor);
}
|