The following issues were found

test/jit/_imported_class_test/very/very/nested.py
6 issues
Unable to import 'torch'
Error

Line: 1 Column: 1

              import torch
# This file contains definitions of script classes.
# They are used by test_jit.py to test ScriptClass imports


@torch.jit.script  # noqa: B903
class FooUniqueName(object):  # noqa: B903
    def __init__(self, y):
        self.y = y

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import torch
# This file contains definitions of script classes.
# They are used by test_jit.py to test ScriptClass imports


@torch.jit.script  # noqa: B903
class FooUniqueName(object):  # noqa: B903
    def __init__(self, y):
        self.y = y

            

Reported by Pylint.

Too few public methods (0/2)
Error

Line: 7 Column: 1

              

@torch.jit.script  # noqa: B903
class FooUniqueName(object):  # noqa: B903
    def __init__(self, y):
        self.y = y

            

Reported by Pylint.

Class 'FooUniqueName' inherits from object, can be safely removed from bases in python3
Error

Line: 7 Column: 1

              

@torch.jit.script  # noqa: B903
class FooUniqueName(object):  # noqa: B903
    def __init__(self, y):
        self.y = y

            

Reported by Pylint.

Missing class docstring
Error

Line: 7 Column: 1

              

@torch.jit.script  # noqa: B903
class FooUniqueName(object):  # noqa: B903
    def __init__(self, y):
        self.y = y

            

Reported by Pylint.

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

Line: 9 Column: 9

              @torch.jit.script  # noqa: B903
class FooUniqueName(object):  # noqa: B903
    def __init__(self, y):
        self.y = y

            

Reported by Pylint.

caffe2/quantization/server/activation_distribution_observer.cc
6 issues
Returning pointer to local variable 'data_temp' that will be invalid when returning.
Error

Line: 78 CWE codes: 562

                } else {
    return nullptr;
  }
  return data;
}

template <>
void FindMinMax<float>(const float* data, float* min, float* max, int len) {
  fbgemm::FindMinMax(data, min, max, len);

            

Reported by Cppcheck.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 228 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  struct tm timeinfo;
    localtime_r(&rawtime, &timeinfo);
    // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,cppcoreguidelines-avoid-magic-numbers,modernize-avoid-c-arrays)
    char buffer[128] = {};
    strftime(buffer, sizeof(buffer), "%Y-%m-%d-%H-%M-%S", &timeinfo);
    // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,cppcoreguidelines-avoid-magic-numbers,modernize-avoid-c-arrays)
    char buffer2[256] = {};
    snprintf(buffer2, sizeof(buffer2), "global_%s.minmax", buffer);


            

Reported by FlawFinder.

char - Statically-sized arrays can be improperly restricted, leading to potential overflows or other issues
Security

Line: 231 Column: 5 CWE codes: 119 120
Suggestion: Perform bounds checking, use functions that limit length, or ensure that the size is larger than the maximum possible length

                  char buffer[128] = {};
    strftime(buffer, sizeof(buffer), "%Y-%m-%d-%H-%M-%S", &timeinfo);
    // NOLINTNEXTLINE(cppcoreguidelines-avoid-c-arrays,cppcoreguidelines-avoid-magic-numbers,modernize-avoid-c-arrays)
    char buffer2[256] = {};
    snprintf(buffer2, sizeof(buffer2), "global_%s.minmax", buffer);

    f.open(buffer2);
    int op_index = 0;
    // NOLINTNEXTLINE(performance-for-range-copy)

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 234 Column: 7 CWE codes: 362

                  char buffer2[256] = {};
    snprintf(buffer2, sizeof(buffer2), "global_%s.minmax", buffer);

    f.open(buffer2);
    int op_index = 0;
    // NOLINTNEXTLINE(performance-for-range-copy)
    for (auto key_value : min_max_map_) {
      ostringstream ost;
      assert(key_value.second.first <= key_value.second.second);

            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 718 Column: 10 CWE codes: 362

                // Optionally dump quantization params to file
  ofstream fout;
  if (!qparams_output_file_name.empty()) {
    fout.open(qparams_output_file_name);
    if (!fout) {
      LOG(WARNING) << this << ": can't open " << qparams_output_file_name;
    }
  }


            

Reported by FlawFinder.

open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 818 Column: 10 CWE codes: 362

                // Optionally dump quantization params to file
  ofstream fout;
  if (!qparams_output_file_name.empty()) {
    fout.open(qparams_output_file_name);
    if (!fout) {
      LOG(WARNING) << this << ": can't open " << qparams_output_file_name;
    }
  }


            

Reported by FlawFinder.

caffe2/python/operator_test/stats_ops_test.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              




from caffe2.python import core, workspace
from caffe2.python.test_util import TestCase
import numpy as np


            

Reported by Pylint.

Missing class docstring
Error

Line: 11 Column: 1

              import numpy as np


class TestCounterOps(TestCase):

    def test_stats_ops(self):
        # The global StatRegistry isn't reset when the workspace is reset,
        #   so there may be existing stats from a previous test
        workspace.RunOperatorOnce(core.CreateOperator(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 13 Column: 5

              
class TestCounterOps(TestCase):

    def test_stats_ops(self):
        # The global StatRegistry isn't reset when the workspace is reset,
        #   so there may be existing stats from a previous test
        workspace.RunOperatorOnce(core.CreateOperator(
            'StatRegistryExport', [], ['prev_k', 'prev_v', 'prev_ts']))
        previous_keys = workspace.FetchBlob('prev_k')

            

Reported by Pylint.

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

Line: 43 Column: 9

                      workspace.RunOperatorOnce(core.CreateOperator(
            'StatRegistryExport', ['reg'], ['k3', 'v3', 't3']))

        k3 = workspace.FetchBlob('k3')
        v3 = workspace.FetchBlob('v3')
        t3 = workspace.FetchBlob('t3')

        self.assertEqual(len(k3) - existing, 2)
        self.assertEqual(len(v3), len(k3))

            

Reported by Pylint.

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

Line: 44 Column: 9

                          'StatRegistryExport', ['reg'], ['k3', 'v3', 't3']))

        k3 = workspace.FetchBlob('k3')
        v3 = workspace.FetchBlob('v3')
        t3 = workspace.FetchBlob('t3')

        self.assertEqual(len(k3) - existing, 2)
        self.assertEqual(len(v3), len(k3))
        self.assertEqual(len(t3), len(k3))

            

Reported by Pylint.

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

Line: 45 Column: 9

              
        k3 = workspace.FetchBlob('k3')
        v3 = workspace.FetchBlob('v3')
        t3 = workspace.FetchBlob('t3')

        self.assertEqual(len(k3) - existing, 2)
        self.assertEqual(len(v3), len(k3))
        self.assertEqual(len(t3), len(k3))
        for key in keys:

            

Reported by Pylint.

caffe2/python/onnx/tests/onnx_backend_test.py
6 issues
Unable to import 'onnx.backend.test'
Error

Line: 12 Column: 1

              import os

import unittest
import onnx.backend.test

import caffe2.python.onnx.backend as c2

from caffe2.python import core
core.SetEnginePref({}, {})

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              # @package onnx
# Module caffe2.python.onnx.tests.onnx_backend_test






import os

            

Reported by Pylint.

Disallow trailing comma tuple
Error

Line: 20 Column: 1

              core.SetEnginePref({}, {})

# This is a pytest magic variable to load extra plugins
pytest_plugins = 'onnx.backend.test.report',

backend_test = onnx.backend.test.BackendTest(c2, __name__)

backend_test.exclude(r'(test_hardsigmoid'  # Does not support Hardsigmoid.
                     '|test_hardmax'  # Does not support Hardmax.

            

Reported by Pylint.

Line too long (101/100)
Error

Line: 46 Column: 1

                                   '|test_maxpool_with_argmax.*'  # MaxPool outputs indices in different format.
                     '|test_maxpool.*dilation.*'  # MaxPool doesn't support dilation yet.
                     '|test_maxpool.*uint8.*'  # MaxPool doesn't support uint8 yet.
                     '|test_convtranspose.*'  # ConvTranspose needs some more complicated translation
                     '|test_mvn.*'  # MeanVarianceNormalization is experimental and not supported.
                     '|test_dynamic_slice.*'  # MeanVarianceNormalization is experimental and not supported.
                     '|test_eyelike.*'  # Needs implementation
                     '|test_maxunpool.*'  # Needs implementation
                     '|test_acosh.*'  # Needs implementation

            

Reported by Pylint.

Line too long (108/100)
Error

Line: 48 Column: 1

                                   '|test_maxpool.*uint8.*'  # MaxPool doesn't support uint8 yet.
                     '|test_convtranspose.*'  # ConvTranspose needs some more complicated translation
                     '|test_mvn.*'  # MeanVarianceNormalization is experimental and not supported.
                     '|test_dynamic_slice.*'  # MeanVarianceNormalization is experimental and not supported.
                     '|test_eyelike.*'  # Needs implementation
                     '|test_maxunpool.*'  # Needs implementation
                     '|test_acosh.*'  # Needs implementation
                     '|test_asinh.*'  # Needs implementation
                     '|test_atanh.*'  # Needs implementation

            

Reported by Pylint.

Line too long (105/100)
Error

Line: 138 Column: 1

                                   '|test_logsoftmax_.*'  # axis attr default value changed from 1 to -1
                     '|test_loop11_.*'  # seg fault issue
                     '|test_loop13_seq_.*'  # no support for sequence inputs for scan input
                     '|test_reduce_sum_.*'  # axes is now an input (not attr), added noop_with_empty_axes
                     '|test_softmax_.*'  # axis attr default value changed from 1 to -1
                     '|test_split_variable_parts_.*'  # axes is now an input (not attr)
                     '|test_squeeze_.*'  # axes is now an input (not attr)
                     '|test_unsqueeze_.*'  # axes is now an input (not attr)
                     '|test_MaxPool1d_stride_padding_dilation_.*'

            

Reported by Pylint.

caffe2/python/onnx/error.py
6 issues
Redefining built-in 'BaseException'
Error

Line: 7 Column: 1

              


class BaseException(Exception): pass
class Unsupported(BaseException): pass

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              ## @package onnx
# Module caffe2.python.onnx.error




class BaseException(Exception): pass
class Unsupported(BaseException): pass

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 7 Column: 33

              


class BaseException(Exception): pass
class Unsupported(BaseException): pass

            

Reported by Pylint.

Missing class docstring
Error

Line: 7 Column: 1

              


class BaseException(Exception): pass
class Unsupported(BaseException): pass

            

Reported by Pylint.

Missing class docstring
Error

Line: 8 Column: 1

              

class BaseException(Exception): pass
class Unsupported(BaseException): pass

            

Reported by Pylint.

More than one statement on a single line
Error

Line: 8 Column: 35

              

class BaseException(Exception): pass
class Unsupported(BaseException): pass

            

Reported by Pylint.

caffe2/python/operator_test/record_queue_test.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              



from caffe2.python import core, workspace
from caffe2.python.dataset import Dataset
from caffe2.python.schema import (
    Struct, Map, Scalar, from_blob_list, NewRecord, FeedRecord)
from caffe2.python.record_queue import RecordQueue

            

Reported by Pylint.

Missing class docstring
Error

Line: 14 Column: 1

              import numpy as np


class TestRecordQueue(TestCase):
    def test_record_queue(self):
        num_prod = 8
        num_consume = 3
        schema = Struct(
            ('floats', Map(

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 15 Column: 5

              

class TestRecordQueue(TestCase):
    def test_record_queue(self):
        num_prod = 8
        num_consume = 3
        schema = Struct(
            ('floats', Map(
                Scalar(np.int32),

            

Reported by Pylint.

Too many local variables (33/15)
Error

Line: 15 Column: 5

              

class TestRecordQueue(TestCase):
    def test_record_queue(self):
        num_prod = 8
        num_consume = 3
        schema = Struct(
            ('floats', Map(
                Scalar(np.int32),

            

Reported by Pylint.

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

Line: 29 Column: 9

                          [1.1, 2.1, 2.2, 3.1, 3.2, 3.3],  # value
        ]
        contents = from_blob_list(schema, contents_raw)
        ds = Dataset(schema)
        net = core.Net('init')
        ds.init_empty(net)

        content_blobs = NewRecord(net, contents)
        FeedRecord(content_blobs, contents)

            

Reported by Pylint.

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

Line: 50 Column: 17

              
        def process(net, fields):
            new_fields = []
            for f in fields.field_blobs():
                new_f = net.Copy(f)
                new_fields.append(new_f)
            new_fields = from_blob_list(fields, new_fields)
            return new_fields


            

Reported by Pylint.

caffe2/python/operator_test/text_file_reader_test.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              



from caffe2.python import core, workspace
from caffe2.python.text_file_reader import TextFileReader
from caffe2.python.test_util import TestCase
from caffe2.python.schema import Struct, Scalar, FetchRecord
import tempfile

            

Reported by Pylint.

standard import "import tempfile" should be placed before "from caffe2.python import core, workspace"
Error

Line: 9 Column: 1

              from caffe2.python.text_file_reader import TextFileReader
from caffe2.python.test_util import TestCase
from caffe2.python.schema import Struct, Scalar, FetchRecord
import tempfile
import numpy as np


class TestTextFileReader(TestCase):
    def test_text_file_reader(self):

            

Reported by Pylint.

Missing class docstring
Error

Line: 13 Column: 1

              import numpy as np


class TestTextFileReader(TestCase):
    def test_text_file_reader(self):
        schema = Struct(
            ('field1', Scalar(dtype=str)),
            ('field2', Scalar(dtype=str)),
            ('field3', Scalar(dtype=np.float32)))

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 14 Column: 5

              

class TestTextFileReader(TestCase):
    def test_text_file_reader(self):
        schema = Struct(
            ('field1', Scalar(dtype=str)),
            ('field2', Scalar(dtype=str)),
            ('field3', Scalar(dtype=np.float32)))
        num_fields = 3

            

Reported by Pylint.

Too many local variables (17/15)
Error

Line: 14 Column: 5

              

class TestTextFileReader(TestCase):
    def test_text_file_reader(self):
        schema = Struct(
            ('field1', Scalar(dtype=str)),
            ('field2', Scalar(dtype=str)),
            ('field3', Scalar(dtype=np.float32)))
        num_fields = 3

            

Reported by Pylint.

Method could be a function
Error

Line: 14 Column: 5

              

class TestTextFileReader(TestCase):
    def test_text_file_reader(self):
        schema = Struct(
            ('field1', Scalar(dtype=str)),
            ('field2', Scalar(dtype=str)),
            ('field3', Scalar(dtype=np.float32)))
        num_fields = 3

            

Reported by Pylint.

.circleci/cimodel/data/simple/bazel_definitions.py
6 issues
Missing module docstring
Error

Line: 1 Column: 1

              from cimodel.data.simple.util.docker_constants import (
    DOCKER_IMAGE_GCC7,
    DOCKER_REQUIREMENT_GCC7
)


def gen_job_name(phase):
    job_name_parts = [
        "pytorch",

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 7 Column: 1

              )


def gen_job_name(phase):
    job_name_parts = [
        "pytorch",
        "bazel",
        phase,
    ]

            

Reported by Pylint.

Missing class docstring
Error

Line: 17 Column: 1

                  return "_".join(job_name_parts)


class BazelJob:
    def __init__(self, phase, extra_props=None):
        self.phase = phase
        self.extra_props = extra_props or {}

    def gen_tree(self):

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 17 Column: 1

                  return "_".join(job_name_parts)


class BazelJob:
    def __init__(self, phase, extra_props=None):
        self.phase = phase
        self.extra_props = extra_props or {}

    def gen_tree(self):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 22 Column: 5

                      self.phase = phase
        self.extra_props = extra_props or {}

    def gen_tree(self):

        template_parts = [
            "pytorch",
            "linux",
            "bazel",

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 68 Column: 1

              ]


def get_workflow_jobs():
    return [item.gen_tree() for item in WORKFLOW_DATA]

            

Reported by Pylint.

benchmarks/framework_overhead_benchmark/pt_wrapper_module.py
6 issues
Unable to import 'torch'
Error

Line: 1 Column: 1

              import torch

class WrapperModule(object):
    """ Wraps the instance of wrapped_type.
    For graph_mode traces the instance of wrapped_type.
    Randomaly initializes num_params tensors with single float element.
    Args:
        wrapped_type:
            - Object type to be wrapped.

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import torch

class WrapperModule(object):
    """ Wraps the instance of wrapped_type.
    For graph_mode traces the instance of wrapped_type.
    Randomaly initializes num_params tensors with single float element.
    Args:
        wrapped_type:
            - Object type to be wrapped.

            

Reported by Pylint.

Too few public methods (1/2)
Error

Line: 3 Column: 1

              import torch

class WrapperModule(object):
    """ Wraps the instance of wrapped_type.
    For graph_mode traces the instance of wrapped_type.
    Randomaly initializes num_params tensors with single float element.
    Args:
        wrapped_type:
            - Object type to be wrapped.

            

Reported by Pylint.

Class 'WrapperModule' inherits from object, can be safely removed from bases in python3
Error

Line: 3 Column: 1

              import torch

class WrapperModule(object):
    """ Wraps the instance of wrapped_type.
    For graph_mode traces the instance of wrapped_type.
    Randomaly initializes num_params tensors with single float element.
    Args:
        wrapped_type:
            - Object type to be wrapped.

            

Reported by Pylint.

Line too long (132/100)
Error

Line: 35 Column: 1

                              file_name = self.module_name + "_" + pt_fn.__name__ + ".pt"
                torch.jit.save(self.module, file_name)
                print("Generated graph is saved in {}".format(file_name))
        print("Benchmarking module {} with fn {}: Graph mode:{}".format(self.module_name, pt_fn.__name__, module_config.graph_mode))
        if (debug and isinstance(self.module, torch.jit.ScriptModule)):
            print(self.module.graph)
            print(self.module.code)

    def forward(self, niters):

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 40 Column: 5

                          print(self.module.graph)
            print(self.module.code)

    def forward(self, niters):
        with torch.no_grad():
            for _ in range(niters):
                self.module.forward(*self.tensor_inputs)

            

Reported by Pylint.

caffe2/python/convnet_benchmarks_test.py
6 issues
TODO: investigate why this randomly core dump in ROCM CI
Error

Line: 6 Column: 3

              from caffe2.python import test_util, workspace


# TODO: investigate why this randomly core dump in ROCM CI
@unittest.skipIf(not workspace.has_cuda_support, "no cuda gpu")
class TestConvnetBenchmarks(test_util.TestCase):
    def testConvnetBenchmarks(self):
        all_args = [
            '--batch_size 16 --order NCHW --iterations 1 '

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              import unittest
from caffe2.python import convnet_benchmarks as cb
from caffe2.python import test_util, workspace


# TODO: investigate why this randomly core dump in ROCM CI
@unittest.skipIf(not workspace.has_cuda_support, "no cuda gpu")
class TestConvnetBenchmarks(test_util.TestCase):
    def testConvnetBenchmarks(self):

            

Reported by Pylint.

Missing class docstring
Error

Line: 8 Column: 1

              
# TODO: investigate why this randomly core dump in ROCM CI
@unittest.skipIf(not workspace.has_cuda_support, "no cuda gpu")
class TestConvnetBenchmarks(test_util.TestCase):
    def testConvnetBenchmarks(self):
        all_args = [
            '--batch_size 16 --order NCHW --iterations 1 '
            '--warmup_iterations 1',
            '--batch_size 16 --order NCHW --iterations 1 '

            

Reported by Pylint.

Method could be a function
Error

Line: 9 Column: 5

              # TODO: investigate why this randomly core dump in ROCM CI
@unittest.skipIf(not workspace.has_cuda_support, "no cuda gpu")
class TestConvnetBenchmarks(test_util.TestCase):
    def testConvnetBenchmarks(self):
        all_args = [
            '--batch_size 16 --order NCHW --iterations 1 '
            '--warmup_iterations 1',
            '--batch_size 16 --order NCHW --iterations 1 '
            '--warmup_iterations 1 --forward_only',

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 9 Column: 5

              # TODO: investigate why this randomly core dump in ROCM CI
@unittest.skipIf(not workspace.has_cuda_support, "no cuda gpu")
class TestConvnetBenchmarks(test_util.TestCase):
    def testConvnetBenchmarks(self):
        all_args = [
            '--batch_size 16 --order NCHW --iterations 1 '
            '--warmup_iterations 1',
            '--batch_size 16 --order NCHW --iterations 1 '
            '--warmup_iterations 1 --forward_only',

            

Reported by Pylint.

Method name "testConvnetBenchmarks" doesn't conform to snake_case naming style
Error

Line: 9 Column: 5

              # TODO: investigate why this randomly core dump in ROCM CI
@unittest.skipIf(not workspace.has_cuda_support, "no cuda gpu")
class TestConvnetBenchmarks(test_util.TestCase):
    def testConvnetBenchmarks(self):
        all_args = [
            '--batch_size 16 --order NCHW --iterations 1 '
            '--warmup_iterations 1',
            '--batch_size 16 --order NCHW --iterations 1 '
            '--warmup_iterations 1 --forward_only',

            

Reported by Pylint.