Giter Site home page Giter Site logo

pytorch's Introduction

pytorch

Wrappers to use torch and lua from python

What is pytorch?

  • create torch tensors, call operations on them
  • instantiate nn network modules, train them, make predictions
  • create your own lua class, call methods on that

Create torch tensors

import PyTorch
a = PyTorch.FloatTensor(2,3).uniform()
a += 3
print('a', a)
print('a.sum()', a.sum())

Instantiate nn network modules

import PyTorch
from PyTorchAug import nn

net = nn.Sequential()
net.add(nn.SpatialConvolutionMM(1, 16, 5, 5, 1, 1, 2, 2))
net.add(nn.ReLU())
net.add(nn.SpatialMaxPooling(3, 3, 3, 3))

net.add(nn.SpatialConvolutionMM(16, 32, 3, 3, 1, 1, 1, 1))
net.add(nn.ReLU())
net.add(nn.SpatialMaxPooling(2, 2, 2, 2))

net.add(nn.Reshape(32 * 4 * 4))
net.add(nn.Linear(32 * 4 * 4, 150))
net.add(nn.Tanh())
net.add(nn.Linear(150, 10))
net.add(nn.LogSoftMax())
net.float()

crit = nn.ClassNLLCriterion()
crit.float()

net.zeroGradParameters()
input = PyTorch.FloatTensor(5, 1, 28, 28).uniform()
labels = PyTorch.ByteTensor(5).geometric(0.9).icmin(10)
output = net.forward(input)
loss = crit.forward(output, labels)
gradOutput = crit.backward(output, labels)
gradInput = net.backward(input, gradOutput)
net.updateParameters(0.02)

Write your own lua class, call methods on it

Example lua class:

require 'torch'
require 'nn'

local TorchModel = torch.class('TorchModel')

function TorchModel:__init(backend, imageSize, numClasses)
  self:buildModel(backend, imageSize, numClasses)
  self.imageSize = imageSize
  self.numClasses = numClasses
  self.backend = backend
end

function TorchModel:buildModel(backend, imageSize, numClasses)
  self.net = nn.Sequential()
  local net = self.net

  net:add(nn.SpatialConvolutionMM(1, 16, 5, 5, 1, 1, 2, 2))
  net:add(nn.ReLU())
  net:add(nn.SpatialMaxPooling(3, 3, 3, 3))
  net:add(nn.SpatialConvolutionMM(16, 32, 3, 3, 1, 1, 1, 1))
  net:add(nn.ReLU())
  net:add(nn.SpatialMaxPooling(2, 2, 2, 2))
  net:add(nn.Reshape(32 * 4 * 4))
  net:add(nn.Linear(32 * 4 * 4, 150))
  net:add(nn.Tanh())
  net:add(nn.Linear(150, numClasses))
  net:add(nn.LogSoftMax())

  self.crit = nn.ClassNLLCriterion()

  self.net:float()
  self.crit:float()
end

function TorchModel:trainBatch(learningRate, input, labels)
  self.net:zeroGradParameters()

  local output = self.net:forward(input)
  local loss = self.crit:forward(output, labels)
  local gradOutput = self.crit:backward(output, labels)
  self.net:backward(input, gradOutput)
  self.net:updateParameters(learningRate)

  local _, prediction = output:max(2)
  local numRight = labels:int():eq(prediction:int()):sum()
  return {loss=loss, numRight=numRight}  -- you can return a table, it will become a python dictionary
end

function TorchModel:predict(input)
  local output = self.net:forward(input)
  local _, prediction = output:max(2)
  return prediction:byte()
end

Python script that calls this. Assume the lua class is stored in file "torch_model.lua"

import PyTorch
import PyTorchHelpers
import numpy as np
from mnist import MNIST

batchSize = 32
numEpochs = 2
learningRate = 0.02

TorchModel = PyTorchHelpers.load_lua_class('torch_model.lua', 'TorchModel')
torchModel = TorchModel(backend, 28, 10)

mndata = MNIST('../../data/mnist')
imagesList, labelsList = mndata.load_training()
labels = np.array(labelsList, dtype=np.uint8)
images = np.array(imagesList, dtype=np.float32)
labels += 1  # since torch/lua labels are 1-based
N = labels.shape[0]

numBatches = N // batchSize
for epoch in range(numEpochs):
  epochLoss = 0
  epochNumRight = 0
  for b in range(numBatches):
    res = torchModel.trainBatch(
      learningRate,
      images[b * batchSize:(b+1) * batchSize],
      labels[b * batchSize:(b+1) * batchSize])
    numRight = res['numRight']
    epochNumRight += numRight
  print('epoch ' + str(epoch) + ' accuracy: ' + str(epochNumRight * 100.0 / N) + '%')

It's easy to modify the lua script to use CUDA, or OpenCL.

Installation

Pre-requisites

luarocks install nn
  • Have installed python (tested with 2.7 and 3.4)
  • lua51 headers should be installed, ie something like sudo apt-get install lua5.1 liblua5.1-dev Run:
pip install -r requirements.txt
  • To be able to run tests, also do:
pip install -r test/requirements.txt

Procedure

Run:

git clone https://github.com/hughperkins/pytorch.git
cd pytorch
source ~/torch/install/bin/torch-activate
./build.sh

Unit-tests

Run:

source ~/torch/install/bin/torch-activate
cd pytorch
./run_tests.sh

Python 2 vs Python 3?

  • pytorch is developed and maintained on python 3
  • you should be able to use it with python 2, but there might be the occasional oversight. Please log an issue for any python 2 incompatibilities you notice

Maintainer guidelines

Maintainer guidelines

Versioning

semantic versioning

Related projects

Examples of training models/networks using pytorch:

Addons, for using cuda tensors and opencl tensors directly from python (no need for this to train networks. could be useful if you want to manipulate cuda tensor directly from python)

Support?

Please note that currently, right now, I'm focused 100.000% on cuda-on-cl, so please be patient during this period

Recent news

12 September:

  • Yannick Hold-Geoffroy added conversion of lists and tuples to Lua tables

