반응형
블로그 이미지
개발자로서 현장에서 일하면서 새로 접하는 기술들이나 알게된 정보 등을 정리하기 위한 블로그입니다. 운 좋게 미국에서 큰 회사들의 프로젝트에서 컬설턴트로 일하고 있어서 새로운 기술들을 접할 기회가 많이 있습니다. 미국의 IT 프로젝트에서 사용되는 툴들에 대해 많은 분들과 정보를 공유하고 싶습니다.
솔웅

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

카테고리


반응형

8.1. Deep Convolutional Neural Networks (AlexNet) — Dive into Deep Learning 1.0.0-beta0 documentation (d2l.ai)

 

8.1. Deep Convolutional Neural Networks (AlexNet) — Dive into Deep Learning 1.0.0-beta0 documentation

 

d2l.ai

https://youtu.be/CQwzsNDpE1c

* AlexNet
  - 머신러닝 기법 탈피 (심층 신경망 모델 사용)
  - Vanishing Gradient 문제 많이 해소 (ReLU activation function 사용)
  - Larger Dataset 사용
  - GPU 를 사용 (GTX580)
  - 과대적합 방지 : Dropoout

 

https://youtu.be/40Gdctb55BY

* AlexNet Architecture : ReLUs, GPU 2대 병렬, Local response norm, overlapping pooling, data augmentation, dropout, Convolutional Layers (5개), Fully-connected layers, 1000-way softmax

 

https://youtu.be/VJX2kBWN7pQ

(2012) AlexNet
- LeNet : AlexNet 이전에 나옴. 손글씨 숫자 인식 하는 모델. tanh activation function 사용, avg pooling, Backpropagation 마지막 레이어에서만 사용
- AlexNet : 5 convolutions, 3 FS, 60M params, 1000 classes, ReLU, 2 GPUs, Local Response Normalization, Overlapping Pooling

 

 

8.1. Deep Convolutional Neural Networks (AlexNet)

 

Although CNNs were well known in the computer vision and machine learning communities following the introduction of LeNet (LeCun et al., 1995), they did not immediately dominate the field. Although LeNet achieved good results on early small datasets, the performance and feasibility of training CNNs on larger, more realistic datasets had yet to be established. In fact, for much of the intervening time between the early 1990s and the watershed results of 2012 (Krizhevsky et al., 2012), neural networks were often surpassed by other machine learning methods, such as kernel methods (Schölkopf and Smola, 2002), ensemble methods (Freund et al., 1996), and structured estimation (Taskar et al., 2004).

 

CNN은 LeNet(LeCun et al., 1995)의 도입 이후 컴퓨터 비전 및 기계 학습 커뮤니티에서 잘 알려져 있었지만 즉시 해당 분야를 지배하지는 못했습니다. LeNet은 초기 소규모 데이터 세트에서 좋은 결과를 얻었지만 더 크고 현실적인 데이터 세트에서 CNN을 교육하는 성능과 실행 가능성은 아직 확립되지 않았습니다. 사실, 1990년대 초반과 2012년 있었던 분수령 (Krizhevsky et al., 2012) 사이의 중간 기간 동안 신경망은 종종 커널 방법, (Schölkopf and Smola, 2002). , 앙상블 방법(Freund et al., 1996) 및 구조화된 추정(Taskar et al., 2004)과 같은 다른 기계 학습 방법에 의해 추월되었습니다.

 

For computer vision, this comparison is perhaps not entirely accurate. That is, although the inputs to convolutional networks consist of raw or lightly-processed (e.g., by centering) pixel values, practitioners would never feed raw pixels into traditional models. Instead, typical computer vision pipelines consisted of manually engineering feature extraction pipelines, such as SIFT (Lowe, 2004), SURF (Bay et al., 2006), and bags of visual words (Sivic and Zisserman, 2003). Rather than learning the features, the features were crafted. Most of the progress came from having more clever ideas for feature extraction on the one hand and deep insight into geometry (Hartley and Zisserman, 2000) on the other hand. The learning algorithm was often considered an afterthought.

 

컴퓨터 비전의 경우 이 비교가 완전히 정확하지 않을 수 있습니다. 즉, 컨볼루션 네트워크에 대한 입력이 원시 또는 가볍게 처리된(예: 센터링) 픽셀 값으로 구성되지만 실무자는 원시 픽셀을 기존 모델에 공급하지 않습니다. 대신 일반적인 컴퓨터 비전 파이프라인은 SIFT(Lowe, 2004), SURF(Bay et al., 2006) 및 시각적 단어 백(Sivic and Zisserman, 2003)과 같은 수동 엔지니어링 feature  추출 파이프라인으로 구성되었습니다. feature 을 배우는 대신 feature 을 제작했습니다. 대부분의 발전은 한편으로는 feature  추출에 대한 더 영리한 아이디어와 다른 한편으로는 기하학에 대한 깊은 통찰력을 갖는 것에서 비롯되었습니다(Hartley and Zisserman, 2000). 학습 알고리즘은 종종 나중에 생각하는 것으로 간주되었습니다.

 

Although some neural network accelerators were available in the 1990s, they were not yet sufficiently powerful to make deep multichannel, multilayer CNNs with a large number of parameters. For instance, NVIDIA’s GeForce 256 from 1999 was able to process at most 480 million operations per second (MFLOPs), without any meaningful programming framework for operations beyond games. Today’s accelerators are able to perform in excess of 300 TFLOPs per device (NVIDIA’s Ampere A100). Note that FLOPs are floating-point operations such as multiplications and additions. Moreover, datasets were still relatively small: OCR on 60,000 low-resolution 28×28 pixel images was considered a highly challenging task. Added to these obstacles, key tricks for training neural networks including parameter initialization heuristics (Glorot and Bengio, 2010), clever variants of stochastic gradient descent (Kingma and Ba, 2014), non-squashing activation functions (Nair and Hinton, 2010), and effective regularization techniques (Srivastava et al., 2014) were still missing.

 

1990년대에 일부 neural network accelerators를 사용할 수 있었지만 아직 많은 매개변수가 있는 깊은 다중 채널, 다층 CNN을 만들 만큼 강력하지 않았습니다. 예를 들어, 1999년 NVIDIA의 GeForce 256은 게임 이외의 작업을 위한 의미 있는 프로그래밍 프레임워크 없이 최대 4억 8천만 MFLOP(초당 작업)를 처리할 수 있었습니다. 오늘날의 가속기는 장치당 300 TFLOP 이상을 수행할 수 있습니다(NVIDIA의 Ampere A100). FLOP는 곱셈 및 덧셈과 같은 부동 소수점 연산입니다. 게다가 데이터 세트는 여전히 상대적으로 작았습니다. 60,000개의 저해상도 28×28 픽셀 이미지에 대한 OCR은 매우 어려운 작업으로 간주되었습니다. 이러한 장애물에 추가하여 매개변수 초기화 휴리스틱(Glorot 및 Bengio, 2010), 확률적 경사 하강의 영리한 변형(Kingma 및 Ba, 2014), 비압축 활성화 기능(Nair 및 Hinton, 2010), 효과적인 정규화 기술(Srivastava et al., 2014)이 여전히 누락되었습니다.

 

Thus, rather than training end-to-end (pixel to classification) systems, classical pipelines looked more like this:

 

따라서 end-to-end(픽셀에서 분류로) 시스템을 교육하는 대신 classical pipelines은 다음과 같이 생겼습니다.

 

  1. Obtain an interesting dataset. In the early days, these datasets required expensive sensors. For instance, the Apple QuickTake 100 of 1994 sported a whopping 0.3 Megapixel (VGA) resolution, capable of storing up to 8 images, all for the price of $1,000.
    흥미로운 데이터 세트를 얻습니다. 초기에는 이러한 데이터 세트에 값비싼 센서가 필요했습니다. 예를 들어, 1994년 Apple QuickTake 100은 무려 0.3메가픽셀(VGA)의 해상도를 자랑했으며, 모두 1,000달러의 가격으로 최대 8개의 이미지를 저장할 수 있었습니다.

  2. Preprocess the dataset with hand-crafted features based on some knowledge of optics, geometry, other analytic tools, and occasionally on the serendipitous discoveries of lucky graduate students.
    광학, 기하학, 기타 분석 도구에 대한 약간의 지식과 때때로 운이 좋은 대학원생의 우연한 발견을 기반으로 수작업으로 만든 기능으로 데이터 세트를 전처리합니다.

  3. Feed the data through a standard set of feature extractors such as the SIFT (scale-invariant feature transform) (Lowe, 2004), the SURF (speeded up robust features) (Bay et al., 2006), or any number of other hand-tuned pipelines. OpenCV still provides SIFT extractors to this day!
    SIFT(scale-invariant feature transform)(Lowe, 2004), SURF(speeded up robust features)(Bay et al., 2006)와 같은 standard set of feature extractors 세트를 통해 데이터를 공급합니다. -튜닝된 파이프라인. OpenCV는 현재까지도 여전히 SIFT 추출기를 제공합니다!

  4. Dump the resulting representations into your favorite classifier, likely a linear model or kernel method, to train a classifier.
    결과 representations favorite classifier(예: 선형 모델 또는 커널 메서드)에 덤프하여 classifier를 교육합니다.

 

