The following issues were found

caffe2/python/allcompare_test.py
22 issues
Unable to import 'hypothesis'
Error

Line: 8 Column: 1

              


from hypothesis import given, settings
import hypothesis.strategies as st
from multiprocessing import Process

import numpy as np
import tempfile

            

Reported by Pylint.

Unable to import 'hypothesis.strategies'
Error

Line: 9 Column: 1

              

from hypothesis import given, settings
import hypothesis.strategies as st
from multiprocessing import Process

import numpy as np
import tempfile
import shutil

            

Reported by Pylint.

Module 'numpy.random' has no 'ranf' member; maybe 'rand'?
Error

Line: 68 Column: 21

                      dims = []
        for _ in range(d):
            dims.append(np.random.randint(1, high=n))
        test_data = np.random.ranf(size=tuple(dims)).astype(np.float32)

        with TemporaryDirectory() as tempdir:
            processes = []
            for idx in range(num_procs):
                process = Process(

            

Reported by Pylint.

Attribute 'tmpdir' defined outside __init__
Error

Line: 23 Column: 9

              
class TemporaryDirectory:
    def __enter__(self):
        self.tmpdir = tempfile.mkdtemp()
        return self.tmpdir

    def __exit__(self, type, value, traceback):
        shutil.rmtree(self.tmpdir)


            

Reported by Pylint.

Redefining built-in 'type'
Error

Line: 26 Column: 24

                      self.tmpdir = tempfile.mkdtemp()
        return self.tmpdir

    def __exit__(self, type, value, traceback):
        shutil.rmtree(self.tmpdir)


def allcompare_process(filestore_dir, process_id, data, num_procs):
    from caffe2.python import core, data_parallel_model, workspace, dyndep

            

Reported by Pylint.

Access to a protected member _rendezvous of a client class
Error

Line: 50 Column: 5

                  )

    model = ModelHelper()
    model._rendezvous = rendezvous

    workspace.FeedBlob("test_data", data)

    data_parallel_model._RunComparison(
        model, "test_data", core.DeviceOption(caffe2_pb2.CPU, 0)

            

Reported by Pylint.

Access to a protected member _RunComparison of a client class
Error

Line: 54 Column: 5

              
    workspace.FeedBlob("test_data", data)

    data_parallel_model._RunComparison(
        model, "test_data", core.DeviceOption(caffe2_pb2.CPU, 0)
    )


class TestAllCompare(hu.HypothesisTestCase):

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3






from hypothesis import given, settings
import hypothesis.strategies as st

            

Reported by Pylint.

standard import "from multiprocessing import Process" should be placed before "from hypothesis import given, settings"
Error

Line: 10 Column: 1

              
from hypothesis import given, settings
import hypothesis.strategies as st
from multiprocessing import Process

import numpy as np
import tempfile
import shutil


            

Reported by Pylint.

standard import "import tempfile" should be placed before "from hypothesis import given, settings"
Error

Line: 13 Column: 1

              from multiprocessing import Process

import numpy as np
import tempfile
import shutil

import caffe2.python.hypothesis_test_util as hu

op_engine = 'GLOO'

            

Reported by Pylint.

caffe2/python/mint/app.py
22 issues
Unable to import 'nvd3'
Error

Line: 7 Column: 1

              import flask
import glob
import numpy as np
import nvd3
import os
import sys
# pyre-fixme[21]: Could not find module `tornado.httpserver`.
import tornado.httpserver
# pyre-fixme[21]: Could not find a module corresponding to import `tornado.wsgi`

            

Reported by Pylint.

Unable to import 'tornado.httpserver'
Error

Line: 11 Column: 1

              import os
import sys
# pyre-fixme[21]: Could not find module `tornado.httpserver`.
import tornado.httpserver
# pyre-fixme[21]: Could not find a module corresponding to import `tornado.wsgi`
import tornado.wsgi

__folder__ = os.path.abspath(os.path.dirname(__file__))


            

Reported by Pylint.

Unable to import 'tornado.wsgi'
Error

Line: 13 Column: 1

              # pyre-fixme[21]: Could not find module `tornado.httpserver`.
import tornado.httpserver
# pyre-fixme[21]: Could not find a module corresponding to import `tornado.wsgi`
import tornado.wsgi

__folder__ = os.path.abspath(os.path.dirname(__file__))

app = flask.Flask(
    __name__,

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 43 Column: 12

              def visualize_summary(filename):
    try:
        data = np.loadtxt(filename)
    except Exception as e:
        return 'Cannot load file {}: {}'.format(filename, str(e))
    chart_name = os.path.splitext(os.path.basename(filename))[0]
    chart = nvd3.lineChart(
        name=chart_name + '_summary_chart',
        height=args.chart_height,

            

Reported by Pylint.

Catching too general exception Exception
Error

Line: 70 Column: 12

                      data = np.loadtxt(filename)
        if data.ndim == 1:
            data = data[:, np.newaxis]
    except Exception as e:
        return 'Cannot load file {}: {}'.format(filename, str(e))
    chart_name = os.path.splitext(os.path.basename(filename))[0]
    chart = nvd3.lineChart(
        name=chart_name + '_log_chart',
        height=args.chart_height,

            

Reported by Pylint.

Using the global statement
Error

Line: 180 Column: 5

                      "number means the total points we will sample on the "
        "whole curve. Default 100 points."
    )
    global args
    args = parser.parse_args(argv)
    server = tornado.httpserver.HTTPServer(tornado.wsgi.WSGIContainer(app))
    server.listen(args.port)
    print("Tornado server starting on port {}.".format(args.port))
    tornado.ioloop.IOLoop.instance().start()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              ## @package app
# Module caffe2.python.mint.app
import argparse
import flask
import glob
import numpy as np
import nvd3
import os
import sys

            

Reported by Pylint.

standard import "import glob" should be placed before "import flask"
Error

Line: 5 Column: 1

              # Module caffe2.python.mint.app
import argparse
import flask
import glob
import numpy as np
import nvd3
import os
import sys
# pyre-fixme[21]: Could not find module `tornado.httpserver`.

            

Reported by Pylint.

standard import "import os" should be placed before "import flask"
Error

Line: 8 Column: 1

              import glob
import numpy as np
import nvd3
import os
import sys
# pyre-fixme[21]: Could not find module `tornado.httpserver`.
import tornado.httpserver
# pyre-fixme[21]: Could not find a module corresponding to import `tornado.wsgi`
import tornado.wsgi

            

Reported by Pylint.

standard import "import sys" should be placed before "import flask"
Error

Line: 9 Column: 1

              import numpy as np
import nvd3
import os
import sys
# pyre-fixme[21]: Could not find module `tornado.httpserver`.
import tornado.httpserver
# pyre-fixme[21]: Could not find a module corresponding to import `tornado.wsgi`
import tornado.wsgi


            

Reported by Pylint.

caffe2/python/ideep/pool_op_test.py
22 issues
Unable to import 'hypothesis.strategies'
Error

Line: 7 Column: 1

              

import unittest
import hypothesis.strategies as st
from hypothesis import assume, given, settings
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu

            

Reported by Pylint.

Unable to import 'hypothesis'
Error

Line: 8 Column: 1

              
import unittest
import hypothesis.strategies as st
from hypothesis import assume, given, settings
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.ideep_test_util as mu

            

Reported by Pylint.

Module 'caffe2.python._import_c_extension' has no 'use_mkldnn' member
Error

Line: 15 Column: 22

              import caffe2.python.hypothesis_test_util as hu
import caffe2.python.ideep_test_util as mu

@unittest.skipIf(not workspace.C.use_mkldnn, "No MKLDNN support.")
class PoolTest(hu.HypothesisTestCase):
    @given(stride=st.integers(1, 3),
           pad=st.integers(0, 3),
           kernel=st.integers(3, 5),
           size=st.integers(7, 9),

            

Reported by Pylint.

Unused argument 'gc'
Error

Line: 58 Column: 34

                         **mu.gcs_cpu_ideep)
    def test_int8_pooling(self, stride, pad, kernel, size,
                         input_channels, batch_size,
                         method, gc, dc):
        assume(pad < kernel)
        pool_fp32 = core.CreateOperator(
            method,
            ["X"],
            ["Y"],

            

Reported by Pylint.

Redundant use of assertTrue with constant value False
Error

Line: 144 Column: 13

                          print(Y_out.flatten())
            print(np.max(np.abs(Y_out - Y)))
            print("MSE", MSE)
            self.assertTrue(False)

        workspace.SwitchWorkspace(old_ws_name)




            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              




import unittest
import hypothesis.strategies as st
from hypothesis import assume, given, settings
import numpy as np

            

Reported by Pylint.

Missing class docstring
Error

Line: 16 Column: 1

              import caffe2.python.ideep_test_util as mu

@unittest.skipIf(not workspace.C.use_mkldnn, "No MKLDNN support.")
class PoolTest(hu.HypothesisTestCase):
    @given(stride=st.integers(1, 3),
           pad=st.integers(0, 3),
           kernel=st.integers(3, 5),
           size=st.integers(7, 9),
           input_channels=st.integers(1, 3),

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 26 Column: 5

                         method=st.sampled_from(["MaxPool", "AveragePool"]),
           **mu.gcs)
    @settings(deadline=10000)
    def test_pooling(self, stride, pad, kernel, size,
                         input_channels, batch_size,
                         method, gc, dc):
        assume(pad < kernel)
        op = core.CreateOperator(
            method,

            

Reported by Pylint.

Argument name "dc" doesn't conform to snake_case naming style
Error

Line: 26 Column: 5

                         method=st.sampled_from(["MaxPool", "AveragePool"]),
           **mu.gcs)
    @settings(deadline=10000)
    def test_pooling(self, stride, pad, kernel, size,
                         input_channels, batch_size,
                         method, gc, dc):
        assume(pad < kernel)
        op = core.CreateOperator(
            method,

            

Reported by Pylint.

Argument name "gc" doesn't conform to snake_case naming style
Error

Line: 26 Column: 5

                         method=st.sampled_from(["MaxPool", "AveragePool"]),
           **mu.gcs)
    @settings(deadline=10000)
    def test_pooling(self, stride, pad, kernel, size,
                         input_channels, batch_size,
                         method, gc, dc):
        assume(pad < kernel)
        op = core.CreateOperator(
            method,

            

Reported by Pylint.

caffe2/python/ideep/relu_op_test.py
22 issues
Unable to import 'hypothesis.strategies'
Error

Line: 7 Column: 1

              

import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu

            

Reported by Pylint.

Unable to import 'hypothesis'
Error

Line: 8 Column: 1

              
import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np
from caffe2.proto import caffe2_pb2
from caffe2.python import core, workspace
import caffe2.python.hypothesis_test_util as hu
import caffe2.python.ideep_test_util as mu

            

Reported by Pylint.

Module 'caffe2.python._import_c_extension' has no 'use_mkldnn' member
Error

Line: 15 Column: 22

              import caffe2.python.hypothesis_test_util as hu
import caffe2.python.ideep_test_util as mu

@unittest.skipIf(not workspace.C.use_mkldnn, "No MKLDNN support.")
class ReluTest(hu.HypothesisTestCase):
    @given(X=hu.tensor(),
           inplace=st.booleans(),
           **mu.gcs)
    @settings(deadline=1000)

            

Reported by Pylint.

Unused argument 'gc'
Error

Line: 41 Column: 73

                         inplace=st.booleans(),
           **mu.gcs_cpu_ideep)
    @settings(max_examples=10, deadline=None)
    def test_int8_relu(self, size, input_channels, batch_size, inplace, gc, dc):
        relu_fp32 = core.CreateOperator(
            "Relu",
            ["X"],
            ["Y"] if not inplace else ["X"],
            device_option=dc[0]

            

Reported by Pylint.

Redundant use of assertTrue with constant value False
Error

Line: 124 Column: 13

                          print(Y_out.flatten())
            print(np.max(np.abs(Y_out - Y)))
            print("MSE", MSE)
            self.assertTrue(False)

        workspace.SwitchWorkspace(old_ws_name)

if __name__ == "__main__":
    unittest.main()

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              




import unittest
import hypothesis.strategies as st
from hypothesis import given, settings
import numpy as np

            

Reported by Pylint.

Missing class docstring
Error

Line: 16 Column: 1

              import caffe2.python.ideep_test_util as mu

@unittest.skipIf(not workspace.C.use_mkldnn, "No MKLDNN support.")
class ReluTest(hu.HypothesisTestCase):
    @given(X=hu.tensor(),
           inplace=st.booleans(),
           **mu.gcs)
    @settings(deadline=1000)
    def test_relu(self, X, inplace, gc, dc):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 21 Column: 5

                         inplace=st.booleans(),
           **mu.gcs)
    @settings(deadline=1000)
    def test_relu(self, X, inplace, gc, dc):
        op = core.CreateOperator(
            "Relu",
            ["X"],
            ["Y"] if not inplace else ["X"],
        )

            

Reported by Pylint.

Argument name "dc" doesn't conform to snake_case naming style
Error

Line: 21 Column: 5

                         inplace=st.booleans(),
           **mu.gcs)
    @settings(deadline=1000)
    def test_relu(self, X, inplace, gc, dc):
        op = core.CreateOperator(
            "Relu",
            ["X"],
            ["Y"] if not inplace else ["X"],
        )

            

Reported by Pylint.

Argument name "gc" doesn't conform to snake_case naming style
Error

Line: 21 Column: 5

                         inplace=st.booleans(),
           **mu.gcs)
    @settings(deadline=1000)
    def test_relu(self, X, inplace, gc, dc):
        op = core.CreateOperator(
            "Relu",
            ["X"],
            ["Y"] if not inplace else ["X"],
        )

            

Reported by Pylint.

android/test_app/app/src/main/java/org/pytorch/testapp/CameraActivity.java
22 issues
A high number of imports can indicate a high degree of coupling within an object.
Design

Line: 1

              package org.pytorch.testapp;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.SystemClock;
import android.util.Log;

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 41

                private static final int REQUEST_CODE_CAMERA_PERMISSION = 200;
  private static final String[] PERMISSIONS = {Manifest.permission.CAMERA};

  private long mLastAnalysisResultTime;

  protected HandlerThread mBackgroundThread;
  protected Handler mBackgroundHandler;
  protected Handler mUIHandler;


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 43

              
  private long mLastAnalysisResultTime;

  protected HandlerThread mBackgroundThread;
  protected Handler mBackgroundHandler;
  protected Handler mUIHandler;

  private TextView mTextView;
  private StringBuilder mTextViewStringBuilder = new StringBuilder();

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 44

                private long mLastAnalysisResultTime;

  protected HandlerThread mBackgroundThread;
  protected Handler mBackgroundHandler;
  protected Handler mUIHandler;

  private TextView mTextView;
  private StringBuilder mTextViewStringBuilder = new StringBuilder();


            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 45

              
  protected HandlerThread mBackgroundThread;
  protected Handler mBackgroundHandler;
  protected Handler mUIHandler;

  private TextView mTextView;
  private StringBuilder mTextViewStringBuilder = new StringBuilder();

  @Override

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 47

                protected Handler mBackgroundHandler;
  protected Handler mUIHandler;

  private TextView mTextView;
  private StringBuilder mTextViewStringBuilder = new StringBuilder();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

            

Reported by PMD.

StringBuffers can grow quite a lot, and so may become a source of memory leak (if the owning class has a long life time).
Design

Line: 48

                protected Handler mUIHandler;

  private TextView mTextView;
  private StringBuilder mTextViewStringBuilder = new StringBuilder();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

            

Reported by PMD.

Private field 'mTextViewStringBuilder' could be made final; it is only initialized in the declaration or constructor.
Design

Line: 48

                protected Handler mUIHandler;

  private TextView mTextView;
  private StringBuilder mTextViewStringBuilder = new StringBuilder();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

            

Reported by PMD.

Found non-transient, non-static member. Please mark as transient or provide accessors.
Error

Line: 48

                protected Handler mUIHandler;

  private TextView mTextView;
  private StringBuilder mTextViewStringBuilder = new StringBuilder();

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

            

Reported by PMD.

Assigning an Object to null is a code smell. Consider refactoring.
Error

Line: 88

                  mBackgroundThread.quitSafely();
    try {
      mBackgroundThread.join();
      mBackgroundThread = null;
      mBackgroundHandler = null;
    } catch (InterruptedException e) {
      Log.e(TAG, "Error on stopping background thread", e);
    }
  }

            

Reported by PMD.

android/pytorch_android_torchvision/src/main/java/org/pytorch/torchvision/TensorImageUtils.java
22 issues
All methods are static. Consider using a utility class instead. Alternatively, you could add a private constructor or make the class abstract to silence this warning.
Design

Line: 19

               * Contains utility functions for {@link org.pytorch.Tensor} creation from {@link
 * android.graphics.Bitmap} or {@link android.media.Image} source.
 */
public final class TensorImageUtils {

  public static float[] TORCHVISION_NORM_MEAN_RGB = new float[] {0.485f, 0.456f, 0.406f};
  public static float[] TORCHVISION_NORM_STD_RGB = new float[] {0.229f, 0.224f, 0.225f};

  /**

            

Reported by PMD.

This class has too many methods, consider refactoring it.
Design

Line: 19

               * Contains utility functions for {@link org.pytorch.Tensor} creation from {@link
 * android.graphics.Bitmap} or {@link android.media.Image} source.
 */
public final class TensorImageUtils {

  public static float[] TORCHVISION_NORM_MEAN_RGB = new float[] {0.485f, 0.456f, 0.406f};
  public static float[] TORCHVISION_NORM_STD_RGB = new float[] {0.229f, 0.224f, 0.225f};

  /**

            

Reported by PMD.

Avoid long parameter lists.
Design

Line: 70

                 * @param normStdRGB standard deviation for RGB channels normalization, length must equal 3, RGB
   *     order
   */
  public static void bitmapToFloatBuffer(
      final Bitmap bitmap,
      final int x,
      final int y,
      final int width,
      final int height,

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 297

                  }

    NativePeer.imageYUV420CenterCropToFloatBuffer(
        Y.getBuffer(),
        Y.getRowStride(),
        Y.getPixelStride(),
        U.getBuffer(),
        V.getBuffer(),
        U.getRowStride(),

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 298

              
    NativePeer.imageYUV420CenterCropToFloatBuffer(
        Y.getBuffer(),
        Y.getRowStride(),
        Y.getPixelStride(),
        U.getBuffer(),
        V.getBuffer(),
        U.getRowStride(),
        U.getPixelStride(),

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 299

                  NativePeer.imageYUV420CenterCropToFloatBuffer(
        Y.getBuffer(),
        Y.getRowStride(),
        Y.getPixelStride(),
        U.getBuffer(),
        V.getBuffer(),
        U.getRowStride(),
        U.getPixelStride(),
        image.getWidth(),

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 300

                      Y.getBuffer(),
        Y.getRowStride(),
        Y.getPixelStride(),
        U.getBuffer(),
        V.getBuffer(),
        U.getRowStride(),
        U.getPixelStride(),
        image.getWidth(),
        image.getHeight(),

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 301

                      Y.getRowStride(),
        Y.getPixelStride(),
        U.getBuffer(),
        V.getBuffer(),
        U.getRowStride(),
        U.getPixelStride(),
        image.getWidth(),
        image.getHeight(),
        rotateCWDegrees,

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 302

                      Y.getPixelStride(),
        U.getBuffer(),
        V.getBuffer(),
        U.getRowStride(),
        U.getPixelStride(),
        image.getWidth(),
        image.getHeight(),
        rotateCWDegrees,
        tensorWidth,

            

Reported by PMD.

Potential violation of Law of Demeter (object not created locally)
Design

Line: 303

                      U.getBuffer(),
        V.getBuffer(),
        U.getRowStride(),
        U.getPixelStride(),
        image.getWidth(),
        image.getHeight(),
        rotateCWDegrees,
        tensorWidth,
        tensorHeight,

            

Reported by PMD.

caffe2/python/layers/homotopy_weight.py
22 issues
self.output_schema is not callable
Error

Line: 124 Column: 56

                  def add_ops(self, net):
        alpha, beta = self.update_weight(net)
        # alpha x + beta y
        net.WeightedSum([self.x, alpha, self.y, beta], self.output_schema())

            

Reported by Pylint.

TODO: currently model building does not have access to iter counter or
Error

Line: 48 Column: 3

                      assert len(data) == 2
        self.x = data[0]
        self.y = data[1]
        # TODO: currently model building does not have access to iter counter or
        # learning rate; it's added at optimization time;
        self.use_external_iter = (atomic_iter is not None)
        self.atomic_iter = (
            atomic_iter if self.use_external_iter else self.create_atomic_iter()
        )

            

Reported by Pylint.

Use lazy % formatting in logging functions
Error

Line: 71 Column: 9

                      x = t * (1.0 + np.sqrt(2.0)) / 2.0 - np.sqrt(2.0)
        gamma = (x - 1.0) / float(half_life)
        power = np.log(2.0) / np.log(x)
        logger.info(
            'homotopy_weighting: found lr param: gamma=%g, power=%g' %
            (gamma, power)
        )
        return gamma, power


            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # @package homotopy_weight
# Module caffe2.fb.python.layers.homotopy_weight






from caffe2.python import core, schema

            

Reported by Pylint.

standard import "import logging" should be placed before "from caffe2.python import core, schema"
Error

Line: 12 Column: 1

              from caffe2.python import core, schema
from caffe2.python.layers.layers import ModelLayer
import numpy as np
import logging
logger = logging.getLogger(__name__)
'''
Homotopy Weighting between two weights x, y by doing:
    alpha x + beta y
where alpha is a decreasing scalar parameter ranging from [min, max] (default,

            

Reported by Pylint.

Missing class docstring
Error

Line: 26 Column: 1

              '''


class HomotopyWeight(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        name='homotopy_weight',

            

Reported by Pylint.

Too many instance attributes (10/7)
Error

Line: 26 Column: 1

              '''


class HomotopyWeight(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        name='homotopy_weight',

            

Reported by Pylint.

Too many arguments (9/5)
Error

Line: 27 Column: 5

              

class HomotopyWeight(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        name='homotopy_weight',
        min_weight=0.,

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 39 Column: 9

                      atomic_iter=None,
        **kwargs
    ):
        super(HomotopyWeight,
              self).__init__(model, name, input_record, **kwargs)
        self.output_schema = schema.Scalar(
            np.float32, self.get_next_blob_reference('homotopy_weight')
        )
        data = self.input_record.field_blobs()

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 45
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                          np.float32, self.get_next_blob_reference('homotopy_weight')
        )
        data = self.input_record.field_blobs()
        assert len(data) == 2
        self.x = data[0]
        self.y = data[1]
        # TODO: currently model building does not have access to iter counter or
        # learning rate; it's added at optimization time;
        self.use_external_iter = (atomic_iter is not None)

            

Reported by Bandit.

caffe2/python/layers/batch_lr_loss.py
22 issues
Missing module docstring
Error

Line: 1 Column: 1

              ## @package batch_lr_loss
# Module caffe2.python.layers.batch_lr_loss





from caffe2.python import core, schema
from caffe2.python.layers.layers import (

            

Reported by Pylint.

Too many instance attributes (19/7)
Error

Line: 18 Column: 1

              import numpy as np


class BatchLRLoss(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        name='batch_lr_loss',

            

Reported by Pylint.

Missing class docstring
Error

Line: 18 Column: 1

              import numpy as np


class BatchLRLoss(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        name='batch_lr_loss',

            

Reported by Pylint.

Too many local variables (17/15)
Error

Line: 19 Column: 5

              

class BatchLRLoss(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        name='batch_lr_loss',
        average_loss=True,

            

Reported by Pylint.

Too many arguments (16/5)
Error

Line: 19 Column: 5

              

class BatchLRLoss(ModelLayer):
    def __init__(
        self,
        model,
        input_record,
        name='batch_lr_loss',
        average_loss=True,

            

Reported by Pylint.

Consider using Python 3 style super() without arguments
Error

Line: 38 Column: 9

                      task_gamma_lb=0.1,
        **kwargs
    ):
        super(BatchLRLoss, self).__init__(model, name, input_record, **kwargs)

        self.average_loss = average_loss

        assert (schema.is_schema_subset(
            schema.Struct(

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 42
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

              
        self.average_loss = average_loss

        assert (schema.is_schema_subset(
            schema.Struct(
                ('label', schema.Scalar()),
                ('logit', schema.Scalar())
            ),
            input_record

            

Reported by Bandit.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 51
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      ))

        self.jsd_fuse = False
        assert jsd_weight >= 0 and jsd_weight <= 1
        if jsd_weight > 0 or homotopy_weighting:
            assert 'prediction' in input_record
            self.init_weight(jsd_weight, homotopy_weighting)
            self.jsd_fuse = True
        self.homotopy_weighting = homotopy_weighting

            

Reported by Bandit.

Simplify chained comparison between the operands
Error

Line: 51 Column: 16

                      ))

        self.jsd_fuse = False
        assert jsd_weight >= 0 and jsd_weight <= 1
        if jsd_weight > 0 or homotopy_weighting:
            assert 'prediction' in input_record
            self.init_weight(jsd_weight, homotopy_weighting)
            self.jsd_fuse = True
        self.homotopy_weighting = homotopy_weighting

            

Reported by Pylint.

Use of assert detected. The enclosed code will be removed when compiling to optimised byte code.
Security

Line: 53
Suggestion: https://bandit.readthedocs.io/en/latest/plugins/b101_assert_used.html

                      self.jsd_fuse = False
        assert jsd_weight >= 0 and jsd_weight <= 1
        if jsd_weight > 0 or homotopy_weighting:
            assert 'prediction' in input_record
            self.init_weight(jsd_weight, homotopy_weighting)
            self.jsd_fuse = True
        self.homotopy_weighting = homotopy_weighting

        assert pos_label_target <= 1 and pos_label_target >= 0

            

Reported by Bandit.

benchmarks/tensorexpr/pooling.py
22 issues
Attempted relative import beyond top-level package
Error

Line: 1 Column: 1

              from . import benchmark


class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from . import benchmark


class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N

            

Reported by Pylint.

Missing class docstring
Error

Line: 4 Column: 1

              from . import benchmark


class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N

            

Reported by Pylint.

Argument name "W" doesn't conform to snake_case naming style
Error

Line: 5 Column: 5

              

class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N
        self.C = C

            

Reported by Pylint.

Argument name "N" doesn't conform to snake_case naming style
Error

Line: 5 Column: 5

              

class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N
        self.C = C

            

Reported by Pylint.

Argument name "C" doesn't conform to snake_case naming style
Error

Line: 5 Column: 5

              

class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N
        self.C = C

            

Reported by Pylint.

Argument name "H" doesn't conform to snake_case naming style
Error

Line: 5 Column: 5

              

class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N
        self.C = C

            

Reported by Pylint.

Too many arguments (10/5)
Error

Line: 5 Column: 5

              

class PoolingBench(benchmark.Benchmark):
    def __init__(self, case, mode, device, dtype, kernel_size, N, C, H, W):
        super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N
        self.C = C

            

Reported by Pylint.

Attribute name "N" doesn't conform to snake_case naming style
Error

Line: 9 Column: 9

                      super().__init__(mode, device)
        self.case = case
        self.kernel_size = kernel_size
        self.N = N
        self.C = C
        self.H = H
        self.W = W
        self.data = self.rand(
            [N, C, H, W], device=device, dtype=dtype, requires_grad=self.requires_grad

            

Reported by Pylint.

Attribute name "C" doesn't conform to snake_case naming style
Error

Line: 10 Column: 9

                      self.case = case
        self.kernel_size = kernel_size
        self.N = N
        self.C = C
        self.H = H
        self.W = W
        self.data = self.rand(
            [N, C, H, W], device=device, dtype=dtype, requires_grad=self.requires_grad
        )

            

Reported by Pylint.

benchmarks/distributed/ddp/diff.py
22 issues
Missing module docstring
Error

Line: 1 Column: 1

              #!/usr/bin/env python3
#
# Computes difference between measurements produced by ./benchmark.py.
#

import argparse
import json

import numpy as np

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 12 Column: 1

              import numpy as np


def load(path):
    with open(path, 'r') as f:
        return json.load(f)


def main():

            

Reported by Pylint.

Variable name "f" doesn't conform to snake_case naming style
Error

Line: 13 Column: 29

              

def load(path):
    with open(path, 'r') as f:
        return json.load(f)


def main():
    parser = argparse.ArgumentParser(description='PyTorch distributed benchmark diff')

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 17 Column: 1

                      return json.load(f)


def main():
    parser = argparse.ArgumentParser(description='PyTorch distributed benchmark diff')
    parser.add_argument("file", nargs=2)
    args = parser.parse_args()

    if len(args.file) != 2:

            

Reported by Pylint.

Too many local variables (24/15)
Error

Line: 17 Column: 1

                      return json.load(f)


def main():
    parser = argparse.ArgumentParser(description='PyTorch distributed benchmark diff')
    parser.add_argument("file", nargs=2)
    args = parser.parse_args()

    if len(args.file) != 2:

            

Reported by Pylint.

Variable name "ja" doesn't conform to snake_case naming style
Error

Line: 25 Column: 5

                  if len(args.file) != 2:
        raise RuntimeError("Must specify 2 files to diff")

    ja = load(args.file[0])
    jb = load(args.file[1])

    keys = (set(ja.keys()) | set(jb.keys())) - set(["benchmark_results"])
    print("{:20s} {:>20s}      {:>20s}".format("", "baseline", "test"))
    print("{:20s} {:>20s}      {:>20s}".format("", "-" * 20, "-" * 20))

            

Reported by Pylint.

Variable name "jb" doesn't conform to snake_case naming style
Error

Line: 26 Column: 5

                      raise RuntimeError("Must specify 2 files to diff")

    ja = load(args.file[0])
    jb = load(args.file[1])

    keys = (set(ja.keys()) | set(jb.keys())) - set(["benchmark_results"])
    print("{:20s} {:>20s}      {:>20s}".format("", "baseline", "test"))
    print("{:20s} {:>20s}      {:>20s}".format("", "-" * 20, "-" * 20))
    for key in sorted(keys):

            

Reported by Pylint.

Variable name "va" doesn't conform to snake_case naming style
Error

Line: 32 Column: 9

                  print("{:20s} {:>20s}      {:>20s}".format("", "baseline", "test"))
    print("{:20s} {:>20s}      {:>20s}".format("", "-" * 20, "-" * 20))
    for key in sorted(keys):
        va = str(ja.get(key, "-"))
        vb = str(jb.get(key, "-"))
        print("{:20s} {:>20s}  vs  {:>20s}".format(key + ":", va, vb))
    print("")

    ba = ja["benchmark_results"]

            

Reported by Pylint.

Variable name "vb" doesn't conform to snake_case naming style
Error

Line: 33 Column: 9

                  print("{:20s} {:>20s}      {:>20s}".format("", "-" * 20, "-" * 20))
    for key in sorted(keys):
        va = str(ja.get(key, "-"))
        vb = str(jb.get(key, "-"))
        print("{:20s} {:>20s}  vs  {:>20s}".format(key + ":", va, vb))
    print("")

    ba = ja["benchmark_results"]
    bb = jb["benchmark_results"]

            

Reported by Pylint.

Variable name "ba" doesn't conform to snake_case naming style
Error

Line: 37 Column: 5

                      print("{:20s} {:>20s}  vs  {:>20s}".format(key + ":", va, vb))
    print("")

    ba = ja["benchmark_results"]
    bb = jb["benchmark_results"]
    for ra, rb in zip(ba, bb):
        if ra["model"] != rb["model"]:
            continue
        if ra["batch_size"] != rb["batch_size"]:

            

Reported by Pylint.