8 September:

  • added PyTorchAug.save(filename, object) and PyTorchAug.load(filename), to save/load Torch .t7 files

26 August:

  • if not deploying to a virtual environment, will install with --user, into home directory

14 April:

  • stack trace should be a bit more useful now :-)

17 March:

  • ctrl-c works now (tested on linux)

16 March:

  • uses luajit on linux now (mac os x continues to use lua)

6 March:

  • all classes should be usable from nn now, without needing to explicitly register inside pytorch
    • you need to upgrade to v3.0.0 to enable this, which is a breaking change, since the nn classes are now in PyTorchAug.nn, instead of directly in PyTorchAug

5 March:

  • added PyTorchHelpers.load_lua_class(lua_filename, lua_classname) to easily import a lua class from a lua file
  • can pass parameters to lua class constructors, from python
  • can pass tables to lua functions, from python (pass in as python dictionaries, become lua tables)
  • can return tables from lua functions, to python (returned as python dictionaries)

2 March:

  • removed requirements on Cython, Jinja2 for installation

28th Februrary:

26th February:

  • modified / to be the div operation for float and double tensors, and // for int-type tensors, such as byte, long, int
  • since the div change is incompatible with 1.0.0 div operators, jumping radically from 1.0.0 to 2.0.0-SNAPSHOT ...
  • added dependency on numpy
  • added .asNumpyTensor() to convert a torch tensor to a numpy tensor

24th February:

  • added support for passing strings to methods
  • added require
  • created prototype for importing your own classes, and calling methods on those
  • works with Python 3 now :-)

Older changes

pytorch's People

Contributors

hughperkins avatar patricksnape avatar soravux avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytorch's Issues

Numpy slicing affects torch Tensor?

EDIT: Sorry, I think this is already addressed in this issue. I'm not too sure if it's because of the same reason or not. Apologies if this issue is a duplicate (I can't find a delete button!)

Hi,

I noticed a small issue when I slice np arrays and send them over to torch using pytorch - some of the values get set to inf on the torch side. Here's a small piece of code that replicates what I observed:

-- echo.lua : a simple class with a method to just echo back a tensor
require 'torch'
require 'nn'

local Echo = torch.class('Echo')

function Echo:__init()
    -- Dummy init
end

function Echo:echo(nparray)
    return nparray
end
# test.py: script to generate a bunch of random tensors,
# slice them, and see if they if they're echo'd back normally
import PyTorchHelpers
import numpy as np

Echo = PyTorchHelpers.load_lua_class('echo.lua', 'Echo')
net = Echo()

for i in range(1000):
    arr = np.random.rand(10,100)
    arr_slice = arr[:,1:] # arbitrary slice
    echo = net.echo(arr_slice)  
    print np.sum(arr_slice), np.sum(echo.asNumpyTensor())

My output looks like:

...
517.576931197 0.0
483.236528627 0.0
487.247049613 0.0
487.437043052 -4.98271150804e+291
503.993869064 0.0
497.493831614 0.0
...

Note that if I either: (1) Don't slice the array or (2) slice, but also multiply by 1.0 (arr_slice = 1.0*arr[:,1:]), then the issue disappears. Any idea why? (I'm using python2.7)

PS: I've been juggling between fbtorch, several forks of lunatic-python, and putting up http servers in lua and querying from python. It's been a nightmare so far. Thank you so much for putting up this repo!

There should be an example for inserting the weights from .t7 into the net - and it's also a crucial test IMO

Hi, I see PyTorchAug.load() was recently added, and there's a test saving a numpy array, loading it and checking they're the same.

But there's no test checking a network is behaving as it should after inserting the weights from a .t7 into it, which I think is a crucial test - and can double as a usage example if one wants to load a pre-trained model and predict with it.