If you spoke to machine learning researchers, they believed that machine learning was both important and beautiful. Elegant theories proved the properties of various classifiers (Boucheron et al., 2005) and convex optimization (Boyd and Vandenberghe, 2004) had become the mainstay for obtaining them. The field of machine learning was thriving, rigorous, and eminently useful. However, if you spoke to a computer vision researcher, you would hear a very different story. The dirty truth of image recognition, they would tell you, is that features, geometry (Hartley and Zisserman, 2000, Hartley and Kahl, 2009), and engineering, rather than novel learning algorithms, drove progress. Computer vision researchers justifiably believed that a slightly bigger or cleaner dataset or a slightly improved feature-extraction pipeline mattered far more to the final accuracy than any learning algorithm.

 

machine learning 연구원들과 대화를 나눈다면 그들은 기계 학습이 중요하고 아름답다고 믿었다고 했을 겁니다. 우아한 이론은 various classifiers(Boucheron et al., 2005)의 속성을 입증했으며 convex optimization(Boyd and Vandenberghe, 2004)는 이를 얻기 위한 주류가 되었습니다. 기계 학습 분야는 번성하고 엄격하며 매우 유용했습니다. 그러나 컴퓨터 비전 연구원과 대화하면 매우 다른 이야기를 듣게 될 것입니다. 이미지 인식의 더러운 진실은 새로운 학습 알고리즘이 아니라 기능, 기하학(Hartley and Zisserman, 2000, Hartley and Kahl, 2009) 및 엔지니어링이 발전을 주도했다는 것입니다. 컴퓨터 비전 연구자들은 약간 더 크거나 깨끗한 데이터 세트 또는 약간 개선된 특징 추출 파이프라인이 어떤 학습 알고리즘보다 최종 정확도에 훨씬 더 중요하다고 정당하게 믿었습니다.

 

Convex optimization refers to the field of mathematical optimization that deals with optimization problems where the objective function and constraints exhibit convexity. In convex optimization, the objective function is a convex function and the feasible region defined by the constraints is a convex set.

Convex optimization problems have several important properties. First, convexity guarantees the existence of a global minimum, meaning there is a unique optimal solution that can be found. Second, any local minimum of a convex optimization problem is also a global minimum, which simplifies the search for the optimal solution. Third, convex optimization problems have efficient algorithms that can solve them to optimality with polynomial time complexity.

Convex optimization has widespread applications in various fields, including machine learning, operations research, finance, engineering, and many others. It provides a powerful framework for formulating and solving optimization problems with desirable properties and efficient algorithms.

 

볼록 최적화(convex optimization)는 목적 함수와 제약 조건이 볼록성(convexity)을 가지는 최적화 문제를 다루는 수학적 최적화 분야를 의미합니다. 볼록 최적화에서는 목적 함수가 볼록 함수(convex function)이고, 제약 조건으로 정의된 실행 가능한 영역이 볼록 집합(convex set)인 경우를 다룹니다.

볼록 최적화 문제는 몇 가지 중요한 특성을 가지고 있습니다. 첫째로, 볼록성은 전역 최솟값의 존재를 보장합니다. 즉, 찾을 수 있는 고유한 최적해가 있습니다. 둘째로, 볼록 최적화 문제의 모든 국소 최솟값은 동시에 전역 최솟값이기 때문에 최적해를 찾는 과정이 단순화됩니다. 셋째로, 볼록 최적화 문제는 다항 시간 복잡도로 최적해를 찾을 수 있는 효율적인 알고리즘을 가지고 있습니다.

볼록 최적화는 기계 학습, 운영 연구, 금융, 공학 등 다양한 분야에서 광범위하게 응용되며, 바람직한 속성과 효율적인 알고리즘을 통해 최적화 문제를 정의하고 해결하는 강력한 프레임워크를 제공합니다.

 

import torch
from torch import nn
from d2l import torch as d2l

 

8.1.1. Representation Learning

Another way to cast the state of affairs is that the most important part of the pipeline was the representation. And up until 2012 the representation was calculated mostly mechanically. In fact, engineering a new set of feature functions, improving results, and writing up the method was a prominent genre of paper. SIFT (Lowe, 2004), SURF (Bay et al., 2006), HOG (histograms of oriented gradient) (Dalal and Triggs, 2005), bags of visual words (Sivic and Zisserman, 2003), and similar feature extractors ruled the roost.

 

state of affairs를 캐스팅하는 또 다른 방법은 파이프라인의 가장 중요한 부분이 표현(representation)이라는 것입니다. 그리고 2012년까지 표현(representation)은 대부분 기계적으로 계산되었습니다. 사실, 새로운 feature functions 세트를 엔지니어링하고, 결과를 개선하고, 방법을 작성하는 것이 중요한 논문 장르였습니다. SIFT(Lowe, 2004), SURF(Bay et al., 2006), HOG(Histograms of oriented gradient)(Dalal and Triggs, 2005), bag of visual words(Sivic and Zisserman, 2003), 그리고 similar feature extractorsroost를 지배했습니다.

 

Another group of researchers, including Yann LeCun, Geoff Hinton, Yoshua Bengio, Andrew Ng, Shun-ichi Amari, and Juergen Schmidhuber, had different plans. They believed that features themselves ought to be learned. Moreover, they believed that to be reasonably complex, the features ought to be hierarchically composed with multiple jointly learned layers, each with learnable parameters. In the case of an image, the lowest layers might come to detect edges, colors, and textures, in analogy to how the visual system in animals processes its input. In particular, the automatic design of visual features such as those obtained by sparse coding (Olshausen and Field, 1996) remained an open challenge until the advent of modern CNNs. It was not until Dean et al. (2012), Le (2013) that the idea of generating features from image data automatically gained significant traction.

 

Yann LeCun, Geoff Hinton, Yoshua Bengio, Andrew Ng, Shun-ichi Amari 및 Juergen Schmidhuber를 포함한 다른 연구원 그룹은 다른 계획을 세웠습니다. 그들은 기능(features ) 자체가 학습되어야 한다고 믿었습니다. 더욱이 그들은 합리적으로 복잡하기 위해서는 features 가 각각 학습 가능한 매개변수가 있는 여러 공동 학습 레이어로 계층적으로 구성되어야 한다고 믿었습니다. 이미지의 경우 동물의 시각 시스템이 입력을 처리하는 방식과 유사하게 최하위 계층이 가장자리, 색상 및 질감을 감지할 수 있습니다. 특히 스파스 코딩(Olshausen and Field, 1996)으로 얻은 것과 같은 시각적 기능의 자동 설계는 현대 CNN이 등장할 때까지 열린 과제로 남아 있었습니다. Dean et al. (2012), Le(2013)는 이미지 데이터에서 features 을 자동으로 생성한다는 아이디어가 상당한 견인력을 얻었다고 말했습니다.

 

The first modern CNN (Krizhevsky et al., 2012), named AlexNet after one of its inventors, Alex Krizhevsky, is largely an evolutionary improvement over LeNet. It achieved excellent performance in the 2012 ImageNet challenge.

 

발명가 중 한 명인 Alex Krizhevsky의 이름을 따서 AlexNet으로 명명된 최초의 현대식 CNN(Krizhevsky et al., 2012)은 대체로 LeNet에 비해 진화적으로 개선된 것입니다. 2012 ImageNet 챌린지에서 우수한 성능을 달성했습니다.

 

Fig. 8.1.1  Image filters learned by the first layer of AlexNet. Reproduction courtesy of Krizhevsky et al. (2012).

 

Interestingly in the lowest layers of the network, the model learned feature extractors that resembled some traditional filters. Fig. 8.1.1 shows lower-level image descriptors. Higher layers in the network might build upon these representations to represent larger structures, like eyes, noses, blades of grass, and so on. Even higher layers might represent whole objects like people, airplanes, dogs, or frisbees. Ultimately, the final hidden state learns a compact representation of the image that summarizes its contents such that data belonging to different categories can be easily separated.

 

흥미롭게도 네트워크의 가장 낮은 계층에서 모델은 일부 traditional filters와 유사한  feature extractors를 학습했습니다. 그림 8.1.1은 lower-level image descriptors를 보여줍니다. 네트워크의 상위 계층은 눈, 코, 풀잎 등과 같은 더 큰 구조를 나타내기 위해 이러한 표현을 기반으로 구축될 수 있습니다. 더 높은 계층은 사람, 비행기, 개 또는 프리스비와 같은 전체 개체를 나타낼 수 있습니다. 궁극적으로 최종 숨겨진 상태는 다른 범주에 속하는 데이터를 쉽게 분리할 수 있도록 내용을 요약하는 이미지의 간결한 표현을 학습합니다.

 

AlexNet (2012) and its precursor LeNet (1995) share many architectural elements. This begs the question: why did it take so long? A key difference is that over the past two decades, the amount of data and computing power available had increased significantly. As such AlexNet was much larger: it was trained on much more data, and on much faster GPUs, compared to the CPUs available in 1995.

 

AlexNet(2012)과 그 전신인 LeNet(1995)은 많은 아키텍처 요소를 공유합니다. 이것은 질문을 던집니다. 왜 그렇게 오래 걸렸습니까? 주요 차이점은 지난 20년 동안 사용 가능한 데이터의 양과 컴퓨팅 성능이 크게 증가했다는 것입니다. 따라서 AlexNet은 훨씬 더 컸습니다. 1995년에 사용 가능한 CPU에 비해 훨씬 더 많은 데이터와 훨씬 더 빠른 GPU에서 훈련되었습니다.

 

8.1.1.1. Missing Ingredient: Data

Deep models with many layers require large amounts of data in order to enter the regime where they significantly outperform traditional methods based on convex optimizations (e.g., linear and kernel methods). However, given the limited storage capacity of computers, the relative expense of (imaging) sensors, and the comparatively tighter research budgets in the 1990s, most research relied on tiny datasets. Numerous papers relied on the UCI collection of datasets, many of which contained only hundreds or (a few) thousands of images captured in low resolution and often with an artificially clean background.

 

레이어가 많은 Deep models은 볼록 최적화-convex optimizations-(예: 선형 및 커널 방법)를 기반으로 하는 기존 방법을 훨씬 능가하는 체제에 진입하기 위해 많은 양의 데이터가 필요합니다. 그러나 컴퓨터의 제한된 저장 용량, (이미징) 센서의 상대적 비용 및 1990년대의 상대적으로 빠듯한 연구 예산을 고려할 때 대부분의 연구는 작은 데이터 세트에 의존했습니다. 수많은 논문이 UCI 데이터 세트 컬렉션에 의존했으며, 그 중 다수는 저해상도로 캡처된 이미지와 종종 인위적으로 깨끗한 배경을 포함하는 수백 또는 (몇) 수천 개의 이미지만 포함했습니다.

 

In 2009, the ImageNet dataset was released (Deng et al., 2009), challenging researchers to learn models from 1 million examples, 1000 each from 1000 distinct categories of objects. The categories themselves were based on the most popular noun nodes in WordNet (Miller, 1995). The ImageNet team used Google Image Search to prefilter large candidate sets for each category and employed the Amazon Mechanical Turk crowdsourcing pipeline to confirm for each image whether it belonged to the associated category. This scale was unprecedented, exceeding others by over an order of magnitude (e.g., CIFAR-100 has 60,000 images). Another aspect was that the images were at relatively high resolution of 224×224 pixels, unlike the 80 million sized TinyImages dataset (Torralba et al., 2008), consisting of 32×32 pixel thumbnails. This allowed for the formation of higher-level features. The associated competition, dubbed the ImageNet Large Scale Visual Recognition Challenge (Russakovsky et al., 2015), pushed computer vision and machine learning research forward, challenging researchers to identify which models performed best at a greater scale than academics had previously considered. The largest vision datasets, such as LAION-5B (Schuhmann et al., 2022) contain billions of images with additional metadata.

 

2009년에 ImageNet 데이터 세트가 출시되었으며(Deng et al., 2009), 연구자들은 1000개의 서로 다른 개체 범주에서 각각 1000개씩 100만 개의 예제에서 모델을 학습해야 했습니다. 범주 자체는 WordNet에서 가장 인기 있는 명사 노드를 기반으로 합니다(Miller, 1995). ImageNet 팀은 Google 이미지 검색을 사용하여 각 범주에 대한 대규모 후보 세트를 사전 필터링하고 Amazon Mechanical Turk 크라우드소싱 파이프라인을 사용하여 각 이미지가 관련 범주에 속하는지 여부를 확인했습니다. 이 규모는 전례가 없었으며 다른 규모보다 한 자릿수 이상 뛰어났습니다(예: CIFAR-100에는 60,000개의 이미지가 있음). 또 다른 측면은 이미지가 32×32 픽셀 썸네일로 구성된 8천만 크기의 TinyImages 데이터 세트(Torralba et al., 2008)와 달리 224×224 픽셀의 비교적 높은 해상도라는 것입니다. 이를 통해 더 높은 수준의 기능을 형성할 수 있었습니다. ImageNet 대규모 시각적 인식 챌린지(Russakovsky et al., 2015)라고 불리는 관련 대회는 컴퓨터 비전 및 기계 학습 연구를 발전시켜 연구자들이 이전에 학자들이 고려했던 것보다 더 큰 규모에서 가장 잘 수행된 모델을 식별하도록 도전했습니다. LAION-5B(Schuhmann et al., 2022)와 같은 가장 큰 비전 데이터 세트에는 추가 메타데이터가 있는 수십억 개의 이미지가 포함되어 있습니다.

 

8.1.1.2. Missing Ingredient: Hardware

 

Deep learning models are voracious consumers of compute cycles. Training can take hundreds of epochs, and each iteration requires passing data through many layers of computationally expensive linear algebra operations. This is one of the main reasons why in the 1990s and early 2000s, simple algorithms based on the more-efficiently optimized convex objectives were preferred.

 

딥 러닝 모델은 compute cycles를 탐욕스럽게 소비합니다. 교육에는 수백 에포크가 걸릴 수 있으며 각 반복에는 계산 비용이 많이 드는 선형 대수 연산의 많은 계층을 통해 데이터를 전달해야 합니다. 이것이 1990년대와 2000년대 초반에 보다 효율적으로 최적화된  convex objectives에 기반한 간단한 알고리즘이 선호되었던 주요 이유 중 하나입니다.

 

Graphical processing units (GPUs) proved to be a game changer in making deep learning feasible. These chips had long been developed for accelerating graphics processing to benefit computer games. In particular, they were optimized for high throughput 4×4 matrix-vector products, which are needed for many computer graphics tasks. Fortunately, the math is strikingly similar to that required to calculate convolutional layers. Around that time, NVIDIA and ATI had begun optimizing GPUs for general computing operations (Fernando, 2004), going as far as to market them as general-purpose GPUs (GPGPUs).

 

그래픽 처리 장치(GPU)는 딥 러닝을 실현 가능하게 만드는 게임 체인저임이 입증되었습니다. 이 칩은 컴퓨터 게임에 도움이 되는 그래픽 처리를 가속화하기 위해 오랫동안 개발되었습니다. 특히 많은 컴퓨터 그래픽 작업에 필요한 높은 처리량의 4×4 행렬-벡터 제품에 최적화되었습니다. 다행스럽게도 수학은 컨볼루션 레이어를 계산하는 데 필요한 것과 놀랍도록 유사합니다. 그 무렵 NVIDIA와 ATI는 일반 컴퓨팅 작업을 위해 GPU를 최적화하기 시작했으며(Fernando, 2004) 범용 GPU(GPGPU)로 마케팅하기까지 했습니다.

 

