[Android] print type name for IValues (#64602)
authorLinbin Yu <linbin@fb.com>
Thu, 9 Sep 2021 23:56:50 +0000 (16:56 -0700)
committerFacebook GitHub Bot <facebook-github-bot@users.noreply.github.com>
Fri, 10 Sep 2021 00:06:15 +0000 (17:06 -0700)
Summary:
Pull Request resolved: https://github.com/pytorch/pytorch/pull/64602

print type name in error message for easier debugging.

Test Plan:
Example:
java.lang.IllegalStateException: Expected IValue type Tensor, actual type TensorList

Reviewed By: beback4u

Differential Revision: D30782318

fbshipit-source-id: 60d88a659e7b4bb2b574b12c7652a28f0d5ad0d2

android/pytorch_android/src/main/java/org/pytorch/IValue.java

index 50ce61c..28ebf7a 100644 (file)
@@ -40,6 +40,24 @@ public class IValue {
   private static final int TYPE_CODE_DICT_STRING_KEY = 13;
   private static final int TYPE_CODE_DICT_LONG_KEY = 14;
 
+  private String[] TYPE_NAMES = {
+    "Unknown",
+    "Null",
+    "Tensor",
+    "Bool",
+    "Long",
+    "Double",
+    "String",
+    "Tuple",
+    "BoolList",
+    "LongList",
+    "DoubleList",
+    "TensorList",
+    "GenericList",
+    "DictStringKey",
+    "DictLongKey",
+  };
+
   @DoNotStrip private final int mTypeCode;
   @DoNotStrip private Object mData;
 
@@ -312,7 +330,14 @@ public class IValue {
     if (typeCode != typeCodeExpected) {
       throw new IllegalStateException(
           String.format(
-              Locale.US, "Expected IValue type %d, actual type %d", typeCodeExpected, typeCode));
+              Locale.US,
+              "Expected IValue type %s, actual type %s",
+              getTypeName(typeCodeExpected),
+              getTypeName(typeCode)));
     }
   }
+
+  private String getTypeName(int typeCode) {
+    return typeCode >= 0 && typeCode < TYPE_NAMES.length ? TYPE_NAMES[typeCode] : "Unknown";
+  }
 }