Skip to content

Add cuda inference example: #155 - #210

Open
a-vartenkov wants to merge 37 commits into
KasperskyLab:masterfrom
a-vartenkov:feature/#155-add-cuda-inference-example
Open

Add cuda inference example: #155#210
a-vartenkov wants to merge 37 commits into
KasperskyLab:masterfrom
a-vartenkov:feature/#155-add-cuda-inference-example

Conversation

@a-vartenkov

Copy link
Copy Markdown
Collaborator

Adding CUDA inference example. Now CUDA backend works at least with a decent speed.

Comment thread examples/mnist-client/inference.cpp
Comment thread examples/mnist-learn/models/network_functions.h
Comment thread examples/mnist-learn/main.cpp
Comment on lines +64 to +80
if (!model_desc.model_saving_path_.empty())
{
if (!model_desc.inference_only_)
{
save_network(model_desc, network);
}
knp::framework::Network new_network = knp::framework::sonata::load_network(model_desc.model_saving_path_);
if (new_network.populations_count() != network.network_.populations_count()
|| new_network.projections_count() != network.network_.projections_count())
{
std::cout << "Populations " << new_network.populations_count() << " vs. "
<< network.network_.populations_count() << std::endl;
std::cout << "Projections: " << new_network.projections_count() << " vs. "
<< network.network_.projections_count() << std::endl;
}
network.network_ = new_network;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Что это такое?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сохранение и загрузка обученной модели?

*/
std::filesystem::path model_saving_path_;

/// A flag to not do the training.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Может, лучше в тэги?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Только если всю в теги, иначе это по-моему естественное место. А всю в теги это другая задача, по переработке примера.

};


struct ValueIndex

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Несколько комментов бы.

gather_index_neuron_kernel<<<num_blocks, num_threads>>>(index.view(), inputs, buffer);
// in-place prefix sum, for each neuron the value is the number of synapses before this, starts with 0.
thrust::exclusive_scan(thrust::device, buffer, buffer + inputs.size_, buffer);
return CUDAVector<unsigned long long>{buffer, inputs.size_}; // The vector would take care of releasing

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Лучше коммент наверх.



template <typename BaseSynapseType>
void Network::upcast_projections()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю, что в Network этого быть не должно.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А где должны быть функции, которые изменяют большой кусок Network?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Функции должны быть во фреймворке (см., там уже есть то, что работает с Network), а вот методов таких не должно быть.

Comment thread knp/base-framework/impl/network.cpp Outdated
is_converted = true;
return core::AllProjectionsVariant{res};
}
return core::AllProjectionsVariant{proj}; // TODO: Remove unnecessary copying.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Коммент наверх.

Comment thread knp/base-framework/impl/network.cpp

@artiomn artiomn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

См. комменты.

@artiomn artiomn left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Продолжаем...

Comment thread examples/mnist-learn/main.cpp
@artiomn artiomn changed the title Feature/#155 add cuda inference example Add cuda inference example: #155 Aug 7, 2026
Comment on lines +159 to +164
// /**
// * @brief Send a message to the message bus.
// * @param message message to send.
// */
// template <class MessageType>
// __host__ __device__ void send_message(const MessageType &message);

@artiomn artiomn Aug 7, 2026

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Удалить.

for (auto iter = buffer.begin(); iter != buffer.end(); ++iter)
{
LongIndex current_neuron = (*iter).first;
// Filling offsets for skipped neurons: if first three are missing that would be (0, 0, 0, 0, 5...

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Скобку в комменте не закрыл.

Comment on lines +54 to +67
template <class T>
struct CUDAVectorView
{
const T * const data_;
const unsigned long long size_;
};

template <class T>
struct CUDAVectorMutableView
{
T * const data_;
const unsigned long long size_;
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Потому что есть отдельно векторы, отдельно view, и если сюда будет что-то ещё добавляться, тут будет помойка.

{
#if defined(__CUDA_ARCH__)
PRINTF_TRACE("Using has_sender on device\n");
// PRINTF_TRACE("Using has_sender on device\n");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

FAST_ERROR_CHECK же, вроде, был?

size_t tail_length = end() - end_iter;
size_t num_destruct = end() - begin_iter;
#ifdef __CUDA_ARCH__
#ifdef __CUDA_ARCH__ // Device only

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

  1. Вообще-то, у нас есть style guide, и никаких "вопросов читабельности" не должно возникать.
  2. Это и нужно для того, чтобы разбивать функцию и видеть макрос, - лишняя "красота" здесь только мешает.

Comment on lines +47 to +48
// size_t new_heap = 128 * 1024 * 1024; // 128 Mb // TEMP!
// cudaDeviceSetLimit(cudaLimitMallocHeapSize, new_heap);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Тогда удали это.

Comment thread knp/backends/gpu/cuda-backend/impl/backend_impl.cu
Comment thread knp/backends/gpu/cuda-backend/impl/backend_impl.cuh
Comment thread knp/backends/gpu/cuda-backend/impl/backend_impl.cuh


template <typename BaseSynapseType>
void Network::upcast_projections()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Функции должны быть во фреймворке (см., там уже есть то, что работает с Network), а вот методов таких не должно быть.

}
knp::framework::Network new_network = knp::framework::sonata::load_network(model_desc.model_saving_path_);
if (new_network.populations_count() != network.network_.populations_count()
|| new_network.projections_count() != network.network_.projections_count())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Отступ.

@@ -45,20 +45,44 @@ template <typename Neuron>
void run_model(const ModelDescription& model_desc)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Переписать.

Comment on lines 67 to 68
case 0: result = extract_message_by_index<0>(msg_ptr); break;
case 1: result = extract_message_by_index<1>(msg_ptr); break;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Сделать константами.

{
bus.sync_with_host();
}
SPDLOG_DEBUG("Message bus 1 spikes {} impacts {}", bus.get_num_messages<cuda::SpikeMessage>(),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

В trace?


foreach (lib_name IN ITEMS "${PROJECT_NAME}" "${PROJECT_NAME}_static")
target_compile_options("${lib_name}" PRIVATE $<$<COMPILE_LANGUAGE:CUDA>: --expt-relaxed-constexpr -rdc=true>)
target_compile_options("${lib_name}" PRIVATE $<$<COMPILE_LANGUAGE:CUDA>: --expt-relaxed-constexpr -rdc=true> --generate-line-info) #Remove generate-line-info or make it debug

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Убрать под DEBUG.

#include <knp/synapse-traits/all_traits.h>


namespace knp::framework::projection::synapse_generators

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Докстринги.

Comment on lines +320 to +325
/**
* @brief Upcast all synapses derived from SynapseType to SynapseType, leaving other synapses intact.
* @tparam BaseSynapseType base synapse type.
*/
template <typename SynapseType>
void upcast_projections();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Перенести в функции.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants