ACMX 2.139.0
Dual-Backend Real-Time GPU Video Synthesis
Loading...
Searching...
No Matches
deep_dream_model.cpp
Go to the documentation of this file.
2
4
5#include <torch/cuda.h>
6#include <torch/nn/functional/pooling.h>
7#include <torch/nn/functional/upsampling.h>
8#include <torch/script.h>
9#include <torch/torch.h>
10
11#include <cuda_runtime_api.h>
12#include <opencv2/cudaarithm.hpp>
13#include <opencv2/cudawarping.hpp>
14#include <opencv2/imgproc.hpp>
15#if __has_include(<opencv2/geometry/2d.hpp>)
16#include <opencv2/geometry/2d.hpp>
17#endif
18
19#include <algorithm>
20#include <charconv>
21#include <cmath>
22#include <filesystem>
23#include <limits>
24#include <ostream>
25#include <stdexcept>
26#include <string>
27#include <unordered_set>
28#include <utility>
29
30namespace acmxvk::dream {
31 namespace {
32 constexpr std::uintmax_t MAX_MODEL_BYTES = 2ULL * 1024ULL * 1024ULL * 1024ULL;
33 constexpr std::size_t MAX_LAYERS = 128;
34 constexpr std::int64_t MAX_SOURCE_LAYER_INDEX = 4096;
35 constexpr std::int64_t MAX_TEST_INPUT_SIZE = 256;
36 constexpr int MAX_GRADIENT_ASCENT_ITERATIONS = 100;
37 constexpr float MAX_GRADIENT_ASCENT_STEP = 10.0F;
38 constexpr float GRADIENT_EPSILON = 1.0e-8F;
39 constexpr float MAX_FEEDBACK = 0.99F;
40 constexpr float MIN_ZOOM = 0.9F;
41 constexpr float MAX_ZOOM = 1.1F;
42 constexpr float MAX_ROTATION_DEGREES = 5.0F;
43 constexpr int MAX_DREAM_DIMENSION = 4096;
44 constexpr int MAX_TARGET_CHANNEL = 65535;
45 constexpr int MAX_OCTAVES = 8;
46 constexpr float MIN_OCTAVE_SCALE = 1.1F;
47 constexpr float MAX_OCTAVE_SCALE = 3.0F;
48 constexpr int MAX_JITTER = 64;
49 constexpr int MAX_SMOOTHING = 16;
50
51 [[nodiscard]] c10::IValue require_attribute(const torch::jit::Module &module, const std::string &name) {
52 if (!module.hasattr(name)) {
53 throw std::runtime_error("Deep Dream model is missing metadata attribute '" + name + "'");
54 }
55 return module.attr(name);
56 }
57
58 [[nodiscard]] std::string string_attribute(const torch::jit::Module &module, const std::string &name) {
59 const c10::IValue value = require_attribute(module, name);
60 if (!value.isString()) {
61 throw std::runtime_error("Deep Dream metadata attribute '" + name + "' must be a string");
62 }
63 return value.toStringRef();
64 }
65
66 [[nodiscard]] std::int64_t integer_attribute(const torch::jit::Module &module, const std::string &name) {
67 const c10::IValue value = require_attribute(module, name);
68 if (!value.isInt()) {
69 throw std::runtime_error("Deep Dream metadata attribute '" + name + "' must be an integer");
70 }
71 return value.toInt();
72 }
73
74 [[nodiscard]] std::vector<std::string> string_list_attribute(const torch::jit::Module &module, const std::string &name) {
75 const c10::IValue value = require_attribute(module, name);
76 if (!value.isList()) {
77 throw std::runtime_error("Deep Dream metadata attribute '" + name + "' must be a string list");
78 }
79 std::vector<std::string> result;
80 result.reserve(value.toListRef().size());
81 for (const c10::IValue &entry : value.toListRef()) {
82 if (!entry.isString()) {
83 throw std::runtime_error("Deep Dream metadata attribute '" + name + "' must contain strings");
84 }
85 result.push_back(entry.toStringRef());
86 }
87 return result;
88 }
89
90 [[nodiscard]] std::vector<std::int64_t> integer_list_attribute(const torch::jit::Module &module, const std::string &name) {
91 const c10::IValue value = require_attribute(module, name);
92 if (!value.isIntList()) {
93 throw std::runtime_error("Deep Dream metadata attribute '" + name + "' must be an integer list");
94 }
95 return value.toIntVector();
96 }
97
98 [[nodiscard]] std::vector<double> double_list_attribute(const torch::jit::Module &module, const std::string &name) {
99 const c10::IValue value = require_attribute(module, name);
100 if (!value.isDoubleList()) {
101 throw std::runtime_error("Deep Dream metadata attribute '" + name + "' must be a float list");
102 }
103 return value.toDoubleVector();
104 }
105
106 void validate_normalization(const std::vector<double> &values, bool standard_deviation) {
107 if (values.size() != 3) {
108 throw std::runtime_error("Deep Dream input normalization must contain three channels");
109 }
110 for (double value : values) {
111 if (!std::isfinite(value) || value < 0.0 || value > 10.0 || (standard_deviation && value <= 0.0)) {
112 throw std::runtime_error("Deep Dream input normalization contains an invalid value");
113 }
114 }
115 }
116
117 [[nodiscard]] ModelMetadata read_metadata(const torch::jit::Module &module) {
118 if (string_attribute(module, "acmxvk_deep_dream_format") != "acmxvk-deep-dream") {
119 throw std::runtime_error("TorchScript file is not an ACMXVK Deep Dream model");
120 }
121 if (integer_attribute(module, "acmxvk_deep_dream_version") != 1) {
122 throw std::runtime_error("Deep Dream model metadata version is unsupported");
123 }
124
125 ModelMetadata metadata;
126 metadata.architecture = string_attribute(module, "architecture");
127 metadata.default_layer = string_attribute(module, "default_layer");
128 metadata.input_channels = integer_attribute(module, "input_channels");
129 metadata.minimum_input_size = integer_attribute(module, "minimum_input_size");
130 metadata.input_mean = double_list_attribute(module, "input_mean");
131 metadata.input_std = double_list_attribute(module, "input_std");
132 const std::vector<std::string> names = string_list_attribute(module, "layer_names");
133 const std::vector<std::int64_t> source_indices = integer_list_attribute(module, "layer_source_indices");
134
135 input::validate_string(metadata.architecture, input::StringKind::Token, "Deep Dream model architecture");
136 input::validate_string(metadata.default_layer, input::StringKind::Identifier, "Deep Dream default layer");
137 if (metadata.input_channels != 3 || metadata.minimum_input_size < 32 || metadata.minimum_input_size > MAX_TEST_INPUT_SIZE) {
138 throw std::runtime_error("Deep Dream model has unsupported input dimensions");
139 }
140 validate_normalization(metadata.input_mean, false);
141 validate_normalization(metadata.input_std, true);
142 if (names.empty() || names.size() > MAX_LAYERS || names.size() != source_indices.size()) {
143 throw std::runtime_error("Deep Dream model has an invalid feature-layer table");
144 }
145
146 std::unordered_set<std::string> unique_names;
147 std::int64_t previous_index = -1;
148 for (std::size_t index = 0; index < names.size(); ++index) {
149 input::validate_string(names[index], input::StringKind::Identifier, "Deep Dream feature-layer name");
150 if (!unique_names.insert(names[index]).second || source_indices[index] <= previous_index || source_indices[index] > MAX_SOURCE_LAYER_INDEX) {
151 throw std::runtime_error("Deep Dream model has an invalid feature-layer table");
152 }
153 metadata.layers.push_back(LayerMetadata{names[index], source_indices[index]});
154 previous_index = source_indices[index];
155 }
156 if (!unique_names.contains(metadata.default_layer)) {
157 throw std::runtime_error("Deep Dream default layer is absent from the layer table");
158 }
159 return metadata;
160 }
161
162 [[nodiscard]] std::size_t resolve_layer(const ModelMetadata &metadata, std::string_view selector) {
163 if (selector.empty()) {
164 selector = metadata.default_layer;
165 }
166 std::size_t numeric_layer = 0;
167 const char *begin = selector.data();
168 const char *end = begin + selector.size();
169 const auto [position, error] = std::from_chars(begin, end, numeric_layer);
170 if (error == std::errc{} && position == end) {
171 if (numeric_layer >= metadata.layers.size()) {
172 throw std::runtime_error("Deep Dream layer index is outside the model's range");
173 }
174 return numeric_layer;
175 }
176 const auto match = std::find_if(metadata.layers.begin(), metadata.layers.end(), [selector](const LayerMetadata &layer) { return layer.name == selector; });
177 if (match == metadata.layers.end()) {
178 throw std::runtime_error("Deep Dream layer is not present in model: " + std::string(selector));
179 }
180 return static_cast<std::size_t>(std::distance(metadata.layers.begin(), match));
181 }
182
183 [[nodiscard]] std::vector<torch::Tensor> feature_outputs(const c10::IValue &value) {
184 if (!value.isTensorList()) {
185 throw std::runtime_error("Deep Dream model forward method must return List[Tensor]");
186 }
187 return value.toTensorVector();
188 }
189
191 if (options.iterations < 1 || options.iterations > MAX_GRADIENT_ASCENT_ITERATIONS) {
192 throw std::runtime_error("Deep Dream iterations must be between 1 and 100");
193 }
194 if (!std::isfinite(options.step_size) || options.step_size <= 0.0F || options.step_size > MAX_GRADIENT_ASCENT_STEP) {
195 throw std::runtime_error("Deep Dream step size must be greater than 0 and no more than 10");
196 }
197 if (!std::isfinite(options.feedback) || options.feedback < 0.0F || options.feedback > MAX_FEEDBACK) {
198 throw std::runtime_error("Deep Dream feedback must be between 0 and 0.99");
199 }
200 if (!std::isfinite(options.zoom) || options.zoom < MIN_ZOOM || options.zoom > MAX_ZOOM) {
201 throw std::runtime_error("Deep Dream zoom must be between 0.9 and 1.1");
202 }
203 if (!std::isfinite(options.rotation_degrees) || std::abs(options.rotation_degrees) > MAX_ROTATION_DEGREES) {
204 throw std::runtime_error("Deep Dream rotation must be between -5 and 5 degrees");
205 }
206 if (options.max_dimension != 0 && (options.max_dimension < 64 || options.max_dimension > MAX_DREAM_DIMENSION)) {
207 throw std::runtime_error("Deep Dream working size must be 0 or between 64 and 4096");
208 }
209 if (options.target_channel < -1 || options.target_channel > MAX_TARGET_CHANNEL) {
210 throw std::runtime_error("Deep Dream target channel must be -1 or between 0 and 65535");
211 }
212 if (options.octaves < 1 || options.octaves > MAX_OCTAVES) {
213 throw std::runtime_error("Deep Dream octaves must be between 1 and 8");
214 }
215 if (!std::isfinite(options.octave_scale) || options.octave_scale < MIN_OCTAVE_SCALE || options.octave_scale > MAX_OCTAVE_SCALE) {
216 throw std::runtime_error("Deep Dream octave scale must be between 1.1 and 3.0");
217 }
218 if (options.jitter < 0 || options.jitter > MAX_JITTER) {
219 throw std::runtime_error("Deep Dream jitter must be between 0 and 64 pixels");
220 }
221 if (options.smoothing < 0 || options.smoothing > MAX_SMOOTHING) {
222 throw std::runtime_error("Deep Dream smoothing must be between 0 and 16 pixels");
223 }
224 }
225
226 [[nodiscard]] torch::Tensor normalization_tensor(const std::vector<double> &values, const torch::Device &device, torch::ScalarType scalar_type) { return torch::tensor(values, torch::TensorOptions().dtype(scalar_type).device(device)).view({1, 3, 1, 1}); }
227
232
233 void check_cuda(cudaError_t result, std::string_view operation) {
234 if (result != cudaSuccess) {
235 throw std::runtime_error(std::string(operation) + ": " + cudaGetErrorString(result));
236 }
237 }
238 } // namespace
239
240 struct Model::Impl {
241 torch::jit::Module module;
243 std::filesystem::path filename;
244 std::vector<std::vector<std::int64_t>> output_shapes;
246 cv::cuda::GpuMat previous_output_cuda;
247 cv::cuda::GpuMat working_input_cuda;
249 cv::cuda::GpuMat blended_input_cuda;
250 std::size_t selected_layer = 0;
251 int cuda_device = 0;
252 torch::ScalarType scalar_type = torch::kFloat32;
253 std::uint64_t frame_sequence = 0;
254
255 [[nodiscard]] TensorAscentResult optimize(const torch::Tensor &input, const GradientAscentOptions &options);
256 };
257
258 [[nodiscard]] TensorAscentResult Model::Impl::optimize(const torch::Tensor &input, const GradientAscentOptions &options) {
259 const torch::Device device(torch::kCUDA, cuda_device);
260 const torch::Tensor mean = normalization_tensor(metadata.input_mean, device, scalar_type);
261 const torch::Tensor standard_deviation = normalization_tensor(metadata.input_std, device, scalar_type);
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;
265
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) {
268 return tensor;
269 }
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));
271 };
272
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));
277 const double minimum_scale = std::min(1.0, std::max(static_cast<double>(metadata.minimum_input_size) / input_height, static_cast<double>(metadata.minimum_input_size) / input_width));
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);
285 }
286 }
287
289 result.processed_width = static_cast<int>(input_width);
290 result.processed_height = static_cast<int>(input_height);
291 result.processed_octaves = static_cast<int>(octave_sizes.size());
292 const std::uint64_t current_frame = frame_sequence++;
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();
300 } else {
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();
303 }
304 previous_source = octave_source;
305 dream_input.requires_grad_(true);
306
307 for (int iteration = 0; iteration < options.iterations; ++iteration) {
308 torch::Tensor model_input = dream_input;
309 if (options.jitter > 0) {
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});
315 }
316 const std::vector<torch::Tensor> outputs = feature_outputs(module.forward({model_input}));
317 if (outputs.size() != metadata.layers.size()) {
318 throw std::runtime_error("Deep Dream model output count changed during gradient ascent");
319 }
320 const torch::Tensor activation = outputs[selected_layer];
321 torch::Tensor target_activation = activation;
322 if (options.target_channel >= 0) {
323 if (options.target_channel >= activation.size(1)) {
324 throw std::runtime_error("Deep Dream target channel is outside the selected layer's range");
325 }
326 target_activation = activation.select(1, options.target_channel);
327 }
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");
331 }
332 loss.backward();
333
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");
337 }
338 if (options.smoothing > 0) {
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));
341 }
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");
346 }
347 result.activation_loss = loss.item<float>();
348 result.mean_gradient = gradient_value;
349 if (gradient_value <= 0.0F) {
350 dream_input.grad().zero_();
351 continue;
352 }
353
354 {
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));
358 }
359 dream_input.grad().zero_();
360 }
361 }
362
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};
366 }
367
368 Model::Model(std::unique_ptr<Impl> implementation) : implementation(std::move(implementation)) {}
369
370 Model::Model(Model &&) noexcept = default;
371 Model &Model::operator=(Model &&) noexcept = default;
372 Model::~Model() = default;
373
374 [[nodiscard]] Model Model::load(std::string_view filename, int cuda_device, std::string_view layer, bool use_half) {
375 input::validate_string(filename, input::StringKind::Path, "Deep Dream model path");
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());
379 }
380 input::validate_file_size(model_path, "Deep Dream TorchScript model", MAX_MODEL_BYTES);
381
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");
385 }
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");
389 }
390
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);
395 module.eval();
396 for (torch::Tensor parameter : module.parameters()) {
397 parameter.set_requires_grad(false);
398 }
399
400 auto implementation = std::make_unique<Impl>();
401 implementation->metadata = read_metadata(module);
402 implementation->selected_layer = resolve_layer(implementation->metadata, layer);
403 implementation->filename = model_path;
404 implementation->cuda_device = cuda_device;
405 implementation->scalar_type = scalar_type;
406 implementation->module = std::move(module);
407
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}));
412 if (outputs.size() != implementation->metadata.layers.size()) {
413 throw std::runtime_error("Deep Dream model output count does not match its metadata");
414 }
415 implementation->output_shapes.reserve(outputs.size());
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");
419 }
420 implementation->output_shapes.push_back(output.sizes().vec());
421 }
422 torch::cuda::synchronize(cuda_device);
423 return Model(std::move(implementation));
424 }
425
426 [[nodiscard]] const ModelMetadata &Model::metadata() const { return implementation->metadata; }
427
428 [[nodiscard]] std::size_t Model::selected_layer() const { return implementation->selected_layer; }
429
430 [[nodiscard]] std::size_t Model::selected_channels() const { return static_cast<std::size_t>(implementation->output_shapes[implementation->selected_layer][1]); }
431
432 [[nodiscard]] GradientAscentResult Model::apply_gradient_ascent(cv::Mat &rgba, const GradientAscentOptions &options) {
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");
436 }
437
438 cv::Mat working_rgba;
439 const int source_max_dimension = std::max(rgba.cols, rgba.rows);
440 double resize_scale = 1.0;
441 if (options.max_dimension > 0 && source_max_dimension > options.max_dimension) {
442 resize_scale = static_cast<double>(options.max_dimension) / source_max_dimension;
443 }
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);
447 } else {
448 working_rgba = rgba;
449 }
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");
452 }
453
454 cv::Mat dream_source = working_rgba;
455 cv::Mat transformed_feedback;
456 cv::Mat blended_source;
457 if (options.feedback > 0.0F && !implementation->previous_output.empty() && implementation->previous_output.type() == working_rgba.type() && implementation->previous_output.size() == working_rgba.size()) {
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;
463 }
464
465 cv::Mat rgb;
466 cv::cvtColor(dream_source, rgb, cv::COLOR_RGBA2RGB);
467 cv::Mat rgb_float;
468 rgb.convertTo(rgb_float, CV_32FC3, 1.0 / 255.0);
469
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();
472 TensorAscentResult tensor_result = implementation->optimize(input, options);
473 GradientAscentResult result = tensor_result.metrics;
474 torch::Tensor output = std::move(tensor_result.output);
475
476 output = output.squeeze(0).permute({1, 2, 0}).mul(255.0F).round().to(torch::kUInt8).to(torch::kCPU).contiguous();
477 torch::cuda::synchronize(implementation->cuda_device);
478
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);
482 implementation->previous_output = dreamed_rgba.clone();
483 if (dreamed_rgba.size() != rgba.size()) {
484 cv::Mat restored;
485 cv::resize(dreamed_rgba, restored, rgba.size(), 0.0, 0.0, cv::INTER_LINEAR);
486 dreamed_rgba = restored;
487 }
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);
494 return result;
495 }
496
497 [[nodiscard]] GradientAscentResult Model::apply_gradient_ascent_cuda(const cv::cuda::GpuMat &rgba, cv::cuda::GpuMat &output, cv::cuda::Stream &stream, const GradientAscentOptions &options) {
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");
501 }
502
503 const int source_max_dimension = std::max(rgba.cols, rgba.rows);
504 double resize_scale = 1.0;
505 if (options.max_dimension > 0 && source_max_dimension > options.max_dimension) {
506 resize_scale = static_cast<double>(options.max_dimension) / source_max_dimension;
507 }
508
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);
513 working_rgba = &implementation->working_input_cuda;
514 }
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");
517 }
518
519 const cv::cuda::GpuMat *dream_source = working_rgba;
520 if (options.feedback > 0.0F && !implementation->previous_output_cuda.empty() && implementation->previous_output_cuda.type() == CV_8UC4 && implementation->previous_output_cuda.size() == working_rgba->size()) {
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);
524 cv::cuda::addWeighted(implementation->transformed_feedback_cuda, options.feedback, *working_rgba, 1.0F - options.feedback, 0.0, implementation->blended_input_cuda, -1, stream);
525 dream_source = &implementation->blended_input_cuda;
526 }
527 stream.waitForCompletion();
528
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();
534
535 TensorAscentResult tensor_result = implementation->optimize(input, options);
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();
539 };
540
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);
543 torch::cuda::synchronize(implementation->cuda_device);
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");
545
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));
549 }
550 const torch::Tensor final_output = rgba_tensor(final_rgb, source_rgba.narrow(2, 3, 1));
551 torch::cuda::synchronize(implementation->cuda_device);
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;
555 }
556
557 void Model::print(std::ostream &output) const {
558 output << "Deep Dream model: " << implementation->filename.string() << '\n' << "Deep Dream architecture: " << implementation->metadata.architecture << '\n' << "Deep Dream CUDA device: " << implementation->cuda_device << '\n' << "Deep Dream precision: " << (implementation->scalar_type == torch::kFloat16 ? "FP16" : "FP32") << '\n' << "Deep Dream feature layers: " << implementation->metadata.layers.size() << '\n';
559 for (std::size_t index = 0; index < implementation->metadata.layers.size(); ++index) {
560 const LayerMetadata &layer = implementation->metadata.layers[index];
561 output << " " << index << ": " << layer.name << " (source " << layer.source_index << ')';
562 if (index == implementation->selected_layer) {
563 output << " [selected]";
564 }
565 output << '\n';
566 }
567 const std::vector<std::int64_t> &shape = implementation->output_shapes[implementation->selected_layer];
568 output << "Deep Dream selected activation: ";
569 for (std::size_t index = 0; index < shape.size(); ++index) {
570 if (index != 0) {
571 output << 'x';
572 }
573 output << shape[index];
574 }
575 output << '\n' << "Deep Dream selected channels: " << selected_channels() << '\n';
576 }
577
578} // namespace acmxvk::dream
std::size_t selected_channels() const
GradientAscentResult apply_gradient_ascent(cv::Mat &rgba, const GradientAscentOptions &options={})
static Model load(std::string_view filename, int cuda_device, std::string_view layer={}, bool use_half=false)
const ModelMetadata & metadata() const
std::unique_ptr< Impl > implementation
std::size_t selected_layer() const
void print(std::ostream &output) const
GradientAscentResult apply_gradient_ascent_cuda(const cv::cuda::GpuMat &rgba, cv::cuda::GpuMat &output, cv::cuda::Stream &stream, const GradientAscentOptions &options={})
Model(Model &&) noexcept
std::int64_t integer_attribute(const torch::jit::Module &module, const std::string &name)
std::vector< torch::Tensor > feature_outputs(const c10::IValue &value)
void validate_gradient_options(const GradientAscentOptions &options)
torch::Tensor normalization_tensor(const std::vector< double > &values, const torch::Device &device, torch::ScalarType scalar_type)
void validate_normalization(const std::vector< double > &values, bool standard_deviation)
std::size_t resolve_layer(const ModelMetadata &metadata, std::string_view selector)
ModelMetadata read_metadata(const torch::jit::Module &module)
void check_cuda(cudaError_t result, std::string_view operation)
std::vector< std::int64_t > integer_list_attribute(const torch::jit::Module &module, const std::string &name)
std::vector< double > double_list_attribute(const torch::jit::Module &module, const std::string &name)
c10::IValue require_attribute(const torch::jit::Module &module, const std::string &name)
std::string string_attribute(const torch::jit::Module &module, const std::string &name)
std::vector< std::string > string_list_attribute(const torch::jit::Module &module, const std::string &name)
void validate_file_size(const std::filesystem::path &path, std::string_view context, std::uintmax_t maximum_bytes)
void validate_string(std::string_view value, StringKind kind, std::string_view context, bool allow_empty)
std::vector< double > input_std
std::vector< double > input_mean
std::vector< LayerMetadata > layers
cv::cuda::GpuMat transformed_feedback_cuda
TensorAscentResult optimize(const torch::Tensor &input, const GradientAscentOptions &options)
cv::cuda::GpuMat previous_output_cuda
std::filesystem::path filename
std::vector< std::vector< std::int64_t > > output_shapes