• Stars
    star
    431
  • Rank 100,866 (Top 2 %)
  • Language
    Python
  • License
    BSD 2-Clause "Sim...
  • Created about 9 years ago
  • Updated over 7 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Python wrappers for torch and lua

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

More Repositories

1

DeepCL

OpenCL library to train deep convolutional neural networks
C++
849
star
2

coriander

Build NVIDIA® CUDA™ code for OpenCL™ 1.2 devices
LLVM
842
star
3

VeriGPU

OpenSource GPU, in Verilog, loosely based on RISC-V ISA
SystemVerilog
792
star
4

tf-coriander

OpenCL 1.2 implementation for Tensorflow
C++
792
star
5

cltorch

An OpenCL backend for torch.
C++
287
star
6

EasyCL

Easy to run kernels using OpenCL
C++
177
star
7

Jinja2CppLight

(very) lightweight version of Jinja2 for C++
C++
140
star
8

clnn

OpenCL backend for Torch nn neural networks library
Lua
123
star
9

howto-jenkins-ssl

quick how to on activating ssl on jenkins, so I can find it easily
109
star
10

jeigen

Java wrapper for Eigen C++ fast matrix library
C++
104
star
11

kgsgo-dataset-preprocessor

Dataset preprocessor for the KGS go dataset, eg according to Clark and Storkey input planes
Python
70
star
12

peaceful-pie

Control Unity from Python! Use for reinforcement learning.
C#
28
star
13

cpu-tutorial

Tutorial on building your own CPU, in Verilog
28
star
14

coriander-dnn

Partial implementation of NVIDIA® cuDNN API for Coriander, OpenCL 1.2
C++
22
star
15

rnn-notes

Notes on how element-research rnn works
17
star
16

luacpptemplater

Write Jinja2-style templates in C++. Uses lua as a scripting language (very lightweight)
C++
16
star
17

jfastparser

Very fast parsing of doubles and ints from a string
Java
15
star
18

UnityFluidSim-pub

UnityFluidSim-pub
C#
14
star
19

pytorch-coriander

OpenCL build of pytorch - (in-progress, not useable)
Python
14
star
20

pub-prototyping

prototyping stuff
C++
13
star
21

securewebcmd

Execute commands on a linux server through a webpage. Secured using md5 hashing
JavaScript
12
star
22

neonCl-underconstruction

experimental port of nervana neon kernels in OpenCL
Python
11
star
23

selfstudy-IBP

Self-study notes for Indian Buffet Process, from reading through "The Indian Buffet Process: An Introduction and Review", Griffiths, Ghahramani, 2011
Jupyter Notebook
11
star
24

torch-modder-notes

Notes for torch maintainers/modders
10
star
25

pycudatorch

poc for using cuda torch from python :-)
Python
7
star
26

nimbix-admin

utility scripts for start/stop/ssh to nimbix instances
Python
7
star
27

coriander-CLBlast

BLAS implementation for Coriander, using CLBlast
C++
6
star
28

ArgParseCpp

C++ version of Python's ArgParse
C++
5
star
29

passwordbookmarklet

bookmarklet to generate unique secure passwords for each website from a single master password
JavaScript
5
star
30

torchunit

torchunit
Shell
4
star
31

tinisles-googleauthenticator

Fork of the code at http://blog.tinisles.com/2011/10/google-authenticator-one-time-password-algorithm-in-javascript/
HTML
3
star
32

springgrid

Runs spring matches on a grid of botrunners
Python
3
star
33

osmp-cs

OSMP C# - Opensource Secondlife clone, from around 2005
C#
3
star
34

ailadder

code to create an ailadder webserver
Python
3
star
35

pycltorch

POC for Python wrappers for cltorch/clnn
Python
3
star
36

yet-another-measure-theoretic-probability-tutorial

Yet another measure theoretic probability tutorial
Jupyter Notebook
3
star
37

HughAI

HughAI Java AI for Spring
Java
3
star
38

selfstudy-LARS

least angle regression, reproducing for self-study
Jupyter Notebook
2
star
39

verigpu-cuda-frontend

Front-end for VeriGPU, providing NVIDIA® CUDA™ compatibility, for compatibility purposes
2
star
40

selfstudy-LIME

LIME
Jupyter Notebook
2
star
41

blameful-indenter

reindent code, whilst preserving git blame
Python
2
star
42

SpringRTS-CSharpAI

AI For Spring RTS game, in C#, from around 2006
C#
2
star
43

neon-benchmarks

benchmarks for neon, both cuda and OpenCL version
Python
2
star
44

FractalSpline-cpp

Provides SecondLife-like primitives , in C++/OpenGL. From around 2005
C++
2
star
45

relooper

Reloop llvm IR output, to have `for`s, `if`s, `while`s. From https://reviews.llvm.org/D12744
C++
2
star
46

osmp-cpp

OSMP C++ - opensource SecondLife clone, from around 2004
C++
2
star
47

python-graphics-numpy

Scripts for youtube video on creating graphics in python using numpy
Python
2
star
48

chat-ai-npcs-video-resources

chat-ai-npcs-video-resources
C#
2
star
49

github-stars

get an email whenever someone stars your github repo :-)
Python
2
star
50

project-ideas

Ideas for projects
2
star
51

scalable-gpt-developer

scalable-gpt-developer
Python
2
star
52

gpu-experiments

Informal experiments on various gpu kernel questions
Python
1
star
53

blender-tips

blender-tips
Python
1
star
54

peaceful-pie-video-resources

Resources for watching Peaceful Pie videos
Python
1
star
55

dockerfiles

dockerfiles
1
star
56

virtualenv-move

Moves a python virtualenv
Shell
1
star
57

privacy-policies

privacy-policies
HTML
1
star
58

openpw

Password hash generator, including console, bookmarklet, chrome extension
JavaScript
1
star
59

headlessopenglstubs

stubs for opengl, glew, sdl, whatever it takes ;-), to get spring to run without an X session
1
star
60

python-threadingx

Erlang-like threading functionality for Python
Python
1
star
61

youtube-likes

Receive a notification/email when someone 'like's one of your videos.
Python
1
star
62

youtube-rl-demos

Scripts, code used in youtube demos
Python
1
star
63

SpringMapDesigner

3d MapDesigner for Spring
1
star
64

chinese-transcriptions

Transcriptions of Chinese language videos
1
star
65

ndplot

high-dimensional viewer, by projecting onto a 3d hypercube. Use the mouse to rotate the 3d projection.
Python
1
star
66

pytorch-prettify

Prettifies exceptions coming out of pytorch
Jupyter Notebook
1
star
67

tf_cached_build

Cache tensorflow build dependencies, to accelerate repeated tf configures, or run on a plane
Python
1
star
68

cppsimpleargsparser

Simple C++ args parser. Easy to use. Automatically provides checking and usage printout.
C++
1
star
69

PortableTensor.Net

Cross-platform Tensor with transpose, slice as views over underlying data
C#
1
star