summation.cxx 55.1 KB
Newer Older
1
#include "summation.h"
2 3 4 5 6 7 8 9
#include "../scaling/strp_tsr.h"
#include "../mapping/mapping.h"
#include "../mapping/distribution.h"
#include "../tensor/untyped_tensor.h"
#include "../shared/util.h"
#include "../shared/memcontrol.h"
#include "sym_seq_sum.h"
#include "sum_tsr.h"
10 11
#include "../symmetry/sym_indices.h"
#include "../symmetry/symmetrization.h"
12
#include "../redistribution/nosym_transp.h"
13
#include "../redistribution/redist.h"
solomon's avatar
solomon committed
14
#include "../scaling/scaling.h"
15 16 17

namespace CTF_int {

18 19
  using namespace CTF;

20
  summation::~summation(){
21 22
    if (idx_A != NULL) cfree(idx_A);
    if (idx_B != NULL) cfree(idx_B);
23 24
  }

solomon's avatar
solomon committed
25
  summation::summation(summation const & other){
26
    A     = other.A;
27
    idx_A = (int*)alloc(sizeof(int)*other.A->order);
28
    memcpy(idx_A, other.idx_A, sizeof(int)*other.A->order);
29
    B     = other.B;
30
    idx_B = (int*)alloc(sizeof(int)*other.B->order);
31
    memcpy(idx_B, other.idx_B, sizeof(int)*other.B->order);
solomon's avatar
solomon committed
32
    if (other.is_custom){
33
      func      = other.func;
solomon's avatar
solomon committed
34
      is_custom = 1;
35 36 37
    } else is_custom = 0; 
    alpha = other.alpha;
    beta  = other.beta;
solomon's avatar
solomon committed
38 39
  }

40 41 42 43 44 45 46 47 48
  summation::summation(tensor *     A_,
                       int const *  idx_A_,
                       char const * alpha_,
                       tensor *     B_,
                       int const *  idx_B_,
                       char const * beta_){
    A         = A_;
    alpha     = alpha_;
    B         = B_;
49 50 51
    beta      = beta_;
    is_custom = 0;

52 53
    idx_A     = (int*)alloc(sizeof(int)*A->order);
    idx_B     = (int*)alloc(sizeof(int)*B->order);
54 55

    memcpy(idx_A, idx_A_, sizeof(int)*A->order);
56
    memcpy(idx_B, idx_B_, sizeof(int)*B->order);
57 58 59 60 61 62 63 64 65 66 67
  }

  summation::summation(tensor *     A_,
                       char const * cidx_A,
                       char const * alpha_,
                       tensor *     B_,
                       char const * cidx_B,
                       char const * beta_){
    A         = A_;
    alpha     = alpha_;
    B         = B_;
68
    beta      = beta_;
69
    is_custom = 0;
70 71
    
    conv_idx(A->order, cidx_A, &idx_A, B->order, cidx_B, &idx_B);
72
  }
73

74
 
75 76
  summation::summation(tensor *        A_,
                       int const *     idx_A_,
77
                       char const *    alpha_,
78 79
                       tensor *        B_,
                       int const *     idx_B_,
80
                       char const *    beta_,
81 82
                       univar_function func_){
    A         = A_;
83
    alpha     = alpha_;
84
    B         = B_;
85 86 87 88
    beta      = beta_;
    func      = func_;
    is_custom = 1;

89 90
    idx_A     = (int*)alloc(sizeof(int)*A->order);
    idx_B     = (int*)alloc(sizeof(int)*B->order);
91 92

    memcpy(idx_A, idx_A_, sizeof(int)*A->order);
93
    memcpy(idx_B, idx_B_, sizeof(int)*B->order);
94 95 96 97 98 99 100 101 102 103 104 105 106
  }

 
  summation::summation(tensor *        A_,
                       char const *    cidx_A,
                       char const *    alpha_,
                       tensor *        B_,
                       char const *    cidx_B,
                       char const *    beta_,
                       univar_function func_){
    A         = A_;
    alpha     = alpha_;
    B         = B_;
107
    beta      = beta_;
108
    func      = func_;
109
    is_custom = 1;
110 111

    conv_idx(A->order, cidx_A, &idx_A, B->order, cidx_B, &idx_B);
112 113
  }

114 115
  void summation::execute(bool run_diag){
    int stat = home_sum_tsr(run_diag);
116 117 118 119 120 121 122 123
    assert(stat == SUCCESS); 
  }
  
  double summation::estimate_time(){
    assert(0); //FIXME
    return 0.0;
  }

124 125
  void summation::get_fold_indices(int *  num_fold,
                                   int ** fold_idx){
126 127 128
    int i, in, num_tot, nfold, broken;
    int iA, iB, inA, inB, iiA, iiB;
    int * idx_arr, * idx;
129 130
    inv_idx(A->order, idx_A,
            B->order, idx_B,
131
            &num_tot, &idx_arr);
132
    CTF_int::alloc_ptr(num_tot*sizeof(int), (void**)&idx);
133 134 135 136 137

    for (i=0; i<num_tot; i++){
      idx[i] = 1;
    }
    
138
    for (iA=0; iA<A->order; iA++){
139 140
      i      = idx_A[iA];
      iB     = idx_arr[2*i+1];
141
      broken = 0;
142
      inA    = iA;
143
      do {
144
        in = idx_A[inA];
145 146 147
        inB = idx_arr[2*in+1];
        if (((inA>=0) + (inB>=0) != 2) ||
            (iB != -1 && inB - iB != in-i) ||
148
            (iB != -1 && A->sym[inA] != B->sym[inB])){
149 150 151
          broken = 1;
        }
        inA++;
152
      } while (A->sym[inA-1] != NS);
153 154
      if (broken){
        for (iiA=iA;iiA<inA;iiA++){
155
          idx[idx_A[iiA]] = 0;
156 157 158 159
        }
      }
    }

160
    for (iB=0; iB<B->order; iB++){
161 162
      i      = idx_B[iB];
      iA     = idx_arr[2*i+0];
163
      broken = 0;
164
      inB    = iB;
165
      do {
166
        in = idx_B[inB];
167 168 169
        inA = idx_arr[2*in+0];
        if (((inB>=0) + (inA>=0) != 2) ||
            (iA != -1 && inA - iA != in-i) ||
170
            (iA != -1 && B->sym[inB] != A->sym[inA])){
171 172 173
          broken = 1;
        }
        inB++;
174
      } while (B->sym[inB-1] != NS);
175 176
      if (broken){
        for (iiB=iB;iiB<inB;iiB++){
177
          idx[idx_B[iiB]] = 0;
178 179 180 181 182 183 184 185 186 187 188 189 190 191
        }
      }
    }
    

    nfold = 0;
    for (i=0; i<num_tot; i++){
      if (idx[i] == 1){
        idx[nfold] = i;
        nfold++;
      }
    }
    *num_fold = nfold;
    *fold_idx = idx;
192
    CTF_int::cfree(idx_arr);
193 194 195 196
  }

  int summation::can_fold(){
    int i, j, nfold, * fold_idx;
197 198 199
    for (i=0; i<A->order; i++){
      for (j=i+1; j<A->order; j++){
        if (idx_A[i] == idx_A[j]) return 0;
200 201
      }
    }
202 203 204
    for (i=0; i<B->order; i++){
      for (j=i+1; j<B->order; j++){
        if (idx_B[i] == idx_B[j]) return 0;
205 206
      }
    }
207
    get_fold_indices(&nfold, &fold_idx);
208
    CTF_int::cfree(fold_idx);
209 210 211 212
    /* FIXME: 1 folded index is good enough for now, in the future model */
    return nfold > 0;
  }

213 214 215 216 217 218 219 220 221 222 223
  int summation::map_fold(){
    int i, j, nfold, nf, all_fdim_A, all_fdim_B;
    int nvirt_A, nvirt_B;
    int * fold_idx, * fidx_map_A, * fidx_map_B;
    int * fnew_ord_A, * fnew_ord_B;
    int * all_flen_A, * all_flen_B;
    tensor * ftsr_A, * ftsr_B;
    int inr_stride;

    get_fold_indices(&nfold, &fold_idx);
    if (nfold == 0){
224
      CTF_int::cfree(fold_idx);
225 226 227 228
      return ERROR;
    }

    /* overestimate this space to not bother with it later */
229 230
    CTF_int::alloc_ptr(nfold*sizeof(int), (void**)&fidx_map_A);
    CTF_int::alloc_ptr(nfold*sizeof(int), (void**)&fidx_map_B);
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259


    A->fold(nfold, fold_idx, idx_A, 
            &all_fdim_A, &all_flen_A);
    B->fold(nfold, fold_idx, idx_B, 
            &all_fdim_B, &all_flen_B);

    nf = 0;
    for (i=0; i<A->order; i++){
      for (j=0; j<nfold; j++){
        if (A->sym[i] == NS && idx_A[i] == fold_idx[j]){
          fidx_map_A[nf] = j;
          nf++;
        }
      }
    }
    nf = 0;
    for (i=0; i<B->order; i++){
      for (j=0; j<nfold; j++){
        if (B->sym[i] == NS && idx_B[i] == fold_idx[j]){
          fidx_map_B[nf] = j;
          nf++;
        }
      }
    }

    ftsr_A = A->rec_tsr;
    ftsr_B = B->rec_tsr;

260
    int * sidx_A, * sidx_B;
261
    CTF_int::conv_idx<int>(ftsr_A->order, fidx_map_A, &sidx_A,
262
                       ftsr_B->order, fidx_map_B, &sidx_B);
263

264
    summation fold_sum(A->rec_tsr, sidx_A, alpha, B->rec_tsr, sidx_B, beta);
265 266
    cfree(sidx_A);
    cfree(sidx_B);
267
  #if DEBUG>=2
268
    if (A->wrld->rank == 0){
269 270
      printf("Folded summation type:\n");
    }
271
    fold_sum.print();//print_sum(&fold_type,0.0,0.0);
272 273 274
  #endif
   
    //for type order 1 to 3 
275
    fold_sum.get_len_ordering(&fnew_ord_A, &fnew_ord_B); 
solomon's avatar
solomon committed
276 277
    permute_target(ftsr_A->order, fnew_ord_A, A->inner_ordering);
    permute_target(ftsr_B->order, fnew_ord_B, B->inner_ordering);
278 279
    

solomon's avatar
solomon committed
280
    nvirt_A = A->calc_nvirt();
281
    for (i=0; i<nvirt_A; i++){
solomon's avatar
solomon committed
282
      nosym_transpose(all_fdim_A, A->inner_ordering, all_flen_A, 
283
                      A->data + A->sr->el_size*i*(A->size/nvirt_A), 1, A->sr);
284
    }
solomon's avatar
solomon committed
285
    nvirt_B = B->calc_nvirt();
286
    for (i=0; i<nvirt_B; i++){
solomon's avatar
solomon committed
287
      nosym_transpose(all_fdim_B, B->inner_ordering, all_flen_B, 
288
                      B->data + B->sr->el_size*i*(B->size/nvirt_B), 1, B->sr);
289 290 291 292
    }

    inr_stride = 1;
    for (i=0; i<ftsr_A->order; i++){
solomon's avatar
solomon committed
293
      inr_stride *= ftsr_A->pad_edge_len[i];
294 295
    }

296 297 298 299 300 301 302
    CTF_int::cfree(fidx_map_A);
    CTF_int::cfree(fidx_map_B);
    CTF_int::cfree(fnew_ord_A);
    CTF_int::cfree(fnew_ord_B);
    CTF_int::cfree(all_flen_A);
    CTF_int::cfree(all_flen_B);
    CTF_int::cfree(fold_idx);
303

solomon's avatar
solomon committed
304
    return inr_stride; 
305 306
  }

307 308
  void summation::get_len_ordering(int ** new_ordering_A,
                                   int ** new_ordering_B){
309 310 311
    int i, num_tot;
    int * ordering_A, * ordering_B, * idx_arr;
    
312 313
    CTF_int::alloc_ptr(sizeof(int)*A->order, (void**)&ordering_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order, (void**)&ordering_B);
314

315 316
    inv_idx(A->order, idx_A,
            B->order, idx_B,
317 318 319 320 321
            &num_tot, &idx_arr);
    for (i=0; i<num_tot; i++){
      ordering_A[i] = idx_arr[2*i];
      ordering_B[i] = idx_arr[2*i+1];
    }
322
    CTF_int::cfree(idx_arr);
323 324 325 326
    *new_ordering_A = ordering_A;
    *new_ordering_B = ordering_B;
  }

327 328 329 330 331 332 333
  tsum * summation::construct_sum(int inner_stride){
    int nvirt, i, iA, iB, order_tot, is_top, sA, sB, need_rep, i_A, i_B, j, k;
    int64_t blk_sz_A, blk_sz_B, vrt_sz_A, vrt_sz_B;
    int nphys_dim;
    int * idx_arr, * virt_dim, * phys_mapped;
    int * virt_blk_len_A, * virt_blk_len_B;
    int * blk_len_A, * blk_len_B;
solomon's avatar
solomon committed
334
    tsum * htsum = NULL , ** rec_tsum = NULL;
335
    mapping * map;
solomon's avatar
solomon committed
336
    strp_tsr * str_A, * str_B;
337 338

    is_top = 1;
solomon's avatar
solomon committed
339 340
    inv_idx(A->order, idx_A,
            B->order, idx_B,
341 342
            &order_tot, &idx_arr);

solomon's avatar
solomon committed
343
    nphys_dim = A->topo->order;
344

345 346 347 348 349 350
    CTF_int::alloc_ptr(sizeof(int)*A->order,    (void**)&blk_len_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order,    (void**)&blk_len_B);
    CTF_int::alloc_ptr(sizeof(int)*A->order,    (void**)&virt_blk_len_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order,    (void**)&virt_blk_len_B);
    CTF_int::alloc_ptr(sizeof(int)*order_tot,   (void**)&virt_dim);
    CTF_int::alloc_ptr(sizeof(int)*nphys_dim*2, (void**)&phys_mapped);
351 352 353 354
    memset(phys_mapped, 0, sizeof(int)*nphys_dim*2);


    /* Determine the block dimensions of each local subtensor */
solomon's avatar
solomon committed
355 356 357
    blk_sz_A = A->size;
    blk_sz_B = B->size;
    calc_dim(A->order, blk_sz_A, A->pad_edge_len, A->edge_map,
358
             &vrt_sz_A, virt_blk_len_A, blk_len_A);
solomon's avatar
solomon committed
359
    calc_dim(B->order, blk_sz_B, B->pad_edge_len, B->edge_map,
360 361 362
             &vrt_sz_B, virt_blk_len_B, blk_len_B);

    /* Strip out the relevant part of the tensor if we are contracting over diagonal */
solomon's avatar
solomon committed
363 364
    sA = strip_diag(A->order, order_tot, idx_A, vrt_sz_A,
                           A->edge_map, A->topo, A->sr,
365
                           blk_len_A, &blk_sz_A, &str_A);
solomon's avatar
solomon committed
366 367
    sB = strip_diag(B->order, order_tot, idx_B, vrt_sz_B,
                           B->edge_map, B->topo, B->sr,
368 369
                           blk_len_B, &blk_sz_B, &str_B);
    if (sA || sB){
solomon's avatar
solomon committed
370
      if (A->wrld->cdt.rank == 0)
371
        DPRINTF(1,"Stripping tensor\n");
solomon's avatar
solomon committed
372 373 374
      strp_sum * ssum = new strp_sum;
      ssum->sr_A = A->sr;
      ssum->sr_B = B->sr;
375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
      htsum = ssum;
      is_top = 0;
      rec_tsum = &ssum->rec_tsum;

      ssum->rec_strp_A = str_A;
      ssum->rec_strp_B = str_B;
      ssum->strip_A = sA;
      ssum->strip_B = sB;
    }

    nvirt = 1;
    for (i=0; i<order_tot; i++){
      iA = idx_arr[2*i];
      iB = idx_arr[2*i+1];
      if (iA != -1){
solomon's avatar
solomon committed
390
        map = &A->edge_map[iA];
391 392 393 394 395 396 397 398
        while (map->has_child) map = map->child;
        if (map->type == VIRTUAL_MAP){
          virt_dim[i] = map->np;
          if (sA) virt_dim[i] = virt_dim[i]/str_A->strip_dim[iA];
        }
        else virt_dim[i] = 1;
      } else {
        ASSERT(iB!=-1);
solomon's avatar
solomon committed
399
        map = &B->edge_map[iB];
400 401 402 403 404 405 406 407 408 409
        while (map->has_child) map = map->child;
        if (map->type == VIRTUAL_MAP){
          virt_dim[i] = map->np;
          if (sB) virt_dim[i] = virt_dim[i]/str_B->strip_dim[iA];
        }
        else virt_dim[i] = 1;
      }
      nvirt *= virt_dim[i];
    }

solomon's avatar
solomon committed
410 411
    for (i=0; i<A->order; i++){
      map = &A->edge_map[i];
412 413 414 415 416 417 418 419 420 421
      if (map->type == PHYSICAL_MAP){
        phys_mapped[2*map->cdt+0] = 1;
      }
      while (map->has_child) {
        map = map->child;
        if (map->type == PHYSICAL_MAP){
          phys_mapped[2*map->cdt+0] = 1;
        }
      }
    }
solomon's avatar
solomon committed
422 423
    for (i=0; i<B->order; i++){
      map = &B->edge_map[i];
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442
      if (map->type == PHYSICAL_MAP){
        phys_mapped[2*map->cdt+1] = 1;
      }
      while (map->has_child) {
        map = map->child;
        if (map->type == PHYSICAL_MAP){
          phys_mapped[2*map->cdt+1] = 1;
        }
      }
    }
    need_rep = 0;
    for (i=0; i<nphys_dim; i++){
      if (phys_mapped[2*i+0] == 0 ||
          phys_mapped[2*i+1] == 0){
        need_rep = 1;
        break;
      }
    }
    if (need_rep){
solomon's avatar
solomon committed
443
      if (A->wrld->cdt.rank == 0)
444 445
        DPRINTF(1,"Replicating tensor\n");

solomon's avatar
solomon committed
446 447 448
      tsum_replicate * rtsum = new tsum_replicate;
      rtsum->sr_A = A->sr;
      rtsum->sr_B = B->sr;
449 450 451 452 453 454
      if (is_top){
        htsum = rtsum;
        is_top = 0;
      } else {
        *rec_tsum = rtsum;
      }
455
      rec_tsum      = &rtsum->rec_tsum;
456 457 458 459
      rtsum->ncdt_A = 0;
      rtsum->ncdt_B = 0;
      rtsum->size_A = blk_sz_A;
      rtsum->size_B = blk_sz_B;
460 461
      rtsum->cdt_A  = NULL;
      rtsum->cdt_B  = NULL;
462 463 464 465 466 467 468 469 470
      for (i=0; i<nphys_dim; i++){
        if (phys_mapped[2*i+0] == 0 && phys_mapped[2*i+1] == 1){
          rtsum->ncdt_A++;
        }
        if (phys_mapped[2*i+1] == 0 && phys_mapped[2*i+0] == 1){
          rtsum->ncdt_B++;
        }
      }
      if (rtsum->ncdt_A > 0)
471
        CTF_int::alloc_ptr(sizeof(CommData*)*rtsum->ncdt_A, (void**)&rtsum->cdt_A);
472
      if (rtsum->ncdt_B > 0)
473
        CTF_int::alloc_ptr(sizeof(CommData*)*rtsum->ncdt_B, (void**)&rtsum->cdt_B);
474 475 476 477
      rtsum->ncdt_A = 0;
      rtsum->ncdt_B = 0;
      for (i=0; i<nphys_dim; i++){
        if (phys_mapped[2*i+0] == 0 && phys_mapped[2*i+1] == 1){
478 479 480
          rtsum->cdt_A[rtsum->ncdt_A] = &A->topo->dim_comm[i];
/*          if (rtsum->cdt_A[rtsum->ncdt_A].alive == 0)
            rtsum->cdt_A[rtsum->ncdt_A].activate(A->wrld->comm);*/
481 482 483
          rtsum->ncdt_A++;
        }
        if (phys_mapped[2*i+1] == 0 && phys_mapped[2*i+0] == 1){
484 485 486
          rtsum->cdt_B[rtsum->ncdt_B] = &B->topo->dim_comm[i];
/*          if (rtsum->cdt_B[rtsum->ncdt_B].alive == 0)
            rtsum->cdt_B[rtsum->ncdt_B].activate(B->wrld->comm);*/
487 488 489 490 491 492 493
          rtsum->ncdt_B++;
        }
      }
      ASSERT(rtsum->ncdt_A == 0 || rtsum->cdt_B == 0);
    }

    int * new_sym_A, * new_sym_B;
494
    CTF_int::alloc_ptr(sizeof(int)*A->order, (void**)&new_sym_A);
solomon's avatar
solomon committed
495
    memcpy(new_sym_A, A->sym, sizeof(int)*A->order);
496
    CTF_int::alloc_ptr(sizeof(int)*B->order, (void**)&new_sym_B);
solomon's avatar
solomon committed
497
    memcpy(new_sym_B, B->sym, sizeof(int)*B->order);
498 499 500

    /* Multiply over virtual sub-blocks */
    if (nvirt > 1){
solomon's avatar
solomon committed
501 502 503
      tsum_virt * tsumv = new tsum_virt;
      tsumv->sr_A = A->sr;
      tsumv->sr_B = B->sr;
504 505 506 507 508 509
      if (is_top) {
        htsum = tsumv;
        is_top = 0;
      } else {
        *rec_tsum = tsumv;
      }
510 511 512 513 514 515 516 517 518 519 520
      rec_tsum         = &tsumv->rec_tsum;

      tsumv->num_dim   = order_tot;
      tsumv->virt_dim  = virt_dim;
      tsumv->order_A   = A->order;
      tsumv->blk_sz_A  = vrt_sz_A;
      tsumv->idx_map_A = idx_A;
      tsumv->order_B   = B->order;
      tsumv->blk_sz_B  = vrt_sz_B;
      tsumv->idx_map_B = idx_B;
      tsumv->buffer    = NULL;
521
    } else CTF_int::cfree(virt_dim);
522

solomon's avatar
solomon committed
523 524 525
    seq_tsr_sum * tsumseq = new seq_tsr_sum;
    tsumseq->sr_A = A->sr;
    tsumseq->sr_B = B->sr;
526 527 528 529 530
    if (inner_stride == -1){
      tsumseq->is_inner = 0;
    } else {
      tsumseq->is_inner = 1;
      tsumseq->inr_stride = inner_stride;
solomon's avatar
solomon committed
531 532
      tensor * itsr;
      itsr = A->rec_tsr;
533
      i_A = 0;
solomon's avatar
solomon committed
534 535
      for (i=0; i<A->order; i++){
        if (A->sym[i] == NS){
536
          for (j=0; j<itsr->order; j++){
solomon's avatar
solomon committed
537
            if (A->inner_ordering[j] == i_A){
538 539 540
              j=i;
              do {
                j--;
solomon's avatar
solomon committed
541
              } while (j>=0 && A->sym[j] != NS);
542 543 544 545 546 547 548 549 550 551
              for (k=j+1; k<=i; k++){
                virt_blk_len_A[k] = 1;
                new_sym_A[k] = NS;
              }
              break;
            }
          }
          i_A++;
        }
      }
solomon's avatar
solomon committed
552
      itsr = B->rec_tsr;
553
      i_B = 0;
solomon's avatar
solomon committed
554 555
      for (i=0; i<B->order; i++){
        if (B->sym[i] == NS){
556
          for (j=0; j<itsr->order; j++){
solomon's avatar
solomon committed
557
            if (B->inner_ordering[j] == i_B){
558 559 560
              j=i;
              do {
                j--;
solomon's avatar
solomon committed
561
              } while (j>=0 && B->sym[j] != NS);
562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
              for (k=j+1; k<=i; k++){
                virt_blk_len_B[k] = 1;
                new_sym_B[k] = NS;
              }
              break;
            }
          }
          i_B++;
        }
      }
    }
    if (is_top) {
      htsum = tsumseq;
      is_top = 0;
    } else {
      *rec_tsum = tsumseq;
    }
579 580 581 582 583 584 585 586 587
    tsumseq->order_A    = A->order;
    tsumseq->idx_map_A  = idx_A;
    tsumseq->edge_len_A = virt_blk_len_A;
    tsumseq->sym_A      = new_sym_A;
    tsumseq->order_B    = B->order;
    tsumseq->idx_map_B  = idx_B;
    tsumseq->edge_len_B = virt_blk_len_B;
    tsumseq->sym_B      = new_sym_B;
    tsumseq->is_custom  = is_custom;
solomon's avatar
solomon committed
588
    if (is_custom){
589
      tsumseq->is_inner = 0;
solomon's avatar
solomon committed
590 591
      tsumseq->func     = func;
    }
592 593
    htsum->alpha        = alpha;
    htsum->beta         = beta;
594

595 596
    htsum->A = A->data;
    htsum->B = B->data;
597

598 599 600 601
    CTF_int::cfree(idx_arr);
    CTF_int::cfree(blk_len_A);
    CTF_int::cfree(blk_len_B);
    CTF_int::cfree(phys_mapped);
602 603 604 605 606 607

    return htsum;
  }

