Main.c 14.7 KB
Newer Older
1
2
3
4
#include <stdio.h>
#include <stdlib.h>
#include <mpi.h>
#include "../IOcodes/read_ini.h"
5
#include "../IOcodes/results.h"
iker_martin's avatar
iker_martin committed
6
7
#include "../malleability/ProcessDist.h"
#include "../malleability/CommDist.h"
8
9
10

#define ROOT 0

iker_martin's avatar
iker_martin committed
11
12
13
int work();
void Sons_init();

14
int checkpoint(int iter, int state, MPI_Request **comm_req);
iker_martin's avatar
iker_martin committed
15
void TC(int numS);
16
17
int start_redistribution(int numS, MPI_Request **comm_req);
int check_redistribution(int iter, MPI_Request **comm_req);
iker_martin's avatar
iker_martin committed
18

19
void iterate(double *matrix, int n, int async_comm);
20
21
22
void computeMatrix(double *matrix, int n);
void initMatrix(double **matrix, int n);

23
24
25
26
void init_group_struct(char *argv[], int myId, int numP);
void init_application();
void free_application_data();

27
void print_general_info(int myId, int grp, int numP);
28
void print_final_results();
29

iker_martin's avatar
iker_martin committed
30
31
32
33
typedef struct {
  int myId;
  int numP;
  int grp;
34
  int iter_start;
iker_martin's avatar
iker_martin committed
35
36
37

  MPI_Comm children, parents;
  char **argv;
38
  char *sync_array, *async_array;
iker_martin's avatar
iker_martin committed
39
40
41
42
} group_data;

configuration *config_file;
group_data *group;
43
results_data *results;
44

45
int main(int argc, char *argv[]) {
46
    int numP, myId, res;
47

48
    MPI_Init(&argc, &argv);
49
    MPI_Comm_size(MPI_COMM_WORLD, &numP);
iker_martin's avatar
iker_martin committed
50
51
    MPI_Comm_rank(MPI_COMM_WORLD, &myId);

52
53
    init_group_struct(argv, myId, numP);
    init_application();
iker_martin's avatar
iker_martin committed
54

55
56
57
    if(group->grp == 0) {
      MPI_Barrier(MPI_COMM_WORLD);
      results->exec_start = MPI_Wtime();
58
    }
59

60
    res = work();
61

62
63
64
    if(res) { // Se he llegado al final de la aplicacion
      MPI_Barrier(MPI_COMM_WORLD);
      results->exec_time = MPI_Wtime() - results->exec_start;
65
    }
66
67
68
    print_final_results();

    free_application_data();
69
70
71
72
73
    MPI_Finalize();
    return 0;
}

/*
74
75
76
77
78
79
80
81
82
 * Función de trabajo principal.
 *
 * Incializa los datos para realizar el computo y a continuacion
 * pasa a realizar "maxiter" iteraciones de computo.
 *
 * Terminadas las iteraciones realiza el redimensionado de procesos.
 * Si el redimensionado se realiza de forma asincrona se 
 * siguen realizando iteraciones de computo hasta que termine la 
 * comunicacion asincrona y realizar entonces la sincrona.
83
84
85
86
 *
 * Si el grupo de procesos es el ultimo que va a ejecutar, se devuelve
 * el valor 1 para indicar que no se va a seguir trabajando con nuevos grupos
 * de procesos. En caso contrario se devuelve 0.
87
 */
iker_martin's avatar
iker_martin committed
88
int work() {
89
  int iter, maxiter, state, res;
90
  double *matrix;
91
  MPI_Request *async_comm;
92

iker_martin's avatar
iker_martin committed
93
94
  maxiter = config_file->iters[group->grp];
  initMatrix(&matrix, config_file->matrix_tam);
95
  state = MAL_COMM_UNINITIALIZED;
iker_martin's avatar
iker_martin committed
96

97
  res = 0;
98
  for(iter=group->iter_start; iter < maxiter; iter++) {
99
    iterate(matrix, config_file->matrix_tam, state);
100
  }
101
  state = checkpoint(iter, state, &async_comm);
102
  
103
104
  iter = 0;
  while(state == MAL_ASYNC_PENDING) {
105
    iterate(matrix, config_file->matrix_tam, state);
106
    iter++;
107
    state = checkpoint(iter, state, &async_comm);
108
  }
109
  
110
111
  if(config_file->resizes - 1 == group->grp) res=1;
  return res;
112
113
}

114
115
116
117
118
119
120
121
/*
 * Se realiza el redimensionado de procesos por parte de los padres.
 *
 * Se crean los nuevos procesos con la distribucion fisica elegida y
 * a continuacion se transmite la informacion a los mismos.
 *
 * Si hay datos asincronos a transmitir, primero se comienza a
 * transmitir estos y se termina la funcion. Se tiene que comprobar con
122
 * llamando a la función de nuevo que se han terminado de enviar
123
124
125
126
127
128
 *
 * Si hay ademas datos sincronos a enviar, no se envian aun.
 *
 * Si solo hay datos sincronos se envian tras la creacion de los procesos
 * y finalmente se desconectan los dos grupos de procesos.
 */
129
130
131
132
133
134
135
int checkpoint(int iter, int state, MPI_Request **comm_req) {
  
  if(state == MAL_COMM_UNINITIALIZED) {
    // Comprobar si se tiene que realizar un redimensionado
    if(config_file->iters[group->grp] > iter || config_file->resizes == group->grp + 1) {return MAL_COMM_UNINITIALIZED;}

    int numS = config_file->procs[group->grp +1];
136
137

      results->spawn_start = MPI_Wtime();
138
    TC(numS);
139
      results->spawn_time[group->grp] = MPI_Wtime() - results->spawn_start;
140

141
142
143
144
145
    state = start_redistribution(numS, comm_req);

  } else if(MAL_ASYNC_PENDING) {
    state = check_redistribution(iter, comm_req);
  }
iker_martin's avatar
iker_martin committed
146

147
148
  return state;
}
iker_martin's avatar
iker_martin committed
149

150
151
152
153
154
155
156
/*
 * Se encarga de realizar la creacion de los procesos hijos.
 */
void TC(int numS){
  // Inicialización de la comunicación con SLURM
  int dist = config_file->phy_dist[group->grp +1];
  init_slurm_comm(group->argv, group->myId, numS, ROOT, dist, COMM_SPAWN_SERIAL);
iker_martin's avatar
iker_martin committed
157

158
159
160
161
162
163
164
  // Esperar a que la comunicación y creación de procesos
  // haya finalizado
  int test = -1;
  while(test != MPI_SUCCESS) {
    test = check_slurm_comm(group->myId, ROOT, MPI_COMM_WORLD, &(group->children));
  }
}
iker_martin's avatar
iker_martin committed
165

166
167
168
169
170
171
172
173
174
175
176
177
178
179
/*
 * Comienza la redistribucion de los datos con el nuevo grupo de procesos.
 *
 * Primero se envia la configuracion a utilizar al nuevo grupo de procesos y a continuacion
 * se realiza el envio asincrono y/o sincrono si lo hay.
 *
 * En caso de que haya comunicacion asincrona, se comienza y se termina la funcion 
 * indicando que se ha comenzado un envio asincrono.
 *
 * Si no hay comunicacion asincrono se pasa a realizar la sincrona si la hubiese.
 *
 * Finalmente se envian datos sobre los resultados a los hijos y se desconectan ambos
 * grupos de procesos.
 */
