259 const torch::Device device(torch::kCUDA,
cuda_device);
262 const torch::Tensor normalized_source = ((
input - mean) / standard_deviation).detach();
263 const torch::Tensor minimum = (torch::zeros_like(mean) - mean) / standard_deviation;
264 const torch::Tensor maximum = (torch::ones_like(mean) - mean) / standard_deviation;
266 const auto resize_tensor = [](
const torch::Tensor &tensor, std::int64_t height, std::int64_t width) {
267 if (tensor.size(2) == height && tensor.size(3) == width) {
270 return torch::nn::functional::interpolate(tensor, torch::nn::functional::InterpolateFuncOptions().size(std::vector<std::int64_t>{height, width}).mode(torch::kBilinear).align_corners(
false));
273 const std::int64_t input_height =
input.size(2);
274 const std::int64_t input_width =
input.size(3);
275 std::vector<std::pair<std::int64_t, std::int64_t>> octave_sizes;
276 octave_sizes.reserve(
static_cast<std::size_t
>(options.
octaves));
278 for (
int octave = options.
octaves - 1; octave >= 0; --octave) {
279 const double scale = std::max(minimum_scale, 1.0 / std::pow(
static_cast<double>(options.
octave_scale), octave));
280 const std::int64_t height = std::max<std::int64_t>(
metadata.
minimum_input_size,
static_cast<std::int64_t
>(std::lround(input_height * scale)));
281 const std::int64_t width = std::max<std::int64_t>(
metadata.
minimum_input_size,
static_cast<std::int64_t
>(std::lround(input_width * scale)));
282 const std::pair<std::int64_t, std::int64_t> size{height, width};
283 if (octave_sizes.empty() || octave_sizes.back() != size) {
284 octave_sizes.push_back(size);
293 torch::Tensor dream_input;
294 torch::Tensor previous_source;
295 for (std::size_t octave_index = 0; octave_index < octave_sizes.size(); ++octave_index) {
296 const auto [octave_height, octave_width] = octave_sizes[octave_index];
297 const torch::Tensor octave_source = resize_tensor(normalized_source, octave_height, octave_width);
298 if (!dream_input.defined()) {
299 dream_input = octave_source.detach();
301 const torch::Tensor restored_detail = octave_source - resize_tensor(previous_source, octave_height, octave_width);
302 dream_input = (resize_tensor(dream_input.detach(), octave_height, octave_width) + restored_detail).clamp(minimum, maximum).detach();
304 previous_source = octave_source;
305 dream_input.requires_grad_(
true);
307 for (
int iteration = 0; iteration < options.
iterations; ++iteration) {
308 torch::Tensor model_input = dream_input;
310 const std::uint64_t span =
static_cast<std::uint64_t
>(options.
jitter * 2 + 1);
311 const std::uint64_t phase = current_frame * 1315423911ULL + octave_index * 2654435761ULL +
static_cast<std::uint64_t
>(iteration) * 2246822519ULL;
312 const std::int64_t shift_x =
static_cast<std::int64_t
>(phase % span) - options.
jitter;
313 const std::int64_t shift_y =
static_cast<std::int64_t
>((phase / span) % span) - options.
jitter;
314 model_input = torch::roll(dream_input, {shift_y, shift_x}, {2, 3});
316 const std::vector<torch::Tensor> outputs = feature_outputs(
module.forward({model_input}));
318 throw std::runtime_error(
"Deep Dream model output count changed during gradient ascent");
321 torch::Tensor target_activation = activation;
324 throw std::runtime_error(
"Deep Dream target channel is outside the selected layer's range");
328 const torch::Tensor loss = target_activation.to(torch::kFloat32).square().mean();
329 if (!torch::isfinite(loss).item<bool>()) {
330 throw std::runtime_error(
"Deep Dream activation loss is not finite");
334 torch::Tensor gradient = dream_input.grad();
335 if (!gradient.defined() || !torch::isfinite(gradient).all().item<
bool>()) {
336 throw std::runtime_error(
"Deep Dream produced an invalid input gradient");
339 const std::int64_t kernel_size = options.
smoothing * 2 + 1;
340 gradient = torch::nn::functional::avg_pool2d(gradient, torch::nn::functional::AvgPool2dFuncOptions({kernel_size, kernel_size}).stride({1, 1}).padding({options.
smoothing, options.
smoothing}).count_include_pad(
false));
342 const torch::Tensor mean_gradient = gradient.to(torch::kFloat32).abs().mean();
343 const float gradient_value = mean_gradient.item<
float>();
344 if (!std::isfinite(gradient_value)) {
345 throw std::runtime_error(
"Deep Dream produced a non-finite input gradient magnitude");
349 if (gradient_value <= 0.0F) {
350 dream_input.grad().zero_();
355 torch::NoGradGuard no_grad;
356 dream_input.add_(gradient * (options.
step_size / (mean_gradient + GRADIENT_EPSILON)));
357 dream_input.copy_(torch::maximum(torch::minimum(dream_input, maximum), minimum));
359 dream_input.grad().zero_();
363 torch::Tensor output = (dream_input.detach() * standard_deviation + mean).clamp(0.0F, 1.0F);
364 result.
mean_pixel_change = (output.to(torch::kFloat32) -
input.to(torch::kFloat32)).abs().mean().item<
float>();
365 return TensorAscentResult{std::move(output), result};
374 [[nodiscard]]
Model Model::
load(std::string_view filename,
int cuda_device, std::string_view layer,
bool use_half) {
376 const std::filesystem::path model_path = std::filesystem::absolute(filename).lexically_normal();
377 if (!std::filesystem::is_regular_file(model_path)) {
378 throw std::runtime_error(
"Deep Dream model is not a regular file: " + model_path.string());
382 const c10::DeviceIndex device_count = torch::cuda::device_count();
383 if (!torch::cuda::is_available() || device_count == 0) {
384 throw std::runtime_error(
"Deep Dream model loading requires an available CUDA device");
386 if (cuda_device < 0 || cuda_device >= device_count) {
387 throw std::runtime_error(
"Deep Dream CUDA device index is outside "
388 "the available range");
391 const torch::Device device(torch::kCUDA, cuda_device);
392 torch::jit::Module module = torch::jit::load(model_path.string(), device);
393 const torch::ScalarType scalar_type = use_half ? torch::kFloat16 : torch::kFloat32;
394 module.to(device, scalar_type);
396 for (torch::Tensor parameter : module.parameters()) {
397 parameter.set_requires_grad(
false);
408 const std::int64_t input_size = std::max<std::int64_t>(64,
implementation->metadata.minimum_input_size);
409 torch::NoGradGuard no_grad;
410 const torch::Tensor
input = torch::zeros({1,
implementation->metadata.input_channels, input_size, input_size}, torch::TensorOptions().dtype(scalar_type).device(device));
411 const std::vector<torch::Tensor> outputs = feature_outputs(
implementation->module.forward({input}));
413 throw std::runtime_error(
"Deep Dream model output count does not match its metadata");
416 for (
const torch::Tensor &output : outputs) {
417 if (!output.defined() || output.dim() != 4 || output.size(0) != 1 || !output.is_floating_point() || !output.device().is_cuda() || output.get_device() != cuda_device || output.size(2) <= 0 || output.size(3) <= 0) {
418 throw std::runtime_error(
"Deep Dream model returned an invalid feature tensor");
422 torch::cuda::synchronize(cuda_device);
433 validate_gradient_options(options);
434 if (rgba.empty() || rgba.type() != CV_8UC4 || rgba.cols < 1 || rgba.rows < 1) {
435 throw std::runtime_error(
"Deep Dream input must be a non-empty RGBA8 image");
438 cv::Mat working_rgba;
439 const int source_max_dimension = std::max(rgba.cols, rgba.rows);
440 double resize_scale = 1.0;
442 resize_scale =
static_cast<double>(options.
max_dimension) / source_max_dimension;
444 if (resize_scale < 1.0) {
445 const cv::Size working_size(std::max(1,
static_cast<int>(std::lround(rgba.cols * resize_scale))), std::max(1,
static_cast<int>(std::lround(rgba.rows * resize_scale))));
446 cv::resize(rgba, working_rgba, working_size, 0.0, 0.0, cv::INTER_AREA);
450 if (working_rgba.cols <
implementation->metadata.minimum_input_size || working_rgba.rows <
implementation->metadata.minimum_input_size) {
451 throw std::runtime_error(
"Deep Dream working image is smaller than the model minimum");
454 cv::Mat dream_source = working_rgba;
455 cv::Mat transformed_feedback;
456 cv::Mat blended_source;
458 const cv::Point2f center(
static_cast<float>(working_rgba.cols - 1) * 0.5F,
static_cast<float>(working_rgba.rows - 1) * 0.5F);
459 const cv::Mat transform = cv::getRotationMatrix2D(center, options.
rotation_degrees, options.
zoom);
460 cv::warpAffine(
implementation->previous_output, transformed_feedback, transform, working_rgba.size(), cv::INTER_LINEAR, cv::BORDER_REFLECT_101);
461 cv::addWeighted(transformed_feedback, options.
feedback, working_rgba, 1.0F - options.
feedback, 0.0, blended_source);
462 dream_source = blended_source;
466 cv::cvtColor(dream_source, rgb, cv::COLOR_RGBA2RGB);
468 rgb.convertTo(rgb_float, CV_32FC3, 1.0 / 255.0);
470 const torch::Device device(torch::kCUDA,
implementation->cuda_device);
471 const torch::Tensor
input = torch::from_blob(rgb_float.data, {rgb_float.rows, rgb_float.cols, 3}, torch::TensorOptions().dtype(torch::kFloat32)).permute({2, 0, 1}).unsqueeze(0).to(device,
implementation->scalar_type).contiguous();
474 torch::Tensor output = std::move(tensor_result.output);
476 output = output.squeeze(0).permute({1, 2, 0}).mul(255.0F).round().to(torch::kUInt8).to(torch::kCPU).contiguous();
479 cv::Mat dreamed_rgb(rgb.rows, rgb.cols, CV_8UC3, output.data_ptr<std::uint8_t>());
480 cv::Mat dreamed_rgba;
481 cv::cvtColor(dreamed_rgb, dreamed_rgba, cv::COLOR_RGB2RGBA);
483 if (dreamed_rgba.size() != rgba.size()) {
485 cv::resize(dreamed_rgba, restored, rgba.size(), 0.0, 0.0, cv::INTER_LINEAR);
486 dreamed_rgba = restored;
488 std::vector<cv::Mat> original_channels;
489 std::vector<cv::Mat> dreamed_channels;
490 cv::split(rgba, original_channels);
491 cv::split(dreamed_rgba, dreamed_channels);
492 dreamed_channels[3] = original_channels[3];
493 cv::merge(dreamed_channels, rgba);
498 validate_gradient_options(options);
499 if (rgba.empty() || rgba.type() != CV_8UC4 || rgba.cols < 1 || rgba.rows < 1) {
500 throw std::runtime_error(
"Deep Dream CUDA input must be a non-empty RGBA8 image");
503 const int source_max_dimension = std::max(rgba.cols, rgba.rows);
504 double resize_scale = 1.0;
506 resize_scale =
static_cast<double>(options.
max_dimension) / source_max_dimension;
509 const cv::cuda::GpuMat *working_rgba = &rgba;
510 if (resize_scale < 1.0) {
511 const cv::Size working_size(std::max(1,
static_cast<int>(std::lround(rgba.cols * resize_scale))), std::max(1,
static_cast<int>(std::lround(rgba.rows * resize_scale))));
512 cv::cuda::resize(rgba,
implementation->working_input_cuda, working_size, 0.0, 0.0, cv::INTER_AREA, stream);
515 if (working_rgba->cols <
implementation->metadata.minimum_input_size || working_rgba->rows <
implementation->metadata.minimum_input_size) {
516 throw std::runtime_error(
"Deep Dream CUDA working image is smaller than the model minimum");
519 const cv::cuda::GpuMat *dream_source = working_rgba;
521 const cv::Point2f center(
static_cast<float>(working_rgba->cols - 1) * 0.5F,
static_cast<float>(working_rgba->rows - 1) * 0.5F);
522 const cv::Mat transform = cv::getRotationMatrix2D(center, options.
rotation_degrees, options.
zoom);
523 cv::cuda::warpAffine(
implementation->previous_output_cuda,
implementation->transformed_feedback_cuda, transform, working_rgba->size(), cv::INTER_LINEAR, cv::BORDER_REFLECT_101, cv::Scalar(), stream);
527 stream.waitForCompletion();
529 const torch::Device device(torch::kCUDA,
implementation->cuda_device);
530 const torch::TensorOptions byte_options = torch::TensorOptions().dtype(torch::kUInt8).device(device);
531 const torch::Tensor source_rgba = torch::from_blob(rgba.data, {rgba.rows, rgba.cols, 4}, {static_cast<std::int64_t>(rgba.step), 4, 1}, byte_options);
532 const torch::Tensor working_rgba_tensor = torch::from_blob(dream_source->data, {dream_source->rows, dream_source->cols, 4}, {static_cast<std::int64_t>(dream_source->step), 4, 1}, byte_options);
533 const torch::Tensor
input = working_rgba_tensor.narrow(2, 0, 3).permute({2, 0, 1}).unsqueeze(0).to(
implementation->scalar_type).div(255.0F).contiguous();
536 const auto rgba_tensor = [](
const torch::Tensor &rgb,
const torch::Tensor &alpha) {
537 const torch::Tensor rgb_bytes = rgb.squeeze(0).permute({1, 2, 0}).mul(255.0F).round().to(torch::kUInt8);
538 return torch::cat({rgb_bytes, alpha}, 2).contiguous();
541 const torch::Tensor working_output = rgba_tensor(tensor_result.output, working_rgba_tensor.narrow(2, 3, 1));
542 implementation->previous_output_cuda.create(dream_source->rows, dream_source->cols, CV_8UC4);
544 check_cuda(cudaMemcpy2D(
implementation->previous_output_cuda.data,
implementation->previous_output_cuda.step, working_output.data_ptr<std::uint8_t>(),
static_cast<std::size_t
>(dream_source->cols) * 4U,
static_cast<std::size_t
>(dream_source->cols) * 4U, dream_source->rows, cudaMemcpyDeviceToDevice),
"Deep Dream could not preserve its CUDA feedback frame");
546 torch::Tensor final_rgb = tensor_result.output;
547 if (dream_source->cols != rgba.cols || dream_source->rows != rgba.rows) {
548 final_rgb = torch::nn::functional::interpolate(final_rgb, torch::nn::functional::InterpolateFuncOptions().size(std::vector<std::int64_t>{rgba.rows, rgba.cols}).mode(torch::kBilinear).align_corners(
false));
550 const torch::Tensor final_output = rgba_tensor(final_rgb, source_rgba.narrow(2, 3, 1));
552 output.create(rgba.rows, rgba.cols, CV_8UC4);
553 check_cuda(cudaMemcpy2D(output.data, output.step, final_output.data_ptr<std::uint8_t>(),
static_cast<std::size_t
>(rgba.cols) * 4U,
static_cast<std::size_t
>(rgba.cols) * 4U, rgba.rows, cudaMemcpyDeviceToDevice),
"Deep Dream could not publish its CUDA output frame");
554 return tensor_result.metrics;