Example 3 showed you how to create a simple PyTorch model for linear regression. However, we did so by utilzing torch::nn::Linear. In this example, we want to go a step further and see how to build our own models. If you have used PyTorch with Python you will see that the process is not very different. We will also see how to load a dataset and save a PyTorch model such that we can then load in Python.
Specifically, we will implement a simple logistic regression model. We will use the MNIST dataset. Make sure that you have downloaded the dataset and the arrangement has the following directory structure. It may also be useful to have a look at the source code for the PyTorch MNIST class here: https://github.com/pytorch/pytorch/blob/main/torch/csrc/api/src/data/datasets/mnist.cpp
The driver code for this tutorial is shown below.
#include "bitrl/base/bitrl_config.h"
#ifdef USE_PYTORCH
#include <torch/torch.h>
#include <fstream>
#include <iostream>
#include <memory>
#include <random>
#include <string>
{
namespace fs = std::filesystem;
const std::string
CONFIG =
"config.json";
class LogisticRegressionModelImpl : public torch::nn::Module
{
public:
void test_model(
const std::string &test_path,
uint_t batch_size, torch::Device device);
torch::Device device);
private:
torch::nn::Linear linear_;
};
: linear_(nullptr)
{
linear_ = register_module("linear_", torch::nn::Linear(input_size, output_size));
bias_ = register_parameter("bias_", torch::randn(output_size));
}
torch_tensor_t LogisticRegressionModelImpl::forward(torch_tensor_t input)
{
return torch::sigmoid(linear_(input) + bias_);
}
void LogisticRegressionModelImpl::test_model(const std::string &test_set_path, uint_t batch_size,
torch::Device device)
{
;
this->eval();
torch::NoGradGuard no_grad;
auto test_dataset =
torch::data::datasets::MNIST(test_set_path, torch::data::datasets::MNIST::Mode::kTest)
.map(torch::data::transforms::Normalize<>(0.1307, 0.3081))
.map(torch::data::transforms::Stack<>());
auto num_test_samples = test_dataset.size().value();
BITRL_LOG_INFO <<
"Number of test examples " << num_test_samples << std::endl;
auto test_loader = torch::data::make_data_loader<torch::data::samplers::SequentialSampler>(
std::move(test_dataset), batch_size);
for (const auto &batch : *test_loader)
{
auto data = batch.data.view({
static_cast<long int>(
batch_size), -1}).to(device);
auto target = batch.target.to(device);
auto output = this->forward(data);
auto loss = torch::nn::functional::cross_entropy(output, target);
running_loss += loss.item<
real_t>() * data.size(0);
auto prediction = output.argmax(1);
num_correct += prediction.eq(target).sum().item<int64_t>();
}
auto test_accuracy = static_cast<double>(num_correct) / num_test_samples;
auto test_sample_mean_loss = running_loss / num_test_samples;
<< ", Accuracy: " << test_accuracy;
}
void LogisticRegressionModelImpl::train_model(const std::string &train_set_path, uint_t batch_size,
uint_t n_epochs, real_t lr, torch::Device device)
{
auto train_dataset =
torch::data::datasets::MNIST(train_set_path, torch::data::datasets::MNIST::Mode::kTrain)
.map(torch::data::transforms::Normalize<>(0.1307, 0.3081))
.map(torch::data::transforms::Stack<>());
auto num_train_samples = train_dataset.size().value();
auto train_loader = torch::data::make_data_loader<torch::data::samplers::RandomSampler>(
std::move(train_dataset), batch_size);
auto optimizer =
std::make_unique<torch::optim::SGD>(this->parameters(), torch::optim::SGDOptions{lr});
for (size_t epoch = 0; epoch != n_epochs; ++epoch)
{
auto running_loss = 0.0;
for (auto &batch : *train_loader)
{
auto data = batch.data.view({
static_cast<long int>(
batch_size), -1}).to(device);
auto target = batch.target.to(device);
auto output = this->forward(data);
auto loss = torch::nn::functional::cross_entropy(output, target);
running_loss += loss.template item<real_t>() * data.size(0);
auto prediction = output.argmax(1);
num_correct += prediction.eq(target).sum().template item<int64_t>();
optimizer->zero_grad();
loss.backward();
optimizer->step();
}
auto sample_mean_loss = running_loss / num_train_samples;
auto accuracy =
static_cast<real_t>(num_correct) / num_train_samples;
<< "], Trainset - Loss: " << sample_mean_loss << ", Accuracy: " << accuracy
<< '\n';
}
}
}
{
try
{
json_reader.open();
auto cuda_available = torch::cuda::is_available();
torch::Device device(cuda_available ? torch::kCUDA : torch::kCPU);
if (cuda_available)
{
}
else
{
BITRL_LOG_INFO <<
"CUDA is not available. Training on CPU " << std::endl;
}
auto train_set_data_path = json_reader.template get_value<std::string>("train_data_path");
auto test_set_data_path = json_reader.template get_value<std::string>("test_data_path");
auto seed = json_reader.template get_value<uint_t>("seed");
auto input_size = json_reader.template get_value<uint_t>(
"input_size");
auto num_classes = json_reader.template get_value<uint_t>(
"num_classes");
auto batch_size = json_reader.template get_value<uint_t>(
"batch_size");
auto num_epochs = json_reader.template get_value<uint_t>(
"num_epochs");
auto lr = json_reader.template get_value<real_t>("lr");
torch::manual_seed(seed);
LogisticRegressionModel model(input_size, num_classes);
model->to(device);
model->train_model(train_set_data_path, batch_size, num_epochs, lr, device);
model->test_model(test_set_data_path, batch_size, device);
}
catch (std::exception &e)
{
std::cout << e.what() << std::endl;
}
catch (...)
{
std::cout << "Unknown exception occured" << std::endl;
}
return 0;
}
#else
#include <iostream>
{
std::cout
<< "This example requires PyTorch. Reconfigure bitrl with USE_PYTORCH flag turned ON."
<< std::endl;
return 0;
}
#endif
bitrl's logging: the logger of bitsim, bitsim/utils/logger.h, with bitrl's messages going to the logg...
#define BITRL_LOG_INFO
Definition bitrl_log.h:36
The IterationCounter class.
Definition iteration_counter.h:15
Definition json_file_reader.h:16
LogisticRegressionModelImpl(uint_t input_size, uint_t output_size)
Definition pytorch_custom_model.cpp:54
void test_model(const std::string &test_path, uint_t batch_size, torch::Device device)
Definition pytorch_custom_model.cpp:67
void train_model(const std::string &train_path, uint_t batch_size, uint_t n_epochs, real_t lr, torch::Device device)
Definition pytorch_custom_model.cpp:116
torch_tensor_t forward(torch_tensor_t input)
Definition pytorch_custom_model.cpp:61
int main()
Definition discounted_returns.cpp:19
torch::Tensor torch_tensor_t
torch_tensor_t
Definition bitrl_types.h:95
std::size_t uint_t
uint_t
Definition bitsim_types.h:40
double real_t
real_t
Definition bitsim_types.h:20
const uint_t num_classes
Definition ml_example_1.cpp:43
const uint_t input_size
Definition ml_example_1.cpp:42
const uint_t num_epochs
Definition ml_example_1.cpp:45
const uint_t batch_size
Definition ml_example_1.cpp:44
Definition pytorch_custom_model.cpp:19
TORCH_MODULE(LogisticRegressionModel)
const std::string CONFIG
Definition pytorch_custom_model.cpp:28