The following issues were found

test/cpp/api/transformer.cpp
3 issues
equal - Function does not check the second iterator for over-read conditions
Security

Line: 1159 Column: 24 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                  torch::Tensor result = model(src, tgt);
    torch::Tensor result_cus = model_cus(src, tgt);
    ASSERT_EQ(result.sizes(), ref_output.sizes());
    ASSERT_TRUE(result.equal(result_cus));
    ASSERT_TRUE(torch::allclose(result, ref_output, 1e-7, 1e-5, /*equal_nan=*/true));

    torch::Tensor src_mask = Transformer::Impl::generate_square_subsequent_mask(src.size(0)).to(tensor_options);
    ref_output = torch::tensor({
      {{2.695875, 0.347114, -0.044355, -0.549541}, {2.696091, 0.347015, -0.044770, -0.548522}},

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 1169 Column: 24 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                  result = model(src, tgt, src_mask);
    result_cus = model_cus(src, tgt, src_mask);
    ASSERT_EQ(result.sizes(), ref_output.sizes());
    ASSERT_TRUE(result.equal(result_cus));
    ASSERT_TRUE(torch::allclose(result, ref_output, 1e-7, 1e-5, /*equal_nan=*/true));

    torch::Tensor tgt_key_padding_mask = torch::zeros({tgt.size(1), tgt.size(0)}, tensor_options) == 1;
    tgt_key_padding_mask[0][0] = 1;
    tgt_key_padding_mask[1][1] = 1;

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 1181 Column: 24 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                  result = model(src, tgt, src_mask, torch::Tensor(), torch::Tensor(), torch::Tensor(), tgt_key_padding_mask);
    result_cus = model_cus(src, tgt, src_mask, torch::Tensor(), torch::Tensor(), torch::Tensor(), tgt_key_padding_mask);
    ASSERT_EQ(result.sizes(), ref_output.sizes());
    ASSERT_TRUE(result.equal(result_cus));
    ASSERT_TRUE(torch::allclose(result, ref_output, 1e-7, 1e-5, /*equal_nan=*/true));
}

TEST_F(TransformerTest, Transformer) {
  transformer_test_helper(/*is_cuda=*/ false, /*use_callable_activation=*/ false);

            

Reported by FlawFinder.

test/cpp/api/support.h
3 issues
equal - Function does not check the second iterator for over-read conditions
Security

Line: 99 Column: 28 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                    if (a.is_floating_point()) {
        // check that NaNs are in the same locations
        auto nan_mask = torch::isnan(a);
        ASSERT_TRUE(torch::equal(nan_mask, torch::isnan(b)));
        diff.index_put_({nan_mask}, 0);
        // inf check if allow_inf=true
        if (allow_inf) {
          auto inf_mask = torch::isinf(a);
          auto inf_sign = inf_mask.sign();

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 105 Column: 30 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                      if (allow_inf) {
          auto inf_mask = torch::isinf(a);
          auto inf_sign = inf_mask.sign();
          ASSERT_TRUE(torch::equal(inf_sign, torch::isinf(b).sign()));
          diff.index_put_({inf_mask}, 0);
        }
      }
      // TODO: implement abs on CharTensor (int8)
      if (diff.is_signed() && diff.scalar_type() != torch::kInt8) {

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 129 Column: 14 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                y = y.type_as(x);
  y = x.is_cuda() ? y.to({torch::kCUDA, x.get_device()}) : y.cpu();
  auto nan_mask = x != x;
  if (torch::equal(nan_mask, y != y)) {
    auto diff = x - y;
    if (diff.is_signed()) {
      diff = diff.abs();
    }
    diff.index_put_({nan_mask}, 0);

            

Reported by FlawFinder.

caffe2/utils/math/transpose.cc
3 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 127 Column: 12 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  if (block_size == 1) {
      Y[Y_index] = X[X_index];
    } else {
      std::memcpy(
          Y + block_size * Y_index,
          X + block_size * X_index,
          block_size * sizeof(TData));
    }
    utils::IncreaseIndexInDims<TIndex>(pivot, Y_dims.data(), index.data());

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 149 Column: 10 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                  return;
  }
  if (utils::IsIdentityPermutation(ndim, axes)) {
    std::memcpy(Y, X, size * sizeof(TData));
    return;
  }
  if (utils::IsBatchTranspose2D(ndim, axes)) {
    const TIndex H = dims[ndim - 2];
    const TIndex W = dims[ndim - 1];

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 180 Column: 12 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                    return;                                                           \
    }                                                                   \
    if (utils::IsIdentityPermutation(ndim, axes)) {                     \
      std::memcpy(Y, X, size * sizeof(TData));                          \
      return;                                                           \
    }                                                                   \
    if (TransposeByHPTT(ndim, dims, axes, X, Y)) {                      \
      return;                                                           \
    }                                                                   \

            

Reported by FlawFinder.

test/fx/named_tup.py
3 issues
Unable to import 'torch'
Error

Line: 3 Column: 1

              from typing import NamedTuple

import torch

class MyNamedTup(NamedTuple):
    i : torch.Tensor
    f : torch.Tensor

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from typing import NamedTuple

import torch

class MyNamedTup(NamedTuple):
    i : torch.Tensor
    f : torch.Tensor

            

Reported by Pylint.

Missing class docstring
Error

Line: 5 Column: 1

              
import torch

class MyNamedTup(NamedTuple):
    i : torch.Tensor
    f : torch.Tensor

            

Reported by Pylint.

caffe2/video/video_decoder.h
3 issues
fopen - 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: 267 Column: 18 CWE codes: 362

                      inputFile_(nullptr),
        inputBuffer_(nullptr),
        inputBufferSize_(0) {
    inputFile_ = fopen(fname.c_str(), "rb");
    if (inputFile_ == nullptr) {
      LOG(ERROR) << "Error opening video file " << fname;
      return;
    }
    ctx_ = avio_alloc_context(

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 370 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                    return AVERROR_EOF;
    }

    memcpy(buf, h->inputBuffer_ + h->offset_, r);
    h->offset_ += r;
    return r;
  }

  static int64_t seekMemory(void* opaque, int64_t offset, int whence) {

            

Reported by FlawFinder.

read - Check buffer boundaries if used in a loop including recursive loops
Security

Line: 305 Column: 7 CWE codes: 120 20

                  }
  }

  int read(unsigned char* buf, int buf_size) {
    if (inputBuffer_) {
      return readMemory(this, buf, buf_size);
    } else if (inputFile_) {
      return readFile(this, buf, buf_size);
    } else {

            

Reported by FlawFinder.

caffe2/python/model_helper_test.py
3 issues
Missing class docstring
Error

Line: 10 Column: 1

              from caffe2.python import brew, model_helper


class ModelHelperTest(unittest.TestCase):
    def test_get_complete_net_type(self):
        model = model_helper.ModelHelper("test_orig")
        brew.conv(
            model,
            "input",

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 11 Column: 5

              

class ModelHelperTest(unittest.TestCase):
    def test_get_complete_net_type(self):
        model = model_helper.ModelHelper("test_orig")
        brew.conv(
            model,
            "input",
            "conv",

            

Reported by Pylint.

Missing function or method docstring
Error

Line: 31 Column: 5

                      self.assertTrue(model2.net.Proto().type, "async_scheduling")
        self.assertTrue(model2.param_init_net.Proto().type, "async_scheduling")

    def test_get_complete_net(self):
        model = model_helper.ModelHelper("test_orig")
        conv = brew.conv(
            model,
            "input",
            "conv",

            

Reported by Pylint.

c10/core/impl/SizesAndStrides.cpp
3 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 18 Column: 5 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      &inlineStorage_[0],
        &tempStorage[0],
        C10_SIZES_AND_STRIDES_MAX_INLINE_SIZE * sizeof(inlineStorage_[0]));
    memcpy(
        &inlineStorage_[C10_SIZES_AND_STRIDES_MAX_INLINE_SIZE],
        &tempStorage[oldSize],
        C10_SIZES_AND_STRIDES_MAX_INLINE_SIZE * sizeof(inlineStorage_[0]));
    // CANNOT USE freeOutOfLineStorage() HERE! outOfLineStorage_
    // HAS BEEN OVERWRITTEN!

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 40 Column: 7 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                    const auto bytesToZero = (newSize > oldSize)
          ? (newSize - oldSize) * sizeof(tempStorage[0])
          : 0;
      memcpy(&tempStorage[0], &inlineStorage_[0], bytesToCopy);
      if (bytesToZero) {
        memset(&tempStorage[oldSize], 0, bytesToZero);
      }
      memcpy(
          &tempStorage[newSize],

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 44 Column: 7 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                    if (bytesToZero) {
        memset(&tempStorage[oldSize], 0, bytesToZero);
      }
      memcpy(
          &tempStorage[newSize],
          &inlineStorage_[C10_SIZES_AND_STRIDES_MAX_INLINE_SIZE],
          bytesToCopy);
      if (bytesToZero) {
        memset(&tempStorage[newSize + oldSize], 0, bytesToZero);

            

Reported by FlawFinder.

benchmarks/distributed/rpc/parameter_server/trainer/ddp_models.py
3 issues
Unable to import 'torch.nn.parallel'
Error

Line: 1 Column: 1

              from torch.nn.parallel import DistributedDataParallel as DDP


def basic_ddp_model(self, rank, model, process_group, hook_state, hook):
    r"""
    A function that creates a ddp_model and hook_state objects.
    The ddp model is is initialized with a single device id and
    the process group. The ddp_model also registers the communication
    hook.

            

Reported by Pylint.

Missing module docstring
Error

Line: 1 Column: 1

              from torch.nn.parallel import DistributedDataParallel as DDP


def basic_ddp_model(self, rank, model, process_group, hook_state, hook):
    r"""
    A function that creates a ddp_model and hook_state objects.
    The ddp model is is initialized with a single device id and
    the process group. The ddp_model also registers the communication
    hook.

            

Reported by Pylint.

Too many arguments (6/5)
Error

Line: 4 Column: 1

              from torch.nn.parallel import DistributedDataParallel as DDP


def basic_ddp_model(self, rank, model, process_group, hook_state, hook):
    r"""
    A function that creates a ddp_model and hook_state objects.
    The ddp model is is initialized with a single device id and
    the process group. The ddp_model also registers the communication
    hook.

            

Reported by Pylint.

caffe2/image/image_input_op.h
3 issues
srand - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 874 Column: 8 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

                  const float brightness,
    const float contrast,
    std::mt19937* randgen) {
  std::srand(unsigned(std::time(0)));
  std::vector<int> jitter_order{0, 1, 2};
  // obtain a time-based seed:
  unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
  std::shuffle(
      jitter_order.begin(),

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 498 Column: 9 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                        datum.height(), datum.width(), (src_c == 3) ? CV_8UC3 : CV_8UC1);

      if (src_c == 1) {
        memcpy(src.ptr<uchar>(0), datum.data().data(), datum.data().size());
      } else {
        // Datum stores things in CHW order, let's do HWC for images to make
        // things more consistent with conventional image storage.
        for (int c = 0; c < 3; ++c) {
          const char* datum_buffer =

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 573 Column: 7 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                        image_proto.dims(0),
          image_proto.dims(1),
          (src_c == 3) ? CV_8UC3 : CV_8UC1);
      memcpy(
          src.ptr<uchar>(0),
          image_proto.byte_data().data(),
          image_proto.byte_data().size());
    } else {
      LOG(FATAL) << "Unknown image data type.";

            

Reported by FlawFinder.

aten/src/ATen/native/cpu/PowKernel.cpp
3 issues
equal - Function does not check the second iterator for over-read conditions
Security

Line: 99 Column: 20 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                if (dtype == ScalarType::Float || dtype == ScalarType::Double ||
      dtype == kBFloat16 || isComplexType(dtype)) {
    // Dispatch to fast specialization for sqrt, rsqrt and reciprocal
    if (exp_scalar.equal(.5)) {
      return sqrt_kernel(iter);
    } else if (exp_scalar.equal(-0.5)) {
      return rsqrt_kernel(iter);
    } else if (exp_scalar.equal(-1.0)) {
      return reciprocal_kernel(iter);

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 101 Column: 27 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                  // Dispatch to fast specialization for sqrt, rsqrt and reciprocal
    if (exp_scalar.equal(.5)) {
      return sqrt_kernel(iter);
    } else if (exp_scalar.equal(-0.5)) {
      return rsqrt_kernel(iter);
    } else if (exp_scalar.equal(-1.0)) {
      return reciprocal_kernel(iter);
    }
  }

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 103 Column: 27 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                    return sqrt_kernel(iter);
    } else if (exp_scalar.equal(-0.5)) {
      return rsqrt_kernel(iter);
    } else if (exp_scalar.equal(-1.0)) {
      return reciprocal_kernel(iter);
    }
  }

  if (dtype == ScalarType::Float || dtype == ScalarType::Double) {

            

Reported by FlawFinder.