forked from Element-Research/dpnn
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Serial.lua
51 lines (40 loc) · 1.32 KB
/
Serial.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
------------------------------------------------------------------------
--[[ Serial ]]--
-- Decorator that modifies the serialization/deserialization
-- behaviour of encapsulated module.
------------------------------------------------------------------------
local Serial, parent = torch.class("nn.Serial", "nn.Decorator")
function Serial:__init(module, tensortype)
parent.__init(self, module)
self.tensortype = tensortype
if self.tensortype then
assert(tensortype:find('torch.*Tensor'), "Expecting tensortype (e.g. torch.LongTensor) at arg1")
end
end
function Serial:write(file)
local state = self:getSerialState()
local function recursiveSetMetaTable(state)
for k,v in pairs(state) do
if torch.type(v) == 'table' then
recursiveSetMetaTable(v)
end
end
if state.dpnn_typename then
torch.setmetatable(state, state.dpnn_typename)
end
end
-- typecast before serialization (useful for cuda)
recursiveSetMetaTable(state)
if self.tensortype then
state:type(self.tensortype)
end
-- removes self's metatable
state = _.map(state, function(k,v) return v end)
file:writeObject(state)
end
function Serial:read(file)
local state = file:readObject()
for k,v in pairs(state) do
self[k] = v
end
end