180
int start_redistribution(int numS, MPI_Request **comm_req) {
iker_martin's avatar
iker_martin committed
181
182
183
184
185
186
187
  int rootBcast = MPI_PROC_NULL;
  if(group->myId == ROOT) rootBcast = MPI_ROOT;

  // Enviar a los hijos que grupo de procesos son
  MPI_Bcast(&(group->grp), 1, MPI_INT, rootBcast, group->children);
  send_config_file(config_file, rootBcast, group->children);

188
  if(config_file->adr > 0) {
189
    results->async_start = MPI_Wtime();
190
191
192
    send_async(group->async_array, config_file->adr, group->myId, group->numP, ROOT, group->children, numS, comm_req, config_file->aib);
    return MAL_ASYNC_PENDING;
  } 
iker_martin's avatar
iker_martin committed
193
  if(config_file->sdr > 0) {
194
      results->sync_start = MPI_Wtime();
iker_martin's avatar
iker_martin committed
195
196
    send_sync(group->sync_array, config_file->sdr, group->myId, group->numP, ROOT, group->children, numS);
  }
197
198

  
199
  send_results(results, rootBcast, config_file->resizes, group->children);
iker_martin's avatar
iker_martin committed
200
201
202
  // Desconectar intercomunicador con los hijos
  MPI_Comm_disconnect(&(group->children));

203
  return MAL_COMM_COMPLETED;
iker_martin's avatar
iker_martin committed
204
205
}

206
207
208
209
210
211
212
213
214
215
216
217
218
/*
 * Comprueba si la redistribucion asincrona ha terminado. 
 * Si no ha terminado la funcion termina indicandolo, en caso contrario,
 * se continua con la comunicacion sincrona, el envio de resultados y
 * se desconectan los grupos de procesos.
 *
 * Esta funcion permite dos modos de funcionamiento al comprobar si la
 * comunicacion asincrona ha terminado.
 * Si se utiliza el modo "MAL_USE_NORMAL", se considera terminada cuando
 * los padres terminan de enviar.
 * Si se utiliza el modo "MAL_USE_IBARRIER", se considera terminada cuando
 * los hijos han terminado de recibir.
 */
219
220
221
222
223
224
int check_redistribution(int iter, MPI_Request **comm_req) {
  int completed, all_completed, test_err, iter_send;
  int numS = config_file->procs[group->grp +1];
  int rootBcast = MPI_PROC_NULL;
  MPI_Request *req_completed;
  if(group->myId == ROOT) rootBcast = MPI_ROOT;
iker_martin's avatar
iker_martin committed
225

226
227
  if(config_file->aib == MAL_USE_NORMAL) {
    req_completed = &(*comm_req)[0];
228
  } else { // MAL_USE_IBARRIER
229
    req_completed = &(*comm_req)[1];
iker_martin's avatar
iker_martin committed
230
  }
231
 
232
  
233
234
  test_err = MPI_Test(req_completed, &completed, MPI_STATUS_IGNORE);
  if (test_err != MPI_SUCCESS && test_err != MPI_ERR_PENDING) {
235
    printf("P%d aborting -- Test Async\n", group->myId);
236
237
238
239
    MPI_Abort(MPI_COMM_WORLD, test_err);
  }

  MPI_Allreduce(&completed, &all_completed, 1, MPI_INT, MPI_MIN, MPI_COMM_WORLD);
240
  if(!all_completed) return MAL_ASYNC_PENDING; // Continue only if asynchronous send has ended 
241
242
243
244
245

  //MPI_Wait(req_completed, MPI_STATUS_IGNORE);
  if(config_file->aib == MAL_USE_IBARRIER) {
    MPI_Wait(&(*comm_req)[0], MPI_STATUS_IGNORE); // Indicar como completado el envio asincrono
  }
246
  
247
248
  iter_send = iter;
  MPI_Bcast(&iter_send, 1, MPI_INT, rootBcast, group->children);
249
  if(config_file->sdr > 0) { // Realizar envio sincrono
250
      results->sync_start = MPI_Wtime();
251
252
    send_sync(group->sync_array, config_file->sdr, group->myId, group->numP, ROOT, group->children, numS);
  }
253
  send_results(results, rootBcast, config_file->resizes, group->children);
254
255
256

  // Desconectar intercomunicador con los hijos
  MPI_Comm_disconnect(&(group->children));
257
  free(*comm_req);
258
  return MAL_COMM_COMPLETED;
iker_martin's avatar
iker_martin committed
259
260
}