To provide some intuition, consider the cores of a modern microprocessor (CPU). Each of the cores is fairly powerful running at a high clock frequency and sporting large caches (up to several megabytes of L3). Each core is well-suited to executing a wide range of instructions, with branch predictors, a deep pipeline, specialized execution units, speculative execution, and many other bells and whistles that enable it to run a large variety of programs with sophisticated control flow. This apparent strength, however, is also its Achilles heel: general-purpose cores are very expensive to build. They excel at general-purpose code with lots of control flow. This requires lots of chip area, not just for the actual ALU (arithmetic logical unit) where computation happens, but also for all the aforementioned bells and whistles, plus memory interfaces, caching logic between cores, high-speed interconnects, and so on. CPUs are comparatively bad at any single task when compared to dedicated hardware. Modern laptops have 4–8 cores, and even high-end servers rarely exceed 64 cores per socket, simply because it is not cost-effective.

 

직관을 제공하기 위해 최신 마이크로프로세서(CPU)의 코어를 고려하십시오. 각 코어는 높은 클록 주파수에서 상당히 강력하게 실행되며 대형 캐시(최대 몇 메가바이트의 L3)를 자랑합니다. 각 코어는 branch predictors, a deep pipeline, specialized execution units, speculative execution 및 정교한 제어 흐름으로 다양한 프로그램을 실행할 수 있게 해주는 기타 많은 부가 기능을 통해 광범위한 명령을 실행하는 데 매우 적합합니다. 그러나 이러한 명백한 강점은 또한 약점이기도 합니다. 범용 코어는 구축 비용이 매우 많이 듭니다. 제어 흐름이 많은 범용 코드에 탁월합니다. 여기에는 연산이 발생하는 실제 ALU(산술 논리 장치)뿐만 아니라 앞서 언급한 모든 부가 기능, 메모리 인터페이스, 코어 간 캐싱 논리, 고속 상호 연결 등 많은 칩 영역이 필요합니다. CPU는 전용 하드웨어와 비교할 때 단일 작업에서 비교적 나쁩니다. 최신 노트북에는 4~8개의 코어가 있으며 고급 서버도 비용 효율적이지 않기 때문에 소켓당 64개의 코어를 거의 초과하지 않습니다.

 

By comparison, GPUs can consist of thousands of small processing elements (NIVIDA’s latest Ampere chips have up to 6912 CUDA cores), often grouped into larger groups (NVIDIA calls them warps). The details differ somewhat between NVIDIA, AMD, ARM and other chip vendors. While each core is relatively weak, running at about 1GHz clock frequency, it is the total number of such cores that makes GPUs orders of magnitude faster than CPUs. For instance, NVIDIA’s recent Ampere A100 GPU offers over 300 TFLOPs per chip for specialized 16 bit precision (BFLOAT16) matrix-matrix multiplications, and up to 20 TFLOPs for more general-purpose floating point operations (FP32). At the same time, floating point performance of CPUs rarely exceeds 1 TFLOPs. For instance, Amazon’s Graviton 3 reaches 2 TFLOPs peak performance for 16 bit precision operations, a number similar to the GPU performance of Apple’s M1 processor.

 

이에 비해 GPU는 수천 개의 작은 처리 요소(NIVIDA의 최신 Ampere 칩에는 최대 6912개의 CUDA 코어가 있음)로 구성될 수 있으며 종종 더 큰 그룹으로 그룹화됩니다(NVIDIA에서는 이를 워프라고 함). 세부 사항은 NVIDIA, AMD, ARM 및 기타 칩 공급업체 간에 다소 다릅니다. 각 코어는 상대적으로 약하고 약 1GHz 클록 주파수에서 실행되지만 GPU를 CPU보다 수십 배 더 빠르게 만드는 것은 이러한 코어의 총 수입니다. 예를 들어, NVIDIA의 최신 Ampere A100 GPU는 전문화된 16비트 정밀도(BFLOAT16) 행렬-행렬 곱셈을 위해 칩당 300 TFLOP 이상을 제공하고 보다 범용적인 부동 소수점 연산(FP32)을 위해 최대 20 TFLOP를 제공합니다. 동시에 CPU의 부동 소수점 성능은 거의 1 TFLOP를 초과하지 않습니다. 예를 들어 Amazon의 Graviton 3은 16비트 정밀 작업에서 2 TFLOPs의 최고 성능에 도달하며 이는 Apple의 M1 프로세서의 GPU 성능과 비슷한 수치입니다.

 

There are many reasons why GPUs are much faster than CPUs in terms of FLOPs. First, power consumption tends to grow quadratically with clock frequency. Hence, for the power budget of a CPU core that runs 4 times faster (a typical number), you can use 16 GPU cores at 1/4 the speed, which yields 16×1/4=4 times the performance. Second, GPU cores are much simpler (in fact, for a long time they were not even able to execute general-purpose code), which makes them more energy efficient. For instance, (i) they tend not to support speculative evaluation, (ii) it typically is not possible to program each processing element individually, and (iii) the caches per core tend to be much smaller. Last, many operations in deep learning require high memory bandwidth. Again, GPUs shine here with buses that are at least 10 times as wide as many CPUs.

 

FLOP 측면에서 GPU가 CPU보다 훨씬 빠른 데는 여러 가지 이유가 있습니다. 첫째, 전력 소비는 클록 주파수에 따라 2차적으로 증가하는 경향이 있습니다. 따라서 4배 더 빠르게 실행되는 CPU 코어의 전력 예산(일반적인 숫자)의 경우 1/4의 속도로 16개의 GPU 코어를 사용할 수 있으며, 이는 16×1/4=4배의 성능을 제공합니다. 둘째, GPU 코어는 훨씬 단순하기 때문에(사실 오랫동안 범용 코드를 실행할 수조차 없었습니다) 에너지 효율이 높아집니다. 예를 들어, (i) 추측 평가를 지원하지 않는 경향이 있고, (ii) 일반적으로 각 처리 요소를 개별적으로 프로그래밍할 수 없으며, (iii) 코어당 캐시가 훨씬 작은 경향이 있습니다. 마지막으로 딥 러닝의 많은 작업에는 높은 메모리 대역폭이 필요합니다. 여기서도 GPU는 CPU보다 최소 10배 더 넓은 버스로 빛을 발합니다.

 

Back to 2012. A major breakthrough came when Alex Krizhevsky and Ilya Sutskever implemented a deep CNN that could run on GPUs. They realized that the computational bottlenecks in CNNs, convolutions and matrix multiplications, are all operations that could be parallelized in hardware. Using two NVIDIA GTX 580s with 3GB of memory, either of which was capable of 1.5 TFLOPs (still a challenge for most CPUs a decade later), they implemented fast convolutions. The cuda-convnet code was good enough that for several years it was the industry standard and powered the first couple years of the deep learning boom.

 

2012년으로 돌아가 보자. Alex Krizhevsky와 Ilya Sutskever가 GPU에서 실행할 수 있는 심층 CNN을 구현했을 때 중대한 돌파구가 마련되었습니다. 그들은 CNN의 계산 병목 현상, 회선 및 행렬 곱셈이 모두 하드웨어에서 병렬화될 수 있는 작업이라는 것을 깨달았습니다. 3GB 메모리가 장착된 2개의 NVIDIA GTX 580을 사용하여 둘 중 하나는 1.5 TFLOP(10년 후에도 대부분의 CPU에는 여전히 문제임)를 지원하여 빠른 컨볼루션을 구현했습니다. cuda-convnet 코드는 충분히 훌륭하여 몇 년 동안 업계 표준이 되었고 딥 러닝 붐의 첫 몇 년 동안 동력이 되었습니다.

 

8.1.2. AlexNet

AlexNet, which employed an 8-layer CNN, won the ImageNet Large Scale Visual Recognition Challenge 2012 by a large margin (Russakovsky et al., 2013). This network showed, for the first time, that the features obtained by learning can transcend manually-designed features, breaking the previous paradigm in computer vision.

 

8 레이어 CNN을 사용하는 AlexNet은 ImageNet Large Scale Visual Recognition Challenge 2012에서 큰 차이로 우승했습니다(Russakovsky et al., 2013). 이 네트워크는 처음으로 학습을 통해 얻은 기능이 수동으로 설계된 기능을 초월하여 컴퓨터 비전의 이전 패러다임을 깨뜨릴 수 있음을 보여주었습니다.

 

