PyTea: PyTorch Tensor shape error analyzer

Overview

PyTea: PyTorch Tensor Shape Error Analyzer

paper project page

Requirements

  • node.js >= 12.x
  • python >= 3.8
    • z3-solver >= 4.8

How to install and use

# install node.js
sudo apt-get install nodejs

# install python z3-solver
pip install z3-solver

# download pytea
wget https://github.com/ropas/pytea/releases/download/v0.1.0/pytea.zip
unzip pytea.zip

# run pytea
python bin/pytea.py path/to/source.py

# run example file
python bin/pytea.py packages/pytea/pytest/basics/scratch.py

How to build

# install dependencies
npm run install:all
pip install z3-solver

# build
npm run build

Documentations

Brief explanation of the analysis result

PyTea is composed of two analyzers.

  • Online analysis: node.js (TypeScript / JavaScript)
    • Find numeric range-based shape mismatch and misuse of API argument. If PyTea has found any error while analyzing the code, it will stop at that position and inform the errors and violated constraints to the user.
  • Offline analysis: Z3 / Python
    • The generated constraints are passed to Z3Py. Z3 will solve the constraint sets of each path and print the first violated constraint (if it exists).

The result of the Online analyzer is divided into three classes:

  • potential success path: the analyzer does not found shape mismatch until now, but the final constraint set can be violated if Z3 analyzes it on closer inspection.
  • potential unreachable path: the analyzer found a shape mismatch or API misuses, but there remain path constraints. In short, path constraint is an unresolved branch condition; that means the stopped path might be unreachable if remaining path constraints have a contradiction. Those cases will be distinguished from Offline analysis.
  • immediate failed path: the analyzer has found an error, stops its analysis immediately.

CAVEAT: If the code contains PyTorch or other third-party APIs that we have not implemented, it will raise false alarms. Nevertheless, we also record each unimplemented API call. See LOGS section from the result and search which unimplemented API call is performed.

The final result of the Offline analysis is divided into several cases.

  • Valid path: SMT solver has not found any error. Every constraint will always be fulfilled.
  • Invalid path: SMT solver found a condition that can violate some constraints. Notice that this does not mean the code will always crash, but it found an extreme case that crashes some executions.
  • Undecidable path: SMT solver has met unsolvable constraints, then timeouts. Some non-linear formulae can be classified into this case.
  • Unreachable path: Hard and Path constraints contain contradicting constraints; this path will not be realized from the beginning.

Result examples

  • Error found by Online analysis

test1

  • Error found by Offline analysis

test2

License

MIT License

This project is based on Pyright, also MIT License

