Visualizzazione post con etichetta SIMD. Mostra tutti i post
Visualizzazione post con etichetta SIMD. Mostra tutti i post

mercoledì 14 ottobre 2026

SIMD Mandelbrot

 E' tempo che si legge per la scheda tecnica dei processori la presenza di SIMD, SSE, AVX ma non avevo mai capito come voleva dire.


 

In sintesi si tratta di comandi assembler che permettono di effettuare funzioni matematiche su piu' di un valore numerico contemporaneamente....in pratica si puo' avere un registro a 128 bit, caricarlo con 4 float a 32 bit ed effettuare in solo ciclo una operazione matematica

Per vedere le capacita' del proprio processore si puo' lanciare il comando 

cat /proc/cpuinfo | grep -m 1 'flags'
flags        : fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault pti ssbd ibrs ibpb stibp tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp vnmi md_clear flush_l1d arch_capabilities
 

Una lane SIMD SSE e' larga 128 bit mentre una AVX/AVX2 ha 256 bit 

Ovviamente invece di usare 4 float 32 bit  in SSE si possono inserire 16 int da 8 bit sempre nello stesso registro SSE

Questo funziona a livello di singolo core...usando OpenMP si puo' parallelizzare in modo ancora piu' spinto dividendo il lavoro su ogni core disponibile del processore  (si puo' vedere usando lscpu)

 

// Mandelbrot con AVX-512 (8 double per registro) o AVX2 (4 double).
//
// Compilazione:
// gcc -O2 -mavx512f mandel_simd.c -o mandel_simd (SIMD 512-bit / 8 lane)
// gcc -O2 -mavx2 mandel_simd.c -o mandel_simd (SIMD 256-bit / 4 lane)
// gcc -O2 -mavx512f -fopenmp mandel_simd.c -o mandel_simd (SIMD + thread)
//
// Output: mandel.pgm (immagine in scala di grigi) e i tempi a schermo.

#include <immintrin.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

// Se AVX512 è attivo usiamo 8 lane, altrimenti fallback a 4 lane (AVX2)
#ifdef __AVX512F__
#define LANES 8
typedef __m512d vdf_t;
#define V_SET1(x) _mm512_set1_pd(x)
#define V_SETZERO() _mm512_setzero_pd()
#define V_ADD(a, b) _mm512_add_pd(a, b)
#define V_SUB(a, b) _mm512_sub_pd(a, b)
#define V_MUL(a, b) _mm512_mul_pd(a, b)
#define V_AND(a, b) _mm512_and_pd(a, b)
#define V_STORE(p, v) _mm512_storeu_pd(p, v)
#define V_MOVEMASK(m) (_mm512_cmp_pd_mask(m, _mm512_setzero_pd(), _CMP_NEQ_OQ)) // o equivalente maschera
// Per AVX-512 le maschere di confronto restituiscono direttamente un intero di bit mask:
#else
#define LANES 4
typedef __m256d vdf_t;
#define V_SET1(x) _mm256_set1_pd(x)
#define V_SETZERO() _mm256_setzero_pd()
#define V_ADD(a, b) _mm256_add_pd(a, b)
#define V_SUB(a, b) _mm256_sub_pd(a, b)
#define V_MUL(a, b) _mm256_mul_pd(a, b)
#define V_AND(a, b) _mm256_and_pd(a, b)
#define V_STORE(p, v) _mm256_storeu_pd(p, v)
#endif

#define W 1200 // deve essere multiplo di LANES (8 o 4)
#define H 800
#define MAX_ITER 500

static const double X_MIN = -2.5, X_MAX = 1.0;
static const double Y_MIN = -1.0, Y_MAX = 1.0;

static double now(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}

// ---------------------------------------------------------------- scalare
static int mandel_scalar(double cr, double ci) {
double zr = 0.0, zi = 0.0;
int n = 0;
while (n < MAX_ITER && zr * zr + zi * zi <= 4.0) {
double t = zr * zr - zi * zi + cr;
zi = 2.0 * zr * zi + ci;
zr = t;
n++;
}
return n;
}

static void render_scalar(int *img) {
double dx = (X_MAX - X_MIN) / W;
double dy = (Y_MAX - Y_MIN) / H;
for (int y = 0; y < H; y++)
for (int x = 0; x < W; x++)
img[y * W + x] = mandel_scalar(X_MIN + x * dx, Y_MIN + y * dy);
}

// ------------------------------------------------------------------- SIMD
static void render_simd(int *img) {
const double dx = (X_MAX - X_MIN) / W;
const double dy = (Y_MAX - Y_MIN) / H;

#ifdef __AVX512F__
const vdf_t vdx = _mm512_set1_pd(dx);
const vdf_t vxmin = _mm512_set1_pd(X_MIN);
const vdf_t four = _mm512_set1_pd(4.0);
const vdf_t two = _mm512_set1_pd(2.0);
const vdf_t one = _mm512_set1_pd(1.0);

#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < H; y++) {
vdf_t ci = _mm512_set1_pd(Y_MIN + y * dy);

for (int x = 0; x < W; x += LANES) {
vdf_t idx = _mm512_set_pd(x+7, x+6, x+5, x+4, x+3, x+2, x+1, x+0);
vdf_t cr = _mm512_add_pd(vxmin, _mm512_mul_pd(idx, vdx));

vdf_t zr = _mm512_setzero_pd();
vdf_t zi = _mm512_setzero_pd();
vdf_t count = _mm512_setzero_pd();

for (int n = 0; n < MAX_ITER; n++) {
vdf_t zr2 = _mm512_mul_pd(zr, zr);
vdf_t zi2 = _mm512_mul_pd(zi, zi);

vdf_t mag = _mm512_add_pd(zr2, zi2);
__mmask8 mask = _mm512_cmp_pd_mask(mag, four, _CMP_LE_OQ);

if (mask == 0)
break;

// Converte la maschera di bit in vettoriale per le operazioni logiche
vdf_t vmask = _mm512_castsi512_pd(_mm512_mask_set1_epi64(_mm512_setzero_si512(), mask, -1));
count = _mm512_add_pd(count, _mm512_and_pd(vmask, one));

vdf_t new_zi = _mm512_add_pd(
_mm512_mul_pd(two, _mm512_mul_pd(zr, zi)), ci);
zr = _mm512_add_pd(_mm512_sub_pd(zr2, zi2), cr);
zi = new_zi;
}

double tmp[LANES];
_mm512_storeu_pd(tmp, count);
for (int k = 0; k < LANES; k++)
img[y * W + x + k] = (int)tmp[k];
}
}
#else
// Versione AVX2 a 4 lane (come l'originale ma strutturata con macro)
const vdf_t vdx = V_SET1(dx);
const vdf_t vxmin = V_SET1(X_MIN);
const vdf_t four = V_SET1(4.0);
const vdf_t two = V_SET1(2.0);
const vdf_t one = V_SET1(1.0);

#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < H; y++) {
vdf_t ci = V_SET1(Y_MIN + y * dy);

for (int x = 0; x < W; x += LANES) {
__m256d idx = _mm256_set_pd(x + 3, x + 2, x + 1, x + 0);
vdf_t cr = V_ADD(vxmin, V_MUL(idx, vdx));

vdf_t zr = V_SETZERO();
vdf_t zi = V_SETZERO();
vdf_t count = V_SETZERO();

for (int n = 0; n < MAX_ITER; n++) {
vdf_t zr2 = V_MUL(zr, zr);
vdf_t zi2 = V_MUL(zi, zi);

vdf_t mag = V_ADD(zr2, zi2);
__m256d mask = _mm256_cmp_pd(mag, four, _CMP_LE_OQ);

if (_mm256_movemask_pd(mask) == 0)
break;

count = V_ADD(count, V_AND(mask, one));

vdf_t new_zi = V_ADD(
V_MUL(two, V_MUL(zr, zi)), ci);
zr = V_ADD(V_SUB(zr2, zi2), cr);
zi = new_zi;
}

double tmp[LANES];
V_STORE(tmp, count);
for (int k = 0; k < LANES; k++)
img[y * W + x + k] = (int)tmp[k];
}
}
#endif
}

