Anyone tried out the PyTorch Mobile demo apps yet?

jspisak: <p>Would love the feedback!</p>

tom: <p>So I gave it a shot for android but immediately entered a world of pain that probably is entirely unrelated to PyTorch but more with Android and my lack of Android experience.</p>
<p>I should admit that my experience with Android is very limited (I adapted the Caffe2 AI Camera demo app to use PyTorch with the ResNet, MarkRCNN, and Style Transfer about a year ago and ported PyTorch to Android for it, but that is about it).</p>
<p>Some of these comments might eventually lead to useful additions to the tutorial, but I don’t think I’m there yet.</p>
<p>The tutorial says:</p>
<blockquote>
<p>We recommend you to open this project in <a href="https://developer.android.com/studio" rel="noopener nofollow ugc">Android Studio</a>, in that case you will be able to install Android NDK and Android SDK using Android Studio UI.</p>
</blockquote>
<p>This looks foolproof, but it seems not quite Thomas-poof:</p>
<ul>
<li>It seems that you absolutely need to use the latest Android studio (mine was, I’m guessing, about 10 months old) - if you don’t have it, you get the most undescriptive error messages for an internet search reveals meant “upgrade to latest android studio” three versions ago, too,</li>
<li>Maybe one could say that one shoud <em>Import</em> the (gradle) project rather than opening it. Opening did nothing for me.</li>
</ul>
<p>Then I tried the Hello World app:</p>
<ul>
<li>Didn’t seem to work on the Android Emulator - I just got a white screen.</li>
<li>Works on actual hardware (I get a Wolf or dog classified as such).</li>
</ul>
<p>Happily, the PyTorch demo app worked better - it worked on both.</p>
<p>On my phone  (BQ Aquaris U Plus, so not a high-end phone), I get ~3.5x images / second for the quantized resnet. This left me wondering what I should expect. In particular, I have been wondering whether the PyTorch build I’m using is a debug or a release build - I realize that Android release builds come with signing and stuff, so it would be a debug build from the android studio side, but that doesn’t necessarily mean anything for the PyTorch library itself. I am guessing that it is a non-debug build of PyTorch – with the assumption that most people don’t need that even when they are debugging their app.</p>
<p>It is neat so see this work out and I admire that you furnished a text classification example, too. It would be supercool if you could add the model construction / serialization for the quantized resnet and text app, too (the HelloWorld app has the (trivially) simple tracing of resnet 18, but I didn’t see them for the PyTorch demo app).</p>
<p>All in all, it looks good! Thank you.</p>
<p>Best regards</p>
<p>Thomas</p>

David_Reiss: <p>Thanks for the feedback!  We’ll get the docs updated and figure out why HelloWorld isn’t working on the emulator.</p>
<p>The ResNet model is not quantized and expected to be fairly slow.  We might just delete it from the demo app.</p>
<p>The quantized MobileNetV2 model is based on this tutorial: <a href="https://pytorch.org/tutorials/advanced/static_quantization_tutorial.html" rel="nofollow noopener">https://pytorch.org/tutorials/advanced/static_quantization_tutorial.html</a> .  The text model was prepared by <a href="https://nbviewer.jupyter.org/gist/dreiss/ee4ff1ed2e137326d13e96bb4f953061" rel="nofollow noopener">https://nbviewer.jupyter.org/gist/dreiss/ee4ff1ed2e137326d13e96bb4f953061</a> .  The weights came from a trained PyText model.  We’ll look into getting these links included in the app or docs.</p>

tom: <p>Thank you, David!</p>
<p>Besteht regards</p>
<p>Thomas</p>

lkhphuc: <p>I trained a custom resnet18 and mobilenetv2 with 3 classes output. However they all failed when I substituted the “resnet18.pt” from the example with my own models.</p>
<pre><code class="lang-auto">    findViewById(R.id.vision_card_resnet_click_area).setOnClickListener(v -&gt; {
      final Intent intent = new Intent(VisionListActivity.this, ImageClassificationActivity.class);
      intent.putExtra(ImageClassificationActivity.INTENT_MODULE_ASSET_NAME, "resnet18-custom.pt");
      intent.putExtra(ImageClassificationActivity.INTENT_INFO_VIEW_TYPE,
          InfoViewFactory.INFO_VIEW_TYPE_IMAGE_CLASSIFICATION_RESNET);
</code></pre>
<p>Relevant error logs:</p>
<pre><code class="lang-auto">E/PyTorchDemo: Error during image analysis
    com.facebook.jni.CppException: false CHECK FAILED at aten/src/ATen/Functions.h (empty at aten/src/ATen/Functions.h:3535)
    (no backtrace available)
        at org.pytorch.Module$NativePeer.initHybrid(Native Method)
        at org.pytorch.Module$NativePeer.&lt;init&gt;(Module.java:70)
        at org.pytorch.Module.&lt;init&gt;(Module.java:25)
        at org.pytorch.Module.load(Module.java:21)
        at org.pytorch.demo.vision.ImageClassificationActivity.analyzeImage(ImageClassificationActivity.java:167)
        at org.pytorch.demo.vision.ImageClassificationActivity.analyzeImage(ImageClassificationActivity.java:31)
</code></pre>
<p>Is there anything else I need to do to change to use my custom model?</p>
<p>Thank you.</p>

tom: <p>Yeah, well.</p>
<ul>
<li>There is no C++ traceback, so it’s hard to tell what went wrong. My guess from the traceback is that it is in the loading of the model rather than executing.</li>
<li>Are you sure you put a <em>TorchScript</em> (most probably traced)  model at the right place?</li>
</ul>
<p>The HelloWorld app has a .py for exporting the model.</p>
<p>Best regards</p>
<p>Thomas</p>

lkhphuc: <p>Thanks for your response. I did put in a traced script module though. And it’s indeed during the model loading time.</p>

johnolafenwa: <p>Hi <a class="mention" href="/u/lkhphuc">@lkhphuc</a> <a class="mention" href="/u/tom">@tom</a>. A common cause for this is converting the model with a version of Pytorch less than 1.3.0. As of present, only models converted with the latest pytorch version would load.</p>
<p>See my latest tutorial on Pytorch Mobile including an easy to reuse open source image recognition example.<br>
This provides a useful guide</p>
<p><a href="https://heartbeat.fritz.ai/pytorch-mobile-image-classification-on-android-5c0cfb774c5b" class="onebox" target="_blank" rel="nofollow noopener">https://heartbeat.fritz.ai/pytorch-mobile-image-classification-on-android-5c0cfb774c5b</a></p>

lkhphuc: <p>My model was jit.trace and save yesterday on Google Colab. I checked and the pytorch version is 1.3.0+cu100. I think it was the latest already.</p>

johnolafenwa: <p>If the Pytorch version is fine. This error also occurs when the model path is not found. Since the Module class accepts an absolute path to the model file. I suggest you confirm that the path to the model is a valid file.</p>

David_Reiss: <p>Are you able to share this model?  If so, we can debug and improve this error message.</p>

lkhphuc: <p><a class="mention" href="/u/johnolafenwa">@johnolafenwa</a> Even if I changed my model name to ‘resnet18.pt’ to replace the current one in the Android repo, it’s still has problem.<br>
<a class="mention" href="/u/david_reiss">@David_Reiss</a> You can find the model here: <a href="https://drive.google.com/file/d/1fAhLpkoqNR32KQtzEkWe0LhBfAYb7Eiu/view?usp=sharing" rel="nofollow noopener">https://drive.google.com/file/d/1fAhLpkoqNR32KQtzEkWe0LhBfAYb7Eiu/view?usp=sharing</a></p>
<p>Thank you.</p>

ljk53: <p>Thanks for sharing the model. We are following up the issue at: <a href="https://github.com/pytorch/pytorch/issues/28379" rel="nofollow noopener">https://github.com/pytorch/pytorch/issues/28379</a></p>

tom: <p>So I have played with it some more:</p>
<ul>
<li>I must say I dislike the hack around reading models (copying from assets to fs). I got burnt by forgetting to overwrite it more than once. My libtorch/JNI adaptation used <code>torch::jit::load</code> with string streams. This is less memory efficient, of course, but for development it is much more convenient. If it isn’t controversial, I could see if I file a PR.</li>
<li>One of the first things I needed was a method to get output pictures, I’ll file a PR for adding something like that to torchvision.</li>
<li>I hit a bug with some arm32 ops. Model works fine on Android/x86, colors/scanline widths are off on Android/arm(32). The net uses <code>aten::_convolution, aten::add, aten::contiguous, aten::instance_norm, aten::reflection_pad2d, aten::relu_, aten::tanh, prim::Constant, prim::GetAttr, prim::ListConstruct</code> with the most fancy convolutions being with stride=2 and a transposed one with stride=2 and output padding=1 (so no non-default dilations,  kernel 1,3,7). I’m still trying to narrow this down. As error looks like it is some “striding”/contiguous problem, I tried inserting lots of <code>contiguous</code> but it didn’t immediately help. I know this isn’t narrowed down enough yet, unfortunately.</li>
</ul>
<p>Best regards</p>
<p>Thomas</p>

jspisak: <p>cc <a class="mention" href="/u/david_reiss">@David_Reiss</a> and <a class="mention" href="/u/ljk53">@ljk53</a></p>

David_Reiss: <blockquote>
<p>I must say I dislike the hack around reading models (copying from assets to fs).</p>
</blockquote>
<p>We expect most production apps to download models at runtime, so reading from the filesystem should be more natural in that case.  However, you’re right that it feels hacky when you’re first developing with the model as an asset.  We would accept a PR that added reading the model directly from the APK.</p>
<blockquote>
<p>I hit a bug with some arm32 ops.</p>
</blockquote>
<p>Please let us know what you find.  Or, if you are comfortable sharing the model, we can debug as well.</p>

Kareem_Belgharbi: <p>I tried out the hello-world app and could not get it to work on an emulator or actual device (Huawei P20 Lite). However, the demo app works perfectly.</p>
<p>I tried setting up a test with my own model (for person re-identification) using a similar setup as on the demo app and I get an error as soon as I load my model:</p>
<pre><code class="lang-auto">java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.pytorchmobile/com.example.pytorchmobile.MainActivity}: com.facebook.jni.CppException: false CHECK FAILED at ../c10/core/Backend.h (tensorTypeIdToBackend at ../c10/core/Backend.h:106)
    (no backtrace available)
</code></pre>
<p>This is also the case when I try importing the Super Resolution model from here: <a href="https://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html" rel="nofollow noopener">https://pytorch.org/tutorials/advanced/super_resolution_with_caffe2.html</a></p>
<p>Also, another question: <strong>is PyTorch mobile stable enough</strong> and suitable for production? Or should we just use ONNX and Caffe 2 until it is more mature?</p>

tom: <p>To me the error being around the Backend sounds like you have your model on GPU but need CPU.</p>
<aside class="quote no-group" data-username="Kareem_Belgharbi" data-post="18" data-topic="58336">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/kareem_belgharbi/48/17340_2.png" class="avatar"> Kareem_Belgharbi:</div>
<blockquote>
<p>Also, another question: <strong>is PyTorch mobile stable enough</strong> and suitable for production? Or should we just use ONNX and Caffe 2 until it is more mature?</p>
</blockquote>
</aside>
<p>So I’m not in a position to make official pronouncements, but so the bulk of PyTorch mobile is “just libtorch”, and that is reasonably stable. So there might be bugs and I would expect that mobile gets better over time (maybe the API can be made nicer, there certainly seems some room for faster), but I would expect that what runs today will continue run well. Also people here will try to help you when you run into something blocking you.<br>
Caffe2 on the other hand <a href="https://discuss.pytorch.org/t/how-to-build-caffe2-with-onnx-opset-version-greater-than-9/59675/3">doesn’t have support anymore.</a></p>
<p>Best regards</p>
<p>Thomas</p>

Kareem_Belgharbi: <p>Thanks for the response. The model was trained with CPU only PyTorch so I’m not sure if it can be the problem.</p>
<p>My main recommendation for PyTorch mobile is to add more descriptive error messages. Most errors just show up in the logcat as a cpp file (usually backend, import, or function_schema_inl.h) and line number, which is hard to debug. Right now the platform is very new, and there isn’t much information out there on how to fix errors so we have to figure it out based on the error messages.</p>
<p>Overall though, I think the API is actually quite nice, and it’s really great that mobile support has been added.</p>

vgsprasad: <p>We tried both ‘Hello World’ and ‘Demo’ apps. We were able to port on device. ResNet18 model with FC layer as final layer is working fine. But, when we try to replace the FC layer with Conv1x1 layer with same weights and bias, the App is not giving same output as the original one. We used Conv1x1 layer instead of FC layer in our models, because some frameworks like Intel’s OpenVINO, etc are not supporting FC layers.</p>
<p>In PyTorch, both models are giving same output. In App, they are giving different outputs. Is there any issue in ‘torch.jit.trace’ API, when Conv1x1 is used in model?</p>
<p>Conv1x1 layer weights and bias are initialized as follows</p>
<p><em>resnet_model.conv1x1.weight.data = (resnet_model.model.fc.weight.data).view(1000, 512, 1, 1)</em><br>
<em>resnet_model.conv1x1.bias.data = resnet_model.model.fc.bias.data</em></p>
<p>Your feedback is appreciated.</p>
<p>Thanks and Regards<br>
Prasad</p>