Comments
  • LSTM/GRU input_size tensor shape errors

    LSTM/GRU input_size tensor shape errors

    Hi, I have met a problem while detecting LSTM tensor shape errors. The testing file below is runnable and pytea returns correctly.

    import torch
    import torch.nn as nn
    import torch.nn.functional as F
    
    
    class Model(nn.Module):
    
        def __init__(self):
            super().__init__()
            self.cnn = nn.Conv2d(3, 1, 3, 1, 1)
            self.rnn = nn.LSTM(32, 64, 1, batch_first=True)
            self.pool = nn.MaxPool2d(2, 2)
            self.fc = nn.Linear(64, 16)
    
        def forward(self, x):
            x = self.pool(F.relu(self.cnn(x)))
            x = x.view(-1, 32, 32)
            x, _ = self.rnn(x)
            x = x[:, -1, :].squeeze(1)
            x = F.relu(self.fc(x))
            x = F.softmax(x, dim=-1)
            return x
    
    
    if __name__ == "__main__":
        net = Model()
        x = torch.randn(2, 3, 64, 64)
        y = net(x)
        target = torch.argmax(torch.randn(2, 16), dim=-1)
        loss = F.cross_entropy(y, target.long())
        loss.backward()
        print(y.size())
    

    However, If I change self.rnn = nn.LSTM(32, 64, 1, batch_first=True) into self.rnn = nn.LSTM(64, 64, 1, batch_first=True), torch will report a RuntimeError: Expected 64, got 32. pytea didn't return any CONSTRAINTS information, as it supposed to.

    Then I tried to more LSTM input_size shape errors, all failed. Same situation with GRU. I think it is a bug, because I can detect Conv2d, Linear error successfully.

    opened by MCplayerFromPRC 4
  • Inconsistent with document description

    Inconsistent with document description

    Hello, I have encountered the following problems:

    First question: The content of my source file is:

       import torch
       import torch.nn as nn
    
      class Net(nn.Module):
          def __init__(self):
              super(Net, self).__init__()
              self.layers = nn.Sequential(
                  nn.Linear(28 * 28, 120),
                  nn.ReLU(),
                  nn.Linear(80, 10))
      
          def a(self):
              pass
    
        if __name__ == "__main__":
            n = Net()
    

    But when I execute the command, I get the following results:

    image

    There should be a problem with defining shape in this model.

    Second question: I used it https://github.com/pytorch/examples/blob/master/mnist/main.py , but the command is stuck and no result is returned. As follows:

    image
    opened by dejavu6 2
  • Ternary expression (A if B else C) bug report

    Ternary expression (A if B else C) bug report

    아래와 같은 코드 실행에서 문제가 발생한다는 것을 깨달았습니다.

    x = 0 if 0 <= 1 else 1
    
    # runtime output
    REDUCED HEAP: (size: 250)
      x => 1
    

    파이썬의 삼항연산자가 x = (((0 <= 1) and 0) or 1)로 파싱됩니다. Logical statement가 True, true-value가 0일 때 발생하는 오류인 것으로 보입니다.

    당장 벤치마크 코드에서 나타나는 문제는 아닙니다. Pylib builtin 구현에서 발생한 문제이므로, 다른 방식으로 구현함으로써 일단은 피해갈 수 있을 것 같습니다.

    감사합니다.

    opened by lego0901 1
  • Develop sehoon

    Develop sehoon

    UT-1~6 코드 분석에 필요한 torch API 구현 완료.

    UT-2: epoch을 1로 수정하지 않으면 timeout이됨. UT-3: Python 빌트인 함수 iter, next의 구현은 우선 넘어갔음. UT-6: buggy 코드에서 target이 free variable인데, 이를 처리해 주지 않고 분석을 실행하면 아무것도 출력하지 않는 버그가 있음.

    위 특이사항을 적절히 처리해주고 분석을 실행하면 1~6 모두 buggy 코드는 invalid, fix 코드는 valid 결과를 냄.

    opened by Sehun0819 0
  • path constraint check

    path constraint check

    분석중 한 패스에서 (텐서 모양 오류 등의) 에러를 만나면 해당 패스는 처리됨. 문제는 분기 조건문에 의해 실제로는 진행되지 않는 패스여도 로 처리가 되는 것.

    따라서 분석중 에러를 만났을 때 그 패스가 path constraint를 갖고 있으면 로 처리하여 z3단에 넘기게 수정하였음.

    TODO: z3단에 넘기기 전에 path constraint를 계산하여 Valid면 , Unsat이면 로 처리하기(else )

    opened by Sehun0819 0
  • Bump node-notifier from 8.0.0 to 8.0.1 in /packages/pyright-internal

    Bump node-notifier from 8.0.0 to 8.0.1 in /packages/pyright-internal

    Bumps node-notifier from 8.0.0 to 8.0.1.

    Changelog

    Sourced from node-notifier's changelog.

    v8.0.1

    • fixes possible injection issue for notify-send
    Commits

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 0
Releases(v0.1.0)
Owner
ROPAS Lab.
ROPAS Lab. @ Seoul National University
ROPAS Lab.
[WWW 2022] Zero-Shot Stance Detection via Contrastive Learning

PT-HCL for Zero-Shot Stance Detection The code of this repository is constantly being updated... Please look forward to it! Introduction This reposito

Akuchi 12 Dec 21, 2022
6D Grasping Policy for Point Clouds

GA-DDPG [website, paper] Installation git clone https://github.com/liruiw/GA-DDPG.git --recursive Setup: Ubuntu 16.04 or above, CUDA 10.0 or above, py

Lirui Wang 48 Dec 21, 2022
[ICLR 2022] DAB-DETR: Dynamic Anchor Boxes are Better Queries for DETR

DAB-DETR This is the official pytorch implementation of our ICLR 2022 paper DAB-DETR. Authors: Shilong Liu, Feng Li, Hao Zhang, Xiao Yang, Xianbiao Qi

336 Dec 25, 2022
Hierarchical Cross-modal Talking Face Generation with Dynamic Pixel-wise Loss (ATVGnet)

Hierarchical Cross-modal Talking Face Generation with Dynamic Pixel-wise Loss (ATVGnet) By Lele Chen , Ross K Maddox, Zhiyao Duan, Chenliang Xu. Unive