// ------------------------------------------------------------------- main
static void save_pgm(const char *name, const int *img) {
FILE *f = fopen(name, "wb");
if (!f) { perror("fopen"); return; }
fprintf(f, "P5\n%d %d\n255\n", W, H);
for (int i = 0; i < W * H; i++) {
unsigned char p = (img[i] >= MAX_ITER)
? 0
: (unsigned char)(255.0 * sqrt((double)img[i] / MAX_ITER));
fputc(p, f);
}
fclose(f);
}

int main(void) {
int *img_s = malloc(sizeof(int) * W * H);
int *img_v = malloc(sizeof(int) * W * H);

double t0 = now();
render_scalar(img_s);
double t1 = now();
render_simd(img_v);
double t2 = now();

int diff = 0;
for (int i = 0; i < W * H; i++)
if (img_s[i] != img_v[i]) diff++;

printf("Immagine %dx%d, max_iter=%d (Lane SIMD: %d)\n", W, H, MAX_ITER, LANES);
printf("Scalare : %.3f s\n", t1 - t0);
printf("SIMD : %.3f s (speedup %.2fx)\n", t2 - t1, (t1 - t0) / (t2 - t1));
printf("Pixel diversi tra le due versioni: %d\n", diff);

save_pgm("mandel.pgm", img_v);
printf("Salvato mandel.pgm\n");

free(img_s);
free(img_v);
return 0;
}

 

