{"id":36427,"date":"2024-11-01T09:48:24","date_gmt":"2024-11-01T09:48:24","guid":{"rendered":"http:\/\/atmokpo.com\/w\/?p=36427"},"modified":"2024-11-01T11:53:13","modified_gmt":"2024-11-01T11:53:13","slug":"deep-learning-pytorch-course-difference-between-using-cpu-and-gpu","status":"publish","type":"post","link":"https:\/\/atmokpo.com\/w\/36427\/","title":{"rendered":"Deep Learning PyTorch Course, Difference between Using CPU and GPU"},"content":{"rendered":"<p><body><\/p>\n<p>Deep learning has rapidly advanced in recent years, and this development relies heavily on powerful hardware. In particular, CPUs and GPUs play a vital role in the training and inference performance of deep learning models. This course will explore the structure, operating principles of CPUs and GPUs, and how to efficiently train deep learning models through PyTorch example code.<\/p>\n<h2>Structural Differences Between CPU and GPU<\/h2>\n<p>The CPU (Central Processing Unit) is the central processing unit of a computer, known for its excellent capability to perform complex calculations and handle various tasks. On the other hand, the GPU (Graphics Processing Unit) is hardware optimized for massive data parallel processing. Each of these processors has the following characteristics:<\/p>\n<ul>\n<li><strong>CPU<\/strong>: Typically has 4-16 cores, making it strong in multitasking by handling multiple programs simultaneously. However, due to the high performance of each core, it is very fast for single-threaded tasks.<\/li>\n<li><strong>GPU<\/strong>: Consists of thousands of small cores that excel at processing large datasets concurrently and performing repetitive calculations. Therefore, it is highly suitable for image and video processing as well as deep learning operations.<\/li>\n<\/ul>\n<h2>Usage of CPU and GPU in Deep Learning<\/h2>\n<p>In deep learning model training, thousands of parameters need to be optimized, and this process involves numerous matrix operations. In this case, the GPU demonstrates its capability for parallel processing by handling massive amounts of data at once, thus reducing training time. For example, training with a GPU can be tens to hundreds of times faster than with a CPU.<\/p>\n<h2>Using CPU and GPU in PyTorch<\/h2>\n<p>In PyTorch, users can easily choose between CPU and GPU. By default, the CPU is used, but when a GPU is available, it can be utilized with just a few simple changes in the code. Let&#8217;s take a look at this through the example code below.<\/p>\n<h3>Example: Training a Simple Neural Network Model<\/h3>\n<pre><code class=\"language-python\">\nimport torch\nimport torch.nn as nn\nimport torch.optim as optim\nfrom torchvision import datasets, transforms\n\n# Data preparation\ntransform = transforms.Compose([\n    transforms.ToTensor(),\n    transforms.Normalize((0.5,), (0.5,))\n])\n\ntrain_dataset = datasets.MNIST(root='.\/data', train=True, transform=transform, download=True)\ntrain_loader = torch.utils.data.DataLoader(dataset=train_dataset, batch_size=64, shuffle=True)\n\n# Neural network model definition\nclass SimpleNN(nn.Module):\n    def __init__(self):\n        super(SimpleNN, self).__init__()\n        self.fc1 = nn.Linear(28 * 28, 128)\n        self.fc2 = nn.Linear(128, 10)\n    \n    def forward(self, x):\n        x = x.view(-1, 28 * 28)  # flatten\n        x = torch.relu(self.fc1(x))\n        x = self.fc2(x)\n        return x\n\n# Device configuration\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nmodel = SimpleNN().to(device)\n\n# Loss function and optimizer configuration\ncriterion = nn.CrossEntropyLoss()\noptimizer = optim.SGD(model.parameters(), lr=0.01)\n\n# Model training\nfor epoch in range(5):  # Number of training epochs\n    for images, labels in train_loader:\n        images, labels = images.to(device), labels.to(device)  # Move data to GPU\n        optimizer.zero_grad()   # Gradient initialization\n        outputs = model(images) # Predictions\n        loss = criterion(outputs, labels) # Loss calculation\n        loss.backward()         # Backpropagation\n        optimizer.step()        # Weight update\n    \n    print(f'Epoch [{epoch + 1}\/5], Loss: {loss.item():.4f}')\n<\/code><\/pre>\n<h3>Code Explanation<\/h3>\n<ul>\n<li><strong>Data preparation<\/strong>: Loads and preprocesses the MNIST dataset into a DataLoader.<\/li>\n<li><strong>Neural network model definition<\/strong>: Defines a simple two-layer structure neural network.<\/li>\n<li><strong>Device configuration<\/strong>: Uses the GPU if available; otherwise, it uses the CPU.<\/li>\n<li><strong>Model training<\/strong>: Trains using the defined data and model, ensuring to move data to the GPU.<\/li>\n<\/ul>\n<h2>Performance Comparison of CPU and GPU<\/h2>\n<p>The performance advantage of using a GPU can be confirmed through various measurements. Typically, both CPU and GPU show differences in terms of training time and accuracy. Below is an example of training time when using CPU and GPU:<\/p>\n<pre><code class=\"language-python\">\nimport time\n\n# CPU performance test\ndevice_cpu = torch.device('cpu')\nmodel_cpu = SimpleNN().to(device_cpu)\n\nstart_time = time.time()\nfor epoch in range(5):\n    for images, labels in train_loader:\n        images, labels = images.to(device_cpu), labels.to(device_cpu)\n        optimizer.zero_grad()\n        outputs = model_cpu(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\nend_time = time.time()\nprint(f'CPU Training Time: {end_time - start_time:.2f} seconds')\n\n# GPU performance test\ndevice_gpu = torch.device('cuda')\nmodel_gpu = SimpleNN().to(device_gpu)\n\nstart_time = time.time()\nfor epoch in range(5):\n    for images, labels in train_loader:\n        images, labels = images.to(device_gpu), labels.to(device_gpu)\n        optimizer.zero_grad()\n        outputs = model_gpu(images)\n        loss = criterion(outputs, labels)\n        loss.backward()\n        optimizer.step()\nend_time = time.time()\nprint(f'GPU Training Time: {end_time - start_time:.2f} seconds')\n<\/code><\/pre>\n<p>Running the code above allows us to compare the training times of CPU and GPU. Generally, the GPU demonstrates faster training performance, but the complexity of the model, size of the data, and hardware performance can lead to differences.<\/p>\n<h2>Conclusion<\/h2>\n<p>To train deep learning models efficiently, it is essential to understand the characteristics and advantages of CPUs and GPUs. While the CPU provides versatility, the GPU is optimized for effectively handling massive data processing. Therefore, if you choose the hardware that suits your project and write code accordingly using PyTorch, you will be able to build deep learning models more efficiently.<\/p>\n<p>Additionally, when utilizing GPUs, it is important to recognize the limitations of GPU memory and, if necessary, adjust mini-batches to suit your needs. These considerations will enhance the utility of PyTorch and deep learning.<\/p>\n<p><\/body><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Deep learning has rapidly advanced in recent years, and this development relies heavily on powerful hardware. In particular, CPUs and GPUs play a vital role in the training and inference performance of deep learning models. This course will explore the structure, operating principles of CPUs and GPUs, and how to efficiently train deep learning models &hellip; <a href=\"https:\/\/atmokpo.com\/w\/36427\/\" class=\"more-link\">\ub354 \ubcf4\uae30<span class=\"screen-reader-text\"> &#8220;Deep Learning PyTorch Course, Difference between Using CPU and GPU&#8221;<\/span><\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[149],"tags":[],"class_list":["post-36427","post","type-post","status-publish","format-standard","hentry","category-pytorch-study"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v26.2 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>Deep Learning PyTorch Course, Difference between Using CPU and GPU - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/atmokpo.com\/w\/36427\/\" \/>\n<meta property=\"og:locale\" content=\"ko_KR\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Deep Learning PyTorch Course, Difference between Using CPU and GPU - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"og:description\" content=\"Deep learning has rapidly advanced in recent years, and this development relies heavily on powerful hardware. In particular, CPUs and GPUs play a vital role in the training and inference performance of deep learning models. This course will explore the structure, operating principles of CPUs and GPUs, and how to efficiently train deep learning models &hellip; \ub354 \ubcf4\uae30 &quot;Deep Learning PyTorch Course, Difference between Using CPU and GPU&quot;\" \/>\n<meta property=\"og:url\" content=\"https:\/\/atmokpo.com\/w\/36427\/\" \/>\n<meta property=\"og:site_name\" content=\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\" \/>\n<meta property=\"article:published_time\" content=\"2024-11-01T09:48:24+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2024-11-01T11:53:13+00:00\" \/>\n<meta name=\"author\" content=\"root\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:site\" content=\"@bebubo4\" \/>\n<meta name=\"twitter:label1\" content=\"\uae00\uc4f4\uc774\" \/>\n\t<meta name=\"twitter:data1\" content=\"root\" \/>\n\t<meta name=\"twitter:label2\" content=\"\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04\" \/>\n\t<meta name=\"twitter:data2\" content=\"4\ubd84\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\/\/atmokpo.com\/w\/36427\/#article\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36427\/\"},\"author\":{\"name\":\"root\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\"},\"headline\":\"Deep Learning PyTorch Course, Difference between Using CPU and GPU\",\"datePublished\":\"2024-11-01T09:48:24+00:00\",\"dateModified\":\"2024-11-01T11:53:13+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36427\/\"},\"wordCount\":551,\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"articleSection\":[\"PyTorch Study\"],\"inLanguage\":\"ko-KR\"},{\"@type\":\"WebPage\",\"@id\":\"https:\/\/atmokpo.com\/w\/36427\/\",\"url\":\"https:\/\/atmokpo.com\/w\/36427\/\",\"name\":\"Deep Learning PyTorch Course, Difference between Using CPU and GPU - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"isPartOf\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#website\"},\"datePublished\":\"2024-11-01T09:48:24+00:00\",\"dateModified\":\"2024-11-01T11:53:13+00:00\",\"breadcrumb\":{\"@id\":\"https:\/\/atmokpo.com\/w\/36427\/#breadcrumb\"},\"inLanguage\":\"ko-KR\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/atmokpo.com\/w\/36427\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/atmokpo.com\/w\/36427\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"\ud648\",\"item\":\"https:\/\/atmokpo.com\/w\/en\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Deep Learning PyTorch Course, Difference between Using CPU and GPU\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/atmokpo.com\/w\/#website\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/atmokpo.com\/w\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"ko-KR\"},{\"@type\":\"Organization\",\"@id\":\"https:\/\/atmokpo.com\/w\/#organization\",\"name\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\",\"url\":\"https:\/\/atmokpo.com\/w\/\",\"logo\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\",\"url\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"contentUrl\":\"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png\",\"width\":400,\"height\":400,\"caption\":\"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8\"},\"image\":{\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/\"},\"sameAs\":[\"https:\/\/x.com\/bebubo4\"]},{\"@type\":\"Person\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7\",\"name\":\"root\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"ko-KR\",\"@id\":\"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g\",\"caption\":\"root\"},\"sameAs\":[\"http:\/\/atmokpo.com\/w\"],\"url\":\"https:\/\/atmokpo.com\/w\/author\/root\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Deep Learning PyTorch Course, Difference between Using CPU and GPU - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/atmokpo.com\/w\/36427\/","og_locale":"ko_KR","og_type":"article","og_title":"Deep Learning PyTorch Course, Difference between Using CPU and GPU - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","og_description":"Deep learning has rapidly advanced in recent years, and this development relies heavily on powerful hardware. In particular, CPUs and GPUs play a vital role in the training and inference performance of deep learning models. This course will explore the structure, operating principles of CPUs and GPUs, and how to efficiently train deep learning models &hellip; \ub354 \ubcf4\uae30 \"Deep Learning PyTorch Course, Difference between Using CPU and GPU\"","og_url":"https:\/\/atmokpo.com\/w\/36427\/","og_site_name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","article_published_time":"2024-11-01T09:48:24+00:00","article_modified_time":"2024-11-01T11:53:13+00:00","author":"root","twitter_card":"summary_large_image","twitter_creator":"@bebubo4","twitter_site":"@bebubo4","twitter_misc":{"\uae00\uc4f4\uc774":"root","\uc608\uc0c1 \ub418\ub294 \ud310\ub3c5 \uc2dc\uac04":"4\ubd84"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/atmokpo.com\/w\/36427\/#article","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/36427\/"},"author":{"name":"root","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7"},"headline":"Deep Learning PyTorch Course, Difference between Using CPU and GPU","datePublished":"2024-11-01T09:48:24+00:00","dateModified":"2024-11-01T11:53:13+00:00","mainEntityOfPage":{"@id":"https:\/\/atmokpo.com\/w\/36427\/"},"wordCount":551,"publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"articleSection":["PyTorch Study"],"inLanguage":"ko-KR"},{"@type":"WebPage","@id":"https:\/\/atmokpo.com\/w\/36427\/","url":"https:\/\/atmokpo.com\/w\/36427\/","name":"Deep Learning PyTorch Course, Difference between Using CPU and GPU - \ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","isPartOf":{"@id":"https:\/\/atmokpo.com\/w\/#website"},"datePublished":"2024-11-01T09:48:24+00:00","dateModified":"2024-11-01T11:53:13+00:00","breadcrumb":{"@id":"https:\/\/atmokpo.com\/w\/36427\/#breadcrumb"},"inLanguage":"ko-KR","potentialAction":[{"@type":"ReadAction","target":["https:\/\/atmokpo.com\/w\/36427\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/atmokpo.com\/w\/36427\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"\ud648","item":"https:\/\/atmokpo.com\/w\/en\/"},{"@type":"ListItem","position":2,"name":"Deep Learning PyTorch Course, Difference between Using CPU and GPU"}]},{"@type":"WebSite","@id":"https:\/\/atmokpo.com\/w\/#website","url":"https:\/\/atmokpo.com\/w\/","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","description":"","publisher":{"@id":"https:\/\/atmokpo.com\/w\/#organization"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/atmokpo.com\/w\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"ko-KR"},{"@type":"Organization","@id":"https:\/\/atmokpo.com\/w\/#organization","name":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8","url":"https:\/\/atmokpo.com\/w\/","logo":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/","url":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","contentUrl":"https:\/\/atmokpo.com\/w\/wp-content\/uploads\/2024\/11\/logo.png","width":400,"height":400,"caption":"\ub77c\uc774\ube0c\uc2a4\ub9c8\ud2b8"},"image":{"@id":"https:\/\/atmokpo.com\/w\/#\/schema\/logo\/image\/"},"sameAs":["https:\/\/x.com\/bebubo4"]},{"@type":"Person","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/91b6b3b138fbba0efb4ae64b1abd81d7","name":"root","image":{"@type":"ImageObject","inLanguage":"ko-KR","@id":"https:\/\/atmokpo.com\/w\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/708197b41fc6435a7ce22d951b25d4a47e9e904270cb1f04682d4f025066f80c?s=96&d=mm&r=g","caption":"root"},"sameAs":["http:\/\/atmokpo.com\/w"],"url":"https:\/\/atmokpo.com\/w\/author\/root\/"}]}},"jetpack_featured_media_url":"","jetpack_sharing_enabled":true,"jetpack-related-posts":[],"_links":{"self":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36427","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/comments?post=36427"}],"version-history":[{"count":1,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36427\/revisions"}],"predecessor-version":[{"id":36428,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/posts\/36427\/revisions\/36428"}],"wp:attachment":[{"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/media?parent=36427"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/categories?post=36427"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/atmokpo.com\/w\/wp-json\/wp\/v2\/tags?post=36427"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}