The architectures of AlexNet and LeNet are strikingly similar, as Fig. 8.1.2 illustrates. Note that we provide a slightly streamlined version of AlexNet removing some of the design quirks that were needed in 2012 to make the model fit on two small GPUs.

 

AlexNet과 LeNet의 아키텍처는 그림 8.1.2에서 볼 수 있듯이 놀랍도록 유사합니다. 모델을 2개의 작은 GPU에 맞추기 위해 2012년에 필요했던 일부 디자인 문제를 제거한 AlexNet의 약간 간소화된 버전을 제공합니다.

 

Fig. 8.1.2  From LeNet (left) to AlexNet (right).

 

There are also significant differences between AlexNet and LeNet. First, AlexNet is much deeper than the comparatively small LeNet5. AlexNet consists of eight layers: five convolutional layers, two fully connected hidden layers, and one fully connected output layer. Second, AlexNet used the ReLU instead of the sigmoid as its activation function. Let’s delve into the details below.

 

AlexNet과 LeNet 사이에는 중요한 차이점도 있습니다. 첫째, AlexNet은 비교적 작은 LeNet5보다 훨씬 더 깊습니다. AlexNet은 5개의 컨볼루션 레이어, 2개의 fully connected hidden layers, 1개의 fully connected output layer 등 8개의 레이어로 구성됩니다. 둘째, AlexNet은 활성화 함수로 시그모이드 대신 ReLU를 사용했습니다. 자세한 내용은 아래에서 살펴보겠습니다.

 

8.1.2.1. Architecture

In AlexNet’s first layer, the convolution window shape is 11×11. Since the images in ImageNet are eight times higher and wider than the MNIST images, objects in ImageNet data tend to occupy more pixels with more visual detail. Consequently, a larger convolution window is needed to capture the object. The convolution window shape in the second layer is reduced to 5×5, followed by 3×3. In addition, after the first, second, and fifth convolutional layers, the network adds max-pooling layers with a window shape of 3×3 and a stride of 2. Moreover, AlexNet has ten times more convolution channels than LeNet.

 

AlexNet의 첫 번째 레이어에서 컨볼루션 창 모양은 11×11입니다. ImageNet의 이미지는 MNIST 이미지보다 8배 더 높고 넓기 때문에 ImageNet 데이터의 개체는 더 많은 시각적 세부 정보로 더 많은 픽셀을 차지하는 경향이 있습니다. 결과적으로 개체를 캡처하려면 더 큰 컨볼루션 창이 필요합니다. 두 번째 레이어의 컨볼루션 창 모양은 5×5로 축소된 다음 3×3으로 축소됩니다. 또한, 첫 번째, 두 번째, 다섯 번째 컨볼루션 레이어 이후에 네트워크는 3×3의 창 모양과 2의 스트라이드를 갖는 최대 풀링 레이어를 추가합니다. 게다가 AlexNet은 LeNet보다 10배 더 많은 컨볼루션 채널을 가지고 있습니다.

 

After the last convolutional layer, there are two huge fully connected layers with 4096 outputs. These layers require nearly 1GB model parameters. Due to the limited memory in early GPUs, the original AlexNet used a dual data stream design, so that each of their two GPUs could be responsible for storing and computing only its half of the model. Fortunately, GPU memory is comparatively abundant now, so we rarely need to break up models across GPUs these days (our version of the AlexNet model deviates from the original paper in this aspect).

 

마지막 컨볼루션 레이어 다음에는 4096개의 출력을 가진 두 개의 거대한 완전 연결 레이어가 있습니다. 이러한 레이어에는 거의 1GB의 모델 매개변수가 필요합니다. 초기 GPU의 제한된 메모리로 인해 원래 AlexNet은 이중 데이터 스트림 설계를 사용하여 두 개의 GPU가 각각 모델의 절반만 저장하고 계산할 수 있도록 했습니다. 다행스럽게도 현재 GPU 메모리는 비교적 풍부하기 때문에 요즘에는 모델을 여러 GPU로 분할할 필요가 거의 없습니다(AlexNet 모델 버전은 이 측면에서 원본 논문과 다릅니다).

 

8.1.2.2. Activation Functions

Besides, AlexNet changed the sigmoid activation function to a simpler ReLU activation function. On the one hand, the computation of the ReLU activation function is simpler. For example, it does not have the exponentiation operation found in the sigmoid activation function. On the other hand, the ReLU activation function makes model training easier when using different parameter initialization methods. This is because, when the output of the sigmoid activation function is very close to 0 or 1, the gradient of these regions is almost 0, so that backpropagation cannot continue to update some of the model parameters. In contrast, the gradient of the ReLU activation function in the positive interval is always 1 (Section 5.1.2). Therefore, if the model parameters are not properly initialized, the sigmoid function may obtain a gradient of almost 0 in the positive interval, so that the model cannot be effectively trained.

 

게다가 AlexNet은 시그모이드 활성화 함수를 더 간단한 ReLU 활성화 함수로 변경했습니다. 한편으로 ReLU 활성화 함수의 계산은 더 간단합니다. 예를 들어 시그모이드 활성화 함수에 있는 지수 연산이 없습니다. 반면에 ReLU 활성화 기능은 다른 매개변수 초기화 방법을 사용할 때 모델 교육을 더 쉽게 만듭니다. 이는 시그모이드 활성화 함수의 출력이 0 또는 1에 매우 가까울 때 이러한 영역의 기울기가 거의 0이므로 역전파가 일부 모델 매개변수를 계속 업데이트할 수 없기 때문입니다. 대조적으로 양의 구간에서 ReLU 활성화 함수의 기울기는 항상 1입니다(섹션 5.1.2). 따라서 모델 매개변수가 제대로 초기화되지 않으면 시그모이드 함수는 양의 구간에서 거의 0의 기울기를 얻을 수 있으므로 모델을 효과적으로 학습할 수 없습니다.

 

8.1.2.3. Capacity Control and Preprocessing

AlexNet controls the model complexity of the fully connected layer by dropout (Section 5.6), while LeNet only uses weight decay. To augment the data even further, the training loop of AlexNet added a great deal of image augmentation, such as flipping, clipping, and color changes. This makes the model more robust and the larger sample size effectively reduces overfitting. We will discuss data augmentation in greater detail in Section 14.1. See also Buslaev et al. (2020) for an in-depth review of such preprocessing steps.

 

AlexNet은 드롭아웃(섹션 5.6)에 의해 완전히 연결된 계층의 모델 복잡성을 제어하는 반면 LeNet은 가중치 감쇠만 사용합니다. 데이터를 더욱 보강하기 위해 AlexNet의 훈련 루프는 뒤집기, 클리핑 및 색상 변경과 같은 많은 이미지 확대를 추가했습니다. 이렇게 하면 모델이 더 견고해지고 더 큰 샘플 크기가 과적합을 효과적으로 줄입니다. 데이터 증대에 대해서는 14.1절에서 더 자세히 논의할 것입니다. Buslaev et al. (2020) 이러한 전처리 단계에 대한 심층 검토.

 

class AlexNet(d2l.Classifier):
    def __init__(self, lr=0.1, num_classes=10):
        super().__init__()
        self.save_hyperparameters()
        self.net = nn.Sequential(
            nn.LazyConv2d(96, kernel_size=11, stride=4, padding=1),
            nn.ReLU(), nn.MaxPool2d(kernel_size=3, stride=2),
            nn.LazyConv2d(256, kernel_size=5, padding=2), nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2),
            nn.LazyConv2d(384, kernel_size=3, padding=1), nn.ReLU(),
            nn.LazyConv2d(384, kernel_size=3, padding=1), nn.ReLU(),
            nn.LazyConv2d(256, kernel_size=3, padding=1), nn.ReLU(),
            nn.MaxPool2d(kernel_size=3, stride=2), nn.Flatten(),
            nn.LazyLinear(4096), nn.ReLU(), nn.Dropout(p=0.5),
            nn.LazyLinear(4096), nn.ReLU(),nn.Dropout(p=0.5),
            nn.LazyLinear(num_classes))
        self.net.apply(d2l.init_cnn)

위 코드는 AlexNet이라는 CNN 모델을 정의하는 부분입니다. AlexNet 클래스는 d2l.Classifier를 상속하고 있으며, 하이퍼파라미터로 학습률(lr)과 클래스의 개수(num_classes)를 받습니다.

self.net은 nn.Sequential을 사용하여 다양한 합성곱(Convolutional) 층과 완전 연결(Fully-Connected) 층, 활성화 함수, 풀링(Pooling) 층, 드롭아웃(Dropout) 등이 순차적으로 배치되어 전체 신경망 모델을 구성합니다. 각 층은 AlexNet 구조에 맞게 설정되어 있으며, 합성곱 층의 파라미터로는 필터 개수, 커널 크기, 스트라이드, 패딩 값 등이 사용되었습니다.

마지막으로 self.net에 d2l.init_cnn 함수를 적용하여 가중치 초기화를 수행합니다.

 

torch.nn.LazyCOnv2d() 

 

LazyConv2d — PyTorch 2.0 documentation

Shortcuts

pytorch.org

torch.nn.LazyConv2d()는 2D 컨볼루션 레이어를 나타내는 PyTorch의 클래스입니다. 이 레이어는 컨볼루션 연산을 수행하여 입력 데이터의 특징을 추출하는 역할을 합니다. "LazyConv2d"라는 이름은 이 레이어가 실제로 계산을 수행하지 않고 필요할 때까지 연산을 지연시키는 특징을 가지고 있음을 나타냅니다.

LazyConv2d는 컨볼루션 필터(kernel)의 크기, 스트라이드(stride), 패딩(padding) 등을 설정하여 입력 데이터에 대한 컨볼루션 연산을 수행합니다. 이를 통해 입력 이미지 또는 특징 맵에 대해 지역적인 패턴을 인식하고 추출할 수 있습니다. LazyConv2d는 컨볼루션 연산을 효율적으로 수행하고, 파라미터로 전달된 설정에 따라 입력 데이터의 크기와 채널 수를 조절하여 다양한 네트워크 구조에서 사용할 수 있습니다.

LazyConv2d는 PyTorch의 nn.Module 클래스를 상속하여 정의되며, 순전파(forward) 메서드를 통해 입력 데이터를 받아 컨볼루션 연산을 수행한 결과를 반환합니다. 이 클래스는 PyTorch의 다른 레이어와 함께 사용하여 신경망 모델을 구성할 수 있으며, 학습이나 추론 과정에서 자동 미분(autograd)을 통해 그래디언트(gradient)를 계산할 수 있습니다.

LazyConv2d의 사용은 신경망 모델을 정의하고 학습하는 과정에서 필요한 컨볼루션 레이어를 구성하는 데 사용됩니다. 이를 통해 컨볼루션 신경망(Convolutional Neural Network, CNN)을 구성하고 이미지 분류, 객체 검출, 세그멘테이션 등의 컴퓨터 비전 작업에 적용할 수 있습니다.

 

nn.LazyConv2d(96, kernel_size=11, stride=4, padding=1)는 96개의 출력 채널을 가지는 2D 컨볼루션 레이어를 나타냅니다. 이 레이어는 입력 데이터에 대해 11x11 크기의 컨볼루션 필터를 사용하여 4개의 픽셀 간격으로 스트라이드(stride)를 적용하고, 입력 주변에 1개의 픽셀을 패딩(padding)합니다.

이러한 설정을 통해 LazyConv2d는 입력 데이터에 대해 지역적인 패턴을 탐지하고 특징을 추출하는 역할을 합니다. 96개의 출력 채널은 컨볼루션 연산을 통해 얻어진 다양한 특징 맵(feature map)을 의미하며, 각 채널은 입력 데이터에서 다른 특징을 인식합니다.

LazyConv2d의 주요한 파라미터는 다음과 같습니다:

  • 입력 채널 수: 이 경우에는 입력 데이터의 채널 수를 나타냅니다. 신경망의 이전 레이어에서 전달된 출력 채널 수와 일치해야 합니다.
  • 컨볼루션 필터 크기: 11x11 크기의 필터를 사용하여 입력 데이터와 합성곱을 수행합니다.
  • 스트라이드(stride): 4개의 픽셀 간격으로 입력 데이터에 대해 컨볼루션 연산을 수행합니다. 이를 통해 출력 특징 맵의 크기가 입력과 비교해 줄어듭니다.
  • 패딩(padding): 입력 데이터 주변에 1개의 픽셀을 추가하여 컨볼루션 연산을 수행하기 전에 입력의 크기를 유지합니다. 이를 통해 출력 특징 맵의 크기를 조절할 수 있습니다.

LazyConv2d는 PyTorch의 nn.Module 클래스를 상속받아 정의되며, 신경망 모델에서 다른 레이어와 함께 사용하여 컨볼루션 신경망(Convolutional Neural Network, CNN)을 구성하는 데 활용됩니다. 이 레이어는 학습 과정에서 가중치를 학습하고, 순전파(forward) 메서드를 통해 입력 데이터에 대한 컨볼루션 연산을 수행하여 출력을 계산합니다.

 

We construct a single-channel data example with both height and width of 224 to observe the output shape of each layer. It matches the AlexNet architecture in Fig. 8.1.2.

 

각 레이어의 출력 모양을 관찰하기 위해 높이와 너비가 모두 224인 단일 채널 데이터 예제를 구성합니다. 그림 8.1.2의 AlexNet 아키텍처와 일치합니다.

 

ReLU()

 

ReLU — PyTorch 2.0 documentation

Shortcuts

pytorch.org

torch.nn.ReLU()는 Rectified Linear Unit(ReLU) 활성화 함수를 나타내는 클래스입니다. ReLU는 주어진 입력에 대해 양수 값을 그대로 반환하고, 음수 값은 0으로 변환하는 비선형 함수입니다.

ReLU 함수는 다음과 같은 수식으로 정의됩니다: f(x) = max(0, x)

여기서 x는 입력값을 나타내며, f(x)는 출력값을 의미합니다. 입력값이 양수인 경우, ReLU 함수는 입력값을 그대로 반환하고, 입력값이 음수인 경우 0으로 변환됩니다. 따라서 ReLU 함수는 입력값이 양수일 때는 선형 함수처럼 작용하고, 음수일 때는 비선형 함수의 특성을 가집니다.

ReLU 함수는 주로 신경망 모델의 비선형성을 증가시키고, 신경망이 복잡한 패턴을 학습할 수 있도록 돕는데 사용됩니다. 특히, 음수 값을 0으로 변환하는 특성으로 인해 희소성(Sparsity)를 도출하며, 신경망의 연산량을 줄이고 계산 효율성을 향상시킬 수 있습니다.

torch.nn.ReLU() 클래스는 PyTorch의 nn.Module 클래스를 상속받아 정의되었으며, 신경망 모델에서 다른 레이어와 함께 사용하여 비선형성을 도입하는 데 활용됩니다. 입력값에 대한 순전파(forward) 연산을 수행하며, 학습 과정에서는 역전파(backward) 연산을 통해 기울기(gradient)를 계산합니다.

 

nn.MaxPool2d(kernel_size=3, stride=2)

torch.nn.MaxPool2d(kernel_size=3, stride=2)는 2D Max Pooling 연산을 수행하는 클래스입니다. Max Pooling은 입력 이미지 또는 특성 맵의 각 영역에서 최댓값을 추출하여 다운샘플링하는 연산입니다.

Max Pooling은 다음과 같은 파라미터를 가집니다:

  • kernel_size: Max Pooling을 수행할 영역의 크기를 정의합니다. 이는 정사각형 형태로 지정됩니다.
  • stride: Max Pooling을 수행할 영역을 이동하는 간격을 정의합니다. 이는 정사각형 형태로 지정됩니다.

Max Pooling은 입력 이미지나 특성 맵의 각 영역에서 가장 큰 값을 선택하여 다운샘플링합니다. 이를 통해 공간 해상도를 줄이고, 이미지의 변형에 대한 강인성을 향상시키고, 계산 부하를 감소시킵니다.

예를 들어, kernel_size=3, stride=2로 설정된 Max Pooling은 입력 이미지나 특성 맵을 3x3 크기의 영역으로 나누고, 각 영역에서 가장 큰 값을 선택합니다. 그리고 이동 간격인 2만큼 영역을 이동시켜 다음 영역에서도 최댓값을 선택합니다.

torch.nn.MaxPool2d 클래스는 PyTorch의 nn.Module 클래스를 상속받아 정의되었으며, 신경망 모델에서 다른 레이어와 함께 사용하여 공간적인 정보를 다운샘플링하고 추상화하는 데 활용됩니다. 입력값에 대한 순전파(forward) 연산을 수행하며, 학습 과정에서는 역전파(backward) 연산을 통해 기울기(gradient)를 계산합니다.

 

