How to load large image data without memory issue

haryngod: <p>I am using libtorch.</p>
<p>I tried to train classification with my own image data.<br>
I concern if I load plenty of images, it must cause a memory issue.</p>
<p>This is my custom dataloader.</p>
<pre><code class="lang-cpp">class ClassificationDataset : public torch::data::Dataset&lt;CustomDataset&gt; {
private:
	std::vector&lt;torch::Tensor&gt; images, labels;
	vector&lt;string&gt; image_list;
	int num_classes;

public:
	ClassificationDataset(std::string path, int num_cls) {
		vector&lt;torch::Tensor&gt; label_t = vector&lt;torch::Tensor&gt;(num_cls);
		for (int i = 0; i &lt; num_cls; i++)
		{
			auto image_path = path + "\\" + to_string(i) + "\\";
			auto images = get_files_inDirectory(image_path, "*.jpg");
			for(auto img : images)
			{
				image_list.push_back(image_path + "\\" + img);
				auto label = torch::tensor(i);
				labels.push_back(label);
			}
		}
		images = process_images(image_list);
		
		num_classes = num_cls;
	};

	torch::data::Example&lt;torch::Tensor, torch::Tensor&gt; get(size_t index) override {
		torch::Tensor sample_img = images.at(index);
		torch::Tensor sample_label = labels.at(index);
		torch::data::Example&lt;torch::Tensor, torch::Tensor&gt; value{ sample_img, sample_label };
		return value;
	};

	torch::optional&lt;size_t&gt; size() const override {
		return labels.size();
	};

	std::vector&lt;torch::Tensor&gt; process_images(std::vector&lt;std::string&gt; list_images)
	{
		std::vector&lt;torch::Tensor&gt; tensor_images;
		for (auto image : list_images)
		{
			cv::Mat img = cv::imread(image);
			cv::resize(img, img, cv::Size(224, 224));

			torch::Tensor tensor_image = torch::from_blob(img.data, { img.rows, img.cols,3 }, at::kByte);
			tensor_image = tensor_image.toType(at::kFloat);
			tensor_image = tensor_image.div_(255);
			tensor_image = tensor_image.permute({ 2, 0, 1 });
			
			tensor_images.push_back(tensor_image);
		}

		return tensor_images;
	}
</code></pre>
<p>Then I use this dataloader.</p>
<pre><code class="lang-cpp">        auto dataset_train = ClassificationDataset("D:\\train", num_classes).map(torch::data::transforms::Stack&lt;&gt;());
		auto data_loader_train = torch::data::make_data_loader(std::move(dataset_train), torch::data::DataLoaderOptions().batch_size(5).workers(4));

		auto dataset_val = ClassificationDataset("D:\\val", num_classes).map(torch::data::transforms::Stack&lt;&gt;());
		auto data_loader_val = torch::data::make_data_loader(std::move(dataset_val), torch::data::DataLoaderOptions().batch_size(2).workers(4));
</code></pre>
<p>If I use my code with 10000 images of train data, does it makes memory issue? right?<br>
If it does, how can I fix it?</p>

Matej_Kompanek: <p>Can’t you just load the image into memory only when ‘get’ is called (instead of loading all of them in constructor) ?<br>
Something like this → </p>
<pre><code class="lang-auto">torch::data::Example&lt;torch::Tensor, torch::Tensor&gt; get(size_t index) override {
		torch::Tensor sample_img = process_images({ image_list[index] })[0];
		torch::Tensor sample_label = labels.at(index);
		torch::data::Example&lt;torch::Tensor, torch::Tensor&gt; value{ sample_img, sample_label };
		return value;
	};
</code></pre>

haryngod: <p>Thanks for your reply!</p>
<p>I tried to load an image at get time.<br>
But the exception occurred.<br>
Debugger pointed at dataloader/base.h file line.</p>
<pre><code class="lang-cpp"> optional&lt;BatchType&gt; next() {
    if (options_.workers &gt; 0) {
      while (optional&lt;Result&gt; result = this-&gt;pop_result()) {
        if (result-&gt;exception) {
          **throw WorkerException(result-&gt;exception);**
        } else if (result-&gt;batch) {
          prefetch(1);
          return std::move(result-&gt;batch);
        }
      }
    } else if (auto batch_request = get_batch_request()) {
      return this-&gt;main_thread_dataset_-&gt;get_batch(std::move(*batch_request));
    }
    return nullopt;
  }
</code></pre>
<p>I am stucked …</p>

Matej_Kompanek: <p>I tried following code, I simplified it a bit, seems to work fine, can you try ?</p>
<pre><code class="lang-auto">class ClassificationDataset : public torch::data::Dataset&lt;ClassificationDataset&gt;
{
private:
	std::vector&lt;std::tuple&lt;std::string, int&gt;&gt; m_data;

	torch::Tensor LoadImageToTensor(const std::string&amp; path)
	{
		cv::Mat img = cv::imread(path);
		cv::resize(img, img, cv::Size(224, 224));

		torch::Tensor tensor_image = torch::from_blob(img.data, { img.rows, img.cols, 3 }, at::kByte);
		tensor_image = tensor_image.toType(at::kFloat);
		tensor_image = tensor_image.div_(255);
		tensor_image = tensor_image.permute({ 2, 0, 1 });

		return tensor_image;
	}

public:
	ClassificationDataset(const std::string&amp; path) 
	{
		for (const auto&amp; dir : std::filesystem::directory_iterator(path))
		{
			int label = std::atoi(dir.path().stem().string().c_str());

			for (const auto&amp; file : std::filesystem::directory_iterator(dir))
			{
				m_data.push_back({ file.path().string(), label });
			}
		}
	};

	torch::data::Example&lt;torch::Tensor, torch::Tensor&gt; get(size_t index) override 
	{
		auto [path, label] = m_data[index];

		torch::Tensor sample_img = LoadImageToTensor(path);
		torch::Tensor sample_label = torch::tensor(label);

		return { sample_img, sample_label };
	};

	torch::optional&lt;size_t&gt; size() const override 
	{
		return m_data.size();
	};
};

void main(int argc, char** argv)
{
	try
	{
		auto dataset_train = ClassificationDataset("D:\\train").map(torch::data::transforms::Stack&lt;&gt;());
		auto data_loader_train = torch::data::make_data_loader(std::move(dataset_train), torch::data::DataLoaderOptions().batch_size(5).workers(4));

		auto dataset_val = ClassificationDataset("D:\\val").map(torch::data::transforms::Stack&lt;&gt;());
		auto data_loader_val = torch::data::make_data_loader(std::move(dataset_val), torch::data::DataLoaderOptions().batch_size(2).workers(4));

		for (auto&amp; batch : *data_loader_train)
		{
			auto data = batch.data;
			auto labels = batch.target;

			std::cout &lt;&lt; data.sizes() &lt;&lt; std::endl;
			std::cout &lt;&lt; labels.sizes() &lt;&lt; std::endl;
		}

		for (auto&amp; batch : *data_loader_val)
		{
			auto data = batch.data;
			auto labels = batch.target;

			std::cout &lt;&lt; data.sizes() &lt;&lt; std::endl;
			std::cout &lt;&lt; labels.sizes() &lt;&lt; std::endl;
		}
	}
	catch (std::runtime_error&amp; e)
	{
		std::cout &lt;&lt; e.what() &lt;&lt; std::endl;
	}
	catch (const c10::Error&amp; e)
	{
		std::cout &lt;&lt; e.msg() &lt;&lt; std::endl;
	}

	system("PAUSE");
}
</code></pre>

haryngod: <p>I really appreciate your help!<br>
My issue is solved now.</p>
<p>I wonder, in case of this code aim to avoid memory issues with large data.<br>
However, could it make a speed issue compared with loading all data in the constructor?<br>
And I’d like to know whether it reads and processes images over and over at each epoch or not?</p>
<p>I really want to know how to avoid memory issues and get high processing speed.<br>
Do you know the way?</p>

Matej_Kompanek: <blockquote>
<p>whether it reads and processes images over and over …</p>
</blockquote>
<p>yes, there is no way around it unless you can fit all data in your memory</p>
<blockquote>
<p>could it make a speed issue …</p>
</blockquote>
<p>yes, it will be somewhat slower depending on how fast your hard drive is</p>
<blockquote>
<p>Do you know the way?</p>
</blockquote>
<p>Not really, most of us probably deal with datasets that will never fit in memory. You could add optional parameter to your dataset that instructs it to load everything in constructor for situations when you’re sure your RAM can handle all of it (probably measure the time difference beforehand to make sure you’re not wasting time on something that will bring only marginal improvement).</p>