-
Notifications
You must be signed in to change notification settings - Fork 96
/
nesting.lua
85 lines (76 loc) · 2.15 KB
/
nesting.lua
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
local nesting = {}
local utils = require('nngraph.utils')
-- Creates a clone of a tensor or of a table with tensors.
function nesting.cloneNested(obj)
if torch.isTensor(obj) then
return obj:clone()
end
local result = {}
for key, child in pairs(obj) do
result[key] = nesting.cloneNested(child)
end
return result
end
-- Fills the obj with the given value.
-- The obj can be a tensor or a table with tensors.
function nesting.fillNested(obj, value)
if torch.isTensor(obj) then
obj:fill(value)
else
for key, child in pairs(obj) do
nesting.fillNested(child, value)
end
end
end
-- Resizes all tensors in the output.
function nesting.resizeNestedAs(output, input)
if torch.isTensor(output) then
output:resizeAs(input)
else
for key, child in pairs(input) do
-- A new element is added to the output, if needed.
if not output[key] then
output[key] = nesting.cloneNested(child)
else
nesting.resizeNestedAs(output[key], child)
end
end
-- Extra elements are removed from the output.
for key, child in pairs(output) do
if not input[key] then
output[key] = nil
end
end
end
end
-- Copies all tensors in the output.
function nesting.copyNested(output, input)
if torch.isTensor(output) then
output:copy(input)
else
for key, child in pairs(input) do
nesting.copyNested(output[key], child)
end
-- Extra elements in the output table cause an error.
for key, child in pairs(output) do
if not input[key] then
error('key ' .. tostring(key) ..
' present in output but not in input')
end
end
end
end
-- Adds the input to the output.
-- The input can contain nested tables.
-- The output will contain the same nesting of tables.
function nesting.addNestedTo(output, input)
if torch.isTensor(output) then
output:add(input)
else
for key, child in pairs(input) do
assert(output[key] ~= nil, "missing key")
nesting.addNestedTo(output[key], child)
end
end
end
return nesting