xref: /petsc/src/ts/utils/dmplexlandau/kokkos/landau.kokkos.cxx (revision af0767da894b3a9c91958d6f68ee0dfeaf72be15)
1 /*
2   Implements the Kokkos kernel
3 */
4 #define PETSC_SKIP_CXX_COMPLEX_FIX
5 #include <petscconf.h>
6 #include <petscvec_kokkos.hpp>
7 #include <petsc/private/dmpleximpl.h>   /*I   "petscdmplex.h"   I*/
8 #include <petsclandau.h>
9 #include <petscts.h>
10 
11 #include <Kokkos_Core.hpp>
12 #include <cstdio>
13 typedef Kokkos::TeamPolicy<>::member_type team_member;
14 #define PETSC_DEVICE_FUNC_DECL KOKKOS_INLINE_FUNCTION
15 #include "../land_tensors.h"
16 #define atomicAdd(e, f) Kokkos::atomic_fetch_add(e, f)
17 #include <petscaijdevice.h>
18 #undef atomicAdd
19 
20 namespace landau_inner_red {  // namespace helps with name resolution in reduction identity
21   template< class ScalarType >
22   struct array_type {
23     ScalarType gg2[LANDAU_DIM];
24     ScalarType gg3[LANDAU_DIM][LANDAU_DIM];
25 
26     KOKKOS_INLINE_FUNCTION   // Default constructor - Initialize to 0's
27     array_type() {
28       for (int j = 0; j < LANDAU_DIM; j++){
29         gg2[j] = 0;
30         for (int k = 0; k < LANDAU_DIM; k++){
31           gg3[j][k] = 0;
32         }
33       }
34     }
35     KOKKOS_INLINE_FUNCTION   // Copy Constructor
36     array_type(const array_type & rhs) {
37       for (int j = 0; j < LANDAU_DIM; j++){
38         gg2[j] = rhs.gg2[j];
39         for (int k = 0; k < LANDAU_DIM; k++){
40           gg3[j][k] = rhs.gg3[j][k];
41         }
42       }
43     }
44     KOKKOS_INLINE_FUNCTION   // add operator
45     array_type& operator += (const array_type& src) {
46       for (int j = 0; j < LANDAU_DIM; j++){
47         gg2[j] += src.gg2[j];
48         for (int k = 0; k < LANDAU_DIM; k++){
49           gg3[j][k] += src.gg3[j][k];
50         }
51       }
52       return *this;
53     }
54     KOKKOS_INLINE_FUNCTION   // volatile add operator
55     void operator += (const volatile array_type& src) volatile {
56       for (int j = 0; j < LANDAU_DIM; j++){
57         gg2[j] += src.gg2[j];
58         for (int k = 0; k < LANDAU_DIM; k++){
59           gg3[j][k] += src.gg3[j][k];
60         }
61       }
62     }
63   };
64   typedef array_type<PetscReal> TensorValueType;  // used to simplify code below
65 }
66 
67 namespace Kokkos { //reduction identity must be defined in Kokkos namespace
68   template<>
69   struct reduction_identity< landau_inner_red::TensorValueType > {
70     KOKKOS_FORCEINLINE_FUNCTION static landau_inner_red::TensorValueType sum() {
71       return landau_inner_red::TensorValueType();
72     }
73   };
74 }
75 
76 extern "C"  {
77   PetscErrorCode LandauKokkosCreateMatMaps(P4estVertexMaps *maps, pointInterpolationP4est (*pointMaps)[LANDAU_MAX_Q_FACE], PetscInt Nf, PetscInt Nq)
78   {
79     P4estVertexMaps   h_maps;  /* host container */
80     const Kokkos::View<pointInterpolationP4est*[LANDAU_MAX_Q_FACE], Kokkos::LayoutRight, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> >    h_points ((pointInterpolationP4est*)pointMaps, maps->num_reduced);
81     const Kokkos::View< LandauIdx*[LANDAU_MAX_SPECIES][LANDAU_MAX_NQ], Kokkos::LayoutRight, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_gidx ((LandauIdx*)maps->gIdx, maps->num_elements);
82     Kokkos::View<pointInterpolationP4est*[LANDAU_MAX_Q_FACE], Kokkos::LayoutRight>   *d_points = new Kokkos::View<pointInterpolationP4est*[LANDAU_MAX_Q_FACE], Kokkos::LayoutRight>("points", maps->num_reduced);
83     Kokkos::View<LandauIdx*[LANDAU_MAX_SPECIES][LANDAU_MAX_NQ], Kokkos::LayoutRight> *d_gidx = new Kokkos::View<LandauIdx*[LANDAU_MAX_SPECIES][LANDAU_MAX_NQ], Kokkos::LayoutRight>("gIdx", maps->num_elements);
84 
85     PetscFunctionBegin;
86     Kokkos::deep_copy (*d_gidx, h_gidx);
87     Kokkos::deep_copy (*d_points, h_points);
88     h_maps.num_elements = maps->num_elements;
89     h_maps.num_face = maps->num_face;
90     h_maps.num_reduced = maps->num_reduced;
91     h_maps.deviceType = maps->deviceType;
92     h_maps.Nf = Nf;
93     h_maps.Nq = Nq;
94     h_maps.c_maps = (pointInterpolationP4est (*)[LANDAU_MAX_Q_FACE]) d_points->data();
95     maps->vp1 = (void*)d_points;
96     h_maps.gIdx = (LandauIdx (*)[LANDAU_MAX_SPECIES][LANDAU_MAX_NQ]) d_gidx->data();
97     maps->vp2 = (void*)d_gidx;
98     {
99       Kokkos::View<P4estVertexMaps, Kokkos::HostSpace> h_maps_k(&h_maps);
100       Kokkos::View<P4estVertexMaps>                    *d_maps_k = new Kokkos::View<P4estVertexMaps>(Kokkos::create_mirror(Kokkos::DefaultExecutionSpace::memory_space(),h_maps_k));
101       Kokkos::deep_copy (*d_maps_k, h_maps_k);
102       maps->data = d_maps_k->data();
103       maps->vp3 = (void*)d_maps_k;
104     }
105     PetscFunctionReturn(0);
106   }
107   PetscErrorCode LandauKokkosDestroyMatMaps(P4estVertexMaps *maps)
108   {
109     Kokkos::View<pointInterpolationP4est*[LANDAU_MAX_Q_FACE], Kokkos::LayoutRight>  *a = (Kokkos::View<pointInterpolationP4est*[LANDAU_MAX_Q_FACE], Kokkos::LayoutRight>*)maps->vp1;
110     Kokkos::View<LandauIdx*[LANDAU_MAX_SPECIES][LANDAU_MAX_NQ], Kokkos::LayoutRight>*b = (Kokkos::View<LandauIdx*[LANDAU_MAX_SPECIES][LANDAU_MAX_NQ], Kokkos::LayoutRight>*)maps->vp2;
111     Kokkos::View<P4estVertexMaps*>                                                  *c = (Kokkos::View<P4estVertexMaps*>*)maps->vp3;
112     delete a;  delete b;  delete c;
113     PetscFunctionReturn(0);
114   }
115 
116   PetscErrorCode LandauKokkosStaticDataSet(DM plex, const PetscInt Nq, PetscReal nu_alpha[], PetscReal nu_beta[], PetscReal a_invMass[], PetscReal a_invJ[], PetscReal a_mass_w[],
117                                            PetscReal a_x[], PetscReal a_y[], PetscReal a_z[], PetscReal a_w[], LandauGeomData *SData_d)
118   {
119     PetscReal       *BB,*DD;
120     PetscErrorCode  ierr;
121     PetscTabulation *Tf;
122     LandauCtx       *ctx;
123     PetscInt        *Nbf,dim,Nf,Nb,nip,cStart,cEnd;
124     PetscDS         prob;
125 
126     PetscFunctionBegin;
127     ierr = DMGetApplicationContext(plex, &ctx);CHKERRQ(ierr);
128     if (!ctx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
129     ierr = DMGetDimension(plex, &dim);CHKERRQ(ierr);
130     ierr = DMPlexGetHeightStratum(plex,0,&cStart,&cEnd);CHKERRQ(ierr);
131     nip = (cEnd - cStart)*Nq;
132     ierr = DMGetDS(plex, &prob);CHKERRQ(ierr);
133     ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
134     ierr = PetscDSGetDimensions(prob, &Nbf);CHKERRQ(ierr); Nb = Nbf[0];
135     if (Nq != Nb) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Nq != Nb. %D  %D",Nq,Nb);
136     if (LANDAU_DIM != dim) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_PLIB, "dim %D != LANDAU_DIM %d",dim,LANDAU_DIM);
137     ierr = PetscDSGetTabulation(prob, &Tf);CHKERRQ(ierr);
138     BB   = Tf[0]->T[0]; DD = Tf[0]->T[1];
139     ierr = PetscKokkosInitializeCheck();CHKERRQ(ierr);
140     {
141       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_alpha (nu_alpha, Nf);
142       auto alpha = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("alpha", Nf);
143       SData_d->alpha = static_cast<void*>(alpha);
144       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_beta (nu_beta, Nf);
145       auto beta = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("beta", Nf);
146       SData_d->beta = static_cast<void*>(beta);
147       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_invMass (a_invMass,Nf);
148       auto invMass = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("invMass", Nf);
149       SData_d->invMass = static_cast<void*>(invMass);
150       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_BB (BB,Nq*Nb);
151       auto B = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("B", Nq*Nb);
152       SData_d->B = static_cast<void*>(B);
153       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_DD (DD,Nq*Nb*dim);
154       auto D = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("D", Nq*Nb*dim);
155       SData_d->D = static_cast<void*>(D);
156       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_mass_w (a_mass_w, nip);
157       auto mass_w = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("mass_w", nip);
158       SData_d->mass_w = static_cast<void*>(mass_w);
159       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_invJ (a_invJ, nip*dim*dim);
160       auto invJ = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("invJ", nip*dim*dim);
161       SData_d->invJ = static_cast<void*>(invJ);
162       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_x (a_x, nip);
163       auto x = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("x", nip);
164       SData_d->x = static_cast<void*>(x);
165       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_y (a_y, nip);
166       auto y = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("y", nip);
167       SData_d->y = static_cast<void*>(y);
168       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_w (a_w, nip);
169       auto w = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("w", nip);
170       SData_d->w = static_cast<void*>(w);
171       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> > h_z (a_z , dim==3 ? nip : 0);
172       auto z = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("z", dim==3 ? nip : 0);
173       SData_d->z = static_cast<void*>(z);
174 
175       Kokkos::deep_copy (*mass_w, h_mass_w);
176       Kokkos::deep_copy (*alpha, h_alpha);
177       Kokkos::deep_copy (*beta, h_beta);
178       Kokkos::deep_copy (*invMass, h_invMass);
179       Kokkos::deep_copy (*B, h_BB);
180       Kokkos::deep_copy (*D, h_DD);
181       Kokkos::deep_copy (*invJ, h_invJ);
182       Kokkos::deep_copy (*x, h_x);
183       Kokkos::deep_copy (*y, h_y);
184       Kokkos::deep_copy (*z, h_z);
185       Kokkos::deep_copy (*w, h_w);
186 
187       auto Eq_m = new Kokkos::View<PetscReal*, Kokkos::LayoutLeft> ("Eq_m",Nf);
188       SData_d->Eq_m = static_cast<void*>(Eq_m);
189       auto IPf = new Kokkos::View<PetscScalar*, Kokkos::LayoutLeft> ("IPf",nip*Nf); // Nq==Nb
190       SData_d->IPf = static_cast<void*>(IPf);
191     }
192     PetscFunctionReturn(0);
193   }
194 
195   PetscErrorCode LandauKokkosStaticDataClear(LandauGeomData *SData_d)
196   {
197     PetscFunctionBegin;
198     if (SData_d->alpha) {
199       auto alpha = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->alpha);
200       delete alpha;
201       auto beta = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->beta);
202       delete beta;
203       auto invMass = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->invMass);
204       delete invMass;
205       auto B = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->B);
206       delete B;
207       auto D = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->D);
208       delete D;
209       auto mass_w = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->mass_w);
210       delete mass_w;
211       auto invJ = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->invJ);
212       delete invJ;
213       auto x = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->x);
214       delete x;
215       auto y = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->y);
216       delete y;
217       auto z = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->z);
218       delete z;
219       auto w = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->w);
220       delete w;
221       auto Eq_m = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->Eq_m);
222       delete Eq_m;
223       if (SData_d->IPf) {
224         auto IPf = static_cast<Kokkos::View<PetscScalar*, Kokkos::LayoutLeft>*>(SData_d->IPf);
225         delete IPf;
226       }
227     }
228     PetscFunctionReturn(0);
229   }
230 
231   PetscErrorCode LandauKokkosJacobian(DM plex, const PetscInt Nq, PetscReal a_Eq_m[], PetscScalar a_IPf[],  const PetscInt N, const PetscScalar a_xarray[], LandauGeomData *SData_d,
232                                       const PetscInt num_sub_blocks, PetscReal shift, const PetscLogEvent events[], Mat JacP)
233   {
234     using scr_mem_t = Kokkos::DefaultExecutionSpace::scratch_memory_space;
235     using g2_scr_t = Kokkos::View<PetscReal***, Kokkos::LayoutRight, scr_mem_t>;
236     using g3_scr_t = Kokkos::View<PetscReal****, Kokkos::LayoutRight, scr_mem_t>;
237     PetscErrorCode    ierr;
238     PetscInt          *Nbf,Nb,cStart,cEnd,Nf,dim,numCells,totDim,global_elem_mat_sz,nip;
239     PetscDS           prob;
240     LandauCtx         *ctx;
241     PetscReal         *d_Eq_m=NULL;
242     PetscScalar       *d_IPf=NULL;
243     P4estVertexMaps   *d_maps=NULL;
244     PetscSplitCSRDataStructure *d_mat=NULL;
245     const int         conc = Kokkos::DefaultExecutionSpace().concurrency(), openmp = !!(conc < 1000), team_size = (openmp==0) ? Nq : 1;
246     int               scr_bytes;
247     auto              d_alpha_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->alpha); //static data
248     const PetscReal   *d_alpha = d_alpha_k->data();
249     auto              d_beta_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->beta);
250     const PetscReal   *d_beta = d_beta_k->data();
251     auto              d_invMass_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->invMass);
252     const PetscReal   *d_invMass = d_invMass_k->data();
253     auto              d_B_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->B);
254     const PetscReal   *d_BB = d_B_k->data();
255     auto              d_D_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->D);
256     const PetscReal   *d_DD = d_D_k->data();
257     auto              d_mass_w_k = *static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->mass_w);
258     auto              d_invJ_k = *static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->invJ); // use Kokkos vector in kernels
259     auto              d_x_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->x); //static data
260     const PetscReal   *d_x = d_x_k->data();
261     auto              d_y_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->y); //static data
262     const PetscReal   *d_y = d_y_k->data();
263     auto              d_z_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->z); //static data
264     const PetscReal   *d_z = d_z_k->data();
265     auto              d_w_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->w); //static data
266     const PetscReal   *d_w = d_w_k->data();
267     // dynamic data pointers
268     auto              d_Eq_m_k = static_cast<Kokkos::View<PetscReal*, Kokkos::LayoutLeft>*>(SData_d->Eq_m); //static data
269     auto              d_IPf_k  = static_cast<Kokkos::View<PetscScalar*, Kokkos::LayoutLeft>*>(SData_d->IPf); //static data
270 
271     PetscFunctionBegin;
272     ierr = PetscLogEventBegin(events[3],0,0,0,0);CHKERRQ(ierr);
273     ierr = DMGetApplicationContext(plex, &ctx);CHKERRQ(ierr);
274     if (!ctx) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "no context");
275     ierr = DMGetDimension(plex, &dim);CHKERRQ(ierr);
276     ierr = DMPlexGetHeightStratum(plex,0,&cStart,&cEnd);CHKERRQ(ierr);
277     numCells = cEnd - cStart;
278     nip = numCells*Nq;
279     ierr = DMGetDS(plex, &prob);CHKERRQ(ierr);
280     ierr = PetscDSGetNumFields(prob, &Nf);CHKERRQ(ierr);
281     ierr = PetscDSGetDimensions(prob, &Nbf);CHKERRQ(ierr); Nb = Nbf[0];
282     if (Nq != Nb) SETERRQ2(PETSC_COMM_SELF, PETSC_ERR_PLIB, "Nq != Nb. %D  %D",Nq,Nb);
283     if (LANDAU_DIM != dim) SETERRQ2(PETSC_COMM_WORLD, PETSC_ERR_PLIB, "dim %D != LANDAU_DIM %d",dim,LANDAU_DIM);
284     scr_bytes = 2*(g2_scr_t::shmem_size(dim,Nf,Nq) + g3_scr_t::shmem_size(dim,dim,Nf,Nq));
285     ierr = PetscDSGetTotalDimension(prob, &totDim);CHKERRQ(ierr);
286     if (ctx->gpu_assembly) {
287       PetscContainer container;
288       ierr = PetscObjectQuery((PetscObject) JacP, "assembly_maps", (PetscObject *) &container);CHKERRQ(ierr);
289       if (container) { // not here first call
290 #if defined(PETSC_HAVE_KOKKOS_KERNELS)
291         P4estVertexMaps   *h_maps=NULL;
292         ierr = PetscContainerGetPointer(container, (void **) &h_maps);CHKERRQ(ierr);
293         if (h_maps->data) {
294           d_maps = h_maps->data;
295         } else {
296           SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "GPU assembly but no metadata in container");
297         }
298         // this does the setup the first time called
299         ierr = MatKokkosGetDeviceMatWrite(JacP,&d_mat);CHKERRQ(ierr);
300         global_elem_mat_sz = 0;
301 #else
302         SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "GPU assembly w/o kokkos kernels -- should not be here");
303 #endif
304       } else { // kernel output - first call assembled on device
305         global_elem_mat_sz = numCells;
306       }
307     } else {
308       global_elem_mat_sz = numCells; // no device assembly
309     }
310     ierr = PetscKokkosInitializeCheck();CHKERRQ(ierr);
311     ierr = PetscLogEventEnd(events[3],0,0,0,0);CHKERRQ(ierr);
312     {
313 #if defined(LANDAU_LAYOUT_LEFT)
314       Kokkos::View<PetscReal***, Kokkos::LayoutLeft >                               d_fdf_k("df", dim+1, Nf, (a_IPf || a_xarray) ? nip : 0);
315 #else
316       Kokkos::View<PetscReal***, Kokkos::LayoutRight >                              d_fdf_k("df", dim+1, Nf, (a_IPf || a_xarray) ? nip : 0);
317 #endif
318       const Kokkos::View<PetscScalar*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> >h_IPf_k  (a_IPf,  (a_IPf || a_xarray) ? nip*Nf : 0);
319       const Kokkos::View<PetscReal*, Kokkos::LayoutLeft, Kokkos::HostSpace, Kokkos::MemoryTraits<Kokkos::Unmanaged> >  h_Eq_m_k (a_Eq_m, (a_IPf || a_xarray) ? Nf : 0);
320       Kokkos::View<PetscScalar**, Kokkos::LayoutRight>                                                                 d_elem_mats("element matrices", global_elem_mat_sz, totDim*totDim);
321       // copy dynamic data to device
322       if (a_IPf || a_xarray) {  // form f and df
323         static int cc=0;
324         ierr = PetscLogEventBegin(events[1],0,0,0,0);CHKERRQ(ierr);
325         Kokkos::deep_copy (*d_Eq_m_k, h_Eq_m_k);
326         d_Eq_m = d_Eq_m_k->data();
327         if (a_IPf) {
328           Kokkos::deep_copy (*d_IPf_k, h_IPf_k);
329           d_IPf  = d_IPf_k->data();
330         } else {
331           d_IPf = (PetscScalar*)a_xarray;
332         }
333         ierr = PetscLogEventEnd(events[1],0,0,0,0);CHKERRQ(ierr);
334 #define KOKKOS_SHARED_LEVEL 1
335         if (cc++ == 0) {
336           ierr = PetscInfo4(plex, "shared memory size: %d bytes in level %d conc=%D team size=%D\n",scr_bytes,KOKKOS_SHARED_LEVEL,conc,team_size);CHKERRQ(ierr);
337         }
338         // get f and df
339         ierr = PetscLogEventBegin(events[8],0,0,0,0);CHKERRQ(ierr);
340         ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
341         Kokkos::parallel_for("f, df", Kokkos::TeamPolicy<>(numCells, team_size, /* Kokkos::AUTO */ 16), KOKKOS_LAMBDA (const team_member team) {
342             const PetscInt    myelem = team.league_rank();
343             const PetscScalar *coef;
344             PetscScalar       coef_buff[LANDAU_MAX_SPECIES*LANDAU_MAX_NQ];
345             // un pack IPData
346             if (!d_maps) {
347               coef = &d_IPf[myelem*Nb*Nf];
348             } else {
349               coef = coef_buff;
350               for (int f = 0; f < Nf; ++f) {
351                 LandauIdx *const Idxs = &d_maps->gIdx[myelem][f][0];
352                 for (int b = 0; b < Nb; ++b) {
353                   PetscInt idx = Idxs[b];
354                   if (idx >= 0) {
355                     coef_buff[f*Nb+b] = d_IPf[idx];
356                   } else {
357                     idx = -idx - 1;
358                     coef_buff[f*Nb+b] = 0;
359                     for (int q = 0; q < d_maps->num_face; q++) {
360                       PetscInt    id = d_maps->c_maps[idx][q].gid;
361                       PetscScalar scale = d_maps->c_maps[idx][q].scale;
362                       coef_buff[f*Nb+b] += scale*d_IPf[id];
363                     }
364                   }
365                   //printf("%f ",coef[f*Nb+b]);
366                 }
367                 //printf("\n");
368               }
369               //printf("\n");
370             }
371             Kokkos::parallel_for(Kokkos::TeamThreadRange(team,0,Nq), [=] (int myQi) {
372                 const PetscInt          ipidx = myQi + myelem * Nq;
373                 const PetscReal *const  invJj = &d_invJ_k(ipidx*dim*dim);
374                 const PetscReal         *Bq = &d_BB[myQi*Nb], *Dq = &d_DD[myQi*Nb*dim];
375                 Kokkos::parallel_for(Kokkos::ThreadVectorRange(team,0,(int)Nf), [=] (int f) {
376                     PetscInt     b, e, d;
377                     PetscReal  refSpaceDer[LANDAU_DIM];
378                     d_fdf_k(0,f,ipidx) = 0.0;
379                     for (d = 0; d < LANDAU_DIM; ++d) refSpaceDer[d] = 0.0;
380                     for (b = 0; b < Nb; ++b) {
381                       const PetscInt    cidx = b;
382                       d_fdf_k(0,f,ipidx) += Bq[cidx]*PetscRealPart(coef[f*Nb+cidx]);
383                       for (d = 0; d < dim; ++d) refSpaceDer[d] += Dq[cidx*dim+d]*PetscRealPart(coef[f*Nb+cidx]);
384                     }
385                     for (d = 0; d < dim; ++d) {
386                       for (e = 0, d_fdf_k(d+1,f,ipidx) = 0.0; e < dim; ++e) {
387                         d_fdf_k(d+1,f,ipidx) += invJj[e*dim+d]*refSpaceDer[e];
388                       }
389                     }
390                   }); // Nf
391               }); // Nq
392           }); // elems
393         Kokkos::fence();
394 #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
395         ierr = PetscLogGpuFlops(nip*(PetscLogDouble)(2*Nb*(1+dim)));CHKERRQ(ierr);
396 #else
397         ierr = PetscLogFlops(nip*(PetscLogDouble)(2*Nb*(1+dim)));CHKERRQ(ierr);
398 #endif
399         ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
400         ierr = PetscLogEventEnd(events[8],0,0,0,0);CHKERRQ(ierr);
401       }
402       ierr = PetscLogEventBegin(events[4],0,0,0,0);CHKERRQ(ierr);
403       ierr = PetscLogGpuTimeBegin();CHKERRQ(ierr);
404 #if defined(PETSC_HAVE_CUDA) || defined(PETSC_HAVE_HIP)
405       ierr = PetscLogGpuFlops(nip*(PetscLogDouble)(!(a_IPf || a_xarray) ? (nip*(11*Nf+ 4*dim*dim) + 6*Nf*dim*dim*dim + 10*Nf*dim*dim + 4*Nf*dim + Nb*Nf*Nb*Nq*dim*dim*5) : Nb*Nf*Nb*Nq*4));CHKERRQ(ierr);
406       if (ctx->deviceType == LANDAU_CPU) PetscInfo(plex, "Warning: Landau selected CPU but no support for Kokkos using CPU\n");
407 #else
408       ierr = PetscLogFlops(nip*(PetscLogDouble)(!(a_IPf || a_xarray) ? (nip*(11*Nf+ 4*dim*dim) + 6*Nf*dim*dim*dim + 10*Nf*dim*dim + 4*Nf*dim + Nb*Nf*Nb*Nq*dim*dim*5) : Nb*Nf*Nb*Nq*4));CHKERRQ(ierr);
409 #endif
410       Kokkos::parallel_for("Landau elements", Kokkos::TeamPolicy<>(numCells, team_size, /*Kokkos::AUTO*/ 16).set_scratch_size(KOKKOS_SHARED_LEVEL, Kokkos::PerTeam(scr_bytes)), KOKKOS_LAMBDA (const team_member team) {
411           const PetscInt  myelem = team.league_rank();
412           g2_scr_t        g2(team.team_scratch(KOKKOS_SHARED_LEVEL),dim,Nf,Nq); // we don't use these for mass matrix
413           g3_scr_t        g3(team.team_scratch(KOKKOS_SHARED_LEVEL),dim,dim,Nf,Nq);
414           if (d_IPf) {
415             g2_scr_t        gg2(team.team_scratch(KOKKOS_SHARED_LEVEL),dim,Nf,Nq);
416             g3_scr_t        gg3(team.team_scratch(KOKKOS_SHARED_LEVEL),dim,dim,Nf,Nq);
417             // get g2[] & g3[]
418             Kokkos::parallel_for(Kokkos::TeamThreadRange(team,0,Nq), [=] (int myQi) {
419                 using Kokkos::parallel_reduce;
420                 const PetscInt                    jpidx = myQi + myelem * Nq;
421                 const PetscReal* const            invJj = &d_invJ_k(jpidx*dim*dim);
422                 const PetscReal                   vj[3] = {d_x[jpidx], d_y[jpidx], d_z ? d_z[jpidx] : 0}, wj = d_w[jpidx];
423                 landau_inner_red::TensorValueType gg_temp; // reduce on part of gg2 and g33 for IP jpidx
424                 Kokkos::parallel_reduce(Kokkos::ThreadVectorRange (team, (int)nip), [=] (const int& ipidx, landau_inner_red::TensorValueType & ggg) {
425                     const PetscReal wi = d_w[ipidx], x = d_x[ipidx], y = d_y[ipidx];
426                     PetscReal       temp1[3] = {0, 0, 0}, temp2 = 0;
427                     PetscInt        fieldA,d2,d3;
428 #if LANDAU_DIM==2
429                     PetscReal Ud[2][2], Uk[2][2];
430                     LandauTensor2D(vj, x, y, Ud, Uk, (ipidx==jpidx) ? 0. : 1.);
431 #else
432                     PetscReal U[3][3], z = d_z[ipidx];
433                     LandauTensor3D(vj, x, y, z, U, (ipidx==jpidx) ? 0. : 1.);
434 #endif
435                     for (fieldA = 0; fieldA < Nf; ++fieldA) {
436                       temp1[0] += d_fdf_k(1,fieldA,ipidx)*d_beta[fieldA]*d_invMass[fieldA];
437                       temp1[1] += d_fdf_k(2,fieldA,ipidx)*d_beta[fieldA]*d_invMass[fieldA];
438 #if LANDAU_DIM==3
439                       temp1[2] += d_fdf_k(3,fieldA,ipidx)*d_beta[fieldA]*d_invMass[fieldA];
440 #endif
441                       temp2    += d_fdf_k(0,fieldA,ipidx)*d_beta[fieldA];
442                     }
443                     temp1[0] *= wi;
444                     temp1[1] *= wi;
445 #if LANDAU_DIM==3
446                     temp1[2] *= wi;
447 #endif
448                     temp2    *= wi;
449 #if LANDAU_DIM==2
450                     for (d2 = 0; d2 < 2; d2++) {
451                       for (d3 = 0; d3 < 2; ++d3) {
452                         /* K = U * grad(f): g2=e: i,A */
453                         ggg.gg2[d2] += Uk[d2][d3]*temp1[d3];
454                         /* D = -U * (I \kron (fx)): g3=f: i,j,A */
455                         ggg.gg3[d2][d3] += Ud[d2][d3]*temp2;
456                       }
457                     }
458 #else
459                     for (d2 = 0; d2 < 3; ++d2) {
460                       for (d3 = 0; d3 < 3; ++d3) {
461                         /* K = U * grad(f): g2 = e: i,A */
462                         ggg.gg2[d2] += U[d2][d3]*temp1[d3];
463                         /* D = -U * (I \kron (fx)): g3 = f: i,j,A */
464                         ggg.gg3[d2][d3] += U[d2][d3]*temp2;
465                       }
466                     }
467 #endif
468                   }, Kokkos::Sum<landau_inner_red::TensorValueType>(gg_temp));
469                 // if (myelem==0) printf("\t:%d.%d) temp gg3=%e %e %e %e\n",myelem,myQi,gg_temp.gg3[0][0],gg_temp.gg3[1][0],gg_temp.gg3[0][1],gg_temp.gg3[1][1]);
470                 // add alpha and put in gg2/3
471                 Kokkos::parallel_for(Kokkos::ThreadVectorRange (team, (int)Nf), [&] (const int& fieldA) {
472                     PetscInt d2,d3;
473                     for (d2 = 0; d2 < dim; d2++) {
474                       gg2(d2,fieldA,myQi) = gg_temp.gg2[d2]*d_alpha[fieldA];
475                       //if (myelem==0 && fieldA==1) printf("\t\t:%d.%d) gg2[%d]=%e = %e %e\n",myelem,myQi,d2,gg2(d2,fieldA,myQi),gg_temp.gg2[d2],d_alpha[fieldA]);
476                       //gg2[d2][myQi][fieldA] += gg_temp.gg2[d2]*d_alpha[fieldA];
477                       for (d3 = 0; d3 < dim; d3++) {
478                         //gg3[d2][d3][myQi][fieldA] -= gg_temp.gg3[d2][d3]*d_alpha[fieldA]*s_invMass[fieldA];
479                         gg3(d2,d3,fieldA,myQi) = -gg_temp.gg3[d2][d3]*d_alpha[fieldA]*d_invMass[fieldA];
480                         //if (myelem==0 && fieldA==1) printf("\t\t\t:%d.%d) gg3[%d][%d]=%e\n",myelem,myQi,d2,d3,gg3(d2,d3,fieldA,myQi));
481                       }
482                     }
483                   });
484                 /* add electric field term once per IP */
485                 Kokkos::parallel_for(Kokkos::ThreadVectorRange (team, (int)Nf), [&] (const int& fieldA) {
486                     //gg.gg2[fieldA][dim-1] += d_Eq_m[fieldA];
487                     gg2(dim-1,fieldA,myQi) += d_Eq_m[fieldA];
488                   });
489                 // Kokkos::single(Kokkos::PerThread(team), [&]() {
490                 Kokkos::parallel_for(Kokkos::ThreadVectorRange (team, (int)Nf), [=] (const int& fieldA) {
491                     int d,d2,d3,dp;
492                     //printf("%d %d %d gg2[][1]=%18.10e\n",myelem,myQi,fieldA,gg.gg2[fieldA][dim-1]);
493                     /* Jacobian transform - g2, g3 - per thread (2D) */
494                     for (d = 0; d < dim; ++d) {
495                       g2(d,fieldA,myQi) = 0;
496                       for (d2 = 0; d2 < dim; ++d2) {
497                         g2(d,fieldA,myQi) += invJj[d*dim+d2]*gg2(d2,fieldA,myQi);
498                         //if (myelem==0 && myQi==0) printf("\t:g2[%d][%d][%d]=%e. %e %e\n",(int)myQi,(int)fieldA,(int)d,g2(fieldA,myQi,d),invJj[d*dim+d2],gg.gg2[fieldA][d2]);
499                         g3(d,d2,fieldA,myQi) = 0;
500                         for (d3 = 0; d3 < dim; ++d3) {
501                           for (dp = 0; dp < dim; ++dp) {
502                             g3(d,d2,fieldA,myQi) += invJj[d*dim + d3]*gg3(d3,dp,fieldA,myQi)*invJj[d2*dim + dp];
503                             //printf("\t%d %d %d %d %d %d %d g3=%g wj=%g g3 = %g * %g * %g\n",myelem,myQi,fieldA,d,d2,d3,dp,g3(fieldA,myQi,d,d2),wj,invJj[d*dim + d3],gg.gg3[fieldA][d3][dp],invJj[d2*dim + dp]);
504                           }
505                         }
506                         g3(d,d2,fieldA,myQi) *= wj;
507                       }
508                       g2(d,fieldA,myQi) *= wj;
509                     }
510                   });
511               }); // Nq
512             team.team_barrier();
513           } // Jacobian
514           /* assemble */
515           //Kokkos::single(Kokkos::PerTeam(team), [&]() {
516           Kokkos::parallel_for(Kokkos::TeamThreadRange(team,0,Nb), [=] (int blk_i) {
517               Kokkos::parallel_for(Kokkos::ThreadVectorRange(team,0,(int)Nf), [=] (int fieldA) {
518                   int blk_j,qj,d,d2;
519                   const PetscInt i = fieldA*Nb + blk_i; /* Element matrix row */
520                   for (blk_j = 0; blk_j < Nb; ++blk_j) {
521                     const PetscInt j    = fieldA*Nb + blk_j; /* Element matrix column */
522                     const PetscInt fOff = i*totDim + j;
523                     PetscScalar t = global_elem_mat_sz ? d_elem_mats(myelem,fOff) : 0;
524                     for (qj = 0 ; qj < Nq ; qj++) { // look at others integration points
525                       const PetscReal *BJq = &d_BB[qj*Nb], *DIq = &d_DD[qj*Nb*dim];
526                       if (d_IPf) {
527                         for (d = 0; d < dim; ++d) {
528                           t += DIq[blk_i*dim+d]*g2(d,fieldA,qj)*BJq[blk_j];
529                           for (d2 = 0; d2 < dim; ++d2) {
530                             t += DIq[blk_i*dim + d]*g3(d,d2,fieldA,qj)*DIq[blk_j*dim + d2];
531                           }
532                         }
533                       } else {
534                         const PetscInt jpidx = qj + myelem * Nq;
535                         t += BJq[blk_i] * d_mass_w_k(jpidx) * shift * BJq[blk_j];
536                       }
537                     }
538                     if (global_elem_mat_sz) d_elem_mats(myelem,fOff) = t; // can set this because local element matrix[fOff]
539                     else {
540                       PetscErrorCode         ierr = 0;
541                       PetscScalar            vals[LANDAU_MAX_Q_FACE*LANDAU_MAX_Q_FACE],row_scale[LANDAU_MAX_Q_FACE],col_scale[LANDAU_MAX_Q_FACE];
542                       PetscInt               q,idx,nr,nc,rows0[LANDAU_MAX_Q_FACE],cols0[LANDAU_MAX_Q_FACE],rows[LANDAU_MAX_Q_FACE],cols[LANDAU_MAX_Q_FACE];
543                       const LandauIdx *const Idxs = &d_maps->gIdx[myelem][fieldA][0];
544                       idx = Idxs[blk_i];
545                       if (idx >= 0) {
546                         nr = 1;
547                         rows0[0] = idx;
548                         row_scale[0] = 1.;
549                       } else {
550                         idx = -idx - 1;
551                         nr = d_maps->num_face;
552                         for (q = 0; q < d_maps->num_face; q++) {
553                           rows0[q]     = d_maps->c_maps[idx][q].gid;
554                           row_scale[q] = d_maps->c_maps[idx][q].scale;
555                         }
556                       }
557                       idx = Idxs[blk_j];
558                       if (idx >= 0) {
559                         nc = 1;
560                         cols0[0] = idx;
561                         col_scale[0] = 1.;
562                       } else {
563                         idx = -idx - 1;
564                         nc = d_maps->num_face;
565                         for (q = 0; q < d_maps->num_face; q++) {
566                           cols0[q]     = d_maps->c_maps[idx][q].gid;
567                           col_scale[q] = d_maps->c_maps[idx][q].scale;
568                         }
569                       }
570                       for (q = 0; q < nr; q++) rows[q] = rows0[q];
571                       for (q = 0; q < nc; q++) cols[q] = cols0[q];
572                       for (q = 0; q < nr; q++) {
573                         for (d = 0; d < nc; d++) {
574                           vals[q*nc + d] = row_scale[q]*col_scale[d]*t;
575                         }
576                       }
577                       MatSetValuesDevice(d_mat,nr,rows,nc,cols,vals,ADD_VALUES,&ierr);
578                       if (ierr) return;
579                     }
580                   }
581                 });
582             });
583         });
584       ierr = PetscLogGpuTimeEnd();CHKERRQ(ierr);
585       Kokkos::fence();
586       ierr = PetscLogEventEnd(events[4],0,0,0,0);CHKERRQ(ierr);
587       if (global_elem_mat_sz) {
588         PetscSection      section, globalSection;
589         Kokkos::View<PetscScalar**, Kokkos::LayoutRight>::HostMirror h_elem_mats = Kokkos::create_mirror_view(d_elem_mats);
590         ierr = PetscLogEventBegin(events[5],0,0,0,0);CHKERRQ(ierr);
591         ierr = DMGetLocalSection(plex, &section);CHKERRQ(ierr);
592         ierr = DMGetGlobalSection(plex, &globalSection);CHKERRQ(ierr);
593         Kokkos::deep_copy (h_elem_mats, d_elem_mats);
594         ierr = PetscLogEventEnd(events[5],0,0,0,0);CHKERRQ(ierr);
595         ierr = PetscLogEventBegin(events[6],0,0,0,0);CHKERRQ(ierr);
596         PetscInt ej;
597         for (ej = cStart ; ej < cEnd; ++ej) {
598           const PetscScalar *elMat = &h_elem_mats(ej-cStart,0);
599           ierr = DMPlexMatSetClosure(plex, section, globalSection, JacP, ej, elMat, ADD_VALUES);CHKERRQ(ierr);
600           if (ej==-1) {
601             int d,f;
602             PetscPrintf(PETSC_COMM_SELF,"Kokkos Element matrix %d/%d\n",1,(int)numCells);
603             for (d = 0; d < totDim; ++d){
604               for (f = 0; f < totDim; ++f) PetscPrintf(PETSC_COMM_SELF," %12.5e",  PetscRealPart(elMat[d*totDim + f]));
605               PetscPrintf(PETSC_COMM_SELF,"\n");
606             }
607             exit(14);
608           }
609         }
610         ierr = PetscLogEventEnd(events[6],0,0,0,0);CHKERRQ(ierr);
611         // transition to use of maps for VecGetClosure
612         {
613           auto IPf = static_cast<Kokkos::View<PetscScalar*, Kokkos::LayoutLeft>*>(SData_d->IPf);
614           delete IPf;
615           SData_d->IPf = NULL;
616         }
617         if (!(a_IPf || a_xarray)) SETERRQ(PETSC_COMM_SELF, PETSC_ERR_PLIB, "transition without Jacobian");
618       }
619     }
620     PetscFunctionReturn(0);
621   }
622 } // extern "C"
623