261
262
263
264
265
266
/*
 * Inicializacion de los datos de los hijos.
 * En la misma se reciben datos de los padres: La configuracion
 * de la ejecucion a realizar; y los datos a recibir de los padres
 * ya sea de forma sincrona, asincrona o ambas.
 */
iker_martin's avatar
iker_martin committed
267
268
269
270
271
272
273
274
void Sons_init() {

  // Enviar a los hijos que grupo de procesos son
  MPI_Bcast(&(group->grp), 1, MPI_INT, ROOT, group->parents);
  group->grp++;

  config_file = recv_config_file(ROOT, group->parents);
  int numP_parents = config_file->procs[group->grp -1];
275
  init_results_data(&results, config_file->resizes - 1, config_file->iters[group->grp]);
iker_martin's avatar
iker_martin committed
276

277
278
  if(config_file->adr > 0) { // Recibir datos asincronos
    recv_async(&(group->async_array), config_file->adr, group->myId, group->numP, ROOT, group->parents, numP_parents, config_file->aib);
279
      results->async_time[group->grp] = MPI_Wtime();
280
281
    MPI_Bcast(&(group->iter_start), 1, MPI_INT, ROOT, group->parents);
  }
282
  if(config_file->sdr > 0) { // Recibir datos sincronos
iker_martin's avatar
iker_martin committed
283
    recv_sync(&(group->sync_array), config_file->sdr, group->myId, group->numP, ROOT, group->parents, numP_parents);
284
    results->sync_time[group->grp] = MPI_Wtime();
iker_martin's avatar
iker_martin committed
285
  }
286
  recv_results(results, ROOT, config_file->resizes, group->parents);
287
288
  results->sync_time[group->grp]  = MPI_Wtime() - results->sync_start;
  results->async_time[group->grp] = MPI_Wtime() - results->async_start;
iker_martin's avatar
iker_martin committed
289
290
291
292
293
294
295
296
297
298
299
300
301

  // Desconectar intercomunicador con los hijos
  MPI_Comm_disconnect(&(group->parents));
}


/////////////////////////////////////////
/////////////////////////////////////////
//COMPUTE FUNCTIONS
/////////////////////////////////////////
/////////////////////////////////////////


302
303
/*
 * Simula la ejecucción de una iteración de computo en la aplicación
304
 * que dura al menos un tiempo de "time" segundos.
305
 */
306
void iterate(double *matrix, int n, int async_comm) {
307
  double start_time, actual_time;
iker_martin's avatar
iker_martin committed
308
  double time = config_file->general_time * config_file->factors[group->grp];
309
  int i, operations = 0;
310
311

  start_time = actual_time = MPI_Wtime();
312
313
  if(async_comm == MAL_ASYNC_PENDING) { // Se esta realizando una redistribucion de datos asincrona
    operations = results->iters_type[config_file->iters[group->grp] - 1];
314
315
316
317
318
319
    for (i=0; i<operations; i++) {
      computeMatrix(matrix, n);
      actual_time = MPI_Wtime(); // Guardar tiempos
    }
    operations = 0;

320
  } else { // No hay redistribucion de datos actualmente	  
321
322
323
324
325
    while (actual_time - start_time < time) {
      computeMatrix(matrix, n);
      operations++;
      actual_time = MPI_Wtime(); // Guardar tiempos
    }
326
  }
327

328
329
330
  results->iters_time[results->iter_index] = actual_time - start_time;
  results->iters_type[results->iter_index] = operations;
  results->iter_index = results->iter_index + 1;
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
}

/*
 * Realiza una multiplicación de matrices de tamaño n
 */
