Pytorch Coding Conventions

LucasVandroux: <p>Hello everybody,</p>
<p>I am new to PyTorch, and I am looking for some <strong>PyTorch Coding Conventions</strong> or <strong>Best Practices</strong>. PyTorch is fantastic to allow you a lot of freedom, but it can sometimes be challenging to find something in someone else code when they have a completely different way of coding with PyTorch. There might also be some best practices to ensure your code can run as fast as possible.</p>
<p>I am thinking about something similar to <a href="https://pytorch.org/docs/stable/notes/serialization.html" rel="nofollow noopener">Serialization semantics</a> but describing more straightforward cases such as in which context should one create a separate module to define a part of a model and the way it should be structured.</p>
<p>The goal is that anyone who knows the coding conventions can easily find what they are looking for in the code and extend it in a way other people will be able to understand it quickly too.</p>
<p>Thanks for your time,</p>

klory: <p><a href="https://pytorch.org/tutorials/" class="onebox" target="_blank" rel="nofollow noopener">https://pytorch.org/tutorials/</a></p>

LucasVandroux: <p><a class="mention" href="/u/klory">@klory</a> thank you for your answer but it doesn’t answer my question.</p>
<p>I found something closer to what I am looking for here:</p>
<aside class="onebox whitelistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicon.ico" class="site-icon" width="32" height="32">
      <a href="https://github.com/IgorSusmelj/pytorch-styleguide" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars3.githubusercontent.com/u/1522766?s=400&amp;amp;v=4" class="thumbnail onebox-avatar" width="400" height="400">

<h3><a href="https://github.com/IgorSusmelj/pytorch-styleguide" target="_blank" rel="nofollow noopener">IgorSusmelj/pytorch-styleguide</a></h3>

<p>An inofficial styleguide and best practices summary for PyTorch - IgorSusmelj/pytorch-styleguide</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>

<p>But still looking for other documents.</p>

justusschock: <p>I don’t think, there are some documents like that (at least not official ones), but if you go by python, I’d recommend you to follow the <a href="https://www.python.org/dev/peps/pep-0008/" rel="nofollow noopener">PEP 8 style </a> as this mostly applies to pytorch as well. There are a few pytorch specific things, I’d append:</p>
<ul>
<li>don’t use autograd of not necessary (use <code>with torch.no_grad()</code> if possible)</li>
<li>only push tensors to GPU, if they are actually needed</li>
<li>try to avoid loops over tensor dimensions (slows things down)</li>
<li>try to free graphs as soon as possible (use <code>detach</code> or <code>item</code> whenever you can) to avoid memory leaks</li>
</ul>
<p>If there’s anything coming up to my mind, I’ll just edit this post.</p>