  int summation::home_sum_tsr(bool run_diag){
    int ret, was_home_A, was_home_B;
solomon's avatar
solomon committed
608 609 610
    tensor * tnsr_A, * tnsr_B;
    summation osum = summation(*this);
   
611
    CTF_int::contract_mst();
612

613 614
    A->unfold();
    B->unfold();
615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631
    // FIXME: if custom function, we currently don't know whether its odd, even or neither, so unpack everything
    if (is_custom){
      bool is_nonsym=true;
      for (int i=0; i<A->order; i++){
        if (A->sym[i] != NS){
          is_nonsym = false;
        }
      }
      if (!is_nonsym){
        int sym_A[A->order];
        std::fill(sym_A, sym_A+A->order, NS);
        int idx_A[A->order];
        for (int i=0; i<A->order; i++){
          idx_A[i] = i;
        }
        tensor tA(A->sr, A->order, A->lens, sym_A, A->wrld, 1);
        tA.is_home = 0;
632
        tA.has_home = 0;
633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669
        summation st(A, idx_A, A->sr->mulid(), &tA, idx_A, A->sr->mulid());
        st.execute();
        summation stme(*this);
        stme.A = &tA;
        stme.execute();
        return SUCCESS;
      }
    }
    if (is_custom){
      bool is_nonsym=true;
      for (int i=0; i<B->order; i++){
        if (B->sym[i] != NS){
          is_nonsym = false;
        }
      }
      if (!is_nonsym){
        int sym_B[B->order];
        std::fill(sym_B, sym_B+B->order, NS);
        int idx_B[B->order];
        for (int i=0; i<B->order; i++){
          idx_B[i] = i;
        }
        tensor tB(B->sr, B->order, B->lens, sym_B, B->wrld, 1);
        tB.is_home = 0;
        if (!B->sr->isequal(B->sr->addid(), beta)){
          summation st(B, idx_B, B->sr->mulid(), &tB, idx_B, B->sr->mulid());
          st.execute();
        }
        summation stme(*this);
        stme.B = &tB;
        stme.execute();
        summation stme2(&tB, idx_B, B->sr->mulid(), B, idx_B, B->sr->addid());
        stme2.execute();
        return SUCCESS;
      }
    }

670 671
  #ifndef HOME_CONTRACT
    #ifdef USE_SYM_SUM
solomon's avatar
solomon committed
672
      ret = sym_sum_tsr(run_diag);
673 674
      return ret;
    #else
solomon's avatar
solomon committed
675
      ret = sum_tensors(run_diag);
676 677 678
      return ret;
    #endif
  #else
solomon's avatar
solomon committed
679 680
    if (A->has_zero_edge_len || 
        B->has_zero_edge_len){
681
      if (!B->sr->isequal(beta,B->sr->mulid()) && !B->has_zero_edge_len){ 
solomon's avatar
solomon committed
682
        int sub_idx_map_B[B->order];
683
        int sm_idx=0;
solomon's avatar
solomon committed
684
        for (int i=0; i<B->order; i++){
685 686 687
          sub_idx_map_B[i]=sm_idx;
          sm_idx++;
          for (int j=0; j<i; j++){
solomon's avatar
solomon committed
688
            if (idx_B[i]==idx_B[j]){
689 690 691 692 693 694
              sub_idx_map_B[i]=sub_idx_map_B[j];
              sm_idx--;
              break;
            }
          }
        }
solomon's avatar
solomon committed
695 696
        scaling scl = scaling(B, sub_idx_map_B, beta);
        scl.execute();
697
      }
solomon's avatar
solomon committed
698
      return SUCCESS;
699
    }
solomon's avatar
solomon committed
700 701 702 703
    if (A == B){
      tensor * cpy_tsr_A = new tensor(A);
      osum.A = cpy_tsr_A;
      osum.execute();
704
      delete cpy_tsr_A;
solomon's avatar
solomon committed
705
      return SUCCESS;
706
    }
solomon's avatar
solomon committed
707 708
    was_home_A = A->is_home;
    was_home_B = B->is_home;
709
    if (was_home_A){
710 711
      tnsr_A              = new tensor(A,0,0);
      tnsr_A->data        = A->data;
solomon's avatar
solomon committed
712
      tnsr_A->home_buffer = A->home_buffer;
713 714 715
      tnsr_A->is_home     = 1;
      tnsr_A->is_mapped   = 1;
      tnsr_A->topo        = A->topo;
solomon's avatar
solomon committed
716 717
      copy_mapping(A->order, A->edge_map, tnsr_A->edge_map);
      tnsr_A->set_padding();
718
      osum.A              = tnsr_A;
719
    } else tnsr_A = NULL;     
720
    if (was_home_B){
721 722
      tnsr_B              = new tensor(B,0,0);
      tnsr_B->data        = B->data;
solomon's avatar
solomon committed
723
      tnsr_B->home_buffer = B->home_buffer;
724 725 726
      tnsr_B->is_home     = 1;
      tnsr_B->is_mapped   = 1;
      tnsr_B->topo        = B->topo;
solomon's avatar
solomon committed
727 728
      copy_mapping(B->order, B->edge_map, tnsr_B->edge_map);
      tnsr_B->set_padding();
729
      osum.B              = tnsr_B;
730
    } else tnsr_B = NULL;
731
  #if DEBUG >= 1
solomon's avatar
solomon committed
732
    if (A->wrld->cdt.rank == 0)
733 734 735 736
      printf("Start head sum:\n");
  #endif
    
    #ifdef USE_SYM_SUM
solomon's avatar
solomon committed
737
    ret = osum.sym_sum_tsr(run_diag);
738
    #else
solomon's avatar
solomon committed
739
    ret = osum.sum_tensors(run_diag);
740 741
    #endif
  #if DEBUG >= 1
solomon's avatar
solomon committed
742
    if (A->wrld->cdt.rank == 0)
743 744 745
      printf("End head sum:\n");
  #endif

solomon's avatar
solomon committed
746
    if (ret!= SUCCESS) return ret;
747 748
    if (was_home_A) tnsr_A->unfold(); 
    else A->unfold();
solomon's avatar
solomon committed
749
    if (was_home_B) tnsr_B->unfold();
750
    else B->unfold();
751

solomon's avatar
solomon committed
752 753
    if (was_home_B && !tnsr_B->is_home){
      if (A->wrld->cdt.rank == 0)
754
        DPRINTF(2,"Migrating tensor %s back to home\n", B->name);
755
      distribution odst(tnsr_B);
solomon's avatar
solomon committed
756 757
      B->data = tnsr_B->data;
      B->is_home = 0;
758
      TAU_FSTART(redistribute_for_sum_home);
solomon's avatar
solomon committed
759
      B->redistribute(odst);
760
      TAU_FSTOP(redistribute_for_sum_home);
761
      memcpy(B->home_buffer, B->data, B->size*B->sr->el_size);
762
      CTF_int::cfree(B->data);
solomon's avatar
solomon committed
763 764 765 766
      B->data = B->home_buffer;
      B->is_home = 1;
      tnsr_B->is_data_aliased = 1;
      delete tnsr_B;
767
    } else if (was_home_B){
solomon's avatar
solomon committed
768 769
      if (tnsr_B->data != B->data){
        printf("Tensor %s is a copy of %s and did not leave home but buffer is %p was %p\n", tnsr_B->name, B->name, tnsr_B->data, B->data);
770 771 772
        ABORT;

      }
solomon's avatar
solomon committed
773 774 775
      tnsr_B->has_home = 0;
      tnsr_B->is_data_aliased = 1;
      delete tnsr_B;
776
    }
solomon's avatar
solomon committed
777 778 779
    if (was_home_A && !tnsr_A->is_home){
      tnsr_A->has_home = 0;
      delete tnsr_A;
780
    } else if (was_home_A) {
solomon's avatar
solomon committed
781 782 783
      tnsr_A->has_home = 0;
      tnsr_A->is_data_aliased = 1;
      delete tnsr_A;
784 785 786 787 788 789
    }
    return ret;
  #endif
  }

