I have to train a convolutional neural network using the Torch framework and then write the same network in C. To do so, I have to read somehow the learned parameters of the net from my C program, but I can't find a way to convert or write to a file the Torch Tensors to make them readable in C. Ideally, I want to convert the Tensors into arrays of double in C.
Does anyone know how to do that? Thanks in advance :)
The most basic (and direct) way is to directly
fread
in C the data you have previously written into a binary file. In such a case you would typically concatenate the weights and biases (if any) for each layer.On the Lua/Torch side you can use the File utilities to literally
fwrite
each tensor data. For example here is a basic function that does that:For example if
m
refers to atorch/nn
module containing weights you would use it as follow:Of course you need to write your own logic to make sure you
fwrite
and concatenate all the weights from all your layers. On the C side, in addition tonet.bin
, you also need to know the structure of your network (nb. layers, parameters like kernel size, etc) to know how many block ofdouble
-s tofread
.As an example (in Lua) you can have a look at overfeat-torch (non official project) that illustrates how to read such a plain binary file: see the ParamBank tool.
Keep in mind that a robust solution would consist in using a proper binary serialization format like msgpack or Protocol Buffers that would make this export/import process clean and portable.
--
Here is a toy example:
Then in C: