20.03.2021 Views

Deep-Learning-with-PyTorch

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

The main entry point for our application

283

Our application’s functionality will be implemented via a class so that we can

instantiate the application and pass it around if we feel the need. This can make testing,

debugging, or invocation from other Python programs easier. We can invoke the

application without needing to spin up a second OS-level process (we won’t do

explicit unit testing in this book, but the structure we create can be helpful for real

projects where that kind of testing is appropriate).

One way to take advantage of being able to invoke our training by either function

call or OS-level process is to wrap the function invocations into a Jupyter Notebook so

the code can easily be called from either the native CLI or the browser.

Listing 11.1

code/p2_run_everything.ipynb

# In[2]:w

def run(app, *argv):

We assume you have a four-core, eightthread

CPU. Change the 4 if needed.

argv = list(argv)

argv.insert(0, '--num-workers=4')

log.info("Running: {}({!r}).main()".format(app, argv))

app_cls = importstr(*app.rsplit('.', 1))

app_cls(argv).main()

log.info("Finished: {}.{!r}).main()".format(app, argv))

# In[6]:

run('p2ch11.training.LunaTrainingApp', '--epochs=1')

This is a slightly cleaner

call to __import__.

NOTE The training here assumes that you’re on a workstation that has a fourcore,

eight-thread CPU, 16 GB of RAM, and a GPU with 8 GB of RAM. Reduce

--batch-size if your GPU has less RAM, and --num-workers if you have fewer

CPU cores, or less CPU RAM.

Let’s get some semistandard boilerplate code out of the way. We’ll start at the end of

the file with a pretty standard if main stanza that instantiates the application object

and invokes the main method.

Listing 11.2

training.py:386

if __name__ == '__main__':

LunaTrainingApp().main()

From there, we can jump back to the top of the file and have a look at the application class

and the two functions we just called, __init__ and main. We’ll want to be able to accept

command-line arguments, so we’ll use the standard argparse library (https://docs

.python.org/3/library/argparse.html) in the application’s __init__ function. Note that

we can pass in custom arguments to the initializer, should we wish to do so. The main

method will be the primary entry point for the core logic of the application.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!