solo SSE

// Mandelbrot con SSE2 (2 double per registro, senza AVX2)
#include <immintrin.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

#define W 1200 // deve essere multiplo di 2
#define H 800
#define MAX_ITER 500

static const double X_MIN = -2.5, X_MAX = 1.0;
static const double Y_MIN = -1.0, Y_MAX = 1.0;

static double now(void) {
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return ts.tv_sec + ts.tv_nsec * 1e-9;
}

// ---------------------------------------------------------------- scalare
static int mandel_scalar(double cr, double ci) {
double zr = 0.0, zi = 0.0;
int n = 0;
while (n < MAX_ITER && zr * zr + zi * zi <= 4.0) {
double t = zr * zr - zi * zi + cr;
zi = 2.0 * zr * zi + ci;
zr = t;
n++;
}
return n;
}

static void render_scalar(int *img) {
double dx = (X_MAX - X_MIN) / W;
double dy = (Y_MAX - Y_MIN) / H;
for (int y = 0; y < H; y++)
for (int x = 0; x < W; x++)
img[y * W + x] = mandel_scalar(X_MIN + x * dx, Y_MIN + y * dy);
}

// ------------------------------------------------------------------- SIMD (SSE2 - 2 lane)
static void render_simd(int *img) {
const double dx = (X_MAX - X_MIN) / W;
const double dy = (Y_MAX - Y_MIN) / H;

const __m128d vdx = _mm_set1_pd(dx);
const __m128d vxmin = _mm_set1_pd(X_MIN);
const __m128d four = _mm_set1_pd(4.0);
const __m128d two = _mm_set1_pd(2.0);
const __m128d one = _mm_set1_pd(1.0);

#pragma omp parallel for schedule(dynamic, 1)
for (int y = 0; y < H; y++) {
__m128d ci = _mm_set1_pd(Y_MIN + y * dy);

for (int x = 0; x < W; x += 2) {
__m128d idx = _mm_set_pd(x + 1, x + 0);
__m128d cr = _mm_add_pd(vxmin, _mm_mul_pd(idx, vdx));

__m128d zr = _mm_setzero_pd();
__m128d zi = _mm_setzero_pd();
__m128d count = _mm_setzero_pd();

for (int n = 0; n < MAX_ITER; n++) {
__m128d zr2 = _mm_mul_pd(zr, zr);
__m128d zi2 = _mm_mul_pd(zi, zi);

__m128d mag = _mm_add_pd(zr2, zi2);
// SSE2 non ha un confronto diretto con _CMP_LE_OQ come AVX, usiamo _mm_cmple_pd
__m128d mask = _mm_cmple_pd(mag, four);

if (_mm_movemask_pd(mask) == 0)
break;

count = _mm_add_pd(count, _mm_and_pd(mask, one));

__m128d new_zi = _mm_add_pd(
_mm_mul_pd(two, _mm_mul_pd(zr, zi)), ci);
zr = _mm_add_pd(_mm_sub_pd(zr2, zi2), cr);
zi = new_zi;
}

double tmp[2];
_mm_storeu_pd(tmp, count);
for (int k = 0; k < 2; k++)
img[y * W + x + k] = (int)tmp[k];
}
}
}

// ------------------------------------------------------------------- main
static void save_pgm(const char *name, const int *img) {
FILE *f = fopen(name, "wb");
if (!f) { perror("fopen"); return; }
fprintf(f, "P5\n%d %d\n255\n", W, H);
for (int i = 0; i < W * H; i++) {
unsigned char p = (img[i] >= MAX_ITER)
? 0
: (unsigned char)(255.0 * sqrt((double)img[i] / MAX_ITER));
fputc(p, f);
}
fclose(f);
}

int main(void) {
int *img_s = malloc(sizeof(int) * W * H);
int *img_v = malloc(sizeof(int) * W * H);

double t0 = now();
render_scalar(img_s);
double t1 = now();
render_simd(img_v);
double t2 = now();

int diff = 0;
for (int i = 0; i < W * H; i++)
if (img_s[i] != img_v[i]) diff++;

printf("Immagine %dx%d, max_iter=%d (SSE2 - 2 lane)\n", W, H, MAX_ITER);
printf("Scalare : %.3f s\n", t1 - t0);
printf("SIMD : %.3f s (speedup %.2fx)\n", t2 - t1, (t1 - t0) / (t2 - t1));
printf("Pixel diversi tra le due versioni: %d\n", diff);

save_pgm("mandel.pgm", img_v);
printf("Salvato mandel.pgm\n");

free(img_s);
free(img_v);
return 0;
}


 

 

 

 

 

SIMD Mandelbrot

 E' tempo che si legge per la scheda tecnica dei processori la presenza di SIMD, SSE, AVX ma non avevo mai capito come voleva dire.   In...