Lele Chen 218 Dec 27, 2022
Spatial Temporal Graph Convolutional Networks (ST-GCN) for Skeleton-Based Action Recognition in PyTorch

Reminder ST-GCN has transferred to MMSkeleton, and keep on developing as an flexible open source toolbox for skeleton-based human understanding. You a

sijie yan 1.1k Dec 25, 2022
[NeurIPS 2021]: Are Transformers More Robust Than CNNs? (Pytorch implementation & checkpoints)

Are Transformers More Robust Than CNNs? Pytorch implementation for NeurIPS 2021 Paper: Are Transformers More Robust Than CNNs? Our implementation is b

Yutong Bai 145 Dec 01, 2022
A Protein-RNA Interface Predictor Based on Semantics of Sequences

PRIP PRIP:A Protein-RNA Interface Predictor Based on Semantics of Sequences installation gensim==3.8.3 matplotlib==3.1.3 xgboost==1.3.3 prettytable==2

李优 0 Mar 25, 2022
A code repository associated with the paper A Benchmark for Rough Sketch Cleanup by Chuan Yan, David Vanderhaeghe, and Yotam Gingold from SIGGRAPH Asia 2020.

A Benchmark for Rough Sketch Cleanup This is the code repository associated with the paper A Benchmark for Rough Sketch Cleanup by Chuan Yan, David Va

33 Dec 18, 2022
Pytorch implementation of Rosca, Mihaela, et al. "Variational Approaches for Auto-Encoding Generative Adversarial Networks."

alpha-GAN Unofficial pytorch implementation of Rosca, Mihaela, et al. "Variational Approaches for Auto-Encoding Generative Adversarial Networks." arXi

Victor Shepardson 78 Dec 08, 2022
Fast, Attemptable Route Planner for Navigation in Known and Unknown Environments

FAR Planner uses a dynamically updated visibility graph for fast replanning. The planner models the environment with polygons and builds a global visi

Fan Yang 346 Dec 30, 2022
Predicting a person's gender based on their weight and height

Logistic Regression Advanced Case Study Gender Classification: Predicting a person's gender based on their weight and height 1. Introduction We turn o

1 Feb 01, 2022
This is the source code for our ICLR2021 paper: Adaptive Universal Generalized PageRank Graph Neural Network.

GPRGNN This is the source code for our ICLR2021 paper: Adaptive Universal Generalized PageRank Graph Neural Network. Hidden state feature extraction i

Jianhao 92 Jan 03, 2023
CurriculumNet: Weakly Supervised Learning from Large-Scale Web Images

CurriculumNet Introduction This repo contains related code and models from the ECCV 2018 CurriculumNet paper. CurriculumNet is a new training strategy

156 Jul 04, 2022
Implementation of the master's thesis "Temporal copying and local hallucination for video inpainting".

Temporal copying and local hallucination for video inpainting This repository contains the implementation of my master's thesis "Temporal copying and

David Álvarez de la Torre 1 Dec 02, 2022
Can we learn gradients by Hamiltonian Neural Networks?

Can we learn gradients by Hamiltonian Neural Networks? This project was carried out as part of the Optimization for Machine Learning course (CS-439) a

2 Aug 22, 2022
An image base contains 490 images for learning (400 cars and 90 boats), and another 21 images for testingAn image base contains 490 images for learning (400 cars and 90 boats), and another 21 images for testing

SVM Données Une base d’images contient 490 images pour l’apprentissage (400 voitures et 90 bateaux), et encore 21 images pour fait des tests. Prétrait

Achraf Rahouti 3 Nov 30, 2021
Ensembling Off-the-shelf Models for GAN Training

Data-Efficient GANs with DiffAugment project | paper | datasets | video | slides Generated using only 100 images of Obama, grumpy cats, pandas, the Br

MIT HAN Lab 1.2k Dec 26, 2022
A generator of point clouds dataset for PyPipes.

CloudPipesGenerator Documentation | Colab Notebooks | Video Tutorials | Master Degree website A generator of point clouds dataset for PyPipes. TODO Us

1 Jan 13, 2022
Measuring if attention is explanation with ROAR

NLP ROAR Interpretability Official code for: Evaluating the Faithfulness of Importance Measures in NLP by Recursively Masking Allegedly Important Toke

Andreas Madsen 19 Nov 13, 2022
A library for hidden semi-Markov models with explicit durations

hsmmlearn hsmmlearn is a library for unsupervised learning of hidden semi-Markov models with explicit durations. It is a port of the hsmm package for

Joris Vankerschaver 69 Dec 20, 2022