| 38 | } |
| 39 | |
| 40 | std::vector<float> apg_guidance( |
| 41 | const std::vector<float> & pred_cond, |
| 42 | const std::vector<float> & pred_uncond, |
| 43 | float guidance_scale, |
| 44 | int64_t frames, |
| 45 | int64_t channels, |
| 46 | std::vector<float> & momentum, |
| 47 | float momentum_coeff, |
| 48 | double norm_threshold) { |
| 49 | constexpr double kEps = 1.0e-12; |
| 50 | require_vector_shape(pred_cond.size(), frames, channels, "APG branch shape mismatch"); |
| 51 | require_same_size(pred_cond.size(), pred_uncond.size(), "APG branch size mismatch"); |
| 52 | if (momentum.size() != pred_cond.size()) { |
| 53 | momentum.assign(pred_cond.size(), 0.0F); |
| 54 | } |
| 55 | std::vector<float> out(pred_cond.size(), 0.0F); |
| 56 | for (size_t i = 0; i < pred_cond.size(); ++i) { |
| 57 | const float update = pred_cond[i] - pred_uncond[i]; |
| 58 | momentum[i] = update + momentum_coeff * momentum[i]; |
| 59 | } |
| 60 | for (int64_t channel = 0; channel < channels; ++channel) { |
| 61 | double diff_norm_sq = 0.0; |
| 62 | double pred_norm_sq = 0.0; |
| 63 | for (int64_t frame = 0; frame < frames; ++frame) { |
| 64 | const size_t index = static_cast<size_t>(frame * channels + channel); |
| 65 | diff_norm_sq += static_cast<double>(momentum[index]) * momentum[index]; |
| 66 | pred_norm_sq += static_cast<double>(pred_cond[index]) * pred_cond[index]; |
| 67 | } |
| 68 | const double diff_norm = std::sqrt(diff_norm_sq); |
| 69 | const double limiter = diff_norm > kEps ? std::min(1.0, norm_threshold / diff_norm) : 1.0; |
| 70 | const double pred_norm = std::sqrt(pred_norm_sq); |
| 71 | double dot = 0.0; |
| 72 | for (int64_t frame = 0; frame < frames; ++frame) { |
| 73 | const size_t index = static_cast<size_t>(frame * channels + channel); |
| 74 | const double diff = static_cast<double>(momentum[index]) * limiter; |
| 75 | const double unit = static_cast<double>(pred_cond[index]) / std::max(pred_norm, kEps); |
| 76 | dot += diff * unit; |
| 77 | } |
| 78 | for (int64_t frame = 0; frame < frames; ++frame) { |
| 79 | const size_t index = static_cast<size_t>(frame * channels + channel); |
| 80 | const double diff = static_cast<double>(momentum[index]) * limiter; |
| 81 | const double unit = static_cast<double>(pred_cond[index]) / std::max(pred_norm, kEps); |
| 82 | const double parallel = dot * unit; |
| 83 | const double orthogonal = diff - parallel; |
| 84 | out[index] = static_cast<float>( |
| 85 | static_cast<double>(pred_cond[index]) + |
| 86 | static_cast<double>(guidance_scale - 1.0F) * orthogonal); |
| 87 | } |
| 88 | } |
| 89 | return out; |
| 90 | } |
| 91 | |
| 92 | std::vector<float> adg_guidance( |
| 93 | const std::vector<float> & latents, |