<commit_before>//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/operators/reader/reader_op_registry.h"
#include "paddle/fluid/recordio/scanner.h"

namespace paddle {
namespace operators {
namespace reader {
class RecordIOFileReader : public framework::FileReader {
 public:
  RecordIOFileReader(const std::string& filename,
                     const std::vector<framework::DDim>& shapes)
      : FileReader(shapes),
        scanner_(filename),
        dev_ctx_(*platform::DeviceContextPool::Instance().Get(
            platform::CPUPlace())) {
    LOG(INFO) << "Creating file reader" << filename;
  }

  void ReadNext(std::vector<framework::LoDTensor>* out) override {
    *out = framework::ReadFromRecordIO(scanner_, dev_ctx_);
  }

  bool HasNext() const override { return scanner_.HasNext(); }

  void ReInit() override { scanner_.Reset(); }

 private:
  recordio::Scanner scanner_;
  const platform::DeviceContext& dev_ctx_;
};

class CreateRecordIOReaderOp : public framework::OperatorBase {
 public:
  using framework::OperatorBase::OperatorBase;

 private:
  void RunImpl(const framework::Scope& scope,
               const platform::Place& dev_place) const override {
    const auto& shape_concat = Attr<std::vector<int>>("shape_concat");
    const auto& ranks = Attr<std::vector<int>>("ranks");
    PADDLE_ENFORCE(!shape_concat.empty() && !ranks.empty());
    PADDLE_ENFORCE_EQ(std::accumulate(ranks.begin(), ranks.end(), 0),
                      int(shape_concat.size()),
                      "The accumulate of all ranks should be equal to the "
                      "shape concat's length.");
    std::vector<framework::DDim> shapes = RestoreShapes(shape_concat, ranks);
    std::string filename = Attr<std::string>("filename");

    auto* out = scope.FindVar(Output("Out"))
                    ->template GetMutable<framework::ReaderHolder>();
    out->Reset(new RecordIOFileReader(filename, shapes));<commit_msg>Make recordio file reader thread-safe by default<commit_after>//   Copyright (c) 2018 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "paddle/fluid/operators/reader/reader_op_registry.h"
#include "paddle/fluid/recordio/scanner.h"

namespace paddle {
namespace operators {
namespace reader {
template <bool ThreadSafe>
class RecordIOFileReader : public framework::FileReader {
 public:
  RecordIOFileReader(const std::string& filename,
                     const std::vector<framework::DDim>& shapes)
      : FileReader(shapes),
        scanner_(filename),
        dev_ctx_(*platform::DeviceContextPool::Instance().Get(
            platform::CPUPlace())) {
    if (ThreadSafe) {
      mutex_.reset(new std::mutex());
    }
    LOG(INFO) << "Creating file reader" << filename;
  }

  void ReadNext(std::vector<framework::LoDTensor>* out) override {
    if (ThreadSafe) {
      std::lock_guard<std::mutex> guard(*mutex_);
      *out = framework::ReadFromRecordIO(scanner_, dev_ctx_);
    } else {
      *out = framework::ReadFromRecordIO(scanner_, dev_ctx_);
    }
  }

  bool HasNext() const override { return scanner_.HasNext(); }

  void ReInit() override { scanner_.Reset(); }

 private:
  std::unique_ptr<std::mutex> mutex_;
  recordio::Scanner scanner_;
  const platform::DeviceContext& dev_ctx_;
};

class CreateRecordIOReaderOp : public framework::OperatorBase {
 public:
  using framework::OperatorBase::OperatorBase;

 private:
  void RunImpl(const framework::Scope& scope,
               const platform::Place& dev_place) const override {
    const auto& shape_concat = Attr<std::vector<int>>("shape_concat");
    const auto& ranks = Attr<std::vector<int>>("ranks");
    PADDLE_ENFORCE(!shape_concat.empty() && !ranks.empty());
    PADDLE_ENFORCE_EQ(std::accumulate(ranks.begin(), ranks.end(), 0),
                      int(shape_concat.size()),
                      "The accumulate of all ranks should be equal to the "
                      "shape concat's length.");
    std::vector<framework::DDim> shapes = RestoreShapes(shape_concat, ranks);
    std::string filename = Attr<std::string>("filename");

    auto* out = scope.FindVar(Output("Out"))
                    ->template GetMutable<framework::ReaderHolder>();
    out->Reset(new RecordIOFileReader<true>(filename, shapes));
{'fraction_non_alphanumeric': 0.12363096343048079, 'fraction_numerical': 0.003341377390012994, 'mean_word_length': 3.713910761154856, 'pattern_counts': {'":': 0, '<': 33, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3314774', 'n_tokens_mistral': 1526, 'n_tokens_neox': 1468, 'n_words': 420}