forked from pytorch/pytorch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpython_list.cpp
315 lines (284 loc) · 9.81 KB
/
python_list.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
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
#include <ATen/core/ivalue.h>
#include <c10/util/irange.h>
#include <pybind11/detail/common.h>
#include <pybind11/pytypes.h>
#include <torch/csrc/jit/python/pybind_utils.h>
#include <torch/csrc/jit/python/python_list.h>
#include <torch/csrc/utils/pybind.h>
#include <stdexcept>
namespace torch::jit {
IValue ScriptListIterator::next() {
if (iter_ == end_) {
throw py::stop_iteration();
}
IValue result = *iter_;
// Advance the iterator for next time.
iter_++;
return result;
}
bool ScriptListIterator::done() const {
return iter_ == end_;
}
namespace {
py::list scriptListToPyList(const ScriptList& src) {
py::list out(src.len());
auto iter = src.iter();
size_t i = 0;
while (!iter.done()) {
auto val = iter.next();
// TODO: Handle nested dictionaries.
if (val.isList()) {
out[i] = scriptListToPyList(val);
} else {
out[i] = toPyObject(val);
}
++i;
}
return out;
}
} // namespace
void initScriptListBindings(PyObject* module) {
auto m = py::handle(module).cast<py::module>();
py::class_<ScriptListIterator>(m, "ScriptListIterator")
.def(
"__next__",
[](ScriptListIterator& iter) {
auto result = iter.next();
return toPyObject(result);
})
.def("__iter__", [](ScriptListIterator& iter) { return iter; });
py::class_<ScriptList, std::shared_ptr<ScriptList>>(m, "ScriptList")
.def(py::init([](py::list list) {
TypePtr type = nullptr;
if (list.size() > 0) {
// If the source list is nonempty, try to infer its type.
auto inferred_type = tryToInferType(list);
if (!inferred_type.success()) {
std::stringstream ss;
ss << "Unable to infer type of list: " << inferred_type.reason();
throw JITException(ss.str());
}
type = inferred_type.type();
} else {
// If is empty, assume the type is List[Tensor] as is done in
// TorchScript code.
type = ListType::create(TensorType::getInferred());
}
auto data = toIValue(std::move(list), type);
return std::make_shared<ScriptList>(data);
}))
.def(
"__repr__",
[](const std::shared_ptr<ScriptList>& self) {
return toPyObject(self->repr());
})
.def(
"__bool__",
[](const std::shared_ptr<ScriptList>& self) {
return toPyObject(self->toBool());
})
.def(
"__len__",
[](const std::shared_ptr<ScriptList>& self) {
return toPyObject(self->len());
})
.def(
"__contains__",
[](const std::shared_ptr<ScriptList>& self, py::object elem) {
try {
return toPyObject(self->contains(
toIValue(std::move(elem), self->type()->getElementType())));
} catch (const py::cast_error& e) {
throw py::type_error();
}
})
.def(
"__getitem__",
[](const std::shared_ptr<ScriptList>& self,
ScriptList::diff_type idx) {
try {
auto value = self->getItem(idx);
return toPyObject(value);
} catch (const std::out_of_range& e) {
throw py::index_error();
}
},
py::return_value_policy::
reference_internal) // Return value is a reference to an object
// that resides in the ScriptList
.def(
"__getitem__",
[](const std::shared_ptr<ScriptList>& self, const py::slice& slice) {
size_t start = 0, stop = 0, step = 0, slicelength = 0;
if (!slice.compute(
self->len(), &start, &stop, &step, &slicelength)) {
throw py::error_already_set();
}
auto seq = std::make_shared<ScriptList>(self->type());
for (const auto i : c10::irange(slicelength)) {
(void)i; // Suppress unused variable warning
seq->append(self->getItem(start));
start += step;
}
return seq;
})
.def(
"__setitem__",
[](const std::shared_ptr<ScriptList>& self,
ScriptList::diff_type idx,
py::object value) {
try {
self->setItem(
idx,
toIValue(std::move(value), self->type()->getElementType()));
} catch (const std::out_of_range& e) {
throw py::index_error();
} catch (const py::cast_error& e) {
throw py::type_error();
}
})
.def(
"__setitem__",
[](const std::shared_ptr<ScriptList>& self,
const py::slice& slice,
const py::list& value) {
size_t start = 0, stop = 0, step = 0, slicelength = 0;
if (!slice.compute(
self->len(), &start, &stop, &step, &slicelength)) {
throw py::error_already_set();
}
if (slicelength != value.size()) {
throw std::runtime_error(
"Left and right hand size of slice assignment have different sizes");
}
for (const auto i : c10::irange(slicelength)) {
try {
self->setItem(
start, toIValue(value[i], self->type()->getElementType()));
} catch (const py::cast_error& e) {
throw py::type_error();
}
start += step;
}
})
.def(
"__delitem__",
[](const std::shared_ptr<ScriptList>& self,
ScriptList::diff_type idx) {
try {
self->delItem(idx);
} catch (const std::out_of_range& e) {
throw py::index_error();
}
})
.def(
"__iter__",
[](const std::shared_ptr<ScriptList>& self) { return self->iter(); },
py::keep_alive<0, 1>()) // ScriptList needs to be alive at least as
// long as the iterator
.def(
"count",
[](const std::shared_ptr<ScriptList>& self, py::object value) {
try {
return self->count(
toIValue(std::move(value), self->type()->getElementType()));
} catch (const py::cast_error& e) {
throw py::type_error();
}
})
.def(
"remove",
[](const std::shared_ptr<ScriptList>& self, py::object value) {
try {
return self->remove(
toIValue(std::move(value), self->type()->getElementType()));
} catch (const py::cast_error& e) {
throw py::type_error();
}
})
.def(
"append",
[](const std::shared_ptr<ScriptList>& self, py::object value) {
try {
return self->append(
toIValue(std::move(value), self->type()->getElementType()));
} catch (const py::cast_error& e) {
throw py::type_error();
}
})
.def(
"clear",
[](const std::shared_ptr<ScriptList>& self) { self->clear(); })
.def(
"extend",
[](const std::shared_ptr<ScriptList>& self, py::list list) {
try {
self->extend(toIValue(std::move(list), self->type()));
} catch (const py::cast_error& e) {
throw py::type_error();
}
})
.def(
"extend",
[](const std::shared_ptr<ScriptList>& self,
const py::iterable& iter) {
ScriptList iter_list(self->type());
try {
for (py::handle obj : iter) {
iter_list.append(toIValue(
py::reinterpret_borrow<py::object>(obj),
self->type()->getElementType()));
}
} catch (const py::cast_error& e) {
throw py::type_error();
}
self->extend(toIValue(py::cast(iter_list), self->type()));
})
.def(
"pop",
[](const std::shared_ptr<ScriptList>& self) {
return toPyObject(self->pop());
})
.def(
"pop",
[](const std::shared_ptr<ScriptList>& self,
ScriptList::diff_type idx) { return toPyObject(self->pop(idx)); })
.def(
"insert",
[](const std::shared_ptr<ScriptList>& self,
ScriptList::diff_type idx,
py::object obj) {
try {
self->insert(
toIValue(std::move(obj), self->type()->getElementType()),
idx);
} catch (const py::cast_error& e) {
throw py::type_error();
}
})
.def(py::pickle(
[](const ScriptList& data) { // __getstate__
return scriptListToPyList(data);
},
[](py::list list) { // __setstate__
TypePtr type = nullptr;
if (list.size() > 0) {
// If the source list is nonempty, try to infer its type.
auto inferred_type = tryToInferType(list);
if (!inferred_type.success()) {
std::stringstream ss;
ss << "Unable to infer type of list: "
<< inferred_type.reason();
throw JITException(ss.str());
}
type = inferred_type.type();
} else {
// If is empty, assume the type is List[Tensor] as is done in
// TorchScript code.
type = ListType::create(TensorType::getInferred());
}
auto data = toIValue(std::move(list), type);
return std::make_shared<ScriptList>(data);
}));
}
} // namespace torch::jit