You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Advice needed: how to check number of/any CUDA devices available? #614
TensorFlow Java calls the C/C++ API of TensorFlow underneath. Many functions are wrapped by an idiomatic Java interface for user-friendliness, but that requires some manual work, hence we don't have a wrapper for all of them. Turns out that listing the devices falls in the category of not being wrapped (unless I missed it?), so you need to invoke directly the less user-friendly C interface via our JNI adapter.
Something like that works out for me, it should be fairly simple to wrap this up as a utility method of the EagerSession object though, let me know if you are interested in doing it, otherwise I might give it a try:
importorg.tensorflow.internal.c_api.*;
importstaticorg.tensorflow.internal.c_api.global.tensorflow.*;
publicclassDevices {
publicstaticvoidprintDevices() {
try (TF_Statusstatus = TF_Status.newStatus()) {
TFE_ContextOptionsoptions = TFE_ContextOptions.newContextOptions();
TFE_Contextcontext = TFE_Context.newContext(options, status);
status.throwExceptionIfNotOK();
TF_DeviceListdeviceList = TFE_ContextListDevices(context, status);
status.throwExceptionIfNotOK();
intnumDevices = TF_DeviceListCount(deviceList);
for (inti = 0; i < numDevices; i++) {
StringdeviceName = TF_DeviceListName(deviceList, i, status).getString();
status.throwExceptionIfNotOK();
StringdeviceType = TF_DeviceListType(deviceList, i, status).getString();
status.throwExceptionIfNotOK();
System.out.println("Device " + i + ": " + deviceName + ", type: " + deviceType);
}
// TODO: make sure to release resources even when an exception has been thrownTF_DeleteDeviceList(deviceList);
TFE_DeleteContext(context);
TFE_DeleteContextOptions(options);
}
}
}
Activity
karllessard commentedon Jun 29, 2025
TensorFlow Java calls the C/C++ API of TensorFlow underneath. Many functions are wrapped by an idiomatic Java interface for user-friendliness, but that requires some manual work, hence we don't have a wrapper for all of them. Turns out that listing the devices falls in the category of not being wrapped (unless I missed it?), so you need to invoke directly the less user-friendly C interface via our JNI adapter.
Something like that works out for me, it should be fairly simple to wrap this up as a utility method of the
EagerSessionobject though, let me know if you are interested in doing it, otherwise I might give it a try: