Data Shuffling Kernel - 2022.1 English

AI Engine Kernel Coding Best Practices Guide (UG1079)

Document ID
UG1079
Release Date
2022-05-25
Version
2022.1 English

Because aie::mmul accepts row-based vector data for shape of matrix multiplication, it may require data shuffling in PL or AI Engine with raw data for performance. This section assumes that the original data is row based for whole matrices. It shuffles the data to match the shape 4*16*8 used in the matrix multiplication.

Following kernel code shuffles data for matrix A, with a target size of 4*16:
//element matrix size
const int M=4;
const int N=16;

//Total matrix sizes
const int rowA=64;
const int colA=64;

void shuffle_4x16(input_window<int8> * __restrict matA, output_window<int8> * __restrict matAout){
  const int sizeA=M*N;
  auto pV=aie::begin_vector<16>((int8*)matA->ptr);
  auto pOut=aie::begin_vector<sizeA>((int8*)matAout->ptr);
  aie::vector<int8,sizeA> mm;

  for(int i=0;i<rowA/M;i++){//output row number of element matrix
    for(int j=0;j<colA/N;j++){//output col number of element matrix
      for(int k=0;k<M;k++){//generate 4*16 matrix
        mm.insert(k,*pV);
        pV=pV+4;
      }
      *pOut++=mm;
      pV=pV-15;
    }
    pV=pV+12;
  }
}
Following is an example of code used to shuffle data for matrix B, with a target size of 16*8:
//element matrix size
const int M=16;
const int N=8;

//Total matrix sizes
const int rowA=64;
const int colA=64;

void shuffle_16x8(input_window<int8> * __restrict matA, output_window<int8> * __restrict matAout){
  const int sizeA=M*N;
  auto pV=aie::begin_vector<16>((int8*)matA->ptr);
  auto pOut=aie::begin_vector<16>((int8*)matAout->ptr);

  aie::vector<int8,16> sv1,sv2;
  for(int i=0;i<rowA/M;i++){
    for(int j=0;j<colA/N/2;j++){//generate two 16*8 matrices an iteration
      for(int k=0;k<M/2;k++){//generate two rows of two 16*8 matrices an iteration
        sv1=*pV;
        pV=pV+4;
        sv2=*pV;
        pV=pV+4;
        auto mm=aie::interleave_zip(sv1,sv2,8);
        *pOut=mm.first;
        pOut+=8;
        *pOut=mm.second;
        pOut-=7;
      }
      pOut+=8;
      pV-=63;
    }
    pV+=60;
  }
}