forked from formal-verification-research/ParallelFGSM
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparallel_fgsm.cu
70 lines (66 loc) · 1.41 KB
/
parallel_fgsm.cu
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
__global__ void fill_with(
float *res,
float *gradsign,
int len,
int num_fill
)
{
int resIdx = blockDim.x * blockIdx.x + threadIdx.x;
int gradIdx = resIdx % len;
if (resIdx < num_fill * len)
{
res[resIdx] = gradsign[gradIdx];
}
}
__global__ void mult_vec_seg(
float *res,
float *epsilon,
int len,
int num_fill
)
{
int resIdx = blockDim.x * blockIdx.x + threadIdx.x;
int epsIdx = resIdx / len;
if (resIdx < num_fill * len)
{
res[resIdx] *= epsilon[epsIdx];
}
}
__global__ void add_vec_seg_clip(
float *res,
float *x,
int len,
int num_fill,
float clip_min,
float clip_max
)
{
int resIdx = blockDim.x * blockIdx.x + threadIdx.x;
int xIdx = resIdx % len;
if (resIdx < num_fill * len)
{
res[resIdx] += x[xIdx];
if(res[resIdx] < clip_min) res[resIdx] = clip_min;
if(res[resIdx] > clip_max) res[resIdx] = clip_max;
}
}
__global__ void gen_examples_fgsm(
float *res,
float *x,
float *gradsign,
float *epsilon,
int num_examples,
int len_example
)
{
int idx = blockIdx.x * blockDim.x + threadIdx.x;
if (idx == 0)
{
int res_len = len_example*num_examples;
fill_with<<<res_len, 1>>>(res, gradsign, len_example, num_examples);
cudaDeviceSynchronize();
mult_vec_seg<<<res_len, 1>>>(res, epsilon, len_example, num_examples);
cudaDeviceSynchronize();
add_vec_seg_clip<<<res_len, 1>>>(res, x, len_example, num_examples, 0.0, 1.0);
}
}