Files
Linus Baumberger 764f07cbe1 AVX2 implementation
2026-05-25 11:43:58 +02:00

453 lines
15 KiB
C++

// # This file uses avx2
// # This is the first variant and should serve as a base for further avx2 optimizations
// Okay our first step is to use a SoA instead of an AoS
// We only do SoA for the pedestrian struct, there we wanna optimize such that we access for the ped-ped forces adjacent pedestrians (in the arrays)
// Now in a second step we wanna really use AVX2 for the mainloop (where we wana optimize the most innerloop first)
#include "../headers/board.hpp"
#include "../headers/constants.hpp"
#include "../headers/pedestrian_reduced.hpp"
#include <immintrin.h> // to use avx2
#include <algorithm>
#include <cmath>
#include <fstream>
#include <iostream>
#include <math.h>
#include <random>
#include <tuple>
#include <vector>
#define SEED 42
#define BOARD_WIDTH 10.0
#define BOARD_LENGTH 50.0
#define WALL_EPS 1e-3
#define BOARD_WIDTH_MINUS_WALL_EPS 9.999
#ifndef RANDOM_SEED
#define RANDOM_SEED 0
#endif
#ifndef BENCHMARK
#define BENCHMARK 0
#endif
using namespace std;
// we wanna use arrays so we can implement SOA, we create arrays for all the data we need and access
vector<double> pos_x, pos_y;
vector<double> sb_sq;
vector<double> sb_e_x, sb_e_y;
vector<double> e_x, e_y;
vector<double> curr_vel_x, curr_vel_y;
vector<double> w_x, w_y;
vector<double> desired_v0;
vector<double> v_max;
vector<double> destination_x, destination_y;
vector<int> color;
Pedestrian *init_pedestrians(int n_p) {
#if RANDOM_SEED
random_device rd;
mt19937 gen(rd());
#else
mt19937 gen(SEED);
#endif
normal_distribution<double> velocity_gen(v0_mean, v0_std_dev);
uniform_real_distribution<double> y_gen(0.3, BOARD_WIDTH - 0.3);
uniform_real_distribution<double> x_gen_left(2.0, BOARD_LENGTH / 2.0);
uniform_real_distribution<double> x_gen_right(BOARD_LENGTH / 2.0, BOARD_LENGTH - 2.0);
const int n_p_pad = (n_p + 3) & ~3; // round up to a multiple of 4 (so its easy to use avx)
// resize all our arrays for this run
pos_x.resize(n_p_pad);
pos_y.resize(n_p_pad);
sb_sq.resize(n_p_pad);
sb_e_x.resize(n_p_pad);
sb_e_y.resize(n_p_pad);
e_x.resize(n_p_pad);
e_y.resize(n_p_pad);
curr_vel_x.resize(n_p_pad);
curr_vel_y.resize(n_p_pad);
w_x.resize(n_p_pad);
w_y.resize(n_p_pad);
desired_v0.resize(n_p_pad);
v_max.resize(n_p_pad);
destination_x.resize(n_p_pad);
destination_y.resize(n_p_pad);
color.resize(n_p_pad);
int n_p_half = n_p / 2;
for (int i = 0; i < n_p_half; i++) {
double x = x_gen_left(gen);
double y = y_gen(gen);
double dest_x = BOARD_LENGTH + 30.0; // renamed to avoid shadowing destination_x[]
double dest_y = y; // same idea for destination_y[]
double init_e_x = dest_x - x;
double init_e_y = dest_y - y;
double init_e_norm = sqrt(init_e_x * init_e_x + init_e_y * init_e_y);
double init_e_unit_x = init_e_x / init_e_norm;
double init_e_unit_y = init_e_y / init_e_norm;
double d_v0;
do {
d_v0 = velocity_gen(gen);
} while (d_v0 <= 0.1);
double v_m = 1.3 * d_v0;
color[i] = 0;
pos_x[i] = x;
pos_y[i] = y;
e_x[i] = init_e_unit_x;
e_y[i] = init_e_unit_y;
v_max[i] = v_m;
desired_v0[i] = d_v0;
destination_x[i] = dest_x;
destination_y[i] = dest_y;
// Fields the Pedestrian constructor would have zero-initialized:
w_x[i] = 0.0;
w_y[i] = 0.0;
curr_vel_x[i] = 0.0;
curr_vel_y[i] = 0.0;
sb_sq[i] = 0.0;
sb_e_x[i] = 0.0;
sb_e_y[i] = 0.0;
}
for (int i = n_p_half; i < n_p; i++) {
double x = x_gen_right(gen);
double y = y_gen(gen);
double dest_x = -30;
double dest_y = y;
double init_e_x = dest_x - x;
double init_e_y = dest_y - y;
double init_e_norm = sqrt(init_e_x * init_e_x + init_e_y * init_e_y);
double init_e_unit_x = init_e_x / init_e_norm;
double init_e_unit_y = init_e_y / init_e_norm;
double d_v0;
do {
d_v0 = velocity_gen(gen);
} while (d_v0 <= 0.1);
double v_m = 1.3 * d_v0;
color[i] = 1;
pos_x[i] = x;
pos_y[i] = y;
e_x[i] = init_e_unit_x;
e_y[i] = init_e_unit_y;
v_max[i] = v_m;
desired_v0[i] = d_v0;
destination_x[i] = dest_x;
destination_y[i] = dest_y;
// Fields the Pedestrian constructor would have zero-initialized:
w_x[i] = 0.0;
w_y[i] = 0.0;
curr_vel_x[i] = 0.0;
curr_vel_y[i] = 0.0;
sb_sq[i] = 0.0;
sb_e_x[i] = 0.0;
sb_e_y[i] = 0.0;
}
// Padding lanes: positions far away, everything else zero. Any unmasked SIMD
// contribution from these lanes will vanish through exp(very negative) roughly 0.
for (int j = n_p; j < n_p_pad; j++) {
pos_x[j] = 1e9;
pos_y[j] = 1e9;
sb_sq[j] = 0.0;
sb_e_x[j] = 0.0;
sb_e_y[j] = 0.0;
}
return nullptr;
}
Board init_board_without_obstacles() { return Board(BOARD_LENGTH, BOARD_WIDTH, 0, nullptr); }
int run_simulation(Pedestrian *pedestrians, Board &board, int n_p, int n_iter, const char *dump_path) {
#if BENCHMARK
(void)dump_path;
#endif
#if !BENCHMARK
const int dump_interval = 1;
vector<tuple<int, int, double, double, double, double, int>> samples;
if (dump_path) {
samples.reserve(static_cast<size_t>(n_iter / dump_interval + 1) * n_p);
for (int i = 0; i < n_p; i++) {
// Pedestrian &p = pedestrians[i];
samples.emplace_back(0, i, pos_x[i], pos_y[i], e_x[i], e_y[i], color[i]);
}
}
#endif
// all the constants for the AVX2 setup
const int n_p_pad = (n_p + 3) & ~3;
alignas(32) const double lane_offset_arr[4] = {0.0, 1.0, 2.0, 3.0};
const __m256d lane_off = _mm256_load_pd(lane_offset_arr);
const __m256d v_neg_v0_div_2s = _mm256_set1_pd(NEG_V0_AB_div_TWO_SIGMA);
const __m256d v_neg_2s_inv = _mm256_set1_pd(NEG_TWO_SIGMA_INV);
const __m256d v_cos_phi_inv = _mm256_set1_pd(cos_phi_inv);
const __m256d v_dt_neg = _mm256_set1_pd(dt_neg);
const __m256d v_c_neg_dt = _mm256_set1_pd(c_neg_times_dt);
const __m256d v_zero = _mm256_setzero_pd();
const __m256d v_np = _mm256_set1_pd((double)n_p);
for (int t = 0; t < n_iter; t++) {
for (int i = 0; i < n_p; i++) {
double desired_velocity_x = e_x[i] * desired_v0[i];
double desired_velocity_y = e_y[i] * desired_v0[i];
double f_alpha_dt_x = (desired_velocity_x - curr_vel_x[i]) * dt_times_tau_alpha_inv;
double f_alpha_dt_y = (desired_velocity_y - curr_vel_y[i]) * dt_times_tau_alpha_inv;
// since i is fixed for the innermost loops we now wanna set all those variables
const __m256d pix = _mm256_set1_pd(pos_x[i]);
const __m256d piy = _mm256_set1_pd(pos_y[i]);
const __m256d eix = _mm256_set1_pd(e_x[i]);
const __m256d eiy = _mm256_set1_pd(e_y[i]);
const __m256d v_i = _mm256_set1_pd((double)i);
__m256d acc_x = _mm256_setzero_pd();
__m256d acc_y = _mm256_setzero_pd();
for (int j = 0; j < n_p_pad; j += 4) {
// 4 lanes at once, lane k maps to pedestrian j+k
__m256d j_idx = _mm256_add_pd(_mm256_set1_pd((double)j), lane_off);
// active = (j+k != i) AND (j+k < n_p), zero in lanes we wanna skip
__m256d m_neq_i = _mm256_cmp_pd(j_idx, v_i, _CMP_NEQ_OQ);
__m256d m_in_range = _mm256_cmp_pd(j_idx, v_np, _CMP_LT_OQ);
__m256d active = _mm256_and_pd(m_neq_i, m_in_range);
// j-side loads, SoA contiguous. loadu because std::vector only guarantees 16B align.
__m256d pjx = _mm256_loadu_pd(&pos_x[j]);
__m256d pjy = _mm256_loadu_pd(&pos_y[j]);
__m256d sbe_jx = _mm256_loadu_pd(&sb_e_x[j]);
__m256d sbe_jy = _mm256_loadu_pd(&sb_e_y[j]);
__m256d sb_jsq = _mm256_loadu_pd(&sb_sq[j]);
// double r_ab_x = pos_x[i] - pos_x[j];
// double r_ab_y = pos_y[i] - pos_y[j];
//
// double r_ab_norm = sqrt(r_ab_x * r_ab_x + r_ab_y * r_ab_y);
// r_ab = pos_i - pos_j ; |r_ab|
__m256d r_ab_x = _mm256_sub_pd(pix, pjx);
__m256d r_ab_y = _mm256_sub_pd(piy, pjy);
__m256d r_ab_n2 = _mm256_fmadd_pd(r_ab_x, r_ab_x, _mm256_mul_pd(r_ab_y, r_ab_y));
__m256d r_ab_n = _mm256_sqrt_pd(r_ab_n2);
// double r_ab2_x = r_ab_x - sb_e_x[j];
// double r_ab2_y = r_ab_y - sb_e_y[j];
//
// double r_ab2_norm = sqrt(r_ab2_x * r_ab2_x + r_ab2_y * r_ab2_y);
// r_ab2 = r_ab - sb_e_j ; |r_ab2|
__m256d r_ab2_x = _mm256_sub_pd(r_ab_x, sbe_jx);
__m256d r_ab2_y = _mm256_sub_pd(r_ab_y, sbe_jy);
__m256d r_ab2_n2 = _mm256_fmadd_pd(r_ab2_x, r_ab2_x, _mm256_mul_pd(r_ab2_y, r_ab2_y));
__m256d r_ab2_n = _mm256_sqrt_pd(r_ab2_n2);
// double r_ab_norm_sum = r_ab_norm + r_ab2_norm;
// double two_b_sq = r_ab_norm_sum * r_ab_norm_sum - sb_sq[j];
// double two_b = sqrt(two_b_sq);
// 2b = sqrt((|r_ab| + |r_ab2|)^2 - sb_sq_j)
__m256d r_sum = _mm256_add_pd(r_ab_n, r_ab2_n);
__m256d two_b_sq = _mm256_fmsub_pd(r_sum, r_sum, sb_jsq);
__m256d two_b = _mm256_sqrt_pd(two_b_sq);
// exp scalar fallback for now, we vectorize in a later step. probably the biggest perf win left.
__m256d e_arg = _mm256_mul_pd(two_b, v_neg_2s_inv);
alignas(32) double tmp_arg[4], tmp_val[4];
_mm256_store_pd(tmp_arg, e_arg);
tmp_val[0] = exp(tmp_arg[0]);
tmp_val[1] = exp(tmp_arg[1]);
tmp_val[2] = exp(tmp_arg[2]);
tmp_val[3] = exp(tmp_arg[3]);
__m256d e_val = _mm256_load_pd(tmp_val);
// double scalar_mult_common = (r_ab_norm_sum / (two_b * r_ab_norm * r_ab2_norm)) * (NEG_V0_AB_div_TWO_SIGMA * exp(two_b * NEG_TWO_SIGMA_INV));
// smc = (r_sum * NEG_V0_AB_div_TWO_SIGMA * e_val) / (two_b * r_ab_n * r_ab2_n)
// the i==j lane collapses denom to 0, so we swap in 1.0 there to keep smc finite.
// the AND with active zeroes the contribution from that lane anyway.
__m256d numer = _mm256_mul_pd(_mm256_mul_pd(r_sum, v_neg_v0_div_2s), e_val);
__m256d denom = _mm256_mul_pd(_mm256_mul_pd(two_b, r_ab_n), r_ab2_n);
__m256d denom_safe = _mm256_blendv_pd(_mm256_set1_pd(1.0), denom, active);
__m256d smc = _mm256_div_pd(numer, denom_safe);
// double scalar_mult_r_ab = scalar_mult_common * r_ab2_norm;
// double scalar_mult_r_ab2 = scalar_mult_common * r_ab_norm;
__m256d sm_r_ab = _mm256_mul_pd(smc, r_ab2_n);
__m256d sm_r_ab2 = _mm256_mul_pd(smc, r_ab_n);
// double f_alpha_beta_neg_x = r_ab_x * scalar_mult_r_ab + r_ab2_x * scalar_mult_r_ab2;
// double f_alpha_beta_neg_y = r_ab_y * scalar_mult_r_ab + r_ab2_y * scalar_mult_r_ab2;
// scalar wants r_ab * sm_r_ab + r_ab2 * sm_r_ab2, the previous fma had the layout wrong
__m256d f_x = _mm256_fmadd_pd(r_ab2_x, sm_r_ab2, _mm256_mul_pd(r_ab_x, sm_r_ab));
__m256d f_y = _mm256_fmadd_pd(r_ab2_y, sm_r_ab2, _mm256_mul_pd(r_ab_y, sm_r_ab));
// w_val = dt_neg by default, c_neg_times_dt when (a >= 0 && a*a > b_sq)
__m256d a = _mm256_mul_pd(_mm256_fmadd_pd(eix, f_x, _mm256_mul_pd(eiy, f_y)), v_cos_phi_inv);
__m256d b_sq = _mm256_fmadd_pd(f_x, f_x, _mm256_mul_pd(f_y, f_y));
__m256d a_sq = _mm256_mul_pd(a, a);
__m256d c1 = _mm256_cmp_pd(a, v_zero, _CMP_GE_OQ);
__m256d c2 = _mm256_cmp_pd(a_sq, b_sq, _CMP_GT_OQ);
__m256d cond = _mm256_and_pd(c1, c2);
__m256d w_val = _mm256_blendv_pd(v_dt_neg, v_c_neg_dt, cond);
// zero out inactive lanes (i==j and padding) before accumulating.
// AND with all-zero mask = 0, AND with all-one mask passes through. cheaper than blendv here.
__m256d f_x_safe = _mm256_and_pd(f_x, active);
__m256d f_y_safe = _mm256_and_pd(f_y, active);
acc_x = _mm256_fmadd_pd(f_x_safe, w_val, acc_x);
acc_y = _mm256_fmadd_pd(f_y_safe, w_val, acc_y);
}
// horizontal sum acc_x, acc_y into the scalar f_alpha_dt
__m256d hsum_xy = _mm256_hadd_pd(acc_x, acc_y); // [x0+x1, y0+y1, x2+x3, y2+y3]
__m128d lo = _mm256_castpd256_pd128(hsum_xy);
__m128d hi = _mm256_extractf128_pd(hsum_xy, 1);
__m128d sum_xy = _mm_add_pd(lo, hi); // [x_total, y_total]
alignas(16) double sum_out[2];
_mm_store_pd(sum_out, sum_xy);
f_alpha_dt_x += sum_out[0];
f_alpha_dt_y += sum_out[1];
for (int k = 0; k < board.n_obstacles; k++) {
double v1_x = pos_x[i] - board.obstacles[k].start.x;
double v1_y = pos_y[i] - board.obstacles[k].start.y;
double projection = (v1_x * board.obstacles[k].obstacle_v.x + v1_y * board.obstacles[k].obstacle_v.y) * board.obstacles[k].length_sq_inv;
if (projection < 0.0)
projection = 0.0;
else if (projection > 1.0)
projection = 1.0;
double r_aB_x = pos_x[i] - (board.obstacles[k].start.x + board.obstacles[k].obstacle_v.x * projection);
double r_aB_y = pos_y[i] - (board.obstacles[k].start.y + board.obstacles[k].obstacle_v.y * projection);
double r_aB_norm = sqrt(r_aB_x * r_aB_x + r_aB_y * r_aB_y);
double scalar_mult = (NEG_U0_AB_div_R * exp(r_aB_norm * NEG_R_INV)) / r_aB_norm;
double f_alpha_B_neg_x = r_aB_x * scalar_mult;
double f_alpha_B_neg_y = r_aB_y * scalar_mult;
double w_val;
double a = (e_x[i] * f_alpha_B_neg_x + e_y[i] * f_alpha_B_neg_y) * cos_phi_inv;
double b_sq = f_alpha_B_neg_x * f_alpha_B_neg_x + f_alpha_B_neg_y * f_alpha_B_neg_y;
w_val = dt_neg;
if (a >= 0 && (a * a > b_sq)) {
w_val = c_neg_times_dt;
}
double f_alpha_B_dt_x = f_alpha_B_neg_x * w_val;
double f_alpha_B_dt_y = f_alpha_B_neg_y * w_val;
f_alpha_dt_x += f_alpha_B_dt_x;
f_alpha_dt_y += f_alpha_B_dt_y;
}
w_x[i] += f_alpha_dt_x;
w_y[i] += f_alpha_dt_y;
}
for (int i = 0; i < n_p; i++) {
double w_norm = sqrt(w_x[i] * w_x[i] + w_y[i] * w_y[i]);
double correction_factor = min(1.0, v_max[i] / w_norm);
curr_vel_x[i] = w_x[i] * correction_factor;
curr_vel_y[i] = w_y[i] * correction_factor;
pos_x[i] = pos_x[i] + curr_vel_x[i] * dt;
pos_y[i] = pos_y[i] + curr_vel_y[i] * dt;
if (color[i] == 0 && pos_x[i] > (BOARD_LENGTH - 1.5)) {
pos_x[i] = 1.0;
destination_y[i] = pos_y[i];
w_x[i] = desired_v0[i];
w_y[i] = 0.0;
curr_vel_x[i] = w_x[i];
curr_vel_y[i] = w_y[i];
}
if (color[i] == 1 && pos_x[i] < 1.5) {
pos_x[i] = BOARD_LENGTH - 1.0;
destination_y[i] = pos_y[i];
w_x[i] = -desired_v0[i];
w_y[i] = 0.0;
curr_vel_x[i] = w_x[i];
curr_vel_y[i] = w_y[i];
}
pos_y[i] = clamp(pos_y[i], WALL_EPS, BOARD_WIDTH_MINUS_WALL_EPS);
double ex = destination_x[i] - pos_x[i];
double ey = destination_y[i] - pos_y[i];
double e_norm_inv = 1.0 / sqrt(ex * ex + ey * ey);
e_x[i] = ex * e_norm_inv;
e_y[i] = ey * e_norm_inv;
double velocity_norm_sq = curr_vel_x[i] * curr_vel_x[i] + curr_vel_y[i] * curr_vel_y[i];
double velocity_norm = sqrt(velocity_norm_sq);
sb_sq[i] = velocity_norm_sq * delta_t_sq;
sb_e_x[i] = e_x[i] * (velocity_norm * delta_t);
sb_e_y[i] = e_y[i] * (velocity_norm * delta_t);
#if !BENCHMARK
if (dump_path && (t % dump_interval == 0)) {
samples.emplace_back(t + 1, i, pos_x[i], pos_y[i], e_x[i], e_y[i], color[i]);
}
#endif
}
}
#if !BENCHMARK
if (dump_path) {
ofstream out(dump_path);
out << "time,id,x,y,p.e.x,p.e.y,color\n";
for (auto &[t, id, x, y, e_x, e_y, c] : samples) {
out << t << ',' << id << ',' << x << ',' << y << ',' << e_x << ',' << e_y << ',' << c << '\n';
}
}
#endif
return 0;
}