  int summation::sym_sum_tsr(bool run_diag){
790
    int sidx, i, nst_B, * new_idx_map;
solomon's avatar
solomon committed
791
    int * map_A, * map_B;
792
    int ** dstack_map_B;
793
    tensor * tnsr_A, * tnsr_B, * new_tsr, ** dstack_tsr_B;
solomon's avatar
solomon committed
794
    std::vector<summation> perm_types;
795
    std::vector<int> signs;
solomon's avatar
solomon committed
796
    char const * dbeta;
797 798 799
  //#if (DEBUG >= 1 || VERBOSE >= 1)
  //  print_sum(type,alpha_,beta);
  //#endif
800
    check_consistency();
801 802 803

    A->unfold();
    B->unfold();
804
    if (A->has_zero_edge_len || B->has_zero_edge_len){
805
      if (!B->sr->isequal(beta, B->sr->mulid()) && !B->has_zero_edge_len){ 
806
        int sub_idx_map_B[B->order];
807
        int sm_idx=0;
808
        for (int i=0; i<B->order; i++){
809 810 811
          sub_idx_map_B[i]=sm_idx;
          sm_idx++;
          for (int j=0; j<i; j++){
812
            if (idx_B[i]==idx_B[j]){
813 814 815 816 817 818
              sub_idx_map_B[i]=sub_idx_map_B[j];
              sm_idx--;
              break;
            }
          }
        }
819 820
        scaling scl = scaling(B, sub_idx_map_B, beta);
        scl.execute();
821
      }
solomon's avatar
solomon committed
822
      return SUCCESS;
823
    }
824 825
    tnsr_A = A;
    tnsr_B = B;
826
    char * new_alpha = (char*)alloc(tnsr_B->sr->el_size);
827 828 829 830
    CTF_int::alloc_ptr(sizeof(int)*tnsr_A->order,     (void**)&map_A);
    CTF_int::alloc_ptr(sizeof(int)*tnsr_B->order,     (void**)&map_B);
    CTF_int::alloc_ptr(sizeof(int*)*tnsr_B->order,    (void**)&dstack_map_B);
    CTF_int::alloc_ptr(sizeof(tensor*)*tnsr_B->order, (void**)&dstack_tsr_B);
831 832 833 834
    memcpy(map_A, idx_A, tnsr_A->order*sizeof(int));
    memcpy(map_B, idx_B, tnsr_B->order*sizeof(int));
    while (!run_diag && tnsr_A->extract_diag(map_A, 1, new_tsr, &new_idx_map) == SUCCESS){
      if (tnsr_A != A) delete tnsr_A;
835
      CTF_int::cfree(map_A);
836
      tnsr_A = new_tsr;
837 838 839
      map_A = new_idx_map;
    }
    nst_B = 0;
840
    while (!run_diag && tnsr_B->extract_diag(map_B, 1, new_tsr, &new_idx_map) == SUCCESS){
841
      dstack_map_B[nst_B] = map_B;
842
      dstack_tsr_B[nst_B] = tnsr_B;
843
      nst_B++;
844
      tnsr_B = new_tsr;
845 846 847
      map_B = new_idx_map;
    }

Edgar Solomonik's avatar
Edgar Solomonik committed
848 849 850
    summation new_sum = summation(*this);
    new_sum.A = tnsr_A;
    new_sum.B = tnsr_B;
851 852
    memcpy(new_sum.idx_A, map_A, sizeof(int)*tnsr_A->order);
    memcpy(new_sum.idx_B, map_B, sizeof(int)*tnsr_B->order);
853
    if (tnsr_A == tnsr_B){
854
      tensor nnew_tsr = tensor(tnsr_A);
Edgar Solomonik's avatar
Edgar Solomonik committed
855 856
      new_sum.A = &nnew_tsr;
      new_sum.B = tnsr_B;
857
      new_sum.sym_sum_tsr(run_diag);
858 859
      
      /*clone_tensor(ntid_A, 1, &new_tid);
860 861 862 863
      new_type = *type;
      new_type.tid_A = new_tid;
      stat = sym_sum_tsr(alpha_, beta, &new_type, ftsr, felm, run_diag);
      del_tsr(new_tid);
864
      return stat;*/
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879
    } else {
      
  /*    new_type.tid_A = ntid_A;
      new_type.tid_B = ntid_B;
      new_type.idx_map_A = map_A;
      new_type.idx_map_B = map_B;*/
  
      //FIXME: make these typefree...
      int sign = align_symmetric_indices(tnsr_A->order,
                                         new_sum.idx_A,
                                         tnsr_A->sym,
                                         tnsr_B->order,
                                         new_sum.idx_B,
                                         tnsr_B->sym);
      int ocfact = overcounting_factor(tnsr_A->order,
880
                                       new_sum.idx_A,
881 882
                                       tnsr_A->sym,
                                       tnsr_B->order,
883
                                       new_sum.idx_B,
884
                                       tnsr_B->sym);
885 886 887 888 889 890 891 892 893 894 895 896 897
  
      if (ocfact != 1 || sign != 1){
        if (ocfact != 1){
          tnsr_B->sr->copy(new_alpha, tnsr_B->sr->addid());
          
          for (int i=0; i<ocfact; i++){
            tnsr_B->sr->add(new_alpha, alpha, new_alpha);
          }
          alpha = new_alpha;
        }
        if (sign == -1){
          tnsr_B->sr->addinv(alpha, new_alpha);
          alpha = new_alpha;
898 899
        }
      }
900 901 902
  
  
      if (new_sum.unfold_broken_sym(NULL) != -1){
solomon's avatar
solomon committed
903
        if (A->wrld->cdt.rank == 0)
904 905 906 907 908 909 910 911
          DPRINTF(1,"Contraction index is broken\n");
  
        summation * unfold_sum;
        sidx = new_sum.unfold_broken_sym(&unfold_sum);
        int sy;
        sy = 0;
        for (i=0; i<A->order; i++){
          if (A->sym[i] == SY) sy = 1;
912
        }
913 914
        for (i=0; i<B->order; i++){
          if (B->sym[i] == SY) sy = 1;
915
        }
916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948
        if (sy && sidx%2 == 0){
          if (A->wrld->cdt.rank == 0)
            DPRINTF(1,"Performing index desymmetrization\n");
          desymmetrize(tnsr_A, unfold_sum->A, 0);
          unfold_sum->B = tnsr_B;
          unfold_sum->sym_sum_tsr(run_diag);
  //        sym_sum_tsr(alpha, beta, &unfold_type, ftsr, felm, run_diag);
          if (tnsr_A != unfold_sum->A){
            unfold_sum->A->unfold();
            tnsr_A->pull_alias(unfold_sum->A);
            delete unfold_sum->A;
          }
        } else {
          //FIXME: unfold B?
          if (sidx != -1 && sidx%2 == 1){
            delete unfold_sum->B;
          } else if (sidx != -1 && sidx%2 == 0){
            delete unfold_sum->A;
          }
          //get_sym_perms(&new_type, alpha, perm_types, signs);
          get_sym_perms(new_sum, perm_types, signs);
          if (A->wrld->cdt.rank == 0)
            DPRINTF(1,"Performing %d summation permutations\n",
                    (int)perm_types.size());
          dbeta = beta;
          char * new_alpha = (char*)alloc(tnsr_B->sr->el_size);
          for (i=0; i<(int)perm_types.size(); i++){
            if (signs[i] == 1)
              B->sr->copy(new_alpha, alpha);
            else
              tnsr_B->sr->addinv(alpha, new_alpha);
            perm_types[i].alpha = new_alpha;
            perm_types[i].beta = dbeta;
949
            //perm_types[i].A->zero_out_padding();
950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967
            perm_types[i].sum_tensors(run_diag);
            /*sum_tensors(new_alpha, dbeta, perm_types[i].tid_A, perm_types[i].tid_B,
                        perm_types[i].idx_map_A, perm_types[i].idx_map_B, ftsr, felm, run_diag);*/
            dbeta = new_sum.B->sr->mulid();
          }
          cfree(new_alpha);
  /*        for (i=0; i<(int)perm_types.size(); i++){
            free_type(&perm_types[i]);
          }*/
          perm_types.clear();
          signs.clear();
        }
        delete unfold_sum;
      } else {
        new_sum.alpha = alpha;
        new_sum.sum_tensors(run_diag);
  /*      sum_tensors(alpha, beta, new_type.tid_A, new_type.tid_B, new_type.idx_map_A,
                    new_type.idx_map_B, ftsr, felm, run_diag);*/
968 969
      }
    }
970
    if (tnsr_A != A) delete tnsr_A;
971
    for (i=nst_B-1; i>=0; i--){
972 973 974 975 976
//      extract_diag(dstack_tid_B[i], dstack_map_B[i], 0, &ntid_B, &new_idx_map);
      dstack_tsr_B[i]->extract_diag(dstack_map_B[i], 0, tnsr_B, &new_idx_map);
      //del_tsr(ntid_B);
      delete tnsr_B;
      tnsr_B = dstack_tsr_B[i];
977
    }
978
    ASSERT(tnsr_B == B);
979
    CTF_int::cfree(new_alpha);
980 981 982 983
    CTF_int::cfree(map_A);
    CTF_int::cfree(map_B);
    CTF_int::cfree(dstack_map_B);
    CTF_int::cfree(dstack_tsr_B);
984

solomon's avatar
solomon committed
985
    return SUCCESS;
986 987 988 989 990 991 992 993
  }