tom: <p>PEP8 (PyTorch uses flake8 for coding style itself) is a good idea, as is the general Python Zen. Don’t write Python like people who don’t like Python.</p>
<p>However, a couple of the PyTorch-specific items I disagree with (in the top two below). My list would be something like:</p>
<ul>
<li>If you need to use torch.no_grad() somewhere where it isn’t because you’re evaluating something that’s written for training, you should ask yourself if you’re doing it wrong.</li>
<li>Be mindful of loops over tensor dimensions slowing that down. It’s conventional wisdom to avoid these, but there are quite a few legitimate cases for them in PyTorch. I have a half-written section “For loop or not for loop” discussing them somewhere.</li>
<li>Using item and detach for things to keep around longer than the next backward is generally a good idea (e.g. when you record loss history, statistics, …), but be careful to not ruin your graph. (Targeted detach is good in <code>nn.Module</code> subclass code, <code>with torch.no_grad()</code> should be needed very rarely.)</li>
<li>If you write for re-use, the functional / Module split of PyTorch has turned out to be a good idea.</li>
<li>Use functional for stuff without state (unless you have a quick and dirty Sequential).</li>
<li>Don’t use deprecated stuff <code>.data</code>, <code>Tensor(...)</code> and friends, <code>.type</code> (might be me), <code>t.new_...</code>. It’s bad!</li>
<li>Use the documented PyTorch interfaces if you can (e.g. when something from <code>torch.nn.functional</code> shows up in <code>torch</code> for internal reasons.</li>
<li>Benchmark your stuff if you think it’s performance critical. Don’t forget CUDA needs synchronising for valid results.</li>
<li>The JIT will speed up chains of pointwise ops a lot.</li>
<li>C++ will be a bit faster than plain Python but for many cases only ca 10%.</li>
<li>Keep your modules clean.</li>
</ul>
<p>Best regards</p>
<p>Thomas</p>

justusschock: <p>I agree with you on the first point. Maybe I did not express my intention very well. What I meant is, that you could theoretically also validate/predict without <code>no_grad</code>. Of course you’re right, but I just assumed people to know, where they need gradients and where they aren’t necessary.</p>
<p>Regarding the second point on your list: sure there are some legitimate cases (LSTMs and stuff), but for most cases they can be avoided. I’ll look forward to your discussion on that!</p>
<p>And I totally agree with the rest of your list.</p>

LucasVandroux: <p><a class="mention" href="/u/justusschock">@justusschock</a> and <a class="mention" href="/u/tom">@tom</a> thank you for your recommendations. I will make sure to keep them in mind.</p>
<p>Browsing the forum a bit more, I also found this link:</p>
<aside class="onebox whitelistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicon.ico" class="site-icon" width="16" height="16">
      <a href="https://github.com/Spandan-Madan/A-Collection-of-important-tasks-in-pytorch" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars0.githubusercontent.com/u/21960611?s=400&amp;amp;v=4" class="thumbnail onebox-avatar" width="60" height="60">

<h3><a href="https://github.com/Spandan-Madan/A-Collection-of-important-tasks-in-pytorch" target="_blank" rel="nofollow noopener">Spandan-Madan/A-Collection-of-important-tasks-in-pytorch</a></h3>

<p>Everyday things people use in Pytorch. No need to spend hours reading Pytorch forums trying to find them! - Spandan-Madan/A-Collection-of-important-tasks-in-pytorch</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>


tom: <p>I meant to delete the first sentence (and did now), sorry. It’s probably hard to  be the first.<br>
My more controversial / situation specific things:</p>
<ul>
<li>Personally, I tend to copy code into one giant notebook and I think most configuration things (argparse etc) are terrible.</li>
<li>When you have all your stuff in <code>def main():</code> and I change something and get an exception, I cannot use <code>ipython -i foo.py</code> to inspect the variables in main.</li>
</ul>
<p>But these are really me.</p>

justusschock: <p>Don’t worry, I can take this <img src="https://discuss.pytorch.org/images/emoji/apple/smile.png?v=9" title=":smile:" class="emoji" alt=":smile:"></p>
<p>For me it’s kind of the other way round. I absolutely prefer splitting code in many files and packages, because this way it’s easier to avoid confusion (for me).<br>
And I usually have a configuration file defining all the hyperparameters. This is coming since I can heavily parallelize jobs on a cluster (grid search etc.) and don’t want to do this manually. Also the files are copied to the directory containing the weights to keep an overview on trained configurations.</p>
<p>I don’t prefer <code>ipython</code> or notebooks at all for GPU related stuff since you always need to restart the notebook server to free the GPU memory.</p>
<p>But that’s only on me <img src="https://discuss.pytorch.org/images/emoji/apple/slight_smile.png?v=9" title=":slight_smile:" class="emoji" alt=":slight_smile:"></p>

Igor_Susmelj: <p><a class="mention" href="/u/lucasvandroux">@LucasVandroux</a>, thanks for referring to my unofficial style guide.</p>
<p><a class="mention" href="/u/justusschock">@justusschock</a> and <a class="mention" href="/u/tom">@tom</a>,  I added most of your recommendation to my style guide.</p>
<p>Feel free to add more if you feel like:</p>
<aside class="onebox whitelistedgeneric">
  <header class="source">
      <img src="https://github.githubassets.com/favicon.ico" class="site-icon" width="16" height="16">
      <a href="https://github.com/IgorSusmelj/pytorch-styleguide" target="_blank" rel="nofollow noopener">GitHub</a>
  </header>
  <article class="onebox-body">
    <img src="https://avatars3.githubusercontent.com/u/1522766?s=400&amp;amp;v=4" class="thumbnail onebox-avatar" width="60" height="60">

<h3><a href="https://github.com/IgorSusmelj/pytorch-styleguide" target="_blank" rel="nofollow noopener">IgorSusmelj/pytorch-styleguide</a></h3>

<p>An inofficial styleguide and best practices summary for PyTorch - IgorSusmelj/pytorch-styleguide</p>


  </article>
  <div class="onebox-metadata">
    
    
  </div>
  <div style="clear: both"></div>
</aside>


tom: <p>Sigh!</p>
<p>While I appreciate that people want checklists and easy to follow instructions and I’m sure that your checklist is as good as any other, checklist invariably mix obvious good things with suggestions of questionable merit. For example I never provide that 10% speedup estimate without context or the opportunity to ask for context, much like Justus’ advice on avoiding loops is quite right for a lot of cases, but it’s important to know when it’s not applicable. When you provide advice in a checklist form, all that context is lost. Here you took a bunch of bullet points and left out even the few qualifications I put in that overly condensed form of discussion.</p>
<p>And that’s the crux: Good style cannot be achieved by following checklists, much like you don’t gain much wit by buying a book of famous quotes. If there is a craft component to writing code, you need to learn - possibly by studying what people who would know - say like Soumith - wrote and trying to understand how it works and why it was written that way.</p>
<p>By following a checklist approach you get the code equivalent of how development processes look like when large companies decide to do “agile”, and implements it just by following an “agile checklist” someone gave them.</p>
<p>Best regards</p>
<p>Thomas</p>

justusschock: <p>Well Thomas,</p>
<p>you’re right, but I think this is a good way to start. The idea behind PEP8 is just about the same.</p>
<p>And instead of asking Soumith, he just follows your advice (which is for sure also pretty good).</p>
<p>And this whole discussion board is meant for asking questions like that.</p>
<p>So in my opinion, this is a good way to start, but of course it cannot replace the learning process.</p>

LucasVandroux: <p>I agree with you. Nothing would ever replace the process of learning by reading and trying to understand what more advanced people have done. However, having some simple snippets to start with the simple tasks and then being able to understand how they work, is also an excellent way to learn too.</p>

henrique: <p>Hey Tom,<br>
If you want to debug your code you should try the python debugger pdb (it took me a while to start using it but it’s a game changer).<br>
ipython -m pdb is your best friend in these cases.<br>
Jupyter notebook (and many IDE’s) also support it pretty well. There are probably some good tutorials around…</p>

Igor_Susmelj: <p>I fully agree with your points. The best way to learn is by doing.</p>
<p>During my learning process, I often struggled because of missing documentation or seeing different ways of doing the same thing. I learned a lot about how to use PyTorch more efficiently by spending hours studying repositories made by companies such as Nvidia or Facebook.</p>
<p>The goal of this style guide and best practices summary is just to help others and myself to learn from this journey.</p>
<p>Being in the area of deep learning since quite a while and starting with tensorflow I saw how many people (as well as myself) struggled with getting started on their custom projects. Tutorials teach you on how to implement a specific model to solve a task but unfortunately, they don’t always tell you why a certain workflow or coding style / pattern can help you avoiding mistakes and keeping the project clean.</p>
<p>This is also one of the main reasons I like PyTorch. Being simpler and more intuitive for Python users, it just allows you to learn faster and make fewer mistakes. In tensorflow I was confused by different strategies on how to build a model all over the place and when to pick one in particular.</p>

CrimpCity: <p>A bit late to the party but while I personally enjoy Igor’s style guide I also think Branislav Holländer’s file organization may be useful to some people.<br>
github: <a href="https://github.com/branislav1991/PyTorchProjectFramework" class="inline-onebox" rel="noopener nofollow ugc">GitHub - branislav1991/PyTorchProjectFramework: A basic framework for your PyTorch projects</a><br>
article: <a href="https://towardsdatascience.com/how-to-structure-your-pytorch-project-89310b8b2da9" rel="noopener nofollow ugc">https://towardsdatascience.com/how-to-structure-your-pytorch-project-89310b8b2da9</a></p>