forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDimname.cpp
104 lines (90 loc) · 2.62 KB
/
Dimname.cpp
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
#ifdef BUILD_NAMEDTENSOR
#include <ATen/Dimname.h>
#include <c10/util/Exception.h>
namespace at {
std::ostream& operator<<(std::ostream& out, const Dimname& dimname) {
if (dimname.type() == NameType::WILDCARD) {
out << "None";
} else {
out << "'" << dimname.full_name().toUnqualString() << "'";
}
return out;
}
bool is_valid_identifier(const std::string& name) {
std::locale loc;
if (name.length() == 0) {
return false;
}
for (auto it = name.begin(); it != name.end(); ++it) {
if (std::isalpha(*it, loc) || *it == '_') {
continue;
}
return false;
}
return true;
}
bool Dimname::can_refer_to(const Dimname& other) const {
switch (type()) {
case NameType::WILDCARD:
return false;
// "C" can be used to refer to "C" or "C.in".
case NameType::NORMAL:
return untagged_name() == other.untagged_name();
default:
return full_name() == other.full_name();
}
}
static void check_valid_identifier(const std::string& name) {
TORCH_CHECK(
is_valid_identifier(name),
"Invalid name: a valid identifier must contain alphabetical characters and/or underscore, got: '",
name, "'.");
}
Dimname Dimname::fromSymbol(Symbol full_name) {
TORCH_INTERNAL_ASSERT(full_name.is_dimname());
if (full_name == kWildcard) {
return Dimname::wildcard();
}
const std::string delimiter = ".";
const std::string str(full_name.toUnqualString());
auto it = str.find(delimiter);
// Check for normal name
if (it == std::string::npos) {
check_valid_identifier(str);
return Dimname(full_name);
}
// Check for tagged name
auto second_dot = str.find(delimiter, it + 1);
TORCH_CHECK(
second_dot == std::string::npos,
"Invalid name '", str, "': A tagged name can only contain one '.'");
auto untagged_name = str.substr(0, it);
auto tag = str.substr(it + 1);
check_valid_identifier(untagged_name);
check_valid_identifier(tag);
return Dimname(NameType::TAGGED, full_name, Symbol::dimname(untagged_name));
}
Dimname Dimname::wildcard() {
static Dimname result(NameType::WILDCARD, kWildcard, kWildcard);
return result;
}
optional<Dimname> unify(Dimname dimname, Dimname other) {
if (other.type() == NameType::WILDCARD) {
return dimname;
}
if (dimname.type() == NameType::WILDCARD) {
return other;
}
if (dimname.full_name() == other.full_name()) {
return dimname;
}
if (dimname.untagged_name() == other.untagged_name()) {
return Dimname::fromSymbol(dimname.untagged_name());
}
return c10::nullopt;
}
bool match(Dimname dimname, Dimname other) {
return unify(dimname, other).has_value();
}
} // namespace at
#endif