nn.Flatten()

Flatten — PyTorch 2.0 documentation

 

Flatten — PyTorch 2.0 documentation

Shortcuts

pytorch.org

nn.Flatten()은 다차원의 텐서를 1차원으로 평탄화(flatten)하는 연산을 수행하는 클래스입니다. 이는 다차원 입력 데이터를 선형 레이어에 전달하기 위해 차원을 조정하는 데 사용됩니다.

nn.Flatten()은 입력 텐서의 모든 차원을 하나의 차원으로 통합하여 1차원 벡터로 만듭니다. 예를 들어, 입력 텐서의 크기가 (batch_size, channels, height, width)인 경우, nn.Flatten()을 적용하면 (batch_size, channels * height * width) 크기의 출력을 얻을 수 있습니다. 이렇게 평탄화된 텐서는 선형 레이어의 입력으로 사용될 수 있습니다.

nn.Flatten() 클래스는 PyTorch의 nn.Module 클래스를 상속받아 정의되었으며, 신경망 모델에서 다양한 레이어와 함께 사용될 수 있습니다. 주로 이미지 처리와 관련된 신경망에서 다차원 입력 데이터를 1차원으로 변환하는 용도로 활용됩니다. 평탄화 연산은 입력 데이터의 공간적 구조를 보존하면서 선형 변환을 적용하기 위해 필요한 전처리 단계입니다.

 

nn.LazyLinear(4096)

LazyLinear — PyTorch 2.0 documentation

 

LazyLinear — PyTorch 2.0 documentation

Shortcuts

pytorch.org

torch.nn.LazyLinear(4096)는 선형 변환(linear transformation)을 수행하는 클래스입니다. 선형 변환은 입력 벡터를 선형 함수를 통해 출력 벡터로 매핑하는 연산을 의미합니다.

nn.LazyLinear은 다음과 같은 파라미터를 가집니다:

  • in_features: 입력 특성의 크기를 정의합니다. 이는 선형 변환의 입력 벡터의 크기입니다.
  • out_features: 출력 특성의 크기를 정의합니다. 이는 선형 변환의 출력 벡터의 크기입니다.

예를 들어, nn.LazyLinear(4096)는 입력 벡터의 크기가 4096인 데이터를 받아들여 선형 변환을 수행하여 출력 벡터의 크기가 4096인 결과를 반환합니다.

torch.nn.LazyLinear 클래스는 PyTorch의 nn.Module 클래스를 상속받아 정의되었으며, 신경망 모델의 선형 레이어로 활용됩니다. 선형 변환은 입력 데이터의 특성을 변환하고 차원을 조정하는 데 사용됩니다. 순전파(forward) 연산에서는 입력값에 선형 변환을 적용하고, 역전파(backward) 연산을 통해 기울기(gradient)를 계산합니다. 이를 통해 신경망의 학습 과정에서 가중치와 편향을 조정하여 최적화할 수 있습니다.

 

nn.Dropout(p=0.5)

nn.Dropout(p=0.5)은 신경망 모델에서 사용되는 드롭아웃(dropout) 연산을 수행하는 클래스입니다. 드롭아웃은 모델의 일부 뉴런을 임의로 비활성화하여 일부러 과적합(overfitting)을 방지하고 일반화 성능을 향상시키는 데 사용됩니다.

nn.Dropout 클래스의 생성자에는 확률적으로 비활성화할 뉴런의 비율을 나타내는 매개변수 p가 포함됩니다. 이 값은 일반적으로 0과 1 사이의 실수로 지정되며, 각 뉴런이 비활성화될 확률을 나타냅니다. 예를 들어, p=0.5인 경우 각 뉴런이 50%의 확률로 비활성화됩니다.

드롭아웃은 학습 중에만 적용되며, 테스트 시에는 모든 뉴런을 활성화하여 출력을 계산합니다. 이는 모델의 일반화 능력을 향상시키는 데 도움이 되는 방법 중 하나입니다. 드롭아웃은 특히 크고 복잡한 신경망에서 과적합을 방지하고 일반화 성능을 향상시키는 데 효과적입니다.

nn.Dropout 클래스는 PyTorch의 nn.Module 클래스를 상속받아 정의되었으며, 신경망 모델의 다른 레이어와 함께 사용될 수 있습니다. 주로 fully connected 레이어 또는 합성곱 레이어 다음에 추가하여 사용되며, 모델의 성능을 개선하고 일반화 성능을 향상시키는 데 도움을 줍니다.

 

---------------------------------------------------------

 

AlexNet().layer_summary((1, 1, 224, 224))

위 코드는 AlexNet 모델의 레이어 요약 정보를 출력하는 부분입니다. AlexNet()을 호출하여 AlexNet 모델의 객체를 생성한 후, layer_summary((1, 1, 224, 224))를 호출합니다. 이를 통해 입력 데이터의 shape를 (1, 1, 224, 224)로 설정하고, 모델의 각 레이어를 순차적으로 통과시킨 후, 각 레이어의 출력 형태를 출력합니다. 이를 통해 모델의 각 레이어가 입력 데이터에 대해 어떤 변화를 주는지 확인할 수 있습니다.

 

형상 (1, 1, 224, 224)은 4차원 텐서를 나타냅니다. 각 차원은 특정한 의미를 가지고 있습니다:

  • 첫 번째 차원 (1)은 배치 크기를 나타냅니다. 이는 한 번의 순전파 또는 역전파 과정에서 함께 처리되는 샘플 또는 예제의 수를 나타냅니다.
  • 두 번째 차원 (1)은 채널의 수를 나타냅니다. 이 경우 1이므로 텐서는 단일 채널을 가지고 있음을 나타냅니다. 예를 들어, 흑백 이미지의 경우 채널은 각 픽셀의 밝기 값을 나타냅니다.
  • 세 번째 차원 (224)은 텐서의 높이를 나타냅니다. 이는 각 채널에서의 행 또는 픽셀 수에 해당합니다.
  • 네 번째 차원 (224)은 텐서의 너비를 나타냅니다. 이는 각 채널에서의 열 또는 픽셀 수에 해당합니다.

요약하면, 형상 (1, 1, 224, 224)은 높이와 너비가 각각 224 픽셀인 단일 흑백 이미지를 나타냅니다. 첫 번째 차원은 배치 크기를 나타내며, 이 경우 1입니다. 두 번째 차원은 채널의 수를 나타내며, 흑백 이미지의 경우 1입니다.

torch.Size([1, 96, 54, 54])는 4차원 텐서의 크기를 나타냅니다. 각 차원은 특정한 의미를 가지고 있습니다:

  • 첫 번째 차원 (1)은 배치 크기를 나타냅니다. 이는 한 번의 순전파 또는 역전파 과정에서 함께 처리되는 샘플 또는 예제의 수를 나타냅니다.
  • 두 번째 차원 (96)은 채널의 수를 나타냅니다. 이 경우 96이므로 텐서는 96개의 채널을 가지고 있음을 나타냅니다. 예를 들어, 컨볼루션 신경망에서는 여러 개의 필터 또는 특성 맵을 사용하여 다양한 채널을 생성합니다.
  • 세 번째 차원 (54)은 텐서의 높이를 나타냅니다. 이는 각 채널에서의 행 또는 픽셀 수에 해당합니다.
  • 네 번째 차원 (54)은 텐서의 너비를 나타냅니다. 이는 각 채널에서의 열 또는 픽셀 수에 해당합니다.

요약하면, torch.Size([1, 96, 54, 54])는 배치 크기가 1이고 96개의 채널을 가진 텐서로, 각 채널은 높이와 너비가 각각 54인 이미지 또는 특성 맵을 나타냅니다.

8.1.3. Training

 

Although AlexNet was trained on ImageNet in Krizhevsky et al. (2012), we use Fashion-MNIST here since training an ImageNet model to convergence could take hours or days even on a modern GPU. One of the problems with applying AlexNet directly on Fashion-MNIST is that its images have lower resolution (28×28 pixels) than ImageNet images. To make things work, we upsample them to 224×224. This is generally not a smart practice, as it simply increases the computational complexity without adding information. Nonetheless, we do it here to be faithful to the AlexNet architecture. We perform this resizing with the resize argument in the d2l.FashionMNIST constructor.

 

