|
| 1 | +#include <stdio.h> |
| 2 | +#include <stdlib.h> |
| 3 | +#include <sys/time.h> |
| 4 | +#include <stdlib.h> |
| 5 | +#include <math.h> |
| 6 | +#include <assert.h> |
| 7 | + |
| 8 | +float tdiff(struct timeval *start, struct timeval *end) { |
| 9 | + return (end->tv_sec-start->tv_sec) + 1e-6*(end->tv_usec-start->tv_usec); |
| 10 | +} |
| 11 | + |
| 12 | +__attribute__((const,noinline)) |
| 13 | +double mag(const double *A, int n) { |
| 14 | + double amt = 0; |
| 15 | + for(int i=0; i<n; i++) amt += A[i]; |
| 16 | + return amt; |
| 17 | +} |
| 18 | + |
| 19 | +void normalize(double *__restrict__ out, const double *__restrict__ in, int n) { |
| 20 | + for(int i = 0; i < n; ++i) |
| 21 | + out[i] = in[i] / mag(in, n); |
| 22 | +} |
| 23 | + |
| 24 | +void __enzyme_autodiff(void*, ...); |
| 25 | +int enzyme_const, enzyme_dup, enzyme_out; |
| 26 | + |
| 27 | +int main(int argc, char *argv[]) { |
| 28 | + struct timeval start, end; |
| 29 | + int n = 1000000; |
| 30 | + int x = 20; |
| 31 | + if (argc > 1) { |
| 32 | + n = atoi(argv[1]); |
| 33 | + if (argc > 2) { |
| 34 | + x = atoi(argv[2]); |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + double *A = (double*)malloc(sizeof(double) * n); |
| 39 | + assert(A != 0); |
| 40 | + |
| 41 | + double *B = (double*)malloc(sizeof(double) * n); |
| 42 | + assert(B != 0); |
| 43 | + for(int i=0; i<n; i++) |
| 44 | + B[i] = x; |
| 45 | + |
| 46 | + |
| 47 | + double *grad_A = (double*)malloc(sizeof(double) * n); |
| 48 | + assert(grad_A != 0); |
| 49 | + for(int i = 0; i < n; i++) |
| 50 | + grad_A[i] = 1.0; |
| 51 | + |
| 52 | + double *grad_B = (double*)malloc(sizeof(double) * n); |
| 53 | + assert(grad_B != 0); |
| 54 | + for(int i = 0; i < n; i++) |
| 55 | + grad_B[i] = 0.0; |
| 56 | + |
| 57 | + |
| 58 | + gettimeofday(&start, NULL); |
| 59 | + |
| 60 | + normalize(A, B, n); |
| 61 | + |
| 62 | + gettimeofday(&end, NULL); |
| 63 | + printf("Serial Normalize %0.6f %f\n", tdiff(&start, &end), A[n-1]); |
| 64 | + |
| 65 | + gettimeofday(&start, NULL); |
| 66 | + |
| 67 | + __enzyme_autodiff((void*)normalize, |
| 68 | + enzyme_dup, A, grad_A, |
| 69 | + enzyme_dup, B, grad_B, |
| 70 | + enzyme_const, n); |
| 71 | + |
| 72 | + gettimeofday(&end, NULL); |
| 73 | + printf("Gradient Normalize %0.6f %f %f\n", tdiff(&start, &end), A[n-1], grad_B[0]); |
| 74 | + |
| 75 | + free(A); |
| 76 | + free(B); |
| 77 | + return 0; |
| 78 | +} |
0 commit comments