-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathNumpyEntryPoint.java
418 lines (322 loc) · 14.9 KB
/
NumpyEntryPoint.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
package ai.konduit.pipelinegenerator.main;
import ai.konduit.serving.pipeline.api.data.Data;
import ai.konduit.serving.pipeline.api.data.NDArray;
import ai.konduit.serving.pipeline.api.pipeline.Pipeline;
import ai.konduit.serving.pipeline.api.pipeline.PipelineExecutor;
import org.bytedeco.javacpp.Loader;
import org.bytedeco.javacpp.Pointer;
import org.graalvm.nativeimage.ImageSingletons;
import org.graalvm.nativeimage.IsolateThread;
import org.graalvm.nativeimage.ObjectHandle;
import org.graalvm.nativeimage.UnmanagedMemory;
import org.graalvm.nativeimage.c.CContext;
import org.graalvm.nativeimage.c.function.CEntryPoint;
import org.graalvm.nativeimage.c.struct.CField;
import org.graalvm.nativeimage.c.struct.CPointerTo;
import org.graalvm.nativeimage.c.struct.CStruct;
import org.graalvm.nativeimage.c.struct.SizeOf;
import org.graalvm.nativeimage.c.type.*;
import org.graalvm.nativeimage.hosted.Feature;
import org.graalvm.word.PointerBase;
import org.graalvm.word.SignedWord;
import org.graalvm.word.WordFactory;
import org.nd4j.common.base.Preconditions;
import org.nd4j.common.io.ClassPathResource;
import org.nd4j.common.util.ArrayUtil;
import org.nd4j.linalg.api.buffer.DataBuffer;
import org.nd4j.linalg.api.buffer.DataType;
import org.nd4j.linalg.api.memory.AllocationsTracker;
import org.nd4j.linalg.api.ndarray.INDArray;
import org.nd4j.linalg.factory.Nd4j;
import org.nd4j.linalg.factory.Nd4jBackend;
import org.nd4j.nativeblas.NativeOps;
import org.nd4j.nativeblas.NativeOpsHolder;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
@CContext(NumpyEntryPoint.NumpyEntryPointDirectives.class)
public class NumpyEntryPoint {
static class NumpyEntryPointDirectives implements CContext.Directives {
@Override
public List<String> getHeaderFiles() {
File kompileDir = new File(System.getProperty("user.home"),".kompile");
File headersDir = new File(kompileDir,"headers");
return Collections.singletonList("\"" + headersDir.getAbsolutePath() + "/numpy_struct.h" + "\"");
}
}
@CStruct("numpy_struct")
interface NumpyStruct extends PointerBase {
@CField("num_arrays")
int numArrays();
@CField("num_arrays")
void setNumArrays(int length);
@CField("numpy_array_addresses")
CLongPointer getNumpyArrayAddresses();
@CField("numpy_array_ranks")
CLongPointer getNumpyArrayRanks();
@CField("numpy_array_shapes")
CLongPointerPointer getNumpyArrayShapes();
@CField("numpy_array_data_types")
CCharPointerPointer getNumpyArrayDataTypes();
@CField("numpy_array_data_types")
void setNumpyArrayDataTypes(CCharPointerPointer numpyArrayDataTypes);
@CField("numpy_array_addresses")
void setNumpyArrayAddresses(CLongPointerPointer numpyArrayAddresses);
@CField("numpy_array_ranks")
void setNumpyArrayRanks(CLongPointer numpyArrayRanks);
@CField("numpy_array_shapes")
void setNumpyArrayShapes(CLongPointerPointer numpyArrayAddresses);
@CField("numpy_array_names")
CCharPointerPointer getNumpyArrayNames();
@CField("numpy_array_names")
void setArrayNames(CCharPointerPointer numpyArrayNames);
}
/**
* A pointer to a pointer to a 64-bit C primitive value.
*
* @since 19.0
*/
@CPointerTo(CLongPointer.class)
public interface CLongPointerPointer extends PointerBase {
/**
* Reads the value at the pointer address.
*
* @since 19.0
*/
CLongPointer read();
/**
* Reads the value of the array element with the specified index, treating the pointer as an
* array of the C type.
*
* @since 19.0
*/
CLongPointer read(int index);
/**
* Reads the value of the array element with the specified index, treating the pointer as an
* array of the C type.
*
* @since 19.0
*/
CIntPointer read(SignedWord index);
/**
* Writes the value at the pointer address.
*
* @since 19.0
*/
void write(CLongPointer value);
/**
* Writes the value of the array element with the specified index, treating the pointer as an
* array of the C type.
*
* @since 19.0
*/
void write(int index, CLongPointer value);
/**
* Writes the value of the array element with the specified index, treating the pointer as an
* array of the C type.
*
* @since 19.0
*/
void write(SignedWord index, CLongPointer value);
/**
* Computes the address of the array element with the specified index, treating the pointer as
* an array of the C type.
*
* @since 19.0
*/
CLongPointer addressOf(int index);
/**
* Computes the address of the array element with the specified index, treating the pointer as
* an array of the C type.
*
* @since 19.0
*/
CLongPointer addressOf(SignedWord index);
}
@CStruct("handles")
interface Handles extends PointerBase {
@CField("native_ops_handle")
ObjectHandle getNativeOpsHandle();
@CField("native_ops_handle")
void setNativeOpsHandle(ObjectHandle nativeOpsHandle);
@CField("pipeline_handle")
void setPipelineHandle(ObjectHandle pipelineHandle);
@CField("pipeline_handle")
ObjectHandle getPipelineHandle();
@CField("executor_handle")
void setExecutorHandle(ObjectHandle executorHandle);
@CField("executor_handle")
ObjectHandle getExecutorHandle();
}
@CEntryPoint(name = "initPipeline")
public static int initPipeline(IsolateThread isolate, Handles handles, CCharPointer pipelinePath) {
try {
String pipelinePath2 = CTypeConversion.toJavaString(pipelinePath);
System.setProperty("pipeline.path",pipelinePath2);
System.setProperty("org.eclipse.python4j.numpyimport", "false");
System.setProperty("org.eclipse.python4j.release_gil_automatically", "false");
System.setProperty("org.eclipse.python4j.path.append", "none");
if(System.getenv().containsKey("KOMPILE_PROPERTIES")) {
File kompileProperties = new File(System.getenv("KOMPILE_PROPERTIES"));
System.out.println("Loading properties from " + System.getenv("KOMPILE_PROPERTIES"));
Properties properties = new Properties();
FileInputStream fileInputStream = new FileInputStream(kompileProperties);
properties.load(fileInputStream);
System.getProperties().putAll(properties);
}
Holder.init();
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public static class Holder {
private static NativeOps nativeOps = null;
private static Pipeline pipeline;
private static PipelineExecutor pipelineExecutor;
public static void init() {
try {
Nd4jBackend load = Nd4jBackend.load();
if(load.getClass().getName().toLowerCase().contains("cpu")) {
Class<? extends NativeOps> nativeOpsClazz = (Class<? extends NativeOps>) Class.forName("org.nd4j.linalg.cpu.nativecpu.bindings.Nd4jCpu");
nativeOps = nativeOpsClazz.newInstance();
} else if(load.getClass().getName().toLowerCase().contains("cuda")) {
Class<? extends NativeOps> nativeOpsClazz = (Class<? extends NativeOps>) Class.forName("org.nd4j.linalg.jcublas.bindings.Nd4jCuda");
nativeOps = nativeOpsClazz.newInstance();
} else if(load.getClass().getName().toLowerCase().contains("aurora")) {
Class<? extends NativeOps> nativeOpsClazz = (Class<? extends NativeOps>) Class.forName("org.nd4j.aurora.Nd4jAuroraOps");
nativeOps = nativeOpsClazz.newInstance();
}
}catch (Exception e) {
throw new RuntimeException(e);
}
String pipelinePath = System.getProperty("pipeline.path");
if (pipeline == null)
pipeline = Pipeline.fromJson(pipelinePath);
if (pipelineExecutor == null)
pipelineExecutor = pipeline.executor();
}
public static PipelineExecutor getPipelineExecutor() {
return pipelineExecutor;
}
public static Pipeline getPipeline() {
return pipeline;
}
public static NativeOps getNativeOps() {
return nativeOps;
}
}
@CEntryPoint(name = "runPipeline")
public static int runPipeline(IsolateThread isolate, Handles handles, NumpyStruct numpyInput, NumpyStruct numpyOutput) {
try {
runPipeline(handles, numpyInput, numpyOutput);
return 0;
} catch (Exception e) {
e.printStackTrace();
return 1;
}
}
public static void runPipeline(Handles handles, NumpyStruct numpyInput, NumpyStruct numpyOutput) throws Exception {
int length = numpyInput.numArrays();
CCharPointerPointer numpyArrayNames = numpyInput.getNumpyArrayNames();
//PinnedObject deviceNativeOpsPinned = ObjectHandles.getGlobal().get(handles.getNativeOpsHandle());
//NativeOps deviceNativeOps = ImageSingletons.lookup(NativeOps.class);
NativeOps deviceNativeOps = Holder.getNativeOps();
//PinnedObject pipelinePinned = ObjectHandles.getGlobal().get(handles.getPipelineHandle());
Pipeline pipeline = Holder.getPipeline();
//PinnedObject pipelineExecutorPinned = ObjectHandles.getGlobal().get(handles.getPipelineHandle());
PipelineExecutor pipelineExecutor = Holder.getPipelineExecutor();
if(pipelineExecutor == null) {
throw new IllegalStateException("Pipeline executioner was null!");
}
String[] namesJava = new String[length];
for (int i = 0; i < length; i++) {
namesJava[i] = CTypeConversion.toJavaString(numpyArrayNames.read(i));
}
CLongPointer numpyArrayAddressesInput = numpyInput.getNumpyArrayAddresses();
long[] addresses = new long[length];
for (int i = 0; i < length; i++) {
addresses[i] = numpyArrayAddressesInput.read(i);
}
long[] ranks = new long[length];
for (int i = 0; i < ranks.length; i++) {
ranks[i] = numpyInput.getNumpyArrayRanks().read(i);
}
long[][] shapes = new long[length][];
for (int i = 0; i < length; i++) {
shapes[i] = new long[(int) ranks[i]];
for (int j = 0; j < ranks[i]; j++) {
shapes[i][j] = numpyInput.getNumpyArrayShapes().read(i).read(j);
}
}
String[] dataTypes = new String[length];
for (int i = 0; i < length; i++) {
dataTypes[i] = CTypeConversion.toJavaString(numpyInput.getNumpyArrayDataTypes().read(i));
}
INDArray[] newArrs = new INDArray[length];
for (int i = 0; i < length; i++) {
long read = addresses[i];
Pointer pointer = deviceNativeOps.pointerForAddress(read);
long len = ArrayUtil.prod(shapes[i]);
pointer.limit(len * DataType.valueOf(dataTypes[i]).width());
DataBuffer dataBuffer = Nd4j.createBuffer(pointer, len, DataType.valueOf(dataTypes[i]));
INDArray arr = Nd4j.create(dataBuffer, shapes[i]);
newArrs[i] = arr;
System.out.println(dataBuffer);
}
Data input = Data.empty();
for (int i = 0; i < length; i++) {
Preconditions.checkNotNull(newArrs[i],"New array for item " + i + " was null!");
Preconditions.checkNotNull(namesJava[i],"New name for item " + i + " was null!");
input.put(namesJava[i], NDArray.create(newArrs[i]));
}
Data exec = pipelineExecutor.exec(input);
numpyOutput.setNumArrays(exec.keys().size());
int size = SizeOf.get(CLongPointer.class) * exec.size();
String[] outputNames = new String[exec.size()];
PointerBase numpyArraysPointer = UnmanagedMemory.calloc(size);
CLongPointerPointer numpyArrayAddresses = WordFactory.pointer(numpyArraysPointer.rawValue());
int currKeyIdx = 0;
CLongPointerPointer shapes2 = UnmanagedMemory.calloc(SizeOf.get(CLongPointerPointer.class) * exec.size());
numpyOutput.setNumpyArrayShapes(shapes2);
CLongPointer rankPointer = UnmanagedMemory.calloc(SizeOf.get(CLongPointer.class) * exec.size());
numpyOutput.setNumpyArrayRanks(rankPointer);
CCharPointerPointer dataTypesOutput = UnmanagedMemory.calloc(SizeOf.get(CCharPointerPointer.class) * exec.size());
numpyOutput.setNumpyArrayDataTypes(dataTypesOutput);
for (String key : exec.keys()) {
INDArray arr = exec.getNDArray(key).getAs(INDArray.class);
long address = arr.data().address();
PointerBase cLong = UnmanagedMemory.calloc(SizeOf.get(CLongPointer.class));
CLongPointer cLongPointer = WordFactory.pointer(cLong.rawValue());
cLongPointer.write(address);
numpyArrayAddresses.write(currKeyIdx, cLongPointer);
outputNames[currKeyIdx] = key;
CLongPointer shape = UnmanagedMemory.calloc(SizeOf.get(CLongPointer.class) * arr.rank());
for (int i = 0; i < arr.rank(); i++) {
shape.write(i, arr.size(i));
}
rankPointer.write(currKeyIdx, arr.rank());
shapes2.write(currKeyIdx, shape);
CCharPointer dataTypePointer = CTypeConversion.toCString(arr.dataType().name().toUpperCase()).get();
dataTypesOutput.write(currKeyIdx, dataTypePointer);
currKeyIdx++;
}
CTypeConversion.CCharPointerPointerHolder cCharPointerPointerHolder = CTypeConversion.toCStrings(outputNames);
numpyOutput.setNumpyArrayAddresses(numpyArrayAddresses);
numpyOutput.setArrayNames(cCharPointerPointerHolder.get());
numpyOutput.setNumArrays(exec.keys().size());
}
@CEntryPoint(name = "printMetrics")
public static void printMetrics(IsolateThread isolate) {
int numDevices = Nd4j.getAffinityManager().getNumberOfDevices();
for(int i = 0; i < numDevices; i++) {
long allocated = AllocationsTracker.getInstance().bytesOnDevice(i);
System.out.println("Allocated memory in bytes via allocation tracker is " + allocated);
}
System.out.println("Available physical bytes is " + Pointer.availablePhysicalBytes());
System.out.println("Memory used is " + Pointer.totalBytes());
}
}