• Stars
    star
    307
  • Rank 136,109 (Top 3 %)
  • Language
    Python
  • License
    GNU General Publi...
  • Created about 6 years ago
  • Updated about 4 years ago

Reviews

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

Repository Details

Unit Testing for pytorch, based on mltest

torchtest

A Tiny Test Suite for pytorch based Machine Learning models, inspired by mltest. Chase Roberts lists out 4 basic tests in his medium post about mltest. torchtest is mostly a pytorch port of mltest(which was written for tensorflow).

Installation

pip install --upgrade torchtest

Tests

# imports for examples
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable

Variables Change

from torchtest import assert_vars_change

inputs = Variable(torch.randn(20, 20))
targets = Variable(torch.randint(0, 2, (20,))).long()
batch = [inputs, targets]
model = nn.Linear(20, 2)

# what are the variables?
print('Our list of parameters', [ np[0] for np in model.named_parameters() ])

# do they change after a training step?
#  let's run a train step and see
assert_vars_change(
    model=model,
    loss_fn=F.cross_entropy,
    optim=torch.optim.Adam(model.parameters()),
    batch=batch)
""" FAILURE """
# let's try to break this, so the test fails
params_to_train = [ np[1] for np in model.named_parameters() if np[0] is not 'bias' ]
# run test now
assert_vars_change(
    model=model,
    loss_fn=F.cross_entropy,
    optim=torch.optim.Adam(params_to_train),
    batch=batch)

# YES! bias did not change

Variables Donโ€™t Change

from torchtest import assert_vars_same

# What if bias is not supposed to change, by design?
#  test to see if bias remains the same after training
assert_vars_same(
    model=model,
    loss_fn=F.cross_entropy,
    optim=torch.optim.Adam(params_to_train),
    batch=batch,
    params=[('bias', model.bias)]
    )
# it does? good. let's move on

Output Range

from torchtest import test_suite

# NOTE : bias is fixed (not trainable)
optim = torch.optim.Adam(params_to_train)
loss_fn=F.cross_entropy

test_suite(model, loss_fn, optim, batch,
    output_range=(-2, 2),
    test_output_range=True
    )

# seems to work
""" FAILURE """
#  let's tweak the model to fail the test
model.bias = nn.Parameter(2 + torch.randn(2, ))

test_suite(
    model,
    loss_fn, optim, batch,
    output_range=(-1, 1),
    test_output_range=True
    )

# as expected, it fails; yay!

NaN Tensors

""" FAILURE """
model.bias = nn.Parameter(float('NaN') * torch.randn(2, ))

test_suite(
    model,
    loss_fn, optim, batch,
    test_nan_vals=True
    )

Inf Tensors

""" FAILURE """
model.bias = nn.Parameter(float('Inf') * torch.randn(2, ))

test_suite(
    model,
    loss_fn, optim, batch,
    test_inf_vals=True
    )

Debugging

torchtest\torchtest.py", line 151, in _var_change_helper
assert not torch.equal(p0, p1)
RuntimeError: Expected object of backend CPU but got backend CUDA for argument #2 'other'

When you are making use of a GPU, you should explicitly specify device=cuda:0. By default device is set to cpu. See issue #1 for more information.

test_suite(
    model,  # a model moved to GPU
    loss_fn, optim, batch,
    test_inf_vals=True,
    device='cuda:0'
    )

Citation