AlexNet은 Krizhevsky et al. (2012), ImageNet 모델을 컨버전스로 교육하는 데 최신 GPU에서도 몇 시간 또는 며칠이 걸릴 수 있으므로 여기서는 Fashion-MNIST를 사용합니다. Fashion-MNIST에 AlexNet을 직접 적용할 때의 문제점 중 하나는 이미지가 ImageNet 이미지보다 해상도(28×28 픽셀)가 낮다는 것입니다. 작업을 수행하기 위해 224×224로 업샘플링합니다. 이는 정보를 추가하지 않고 단순히 계산 복잡성을 증가시키기 때문에 일반적으로 현명한 방법이 아닙니다. 그럼에도 불구하고 여기서는 AlexNet 아키텍처에 충실하기 위해 수행합니다. d2l.FashionMNIST 생성자에서 resize 인수를 사용하여 이 크기 조정을 수행합니다.

 

Now, we can start training AlexNet. Compared to LeNet in Section 7.6, the main change here is the use of a smaller learning rate and much slower training due to the deeper and wider network, the higher image resolution, and the more costly convolutions.

 

7.6. Convolutional Neural Networks (LeNet) — Dive into Deep Learning 1.0.0-beta0 documentation

 

d2l.ai

 

이제 AlexNet 교육을 시작할 수 있습니다. 섹션 7.6의 LeNet과 비교할 때 여기서 주요 변경 사항은 더 깊고 넓은 네트워크, 더 높은 이미지 해상도 및 더 많은 비용이 드는 컨볼루션으로 인해 더 작은 학습 속도와 훨씬 더 느린 훈련을 사용한다는 것입니다.

 

model = AlexNet(lr=0.01)
data = d2l.FashionMNIST(batch_size=128, resize=(224, 224))
trainer = d2l.Trainer(max_epochs=10, num_gpus=1)
trainer.fit(model, data)

위 코드는 AlexNet 모델을 사용하여 FashionMNIST 데이터셋을 학습하는 부분입니다.

먼저 AlexNet(lr=0.01)을 호출하여 model이라는 AlexNet 모델 객체를 생성합니다. 이 때, 학습률 lr은 0.01로 설정됩니다.

다음으로 d2l.FashionMNIST(batch_size=128, resize=(224, 224))를 호출하여 FashionMNIST 데이터셋을 생성합니다. 이 때, 배치 크기 batch_size는 128로 설정되고, 이미지 크기를 (224, 224)로 리사이즈합니다.

마지막으로 d2l.Trainer(max_epochs=10, num_gpus=1)를 호출하여 트레이너 객체 trainer를 생성합니다. 이 때, 최대 에폭 수 max_epochs는 10으로 설정되고, GPU 개수 num_gpus는 1로 설정됩니다.

마지막으로 trainer.fit(model, data)를 호출하여 모델을 데이터에 대해 학습시킵니다. 학습은 지정된 최대 에폭 수까지 진행되며, GPU를 사용하여 학습을 가속화합니다.

 

Result from Book

Result from CoLab

 

Result from SageMaker

 

8.1.4. Discussion

 

AlexNet’s structure bears a striking resemblance to LeNet, with a number of critical improvements, both for accuracy (dropout) and for ease of training (ReLU). What is equally striking is the amount of progress that has been made in terms of deep learning tooling. What was several months of work in 2012 can now be accomplished in a dozen lines of code using any modern framework.

 

AlexNet의 구조는 정확성(드롭아웃)과 교육 용이성(ReLU) 모두에서 여러 가지 중요한 개선 사항을 포함하여 LeNet과 놀라울 정도로 유사합니다. 똑같이 놀라운 것은 딥 러닝 툴링 측면에서 이루어진 진전의 양입니다. 2012년에 몇 달 동안 작업했던 작업을 이제 최신 프레임워크를 사용하여 12줄의 코드로 수행할 수 있습니다. 

 

Reviewing the architecture, we see that AlexNet has an Achilles heel when it comes to efficiency: the last two hidden layers require matrices of size 6400×4096 and 4096×4096, respectively. This corresponds to 164 MB of memory and 81 MFLOPs of computation, both of which are a nontrivial outlay, especially on smaller devices, such as mobile phones. This is one of the reasons why AlexNet has been surpassed by much more effective architectures that we will cover in the following sections. Nonetheless, it is a key step from shallow to deep networks that are used nowadays. Note that even though the number of parameters by far exceeds the amount of training data in our experiments (the last two layers have more than 40 million parameters, trained on a datasets of 60 thousand images), there is hardly any overfitting: training and validation loss are virtually identical throughout training. This is due to the improved regularization, such as Dropout, inherent in modern deep network designs.

 

아키텍처를 검토하면 AlexNet이 효율성 측면에서 약점이 있음을 알 수 있습니다. 마지막 두 개의 숨겨진 레이어에는 각각 크기가 6400×4096 및 4096×4096인 행렬이 필요합니다. 이것은 164MB의 메모리와 81MFLOP의 계산에 해당하며, 둘 다 특히 휴대폰과 같은 소형 장치에서 적지 않은 지출입니다. 이것은 다음 섹션에서 다룰 훨씬 더 효과적인 아키텍처가 AlexNet을 능가하는 이유 중 하나입니다. 그럼에도 불구하고 오늘날 사용되는 얕은 네트워크에서 깊은 네트워크로의 핵심 단계입니다. 매개변수의 수가 실험에서 훈련 데이터의 양을 훨씬 초과하더라도(마지막 두 레이어에는 4천만 개 이상의 매개변수가 있으며 6만 개의 이미지 데이터 세트에서 훈련됨) 과적합이 거의 없습니다. 훈련 및 검증 손실은 훈련 전반에 걸쳐 거의 동일합니다. 이는 최신 심층 네트워크 디자인에 내재된 Dropout과 같은 개선된 정규화 때문입니다.

 

Although it seems that there are only a few more lines in AlexNet’s implementation than in LeNet’s, it took the academic community many years to embrace this conceptual change and take advantage of its excellent experimental results. This was also due to the lack of efficient computational tools. At the time neither DistBelief (Dean et al., 2012) nor Caffe (Jia et al., 2014) existed, and Theano (Bergstra et al., 2010) still lacked many distinguishing features. It is only the availability of TensorFlow (Abadi et al., 2016) that changed this situation dramatically.

 

AlexNet의 구현에는 LeNet보다 몇 줄만 더 있는 것처럼 보이지만 학계에서 이러한 개념적 변화를 수용하고 우수한 실험 결과를 활용하는 데 수년이 걸렸습니다. 이는 효율적인 계산 도구가 부족했기 때문이기도 합니다. 그 당시에는 DistBelief(Dean et al., 2012)나 Caffe(Jia et al., 2014)도 존재하지 않았고 Theano(Bergstra et al., 2010)는 여전히 많은 구별 기능이 부족했습니다. 이 상황을 극적으로 변화시킨 것은 TensorFlow(Abadi et al., 2016)의 가용성뿐입니다.

 

8.1.5. Exercises

  1. Following up on the discussion above, analyze the computational properties of AlexNet.
    1. Compute the memory footprint for convolutions and fully connected layers, respectively. Which one dominates?
    2. Calculate the computational cost for the convolutions and the fully connected layers.
    3. How does the memory (read and write bandwidth, latency, size) affect computation? Is there any difference in its effects for training and inference?
  2. You are a chip designer and need to trade off computation and memory bandwidth. For example, a faster chip requires more power and possibly a larger chip area. More memory bandwidth requires more pins and control logic, thus also more area. How do you optimize?
  3. Why do engineers no longer report performance benchmarks on AlexNet?
  4. Try increasing the number of epochs when training AlexNet. Compared with LeNet, how do the results differ? Why?
  5. AlexNet may be too complex for the Fashion-MNIST dataset, in particular due to the low resolution of the initial images.
    1. Try simplifying the model to make the training faster, while ensuring that the accuracy does not drop significantly.
    2. Design a better model that works directly on 28×28 images.
  6. Modify the batch size, and observe the changes in throughput (images/s), accuracy, and GPU memory.
  7. Apply dropout and ReLU to LeNet-5. Does it improve? Can you improve things further by preprocessing to take advantage of the invariances inherent in the images?
  8. Can you make AlexNet overfit? Which feature do you need to remove or change to break training?
반응형