void computeMatrix(double *matrix, int n) {
  int row, col, i, aux;

  for(row=0; i<n; row++) {
    /* COMPUTE */
    for(col=0; col<n; col++) {
      aux=0;
      for(i=0; i<n; i++) {
        aux += matrix[row*n + i] * matrix[i*n + col];
      }
    }
  }
}

/*
 * Init matrix
 */
void initMatrix(double **matrix, int n) {
  int i, j;

  // Init matrix
  if(matrix != NULL) {
    *matrix = malloc(n * n * sizeof(double));
    if(*matrix == NULL) { MPI_Abort(MPI_COMM_WORLD, -1);}
    for(i=0; i < n; i++) {
      for(j=0; j < n; j++) {
        (*matrix)[i*n + j] = i+j;
      }
    }
  }
}
367
368
369

//======================================================||
//======================================================||
370
//=============INIT/FREE/PRINT FUNCTIONS================||
371
372
373
//======================================================||
//======================================================||

374
375
376
377
/*
 * Muestra datos generales sobre los procesos, su grupo,
 * en que nodo residen y la version de MPI utilizada.
 */
378
379
380
381
382
383
384
385
386
387
388
389
void print_general_info(int myId, int grp, int numP) {
  int len;
  char *name = malloc(MPI_MAX_PROCESSOR_NAME * sizeof(char));
  char *version = malloc(MPI_MAX_LIBRARY_VERSION_STRING * sizeof(char));
  MPI_Get_processor_name(name, &len);
  MPI_Get_library_version(version, &len);
  printf("P%d Nuevo GRUPO %d de %d procs en nodo %s con %s\n", myId, grp, numP, name, version);

  free(name);
  free(version);
}

390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
 * Pide al proceso raiz imprimir los datos sobre las iteraciones realizadas por el grupo de procesos.
 *
 * Si es el ultimo grupo de procesos, muestra los datos obtenidos de tiempo de ejecucion, creacion de procesos
 * y las comunicaciones.
 */
void print_final_results() {
  if(group->myId == ROOT) {
    print_config_group(config_file, group->grp);
    print_iter_results(results, config_file->iters[group->grp] -1);

    if(group->grp == config_file->resizes -1) {
      print_config(config_file, group->grp);
      print_global_results(results, config_file->resizes);
    }
  }
}

/*
 * Inicializa la estructura group
 */
void init_group_struct(char *argv[], int myId, int numP) {
  group = malloc(1 * sizeof(group_data));
  group->myId        = myId;
  group->numP        = numP;
  group->grp         = 0;
  group->iter_start  = 0;
  group->argv        = argv;
}
419

420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
/*
 * Inicializa los datos para este grupo de procesos.
 *
 * En caso de ser el primer grupo de procesos, lee el fichero de configuracion
 * e inicializa los vectores de comunicacion.
 *
 * En caso de ser otro grupo de procesos entra a la funcion "Sons_init()" donde
 * se comunican con los padres para inicializar sus datos.
 */
void init_application() {
  MPI_Comm_get_parent(&(group->parents));
  if(group->parents != MPI_COMM_NULL ) { // Si son procesos hijos deben comunicarse con las padres
    Sons_init();
  } else { // Si son el primer grupo de procesos, recogen la configuracion inicial
    config_file = read_ini_file(group->argv[1]);
    init_results_data(&results, config_file->resizes, config_file->iters[group->grp]);
    if(config_file->sdr > 0) {
      malloc_comm_array(&(group->sync_array), config_file->sdr , group->myId, group->numP);
    }
    if(config_file->adr > 0) {
      malloc_comm_array(&(group->async_array), config_file->adr , group->myId, group->numP);
    }
  }
}

/*
 * Libera toda la memoria asociada con la aplicacion
 */
void free_application_data() {
  if(config_file->sdr > 0) {
    free(group->sync_array);
  }
  if(config_file->adr > 0) {
    free(group->async_array);
  }
  free(group);
  free_config(config_file);
  free_results_data(&results);
}