@misc{Ram2019,
  author = {Suriyadeepan Ramamoorthy},
  title = {torchtest},
  year = {2019},
  publisher = {GitHub},
  journal = {GitHub repository},
  howpublished = {\url{https://github.com/suriyadeepan/torchtest}},
  commit = {42ba442e54e5117de80f761a796fba3589f9b223}
}

More Repositories

1

practical_seq2seq

A simple, minimal wrapper for tensorflow's seq2seq module, for experimenting with datasets rapidly
Jupyter Notebook
570
star
2

easy_seq2seq

[unmaintained] go to https://github.com/suriyadeepan/practical_seq2seq
Python
299
star
3

datasets

A collection of all my datasets
Jupyter Notebook
239
star
4

rnn-from-scratch

Use tensorflow's tf.scan to build vanilla, GRU and LSTM RNNs
Python
128
star
5

BayesianML

Experiments in Bayesian Machine Learning
Jupyter Notebook
67
star
6

pm-pyro

PyMC3-like Interface for Pyro
Jupyter Notebook
37
star
7

augmented_seq2seq

enhance seq2seq model for open ended dialog generation
Python
28
star
8

tweet_bot

A Twitter bot based on seq2seq model, trained on twitter chat log
Python
10
star
9

match-lstm

Match LSTM for Textual Entailment
Jupyter Notebook
8
star
10

python3

Learn to programmatically express your will with Python 3
HTML
7
star
11

PyroDemystified-PyCon2019

Content for the workshop "Pyro Demystified : Bayesian Deep Learning" (PyCon 2019 - Chennai)
Jupyter Notebook
7
star
12

neural-pde

A Deep Learning library for Partial Differential Equations
Python
7
star
13

anatomy-of-ppl

Anatomy of Probabilistic Programming Languages
Jupyter Notebook
6
star
14

Castalia

My Castalis Repository : Simulation of MAC and Routing protocols
C++
6
star
15

language-modeling

Language Modeling with RNN in Tensorflow
Python
5
star
16

deeplearning

Deep Learning Reading List
Python
5
star
17

NeuralQA

Neural Question-Answering/Reading Comprehension (SQuAD, bAbI, CBT, NarrativeQA, VQA)
Python
5
star
18

recompute.py

A sweet tool for Remote Execution
Python
4
star
19

WebScraping-for-Healthcare

Web Scraping for Healthcare
Jupyter Notebook
4
star
20

TF

Tutorials, practice exercises for TensorFlow
Jupyter Notebook
4
star
21

reddit-ml-threads

Use PRAW to scrape threads on Machine Learning
Jupyter Notebook
3
star
22

swecha-machine-learning-workshop

Introduction to Machine Learning using Tensorflow, at SWECHA, Hyderabad
Jupyter Notebook
3
star
23

SRM-NLP-Workshop-2019

Code, Notes, Slides, Data
HTML
3
star
24

NetCla

Network Activity Classification with Machine Learning
Jupyter Notebook
3
star
25

tana

This Aint No AutoML
Python
3
star
26

IndoorTracking

Implementation of Detecting People in Indoor Clutter Scenes
Python
3
star
27

robot_vision_android

Android Application built with opencv libraries, for an Object Tracking Mobile Android Robot...
Java
3
star
28

wiki-graph

Graphical representation of wikipedia information.
Python
3
star
29

memory-networks

experiments with explicit memory for NLP
Python
3
star
30

bec-gp

Simulating the dynamics of Bose Einstein Condensates using Gaussian Processes
Jupyter Notebook
3
star
31

MachineLearning-101

Introduction to Machine Learning
Shell
3
star
32

TrackMe

Indoor multi-object (human) tracking
Jupyter Notebook
3
star
33

deconstructing-pymc3

Deconstructing PyMC3 source code and reconstructing it incrementally.
Python
2
star
34

frhp-wsn

Frequency Hopping in Wireless Sensor Networks using FTSP - Tested on MicaZ and TelosB platforms
Java
2
star
35

Bayesian-Data-Analysis

Bayesian Data Analysis with PyMC3
Jupyter Notebook
2
star
36

NeuralRC

Neural Reading Comprehension
HTML
2
star
37

everynoise.com_scraper

Scrape mp3 clips from everynoise.com
Python
2
star
38

sfd2017

Creative Coding and Data Visualization for Software Freedom Day 2017
JavaScript
2
star
39

thea

Deep Learning in Robotics
Jupyter Notebook
2
star
40

nodebox-art

My NodeBox Sketches
Python
2
star
41

frequency-hopping-wsn

Implementation of Frequency Hopping in WSN - Time Synchronization done using TPSN
nesC
2
star
42

PracticalBayes

Probabilistic programming, Bayesian Thinking, Bayesian Data Analysis and Applications
Jupyter Notebook
2
star
43

adhoc-on-android

Automatically exported from code.google.com/p/adhoc-on-android
Java
1
star
44

tfp_helper

Helper Library for prototyping with Tensorflow Probability
Python
1
star
45

SMIL4Inkscape

an inkscape extension for declarative animation using SMIL
Python
1
star
46

myshkin

A Telegram Chat-bot @Nikila_bot who offers you valuable advise
JavaScript
1
star
47

keras

a scaffold for using keras to build awesome deep models :D
Jupyter Notebook
1
star
48

rl-toys

Toys examples for Reinforcement Learning
Jupyter Notebook
1
star
49

genai-portfolio-optimization

Portfolio Optimization using Generative AI
1
star
50

pandas

scaffold for learning pandas...
Jupyter Notebook
1
star
51

vivisecto

Yet Another Visualizer for the infamous Castalia
C++
1
star
52

pi-mote

A Mobile Node with Raspberry Pi as brain, a TelosB module for node to node wireless communication and a WiFi module for multimedia communication and file transfer.
C
1
star
53

twitter-scraper

Scrape tweets from twitter for Sentiment Analysis
Python
1
star