  /**
   * \brief PDAXPY: a*idx_map_A(A) + b*idx_map_B(B) -> idx_map_B(B).
   * \param[in] run_diag if 1 run diagonal sum
   */
  int summation::sum_tensors(bool run_diag){
994
    int stat, * new_idx_map;
995
    int * map_A, * map_B;
996
    int nst_B;
997
    int ** dstack_map_B;
998 999
    tensor * tnsr_A, * tnsr_B, * new_tsr, ** dstack_tsr_B;
//    tsum<dtype> * sumf;
solomon's avatar
solomon committed
1000
    tsum * sumf;
1001 1002 1003
    //check_sum(tid_A, tid_B, idx_map_A, idx_map_B);
    //FIXME: hmm all of the below already takes place in sym_sum
    check_consistency();
1004 1005
    A->unfold();
    B->unfold();
1006
    if (A->has_zero_edge_len || B->has_zero_edge_len){
1007
      if (!B->sr->isequal(beta,B->sr->mulid()) && !B->has_zero_edge_len){ 
1008
    /*    fseq_scl<dtype> fs;
1009 1010
        fs.func_ptr=sym_seq_scl_ref<dtype>;
        fseq_elm_scl<dtype> felm;
1011
        felm.func_ptr = NULL;*/
1012
        int sub_idx_map_B[B->order];
1013
        int sm_idx=0;
1014
        for (int i=0; i<B->order; i++){
1015 1016 1017
          sub_idx_map_B[i]=sm_idx;
          sm_idx++;
          for (int j=0; j<i; j++){
1018
            if (idx_B[i]==idx_B[j]){
1019 1020 1021 1022 1023 1024
              sub_idx_map_B[i]=sub_idx_map_B[j];
              sm_idx--;
              break;
            }
          }
        }
1025 1026
        scaling scl = scaling(B, sub_idx_map_B, beta);
        scl.execute();
1027
      }
solomon's avatar
solomon committed
1028
      return SUCCESS;
1029 1030 1031
    }


1032
    //FIXME: remove all of the below, sum_tensors should never be called without sym_sum
1033 1034 1035 1036
    CTF_int::alloc_ptr(sizeof(int)*A->order,  (void**)&map_A);
    CTF_int::alloc_ptr(sizeof(int)*B->order,  (void**)&map_B);
    CTF_int::alloc_ptr(sizeof(int*)*B->order, (void**)&dstack_map_B);
    CTF_int::alloc_ptr(sizeof(tensor*)*B->order, (void**)&dstack_tsr_B);
1037 1038 1039 1040 1041 1042
    tnsr_A = A;
    tnsr_B = B;
    memcpy(map_A, idx_A, tnsr_A->order*sizeof(int));
    memcpy(map_B, idx_B, tnsr_B->order*sizeof(int));
    while (!run_diag && tnsr_A->extract_diag(map_A, 1, new_tsr, &new_idx_map) == SUCCESS){
      if (tnsr_A != A) delete tnsr_A;
1043
      CTF_int::cfree(map_A);
1044
      tnsr_A = new_tsr;
1045 1046 1047
      map_A = new_idx_map;
    }
    nst_B = 0;
1048
    while (!run_diag && tnsr_B->extract_diag(map_B, 1, new_tsr, &new_idx_map) == SUCCESS){
1049
      dstack_map_B[nst_B] = map_B;
1050
      dstack_tsr_B[nst_B] = tnsr_B;
1051
      nst_B++;
1052
      tnsr_B = new_tsr;
1053 1054
      map_B = new_idx_map;
    }
Edgar Solomonik's avatar
Edgar Solomonik committed
1055 1056 1057
    summation new_sum = summation(*this);
    new_sum.A = tnsr_A;
    new_sum.B = tnsr_B;
1058
    if (tnsr_A == tnsr_B){
solomon's avatar
solomon committed
1059
      tensor * nnew_tsr = new tensor(tnsr_A);
Edgar Solomonik's avatar
Edgar Solomonik committed
1060 1061
      new_sum.A = nnew_tsr;
      new_sum.B = tnsr_B;
1062
    } else{ 
1063 1064
     //FIXME: remove the below, sum_tensors should never be called without sym_sum
     int sign = align_symmetric_indices(tnsr_A->order,
1065
                                        new_sum.idx_A,
1066 1067
                                        tnsr_A->sym,
                                        tnsr_B->order,
1068
                                        new_sum.idx_B,
1069
                                        tnsr_B->sym);
1070 1071 1072 1073 1074

      #if DEBUG >= 1
        new_sum.print();
      #endif

1075
      ASSERT(sign == 1);
solomon's avatar
solomon committed
1076
/*        if (sign == -1){
1077 1078
          char * new_alpha = (char*)malloc(tnsr_B->sr->el_size);
          tnsr_B->sr->addinv(alpha, new_alpha);
solomon's avatar
solomon committed
1079 1080
          alpha = new_alpha;
        }*/
1081

1082
  #if 0 //VERIFY
1083 1084 1085 1086 1087 1088 1089 1090
      int64_t nsA, nsB;
      int64_t nA, nB;
      dtype * sA, * sB;
      dtype * uA, * uB;
      int order_A, order_B,  i;
      int * edge_len_A, * edge_len_B;
      int * sym_A, * sym_B;
      stat = allread_tsr(ntid_A, &nsA, &sA);
solomon's avatar
solomon committed
1091
      assert(stat == SUCCESS);
1092 1093

      stat = allread_tsr(ntid_B, &nsB, &sB);
solomon's avatar
solomon committed
1094
      assert(stat == SUCCESS);
1095 1096 1097 1098 1099 1100 1101 1102
  #endif

      TAU_FSTART(sum_tensors);

      /* Check if the current tensor mappings can be summed on */
  #if REDIST
      if (1) {
  #else
1103
      if (new_sum.check_mapping() == 0) {
1104 1105
  #endif
        /* remap if necessary */
1106
        stat = new_sum.map();
1107
        if (stat == ERROR) {
1108
          printf("Failed to map tensors to physical grid\n");
1109
          return ERROR;
1110 1111
        }
      } else {
1112
  #if DEBUG > 2
solomon's avatar
solomon committed
1113
        if (A->wrld->cdt.rank == 0){
1114 1115
          printf("Keeping mappings:\n");
        }
1116 1117
        tnsr_A->print_map(stdout);
        tnsr_B->print_map(stdout);
1118 1119 1120
  #endif
      }
      /* Construct the tensor algorithm we would like to use */
1121
      ASSERT(new_sum.check_mapping());
1122
  #if FOLD_TSR
1123
      if (is_custom == false && new_sum.can_fold()){
1124 1125
        int inner_stride;
        TAU_FSTART(map_fold);
1126
        inner_stride = new_sum.map_fold();
1127
        TAU_FSTOP(map_fold);
Edgar Solomonik's avatar
Edgar Solomonik committed
1128
        sumf = new_sum.construct_sum(inner_stride);
solomon's avatar
solomon committed
1129 1130
        /*alpha, beta, ntid_A, map_A, ntid_B, map_B,
                              ftsr, felm, inner_stride);*/
1131
      } else
Edgar Solomonik's avatar
Edgar Solomonik committed
1132
        sumf = new_sum.construct_sum();
solomon's avatar
solomon committed
1133 1134
        /*sumf = construct_sum(alpha, beta, ntid_A, map_A, ntid_B, map_B,
                             ftsr, felm);*/
1135
  #else
Edgar Solomonik's avatar
Edgar Solomonik committed
1136
      sumf = new_sum.construct_sum();
solomon's avatar
solomon committed
1137 1138
      /*sumf = construct_sum(alpha, beta, ntid_A, map_A, ntid_B, map_B,
                           ftsr, felm);*/
1139 1140 1141 1142 1143 1144 1145
  #endif
      /*TAU_FSTART(zero_sum_padding);
      stat = zero_out_padding(ntid_A);
      TAU_FSTOP(zero_sum_padding);
      TAU_FSTART(zero_sum_padding);
      stat = zero_out_padding(ntid_B);
      TAU_FSTOP(zero_sum_padding);*/
solomon's avatar
solomon committed
1146
      DEBUG_PRINTF("[%d] performing tensor sum\n", A->wrld->cdt.rank);
1147
  #if DEBUG >=3
1148
      /*if (A->wrld->cdt.rank == 0){
1149 1150 1151 1152 1153 1154
        for (int i=0; i<tensors[ntid_A]->order; i++){
          printf("padding[%d] = %d\n",i, tensors[ntid_A]->padding[i]);
        }
        for (int i=0; i<tensors[ntid_B]->order; i++){
          printf("padding[%d] = %d\n",i, tensors[ntid_B]->padding[i]);
        }
1155
      }*/
1156 1157
  #endif

1158 1159 1160
  #if DEBUG >= 2
      if (tnsr_B->wrld->rank==0)
        sumf->print();
1161 1162
      tnsr_A->print_map();
      tnsr_B->print_map();
1163
  #endif
1164 1165
      TAU_FSTART(sum_func);
      /* Invoke the contraction algorithm */
1166
      tnsr_A->topo->activate();
1167
      MPI_Barrier(tnsr_B->wrld->comm);
1168
      sumf->run();
1169
      /*tnsr_B->unfold();
1170 1171 1172 1173 1174 1175 1176 1177
      tnsr_B->print();
      MPI_Barrier(tnsr_B->wrld->comm);
      if (tnsr_B->wrld->rank==1){
      for (int i=0; i<tnsr_B->size; i++){
        printf("[%d] %dth element  ",tnsr_B->wrld->rank,i);
        tnsr_B->sr->print(tnsr_B->data+i*tnsr_B->sr->el_size);
        printf("\n");
      }
1178 1179
      }*/
      tnsr_A->topo->deactivate();
solomon's avatar
solomon committed
1180 1181
      tnsr_A->unfold();
      tnsr_B->unfold();
1182 1183 1184
#ifndef SEQ
      stat = tnsr_B->zero_out_padding();
#endif
1185
      TAU_FSTOP(sum_func);
1186

1187
  #if 0 //VERIFY
1188
      stat = allread_tsr(ntid_A, &nA, &uA);
solomon's avatar
solomon committed
1189
      assert(stat == SUCCESS);
1190
      stat = get_info(ntid_A, &order_A, &edge_len_A, &sym_A);
solomon's avatar
solomon committed
1191
      assert(stat == SUCCESS);
1192 1193

      stat = allread_tsr(ntid_B, &nB, &uB);
solomon's avatar
solomon committed
1194
      assert(stat == SUCCESS);
1195
      stat = get_info(ntid_B, &order_B, &edge_len_B, &sym_B);
solomon's avatar
solomon committed
1196
      assert(stat == SUCCESS);
1197 1198 1199

      if (nsA != nA) { printf("nsA = " PRId64 ", nA = " PRId64 "\n",nsA,nA); ABORT; }
      if (nsB != nB) { printf("nsB = " PRId64 ", nB = " PRId64 "\n",nsB,nB); ABORT; }
1200
      for (i=0; (int64_t)i<nA; i++){
1201 1202 1203 1204 1205 1206 1207
        if (fabs(uA[i] - sA[i]) > 1.E-6){
          printf("A[i] = %lf, sA[i] = %lf\n", uA[i], sA[i]);
        }
      }

      cpy_sym_sum(alpha, uA, order_A, edge_len_A, edge_len_A, sym_A, map_A,
                  beta, sB, order_B, edge_len_B, edge_len_B, sym_B, map_B);
solomon's avatar
solomon committed
1208
      assert(stat == SUCCESS);
1209

1210
      for (i=0; (int64_t)i<nB; i++){
1211 1212 1213 1214 1215
        if (fabs(uB[i] - sB[i]) > 1.E-6){
          printf("B[%d] = %lf, sB[%d] = %lf\n", i, uB[i], i, sB[i]);
        }
        assert(fabs(sB[i] - uB[i]) < 1.E-6);
      }
1216 1217 1218 1219
      CTF_int::cfree(uA);
      CTF_int::cfree(uB);
      CTF_int::cfree(sA);
      CTF_int::cfree(sB);
1220 1221 1222
  #endif

      delete sumf;
solomon's avatar
solomon committed
1223
      if (tnsr_A != A) delete tnsr_A;
1224
      for (int i=nst_B-1; i>=0; i--){
solomon's avatar
solomon committed
1225
        int ret = dstack_tsr_B[i]->extract_diag(dstack_map_B[i], 0, tnsr_B, &new_idx_map);
solomon's avatar
solomon committed
1226
        ASSERT(ret == SUCCESS);
solomon's avatar
solomon committed
1227 1228
        delete tnsr_B;
        tnsr_B = dstack_tsr_B[i];
1229
      }
solomon's avatar
solomon committed
1230
      ASSERT(tnsr_B == B);
1231
    }
1232
  //#ifndef SEQ
1233
    //stat = B->zero_out_padding();
1234
  //#endif
1235 1236 1237 1238
    CTF_int::cfree(map_A);
    CTF_int::cfree(map_B);
    CTF_int::cfree(dstack_map_B);
    CTF_int::cfree(dstack_tsr_B);
1239 1240

    TAU_FSTOP(sum_tensors);
solomon's avatar
solomon committed
1241
    return SUCCESS;
1242 1243
  }

1244 1245 1246 1247
  int summation::unfold_broken_sym(summation ** nnew_sum){
    int sidx, i, num_tot, iA, iA2, iB;
    int * idx_arr;

solomon's avatar
solomon committed
1248
    summation * new_sum;
1249 1250 1251 1252
   
    if (nnew_sum != NULL){
      new_sum = new summation(*this);
      *nnew_sum = new_sum;
1253
    } else new_sum = NULL;
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315

    inv_idx(A->order, idx_A,
            B->order, idx_B,
            &num_tot, &idx_arr);

    sidx = -1;
    for (i=0; i<A->order; i++){
      if (A->sym[i] != NS){
        iA = idx_A[i];
        if (idx_arr[2*iA+1] != -1){
          if (B->sym[idx_arr[2*iA+1]] == NS ||
              idx_arr[2*idx_A[i+1]+1] == -1 ||
              idx_A[i+1] != idx_B[idx_arr[2*iA+1]+1]){
            sidx = 2*i;
            break;
          }
        } else if (idx_arr[2*idx_A[i+1]+1] != -1){
          sidx = 2*i;
          break;
        }
      }
    } 
    if (sidx == -1){
      for (i=0; i<B->order; i++){
        if (B->sym[i] != NS){
          iB = idx_B[i];
          if (idx_arr[2*iB+0] != -1){
            if (A->sym[idx_arr[2*iB+0]] == NS ||
                idx_arr[2*idx_B[i+1]+0] == -1 ||
                idx_B[i+1] != idx_A[idx_arr[2*iB+0]+1]){
              sidx = 2*i+1;
              break;
            }
          } else if (idx_arr[2*idx_B[i+1]+0] != -1){
            sidx = 2*i+1;
            break;
          }
        }
      }
    }
    if (sidx == -1){
      for (i=0; i<A->order; i++){
        if (A->sym[i] == SY){
          iA = idx_A[i];
          iA2 = idx_A[i+1];
          if (idx_arr[2*iA+1] == -1 &&
              idx_arr[2*iA2+1] == -1){
            sidx = 2*i;
            break;
          }
        }
      }
    } 
    if (nnew_sum != NULL && sidx != -1){
      if(sidx%2 == 0){
        new_sum->A = new tensor(A, 0, 0);
        new_sum->A->sym[sidx/2] = NS;
      } else {
        new_sum->B = new tensor(B, 0, 0);
        new_sum->B->sym[sidx/2] = NS;
      }
    }
1316
    CTF_int::cfree(idx_arr);
1317 1318 1319 1320 1321 1322 1323 1324
    return sidx;
  }

  void summation::check_consistency(){
    int i, num_tot, len;
    int iA, iB;
    int * idx_arr;
       
1325 1326
    inv_idx(A->order, idx_A,
            B->order, idx_B,
1327 1328 1329 1330 1331 1332 1333 1334 1335 1336
            &num_tot, &idx_arr);

    for (i=0; i<num_tot; i++){
      len = -1;
      iA = idx_arr[2*i+0];
      iB = idx_arr[2*i+1];
      if (iA != -1){
        len = A->lens[iA];
      }
      if (len != -1 && iB != -1 && len != B->lens[iB]){
solomon's avatar
solomon committed
1337
        if (A->wrld->cdt.rank == 0){
1338
          printf("i = %d Error in sum call: The %dth edge length (%d) of tensor %s does not",
solomon's avatar
solomon committed
1339
                  i, iA, len, A->name);
1340
          printf("match the %dth edge length (%d) of tensor %s.\n",
solomon's avatar
solomon committed
1341
                  iB, B->lens[iB], B->name);
1342 1343 1344 1345
        }
        ABORT;
      }
    }
1346
    CTF_int::cfree(idx_arr);
1347 1348 1349 1350

  }


1351
  int summation::is_equal(summation const & os){
1352 1353
    int i;

1354 1355
    if (A != os.A) return 0;
    if (B != os.B) return 0;
1356

solomon's avatar
solomon committed
1357
    for (i=0; i<A->order; i++){
1358
      if (idx_A[i] != os.idx_A[i]) return 0;
1359
    }
solomon's avatar
solomon committed
1360
    for (i=0; i<B->order; i++){
1361
      if (idx_B[i] != os.idx_B[i]) return 0;
1362 1363 1364
    }
    return 1;
  }
1365

1366 1367
  int summation::check_mapping(){
    int i, pass, order_tot, iA, iB;
1368
    int * idx_arr; //, * phys_map;
1369
    //mapping * map;
1370 1371 1372 1373 1374 1375 1376 1377

    TAU_FSTART(check_sum_mapping);
    pass = 1;
    
    if (A->is_mapped == 0) pass = 0;
    if (B->is_mapped == 0) pass = 0;
    
    
1378 1379
    if (A->is_folded == 1) pass = 0;
    if (B->is_folded == 1) pass = 0;
1380 1381 1382 1383
    
    if (A->topo != B->topo) pass = 0;

    if (pass==0){
1384
      DPRINTF(4,"failed confirmation here\n");
1385 1386 1387 1388
      TAU_FSTOP(check_sum_mapping);
      return 0;
    }
    
1389 1390
    //CTF_int::alloc_ptr(sizeof(int)*A->topo->order, (void**)&phys_map);
    //memset(phys_map, 0, sizeof(int)*A->topo->order);
1391

1392 1393
    inv_idx(A->order, idx_A,
            B->order, idx_B,
1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411
            &order_tot, &idx_arr);

    if (!check_self_mapping(A, idx_A))
      pass = 0;
    if (!check_self_mapping(B, idx_B))
      pass = 0;
    if (pass == 0)
      DPRINTF(4,"failed confirmation here\n");

    for (i=0; i<order_tot; i++){
      iA = idx_arr[2*i];
      iB = idx_arr[2*i+1];
      if (iA != -1 && iB != -1) {
        if (!comp_dim_map(&A->edge_map[iA], &B->edge_map[iB])){
          pass = 0;
          DPRINTF(4,"failed confirmation here i=%d\n",i);
        }
      }
1412
      /*if (iA != -1) {
1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430
        map = &A->edge_map[iA];
        if (map->type == PHYSICAL_MAP)
          phys_map[map->cdt] = 1;
        while (map->has_child) {
          map = map->child;
          if (map->type == PHYSICAL_MAP)
            phys_map[map->cdt] = 1;
        }
      }
      if (iB != -1){
        map = &B->edge_map[iB];
        if (map->type == PHYSICAL_MAP)
          phys_map[map->cdt] = 1;
        while (map->has_child) {
          map = map->child;
          if (map->type == PHYSICAL_MAP)
            phys_map[map->cdt] = 1;
        }
1431
      }*/
1432 1433 1434 1435 1436 1437 1438 1439 1440 1441
    }
    /* Ensure that something is mapped to each dimension, since replciation
       does not make sense in sum for all tensors */
  /*  for (i=0; i<topovec[A->itopo].order; i++){
      if (phys_map[i] == 0) {
        pass = 0;
        DPRINTF(3,"failed confirmation here i=%d\n",i);
      }
    }*/

1442
    //CTF_int::cfree(phys_map);
1443
    CTF_int::cfree(idx_arr);
1444 1445 1446 1447 1448 1449

    TAU_FSTOP(check_sum_mapping);

    return pass;
  }

1450 1451 1452
  int summation::map_sum_indices(topology const * topo){
    int tsr_order, isum, iA, iB, i, j, jsum, jX, stat;
    int * tsr_edge_len, * tsr_sym_table, * restricted;
solomon's avatar
solomon committed
1453
    int * idx_arr, * idx_sum;
1454 1455 1456 1457 1458
    int num_sum, num_tot, idx_num;
    idx_num = 2;
    mapping * sum_map;

    TAU_FSTART(map_sum_indices);
solomon's avatar
solomon committed
1459

1460 1461
    inv_idx(A->order, idx_A,
            B->order, idx_B,
solomon's avatar
solomon committed
1462 1463
            &num_tot, &idx_arr);

1464
    CTF_int::alloc_ptr(sizeof(int)*num_tot, (void**)&idx_sum);
solomon's avatar
solomon committed
1465 1466 1467 1468 1469 1470 1471
    
    num_sum = 0;
    for (i=0; i<num_tot; i++){
      if (idx_arr[2*i] != -1 && idx_arr[2*i+1] != -1){
        idx_sum[num_sum] = i;
        num_sum++;
      }
1472
    }
1473 1474 1475 1476

    tsr_order = num_sum;


1477 1478 1479 1480
    CTF_int::alloc_ptr(tsr_order*sizeof(int),           (void**)&restricted);
    CTF_int::alloc_ptr(tsr_order*sizeof(int),           (void**)&tsr_edge_len);
    CTF_int::alloc_ptr(tsr_order*tsr_order*sizeof(int), (void**)&tsr_sym_table);
    CTF_int::alloc_ptr(tsr_order*sizeof(mapping),       (void**)&sum_map);
1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559

    memset(tsr_sym_table, 0, tsr_order*tsr_order*sizeof(int));
    memset(restricted, 0, tsr_order*sizeof(int));

    for (i=0; i<tsr_order; i++){ 
      sum_map[i].type             = NOT_MAPPED; 
      sum_map[i].has_child        = 0;
      sum_map[i].np               = 1;
    }
    for (i=0; i<num_sum; i++){
      isum = idx_sum[i];
      iA = idx_arr[isum*2+0];
      iB = idx_arr[isum*2+1];

      if (A->edge_map[iA].type != NOT_MAPPED){
        ASSERT(B->edge_map[iB].type == NOT_MAPPED);
        copy_mapping(1, &A->edge_map[iA], &sum_map[i]);
      } else if (B->edge_map[iB].type != NOT_MAPPED){
        copy_mapping(1, &B->edge_map[iB], &sum_map[i]);
      }
    }

    /* Map a tensor of dimension.
     * Set the edge lengths and symmetries according to those in sum dims of A and B.
     * This gives us a mapping for the common mapped dimensions of tensors A and B. */
    for (i=0; i<num_sum; i++){
      isum = idx_sum[i];
      iA = idx_arr[isum*idx_num+0];
      iB = idx_arr[isum*idx_num+1];

      tsr_edge_len[i] = A->pad_edge_len[iA];

      /* Check if A has symmetry among the dimensions being contracted over.
       * Ignore symmetry with non-contraction dimensions.
       * FIXME: this algorithm can be more efficient but should not be a bottleneck */
      if (A->sym[iA] != NS){
        for (j=0; j<num_sum; j++){
          jsum = idx_sum[j];
          jX = idx_arr[jsum*idx_num+0];
          if (jX == iA+1){
            tsr_sym_table[i*tsr_order+j] = 1;
            tsr_sym_table[j*tsr_order+i] = 1;
          }
        }
      }
      if (B->sym[iB] != NS){
        for (j=0; j<num_sum; j++){
          jsum = idx_sum[j];
          jX = idx_arr[jsum*idx_num+1];
          if (jX == iB+1){
            tsr_sym_table[i*tsr_order+j] = 1;
            tsr_sym_table[j*tsr_order+i] = 1;
          }
        }
      }
    }
    /* Run the mapping algorithm on this construct */
    stat = map_tensor(topo->order,        tsr_order, 
                      tsr_edge_len,       tsr_sym_table,
                      restricted,         topo->dim_comm,
                      NULL,               0,
                      sum_map);

    if (stat == ERROR){
      TAU_FSTOP(map_sum_indices);
      return ERROR;
    }
    
    /* define mapping of tensors A and B according to the mapping of sum dims */
    if (stat == SUCCESS){
      for (i=0; i<num_sum; i++){
        isum = idx_sum[i];
        iA = idx_arr[isum*idx_num+0];
        iB = idx_arr[isum*idx_num+1];

        copy_mapping(1, &sum_map[i], &A->edge_map[iA]);
        copy_mapping(1, &sum_map[i], &B->edge_map[iB]);
      }
    }
1560 1561 1562
    CTF_int::cfree(restricted);
    CTF_int::cfree(tsr_edge_len);
    CTF_int::cfree(tsr_sym_table);
1563 1564 1565
    for (i=0; i<num_sum; i++){
      sum_map[i].clear();
    }
1566 1567 1568
    CTF_int::cfree(sum_map);
    CTF_int::cfree(idx_sum);
    CTF_int::cfree(idx_arr);
1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586

    TAU_FSTOP(map_sum_indices);
    return stat;

  }

  int summation::map(){
    int i, ret, need_remap;
    int need_remap_A, need_remap_B;
    int d;
    topology * old_topo_A, * old_topo_B;
    int btopo;
    int gtopo;

    ASSERT(A->wrld == B->wrld);
    World * wrld = A->wrld;
   
    TAU_FSTART(map_tensor_pair);
solomon's avatar
solomon committed
1587
  #if DEBUG >= 2
1588
    if (wrld->rank == 0)
solomon's avatar
solomon committed
1589
      printf("Initial mappings:\n");
1590
    A->print_map(stdout);
1591
    B->print_map(stdout);
solomon's avatar
solomon committed
1592 1593
  #endif

1594 1595 1596 1597 1598 1599
    //FIXME: try to avoid unfolding immediately, as its not always necessary
    A->unfold();
    B->unfold();
    A->set_padding();
    B->set_padding();

1600

1601 1602
    distribution dA(A);
    distribution dB(B);
1603 1604 1605 1606 1607 1608
    old_topo_A = A->topo;
    old_topo_B = B->topo;
    mapping * old_map_A = new mapping[A->order];
    mapping * old_map_B = new mapping[B->order];
    copy_mapping(A->order, A->edge_map, old_map_A);
    copy_mapping(B->order, B->edge_map, old_map_B);
solomon's avatar
solomon committed
1609
    btopo = -1;
1610 1611
    int64_t size;
    int64_t min_size = INT64_MAX;
solomon's avatar
solomon committed
1612
    /* Attempt to map to all possible permutations of processor topology */
1613
    for (i=A->wrld->cdt.rank; i<2*(int)A->wrld->topovec.size(); i+=A->wrld->cdt.np){
solomon's avatar
solomon committed
1614
  //  for (i=global_comm.rank*topovec.size(); i<2*(int)topovec.size(); i++){
1615 1616 1617 1618
      A->clear_mapping();
      B->clear_mapping();
      A->set_padding();
      B->set_padding();
solomon's avatar
solomon committed
1619

1620 1621 1622 1623
      A->topo = wrld->topovec[i/2];
      B->topo = wrld->topovec[i/2];
      A->is_mapped = 1;
      B->is_mapped = 1;
solomon's avatar
solomon committed
1624 1625

      if (i%2 == 0){
1626 1627
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1628 1629
        else if (ret != SUCCESS) return ret;
      } else {
1630 1631
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1632 1633
        else if (ret != SUCCESS) return ret;
      }
1634 1635
      ret = map_sum_indices(A->topo);
      if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1636 1637 1638 1639
      else if (ret != SUCCESS){
        return ret;
      }
      if (i%2 == 0){
1640 1641
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1642 1643
        else if (ret != SUCCESS) return ret;
      } else {
1644 1645
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1646 1647 1648 1649
        else if (ret != SUCCESS) return ret;
      }

      if (i%2 == 0){
1650 1651
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1652
        else if (ret != SUCCESS) return ret;
1653 1654 1655
        ret = A->map_tensor_rem(A->topo->order, 
                                A->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1656
        else if (ret != SUCCESS) return ret;
1657 1658 1659 1660 1661 1662
        copy_mapping(A->order, B->order,
                     idx_A, A->edge_map, 
                     idx_B, B->edge_map,0);
        ret = B->map_tensor_rem(B->topo->order, 
                                B->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1663 1664
        else if (ret != SUCCESS) return ret;
      } else {
1665 1666
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1667
        else if (ret != SUCCESS) return ret;
1668 1669 1670
        ret = B->map_tensor_rem(B->topo->order, 
                                B->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1671
        else if (ret != SUCCESS) return ret;
1672 1673 1674 1675 1676 1677
        copy_mapping(B->order, A->order,
                     idx_B, B->edge_map, 
                     idx_A, A->edge_map,0);
        ret = A->map_tensor_rem(A->topo->order, 
                                A->topo->dim_comm);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1678 1679 1680
        else if (ret != SUCCESS) return ret;
      }
      if (i%2 == 0){
1681 1682
        ret = map_self_indices(B, idx_B);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1683 1684
        else if (ret != SUCCESS) return ret;
      } else {
1685 1686
        ret = map_self_indices(A, idx_A);
        if (ret == NEGATIVE) continue;
solomon's avatar
solomon committed
1687 1688 1689
        else if (ret != SUCCESS) return ret;
      }

1690 1691
  /*    ret = map_symtsr(A->order, A->sym_table, A->edge_map);
      ret = map_symtsr(B->order, B->sym_table, B->edge_map);
solomon's avatar
solomon committed
1692 1693 1694
      if (ret!=SUCCESS) return ret;
      return SUCCESS;*/

1695
  #if DEBUG >= 4
1696 1697
      A->print_map(stdout,0);
      B->print_map(stdout,0);
solomon's avatar
solomon committed
1698
  #endif
1699 1700 1701 1702
      if (!check_mapping()) continue;
      A->set_padding();
      B->set_padding();
      size = A->size + B->size;
solomon's avatar
solomon committed
1703 1704 1705 1706

      need_remap_A = 0;
      need_remap_B = 0;

1707 1708 1709
      if (A->topo == old_topo_A){
        for (d=0; d<A->order; d++){
          if (!comp_dim_map(&A->edge_map[d],&old_map_A[d]))
solomon's avatar
solomon committed
1710 1711 1712 1713 1714
            need_remap_A = 1;
        }
      } else
        need_remap_A = 1;
      if (need_remap_A){
1715 1716
        if (can_block_reshuffle(A->order, dA.phase, A->edge_map)){
          size += A->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1717
        } else {
1718
          size += 5.*A->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1719 1720
        }
      }
1721 1722 1723
      if (B->topo == old_topo_B){
        for (d=0; d<B->order; d++){
          if (!comp_dim_map(&B->edge_map[d],&old_map_B[d]))
solomon's avatar
solomon committed
1724 1725 1726 1727 1728
            need_remap_B = 1;
        }
      } else
        need_remap_B = 1;
      if (need_remap_B){
1729 1730
        if (can_block_reshuffle(B->order, dB.phase, B->edge_map)){
          size += B->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1731
        } else {
1732
          size += 5.*B->size*log2(wrld->cdt.np);
solomon's avatar
solomon committed
1733 1734 1735
        }
      }

1736 1737
      /*nvirt = (int64_t)calc_nvirt(A);
      tnvirt = nvirt*(int64_t)calc_nvirt(B);
solomon's avatar
solomon committed
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749
      if (tnvirt < nvirt) nvirt = UINT64_MAX;
      else nvirt = tnvirt;
      if (btopo == -1 || nvirt < bnvirt ) {
        bnvirt = nvirt;
        btopo = i;      
      }*/
      if (btopo == -1 || size < min_size){
        min_size = size;
        btopo = i;      
      }
    }
    if (btopo == -1)
1750
      min_size = INT64_MAX;
solomon's avatar
solomon committed
1751
    /* pick lower dimensional mappings, if equivalent */
1752
    gtopo = get_best_topo(min_size, btopo, wrld->cdt);
solomon's avatar
solomon committed
1753 1754 1755 1756 1757 1758 1759
    TAU_FSTOP(map_tensor_pair);
    if (gtopo == -1){
      printf("ERROR: Failed to map pair!\n");
      ABORT;
      return ERROR;
    }
    
1760 1761 1762 1763
    A->clear_mapping();
    B->clear_mapping();
    A->set_padding();
    B->set_padding();
1764

1765 1766
    A->topo = wrld->topovec[gtopo/2];
    B->topo = wrld->topovec[gtopo/2];
1767 1768 1769

    A->is_mapped = 1;
    B->is_mapped = 1;
solomon's avatar
solomon committed
1770 1771
      
    if (gtopo%2 == 0){
1772
      ret = map_self_indices(A, idx_A);
solomon's avatar
solomon committed
1773
      ASSERT(ret == SUCCESS);
1774
    } else {
1775
      ret = map_self_indices(B, idx_B);
solomon's avatar
solomon committed
1776
      ASSERT(ret == SUCCESS);
1777
    }
1778
    ret = map_sum_indices(A->topo);
solomon's avatar
solomon committed
1779
    ASSERT(ret == SUCCESS);
1780 1781 1782 1783 1784 1785 1786
    if (gtopo%2 == 0){
      ret = map_self_indices(A, idx_A);
      ASSERT(ret == SUCCESS);
    } else {
      ret = map_self_indices(B, idx_B);
      ASSERT(ret == SUCCESS);
    }
1787

solomon's avatar
solomon committed
1788
    if (gtopo%2 == 0){
1789
      ret = map_self_indices(A, idx_A);
solomon's avatar
solomon committed
1790
      ASSERT(ret == SUCCESS);
1791 1792
      ret = A->map_tensor_rem(A->topo->order, 
                              A->topo->dim_comm);
solomon's avatar
solomon committed
1793
      ASSERT(ret == SUCCESS);
1794 1795 1796 1797 1798
      copy_mapping(A->order, B->order,
                   idx_A, A->edge_map, 
                   idx_B, B->edge_map,0);
      ret = B->map_tensor_rem(B->topo->order, 
                              B->topo->dim_comm);
solomon's avatar
solomon committed
1799
      ASSERT(ret == SUCCESS);
1800
    } else {
1801
      ret = map_self_indices(B, idx_B);
solomon's avatar
solomon committed
1802
      ASSERT(ret == SUCCESS);
1803 1804
      ret = B->map_tensor_rem(B->topo->order, 
                              B->topo->dim_comm);
solomon's avatar
solomon committed
1805
      ASSERT(ret == SUCCESS);
1806 1807 1808 1809 1810
      copy_mapping(B->order, A->order,
                   idx_B, B->edge_map, 
                   idx_A, A->edge_map,0);
      ret = A->map_tensor_rem(A->topo->order, 
                              A->topo->dim_comm);
solomon's avatar
solomon committed
1811
      ASSERT(ret == SUCCESS);
1812
    }
1813
    if (gtopo%2 == 0){
1814
      ret = map_self_indices(B, idx_B);
1815 1816
      ASSERT(ret == SUCCESS);
    } else {
1817
      ret = map_self_indices(A, idx_A);
1818 1819 1820
      ASSERT(ret == SUCCESS);
    }

1821
    ASSERT(check_mapping());
1822

1823 1824
    A->set_padding();
    B->set_padding();
1825
  #if DEBUG > 2
1826
    if (wrld->cdt.rank == 0)
solomon's avatar
solomon committed
1827
      printf("New mappings:\n");
1828 1829
    A->print_map(stdout);
    B->print_map(stdout);
solomon's avatar
solomon committed
1830
  #endif
1831

solomon's avatar
solomon committed
1832 1833
    TAU_FSTART(redistribute_for_sum);
   
1834 1835
    A->is_cyclic = 1;
    B->is_cyclic = 1;
solomon's avatar
solomon committed
1836
    need_remap = 0;
1837 1838 1839
    if (A->topo == old_topo_A){
      for (d=0; d<A->order; d++){
        if (!comp_dim_map(&A->edge_map[d],&old_map_A[d]))
solomon's avatar
solomon committed
1840
          need_remap = 1;
1841 1842
      }
    } else
solomon's avatar
solomon committed
1843 1844
      need_remap = 1;
    if (need_remap)
1845
      A->redistribute(dA);
solomon's avatar
solomon committed
1846
    need_remap = 0;
1847 1848 1849
    if (B->topo == old_topo_B){
      for (d=0; d<B->order; d++){
        if (!comp_dim_map(&B->edge_map[d],&old_map_B[d]))
solomon's avatar
solomon committed
1850
          need_remap = 1;
1851 1852
      }
    } else
solomon's avatar
solomon committed
1853 1854
      need_remap = 1;
    if (need_remap)
1855
      B->redistribute(dB);
solomon's avatar
solomon committed
1856 1857

    TAU_FSTOP(redistribute_for_sum);
1858 1859
    delete [] old_map_A;
    delete [] old_map_B;
1860

solomon's avatar
solomon committed
1861
    return SUCCESS;
1862
  }
1863 1864 1865 1866 1867 1868 1869 1870 1871 1872

  void summation::print(){
    int i,j,max,ex_A, ex_B;
    max = A->order+B->order;
    CommData global_comm = A->wrld->cdt;
    MPI_Barrier(global_comm.cm);
    if (global_comm.rank == 0){
      printf("Summing Tensor %s into %s\n", A->name, B->name);
      if (alpha != NULL){
        printf("alpha is "); 
1873 1874
        if (beta != NULL) A->sr->print(alpha);
        printf("null"); 
1875
        printf("\nbeta is "); 
1876 1877
        if (beta != NULL) B->sr->print(beta);
        printf("null"); 
1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913
        printf("\n");
      }
      printf("Summation index table:\n");
      printf("     A     B\n");
      for (i=0; i<max; i++){
        ex_A=0;
        ex_B=0;
        printf("%d:   ",i);
        for (j=0; j<A->order; j++){
          if (idx_A[j] == i){
            ex_A++;
            if (A->sym[j] != NS)
              printf("%d' ",j);
            else
              printf("%d  ",j);
          }
        }
        if (ex_A == 0)
          printf("      ");
        if (ex_A == 1)
          printf("   ");
        for (j=0; j<B->order; j++){
          if (idx_B[j] == i){
            ex_B=1;
            if (B->sym[j] != NS)
              printf("%d' ",j);
            else
              printf("%d  ",j);
          }
        }
        printf("\n");
        if (ex_A + ex_B== 0) break;
      }
    }
  }

1914
}