In the meantime, can someone enlighten me as to how to do it? (i.e. load the lua model, than insert the .t7 weights into it's layers, load an image, and call predict)

Can I save numpy arrays in .t7 using pytorch ?

I have some arrays generated by a python script and I want to save them as .t7 tensors used in torch, is this possible in pytorch ? Or maybe use pytorch to load pickle files ? Thanks!

Unable to install pytorch

I'm getting the error below while trying to run "./build.sh". I'm having Lua5.1 and all dependencies installed.

creating build/temp.linux-x86_64-2.7/src
x86_64-linux-gnu-gcc -pthread -fno-strict-aliasing -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/TH -Ithirdparty/lua-5.1.5/src -I/usr/local/include -I/usr/include/python2.7 -c src/lua.cpp -o build/temp.linux-x86_64-2.7/src/lua.o -std=c++0x -Wno-unused-function -Wno-unreachable-code -Wno-strict-prototypes
cc1plus: warning: command line option ‘-Wno-strict-prototypes’ is valid for C/ObjC but not for C++ [enabled by default]
src/lua.cpp:248:22: fatal error: THRandom.h: No such file or directory
 #include "THRandom.h"
                      ^
compilation terminated.
error: command 'x86_64-linux-gnu-gcc' failed with exit status 1

Adding support for lists and tuples in data

I am currently using PyTorch to train a neural network using two heads, like the one explained on this thread. Basically, the output of the network is a nn.ConcatTable() and the criterion is a nn.ParallelCriterion().

This requires a table for its labels, containing as many tensors as there are "heads" on the network.

In PyTorch, I would have guessed it needed a list of Numpy arrays, but pushSomething() in PyTorchAug.py complains about not knowing Python tuples and lists.

I have worked around this by creating a dictionary and attributing the values 1, 2, 3, etc. to as the keys of each numpy array. I believe this is how Lua tables work under the hood. It would not be hard to add this implementation directly into PyTorch.

Are you interested in a Pull Request adding support for lists and tuples (implementing them as dictionaries with incrementing keys)? I can have it ready soon, if you wish.

By the way, thanks a lot for developing this useful project!

import class from arbitrary torch package

Can I import an arbitrary lua package and use one of its classes in python?
I have been trying to load the file from the installation directory directly but it doesn't seem to load any of the methods of the class.

myclass =PyTorchHelpers.load_lua_class('/home/user/torch/install/share/lua/5.1/mypackage/init.lua','myclass')

Any help would be appreciated here.

Referencing .lua files in parent directories

I have a torch_model.lua file in my parent directory (/home/tushar/) that I'm trying to reference from /home/tushar/test using its relative path.

import PyTorchHelpers
TorchModel = PyTorchHelpers.load_lua_class('../torch_model.lua', 'TorchModel')

I get the following error

unprotected error in call to Lua API (module '../torch_model' not found:
	no field package.preload['../torch_model']
	no file '/home/tushar/.luarocks/share/lua/5.1////torch_model.lua'
	...

Absolute paths also fail for me.

TorchModel = PyTorchHelpers.load_lua_class('/home/tushar/torch_model.lua', 'TorchModel')

If the .lua is in the same directory (or a child directory) then it works fine. Is there any other way to reference files in my parent directory?

unknown Torch class <nn.gModule>

steps to reproduce:
import PyTorchAug x = PyTorchAug.load('umich-stacked-hourglass.t7')
output:
~/.luarocks/share/lua/5.1/torch/File.lua:343: unknown Torch class <nn.gModule>

but there is a ~/.luarocks/share/lua/5.1/nngraph/gmodule.lua
also there is a ~/.luarocks/share/lua/5.1/nn directory - maybe something incompatible/confusing/wrong require?
How to solve the problem?

Installation fails due to unknown '.pyx' file type

Following the installation instructions, the install fails after typing ./build.sh with the following message:
error: unknown file type '.pyx' (from 'src/Storage.pyx')

I could fix it by installing python-pyrex, but that should be listed in the instructions.

Segmentation fault importing PyTorch with Torch 1.0.0

Hello,

First of all thank you for the library, it worked like a charm until i upgraded torch to the most recent version (1.0.0), here is what i get on my machine:

>>> import PyTorch
>>> import torch
>>> torch.zeros(10)
Fatal Python error: Segmentation fault

or if you import Torch before PyTorch:

>>> import torch
>>> import PyTorch
Fatal Python error: Segmentation fault

Do you think there is a easy fix to solve this incompatibility?

My system:

> python --version
Python 3.6.5 :: Anaconda, Inc.
> pip list | grep -i torch
PyTorch (4.1.1-SNAPSHOT)
torch (1.0.0)

How to delete PyTorch objects correctly from memory within Python?

I'm having an issue with properly deleting PyTorch objects from memory. With this dummy class:

require 'nn'
require 'cunn'
require 'cutorch'

local Test = torch.class('Test')

function Test:__init()
    self.tensor = torch.CudaTensor(10000, 10000)
end

If I instantiate from Python:

>>> from PyTorchHelpers import load_lua_class
>>> Test = load_lua_class('modules/test.lua', 'Test')
>>> test = Test()

Then delete the object:

>>> del test

CUDA memory is not freed up.

Is there a clean way to delete a PyTorch object from memory?

Cannot install Pytorch from source python 2.7 (No GPU)

Cannot uninstall requirement PyTorch, not installed
-- The C compiler identification is GNU 4.8.4
-- The CXX compiler identification is GNU 4.8.4
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Found Torch7 in /home/rockstar/torch/install
-- Configuring done
-- Generating done
-- Build files have been written to: /home/rockstar/torch/pytorch/cbuild
Scanning dependencies of target PyTorchNative
[ 50%] [100%] Building CXX object CMakeFiles/PyTorchNative.dir/src/nnWrapper.cpp.o
Building CXX object CMakeFiles/PyTorchNative.dir/src/LuaHelper.cpp.o
Linking CXX shared library libPyTorchNative.so
/usr/bin/ld: cannot find -lluajit
collect2: error: ld returned 1 exit status
make[2]: *** [libPyTorchNative.so] Error 1
make[1]: *** [CMakeFiles/PyTorchNative.dir/all] Error 2
make: *** [all] Error 2

do we need train and test the code with same wrapper?

i have model which is trained using torch directly now , i have written prediction class in torch which i want to call using python (pytorchhelpers) , but i got below error
PANIC: unprotected error in call to Lua API (/home/tiru/torch/install/share/lua/5.1/torch/File.lua:343: unknown Torch class <torch.CudaTensor>)

CMake Warning at CMakeLists.txt:48 (FIND_PACKAGE):

Hello,
My error is related to line 48 from this file code https://github.com/SeanNaren/warp-ctc/blob/pytorch_bindings/CMakeLists.txt

After installing pytorch corrctly. l want to install the Fast parallel CTC https://github.com/SeanNaren/warp-ctc
l started installing as follow :

git clone https://github.com/baidu-research/warp-ctc.git
cd warp-ctc
mkdir build
cd build

then l stacked at the (cmake command)

cmake ../

-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Looking for pthread.h
-- Looking for pthread.h - found
-- Looking for pthread_create
-- Looking for pthread_create - not found
-- Looking for pthread_create in pthreads
-- Looking for pthread_create in pthreads - not found
-- Looking for pthread_create in pthread
-- Looking for pthread_create in pthread - found
-- Found Threads: TRUE  
-- Found CUDA: /usr/local/cuda (found suitable version "8.0", minimum required is "6.5") 
-- cuda found TRUE
_**CMake Warning at CMakeLists.txt:48 (FIND_PACKAGE):
  By not providing "FindTorch.cmake" in CMAKE_MODULE_PATH this project has
  asked CMake to find a package configuration file provided by "Torch", but
  CMake did not find one.

  Could not find a package configuration file provided by "Torch" with any of
  the following names:

    TorchConfig.cmake
    torch-config.cmake

  Add the installation prefix of "Torch" to CMAKE_PREFIX_PATH or set
  "Torch_DIR" to a directory containing one of the above files.  If "Torch"
  provides a separate development package or SDK, be sure it has been
  installed.**_


-- Torch found Torch_DIR-NOTFOUND
-- Building shared library with GPU support
-- Configuring done
-- Generating done
-- Build files have been written to: /home/ahmed/Downloads/warp-ctc/build

l don't understand the error :

**"_CMake Warning at CMakeLists.txt:48 (FIND_PACKAGE):
By not providing "FindTorch.cmake" in CMAKE_MODULE_PATH this project has
asked CMake to find a package configuration file provided by "Torch", but
CMake did not find one.

Could not find a package configuration file provided by "Torch" with any of
the following names:

TorchConfig.cmake
torch-config.cmake

Add the installation prefix of "Torch" to CMAKE_PREFIX_PATH or set
"Torch_DIR" to a directory containing one of the above files. If "Torch"
provides a separate development package or SDK, be sure it has been
installed.
"**

got below error while initiating the class

Traceback (most recent call last):
File "pythonwrap.py", line 5, in
tansclass=Torchclass()
File "/home/tiru/qgencode/qgen/lib/python3.5/site-packages/PyTorch-4.1.1_SNAPSHOT-py3.5-linux-x86_64.egg/PyTorchHelpers.py", line 20, in init
PyTorchAug.LuaClass.init(self, splitName, *args)
File "/home/tiru/qgencode/qgen/lib/python3.5/site-packages/PyTorch-4.1.1_SNAPSHOT-py3.5-linux-x86_64.egg/PyTorchAug.py", line 255, in init
raise Exception(errorMessage)
Exception: attempt to call a nil value

Can not import PyTorch together with pytorch

I have my code in python which is using pytorch library. Now I want to import another network from lua. When I load model it show an error: "Found Environment variable CUDNN_PATH = /usr/local/cuda/lib64/libcudnn.so.5*** stack smashing detected ***: python3 terminated". However if I delete import torch line, it can work normally. Anyone can help me?

How to import torch pkg.classe_name into python

Hey,

I am facing problem in accessing the classes of torch in python.
Here is an example,

local object = {}

function object.func(self, arg1, arg2)
print(arg1, arg2)
end

How to access this function named 'func' in my python code using this library(PyTorchHelpers).
Please help!!!

Thanks,
Basavaraj

Issue installing pytorch

I am following the instructions from README:installation.
I installed torch with lua5.2 instead of luajit.
I added TORCH_INSTALL variable to my .bashrc.
When I run ./build.sh I get following error. Any help is appreciated

./build.sh
Cannot uninstall requirement PyTorch, not installed
-- The C compiler identification is GNU 5.4.0
-- The CXX compiler identification is GNU 5.4.0
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Torch7 in /home/swaghmare/torch/install
-- Configuring done
-- Generating done
-- Build files have been written to: /home/swaghmare/repositories/pytorch/cbuild
Scanning dependencies of target PyTorchNative
[ 33%] Building CXX object CMakeFiles/PyTorchNative.dir/src/LuaHelper.cpp.o
[ 66%] Building CXX object CMakeFiles/PyTorchNative.dir/src/nnWrapper.cpp.o
In file included from /home/swaghmare/repositories/pytorch/src/LuaHelper.cpp:6:0:
/home/swaghmare/torch/install/include/luaT.h:41:12: warning: ‘int luaL_typerror(lua_State*, int, const char*)’ defined but not used [-Wunused-function]
static int luaL_typerror(lua_State L, int narg, const char tname)
^
In file included from /home/swaghmare/repositories/pytorch/src/nnWrapper.cpp:17:0:
/home/swaghmare/torch/install/include/luaT.h:41:12: warning: ‘int luaL_typerror(lua_State
, int, const char
)’ defined but not used [-Wunused-function]
static int luaL_typerror(lua_State *L, int narg, const char *tname)
^
[100%] Linking CXX shared library libPyTorchNative.so
/usr/bin/ld: cannot find -lluajit
collect2: error: ld returned 1 exit status
CMakeFiles/PyTorchNative.dir/build.make:122: recipe for target 'libPyTorchNative.so' failed
make[2]: *** [libPyTorchNative.so] Error 1
CMakeFiles/Makefile2:67: recipe for target 'CMakeFiles/PyTorchNative.dir/all' failed
make[1]: *** [CMakeFiles/PyTorchNative.dir/all] Error 2
Makefile:127: recipe for target 'all' failed
make: *** [all] Error 2

Install completes but tests fail: version `GOMP_4.0' not found

Hi Hugh,

I'm attempting an install on a new GTX1070, Ubuntu 16.10, CUDA 8.0, NVIDIA 367 (it took some research to get this working finally with cutorch and cunn).

Installing PyTorch completes like so:

Uninstalling PyTorch-4.1.1-SNAPSHOT:
  Successfully uninstalled PyTorch-4.1.1-SNAPSHOT
Traceback (most recent call last):
  File "/home/cjmcmurtrie/anaconda/bin/pip", line 11, in <module>
    sys.exit(main())
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/__init__.py", line 233, in main
    return command.main(cmd_args)
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/basecommand.py", line 252, in main
    pip_version_check(session)
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/utils/outdated.py", line 102, in pip_version_check
    installed_version = get_installed_version("pip")
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/utils/__init__.py", line 838, in get_installed_version
    working_set = pkg_resources.WorkingSet()
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 644, in __init__
    self.add_entry(entry)
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 700, in add_entry
    for dist in find_distributions(entry, True):
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1949, in find_eggs_in_zip
    if metadata.has_metadata('PKG-INFO'):
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1463, in has_metadata
    return self.egg_info and self._has(self._fn(self.egg_info, name))
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1823, in _has
    return zip_path in self.zipinfo or zip_path in self._index()
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1703, in zipinfo
    return self._zip_manifests.load(self.loader.archive)
  File "/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/pip/_vendor/pkg_resources/__init__.py", line 1643, in load
    mtime = os.stat(path).st_mtime
OSError: [Errno 2] No such file or directory: '/home/cjmcmurtrie/.local/lib/python2.7/site-packages/PyTorch-4.1.1_SNAPSHOT-py2.7-linux-x86_64.egg'
-- The C compiler identification is GNU 4.9.4
-- The CXX compiler identification is GNU 4.9.4
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
-- Found Torch7 in /home/cjmcmurtrie/torch/install
-- Configuring done
-- Generating done
-- Build files have been written to: /home/cjmcmurtrie/pytorch/cbuild
Scanning dependencies of target PyTorchNative
[ 66%] Building CXX object CMakeFiles/PyTorchNative.dir/src/nnWrapper.cpp.o
[ 66%] Building CXX object CMakeFiles/PyTorchNative.dir/src/LuaHelper.cpp.o
[100%] Linking CXX shared library libPyTorchNative.so
[100%] Built target PyTorchNative
Install the project...
-- Install configuration: "Debug"
-- Installing: /home/cjmcmurtrie/torch/install/lib/libPyTorchNative.so
-- Set runtime path of "/home/cjmcmurtrie/torch/install/lib/libPyTorchNative.so" to "$ORIGIN/../lib:/home/cjmcmurtrie/torch/install/lib:/opt/OpenBLAS/lib"
torch_install: /home/cjmcmurtrie/torch/install
os family Linux
/home/cjmcmurtrie/anaconda/lib/python2.7/site-packages/setuptools-27.2.0-py2.7.egg/setuptools/dist.py:340: UserWarning: The version specified ('4.1.1-SNAPSHOT') is an invalid version, this may not work as expected with newer versions of setuptools, pip, and PyPI. Please see PEP 440 for more details.
running install
running bdist_egg
running egg_info
writing requirements to src/PyTorch.egg-info/requires.txt
writing src/PyTorch.egg-info/PKG-INFO
writing top-level names to src/PyTorch.egg-info/top_level.txt
writing dependency_links to src/PyTorch.egg-info/dependency_links.txt
reading manifest file 'src/PyTorch.egg-info/SOURCES.txt'
writing manifest file 'src/PyTorch.egg-info/SOURCES.txt'
installing library code to build/bdist.linux-x86_64/egg
running install_lib
running build_py
creating build
creating build/lib.linux-x86_64-2.7
copying src/floattensor.py -> build/lib.linux-x86_64-2.7
copying src/PyTorchAug.py -> build/lib.linux-x86_64-2.7
copying src/PyTorchHelpers.py -> build/lib.linux-x86_64-2.7
copying src/PyTorchLua.py -> build/lib.linux-x86_64-2.7
running build_ext
building 'lua' extension
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/src
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/cjmcmurtrie/torch/install/include/TH -Ithirdparty/lua-5.1.5/src -I/home/cjmcmurtrie/torch/install/include -I/home/cjmcmurtrie/anaconda/include/python2.7 -c src/lua.cpp -o build/temp.linux-x86_64-2.7/src/lua.o -std=c++0x -Wno-unused-function -Wno-unreachable-code -Wno-strict-prototypes
cc1plus: warning: command line option ‘-Wno-strict-prototypes’ is valid for C/ObjC but not for C++
g++ -pthread -shared -L/home/cjmcmurtrie/anaconda/lib -Wl,-rpath=/home/cjmcmurtrie/anaconda/lib,--no-as-needed build/temp.linux-x86_64-2.7/src/lua.o -L/home/cjmcmurtrie/torch/install/lib -L/home/cjmcmurtrie/anaconda/lib -Wl,-R/home/cjmcmurtrie/torch/install/lib -lPyTorchNative -lpython2.7 -o build/lib.linux-x86_64-2.7/lua.so
building 'Storage' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/cjmcmurtrie/torch/install/include/TH -Ithirdparty/lua-5.1.5/src -I/home/cjmcmurtrie/torch/install/include -I/home/cjmcmurtrie/anaconda/include/python2.7 -c src/Storage.cpp -o build/temp.linux-x86_64-2.7/src/Storage.o -std=c++0x -Wno-unused-function -Wno-unreachable-code -Wno-strict-prototypes
cc1plus: warning: command line option ‘-Wno-strict-prototypes’ is valid for C/ObjC but not for C++
g++ -pthread -shared -L/home/cjmcmurtrie/anaconda/lib -Wl,-rpath=/home/cjmcmurtrie/anaconda/lib,--no-as-needed build/temp.linux-x86_64-2.7/src/Storage.o -L/home/cjmcmurtrie/torch/install/lib -L/home/cjmcmurtrie/anaconda/lib -Wl,-R/home/cjmcmurtrie/torch/install/lib -lPyTorchNative -lpython2.7 -o build/lib.linux-x86_64-2.7/Storage.so
building 'PyTorch' extension
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/cjmcmurtrie/torch/install/include/TH -Ithirdparty/lua-5.1.5/src -I/home/cjmcmurtrie/torch/install/include -I/home/cjmcmurtrie/anaconda/include/python2.7 -c src/PyTorch.cpp -o build/temp.linux-x86_64-2.7/src/PyTorch.o -std=c++0x -Wno-unused-function -Wno-unreachable-code -Wno-strict-prototypes
cc1plus: warning: command line option ‘-Wno-strict-prototypes’ is valid for C/ObjC but not for C++
g++ -pthread -shared -L/home/cjmcmurtrie/anaconda/lib -Wl,-rpath=/home/cjmcmurtrie/anaconda/lib,--no-as-needed build/temp.linux-x86_64-2.7/src/PyTorch.o -L/home/cjmcmurtrie/torch/install/lib -L/home/cjmcmurtrie/anaconda/lib -Wl,-R/home/cjmcmurtrie/torch/install/lib -lPyTorchNative -lpython2.7 -o build/lib.linux-x86_64-2.7/PyTorch.so
creating build/bdist.linux-x86_64
creating build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-2.7/PyTorchHelpers.py -> build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-2.7/PyTorchLua.py -> build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-2.7/floattensor.py -> build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-2.7/lua.so -> build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-2.7/PyTorchAug.py -> build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-2.7/PyTorch.so -> build/bdist.linux-x86_64/egg
copying build/lib.linux-x86_64-2.7/Storage.so -> build/bdist.linux-x86_64/egg
byte-compiling build/bdist.linux-x86_64/egg/PyTorchHelpers.py to PyTorchHelpers.pyc
byte-compiling build/bdist.linux-x86_64/egg/PyTorchLua.py to PyTorchLua.pyc
byte-compiling build/bdist.linux-x86_64/egg/floattensor.py to floattensor.pyc
byte-compiling build/bdist.linux-x86_64/egg/PyTorchAug.py to PyTorchAug.pyc
creating stub loader for lua.so
creating stub loader for Storage.so
creating stub loader for PyTorch.so
byte-compiling build/bdist.linux-x86_64/egg/lua.py to lua.pyc
byte-compiling build/bdist.linux-x86_64/egg/Storage.py to Storage.pyc
byte-compiling build/bdist.linux-x86_64/egg/PyTorch.py to PyTorch.pyc
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying src/PyTorch.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying src/PyTorch.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying src/PyTorch.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying src/PyTorch.egg-info/requires.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying src/PyTorch.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
writing build/bdist.linux-x86_64/egg/EGG-INFO/native_libs.txt
zip_safe flag not set; analyzing archive contents...
creating dist
creating 'dist/PyTorch-4.1.1_SNAPSHOT-py2.7-linux-x86_64.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing PyTorch-4.1.1_SNAPSHOT-py2.7-linux-x86_64.egg
Copying PyTorch-4.1.1_SNAPSHOT-py2.7-linux-x86_64.egg to /home/cjmcmurtrie/.local/lib/python2.7/site-packages
Adding PyTorch 4.1.1-SNAPSHOT to easy-install.pth file

Installed /home/cjmcmurtrie/.local/lib/python2.7/site-packages/PyTorch-4.1.1_SNAPSHOT-py2.7-linux-x86_64.egg
Processing dependencies for PyTorch===4.1.1-SNAPSHOT
Searching for numpy==1.11.1
Best match: numpy 1.11.1
Adding numpy 1.11.1 to easy-install.pth file

Using /home/cjmcmurtrie/anaconda/lib/python2.7/site-packages
Finished processing dependencies for PyTorch===4.1.1-SNAPSHOT

However the following tests fail, complaining that version GOMP_4.0' not found` (related to gcc version? I have 4.9 with I thought was correct):

------------ generated xml file: /home/cjmcmurtrie/pytorch/test/junit-pytest-report.xml -------------
====================================== short test summary info ======================================
ERROR test/testByteTensor.py
ERROR test/test_call_lua.py
ERROR test/testDoubleTensor.py
ERROR test/testFloatTensor.py
ERROR test/testLongTensor.py
ERROR test/test_nnx.py
ERROR test/test_pynn.py
ERROR test/test_pytorch.py
ERROR test/test_pytorch_refcount.py
ERROR test/test_save_load.py
ERROR test/test_throw.py
============================================== ERRORS ===============================================
______________________________ ERROR collecting test/testByteTensor.py ______________________________
test/testByteTensor.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
______________________________ ERROR collecting test/test_call_lua.py _______________________________
test/test_call_lua.py:1: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
_____________________________ ERROR collecting test/testDoubleTensor.py _____________________________
test/testDoubleTensor.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
_____________________________ ERROR collecting test/testFloatTensor.py ______________________________
test/testFloatTensor.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
______________________________ ERROR collecting test/testLongTensor.py ______________________________
test/testLongTensor.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
_________________________________ ERROR collecting test/test_nnx.py _________________________________
test/test_nnx.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
________________________________ ERROR collecting test/test_pynn.py _________________________________
test/test_pynn.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
_______________________________ ERROR collecting test/test_pytorch.py _______________________________
test/test_pytorch.py:5: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
__________________________ ERROR collecting test/test_pytorch_refcount.py ___________________________
test/test_pytorch_refcount.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
______________________________ ERROR collecting test/test_save_load.py ______________________________
test/test_save_load.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
________________________________ ERROR collecting test/test_throw.py ________________________________
test/test_throw.py:1: in <module>
    import PyTorchHelpers
build/bdist.linux-x86_64/egg/PyTorchHelpers.py:1: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)
================================ 11 passed, 11 error in 0.52 seconds ================================

And a load_lua_class import complains about the same thing:

>>> from PyTorchHelpers import load_lua_class
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "build/bdist.linux-x86_64/egg/PyTorchHelpers.py", line 1, in <module>
  File "build/bdist.linux-x86_64/egg/PyTorch.py", line 7, in <module>
  File "build/bdist.linux-x86_64/egg/PyTorch.py", line 6, in __bootstrap__
ImportError: /home/cjmcmurtrie/anaconda/lib/libgomp.so.1: version `GOMP_4.0' not found (required by /home/cjmcmurtrie/torch/install/lib/../lib/libTH.so.0)

Any suggestions? Thanks!

Segmentation fault OSX

I got this error when trying to import PyTorch under OS X

import PyTorch
dlopen(liblua5.1.so, 10): image not found
Segmentation fault: 11

Path of a lua file not recognized

Hi,

I am using pytorch in one of my projects and when I give the path of lua file in the following line like this:
TorchModel = PyTorchHelpers.load_lua_class('/home/ubuntu/deshraj/grad-cam/sample.lua', 'TorchModel')

Then it shows the following error: PANIC: unprotected error in call to Lua API (module '/home/ubuntu/deshraj/grad-cam/sample' not found: but the file exists there.

@hughperkins Is this not the correct way of giving the path ?

Invalid argument 2: 3D or 4D input tensor expected but got: [32 x 784]

Hi Hugh, thanks for this nice software, when I run the example code of MNIST, it shows the following error,

Connected to pydev debugger (build 171.4694.67)
$ Invalid argument 2: 3D or 4D input tensor expected but got: [32 x 784] at /tmp/luarocks_nn-scm-1-8028/nn/lib/THNN/generic/SpatialConvolutionMM.c:33

How to deal with it

Pushing type 'numpy.ndarray' failing on OSX

I managed to build pytorch on OSX and all the tests passed. Running python pybit.py also worked without a hitch.

However, I cannot get the more complex example from the front-page to run (the convolutional network on MNIST). Both versions of this (from the examples folder and from the frontpage) throw the same error. I'm in a Python 2.71 environment, no CUDA GPU on this machine. This is the traceback:

$ python run_torch_model.py
Traceback (most recent call last):
  File "run_torch_model.py", line 35, in <module>
    lab_batch)
  File "build/bdist.macosx-10.5-x86_64/egg/PyTorchAug.py", line 147, in mymethod
  File "build/bdist.macosx-10.5-x86_64/egg/PyTorchAug.py", line 109, in pushSomething
Exception: ("pushing type <type 'numpy.ndarray'> not implemented, value ", array([[0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       ..., 
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0],
       [0, 0, 0, ..., 0, 0, 0]], dtype=uint8))

This is the Python script I'm running (I grabbed the MNIST data from Sklearn but the error is the same using the python-mnist package):

from __future__ import print_function, division
import PyTorch
import PyTorchHelpers
import numpy as np
from sklearn.datasets import fetch_mldata


batchSize = 32
numEpochs = 2
learningRate = 0.02

TorchModel = PyTorchHelpers.load_lua_class('torch_model.lua', 'TorchModel')
torchModel = TorchModel('cpu', 28, 10)

mnist = fetch_mldata('MNIST original', '')

images = mnist.data
labels = mnist.target

labels += 1  # since torch/lua labels are 1-based
N = labels.shape[0]

numBatches = N // batchSize
for epoch in range(numEpochs):
  epochLoss = 0
  epochNumRight = 0
  for b in range(numBatches):

    im_batch = images[b * batchSize:(b+1) * batchSize]
    lab_batch = labels[b * batchSize:(b+1) * batchSize]

    res = torchModel.trainBatch(
      learningRate,
      im_batch,
      lab_batch)

    numRight = res['numRight']
    epochNumRight += numRight
  print('epoch ' + str(epoch) + ' accuracy: ' + str(epochNumRight * 100.0 / N) + '%')

This is the Torch script:

require 'torch'
require 'nn'

local TorchModel = torch.class('TorchModel')

function TorchModel:__init(backend, imageSize, numClasses)
  self:buildModel(backend, imageSize, numClasses)
  self.imageSize = imageSize
  self.numClasses = numClasses
  self.backend = backend
end

function TorchModel:buildModel(backend, imageSize, numClasses)
  self.net = nn.Sequential()
  local net = self.net

  net:add(nn.SpatialConvolutionMM(1, 16, 5, 5, 1, 1, 2, 2))
  net:add(nn.ReLU())
  net:add(nn.SpatialMaxPooling(3, 3, 3, 3))
  net:add(nn.SpatialConvolutionMM(16, 32, 3, 3, 1, 1, 1, 1))
  net:add(nn.ReLU())
  net:add(nn.SpatialMaxPooling(2, 2, 2, 2))
  net:add(nn.Reshape(32 * 4 * 4))
  net:add(nn.Linear(32 * 4 * 4, 150))
  net:add(nn.Tanh())
  net:add(nn.Linear(150, numClasses))
  net:add(nn.LogSoftMax())

  self.crit = nn.ClassNLLCriterion()

  self.net:float()
  self.crit:float()
end

function TorchModel:trainBatch(learningRate, input, labels)
  self.net:zeroGradParameters()

  local output = self.net:forward(input)
  local loss = self.crit:forward(output, labels)
  local gradOutput = self.crit:backward(output, labels)
  self.net:backward(input, gradOutput)
  self.net:updateParameters(learningRate)

  local _, prediction = output:max(2)
  local numRight = labels:int():eq(prediction:int()):sum()
  return {loss=loss, numRight=numRight}  -- you can return a table, it will become a python dictionary
end

function TorchModel:predict(input)
  local output = self.net:forward(input)
  local _, prediction = output:max(2)
  return prediction:byte()
end

'version `GFORTRAN_1.4'' not found when running tests

Hi Hugh, I'm now attempting a build on an Ubuntu 14.04 machine with CUDA 7.5. I have a fresh Torch install and Python 2.7.11 Anaconda distribution.

After building PyTorch, running the tests fails with the followings errors:

platform linux2 -- Python 2.7.11, pytest-2.8.5, py-1.4.31, pluggy-0.3.1 -- /home/dg/anaconda2/bin/python
cachedir: .cache
rootdir: /home/dg/pytorch, inifile: 
collected 0 items / 8 errors 

======================================================= ERRORS =======================================================
______________________________________ ERROR collecting test/testByteTensor.py _______________________________________
test/testByteTensor.py:3: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
_____________________________________ ERROR collecting test/testDoubleTensor.py ______________________________________
test/testDoubleTensor.py:3: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
______________________________________ ERROR collecting test/testFloatTensor.py ______________________________________
test/testFloatTensor.py:3: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
______________________________________ ERROR collecting test/testLongTensor.py _______________________________________
test/testLongTensor.py:3: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
_________________________________________ ERROR collecting test/test_nnx.py __________________________________________
test/test_nnx.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
_________________________________________ ERROR collecting test/test_pynn.py _________________________________________
test/test_pynn.py:2: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
_______________________________________ ERROR collecting test/test_pytorch.py ________________________________________
test/test_pytorch.py:5: in <module>
    import PyTorch
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
________________________________________ ERROR collecting test/test_throw.py _________________________________________
test/test_throw.py:1: in <module>
    import PyTorchHelpers
build/bdist.linux-x86_64/egg/PyTorchHelpers.py:1: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:7: in <module>
    ???
build/bdist.linux-x86_64/egg/PyTorch.py:6: in __bootstrap__
    ???
E   ImportError: /home/dg/anaconda2/lib/libgfortran.so.3: version `GFORTRAN_1.4' not found (required by /usr/lib/liblapack.so.3)
============================================== 8 error in 0.26 seconds ===============================================

Any idea what could be causing this? Since I was using the same distribution (Anaconda) with a successful build on OSX, I'm not sure what the problem could be here.

None -> nil?

Would it make sense to convert None passed as a Python method param into nil? Is there some unobvious caveat that makes this nontrivial?

torch-hdf5 causes pytorch to choke

I have torch-hdf5 installed in my torch-cl installation. Although I can successfully access the hdf5 functions in that rock from within trepl, I observe the following error when I try adding require 'hdf5' to a Lua file containing an otherwise loadable class and loading the latter with PyTorch:

PANIC: unprotected error in call to Lua API (...projects/torch-cl/install/share/lua/5.1/hdf5/ffi.lua:3: module 'bit' not found:

Oddly, I can access the support for bit operations when I'm in trepl. Any idea why the torch-hdf5 rock elicits the above error?

I'm using pytorch 65e8871 and revision c77d374 of the hughperkins/distro repo with Python 2.7.12 on MacOS 10.11.6.

Is work with mac

I tried with mac and I received this error at the end any way I will try it tomorrow in Linux.

14 warnings generated.
creating build/lib.macosx-10.6-intel-2.7
/usr/bin/clang++ -bundle -undefined dynamic_lookup -arch i386 -arch x86_64 -g build/temp.macosx-10.6-intel-2.7/src/lua.o -Lcbuild -L/Users/salemameen/torch/install/lib -lTorchLanguageIndependence -o build/lib.macosx-10.6-intel-2.7/lua.so
ld: warning: directory not found for option '-Lcbuild'
ld: library not found for -lTorchLanguageIndependence
clang: error: linker command failed with exit code 1 (use -v to see invocation)
error: command '/usr/bin/clang++' failed with exit status 1

Can't install pytorch

I've successfully built pytorch but run_tests.sh fails with ./run_tests.sh: line 25: py.test: command not found and installing as library (python3 setup.py install) fails with src/lua.cpp:248:10: fatal error: 'THRandom.h' file not found

What should I do?

permission denied: python setup.py install

I have python 2.7 which installed by default in Ubuntu 14.04
And torch is installed in my home directory.

When I run the script build.sh, there's permission denied error like below:

running install
error: can't create or remove files in install directory

The following error occurred while trying to add or remove files in the
installation directory:

    [Errno 13] Permission denied: '/usr/local/lib/python2.7/dist-packages/test-easy-install-18167.write-test'

The installation directory you specified (via --install-dir, --prefix, or
the distutils default setting) was:

    /usr/local/lib/python2.7/dist-packages/

This is obvious because python setup.py install tend to install below /usr/local/lib/python2.7
sudo ./build.sh also fails because it cannot find the torch when I use sudo.

My solution was update the last line of build.sh like this:

python setup.py install --user || exit 1

pytorch package is installed below my home directory and it works well.

However, how do you install this package in general situation?

Jupyter notebook dies

If i try to do even the most basic thing into a ipython notebook:

import PyTorch

The notebook dies:

The kernel appears to have died. It will restart automatically.

But the import (and all the other functionality) works good in a normal python terminal, any idea why this is happening?

Inline operations while calling a torch class

Hi,
First of all thanks for pytorch, is an awesome work and really useful!

I just found that when doing inline operations (i.e: on a numpy array) and passing that to a method on Torch to lets say store it as a class value something goes wrong. I guess this has to do with memory reference while passing data from one side to the other.

I made a simple example code reproducing the issue.
I have a python main.py file that imports, creates and uses a Torch class.
The torch class has an 'init' method, which does nothing, a 'set' method which sets a tensor of the class to a given numpy array. And a write method that prints the mentioned tensor.

The main.py file only creates the class and set/prints the torch tensor inside the torch class. First by creating a numpy array and modifying and storing the value in a separate variable and after modifying the numpy array inline while passing to torch.

The problem is, when passing the numpy array created inline in the call, the values the Torch class stores are not right.
The way this doesn't happen is:

  1. Avoiding inline operations
  2. Explicitly cloning the tensor inside the torch class (that's why I think is a mem. reference issue)

Running the example will be way more clarifying that my explanation.

Not sure if this is supposed to work this way, I just though that in case you are not aware this might help you and others.

I attach the two mentioned pieces of code in a zip file.

code.zip

pop type torch.CudaTensor not implemented

Hi,
I get a strange error while trying a forward pass through a loaded Torch model:

function TorchModel:forward(input)
  local output = self.net:forward(torch.rand(1,3,112,112):cuda())
  return output
end
PyTorchAug.py", line 181, in popSomething
    raise Exception('pop type ' + str(typestring) + ' not implemented')
Exception: pop type torch.CudaTensor not implemented

PyTorchAug.save() doesn't save correct weights.

>>> l
nn.SpatialConvolution(1 -> 3, 3x3, 1,1, 1,1)

>>> l.weight.asNumpyTensor()
array([[[[2., 2., 2.],
         [2., 2., 2.],
         [2., 2., 2.]]],


       [[[2., 2., 2.],
         [2., 2., 2.],
         [2., 2., 2.]]],


       [[[2., 2., 2.],
         [2., 2., 2.],
         [2., 2., 2.]]]], dtype=float32)

>>> PyTorchAug.save('/home/jatin17/workspace/pySeer/sketch/test_WW.net',l)
>>> l2=PyTorchAug.load('/home/jatin17/workspace/pySeer/sketch/test_WW.net')

>>> l2.weight.asNumpyTensor()
array([[[[-0.20179332, -0.32749048,  0.22701705],
         [ 0.18695774, -0.11507146,  0.32600074],
         [-0.3111914 , -0.24465627,  0.26392609]]],


       [[[ 0.14200437, -0.17333959,  0.25616663],
         [ 0.04954733, -0.14041339,  0.00439858],
         [-0.18362816, -0.13976645, -0.26147268]]],


       [[[-0.16414926, -0.31703166,  0.13214643],
         [ 0.06721597, -0.26673907, -0.13336769],
         [-0.02258702,  0.22950082,  0.30467097]]]])

#Lua torch7
th> xx=torch.load('test_WW.net')
th> xx.weight
(1,1,.,.) = 
 -0.2018 -0.3275  0.2270
  0.1870 -0.1151  0.3260
 -0.3112 -0.2447  0.2639

(2,1,.,.) = 
  0.1420 -0.1733  0.2562
  0.0495 -0.1404  0.0044
 -0.1836 -0.1398 -0.2615

(3,1,.,.) = 
 -0.1641 -0.3170  0.1321
  0.0672 -0.2667 -0.1334
 -0.0226  0.2295  0.3047
[torch.DoubleTensor of size 3x1x3x3]

PyTorchAug.load works fine and loads correct weights. Verified using luaTorch load method which matches the weights.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.